-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathduco.py
244 lines (208 loc) · 6.86 KB
/
duco.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import serial
import re
import json
import sys
import logging
import paho.mqtt.client as mqtt
from datetime import datetime
from time import sleep
from threading import Thread
from utils import pathify, changes
# TODO: clean this up
from commands import *
# Set up logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
_running = None
settings = None
mqtt_client = None
conn = None
ctrl = None
topic_namespace = None
initial_get = True
def init():
global _running, settings, mqtt_client, conn, topic_namespace, ctrl
# Default settings
settings = {
"duco" : {
"type": "serial",
"device": "/dev/serial0",
"baudrate": 115200
},
"control": {
"type": "gpio",
"active_low": True,
"states": {}
},
"mqtt" : {
"client_id": "duco",
"host": "127.0.0.1",
"port": 1883,
"keepalive": 60,
"bind_address": "",
"username": None,
"password": None,
"qos": 0,
"pub_topic_namespace": "value/duco",
"sub_topic_namespace": "set/duco",
"retain": False
}
}
# Update default settings from the settings file
with open('config.json') as f:
settings.update(json.load(f))
# Set the namespace of the mqtt messages from the settings
topic_namespace=settings['mqtt']['pub_topic_namespace']
log.info("Initializing MQTT")
# Set up paho-mqtt
mqtt_client = mqtt.Client(
client_id=settings['mqtt']['client_id'])
mqtt_client.on_connect = on_mqtt_connect
mqtt_client.on_message = on_mqtt_message
if settings['mqtt']['username']:
mqtt_client.username_pw_set(
settings['mqtt']['username'],
settings['mqtt']['password'])
# The will makes sure the device registers as offline when the connection
# is lost
mqtt_client.will_set(
topic=topic_namespace,
payload="offline",
qos=settings['mqtt']['qos'],
retain=True)
# Let's not wait for the connection, as it may not succeed if we're not
# connected to the network or anything. Such is the beauty of MQTT
mqtt_client.connect_async(
host=settings['mqtt']['host'],
port=settings['mqtt']['port'],
keepalive=settings['mqtt']['keepalive'],
bind_address=settings['mqtt']['bind_address'])
mqtt_client.loop_start()
log.info("Initializing Duco")
duco_type = {
"serial" : lambda: __import__('ducobox_serial',
globals(), locals(), ['DucoboxSerialClient'], 0) \
.DucoboxSerialClient,
}[settings['duco']['type']]()
conn = duco_type(settings['duco'])
control_types = {
"gpio" : lambda: __import__('control_gpio',
globals(), locals(), ['DucoboxGpioControl'], 0) \
.DucoboxGpioControl,
}
my_type = settings['control']['type']
if my_type in control_types:
control_type = control_types[my_type]()
ctrl = control_type(settings['control'])
_running = True
def main():
init()
# TODO: bleeegh
global _running
conn.open()
if ctrl != None:
ctrl.open()
_worker = Thread(target=worker)
_worker.start()
try:
while _running:
sleep(60)
except:
log.warn("Handling exception")
_running = False
_worker.join()
conn.close()
if ctrl != None:
ctrl.close()
def publish(topic, payload):
mqtt_client.publish(
topic=topic,
payload=payload,
qos=settings['mqtt']['qos'],
retain=settings['mqtt']['retain'])
def worker():
# TODO: clean this up
global _running, initial_get
_running = True
initial_get = True
log.info("Starting read loop")
while _running:
if initial_get:
initial_get = False
netw = {}
fan = {}
co2 = None
humi = None
temp = None
try:
_netw = get_network_data(conn)
cnetw = changes(netw, _netw)
netw = _netw
for (t, v) in pathify(cnetw, "{}/network".format(topic_namespace)):
publish(t, v)
except Exception as e:
log.warn("An exception occured getting network, skipping", exc_info=True)
try:
_fan = get_fan_speed(conn)
cfan = changes(fan, _fan)
fan = _fan
for (t, v) in pathify(cfan, "{}/fan".format(topic_namespace)):
publish(t, v)
except Exception as e:
log.warn("An exception occured getting fan speed, skipping", exc_info=True)
try:
_temp = get_temperature(conn)
if _temp != temp:
temp = _temp
publish("{}/temp".format(topic_namespace), temp)
except Exception as e:
log.warn("An exception occured getting temp, skipping", exc_info=True)
try:
_co2 = get_co2(conn)
if _co2 != co2:
co2 = _co2
publish("{}/co2".format(topic_namespace), co2)
except Exception as e:
log.warn("An exception occured getting CO2, skipping", exc_info=True)
try:
_humi = get_humidity(conn)
if _humi != humi:
humi = _humi
publish("{}/humi".format(topic_namespace), humi)
except Exception as e:
log.warn("An exception occured getting humidity, skipping", exc_info=True)
for _ in range(15):
sleep(1)
if not _running:
break
def get_all(_):
global initial_get
initial_get = True
def on_mqtt_connect(client, userdata, flags, rc):
# Subscribe to all topics in our namespace when we're connected. Send out
# a message telling we're online
log.info("Connected with result code "+str(rc))
mqtt_client.subscribe('{}/#'.format(settings['mqtt']['sub_topic_namespace']))
mqtt_client.subscribe('{}'.format(settings['mqtt']['sub_topic_namespace']))
mqtt_client.publish(
topic=topic_namespace,
payload="online",
qos=settings['mqtt']['qos'],
retain=settings['mqtt']['retain'])
def on_mqtt_message(client, userdata, msg):
# Handle incoming messages
log.info("Received message on topic {} with payload {}".format(
msg.topic, str(msg.payload)))
namespace = settings['mqtt']['sub_topic_namespace']
command_generators={
"{}/state".format(namespace): \
lambda _ :ctrl.set_state(_),
"{}/get".format(namespace): \
get_all,
}
# Find the correct command generator from the dict above
command = command_generators.get(msg.topic)
if command:
log.debug("Calling command")
# Get the command and call it
command(msg.payload)