From c412bf2ee0a3fbf9032fc32a26837d4fbc7585c5 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Sat, 27 Nov 2021 16:17:05 +0300 Subject: initial public --- src/sensors_mqtt_receiver.py | 56 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100755 src/sensors_mqtt_receiver.py (limited to 'src/sensors_mqtt_receiver.py') diff --git a/src/sensors_mqtt_receiver.py b/src/sensors_mqtt_receiver.py new file mode 100755 index 0000000..011ee44 --- /dev/null +++ b/src/sensors_mqtt_receiver.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +import paho.mqtt.client as mqtt +import logging +import re + +from home.mqtt import MQTTBase +from home.config import config +from home.mqtt.message import Temperature +from home.api.types import TemperatureSensorLocation +from home.database import SensorsDatabase + +logger = logging.getLogger(__name__) + + +def get_sensor_type(sensor: str) -> TemperatureSensorLocation: + for item in TemperatureSensorLocation: + if sensor == item.name.lower(): + return item + raise ValueError(f'unexpected sensor value: {sensor}') + + +class MQTTServer(MQTTBase): + def __init__(self): + super().__init__(clean_session=False) + self.database = SensorsDatabase() + + def on_connect(self, client: mqtt.Client, userdata, flags, rc): + super().on_connect(client, userdata, flags, rc) + logger.info("subscribing to home/#") + client.subscribe('home/#', qos=1) + + def on_message(self, client: mqtt.Client, userdata, msg): + try: + variants = '|'.join([s.name.lower() for s in TemperatureSensorLocation]) + match = re.match(rf'home/(\d+)/si7021/({variants})', msg.topic) + if not match: + return + + home_id = int(match.group(1)) + sensor = get_sensor_type(match.group(2)) + + packer = Temperature() + client_time, temp, rh = packer.unpack(msg.payload) + + self.database.add_temperature(home_id, client_time, sensor, + temp=int(temp*100), + rh=int(rh*100)) + except Exception as e: + logger.exception(str(e)) + + +if __name__ == '__main__': + config.load('sensors_mqtt_receiver') + + server = MQTTServer() + server.connect_and_loop() -- cgit v1.2.3