Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Device Support Request] Tuya Zigbee smart energy meter DDS238-2 Zigbee with a new manufacturer variant (_TZE200_bkkmqmyo) #1700

Closed
mmaccaroni opened this issue Aug 21, 2022 · 43 comments
Labels
stale Issue is inactivate and might get closed soon Tuya Request/PR regarding a Tuya device waiting for reply Waiting for a reply (e.g. to test a custom quirk)

Comments

@mmaccaroni
Copy link

Hi, I purchased this device which was markes as working with zha, unfortunatrly I got one with a new manufacturer, and, upon pairing, no entities appear.
This is the signature

{
  "node_descriptor": "NodeDescriptor(logical_type=<LogicalType.Router: 1>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.AllocateAddress|RxOnWhenIdle|MainsPowered|FullFunctionDevice: 142>, manufacturer_code=4098, maximum_buffer_size=82, maximum_incoming_transfer_size=82, server_mask=11264, maximum_outgoing_transfer_size=82, descriptor_capability_field=<DescriptorCapability.NONE: 0>, *allocate_address=True, *is_alternate_pan_coordinator=False, *is_coordinator=False, *is_end_device=False, *is_full_function_device=True, *is_mains_powered=True, *is_receiver_on_when_idle=True, *is_router=True, *is_security_capable=False)",
  "endpoints": {
    "1": {
      "profile_id": 260,
      "device_type": "0x0051",
      "in_clusters": [
        "0x0000",
        "0x0004",
        "0x0005",
        "0xef00"
      ],
      "out_clusters": [
        "0x000a",
        "0x0019"
      ]
    }
  },
  "manufacturer": "_TZE200_bkkmqmyo",
  "model": "TS0601",
  "class": "zigpy.device.Device"
}

Tried to adapt other quirks that were shared in the past with no success

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

Hello @mmaccaroni ,

I assume the new device is the single phase power metter, correct?
What you tried to change in the quirk, and how installed it?

@mmaccaroni
Copy link
Author

Hello @mmaccaroni ,

I assume the new device is the single phase power metter, correct? What you tried to change in the quirk, and how installed it?

Hi darckly, thanks for your reply. Yes it is the single phase.
I set up a folder for custom quirks and pointed to in my configuration.yaml.
The change I made iwas the manufacturer string as per signature, but nothing happened. I truly have no idea what am I doing wrong.

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

Hi @mmaccaroni

Looks like you are doing the right things,
What you see in the Device Info screen?

If it loaded with using custom quirk, the screen should be like this:
image

@mmaccaroni
Copy link
Author

If I use the quirk I got thus error

Logger: homeassistant.config_entries
Source: quirks/ts0601_din_power.py:28
First occurred: 13:36:46 (1 occurrences)
Last logged: 13:36:46

