CestLaGalere / mobilealerts

Retrieves sensor data for Mobile Alerts sensors for Home Assistant
Apache License 2.0
15 stars 4 forks source link

Water leak sensor #5

Open zmechu opened 1 year ago

zmechu commented 1 year ago

Hello! I have got Mobile Alerts sensor: https://mobile-alerts.eu/en/temperatur-und-luftfeuchtesensor-mit-zusaetzlichem-wasserdetektor-ma-10350-2/ It has ability to measure temperature, humidity and has water leak sensor.

Under HA it returns attributes:

ma

Measuring temperature and humidity works fine. My question is: how to get information from water leak sensor? Thank you in advance!

petrleocompel commented 1 year ago

Can you test what value will change if you "trigger" the leak sensor ?

Please post measurements before and after triggering to clearly see what we should look on.

Then we will add it to the entities for support (it will have to be configured)

zmechu commented 12 months ago

Hello! Sorry for delay! Seems to be clear. Water sensor not triggered: obraz Triggered: obraz Then not triggered: obraz So, "t2" attribute shows water sensor. Voila :-)

Only one thing: "t2" attribute shows temperature, and water leak sensor is decoded as "0,0 °C" or "1,0 °C" when triggered. It can be "fixed" using templates, but maybe there is more convenient way?

petrleocompel commented 12 months ago

@zmechu can you post your configuration for mobilealerts ? Delete account related info. This sensor is needed.

I guess we should introduce new type for water leak sensor and correctly decode it. I will take look in docs for it, what will be the best implementation.

zmechu commented 12 months ago

My config:

  - platform: mobile_alerts
    phone_id: XXXXXXX
    devices:  
      - device_id: YYYYYYYYY
        name: TEMP YYYYYYYYY
        type: t1       
      - device_id: YYYYYYYYY
        name: RH YYYYYYYYY
        type: h            
      - device_id: YYYYYYYYY
        name: BATT YYYYYYYYY
        type: lb    

//leak sensor
      - device_id: YYYYYYYYY
        name: WATER YYYYYYYYY
        type: t2

In my opinion it will be enough to "expand" "t2" sensor for two sensors: one "t2" as ordinary temperature sensor (measured temperature in Celsius) and second one (for example "t2_leak") used as leak sensor - on/off binary sensor.

Or, easier way: create additional (optional) section, for example "mode", look like:

//temperature sensor
      - device_id: YYYYYYYYY
        name: TEMP YYYYYYYYY
        type: t1
//leak sensor
      - device_id: YYYYYYYYY
        name: WATER YYYYYYYYY
        type: t2
        // optional
        mode: binary (or leak, or alarm, or warning, or water, or wet)

Then, "t2" sensor will return "°C" value when "mode" not defined (by default) or return "on/off" when "mode" section is defined.

CestLaGalere commented 12 months ago

