MQTT Automation: parse payload as JSON (#4703)

This commit is contained in:
Paulus Schoutsen 2016-12-04 09:53:05 -08:00 committed by GitHub
parent 9bf13231f7
commit b2a15e17d3
2 changed files with 19 additions and 9 deletions

View file

@ -4,6 +4,8 @@ Offer MQTT listening automation rules.
For more details about this automation rule, please refer to the documentation For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#mqtt-trigger at https://home-assistant.io/components/automation/#mqtt-trigger
""" """
import json
import voluptuous as vol import voluptuous as vol
from homeassistant.core import callback from homeassistant.core import callback
@ -31,13 +33,20 @@ def async_trigger(hass, config, action):
def mqtt_automation_listener(msg_topic, msg_payload, qos): def mqtt_automation_listener(msg_topic, msg_payload, qos):
"""Listen for MQTT messages.""" """Listen for MQTT messages."""
if payload is None or payload == msg_payload: if payload is None or payload == msg_payload:
hass.async_run_job(action, { data = {
'trigger': {
'platform': 'mqtt', 'platform': 'mqtt',
'topic': msg_topic, 'topic': msg_topic,
'payload': msg_payload, 'payload': msg_payload,
'qos': qos, 'qos': qos,
} }
try:
data['payload_json'] = json.loads(msg_payload)
except ValueError:
pass
hass.async_run_job(action, {
'trigger': data
}) })
return mqtt.async_subscribe(hass, topic, mqtt_automation_listener) return mqtt.async_subscribe(hass, topic, mqtt_automation_listener)

View file

@ -42,16 +42,17 @@ class TestAutomationMQTT(unittest.TestCase):
'service': 'test.automation', 'service': 'test.automation',
'data_template': { 'data_template': {
'some': '{{ trigger.platform }} - {{ trigger.topic }}' 'some': '{{ trigger.platform }} - {{ trigger.topic }}'
' - {{ trigger.payload }}' ' - {{ trigger.payload }} - '
'{{ trigger.payload_json.hello }}'
}, },
} }
} }
}) })
fire_mqtt_message(self.hass, 'test-topic', 'test_payload') fire_mqtt_message(self.hass, 'test-topic', '{ "hello": "world" }')
self.hass.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
self.assertEqual('mqtt - test-topic - test_payload', self.assertEqual('mqtt - test-topic - { "hello": "world" } - world',
self.calls[0].data['some']) self.calls[0].data['some'])
automation.turn_off(self.hass) automation.turn_off(self.hass)