2015-08-07 17:20:27 +00:00
|
|
|
"""
|
|
|
|
homeassistant.components.mqtt
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2015-10-23 20:34:02 +00:00
|
|
|
MQTT component, using paho-mqtt.
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-10-23 20:34:02 +00:00
|
|
|
For more details about this component, please refer to the documentation at
|
2015-11-09 12:12:18 +00:00
|
|
|
https://home-assistant.io/components/mqtt/
|
2015-08-07 17:20:27 +00:00
|
|
|
"""
|
2015-11-22 23:09:56 +00:00
|
|
|
import json
|
2015-08-07 17:20:27 +00:00
|
|
|
import logging
|
2015-09-30 07:09:07 +00:00
|
|
|
import os
|
2015-08-09 06:49:38 +00:00
|
|
|
import socket
|
2015-11-22 23:09:56 +00:00
|
|
|
import time
|
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-08-30 02:34:35 +00:00
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
2015-08-09 06:49:38 +00:00
|
|
|
import homeassistant.util as util
|
2015-08-07 17:20:27 +00:00
|
|
|
from homeassistant.helpers import validate_config
|
|
|
|
from homeassistant.const import (
|
|
|
|
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
DOMAIN = "mqtt"
|
2015-08-09 06:49:38 +00:00
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
MQTT_CLIENT = None
|
2015-08-09 06:49:38 +00:00
|
|
|
|
|
|
|
DEFAULT_PORT = 1883
|
|
|
|
DEFAULT_KEEPALIVE = 60
|
2015-09-10 06:37:15 +00:00
|
|
|
DEFAULT_QOS = 0
|
2015-11-24 20:30:06 +00:00
|
|
|
DEFAULT_RETAIN = False
|
2015-08-09 06:49:38 +00:00
|
|
|
|
|
|
|
SERVICE_PUBLISH = 'publish'
|
2015-08-07 17:20:27 +00:00
|
|
|
EVENT_MQTT_MESSAGE_RECEIVED = 'MQTT_MESSAGE_RECEIVED'
|
2015-08-09 06:49:38 +00:00
|
|
|
|
2015-11-22 15:28:21 +00:00
|
|
|
REQUIREMENTS = ['paho-mqtt==1.1', 'jsonpath-rw==1.4.0']
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
CONF_BROKER = 'broker'
|
|
|
|
CONF_PORT = 'port'
|
2015-08-09 18:29:50 +00:00
|
|
|
CONF_CLIENT_ID = 'client_id'
|
2015-08-09 06:49:38 +00:00
|
|
|
CONF_KEEPALIVE = 'keepalive'
|
2015-08-09 18:40:23 +00:00
|
|
|
CONF_USERNAME = 'username'
|
|
|
|
CONF_PASSWORD = 'password'
|
2015-09-30 07:09:07 +00:00
|
|
|
CONF_CERTIFICATE = 'certificate'
|
2015-08-09 06:49:38 +00:00
|
|
|
|
|
|
|
ATTR_TOPIC = 'topic'
|
2015-08-08 16:52:59 +00:00
|
|
|
ATTR_PAYLOAD = 'payload'
|
2015-09-07 00:16:31 +00:00
|
|
|
ATTR_QOS = 'qos'
|
2015-11-24 20:30:06 +00:00
|
|
|
ATTR_RETAIN = 'retain'
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
MAX_RECONNECT_WAIT = 300 # seconds
|
|
|
|
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2015-11-24 20:30:06 +00:00
|
|
|
def publish(hass, topic, payload, qos=None, retain=None):
|
2015-08-08 16:52:59 +00:00
|
|
|
""" Send an MQTT message. """
|
2015-08-09 18:29:50 +00:00
|
|
|
data = {
|
|
|
|
ATTR_TOPIC: topic,
|
|
|
|
ATTR_PAYLOAD: payload,
|
|
|
|
}
|
2015-09-10 06:37:15 +00:00
|
|
|
if qos is not None:
|
|
|
|
data[ATTR_QOS] = qos
|
2015-11-24 20:30:06 +00:00
|
|
|
|
|
|
|
if retain is not None:
|
|
|
|
data[ATTR_RETAIN] = retain
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
hass.services.call(DOMAIN, SERVICE_PUBLISH, data)
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-09-10 06:37:15 +00:00
|
|
|
def subscribe(hass, topic, callback, qos=DEFAULT_QOS):
|
2015-08-09 18:29:50 +00:00
|
|
|
""" Subscribe to a topic. """
|
|
|
|
def mqtt_topic_subscriber(event):
|
2015-08-11 01:12:22 +00:00
|
|
|
""" Match subscribed MQTT topic. """
|
|
|
|
if _match_topic(topic, event.data[ATTR_TOPIC]):
|
2015-08-11 04:49:19 +00:00
|
|
|
callback(event.data[ATTR_TOPIC], event.data[ATTR_PAYLOAD],
|
|
|
|
event.data[ATTR_QOS])
|
2015-08-09 18:29:50 +00:00
|
|
|
|
|
|
|
hass.bus.listen(EVENT_MQTT_MESSAGE_RECEIVED, mqtt_topic_subscriber)
|
2015-11-22 23:09:56 +00:00
|
|
|
MQTT_CLIENT.subscribe(topic, qos)
|
2015-08-09 18:29:50 +00:00
|
|
|
|
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
def setup(hass, config):
|
|
|
|
""" Get the MQTT protocol service. """
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
if not validate_config(config, {DOMAIN: ['broker']}, _LOGGER):
|
2015-08-07 17:20:27 +00:00
|
|
|
return False
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
conf = config[DOMAIN]
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
broker = conf[CONF_BROKER]
|
|
|
|
port = util.convert(conf.get(CONF_PORT), int, DEFAULT_PORT)
|
2015-08-09 18:29:50 +00:00
|
|
|
client_id = util.convert(conf.get(CONF_CLIENT_ID), str)
|
2015-08-09 06:49:38 +00:00
|
|
|
keepalive = util.convert(conf.get(CONF_KEEPALIVE), int, DEFAULT_KEEPALIVE)
|
2015-08-09 18:40:23 +00:00
|
|
|
username = util.convert(conf.get(CONF_USERNAME), str)
|
|
|
|
password = util.convert(conf.get(CONF_PASSWORD), str)
|
2015-09-30 07:09:07 +00:00
|
|
|
certificate = util.convert(conf.get(CONF_CERTIFICATE), str)
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2015-09-30 07:09:35 +00:00
|
|
|
# For cloudmqtt.com, secured connection, auto fill in certificate
|
|
|
|
if certificate is None and 19999 < port < 30000 and \
|
|
|
|
broker.endswith('.cloudmqtt.com'):
|
|
|
|
certificate = os.path.join(os.path.dirname(__file__),
|
|
|
|
'addtrustexternalcaroot.crt')
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
global MQTT_CLIENT
|
|
|
|
try:
|
2015-08-09 18:40:23 +00:00
|
|
|
MQTT_CLIENT = MQTT(hass, broker, port, client_id, keepalive, username,
|
2015-09-30 07:09:07 +00:00
|
|
|
password, certificate)
|
2015-08-09 06:49:38 +00:00
|
|
|
except socket.error:
|
|
|
|
_LOGGER.exception("Can't connect to the broker. "
|
|
|
|
"Please check your settings and the broker "
|
|
|
|
"itself.")
|
|
|
|
return False
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
def stop_mqtt(event):
|
|
|
|
""" Stop MQTT component. """
|
|
|
|
MQTT_CLIENT.stop()
|
|
|
|
|
|
|
|
def start_mqtt(event):
|
|
|
|
""" Launch MQTT component when Home Assistant starts up. """
|
2015-08-09 06:49:38 +00:00
|
|
|
MQTT_CLIENT.start()
|
2015-08-07 17:20:27 +00:00
|
|
|
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_mqtt)
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
def publish_service(call):
|
|
|
|
""" Handle MQTT publish service calls. """
|
2015-08-09 18:29:50 +00:00
|
|
|
msg_topic = call.data.get(ATTR_TOPIC)
|
2015-08-08 16:52:59 +00:00
|
|
|
payload = call.data.get(ATTR_PAYLOAD)
|
2015-09-10 06:37:15 +00:00
|
|
|
qos = call.data.get(ATTR_QOS, DEFAULT_QOS)
|
2015-11-24 20:30:06 +00:00
|
|
|
retain = call.data.get(ATTR_RETAIN, DEFAULT_RETAIN)
|
2015-08-09 18:29:50 +00:00
|
|
|
if msg_topic is None or payload is None:
|
2015-08-09 06:49:38 +00:00
|
|
|
return
|
2015-11-24 20:30:06 +00:00
|
|
|
MQTT_CLIENT.publish(msg_topic, payload, qos, retain)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_mqtt)
|
|
|
|
|
2015-08-09 06:49:38 +00:00
|
|
|
hass.services.register(DOMAIN, SERVICE_PUBLISH, publish_service)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2015-11-21 16:57:15 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
2015-11-20 21:55:52 +00:00
|
|
|
class _JsonFmtParser(object):
|
2015-11-29 14:52:44 +00:00
|
|
|
""" Implements a JSON parser on xpath. """
|
2015-11-20 21:45:09 +00:00
|
|
|
def __init__(self, jsonpath):
|
2015-11-22 15:18:05 +00:00
|
|
|
import jsonpath_rw
|
2015-11-20 21:55:52 +00:00
|
|
|
self._expr = jsonpath_rw.parse(jsonpath)
|
|
|
|
|
|
|
|
def __call__(self, payload):
|
|
|
|
match = self._expr.find(json.loads(payload))
|
|
|
|
return match[0].value if len(match) > 0 else payload
|
|
|
|
|
|
|
|
|
2015-11-21 16:57:15 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
2015-11-20 21:55:52 +00:00
|
|
|
class FmtParser(object):
|
2015-11-25 07:56:50 +00:00
|
|
|
""" Wrapper for all supported formats. """
|
2015-11-20 21:55:52 +00:00
|
|
|
def __init__(self, fmt):
|
2015-11-21 16:57:15 +00:00
|
|
|
self._parse = lambda x: x
|
2015-11-20 22:42:22 +00:00
|
|
|
if fmt:
|
|
|
|
if fmt.startswith('json:'):
|
2015-11-21 16:57:15 +00:00
|
|
|
self._parse = _JsonFmtParser(fmt[5:])
|
2015-11-20 21:55:52 +00:00
|
|
|
|
2015-11-20 21:45:09 +00:00
|
|
|
def __call__(self, payload):
|
2015-11-21 16:57:15 +00:00
|
|
|
return self._parse(payload)
|
2015-11-20 21:03:17 +00:00
|
|
|
|
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
# This is based on one of the paho-mqtt examples:
|
|
|
|
# http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.python.git/tree/examples/sub-class.py
|
2015-08-09 19:22:05 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
2015-11-23 00:04:16 +00:00
|
|
|
class MQTT(object):
|
2015-08-07 17:20:27 +00:00
|
|
|
""" Implements messaging service for MQTT. """
|
2015-08-09 18:40:23 +00:00
|
|
|
def __init__(self, hass, broker, port, client_id, keepalive, username,
|
2015-09-30 07:09:07 +00:00
|
|
|
password, certificate):
|
2015-08-09 06:49:38 +00:00
|
|
|
import paho.mqtt.client as mqtt
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
self.userdata = {
|
|
|
|
'hass': hass,
|
|
|
|
'topics': {},
|
|
|
|
'progress': {},
|
|
|
|
}
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
if client_id is None:
|
|
|
|
self._mqttc = mqtt.Client()
|
2015-08-09 06:49:38 +00:00
|
|
|
else:
|
2015-08-09 18:29:50 +00:00
|
|
|
self._mqttc = mqtt.Client(client_id)
|
2015-09-30 07:09:07 +00:00
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
self._mqttc.user_data_set(self.userdata)
|
|
|
|
|
2015-08-09 18:40:23 +00:00
|
|
|
if username is not None:
|
|
|
|
self._mqttc.username_pw_set(username, password)
|
2015-09-30 07:09:07 +00:00
|
|
|
if certificate is not None:
|
|
|
|
self._mqttc.tls_set(certificate)
|
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
self._mqttc.on_subscribe = _mqtt_on_subscribe
|
|
|
|
self._mqttc.on_unsubscribe = _mqtt_on_unsubscribe
|
|
|
|
self._mqttc.on_connect = _mqtt_on_connect
|
|
|
|
self._mqttc.on_disconnect = _mqtt_on_disconnect
|
|
|
|
self._mqttc.on_message = _mqtt_on_message
|
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
self._mqttc.connect(broker, port, keepalive)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-11-24 20:30:06 +00:00
|
|
|
def publish(self, topic, payload, qos, retain):
|
2015-08-09 18:29:50 +00:00
|
|
|
""" Publish a MQTT message. """
|
2015-11-24 20:30:06 +00:00
|
|
|
self._mqttc.publish(topic, payload, qos, retain)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
def start(self):
|
|
|
|
""" Run the MQTT client. """
|
|
|
|
self._mqttc.loop_start()
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2015-08-09 06:49:38 +00:00
|
|
|
""" Stop the MQTT client. """
|
2015-08-07 17:20:27 +00:00
|
|
|
self._mqttc.loop_stop()
|
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
def subscribe(self, topic, qos):
|
|
|
|
""" Subscribe to a topic. """
|
2015-11-22 23:09:56 +00:00
|
|
|
if topic in self.userdata['topics']:
|
2015-08-09 18:29:50 +00:00
|
|
|
return
|
|
|
|
result, mid = self._mqttc.subscribe(topic, qos)
|
2015-08-09 19:22:05 +00:00
|
|
|
_raise_on_error(result)
|
2015-11-22 23:09:56 +00:00
|
|
|
self.userdata['progress'][mid] = topic
|
|
|
|
self.userdata['topics'][topic] = None
|
|
|
|
|
2015-11-23 00:04:16 +00:00
|
|
|
def unsubscribe(self, topic):
|
|
|
|
""" Unsubscribe from topic. """
|
|
|
|
result, mid = self._mqttc.unsubscribe(topic)
|
|
|
|
_raise_on_error(result)
|
|
|
|
self.userdata['progress'][mid] = topic
|
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
|
|
|
|
def _mqtt_on_message(mqttc, userdata, msg):
|
|
|
|
""" Message callback """
|
|
|
|
userdata['hass'].bus.fire(EVENT_MQTT_MESSAGE_RECEIVED, {
|
|
|
|
ATTR_TOPIC: msg.topic,
|
|
|
|
ATTR_QOS: msg.qos,
|
|
|
|
ATTR_PAYLOAD: msg.payload.decode('utf-8'),
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
def _mqtt_on_connect(mqttc, userdata, flags, result_code):
|
|
|
|
""" On connect, resubscribe to all topics we were subscribed to. """
|
|
|
|
if result_code != 0:
|
|
|
|
_LOGGER.error('Unable to connect to the MQTT broker: %s', {
|
|
|
|
1: 'Incorrect protocol version',
|
|
|
|
2: 'Invalid client identifier',
|
|
|
|
3: 'Server unavailable',
|
|
|
|
4: 'Bad username or password',
|
|
|
|
5: 'Not authorised'
|
2015-11-23 00:04:16 +00:00
|
|
|
}.get(result_code, 'Unknown reason'))
|
2015-11-22 23:09:56 +00:00
|
|
|
mqttc.disconnect()
|
|
|
|
return
|
|
|
|
|
|
|
|
old_topics = userdata['topics']
|
|
|
|
|
|
|
|
userdata['topics'] = {}
|
|
|
|
userdata['progress'] = {}
|
|
|
|
|
|
|
|
for topic, qos in old_topics.items():
|
|
|
|
# qos is None if we were in process of subscribing
|
|
|
|
if qos is not None:
|
|
|
|
mqttc.subscribe(topic, qos)
|
|
|
|
|
|
|
|
|
|
|
|
def _mqtt_on_subscribe(mqttc, userdata, mid, granted_qos):
|
2015-11-25 07:56:50 +00:00
|
|
|
""" Called when subscribe successful. """
|
2015-11-22 23:09:56 +00:00
|
|
|
topic = userdata['progress'].pop(mid, None)
|
|
|
|
if topic is None:
|
|
|
|
return
|
|
|
|
userdata['topics'][topic] = granted_qos
|
|
|
|
|
|
|
|
|
|
|
|
def _mqtt_on_unsubscribe(mqttc, userdata, mid, granted_qos):
|
2015-11-25 07:56:50 +00:00
|
|
|
""" Called when subscribe successful. """
|
2015-11-22 23:09:56 +00:00
|
|
|
topic = userdata['progress'].pop(mid, None)
|
|
|
|
if topic is None:
|
|
|
|
return
|
|
|
|
userdata['topics'].pop(topic, None)
|
|
|
|
|
|
|
|
|
|
|
|
def _mqtt_on_disconnect(mqttc, userdata, result_code):
|
|
|
|
""" Called when being disconnected. """
|
|
|
|
# When disconnected because of calling disconnect()
|
|
|
|
if result_code == 0:
|
|
|
|
return
|
|
|
|
|
|
|
|
tries = 0
|
|
|
|
wait_time = 0
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
if mqttc.reconnect() == 0:
|
|
|
|
_LOGGER.info('Successfully reconnected to the MQTT server')
|
|
|
|
break
|
|
|
|
except socket.error:
|
|
|
|
pass
|
|
|
|
|
|
|
|
wait_time = min(2**tries, MAX_RECONNECT_WAIT)
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Disconnected from MQTT (%s). Trying to reconnect in %ss',
|
|
|
|
result_code, wait_time)
|
|
|
|
# It is ok to sleep here as we are in the MQTT thread.
|
|
|
|
time.sleep(wait_time)
|
|
|
|
tries += 1
|
2015-08-09 19:22:05 +00:00
|
|
|
|
|
|
|
|
2015-11-23 00:04:16 +00:00
|
|
|
def _raise_on_error(result):
|
2015-08-09 19:22:05 +00:00
|
|
|
""" Raise error if error result. """
|
|
|
|
if result != 0:
|
|
|
|
raise HomeAssistantError('Error talking to MQTT: {}'.format(result))
|
2015-08-11 01:12:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _match_topic(subscription, topic):
|
|
|
|
""" Returns if topic matches subscription. """
|
2015-08-11 04:49:19 +00:00
|
|
|
if subscription.endswith('#'):
|
|
|
|
return (subscription[:-2] == topic or
|
|
|
|
topic.startswith(subscription[:-1]))
|
2015-08-11 01:12:22 +00:00
|
|
|
|
2015-08-11 04:49:19 +00:00
|
|
|
sub_parts = subscription.split('/')
|
|
|
|
topic_parts = topic.split('/')
|
|
|
|
|
|
|
|
return (len(sub_parts) == len(topic_parts) and
|
|
|
|
all(a == b for a, b in zip(sub_parts, topic_parts) if a != '+'))
|