miflora-mqtt-daemon.py 19 KB

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