Skip to content

Commit

Permalink
Cast attribute values to string before publishing to MQTT (#9872)
Browse files Browse the repository at this point in the history
* Cast attribute values to string before publishing to MQTT

* Simplify

* Use JSON serialization, add test
  • Loading branch information
tinloaf authored and balloob committed Oct 27, 2017
1 parent 2d93285 commit 248d974
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
5 changes: 4 additions & 1 deletion homeassistant/components/mqtt_statestream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
https://home-assistant.io/components/mqtt_statestream/
"""
import asyncio
import json

import voluptuous as vol

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'
Expand Down Expand Up @@ -65,8 +67,9 @@ def _state_publisher(entity_id, old_state, new_state):
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
12 changes: 10 additions & 2 deletions tests/components/test_mqtt_statestream.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,11 @@ def test_state_changed_attr_sends_message(self, mock_utcnow, mock_pub):
# 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',
Expand All @@ -138,7 +142,11 @@ def test_state_changed_attr_sends_message(self, mock_utcnow, mock_pub):
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)
]

Expand Down

0 comments on commit 248d974

Please sign in to comment.