zha-device-handlers: _TZE204_ntcy3xu1 Smoke detector, battery missing

Bug description

Hi, I own a Tuya smoke detector. With the released quirk, only the smoke sensor is exposed, but the battery entity is missing. for Model _TZE204_ntcy3xu1. I have a custom quirk (see below), that offers the battery sensor, but the value readout is not correct. It jumps from 100% immediately to 5%

Steps to reproduce

Na

Expected behavior

Please Include the battery entity as well.

Screenshots/Video

Screenshots/Video

[Paste/upload your media here]

Device signature

Device signature
{
  "node_descriptor": {
    "logical_type": 2,
    "complex_descriptor_available": 0,
    "user_descriptor_available": 0,
    "reserved": 0,
    "aps_flags": 0,
    "frequency_band": 8,
    "mac_capability_flags": 128,
    "manufacturer_code": 4417,
    "maximum_buffer_size": 66,
    "maximum_incoming_transfer_size": 66,
    "server_mask": 10752,
    "maximum_outgoing_transfer_size": 66,
    "descriptor_capability_field": 0
  },
  "endpoints": {
    "1": {
      "profile_id": "0x0104",
      "device_type": "0x0402",
      "input_clusters": [
        "0x0000",
        "0x0001",
        "0x0004",
        "0x0005",
        "0x000f",
        "0x0500",
        "0xef00"
      ],
      "output_clusters": [
        "0x000a",
        "0x0019"
      ]
    }
  },
  "manufacturer": "_TZE204_ntcy3xu1",
  "model": "TS0601",
  "class": "TS0601_TZE204_ntcy3xu1.TuyaSmokeDetector0601"
}

Diagnostic information

Diagnostic information
[Paste the diagnostic information here]

Logs

Logs
[Paste the logs here]

Additional information

Custom quirk

import logging

import zigpy.profiles.zha
from zigpy.quirks import CustomDevice
import zigpy.types as t
from zigpy.zcl.clusters.general import (
    Basic,
    Groups,
    Ota,
    Scenes,
    Time,
    BinaryInput,
    BatterySize,
)
from zigpy.zcl.clusters.security import IasZone
from zhaquirks import Bus
from zhaquirks.const import (
    DEVICE_TYPE,
    ENDPOINTS,
    INPUT_CLUSTERS,
    MODELS_INFO,
    OUTPUT_CLUSTERS,
    PROFILE_ID,
    ZONE_TYPE,
)
from zhaquirks.tuya import (
    TuyaLocalCluster,
    TuyaManufCluster,
    TuyaManufClusterAttributes,
    TuyaPowerConfigurationCluster,
)

_LOGGER = logging.getLogger(__name__)

TUYA_SMOKE_DETECTED_ATTR = 0x0401  # [0]/[1] [Detected]/[Clear]!
TUYA_SMOKE_TAMPERED_ATTR = 0x0104  # [0]/[1] [Clear]/[Tampered]!
TUYA_SMOKE_BATTERY_ATTR = 0x040e  # [0]/[1]/[2] [Low]/[Med]]/[Full]!


class TuyaSmokeDetectorCluster(TuyaManufClusterAttributes):
    """Manufacturer Specific Cluster of the TS0601 smoke detector."""

    attributes = {
        TUYA_SMOKE_DETECTED_ATTR: ("smoke_detected", t.uint8_t, True),
        TUYA_SMOKE_TAMPERED_ATTR: ("tampered_device", t.uint8_t, True),
        TUYA_SMOKE_BATTERY_ATTR: ("battery_status", t.uint8_t, True),
    }

    def _update_attribute(self, attrid, value):
        super()._update_attribute(attrid, value)
        if attrid == TUYA_SMOKE_DETECTED_ATTR:
            status = IasZone.ZoneStatus.Alarm_1 if value == 0 else 0
            self.endpoint.device.ias_bus.listener_event("update_attribute", "zone_status", status)
        elif attrid == TUYA_SMOKE_TAMPERED_ATTR:
            self.endpoint.device.tamper_detection_bus.listener_event(
                "update_attribute", "present_value", bool(value)
            )
        elif attrid == TUYA_SMOKE_BATTERY_ATTR:
            batt = 5 if value == 0 else 40 if value == 1 else 100
            self.endpoint.device.battery_bus.listener_event("battery_change", batt)
        else:
            _LOGGER.warning(
                "[0x%04x:%s:0x%04x] unhandled attribute: 0x%04x",
                self.endpoint.device.nwk,
                self.endpoint.endpoint_id,
                self.cluster_id,
                attrid,
            )


