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

Add quirk for the TS0207 rain solar sensor #3475

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from

Conversation

aarongorka
Copy link

Proposed change

Adds a quirk that fixes this device by changing the "moving" and "closed" sensors to the rain and illuminance sensors that the device actually has.

image

Additional information

Most of the credit for this code goes to @hadeshimself from this comment.

Fixes #3249.

Checklist

  • The changes are tested and work correctly
  • pre-commit checks pass / the code has been formatted using Black
  • Tests have been added to verify that the new code works

Copy link

codecov bot commented Oct 30, 2024

Codecov Report

Attention: Patch coverage is 87.23404% with 6 lines in your changes missing coverage. Please review.

Project coverage is 89.43%. Comparing base (728ee42) to head (e1fa887).
Report is 54 commits behind head on dev.

Files with missing lines Patch % Lines
zhaquirks/tuya/ts0207.py 87.23% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #3475      +/-   ##
==========================================
- Coverage   89.44%   89.43%   -0.02%     
==========================================
  Files         311      312       +1     
  Lines       10033    10080      +47     
==========================================
+ Hits         8974     9015      +41     
- Misses       1059     1065       +6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Adds a quirk that fixes this device by changing the "moving" and
"closed" sensors to the rain and illuminance sensors that the device
actually has.

Most of the credit for this code goes to @hadeshimself from
[this](zigpy#3249 (comment))
comment.

Fixes zigpy#3249.
@aarongorka aarongorka force-pushed the add-ts0207-rain-solar-sensor branch from 57eac57 to a940591 Compare October 30, 2024 11:23
@aarongorka
Copy link
Author

FWIW I did briefly look at adding a test at least for the illuminance measurement getting copied in to a new cluster but I couldn't really get my head around how the existing tests are working.

@Fredyy90
Copy link

would be great is someone with the knowledeg, how the test should look like, could chip into this pr, currently my sensor is useless in homeassitant/zah until this quirk is live

@TheJulianJES TheJulianJES added the Tuya Request/PR regarding a Tuya device label Nov 24, 2024
Copy link
Collaborator

@TheJulianJES TheJulianJES left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might be able to do this cleaner with the new TuyaQuirkBuilder for v2 quirks.
Some WIP docs are here (from #3480). You can also search for TuyaQuirkBuilder in the repo to see existing quirks use this.

@TheJulianJES TheJulianJES added the v2 quirk candidate This PR is a good fit to be converted to a v2 quirk. label Nov 24, 2024
@prairiesnpr
Copy link
Contributor

prairiesnpr commented Nov 25, 2024

Just to give you something to start with, a v2 version might look something like this. Untested, I don't have the device.

"""Quirk for TS0207 rain sensors."""

from zigpy.quirks.v2.homeassistant import LIGHT_LUX, EntityType
from zigpy.quirks.v2.homeassistant.sensor import SensorDeviceClass, SensorStateClass
import zigpy.types as t
from zigpy.zcl.clusters.measurement import IlluminanceMeasurement
from zigpy.zcl.clusters.security import IasZone

from zhaquirks.tuya import TuyaLocalCluster
from zhaquirks.tuya.builder import TuyaQuirkBuilder


class TuyaIasZone(IasZone, TuyaLocalCluster):
    """IAS Zone for rain sensors."""

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


class TuyaIlluminanceCluster(IlluminanceMeasurement, TuyaLocalCluster):
    """Tuya Illuminance cluster."""


(
    TuyaQuirkBuilder("_TZ3210_tgvtvdoc", "TS0207")
    .tuya_dp(
        dp_id=101,
        ep_attribute=TuyaIlluminanceCluster.ep_attribute,
        attribute_name=TuyaIlluminanceCluster.AttributeDefs.measured_value.name,
        converter=lambda x: x * 7,
    )
    .adds(TuyaIlluminanceCluster)
    .tuya_sensor(
        dp_id=102,
        attribute_name="average_light_intensity_20mins",
        type=t.uint32_t,
        state_class=SensorStateClass.MEASUREMENT,
        device_class=SensorDeviceClass.DURATION,
        unit=LIGHT_LUX,
        entity_type=EntityType.DIAGNOSTIC,
        translation_key="average_light_intensity_20mins",
        fallback_name="Average light intensity last 20 min",
    )
    .tuya_sensor(
        dp_id=103,
        attribute_name="todays_max_light_intensity",
        type=t.uint32_t,
        state_class=SensorStateClass.MEASUREMENT,
        device_class=SensorDeviceClass.DURATION,
        unit=LIGHT_LUX,
        entity_type=EntityType.DIAGNOSTIC,
        translation_key="todays_max_light_intensity",
        fallback_name="Todays max light intensity",
    )
    .tuya_binary_sensor(
        dp_id=104,
        attribute_name="cleaning_reminder",
        translation_key="cleaning_reminder",
        fallback_name="Cleaning reminder",
    )
    .tuya_dp(
        dp_id=105,
        ep_attribute=TuyaIasZone.ep_attribute,
        attribute_name=TuyaIasZone.AttributeDefs.zone_status.name,
    )
    .adds(TuyaIasZone)
    .skip_configuration()
    .add_to_registry()
)

@inigortega
Copy link

Any updates with the merge of this pull request?
Thanks in advance,

@w-Oeps
Copy link

w-Oeps commented Dec 4, 2024

Hi, just bought this sensor and found this thread. So why not test the latest quirck code.
Tested the v2 code but getting an error:
In the ZHA integration
rainsensor

In the log I get::
2024-12-04 15:37:54.139 WARNING (SyncWorker_6) [zhaquirks] Loaded custom quirks. Please contribute them to https://github.com/zigpy/zha-device-handlers
2024-12-04 15:37:54.149 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Sonoff Zigbee 3.0 USB Dongle Plus V2, s/n: c84c4fc1d112ef11bca275b8bf9df066 - Itead for zha
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 635, in __async_setup_with_context
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/components/zha/init.py", line 132, in async_setup_entry
async with radio_mgr.connect_zigpy_app() as app:
File "/usr/local/lib/python3.12/contextlib.py", line 210, in aenter
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/components/zha/radio_manager.py", line 182, in connect_zigpy_app
app = await self.radio_type.controller.new(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zigpy/application.py", line 238, in new
await app._load_db()
File "/usr/local/lib/python3.12/site-packages/zigpy/application.py", line 110, in _load_db
await self._dblistener.load()
File "/usr/local/lib/python3.12/site-packages/zigpy/appdb.py", line 684, in load
device = zigpy.quirks.get_device(device)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/init.py", line 43, in get_device
return _DEVICE_REGISTRY.get_device(device)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/registry.py", line 130, in get_device
return quirk_entry.create_device(device)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/v2/init.py", line 429, in create_device
return CustomDeviceV2(device.application, device.ieee, device.nwk, device, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/v2/init.py", line 96, in init
replace_meta(self)
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/v2/init.py", line 212, in call
self.add(device)
File "/usr/local/lib/python3.12/site-packages/zigpy/quirks/v2/init.py", line 173, in call
cluster = self.cluster(endpoint, is_server=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/zhaquirks/tuya/mcu/init.py", line 209, in init
super().init(*args, **kwargs)
File "/usr/local/lib/python3.12/site-packages/zhaquirks/tuya/init.py", line 1529, in init
cluster = getattr(endpoint, dp_map.ep_attribute, None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: attribute name must be string, not 'type'
2024-12-04 15:37:54.985 ERROR (SyncWorker_10) [homeassistant] Error doing job: Task was destroyed but it is pending! (<Task pending name='Task-395' coro=<PersistingListener._worker() running at /usr/local/lib/python3.12/site-packages/zigpy/appdb.py:171> wait_for=>)

As double check installed the "v1" code from: #3249 (comment)
rainsensorok

And get the sensors came back (these are my first steps with ZHA, moving from Phoscon, and wanted to try first this rainsensor)

@prairiesnpr
Copy link
Contributor

Hi, just bought this sensor and found this thread. So why not test the latest quirck code. Tested the v2 code but getting an error: In the ZHA integration

Sorry about that, made a correction above, please test again if able.

@prairiesnpr prairiesnpr mentioned this pull request Dec 10, 2024
3 tasks
@w-Oeps
Copy link

w-Oeps commented Dec 11, 2024

Test have to wait a little. Rechargeable battery of the sensor is empty due to cloudy weather past week. No external charging possible.
Will test when the sun shines again

@bigman3
Copy link

bigman3 commented Dec 21, 2024

Quirk in v2 was tested
I suggest also to add the export of the raw value in mV, a block above the original 105 dp

   .tuya_sensor(
        dp_id=105,
        type=t.uint32_t,
        attribute_name="rain_intensity",
        device_class=SensorDeviceClass.VOLTAGE,
        unit=UnitOfElectricPotential.MILLIVOLT,
        fallback_name="Rain Intensity",
    )
    .tuya_dp(
        dp_id=105,
        ep_attribute=TuyaIasZone.ep_attribute,
        attribute_name=TuyaIasZone.AttributeDefs.zone_status.name,
    )
    .adds(TuyaIasZone)

Attaching example for several rainy hours. Rain was falling on and off, but in the periods it wasn't raining sensor stays wet, so can't rely on sensor as a realtime rain detector.

I'm going to use with some heuristic with average 5 or 10 samples to determine the start/finish of a rain, to close shutters, hope it will be reliable

image image

@prairiesnpr
Copy link
Contributor

I suggest also to add the export of the raw value in mV, a block above the original 105 dp

A couple questions, did the illuminance sensor work, looks like several other Tuya sensors need converter=lambda x: 10000 * math.log10(x) + 1 if x != 0 else 0, to scale to a reasonable value, wondering if it should be the same here.

Did the moisture binary actually show rain? I didn't realize that was in mv. Thinking this should be something like converter=lambda x: IasZone.ZoneStatus.Alarm_1 if x > 1000 else 0,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Tuya Request/PR regarding a Tuya device v2 quirk candidate This PR is a good fit to be converted to a v2 quirk.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Device Support Request] Tuya rainsensor TS0207_TZ3210_tgvtvdoc
7 participants