From 248d974dedfd260d9c10d4441d846d6ba2fbf993 Mon Sep 17 00:00:00 2001 From: Lukas Barth Date: Fri, 27 Oct 2017 17:55:04 +0200 Subject: [PATCH] Cast attribute values to string before publishing to MQTT (#9872) * Cast attribute values to string before publishing to MQTT * Simplify * Use JSON serialization, add test --- homeassistant/components/mqtt_statestream.py | 5 ++++- tests/components/test_mqtt_statestream.py | 12 ++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/mqtt_statestream.py b/homeassistant/components/mqtt_statestream.py index 8469cb3b334..d24361637e9 100644 --- a/homeassistant/components/mqtt_statestream.py +++ b/homeassistant/components/mqtt_statestream.py @@ -5,6 +5,7 @@ For more details about this component, please refer to the documentation at https://home-assistant.io/components/mqtt_statestream/ """ import asyncio +import json import voluptuous as vol @@ -12,6 +13,7 @@ from homeassistant.const import MATCH_ALL from homeassistant.core import callback from homeassistant.components.mqtt import valid_publish_topic from homeassistant.helpers.event import async_track_state_change +from homeassistant.remote import JSONEncoder import homeassistant.helpers.config_validation as cv CONF_BASE_TOPIC = 'base_topic' @@ -65,8 +67,9 @@ def async_setup(hass, config): if publish_attributes: for key, val in new_state.attributes.items(): if val: + encoded_val = json.dumps(val, cls=JSONEncoder) hass.components.mqtt.async_publish(mybase + key, - val, 1, True) + encoded_val, 1, True) async_track_state_change(hass, MATCH_ALL, _state_publisher) return True diff --git a/tests/components/test_mqtt_statestream.py b/tests/components/test_mqtt_statestream.py index 802d62bfdd1..cc1ea277a34 100644 --- a/tests/components/test_mqtt_statestream.py +++ b/tests/components/test_mqtt_statestream.py @@ -127,7 +127,11 @@ class TestMqttStateStream(object): # mqtt_statestream state change on initialization, etc. mock_pub.reset_mock() - test_attributes = {"testing": "YES"} + test_attributes = { + "testing": "YES", + "list": ["a", "b", "c"], + "bool": True + } # Set a state of an entity mock_state_change_event(self.hass, State(e_id, 'off', @@ -138,7 +142,11 @@ class TestMqttStateStream(object): calls = [ call.async_publish(self.hass, 'pub/fake/entity/state', 'off', 1, True), - call.async_publish(self.hass, 'pub/fake/entity/testing', 'YES', + call.async_publish(self.hass, 'pub/fake/entity/testing', '"YES"', + 1, True), + call.async_publish(self.hass, 'pub/fake/entity/list', + '["a", "b", "c"]', 1, True), + call.async_publish(self.hass, 'pub/fake/entity/bool', "true", 1, True) ]