How to define an MQTT sensor with attributes

Hi All,

Im trying to define an MQTT sensor with attributes, but I cannot get it to work using value templates. I would realy appreciate some help pointing me in the right direction.

So what I would like to do is converting an MQTT response into one entity with multiple attributes.
So for instance when

  • MQTT Topic is X/Y/Z
  • MQTT value is {“A”=“a”, “B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”},
    I would like to create an entity A with attributes B=b, C=c, D=d and E=e

So now I’m puzzling around in the MQTT sensor docs, producing code like below, but without succes.

- name: "sensor"
  platform: mqtt
  state_topic: "X/Y/Z"
  value_template: '{{ value_json["A"] }}'
  json_attributes_topic: "X/Y/Z"
  json_attributes_template: "{{ value_json.B| tojson }}"
  json_attributes_template: "{{ value_json.C | tojson }}"
...

Any help is appreciated.
PPee

If your mqtt topic is X/Y/Z, your state_topic needs to be X/Y/Z

What is more, A = {“B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”} is not valid json, so value_json will not work.

if it was just {“B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”} you would have valid json, but with the A = before it, no.

Oh yeah, sorry misrepresentation. I will edit the question because topic part is not repeated.

try :

- name: "sensor"
  platform: mqtt
  state_topic: "X/Y/Z"
  value_template: '{{ value_json.A }}'
  json_attributes_topic: "X/Y/Z"

mmmm no attributes are created
just sensor.sensor with value unknown

Did your sensor already receive a mqtt message ?

No it has no value. I would like to create the sensor with the mqtt messagge.
So I have published a retained mqtt message like


and would like to create the sensor with attributes based on this message. Attributes should be B, C, D and E.

That won’t work. You can’t create a sensor with just attributes.

Make up your mind

First it was
MQTT value is A = {“B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”} (which is invalid json)
then
{“A”=“a”, “B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”}, (still invalid json)
then
{“B”:“b” ,“C”:“c”, “D”:“d”, “E”:“e”} (valid json, but without main working state_topic you will never get a working sensor)

Hi Francis, I did make up my mind, but may be failed in presenting it well.
I’m trying to understand how I can make attributes for a sensor from an MQTT message containing a json. Both the sensor value and the attributes must come from the json.
So for the previously send screenshot for instance, the sensor value could be B and the attributes C, D and E. I know I can define the sensor values with the value_template instruction, but I would like to know how i can make attributes for the rest of the values.
Sorry for annoying you with an unclear question.
PPee

Your attributes are automatically created if you add a json_attributes_topic with contains valid json