openHAB integration to Spotify Web Connect API (player)


(Patrick) #62

Correct, right now it only works by setting id. I haven’t merged the fuzzy search code in. Since the number of devices doesn’t change often and it’s easy to update the list of ids, I think this covers most use cases.

Good one re “explicit”. It should be possible but it may actually already be a setting inside Spotify. Did you check?

Yes, cron job, but again ponían Spotify API every 5 minutes around the clock seems exesssive.


(Bullet Proof Fool) #63

Yes, cron job, but again ponían Spotify API every 5 minutes around the clock seems exesssive.

I was thinking more like every 5 seconds!
Shame there’s not mqtt type setup for the spotify data…


(Patrick) #64

Yeah, every 5s sounds good IF music is playing … but not all day long. :frowning:


(Unparagoned) #65

What I did was just make a new IFTTT for my google echo which passes on the argument. So I say “Hey google spotify [args]” it runs spotify.py [args]. So say I want to play spotify using my pc speakers I’ll say “Hey Google spotify play PC”, which then runs spotify.py play PC. I’ts a bit awkward and you have to set up a rule to handle all the different commands. With Alex your have to have something like “Alexa turn on bathroom beats”, with custom rules, etc. If spotify is already playing then I just need to say “hey google spotify play/pause” and it will use the current device rather than the device receiving the command.

It would be really cool/amazing if we could access the media player commands for alexa/google to modify or create your own media player that is device sensitive, etc. I have seen a few things about this recently but not sure on the progress.


(Alan Fenwick) #66

Hi,

I’ve set up a simple switch which can be managed by Alexa (if I want) - I then run the .py regularly (every 10 seconds)
If someone starts anything using the echo ON the echo, within 10 seconds, a spotify update runs, identifies that the incorrect source is being used and then takes ownership of that spotify track - shifting the spotify to the correct target device (if the AV receiver that should be playing is not on, it also handles powering that up, changing to the correct source and shifting to the correct default volume)

The up (and down) side, is that my wife and children are now also able to drive the music in the house, without my ceiling mounted echo dot having to play tinny music, when I have a bucket load of proper AV gear around the house, waiting to be used.


(Alan Fenwick) #67

Hi Patrick, had a quick look @https://developer.spotify.com/web-api/get-the-users-currently-playing-track/

Explicit is brightly tagged: “explicit”: false,
You’re already grabbing the info, so just need an item to assign the data to and a minor addition to your .py script.

I won’t branch your code, since it is a minor update and my .py code is quite average.

Thanks again for the work on this - you’re a rockstar!

spotify.py

 self.oh.sendCommand('spotify_current_track', getJSONValue(resp, ['item','name']))
                self.oh.sendCommand('spotify_current_artist', getJSONValue(resp, ['item', 'artists', 0, 'name']))
                self.oh.sendCommand('spotify_current_cover', getJSONValue(resp, ['item', 'album', 'images', 1, 'url']))
                self.oh.sendCommand('spotify_current_duration', getJSONValue(resp, ['item', 'duration_ms']))
                self.oh.sendCommand('spotify_current_progress', getJSONValue(resp, ['progress_ms']))
                self.oh.sendCommand('spotify_current_playing', mapValues(getJSONValue(resp, ['is_playing']), { 'True': 'ON', 'False': 'OFF' }))
                self.oh.sendCommand('spotify_current_device', getJSONValue(resp, ['device', 'name']))
                self.oh.sendCommand('spotify_current_volume', getJSONValue(resp, ['device', 'volume_percent']))
                self.oh.sendCommand('spotify_current_context_uri', getJSONValue(resp, ['context', 'uri']))
                self.oh.sendCommand('spotify_current_device_id', getJSONValue(resp, ['device', 'id']))
                self.oh.sendCommand('spotify_current_playing_explicit', mapValues(getJSONValue(resp, ['item', 'explicit']), {'True': 'ON', 'False': 'OFF' }))

and

*.items

 /* Strings to store Player Data */
String spotify_current_track
String spotify_current_artist
String spotify_current_cover
String spotify_current_duration
String spotify_current_progress
Number spotify_current_progress_percent
Switch spotify_current_playing

Switch spotify_current_playing_explicit

TESTED - WORKS - can’t see much else to change.
Since I regularly poll spotify whilst running audio through the house, I’ll be able to filter explicit tracks from my darling children … In addition to the already running Nicky Minaj filter!


(Kim Eide) #68

Invalid client id it says… Anyone?

Successfully got state from OpenHab: spotify_client_id
Successfully got state from OpenHab: spotify_client_secret
Successfully got state from OpenHab: spotify_access_token
Successfully got state from OpenHab: spotify_refresh_token
Successfully got state from OpenHab: spotify_token_issued
Successfully got state from OpenHab: spotify_token_expiry
– Calling Token Refresh Service
{‘Content-Length’: ‘63’, ‘Keep-Alive’: ‘timeout=600’, ‘Server’: ‘nginx’, ‘Connection’: ‘keep-alive’, ‘Date’: ‘Wed, 06 Sep 2017 06:30:19 GMT’, ‘Content-Type’: ‘application/json’}
{u’error_description’: u’Invalid client’, u’error’: u’invalid_client’}
Successfully got state from OpenHab: spotify_auth_code
– Calling Token Service for the first time
{‘Content-Length’: ‘63’, ‘Keep-Alive’: ‘timeout=600’, ‘Server’: ‘nginx’, ‘Connection’: ‘keep-alive’, ‘Date’: ‘Wed, 06 Sep 2017 06:30:19 GMT’, ‘Content-Type’: ‘application/json’}
{u’error_description’: u’Invalid client’, u’error’: u’invalid_client’}
– Calling Service: Update
{u’error’: {u’status’: 401, u’message’: u’Invalid access token’}}
-> Item node missing from response :frowning:
Successfully posted state to OpenHab: spotify_lastConnectionDateTime = 2017-09-06T06:30:19+0000
Done in 1.25276994705 seconds


(Pablo Melendez Trivick) #69

Hello everyone, I can not understand how to add spotify to my panel …

I already do the authentication and everything is correct.
But I am still inexperienced and I want to learn how to visualize it in my HABpanel, what should I do?

Add button?
Add Chart?

If someone is so kind I can send the widget because I really do not understand.

regards.


(Pablo Melendez Trivick) #70

Hi everyone again, I know I’ve been a little annoyed asking for help but I have already advanced part of the study.

now I want to know how to delete everything except spotify, is there any program to edit these codes?

Saludos.


(Pablo Melendez Trivick) #71

i did it

now I need to order, can anyone help me with that?.
add the artist

I am excited, to know nothing to learn a little bit in a short time.

Thx.


(Jonas) #72

Hi all! I followed the instructions but on point 7 (test spotify.py in ssh) it gives me a failure after calling service: update.:
-> Failure: <type ‘exceptions.ValueError’>
can you help me?
on the spotify developers site i did not paste http://openhabianpi.local:8080/static/spotify-auth.html but http://IPADRESSOFMYPI:8080/static/spotify-auth.html because it did not work the other way. i tried both in the spotify.py but i got no luck.

To which value do i have to set the redirect_uri in the spotify.py?

in the doc is written:

  • OpenHab 2.1 installed on Raspberry Pi (or similar)
  • OpenHab REST installed
  • Spotify User Account
  • Spotify Developer Account
  • The script uses OpenHab items to store parameters and credentials. Make sure you have persistance turned on, otherwise all your settingd are lost upon reboot/restart
  • Know your OpenHab root URL/IP and port. In this doc, I assume http://openhabianpi.local:8080/. -> where to put the root? i did http://myip:8080. is this right or do i have to add etc/openhab2 to this url?

how do i have to turn on persistance? i found the menu entry in my paperui and it’s empty. is it turned off or just set to an initial value?


(Jonas) #73

Hi! I got it working now - at least once. after a reboot my data is gone. How do i activate “persistance”? can you link me to a tutorial or make a short explanation, please?

thank you!


(Jonas) #74

hello. i found this and got it working:


As i can see it saves items (in the provided example), so the spotify_client_id and secret should be stored. it does not work for me … after each restart i have to write the values into these 2 items manually to get it working. do i have to add anything else to the persistence file?


(Lorenzo Giordano) #75

Hi Bullet.
I get the same error. I can’t understand what is the right value to set the REDIRECT_URI.
Thanks
Lorenzo


(Lorenzo Giordano) #76

Just one more info.
I get the “import requests” error while in Habpanel

10:58:20.255 [INFO ] [lipse.smarthome.model.script.Spotify] - Traceback (most recent call last):
  File "/etc/openhab2/scripts/spotify.py", line 6, in <module>
    import requests

The Happanel items are not updated, while If I send the command from terminal work propely and the item are correctly updated ?!?

I tried to launch other python script from habpanel but I got the same error !!
maybe any permission issue?

Thanks for your help


(Andrew Pawelski) #77

Hi is there a way to get a list of my playlists and then dynamically fill a listbox or modal windows?


(Alan Fenwick) #78

UPDATED - this works just great :slight_smile:


(Bas) #79

@pmpkk First of all, thanks for your work on your fantastic ‘matrix’ theme, really nice theme and also a great starting point for me to learn how to customize my own panels/themes.

I also installed your spotify script to enable Spotify playback from HABPanel and it’s working great so far. The only thing I cannot seem to get to work (but this is probably related to the Spotify API) is to get access to my different devices for playback.

