yamlsensorshome-assistant

Home Assistant RESTful sensor YAML. How to filter REST API results?


in the configuration.yaml file of Home Assistant I created this RESTful sensor:

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] }}"

This queries an API from my speaker that returns all available sources (in the above snippet, the first entry):

{
    "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"
    }]
}

On every reboot of the speaker, the order of this list changes and the value of the sourceId field changes for each device. My goal is to get the sourceId for the devices with “type”: “opticaljack” AND “streamLockAvailable”: false.

How can I extract the correct item, and consequently the value of sourceId and set that as a state for the sensor? I want to use this as an input for an automation afterwards.

I’ve tried to cobble together some code that does not function and is not compliant:

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

Solution

  • I think you're close. The main problem is that you're missing the second selectattr. You also don't need the 'if' test, because these are already filtered with the 'selectattr'. So you would have:

    {% set c = value_json.sources 
      | selectattr('type', 'eq', 'opticaljack') 
      | selectattr('streamLockAvailable', 'eq',  false) 
      | first
      | default %}
    {{ c }}
    

    Assuming you're not doing other processing, you could simplify this to:

    {{ value_json.sources 
      | selectattr('type', 'eq', 'opticaljack') 
      | selectattr('streamLockAvailable', 'eq',  false) 
      | first
      | default }}