Skip to content

Instantly share code, notes, and snippets.

@jeroenboumans
Created March 7, 2021 16:37
Show Gist options
  • Select an option

  • Save jeroenboumans/7772770e0405bfc33d7c2a729f1fab8e to your computer and use it in GitHub Desktop.

Select an option

Save jeroenboumans/7772770e0405bfc33d7c2a729f1fab8e to your computer and use it in GitHub Desktop.
async def initSocket():
websocket = await asyncws.connect('ws://{}:{}/api/websocket'.format(host, port))
await websocket.send(json.dumps({'type': 'auth','access_token': token}))
await websocket.send(json.dumps({'id': 1, 'type': 'subscribe_events', 'event_type': 'state_changed'}))
print("Start socket...")
while True:
message = await websocket.recv()
if message is None:
break
try:
data = json.loads(message)['event']['data']
entity_id = data['entity_id']
if entity_id in entities:
print("writing {} to cache".format(entity_id))
if 'unit_of_measurement' in data['new_state']['attributes']:
cache[entity_id] = "{} {}".format(data['new_state']['state'], data['new_state']['attributes']['unit_of_measurement'])
else:
cache[entity_id] = data['new_state']['state']
except Exception:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment