Skip to content

Device Configuration Options

Todd Lucas edited this page Aug 21, 2024 · 47 revisions

Spotify Developer Application Configuration

This integration utilizes the Spotify Web API services to control the Spotify Connect Player, as well as access information on behalf of your Spotify user account(s). Spotify secures access to its Web API services using the OAuth 2.0 authorization standard, so there are some pre-requisites to complete before installing the integration to Home Assistant.

This page is fairly lengthy, so use the following index to get to where you want to be:

Or continue reading for detailed information on how things work pertaining to the installation process.

OAuth2 Authorization Protocol

For those already familiar with OAuth 2.0 and how it works, you can probably skip this section. If you're not familiar with OAuth2, then read on.

OAuth 2.0 (or OAuth2), which stands for “Open Authorization”, is a standard designed to allow an application to access resources hosted by other applications on behalf of a user. OAuth2 provides consented access and restricts actions of what the client application can perform on resources on behalf of the user, without ever sharing the user's logon credentials.

The OAuth2 protocol provides a way for resource owners to provide a client application with secure delegated access to server resources. It specifies a process for resource owners to authorize third-party access to their server resources without providing credentials. OAuth2 essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner (you). The third party client then uses the access token to access the protected resources hosted by the resource server.

In the case of Home Assistant and our integration, the following can be used when interpreting the OAuth2 authorization flow explained below:

  • Client: the Home Assistant OAuth2 Authorization Provider.
  • Resource: the Spotify data accessed - a users playlist, media player commands, etc.
  • Consumer: the SpotifyPlus integration accessing the Resource.

The Spotify Web API supports the OAuth2 Authorization Code authorization flow type. More information on Spotify Authorization Flows can be found on the Spotify Developer Documentation, Authorization page.

The following lists the basic authorization flow that is performed when accessing Spotify resources.

In the case of our integration, all but the last of the following steps will happen when the integration is installed to Home Assistant and a new Application Credential is defined by using the "Add Service" link.

  • The user shows intent. Basically, it means any access to a restricted resource that requires them to sign in. It signifies the user's intent to initiate the OAuth2 process to grant access to their data.

  • The user gets permission. Here, the client prepares an OAuth2 request and directs the user to the OAuth2 authorization server. The server will show a consent screen, listing the kinds of data the client wants to access and what actions it wants to perform.

  • The user is redirected to the service provider. The user is redirected to the authorization server's UI (a web page) where they must log in with their credentials and approve the permissions requested by the client.

  • The user gives permission. Once the user has authenticated, they give consent for the permissions requested. This is done by clicking on the “Agree” button on the authorization server's UI.

  • The consumer obtains an access token. After successful authentication and approval, the user is redirected back to the client with an authorization code. The client then exchanges this code for an access token by making a server-to-server request.

  • The consumer accesses the protected resource. Finally, the client uses the acquired access token to access the protected resources hosted by the resource server. Depending on the OAuth2 flow, this token can be short-lived and optionally refreshed.

Again, all of the above happens without Home Assistant having to store your Spotify username and password. Theat's the beauty of OAuth2.

Pre-Installation Requirements

The following steps need to be completed prior to installing the integration.

NOTE - You can use the same Spotify Developer Application (Client ID and Secret) that you use for the HA Spotify (not SpotifyPlus) integration. You just have to create two separate HA OAuth Application Credentials (one for Spotify and one for SpotifyPlus) as each integration requires a separate token value to access the Spotify Web API. This allows you to use both Spotify and SpotifyPlus integrations at the same time for comparison if you like.

Step 1 - Create a Spotify User Account(s)

An active Spotify account is required. If you don't have a Spotify user account, then hop out to the Spotify web-site and create an account.

A premium-level account is recommended, as Spotify limits playback operations (e.g. play, pause, adjust volume, skip to the next track, etc) to premium-level accounts. You will need a premium-level membership if you want to control the Spotify Connect player from Home Assistant. Note that the premium-level membership does require a monthly service fee.

