0

I'm sending JSON data from a python script to Home Assistant. HA receives the data but I cannot get my template to read it correctly. I can't see what I'm missing – I want to access the temperature and humidity properties in the JSON.

Python Client Publish Script (Python 2.7.16)

msg_json = {
  "climate": {
    "temperature": str(temperature_f),
    "humidity": str(humidity_f)
  }
}
result = client.publish(topic, payload=json.dumps(msg_json))
status = result[0]
print("Send {0} to topic {1}").format(msg_json, topic)

// OUTPUT -> Send {'climate': {'temperature': '9', 'humidity': '7'}} to topic rpi3/sensors/climate

HA configuration.yaml

    - platform: mqtt
      state_topic: 'rpi3/sensors/climate'
      name: 'RPi3 Climate'
      value_template: '{{ value_json.climate }}'

HA Dev Template

Data: {{ states('sensor.rpi3_climate') }} 
    -> OUTPUTS: Data: {'temperature': '9', 'humidity': '7'}

Temperature: {{ state_attr('sensor.rpi3_climate', "temperature") }}
    -> OUTPUTS: Temperature: None

HA Dev Template Alternative

{% set temp = states("sensor.rpi3_climate") %}
{% set climate_json = temp|to_json %}
The temperature is: {{ climate_json }}
    -> OUTPUTS: The temperature is: "{'temperature': '9', 'humidity': '7'}"

The temperature is: {{ climate_json.temperature }} 
    -> OUTPUTS: The temperature is: 
Trist
  • 1,306
  • 1
  • 11
  • 17

1 Answers1

0

OK, so to answer my own question... I came up with what I think is a work around but I'm sure I've missed something and should be able to access the data being sent in it's original format.

I changed the format of the JSON message being sent:

msg_json = {
   "temperature": str(temperature_f),
   "humidity": str(humidity_f)
}

and edited my configuration.yaml so that humidity and temperature had they're own entity:

    - platform: mqtt
      state_topic: 'rpi3/sensors/climate'
      name: 'RPi3 Climate'

    - platform: mqtt
      state_topic: 'rpi3/sensors/climate'
      name: 'RPi3 Temperature'
      value_template: '{{ value_json.temperature }}'

    - platform: mqtt
      state_topic: 'rpi3/sensors/climate'
      name: 'RPi3 Humidity'
      value_template: '{{ value_json.humidity }}'

I was then able to create a card using that sensor's data.

Trist
  • 1,306
  • 1
  • 11
  • 17