mqtt-tools/mqtt-config

45 lines
1.3 KiB
Plaintext
Raw Normal View History

2019-11-25 15:59:08 +00:00
#!/usr/bin/env python
import argparse
import yaml
import paho.mqtt.publish
def read_config(config_dict, base_topic=''):
ret = {}
for elem in config_dict:
if 'topic' not in elem:
raise Exception("Invalid config")
sep = '/' if base_topic else ''
topic = '{}{}{}'.format(base_topic.rstrip("/"), sep,
elem["topic"].lstrip("/"))
if 'children' in elem:
ret.update(read_config(elem['children'], base_topic=topic))
if 'value' in elem:
ret[topic] = elem['value']
return ret
def main():
options = argparse.ArgumentParser()
options.add_argument('--broker', '-b', default='localhost')
options.add_argument('--port', '-p', default='1883', type=int)
options.add_argument('config')
args = options.parse_args()
with open(args.config, 'r') as f:
config_dict = yaml.load(f, Loader=yaml.Loader)
topics = read_config(config_dict)
msgs = [(topic, value, 1, True) for topic, value in topics.items()]
paho.mqtt.publish.multiple(msgs,
hostname=args.broker,
port=args.port,
client_id='configuration')
if __name__ == '__main__':
main()