A free-level membership will also work, but you will only be able to browse media and retrieve player playback status with it (no player control, no playing of media content from Home Assistant).

Step 2 - Create Spotify Developer Application(s)

In order for our integration to access Spotify user resources, we must define a Spotify Developer Application in the Spotify Developer Portal. An Application provides the Client ID and Client Secret needed by the Home Assistant OAuth2 Authorization Provider to request an access token. The access token will be created when we define the Application Credentials in Home Assistant.

You can use the same Spotify Developer Application (Client ID and Secret) that you use for the HA Spotify (not SpotifyPlus) integration. You just have to create two separate HA OAuth Application Credentials (one for Spotify and one for SpotifyPlus) as each integration requires a separate token value to access the Spotify Web API. This allows you to use both Spotify and SpotifyPlus integrations at the same time for comparison if you like.

If using multiple Spotify user accounts ... you will need to create a separate Spotify Developer Application for each Spotify user account that you wish to access from HA, regardless of membership level (premium or free). This allows you to access the Spotify Web API for each account separately.

You may proceed to Step 3 - Home Assistant Application Credential(s) if you have already created a Spotify Developer Application(s), and have your Client ID / Client Secret values.

Otherwise, use the following steps to create a Spotify Developer Application(s).

Step 2a - Spotify Developer Portal Login

Go to the Spotify for Developers portal and log in using your Spotify credentials. The login button is located toward the upper-right of the screen. Once you are logged in, go to the Spotify Developer Dashboard. The dashboard (see Figure 2a) is where you can create apps, control the API credentials bound to the app, or just get some nice app usage statistics.

Figure 2a - Spotify Developer Dashboard

Step 2b - Create Application

Click on the Create App button to start the application create process (see Figure 2b).

Use the following details for the input fields on the form.

