diff --git a/homeassistant/components/sql/sensor.py b/homeassistant/components/sql/sensor.py index 26c899d4d3c..39a11049aaa 100644 --- a/homeassistant/components/sql/sensor.py +++ b/homeassistant/components/sql/sensor.py @@ -242,10 +242,15 @@ class SQLSensor(SensorEntity): for key, value in res.items(): if isinstance(value, decimal.Decimal): value = float(value) - if isinstance(value, date): + elif isinstance(value, date): value = value.isoformat() + elif isinstance(value, (bytes, bytearray)): + value = f"0x{value.hex()}" self._attr_extra_state_attributes[key] = value + if data is not None and isinstance(data, (bytes, bytearray)): + data = f"0x{data.hex()}" + if data is not None and self._template is not None: self._attr_native_value = ( self._template.async_render_with_possible_json_value(data, None) diff --git a/tests/components/sql/__init__.py b/tests/components/sql/__init__.py index ea58d066325..c794f7a6b9a 100644 --- a/tests/components/sql/__init__.py +++ b/tests/components/sql/__init__.py @@ -63,6 +63,16 @@ YAML_CONFIG = { } } +YAML_CONFIG_BINARY = { + "sql": { + CONF_DB_URL: "sqlite://", + CONF_NAME: "Get Binary Value", + CONF_QUERY: "SELECT cast(x'd34324324230392032' as blob) as value, cast(x'd343aa' as blob) as test_attr", + CONF_COLUMN_NAME: "value", + CONF_UNIQUE_ID: "unique_id_12345", + } +} + YAML_CONFIG_INVALID = { "sql": { CONF_QUERY: "SELECT 5 as value", diff --git a/tests/components/sql/test_sensor.py b/tests/components/sql/test_sensor.py index 32e5a778a87..400e3056d5a 100644 --- a/tests/components/sql/test_sensor.py +++ b/tests/components/sql/test_sensor.py @@ -17,7 +17,7 @@ from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from homeassistant.util import dt -from . import YAML_CONFIG, init_integration +from . import YAML_CONFIG, YAML_CONFIG_BINARY, init_integration from tests.common import MockConfigEntry, async_fire_time_changed @@ -304,3 +304,15 @@ async def test_attributes_from_yaml_setup( assert state.attributes["device_class"] == SensorDeviceClass.DATA_RATE assert state.attributes["state_class"] == SensorStateClass.MEASUREMENT assert state.attributes["unit_of_measurement"] == "MiB" + + +async def test_binary_data_from_yaml_setup( + recorder_mock: Recorder, hass: HomeAssistant +) -> None: + """Test binary data from yaml config.""" + + assert await async_setup_component(hass, DOMAIN, YAML_CONFIG_BINARY) + await hass.async_block_till_done() + state = hass.states.get("sensor.get_binary_value") + assert state.state == "0xd34324324230392032" + assert state.attributes["test_attr"] == "0xd343aa"