HAMqttDevice icon indicating copy to clipboard operation
HAMqttDevice copied to clipboard

Sensors with Multiple Values

Open lanrat opened this issue 2 years ago • 3 comments

As per the Home Assistant MQTT Discovery Documentation, it is possible to define a single sensor that can define multiple values in a single payload (with multiple configs needed) by defineing a value_template for each that use the same state_topic.

As far as I can tell, this is not possible with this library. Is that correct? Would it be much work to add support for this?

https://www.home-assistant.io/docs/mqtt/discovery/#sensors-with-multiple-values

lanrat avatar Dec 05 '21 21:12 lanrat

You may be able to do this with plapointe6/HaMqttConfigBuilder

Here how:

// Publish this to: homeassistant/sensor/sensorBedroomT/config
String generateConfigPayload1() {
  return HaMqttConfigBuilder()
    .add("device_class", "temperature")
    .add("name", "Temperature")
    .add("state_topic", "homeassistant/sensor/sensorBedroom/state")
    .add("unit_of_measurement", "°C")
    .add("value_template", "{{ value_json.temperature}}")
    .generatePayload();
}

// Publish this to: homeassistant/sensor/sensorBedroomH/config
String generateConfigPayload2() {
  return HaMqttConfigBuilder()
    .add("device_class", "humidity")
    .add("name", "Humidity")
    .add("state_topic", "homeassistant/sensor/sensorBedroom/state")
    .add("unit_of_measurement", "%")
    .add("value_template", "{{ value_json.humidity}}")
    .generatePayload();
}

// To generate { "temperature": 23.20, "humidity": 43.70 }
String generateValuesPayload(const double temperature, const double humidity) {
  return HaMqttConfigBuilder()
    .add("temperature", temperature)
    .add("humidity", humidity)
    .generatePayload();
}

I will replace HAMqttDevice by the new lib HaMqttConfigBuilder soon in my other projects.

plapointe6 avatar Dec 07 '21 23:12 plapointe6

Oh, cool!

What the main difference between HAMqttDevice and the new HaMqttConfigBuilder?

lanrat avatar Dec 08 '21 00:12 lanrat

HaMqttConfigBuilder is simple and tiny. It is a tool to generate key/value pairs into a JSON string. HAMqttDevice does more things on its own under the hood like setting the state topic and generating some key/value entries into the config automatically.

So, why replace HAMqttDevice with HaMqttConfigBuilder if HAMqttDevice does, in fact, more things?

  1. HaMqttConfigBuilder is lighter and more flexible.
  2. While HAMqttDevice does things in the background, it was not always clear which thing it does and when. Doing this the new way will put all config key/value pairs for your device into the main sketch at the same place. Noting is done in the background.

I will update my IoT devices soon and I will put more examples into HaMqttConfigBuilder.

plapointe6 avatar Dec 08 '21 01:12 plapointe6