-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradio_class.py
executable file
·2323 lines (1973 loc) · 59.2 KB
/
radio_class.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 python
#
# Raspberry Pi Internet Radio Class
# $Id: radio_class.py,v 1.258 2017/02/13 13:01:08 bob Exp $
#
#
# Author : Bob Rathbone
# Site : http://www.bobrathbone.com
#
# This class uses Music Player Daemon 'mpd' and the python-mpd library
# Use "apt-get install python-mpd" to install the library
# Modified to use python-mpd2 library mpd.wikia.com
# See http://mpd.wikia.com/wiki/Music_Player_Daemon_Wiki
#
# License: GNU V3, See https://www.gnu.org/copyleft/gpl.html
#
# Disclaimer: Software is provided as is and absolutly no warranties are implied or given.
# The authors shall not be liable for any loss or damage however caused.
#
import os
import sys
import string
import time,datetime
import re
import ConfigParser
import SocketServer
from time import strftime
import pdb
from udp_server_class import UDPServer
from udp_server_class import RequestHandler
from log_class import Log
from translate_class import Translate
from config_class import Configuration
from language_class import Language
from mpd import MPDClient
# System files
ConfigFile = "/etc/radiod.conf"
RadioLibDir = "/var/lib/radiod"
PlaylistsDirectory = "/var/lib/mpd/playlists"
MusicDirectory = "/var/lib/mpd/music"
CurrentStationFile = RadioLibDir + "/current_station"
CurrentTrackFile = RadioLibDir + "/current_track"
RandomSettingFile = RadioLibDir + "/random"
VolumeFile = RadioLibDir + "/volume"
TimerFile = RadioLibDir + "/timer"
AlarmFile = RadioLibDir + "/alarm"
StreamFile = RadioLibDir + "/streaming"
BoardRevisionFile = RadioLibDir + "/boardrevision"
Icecast = "/usr/bin/icecast2"
log = Log()
translate = Translate()
config = Configuration()
language = None
server = None
Mpd = "/usr/bin/mpd" # Music Player Daemon
Mpc = "/usr/bin/mpc" # Music Player Client
client = MPDClient() # Create the MPD client
class Radio:
# Input source
RADIO = 0
PLAYER = 1
# Rotary class
ROTARY_STANDARD = config.STANDARD
ROTARY_ALTERNATIVE = config.ALTERNATIVE
# Player options
RANDOM = 0
CONSUME = 1
REPEAT = 2
RELOADLIB = 3
TIMER = 4
ALARM = 5
ALARMSETHOURS = 6
ALARMSETMINS = 7
STREAMING = 8
SELECTCOLOR = 9
OPTION_LAST = STREAMING
OPTION_ADA_LAST = SELECTCOLOR
# Display Modes
MODE_TIME = 0
MODE_SEARCH = 1
MODE_SOURCE = 2
MODE_OPTIONS = 3
MODE_RSS = 4
MODE_IP = 5
MODE_LAST = MODE_IP # Last one a user can select
MODE_SLEEP = 6 # Sleep after timer or waiting for alarm
MODE_SHUTDOWN = -1
# Alarm definitions
ALARM_OFF = 0
ALARM_ON = 1
ALARM_REPEAT = 2
ALARM_WEEKDAYS = 3
ALARM_LAST = ALARM_WEEKDAYS
# Other definitions
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
ONEDAYSECS = 86400 # Day in seconds
ONEDAYMINS = 1440 # Day in minutes
boardrevision = 2 # Raspberry board version type
udphost = 'localhost' # Remote IR listener UDP Host
udpport = 5100 # Remote IR listener UDP port number
mpdport = 6600 # MPD port number
volume = 80 # Volume level 0 - 100%
device_error_cnt = 0 # Device error causes an abort
isMuted = False # Is radio state "pause" or "stop"
isMuteda = False # Is the scrolling 2nd line stopped/blanked
isMutedDisplay = False # Has the backlight been switched off/on
playlist = [] # Play list (tracks or radio stations)
current_id = 1 # Currently playing track or station
source = RADIO # Source RADIO or Player
reload = False # Reload radio stations or player playlists
artist = "" # Artist (Search routines)
error = False # Stream error handling
errorStr = "" # Error string
switch = 0 # Switch just pressed
updateLib = False # Reload radio stations or player
numevents = 0 # Number of events recieved for a rotary switch
volumeChange = False # Volume change flag (external clients)
interrupt = False # Was IR remote interrupt received
stats = None # MPD Stats array
currentsong = None # Current song / station
state = 'play' # State (used if get state fails)
getIdError = False # Prevent repeated display of ID error
StationNamesSource = config.LIST # Use own names from playlist
use_playlist_extensions = False # MPD 0.16 requires playlist.<ext>
rotary_class = config.STANDARD # Rotary class standard all alternate
mode_last = MODE_IP # Last mode a user can select
option_last = OPTION_LAST # Last available option
display_mode = MODE_TIME # Display mode
display_artist = False # Display artist (or tracck) flag
current_file = "" # Currently playing track or station
option_changed = False # Option changed
channelChanged = True # Used to display title
configOK = False # Do we have a configuration file
display_playlist_number = False # Display playlist number
# MPD Options
random = False # Random play
repeat = False # Repeat play
consume = False # Consume tracks
# Clock and timer options
timer = False # Timer on
timerValue = 30 # Timer value in minutes
timeTimer = 0 # The time when the Timer was activated in seconds
volumetime = 0 # Last volume check time
dateFormat = "%H:%M %d/%m/%Y" # Date format
alarmType = ALARM_OFF # Alarm on
alarmTime = "0:7:00" # Alarm time default type,hours,minutes
alarmTriggered = False # Alarm fired
stationName = '' # Radio station name
stationTitle = '' # Radio station title
option = RANDOM # Player option
search_index = 0 # The current search index
loadnew = False # Load new track from search
streaming = False # Streaming (Icecast) disabled
VERSION = "5.9" # Version number
ADAFRUIT = 1 # I2C backpack type AdaFruit
PCF8574 = 2 # I2C backpack type PCF8574
i2c_backpack = ADAFRUIT
i2c_address = 0x00 # Use default I2C address
speech = False # Speech for visually impaired or blind persons
# Configuration files
ConfigFiles = {
CurrentStationFile: 1,
CurrentTrackFile: 1,
VolumeFile: 75,
TimerFile: 30,
AlarmFile: "0:07:00",
StreamFile: "off",
RandomSettingFile: 0,
}
# Initialisation routine
def __init__(self):
log.init('radio')
self.setupConfiguration()
return
# Set up configuration files
def setupConfiguration(self):
# Create directory
if not os.path.isfile(CurrentStationFile):
self.execCommand ("mkdir -p " + RadioLibDir )
# Initialise configuration files from ConfigFiles list
for file in self.ConfigFiles:
value = self.ConfigFiles[file]
if not os.path.isfile(file) or os.path.getsize(file) == 0:
self.execCommand ("echo " + str(value) + " > " + file)
# Create mount point for USB stick and link it to the music directory
if not os.path.isfile("/media"):
self.execCommand("mkdir -p /media")
if not os.path.ismount("/media"):
self.execCommand("chown pi:pi /media")
self.execCommand("ln -f -s /media /var/lib/mpd/music")
# Create mount point for networked music library (NAS)
if not os.path.isfile("/share"):
self.execCommand("mkdir -p /share")
if not os.path.ismount("/share"):
self.execCommand("chown pi:pi /share")
self.execCommand("ln -f -s /share /var/lib/mpd/music")
self.execCommand("chown -R pi:pi " + RadioLibDir)
self.execCommand("chmod -R 764 " + RadioLibDir)
self.current_file = CurrentStationFile
self.current_id = self.getStoredID(self.current_file)
return
# Call back routine for the IR remote
def remoteCallback(self):
global server
key = server.getData()
log.message("IR remoteCallback " + key, log.DEBUG)
if key == 'KEY_MUTE':
if self.muted():
self.unmute()
else:
self.mute()
self.setInterrupt()
elif key == 'KEY_DISPLAYTOGGLE':
if self.muteda():
self.unmutea()
else:
self.mutea()
self.setInterrupt()
elif key == 'KEY_DISPLAY_OFF':
if self.mutedDisplay():
self.unmuteDisplay()
else:
self.muteDisplay()
self.setInterrupt()
elif key == 'KEY_PLAYPAUSE':
self.playpauseToggle()
self.setInterrupt()
elif key == 'KEY_STOP':
self.stopPlaying()
self.setInterrupt()
elif key == 'KEY_VOLUMEUP':
self.increaseVolume()
self.setInterrupt()
self.volumeChange = True
elif key == 'KEY_VOLUMEDOWN':
self.decreaseVolume()
self.setInterrupt()
self.volumeChange = True
elif key == 'KEY_CHANNELUP':
self.channelUp()
self.setInterrupt()
elif key == 'KEY_CHANNELDOWN':
self.channelDown()
self.setInterrupt()
elif key == 'KEY_MENU' or key == 'KEY_OK':
self.cycleMenu()
self.setInterrupt()
elif key == 'KEY_LANGUAGE':
self.toggleSpeech()
self.setInterrupt()
elif key == 'KEY_INFO':
self.speakInformation()
self.setInterrupt()
elif key == 'KEY_POWER':
self.restart()
self.setInterrupt()
# These come from the Web CGI script
elif key == 'MEDIA':
self.loadMedia()
self.setInterrupt()
elif key == 'RADIO':
self.loadStations()
self.setInterrupt()
elif key == 'INTERRUPT':
self.setInterrupt()
# Handle left,right, up and down keys
else:
self.handle_key(key)
self.setInterrupt()
return
# Set up radio configuration and start the MPD daemon
def start(self):
global server
global language
config.display()
# Get Configuration parameters /etc/radiod.conf
self.boardrevision = self.getBoardRevision()
self.mpdport = config.getMpdPort()
self.udpport = config.getRemoteUdpPort()
self.udphost = config.getRemoteListenHost()
self.display_playlist_number = config.getDisplayPlaylistNumber()
self.source = config.getSource()
self.speech = config.getSpeech()
self.stationNamesSource = config.getStationNamesSource()
language = Language(self.speech) # language is a global
self.use_playlist_extensions = config.getPlaylistExtensions()
self.rotary_class = config.getRotaryClass()
# Log OS version information
OSrelease = self.execCommand("cat /etc/os-release | grep NAME")
OSrelease = OSrelease.replace("PRETTY_NAME=", "OS release: ")
OSrelease = OSrelease.replace('"', '')
log.message(OSrelease, log.INFO)
myos = self.execCommand('uname -a')
log.message(myos, log.INFO)
# Start the player daemon
self.execCommand("service mpd start")
# Connect to MPD
self.connect(self.mpdport)
client.clear()
self.randomOff()
self.consumeOff()
self.repeatOff()
self.current_id = self.getStoredID(self.current_file)
log.message("radio.start current ID " + str(self.current_id), log.DEBUG)
self.volume = self.getStoredVolume()
self._setVolume(self.volume)
# Alarm and timer settings
self.timeTimer = int(time.time())
self.timerValue = self.getStoredTimer()
self.alarmTime = self.getStoredAlarm()
sType,sHours,sMinutes = self.alarmTime.split(':')
self.alarmType = int(sType)
if self.alarmType > self.ALARM_OFF:
self.alarmType = self.ALARM_OFF
# Icecast Streaming settings
self.streaming = self.getStoredStreaming()
if self.streaming:
self.streamingOn()
else:
self.streamingOff()
# Start the remote control listener
try:
server = UDPServer((self.udphost,self.udpport),RequestHandler)
msg = "UDP Server listening on " + self.udphost + " port " + str(self.udpport)
log.message(msg, log.INFO)
server.listen(server,self.remoteCallback)
except:
log.message("UDP server could not bind to " + self.udphost
+ " port " + str(self.udpport), log.ERROR)
return
# Connect to MPD
def connect(self,port):
global client
connection = False
retry = 2
while retry > 0:
client = MPDClient() # Create the MPD client
try:
client.timeout = 10
client.idletimeout = None
client.connect("localhost", port)
log.message("Connected to MPD port " + str(port), log.INFO)
connection = True
retry = 0
except:
log.message("Failed to connect to MPD on port " + str(port), log.ERROR)
time.sleep(2.5) # Wait for interrupt in the case of a shutdown
sys.exit(0)
#log.message("Restarting MPD",log.DEBUG)
#if retry < 2:
# self.execCommand("service mpd restart")
#else:
# self.execCommand("service mpd start")
#time.sleep(2) # Give MPD time to restart
#retry -= 1
return connection
# Handle IR remote key
def handle_key(self,key):
if self.display_mode == self.MODE_OPTIONS:
self.handle_options(key)
elif self.display_mode == self.MODE_SOURCE:
self.handle_source(key)
elif self.display_mode == self.MODE_SEARCH:
self.handle_search(key)
self.optionChangedTrue()
return
# Handle stepping through menu options and changing them
def handle_options(self,key):
direction = -1
if key == 'KEY_UP':
direction = self.UP
elif key == 'KEY_DOWN':
direction = self.DOWN
elif key == 'KEY_LEFT':
direction = self.LEFT
elif key == 'KEY_RIGHT':
direction = self.RIGHT
if direction == self.UP or direction == self.DOWN:
self.cycleOptions(direction)
elif direction == self.LEFT or direction == self.RIGHT:
self.changeOption(direction)
return
# Handle stepping through menu options
def cycleOptions(self,direction):
option = self.getOption()
log.message("radio.cycleOptions option=" + str(option) \
+ " direction=" + str(direction), log.DEBUG)
# Cycle through option
if direction == self.UP:
option += 1
elif direction == self.DOWN:
option -= 1
# Skip reload if not in player mode
if option == self.RELOADLIB and self.source != self.PLAYER:
if direction == self.UP:
option += 1
else:
option -= 1
if option > self.option_last:
option = self.RANDOM
elif option < 0:
option = self.option_last
if option == self.RELOADLIB and self.source != self.PLAYER:
option -= 1
self.setOption(option)
return
# Handle search (IR routine)
def handle_search(self,key):
direction = self.UP
if key == 'KEY_LEFT' or key == 'KEY_DOWN':
direction = self.DOWN
if self.source == self.RADIO:
self.getNext(direction)
else:
# Step through tracks
if key == 'KEY_LEFT' or key == 'KEY_RIGHT':
self.getNext(direction)
else:
# Step through artist
self.findNextArtist(direction)
return
# Toggle speech
def toggleSpeech(self):
sVoice = language.getText('voice')
if self.speech:
sOff = language.getText('off')
self.speak(sVoice + ' ' + sOff)
self.speech = False
else:
self.speech = True
sOn = language.getText('on')
self.speak(sVoice + ' ' + sOn)
return
# Scroll up and down between stations/tracks
def getNext(self,direction):
playlist = self.getPlayList()
index = self.getSearchIndex()
# Artist displayed then don't increment track first time in
if not self.displayArtist():
leng = len(playlist)
if leng > 0:
if direction == self.UP:
index = index + 1
if index >= leng:
index = 0
else:
index = index - 1
if index < 0:
index = leng - 1
self.setSearchIndex(index)
self.setLoadNew(True)
name = self.getStationName(index)
if name.startswith("http:") and '#' in name:
url,name = name.split('#')
msg = "radio.getNext index " + str(index) + " "+ name
log.message(msg, log.DEBUG)
if self.speech:
self.speak(language.getText('search') + " " + str(index+1)
+ " " + name)
return
# Scroll through tracks by artist
def findNextArtist(self,direction):
self.setLoadNew(True)
index = self.getSearchIndex()
playlist = self.getPlayList()
current_artist = self.getArtistName(index)
found = False
leng = len(playlist)
count = leng
while not found:
if direction == self.UP:
index = index + 1
if index >= leng:
index = 0
else:
index = index - 1
if index < 1:
index = leng - 1
new_artist = self.getArtistName(index)
if current_artist != new_artist:
found = True
count = count - 1
# Prevent everlasting loop
if count < 1:
found = True
index = self.current_id
# If a Backward Search find start of this list
found = False
if direction == self.DOWN:
self.current_artist = new_artist
while not found:
index = index - 1
new_artist = self.getArtistName(index)
if self.current_artist != new_artist:
found = True
index = index + 1
if index >= leng:
index = leng-1
self.setSearchIndex(index)
if self.speech:
self.speak( str(index+1) + " " + new_artist)
return
# Change option (Used by remote control and non display radio only)
def changeOption(self,direction):
option = self.getOption()
sOptions = language.getOptionText()
sOption = sOptions[option]
log.message("radio.changeOption " + str(option) + " " + sOption, log.DEBUG)
if option == self.RANDOM:
if self.getRandom():
self.randomOff()
else:
self.randomOn()
elif option == self.CONSUME:
if self.getConsume():
self.consumeOff()
else:
self.consumeOn()
elif option == self.REPEAT:
if self.getRepeat():
self.repeatOff()
else:
self.repeatOn()
elif option == self.ALARM:
self.alarmCycle(direction)
elif option == self.STREAMING:
self.toggleStreaming()
elif option == self.RELOADLIB:
if self.getUpdateLibrary():
self.setUpdateLibOff()
else:
self.setUpdateLibOn()
elif option == self.TIMER:
if self.getTimer():
if direction == self.UP:
self.incrementTimer(1)
else:
self.decrementTimer(1)
else:
self.timerOn()
elif option == self.ALARMSETHOURS or option == self.ALARMSETMINS :
value = 1
if option == self.ALARMSETHOURS:
value = 60
if direction == self.UP:
self.incrementAlarm(value)
else:
self.decrementAlarm(value)
self.optionChangedTrue()
self.speakOption(option)
return
# Handle toggling of source
def handle_source(self,key):
if key == 'KEY_UP' or key == 'KEY_DOWN':
self.toggleSource()
return
# Input Source RADIO, NETWORK or PLAYER
def getSource(self):
return self.source
def setSource(self,source):
self.source = source
# Reload playlists flag
def getReload(self):
return self.reload
def setReload(self,reload):
log.message("radio.setReload " + str(reload), log.DEBUG)
self.reload = reload
# Reload music library flag
def getUpdateLibrary(self):
return self.updateLib
def setUpdateLibOn(self):
self.updateLib = True
def setUpdateLibOff(self):
self.updateLib = False
# Load new track flag
def loadNew(self):
return self.loadnew
def setLoadNew(self,loadnew):
log.message("radio.setLoadNew " + str(loadnew), log.DEBUG)
self.loadnew = loadnew
return
# Get the Raspberry pi board version from /proc/cpuinfo
def getBoardRevision(self):
revision = 1
with open("/proc/cpuinfo") as f:
cpuinfo = f.read()
rev_hex = re.search(r"(?<=\nRevision)[ |:|\t]*(\w+)", cpuinfo).group(1)
rev_int = int(rev_hex,16)
if rev_int > 3:
revision = 2
self.boardrevision = revision
log.message("Board revision " + str(self.boardrevision), log.INFO)
return self.boardrevision
# Get the MPD port number
def getMpdPort(self):
port = 6600
if os.path.isfile(MpdPortFile):
try:
port = int(self.execCommand("cat " + MpdPortFile) )
except ValueError:
port = 6600
else:
log.message("Error reading " + MpdPortFile, log.ERROR)
return port
# Get MPD version
def getMpdVersion(self):
sVersion = self.execCommand('mpd -V | grep Daemon')
return sVersion.split()[3]
# Get options (synchronise with external mpd clients)
def getOptions(self,stats):
try:
random = int(stats.get("random"))
if random == 1:
self.random = True
else:
self.random = False
repeat = int(stats.get("repeat"))
if repeat == 1:
self.repeat = True
else:
self.repeat = False
consume = int(stats.get("consume"))
if consume == 1:
self.consume = True
else:
self.consume = False
except:
log.message("radio.getOptions get error" + MpdPortFile, log.ERROR)
return
# Get volume and check if it has been changed by any MPD external client
# Slug MPD calls to no more than per 0.5 second
def _getVolume(self):
volume = 0
error = False
try:
now = time.time()
if now > self.volumetime + 0.5:
stats = self.getStats()
volume = int(stats.get("volume"))
self.volumetime = time.time()
else:
volume = self.volume
except:
log.message("radio._getVolume failed", log.ERROR)
volume = 1
error = True
if volume == str("None"):
volume = -1
error = True
if volume < 0:
error = True
if volume != self.volume:
if not error:
self.device_error_cnt = 0
log.message("radio._getVolume external client changed volume "
+ str(volume),log.DEBUG)
self._setVolume(volume)
self.volumeChange = True
else:
self.device_error_cnt += 1
log.message("radio._getVolume audio device error " + str(volume), log.ERROR)
if self.device_error_cnt > 10:
msg = "Sound device error - exiting"
log.message("radio._getVolume " + msg , log.ERROR)
print msg
sys.exit(1)
return self.volume
def getVolume(self):
increment = config.getVolumeIncrement()
return self._getVolume()/increment
# Check for volume change
def volumeChanged(self):
volumeChange = self.volumeChange
self.volumeChange = False
return volumeChange
# Return the volume range
def getVolumeRange(self):
return config.getVolumeRange()
# Set volume (Called from the radio client or external mpd client via getVolume())
def setVolume(self,volume):
range = config.getVolumeRange()
log.message("radio.setVolume vol=" + str(volume)
+ " (range 0-" + str(range) + ")",log.DEBUG)
increment = config.getVolumeIncrement()
volume = self._setVolume(volume * increment)
return volume/increment
# Set volume 0-100 (only called from in this class)
def _setVolume(self,volume):
if self.muted():
self.unmute()
else:
if volume > 100:
volume = 100
elif volume < 0:
volume = 0
try:
if volume != self.volume:
log.message("radio._setVolume vol=" + str(volume),log.DEBUG)
client.setvol(volume)
self.volume = volume
# Don't change stored volume (Needed for unmute function)
if not self.muted():
self.storeVolume(self.volume)
except:
log.message("radio._setVolume error vol=" + str(self.volume),log.ERROR)
return self.volume
# Increase volume
def increaseVolume(self):
increment = config.getVolumeIncrement()
volume = self.volume + increment
log.message("radio.increaseVolume vol=" + str(volume),log.DEBUG)
volume = self._setVolume(volume)
return volume/increment
# Decrease volume
def decreaseVolume(self):
increment = config.getVolumeIncrement()
volume = self.volume - increment
log.message("radio.decreaseVolume vol=" + str(volume),log.DEBUG)
volume = self._setVolume(volume)
return volume/increment
# Mute sound functions (Also stops MPD if not streaming)
def mute(self):
log.message("radio.mute streaming=" + str(self.streaming),log.DEBUG)
try:
if self.source == self.RADIO:
client.stop() # Disconnect from stream
else:
client.pause(1) # Pause playing track
self.isMuted = True
except:
log.message("radio.mute error",log.DEBUG)
return
# Unmute sound fuction, get stored volume
def unmute(self):
if self.muted():
self.volume = self.getStoredVolume()
log.message("radio.unmute volume=" + str(self.volume),log.DEBUG)
try:
client.play()
client.setvol(self.volume)
self.isMuted = False
except:
log.message("radio.unmute error",log.ERROR)
return self.volume
def muted(self):
return self.isMuted
##########################################################################
# The following three functions relate to the muting of the scrolling #
# display line. The request to mute/unmute is provided by IR key #
# KEY_DISPLAYTOGGLE.. #
##########################################################################
# Mute second line of the LCD
def mutea(self):
self.isMuteda = True
log.message("mutea changed status of isMuteda to True hopefully " , log.DEBUG)
return
# Unmute the second line of the LCD
def unmutea(self):
self.isMuteda = False
log.message("unmutea changed status of isMuteda to False hopefully " ,log.DEBUG)
return
def muteda(self):
return self.isMuteda
##########################################################################
# end of mute LCD scrolling line function block #
##########################################################################
##########################################################################
# The following three functions control the LCD display backlight. #
# The request to switch the backlight on or off is by IR KEY_DISPLAY_OFF # #
##########################################################################
# Mute second line of the LCD
def muteDisplay(self):
self.isMutedDisplay = True
log.message("muteDisplay changed status of isMutedDisplay to True hopefully " , log.DEBUG)
return
# Unmute the second line of the LCD
def unmuteDisplay(self):
self.isMutedDisplay = False
log.message("unmuteDisplay changed status of isMuteda to False hopefully " ,log.DEBUG)
return
def muteda(self):
return self.isMutedDisplay
############################################################################
# end of mute LCD function block #
############################################################################
# Start MPD (Alarm mode)
def startMPD(self):
try:
client.play()
except:
log.message("radio.startMPD error",log.ERROR)
return
# Stop MPD (Alarm mode)
def stopMPD(self):
try:
client.stop()
except:
log.message("radio.stopMPD error",log.ERROR)
return
# Get the stored volume
def getStoredVolume(self):
volume = 75
if os.path.isfile(VolumeFile):
try:
volume = int(self.execCommand("cat " + VolumeFile) )
except ValueError:
volume = 75
else:
log.message("Error reading " + VolumeFile, log.ERROR)
return volume
# Store volume in volume file
def storeVolume(self,volume):
self.execCommand ("echo " + str(volume) + " > " + VolumeFile)
return
# Random setting
def getRandom(self):
if self.source == self.PLAYER:
self.random = self.getStoredRandomSetting()
return self.random
def randomOn(self):
try:
client.random(1)
self.random = True
if self.source == self.PLAYER:
self.execCommand ("echo " + str(1) + " > " + RandomSettingFile)
except:
log.message("radio.randomOn error",log.ERROR)
return self.random
def randomOff(self):
try:
client.random(0)
self.random = False
if self.source == self.PLAYER:
self.execCommand ("echo " + str(0) + " > " + RandomSettingFile)
except:
log.message("radio.randomOff error",log.ERROR)
return self.random
# Get the stored random setting 0=off 1=on
def getStoredRandomSetting(self):
random = 0
if os.path.isfile(RandomSettingFile):
try:
random = int(self.execCommand("cat " + RandomSettingFile) )
except ValueError:
random = 0
else: