ChristianKuehnel / plantgateway

Bluetooth to mqtt gateway for Xiaomi Mi plant sensors
Apache License 2.0
271 stars 43 forks source link

Persistance with home assistant auto discovery #45

Open cfuerst opened 3 years ago

cfuerst commented 3 years ago

Hello 👋 first, many thanks for the plant gateway 🙇

EDIT: only works if config message has retain flag

I am not entirely sure about all my assumption. But if I get this right, it would be very much useful to add force_update: true and or unique_id: sensor.ALIAS to the DISCOVERY_PREFIX/sensor/plant_MAC_TYPE/config payload.

If I just use autodiscovery feature in home assistant, after a restart the entities are in undefined state. After reading up on the docs if force_update: true this should do the trick.

If I configure the whole sensor with the payload of the autodiscovery pushed by plant gateway to mqtt:

- platform: mqtt
  state_topic: "plantgw/ALIAS/"
  unit_of_measurement: "%"
  value_template: "{{value_json.battery}}"
  name: ALIAD_battery
  device_class: battery
  force_update: true

This will make the entity state available right away. What also works is defining the unique_id: sensor.ALIAS so it can leverage on the entity registry.

- platform: mqtt
  state_topic: "plantgw/ALIAS/"
  unit_of_measurement: "%"
  value_template: "{{value_json.battery}}"
  name: ALIAD_battery
  device_class: battery
  unique_id: sensor.ALIAS

Of course, I can define all of that as mqtt sensors themselves but that renders the autodiscovery feature a bit pointless, while it would be super useful.

What do you think about adding both while keeping the backwards compatibility by sending the unique_id how its auto-generated currently?

Cheers 🍻

cfuerst commented 3 years ago

I can produce the desired results as seen in my mqtt topic:

prefix/sensor/plant_MAC_battery/config

{
    "state_topic": "plantgw/ALIAS/",
    "unit_of_measurement": "%",
    "value_template": "{{value_json.battery}}",
    "force_update": true,
    "name": "ALIAS_battery",
    "unique_id": "sensor.ALIAS_battery",
    "device_class": "battery"
}

Tested by directly modified /usr/local/lib/python3.7/dist-packages/plantgw/plantgw.py on all my polling machines and made a run each. Restarted home assistant (without having any manual mqtt sensor configuration) - waited a bit (while no data to mqtt was published by plant gateway).

By additionally retain the config message it works.