Error setting up entry Sonoff Zigbee 3.0 USB Dong - /dev/serial/by-id/usb-ITead_Sonoff_Zigbee_3.0_USB_Dongle_Plus_9a4120891045ec118fb796fd6f14af06-if00-port0, s/n: 9a4120891045ec118fb796fd6f14af06 - ITead - 10C4:EA60 for zha
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 357, in async_setup
result = await component.async_setup_entry(hass, self)
File "/usr/src/homeassistant/homeassistant/components/zha/init.py", line 101, in async_setup_entry
setup_quirks(config)
File "/usr/local/lib/python3.10/site-packages/zhaquirks/init.py", line 409, in setup
importer.find_module(modname).load_module(modname)
File "", line 548, in _check_name_wrapper
File "", line 1063, in load_module
File "", line 888, in load_module
File "", line 290, in _load_module_shim
File "", line 719, in _load
File "", line 688, in _load_unlocked
File "", line 883, in exec_module
File "", line 241, in _call_with_frames_removed
File "/config/quirks/ts0601_din_power.py", line 28, in
class TuyaManufClusterDinPower(TuyaManufClusterAttributes):
File "/usr/local/lib/python3.10/site-packages/zigpy/zcl/init.py", line 91, in init_subclass
raise TypeError(
TypeError: manufacturer_attributes is deprecated. Copy the parent class's attributes dictionary and update it with your manufacturer-specific attributes. Make sure to specify that it is manufacturer-specific through the appropriate constructor or tuple!

@mmaccaroni
Copy link
Author

This is the quirk I am loading for that error

`"""Tuya Din Power Meter."""
from zigpy.profiles import zha
import zigpy.types as t
from zigpy.zcl.clusters.general import Basic, Groups, Ota, Scenes, Time
from zigpy.zcl.clusters.homeautomation import ElectricalMeasurement
from zigpy.zcl.clusters.smartenergy import Metering

from zhaquirks import Bus, LocalDataCluster
from zhaquirks.const import (
DEVICE_TYPE,
ENDPOINTS,
INPUT_CLUSTERS,
MODELS_INFO,
OUTPUT_CLUSTERS,
PROFILE_ID,
)
from zhaquirks.tuya import TuyaManufClusterAttributes, TuyaOnOff, TuyaSwitch

TUYA_TOTAL_ENERGY_ATTR = 0x0211
TUYA_CURRENT_ATTR = 0x0212
TUYA_POWER_ATTR = 0x0213
TUYA_VOLTAGE_ATTR = 0x0214
TUYA_DIN_SWITCH_ATTR = 0x0101

SWITCH_EVENT = "switch_event"

class TuyaManufClusterDinPower(TuyaManufClusterAttributes):
"""Manufacturer Specific Cluster of the Tuya Power Meter device."""

manufacturer_attributes = {
    TUYA_TOTAL_ENERGY_ATTR: ("energy", t.uint16_t),
    TUYA_CURRENT_ATTR: ("current", t.int16s),
    TUYA_POWER_ATTR: ("power", t.uint16_t),
    TUYA_VOLTAGE_ATTR: ("voltage", t.uint16_t),
    TUYA_DIN_SWITCH_ATTR: ("switch", t.uint8_t),
}

def _update_attribute(self, attrid, value):
    super()._update_attribute(attrid, value)
    if attrid == TUYA_TOTAL_ENERGY_ATTR:
        self.endpoint.smartenergy_metering.energy_reported(value / 100)
    elif attrid == TUYA_CURRENT_ATTR:
        self.endpoint.electrical_measurement.current_reported(value)
    elif attrid == TUYA_POWER_ATTR:
        self.endpoint.electrical_measurement.power_reported(value / 10)
    elif attrid == TUYA_VOLTAGE_ATTR:
        self.endpoint.electrical_measurement.voltage_reported(value / 10)
    elif attrid == TUYA_DIN_SWITCH_ATTR:
        self.endpoint.device.switch_bus.listener_event(
            SWITCH_EVENT, self.endpoint.endpoint_id, value
        )

class TuyaPowerMeasurement(LocalDataCluster, ElectricalMeasurement):
"""Custom class for power, voltage and current measurement."""

cluster_id = ElectricalMeasurement.cluster_id

POWER_ID = 0x050B
VOLTAGE_ID = 0x0505
CURRENT_ID = 0x0508

AC_CURRENT_MULTIPLIER = 0x0602
AC_CURRENT_DIVISOR = 0x0603

_CONSTANT_ATTRIBUTES = {AC_CURRENT_MULTIPLIER: 1, AC_CURRENT_DIVISOR: 1000}

def voltage_reported(self, value):
    """Voltage reported."""
    self._update_attribute(self.VOLTAGE_ID, value)

def power_reported(self, value):
    """Power reported."""
    self._update_attribute(self.POWER_ID, value)

def current_reported(self, value):
    """Ampers reported."""
    self._update_attribute(self.CURRENT_ID, value)

class TuyaElectricalMeasurement(LocalDataCluster, Metering):
"""Custom class for total energy measurement."""

cluster_id = Metering.cluster_id
CURRENT_ID = 0x0000
POWER_WATT = 0x0000

"""Setting unit of measurement."""
_CONSTANT_ATTRIBUTES = {0x0300: POWER_WATT}

def energy_reported(self, value):
    """Summation Energy reported."""
    self._update_attribute(self.CURRENT_ID, value)

class TuyaPowerMeter(TuyaSwitch):
"""Tuya power meter device."""

def __init__(self, *args, **kwargs):
    """Init device."""
    self.switch_bus = Bus()
    super().__init__(*args, **kwargs)

signature = {
    # "node_descriptor": "<NodeDescriptor byte1=1 byte2=64 mac_capability_flags=142 manufacturer_code=4098
    #                       maximum_buffer_size=82 maximum_incoming_transfer_size=82 server_mask=11264
    #                       maximum_outgoing_transfer_size=82 descriptor_capability_field=0>",
    # device_version=1
    # input_clusters=[0x0000, 0x0004, 0x0005, 0xef00]
    # output_clusters=[0x000a, 0x0019]
    MODELS_INFO: [
        ("_TZE200_byzdayie", "TS0601"),
        ("_TZE200_ewxhg6o9", "TS0601"),
        ("_TZE200_bkkmqmyo", "TS0601"),
    ],
    ENDPOINTS: {
        # <SimpleDescriptor endpoint=1 profile=260 device_type=51
        # device_version=1
        # input_clusters=[0, 4, 5, 61184]
        # output_clusters=[10, 25]>
        1: {
            PROFILE_ID: zha.PROFILE_ID,
            DEVICE_TYPE: zha.DeviceType.SMART_PLUG,
            INPUT_CLUSTERS: [
                Basic.cluster_id,
                Groups.cluster_id,
                Scenes.cluster_id,
                TuyaManufClusterAttributes.cluster_id,
            ],
            OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id],
        }
    },
}

replacement = {
    ENDPOINTS: {
        1: {
            PROFILE_ID: zha.PROFILE_ID,
            DEVICE_TYPE: zha.DeviceType.SMART_PLUG,
            INPUT_CLUSTERS: [
                Basic.cluster_id,
                Groups.cluster_id,
                Scenes.cluster_id,
                TuyaManufClusterDinPower,
                TuyaPowerMeasurement,
                TuyaElectricalMeasurement,
                TuyaOnOff,
            ],
            OUTPUT_CLUSTERS: [Time.cluster_id, Ota.cluster_id],
        }
    }
}

`

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

@mmaccaroni

Hmm, I don't update my instance of HA for several months, so looks like my configuration is not affected. But I see that a lot of dicsussions about this error: home-assistant/core#69494

The possible solutions, as I see from the discussion:

  • Remove /config/deps/lib/
  • Reverting to version 2022.3.8
  • Changing "manufacturer_attributes" to "attributes"

Could you try the solutions from that tread?
Sorry, can't support you with testing, as temporary I haven't ability to update my configuration and check.

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

@mmaccaroni

I was not aware, but indeed, some changes were made in April to support ZCLv7 zigpy changes.
Please use as a source for modification this file: https://github.com/zigpy/zha-device-handlers/blob/dev/zhaquirks/tuya/ts0601_din_power.py

Not the file attached in the issue #1298

@mmaccaroni
Copy link
Author

@darckly

You are the man thanks now the quirk seems to be working when I rejoin the device! I see the switch control and the electrical measurement entity. However none of them seems to be working. What do you need ? Is it because of clusters right?
Screenshot_20220821-161611_Home Assistant

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

@mmaccaroni sometimes it need some time for sensors to appear (or restart HA again), and also connect the load to the power metter, e.g. iron or kettle.

@mmaccaroni
Copy link
Author

Ok i will try, in the meantime if you need me for debugging, if needed, I am at full disposal. Thank you again!

@darckly
Copy link
Contributor

darckly commented Aug 21, 2022

Well, in parallel you can debug your device as desribed here: #1298 (comment) and send me the logs

@mmaccaroni
Copy link
Author

zhaquirks.log
@darckly thanks a lot, I enabled debugging as per instructions, let me kn ow if it is sufficient for you.

@darckly
Copy link
Contributor

darckly commented Aug 22, 2022

@mmaccaroni Could you send me a link where you ordered this version of power meter?
I briefly looked into the log, and a bit puzzled. Looks like this is completelly new device with own attributes.
I want to check the specification of your device.

@mmaccaroni
Copy link
Author

@darckly this is the link where I ordered from Aliexpress:
https://a.aliexpress.com/_v1DOnz
Nes device? Wow that was really unexpected.

@darckly
Copy link
Contributor

darckly commented Aug 22, 2022

@mmaccaroni may I ask you to unpair the power meter, enable logging, pair the metter again (with load), turn on/off the device and send me the logs again.
I don't know what the reason, but I don't see the strings with "(command 0x0001)" ending in the log. Command 0x0001 is TUYA_GET_DATA, so after this command the device should send the actual data to HA

@darckly
Copy link
Contributor

darckly commented Aug 22, 2022

And do you have any other devices connected via ZHA, like termostat?

@mmaccaroni
Copy link
Author

Sure will do, power on and off from zha or manually from the device?
Yes I have other devices: Ikea Fyrtur covers with their remotes and repeaters, TS011F pkugs, Aqara Opple 6 button remote and my coordinator is a Sonoff zigbee 3.0. Everytings works perfectly with no issues.

@darckly
Copy link
Contributor

darckly commented Aug 22, 2022

Please do the both: on and off from ZHA and manually.

@mmaccaroni
Copy link
Author

@darckly ok I performed the operations, the log is attached. I don't know if it is good but I enclose every ZHA related events, not only the quirk debug strings.
For your reference the device is joinded with Nwk: 0xc150.
When trying to operate upoon the zha switch entityi get the following error:

[546990539824] 'Status' object is not subscriptable Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 199, in handle_call_service await hass.services.async_call( File "/usr/src/homeassistant/homeassistant/core.py", line 1713, in async_call task.result() File "/usr/src/homeassistant/homeassistant/core.py", line 1750, in _execute_service await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)( File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 204, in handle_service await service.entity_service_call( File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 676, in entity_service_call future.result() # pop exception if have File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 930, in async_request_call await coro File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 713, in _handle_entity_call await result File "/usr/src/homeassistant/homeassistant/components/zha/switch.py", line 89, in async_turn_on result = await self._on_off_channel.turn_on() File "/usr/src/homeassistant/homeassistant/components/zha/core/channels/general.py", line 342, in turn_on if isinstance(result, Exception) or result[1] is not Status.SUCCESS: TypeError: 'Status' object is not subscriptable

it is also in the attached log. Events in the log are from the device join process, load attached since the beginning. Let me know if you need anything else and again thanks a lot for your support.
home-assistant.log

@darckly
Copy link
Contributor

darckly commented Aug 23, 2022

@mmaccaroni Could you try this slightly modified quirk? At least to test on/off functionality

I'm trying to see what changed in other tuya quirks and apply the same changes..
ts0601_din_power.zip
.

@mmaccaroni
Copy link
Author

@darckly thanks for your reply, loaded the quirk and repaired the device, the switch doe not work, but Idon't get the error message anymore. I attach the log for your reference
home-assistant.log

@darckly
Copy link
Contributor

darckly commented Aug 27, 2022

@mmaccaroni unfortunatelly, can't find the way how to implement the support without having this device. I see that on zigbee2mqtt also has an issue with this manufacturing ID : On the outside, there are no differences. This version is not recognised by zigbee2mqtt; apparently it uses another format. (Koenkk/zigbee2mqtt.io@e463498)

Maybe someone else from contibutors can support... Also I'll continue to monitor Z2M forum.

@mmaccaroni
Copy link
Author

Thanks a lot @darckly really appreciated your support!

@gerrytb
Copy link

gerrytb commented Sep 12, 2022

I am on the same situation, I bought this device because it was marked as "supported" on https://zigbee.blakadder.com/Hiking_DDS238-2.html
So I followed the link of aliexpress and now I realized that is a total different product. I didn't receive it yet, so by the moment I cannot help.
I hope that it can be supported soon.

@johndekroon
Copy link

johndekroon commented Oct 1, 2022

Just received the same device. And since I'm here you can guess I also received the unsupported _TZE200_bkkmqmyo version, which was sold as "supported". I can pair it, but no entities are showing up. I was able to load the suggested quirk, and got the same results as described above.

@boszenlaszlo
Copy link

boszenlaszlo commented Oct 13, 2022

I have the same device and i managed to work almost everything, except the current reading. Based on Zigbee2mqtt Koenkk/zigbee2mqtt#13767 i need to separate the voltage and current readings from one attribute, but i dont know how.
power_meter1

My custom quirks: ts0601_din_power.txt

@johndekroon
Copy link

johndekroon commented Oct 13, 2022

I have the same device and i managed to work almost everything, except the current reading. Based on Zigbee2mqtt Koenkk/zigbee2mqtt#13767 i need to separate the voltage and current readings from one attribute, but i dont know how.

Interessing. I tried your quirk and now it indeed shows readings. However: the readings are entirely different than on the screen of the device. The current reading is indeed different, but also the energy summation is 0kWh instead of 51.1kWh.

@EstSoft87
Copy link

Any good news?

@boszenlaszlo
Copy link

Current reading is works now. I put the some comment about the cluster data in the file. I put the reactive power in the code, but dont show up as sensor.
zha1

zha2

You can download the new version here: ts0601_din_power_v2.zip

@Dogmeat88
Copy link

Dogmeat88 commented Oct 29, 2022

You can download the new version here: ts0601_din_power_v2.zip

Thanks for your efforts @boszenlaszlo
I have added the quirk you have been working on and all the values seem to be displaying fine. However the toggling the switch produces the error: 'Status' object is not subscriptable
Any idea what could be causing this?
Thanks in advance.
Update: Oops sorry I see the switch issue is referenced a couple of posts above, with no resolution.

image

Logger: homeassistant.components.websocket_api.http.connection
Source: components/zha/core/channels/general.py:350
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 8:53:10 AM (3 occurrences)
Last logged: 9:48:39 AM

[139654927593296] 'Status' object is not subscriptable
[139654898783744] 'Status' object is not subscriptable
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 202, in handle_call_service
    await hass.services.async_call(
  File "/usr/src/homeassistant/homeassistant/core.py", line 1738, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1775, in _execute_service
    await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 207, in handle_service
    await service.entity_service_call(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 678, in entity_service_call
    future.result()  # pop exception if have
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 931, in async_request_call
    await coro
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 715, in _handle_entity_call
    await result
  File "/usr/src/homeassistant/homeassistant/components/zha/switch.py", line 97, in async_turn_off
    result = await self._on_off_channel.turn_off()
  File "/usr/src/homeassistant/homeassistant/components/zha/core/channels/general.py", line 350, in turn_off
    if isinstance(result, Exception) or result[1] is not Status.SUCCESS:
TypeError: 'Status' object is not subscriptable

@johndekroon
Copy link

johndekroon commented Oct 30, 2022

I have a feeling that the current wattage is a bit off :) Voltage and Amperage seem to work fine, so it would be possible to calculate it.
image

@flaktivated
Copy link
Contributor

flaktivated commented Nov 1, 2022

Hello, I have one of these devices and seem to be working on it in parallel. My PR is here: #1878

I have the following configured and displaying correct values in Home Assistant:

  • Sum of Energy Consumed (Delivered)
  • RMS Voltage
  • RMS Current
  • Active Power
  • AC Frequency
  • Power Factor
    image

The switch successfully toggles the Meter, but get the error message as well. @javicalle hopes that the following PR will fix the error message: #1859

With the following attributes correctly mapped but not showing as sensors (These are committed in my PR as I do not believe it is an issue with the quirk):

  • Reactive Power
  • Sum of Reactive Power
  • Sum of Energy Generated (Received)

image
image
image


Has anyone here got the reactive power and energy generated to display under sensors?

Update: So I did some digging and it seems the ZHA core does not support all the options under ElelctricalMeasurement or Metering. See here: https://github.com/home-assistant/core/blob/dev/homeassistant/components/zha/sensor.py#L265

Noticed that it does have a provision for apparent_power: https://github.com/home-assistant/core/blob/dev/homeassistant/components/zha/sensor.py#L265

I tried updating reactive power to apparent power mapping to test and it displayed as a sensor:
image

To Do: We will need to raise a PR for ZHA core to add support for the missing sensors.
I imagine something like this added to sensor.py should do the trick

from homeassistant.const import (
...
    POWER_VOLT_AMPERE_REACTIVE,
    POWER_KILO_VOLT_AMPERE_REACTIVE_HOUR,
...
}

@MULTI_MATCH(channel_names=CHANNEL_ELECTRICAL_MEASUREMENT)
class ElectricalMeasurementReactivePower(ElectricalMeasurement, id_suffix="reactive_power"):
    """Reactive power measurement."""

    SENSOR_ATTR = "reactive_power"
    _attr_device_class: SensorDeviceClass = SensorDeviceClass.REACTIVE_POWER
    _attr_should_poll = False  # Poll indirectly by ElectricalMeasurementSensor
    _unit = POWER_VOLT_AMPERE_REACTIVE


@MULTI_MATCH(channel_names=CHANNEL_ELECTRICAL_MEASUREMENT)
class ElectricalMeasurementTotalReactivePower(ElectricalMeasurement, id_suffix="total_reactive_power"):
    """Total Reactive Power measurement."""

    SENSOR_ATTR = "total_reactive_power"
    _attr_device_class: SensorDeviceClass = SensorDeviceClass.REACTIVE_POWER
    _attr_should_poll = False  # Poll indirectly by ElectricalMeasurementSensor
    _unit = POWER_KILO_VOLT_AMPERE_REACTIVE_HOUR
    _decimals: 2

    def formatter(self, value: int) -> int | float:
        """Return 'normalized' value."""
        value = float(value) / 100
        if value < 100:  # only round tinny values
            return round(value, self._decimals)
        return round(value)

class SmartEnergyReceivedSummation(SmartEnergyMetering, id_suffix="summation_received"):
    """Smart Energy Metering summation sensor."""

    SENSOR_ATTR: int | str = "current_summ_received"
    _attr_device_class: SensorDeviceClass = SensorDeviceClass.ENERGY
    _attr_state_class: SensorStateClass = SensorStateClass.TOTAL_INCREASING

    unit_of_measure_map = {
        0x00: ENERGY_KILO_WATT_HOUR,
        0x01: VOLUME_CUBIC_METERS,
        0x02: VOLUME_CUBIC_FEET,
        0x03: f"100 {VOLUME_CUBIC_FEET}",
        0x04: f"US {VOLUME_GALLONS}",
        0x05: f"IMP {VOLUME_GALLONS}",
        0x06: "BTU",
        0x07: VOLUME_LITERS,
        0x08: "kPa",  # gauge
        0x09: "kPa",  # absolute
        0x0A: f"1000 {VOLUME_CUBIC_FEET}",
        0x0B: "unitless",
        0x0C: "MJ",
    }

    def formatter(self, value: int) -> int | float:
        """Numeric pass-through formatter."""
        if self._channel.unit_of_measurement != 0:
            return self._channel.summa_formatter(value)

        cooked = float(self._channel.multiplier * value) / self._channel.divisor
        return round(cooked, 3)

Also add support for the new unit in const.py

# Reactive power units
...
POWER_KILO_VOLT_AMPERE_REACTIVE_HOUR: Final = "kVAr"

The above should solve our issue - hacked it into my HA directly and seems like it works!
image

Two things I am not sure of:

  1. How to increase the resolution of sensors (i.e. Total Reactive Power, would be nice to have 2 Decimal Places)
  2. How to get the above code changes into the zha core. Seems to be quite involved.

@javicalle
Copy link
Collaborator

  1. How to increase the resolution of sensors (i.e. Total Reactive Power, would be nice to have 2 Decimal Places)

The Sensor class have a decimal attribute:

@flaktivated
Copy link
Contributor

flaktivated commented Nov 1, 2022

Updated the total reactive power sensor definition as follows:

@MULTI_MATCH(channel_names=CHANNEL_ELECTRICAL_MEASUREMENT)
class ElectricalMeasurementTotalReactivePower(ElectricalMeasurement, id_suffix="total_reactive_power"):
    """Total Reactive Power measurement."""

    SENSOR_ATTR = "total_reactive_power"
    _attr_device_class: SensorDeviceClass = SensorDeviceClass.REACTIVE_POWER
    _attr_should_poll = False  # Poll indirectly by ElectricalMeasurementSensor
    _unit = POWER_KILO_VOLT_AMPERE_REACTIVE_HOUR
    _decimals: 2

Restarted HA and checked sensor dashboard and still shows 0dp:
image

Thought my quirk might have a bug, checked configuration for a division error:

elif attrid == HIKING_TOTAL_REACTIVE_ATTR:
            self.endpoint.electrical_measurement.reactive_energy_reported(value / 100)

image
Meter shows 0.2kvar on display so all looks good with the above.

Changes the divisor from 100 to 10 to test and the value for the sensor shows the value 2.
image

So the quirk doesn't seem to be the issue.

@javicalle
Copy link
Collaborator

I believe that the total_reactive_power attribute is a integer:

So, the 23/100=0,23 --> 0

The problem is that total_reactive_power don't configure any multiplier or divisor that can allow the decimal values.

Maybe you can keep the value as is in the _update_attribute and overwritte the formatter in the ElectricalMeasurementTotalReactivePower:

    def formatter(self, value: int) -> int | float:
        """Return 'normalized' value."""
        value = float(value) / 100
        if value < 100:  # only round tinny values
            return round(value, self._decimals)
        return round(value)

@flaktivated
Copy link
Contributor

flaktivated commented Nov 1, 2022

That works perfectly!
image

Updated the sensor.py code in my comment above with the addition.
Merged this change into (#1878) to make it ready for display in the future.

@javicalle
Copy link
Collaborator

# Reactive power units
...
POWER_KILO_VOLT_AMPERE_REACTIVE_HOUR: Final = "kvarh"

According to the specification the units would be kVAr:

image

image

Reference:

@flaktivated
Copy link
Contributor

flaktivated commented Nov 2, 2022

Thanks for picking that up, I just copied what came with the meter instructions.

Code snippet above updated.

Keen to get this merged into core is there any etiquette or best practices to follow? Or just fork and PR?

@javicalle
Copy link
Collaborator

Let see if I can recall all the info.

The current device classes in HA are listed here:

There is a reactive_power type and the supported units are var (in lowercase 🤷🏻‍♂️)

Usually, any change of types and units will require a architecture discussion.
The reactive_power was discused here:

After that, a couple of discussions have been arise:

The first one (724) talks about the reactive energy and its units kvarh (so your device measure reactive_power or reactive_energy?) . Also reference some specifications and integrations that use it.

So, what now?
I guess that the path to follow would be the architecture discussion. Can be a slow way but I believe that is the right one.
You can expose your case there and see if that drives you somewhere.

dmulcahey pushed a commit that referenced this issue Nov 11, 2022
…iguration (#1877)(#1700) (#1878)

* TS0601 - _TZE200_bkkmqmyo - Basic Switch Support Added (#1877)

* Fixing code style errors and warnings from flake8 (#1877)

* Fixing code style errors from black (#1877)

* Fixing code style errors from black and flake8 (#1877)

* Energy Summation and RMS Voltage Support (#1877)

* Adding Power Measurement and Fixing Switch Attribute (#1877)

* Fixing code style errors from black (#1877)

* Add Support for AC Frequency (#1878)

* Fix code style issues identified by flake8 and black (#1878)

* Fix code style issues identified by black (#1878)

* Add Support for Power Factor (#1878)

* Code style fixes - black and flake8 (#1878)

* Code style fixes - black (#1878)

* Add Support for RMS Current (#1878)

* Add Support For Energy Received / Generated (#1878)

* Add Support for Reactive Power and Totals (#1878)

Note this does not display under sensors for HA

* Removing Divide for Total Reactive Power for better resolution(#1878)

total_reactive_power is an integer so decimals are rounded during conversion. Moving the formatting to happen at the sensor level.
@marcoNieddu
Copy link

marcoNieddu commented Dec 3, 2022

No possible to change the reporting frequency

@javicalle
Copy link
Collaborator

Can someone confirm that #1878 fix that issue?

@TheJulianJES TheJulianJES added Tuya Request/PR regarding a Tuya device waiting for reply Waiting for a reply (e.g. to test a custom quirk) labels Jan 4, 2023
@github-actions
Copy link

github-actions bot commented Jul 3, 2023

There hasn't been any activity on this issue recently. Due to the high number of incoming GitHub notifications, we have to clean some of the old issues, as many of them have already been resolved with the latest updates. Please make sure to update to the latest version and check if that solves the issue. Let us know if that works for you by adding a comment 👍 This issue has now been marked as stale and will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions bot added the stale Issue is inactivate and might get closed soon label Jul 3, 2023
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jul 10, 2023
@jovanyeo
Copy link

Current reading is works now. I put the some comment about the cluster data in the file. I put the reactive power in the code, but dont show up as sensor.
zha1

zha2

You can download the new version here: ts0601_din_power_v2.zip

Hello,

Does this quirk works for this: _TZE204_cjbofhxw too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stale Issue is inactivate and might get closed soon Tuya Request/PR regarding a Tuya device waiting for reply Waiting for a reply (e.g. to test a custom quirk)
Projects
None yet
Development

No branches or pull requests