Spotcast - custom component to start playback on an idle chromecast device

No bother at all. Lots of people helped me out when I got started (and even still!). I assumed you were a little farther along here. So I’ve eliminated everything but selecting and playing the playlist. You can build it up from here if you need to.

There are a couple parts to this. The select template stores your playlist names, which you will use to select the playlist you want to play in the UI. This needs to go in your config under a template section somewhere (depends on how you set up your configuration). I chose to make it a trigger template so the options will automatically update any time your Spotify playlists change (and only then). You’ll need something to trigger the play script also so I’ve also included a template button here to do that.

Spotify Templates
template:
  - trigger:
      - platform: state
        entity_id: sensor.playlists_sensor
        attribute: playlists
        to: ~

      - platform: state
        entity_id: input_text.spotify_playlist
        to: ~

      - platform: homeassistant
        event: start

      - platform: event
        event_type: event_template_reloaded
    select:
      - name: 'Spotify Playlist'
        state: "{{ states('input_text.spotify_playlist') }}"
        select_option:
          - condition: template
            value_template: '{{ option != none }}'

          - service: input_text.set_value
            target:
              entity_id: input_text.spotify_playlist
            data:
              value: '{{ option }}'
        options: >
          {% set plist = namespace(value =[]) %}
          {% set playlists = state_attr('sensor.playlists_sensor','playlists') %}
          {% if playlists != none %}
            {% for item in playlists %}
              {% set plist.value = plist.value + [item.name] %}
            {% endfor %}
          {% endif %}
          {{ plist.value }}

  - button:
      - name: 'Play Spotify'
        press:
          - service: script.play_spotify_playist

Along with this you need an input text to store your current playlist selection. We use this to reselect your selection after a restart or template reload. You can create input text in the Helpers page. The entity id must be input_text.spotify_playlist to work with the template.

Link to Helpers – My Home Assistant

Now you need a script which you call to use your selected playlist to start with spotcast.

Play Selected Spotify Playlist Script
script:
  play_spotify_playist:
    alias: 'Play Spotify Playlist'
    description: 'Play selected Spotify playlist.'
    sequence:
      - service: spotcast.start
        data:
          device_name: Dining Room Hub # change to your device
          uri: >
            {% set playlists = state_attr('sensor.playlists_sensor','playlists') %}
            {% if playlists != none %}
              {% for item in playlists %}
                {% if item.name == states('select.spotify_playlist') %}
                  {{ item.uri }}
                {% endif %}
              {% endfor %}
            {% else %} {{ none }}
            {% endif %}

Add these entities to a lovelace view, reload templates and scripts, and you should be ready to rock.

  - type: entities
    entities:
      - select.spotify_playlist
      - button.play_spotify
1 Like

Thanks a lot… you are my hero… :slight_smile: :slight_smile:

Last question.
This sensor will be created by the template or i must create?

Neither! That was 100% an oversight on my part. That is actually the entity id of the template sensor I created for my config to make things simpler for my spotify scripts because I have multiple spotify accounts to deal with. I forgot to change it when I copied the code from my config (and why it still worked when I tested…lol)

Change

      - platform: state
        entity_id: sensor.spotify_playlists
        attribute: playlists
        to: ~

to

      - platform: state
        entity_id: sensor.playlists_sensor
        attribute: playlists
        to: ~

Sorry for the confusion! I corrected it in the original reply also.

1 Like

Yes, i understood just after i wrote the message…
Thanks to you i understand better about template option…
Thanks again…

Ok i added all to my configuration files, restarted HA and tried to use the button to play some of my playlist, but the media player plays always the track i was playing before i restarted HA. It seems to me that spotcast doesn’t recognize the URI listed inside the sensor.playlists_sensor.

This is the screenshot i get in developers tools/models:

If i use the developers tool/services putting manually the URI, spotcast does his works as expected.
Maybe it’s my fault in something but i pasted and copied your configs…
EDIT: Sorry, was my fault… i was wrong creating the input text… Now it works GREATLY!!!

1 Like

It seems you forgot to mention the option categories in your modified scripts… if and when you have time, can you tell us something about it?
Thanks in advance…

I left them out on purpose because they were specific to my config and so I could reduce the templates and scripts to the simplest form for you so you could get up and running.

Categories are basically Spotify genres. The ability to play by category was only recently added to Spotcast and there is no real official “list” available from Spotify. The list I have was hand picked for myself using this utility. It ends up being a bit of guesswork to figure out the proper category names .

There are a couple of ways one could approach using categories with spotcast but in my config I chose to treat categories just as additional playlists to simplify things so that’s what I’ll do here.

You’ll have to create a categories template sensor (similar to the playlist sensor spotcast creates on it’s own). The one I included here is mine, which should give you a good start. I’m not sure if I tested all of the categories so be aware of that if one or two don’t seem to work. Always check the logs if something isn’t working, it will usually tell you why. You should be able to figure out how to add and delete categories from that sensor. Then you have to add those category names to your playlist select template options. And finally, your spotify play script needs to be able to figure out if the “playlist” you selected is actually a playlist or category and then send the correct parameters to spotcast.

