mqtt-sensord/mqtt_sensord/mqtt_sensord.py

82 lines
2.5 KiB
Python
Raw Normal View History

2019-07-09 22:01:39 +02:00
#!/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
2019-07-09 22:01:39 +02:00
def main():
if sys.implementation.name != 'micropython':
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", default="/etc/mqtt-sensord.conf")
2021-01-10 03:13:50 +01:00
parser.add_argument("-d", "--debug", action="store_true", default=False)
args = parser.parse_args()
config_path = args.config
2021-01-10 03:13:50 +01:00
debug = args.debug
else:
# most probably on micropython
config_path = "mqtt-sensord.conf"
2021-01-10 03:13:50 +01:00
debug = False
2019-07-09 22:01:39 +02:00
config = sensorlib.load_config(config_path)
2021-01-10 03:13:50 +01:00
debug = debug or config.get('debug')
config['debug'] = debug
2019-07-09 22:01:39 +02:00
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
2019-07-09 22:01:39 +02:00
mqtt = MQTTClient(mcfg['host'], mcfg['user'], mcfg['password'], client_id)
2021-01-10 03:16:51 +01:00
default_mqtt_topic = mcfg.get('sensor_topic')
print("Connected to", mqtt.host, "with default topic", default_mqtt_topic)
2019-07-31 22:31:50 +02:00
mqtt.set_callback(sensorlib.Sensor.run_mqtt_callback)
2019-07-09 22:01:39 +02:00
sensors = []
2019-07-31 22:31:50 +02:00
extra_topics = set()
2019-07-09 22:01:39 +02:00
for scfg in config['sensors']:
s = sensorlib.Sensor.make_sensor(**scfg)
2019-07-31 22:31:50 +02:00
s.register_callbacks()
for topic in s.get_topics():
extra_topics.add(topic)
2019-07-09 22:01:39 +02:00
sensors.append(s)
2019-07-31 22:31:50 +02:00
for topic in extra_topics:
print("Subscribe to", topic)
mqtt.subscribe(topic)
2019-07-09 22:01:39 +02:00
last_measurement = time.time()
while True:
2019-07-31 22:31:50 +02:00
# handle regular sensor data
2021-01-10 03:13:50 +01:00
if debug:
print("Getting values from sensors...")
2019-07-09 22:01:39 +02:00
for sensor in sensors:
2019-07-31 22:31:50 +02:00
if sensor.HAS_SENSOR_DATA:
data = sensor.gen_datapoint()
2021-01-10 03:13:50 +01:00
if debug:
2021-01-10 03:16:51 +01:00
print(default_mqtt_topic, data)
mqtt.send_data(default_mqtt_topic, data)
2019-07-31 22:31:50 +02:00
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)
2019-07-09 22:01:39 +02:00
last_measurement = time.time()
if __name__ == '__main__':
main()