-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.phat.py
79 lines (60 loc) · 2.17 KB
/
log.phat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
import time
import asyncws
import asyncio
import threading
import json
from microdotphat import write_string, set_decimal, clear, show
token = "HASS_IO_AUTHORIZATION_TOKEN"
host = "HASS_IO_HOSTNAME_OR_URL"
port = 8123
cache = {} # cache
entities = [
"sensor.power_tariff",
"sensor.power_consumption_watt",
"sensor.gas_consumption"
]
async def initLogger():
print("Start logger...")
await asyncio.sleep(1)
while True:
if len(cache) == 0:
await asyncio.sleep(2)
else:
try:
for key in cache:
print(cache[key])
# Write to PHAT
clear()
write_string(cache[key], kerning=False)
show()
await asyncio.sleep(2)
except Exception:
pass
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
async def main():
listen = asyncio.create_task(initSocket())
log = asyncio.create_task(initLogger())
await listen
await log
if __name__ == "__main__":
asyncio.run(main())