From cfc511156108c2cb9299d137e32317635df25124 Mon Sep 17 00:00:00 2001 From: Chris Date: Mon, 2 Aug 2021 20:50:57 -0700 Subject: [PATCH] Handle powerConsumption reports with null value (#53888) --- .../components/smartthings/sensor.py | 11 +++++++++- tests/components/smartthings/test_sensor.py | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/smartthings/sensor.py b/homeassistant/components/smartthings/sensor.py index 5059bcc4403..cb8fa4bb6d2 100644 --- a/homeassistant/components/smartthings/sensor.py +++ b/homeassistant/components/smartthings/sensor.py @@ -554,6 +554,8 @@ class SmartThingsPowerConsumptionSensor(SmartThingsEntity, SensorEntity): """Init the class.""" super().__init__(device) self.report_name = report_name + # This is an exception for STATE_CLASS_MEASUREMENT per @balloob + self._attr_state_class = STATE_CLASS_MEASUREMENT @property def name(self) -> str: @@ -569,7 +571,7 @@ class SmartThingsPowerConsumptionSensor(SmartThingsEntity, SensorEntity): def state(self): """Return the state of the sensor.""" value = self._device.status.attributes[Attribute.power_consumption].value - if value.get(self.report_name) is None: + if value is None or value.get(self.report_name) is None: return None if self.report_name == "power": return value[self.report_name] @@ -588,3 +590,10 @@ class SmartThingsPowerConsumptionSensor(SmartThingsEntity, SensorEntity): if self.report_name == "power": return POWER_WATT return ENERGY_KILO_WATT_HOUR + + @property + def last_reset(self) -> datetime | None: + """Return the time when the sensor was last reset, if any.""" + if self.report_name != "power": + return utc_from_timestamp(0) + return None diff --git a/tests/components/smartthings/test_sensor.py b/tests/components/smartthings/test_sensor.py index fa849a3cc67..70103c3a837 100644 --- a/tests/components/smartthings/test_sensor.py +++ b/tests/components/smartthings/test_sensor.py @@ -187,6 +187,28 @@ async def test_power_consumption_sensor(hass, device_factory): assert entry.model == device.device_type_name assert entry.manufacturer == "Unavailable" + device = device_factory( + "vacuum", + [Capability.power_consumption_report], + {Attribute.power_consumption: {}}, + ) + entity_registry = er.async_get(hass) + device_registry = dr.async_get(hass) + # Act + await setup_platform(hass, SENSOR_DOMAIN, devices=[device]) + # Assert + state = hass.states.get("sensor.vacuum_energy") + assert state + assert state.state == "unknown" + entry = entity_registry.async_get("sensor.vacuum_energy") + assert entry + assert entry.unique_id == f"{device.device_id}.energy" + entry = device_registry.async_get_device({(DOMAIN, device.device_id)}) + assert entry + assert entry.name == device.label + assert entry.model == device.device_type_name + assert entry.manufacturer == "Unavailable" + async def test_update_from_signal(hass, device_factory): """Test the binary_sensor updates when receiving a signal."""