2017-02-09 21:15:25 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2017-07-24 10:41:39 +02:00
|
|
|
import sys
|
2017-02-09 21:15:25 +01:00
|
|
|
import json
|
2017-07-25 00:02:18 +02:00
|
|
|
import os.path
|
2017-07-24 10:41:39 +02:00
|
|
|
from time import sleep, localtime, strftime
|
|
|
|
from configparser import ConfigParser
|
|
|
|
from miflora.miflora_poller import MiFloraPoller, MI_BATTERY, MI_CONDUCTIVITY, MI_LIGHT, MI_MOISTURE, MI_TEMPERATURE
|
|
|
|
import paho.mqtt.client as mqtt
|
2017-07-26 02:17:20 +02:00
|
|
|
import sdnotify
|
2017-07-24 10:41:39 +02:00
|
|
|
|
|
|
|
parameters = [MI_BATTERY, MI_CONDUCTIVITY, MI_LIGHT, MI_MOISTURE, MI_TEMPERATURE]
|
2017-02-09 21:15:25 +01:00
|
|
|
|
2017-07-26 00:19:26 +02:00
|
|
|
# Intro
|
2017-07-24 10:41:39 +02:00
|
|
|
print('Xiaomi Mi Flora Plant Sensor MQTT Client/Daemon')
|
2017-07-26 00:19:26 +02:00
|
|
|
print('Source: https://github.com/ThomDietrich/miflora-mqtt-daemon')
|
2017-07-24 10:41:39 +02:00
|
|
|
print()
|
2017-02-09 21:15:25 +01:00
|
|
|
|
2017-07-26 02:17:20 +02:00
|
|
|
# Systemd Service Notifications - https://github.com/bb4242/sdnotify
|
|
|
|
sd_notifier = sdnotify.SystemdNotifier()
|
|
|
|
|
|
|
|
# Eclipse Paho callbacks - http://www.eclipse.org/paho/clients/python/docs/#callbacks
|
2017-07-25 17:17:20 +02:00
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
|
|
if rc == 0:
|
|
|
|
print('Connected.\n')
|
2017-07-26 02:17:20 +02:00
|
|
|
sd_notifier.notify('STATUS=MQTT connection established')
|
2017-07-25 17:17:20 +02:00
|
|
|
else:
|
|
|
|
print('Connection error with result code {} - {}'.format(str(rc), mqtt.connack_string(rc)), file=sys.stderr)
|
|
|
|
#kill main thread
|
|
|
|
os._exit(1)
|
|
|
|
|
|
|
|
def on_publish(client, userdata, mid):
|
2017-07-27 00:49:57 +02:00
|
|
|
print('Data successfully published.')
|
2017-07-25 17:17:20 +02:00
|
|
|
|
2017-07-24 10:41:39 +02:00
|
|
|
# Load configuration file
|
2017-02-09 21:15:25 +01:00
|
|
|
config = ConfigParser(delimiters=('=', ))
|
2017-07-24 10:41:39 +02:00
|
|
|
config.optionxform = str
|
2017-07-26 02:17:20 +02:00
|
|
|
config.read([os.path.join(sys.path[0], 'config.ini'), os.path.join(sys.path[0], 'config.local.ini')])
|
2017-07-25 17:17:20 +02:00
|
|
|
|
|
|
|
reporting_mode = config['General'].get('reporting_method', 'mqtt-json')
|
2017-07-24 10:41:39 +02:00
|
|
|
daemon_enabled = config['Daemon'].getboolean('enabled', True)
|
|
|
|
topic_prefix = config['MQTT'].get('topic_prefix', 'miflora')
|
2017-07-26 00:19:26 +02:00
|
|
|
sleep_period = config['Daemon'].getint('period', 300)
|
|
|
|
#miflora_cache_timeout = config['MiFlora'].getint('cache_timeout', 600)
|
|
|
|
miflora_cache_timeout = sleep_period - 1
|
2017-07-25 17:17:20 +02:00
|
|
|
|
2017-07-26 00:19:26 +02:00
|
|
|
# Check configuration
|
2017-07-25 17:17:20 +02:00
|
|
|
if not reporting_mode in ['mqtt-json', 'json']:
|
|
|
|
print('Error. Configuration parameter reporting_mode set to an invalid value.', file=sys.stderr)
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS=Configuration parameter reporting_mode set to an invalid value')
|
2017-07-25 17:17:20 +02:00
|
|
|
sys.exit(1)
|
2017-07-24 10:41:39 +02:00
|
|
|
if not config['Sensors']:
|
|
|
|
print('Error. Please add at least one sensor to the configuration file "config.ini".', file=sys.stderr)
|
2017-07-26 00:19:26 +02:00
|
|
|
print('Scan for available Miflora sensors with "sudo hcitool lescan".', file=sys.stderr)
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS=No sensors found in configuration file "config.ini"')
|
2017-07-24 10:41:39 +02:00
|
|
|
sys.exit(1)
|
2017-07-26 02:17:20 +02:00
|
|
|
sd_notifier.notify('STATUS=Configuration accepted')
|
2017-02-09 21:15:25 +01:00
|
|
|
|
2017-07-25 17:17:20 +02:00
|
|
|
# MQTT connection
|
|
|
|
if reporting_mode == 'mqtt-json':
|
|
|
|
print('Connecting to MQTT broker ...')
|
|
|
|
mqtt_client = mqtt.Client()
|
|
|
|
mqtt_client.on_connect = on_connect
|
|
|
|
mqtt_client.on_publish = on_publish
|
|
|
|
if config['MQTT'].get('username'):
|
|
|
|
mqtt_client.username_pw_set(config['MQTT'].get('username'), config['MQTT'].get('password', None))
|
|
|
|
try:
|
|
|
|
mqtt_client.connect(config['MQTT'].get('hostname', 'localhost'),
|
|
|
|
port=config['MQTT'].getint('port', 1883),
|
|
|
|
keepalive=config['MQTT'].getint('keepalive', 60))
|
|
|
|
except:
|
|
|
|
print('Error. Please check your MQTT connection settings in the configuration file "config.ini".', file=sys.stderr)
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS=Please check your MQTT connection settings in the configuration file "config.ini"')
|
2017-07-25 17:17:20 +02:00
|
|
|
sys.exit(1)
|
|
|
|
else:
|
|
|
|
mqtt_client.loop_start()
|
2017-07-27 00:49:57 +02:00
|
|
|
sleep(0.5) # some slack to establish the connection
|
|
|
|
mqtt_client.publish('{}/$announce'.format(topic_prefix), payload='{}', retain=True)
|
|
|
|
sleep(0.5) # some slack for the publish roundtrip and callback function
|
2017-07-25 17:17:20 +02:00
|
|
|
|
2017-07-26 02:17:20 +02:00
|
|
|
sd_notifier.notify('READY=1')
|
|
|
|
|
2017-07-24 10:41:39 +02:00
|
|
|
# Initialize Mi Flora sensors
|
2017-07-26 00:19:26 +02:00
|
|
|
flores = dict()
|
|
|
|
for [name, mac] in config['Sensors'].items():
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS=Attempting initial connection to MiFlora sensor "{}" ({})'.format(name, mac))
|
|
|
|
print('Adding sensor to device list and testing connection...')
|
2017-07-26 00:19:26 +02:00
|
|
|
print('Name: "{}"'.format(name))
|
|
|
|
flora_poller = MiFloraPoller(mac=mac, cache_timeout=miflora_cache_timeout, retries=9)
|
2017-07-27 00:21:15 +02:00
|
|
|
try:
|
2017-07-27 21:51:38 +02:00
|
|
|
flora_poller.fill_cache()
|
2017-07-27 00:21:15 +02:00
|
|
|
flora_poller.parameter_value(MI_LIGHT)
|
|
|
|
except IOError:
|
2017-07-27 21:51:38 +02:00
|
|
|
print('Error. Initial connection to Mi Flora sensor "{}" ({}) failed. Please check your setup and the MAC address.'.format(name, mac), file=sys.stderr)
|
|
|
|
sd_notifier.notify('STATUS=Initial connection to Mi Flora sensor "{}" ({}) failed'.format(name, mac))
|
2017-07-27 00:21:15 +02:00
|
|
|
sys.exit(1)
|
|
|
|
else:
|
|
|
|
print('Device name: "{}"'.format(flora_poller.name()))
|
|
|
|
print('MAC address: {}'.format(flora_poller._mac))
|
|
|
|
print('Firmware: {}'.format(flora_poller.firmware_version()))
|
|
|
|
flores[name] = flora_poller
|
2017-07-24 10:41:39 +02:00
|
|
|
print()
|
2017-02-09 21:15:25 +01:00
|
|
|
|
2017-07-27 00:49:57 +02:00
|
|
|
# Discovery Announcement
|
|
|
|
print('Announcing MiFlora devices to MQTT broker for auto-discovery ...')
|
|
|
|
flores_info = dict()
|
|
|
|
for [flora_name, flora_poller] in flores.items():
|
|
|
|
flora_info = dict()
|
|
|
|
flora_info['mac'] = flora_poller._mac
|
|
|
|
flora_info['topic'] = '{}/{}'.format(topic_prefix, flora_name)
|
|
|
|
flora_info['firmware'] = flora_poller.firmware_version()
|
|
|
|
flora_info['refresh'] = sleep_period
|
|
|
|
flora_info['location'] = ''
|
|
|
|
flores_info[flora_name] = flora_info
|
|
|
|
mqtt_client.publish('{}/$announce'.format(topic_prefix), json.dumps(flores_info), retain=True)
|
|
|
|
sleep(0.5) # some slack for the publish roundtrip and callback function
|
|
|
|
|
2017-07-26 02:17:20 +02:00
|
|
|
sd_notifier.notify('STATUS=Initialization complete, starting MQTT publish loop')
|
|
|
|
|
2017-07-25 17:17:20 +02:00
|
|
|
# Sensor data retrieval and publication
|
2017-02-09 21:15:25 +01:00
|
|
|
while True:
|
2017-07-26 00:19:26 +02:00
|
|
|
for [flora_name, flora_poller] in flores.items():
|
|
|
|
data = dict()
|
2017-07-27 21:51:38 +02:00
|
|
|
while not flora_poller._cache:
|
|
|
|
try:
|
|
|
|
flora_poller.fill_cache()
|
|
|
|
except IOError:
|
|
|
|
print('Failed to retrieve data from Mi Flora Sensor "{}" ({}). Retrying ...'.format(name, mac), file=sys.stderr)
|
|
|
|
sd_notifier.notify('STATUS=Failed to retrieve data from Mi Flora Sensor "{}" ({}). Retrying ...'.format(name, mac))
|
2017-02-09 21:15:25 +01:00
|
|
|
for param in parameters:
|
2017-07-26 00:19:26 +02:00
|
|
|
data[param] = flora_poller.parameter_value(param)
|
2017-07-27 21:51:38 +02:00
|
|
|
|
2017-07-25 17:17:20 +02:00
|
|
|
timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime())
|
|
|
|
|
|
|
|
if reporting_mode == 'mqtt-json':
|
2017-07-26 00:19:26 +02:00
|
|
|
print('[{}] Attempting to publishing to MQTT topic "{}/{}" ...\nData: {}'.format(timestamp, topic_prefix, flora_name, json.dumps(data)))
|
|
|
|
mqtt_client.publish('{}/{}'.format(topic_prefix, flora_name), json.dumps(data))
|
2017-07-25 17:17:20 +02:00
|
|
|
sleep(0.5) # some slack for the publish roundtrip and callback function
|
|
|
|
print()
|
|
|
|
elif reporting_mode == 'json':
|
|
|
|
data['timestamp'] = timestamp
|
2017-07-26 00:19:26 +02:00
|
|
|
data['name'] = flora_name
|
|
|
|
data['mac'] = flora_poller._mac
|
2017-07-27 00:21:15 +02:00
|
|
|
data['firmware'] = flora_poller.firmware_version()
|
2017-07-26 00:19:26 +02:00
|
|
|
print('Data:', json.dumps(data))
|
2017-07-25 17:17:20 +02:00
|
|
|
else:
|
|
|
|
raise NameError('Unexpected reporting_mode.')
|
|
|
|
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS={} - Status messages for all sensors published'.format(strftime('%Y-%m-%d %H:%M:%S', localtime())))
|
2017-07-26 02:17:20 +02:00
|
|
|
|
2017-07-26 00:19:26 +02:00
|
|
|
if daemon_enabled:
|
2017-07-25 17:17:20 +02:00
|
|
|
print('Sleeping ({} seconds) ...'.format(sleep_period))
|
|
|
|
sleep(sleep_period)
|
|
|
|
print()
|
2017-07-26 00:19:26 +02:00
|
|
|
else:
|
2017-07-27 00:21:15 +02:00
|
|
|
sd_notifier.notify('STATUS=Execution finished in non-daemon-mode')
|
2017-07-26 02:17:20 +02:00
|
|
|
if reporting_mode == 'mqtt-json':
|
|
|
|
mqtt_client.disconnect()
|
2017-07-26 00:19:26 +02:00
|
|
|
break
|
2017-02-09 21:15:25 +01:00
|
|
|
|