Created
March 7, 2021 16:37
-
-
Save jeroenboumans/7772770e0405bfc33d7c2a729f1fab8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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