-
Notifications
You must be signed in to change notification settings - Fork 6
/
watcher.py
65 lines (43 loc) · 1.47 KB
/
watcher.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
import time
import json
import yaml
import ltr559
import sys, os, pathlib
from grow.moisture import Moisture
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
print(client.subscribe(broker().get('topic')))
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def load_config():
pathlib.Path(__file__).parent.absolute()
with open(os.path.join(pathlib.Path(__file__).parent.absolute(), 'config.yaml')) as f:
return yaml.load(f)
def broker():
return load_config().get('broker')
def auth():
return load_config().get('auth')
config = load_config()
broker = broker()
auth = auth()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(auth.get('username'), auth.get('password'))
client.connect(broker.get('host', 'homeassistant.local'), broker.get('port', 1883), 60)
print("Start submitting sensor data on MQTT topic {}".format(broker.get('topic')))
sensors = [Moisture(1), Moisture(2), Moisture(3)]
light = ltr559.LTR559()
while True:
i = 0
payload = {"light": light.get_lux()}
for i in range(0, len(sensors)):
payload["sensor_{}".format(i)] = {
"moisture": sensors[i].moisture,
"saturation": sensors[i].saturation
}
client.publish(broker.get('topic'), json.dumps(payload))
print(json.dumps(payload))
time.sleep(30)
client.loop_forever()