-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlights.py
308 lines (217 loc) · 6.98 KB
/
lights.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
#!/usr/bin/env python3
import glob
import subprocess
WORKING_DIR = "/home/pi/lightshowpi"
MUSIC_DIR = WORKING_DIR + "/music"
PLAYLIST_DIR = WORKING_DIR + "/playlists"
LIGHTSHOWPI = WORKING_DIR + "/py/synchronized_lights.py"
COL_WIDTH = 50
MODES = {
"now playing": 0,
"play song": 1,
"play playlist": 2,
"stop": 3,
"make playlist": 4,
"reload files": 5,
"exit": 6
}
class Song:
def __init__(self, path, extension=".mp3", delimiter="_"):
self.type = "song"
self.path = path
self.path_tree = path.split("/")
self.filename = self.path_tree[len(self.path_tree) - 1]
self.title = self.filename[:(-1 * len(extension))].replace(delimiter, " ").title()
self.process = None
def play(self):
self.process = subprocess.Popen(["sudo", LIGHTSHOWPI, "--file=" + self.path])
def stop(self):
if self.process is not None:
self.process.terminate()
self.process = None
class Playlist:
def __init__(self, path, extension=".playlist", delimiter="-"):
self.type = "playlist"
self.path = path
self.path_tree = path.split("/")
self.filename = self.path_tree[len(self.path_tree) - 1]
self.title = self.filename[:(-1 * len(extension))].replace(delimiter, " ").title()
self.songs = []
self.is_saved = False
self.process = None
try:
self.load()
except IOError:
self.save()
def play(self):
self.process = subprocess.Popen(["sudo", LIGHTSHOWPI, "--playlist" + self.path])
def stop(self):
if self.process is not None:
self.process.terminate()
self.process = None
def add(self, song):
self.songs.append(song)
self.is_saved = False
def remove(self, song):
self.songs.remove(song)
self.is_saved = False
def remove_by_index(self, index):
self.songs.remove(self.songs[index])
self.is_saved = False
def save(self):
with open(self.path, "w+") as outfile:
for song in self.songs:
outfile.write("{}\t{}\n".format(song.title, song.path))
self.is_saved = True
def load(self):
self.songs = []
with open(self.path, "r") as infile:
for line in infile.readlines():
parts = line.split("\t")
self.songs.append(Song(parts[1]))
self.is_saved = True
def print_item_list(items):
length = len(items) // 2
if len(items) % 2 == 0:
length += 1
for i in range(length):
item1 = items[i].title
i2 = i + length
if i2 < len(items):
item2 = items[i2].title
else:
i2 = ""
item2 = ""
gap = (COL_WIDTH - len(item1)) * " "
if i < 9:
item1 = " " + item1
print("{}. {}{}{}. {}".format(i+1, item1, gap, i2+1, item2))
def validate_numeric(num, low, high):
if isinstance(num, str) and num.isnumeric():
num = int(num)
if low <= num <= high:
return True
return False
def choose(item_desc, items, prev_playing):
prev_ok = True
while True:
print_item_list(items)
if not prev_ok:
print("Previous input was invalid. Try again.")
print("\nWhich {} to play? (type 'done' to return to menu)".format(item_desc))
choice = input(">>>")
if validate_numeric(choice, 1, len(items)):
if prev_playing is not None:
prev_playing.stop()
selection = items[int(choice) - 1]
selection.play()
return selection
elif choice == "done":
prev_playing.stop()
return None
else:
prev_ok = False
print("Invalid.")
def make_playlist(songs):
named = False
name = ""
while not named:
print("/nEnter a name for this playlist. (alphanumeric characters legal)")
name = input(">>>")
if name.isalnum():
named = True
else:
print("Invalid.")
new_playlist = Playlist(PLAYLIST_DIR + "/" + name + ".playlist")
adding_songs = True
prev_ok = True
while adding_songs:
print_item_list(songs)
if not prev_ok:
print("ERROR: previous choice invalid.")
print(" Either it was already on the playlist, or choice not on list.")
print("/nWhich song to add? (type 'done' when finished)")
choice = input(">>>")
if validate_numeric(choice, 1, len(songs)):
choice = int(choice)
selected_song = songs[choice - 1]
if selected_song not in new_playlist.songs:
new_playlist.add(selected_song)
prev_ok = True
else:
prev_ok = False
elif choice.casefold() == "done":
adding_songs = False
else:
prev_ok = False
new_playlist.save()
return new_playlist
def whats_playing(item):
if item is not None and item.poll() is not None:
print("The {} entitled \"{}\" is playing.".format(item.type, item.title))
else:
print("Nothing is playing!")
def menu():
while True:
print("""
---LightShowPi Menu---
0. See what's playing
1. Play a song
2. Play a playlist
3. Stop playing
4. Make a playlist
5. Refresh file index
6. Exit
""")
print("What to do?")
choice = input(">>>")
if validate_numeric(choice, 1, 6):
return int(choice)
def get_songs():
files = sorted(glob.glob(MUSIC_DIR + "/*.mp3"))
songs = []
for item in files:
songs.append(Song(item))
return songs
def get_playlists():
files = sorted(glob.glob(MUSIC_DIR + "/*.playlist"))
playlists = []
for item in files:
playlists.append(Playlist(item))
return playlists
running = True
now_playing = None
mode = 0
all_songs = get_songs()
all_playlists = get_playlists()
while running:
mode = menu()
print(mode)
if mode == MODES["now playing"]:
whats_playing(now_playing)
elif mode == MODES["play song"]:
finished = False
while not finished:
now_playing = choose("song", all_songs, now_playing)
if now_playing is None:
finished = True
elif mode == MODES["play playlist"]:
finished = False
while not finished:
now_playing = choose("playlist", all_playlists, now_playing)
if now_playing is not None:
finished = True
elif mode == MODES["stop"]:
if now_playing is not None:
now_playing.stop()
now_playing = None
elif mode == MODES["make playlist"]:
all_playlists.append(make_playlist(all_songs))
elif mode == MODES["reload files"]:
all_songs = get_songs()
all_playlists = get_playlists()
elif mode == MODES["exit"]:
if now_playing is not None:
now_playing.stop()
running = False
print("Goodbye!")