-
Notifications
You must be signed in to change notification settings - Fork 0
/
musicBox.py
493 lines (365 loc) · 12.9 KB
/
musicBox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!/usr/bin/env python3
####
# Setup
# pip3 install beautifulsoup4
# pip3 install soco
# pip3 install pysftp
# manually install the raspberry pi pn532 python package. Get that from https://www.waveshare.com/wiki/PN532_NFC_HAT#Resources
#
# Buy some CD jewel cases from Amazon. I used the thin ones.
# Make album art with https://pixlr.com/
# Use Apple Music to create PDF templates of album art
# buy these magnets: https://www.kjmagnetics.com/proddetail.asp?prod=DA1
# glue magnets in the jewel cases and in your container for the pi/NFC reader
#
# I used https://en.makercase.com/ to generate an SVG for lasercutting a box to house the pi/NFC reader
####
#### TODO's ####
# General
# + play a Spotify playlist (http://docs.python-soco.com/en/latest/api/soco.plugins.sharelink.html or https://github.com/avantrec/soco-cli#albums-and-playlists)
# + play a Spotify song
# + determine whether it's pandora/spotify then do the right thing
# + get speaker groupings working
# + replace for loop discovery with http://docs.python-soco.com/en/latest/api/soco.discovery.html
# + periodically sync databases
# + Make an improvementin setSpeakerGroup to avoid unnecessary joining and unjoining
# + Refactor setSpeakerGroup
# NFC stuff: https://www.waveshare.com/wiki/PN532_NFC_HAT#Resources
# + read NFC tag
# + add NFC tags to playlist db
# - special NFC tag to trigger a manually db sync (probably not going to do this)
from operator import truediv
import threading
import time #this is only used for debug and SyncSchedule. If you aren't using SyncSchedule, this can be removed.
# import os
import sys
## Control the Sonos with python: https://github.com/SoCo/SoCo
import soco
from soco.snapshot import Snapshot
from soco.plugins import sharelink
#Scrape webserver to sync the database
from bs4 import BeautifulSoup
import requests
# NFC Reader
import RPi.GPIO as GPIO
from pn532 import *
defaultSpeakerGroup = ["Kitchen", "Living Room"]
speakerGroup = ["Kitchen", "Living Room"] # the Sonos names of the speakers you want to use
databaseFile = "database.txt" # name of the local database text file
# You could remove remoteDB code out if you don't want to sync multiple devices/sync db off your raspberry pi.
remoteDBUrl = 'https://zaccohn.com/misc/audio/musicbox/database.txt' #URL of the remote database text file.
defaultVolume = 20
# Uncomment when there are multiple devices to keep in sync with remote database
# also uncomment the line in main()
# class SyncSchedule(object):
# def __init__(self, interval=1):
# self.interval = interval
# thread = threading.Thread(target=self.run, args=())
# thread.daemon = True
# thread.start()
# def run(self):
# # sync every 4 hours
# seconds = 14400
# while True:
# time.sleep(seconds)
# syncWithRemoteDB()
# print("going to sleep for " + str(seconds) + " seconds.")
class NFCReader(object):
def __init__(self, interval=1):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
nfcActive = 0
global speakerGroup
deviceName = "Kitchen"
nameFlipper = 1
pn532 = None
try:
pn532 = PN532_SPI(debug=False, reset=20, cs=4)
ic, ver, rev, support = pn532.get_firmware_version()
print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev))
# Configure PN532 to communicate with MiFare cards
pn532.SAM_configuration()
print('Waiting for RFID/NFC card...')
except Exception as e:
print(e)
with open("errorlog.txt", "a") as dbFile:
dbFile.write(time.strftime("%-m.%-d %H:%M:%S", time.localtime()))
dbFile.write(": initializing: ")
dbFile.write(str(e))
dbFile.write("\n")
dbFile.write(sys.exc_info()[2])
dbFile.write("\n\n*****************\n\n")
#finally:
# GPIO.cleanup()
while True:
try:
uid = ""
# Check if a card is available to read
rawuid = pn532.read_passive_target(timeout=0.5)
#print('.', end="")
#print(time.strftime("%H:%M:%S", time.localtime()) + " nfcActive: " + str(nfcActive))
#if there is a card and it hasn't taken an action on that card yet.
if rawuid is not None and nfcActive == 0:
for i in rawuid:
bit = str(hex(i)).lower()[2:]
if len(bit) == 1:
bit = "0" + bit
uid += bit + ":"
uid = uid[:-1]
nfcActive = 1
#print("found a card: " + uid)
writeActivityLog("found a card: " + uid)
playNFCStream(uid)
#if no card is available.
if rawuid is None:
# if an NFC tag is removed.
if nfcActive == 1:
# if it's already paused or stopped, don't do anything
devices = {device.player_name: device for device in soco.discover()}
deviceStatus = devices[deviceName].get_current_transport_info()["current_transport_state"]
#print(deviceStatus + "\n")
if deviceStatus == "PAUSED_PLAYBACK" or deviceStatus == "STOPPED":
nfcActive = 0
continue
# pause the speakers
else:
#print("NFC removed. Pausing Sonos.")
writeActivityLog("NFC removed. Pausing Sonos.")
devices[speakerGroup[0]].pause()
nfcActive = 0
else:
print("nothin' here " + time.strftime("%H:%M:%S", time.localtime()))
continue
# If you want to be able to remove the NFC tag without pausing the music.
# nfcActive = 0
# print("nothin' here " + time.strftime("%H:%M:%S", time.localtime()))
# continue
except Exception as e:
if str(e) == "The method or property \"pause\" can only be called/used on the coordinator in a group":
if nameFlipper == 1:
deviceName = "Living Room"
nameFlipper = 0
else:
deviceName = "Kitchen"
nameFlipper = 1
print(e)
with open("errorlog.txt", "a") as dbFile:
dbFile.write(time.strftime("%-m.%-d %H:%M:%S", time.localtime()))
dbFile.write(": active: ")
dbFile.write(str(e))
dbFile.write('\n\n')
continue
def main():
# the sleep is not necessary, but since the program auto-runs when you log into the pi, i found it useful to give myself
# some time to kill the program when SSH'ing in.
time.sleep(3)
syncWithRemoteDB()
# uncomment if you want to sync with remote on a regular schedule. Important if you have multiple jukeboxes
#sync = SyncSchedule()
reader = NFCReader()
while True:
continue
def playNFCStream(nfcUID):
playlists = getPlaylists()
speaker = getSpeaker()
setSpeakerGroup()
x = 0
for i in playlists:
dbNFC = str(i[0]).lower()
if dbNFC == nfcUID:
service = identifyService(playlists[x])
if service == "spotify":
playSpotifyPlaylist(playlists[x])
resetSpeakerGroup()
elif service == "pandora":
playPandoraPlaylist(playlists[x])
resetSpeakerGroup()
elif service == "utility":
utilityControls(playlists[x])
else:
print("uhhhh whoops need to build this")
break
x = x + 1
# def playStream():
#this function is deprecated and is no longer used.
#it was replaced by playNFCStream
# playlists = getPlaylists()
# speaker = getSpeaker()
# printPlaylists()
# selection = int(input("Which number would you like to listen to? "))
# setSpeakerGroup()
# if identifyService(playlists[selection]) == "spotify":
# print("do some spotify stuff")
# playSpotifyPlaylist(playlists[selection][2])
# elif identifyService(playlists[selection]) == "pandora":
# print("do some pandora stuff")
# playPandoraPlaylist(playlists[selection])
# else:
# print("uhhhh whoops need to build this")
def utilityControls(playlists):
global defaultVolume
global speakerGroup
control = playlists[2].strip()
if control == "vol reset":
speaker = getSpeaker()
speaker.group.volume = defaultVolume
elif control == "vol down":
speaker = getSpeaker()
speaker.group.volume = (defaultVolume - 10)
elif control == "everywhere":
speakerGroup = ["Kitchen", "Living Room", "Den", "Bedroom", "Nursery", "Bathroom"]
print("everywhere")
elif control == "nursery":
speakerGroup = ["Nursery"]
elif control == "bathroom":
speakerGroup = ["Bathroom"]
print("bathroom")
def playSpotifyPlaylist(playlists):
playlistURL = playlists[3]
media_uri = sharelink.SpotifyShare().canonical_uri(playlistURL)
speaker = getSpeaker()
speaker.clear_queue()
sharelink.ShareLinkPlugin(speaker).add_share_link_to_queue(media_uri, position=1,as_next=True)
speaker.play_from_queue(0, start=True)
#print("Playing the Spotify playlist.")
writeActivityLog("Playing Spotify: " + playlists[2])
def playPandoraPlaylist(playlists):
speaker = getSpeaker()
speaker.clear_queue()
media_uri = playlists[3]
media_metadata = playlists[4]
speaker.play_uri(media_uri, media_metadata, start=True)
#print("Playing your Pandora jams")
writeActivityLog("Playing Pandora: " + playlists[2])
# Maybe delete this since it lives in the admin script now?
# def addToDatabase():
# #only works with Pandora right now
# speaker = getSpeaker()
# text = input("What is this station called? ")
# snap = Snapshot(speaker) #create snapshot class
# snap.snapshot() #take a snapshot of current state
# playlist = text + "," + snap.media_uri + "," + snap.media_metadata
# database = open(databaseFile, "a")
# database.write(playlist + "\n")
# database.close()
###
# Utilities
###
# def printPlaylists():
# playlists = getPlaylists()
# x = 0
# for p in playlists:
# print(str(x) + ". " + p[1])
# x = x + 1
# def printCurrentInfo():
# global speakerGroup
# speaker = getSpeaker()
# info = speaker.get_current_track_info()
# print ("Now listening to: " + info["title"] + " by " + info["artist"] + " on " + speakerGroup[0] + " speaker.")
def writeActivityLog(msg):
with open("activitylog.txt", "a") as dbFile:
dbFile.write(time.strftime("%H:%M:%S", time.localtime()))
dbFile.write(": ")
dbFile.write(msg)
dbFile.write("\n")
def identifyService(playlists):
result = playlists[1]
return result
def syncWithRemoteDB():
global remoteDBUrl
global databaseFile
remotedb = requests.get(remoteDBUrl).text
with open(databaseFile, "w") as dbFile:
dbFile.write(remotedb)
print("Remote database sync complete.")
#####
# Setters
#####
def setSpeakerGroup():
global speakerGroup
print("357: " + str(speakerGroup))
# get a dict of devices
devices = {device.player_name: device for device in soco.discover()}
numOfSpeakersInGroup = len(devices[speakerGroup[0]].group.members)
print("361: " + str(numOfSpeakersInGroup))
# this is hacky, but if the main speaker is in a group
# that is the same size as the group it's supposed to be in,
# it assumes its in the right size and does nothing.
# This works for my setup and is a nice speed boost,
# but it may not work for your setup.
if numOfSpeakersInGroup != len(speakerGroup):
print("unjoin some stuff")
for speaker in speakerGroup:
print("Unjoin " + speaker)
devices[speaker].unjoin()
devices[speaker].stop()
for speaker in speakerGroup:
for apparatus in devices:
if speaker == apparatus and speaker != speakerGroup[0]:
print("Joining " + apparatus)
devices[apparatus].join(devices[speakerGroup[0]])
break
def resetSpeakerGroup():
global speakerGroup
global defaultSpeakerGroup
speakerGroup = defaultSpeakerGroup
#######DEPRECATED#######
# keeping it for now until the replacement proves itself worthy.
# this was an inefficient hot mess of similar sounding variable names.
########################
# def oldsetSpeakerGroup():
# global speakerGroup
# config = open("config.txt", "r")
# speakersNameList = config.read().rstrip().split(",")
# config.close()
# speakersList = []
# speakers = soco.discover()
# devices = {device.player_name: device for device in soco.discover()}
# devicesLength = len(devices['Living Room'].group.members)
# # match the list of devices to the string list of speaker names
# for n in speakersNameList:
# for s in speakers:
# if s.player_name == n:
# speakersList.append(s)
# break
# speakerName = speakersList[0].player_name
# print("speakerNameListLen: " + str(len(speakersNameList)))
# print("devicesLength: " + str(devicesLength))
# if len(speakersNameList) != devicesLength:
# # we aren't in our standard configuration, so ungroup everything and start over
# speakersList[0].unjoin()
# #if there's more than one speaker in config, group an infinite number of speakers
# if len(speakersList) > 1:
# length = len(speakersList)
# x = 1
# while x < length:
# #print("x: " + str(x) + " adding: " + speakersList[x].player_name)
# speakersList[x].unjoin()
# speakersList[x].join(speakersList[0])
# x = x + 1
#####
# Getters
#####
def getPlaylists():
global databaseFile
database = open(databaseFile, "r")
playlists = []
for p in database:
playlists.append(p.split(","))
database.close()
return playlists
def getSpeaker():
global speakerGroup
# speakers = soco.discover()
# for val in speakers:
# if str(val.player_name) == speakerName:
# speaker = val
# break
speaker = soco.discovery.by_name(speakerGroup[0])
#print("speaker: " + str(speaker))
return speaker
if __name__ == "__main__":
main()