Script to resume Google Cast devices after they have been interrupted by any action

Description

A script to send actions to Google Cast devices, resume what was playing afterwards and restore the previous volume in case the volume was changed.
Note: Only service calls are supported, but you can call a script in a service call, so other actions can be performed by calling a script.

This script supports

  • Resuming of TuneIn, Spotify, YouTube (only for players with screen) YouTube music (only if custom integration is used) and generic streams after any actions which interrupted the audio
  • Resuming an entire speaker group after a single group member has been interrupted
  • Resuming of individual group members after the speaker group has performed an action

Requirements

General

  • Home Assistant version 2022.5 is required
  • The script creates groups while running, so if you don’t have any groups set up already, add group: to your configuration.yaml.

Spotify resume

YouTube Music resume

  • Resume can be performed in case the custom YouTube Music player integration is used. And only when YouTube music was started using that custom integration (which is quite easy now with the changes to the media panel)

Most recent change

Version 2.5.0 - 28 May 2022

:star2: Improvements

  • Combined all helper scripts in one script (script.google_home_resume_helper)

:bug: Bug fixes

  • Fix for uppercase characters in context.id causing errors in creating groups
  • Fixed resume for the Ytube Music custom integration

Setup

The script itself

Link to the script on my Github config, so I don have to maintain it in two places

Add this script to scripts.yaml by copying the contents of the link below, and pasting it in scripts.yaml. Don’t use the GUI, use a file editor (add-on).
Change the variables described below to match your setup.

Spotify specific settings

  • In case you only have one Spotify account set up in Home Assistant, there are no additional settings needed besides intalling the Spotify integration and Spotcast (available on HACS)

In case you use multiple accounts, you need to add the Spotify integration for all accounts, besides that you take care of the following:

  1. The entity_id’s for media_player entities from the Spotify integration should be formatted like media_player.spotify_{{ spotcast user }}. For the primary Spotcast user you can use whatever you want as {{ spotcast user }}.
  2. The primary Spotcast user needs to be specified under primary_spotcast (see comment above).
  3. To determine the Spotify account, the source in the Spotify media_players is used. This is compared to the friendly name of the Goolge Home media_player. Therefor the Google Home media players in HA need to have the exact same name as they have in the Google Home app (this is also already a requirement for Spotcast to work with entity_id’s).

This is how it is set up in my system:
4 Spotify integrations (account Pepijn not shown here, as it didn’t fit):
image

Spotcast (the Spotify account for Pepijn is the primary account, and has no named account in the spotcast setup):

spotcast:
  sp_dc: !secret sp_dc
  sp_key: !secret sp_key
  country: NL
  accounts:
    martijn:
      sp_dc: !secret sp_dc_martijn
      sp_key: !secret sp_key_martijn
    marleen:
      sp_dc: !secret sp_dc_marleen
      sp_key: !secret sp_key_marleen
    floris:
      sp_dc: !secret sp_dc_floris
      sp_key: !secret sp_key_floris

The media_players connected to the Spotify integration are named (matching the spotcast configuration and the primary_spotcast variable in the script, which is pepijn):

media_player.spotify_pepijn
media_player.spotify_martijn
media_player.spotify_marleen
media_player.spotify_floris

Cast devices with screen (like Google Nest Hub or Android TV)

  • Google Nest Hub speakers and other cast devices with a screen can be entered under the variable players_screen. This will make sure the photo display is turned on again after the TTS in case nothing was already playing, and supports resume of YouTube.
  • In case you want to send a TTS with a picture and some text, you need to set up a dummy media_player which accepts TTS messages. More info below.

Dummy player for TTS with picture and text

The feature to send a TTS together with picture and text works as as follows. The TTS is sent to a dummy player, and the script will wait for this event, and will take the url the the mp3 used as TTS message. It will then send this mp3 together with the picture and text to the actual target.
As of Home Assistant 2022.4 there is a check if a target of a service call actually supports the service call. So the dummy player has to support TTS. As the media_player created by the VLC Telnet integration supports TTS, I use this.

In case you use HA OS, or run a supervised install, you can add the VLS Telnet add-on from the add-on store. After starting the add-on it will automatically be detected by Home Assistant, and you can add the VLC Telnet integration. This will create media_player.vlc_telnet which you can use as dummy player.

