Controlling Spotify via Home Assistant
You might have seen my previous article on turning a switch into a Zigbee device (Spaceballs! — The Switch). Concord Aerospace recently released a new switch called Fortunate Son.
I wanted to make it also functional and to do, well, what is says on the box. Since I’m operating via Zigbee and paired with Home Assistant, I wanted a Home Assistant automation to be able to trigger actions based on this on my PC and control Spotify (and possibly some other things in the future as well).
You can achieve this in two different ways, use the Home Assistant Spotify integration or use HASS agent to run arbitrary commands on your PC:
HASS agent doesn’t directly have support for Spotify and Spotify’s client on Windows doesn’t unfortunately support command line parameters in a way that would be useful for us (nor it has support for D-Bus like on Linux).
So the workflow we can set up is:
- Zigbee switch signals its state towards Home Assistant
- Automation triggers based on switch going from on to off or vice versa
- Home Assistant sends a custom HASS agent command to a MQTT broker (I use the Mosquitto broker installed on Home Assistant)
- HASS agent picks up the command on the PC and executes a PowerShell script
There are some recipes floating around online on controlling Spotify on Windows via WMI, but it didn’t seem to be a very robust solution. So I turned towards PowerShell as it’s a fairly easy way to add some scripting on Windows. There are a few PowerShell modules for Spotify, but they don’t seem to be very recently updated, except for lennyomg/Spotify-PowerShell
.
To make everything work, you’ll need to do the following:
- Install HASS agent on the PC and configure it to work with Home Assistant,
- Install HASS agent add on to Home Assistant,
- Create your application on developer.spotify.com (remember to follow instructions from the Spotify-PowerShell module),
- Initialize the connection between your PC and Spotify’s API,
- Configure automations in Home Assistant to trigger the custom commands in HASS agent,
As there is nothing particular special about steps 1 to 3, we’ll skip straight to step 4. But before, we did install PowerShell 7 via WinGet:
winget install --id Microsoft.PowerShell --source winget
After installation, we should have the PowerShell binary at C:\Program Files\PowerShell\7\pwsh.exe
. We can start a PowerShell session and set up the initial connection. Have your Spotify app client ID handy and run:
Import-Module Spotify
New-SpotifyAccessToken -ClientId "123456789...abcdef" -Scope "app-remote-control", "streaming", "user-read-playback-state", "user-modify-playback-state"
Open the URL and copy the command from the text box you receive afterwards into PowerShell and execute it.
Now we’ll use the following script (also Gist available here, which has extended features like playlists and shuffle) that we will play in our home directory (eg. C:\Users\yourusername\
):
Param
(
[Parameter(Position=0)]
[ValidateSet('play', 'stop')]
[String]
$Operation = $(throw "Operation is required (play or stop)."),
[alias("Device")]
[String]
$DeviceName = $env:COMPUTERNAME,
[String]
$Track = "spotify:track:4BP3uh0hFLFRb5cjsgLqDh",
[String]
$SpotifyExe = "spotify:" # UWP apps are launched through URL scheme
)
Import-Module Spotify
# Update the access token
Update-SpotifyAccessToken
# Check if Spotify is running, if not, start it
if ((Get-Process "Spotify" -ErrorAction SilentlyContinue) -eq $Null) {
Start-Process -FilePath $SpotifyExe
}
$DeviceId = $null
$Attempt = 0
do {
Get-SpotifyDevices | ForEach-Object {
if ($_.name -eq $DeviceName) {
$DeviceId = $_.id
}
}
if ($DeviceId -eq $null) {
# If the device isn't here yet, wait for 20 seconds until it appears
Start-Sleep -Seconds 2
$Attempt++
} else {
break
}
} while ($Attempt -lt 10)
if ($DeviceId -eq $null) {
throw "Unable to find Spotify device: $DeviceName"
}
switch ($Operation) {
"play" {
Start-SpotifyPlayback -TrackUri $Track -DeviceId $DeviceId
}
"stop" {
Suspend-SpotifyPlayback -DeviceId $DeviceId
}
}
The default use is simple, simply run the script with play
or stop
argument and it’ll start up Spotify, if it’s not already running and start playing the track. You can set device and track ID via Device
and Track
parameters.
Finally, we will add two custom commands to HASS:
For the command, we will use these:
To play:
"C:\Program Files\PowerShell\7\pwsh.exe" "C:\Users\yourusername\fortunate-son.ps1" play
To stop:
"C:\Program Files\PowerShell\7\pwsh.exe" "C:\Users\yourusername\fortunate-son.ps1" stop
You should now be able to trigger these commands from Home Assistant and watch the magic at work:
That’s it, hopefully this was useful!