Skip to content

Device Configuration Options

Todd Lucas edited this page Dec 12, 2024 · 82 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).
    Note - if you don't see the SpotifyPlus entry in the list, then it denotes that a problem occured with the HACS installation (e.g. failed, HA was not restarted, browser cache was not cleared, etc). Note that the SpotifyPlus integration will appear at the bottom of the list if you did not reboot Home Assistant after the HACS installation.
  • 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 LoginId

This option contains the Spotify Connect canonical login ID (e.g. 3758dfdsfjk435hjk6k79lm0n3c4, 1257898300, etc) used to login to a Spotify Connect device. This MUST be the canonical equivalent value of the spotifyConnectUsername value. Note that for some Spotify accounts, the LoginId and Username values are the same. Not sure why that is, as it's a Spotify internals kind of thing.

The LoginId value can easily be found using the Spotify Developer Web portal, using the Get Current Users profile service. Click on the Try It button, then find the id response value.

This option is required when activating Spotify Connect devices (including librespot).

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. Note that for some Spotify accounts, the LoginId and Username values are the same. Not sure why that is, as it's a Spotify internals kind of thing.

This option is required when activating Spotify Connect devices that utilize a user-id and password authorization parameters.

This option is not required when activating Spotify Connect devices that utilize the librespot application.

Spotify Connect Device Password

This option contains the Spotify Connect password used to login to a Spotify Connect device.

This option is required when activating Spotify Connect devices that utilize a user-id and password authorization parameters.

This option is not required when activating Spotify Connect devices that utilize the librespot application.

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 Polling Scan Interval

This option specifies the polling scan interval (in seconds) used to query Spotify Player playstate. Value entered must be in the range of 4 to 60 (seconds). If not specified, the polling interval is set to 30 seconds. It is highly recommended that you use the default value (e.g. 30 seconds) for this option; use a lower value (e.g. 5 seconds) if you control the Spotify Player from another application besides Home Assistant (e.g. Spotify Mobile) and want Home Assistant to recognize Spotify Player state changes faster.

A higher value equates to slower detection of Spotify player updates made outside of Home Assistant, but also decreases network bandwidth. As an example, let's say you set the value to 30 seconds. This would generate 2,880 requests per day to the Spotify Web API for player updates (e.g. 2 requests per minute; 120 requests per hour; 2,880 requests per day).

A lower value equates to faster detection of Spotify player updates made outside of Home Assistant, but also increases network bandwidth. It could also get you rate-limited by Spotify, depending on how much other data you are retrieving via the Spotify Web API. As an example, let's say you set the polling scan interval to 5 seconds. This would generate 17,280 requests per day to the Spotify Web API for player updates (e.g. 12 requests per minute; 720 requests per hour; 17,280 requests per day).

Note

The Spotify Web API will not be polled when the media player is turned off - this is by design. It reduces traffic on your local network, as well as the extra load placed on Spotify Web API servers (and your Home Assistant instance) that service the polling request.

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

You can ignore this section if you don't utilize OAuth2 Token functionality, which currently only applies to Sonos devices that support Spotify Connect.

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.

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.65) 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 to the virtual environment.
    -> 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 to the virtual environment.
    -> 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 tokenStorageFile variable. This variable contains the name of the Token Cache File (e.g. spotifyplus_tokens.json), and will contain the token(s) that are generated by this process. This file will be created in the current directory from where the script is ran.

  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 Token Cache File (e.g. spotifyplus_tokens.json) from the script current directory to your Home Assistant server configuration directory that contains persistent storage data.

    Use the How to find the HA configuration directory instructions for how to locate the Home Assistant configuration directory, then the .storage directory will be located beneath it. Here are a few examples of where that may be located on your installation of HA:

    • Home Assistant Operating System (config directory of the installation)
      /config/.storage/
    • Home Assistant Container (config directory that you mounted in your container)
      /mnt/data/supervisor/homeassistant/.storage/
    • Home Assistant Core (config directory passed to the hass command)
      ~/.homeassistant/.storage/

    Please note that file paths are case-sensitive on some operating systems.

  9. The process should now be complete. 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)".

librespot Device Support

You can ignore this section if you don't utilize librespot, spotifyD, or Spotify Connect AddOn services.

The integration supports Spotify Connect devices that are hosted by applications that utilize the librespot library for playback control (e.g. spotifyd, Spotify Connect AddOn, etc).

The application must utilize librespot discovery mode, so that it will advertise its available Spotify Connect device(s) via the Zeroconf / mDNS protocol. The integration does not support librespot applications that utilize the non-discovery mode of librespot. If not ran in "discovery mode", the Spotify Connect device(s) will not be registered to Zeroconf and the integration will not be able to find the device(s).