In case you don’t have the supervisor or already use this add-on for other purposes, you can possibly use the media_player created by the browser_mod custom component. Or you can buy an additionaly Nest Mini, set the volume to 0 and hide it somewhere :wink:

Google Home Speaker groups

  • If you use speaker groups in the Google Home app, you can enter them under the variable speaker_groups. If you use them, you’ll need to complete this variable, and add the group members in there as well (see the script for an example).

Explanation of variables in the script

There are no required variables, but if you use Google Home speaker groups and players with a screen you should define those as described above. Resuming Spotify with multiple accounts won’t work properly without primary_spotcast. dummy_tts is required to send a TTS with picture and text.

Variable Default Example Description
players_screen See script on Github Enter a list of cast devices with a screen. Do not use a comma seperated string here.
primary_spotcast pepijn The Spotify account which is used as primary account for spotcast, should match the last part of the Spotify media player.
radio_data See script on Github A dictionary with the pictures and titles. The picture urls should be full urls, not HA internal urls). As key value the artist should be used (check media_artist in developer tools > states)
speaker_groups See script on Github A combination of a dictionary and a list, with speaker groups of which all entities are included in another speaker group.
default_volume_level 0.25 0.5 The default volume level to use to set the entity to if the old volume can not be retreived (this should actually never be used, but it there as a failsafe)
dummy_player media_player.vlc_telnet The dummy media_player used for the TTS with picture and text feature

How to use the script

This script only contains the code to resume after the interruption, it doesn’t contain any standard actions (like sending a TTS or playing an MP3 file)

To perform such an action, you need to provide them in the action field. In case you use the GUI, it will allow al kind of actions (like delay or choose) but the script can only handle service calls (so starting with service).

You can also start a script in a service call, so this allows you to do more advanced actions, like using choose or a wait_template. But in that case there will be no information regarding the target of the service call in the action data. In that case you can enter that information in the target field.

The boolean resume_this_action can be set to false if you don’t want to resume the actions from the action field. To explain why you would want to do this, I have the following real life example:
I’ve set up a tag scanner on which my kids can scan a card, and then some song will play. If there was already something playing (a TuneIn stream for example) I want that stream to resume after the song finished. However, the kids tend to scan the card a second time when they don’t like the song. If that happens the first kids song which was already playing, would be resumed afterwards. With resume_this_action: false this will not be the case.

When calling the script, there are 3 fields you can provide. action is required, target is only required in case it is not clear from the action part. More details in the examples

Field Required Description
target No The targets which should be resumed, only needed if these targets are not clear from the actions. All usual targets (area_id, device_id and entity_id) are supported.
action Yes The ations to be performed, only service calls are supported. If other actions are needed, you can create a script and call the script.
resume_this_action No Actions from the action field will not be resumed if set to false. Default is true.

As of version 2.0.0 you can also add extra variables together with each of your actions. These additional variables have to be entered in the service call information, on the same level as service, target and data. It is also possible to add them under data, in that case you can use script_extra. Don’t put wait: true at the end of the last service_call, this will block the Perform Resume script
The following variables are supported:

Variable Example Description
volume 0.25 or 25 Applies the volume set for the service call
wait true If set to true the script will wait until the target(s) are idle or off again until resuming with the next service call
screen_tts Use this to provide the details to send a TTS together with picture and text (see the next variables below)
> large_text BIG Will be displayed large on the screen together with the TTS message (normally used for the title)
> small_text small Will be displayed small on the screen together with the TTS message (normally used for the artist)
> picture_url small Will be displayed small on the screen together with the TTS message (normally used for the media_picture)
entity_id media_player.kitchen Target of the service_call in case this is not clear from the call itself, eg when calling a script. Use this when you want to set the volume for the service call
area_id kitchen Target of the service_call in case this is not clear from the call itself, eg when calling a script. Use this when you want to set the volume for the service call
device_id whatever Target of the service_call in case this is not clear from the call itself, eg when calling a script. Use this when you want to set the volume for the service call

Examples for different use cases can be found here

The script can also be started from the GUI, both in YAML mode and full GUI mode.

