MQTT - Dict Object has no attribute

I hope that it will help some of you but this is how I had it working in my case (Zigbee Bridge from Sonoff flashed with Tasmota):

mqtt:
  sensor:
    - state_topic: "tele/tasmota_F1234F/SENSOR"
      name: "Bedroom_Temperature"
      device_class: temperature
      value_template: "{% if value_json['ZbReceived']['0x123A'].Temperature is defined %} {{ value_json['ZbReceived']['0x123A'].Temperature }} {% else %} {{ state('sensor.Bedroom_Temperature') }} {% endif %}"
      unit_of_measurement: "°C"
    - state_topic: "tele/tasmota_F1234F/SENSOR"
      name: "Bedroom_Humidity"
      device_class: humidity
      value_template: "{% if value_json['ZbReceived']['0x123A'].Humidity is defined %} {{ value_json['ZbReceived']['0x123A'].Humidity }} {% else %} {{ state('sensor.Bedroom_Humidity') }} {% endif %}"
      unit_of_measurement: "%"

In my case my Zigbee sensors return only one value at a time, either ‘Temperature’ or ‘Humidity’, but inside the exact same JSON topic from my bridge, and when I had one the other was always reset inside HA.
Here I use “is defined” to check the presence of the value and set the current state if it’s not defined, this way when I get ‘Humidity’ it doesn’t reset the ‘Temperature’ value to “unknown” :slight_smile:

Here are two example topics I got from my bridge (to explain the issue):

tele/tasmota_F1234F/SENSOR = {"ZbReceived":{"0x123A":{"Device":"0x123A","Name":"Bedroom_Sensor","Temperature":19.77,"Endpoint":1,"LinkQuality":58}}}
tele/tasmota_F1234F/SENSOR = {"ZbReceived":{"0x123A":{"Device":"0x123A","Name":"Bedroom_Sensor","Humidity":60.48,"Endpoint":1,"LinkQuality":52}}}

My solution is based on the following pages:

1 Like