In case anyone stumble on a similar problem…
I thought I might share my solution.
Step 1
It seems that the problem with my original sensor has something to do with the 255-char limitation on a RESTful sensor’s state. Even though my template’s final result is either true
or false
, it seems that passing the entire value_json
for processing inthe state wasn’t working.
As a workaround, I used the sensor’s attributes (similar to the official example) to “dump” the JSON response I needed.
sensor:
- platform: rest
...
# Dummy state; using the attributes which can hold >255 chars
value_template: OK
json_attributes_path: ...
json_attributes:
...
Step 2
Now came a tough part - how to simulate the for
loop I had in my template? That is, how to filter the JSON response, which includes an array of sessions, to find the only relevant one that contains NowPlayingItem
?
This was solved using some JSONPath magic, with the help of online exp tutorial, dummy data and tester. value_json
is filtered to give only that item which has a property key NowPlayingItem
.
json_attributes_path: "$[?(@.NowPlayingItem)]"
json_attributes:
- Id
- PlayState
- NowPlayingItem
Step 3
Now that I had the REST sensor, I used a template binary sensor to create the actual boolean value (and extract other useful info from the session object).
Final result:
sensor:
- platform: rest
name: Jellyfin playing
resource_template: "{{ states('input_text.jellyfin_url') }}/Sessions"
headers:
X-MediaBrowser-Token: !secret jellyfin_apikey
# Dummy state; actually using the attributes which can hold >255 chars
value_template: OK
json_attributes_path: "$[?(@.NowPlayingItem)]"
json_attributes:
- Id
- PlayState
- NowPlayingItem
template:
- binary_sensor:
- name: Jellyfin playing
device_class: running
state: "{{ iif(state_attr('sensor.jellyfin_playing', 'Id') != None, 'on', 'off') }}"
attributes:
session_id: "{{ state_attr('sensor.jellyfin_playing', 'Id') }}"
is_paused: "{{ state_attr('sensor.jellyfin_playing', 'PlayState')['IsPaused'] }}"
name: "{{ state_attr('sensor.jellyfin_playing', 'NowPlayingItem')['Name'] }}"
rating: "{{ state_attr('sensor.jellyfin_playing', 'NowPlayingItem')['OfficialRating'] }}"
Multiple active sessions?
This does NOT address the case where there is more than one active playing session. In that case, the JSONPath $[?(@.NowPlayingItem)]
will return an array of matches, but the json_attributes
will populate only from the last match, I believe. If anyone has any ideas on how to solve THAT problem - lemme know!