Known limitations

  • It is possible to create speaker groups on the fly from the Google Home app, e.g. if you are playing something from Spotify on your Kitchen speaker, you can add your Living Room speaker in the Google Home app, without them belonging to a speaker group. The script won’t recognize these groups created on the fly. The cast integration won’t recognize these devices as playing anymore, so they won’t be resumed.
  • When Spotify switches to a new song or starts playing, the Spotify Media Player will shortly not show as playing. When at that moment the script is started, the stream will not be resumed afterwards. To minimize this, Spotify entities are updated just before the information is stored.
  • YouTube and YouTube music will only resume the video/song which was playing at the time of the interruption, and only on players with a screen if not started using the ytube_music_player custom integration.

Questions/issues/bugs/feature requests?

In case you have a question, you found a bug, or have a feature request, you can either ask here, or open an issue on my GitHub repository. In case you create a GitHub issue, please label it with google home scripts

In case something isn’t working or you found a bug, a trace of the script will be needed in most cases to determine the cause. The trace can be downloaded as a json file. To do this follow the steps below:

  1. Go to Configuration > Automations & Scenes > Scripts or use Open your Home Assistant instance and show your scripts.
  2. Find the Google Home Resume script in the list.
  3. Click on the clock icon (with the arrow around it) next to the script.
  4. Press the download icon in the top right corner.
  5. Repeat for the Google Home Resume - Helper Script if the error is in that step.

In case you create the issue on GitHub you can upload the json files, in case you create the issue as a post here, you can copy the json files to a code sharing website like dpaste.org. Please create a different link for each json file.

Why not a blueprint?

I’ve been asked a couple of times if I ever considered to make a blueprint out of this script. I do understand this would make updates more easy, however there are also some things which make it quite complicated:

  • You need to provide information on your speaker groups, players with a screen and spotcast account. That would mean that you will have to do that each time you use the blueprint to create a script, or that you’ll have to add this information each time the blueprint is updated, which would reduce the easiness of updating the script.
  • I tried to bypass the point above by using includes, but the blueprint would do that once, and add the informaton in the yaml, instead of keeping the include code.
  • I use really large and complicated templates, and these would be converted to really messy one line templates, making it impossible to read and debug if needed.

So, basically, I gave it a try, and decided it would not work :slight_smile:

Other scripts

For other related Google Home scripst, see my Github page

Buy me a coffee

If you like this script, please feel free to buy me a coffee (I might spend it on another beverage though).
In case you decide to do so, thanks a lot!

Buy Me A Coffee

24 Likes

That looks great @TheFes . However it is not clear no me how to call the script. I have automation that use google say to broadcast a message to google nest hub everytime the garage door is opened. How could I use the script to resume spotify music or youtube video after the message is played?

@jpleite What is the current YAML code to perform that action? If it is service call (so service: some.service) you can use it directly with this script. If not, you need to create a script and call that.

If you want you can paste the YAML code here, and I can show how it should work in cooperation with the script.

BTW, if you are sending a TTS message, you can also use the TTS specific script linked in the Background section.

So is this script also usable without spotify?
I don’t use speakergroups, can is just delete those lines?

Hi @TheFes. Thanks for your prompt reply. As an example, when the garage door is opened I have an automation to notify several devices including google nest via tts.cloud_say. Bellow the automation

alias: Garage Door Open (Tileboard; TTS; iOS; WebOS)
description: ''
trigger:
  - type: opened
    platform: device
    device_id: 127dea8fbf242d4f9a0f2b849474aec9
    entity_id: binary_sensor.garage_door_sensor
    domain: binary_sensor
condition: []
action:
  - event: tileboard
    event_data:
      command: open_garagedoorentry
  - service: notify.mobile_app_milkphone_13_pro_max
    data:
      title: Attention!
      message: Garage is door is open!
      data:
        entity_id: camera.garage
  - service: notify.milkhome
    data:
      message: O portão da garagem foi aberto!
  - service: notify.living_room_tv
    data:
      message: O portão da garagem foi aberto!
  - service: notify.basement_room_tv
    data:
      message: O portão da garagem foi aberto!
  - service: tts.cloud_say
    data:
      entity_id: media_player.kitchen_google_hub
      message: O portão da garagem foi aberto!
mode: single
initial_state: true

Yes, just remove the variables speaker_groups and primary_spotccast

@jpleite
As far as I can see, the only action which will stop Google Cast devices, and will need resuming, is the last one (the TTS).
You could also use the TTS specific script in that case, but this script will also work.
After you included the script in your HA setup, and amended the variables for your needs, you can amend the automation to this:

alias: Garage Door Open (Tileboard; TTS; iOS; WebOS)
description: ''
trigger:
  - type: opened
    platform: device
    device_id: 127dea8fbf242d4f9a0f2b849474aec9
    entity_id: binary_sensor.garage_door_sensor
    domain: binary_sensor
condition: []
action:
  - event: tileboard
    event_data:
      command: open_garagedoorentry
  - service: notify.mobile_app_milkphone_13_pro_max
    data:
      title: Attention!
      message: Garage is door is open!
      data:
        entity_id: camera.garage
  - service: notify.milkhome
    data:
      message: O portão da garagem foi aberto!
  - service: notify.living_room_tv
    data:
      message: O portão da garagem foi aberto!
  - service: notify.basement_room_tv
    data:
      message: O portão da garagem foi aberto!
  - service: script.google_home_resume
    data:
      action:
        - service: tts.cloud_say
          data:
            entity_id: media_player.kitchen_google_hub
            message: O portão da garagem foi aberto!
mode: single
initial_state: true

Hi @TheFes . It worked like a charm! Thanks for your help and great work!

Added To Do section to first post

To Do

  • Dynamic creation of the group.resume_active, so it is possible to track for which entities the script is active
  • Make it possible to queue actions if the script is called multiple times for the same entity (this will requre the script to be cut into different scripts)
  • Add some information on how do the TTS actions like I did in the Google Home Say script which is no longer maintained. (basically it is calling this script as an action in the Google Home Resume script and provide the target (example)).

Update

1 February 2022

  • The script will now create a group (group.resume_active) and add the entties which are going to be resumed there. It will remove the entity from the group after it has been resumed. Entities which are listed in this group will be ignored, so only the original stream will be resumed.
  • Replaced persistant notifications with log messages. In case no valid service calls are provided, the script will abort and an error will be logged. In case thre are valid service calls, but also other invalid actions, a warning will be logged.
  • Adjusted some templates to avoid warnings in the log.

I’m trying to give this one a try. I’ve added the script in the scripts section of my Home Assistant and can call the script by a call. When I use the google_translate_say there, it works like a charm and tts my message. If I was playing a Youtube cast on my Nest Hub, will this resume afterwards or? That’s the thing I still can’t get to work.

1 Like

Well, not at this moment, I originally focused on audio (Spotify/TuneIn)
I can have a look, I think the most tricky part will be to get the the right moment the video was stopped.

That should be really awesome. I gave the broadcast function a try as well, so the TTS messages are just an ‘overlay’ of the content behind it. That is in my opinion the best approach, but I believe that’s even more difficult :wink: I tried it with: Assistant Relay

I’ve tried Assistant Relay, not it is not maintained anymore. And as Dutch is not supported, it was no solution for me.

Also it always sends the broadcast to all devices in your home, and it announced the broadcast, which can be annoying.

Hi, I’m having some issues implementing this script and getting the error ‘Failed to call service script/google_home_resume_wip. Error rendering data template: UndefinedError: ‘iif’ is undefined’.

No doubt it is something I have or haven’t done but any ideas where I’m going wrong, please? Would love to get this set up, my family get quite annoyed with my announcements interrupting their music and have to start the music from the beginning.

Oh, sorry, should have waited to after today to publish it. The iif function is new in 2022.2 which will be released today.
I also forgot to remove the _wip part

Yeah, got the same issue with that :wink: All devices & no dutch language. But the overlay was nice though. I’m interested if you can manage to let something like the youtube stream continue after TTS. Will follow this one :wink: Thanks for your effort!

Update

3 February 2022

  • Added requirements (HA Version 2022.2) to first post, also added requirements for Spotify resume there.
  • Removed WIP (work in progress) references in script object_id and alias.

The script now fires up with no errors after the HA core update but I’m still facing some issues.

if I fire up:

service: script.google_home_resume
data:
  action:
    - service: tts.cloud_say
      data:
        entity_id: media_player.dressing_room_speaker
        message: test

It plays the TTS announcement, makes a few google sounds but the music does not resume, any idea where I’m going wrong please?

I’m currently debugging a bit myself, but could you try if it works like this:

service: script.google_home_resume
data:
  target:
    entity_id: media_player.dressing_room_speaker
  action:
    - service: tts.cloud_say
      data:
        entity_id: media_player.dressing_room_speaker
        message: test
1 Like