@zmechu do you have curl? if so please try the command below (replace XXXXXXXX with your deviceid & post the json response here. if you cannot run this I am happy to do so if I can have your deviceid - it will allow me to see what data is returned. Thanks. Their documentation is outdated as it does not show any info on water leak sensors.

curl -d "{'deviceids': 'XXXXXXXXX'}" -H "Content-Type: application/json" https://www.data199.com/api/pv1/device/lastmeasurement
zmechu commented 12 months ago
curl -d "{'deviceids': 'XXXXXXXXX'}" -H "Content-Type: application/json" https://www.data199.com/api/pv1/device/lastmeasurement
{
  "devices": [
    {
      "deviceid": "XXXXXXXXX",
      "lastseen": 1690390222,
      "lowbattery": false,
      "measurement": {
        "idx": 143389,
        "ts": 1690390217,
        "c": 1690390222,
        "lb": false,
        "t1": 23.0,
        "t2": 0.0,
        "h": 48.0
      }
    }
  ],
  "success": true
CestLaGalere commented 12 months ago

I have created a Water sensor that needs the setup:

      - device_id: YYYYYYYYY
        name: WATER YYYYYYYYY
        type: water

this should return two states: 'dry' and 'wet' (to correspond to the Mobile Alerts app UI.

zmechu commented 12 months ago

Almost perfect :-) mobile_alerts updated, HA restarted, and errors in log:

Logger: homeassistant.components.sensor
Source: custom_components/mobile_alerts/sensor.py:312
Integration: Sensor (documentation, issues)
First occurred: 19:16:08 (2 occurrences)
Last logged: 19:16:09

Error adding entities for domain sensor with platform mobile_alerts
Error while setting up mobile_alerts platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 504, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 788, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1006, in add_to_platform_finish
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 742, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 810, in _async_write_ha_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 748, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 478, in state
    value = self.native_value
            ^^^^^^^^^^^^^^^^^
  File "/config/custom_components/mobile_alerts/sensor.py", line 312, in native_value
    return WATER_SENSOR_WET
           ^^^^^^^^^^^^^^^^
NameError: name 'WATER_SENSOR_WET' is not defined
CestLaGalere commented 12 months ago

@zmechu apologies - missed this & didn't look at the logs! Hopefully OK now

zmechu commented 12 months ago

99% done :-) Kind of data types conversion...

Logger: homeassistant.components.sensor
Source: components/sensor/__init__.py:594
Integration: Sensor (documentation, issues)
First occurred: 22:38:28 (2 occurrences)
Last logged: 22:38:28

Error adding entities for domain sensor with platform mobile_alerts
Error while setting up mobile_alerts platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 592, in state
    numerical_value = float(value)  # type:ignore[arg-type]
                      ^^^^^^^^^^^^
ValueError: could not convert string to float: 'wet'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 504, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 788, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1006, in add_to_platform_finish
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 742, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 810, in _async_write_ha_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 748, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 594, in state
    raise ValueError(
ValueError: Sensor sensor.water_xxxxx has device class 'None', state class 'measurement' unit 'None' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'wet' (<class 'str'>)
CestLaGalere commented 12 months ago

@petrleocompel any ideas? the SensorDeviceClass doesn't have a sensor that returns a string unfortunately - do we need to add a sensor that can do this, then revisit this sensor when this is available? I don't have the time as a beginner to get up to speed with the internal workings as to how to get this sorted. Thanks

zmechu commented 12 months ago

Maybe in a place of "string" value (wet/dry) leak sensor could work as binary one (true/false, on/off, 0/1)?

petrleocompel commented 12 months ago

I will check today evening the best way.

petrleocompel commented 11 months ago

Correct integration of "flood sensor / Leak sensor" should be -> BinarySensorDeviceClass.MOISTURE

I will step in and fix it.

CestLaGalere commented 11 months ago

Thanks for the pointer - I have made the change but not committed it yet - I am assuming we need below, though not sure if this is a MEASUREMENT or there is a different state class for this?

class MobileAlertsWaterSensor(MobileAlertsSensor, CoordinatorEntity, SensorEntity):
    """Implementation of a MobileAlerts humidity sensor. """

    def __init__(self, coordinator, device: dict[str, str]) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator, device=device)
        self._device_class = None
        self._attr_native_unit_of_measurement = None
        self._type = "t2"
        self.entity_description = BinarySensorEntityDescription(
            BinarySensorDeviceClass.MOISTURE,
            device_class=BinarySensorDeviceClass.MOISTURE,
            state_class=SensorStateClass.MEASUREMENT,
            native_unit_of_measurement=None,
        )

    @property
    def native_value(self) -> StateType:
        if self._attr_native_value == 0:
            return STATE_OFF
        else:
            return STATE_ON
CestLaGalere commented 11 months ago

@zmechu try that. Chris

zmechu commented 11 months ago

Still errors....

Logger: homeassistant.components.sensor
Source: custom_components/mobile_alerts/sensor.py:303
Integration: Sensor (documentation, issues)
First occurred: 10:52:34 (1 occurrences)
Last logged: 10:52:34

Error while setting up mobile_alerts platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 353, in _async_setup_platform
    await asyncio.shield(task)
  File "/config/custom_components/mobile_alerts/sensor.py", line 130, in async_setup_platform
    sensors.append(MobileAlertsWaterSensor(coordinator, device))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/mobile_alerts/sensor.py", line 303, in __init__
    self.entity_description = BinarySensorEntityDescription(
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BinarySensorEntityDescription.__init__() got an unexpected keyword argument 'state_class'
petrleocompel commented 11 months ago

For these test builds @CestLaGalere we should make "beta" releases. And have stable release for normal.

Example here https://github.com/petrleocompel/hikaxpro_hacs/releases Screenshot 2023-07-31 at 6 57 48

You can release as many versions you want. Just keep the suffix for the beta release in this format. And people who do not need it will stay on stable version.

CestLaGalere commented 11 months ago

@petrleocompel - I'm going round in circles here - I implemented this as below, it generates an error but I cannot see where it needs fixing!

class MobileAlertsWaterSensor(MobileAlertsSensor, CoordinatorEntity, BinarySensorEntity):
    """Implementation of a MobileAlerts humidity sensor. """

    def __init__(self, coordinator, device: dict[str, str]) -> None:
        """Initialize the sensor."""
        super().__init__(coordinator, device=device)
        self._device_class = None
        self._type = "t2"
        self.entity_description = BinarySensorEntityDescription(
            BinarySensorDeviceClass.MOISTURE,
            device_class=SensorDeviceClass.MOISTURE,
        )

    @property
    def native_value(self) -> StateType:
        if self._attr_native_value == 0:
            return STATE_OFF
        else:
            return STATE_ON

It generates the error below, to me it seems hass requires a unit of measurement, however the binary sensor doesn't seem to provide one.

2023-08-03 18:37:26.709 ERROR (MainThread) [homeassistant.components.sensor] Error adding entities for domain sensor with platform mobile_alerts
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 510, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 566, in _async_add_entity
    entity.add_to_platform_start(
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 208, in add_to_platform_start
    self._sensor_option_unit_of_measurement = self._get_initial_suggested_unit()
                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 337, in _get_initial_suggested_unit
    suggested_unit_of_measurement = self.suggested_unit_of_measurement
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 441, in suggested_unit_of_measurement
    return self.entity_description.suggested_unit_of_measurement
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'BinarySensorEntityDescription' object has no attribute 'suggested_unit_of_measurement'
petrleocompel commented 11 months ago

Any details for testing ? credentials..

CestLaGalere commented 11 months ago

no, I added it to an existing temperature sensor ID so that it would get created and I could check the creation (it would then fail to get a value but that't the next step!) I have:

      - device_id: XXXXXXXXXXX
        name: Wash Area Leak
        type: water
      - device_id: XXXXXXXXXXX
        name: Wash Area Temp
        type: t1
petrleocompel commented 11 months ago

I see the problem the MobileAlertsSensor is extending SensorEntity. I will try to provide fix.

petrleocompel commented 11 months ago

@CestLaGalere @zmechu please try now

zmechu commented 11 months ago

Errors... All sensora are down now. Maybe lets test it with kind of "beta" channel?

Logger: homeassistant.components.sensor
Source: custom_components/mobile_alerts/sensor.py:301
Integration: Sensor (documentation, issues)
First occurred: 21:39:04 (1 occurrences)
Last logged: 21:39:04

Error while setting up mobile_alerts platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 362, in _async_setup_platform
    await asyncio.shield(task)
  File "/config/custom_components/mobile_alerts/sensor.py", line 132, in async_setup_platform
    sensors.append(MobileAlertsWaterSensor(coordinator, device))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/mobile_alerts/sensor.py", line 301, in __init__
    super().__init__(coordinator, device=device)
TypeError: CoordinatorEntity.__init__() got an unexpected keyword argument 'device'
petrleocompel commented 11 months ago

Quick fix for you @zmechu landed with last provided feedback. Yes I agree. Next version will be released. And later these tests will land as separate versions.

petrleocompel commented 11 months ago

Quickly managed the versions and tags

https://github.com/CestLaGalere/mobilealerts/releases

CestLaGalere commented 11 months ago

@petrleocompel thanks - seems odd that we cannot extend the MobileAlertsSensor - the BinarySensor should provide stubs for unit_of_measurement etc? Or do we need another base class to provide the extract_reading & _handle_coordinator_update for all MobileAlertsXXXXXSensor classes?

petrleocompel commented 11 months ago

@CestLaGalere Well the BinarySensor is not "normal Sensor" Later i might create MobileAlertsBinarySensor but right now it is single entity.

We could have MobileAlertsSensor extend just Entity. But the handling is different for Sensor and BinarySensor soooo it does not make sense.

The BinarySensor does not have unit_of_measurement and _attr_state it has only device_class and _attr_is_on: bool.

Later having MobileAlertsBinarySensor seems like only option but currently not needed. Should be fixed. After @zmechu will test we can release it as normal version.

petrleocompel commented 11 months ago

@zmechu any update ? can you check the latest "released version" 1.2.0-beta1 ?

zmechu commented 11 months ago

@zmechu any update ? can you check the latest "released version" 1.2.0-beta1 ?

Still the same. There is no errors in HA log, but leak sensors has "unknown" state. obraz

petrleocompel commented 7 months ago

@zmechu If you could share The Acc ID + Device ID via email (privately) would be amazing. I would debug it why is it happening. I do not have any of these. I will ask my friend if he has but i think he does not have leak sensor.

or even just maybe share the API response i will mock it in request.

petrleocompel commented 7 months ago

"devices": [ { "deviceid": "XXXXXXXXX", "lastseen": 1690390222, "lowbattery": false, "measurement": { "idx": 143389, "ts": 1690390217, "c": 1690390222, "lb": false, "t1": 23.0, "t2": 0.0, "h": 48.0 } }

Found the API response. I will take a look on this today