You must also generate a librespot credentials.json file that contains cached Spotify credentials. The contents of this file will not change, unless you change your Spotify password.

The location of the file can vary depending on the application that you are using - refer to the following topics for application-specific details:

SpotifyPlus librespot Credentials File

Once you have a librespot credentials file (or files), you can then proceed to create the spotifywebapiPython librespot credentials file. How that file is created is determined by the number of Spotify accounts that will be accessed by the SpotifyPlus integration.

The SpotifyPlus integration utilizes the spotifywebapiPython library to connect to a Spotify Connect enabled device. The spotifywebapiPython library will load librespot credentials from a file named SpotifyWebApiPython_librespot_credentials.json, also know as the SpotifyPlus librespot Credentials File. To be clear, the SpotifyPlus librespot Credentials File and the librespot credentials file are two different files, even though they may contain the same contents.

The SpotifyPlus librespot Credentials File format is determined by how many Spotify accounts you will be using with the SpotifyPlus integration (e.g. single user vs multi user). The librespot credentials.json file format only supports a single user format (e.g. 1 credential per file). The SpotifyPlus librespot Credentials File format supports both single user (e.g. 1 credential per file) and multiple users (e.g. 1+ credentials per file).

If you only have 1 Spotify account that will be using the integration, then you will want to utilize the single user credential format for the spotifywebapiPython librespot credentials file.

If you have more than 1 Spotify account that will be using the integration, then you will want to utilize the multiple user credential format for the spotifywebapiPython librespot credentials file.

Credentials File Location

The SpotifyPlus librespot Credentials File is located in the Home Assistant configuration directory's persistent storage data sub-directory (e.g. <configuration directory>\.storage).

Use the How to find the HA configuration directory instructions for how to locate the Home Assistant configuration directory, then the .storage directory will be located beneath it. Here are a few examples of where that may be located on your installation of HA:

  • Home Assistant Operating System (config directory of the installation)
    /config/.storage/
  • Home Assistant Container (config directory that you mounted in your container)
    /mnt/data/supervisor/homeassistant/.storage/
  • Home Assistant Core (config directory passed to the hass command)
    ~/.homeassistant/.storage/

Please note that file paths are case-sensitive on some operating systems.

If using the File editor or Filebrowser addons to modify the credentials file, you must enable configuration options that allow you to view hidden directories in the file system. This is due to the HA-specific .storage location. Consult the addon documentation for instructions on how to enable these features.

Note that if your Spotify account password changes, you must re-generate the librespot credentials file and update the SpotifyPlus librespot Credentials File with the new authorization credentials.

Single User Credential Format

For single user accounts, you can simply copy the librespot credentials.json to the SpotifyWebApiPython_librespot_credentials.json file; the single user credential format is the same format as the librespot credentials.json format. The spotifywebapiPython package understands this format, and it will read the file "as-is" without modifications.

The single credential file format is organized as follows:

{
  "username": "31l77xxxxxxxxxxxxxxxxxxxxxxx",
  "auth_type": 1,
  "auth_data": "QVFET2h6 ... aFp3OHg="
}

Multiple User Credential Format

For multiple user accounts, you must combine the contents of individual librespot credentials.json files (1 file per user account) into a single spotifywebapiPython SpotifyWebApiPython_librespot_credentials.json file.

The multi-credential file format is organized as follows:

[
  {
    "username": "31l77xxxxxxxxxxxxxxxxxxxxxxx",
    "auth_type": 1,
    "auth_data": "QVFET2h6 ... aFp3OHg="
  },
  {
    "username": "31dg6xxxxxxxxxxxxxxxxxxxxxxx",
    "auth_type": 1,
    "auth_data": "QVFET2h6 ... aFp3OHg="
  }
  ...
]

Note the similarities to the single user format; the multi-user format is simply an array of single user format credentials (e.g. starting bracket [, ending bracket ], and comma , separator between credentials).

With this format, you can add as many user credentials that you need.

Requirements

librespot Helpful Links

The following topics discuss how to generate the credentials.json file for various applications that utilize librespot.

Snapcast Server librespot Support

Snapcast can use the librespot stream source to authenticate to Spotify and control the player. These instructions are for the librespot stream source, and will not work for other Snapcast server stream sources.

The snapcast server librespot stream sources must be ran in "discovery mode", which will advertise them as Spotify Connect devices to the local network. This means that you cannot use the following options in the librespot stream source configuration: username, password. If configured correctly, you should see the line no usable credentials found, enabling discovery in the snapcast server logs.

When ran in "dicovery mode", the snapcast server will store the librespot credentials.json file to the location specified by the "cache" librespot configuration parameter (e.g. /tmp/snapserver-cache/credentials.json).

