-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluftdaten2mqtt.py
321 lines (271 loc) · 11.8 KB
/
luftdaten2mqtt.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""This module runs a bottle webserver and listens for a post request that
contains a JSON payload which will be transmitted over to an MQTT broker."""
import paho.mqtt.client as mqtt
import bottle
import logging
import os
import signal
import sys
# TODO separate routes and logic
# units of measurements
VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m³"
TEMP_CELSIUS = "°C"
# sensor names
SENSOR_TEMPERATURE = "temperature"
SENSOR_HUMIDITY = "humidity"
SENSOR_BME280_TEMPERATURE = "BME280_temperature"
SENSOR_BME280_HUMIDITY = "BME280_humidity"
SENSOR_BME280_PRESSURE = "BME280_pressure"
SENSOR_BMP_TEMPERATURE = "BMP_temperature"
SENSOR_BMP_PRESSURE = "BMP_pressure"
SENSOR_BMP280_TEMPERATURE = "BMP280_temperature"
SENSOR_BMP280_PRESSURE = "BMP280_pressure"
SENSOR_PM1 = "SDS_P1"
SENSOR_PM2 = "SDS_P2"
SENSOR_WIFI_SIGNAL = "signal"
SENSOR_HTU21D_TEMPERATURE = "HTU21D_temperature"
SENSOR_HTU21D_HUMIDITY = "HTU21D_humidity"
SENSOR_SPS30_P0 = "SPS30_P0"
SENSOR_SPS30_P2 = "SPS30_P2"
SENSOR_SPS30_P4 = "SPS30_P4"
SENSOR_SPS30_P1 = "SPS30_P1"
SENSOR_PMS_P0 = "PMS_P0"
SENSOR_PMS_P1 = "PMS_P1"
SENSOR_PMS_P2 = "PMS_P2"
SENSOR_RSSI = "signal"
# template placeholders
TEMPLATE_TEMPERATURE = "{{value|float|round(1)}}"
TEMPLATE_HUMIDITY = "{{value|float|round(0)}}"
TEMPLATE_PRESSURE = "{{((value|float)/100)|round(0)}}"
TEMPLATE_MICROGRAM = "{{value|float|round(0)}}"
# map for sensors
# SENSOR_NAME: [ Friendly Name, Unit of measurement, Device class ]
SENSOR_TYPES = {
SENSOR_TEMPERATURE: ["Temperature", TEMP_CELSIUS, "temperature"],
SENSOR_HUMIDITY: ["Humidity", "%", "humidity"],
SENSOR_BME280_TEMPERATURE: ["Temperature", TEMP_CELSIUS, "temperature"],
SENSOR_BME280_HUMIDITY: ["Humidity", "%", "humidity"],
SENSOR_BME280_PRESSURE: ["Pressure", "hPa", "pressure"],
SENSOR_BMP_TEMPERATURE: ["Temperature", TEMP_CELSIUS, "temperature"],
SENSOR_BMP_PRESSURE: ["Pressure", "hPa", "pressure"],
SENSOR_BMP280_TEMPERATURE: ["Temperature", TEMP_CELSIUS, "temperature"],
SENSOR_BMP280_PRESSURE: ["Pressure", "hPa", "pressure"],
SENSOR_PM1: ["PM10", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm10"],
SENSOR_PM2: ["PM2.5", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm25"],
SENSOR_WIFI_SIGNAL: ["Wifi signal", "dBm", "signal_strength"],
SENSOR_HTU21D_TEMPERATURE: ["Temperature", TEMP_CELSIUS, "temperature"],
SENSOR_HTU21D_HUMIDITY: ["Humidity", "%", "humidity"],
SENSOR_SPS30_P0: ["PM1", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm1"],
SENSOR_SPS30_P2: ["PM2.5", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm25"],
SENSOR_SPS30_P4: ["PM4", VOLUME_MICROGRAMS_PER_CUBIC_METER, None],
SENSOR_SPS30_P1: ["PM10", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm10"],
SENSOR_PMS_P0: ["PM1", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm1"],
SENSOR_PMS_P1: ["PM10", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm10"],
SENSOR_PMS_P2: ["PM2.5", VOLUME_MICROGRAMS_PER_CUBIC_METER, "pm25"],
SENSOR_RSSI: ["RSSI", "dB", "signal_strength"],
}
# icons for sensors that have no class
SENSOR_ICONS = {
SENSOR_PM1: ["mdi:thought-bubble"],
SENSOR_PM2: ["mdi:thought-bubble-outline"],
SENSOR_SPS30_P0: ["mdi:cloud"],
SENSOR_SPS30_P2: ["mdi:thought-bubble-outline"],
SENSOR_SPS30_P4: ["mdi:cloud-outline"],
SENSOR_SPS30_P1: ["mdi:thought-bubble"],
SENSOR_PMS_P0: ["mdi:cloud"],
SENSOR_PMS_P1: ["mdi:thought-bubble"],
SENSOR_PMS_P2: ["mdi:thought-bubble-outline"],
}
# map for value templates
VALUE_TEMPLATES = {
SENSOR_BME280_HUMIDITY: TEMPLATE_HUMIDITY,
SENSOR_BME280_PRESSURE: TEMPLATE_PRESSURE,
SENSOR_BME280_TEMPERATURE: TEMPLATE_TEMPERATURE,
SENSOR_BMP280_PRESSURE: TEMPLATE_PRESSURE,
SENSOR_BMP280_TEMPERATURE: TEMPLATE_TEMPERATURE,
SENSOR_BMP_PRESSURE: TEMPLATE_PRESSURE,
SENSOR_BMP_TEMPERATURE: TEMPLATE_TEMPERATURE,
SENSOR_HTU21D_HUMIDITY: TEMPLATE_HUMIDITY,
SENSOR_HTU21D_TEMPERATURE: TEMPLATE_TEMPERATURE,
SENSOR_HUMIDITY: TEMPLATE_HUMIDITY,
SENSOR_TEMPERATURE: TEMPLATE_TEMPERATURE,
SENSOR_PM1: TEMPLATE_MICROGRAM,
SENSOR_PM2: TEMPLATE_MICROGRAM,
SENSOR_SPS30_P0: TEMPLATE_MICROGRAM,
SENSOR_SPS30_P1: TEMPLATE_MICROGRAM,
SENSOR_SPS30_P2: TEMPLATE_MICROGRAM,
SENSOR_SPS30_P4: TEMPLATE_MICROGRAM,
SENSOR_PMS_P0: TEMPLATE_MICROGRAM,
SENSOR_PMS_P1: TEMPLATE_MICROGRAM,
SENSOR_PMS_P2: TEMPLATE_MICROGRAM,
}
# Map for state classes
STATE_CLASSES = {
SENSOR_TEMPERATURE: ["measurement"],
SENSOR_HUMIDITY: ["measurement"],
SENSOR_BME280_TEMPERATURE: ["measurement"],
SENSOR_BME280_HUMIDITY: ["measurement"],
SENSOR_BME280_PRESSURE: ["measurement"],
SENSOR_BMP_TEMPERATURE: ["measurement"],
SENSOR_BMP_PRESSURE: ["measurement"],
SENSOR_BMP280_TEMPERATURE: ["measurement"],
SENSOR_BMP280_PRESSURE: ["measurement"],
SENSOR_PM1: ["measurement"],
SENSOR_PM2: ["measurement"],
SENSOR_HTU21D_TEMPERATURE: ["measurement"],
SENSOR_HTU21D_HUMIDITY: ["measurement"],
SENSOR_SPS30_P0: ["measurement"],
SENSOR_SPS30_P2: ["measurement"],
SENSOR_SPS30_P4: ["measurement"],
SENSOR_SPS30_P1: ["measurement"],
SENSOR_PMS_P0: ["measurement"],
SENSOR_PMS_P1: ["measurement"],
SENSOR_PMS_P2: ["measurement"],
SENSOR_WIFI_SIGNAL: [None],
SENSOR_RSSI: [None],
}
application = bottle.default_app()
@application.post("/luftdaten/json2mqtt")
def route_luftdaten_json2mqtt():
"""The default route that is listening to post requests."""
# take the json and parse it
json_req = bottle.request.json
logging.debug("json req received %s", json_req)
device_address = bottle.request.environ.get("HTTP_X_FORWARDED_FOR") or bottle.request.environ.get("REMOTE_ADDR")
if bottle.request.headers.get("X-Mac-Id"):
publish(json_req, MQTT_TOPIC + bottle.request.headers.get("X-Mac-Id"), device_address)
def publish(json, topic_prefix, device_address):
"""Publish to mqtt whatever we can/want"""
topic_prefix = topic_prefix.replace(":", "-")
if json["software_version"]:
t = topic_prefix + "/firmware"
val = json["software_version"]
logging.debug("publishing to broker: '%s' '%s'", t, str(val))
CLIENT.publish(topic=t, payload=val, retain=False)
interval = 0
for item in json["sensordatavalues"]:
if str(item["value_type"]) == "interval":
interval = int(item["value"]) / 1000
for item in json["sensordatavalues"]:
# do not explode on unknown measurements
if str(item["value_type"]) in SENSOR_TYPES:
uniq_id = str("luftdaten-" + str(topic_prefix).split("/")[-1] + "-" + str(item["value_type"])).lower()
dev_name = "Luftdaten " + str(bottle.request.headers.get("X-Sensor").split("-")[-1])
# homeassistant autodiscovery
t = "homeassistant/sensor/" + uniq_id + "/config"
val = {
"~": topic_prefix,
"name": str(SENSOR_TYPES[str(item["value_type"])][0]),
"stat_t": "~/" + str(item["value_type"]),
"frc_upd": "False",
"qos": 0,
"uniq_id": uniq_id,
"unit_of_meas": SENSOR_TYPES[str(item["value_type"])][1],
"dev": {
"ids": [str(topic_prefix).split("/")[-1].lower()],
"name": dev_name,
"mdl": "DIY " + str(bottle.request.headers.get("X-Sensor").split("-")[1]),
"sw": json["software_version"],
"mf": "DIY Luftdaten",
"cu": "http://" + str(device_address),
},
"exp_aft": 4 * interval,
"entity_category": "diagnostic",
# add origin as per: https://github.com/home-assistant/core/pull/98782
"o": {
"name": "luftdaten2mqtt",
"sw": "2.0.2",
"url": "https://github.com/zeridon/luftdaten2mqtt/issues",
},
}
# set device class if available, else set an icon to be better
# looking
if SENSOR_TYPES[str(item["value_type"])][2]:
val["dev_cla"] = SENSOR_TYPES[str(item["value_type"])][2]
else:
val["icon"] = SENSOR_ICONS[str(item["value_type"])][0]
# Set value template if such exists
if str(item["value_type"]) in VALUE_TEMPLATES:
val["val_tpl"] = str(VALUE_TEMPLATES[str(item["value_type"])])
# set state class if available
if STATE_CLASSES[str(item["value_type"])][0]:
val["stat_cla"] = STATE_CLASSES[str(item["value_type"])][0]
logging.debug("publishing to broker: '%s' '%s'", t, str(val))
CLIENT.publish(topic=t, payload=str(val).replace("'", '"'), retain=True)
# report data
t = topic_prefix + "/" + str(item["value_type"])
val = item["value"]
logging.debug("publishing to broker: '%s' '%s'", t, str(val))
CLIENT.publish(topic=t, payload=val, retain=False)
@application.get("/status")
def status():
return "OK"
"""Simple page documenting what this is"""
@application.get("/luftdaten")
@application.get("/")
def route_index():
return bottle.template("index")
"""on_connect handler to disconnect and die in case of error"""
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
logging.info("Connected to broker %s", MQTT_HOST)
elif reason_code == "Unsupported protocol version":
logging.error("Can't connect to MQTT Broker %s. Unsupported protocol version", MQTT_HOST)
os._exit(1)
elif reason_code == "Client identifier not valid":
logging.error("MQTT Broker %s Refused connection. Client identifier not valid", MQTT_HOST)
os._exit(2)
elif reason_code == "Server unavailable":
logging.error("MQTT Broker %s Server unavailable", MQTT_HOST)
os._exit(3)
elif reason_code == "Bad user name or password":
logging.error("MQTT Broker %s Refused connection. Bad user name or password", MQTT_HOST)
os._exit(4)
elif reason_code == "Not authorized":
logging.error("MQTT Broker %s Refused connection. Not authorized", MQTT_HOST)
os._exit(5)
else:
logging.info("Reserved error code (%s), from Broker %s", reason_code, MQTT_HOST)
os._exit(99)
def setup():
"""Port to listen on"""
global HTTP_PORT
HTTP_PORT = os.getenv("HTTP_PORT", "8080")
""" MQTT Related """
global MQTT_HOST
MQTT_HOST = os.getenv("MQTT_HOST", "192.168.1.1")
global MQTT_TOPIC
MQTT_TOPIC = os.getenv("MQTT_TOPIC", "luftdaten/")
global MQTT_USER
MQTT_USER = os.getenv("MQTT_USER", "")
global MQTT_PASS
MQTT_PASS = os.getenv("MQTT_PASS", "")
logging.debug("connecting to mqtt broker %s", MQTT_HOST)
global CLIENT
CLIENT = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, clean_session=True)
CLIENT.on_connect = on_connect
if MQTT_USER and MQTT_PASS:
CLIENT.username_pw_set(username=MQTT_USER, password=MQTT_PASS)
CLIENT.connect(MQTT_HOST)
CLIENT.loop_start()
def run_server():
"""Run the bottle-server on the configured http-port."""
bottle.run(app=application, host="0.0.0.0", port=HTTP_PORT, reloader=True)
def sigterm_handler(signo, stack_frame):
logging.debug("Processing SIGTERM, %s, %s" % (signo, stack_frame))
sys.exit(0)
if __name__ == "__main__":
"""Hook our sigterm handler"""
signal.signal(signal.SIGTERM, sigterm_handler)
""" Init loglevel and errorcheck it """
global LOG_LEVEL
LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG")
numeric_level = getattr(logging, LOG_LEVEL.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError("Invalid log level: %s" % LOG_LEVEL)
""" setup logging """
logging.basicConfig(level=numeric_level)
""" Go for MQTT """
setup()
""" Open server """
run_server()