-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (50 loc) · 1.55 KB
/
main.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
import json
import os
import sys
from datetime import datetime
from serial import SerialException
from backoff import Backoff
from mqtt import setup_mqtt
from sensors.bme280_sensor import BME280
from sensors.ltr559 import LTR559
from sensors.pms7003 import PMS7003
from sensors.s8 import S8
sensors = [
BME280(),
LTR559(),
S8(),
PMS7003(),
]
sensor_backoff = Backoff(initial_backoff=60, max_backoff=180, backoff_increment=60)
LTR559().read_data()
PMS7003().read_data()
def loop():
mqtt_client = setup_mqtt()
mqtt_client.loop_start()
for sensor in sensors:
for topic, payload in sensor.home_assistant_auto_discovery():
mqtt_client.publish(topic, payload=json.dumps(payload), retain=True)
try:
while True:
for sensor in sensors:
try:
mqtt_client.publish(
sensor.home_assistant_state_topic(),
payload=json.dumps(sensor.read_data()),
retain=True,
)
print(f"[{datetime.utcnow()}] - reading {type(sensor).__name__}")
except SerialException as e:
print(e)
print(
f"[{datetime.utcnow()}] - Failed reading {type(sensor).__name__}. SKIPPED!"
)
print("backoff")
sensor_backoff.backoff()
print("")
except KeyboardInterrupt:
sys.exit(0)
finally:
mqtt_client.loop_stop()
if __name__ == "__main__":
loop()