After you generate the librespot credentials file, you must make a copy of it and place it in the Home Assistant storage directory so that the SpotifyPlus integration can access it. This is required, as the SpotifyPlus integration is not able to access the librespot credentials file from where it resides on whatever server is hosting your librespot application.

Use the following steps to generate the librespot credentials file for the snapserver service.

  1. Edit the /etc/snapserver.conf to add the cache parameter to one of your defined librespot stream source devices (which Snapcast calls a "source"). Note that this only needs to be done for a single device, as it is assumed that the same credentials are used across multiple devices.

    Example:
    source = spotify:///librespot?bitrate=320&devicename=All Speakers&cache=/tmp/snapserver-cache

  2. Restart the Snapcast server.
    sudo systemctl restart snapserver

  3. Connect with any of the official Spotify clients (e.g. Mobile, Desktop, etc) to the Snapcast device that you configured the cache for (in step 1). In this example, it's "All Speakers".

  4. Revert the change in /etc/snapserver.conf and restart the server again.
    source = spotify:///librespot?bitrate=320&devicename=All Speakers
    sudo systemctl restart snapserver

At this point, you should have a valid librespot credentials.json file, located in the cache path; in this example it's /tmp/snapserver-cache/credentials.json, as specified in step 1.

Please refer to the SpotifyPlus librespot Credentials File topic for further instructions on how to utilize the librespot credentials with the integration.

Snapcast Server Helpful Links

SpoCon Service librespot Support

SpoCon is a Spotify Connect for Debian package and associated repository which thinly wraps the librespot-java library. It works out of the box on all three revisions of the Pi, immediately after installation.

Adjust your SpoCon /opt/spocon/config.toml configuration settings to use the following options for librespot Zeroconf authentication:

# Spotify Connect device name and info
deviceName = "My-Spocon"
deviceType = "COMPUTER" 
preferredLocale = "en"

[auth] # use zeroconf authentication (no username, password, blob)
strategy = "ZEROCONF"

[zeroconf] # listen on all interfaces, and bind to specific port 8600
listenPort = 8600
listenAll = true

[cache] # enable cache path for librespot auth credentials
enabled = true
dir = "./cache/"
doCleanUp = true

That should force SpoCon to advertise itself via Zeroconf / mdns on port 8600. I just picked 8600 out of the blue, you can choose whatever port you want. I like a dedicated (vs random) port, in case you need to open firewalls. If you do have to open firewalls, open activity for 8600 TCP and 5353 UDP (mdns advertise).

I would also avoid spaces in the deviceName parameter, as some Spotify Clients have issues with handling spaces in the name.

You must also enable the [cache] settings section so that librespot can store its credentials.json file. This file contains the authorization credentials that are sent from the Spotify client, which will be used by the SpotifyPlus integration.

Use the following steps to generate the librespot credentials file for the SpoCon service.

  1. Edit the SpoCon /opt/spocon/config.toml configuration settings as described above. Zeroconf discovery mode should be enabled, and cache enabled with a specified directory.

  2. Restart the SpoCon service to apply configuration settings.
    sudo systemctl restart spocon

  3. Connect with any of the official Spotify clients (e.g. Desktop, Mobile, etc) to the configured SpoCon device. In this example, it's "My-Spocon".

At this point, you should have a valid librespot credentials.json file, located in the cache directory. In this example, it's ./cache/credentials.json.

Please refer to the SpotifyPlus librespot Credentials File topic for further instructions on how to utilize the librespot credentials with the integration.

Snapcast Server Helpful Links

spotifyd Service librespot Support

The spotifyd Service uses librespot to authenticate to Spotify and control the player. The service must be ran in "discovery mode", which will advertise itself as a Spotify Connect device to the local network. This means that you cannot use the following options in the service configuration options: username, username_cmd, password. If configured correctly, you should see the line no usable credentials found, enabling discovery in the spotifyd service logs.

When ran in "dicovery mode", the spotifyd service will store the librespot credentials.json file to the location specified by the CACHE_PATH configuration setting (e.g. /home/<user>/.cache/spotifyd/credentials.json).

After you generate the librespot credentials file, you must make a copy of it and place it in the Home Assistant storage directory so that the SpotifyPlus integration can access it. This is required, as the SpotifyPlus integration is not able to access the librespot credentials file from where it resides on whatever server is hosting your spotifyd service.

Use the following steps to generate the librespot credentials file for the spotifyd service.

  1. Set cache_path to a writable directory (e.g. /home/<user>/.cache/spotifyd).

  2. Start spotifyd in discovery mode (by commenting all the username, username_cmd, password options). You should see the line no usable credentials found, enabling discovery in the spotifyd logs.

  3. Connect with any of the official Spotify clients to spotifyd (which has to be on the same network), and start playing a track.

  4. Stop spotifyd. Make sure that in the cache directory that you set before, there is now a file called credentials.json.