Here it is all put together.
script:
  play_spotify_playist:
    alias: 'Play Spotify Playlist'
    description: 'Play selected Spotify playlist.'
    variables:
      category: >
        {% set category = namespace(value=none) %}
        {% set categories = state_attr('sensor.spotify_categories','categories') %}
        {% for item in categories %}
          {% if item.name == states('select.spotify_playlist') %}
            {% set category.value = item.category %}
          {% endif %}
        {% endfor %}
        {{ category.value }}
      uri: >
        {% set playlist = namespace(value=none) %}
        {% if category == none %}
          {% set playlists = state_attr('sensor.playlists_sensor','playlists') %}
          {% if playlists != none %}
            {% for item in playlists %}
              {% if item.name == states('select.spotify_playlist') %}
                {% set playlist.value = item.uri %}
              {% endif %}
            {% endfor %}
          {% endif %}
        {% endif %}
        {{ playlist.value }}
    sequence:
      - service: spotcast.start
        data:
          device_name: Dining Room Hub # change to your device
          "{{ iif(category != none,'category','uri') }}": '{{ iif(category != none,category,uri) }}'

template:
  - sensor:
      - name: 'Spotify Categories'
        unique_id: spotify_categories
        icon: mdi:spotify
        state: >
          {% set categories = state_attr('sensor.spotify_categories','categories') %}
          {{ 0 if categories == none else categories|count }}
        attributes:
          categories: >
            {{
              [
                {
                  "name":"Alternative",
                  "category":"alternative"
                },
                {
                  "name":"American Folk",
                  "category":"folk_americana"
                },
                {
                  "name":"Chill",
                  "category":"chill"
                },
                {
                  "name":"Classical",
                  "category":"classical"
                },
                {
                  "name":"Country",
                  "category":"country"
                },
                {
                  "name":"Dance",
                  "category":"edm_dance"
                },
                {
                  "name":"Decades",
                  "category":"decades"
                },
                {
                  "name":"Dinner",
                  "category":"dinner"
                },
                {
                  "name":"Focus",
                  "category":"focus"
                },
                {
                  "name":"Hip Hop",
                  "category":"hiphop"
                },
                {
                  "name":"Indie Alternative",
                  "category":"indie_alt"
                },
                {
                  "name":"Jazz",
                  "category":"jazz"
                },
                {
                  "name":"Metal",
                  "category":"metal"
                },
                {
                  "name":"Mood",
                  "category":"mood"
                },
                {
                  "name":"Party",
                  "category":"party"
                },
                {
                  "name":"R & B",
                  "category":"rnb"
                },
                {
                  "name":"Rock",
                  "category":"rock"
                },
                {
                  "name":"Sleep",
                  "category":"sleep"
                },
                {
                  "name":"Soul",
                  "category":"soul"
                },
                {
                  "name":"Toplists",
                  "category":"toplists"
                },
                {
                  "name":"Travel",
                  "category":"travel"
                },
                {
                  "name":"Workout",
                  "category":"workout"
                }
              ]
            }}

  - trigger:
      - platform: state
        entity_id: sensor.playlists_sensor
        attribute: playlists
        to: ~

      - platform: state
        entity_id: input_text.spotify_playlist
        to: ~

      - platform: homeassistant
        event: start

      - platform: event
        event_type: event_template_reloaded
    select:
      - name: 'Spotify Playlist'
        state: "{{ states('input_text.spotify_playlist') }}"
        select_option:
          - condition: template
            value_template: '{{ option != none }}'

          - service: input_text.set_value
            target:
              entity_id: input_text.spotify_playlist
            data:
              value: '{{ option }}'
        options: >
          {% set plist = namespace(value =[]) %}
          {% set clist = namespace(value =[]) %}
          {% set playlists = state_attr('sensor.playlists_sensor','playlists') %}
          {% set categories = state_attr('sensor.spotify_categories','categories') %}
          {% if playlists != none %}
            {% for item in playlists %}
              {% set plist.value = plist.value + [item.name] %}
            {% endfor %}
          {% endif %}
          {% if categories != none %}
            {% for item in categories %}
              {% set clist.value = clist.value + [item.name] %}
            {% endfor %}
          {% endif %}
          {{ plist.value + clist.value }}

  - button:
      - name: 'Play Spotify'
        press:
          - service: script.play_spotify_playist

1 Like

Are there some other tests I can do to confirm that the Spotify integration and spotcast are installed correctly?

Does the service spotcast.start exist? Do the entities sensor.chromecast_devices and sensor.playlists_sensor exist in your config? Spotcast creates all of these.

Try calling spotcast.start right from devtools. If it works from the the issue is in your script.

