diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2021-11-27 16:17:05 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2022-04-24 01:33:04 +0300 |
commit | c412bf2ee0a3fbf9032fc32a26837d4fbc7585c5 (patch) | |
tree | 5cca6bcab79331ad82cab4219c7692b9dd4eea21 /src/sensors_mqtt_sender.py |
initial public
Diffstat (limited to 'src/sensors_mqtt_sender.py')
-rwxr-xr-x | src/sensors_mqtt_sender.py | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/sensors_mqtt_sender.py b/src/sensors_mqtt_sender.py new file mode 100755 index 0000000..f4f8ec9 --- /dev/null +++ b/src/sensors_mqtt_sender.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +import paho.mqtt.client as mqtt +import logging +import time +import json + +from home.util import parse_addr, MySimpleSocketClient +from home.mqtt import MQTTBase, poll_tick +from home.mqtt.message import Temperature +from home.config import config + +logger = logging.getLogger(__name__) + + +class MQTTClient(MQTTBase): + def on_connect(self, client: mqtt.Client, userdata, flags, rc): + super().on_connect(client, userdata, flags, rc) + + def poll(self): + freq = int(config['mqtt']['sensors']['poll_freq']) + logger.debug(f'freq={freq}') + + g = poll_tick(freq) + while True: + time.sleep(next(g)) + for k, v in config['mqtt']['sensors']['si7021'].items(): + host, port = parse_addr(v['addr']) + self.publish_si7021(host, port, k) + + def publish_si7021(self, host: str, port: int, name: str): + logging.debug(f"publish_si7021/{name}: {host}:{port}") + + try: + now = time.time() + socket = MySimpleSocketClient(host, port) + + socket.write('read') + response = json.loads(socket.read().strip()) + + temp = response['temp'] + humidity = response['humidity'] + + logging.debug(f'publish_si7021/{name}: temp={temp} humidity={humidity}') + + packer = Temperature() + self.client.publish(f'home/{self.home_id}/si7021/{name}', + payload=packer.pack(round(now), temp, humidity), + qos=1) + except Exception as e: + logger.exception(e) + + +if __name__ == '__main__': + config.load('sensors_mqtt_sender') + + client = MQTTClient() + client.configure_tls() + client.connect_and_loop(loop_forever=False) + client.poll() |