class TuyaIasZone(TuyaLocalCluster, IasZone):
    """
    IAS Zone: this generates the "Smoke" entity for HA.
    Receives updates from TuyaSmokeDetectorCluster.
    """

    _CONSTANT_ATTRIBUTES = {ZONE_TYPE: IasZone.ZoneType.Fire_Sensor}

    def __init__(self, *args, **kwargs):
        """Init."""
        super().__init__(*args, **kwargs)
        self.endpoint.device.ias_bus.add_listener(self)


class TuyaPowerConfigCluster(TuyaPowerConfigurationCluster):
    """
    Power Config Cluster: this generates the "Battery" entity for HA.
    Receives updates from TuyaSmokeDetectorCluster.
    """

    _CONSTANT_ATTRIBUTES = {
        TuyaPowerConfigurationCluster.attributes_by_name["battery_size"].id: BatterySize.AAA,
        TuyaPowerConfigurationCluster.attributes_by_name["battery_quantity"].id: 2,
        TuyaPowerConfigurationCluster.attributes_by_name["battery_rated_voltage"].id: 15,
    }


class TuyaTamperDetection(TuyaLocalCluster, BinaryInput):
    """
    Tamper Detection Cluster: this generates the "Binary input" entity for HA, which is updated
    with the Tampered state. Receives updates from TuyaSmokeDetectorCluster.
    """

    _CONSTANT_ATTRIBUTES = {
        BinaryInput.attributes_by_name["description"].id: "Tamper Detected",
        BinaryInput.attributes_by_name["active_text"].id: "Tampered",
        BinaryInput.attributes_by_name["inactive_text"].id: "Clear",
    }

    def __init__(self, *args, **kwargs):
        """Init."""
        super().__init__(*args, **kwargs)
        self.endpoint.device.tamper_detection_bus.add_listener(self)


class TuyaSmokeDetector0601(CustomDevice):
    """TS0601 Smoke detector quirk."""

    def __init__(self, *args, **kwargs):
        """Init."""
        self.ias_bus = Bus()
        self.battery_bus = Bus()
        self.tamper_detection_bus = Bus()
        super().__init__(*args, **kwargs)

    signature = {
        MODELS_INFO: [
            ("_TZE204_ntcy3xu1", "TS0601"),
        ],
        ENDPOINTS: {
            1: {
                PROFILE_ID: zigpy.profiles.zha.PROFILE_ID,
                DEVICE_TYPE: zigpy.profiles.zha.DeviceType.SMART_PLUG,
                INPUT_CLUSTERS: [
                    Basic.cluster_id,
                    Groups.cluster_id,
                    Scenes.cluster_id,
                    TuyaManufCluster.cluster_id,
                ],
                OUTPUT_CLUSTERS: [
                    Time.cluster_id,
                    Ota.cluster_id,
                ],
            },
        },
    }

    replacement = {
        ENDPOINTS: {
            1: {
                PROFILE_ID: zigpy.profiles.zha.PROFILE_ID,
                DEVICE_TYPE: zigpy.profiles.zha.DeviceType.IAS_ZONE,
                INPUT_CLUSTERS: [
                    Basic.cluster_id,
                    Groups.cluster_id,
                    Scenes.cluster_id,
                    TuyaIasZone,
                    TuyaSmokeDetectorCluster,
                    TuyaPowerConfigCluster,
                    TuyaTamperDetection,
                ],
                OUTPUT_CLUSTERS: [
                    Time.cluster_id,
                    Ota.cluster_id,
                ],
            },
        },
    }

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 27

Most upvoted comments

@prairiesnpr Sorry, I have another small question. Since I played with this custom quirk, Reloading the ZHA integration gives this error: zigpy.exceptions.MultipleQuirksMatchException: Multiple matches found for device <Device model='TS0601' manuf='_TZE204_ntcy3xu1' When I fully restart HA, ZHA loads normal, but reloading still will fail. Is there some cache I can cleanup ?!

Update: found the cause: https://github.com/zigpy/zigpy/issues/1508, This work around works:

...
from zigpy.quirks import DEVICE_REGISTRY
del DEVICE_REGISTRY._registry_v2[("_TZE204_ntcy3xu1", "TS0601")]

class TuyaIAS(IasZone, TuyaLocalCluster):
...
Final custom quirk for TZE204_ntcy3xu1
from zhaquirks.tuya import TuyaLocalCluster
from zigpy.zcl.clusters.security import IasZone

from zhaquirks.tuya.builder import TuyaPowerConfigurationCluster2AAA, TuyaQuirkBuilder

from zigpy.quirks import DEVICE_REGISTRY
if DEVICE_REGISTRY._registry_v2[("_TZE204_ntcy3xu1", "TS0601")]:
    del DEVICE_REGISTRY._registry_v2[("_TZE204_ntcy3xu1", "TS0601")]


class TuyaIAS(IasZone, TuyaLocalCluster):
    """Tuya local IAS cluster."""

    _CONSTANT_ATTRIBUTES = {
        IasZone.AttributeDefs.zone_type.id: IasZone.ZoneType.Fire_Sensor
    }

