miflora-mqtt-daemon.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #!/usr/bin/env python3
  2. import ssl
  3. import sys
  4. import re
  5. import json
  6. import os.path
  7. import os
  8. import argparse
  9. from time import time, sleep, localtime, strftime
  10. from collections import OrderedDict
  11. from colorama import init as colorama_init
  12. from colorama import Fore, Back, Style
  13. from configparser import ConfigParser
  14. from unidecode import unidecode
  15. from miflora.miflora_poller import MiFloraPoller, MI_BATTERY, MI_CONDUCTIVITY, MI_LIGHT, MI_MOISTURE, MI_TEMPERATURE
  16. from btlewrap import BluepyBackend, GatttoolBackend, BluetoothBackendException
  17. import paho.mqtt.client as mqtt
  18. import sdnotify
  19. project_name = 'Xiaomi Mi Flora Plant Sensor MQTT Client/Daemon'
  20. project_url = 'https://github.com/ThomDietrich/miflora-mqtt-daemon'
  21. parameters = OrderedDict([
  22. (MI_LIGHT, dict(name="LightIntensity", name_pretty='Sunlight Intensity', typeformat='%d', unit='lux', device_class="illuminance")),
  23. (MI_TEMPERATURE, dict(name="AirTemperature", name_pretty='Air Temperature', typeformat='%.1f', unit='°C', device_class="temperature")),
  24. (MI_MOISTURE, dict(name="SoilMoisture", name_pretty='Soil Moisture', typeformat='%d', unit='%', device_class="humidity")),
  25. (MI_CONDUCTIVITY, dict(name="SoilConductivity", name_pretty='Soil Conductivity/Fertility', typeformat='%d', unit='µS/cm')),
  26. (MI_BATTERY, dict(name="Battery", name_pretty='Sensor Battery Level', typeformat='%d', unit='%', device_class="battery"))
  27. ])
  28. if False:
  29. # will be caught by python 2.7 to be illegal syntax
  30. print('Sorry, this script requires a python3 runtime environemt.', file=sys.stderr)
  31. # Argparse
  32. parser = argparse.ArgumentParser(description=project_name, epilog='For further details see: ' + project_url)
  33. parser.add_argument('--gen-openhab', help='generate openHAB items based on configured sensors', action='store_true')
  34. parser.add_argument('--config_dir', help='set directory where config.ini is located', default=sys.path[0])
  35. parse_args = parser.parse_args()
  36. # Intro
  37. colorama_init()
  38. print(Fore.GREEN + Style.BRIGHT)
  39. print(project_name)
  40. print('Source:', project_url)
  41. print(Style.RESET_ALL)
  42. # Systemd Service Notifications - https://github.com/bb4242/sdnotify
  43. sd_notifier = sdnotify.SystemdNotifier()
  44. # Logging function
  45. def print_line(text, error = False, warning=False, sd_notify=False, console=True):
  46. timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime())
  47. if console:
  48. if error:
  49. print(Fore.RED + Style.BRIGHT + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL, file=sys.stderr)
  50. elif warning:
  51. print(Fore.YELLOW + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL)
  52. else:
  53. print(Fore.GREEN + '[{}] '.format(timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL)
  54. timestamp_sd = strftime('%b %d %H:%M:%S', localtime())
  55. if sd_notify:
  56. sd_notifier.notify('STATUS={} - {}.'.format(timestamp_sd, unidecode(text)))
  57. # Identifier cleanup
  58. def clean_identifier(name):
  59. clean = name.strip()
  60. for this, that in [[' ', '-'], ['ä', 'ae'], ['Ä', 'Ae'], ['ö', 'oe'], ['Ö', 'Oe'], ['ü', 'ue'], ['Ü', 'Ue'], ['ß', 'ss']]:
  61. clean = clean.replace(this, that)
  62. clean = unidecode(clean)
  63. return clean
  64. # Eclipse Paho callbacks - http://www.eclipse.org/paho/clients/python/docs/#callbacks
  65. def on_connect(client, userdata, flags, rc):
  66. if rc == 0:
  67. print_line('MQTT connection established', console=True, sd_notify=True)
  68. print()
  69. else:
  70. print_line('Connection error with result code {} - {}'.format(str(rc), mqtt.connack_string(rc)), error=True)
  71. #kill main thread
  72. os._exit(1)
  73. def on_publish(client, userdata, mid):
  74. #print_line('Data successfully published.')
  75. pass
  76. def flores_to_openhab_items(flores, reporting_mode):
  77. print_line('Generating openHAB items. Copy to your configuration and modify as needed...')
  78. items = list()
  79. items.append('// miflora.items - Generated by miflora-mqtt-daemon.')
  80. items.append('// Adapt to your needs! Things you probably want to modify:')
  81. items.append('// Room group names, icons,')
  82. items.append('// "gAll", "broker", "UnknownRoom"')
  83. items.append('')
  84. items.append('// Mi Flora specific groups')
  85. items.append('Group gMiFlora "All Mi Flora sensors and elements" (gAll)')
  86. for param, param_properties in parameters.items():
  87. items.append('Group g{} "Mi Flora {} elements" (gAll, gMiFlora)'.format(param_properties['name'], param_properties['name_pretty']))
  88. if reporting_mode == 'mqtt-json':
  89. for [flora_name, flora] in flores.items():
  90. location = flora['location_clean'] if flora['location_clean'] else 'UnknownRoom'
  91. items.append('\n// Mi Flora "{}" ({})'.format(flora['name_pretty'], flora['mac']))
  92. items.append('Group g{}{} "Mi Flora Sensor {}" (gMiFlora, g{})'.format(location, flora_name, flora['name_pretty'], location))
  93. for [param, param_properties] in parameters.items():
  94. basic = 'Number {}_{}_{}'.format(location, flora_name, param_properties['name'])
  95. label = '"{} {} {} [{} {}]"'.format(location, flora['name_pretty'], param_properties['name_pretty'], param_properties['typeformat'], param_properties['unit'].replace('%', '%%'))
  96. details = '<text> (g{}{}, g{})'.format(location, flora_name, param_properties['name'])
  97. channel = '{{mqtt="<[broker:{}/{}:state:JSONPATH($.{})]"}}'.format(base_topic, flora_name, param)
  98. items.append(' '.join([basic, label, details, channel]))
  99. items.append('')
  100. print('\n'.join(items))
  101. #elif reporting_mode == 'mqtt-homie':
  102. else:
  103. raise IOError('Given reporting_mode not supported for the export to openHAB items')
  104. # Load configuration file
  105. config_dir = parse_args.config_dir
  106. config = ConfigParser(delimiters=('=', ), inline_comment_prefixes=('#'))
  107. config.optionxform = str
  108. config.read([os.path.join(config_dir, 'config.ini.dist'), os.path.join(config_dir, 'config.ini')])
  109. reporting_mode = config['General'].get('reporting_method', 'mqtt-json')
  110. used_adapter = config['General'].get('adapter', 'hci0')
  111. daemon_enabled = config['Daemon'].getboolean('enabled', True)
  112. if reporting_mode == 'mqtt-homie':
  113. default_base_topic = 'homie'
  114. elif reporting_mode == 'homeassistant-mqtt':
  115. default_base_topic = 'homeassistant'
  116. elif reporting_mode == 'thingsboard-json':
  117. default_base_topic = 'v1/devices/me/telemetry'
  118. elif reporting_mode == 'wirenboard-mqtt':
  119. default_base_topic = ''
  120. else:
  121. default_base_topic = 'miflora'
  122. base_topic = config['MQTT'].get('base_topic', default_base_topic).lower()
  123. device_id = config['MQTT'].get('homie_device_id', 'miflora-mqtt-daemon').lower()
  124. sleep_period = config['Daemon'].getint('period', 300)
  125. miflora_cache_timeout = sleep_period - 1
  126. # Check configuration
  127. if reporting_mode not in ['mqtt-json', 'mqtt-homie', 'json', 'mqtt-smarthome', 'homeassistant-mqtt', 'thingsboard-json', 'wirenboard-mqtt']:
  128. print_line('Configuration parameter reporting_mode set to an invalid value', error=True, sd_notify=True)
  129. sys.exit(1)
  130. if not config['Sensors']:
  131. print_line('No sensors found in configuration file "config.ini"', error=True, sd_notify=True)
  132. sys.exit(1)
  133. if reporting_mode == 'wirenboard-mqtt' and base_topic:
  134. print_line('Parameter "base_topic" ignored for "reporting_method = wirenboard-mqtt"', warning=True, sd_notify=True)
  135. print_line('Configuration accepted', console=False, sd_notify=True)
  136. # MQTT connection
  137. if reporting_mode in ['mqtt-json', 'mqtt-homie', 'mqtt-smarthome', 'homeassistant-mqtt', 'thingsboard-json', 'wirenboard-mqtt']:
  138. print_line('Connecting to MQTT broker ...')
  139. mqtt_client = mqtt.Client()
  140. mqtt_client.on_connect = on_connect
  141. mqtt_client.on_publish = on_publish
  142. if reporting_mode == 'mqtt-json':
  143. mqtt_client.will_set('{}/$announce'.format(base_topic), payload='{}', retain=True)
  144. elif reporting_mode == 'mqtt-homie':
  145. mqtt_client.will_set('{}/{}/$online'.format(base_topic, device_id), payload='false', retain=True)
  146. elif reporting_mode == 'mqtt-smarthome':
  147. mqtt_client.will_set('{}/connected'.format(base_topic), payload='0', retain=True)
  148. if config['MQTT'].getboolean('tls', False):
  149. # According to the docs, setting PROTOCOL_SSLv23 "Selects the highest protocol version
  150. # that both the client and server support. Despite the name, this option can select
  151. # “TLS” protocols as well as “SSL”" - so this seems like a resonable default
  152. mqtt_client.tls_set(
  153. ca_certs=config['MQTT'].get('tls_ca_cert', None),
  154. keyfile=config['MQTT'].get('tls_keyfile', None),
  155. certfile=config['MQTT'].get('tls_certfile', None),
  156. tls_version=ssl.PROTOCOL_SSLv23
  157. )
  158. mqtt_username = os.environ.get("MQTT_USERNAME", config['MQTT'].get('username'))
  159. mqtt_password = os.environ.get("MQTT_PASSWORD", config['MQTT'].get('password', None))
  160. if mqtt_username:
  161. mqtt_client.username_pw_set(mqtt_username, mqtt_password)
  162. try:
  163. mqtt_client.connect(os.environ.get('MQTT_HOSTNAME', config['MQTT'].get('hostname', 'localhost')),
  164. port=int(os.environ.get('MQTT_PORT', config['MQTT'].get('port', '1883'))),
  165. keepalive=config['MQTT'].getint('keepalive', 60))
  166. except:
  167. print_line('MQTT connection error. Please check your settings in the configuration file "config.ini"', error=True, sd_notify=True)
  168. sys.exit(1)
  169. else:
  170. if reporting_mode == 'mqtt-smarthome':
  171. mqtt_client.publish('{}/connected'.format(base_topic), payload='1', retain=True)
  172. if reporting_mode != 'thingsboard-json':
  173. mqtt_client.loop_start()
  174. sleep(1.0) # some slack to establish the connection
  175. sd_notifier.notify('READY=1')
  176. # Initialize Mi Flora sensors
  177. flores = OrderedDict()
  178. for [name, mac] in config['Sensors'].items():
  179. if not re.match("[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}", mac.lower()):
  180. print_line('The MAC address "{}" seems to be in the wrong format. Please check your configuration'.format(mac), error=True, sd_notify=True)
  181. sys.exit(1)
  182. if '@' in name:
  183. name_pretty, location_pretty = name.split('@')
  184. else:
  185. name_pretty, location_pretty = name, ''
  186. name_clean = clean_identifier(name_pretty)
  187. location_clean = clean_identifier(location_pretty)
  188. flora = dict()
  189. print('Adding sensor to device list and testing connection ...')
  190. print('Name: "{}"'.format(name_pretty))
  191. #print_line('Attempting initial connection to Mi Flora sensor "{}" ({})'.format(name_pretty, mac), console=False, sd_notify=True)
  192. flora_poller = MiFloraPoller(mac=mac, backend=BluepyBackend, cache_timeout=miflora_cache_timeout, retries=3, adapter=used_adapter)
  193. flora['poller'] = flora_poller
  194. flora['name_pretty'] = name_pretty
  195. flora['mac'] = flora_poller._mac
  196. flora['refresh'] = sleep_period
  197. flora['location_clean'] = location_clean
  198. flora['location_pretty'] = location_pretty
  199. flora['stats'] = {"count": 0, "success": 0, "failure": 0}
  200. try:
  201. flora_poller.fill_cache()
  202. flora_poller.parameter_value(MI_LIGHT)
  203. flora['firmware'] = flora_poller.firmware_version()
  204. except (IOError, BluetoothBackendException):
  205. print_line('Initial connection to Mi Flora sensor "{}" ({}) failed.'.format(name_pretty, mac), error=True, sd_notify=True)
  206. else:
  207. print('Internal name: "{}"'.format(name_clean))
  208. print('Device name: "{}"'.format(flora_poller.name()))
  209. print('MAC address: {}'.format(flora_poller._mac))
  210. print('Firmware: {}'.format(flora_poller.firmware_version()))
  211. print_line('Initial connection to Mi Flora sensor "{}" ({}) successful'.format(name_pretty, mac), sd_notify=True)
  212. if int(flora_poller.firmware_version().replace(".", "")) < 319:
  213. print_line('Mi Flora sensor with a firmware version before 3.1.9 is not supported. Please update now.'.format(name_pretty, mac), error=True, sd_notify=True)
  214. print()
  215. flores[name_clean] = flora
  216. # openHAB items generation
  217. if parse_args.gen_openhab:
  218. flores_to_openhab_items(flores, reporting_mode)
  219. sys.exit(0)
  220. # Discovery Announcement
  221. if reporting_mode == 'mqtt-json':
  222. print_line('Announcing Mi Flora devices to MQTT broker for auto-discovery ...')
  223. flores_info = dict()
  224. for [flora_name, flora] in flores.items():
  225. flora_info = {key: value for key, value in flora.items() if key not in ['poller', 'stats']}
  226. flora_info['topic'] = '{}/{}'.format(base_topic, flora_name)
  227. flores_info[flora_name] = flora_info
  228. mqtt_client.publish('{}/$announce'.format(base_topic), json.dumps(flores_info), retain=True)
  229. sleep(0.5) # some slack for the publish roundtrip and callback function
  230. print()
  231. elif reporting_mode == 'mqtt-homie':
  232. print_line('Announcing Mi Flora devices to MQTT broker for auto-discovery ...')
  233. mqtt_client.publish('{}/{}/$homie'.format(base_topic, device_id), '2.1.0-alpha', 1, True)
  234. mqtt_client.publish('{}/{}/$online'.format(base_topic, device_id), 'true', 1, True)
  235. mqtt_client.publish('{}/{}/$name'.format(base_topic, device_id), device_id, 1, True)
  236. mqtt_client.publish('{}/{}/$fw/version'.format(base_topic, device_id), flora['firmware'], 1, True)
  237. nodes_list = ','.join([flora_name for [flora_name, flora] in flores.items()])
  238. mqtt_client.publish('{}/{}/$nodes'.format(base_topic, device_id), nodes_list, 1, True)
  239. for [flora_name, flora] in flores.items():
  240. topic_path = '{}/{}/{}'.format(base_topic, device_id, flora_name)
  241. mqtt_client.publish('{}/$name'.format(topic_path), flora['name_pretty'], 1, True)
  242. mqtt_client.publish('{}/$type'.format(topic_path), 'miflora', 1, True)
  243. mqtt_client.publish('{}/$properties'.format(topic_path), 'battery,conductivity,light,moisture,temperature', 1, True)
  244. mqtt_client.publish('{}/battery/$settable'.format(topic_path), 'false', 1, True)
  245. mqtt_client.publish('{}/battery/$unit'.format(topic_path), 'percent', 1, True)
  246. mqtt_client.publish('{}/battery/$datatype'.format(topic_path), 'int', 1, True)
  247. mqtt_client.publish('{}/battery/$range'.format(topic_path), '0:100', 1, True)
  248. mqtt_client.publish('{}/conductivity/$settable'.format(topic_path), 'false', 1, True)
  249. mqtt_client.publish('{}/conductivity/$unit'.format(topic_path), 'µS/cm', 1, True)
  250. mqtt_client.publish('{}/conductivity/$datatype'.format(topic_path), 'int', 1, True)
  251. mqtt_client.publish('{}/conductivity/$range'.format(topic_path), '0:*', 1, True)
  252. mqtt_client.publish('{}/light/$settable'.format(topic_path), 'false', 1, True)
  253. mqtt_client.publish('{}/light/$unit'.format(topic_path), 'lux', 1, True)
  254. mqtt_client.publish('{}/light/$datatype'.format(topic_path), 'int', 1, True)
  255. mqtt_client.publish('{}/light/$range'.format(topic_path), '0:50000', 1, True)
  256. mqtt_client.publish('{}/moisture/$settable'.format(topic_path), 'false', 1, True)
  257. mqtt_client.publish('{}/moisture/$unit'.format(topic_path), 'percent', 1, True)
  258. mqtt_client.publish('{}/moisture/$datatype'.format(topic_path), 'int', 1, True)
  259. mqtt_client.publish('{}/moisture/$range'.format(topic_path), '0:100', 1, True)
  260. mqtt_client.publish('{}/temperature/$settable'.format(topic_path), 'false', 1, True)
  261. mqtt_client.publish('{}/temperature/$unit'.format(topic_path), '°C', 1, True)
  262. mqtt_client.publish('{}/temperature/$datatype'.format(topic_path), 'float', 1, True)
  263. mqtt_client.publish('{}/temperature/$range'.format(topic_path), '*', 1, True)
  264. sleep(0.5) # some slack for the publish roundtrip and callback function
  265. print()
  266. elif reporting_mode == 'homeassistant-mqtt':
  267. print_line('Announcing Mi Flora devices to MQTT broker for auto-discovery ...')
  268. for [flora_name, flora] in flores.items():
  269. state_topic = '{}/sensor/{}'.format(base_topic, flora_name.lower())
  270. for [sensor, params] in parameters.items():
  271. discovery_topic = 'homeassistant/sensor/{}_{}/config'.format(flora_name, sensor).lower()
  272. payload = OrderedDict()
  273. payload['name'] = "{} {}".format(flora_name, sensor.title())
  274. payload['unique_id'] = "{}-{}".format(flora['mac'].lower().replace(":", ""), sensor)
  275. payload['unit_of_measurement'] = params['unit']
  276. if 'device_class' in params:
  277. payload['device_class'] = params['device_class']
  278. payload['state_topic'] = state_topic
  279. payload['value_template'] = "{{{{ value_json.{} }}}}".format(sensor)
  280. payload['device'] = {
  281. 'identifiers' : ["MiFlora{}".format(flora['mac'].lower().replace(":", ""))],
  282. 'connections' : [["mac", flora['mac'].lower()]],
  283. 'manufacturer' : 'Xiaomi',
  284. 'name' : flora_name,
  285. 'model' : 'MiFlora Plant Sensor (HHCCJCY01)',
  286. 'sw_version': flora['firmware']
  287. }
  288. mqtt_client.publish(discovery_topic, json.dumps(payload), 1, True)
  289. elif reporting_mode == 'wirenboard-mqtt':
  290. print_line('Announcing Mi Flora devices to MQTT broker for auto-discovery ...')
  291. for [flora_name, flora] in flores.items():
  292. mqtt_client.publish('/devices/{}/meta/name'.format(flora_name), flora_name, 1, True)
  293. topic_path = '/devices/{}/controls'.format(flora_name)
  294. mqtt_client.publish('{}/battery/meta/type'.format(topic_path), 'value', 1, True)
  295. mqtt_client.publish('{}/battery/meta/units'.format(topic_path), '%', 1, True)
  296. mqtt_client.publish('{}/conductivity/meta/type'.format(topic_path), 'value', 1, True)
  297. mqtt_client.publish('{}/conductivity/meta/units'.format(topic_path), 'µS/cm', 1, True)
  298. mqtt_client.publish('{}/light/meta/type'.format(topic_path), 'value', 1, True)
  299. mqtt_client.publish('{}/light/meta/units'.format(topic_path), 'lux', 1, True)
  300. mqtt_client.publish('{}/moisture/meta/type'.format(topic_path), 'rel_humidity', 1, True)
  301. mqtt_client.publish('{}/temperature/meta/type'.format(topic_path), 'temperature', 1, True)
  302. mqtt_client.publish('{}/timestamp/meta/type'.format(topic_path), 'text', 1, True)
  303. sleep(0.5) # some slack for the publish roundtrip and callback function
  304. print()
  305. print_line('Initialization complete, starting MQTT publish loop', console=False, sd_notify=True)
  306. # Sensor data retrieval and publication
  307. while True:
  308. for [flora_name, flora] in flores.items():
  309. data = dict()
  310. attempts = 2
  311. flora['poller']._cache = None
  312. flora['poller']._last_read = None
  313. flora['stats']['count'] = flora['stats']['count'] + 1
  314. print_line('Retrieving data from sensor "{}" ...'.format(flora['name_pretty']))
  315. while attempts != 0 and not flora['poller']._cache:
  316. try:
  317. flora['poller'].fill_cache()
  318. flora['poller'].parameter_value(MI_LIGHT)
  319. except (IOError, BluetoothBackendException):
  320. attempts = attempts - 1
  321. if attempts > 0:
  322. print_line('Retrying ...', warning = True)
  323. flora['poller']._cache = None
  324. flora['poller']._last_read = None
  325. if not flora['poller']._cache:
  326. flora['stats']['failure'] = flora['stats']['failure'] + 1
  327. print_line('Failed to retrieve data from Mi Flora sensor "{}" ({}), success rate: {:.0%}'.format(
  328. flora['name_pretty'], flora['mac'], flora['stats']['success']/flora['stats']['count']
  329. ), error = True, sd_notify = True)
  330. print()
  331. continue
  332. else:
  333. flora['stats']['success'] = flora['stats']['success'] + 1
  334. for param,_ in parameters.items():
  335. data[param] = flora['poller'].parameter_value(param)
  336. print_line('Result: {}'.format(json.dumps(data)))
  337. if reporting_mode == 'mqtt-json':
  338. print_line('Publishing to MQTT topic "{}/{}"'.format(base_topic, flora_name))
  339. mqtt_client.publish('{}/{}'.format(base_topic, flora_name), json.dumps(data))
  340. sleep(0.5) # some slack for the publish roundtrip and callback function
  341. elif reporting_mode == 'thingsboard-json':
  342. print_line('Publishing to MQTT topic "{}" username "{}"'.format(base_topic, flora_name))
  343. mqtt_client.username_pw_set(flora_name)
  344. mqtt_client.reconnect()
  345. sleep(1.0)
  346. mqtt_client.publish('{}'.format(base_topic), json.dumps(data))
  347. sleep(0.5) # some slack for the publish roundtrip and callback function
  348. elif reporting_mode == 'homeassistant-mqtt':
  349. print_line('Publishing to MQTT topic "{}/sensor/{}"'.format(base_topic, flora_name.lower()))
  350. mqtt_client.publish('{}/sensor/{}'.format(base_topic, flora_name.lower()), json.dumps(data))
  351. sleep(0.5) # some slack for the publish roundtrip and callback function
  352. elif reporting_mode == 'mqtt-homie':
  353. print_line('Publishing data to MQTT base topic "{}/{}/{}"'.format(base_topic, device_id, flora_name))
  354. for [param, value] in data.items():
  355. mqtt_client.publish('{}/{}/{}/{}'.format(base_topic, device_id, flora_name, param), value, 1, True)
  356. sleep(0.5) # some slack for the publish roundtrip and callback function
  357. elif reporting_mode == 'mqtt-smarthome':
  358. for [param, value] in data.items():
  359. print_line('Publishing data to MQTT topic "{}/status/{}/{}"'.format(base_topic, flora_name, param))
  360. payload = dict()
  361. payload['val'] = value
  362. payload['ts'] = int(round(time() * 1000))
  363. mqtt_client.publish('{}/status/{}/{}'.format(base_topic, flora_name, param), json.dumps(payload), retain=True)
  364. sleep(0.5) # some slack for the publish roundtrip and callback function
  365. elif reporting_mode == 'wirenboard-mqtt':
  366. for [param, value] in data.items():
  367. print_line('Publishing data to MQTT topic "/devices/{}/controls/{}"'.format(flora_name, param))
  368. mqtt_client.publish('/devices/{}/controls/{}'.format(flora_name, param), value, retain=True)
  369. mqtt_client.publish('/devices/{}/controls/{}'.format(flora_name, 'timestamp'), strftime('%Y-%m-%d %H:%M:%S', localtime()), retain=True)
  370. sleep(0.5) # some slack for the publish roundtrip and callback function
  371. elif reporting_mode == 'json':
  372. data['timestamp'] = strftime('%Y-%m-%d %H:%M:%S', localtime())
  373. data['name'] = flora_name
  374. data['name_pretty'] = flora['name_pretty']
  375. data['mac'] = flora['mac']
  376. data['firmware'] = flora['firmware']
  377. print('Data for "{}": {}'.format(flora_name, json.dumps(data)))
  378. else:
  379. raise NameError('Unexpected reporting_mode.')
  380. print()
  381. print_line('Status messages published', console=False, sd_notify=True)
  382. if daemon_enabled:
  383. print_line('Sleeping ({} seconds) ...'.format(sleep_period))
  384. sleep(sleep_period)
  385. print()
  386. else:
  387. print_line('Execution finished in non-daemon-mode', sd_notify=True)
  388. if reporting_mode == 'mqtt-json':
  389. mqtt_client.disconnect()
  390. break