This repository was archived by the owner on Jan 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmqtt2spacestatus.py
executable file
·242 lines (200 loc) · 6.33 KB
/
mqtt2spacestatus.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import datetime
from dateutil.parser import parse
import paho.mqtt.client as paho
import yaml
import json
import time
from _thread import start_new_thread
import copy
def read_configuration(path="config.yaml"):
"""
opens and reads yaml configuration file
:path: str
:returns: dict
"""
with open(path, "r") as conffile:
conf = yaml.load(conffile)
return conf
def read_status(path="status.json"):
"""
opens the written status file in case of restarts
that we do not start with an empty status file.
If there is no file, create empty status dict
:path: str
:returns: dict
"""
try:
with open(path, "r") as jsonfile:
status = json.load(jsonfile)
except (IOError,json.decoder.JSONDecodeError):
status = {}
return status
def write_status(status, path="status.json"):
"""
Checks every some seconds if current status has changed.
On Change it adds the latest timestamp and persists to json file.
:status: dict
"""
old_status = {}
while True:
# Write file only if necessary
if old_status != status:
status.update({"date": datetime.datetime.now().isoformat()})
with open(path, "w") as jsonfile:
json.dump(status, jsonfile, indent=2, sort_keys=True)
old_status = copy.copy(status)
time.sleep(5)
def log(handler, timestamp, value):
try:
ts = parse(str(timestamp))
except ValueError:
ts = datetime.datetime.fromtimestamp(timestamp)
print("Handler: %s, Timestamp %s, Value: %s" % (handler, ts, value), flush=True)
def handler_temperature(msg):
"""
Parses temperature message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
temp = resp["temperature"] / 100
resp = { "temperature": temp }
log("temperature", ts, temp)
return resp
def handler_sound(msg):
"""
Parses sound message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
sound = resp["intensity"]
resp = { "sound": sound }
log("sound", ts, sound)
return resp
def handler_light(msg):
"""
Parses light message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
light = resp["uv_light"]
resp = { "light": light}
log("light", ts, light)
return resp
def handler_humidity(msg):
"""
Parses humidity message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
hum = float(resp["value"])
resp = { "humidity": hum}
log("humidity", ts, hum)
return resp
def handler_hosts(msg):
"""
Parses hosts message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
online = int(resp["online"])
resp = { "online": online }
log("hosts", ts, online)
return resp
def handler_door(msg):
"""
Parses door message from topic
and sends back formatted json data for status.json
:msg: message object from mqtt
:returns: dict
"""
# parse message
resp = json.loads(msg.payload.decode("utf-8"))
# fetch timestamp
timestamp = resp["_timestamp"]
timestamp =datetime.datetime.fromtimestamp(timestamp)
# fetch actual value
door = resp["value"]
# if timestamp is older then 30 minutes
if timestamp < datetime.datetime.now()-datetime.timedelta(minutes=30):
resp = { "door": "unknown" }
else:
resp = { "door": door}
log("door", timestamp, door)
return resp
def handler_octopi(msg):
"""
Parses octopi 3d printer data
:msg: message object from mqtt
:returns: dict
"""
resp = json.loads(msg.payload.decode("utf-8"))
ts = resp["_timestamp"]
progress = float(resp["progress"])
resp = { "octopi_progress": progress}
log("octopi", ts, progress)
return resp
### On Message Parser
def on_message(client, userdata, msg):
"""
This function parses all messages coming from the subscribed mqtt topics
and hands them over to the correct handler
:client: paho mqtt object
:userdata:
:msg: paho message object
:returns: boolean
"""
# debug
if len(sys.argv) > 1:
if sys.argv[1] == "--debug":
print("topic: ", msg.topic, "message: ", str(msg.payload.decode("utf-8")))
# Pattern match on topic and give message to corresponding handler
if msg.topic == "sensors/tischtennis/bricklet/temperature/tfj/temperature":
doc = handler_temperature(msg)
elif msg.topic == "sensors/tischtennis/bricklet/sound_intensity/voE/intensity":
doc = handler_sound(msg)
elif msg.topic == "sensors/tischtennis/bricklet/uv_light/xpa/uv_light":
doc = handler_light(msg)
elif msg.topic == "sensors/door/default/bme280/humidity":
doc = handler_humidity(msg)
elif msg.topic == "sensors/wifi/online":
doc = handler_hosts(msg)
elif msg.topic == "sensors/door/default/status":
doc = handler_door(msg)
elif msg.topic == "sensors/octopi/progress/printing":
doc = handler_octopi(msg)
else:
doc = {}
# update internal dict with latest data (any)
status.update(doc)
return True
def on_connect(client, userdata, flags, rc):
client.subscribe("sensors/#")
if __name__ == "__main__":
conf = read_configuration()
status = read_status(path=conf['output'])
client = paho.Client(conf['username'])
client.username_pw_set(conf['username'], conf['password'])
client.on_message = on_message
client.on_connect = on_connect
client.connect(conf['broker'])
# Trigger file writing asynchronous
start_new_thread(write_status, (status, conf['output']))
client.loop_forever()