Media-player get and set volume doesn't work

I’m trying to implement an automation as follows…

  1. store the current volume of a media_player in an input_number variable ‘volume’
  2. set the media_player’s volume to a new value
  3. play a sound file on the media_player
  4. reset the volume back to what was saved in 1. above
  5. let the media player resume what it was doing before all of this

The “Traces” view shows the following:

Step 1 code

target:
  entity_id:
    - input_number.volume
data:
  value: '{{ state_attr(''media_player.soundtouch_30'', ''volume_level'') | float }}'
action: input_number.set_value

Step 1 trace:

Result:
params:
  domain: input_number
  service: set_value
  service_data:
    value: 0.7
    entity_id:
      - input_number.volume
  target:
    entity_id:
      - input_number.volume
running_script: false

Step 2 code:

action: media_player.volume_set
metadata: {}
data:
  volume_level: 0.4
target:
  entity_id: media_player.soundtouch_30

Step 2 trace:

Error: not well-formed (invalid token): line 1, column 0
Result:
params:
  domain: media_player
  service: volume_set
  service_data:
    volume_level: 0.4
    entity_id:
      - media_player.soundtouch_30
  target:
    entity_id:
      - media_player.soundtouch_30
running_script: false

Sometimes step 2 works, but then it bombs on step 4:

Step 4 code:

action: media_player.volume_set
metadata: {}
data:
  volume_level: '{{ states(''input_number.volume'') | float }}'
target:
  entity_id: media_player.soundtouch_30

Step 4 trace:

Error: Error rendering data template: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('input_number.volume') | float }}' but no default was specified

Any ideas what is going on here?

Thanks
Pete

Hi petehug.

My first thought is there anything there? Put that in the developer - template and see. I probably needs a default or something to trap an error as well to prevent error.

Open your Home Assistant instance and show your template developer tools.

Hi SG,
Thanks for your feedback.

This is what I saw in the developer:


I then triggered the automation and saw this for step 1 in the trace:

The volume level in the developer matches the volume spotted by trace.

I wonder if the problem is that the device is busy? Maybe I need to wait for it to become idle?