mqtt-sensord/mqtt_sensord/mqtt_sensord.py

55 lines
1.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")
args = parser.parse_args()
config_path = args.config
else:
# most probably on micropython
config_path = "mqtt-sensord.conf"
2019-07-09 22:01:39 +02:00
config = sensorlib.load_config(config_path)
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)
mqtt_topic = mcfg['sensor_topic']
print("Connected to", mqtt.host, "with topic", mqtt_topic)
sensors = []
for scfg in config['sensors']:
s = sensorlib.Sensor.make_sensor(**scfg)
sensors.append(s)
last_measurement = time.time()
while True:
print("Getting values from sensors...")
for sensor in sensors:
data = sensor.gen_datapoint()
print(mqtt_topic, data)
mqtt.send_data(mqtt_topic, data)
time.sleep(max(0.0, time.time() + config['host']['interval'] - last_measurement))
last_measurement = time.time()
if __name__ == '__main__':
main()