pyscript with websocket crashes the HA front end
I've created pyscript to enable/disable integrations. It uses the websocket to control it.
Each time I run it with dev console, it leads to connection lost and HA front end stops working. HA CLI is available. The home-assistant.log doesn't contain any useful information.
import websocket
import json
@service(supports_response="optional")
def manage_integration(integration_id, state, ip, token):
"""yaml
name: Manage integration
description: Pyscript to enable or disable integration
fields:
integration_id:
description: id of the integration to enable or disable (see hidden file .storage/core.config_entries to get it)
example: e59119ee8e73f49aae212385b8758a7b
required: true
selector:
text:
state:
description: target state of the integration
example: disable
required: true
selector:
select:
options:
- disable
- enable
ip:
description: Home Assistant IP and port
example: 192.168.1.110:8123
required: true
selector:
text:
token:
description: long-lived access token (generate at http://home-assistant-ip:8123/profile/security)
required: true
selector:
text:
"""
ws = websocket.WebSocket()
ws.connect("ws://"+ip+"/api/websocket")
json_auth = "{\"type\":\"auth\",\"access_token\":\""+token+"\"}"
ws.send(json_auth)
wsid = 0
if state == 'enable':
json_state = "{\"type\":\"config_entries/enable\",\"entry_id\":\""+integration_id+"\",\"disabled_by\":null,\"id\":"+str(wsid)+"}"
elif state == 'disable':
json_state = "{\"type\":\"config_entries/disable\",\"entry_id\":\""+integration_id+"\",\"disabled_by\":\"pyscript\",\"id\":"+str(wsid)+"}"
ws.send(json_state)
return json.loads(ws.recv())
I am also experiencing a similar issue, about 50% of the time when receiving data it works and the rest of the time it crashes Home Assistant. Same symptoms as described above. Sending data hasn't caused me as much trouble.
websocket will block the main event loop, which could create the deadlock. You should try using an async implementation of websocket., or use @pyscript_executor so it runs in its own task.