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

I did a virtual switch in SmartThings (Simulated Alexa Switch) which both HA and Alexa can see.

Then the routine in Alexa was a super basic one, when the switch is open it played a silent track from Spotify.

Something like this, but here it shuffles and plays a playlist when the Simulated Alexa Switch (called Charlie Green Light) opens from HA.

Thanks!
Fun fact: SmartThings virtual switches are not available anymore. :frowning:

Seems weā€™re going a little bit off topic here, but I have this one as a device handler in SmartThings which works. But maybe theyā€™ve changed how to add device handlers?

seems spotcast ist broken with 2023.4.x i cant wake up my Google Speaker since upgrade. any ideas?

1 Like

Did you ever find a solution to this. Iā€™m experiencing the same issue (though Iā€™m trying to use it for device ID and/or Device Name, but almost identical code and experiencing the same outcome.

Hello,

the Spotcast integration, where about 10 call services executed with spotcast.start, begins to stop working and throws errors like: ā€œCall-service error. HTTP status: 404, code:-1 - https://api.spotify.com/v1/me/player/volume?volume_percent=90&device_id=310ae54b22a7c6e32f0dbcb76a864a22: Device not found, reason: Noneā€. The only way to solve the problem is to restart Home Assistant. Is there a way to restart the Spotcast integration without restarting the entire Home Assistant? This way, I could ā€œcaptureā€ the error, and when it happens, automatically restart the integration.

Any chance you can share that automation?
Iā€™m trying to set up a script that will play a specific playlist on a specific Alexa Echo Dot device but I keep get error

Stopped because an error was encountered at May 21, 2023 at 5:42:28 PM (runtime: 5.02 seconds)

Could not get spotify token.

alias: Shower Music
sequence:
  - service: spotcast.start
    data:
      uri: spotify:playlist:3OrzpgkRM3gHd4xAhy86Zr
      random_song: true
      shuffle: true
      device_name: Shower Echo Dot
mode: single
icon: mdi:account-music

Your Amazon Alexa Echo Dot is not covered by this.

I can start playback with a non default account using this service:

- service: spotcast.start
  data:
    account: "niklas"
    device_name: "Speaker kitchen"
    uri: "spotify:playlist:37i9dQZF1DX3yvAYDslnv8"

But when I use the Media Control or Mini Media Player in Home Assistant, click on ā€œBrowse mediaā€, select one of my spotify accounts and select a song, it always uses the default spotify account to playback.

Does anybody know if I can use the selected spotify account instead of the default one?

1 Like

Hello, I am throwing this out there in the hopes that someone can help. I have scoured this thread and while I see hints of similar issues Iā€™m not sure this has been fully addressed.

Problem:
I am unable to reliably Spotcast to Sonos speakers due to Spotcast/Spotify ā€˜forgettingā€™ the ā€˜spotify_device_idā€™ values (extracted from browser traffic). entity_id and device_name do not work at all for Sonos as far as I can tell.

Setup:
I have the official Spotify and Sonos integrations, with Spotcast and Mini Media Player installed with HACS. I use the ā€˜mini-media-playerā€™ integration, with a button button to call spotcast.start service and start a personal playlist.

Sonos is running on SonosNet as one speaker is wired direct to the router. HomeAssistant server is also wired direct to router. Computer I am testing on is on same network, wired through homeplug.

Example YAML:

type: custom:mini-media-player
entity: media_player.<sonos entity>
shortcuts:
    columns: 1
    buttons:
     - id: spotcast.start
       type: service
       data:
        uri: <my playlist>
        spotify_device_id: <Sonos device ID extracted from browser>
        <device_name and entity_id have never worked here>
        random_song: true
        shuffle: true

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

Possible Issues:
My speculation is the issue sits with the Web API, my Android and Desktop Spotify apps show all Sonos Speakers without issue all day, but the browser app (open.spotify.com) doesnā€™t show the speakers in the Connect menu when idle. This is even when on the same desktop and same network, switching between browser and app.

If I ā€˜castā€™ to a speaker, it suddenly appears in the web app, and then Spotcast works perfectly. Once the speaker goes idle, or disappears from the web app it is broken again.

Context:
For wider context, I want to use Spotcast with Sonos because this is the only method I have found that actually shows the music status in other Spotify apps (Phone, Desktop), and allows you to join, take control or add to queues. Initiating URIs with the Sonos/Media Player integration, or initiating Sonos Favourite playlists (tied to Spotify) will play music correctly, but Spotify apps are ā€˜blindā€™ to the activity: You and others on the network cannot join the listening session as the official apps have no idea itā€™s going on.

Help?
Is this an inherent issue due to the stupid ā€˜partialā€™ API support that Spotify has granted Sonos (or vice versa)? Is there a way to wake Sonos devices so that Spotify web can see their device IDs? Can the Sonos integration be manipulated to sync with Spotify apps? Am I doomed? I am all ears if there are workarounds!

4 Likes

I continue to have trouble getting Spotcast to actually use the non default account. Itā€™s annoying because I want my kids bedtime music to stop cluttering my personal Spotify

i am using spotcast to play spotify on a google home mini as my morning alarm.

However it is extremely unreliable. It rarely actually function and i canā€™t find out why it doesnā€™t work most of the time.

I have the sp-dc and the sp-key. I am using only one account.

I have a few playlists that I want to be chosen through a single script depending on the time of day.

I have created a text input helper which has automations to update based on time of time, is it possible for me to call the value of this input helper in the ā€œuri:ā€ part of the spotcast service?

Hi again, the striped trough text has been fixed by using the Spotify_device_id. However when I reboot HomeAssistant and use my Sonos Arc for lets say my TV audio it forgets the spotify_device_id. I get the same message ā€œā€¦ device not foundā€

Deze fout is ontstaan door een aangepaste integratie.

Logger: spotipy.client
Source: custom_components/spotcast/spotcast_controller.py:323 
Integration: Spotcast (documentation, issues) 
First occurred: 09:42:34 (1 occurrences) 
Last logged: 09:42:34

HTTP Error for PUT to https://api.spotify.com/v1/me/player/play?device_id=343e3e31d3db6feaf130aa3a967afa1990352477 with Params: {} returned 404 due to Device not found

I first have to go to the Spotify app on my mobile phone (connected on the same network), select my Sonos speaker as output and then the spotify_device_id is registered again and working. Is there a way to fix this?

I also get another few errors and Iā€™ve noticed that the sensor is not being created. If wanted I can post the full error-log here.

Kind regards,
Remco

hello all,

Iā€™ve been struggling for 2 days now to get spotcast to work. I managed to be able to start my Spotify to my google nest mini but it doesnā€™t seem to work on my Sonos setup. I can cast to the Sonos from within the Spotify app and when I then take a look at (for example) the web version of Spotify I can see that its streaming to the Sonos.

However I cannot seem to cast it directly from within HA (via services). I get the following error:

```
Logger: homeassistant.components.websocket_api.http.connection
Source: components/websocket_api/connection.py:231
Integration: Home Assistant WebSocket API (documentation, issues)
First occurred: 22:23:38 (1 occurrences)
Last logged: 22:23:38

[547812702160] Error handling message: Could not find device with name Sonos (unknown_error) Admin from 192.168.1.51 (Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15)
```

the strange thing is that Iā€™ve tried Sonos, sonos, media_player.sonos and nothing seems to work.

Can someone help me figure out what Iā€™m doing wrong?

it works on my Google Nest mini btwā€¦ but I want it to work on my Sonos Arc since I use that for playing music in my house.

I have learned that we donā€™t want to rely on Spotify for our morning alarms. Even in the best of circumstances, Spotcast will lose itā€™s tokens once in a while. Plus, it is a cloud service, so bound to be offline sometimes.

I am only using local MP3 for our alarms nowadays.

Firstly Amazing work, My missus loves spotcast. However i was wondering if there is a way to move an existing cast session to another speaker or group by way of automation, just like the (GitHub - custom-cards/spotify-card: Spotify playlist card for Home Assistant card) spotify lovlace card can when you select a different chromecast device in the UI.

i would like to move the cast from upstairs to the livingroom after her shower without starting a new cast

EDIT: nvm, i think i found it under force_playback:

Iā€™ve a very similar setup as you do (spotify duo instead of familiy, but otherwise the same), and iā€™ve been dealing with that issue for months now. But today i stumbled upon something. Iā€™ve noticed that only two out of my nine echo-media-players go into ā€œinactiveā€ state, while all the others just stay in standby. And iā€™m quite sure now, that this ā€œinactiveā€ is the state in which i get these errors (iā€™ll have an eye on this in the future), because these two echos weā€™re the ones where i noticed problems.

Also: These two echos are the only ones configured as ā€œEcho Kidsā€. Iā€™m wondering if the ā€œinactiveā€ state is exclusive to those.

Has anyone allready looked into this?

Is there a way to disable the creation of the sensor.playlists_sensor?
i get tons of errors about this sensor everydayā€¦ Just like these:

2023-08-23 13:14:54.413 ERROR (SyncWorker_29) [spotipy.client] Max Retries reached
2023-08-23 13:14:54.419 ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.playlists_sensor fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/requests/adapters.py", line 486, in send
    resp = conn.urlopen(
           ^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 889, in urlopen
    return self.urlopen(
           ^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 889, in urlopen
    return self.urlopen(
           ^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 889, in urlopen
    return self.urlopen(
           ^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 879, in urlopen
    retries = retries.increment(method, url, response=response, _pool=self)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.spotify.com', port=443): Max retries exceeded with url: /v1/me/playlists?limit=30&offset=0 (Caused by ResponseError('too many 502 error responses'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/spotipy/client.py", line 266, in _internal_call
    response = self._session.request(
               ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/adapters.py", line 510, in send
    raise RetryError(e, request=request)
requests.exceptions.RetryError: HTTPSConnectionPool(host='api.spotify.com', port=443): Max retries exceeded with url: /v1/me/playlists?limit=30&offset=0 (Caused by ResponseError('too many 502 error responses'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 699, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 940, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/spotcast/sensor.py", line 116, in update
    resp = self.hass.data[DOMAIN]["controller"].get_playlists(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/spotcast/spotcast_controller.py", line 333, in get_playlists
    resp = client.current_user_playlists(limit=limit)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/spotipy/client.py", line 637, in current_user_playlists
    return self._get("me/playlists", limit=limit, offset=offset)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/spotipy/client.py", line 323, in _get
    return self._internal_call("GET", url, payload, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/spotipy/client.py", line 307, in _internal_call
    raise SpotifyException(
spotipy.exceptions.SpotifyException: http status: 429, code:-1 - /v1/me/playlists?limit=30&offset=0:
 Max Retries, reason: too many 502 error responses

I already talked about this with the developer, but unsuccesfullyā€¦

Itā€™s reasonably straightforward to do this by making some edits to the python files for the custom component - how confident would you feel about doing that?