NOTE - it is VERY IMPORTANT that you get the Redirect URI correct, as it is case-sensitive and must match exactly what is specified below! I would also avoid any special characters in the App Name and Description fields (e.g. + % & # etc).

  • App name: Home Assistant Spotify Plus Integration
  • App description: Home Assistant integration that allows Spotify content to be played for a Premium user account.
  • Website: https://www.home-assistant.io/
  • Redirect URI: https://my.home-assistant.io/redirect/oauth
  • API/SDKs used: Web API
  • Accept the terms and conditions by checking the box.
  • Click the Save button to save the application.

Figure 2b - Spotify Developer Create App

Now that the application has been created, we can look at the settings to retrieve the client id and client secret values.

Step 2c - Get Client ID / Secret Values

Click on the Settings button to view the application details form (see Figure 2c).

Figure 2c - Spotify Developer App Details Form

You will need to click on the View Client Secret link in order to view the secret.

Copy down the Client ID and the Client Secret values, and store them in a safe place. We will be entering these values into Home Assistant in a later step. In our example, the client id is 95576e7c24e94c2d839068aa1b2e7f5e, and the client secret is 28e0224edc8c4419b9adb6feddf33ca6. Note that you cannot use OUR example values, as they have been deleted by the time this document is published.

Your new application contains your Client ID and Client Secret needed to authorize the SpotifyPlus integration to use Spotify resources via Home Assistant.

NOTE - The above steps will need to be done for each Spotify user-account that you wish to access from the Home Assistant SpotifyPlus integration, regardless of membership level (premium or free).

We are now ready to configure the Home Assistant Application Credential for the integration.

Step 3 - Home Assistant Application Credential(s)

We are now ready to add Home Assistant Application Credentials for each of the Spotify Developer Applications that were created in Step 2.

Go to the Application Credentials page to list any existing OAuth2 application credentials, as well as define new ones. This is located under Settings \ Devices & Services \ Application Credentials (have to click the 3 dots menu in the upper right corner).

Step 3a - Add Application Credential(s)

Click the Add Application Credentials button to add a new credential.

Fill in the Credential Form fields (see Figure 3a):

  • Integration: SpotifyPlus (select from dropdown list).
  • Name: Enter a name for the credential. I would suggest using "Spotify FIRST LAST" for this value, with FIRST being the Spotify user first name and LAST being the Spotify user last name (e.g. "Spotify John Smith").
  • OAuth client ID: The Client ID value for the Spotify User.
  • OAuth client secret: The Client Secret value for the Spotify User.
  • click Add to add the credential.

Figure 3a - Home Assistant Application Credentials Form

For multiple Spotify User support, repeat the above step for each of the Spotify Developer Applications that you created.

We are now ready to add the SpotifyPlus integration.

Integration Install

Use the following steps to install and configure the integration.

*** IMPORTANT ***
Please restart Home Assistant and clear your browser cache (including files, cookies, and images) prior to executing the following steps! There have been quite a few issues with HA OAuth2 Authorization with Spotify and cached pages of late, so just to save you (and me) some headaches: clear your browser cache before installing the integration.

Step 4a - Integration Install

Go to the Integrations Dashboard page to add the integration. This is located under Settings \ Devices & Services. Click on the Add Integration button to start the process.

Or, if you have already added the integration and want to add another Spotify user, go to the SpotifyPlus Integration Details page and use the ADD SERVICE button.

Step 4b - Select Application Credential

The OAuth Application Credential selection form (see Figure 4b) should be displayed at this point. This will allow you to select the Application Credential that was defined earlier for the Spotify user you wish to add access for.

Check the button next to the Application Credential item that was previously defined, and click Submit to start the Spotify authorization process.

Figure 4b - Select SpotifyPlus OAuth Credential Form

Step 4c - Spotify Login

Home Assistant OAuth2 security will now open a secure browser window to the Spotify authorization web-site (see Figure 4c), prompting you for your Spotify login credentials (see Figure 4c).

Enter your Spotify username and password credentials.

Figure 4c - Spotify Login Form

Note that the Spotify login prompt may be bypassed if you have logged into Spotify before and are using cached credentials. If that is the case, you will see the Authorization Form instead. If this happens, MAKE SURE that the Spotify user display name is the same Spotify account that you entered Application Credentials for!

Step 4d - Spotify Authorization

Click on Agree on the Spotify Authorization Access Form (see Figure 4d) to allow Home Assistant to access Spotify resources on your behalf.

Figure 4d - Spotify Authorization Access Form

Step 4e - Home Assistant Link Account

Click on Link Account (see Figure 4e) to allow Home Assistant to link the OAuth2 Application Credential to Spotify.

IMPORTANT - Note the hi-lited URL prefix value in the Figure 4e example (top of the page in the URL); this should match the Redirect URI value (e.g. https://my.home-assistant.io/redirect/oauth) that you entered for the Spotify Developer Application in Step 2b - Create Application. If it does NOT match, then you will need to modify the Spotify Developer Application settings and add it as an allowed Redirect URI value. Note that you can specify more than one Redirect URI value in the Spotify Developer Application settings. You can adjust the Spotify Developer Application settings after this step is complete if need be.

IMPORTANT - Note the Your Instance URL value in the Figure 4e example (toward the bottom); this should match the url that you use to access Home Assistant. You may need to adjust the http:// to https:// if you access your instance of Home Assistant via Secure Sockets Layer (SSL).

Figure 4e - Home Assistant Link Account Form

Step 4f - Verify Results

Verify the result (see Figure 4f) and click on FINISH to complete the setup for this user if the addition was successful.

Figure 4f - Integration Added Form

Repeat the SpotifyPlus Integration Install steps for each Spotify user account that needs to be added.

Integration Remove

Use the following steps to remove the integration.

Step 5a - Remove Integration

Go to the SpotifyPlus Integration Dashboard page to remove the integration. This is located under Settings \ Devices & Services \ Spotify Plus.

From the Integration Summary Form (see Figure 5a), click the 3 dots menu next to the service that you want to remove and select the Delete menu item. A confirmation dialog box will be displayed - just click DELETE to confirm the action.

Figure 5a - Integration Remove Confirm Form

Figure 5a2 - Integration Remove Confirm Form

Step 5b - Remove Application Credential

Home Assistant will also prompt you (see Figure 5b) to remove the Application Credentials associated with the integration. You can either keep the Application Credentials or delete them.

I would suggest keeping them if you are going to re-install the integration later, which will save you the process of re-entering them again later. If you choose to keep them, but decide later that you don't need them, they can still be removed via the Application Credentials page.

Figure 5b - Application Credential Remove Confirm Form

Integration Options

The SpotifyPlus Service Options Form (Figure 6) allows you to customize various aspects of the integration. Adjust the settings to your taste. Click the Save button once you are finished to save your changes, or the X button at the top right to cancel without saving.

Figure 6 - SpotifyPlus Service Options Form

The following fields are available for this form:

Default Player Device ID

This option contains the Device Name and ID of the Spotify Connect device that will be used to play content when ANY of the following conditions are met:

  • when there is no active device.
  • when the default player device id (e.g. *) is specified for a service that requires a device id parameter (e.g. play, pause, transfer playback, etc).
  • when the media player is initially powered on; in this case, the active player is transferred to the specified default player device id if there is no previously selected source.

A dropdown list of Spotify Connect device id's (gathered when the options form is opened) are displayed to select an entry from. If you don't see your desired device id in the list, then start playing some Spotify content on the device of choice, and close / re-open the configuration options; the desired device should then be present.

Select an item from the dropdown list to set the default player for the specified integration. If no selection is made, then the previously active player will be used. If no player is active, then the player command will probably fail as there will be no active device.

Static Device ID's
Some Spotify Connect capable devices retain the same device id for the life of the device (e.g. static / does not change). For example, the Bose SoundTouch line of speakers utilize the same Spotify Connect Player device id, even between power cycles. Static device id's are the best choice when assigning a default player device id.

Dynamic Device ID's
Some Spotify Connect capable devices retain the device id for the life of the session (e.g. dynamic / will change frequently). For example, web and mobile based players as well as Google Cast devices will create a new device id when establishing a new session to Spotify Connect. This is why dynamic device id's are not a good choice when assigning a default player device id - they will not exist when you need them.

Disappearing Device ID's
Regardless of whether you have a dynamic or static device id, the device id WILL disappear from the Spotify Web API available device list once the session or application has been shut down or a period of inactivity has passed (e.g. approximately 10 minutes). In this case, you need a way of "waking up" the device so that it is re-discovered by the Spotify Web API as an available device. You can utilize the SpoytifyPlus Turn On Script configuration option to accomplish this.

Figure 6a - Default Device ID Selection

Spotify Connect Device Username

This option contains the Spotify Connect user name (e.g. [email protected]) used to login to a Spotify Connect device. This MUST match the account name (or one of them) that was used to configure Spotify Connect on a manufacturer device.

The spotifyConnectUsername, spotifyConnectPassword, and spotifyConnectLoginid values are only used when a Spotify Connect account switch is performed on a selected player device. Note that these credentials are NOT used to access the Spotify Web API (the Spotify Web API token is used for that).

Spotify Connect Device Password

This option contains the Spotify Connect password used to login to a Spotify Connect device. This value is required if a non-null value was specified for the spotifyConnectUsername value.

Note that if you don't have a password setup for your Spotify account (e.g. you utilize the "Continue with Google" or other non-password methods for login), then you will need to define a "device password" in order to use the ZeroConf Connect service; use the Spotify Set Device Password page to define a device password. You will then use your Spotify username and the device password as your Spotify Connect credentials.

Spotify Connect Device LoginId

This option contains the Spotify Connect canonical login ID (e.g. 3758dfdsfjk435hjk6k79lm0n3c4) used to login to a Spotify Connect device. This MUST be the canonical equivalent value of the spotifyConnectUsername value.

The spotifyConnectUsername, spotifyConnectPassword, and spotifyConnectLoginid values are only used when a Spotify Connect account switch is performed on a selected player device. Note that these credentials are NOT used to access the Spotify Web API (the Spotify Web API token is used for that).

Turn On Script

This option allows you to specify a script that will be executed when a turn_on service request is made to power on the integration. The script can be used to prepare the audio output device(s) (e.g. speaker, AV receiver, etc) for playing Spotify Connect Player content. For example, you could have a script that performs the following actions:

  • turn on AV receiver.
  • switch AV receiver input to AUX 1.
  • issue a media_player.select_source service call to activate a source on the device (e.g. force the device to be re-discovered by the Spotify Web API as an available device).
  • issue a call to service spotifyplus.player_transfer_playback to transfer Spotify Player playback to the device.

The script is executed syncronously, which means the integration will wait until the script ends before proceeding with other power-related events. Any changes to the script take effect immediately - you do not need to restart HA for script changes.

The script configuration option is optional - you don't have to select a script. If your device or audio equipment does not require any preparation steps to play output then leave the option blank.

Turn On Script Example - Bose SoundTouch Speaker

I use the following to prepare my Bose SoundTouch speaker for playing Spotify content.

alias: SpotifyPlus Todd L - Turn On
sequence:
  - service: spotifyplus.player_transfer_playback
    data:
      entity_id: media_player.spotifyplus_john_s
      device_id: "*"
      play: true
    enabled: true
    alias: >-
      Transfer Spotify Playback to Bose SoundTouch device.
mode: single
icon: mdi:power

Turn Off Script

This option allows you to specify a script that will be executed when a turn_off service request is made to power off the integration. The script can be used to shut down the audio output device(s) (e.g. speaker, AV receiver, etc) after playing Spotify Connect Player content. For example, you could have a script that performs the following actions:

  • turn off AV receiver.
  • turn off speaker device.

The script is executed syncronously, which means the integration will wait until the script ends before proceeding with other power-related events. Any changes to the script take effect immediately - you do not need to restart HA for script changes.

The script configuration option is optional - you don't have to select a script. If your audio equipment does not require any shutdown steps after playing output then leave the option blank.

Turn Off Script Example - Bose SoundTouch Speaker

I use the following to power down Bose SoundTouch speaker after playing Spotify content.

alias: SpotifyPlus Todd L - Turn Off
sequence:
  - service: media_player.turn_off
    target:
      entity_id:
        - media_player.bose_st10_1
    data: {}
mode: single
icon: mdi:power

Hide Source List Devices

This option allows you to specify a list of device names (semi-colon delimited) that will be hidden from the HA media player UI source list. The device names listed here will not be displayed in the HA media player UI source_list attribute of device names. Note that hidden device names are still accessible via the various integration custom service calls though.

The device names can be specified case-insensitive (e.g. "bose-st10-1" and "Bose-ST10-1" specify the same device), and have leading / trailing spaces; all comparisons are done with lower-case, and leading / trailing spaces removed.

This option was introduced with integration v1.0.47.

Integration Log Filtering

The SpotifyPlus integration expects a response from Spotify within 1 second. It should be noted that SpotifyPlus does not call the Spotify Web API every second, but it can call the Spotify Web API every second for 8-10 consecutive seconds in certain scenarios.

There are times when the Spotify Web API services become overloaded by circumstances beyond our control, and are subsequently sluggish to respond. In those times, Home Assistant will detect that the SpotifyPlus integration has not responded within the expected 1 second timeframe (because it's waiting on Spotify Web API to return a response). A System Log warning message is issued when this happens, which will look like the following:

2024-07-21 09:37:04.778 WARNING (MainThread) [homeassistant.components.media_player] Updating spotifyplus media_player took longer than the scheduled update interval 0:00:01
2024-07-21 09:37:05.784 WARNING (MainThread) [homeassistant.components.media_player] Updating spotifyplus media_player took longer than the scheduled update interval 0:00:01
2024-07-21 09:37:06.790 WARNING (MainThread) [homeassistant.components.media_player] Updating spotifyplus media_player took longer than the scheduled update interval 0:00:01

To avoid numerous duplicated log messages, it is recommended that you add the following to your configuration.yaml to filter out these warning messages:

logger:
  filters:
    # filter spotifyplus media_player log warnings for lengthy Spotify responses.
    homeassistant.components.media_player:
      - "Updating spotifyplus media_player took longer than the scheduled update interval"

OAuth2 Token for TokenType=Authorization_Code Devices

The SpotifyPlus integration uses OAuth2 secure token processing for Spotify Connect devices that utilize the authorization_code token type. As of this writing (08/15/2024), it appears that only Sonos devices utilize this type of token authorization for Spotify Connect authentication. To be clear, if you don't use (or don't care about) Sonos devices then you can ignore this OAuth2 Token functionality.

In order to accomodate this token type, you need to authorize the Spotify Desktop Application for access to your Spotify account via the Spotify Authorization URL. This will create an OAuth2 authorization access token, which can then be used by SpotifyPlus to authenticate to the device. This process only needs to be performed once, as it will automatically refresh the access token when it expires.

I have created a Python Script to do this for you, but it has to be executed (by you) on your local desktop. It will open a default browser window and have you authorize the "Allow Spotify to connect to: Spotify for Desktop" request. You may be prompted to login as part of the authorization if you have not logged in using your desktop before. It should not matter what operating system you use to execute the script (e.g. Windows, Mac OS, Linux), just as long as it's a desktop and has a default browser available; that said, I have only tested this on Windows, so reach out if you have issues.

You will need to repeat the python script execution process for each Spotify User account that you will be using with the HA SpotifyPlus integration.

It is important to note that your Spotify login credentials are NOT saved as part of this process; only the token information returned by the Spotify OAuth2 authorization server is stored in the SpotifyPlus Token Cache file. This file will then be moved to your Home Assistant server once you have authorized all Spotify Login ID's that are used with SpotifyPlus.

To be clear, this is an inconvenient work-around for this issue; but after much trial and error, this is the only way that I could find to do this. I would much prefer to just login to Spotiify using the supplied username and password, but it seems that Spotify is transitioning away from username / password authentication to using OAuth2 authorization for third-party apps.

Requirements

  • SpotifyPlus integration (>= 1.0.49) is installed and properly configured.
  • the device in question natively supports the Spotify Connect ZeroConf API and utilizes the authorization_code token type.
  • It is recommended that you assign static ip addresses (via router DHCP reservation) to each of your Spotify Connect devices if you have not done so already.
  • ensure you have the Spotify Connect Device Username, Password, and LoginId values set.
  • Python version 3.11 or greater installed.
  • Knowledge of how to run a Python script.

Python Environment Setup Instructions

Use any of the following operating-specific instructions to create a new virtual environment for Python on your machine. This assumes that you already have Python 3.11 (or greater) installed and configured correctly. Note that the script requires Python 3.11 or greater.

Windows
  1. open a new MS-DOS prompt window (e.g. cmd.exe).
  2. execute the following command to create a new temporary directory:
    -> md tokengen
  3. execute the following command to switch to the temporary directory:
    -> cd tokengen
  4. execute the following command to create a new Python virtual environment. This allows us to install temporary packages, so that they are not installed to your permanent Python environment. Change the -3.11 to whatever version of Python you have installed.
    -> py -3.11 -m venv ./env
  5. execute the following command to switch to the virtual environment.
    -> env\Scripts\activate.bat
  6. execute the following to install script requirements.
    -> pip install spotifywebapipython
    -> pip install lxml
  7. proceed to the Token Creation Instructions.
MacOS, CentOS7, Debian, etc

Assumes pyenv is installed.

  1. open a new Terminal window.
  2. execute the following command to create a new temporary directory:
    -> mkdir tokengen
  3. execute the following command to switch to the temporary directory:
    -> cd tokengen
  4. execute the following commands to create a new Python virtual environment. This allows us to install temporary packages, so that they are not installed to your permanent Python environment.
    -> pyenv install 3.11 (optional - installs python 3.11 if not present)
    -> pyenv local 3.11 (switch local context to python version 3.11)
    -> python -m venv ./env311 (creates env311 virtual environment)
  5. execute the following command to switch to the virtual environment.
    -> source env311/bin/activate
  6. execute the following to install script requirements.
    -> pip install spotifywebapipython
    -> pip install lxml
  7. proceed to the Token Creation Instructions.

Token Creation Instructions

Prior to downloading the python script, ensure you have followed the instructions in the Python Environment Setup Instructions section of this document.

  1. Download the SpotifyPlus OAuth2 Authorization Token Updater for Spotify Python script to your temporary directory. Ensure that you do not rename the script to a common Python class name or reserved word (e.g. "token.py"), as it will cause issues when running the script. It's best to leave the name as AuthTokenGenerator.py.

  2. Open the script in your editor of choice (e.g. Notepad, etc).

  3. Modify the tokenProfileId variable; change the YourSpotifyLoginId value to your Spotify Login ID value (in canonical format). This value can be found by logging into the Spotify Developer web-site, and using the Get Current Users Profile page to retrieve the id value via the "Try It" functionality. This value is also the ending portion of your Spotify User URI (e.g. spotify:user:xxx, where xxx is the id value).

  4. Note the value of the tokenStorageDir variable. This variable contains the relative directory path of the Token Cache File. This directory will be created by the process, and will contain a spotifyplus_tokens.json file that contains the token(s) that are generated by this process. Default value is ./spotifyplus_tokendata.

  5. Save script changes and exit the editor.

  6. execute the python script, using the following command:
    NOTE - ensure you have switched to the virtual environment created in step 5 of the Python Environment Setup Instructions first.
    -> python AuthTokenGenerator.py Follow the prompts in the script console log.

  7. Once the script completes, repeat steps 1-6 for each Spotify Login ID that will be used with SpotifyPlus. The process will create one authorization access token per Login ID in the Token Cache file.

  8. Once all access tokens have been created, copy the spotifyplus_tokens.json file from the tokenStorageDir location (step 4, default is ./spotifyplus_tokendata) to your Home Assistant server configuration folder that contains SpotifyPlus integration data: ./config/.storage/spotifyplus_tokens.json.

  9. The process should now be complete, and the Python script and any temporary directories can be removed from your desktop machine. You do not have to reboot Home Assistant for these changes to take effect.

Testing

You can test the changes by simply selecting a Sonos device from the media player source list to transfer playback to the device.

You can also use the SpotifyPlus Player Transfer Playback service, specifying any Sonos device as the target device_id:

service: spotifyplus.player_transfer_playback
data:
  entity_id: media_player.spotifyplus_john_s
  device_id: "Sonos-Office"
  play: true
  refresh_device_list: true

It should transfer to the Sonos device, picking up where it left off from the source player. You can verify that Spotify Connect is the music source by starting the Sonos Dekstop App, and verifying that the device local queue is not in use - e.g. "Queue (not in use)".

Common Spotify Connect Issues

The following tries to document solutions to various common problems that arise when using devices that utilize Spotify Connect functionality.

Disappearing Device ID's

Regardless of whether you have a dynamic or static device id, the device id WILL disappear from the Spotify Web API available device list once the session or application has been shut down or a period of inactivity has passed (e.g. approximately 10 minutes). In this case, you need a way of "waking up" the device so that a Spotify Connect client will re-add it to the active device list.

Requirements

  • SpotifyPlus integration (>= 1.0.28) is installed and properly configured.
  • the device in question natively supports the Spotify Connect ZeroConf API. You will need to consult the manufacturer specifications of the device to determine if it supports Spotify Connect or not.
  • It is recommended that you assign static ip addresses (via router DHCP reservation) to each of your Spotify Connect devices if you have not done so already.
  • ensure you have the Spotify Connect Device Username and Password values set.

The Solution (for ALL devices)
The easiest way to solve this is to utilize the Player Activate Devices service. This service activates all static Spotify Connect player devices, and (optionally) switches the active user context to the current user context. Note that this will disconnect other users from all spotify connect player devices defined to the local network.

Example YAML

service: spotifyplus.player_activate_devices
data:
  entity_id: media_player.spotifyplus_john_s
  verify_user_context: true
  delay: 0.5

The Solution (for INDIVIDUAL devices)
Prior to re-connecting, we must discover details of the device using the SpotifyPlus ZeroConf Discover Devices service. This will return the various details that are used to call the ZeroConf Connect service, namely the ip address, port, and CPath of the device. Use the following service call to get that information:

service: spotifyplus.zeroconf_discover_devices
data:
  entity_id: media_player.YOUR_SPOTIFYPLUS_ENTITY_ID
  timeout: 2

This will generate a similar response like the following (abbreviated for brevity) for each device that supports Spotify Connect on your local network. In this example, I am only listing one device (my Bose ST-10):

user_profile:
  display_name: John Smith
  email: [email protected]
  id: 3758dfdsfjk435hjk6k79lm0n3c4
  product: premium
  ...
result:
  - DeviceName: Bose-ST10-1
    HostIpv4Address: 192.168.1.81
    HostIpPort: 8200
    SpotifyConnectCPath: /zc
    SpotifyConnectVersion: "1.0"
...

The key pieces of information that we want are:

  • HostIpv4Address - IPV4 address at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. '192.168.1.81').
  • HostIpPort - Port number at which the Spotify Connect Zeroconf API can be reached on the Spotify Connect device (e.g. 8200).
  • SpotifyConnectCPath - Spotify Connect Zeroconf API CPath property value (e.g. '/zc').
  • SpotifyConnectVersion - Spotify Connect Zeroconf API version number that the device supports (e.g. '1.0').

Armed with these four values, we can then issue a call to the SpotifyPlus ZeroConf Connect service to re-connect the device. In summary, this service causes the device to re-authenticate to Spotify Connect using supplied user credentials. You can also perform a user account switch if you have multiple Spotify accounts in play.

Use the following service call to re-connect the device. Note that you will need to change the entity_id, host_ipv4_address, host_ip_port, cpath, version to the equivalent values returned from the zeroconf_discover_devices call. You will also need to supply your Spotify user credentials (username, password) that you use to login to Spotify with.

The example for my Bose ST-10 looks like this:

service: spotifyplus.zeroconf_device_connect
data:
  entity_id: media_player.YOUR_SPOTIFYPLUS_ENTITY_ID
  host_ipv4_address: 192.168.1.81
  host_ip_port: 8200
  cpath: "/zc"
  version: "1"
  use_ssl: false
  username: [email protected]
  password: yourpassword
  pre_disconnect: true
  verify_device_list_entry: true

Once the zeroconf_device_connect completes, the device should appear in the device list of the Spotify Connect player client.

You can then issue a call to the Transfer Playback Service to transfer play to the Spotify Connect Player device name, like so:

service: spotifyplus.player_transfer_playback
data:
  entity_id: media_player.YOUR_SPOTIFYPLUS_ENTITY_ID  
  device_id: "Bose-ST10-1"  # Could also use device id if you want
  play: true
Clone this wiki locally