I have several Sonos speakers in my house, a spotify client on my Windows PC and several mobile devices with a Spotify app. When I query my devices using the ‘spotify.py’ script I cannot see any of my devices - this is not a problem of the script, when I try the Spotify API web console I get the same result. The permissions are okay (scope) and my access key is also working, but I just cannot see my Sonos devices…

Did you have to perform some additional task to get the Sonos devices to show?

EDIT: To elaborate, when I see the Sonos player data from the Spotify API return, it doesn’t show a device_id (NULL), only a device name.

Successfully posted state to OpenHab: spotify_current_track = Sfumato - Kerri Chandler Remix
Successfully posted state to OpenHab: spotify_current_artist = Matthias Tanzmann
Successfully posted state to OpenHab: spotify_current_cover = https://i.scdn.co/image/17aa60d54abd913270aba8680840ae43c2f237d6
Successfully posted state to OpenHab: spotify_current_duration = 432286
Successfully posted state to OpenHab: spotify_current_progress = 132958
Successfully posted state to OpenHab: spotify_current_playing = ON
Successfully posted state to OpenHab: spotify_current_device = Office
Successfully posted state to OpenHab: spotify_current_volume = 12
Successfully posted state to OpenHab: spotify_current_context_uri =     spotify:user:spotify:playlist:37i9dQZF1DX2TRYkJECvfC
Successfully posted state to OpenHab: spotify_current_device_id = NULL
Successfully posted state to OpenHab: spotify_current_progress_percent = 30.76
 -> Success
Successfully posted state to OpenHab: spotify_lastConnectionDateTime = 2017-09-20T19:05:28+0000
Done in 0.819099903107 seconds

Additionally, when I open a Chrome tab and use the Spotify Web Player, it does show up as a ‘device’ and I can control it using the widget…

Hope you can help!


(Andrew Pawelski) #80

can you share your rule for the update?
is it correct that the progress bar is not updating every second - only on a refresh?


(Alan Fenwick) #81

Hi Andrew,

The status only updates when you execute the .py script again.
I’ve been running mine every 10 seconds for a couple of weeks without issue.

On email, please IGNORE formatting for now

var Timer spotifyTimer = null
rule "Monitor Spotify and move from Echo"
when Item Track_Spotify changed from OFF to ON then
if (spotifyTimer == null)
{
logInfo(“spotifyTimer”, “Schedule timer”)
spotifyTimer = createTimer(now.plusSeconds(10))
[|
// Run your code here
if (Track_Spotify.state == ON)
{

// logInfo(“spotifyTimer”, “Update spotify data and Reschedule timer - Track_Spotify Switch is still ON”)
var resp = executeCommandLine("/usr/bin/python /etc/openhab2/scripts/spotify.py",5000)
if(spotify_current_device.state == “EchoGround” || spotify_current_device.state == “Speakers”){
if(spotify_current_playing_explicit.state == ON){
var resp =1 executeCommandLine("/usr/bin/python /etc/openhab2/scripts/spotify.py next", 5000)
}
if(spotify_current_playing.state == ON){
if(TXNR636GROUND_Zone1_Power.state != ON ){
sendCommand(TXNR636GROUND_Zone1_Power, ON)
sendCommand(TXNR636GROUND_Zone1_Volume, 30)
sendCommand(TXNR636GROUND_Zone2_Power, ON)
sendCommand(TXNR636GROUND_Zone2_Volume, 30)
sendCommand(TXNR636_Zone1_InputSource, 01)
}
if(spotify_current_device.state == “EchoGround”){
logInfo(“WARNING”,“Spotify running on Alexa - yuck . . .move house: " + spotify_current_device)
sendNotification("foo@bar.com”,“Yuck - Spotify on Alexa - migrate!”)
sendCommand(spotify_current_device_id, “81d0483c678992da4554903fc16af85aaaaaaaa”);
var resp = executeCommandLine("/usr/bin/python /etc/openhab2/scripts/spotify.py transfer_playback",5000)
}
}
}

spotifyTimer.reschedule(now.plusSeconds(10))
}
]
}
else
{
// this should not be possible, Sample Rule2 should
prevent this
logInfo(“spotifyTimer”, “Reschedule timer”)
spotifyTimer.reschedule(now.plusSeconds(10))
}
end rule “Monitor Spotify and move from Echo cleanup” when Item
Track_Spotify changed from ON to OFF then
if(spotifyTimer != null)
{
sendNotification("foo@bar.com", “Openhab Spotify Scheduler switched OFF!”)
logInfo(“spotifyTimer”, “Cancel timer”)
spotifyTimer.cancel
spotifyTimer = null
}
end

Obviously edit to manage your AV gear etc.
Track_Spotify is a dummy switch to manage whether the rule runs, I’m about to change that so it only runs when my nest says I am home.

Let me know how you get on.