mqtt-flora.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. import paho.mqtt.client as mqtt
  3. import time
  4. from miflora.miflora_poller import MiFloraPoller, \
  5. MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE
  6. from configparser import ConfigParser
  7. import json
  8. parameters = [MI_TEMPERATURE,
  9. MI_LIGHT,
  10. MI_MOISTURE,
  11. MI_CONDUCTIVITY]
  12. config = ConfigParser(delimiters=('=', ))
  13. config.read('config.ini')
  14. sleep_time = config['miflora'].getint('sleep', 60)
  15. topic_prefix = config['mqtt'].get('topic_prefix', 'miflora')
  16. miflora_timeout = config['miflora'].getint('timeout', 600)
  17. # The callback for when the client receives a CONNACK response from the server.
  18. def on_connect(client, userdata, flags, rc):
  19. print("Connected with result code "+str(rc))
  20. # Initialize Flora sensors
  21. flores = {}
  22. for flora in config['sensors'].items():
  23. print('Adding', flora[0])
  24. flores[flora[0]] = MiFloraPoller(
  25. mac=flora[1],
  26. cache_timeout=miflora_timeout)
  27. client = mqtt.Client()
  28. client.on_connect = on_connect
  29. client.connect(config['mqtt'].get('hostname', 'homeassistant'),
  30. config['mqtt'].getint('port', 1883),
  31. config['mqtt'].getint('timeout', 60))
  32. client.loop_start()
  33. while True:
  34. for flora in flores:
  35. print('Publishing for', flora)
  36. data = {}
  37. for param in parameters:
  38. data[param] = flores.get(flora).parameter_value(param)
  39. client.publish("{}/{}".format(
  40. topic_prefix,
  41. flora), json.dumps(data))
  42. print('Sleeping ...')
  43. time.sleep(sleep_time)