unixorn/ha-mqtt-discoverable

[BUG] Binary sensor has wrong availability message

Closed this issue · 3 comments

Describe the bug
When creating a binary sensor, the availability topic is currently hard-coded to the state topic.

According to the docs however the availability payload expects an online or offline message by default, so using ON and OFF state confuses HA.

To Reproduce
The following example code creates a binary sensor, then toggles its state.

mysensor = BinarySensor(settings={
    "mqtt_server": "localhost",
    "client_name": "client",
    "mqtt_user": "user",
    "mqtt_password": "password",
    "mqtt_prefix": "homeassistant",

    "metric_name": "sensor",
    "device_id": "test_device",
    "unique_id": "my_sensor",
    "device_name": "MySensor",
    "device_class": "motion",
})
mysensor.on()
await asyncio.sleep(5)
mysensor.off()
await asyncio.sleep(5)
mysensor.on()

Expected behavior
At the end of the script the sensor should appear on, instead it appears unavailable.

Screenshots
Screenshot from 2023-02-12 08-56-26

After manually publishing a MQTT message to the availability topic homeassistant/binary_sensor/MySensor/state with content online:
Screenshot from 2023-02-12 09-03-58

Desktop (please complete the following information):

  • OS: Linux Mint 20.3 Cinammon
  • Browser Google Chrome
  • Version 109.0.5414.74

Deferring until after #15 is merged

Since the changes are about sensor availability, may I suggest the option to expose it to the end-user (as methods in the sensor object?). This should have an effect only if availability_topic has been set in the sensor instance, otherwise the sensor is always treated as available by HA.
Something like sensor.is_available(True) sensor.is_available(False)?
This way we avoid having to manage this layer of abstraction inside the library, leaving the options to the user.

Sounds good to me.