At this point, you should have a valid librespot credentials.json file, located in the cache path; in this example it's /home/<user>/.cache/spotifyd/credentials.json, as specified in step 1.

Please refer to the SpotifyPlus librespot Credentials File topic for further instructions on how to utilize the librespot credentials with the integration.

spotifyd Service Helpful Links

Spotify Connect AddOn librespot Support

The Spotify Connect AddOn utilizes the spotifyd service, which in turn uses librespot to authenticate to Spotify and control the player. As of 2024/08, the Spotify Connect AddOn can no longer authenticate using the username and password configuration options; you must initiate player control from a Spotify Client (mobile, desktop, etc), and then the player can be controlled from Home Assistant. This is a big limitation, as it restricts you from starting the Spotify player directly from HA.

There is a workaround for this limitation, and that is to copy the librespot authorization credentials to a file which can then be used by SpotifyPlus to authenticate to Spotify. The integration will then pass the credentials on to the Spotify Connect Zeroconf addUser endpoint to authenticate to Spotify. This is the same way the official Spotify apps do it, but they store the credentials on their own file systems.

See the librespot-auth Credentials Generator topic below for detailed instructions on how to generate the librespot credentials.json file.

Spotify Connect AddOn Helpful Links

librespot Credentials Generator

librespot-auth is a simple program for populating a credentials.json file via Spotify's Zeroconf authentication. It was developed by Dominic Pearson, and is hosted on the librespot-auth Credentials Generator GitHub repository.

This program is useful in cases where you run librespot on remote hosts on a different network (thus complicating Zeroconf). As of version 3.203.235 of the Spotify eSDK, the SpConnectionLoginPassword API has been removed.

This program only needs to be ran initially, or whenever you change your Spotify password.

How librespot-auth Works

While running on the same network as a Spotify client, it should appear as a Spotify Connect device with the given name. Select it once as an output device, and the Spotify client will transmit the required authentication blob. This blob is received by the application, written to the specified credentials path, and the application immediately exits.

librespot-auth Command-Line Arguments

  • --name - Spotify Connect device name (default: "Speaker"). Note that the name is not saved with the authorization credentials. You should also avoid using spaces in the name, as some Spotify clients have trouble with spaces in the name.
  • --path - Target path for credentials file (default: credentials.json, relative to execution current directory).
  • --class - Spotify Connect device class (default is "speaker"). Valid values are: computer, tablet, smartphone, speaker, tv, avr, stb, audiodongle, gameconsole, castaudio, castvideo, automobile, smartwatch, chromebook, carthing, homething. Some users have pointed out that if you select a device type of class computer then premium is not required.

How To Build librespot-auth

The source code is written in the Rust programming language, so you must have the Rust compiler installed to build it. Check out the rust toolchain site for more information on how to install the Rust compiler if required.

IMPORTANT - this should be done from a machine on the same network where you run your Spotify client (e.g. Spotify Desktop) from, ensuring no proxy is in use that may interfere with Zeroconf connectivity.

Use the following steps to clone the repository to your local workspace, and build the binary executable.

  1. open a new terminal window on Linux. This should run on any flavor of Linux; I personally use Windows 11 WSL Debian for mine, but I'm a Windows guy (don't hate me :) ).

  2. clone the librespot-auth github repository to your local machine.
    git clone https://github.com/dspearson/librespot-auth

  3. change directory to the cloned repository.
    cd librespot-auth

  4. build the library.
    cargo build --release

How To Execute librespot-auth

Use the following steps to execute the program. It should be ran from the same location where you built the binary using the How To Build librespot-auth instructions.

  1. execute the program.
    ./target/release/librespot-auth --name "Librespot-Auth" --class=computer

    You should see the following console message:
    Open Spotify and select output device: Librespot-Auth

  2. Open the Spotify Desktop client from a machine on the same network as you ran this, ensuring no proxy is in use that may interfere with zeroconf. Note that the Spotify Mobile client does not find devices immediately like the Spotify Desktop client does. It is suggested that you use the Spotify Desktop client for this process.

  3. Use the Spotify client "Connect to a Device" menu to select the Librespot-Auth device name that you specified on the command-line in step 1 (or whatever you chose as the device name using the --name command-line option).

  4. The credentials are then saved to credentials.json in the provided path (using the --path command-line option).

    You should see the following console message:
    Credentials saved: credentials.json

    The tool should then exit, returning control back to the command prompt.

At this point, you should have a valid librespot credentials.json file, located in the listed Credentials saved path.

Please refer to the SpotifyPlus librespot Credentials File topic for further instructions on how to utilize the librespot credentials with the integration.

Spotify Password Changes

Use the following checklist when updating your Spotify Password. These are various places that your Spotify credentials could be specified in / indirectly accessed from.

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