Did you get this resolved?

Thank you Jason.
Yes, the spotcast.start service exists. I do not see any entities named sensor.chromecast_devices, sensor.playlists_sensor or anything else similar. I do have a media player entity for my chromecast device though (perhaps that’s what you meant?), called ‘media_player.study_display’.

I tried using spotcast.start from devtools, but that produced an error. My script is exactly the same is the one I previously used on my old HA install which worked flawlessly.

I’m wondering if there is a problem with me using the existing Spotify ‘App’ on the Spotify Developers page that I used for my old HA installation? Should I create a new one?

Your study media player was set up by the cast integration and is independent of spotify or spotcast.

If the device and playlist sensor do not exist, I believe you spotcast integration is not set up correctly.

First, are you sure the Spotify integration itself is working properly? You need both the HA Spotify integration and Spotcast for Spotcast to work. If yes (ie - you have a working spotify media player in your config) , then I am going to guess that there is something wrong with your spotcast config - most likely the sp_key and sp_dc cookie values have changed.

I would go through the spotcast configuration again carefully, recopying the cookie values into your config. If you’ve done all that and it’s still not working post your script here and we’ll have a look to see if the problem is with that.

Are you specifying a device when you call spotcast?

image

When you click a media player card you’ve already selected which devices to play on. When you call spotcast, you need to tell it what device to play on.

I think what you’re seeing with the media browser is the built in Spotify integration media player “loses” the available source devices after a while (this is the reason spotcast is a thing). While the spotify media player still has source device in “memory” you can start spotcast and it will default to the sources still in memory. After that you need to specify the device again when you call spotcast.

Thanks, i am really learning a lot of new stuff reading your posts…

I am specifying a device, though I notice I am using the spotify_device_id (which I thought was the preferred way to do it as that was in the first code example on github) and not the device_name you use in your screenshot. Let me test that to see if it makes a difference!

Let me know how you make out. I’m curious if were you trying to use the Home Assistant device ID or the Spotify Device ID? Personally I’ve never bothered with the spotify device id, using the device name and/or entity id work fine so I never saw the point.

Good news! Using the device name in the service call fixed it. I’m not sure why this works differently than the device ID, especially because I assumed from the way the docs talk about it that the device ID is a more direct link to the device, but super happy that this easily solves it! @DIY-techie using device_name instead of spotify_device_id fixed it for me.

Just for added info, I was using the correct Spotify Device ID. The service call also works with this ID later, as long as the cast device has been activated via another route. But it won’t pull it out of idle.

1 Like

Unfortunately not. A friend of mine copied my code into his HA and just changed the entities and it works fine. So I know at least it isn’t the code but something with the spotcast install. Problem is I have re-installed spotcast and it’s still not working. I don’t want to give up on it as I really need this functionality.

How did you verify you credentials are correct?
Have you tried calling spotcast.start right from Developer Tools → Services?

service: spotcast.start
data:
  device_name: Dining Room Hub
  uri: spotify:playlist:37i9dQZF1DWSK8os4XIQBk

What happens when you do this?

If it didn’t work, set the spotcast level to debug and try again.

service: logger.set_level
data:
  custom_components.spotcast: debug

What do the logs say?

I configured a Mini Media Player with a Spotcast shortcut to start a playlist on one of my children’s Echo dots using the device ID specific to one of the accounts under my Spotify Family plan and the device. Initially, it works as expected, but within 1-2 days it will randomly stop working giving a generic device not found error when I tap the button:

Failed to call service spotcast/start. http status: 404, code:-1 - https://api.spotify.com/v1/me/player/play?device_id=<THEDEVICEID>: Device not found, reason: None

When I go to verify the Device ID using the same steps as before, I find (1) I have to say “Spotify Connect” and tap the Echo device in my Spotify app to get it to re-establish the connection and make it available for retrieval and (2) the Device ID has changed.

I think the problem is that this Echo device (and most others throughout my house) are logged into my primary Amazon Household account which is tied into the Spotify skill using a different Spotify account under the same Family Plan.

Has anyone else had a similar issue? Any ideas?

I have 3 spotify accounts. One is the “house” or HA account which is generally used if spotify is started by HA. This was done so HA starting spotify doesn’t interrupt our personal accounts if we are using them somewhere else (ie our phones)

The others are my wifes and my own personal accounts. If either of us start spotify via voice with the google assistants or from our phones Spotify is played using our respective accounts. (We can also use our own accounts from the UI if desired, for example if someone else is using the house account somewhere else or we want to play a personal playlist that isn’t on the house spotify account).

I have to account for all of these in my automations and scripts because one or more accounts may be in use at a time.

As for your error… try changing you service call from spotify_device_id to device_name. That seems to be much more reliable. See this recent post and the reply.

- service: spotcast.start
  data:
    device_name: Dining Room Hub
    uri: spotify:playlist:37i9dQZF1DXbYM3nMM0oPk