0

我将 JSON 数据从 python 脚本发送到 Home Assistant。HA 收到数据,但我无法让我的模板正确读取它。我看不到我缺少什么——我想访问 JSON 中的温度和湿度属性。

Python 客户端发布脚本 (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 配置.yaml

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

高可用性开发模板

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

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

HA 开发模板替代方案

{% 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: 
4

1 回答 1

0

好的,所以回答我自己的问题......我想出了一个我认为可以解决的问题,但我确定我错过了一些东西,应该能够访问以原始格式发送的数据。

我更改了正在发送的 JSON 消息的格式:

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

并编辑我的configuration.yaml,以便湿度和温度拥有它们自己的实体:

    - 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 }}'

然后我能够使用该传感器的数据创建一张卡片。

于 2021-10-28T19:41:36.907 回答