[英]Home Assistant RESTful sensor YAML. How to filter REST API results?
在 Home Assistant 的 configuration.yaml 文件中,我创建了这个 RESTful 传感器:
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"
}]
}
每次重新启动扬声器时,此列表的顺序都会发生变化,每个设备的 sourceId 字段的值也会发生变化。 我的目标是获取具有“type”的设备的 sourceId:“opticaljack”和“streamLockAvailable”:false。
如何提取正确的项目,从而提取 sourceId 的值并将其设置为传感器的 state? 之后我想将其用作自动化的输入。
我试图拼凑一些不符合 function 且不兼容的代码:
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 %}
我认为你很接近。 主要问题是您缺少第二个selectattr
。 您也不需要“if”测试,因为这些已经用“selectattr”过滤了。 所以你会有:
{% set c = value_json.sources
| selectattr('type', 'eq', 'opticaljack')
| selectattr('streamLockAvailable', 'eq', false)
| first
| default %}
{{ c }}
假设您没有进行其他处理,您可以将其简化为:
{{ value_json.sources
| selectattr('type', 'eq', 'opticaljack')
| selectattr('streamLockAvailable', 'eq', false)
| first
| default }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.