MQTT Sensor from JSON Array

I’m at a loss - the payload looks like JSON.
Templating - Home Assistant clearly says value_json is available for MQTT payloads.

@123 can you take a look please?

It’s a Trigger-based Template Sensor so it will produce a trigger variable.

The trigger variable for an MQTT Trigger is documented here.

template:
  - trigger:
      - platform: mqtt
        topic: v1/devices/me/telemetry
    sensor:
      - name: ecs_cell_1
        state: "{{ trigger.payload_json['cell1.Voltage'] if trigger.payload_json['cell1.Voltage'] is defined else this.state }}"
        device_class: voltage
        state_class: measurement
        unique_id: ecs-bat-a4af5a96-02f6-418b-8e33-a80e7c7242b0
      - name: ecs_cell_2
        state: "{{ trigger.payload_json['cell2.Voltage'] if trigger.payload_json['cell2.Voltage'] is defined else this.state }}"
        device_class: voltage
        state_class: measurement
        unique_id: ecs-bat-54fa7a4f-c7d6-47fc-80bb-0922fdbf8e97

NOTE

It’s been my experience that if the received payload is normally in JSON format but on occasion it arrives not in JSON format, the template’s use of trigger.payload_json will produce an error. Hopefully this application doesn’t experience that problem with its payload format.

1 Like

Urgh, I must have passed that section of the template sensor page loads of times.

Whenever the trigger fires, all related entities will re-render and it will have access to the trigger data in the templates.

Ah well.

now i get

Invalid config for ‘template’ at conf/ecs/escmqttneu.yaml, line 5: ‘sensor’ is an invalid option for ‘template’, check: sensor->0->sensor Invalid config for ‘template’ at conf/ecs/escmqttneu.yaml, line 5: required key ‘state’ not provided

Please post the full code, it’s probably an indentation issue.

looks ok in studio code

template:
  trigger:
    - platform: mqtt
      topic: v1/devices/me/telemetry
  sensor:
    sensor:
      - name: ecs_cell_1
        state: "{{ trigger.payload_json['cell1.Voltage'] if trigger.payload_json['cell1.Voltage'] is defined else this.state }}"
        device_class: voltage
        state_class: measurement
        unique_id: ecs-bat-a4af5a96-02f6-418b-8e33-a80e7c7242b0
      - name: ecs_cell_2
        state: "{{ trigger.payload_json['cell2.Voltage'] if trigger.payload_json['cell2.Voltage'] is defined else this.state }}"
        device_class: voltage
        state_class: measurement
        unique_id: ecs-bat-54fa7a4f-c7d6-47fc-80bb-0922fdbf8e97

sorry i´ve made mistake by copy paste
wow - it works :grinning:

thank you lot for your help

Now you can repeat for the rest of the Cells :+1:

yes - an temperature etc
once again thank you :pray: