core/homeassistant/components/automation/mqtt.py

56 lines
1.5 KiB
Python
Raw Normal View History

"""Offer MQTT listening automation rules."""
import json
import voluptuous as vol
2015-08-10 00:12:22 +00:00
from homeassistant.core import callback
from homeassistant.components import mqtt
2019-07-31 19:25:30 +00:00
from homeassistant.const import CONF_PLATFORM, CONF_PAYLOAD
import homeassistant.helpers.config_validation as cv
2015-08-10 00:12:22 +00:00
# mypy: allow-untyped-defs
2019-07-31 19:25:30 +00:00
CONF_ENCODING = "encoding"
CONF_TOPIC = "topic"
DEFAULT_ENCODING = "utf-8"
2015-08-10 00:12:22 +00:00
2019-07-31 19:25:30 +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,
vol.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string,
}
)
2015-08-10 00:12:22 +00:00
async def async_attach_trigger(hass, config, action, automation_info):
2016-03-07 16:14:55 +00:00
"""Listen for state changes based on configuration."""
topic = config[CONF_TOPIC]
2015-08-10 00:12:22 +00:00
payload = config.get(CONF_PAYLOAD)
encoding = config[CONF_ENCODING] or None
2015-08-10 00:12:22 +00:00
@callback
def mqtt_automation_listener(mqttmsg):
2016-03-07 19:20:07 +00:00
"""Listen for MQTT messages."""
if payload is None or payload == mqttmsg.payload:
data = {
2019-07-31 19:25:30 +00:00
"platform": "mqtt",
"topic": mqttmsg.topic,
"payload": mqttmsg.payload,
"qos": mqttmsg.qos,
}
try:
2019-07-31 19:25:30 +00:00
data["payload_json"] = json.loads(mqttmsg.payload)
except ValueError:
pass
2019-07-31 19:25:30 +00:00
hass.async_run_job(action, {"trigger": data})
2015-08-10 00:12:22 +00:00
remove = await mqtt.async_subscribe(
2019-07-31 19:25:30 +00:00
hass, topic, mqtt_automation_listener, encoding=encoding
)
return remove