如何在Home Assistant中过滤REST API结果获取指定sourceId
问题:Home Assistant REST Sensor 筛选特定SourceId的正确配置
我在Home Assistant的configuration.yaml中创建了RESTful传感器,调用音箱API获取sources列表,但音箱重启后列表顺序及设备的sourceId会变化。需要筛选出type为opticaljack且streamLockAvailable为false的设备的sourceId作为传感器状态,用于后续自动化。此前的代码无法正常运行,求正确配置方法。
原配置
sensor: - platform: rest resource: "http://192.168.1.84/ipcontrol/v1/groups/current/sources/" method: GET name: "devialet AUX" value_template: "{{ value_json.sources[0] }}"
API返回示例
{ "sources": [{ "deviceId": "c803cc3b-647f-5d95-b712-b867abe80181", "sourceId": "f4a7f06a-da1d-4fc7-b341-39a702969ca4", "type": "upnp" }, { "deviceId": "19ee4eeb-1ed0-5b20-b834-6d66a2bf4acc", "sourceId": "549ad3aa-3e5f-4905-80c7-dc182ba040d0", "streamLockAvailable": false, "type": "opticaljack" }, { "deviceId": "c803cc3b-647f-5d95-b712-b867abe80181", "sourceId": "5789cce5-8ab6-4832-9b10-514be4b86fe5", "streamLockAvailable": true, "type": "opticaljack" }, { "deviceId": "c803cc3b-647f-5d95-b712-b867abe80181", "sourceId": "dfa269e5-ce7f-4b79-85d3-90826a4a040b", "type": "spotifyconnect" }] }
此前无效代码
value_template: > {% set c = value_json.sources | selectattr('type', 'eq', 'opticaljack' | 'streamLockAvailable', 'eq', false) | first | default %} {% if c.type == 'opticaljack' and c.streamLockAvailable == false %} {{ c.selectattr('sourceId') }} {% endif %}
正确配置方法
完整传感器配置
sensor: - platform: rest resource: "http://192.168.1.84/ipcontrol/v1/groups/current/sources/" method: GET name: "devialet AUX" value_template: > {% set target_source = value_json.sources | selectattr('type', 'eq', 'opticaljack') | selectattr('streamLockAvailable', 'eq', false) | first | default(none) %} {{ target_source.sourceId if target_source is not none else '' }}
错误原因说明
selectattr多条件写法错误:原代码把多个筛选条件用|拼接在同一个selectattr里,属于语法错误。多个条件需要用链式的selectattr依次筛选。- 属性获取方式错误:获取
sourceId不需要用selectattr,直接通过.访问对象属性即可。 - 默认值处理不严谨:原代码的
default未指定默认值,当没有匹配到目标设备时会导致模板报错,这里指定default(none)并通过判断输出空字符串避免报错。
内容的提问来源于stack exchange,提问作者cmplieger
相关产品推荐
相关产品推荐

