#!/usr/bin/env python3 import sys import time if sys.implementation.name != 'micropython': import argparse from . import sensorlib from .mqttlib import MQTTClient else: import sensorlib from mqttlib import MQTTClient def main(): if sys.implementation.name != 'micropython': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", default="/etc/mqtt-sensord.conf") args = parser.parse_args() config_path = args.config else: # most probably on micropython config_path = "mqtt-sensord.conf" config = sensorlib.load_config(config_path) sensorlib.Sensor.configure(config['host']['name'], sys.platform) mcfg = config['mqtt'] if 'client_id' in config['mqtt']: client_id = config['mqtt']['client_id'] else: client_id = None mqtt = MQTTClient(mcfg['host'], mcfg['user'], mcfg['password'], client_id) mqtt_topic = mcfg['sensor_topic'] print("Connected to", mqtt.host, "with topic", mqtt_topic) mqtt.set_callback(sensorlib.Sensor.run_mqtt_callback) sensors = [] extra_topics = set() for scfg in config['sensors']: s = sensorlib.Sensor.make_sensor(**scfg) s.register_callbacks() for topic in s.get_topics(): extra_topics.add(topic) sensors.append(s) for topic in extra_topics: print("Subscribe to", topic) mqtt.subscribe(topic) last_measurement = time.time() while True: # handle regular sensor data print("Getting values from sensors...") for sensor in sensors: if sensor.HAS_SENSOR_DATA: data = sensor.gen_datapoint() print(mqtt_topic, data) mqtt.send_data(mqtt_topic, data) if not mqtt.is_async(): mqtt.process_mqtt() if mqtt.is_async(): time.sleep(max(0.0, time.time() + config['host']['interval'] - last_measurement)) else: while time.time() - last_measurement < config['host']['interval']: mqtt.process_mqtt() time.sleep(0.1) last_measurement = time.time() if __name__ == '__main__': main()