Home Assistant无法提取Python发送的MQTT JSON报文中的温湿度数据
问题说明
通过Python脚本向Home Assistant发送JSON格式数据,HA可正常接收数据,但模板无法正确读取数据内容,无法定位遗漏配置点,需要实现访问JSON中temperature和humidity属性的需求。
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) # 输出示例: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开发模板测试结果
Data: {{ states('sensor.rpi3_climate') }} # 输出:Data: {'temperature': '9', 'humidity': '7'} Temperature: {{ state_attr('sensor.rpi3_climate', "temperature") }} # 输出:Temperature: None
替代测试方案结果
{% set temp = states("sensor.rpi3_climate") %} {% set climate_json = temp|to_json %} The temperature is: {{ climate_json }} # 输出:The temperature is: "{'temperature': '9', 'humidity': '7'}" The temperature is: {{ climate_json.temperature }} # 输出为空
原因说明
当前配置中把value_template设置为返回整个climate对象,但是HA传感器的state属性默认会把所有返回值转为字符串存储,不会自动解析为字典结构,所以无法直接通过state_attr读取属性;同时测试时错误使用了to_json过滤器(它的作用是把对象转为JSON字符串,而你需要的是把字符串转为JSON对象的from_json过滤器)。
解决方案
这里提供三种适配方案,可按需选择:
方案1:拆分为独立的温湿度传感器(最常用,后续使用最简单)
修改configuration.yaml配置,分别定义温度和湿度两个传感器:
# 温度传感器 - platform: mqtt state_topic: 'rpi3/sensors/climate' name: 'RPi3 Temperature' value_template: '{{ value_json.climate.temperature }}' unit_of_measurement: "°C" # 可根据实际单位修改 # 湿度传感器 - platform: mqtt state_topic: 'rpi3/sensors/climate' name: 'RPi3 Humidity' value_template: '{{ value_json.climate.humidity }}' unit_of_measurement: "%"
后续可直接通过states('sensor.rpi3_temperature')和states('sensor.rpi3_humidity')读取对应数值。
方案2:保留单个传感器,将温湿度设为其属性
如果需要保留单个RPi3 Climate传感器,在配置中增加属性解析模板:
- platform: mqtt state_topic: 'rpi3/sensors/climate' name: 'RPi3 Climate' value_template: '正常' # 传感器主状态可自定义 json_attributes_template: '{{ value_json.climate | tojson }}'
后续即可通过state_attr('sensor.rpi3_climate', 'temperature')和state_attr('sensor.rpi3_climate', 'humidity')读取对应属性。
临时模板读取方案(不修改现有配置的场景)
如果暂时不想调整现有配置,可在模板中通过from_json过滤器手动把状态字符串转为字典后读取:
{% set climate_data = states('sensor.rpi3_climate') | from_json %} 温度:{{ climate_data.temperature }} 湿度:{{ climate_data.humidity }}
内容的提问来源于stack exchange,提问作者Trist
相关产品推荐
相关产品推荐

