-
Notifications
You must be signed in to change notification settings - Fork 0
/
Radio.py
639 lines (546 loc) · 24.1 KB
/
Radio.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import configparser
import curses
import curses.panel
import curses.textpad
import logging
from logger import Logger
import random
import time
from NightrideAPI import NightRideAPI
class RadioInterface:
def __init__(self, loglevel=logging.INFO, logfile: str = "radio.log"):
### ArgParse ###
# parser = argparse.ArgumentParser(description='Text-based user interface for Nightride.fm.')
# args = parser.parse_args()
# parser.print_usage()
self.logger = Logger(
module_name=__name__,
log_file=logfile,
log_level=loglevel,
delete_old_logfile=True,
streamhandler=False,
filehandler=True,
)
### Read config ###
self.config = configparser.ConfigParser()
self.config.read("settings.ini")
self.LCD1602_MODULE = self.config.getboolean("ADDONS", "LCD1602")
if self.LCD1602_MODULE:
self.logger.log.debug(f"Initializing lcd module")
import RGB1602
self.lcd = RGB1602.RGB1602(16, 2, "error", logfile="radio.log")
self.api = NightRideAPI(loglevel=loglevel, logfile="radio.log")
stationlist = self.config.items("STATIONS")
self.stations = []
for key, value in stationlist:
self.stations.append(value)
self.VU_METER = self.config.getboolean("SETTINGS", "VU_METER")
self.volume = 4
self.api.audioPlayer.set_volume(self.volume)
self.station = self.config["SETTINGS"]["default_station"]
self.orig_time = False
self.now_playing = {
"artist": "",
"artist_short": "",
"song": "",
"song_short": "",
}
self.version = "v1.0"
try:
curses.wrapper(self.main)
except Exception as e:
print("An error caused the program to crash. See radio.log for details")
self.logger.log.error(e)
def main(self, stdscr):
# curses.noecho()
curses.curs_set(0)
curses.start_color()
stdscr.nodelay(True)
curses.init_pair(1, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_CYAN)
# curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_MAGENTA) # Cyan on magenta is hard to read
curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_MAGENTA)
curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_MAGENTA)
curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_RED)
curses.init_pair(8, curses.COLOR_BLACK, curses.COLOR_GREEN)
curses.init_pair(9, curses.COLOR_BLACK, curses.COLOR_BLUE)
curses.init_pair(10, curses.COLOR_BLACK, curses.COLOR_BLACK)
rows, cols = stdscr.getmaxyx()
self.logger.log.debug(f"Window size at x:{cols} y:{rows}")
if rows < 11 or cols < 52:
self.logger.log.error(
f"Window size too small to draw interface! Needs to be at least 52 by 11 characters."
)
self.draw_radio_frame(stdscr)
self.draw_now_playing_win()
self.set_station(self.station)
self.set_volume_slider(self.volume)
self.t1 = time.perf_counter()
while True:
self.read_key(stdscr)
self.set_playtime()
self.draw_now_playing_win()
self.draw_vu_meter()
self.draw_menu_bar(stdscr)
self.draw_station_win()
self.draw_volume_win()
stdscr.refresh()
time.sleep(0.1)
def draw_radio_frame(self, stdscr):
# Draw a rectangle with single line
# curses.textpad.rectangle(stdscr, 2, 2, 10, 50)
# Draw a double line thick rectangle, 50columns wide
# stdscr.addstr(2, 2, "╔═ --------- -- ════════════════════════════════╗")
stdscr.addstr(2, 2, "┏━ ───────── ── ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓")
for i in range(7):
# stdscr.addstr(i + 3, 2, f"║{str().center(47)}║")
stdscr.addstr(i + 3, 2, f"┃{str().center(47)}┃")
# stdscr.addstr(10, 2, "╚═══════════════════════════════════════════════╝")
stdscr.addstr(10, 2, "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛")
# Draw the rest of the interface
stdscr.addstr(2, 5, "NIGHTRIDE.", curses.color_pair(2))
stdscr.addstr(2, 15, "FM", curses.color_pair(2))
stdscr.addstr(4, 3, "...............................................")
def read_key(self, stdscr):
key = ""
try:
key = stdscr.getkey()
if key == "KEY_RESIZE":
rows, cols = stdscr.getmaxyx()
self.logger.log.debug(f"User resized the window to x:{cols} y:{rows}")
self.draw_radio_frame(stdscr)
else:
self.logger.log.debug(f"User pressed key {key}")
except curses.error as e:
# No input from user. Let's pass.
pass
# Change channels inputting numbers
if key in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
self.api.audioPlayer.stop()
self.set_station(self.stations[int(key) - 1])
# Volume up
if key == "+":
if self.volume < 9:
self.volume += 1
self.set_volume_slider(self.volume)
self.api.audioPlayer.set_volume(self.volume)
# Volume down
if key == "-":
if self.volume > 0:
self.volume -= 1
self.set_volume_slider(self.volume)
self.api.audioPlayer.set_volume(self.volume)
# Legacy: change station with arrow keys
# # Previous station
# if key == "KEY_LEFT":
# self.logger.log.debug("Previous station")
# index_of_prev = self.stations.index(self.station) - 1
# if index_of_prev >= 0:
# prev_station = self.stations[index_of_prev]
# self.set_station(prev_station)
# # Next station
# if key == "KEY_RIGHT":
# self.logger.log.debug("Next station")
# index_of_next = self.stations.index(self.station) + 1
# if index_of_next < len(self.stations):
# next_station = self.stations[index_of_next]
# self.set_station(next_station)
# Resize window
if key == "KEY_RESIZE":
self.station_win.refresh()
self.now_playing_win.refresh()
self.station_win = curses.newwin(1, 23, 3, 5)
n = self.stations.index(self.station)
self.station_win.addstr(f"station {n+1}: {self.station}")
self.station_win.refresh()
stdscr.refresh()
# Disable VU meter
if key == "v":
self.VU_METER = not self.VU_METER
self.config.set("SETTINGS", "VU_METER", f"{self.VU_METER}")
self.save_config()
if key == "r":
self.LCD1602_MODULE = not self.LCD1602_MODULE
self.config.set("ADDONS", "lcd1602", f"{self.VU_METER}")
self.save_config()
if not self.LCD1602_MODULE:
self.lcd.clear()
self.lcd.turnOff()
else:
self.lcd.printOnTwoRows(
argTopRow=self.now_playing["artist"],
argBotRow=self.now_playing["song"],
color="PURPLE",
turnOffAfter=False,
freezeFor=0,
)
# Quit
if key == "KEY_F(12)":
if self.LCD1602_MODULE:
self.lcd.clear()
self.lcd.turnOff()
exit()
# Show "About" info
if key == "KEY_F(1)":
self.draw_popup_about(stdscr)
# Show "Stations" panel
if key == "KEY_F(2)":
self.draw_popup_select_station(stdscr)
def draw_popup_about(self, stdscr):
self.panwin = curses.newwin(9, 49, 2, 2)
self.panwin.erase()
self.panwin.box()
max_rows, max_cols = stdscr.getmaxyx()
menu_win = curses.newwin(1, 11, 0, 0)
menu_win_2 = curses.newwin(1, max_cols - 11, 0, 10)
try:
menu_win.addstr("F1: ABOUT ", curses.color_pair(3))
menu_win_2.addstr(
"| F2: STATION | -/+: VOLUME | F12: QUIT".ljust(max_cols),
curses.color_pair(5),
)
except curses.error:
# Accursed curses raises an error if you write in the last column.
# We will discard that...
pass
menu_win.refresh()
menu_win_2.refresh()
self.panwin.addstr(0, 20, ">>ABOUT<<", curses.color_pair(5))
self.panwin.addstr(2, 3, "AUTHOR:", curses.color_pair(3))
self.panwin.addstr(2, 10, " Matias Räisänen 2022 ", curses.color_pair(6))
self.panwin.addstr(3, 2, "CONTACT:", curses.color_pair(3))
self.panwin.addstr(3, 10, " matias@matiasraisanen.com ", curses.color_pair(6))
self.panwin.addstr(4, 3, "SOURCE:", curses.color_pair(3))
self.panwin.addstr(
4, 10, " github.com/matiasraisanen/nightride ", curses.color_pair(6)
)
self.panwin.addstr(5, 2, "VERSION:", curses.color_pair(3))
self.panwin.addstr(5, 10, f" {self.version}", curses.color_pair(6))
self.panwin.addstr(6, 2, "Player for Nightride.fm")
self.panwin.addstr(7, 2, "(https://nightride.fm)")
self.panwin.addstr(8, 3, "ENTER: [OK]", curses.color_pair(8))
self.panwin.addstr(8, 31, "F1: [CLOSE]", curses.color_pair(7))
panel = curses.panel.new_panel(self.panwin)
panel.top()
# NOTE: Update panels will crash on WIN10. Should figure out a workaround later!
curses.panel.update_panels()
stdscr.refresh()
while True:
key = ""
try:
key = stdscr.getkey()
self.logger.log.debug(f"User pressed key {key}")
except curses.error as e:
# No input from user. Let's pass.
pass
if key == "KEY_F(1)" or key == "\n":
self.draw_radio_frame(stdscr)
break
if key == "KEY_F(12)":
exit()
def draw_popup_select_station(self, stdscr):
# Draw menu with "station" active
max_rows, max_cols = stdscr.getmaxyx()
menu_win = curses.newwin(1, 12, 0, 0)
menu_win_2 = curses.newwin(1, 14, 0, 11)
menu_win_3 = curses.newwin(1, max_cols - 25, 0, 24)
try:
menu_win.addstr("F1: ABOUT |", curses.color_pair(5))
menu_win_2.addstr(" F2: STATION ", curses.color_pair(3))
menu_win_3.addstr(
"| ↑/↓: MOVE | F12: QUIT".ljust(max_cols), curses.color_pair(5)
)
except curses.error:
# Accursed curses raises an error if you write in the last column.
# We will discard that...
pass
menu_win.refresh()
menu_win_2.refresh()
menu_win_3.refresh()
self.panwin = curses.newwin(9, 49, 2, 2)
self.panwin.erase()
self.panwin.box()
selected = self.stations.index(self.station)
index_of_prev = self.stations.index(self.station) - 1
if index_of_prev >= 0:
prev_station = self.stations[index_of_prev]
else:
prev_station = ""
index_of_next = self.stations.index(self.station) + 1
if index_of_next < len(self.stations):
next_station = self.stations[index_of_next]
else:
next_station = ""
top = prev_station
mid = self.stations[selected]
bot = next_station
self.panwin.addstr(0, 15, f">>SELECT STATION<<", curses.color_pair(5))
# self.panwin.addstr(2, 6, f'↑', curses.color_pair(5))
self.panwin.addstr(3, 3, f"Station {selected+1}:")
# self.panwin.addstr(4, 6, f'↓', curses.color_pair(5))
# Draw top row
if top == "":
# Draw black on top row, if the selected station is first in list
top_color = curses.color_pair(10)
else:
top_color = curses.color_pair(9)
self.panwin.addstr(2, 18, f" {top.center(11)} ", top_color)
# Draw mid row
self.panwin.addstr(3, 19, f"→ {mid.center(11)} ←", curses.color_pair(3))
# Draw bot row
if bot == "":
# Draw black on bot row, if the selected station is last in list
bot_color = curses.color_pair(10)
else:
bot_color = curses.color_pair(9)
self.panwin.addstr(4, 18, f" {bot.center(11)} ", bot_color)
# Draw "NOW PLAYING"-section
self.panwin.addstr(5, 1, "...............................................")
self.panwin.addstr(5, 3, "NOW.PLAYING")
artist = self.api.now_playing[self.stations[selected]]["artist"]
artist = self.shorten(artist, 37)
song = self.api.now_playing[self.stations[selected]]["song"]
song = self.shorten(song, 37)
self.panwin.addstr(6, 2, f"Artist: ")
self.panwin.addstr(6, 10, f"{artist}", curses.color_pair(3))
self.panwin.addstr(7, 4, f"Song: ")
self.panwin.addstr(7, 10, f"{song}", curses.color_pair(4))
self.panwin.addstr(8, 3, "ENTER: [OK]", curses.color_pair(8))
self.panwin.addstr(8, 31, "F2: [CLOSE]", curses.color_pair(7))
panel = curses.panel.new_panel(self.panwin)
panel.top()
# NOTE: Update panels will crash on WIN10. Should figure out a workaround later!
curses.panel.update_panels()
stdscr.refresh()
if self.LCD1602_MODULE:
self.lcd.printOnOneRow(arg=f"Select station: ", row=0)
self.lcd.printOnOneRow(arg=f"{mid}".center(16).upper(), row=1)
# User changing stations
while True:
key = ""
if self.LCD1602_MODULE:
self.lcd.printOnOneRow(arg="Select station:", row=0)
try:
key = stdscr.getkey()
if key == "KEY_UP":
# Check if top of list.
index_of_prev = selected - 1
if index_of_prev >= 0:
if index_of_prev == 0:
top = ""
else:
top = self.stations[selected - 2]
mid = self.stations[selected - 1]
bot = self.stations[selected]
selected -= 1
if selected > 0:
top = self.stations[selected - 1]
else:
top = ""
if key == "KEY_DOWN":
max_num = len(self.stations) - 1
index_of_next = selected + 1
if index_of_next <= max_num:
mid = self.stations[selected + 1]
top = self.stations[selected]
if index_of_next == max_num:
bot = ""
selected += 1
if selected < max_num:
bot = self.stations[selected + 1]
else:
bot = ""
if key == "KEY_F(2)":
self.draw_radio_frame(stdscr)
self.set_now_playing(redraw=True)
break
if key == "KEY_F(12)":
exit()
mid = self.stations[selected]
# Start drawing the channel selector
# Draw top row
if top == "":
# Draw black on top row, if the selected station is first in list
top_color = curses.color_pair(10)
else:
top_color = curses.color_pair(9)
self.panwin.addstr(2, 18, f" {top.center(11)} ", top_color)
# Draw mid row
self.panwin.addstr(3, 3, f"Station {selected+1}:")
self.panwin.addstr(3, 19, f"→ {mid.center(11)} ←", curses.color_pair(3))
# Draw bot row
if bot == "":
# Draw black on bot row, if the selected station is last in list
bot_color = curses.color_pair(10)
else:
bot_color = curses.color_pair(9)
self.panwin.addstr(4, 18, f" {bot.center(11)} ", bot_color)
# Set data for the "NOW PLAYING"-section
artist = self.api.now_playing[self.stations[selected]]["artist"]
artist = self.shorten(artist, 37)
song = self.api.now_playing[self.stations[selected]]["song"]
song = self.shorten(song, 37)
# Draw the "NOW PLAYING"-section
self.panwin.addstr(6, 2, f"Artist: {artist.ljust(38)}")
self.panwin.addstr(6, 10, f"{artist}", curses.color_pair(3))
self.panwin.addstr(7, 4, f"Song: {song.ljust(38)}")
self.panwin.addstr(7, 10, f"{song}", curses.color_pair(4))
panel = curses.panel.new_panel(self.panwin)
panel.top()
# NOTE: Update panels will crash on WIN10. Should figure out a workaround later!
curses.panel.update_panels()
stdscr.refresh()
# User pressing "ENTER" will activate the selection
if key == curses.KEY_ENTER or key == 10 or key == 13 or key == "\n":
self.logger.log.debug(
f"User selected station {self.stations[selected]} via F2"
)
self.set_station(self.stations[selected])
break
if self.LCD1602_MODULE:
self.lcd.printOnOneRow(arg=f"{mid}".center(16).upper(), row=1)
except curses.error as e:
# No input from user. Let's pass.
pass
def save_config(self):
with open("settings.ini", "w") as configfile:
self.config.write(configfile)
def set_volume_slider(self, volume):
self.logger.log.debug(f"Set volume slider to {volume}")
try:
slider = list("VOL: ◄──────────►")
slider[int(volume) + 6] = str(volume)
self.vol_win = curses.newwin(1, 18, 3, 31)
self.vol_win.addstr("".join(slider))
self.vol_win.refresh()
except:
self.logger.log.error(f"Failed to set volume slider to {volume}")
def shorten(self, word, max_length=29):
if len(word) > max_length:
self.logger.log.debug(f'Truncating "{word}" for interface')
trunc_word = list(word[0:max_length])
trunc_word[-3:] = "..."
word = "".join(trunc_word)
self.logger.log.debug(f'Truncated into "{word}"')
return word
def draw_now_playing_win(self):
self.set_now_playing()
artist = self.now_playing["artist_short"]
song = self.now_playing["song_short"]
self.now_playing_win = curses.newwin(2, 40, 6, 5)
self.now_playing_win.addstr(0, 0, f"Artist: ")
self.now_playing_win.addstr(1, 2, f"Song: ")
# Erroneous artist/song titles will be replaced with ???ERR
fail_title = "???ERR"
try:
self.now_playing_win.addstr(0, 8, f" {artist} ", curses.color_pair(3))
except:
self.now_playing_win.addstr(0, 8, f" {fail_title} ", curses.color_pair(3))
try:
self.now_playing_win.addstr(1, 8, f" {song} ", curses.color_pair(4))
except:
self.now_playing_win.addstr(1, 8, f" {fail_title} ", curses.color_pair(4))
self.now_playing_win.refresh()
def draw_station_win(self):
n = self.stations.index(self.station)
self.station_win = curses.newwin(1, 23, 3, 5)
self.station_win.addstr(f"station {n+1}: {self.station}")
self.station_win.refresh()
def draw_volume_win(self):
try:
slider = list("VOL: ◄──────────►")
slider[int(self.volume) + 6] = str(self.volume)
self.vol_win = curses.newwin(1, 18, 3, 31)
self.vol_win.addstr("".join(slider))
self.vol_win.refresh()
except:
self.logger.log.error(f"Failed to draw volume window")
def set_now_playing(self, redraw=False):
try:
# Force LCD redraw with redraw = True
if (
self.now_playing == self.api.now_playing[self.station]
and redraw == False
):
# Already playing the song, do nothing.
pass
else:
self.now_playing = self.api.now_playing[self.station]
artist = self.now_playing["artist"]
song = self.now_playing["song"]
self.now_playing["artist_short"] = self.shorten(artist)
self.now_playing["song_short"] = self.shorten(song)
if self.LCD1602_MODULE:
self.lcd.printOnTwoRows(
argTopRow=artist,
argBotRow=song,
color="PURPLE",
turnOffAfter=False,
freezeFor=0,
)
except KeyError as e:
self.logger.log.warning(f"No data for station {self.station} yet")
except Exception as e:
self.logger.log.error(f"Failed to set now playing: {e}")
def set_playtime(self):
try:
current_song_start = self.api.now_playing[self.station]["started_at"]
except KeyError:
self.logger.log.warning("Could not get current_song_start")
current_song_start = 0
timenow = time.perf_counter()
timedelta = int(timenow) - int(current_song_start)
minutes = int(timedelta / 60)
seconds = timedelta % 60
time_to_print = f"Played: {str(minutes).zfill(2)}:{str(seconds).zfill(2)}"
try:
time_played_win = curses.newwin(1, 20, 8, 5)
time_played_win.addstr(time_to_print)
time_played_win.refresh()
except:
self.logger.log.error(f"Failed to draw time played.")
self.orig_time = time_to_print
def set_station(self, station):
self.logger.log.debug(f"Set station => {station}")
try:
self.station = station
self.api.audioPlayer.play(station)
except Exception as e:
self.logger.log.error(f"Failed to set station to {station}")
self.logger.log.error(e)
def draw_vu_meter(self):
# Obviously, this VU meter is purely cosmetic :-)
if self.VU_METER:
icons = list("▁▂▃▄▅▆▇█")
meter_list = []
for i in range(10):
meter_list.append(random.choice(icons))
meter = "".join(meter_list)
else:
meter = ""
try:
vu_win = curses.newwin(1, 15, 8, 35)
vu_win.addstr(0, 0, meter)
vu_win.refresh()
except:
self.logger.log.error(f"Failed to draw VU meter")
def draw_menu_bar(self, stdscr):
max_rows, max_cols = stdscr.getmaxyx()
self.menu_win = curses.newwin(1, max_cols, 0, 0)
try:
self.menu_win.addstr(
"F1: ABOUT | F2: STATION | -/+: VOLUME | F12: QUIT".ljust(max_cols),
curses.color_pair(5),
)
except curses.error:
# Accursed curses raises an error if you write in the last column.
# We will discard that...
pass
self.menu_win.refresh()
if __name__ == "__main__":
radio = RadioInterface(loglevel=logging.INFO)
if radio.LCD1602_MODULE:
radio.lcd.clear()
radio.lcd.turnOff()