(
    TuyaQuirkBuilder("_TZE204_ntcy3xu1", "TS0601")
    .tuya_dp(
        dp_id=1,
        ep_attribute=TuyaIAS.ep_attribute,
        attribute_name=IasZone.AttributeDefs.zone_status.name,
        converter=lambda x: IasZone.ZoneStatus.Alarm_1 if x == 0 else 0,
    )
    .adds(TuyaIAS)
    .tuya_dp(
        dp_id=14,
        ep_attribute=TuyaPowerConfigurationCluster2AAA.ep_attribute,
        attribute_name="battery_percentage_remaining",
        converter=lambda x: {0: 10, 1: 80, 2: 200}[x],
    )
    .adds(TuyaPowerConfigurationCluster2AAA)
    .skip_configuration()
    .add_to_registry()
)

Thanks again for all the help

Best Eric

Or is that the default for:

    .tuya_ias(dp_id=1)

That’s correct, see https://github.com/prairiesnpr/zha-device-handlers/blob/dee4296a65f49efee31231fd9807b5c3b67bb45b/zhaquirks/tuya/builder/__init__.py#L122

Since all of the smoke quirks used the same logic, I took the opportunity to add a helper method to TuyaQuirkBuilder and update all of the old style quirks in the same PR.

Update: with this ‘doubling modification’ it reports 100% for raw value 0x02. These relevant lines where in the log when pressing the test button:

Perfect, PR is updated once it’s merged you should be good.

Zigbee values are supposed to be doubled, I don’t recall where the conversation takes place right now though. You can try converter=lambda x: {0: 10, 1: 80, 2: 200}[x],

Changed the line and waiting for the next battery update… I start to understand the logging 😃 The raw battery value in the log is 0x02, so doubling seems right.

Update: with this ‘doubling modification’ it reports 100% for raw value 0x02. These relevant lines where in the log when pressing the test button:

[Alarm on]: 2024-12-09 13:46:41.068 DEBUG (MainThread) [zigpy.zcl] [0xCD84:1:0xef00] Received command 0x02 (TSN 105): set_data_response(data=TuyaCommand(status=0, tsn=55, datapoints=[TuyaDatapointData(dp=1, data=TuyaData(dp_type=<TuyaDPType.ENUM: 4>, function=0, raw=b'\x00', *payload=<enum8.undefined_0x00: 0>))]))
[battery]: 2024-12-09 13:46:41.215 DEBUG (MainThread) [zigpy.zcl] [0xCD84:1:0xef00] Received command 0x02 (TSN 106): set_data_response(data=TuyaCommand(status=0, tsn=56, datapoints=[TuyaDatapointData(dp=14, data=TuyaData(dp_type=<TuyaDPType.ENUM: 4>, function=0, raw=b'\x02', *payload=<enum8.undefined_0x02: 2>))]))
[Alarm off]: 2024-12-09 13:46:42.045 DEBUG (MainThread) [zigpy.zcl] [0xCD84:1:0xef00] Received command 0x02 (TSN 107): set_data_response(data=TuyaCommand(status=0, tsn=57, datapoints=[TuyaDatapointData(dp=1, data=TuyaData(dp_type=<TuyaDPType.ENUM: 4>, function=0, raw=b'\x01', *payload=<enum8.undefined_0x01: 1>))]))

Thanks for your help

Other note: All the testing seems to deplete the batteries quickly. Strange is that the battery reports 50% (instead of the coded 40% in the quirk). Doubth if this line is working (and maybe not needed): converter=lambda x: {0: 5, 1: 40, 2: 100}[x],

Zigbee values are supposed to be doubled, I don’t recall where the conversation takes place right now though. You can try converter=lambda x: {0: 10, 1: 80, 2: 200}[x],

I’m at work right now, will look at your logs this evening.

Good news on the inversion, I’ll correct the PR tonight.

Test it tomorrow 👌

Just tried the new version. It only offers the battery. Alarm sensor is gone.

PS: I didn’t trigger tamper in the provided log. I will record one for tamper as well

My bad, cp error, needed .adds(TuyaIAS), added it above.

Test it tomorrow 👌

I logged with my old V1 quirk. Device info:

IEEE: a4:c1:38:66:3a:ee:86:34
Nwk: 0xcd84
Device Type: EndDevice
LQI: 255
RSSI: -79
Last seen: 2024-12-08T15:42:20
Power source: Battery or Unknown
Quirk: TS0601_TZE204_ntcy3xu1.TuyaSmokeDetector0601

Look at timestamp 15:42:19.464

Thanks for your help! ZHA debug Smoke.txt

Yes, enable debug logging in ZHA, then if you can cut it to just the timestamps when are testing we should see the traffic and be able to tell where I went wrong.