2015-08-07 17:20:27 +00:00
|
|
|
"""
|
2016-04-13 11:50:28 +00:00
|
|
|
Support for MQTT message handling.
|
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
|
|
|
"""
|
2016-09-30 19:57:24 +00:00
|
|
|
import asyncio
|
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
|
|
|
|
|
2016-04-02 15:46:09 +00:00
|
|
|
import voluptuous as vol
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2016-03-08 00:45:37 +00:00
|
|
|
from homeassistant.bootstrap import prepare_setup_platform
|
2016-02-11 05:23:27 +00:00
|
|
|
from homeassistant.config import load_yaml_config_file
|
2015-08-30 02:34:35 +00:00
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
2016-10-04 05:39:27 +00:00
|
|
|
from homeassistant.helpers import template, config_validation as cv
|
|
|
|
from homeassistant.helpers.event import threaded_listener_factory
|
2015-08-07 17:20:27 +00:00
|
|
|
from homeassistant.const import (
|
2016-10-19 01:10:28 +00:00
|
|
|
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, CONF_VALUE_TEMPLATE)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
_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
|
|
|
|
|
|
|
SERVICE_PUBLISH = 'publish'
|
2015-12-27 23:46:44 +00:00
|
|
|
EVENT_MQTT_MESSAGE_RECEIVED = 'mqtt_message_received'
|
2015-08-09 06:49:38 +00:00
|
|
|
|
2016-06-21 04:51:50 +00:00
|
|
|
REQUIREMENTS = ['paho-mqtt==1.2']
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2016-03-08 00:45:37 +00:00
|
|
|
CONF_EMBEDDED = 'embedded'
|
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'
|
2016-05-02 06:21:28 +00:00
|
|
|
CONF_CLIENT_KEY = 'client_key'
|
|
|
|
CONF_CLIENT_CERT = 'client_cert'
|
|
|
|
CONF_TLS_INSECURE = 'tls_insecure'
|
2016-01-19 17:00:40 +00:00
|
|
|
CONF_PROTOCOL = 'protocol'
|
2016-04-07 01:35:46 +00:00
|
|
|
|
|
|
|
CONF_STATE_TOPIC = 'state_topic'
|
|
|
|
CONF_COMMAND_TOPIC = 'command_topic'
|
2016-04-05 04:21:31 +00:00
|
|
|
CONF_QOS = 'qos'
|
2016-04-07 01:35:46 +00:00
|
|
|
CONF_RETAIN = 'retain'
|
2016-01-19 17:00:40 +00:00
|
|
|
|
|
|
|
PROTOCOL_31 = '3.1'
|
|
|
|
PROTOCOL_311 = '3.1.1'
|
|
|
|
|
|
|
|
DEFAULT_PORT = 1883
|
|
|
|
DEFAULT_KEEPALIVE = 60
|
|
|
|
DEFAULT_QOS = 0
|
|
|
|
DEFAULT_RETAIN = False
|
|
|
|
DEFAULT_PROTOCOL = PROTOCOL_311
|
2015-08-09 06:49:38 +00:00
|
|
|
|
|
|
|
ATTR_TOPIC = 'topic'
|
2015-08-08 16:52:59 +00:00
|
|
|
ATTR_PAYLOAD = 'payload'
|
2016-02-09 15:41:31 +00:00
|
|
|
ATTR_PAYLOAD_TEMPLATE = 'payload_template'
|
2016-04-05 04:21:31 +00:00
|
|
|
ATTR_QOS = CONF_QOS
|
2016-04-07 01:35:46 +00:00
|
|
|
ATTR_RETAIN = CONF_RETAIN
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2015-11-22 23:09:56 +00:00
|
|
|
MAX_RECONNECT_WAIT = 300 # seconds
|
|
|
|
|
2016-04-07 01:35:46 +00:00
|
|
|
|
|
|
|
def valid_subscribe_topic(value, invalid_chars='\0'):
|
|
|
|
"""Validate that we can subscribe using this MQTT topic."""
|
|
|
|
if isinstance(value, str) and all(c not in value for c in invalid_chars):
|
|
|
|
return vol.Length(min=1, max=65535)(value)
|
|
|
|
raise vol.Invalid('Invalid MQTT topic name')
|
|
|
|
|
|
|
|
|
|
|
|
def valid_publish_topic(value):
|
|
|
|
"""Validate that we can publish using this MQTT topic."""
|
|
|
|
return valid_subscribe_topic(value, invalid_chars='#+\0')
|
|
|
|
|
2016-04-05 04:21:31 +00:00
|
|
|
_VALID_QOS_SCHEMA = vol.All(vol.Coerce(int), vol.In([0, 1, 2]))
|
2016-04-04 04:22:04 +00:00
|
|
|
_HBMQTT_CONFIG_SCHEMA = vol.Schema(dict)
|
|
|
|
|
2016-05-02 06:21:28 +00:00
|
|
|
CLIENT_KEY_AUTH_MSG = 'client_key and client_cert must both be present in ' \
|
|
|
|
'the mqtt broker config'
|
|
|
|
|
2016-04-04 04:22:04 +00:00
|
|
|
CONFIG_SCHEMA = vol.Schema({
|
|
|
|
DOMAIN: vol.Schema({
|
|
|
|
vol.Optional(CONF_CLIENT_ID): cv.string,
|
|
|
|
vol.Optional(CONF_KEEPALIVE, default=DEFAULT_KEEPALIVE):
|
|
|
|
vol.All(vol.Coerce(int), vol.Range(min=15)),
|
|
|
|
vol.Optional(CONF_BROKER): cv.string,
|
|
|
|
vol.Optional(CONF_PORT, default=DEFAULT_PORT):
|
|
|
|
vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)),
|
|
|
|
vol.Optional(CONF_USERNAME): cv.string,
|
|
|
|
vol.Optional(CONF_PASSWORD): cv.string,
|
2016-04-07 17:52:25 +00:00
|
|
|
vol.Optional(CONF_CERTIFICATE): cv.isfile,
|
2016-05-02 06:21:28 +00:00
|
|
|
vol.Inclusive(CONF_CLIENT_KEY, 'client_key_auth',
|
|
|
|
msg=CLIENT_KEY_AUTH_MSG): cv.isfile,
|
|
|
|
vol.Inclusive(CONF_CLIENT_CERT, 'client_key_auth',
|
|
|
|
msg=CLIENT_KEY_AUTH_MSG): cv.isfile,
|
|
|
|
vol.Optional(CONF_TLS_INSECURE): cv.boolean,
|
2016-04-04 04:22:04 +00:00
|
|
|
vol.Optional(CONF_PROTOCOL, default=DEFAULT_PROTOCOL):
|
2016-04-09 16:03:41 +00:00
|
|
|
vol.All(cv.string, vol.In([PROTOCOL_31, PROTOCOL_311])),
|
2016-04-04 04:22:04 +00:00
|
|
|
vol.Optional(CONF_EMBEDDED): _HBMQTT_CONFIG_SCHEMA,
|
|
|
|
}),
|
2016-04-07 04:42:56 +00:00
|
|
|
}, extra=vol.ALLOW_EXTRA)
|
2016-04-04 04:22:04 +00:00
|
|
|
|
2016-10-19 01:10:28 +00:00
|
|
|
SCHEMA_BASE = {
|
2016-04-05 04:21:31 +00:00
|
|
|
vol.Optional(CONF_QOS, default=DEFAULT_QOS): _VALID_QOS_SCHEMA,
|
2016-10-19 01:10:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
MQTT_BASE_PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend(SCHEMA_BASE)
|
2016-04-05 04:21:31 +00:00
|
|
|
|
2016-04-13 11:50:28 +00:00
|
|
|
# Sensor type platforms subscribe to MQTT events
|
2016-04-07 01:35:46 +00:00
|
|
|
MQTT_RO_PLATFORM_SCHEMA = MQTT_BASE_PLATFORM_SCHEMA.extend({
|
|
|
|
vol.Required(CONF_STATE_TOPIC): valid_subscribe_topic,
|
|
|
|
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
})
|
2015-08-08 16:52:59 +00:00
|
|
|
|
2016-04-13 11:50:28 +00:00
|
|
|
# Switch type platforms publish to MQTT and may subscribe
|
2016-04-07 01:35:46 +00:00
|
|
|
MQTT_RW_PLATFORM_SCHEMA = MQTT_BASE_PLATFORM_SCHEMA.extend({
|
|
|
|
vol.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
|
|
|
|
vol.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
|
|
|
|
vol.Optional(CONF_STATE_TOPIC): valid_subscribe_topic,
|
|
|
|
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
})
|
2016-04-05 04:21:31 +00:00
|
|
|
|
|
|
|
|
2016-04-07 01:35:46 +00:00
|
|
|
# Service call validation schema
|
2016-04-02 15:46:09 +00:00
|
|
|
MQTT_PUBLISH_SCHEMA = vol.Schema({
|
2016-04-05 04:21:31 +00:00
|
|
|
vol.Required(ATTR_TOPIC): valid_publish_topic,
|
2016-04-02 15:46:09 +00:00
|
|
|
vol.Exclusive(ATTR_PAYLOAD, 'payload'): object,
|
|
|
|
vol.Exclusive(ATTR_PAYLOAD_TEMPLATE, 'payload'): cv.string,
|
2016-04-05 04:21:31 +00:00
|
|
|
vol.Required(ATTR_QOS, default=DEFAULT_QOS): _VALID_QOS_SCHEMA,
|
2016-04-03 17:19:09 +00:00
|
|
|
vol.Required(ATTR_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
|
2016-04-03 07:54:05 +00:00
|
|
|
}, required=True)
|
2016-04-02 15:46:09 +00:00
|
|
|
|
|
|
|
|
2016-02-10 22:38:33 +00:00
|
|
|
def _build_publish_data(topic, qos, retain):
|
|
|
|
"""Build the arguments for the publish service without the payload."""
|
|
|
|
data = {ATTR_TOPIC: topic}
|
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
|
2016-02-10 22:38:33 +00:00
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
def publish(hass, topic, payload, qos=None, retain=None):
|
|
|
|
"""Publish message to an MQTT topic."""
|
|
|
|
data = _build_publish_data(topic, qos, retain)
|
|
|
|
data[ATTR_PAYLOAD] = payload
|
|
|
|
hass.services.call(DOMAIN, SERVICE_PUBLISH, data)
|
|
|
|
|
2015-11-24 20:30:06 +00:00
|
|
|
|
2016-02-10 22:38:33 +00:00
|
|
|
def publish_template(hass, topic, payload_template, qos=None, retain=None):
|
|
|
|
"""Publish message to an MQTT topic using a template payload."""
|
|
|
|
data = _build_publish_data(topic, qos, retain)
|
|
|
|
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
|
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
|
|
|
|
2016-10-01 07:39:07 +00:00
|
|
|
def async_subscribe(hass, topic, callback, qos=DEFAULT_QOS):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Subscribe to an MQTT topic."""
|
2016-09-30 19:57:24 +00:00
|
|
|
@asyncio.coroutine
|
2015-08-09 18:29:50 +00:00
|
|
|
def mqtt_topic_subscriber(event):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Match subscribed MQTT topic."""
|
2016-09-30 19:57:24 +00:00
|
|
|
if not _match_topic(topic, event.data[ATTR_TOPIC]):
|
|
|
|
return
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
hass.async_run_job(callback, event.data[ATTR_TOPIC],
|
2016-10-04 05:39:27 +00:00
|
|
|
event.data[ATTR_PAYLOAD], event.data[ATTR_QOS])
|
2015-08-09 18:29:50 +00:00
|
|
|
|
2016-10-01 07:39:07 +00:00
|
|
|
async_remove = hass.bus.async_listen(EVENT_MQTT_MESSAGE_RECEIVED,
|
|
|
|
mqtt_topic_subscriber)
|
2016-08-26 06:25:35 +00:00
|
|
|
|
|
|
|
# Future: track subscriber count and unsubscribe in remove
|
2015-11-22 23:09:56 +00:00
|
|
|
MQTT_CLIENT.subscribe(topic, qos)
|
2015-08-09 18:29:50 +00:00
|
|
|
|
2016-10-01 07:39:07 +00:00
|
|
|
return async_remove
|
2016-08-26 06:25:35 +00:00
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
|
2016-10-04 05:39:27 +00:00
|
|
|
# pylint: disable=invalid-name
|
|
|
|
subscribe = threaded_listener_factory(async_subscribe)
|
|
|
|
|
|
|
|
|
2016-03-08 00:45:37 +00:00
|
|
|
def _setup_server(hass, config):
|
|
|
|
"""Try to start embedded MQTT broker."""
|
|
|
|
conf = config.get(DOMAIN, {})
|
|
|
|
|
|
|
|
# Only setup if embedded config passed in or no broker specified
|
|
|
|
if CONF_EMBEDDED not in conf and CONF_BROKER in conf:
|
|
|
|
return None
|
|
|
|
|
|
|
|
server = prepare_setup_platform(hass, config, DOMAIN, 'server')
|
|
|
|
|
|
|
|
if server is None:
|
|
|
|
_LOGGER.error('Unable to load embedded server.')
|
|
|
|
return None
|
|
|
|
|
|
|
|
success, broker_config = server.start(hass, conf.get(CONF_EMBEDDED))
|
|
|
|
|
|
|
|
return success and broker_config
|
|
|
|
|
|
|
|
|
2015-08-07 17:20:27 +00:00
|
|
|
def setup(hass, config):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Start the MQTT protocol service."""
|
2016-03-08 00:45:37 +00:00
|
|
|
conf = config.get(DOMAIN, {})
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2016-04-04 04:22:04 +00:00
|
|
|
client_id = conf.get(CONF_CLIENT_ID)
|
|
|
|
keepalive = conf.get(CONF_KEEPALIVE)
|
2016-03-08 00:45:37 +00:00
|
|
|
|
|
|
|
broker_config = _setup_server(hass, config)
|
|
|
|
|
2016-07-14 00:44:46 +00:00
|
|
|
broker_in_conf = CONF_BROKER in conf
|
2016-05-02 06:21:28 +00:00
|
|
|
|
2016-03-08 00:45:37 +00:00
|
|
|
# Only auto config if no server config was passed in
|
|
|
|
if broker_config and CONF_EMBEDDED not in conf:
|
|
|
|
broker, port, username, password, certificate, protocol = broker_config
|
2016-05-02 06:21:28 +00:00
|
|
|
# Embedded broker doesn't have some ssl variables
|
|
|
|
client_key, client_cert, tls_insecure = None, None, None
|
2016-07-14 00:44:46 +00:00
|
|
|
elif not broker_config and not broker_in_conf:
|
2016-03-08 00:45:37 +00:00
|
|
|
_LOGGER.error('Unable to start broker and auto-configure MQTT.')
|
|
|
|
return False
|
|
|
|
|
2016-05-02 06:21:28 +00:00
|
|
|
if broker_in_conf:
|
2016-03-08 00:45:37 +00:00
|
|
|
broker = conf[CONF_BROKER]
|
2016-04-04 04:22:04 +00:00
|
|
|
port = conf[CONF_PORT]
|
|
|
|
username = conf.get(CONF_USERNAME)
|
|
|
|
password = conf.get(CONF_PASSWORD)
|
|
|
|
certificate = conf.get(CONF_CERTIFICATE)
|
2016-05-02 06:21:28 +00:00
|
|
|
client_key = conf.get(CONF_CLIENT_KEY)
|
|
|
|
client_cert = conf.get(CONF_CLIENT_CERT)
|
|
|
|
tls_insecure = conf.get(CONF_TLS_INSECURE)
|
2016-04-04 04:22:04 +00:00
|
|
|
protocol = conf[CONF_PROTOCOL]
|
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:
|
2016-05-02 06:21:28 +00:00
|
|
|
MQTT_CLIENT = MQTT(hass, broker, port, client_id, keepalive,
|
|
|
|
username, password, certificate, client_key,
|
|
|
|
client_cert, tls_insecure, protocol)
|
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):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Stop MQTT component."""
|
2015-08-07 17:20:27 +00:00
|
|
|
MQTT_CLIENT.stop()
|
|
|
|
|
|
|
|
def start_mqtt(event):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""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):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Handle MQTT publish service calls."""
|
2016-04-02 15:46:09 +00:00
|
|
|
msg_topic = call.data[ATTR_TOPIC]
|
2016-02-09 15:41:31 +00:00
|
|
|
payload = call.data.get(ATTR_PAYLOAD)
|
2016-02-10 11:11:02 +00:00
|
|
|
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
|
2016-04-02 15:46:09 +00:00
|
|
|
qos = call.data[ATTR_QOS]
|
|
|
|
retain = call.data[ATTR_RETAIN]
|
|
|
|
try:
|
2016-09-28 04:29:55 +00:00
|
|
|
if payload_template is not None:
|
|
|
|
payload = template.Template(payload_template, hass).render()
|
2016-04-02 15:46:09 +00:00
|
|
|
except template.jinja2.TemplateError as exc:
|
|
|
|
_LOGGER.error(
|
|
|
|
"Unable to publish to '%s': rendering payload template of "
|
|
|
|
"'%s' failed because %s.",
|
|
|
|
msg_topic, payload_template, exc)
|
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)
|
|
|
|
|
2016-02-11 05:23:27 +00:00
|
|
|
descriptions = load_yaml_config_file(
|
|
|
|
os.path.join(os.path.dirname(__file__), 'services.yaml'))
|
|
|
|
|
|
|
|
hass.services.register(DOMAIN, SERVICE_PUBLISH, publish_service,
|
2016-04-02 15:46:09 +00:00
|
|
|
descriptions.get(SERVICE_PUBLISH),
|
|
|
|
schema=MQTT_PUBLISH_SCHEMA)
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2015-11-23 00:04:16 +00:00
|
|
|
class MQTT(object):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Home Assistant MQTT client."""
|
|
|
|
|
2015-08-09 18:40:23 +00:00
|
|
|
def __init__(self, hass, broker, port, client_id, keepalive, username,
|
2016-05-02 06:21:28 +00:00
|
|
|
password, certificate, client_key, client_cert,
|
|
|
|
tls_insecure, protocol):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Initialize Home Assistant MQTT client."""
|
2015-08-09 06:49:38 +00:00
|
|
|
import paho.mqtt.client as mqtt
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2016-01-18 05:39:25 +00:00
|
|
|
self.hass = hass
|
|
|
|
self.topics = {}
|
|
|
|
self.progress = {}
|
2015-08-07 17:20:27 +00:00
|
|
|
|
2016-01-19 17:00:40 +00:00
|
|
|
if protocol == PROTOCOL_31:
|
|
|
|
proto = mqtt.MQTTv31
|
|
|
|
else:
|
|
|
|
proto = mqtt.MQTTv311
|
|
|
|
|
2015-08-09 18:29:50 +00:00
|
|
|
if client_id is None:
|
2016-01-19 17:00:40 +00:00
|
|
|
self._mqttc = mqtt.Client(protocol=proto)
|
2015-08-09 06:49:38 +00:00
|
|
|
else:
|
2016-01-19 17:00:40 +00:00
|
|
|
self._mqttc = mqtt.Client(client_id, protocol=proto)
|
2015-09-30 07:09:07 +00:00
|
|
|
|
2015-08-09 18:40:23 +00:00
|
|
|
if username is not None:
|
|
|
|
self._mqttc.username_pw_set(username, password)
|
2016-05-02 06:21:28 +00:00
|
|
|
|
2015-09-30 07:09:07 +00:00
|
|
|
if certificate is not None:
|
2016-05-02 06:21:28 +00:00
|
|
|
self._mqttc.tls_set(certificate, certfile=client_cert,
|
|
|
|
keyfile=client_key)
|
|
|
|
|
|
|
|
if tls_insecure is not None:
|
|
|
|
self._mqttc.tls_insecure_set(tls_insecure)
|
2015-09-30 07:09:07 +00:00
|
|
|
|
2016-01-18 05:39:25 +00:00
|
|
|
self._mqttc.on_subscribe = self._mqtt_on_subscribe
|
|
|
|
self._mqttc.on_unsubscribe = self._mqtt_on_unsubscribe
|
|
|
|
self._mqttc.on_connect = self._mqtt_on_connect
|
|
|
|
self._mqttc.on_disconnect = self._mqtt_on_disconnect
|
|
|
|
self._mqttc.on_message = self._mqtt_on_message
|
2015-11-22 23:09:56 +00:00
|
|
|
|
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):
|
2016-01-18 05:39:25 +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):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Run the MQTT client."""
|
2015-08-09 18:29:50 +00:00
|
|
|
self._mqttc.loop_start()
|
2015-08-07 17:20:27 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Stop the MQTT client."""
|
|
|
|
self._mqttc.disconnect()
|
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):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Subscribe to a topic."""
|
|
|
|
assert isinstance(topic, str)
|
|
|
|
|
|
|
|
if topic in self.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)
|
2016-01-18 05:39:25 +00:00
|
|
|
self.progress[mid] = topic
|
|
|
|
self.topics[topic] = None
|
2015-11-22 23:09:56 +00:00
|
|
|
|
2015-11-23 00:04:16 +00:00
|
|
|
def unsubscribe(self, topic):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Unsubscribe from topic."""
|
2015-11-23 00:04:16 +00:00
|
|
|
result, mid = self._mqttc.unsubscribe(topic)
|
|
|
|
_raise_on_error(result)
|
2016-01-18 05:39:25 +00:00
|
|
|
self.progress[mid] = topic
|
|
|
|
|
|
|
|
def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code):
|
|
|
|
"""On connect callback.
|
|
|
|
|
|
|
|
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'
|
|
|
|
}.get(result_code, 'Unknown reason'))
|
|
|
|
self._mqttc.disconnect()
|
|
|
|
return
|
|
|
|
|
|
|
|
old_topics = self.topics
|
|
|
|
|
|
|
|
self.topics = {key: value for key, value in self.topics.items()
|
|
|
|
if value is None}
|
|
|
|
|
|
|
|
for topic, qos in old_topics.items():
|
|
|
|
# qos is None if we were in process of subscribing
|
|
|
|
if qos is not None:
|
|
|
|
self.subscribe(topic, qos)
|
|
|
|
|
|
|
|
def _mqtt_on_subscribe(self, _mqttc, _userdata, mid, granted_qos):
|
|
|
|
"""Subscribe successful callback."""
|
|
|
|
topic = self.progress.pop(mid, None)
|
|
|
|
if topic is None:
|
|
|
|
return
|
|
|
|
self.topics[topic] = granted_qos[0]
|
|
|
|
|
|
|
|
def _mqtt_on_message(self, _mqttc, _userdata, msg):
|
|
|
|
"""Message received callback."""
|
2016-10-15 04:08:44 +00:00
|
|
|
try:
|
|
|
|
payload = msg.payload.decode('utf-8')
|
|
|
|
except AttributeError:
|
|
|
|
_LOGGER.error("Illegal utf-8 unicode payload from "
|
|
|
|
"MQTT topic: %s, Payload: %s", msg.topic,
|
|
|
|
msg.payload)
|
|
|
|
else:
|
|
|
|
_LOGGER.debug("received message on %s: %s",
|
|
|
|
msg.topic, payload)
|
|
|
|
self.hass.bus.fire(EVENT_MQTT_MESSAGE_RECEIVED, {
|
|
|
|
ATTR_TOPIC: msg.topic,
|
|
|
|
ATTR_QOS: msg.qos,
|
|
|
|
ATTR_PAYLOAD: payload,
|
|
|
|
})
|
2016-01-18 05:39:25 +00:00
|
|
|
|
|
|
|
def _mqtt_on_unsubscribe(self, _mqttc, _userdata, mid, granted_qos):
|
|
|
|
"""Unsubscribe successful callback."""
|
|
|
|
topic = self.progress.pop(mid, None)
|
|
|
|
if topic is None:
|
|
|
|
return
|
|
|
|
self.topics.pop(topic, None)
|
|
|
|
|
|
|
|
def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code):
|
|
|
|
"""Disconnected callback."""
|
|
|
|
self.progress = {}
|
|
|
|
self.topics = {key: value for key, value in self.topics.items()
|
|
|
|
if value is not None}
|
|
|
|
|
|
|
|
# Remove None values from topic list
|
|
|
|
for key in list(self.topics):
|
|
|
|
if self.topics[key] is None:
|
|
|
|
self.topics.pop(key)
|
|
|
|
|
|
|
|
# When disconnected because of calling disconnect()
|
|
|
|
if result_code == 0:
|
|
|
|
return
|
|
|
|
|
|
|
|
tries = 0
|
|
|
|
wait_time = 0
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
if self._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):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Raise error if error result."""
|
2015-08-09 19:22:05 +00:00
|
|
|
if result != 0:
|
|
|
|
raise HomeAssistantError('Error talking to MQTT: {}'.format(result))
|
2015-08-11 01:12:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _match_topic(subscription, topic):
|
2016-01-18 05:39:25 +00:00
|
|
|
"""Test 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 != '+'))
|