【问题标题】:Home Assistant Can't Extract Data from Python/JSON MQTT Message家庭助理无法从 Python/JSON MQTT 消息中提取数据
【发布时间】:2021-10-25 14:29:25
【问题描述】:

我正在将 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: 

【问题讨论】:

    标签: python jinja2 mqtt home-assistant


    【解决方案1】:

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

    我更改了正在发送的 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 }}'
    

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

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2022-06-23
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多