2015-08-10 00:12:22 +00:00
|
|
|
"""
|
2016-03-07 19:20:07 +00:00
|
|
|
Offer MQTT listening automation rules.
|
2015-10-13 19:07:40 +00:00
|
|
|
|
|
|
|
For more details about this automation rule, please refer to the documentation
|
2017-04-06 06:23:02 +00:00
|
|
|
at https://home-assistant.io/docs/automation/trigger/#mqtt-trigger
|
2015-08-10 00:12:22 +00:00
|
|
|
"""
|
2016-12-04 17:53:05 +00:00
|
|
|
import json
|
|
|
|
|
2016-04-07 01:12:51 +00:00
|
|
|
import voluptuous as vol
|
2015-08-10 00:12:22 +00:00
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
from homeassistant.core import callback
|
2018-07-18 09:54:27 +00:00
|
|
|
from homeassistant.components import mqtt
|
2016-09-09 00:32:32 +00:00
|
|
|
from homeassistant.const import (CONF_PLATFORM, CONF_PAYLOAD)
|
2016-04-07 01:12:51 +00:00
|
|
|
import homeassistant.helpers.config_validation as cv
|
2015-08-10 00:12:22 +00:00
|
|
|
|
|
|
|
DEPENDENCIES = ['mqtt']
|
|
|
|
|
2015-09-15 05:05:40 +00:00
|
|
|
CONF_TOPIC = 'topic'
|
2015-08-10 00:12:22 +00:00
|
|
|
|
2016-04-07 01:12:51 +00:00
|
|
|
TRIGGER_SCHEMA = vol.Schema({
|
|
|
|
vol.Required(CONF_PLATFORM): mqtt.DOMAIN,
|
|
|
|
vol.Required(CONF_TOPIC): mqtt.valid_subscribe_topic,
|
|
|
|
vol.Optional(CONF_PAYLOAD): cv.string,
|
|
|
|
})
|
|
|
|
|
2015-08-10 00:12:22 +00:00
|
|
|
|
2018-11-05 08:23:58 +00:00
|
|
|
async def async_trigger(hass, config, action, automation_info):
|
2016-03-07 16:14:55 +00:00
|
|
|
"""Listen for state changes based on configuration."""
|
2016-09-09 00:32:32 +00:00
|
|
|
topic = config.get(CONF_TOPIC)
|
2015-08-10 00:12:22 +00:00
|
|
|
payload = config.get(CONF_PAYLOAD)
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
@callback
|
2015-08-10 00:12:22 +00:00
|
|
|
def mqtt_automation_listener(msg_topic, msg_payload, qos):
|
2016-03-07 19:20:07 +00:00
|
|
|
"""Listen for MQTT messages."""
|
2015-08-10 00:12:22 +00:00
|
|
|
if payload is None or payload == msg_payload:
|
2016-12-04 17:53:05 +00:00
|
|
|
data = {
|
|
|
|
'platform': 'mqtt',
|
|
|
|
'topic': msg_topic,
|
|
|
|
'payload': msg_payload,
|
|
|
|
'qos': qos,
|
|
|
|
}
|
|
|
|
|
|
|
|
try:
|
|
|
|
data['payload_json'] = json.loads(msg_payload)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
hass.async_run_job(action, {
|
2016-12-04 17:53:05 +00:00
|
|
|
'trigger': data
|
2016-04-21 20:59:42 +00:00
|
|
|
})
|
2015-08-10 00:12:22 +00:00
|
|
|
|
2018-10-01 06:49:19 +00:00
|
|
|
remove = await mqtt.async_subscribe(
|
2017-02-18 22:17:18 +00:00
|
|
|
hass, topic, mqtt_automation_listener)
|
|
|
|
return remove
|