-
Notifications
You must be signed in to change notification settings - Fork 1
/
pinetradio.py
executable file
·1825 lines (1377 loc) · 45.9 KB
/
pinetradio.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# pinetradio tiny internet radio with Raspberry Zero WH and Pirate-Audio HAT
#
# requires an alsa device with dmix properties
# because we need to play a stream and additional signals like beeps
#
# 20230826 buttons work immediately after mute
# 20230731 2-key-rollover for all four buttons
# 20230416 using pigpio
# 20230325 using apscheduler
# 20230318 version for mpv
# init 20230218
networkadapter="wlan0"
ambience="/home/pi/jukebox/ambientmixer/Ambientmix Bleiche VBR 80-120kbps.mp3"
minimal1="/home/pi/jukebox/minimal/Simeon ten Holt - Canto Ostinato (1979) - Original 1984 Live Recording.mp3"
minimal2="/home/pi/jukebox/minimal/Arvo Pärt - Für Alina (1976).mp3"
minimal3="/home/pi/jukebox/shepard.mp3"
minimal4="/home/pi/jukebox/BCC CCC Pausenmucke - Fear of Ghosts - Machine Lullaby.mp3"
beepsound = "/home/pi/sounds/beep.wav"
quindar1sound = "/home/pi/sounds/Quindar1.wav"
quindar2sound = "/home/pi/sounds/Quindar2.wav"
quindar1soundshort = "/home/pi/sounds/Quindar1short.wav"
quindar2soundshort = "/home/pi/sounds/Quindar2short.wav"
servicebellsound = "/home/pi/sounds/service-bell-receptionsklingel.wav"
gongsound1 = "/home/pi/sounds/Glockenturm1.wav"
gongsoundlast = "/home/pi/sounds/GlockenturmLast.wav"
STATIONS = [
[ "DLF Kultur", "http://st02.dlf.de/dlf/02/128/mp3/stream.mp3" ],
[ "DLF", "http://st01.dlf.de/dlf/01/128/mp3/stream.mp3" ],
[ "Kulturradio", "http://kulturradio.de/live.m3u" ],
[ "Radio Eins", "http://www.radioeins.de/livemp3" ],
[ "WDR 5", "http://wdr-wdr5-live.icecast.wdr.de/wdr/wdr5/live/mp3/128/stream.mp3" ],
[ "JazzRadio Berlin", "http://streaming.radio.co/s774887f7b/listen" ],
[ "WDR Cosmo", "http://wdr-cosmo-live.icecast.wdr.de/wdr/cosmo/live/mp3/128/stream.mp3" ],
[ "Ellinikos 93,2", "http://netradio.live24.gr/orange9320" ],
[ "Left Coast", "http://somafm.com/seventies.pls" ],
[ "Groove Salad", "http://ice1.somafm.com/groovesalad-128-mp3" ],
[ "Heavyweight Reggae", "http://somafm.com/reggae.pls" ],
[ "DEF CON Radio", "https://somafm.com/defcon.pls" ],
[ "Radio Gold", "https://radiogold-live.cast.addradio.de/radiogold/live/mp3/high/stream.mp3" ],
[ "Caprice Minimalism", "http://213.141.131.10:8000/minimalism" ]
]
graceperiod = 2.0 # seconds between new station is actually selected
buttonBacklightTimeout = 30
mutedBacklightTimeout = 5
icyBacklightTimeout = 10
showtimeTimeout = 5
short_showtimeTimeout = 1.5
watchdogTimeout = 15 # Test
showtime_every_n_seconds = 60
# after mute:
# whether volume buttons immediately control volume
# or first press only restart backlight display
buttons_work_after_mute_direct = True
global dict
# words longer than this will be tried to hyphenate
global maxwordlength
maxwordlength = 14
# max length of first hyphenated part of a word
global maxpartialwordlength
maxpartialwordlength=8
global anybuttonpressed
anybuttonpressed = False
volumesteps = [ 0, 5, 8, 10, 12, 15, 17, 20,
22, 25, 28, 30, 35, 40, 45, 50, 55,
60, 65, 70, 75, 80, 85, 90, 95, 100 ]
startvolstep = 4
# Code for special operations (sequence of pin numbers)
code5656 = [5,6,5,6] # restart WiFi
code6565 = [6,5,6,5] # restart player
code5566 = [5,5,6,6]
code55566 = [5,5,5,6,6]
code555566 = [5,5,5,5,6,6]
code5555566 = [5,5,5,5,5,6,6]
code55555566 = [5,5,5,5,5,5,6,6]
global icyinfo
icyinfo= ""
# Test speakers
# aplay -L
# speaker-test -Dplughw:CARD=sndrpihifiberry,DEV=0 -c2 -s1
# speaker-test -Dplughw:CARD=sndrpihifiberry,DEV=0 -c2 -s2
# for PI OS LITE (32 bit) install:
#
#
# sudo apt install git libi2c-dev
# sudo raspi-config
# Interface Options: enable SPI for LCD-display
# enable I2C for DAC
# sudo reboot now
# https://domoticproject.com/extending-life-raspberry-pi-sd-card/
#
# setup /tmp as a RAM disk
#
# sudo nano /etc/fstab
#
# add a line:
# tmpfs /tmp tmpfs defaults,size=50M 0 0
# disable swapping and check zero-byte swap file
#
# https://community.element14.com/products/raspberry-pi/f/forum/20159/how-do-i-permanently-disable-the-swap-service/151444
# sudo nano /etc/dphys-swapfile
# change CONF_SWAPSIZE=0
#
# After reboot
# confirm that no swap exists by checking that the Swap line of the following command is 0:
# sudo free -h
#
# Best practice: disable the system logging
# sudo systemctl disable rsyslog
# disable wifi_powersave
# sudo nano /etc/network/interfaces
#
# interfaces(5) file used by ifup(8) and ifdown(8)
# Include files from /etc/network/interfaces.d:
# source /etc/network/interfaces.d/*
# allow-hotplug wlan0
# iface wlan0 inet manual
# post-up iw wlan0 set power_save off
# check that wifi_powersave is really off
# iw wlan0 get power_save
# should report: "Power save: off"
# enable the pirate radio DAC audio output
# and you can better also disable raspi onboard audio.
#
# see https://github.com/pimoroni/pirate-audio
# see https://shop.pimoroni.com/products/pirate-audio-line-out
#
# sudo nano /boot/config.txt
# dtoverlay=hifiberry-dac
# gpio=25=op,dh
# dtparam=audio=off
# sudo apt install mpv libmpv-dev python3-mpv libasound2-plugin-equal
# make sure not to have pulseaudio and vlc and mplayer
# sudo apt remove pulseaudio vlc mplayer
# pip install pyphen st7789
# use the ~/.asoundrc file
# check:
#
# aplay -l
# aplay -L
# alsamixer -D equal
# usually not needed:
# alsactl kill rescan
# List all audiodevices
# mpv --audio-device=help
#
# Test
# mpv --audio-device=alsa/plugmixequal http://www.radioeins.de/livemp3 --volume=50 --cache=no
# check not to have any display manager onboad, otherwise stop and disable
# ps -ef | grep dm
# sudo systemctl stop lightdm
# sudo systemctl disable lightdm
# sudo systemctl stop cups
# sudo systemctl disable cups
# optional:
#
# crontab -e
# * * * * * /home/pi/network.py >> /tmp/wifi.log
#
# sudo crontab -e
# NOW=date +%Y%m%d-%H%M%S
# */15 * * * * /usr/local/bin/wifi_reconnect.sh
# @reboot echo "`$NOW` -- boot --" > /var/log/wifi_reconnect
import mpv
# we import this big libraries - at the latest moment, after playing
# lazy loading later
# import pyphen
# import apscheduler
import signal
from threading import Timer, Thread
import pigpio
import sys
import os
import re
import time
from datetime import datetime
import subprocess
import ST7789
from PIL import Image, ImageDraw, ImageFont
import socket
import json
cfgfile ="/home/pi/pinetradio.cfg"
global stationcounter
global volstep
global muted
global volumedecrementbuttonblock
volumedecrementbuttonblock = False
global hostname
hostname = os.uname()[1]
stationfont = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 28)
font20 = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
font46 = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 46)
def playsound(volumepercent=100, soundfile=beepsound):
nowtime=timenow()
logger.warning( f"playsound {soundfile} ({volumepercent} %)")
soundplayer.volume=volumepercent*player.volume/100
soundplayer.play(soundfile)
soundplayer.wait_for_playback
soundplayer.wait_for_property('idle-active')
def speak(speechfile):
playsound( soundfile="/home/pi/sounds/" + speechfile + ".wav" )
def threadedPlaysoundFunction(volumepercent,soundfile):
playsound(volumepercent,soundfile)
def beepwait(volumepercent=100,soundfile=beepsound):
playsound(volumepercent,soundfile)
def quindar1wait(volumepercent=100,soundfile=quindar1sound):
playsound(volumepercent,soundfile)
logger.warning("quindar1wait")
def quindar2wait(volumepercent=100,soundfile=quindar2sound):
playsound(volumepercent,soundfile)
logger.warning("quindar2wait")
def beep(volumepercent=100,soundfile=beepsound):
t = Thread( target=threadedPlaysoundFunction, daemon=True, args=( volumepercent,soundfile ) )
t.start()
def quindar1(volumepercent=100,soundfile=quindar1soundshort):
t = Thread( target=threadedPlaysoundFunction, daemon=True, args=( volumepercent,soundfile ) )
t.start()
def quindar2(volumepercent=100,soundfile=quindar2soundshort):
t = Thread( target=threadedPlaysoundFunction, daemon=True, args=( volumepercent,soundfile ) )
t.start()
def servicebell(volumepercent=50,soundfile=servicebellsound):
t = Thread( target=threadedPlaysoundFunction, daemon=True, args=( volumepercent,soundfile ) )
t.start()
def servicebellwait(volumepercent=100,soundfile=servicebellsound):
playsound(volumepercent,soundfile)
logger.warning("servicebellwait")
def gong1Function(volumepercent):
if muted:
return
playsound(volumepercent,gongsoundlast)
def gong1(volumepercent=70,soundfile=gongsound1):
t = Thread( target=gong1Function, daemon=True, args=( volumepercent, ) )
t.start()
def gong2Function(volumepercent):
if muted:
return
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsoundlast)
def gong2(volumepercent=70,soundfile=gongsound1):
t = Thread( target=gong2Function, daemon=True, args=( volumepercent, ) )
t.start()
def gong3Function(volumepercent):
if muted:
return
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsoundlast)
def gong3(volumepercent=70,soundfile=gongsound1):
t = Thread( target=gong3Function, daemon=True, args=( volumepercent, ) )
t.start()
def gong4Function(volumepercent):
if muted:
return
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsound1)
playsound(volumepercent,gongsoundlast)
def gong4(volumepercent=70,soundfile=gongsound1):
t = Thread( target=gong4Function, daemon=True, args=( volumepercent, ) )
t.start()
def threadedBeep3Function(volumepercent):
playsound(volumepercent,beepsound)
time.sleep(0.5)
playsound(volumepercent,beepsound)
time.sleep(0.5)
playsound(volumepercent,beepsound)
def beep3(volumepercent=50):
t = Thread( target=threadedBeep3Function, daemon=True, args=(volumepercent, ) )
t.start()
def get_git_revision_short_hash() -> str:
# return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'],
return subprocess.check_output(['git',
'log','-1', '--date=format:%Y%m%d-%H%M', '--format=%ad %h'],
cwd=os.path.dirname(os.path.realpath(__file__))).decode('ascii').strip().split()
global cfgdata
try:
with open( cfgfile, "r") as f:
cfgdata = json.load(f)
stationcounter=cfgdata['station']
volstep=cfgdata['volstep']
muted=cfgdata['muted']
f.close()
except IOError:
stationcounter=0
volstep=startvolstep
muted=False
cfgdata = {
'station': stationcounter,
'volstep' : startvolstep,
'muted': muted
}
steady = 20000 # microseconds
pressed = pigpio.LOW
released = pigpio.HIGH
class TwoButtons():
def __init__(self,
button1,button2,button3,button4,
callback1,callback2,callback3,callback4,
callback12,callback13,callback14,
callback23,callback24,
callback34):
self.last = ""
# get a pigpio instance
self.pi = pigpio.pi()
# set up buttons
self.button1 = button1
self.button2 = button2
self.button3 = button3
self.button4 = button4
# set up glitch filter to debounce each switch
self.pi.set_glitch_filter(self.button1, steady)
self.pi.set_glitch_filter(self.button2, steady)
self.pi.set_glitch_filter(self.button3, steady)
self.pi.set_glitch_filter(self.button4, steady)
# set up each button as an input
self.pi.set_mode(self.button1, pigpio.INPUT)
self.pi.set_mode(self.button2, pigpio.INPUT)
self.pi.set_mode(self.button3, pigpio.INPUT)
self.pi.set_mode(self.button4, pigpio.INPUT)
# create a callback for when button is pressed
self.pi.callback(self.button1, pigpio.EITHER_EDGE, self.button_pressed)
self.pi.callback(self.button2, pigpio.EITHER_EDGE, self.button_pressed)
self.pi.callback(self.button3, pigpio.EITHER_EDGE, self.button_pressed)
self.pi.callback(self.button4, pigpio.EITHER_EDGE, self.button_pressed)
self.callback1 = callback1
self.callback2 = callback2
self.callback3 = callback3
self.callback4 = callback4
self.callback12 = callback12
self.callback13 = callback13
self.callback14 = callback14
self.callback23 = callback23
self.callback24 = callback24
self.callback34 = callback34
def clrlast_cb(self):
self.last = ""
def callbackTwo(self,both,pin,level,tick):
if both != self.last:
self.last = both
clrlastTimer = Timer( 0.1, self.clrlast_cb, args=() )
clrlastTimer.start()
if both == "12":
self.callback12(pin,level,tick)
elif both == "13":
self.callback13(pin,level,tick)
elif both == "14":
self.callback14(pin,level,tick)
elif both == "23":
self.callback23(pin,level,tick)
elif both == "24":
self.callback24(pin,level,tick)
elif both == "34":
self.callback34(pin,level,tick)
# common button press callback for both buttons
def button_pressed(self, pin, level, tick):
both = None
if pin == self.button1:
if level == pressed:
for _ in range(10):
if self.pi.read(self.button2) == pressed:
both = "12"
break
if self.pi.read(self.button3) == pressed:
both = "13"
break
if self.pi.read(self.button4) == pressed:
both = "14"
break
time.sleep(0.005)
if not both:
if self.pi.read(self.button1) == pressed:
self.callback1(pin,level,tick)
if self.pi.read(self.button2) == pressed:
self.callback2(pin,level,tick)
if self.pi.read(self.button3) == pressed:
self.callback3(pin,level,tick)
if self.pi.read(self.button4) == pressed:
self.callback4(pin,level,tick)
if both:
self.callbackTwo(both,pin,level,tick)
elif pin == self.button2:
if level == pressed:
for _ in range(10):
if self.pi.read(self.button1) == pressed:
both = "12"
break
if self.pi.read(self.button3) == pressed:
both = "23"
break
if self.pi.read(self.button4) == pressed:
both = "24"
break
time.sleep(0.005)
if not both:
if self.pi.read(self.button1) == pressed:
self.callback1(pin,level,tick)
if self.pi.read(self.button2) == pressed:
self.callback2(pin,level,tick)
if self.pi.read(self.button3) == pressed:
self.callback3(pin,level,tick)
if self.pi.read(self.button4) == pressed:
self.callback4(pin,level,tick)
if both:
self.callbackTwo(both,pin,level,tick)
elif pin == self.button3:
if level == pressed:
for _ in range(10):
if self.pi.read(self.button1) == pressed:
both = "13"
break
if self.pi.read(self.button2) == pressed:
both = "23"
break
if self.pi.read(self.button4) == pressed:
both = "34"
break
time.sleep(0.005)
if not both:
if self.pi.read(self.button1) == pressed:
self.callback1(pin,level,tick)
if self.pi.read(self.button2) == pressed:
self.callback2(pin,level,tick)
if self.pi.read(self.button3) == pressed:
self.callback3(pin,level,tick)
if self.pi.read(self.button4) == pressed:
self.callback4(pin,level,tick)
if both:
self.callbackTwo(both,pin,level,tick)
elif pin == self.button4:
if level == pressed:
for _ in range(10):
if self.pi.read(self.button1) == pressed:
both = "14"
break
if self.pi.read(self.button2) == pressed:
both = "24"
break
if self.pi.read(self.button3) == pressed:
both = "34"
break
time.sleep(0.005)
if not both:
if self.pi.read(self.button1) == pressed:
self.callback1(pin,level,tick)
if self.pi.read(self.button2) == pressed:
self.callback2(pin,level,tick)
if self.pi.read(self.button3) == pressed:
self.callback3(pin,level,tick)
if self.pi.read(self.button4) == pressed:
self.callback4(pin,level,tick)
if both:
self.callbackTwo(both,pin,level,tick)
# Get signal strength and basic network adapter parameters
def get_networkinfo_raw(interface="wlan0"):
proc = subprocess.Popen(
["/usr/sbin/iwlist", interface, "scan"],
stdout=subprocess.PIPE,
universal_newlines=True)
out, err = proc.communicate()
out = out.split("\n")
for i, val in enumerate(out):
if 'Signal' in val:
signal_line = val.split()
if 'Signal' in signal_line:
rssi = int(signal_line[signal_line.index('Signal')+1].split('=')[1])
if 'ESSID' in val:
ssid_line = val.split('"')
ssid = ssid_line[1]
hostname = socket.gethostname()
ipaddr = socket.gethostbyname(hostname)
return hostname,ipaddr,ssid,rssi
def get_networkinfo(interface="wlan0"):
ipaddr = None
connectionwaslost = False
while ipaddr is None:
try:
# try to get an ip addr
hostname,ipaddr,ssid,rssi = get_networkinfo_raw(interface)
except:
if not connectionwaslost:
noiptime = time.time()
logger.warning("*** reconnecting: waiting for ip")
connectionwaslost = True
time.sleep(1.0)
# we only print the regained ip addr when we were disconnected
# we do not print the addr in normal program flow
if connectionwaslost:
deltatime = 1.0 + time.time() - noiptime
logger.warning(f"*** without ip: {deltatime:.1f} seconds")
logger.warning(f"*** ip after reconnect: {ipaddr}")
return hostname,ipaddr,ssid,rssi
# https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully
class GracefulKiller:
killed = False
shutdown = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self, *args):
self.killed = True
# The buttons on Pirate Audio are connected to pins 5, 6, 16 and 24
# Boards prior to 23 January 2020 used 5, 6, 16 and 20
# try changing 24 to 20 if your Y button doesn't work.
BUTTONS = [5, 6, 16, 24]
# These correspond to buttons A, B, X and Y respectively
LABELS = ['A', 'B', 'X', 'Y']
PIN = {
'A': 5,
'B': 6,
'X': 16,
'Y': 24
}
# Activity LED on Raspberry Pi Zero is BCM pin 47
ACT = 47
global buttonqueue
buttonqueue = []
pi = pigpio.pi() # pi accesses the local Pi's GPIO
pi.write(ACT, 1)
pi.set_mode(ACT, pigpio.OUTPUT)
# Buttons connect to ground when pressed, so we should set them up
# with a "PULL UP", which weakly pulls the input signal to 3.3V.
# Create ST7789 LCD display class for square LCD
# Standard display setup for Pirate Audio, except we omit the backlight pin
SPI_SPEED_MHZ = 90
rotation = 270
# regarding backlight pin 13, read:
# https://github.com/pimoroni/pirate-audio/issues/31#issuecomment-678313017
disp = ST7789.ST7789(
height=240,
rotation=rotation, # Needed to display the right way up on Pirate Audio
port=0, # SPI port
# cs=1, # SPI port Chip-select channel
cs=ST7789.BG_SPI_CS_FRONT, # BG_SPI_CS_BACK or BG_SPI_CS_FRONT
dc=9, # BCM pin used for data/command
backlight=None, # We'll control the backlight ourselves
# backlight=13, # 13 for Pirate-Audio; 18 for back BG slot, 19 for front BG slot.
spi_speed_hz=SPI_SPEED_MHZ * 1000 * 1000,
offset_left=0,
offset_top=0
)
def now():
currentDateAndTime = datetime.now()
return currentDateAndTime.strftime("%Y%m%d%H%M%S")
def timenow():
currentDateAndTime = datetime.now()
return currentDateAndTime.strftime("%H:%M:%S")
def cleardisplay():
global img,draw,stationimg
img = Image.new('RGB', (disp.width, disp.height), color="black")
stationimg = img.copy()
draw = ImageDraw.Draw(img)
def showvolume(draw,volcolor="red",restcolor="yellow"):
total = len(volumesteps)-1
length = disp.height*(total-volstep) // total
draw.line( (disp.width-1,disp.height-1,disp.width-1,length), fill=volcolor )
draw.line( (disp.width-1,length-1,disp.width-1,0), fill=restcolor )
def setupdisplay():
global disp,img,draw,display
# We must set the backlight pin up as an output first
pi.set_mode(13, pigpio.OUTPUT)
# Set up our pin as a PWM output at 1000Hz
pi.set_PWM_frequency(13, 1000)
display = 100
triggerdisplay()
cleardisplay()
draw.rectangle( ((0, 0, disp.height-1, disp.width-1)), outline="yellow")
stwrite3("[ Pinetradio started ]")
def setbacklight(dutycycle):
global display
display=dutycycle
pi.set_PWM_dutycycle(13, dutycycle*255/100)
def display_is_on():
global display
return display > 0
def retriggerbacklight(dutycycle=100,timeout=buttonBacklightTimeout):
# returns True if backlight was on
global backlighttimer,display
try:
is_backlightOn = not backlighttimer.finished.is_set()
backlighttimer.cancel()
except:
is_backlightOn = True
pi.set_PWM_dutycycle(13, dutycycle*255/100)
display = dutycycle
backlighttimer = Timer( timeout, setbacklight, args=( 0, ) )
backlighttimer.start()
return is_backlightOn
def stwrite( position, message, font, color ):
global disp,img,draw
draw.text( position, message, font=font, fill=color)
sizex, sizey = draw.textsize( message, font=font )
return ( position[0]+sizex, position[1] )
# wrap text into display width
# https://stackoverflow.com/questions/8257147/wrap-text-in-pil
def get_wrapped_text(text: str, font: ImageFont.ImageFont,
line_length_in_pixels: int):
lines = ['']
text2=['']
for word in re.split(r"([ /-])", text):
if len(word) > maxwordlength:
try:
wx = dict.wrap(word,maxpartialwordlength)
if wx:
text2.append(wx[0].strip())
text2.append(wx[1].strip())
except:
# none indicates: no hyphenation possible
text2.append(word.strip())
else:
text2.append(word.strip())
text3 = " ".join(text2)
# split and keep the separators:
# for word in re.split(r"([ /-])", text3):
for word in re.split(r"([ ])", text3):
word=word.strip()
line = f'{lines[-1]} {word}'.strip()
if ( font.getlength(line) > line_length_in_pixels ):
lines.append(word)
else:
lines[-1] = line
try:
# this is apparently no longer needed
if ( word[-1] == "-" or word[-1] == "," or word[-1] == "/" ):
lines.append('') # add a new line after "-" and ","
except:
pass
cleanlines = []
for line in lines:
if not ( line == "" or line == "," or line == "-" or line == "/" ):
cleanlines.append(line.strip())
return '\n'.join(cleanlines)
def testsize( box, font_size, text):
global disp,wrappedtext,font
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
wrappedtext = get_wrapped_text( text, font, disp.width )
size = font.getsize_multiline(wrappedtext)
if ( (size is None)
or ( size[0] > box[2] - box[0] + 1 )
or ( size[1] > box[3] - box[1] + 1 ) ):
return None
else:
return size
def bisectsize( box, a, b, text):
# returns the optimal maximum font_size to fully fill the part of the display
# textsize() sets the global wrappedtext
mid = abs(b-a) // 2
if (mid == 0 ):
if not ( testsize( box, b, text) is None ):
return b
if not ( testsize( box, a, text) is None ):
return a
else:
testsize( box, a-1, text)
return a-1
else:
if ( testsize( box, a+mid, text ) is None ):
return bisectsize( box, a, a+mid-1, text)
else:
return bisectsize( box, a+mid+1, b, text)
def writebox(draw, box, text, fontsize_min, fontsize_max):
global disp,wrappedtext,font
font_size = bisectsize( box, fontsize_min, fontsize_max, text )
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
wrappedtext = get_wrapped_text( text, font, disp.width )
draw.multiline_text((box[0], box[2]), wrappedtext, anchor="ld", font=font, fill="cyan")
def stwrite3(message):
global disp,img,stationimg,logger
hostname,ipaddr,ssid,rssi = get_networkinfo(networkadapter)
message = message.strip(', ')
logger.warning(f"{message} ({rssi} db)")
if muted:
return
stationimg = img.copy()
draw = ImageDraw.Draw(stationimg)
writebox( draw, ((0, 34, disp.height-1, disp.width-1)), message + " (–" + str(-rssi) + " db)", fontsize_min=20, fontsize_max = 70)
disp.display(stationimg)
def stationplay(stationnr):
global stationselecttimer,draw
draw.rectangle( ((0, 0, disp.height-1, disp.width-1)), outline="yellow")
stwrite3("[ Gönnen Sie sich eine Pause - die Musiktitel kommen gleich! ]")
station = STATIONS[stationnr]
stationname =station[0]
stationurl = station[1]
try:
stationselecttimer.cancel()
except:
pass
if muted:
startvolume = 0
else:
startvolume = 1.0*volumesteps[volstep]
player.volume = startvolume
logger.warning(f"playing station #{stationnr} ({stationname}) {stationurl}")
player.play(stationurl)
showvolume(draw)
def kill_processes():
global watchdogtimer
os.system( "pulseaudio --kill 1>/dev/null 2>/dev/null" )
try:
watchdogtimer.cancel()
except:
pass
# "handle_button" will be called every time a button is pressed
# It receives one argument: the associated input pin.
def handle_button(pin):
label = LABELS[BUTTONS.index(pin)]
print("Button press detected on pin: {} label: {}".format(pin, label))
def sendvolume(volume):
player.volume = 1.0*volume
def setvol(volstep, graceful, show=False):
global volumetimer,disp,img,stationimg,volimg
volimg = stationimg.copy()
draw = ImageDraw.Draw(volimg)
showvolume(draw)
if show:
disp.display(volimg)
volume = volumesteps[volstep]
try:
volumetimer.cancel()
except:
pass
if (graceful):
volumetimer = Timer( 0.2, sendvolume, args=( volume, ) )
volumetimer.start()
else:
sendvolume( volume )
def playstation(stationnr, graceful=True):
global stationselecttimer,draw,disp,img
try:
stationselecttimer.cancel()
except:
pass
station = STATIONS[stationnr]
cleardisplay()
draw.rectangle( ((0, 0, disp.width-1, disp.height-1)), outline="yellow")
# draw.rectangle((1, 1, disp.width-2, 31), fill=(0, 0, 0, 0))
cursor = stwrite( (0,0), "{0}".format( stationcounter+1 ), stationfont, "red" )
cursor = stwrite( cursor, " {0}".format( station[0] ), stationfont, "white" )
disp.display(img)
if (graceful):
stationselecttimer = Timer( graceperiod, stationplay, args=( stationnr, ) )
stationselecttimer.start()
else:
stationplay( stationnr )
def updstationcounter(stationcounter):
global cfgdata
cfgdata['station']=stationcounter
with open(cfgfile, "w") as outfile:
json.dump(cfgdata, outfile, indent=4)
def updmuted():
global cfgdata,muted
muted=player.mute
cfgdata['muted']=muted
logger.warning(f"muted: {muted}")
with open(cfgfile, "w") as outfile:
json.dump(cfgdata, outfile, indent=4)
def updvol(volstep):
global cfgdata
cfgdata['volstep']=volstep