From f8bbf745233726d669ac8920c3b1e09f5cec97b0 Mon Sep 17 00:00:00 2001 From: XS400DOHC <63352197+xs400dohc@users.noreply.github.com> Date: Wed, 12 Feb 2025 10:42:15 +0100 Subject: [PATCH] possible solution for issue #26028 Made some investigation: - as written in my post, energy has a device_class and state_class power and current don't. - searched for the reason why energy behaves different to power and current - in [homeassistant.ts](https://github.com/Koenkk/zigbee2mqtt/blob/master/lib/extension/homeassistant.ts) I found this code in line 1018: ``` // If a variable includes Wh, mark it as energy if (firstExpose.unit && ['Wh', 'kWh'].includes(firstExpose.unit)) { Object.assign(extraAttrs, {device_class: 'energy', state_class: 'total_increasing'}); } ``` I think a possible solution could be to add following ``` // If a variable includes A or mA, mark it as energy if (firstExpose.unit && ['A', 'mA'].includes(firstExpose.unit)) { Object.assign(extraAttrs, {device_class: 'current', state_class: 'measurement'}); } // If a variable includes mW, W, kW, MW, GW, TW, mark it as energy if (firstExpose.unit && ['mW', 'W', 'kW', 'MW', 'GW', 'TW'].includes(firstExpose.unit)) { Object.assign(extraAttrs, {device_class: 'power', state_class: 'measurement'}); } ``` But I don't know how to test the changes in my homeassistant if that would fix the problem. Didn't found homeassistant.ts in my installation (using VS-Code-extension). Perhaps it's also way for other sensors with other units, e.g. Data rate in bit/s, kbit/s, Mbit/s, Gbit/s, B/s, kB/s, MB/s, GB/s, KiB/s, MiB/s or GiB/s (see [here](https://www.home-assistant.io/integrations/sensor#device-class)). --- lib/extension/homeassistant.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/extension/homeassistant.ts b/lib/extension/homeassistant.ts index 20f3745a6f..6f78894011 100644 --- a/lib/extension/homeassistant.ts +++ b/lib/extension/homeassistant.ts @@ -1020,6 +1020,16 @@ export default class HomeAssistant extends Extension { Object.assign(extraAttrs, {device_class: 'energy', state_class: 'total_increasing'}); } + // If a variable includes A or mA, mark it as energy + if (firstExpose.unit && ['A', 'mA'].includes(firstExpose.unit)) { + Object.assign(extraAttrs, {device_class: 'current', state_class: 'measurement'}); + } + + // If a variable includes mW, W, kW, MW, GW, TW, mark it as energy + if (firstExpose.unit && ['mW', 'W', 'kW', 'MW', 'GW', 'TW'].includes(firstExpose.unit)) { + Object.assign(extraAttrs, {device_class: 'power', state_class: 'measurement'}); + } + let key = firstExpose.name; // Home Assistant uses a different voc device_class for µg/m³ versus ppb or ppm.