-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlircradio.py
executable file
·1386 lines (1099 loc) · 56.1 KB
/
lircradio.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 python2
# -*- coding: utf-8 -*-
description_text = """
This script listens to commands comming in through a fifopipe.
In reaction commands in radioFunctions.py are executed.
It also starts an ircat daemon that puts lirc commands into the pipe,
but very nice you can also do this through ssh, remotely starting
your radio or suspending a machine, without locking up your console:
ssh pc-x "echo suspend > /tmp/hika-fiforadio"
Possible commands are among others to run a suspend script,
start a radiodevice and manage audio volume.
It also can check mythtv for availability of the radio device.
The latest version can be found at:
https://github.com/hikavdh/lircradio
"""
import sys, io, os, pwd
import re, codecs, locale
import socket, argparse
from stat import *
from threading import Thread
try:
from subprocess32 import *
except:
from subprocess import *
try:
from radioFunctions import log
from radioFunctions import config as rfconf
from radioFunctions import RadioFunctions as rfcalls
except:
print "I cannot load radioFunctions.py. Make sure it's in the same directory!"
sys.exit(2)
# check Python version
if sys.version_info[:2] < (2,6):
sys.stderr.write("lircradio requires Pyton 2.6 or higher\n")
sys.exit(2)
elif sys.version_info[:2] >= (3,0):
sys.stderr.write("lircradio does not support Pyton 3 or higher.\nExpect errors while we proceed\n")
if rfconf.version()[:2] < (0,2):
sys.stderr.write("lircradio requires radioFunctions 0.1 or higher\n")
sys.exit(2)
class Configure:
"""This class holds all configuration details and manages file IO"""
def __init__(self):
self.name ='lircradio.py'
self.major = 0
self.minor = 2
self.patch = 1
self.beta = True
self.write_info_files = False
# 1=Log System Actions and errors
# 2=Log all commands coming through the pipe, Mainly for debugging
# 4=log unknown commands coming through the pipe
# 8=log Channel changes
# 16=log Volume changes
# 32=log all radiofunction calls, Mainly for debugging
rfconf.log_level = 29
self.opt_dict = {}
self.file_encoding = 'utf-8'
# default configuration file locations
self.hpath = ''
if 'HOME' in os.environ:
self.hpath = os.environ['HOME']
# extra test for windows users
elif 'HOMEPATH' in os.environ:
self.hpath = os.environ['HOMEPATH']
self.username = pwd.getpwuid(os.getuid())[0]
self.ivtv_dir = u'%s/.ivtv' % self.hpath
# check for the ~.ivtv dir
if not os.path.exists(self.ivtv_dir):
log('Creating %s directory,' % self.ivtv_dir)
os.mkdir(self.ivtv_dir)
self.etc_dir = u'/etc/lircradio'
self.config_file =u'/lircradio.conf'
self.log_file = u'%s/lircradio.log' % self.ivtv_dir
self.myth_menu_file = 'fmmenu.xml'
self.opt_dict['verbose'] = False
self.opt_dict['case_sensitive'] = False
# Initialising fifo variables
self.opt_dict['fifo_file'] = u'/tmp/%s-fiforadio' % self.username
self.opt_dict['lirc_id'] = u'lircradio'
self.fifo_read = None
self.fifo_write = None
self.ircat_pid = None
self.functioncalls = {}
self.functioncalls_lower = {}
self.external_commands = {}
self.external_commands_lower = {}
self.shell_commands = {'test': ['echo', 'Testing the pipe\n']}
self.shell_commands_lower = {'test': ['echo', 'Testing the pipe\n']}
# Initialising radio and audio
self.dev_types = {}
self.dev_types[0] = 'ivtv radio device'
self.dev_types[1] = 'radio with alsa device'
self.dev_types[2] = 'radio cabled to an audio card'
self.opt_dict['myth_backend'] = None
self.opt_dict['radio_cardtype'] = -1
self.opt_dict['radio_device'] = None
self.opt_dict['radio_out'] = None
self.opt_dict['source_switch'] = None
self.opt_dict['source'] = None
self.opt_dict['source_mixer'] = None
rfconf.check_dependencies(self.ivtv_dir)
# Detecting radio and audio defaults
self.select_card = u'You have to set audio-card to where the tv-card is cabled to: ['
for a in rfcalls().get_alsa_cards():
self.select_card += u'%s, ' % a
self.select_card = self.select_card[0: -2] + u']'
self.detect_radiodevice()
if len(self.radio_devs) > 0:
for card in self.radio_devs:
if card['radio_cardtype'] == 0:
# There is a ivtv-radiocard
self.opt_dict['radio_cardtype'] = card['radio_cardtype']
self.opt_dict['radio_device'] = card['radio_device']
self.opt_dict['radio_out'] = card['radio_out']
self.opt_dict['video_device'] =card['video_device']
else:
#We take the first
self.opt_dict['radio_cardtype'] = self.radio_devs[0]['radio_cardtype']
self.opt_dict['radio_device'] = self.radio_devs[0]['radio_device']
self.opt_dict['radio_out'] = self.radio_devs[0]['radio_out']
self.opt_dict['video_device'] =self.radio_devs[0]['video_device']
self.opt_dict['audio_card'] = rfcalls().get_alsa_cards(0)
for m in ('Front', 'Master', 'PCM'):
if m in rfcalls().get_alsa_mixers(0):
self.opt_dict['audio_mixer'] = m
break
else:
self.opt_dict['audio_mixer'] = rfcalls().get_alsa_mixers(0, 0)
self.__CONFIG_SECTIONS__ = { 1: u'Configuration', \
2: u'Radio Channels', \
3: u'Function Calls'}
# end Init()
def version(self, as_string = False):
if as_string and self.beta:
return u'%s Version: %s.%s.%s-beta' % (self.name, self.major, self.minor, self.patch)
if as_string and not self.beta:
return u'%s Version: %s.%s.%s' % (self.name, self.major, self.minor, self.patch)
else:
return (self.name, self.major, self.minor, self.patch, self.beta)
# end version()
def save_oldfile(self, file):
""" save the old file to .old if it exists """
try:
os.rename(file, file + '.old')
except Exception as e:
pass
# end save_old()
def open_file(self, file_name, mode = 'rb', encoding = None, buffering = 'default'):
""" Open a file and return a file handler if success """
if file_name == None:
return None
if encoding == None:
encoding = self.file_encoding
if buffering == 'default':
buffering = -1
elif buffering == None and ('b' in mode):
buffering = 0
elif buffering == None and not ('b' in mode):
buffering = 1
try:
if 'b' in mode:
file_handler = io.open(file_name, mode = mode, buffering = buffering)
else:
file_handler = io.open(file_name, mode = mode, encoding = encoding, buffering = buffering)
except IOError as e:
if e.errno == 2:
log('File: \"%s\" not found.\n' % file_name)
else:
log('File: \"%s\": %s.\n' % (file_name, e.strerror))
return None
return file_handler
# end open_file ()
def get_line(self, file, byteline, isremark = False, encoding = None):
"""
Check line encoding and if valid return the line
If isremark is True or False only remarks or non-remarks are returned.
If None all are returned
"""
if encoding == None:
encoding = self.file_encoding
try:
line = byteline.decode(encoding)
line = line.lstrip()
line = line.replace('\n','')
if len(line) == 0:
return False
if isremark == None:
return line
if isremark and line[0:1] == '#':
return line
if not isremark and not line[0:1] == '#':
return line
except UnicodeError:
log('%s is not encoded in %s.\n' % (file.name, encoding))
return False
# end get_line()
def check_encoding(self, file, encoding = None):
"""Check file encoding. Return True or False"""
# regex to get the encoding string
reconfigline = re.compile(r'#\s*(\w+):\s*(.+)')
if encoding == None:
encoding = self.file_encoding
file.seek(0,0)
for byteline in file.readlines():
line = self.get_line(file, byteline, True)
if not line:
continue
else:
match = reconfigline.match(line)
if match is not None and match.group(1) == "encoding":
encoding = match.group(2)
try:
codecs.getencoder(encoding)
except LookupError:
log('%s has invalid encoding %s.\n' % (file.name, encoding))
return False
return True
continue
return False
# end check_encoding()
def read_commandline(self):
"""Initiate argparser and read the commandline"""
parser = argparse.ArgumentParser(description=u'%(prog)s: ' +
'A daemon to play radio and process Lirc commands\n',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-V', '--version', action = 'store_true', default = False, dest = 'version',
help = 'display version')
parser.add_argument('-D', '--description', action = 'store_true', default = False, dest = 'description',
help = 'prints a description in english of the program')
parser.add_argument('-v', '--verbose', action = 'store_true', default = None, dest = 'verbose',
help = 'Sent log-info also to the screen.')
parser.add_argument('-q', '--quiet', action = 'store_false', default = None, dest = 'verbose',
help = 'suppress all output.')
parser.add_argument('-s', '--case-sensitive', action = 'store_true', default = None, dest = 'case_sensitive',
help = 'Make all commands case sensitive.')
#~ parser.add_argument('-d', '--daemon', action = 'store_true', default = None, dest = 'daemon',
#~ help = 'run as a daemon.')
parser.add_argument('-c', '--configure', action = 'store_true', default = False, dest = 'configure',
help = 'create configfile; rename an existing file to *.old.')
parser.add_argument('-C', '--config-file', type = str, default = None, dest = 'config_file',
metavar = '<file>',
help = 'name of the configuration file\nFalls back to \'%s%s\'\nand then \'%s%s\'' % \
(self.ivtv_dir, self.config_file, self.etc_dir, self.config_file))
parser.add_argument('-L', '--log-file', type = str, default = None, dest = 'log_file',
metavar = '<file>',
help = 'name and path of the log file. If not writable it\nfalls back to ' +
'\'%s\'\nThe directory must exist with rw permission.' % (self.log_file))
parser.add_argument('-O', '--save-options', action = 'store_true', default = False, dest = 'save_options',
help = 'save the currently defined options to the config file\n' +
'add options to the command-line to adjust the file.')
parser.add_argument('-F', '--fifo-file', type = str, default = None, dest = 'fifo_file',
metavar = '<file>',
help = 'name of the fifo-file (%s)' % self.opt_dict['fifo_file'])
parser.add_argument('-l', '--lirc-id', type = str, default = None, dest = 'lirc_id',
metavar = '<name>',
help = 'name of the lirc ID to respond to (%s)' % self.opt_dict['lirc_id'])
parser.add_argument('-r', '--card-type', type = str, default = None, dest = 'radio_cardtype',
metavar = '<device>',
help = 'type of radio-device/ (%s)\n' % self.opt_dict['radio_cardtype'] +
' 0 = ivtv (with /dev/video24 radio-out)\n' +
' 1 = with corresponding alsa device\n' +
' 2 = cabled to an audiocard\n' +
' -1 = No radiocard' )
parser.add_argument('-R', '--radio-device', type = str, default = None, dest = 'radio_device',
metavar = '<device>',
help = 'name of the radio-device in /dev/ (%s)\n' % self.opt_dict['radio_device'] )
parser.add_argument('-A', '--radio-out', type = str, default = None, dest = 'radio_out',
metavar = '<device>',
help = 'name of the audio-out-device in /dev/ or\n' +
'the alsa device (%s)' % self.opt_dict['radio_out'])
parser.add_argument('-T', '--video-device', type = str, default = None, dest = 'video_device',
metavar = '<device>',
help = 'name of the corresponding video-device in /dev/\n(%s)' % self.opt_dict['video_device'] )
parser.add_argument('-B', '--myth-backend', type = str, default = None, dest = 'myth_backend',
metavar = '<hostname>',
help = 'backend dns hostname. (%s)\nSet to \'None\' string to disable checking.' % self.opt_dict['myth_backend'])
parser.add_argument('-a', '--audio-card', type = str, default = None, dest = 'audio_card',
metavar = '<cardname>',
help = 'The audiocard name to play the radio. (%s)\n' % self.opt_dict['audio_card'])
parser.add_argument('-m', '--audio-mixer', type = str, default = None, dest = 'audio_mixer',
metavar = '<mixername>',
help = 'The mixer name. (%s)\n' % self.opt_dict['audio_mixer'])
parser.add_argument('--list-alsa-cards', action = 'store_true', default = False, dest = 'list_alsa',
help = 'Give a list of the alsa-audio cards on this system')
parser.add_argument('--list-mixers', action = 'store_true', default = False, dest = 'list_mixers',
help = 'Give a list of the available mixer-controls for the given card')
parser.add_argument('-M', '--create-menu', action = 'store_true', default = False, dest = 'create_menu',
help = 'create a Radiomenu file %s in %s\n' % (self.myth_menu_file, self.ivtv_dir) +
'with the defined channels to be used in MythTV.')
# Handle the sys.exit(0) exception on --help more gracefull
try:
self.args = parser.parse_args()
except:
return(0)
# end read_commandline()
def read_config(self):
"""Read the configurationfile Return False on failure."""
f = None
for file in (self.args.config_file, self.ivtv_dir + self.config_file, self.etc_dir + self.config_file, ):
if file == None or not os.access(file, os.F_OK) :
log('Error opening configfile: %s\n' % file, 1)
continue
if os.access(file, os.R_OK):
f = self.open_file(file)
if f != None and self.check_encoding(f):
self.args.config_file = file
break
else:
log('Error opening configfile: %s\n' % file, 1)
else:
log('configfile: %s is not readable!\n' % file, 1 )
if f == None or not self.check_encoding(f):
if os.access(self.ivtv_dir + 'radioFunctions.conf', os.F_OK) :
os.rename(self.ivtv_dir + 'radioFunctions.conf', self.ivtv_dir + self.config_file)
self.args.config_file = self.ivtv_dir + self.config_file
f = self.open_file(self.args.config_file)
if f == None or not self.check_encoding(f):
self.args.config_file = None
x = self.read_radioFrequencies_File()
if x == False:
log('Could not find an accessible configfile!\n', 1)
return(x)
self.args.config_file = file
f.seek(0,0)
type = 0
ch_num = 0
for byteline in f.readlines():
try:
line = self.get_line(f, byteline)
if not line:
continue
# Look for section headers
config_title = re.search('\[(.*?)\]', line)
if config_title != None and (config_title.group(1) in self.__CONFIG_SECTIONS__.values()):
for i, v in self.__CONFIG_SECTIONS__.items():
if v == config_title.group(1):
type = i
continue
continue
# Unknown Section header, so ignore
if line[0:1] == '[':
type = 0
continue
# Read Configuration options
elif type == 1:
try:
# Strip the name from the value
a = line.split('=',1)
# Boolean values
if a[0].lower().strip() in ('write_info_files', 'verbose', 'case_sensitive', 'daemon'):
if len(a) == 1:
self.opt_dict[a[0].lower().strip()] = True
elif a[1].lower().strip() in ('true', '1', 'on' ):
self.opt_dict[a[0].lower().strip()] = True
else:
self.opt_dict[a[0].lower().strip()] = False
# Values that can be None
elif a[0].lower().strip() in ('radio_device', 'radio_out', 'video_device', 'myth_backend','source_switch' , 'source','source_mixer'):
self.opt_dict[a[0].lower().strip()] = None if (len(a) == 1 or a[1].lower().strip() == 'none') else a[1].strip()
elif len(a) == 2:
#Integer values
if a[0].lower().strip() in ('log_level', 'radio_cardtype'):
try:
int(a[1])
except ValueError:
self.opt_dict[a[0].lower().strip()] = 0
else:
self.opt_dict[a[0].lower().strip()] = int(a[1])
#String values
else:
self.opt_dict[a[0].lower().strip()] = a[1].strip()
else:
log('Ignoring incomplete Options line in config file %s: %r\n' % (file, line))
except Exception:
log('Invalid Options line in config file %s: %r\n' % (file, line))
continue
# Read the channel stuff
if type == 2:
try:
# Strip the name from the frequency
a = line.split('=',1)
if len(a) != 2:
log('Ignoring incomplete Channel line in config file %s: %r\n' % (file, line))
continue
ch_num += 1
rfconf.frequencies[float(a[0].strip())] = ch_num
rfconf.channels[ch_num] = {}
rfconf.channels[ch_num]['frequency'] = float(a[0].strip())
rfconf.channels[ch_num]['title'] = unicode(a[1].strip())
if rfconf.channels[ch_num]['title'] == '':
rfconf.channels[ch_num]['title'] = u'Frequency %s' % a[0].strip()
except Exception:
log('Invalid Channel line in config file %s: %r\n' % (file, line))
continue
# Read the lirc IDs
if type == 3:
try:
# Strip the lircname from the command
a = line.split('=',1)
lirc_cmd = unicode(a[0].strip())
cmd_line = lirc_cmd
if len(a) > 1:
cmd_line = unicode(a[1].strip())
if cmd_line.lower() in rfconf.call_list.keys():
self.functioncalls[lirc_cmd] = rfconf.call_list[cmd_line.lower()]
self.functioncalls_lower[lirc_cmd.lower()] = rfconf.call_list[cmd_line.lower()]
elif (len(a) > 1) and cmd_line.lower()[0:8] == 'command:':
self.external_commands[lirc_cmd] =cmd_line[8:].strip()
self.external_commands_lower[lirc_cmd.lower()] = self.external_commands[lirc_cmd]
elif (len(a) > 1) and cmd_line.lower()[0:5] == 'bash:':
self.shell_commands[lirc_cmd] = []
quote_cnt = 0
quote_cmd = ''
word_cmd = ''
aa = cmd_line[5:].strip()
for c in range(len(aa)):
if quote_cnt == 1:
if aa[c] == '"':
self.shell_commands[lirc_cmd].append(quote_cmd)
quote_cnt = 0
quote_cmd = ''
continue
else:
quote_cmd = u'%s%s' % (quote_cmd, aa[c])
continue
elif quote_cnt == 0:
if aa[c] == '"':
quote_cnt = 1
quote_cmd = ''
elif aa[c] != ' ':
word_cmd = u'%s%s' % (word_cmd, aa[c])
continue
if word_cmd != '':
self.shell_commands[lirc_cmd].append(word_cmd)
word_cmd = ''
self.shell_commands_lower[lirc_cmd.lower()] = self.shell_commands[lirc_cmd]
else:
log('Ignoring Lirc line in config file %s: %r\n' % (file, line))
except Exception:
log('Invalid Lirc line in config file %s: %r\n' % (file, line))
continue
except Exception as e:
log(u'Error reading Config')
continue
f.close()
#~ self.write_config(True)
if 'log_level' in self.opt_dict.keys():
rfconf.log_level = self.opt_dict['log_level']
if 'log_file' in self.opt_dict.keys():
self.log_file = self.opt_dict['log_file']
if len(rfconf.channels) == 0:
# There are no channels so looking for an old ~\.ivtv\radioFrequencies file
if not self.read_radioFrequencies_File():
# We scan for frequencies
self.freq_list = rfcalls().detect_channels(config.opt_dict['radio_device'])
if len(self.freq_list) == 0:
return False
else:
ch_num = 0
for freq in self.freq_list:
ch_num += 1
rfconf.frequencies[freq] = ch_num
rfconf.channels[ch_num] = {}
rfconf.channels[ch_num]['frequency'] = freq
rfconf.channels[ch_num]['title'] = 'Channel %s' % ch_num
return True
# end read_config()
def read_radioFrequencies_File(self):
"""Check for an old RadioFrequencies file."""
if not os.access(self.ivtv_dir + '/radioFrequencies', os.F_OK and os.R_OK) :
self.args.config_file = None
return False
f = self.open_file(self.ivtv_dir + '/radioFrequencies')
if f == None:
self.args.config_file = None
return False
f.seek(0,0)
ch_num = 0
for byteline in f.readlines():
try:
line = self.get_line(f, byteline)
if not line:
continue
# Read the channel stuff
try:
# Strip the name from the frequency
a = re.split(';',line)
if len(a) != 2:
continue
ch_num += 1
rfconf.frequencies[float(a[1].strip())] = ch_num
rfconf.channels[ch_num] = {}
rfconf.channels[ch_num]['title'] = a[0].strip()
rfconf.channels[ch_num]['frequency'] = float(a[1].strip())
if rfconf.channels[ch_num]['title'] == '':
rfconf.channels[ch_num]['title'] = u'Frequency %s' % a[1].strip()
except Exception:
log('Invalid line in config file %s: %r\n' % (self.ivtv_dir + '/radioFrequencies', line))
continue
except Exception as e:
log(u'Error reading Config')
continue
f.close()
if len(rfconf.channels) == 0:
return False
return True
# end read_radioFrequencies_File()
def validate_commandline(self):
"""Read the commandline and validate the values"""
def is_video_device(path):
if path == None or path.lower() == 'none':
return None
if (not os.access(path, os.F_OK and os.R_OK)):
return False
if ((os.major(os.stat(path).st_rdev)) != 81):
return False
return path
if self.read_commandline() == 0:
return(0)
if self.args.version:
print("The Netherlands (%s)" % self.version(True))
print("The Netherlands (%s)" % rfconf.version(True))
return(0)
if self.args.description:
print("The Netherlands (%s)" % self.version(True))
print("The Netherlands (%s)" % rfconf.version(True))
print(description_text)
return(0)
conf_read = self.read_config()
if self.args.list_alsa:
print 'The available alsa audio-cards are:'
for c in rfcalls().get_alsa_cards():
print ' %s' % c
return(0)
if self.args.list_mixers:
if self.args.audio_card != None and self.args.audio_card in rfcalls().get_alsa_cards():
self.opt_dict['audio_card'] = self.args.audio_card
cardid = rfcalls().get_cardid(self.opt_dict['audio_card'])
print 'The available mixer controls for audio-card: %s are:' % self.opt_dict['audio_card']
for m in rfcalls().get_alsa_mixers(cardid):
print ' %s' % m
return(0)
if self.args.create_menu:
rfcalls().create_fm_menu_file(self.ivtv_dir, self.opt_dict['fifo_file'])
return(0)
if self.args.verbose != None:
self.opt_dict['verbose'] = self.args.verbose
rfconf.opt_dict['verbose'] = self.opt_dict['verbose']
if self.args.case_sensitive != None:
self.opt_dict['case_sensitive'] = self.args.case_sensitive
# Opening the logfile
if self.args.log_file != None:
rfconf.log_output = self.open_file(self.args.log_file, mode = 'ab')
if rfconf.log_output != None:
rfconf.log_file = self.args.log_file
sys.stderr = rfconf.log_output
else:
rfconf.log_output = self.open_file(self.log_file, mode = 'ab')
if rfconf.log_output != None:
rfconf.log_file = self.log_file
sys.stderr = rfconf.log_output
if self.args.log_file != None and not os.access(self.args.log_file, os.W_OK):
log('Error opening supplied logfile: %s. \nCheck permissions! Falling back to %s\n' % (self.args.log_file, self.log_file), 0)
if self.args.fifo_file != None:
self.opt_dict['fifo_file'] = self.args.fifo_file
if self.args.lirc_id != None:
self.opt_dict['lirc_id'] = self.args.lirc_id
if self.args.myth_backend != None:
self.opt_dict['myth_backend'] = self.args.myth_backend
if self.opt_dict['myth_backend'] == None:
if rfcalls().query_backend(socket.gethostname()) != -2:
self.opt_dict['myth_backend'] = socket.gethostname()
elif self.opt_dict['myth_backend'].lower().strip() == 'none':
self.opt_dict['myth_backend'] = None
if self.opt_dict['myth_backend'] != None and rfcalls().query_backend(self.opt_dict['myth_backend']) == -2:
log('The MythTV backend %s is not responding!\n' % self.opt_dict['myth_backend'],1)
log('Run with --myth-backend None to disable checking!\n', 0)
if self.args.radio_cardtype != None:
self.opt_dict['radio_cardtype'] = self.args.radio_cardtype
if self.opt_dict['radio_cardtype'] != None and 0 <= self.opt_dict['radio_cardtype'] <= 2:
if self.args.radio_device != None:
x = is_video_device(self.args.radio_device)
if x != False:
self.opt_dict['radio_device'] = x
x = is_video_device(self.opt_dict['radio_device'])
if x == False:
log('%s is not readable or not a valid radio device. Disabling radio\n' % self.opt_dict['radio_device'])
self.opt_dict['radio_cardtype'] = None
self.opt_dict['radio_device'] = None
self.opt_dict['video_device'] = None
self.opt_dict['radio_out'] = None
else:
self.opt_dict['radio_device'] = x
udevpath = rfcalls().query_udev_path( self.opt_dict['radio_device'], 'video4linux')
autodetect_card = None
for card in self.radio_devs:
if card['udevpath'] == udevpath:
autodetect_card = card
self.opt_dict['radio_cardtype'] = card['radio_cardtype']
break
else:
log('%s is not a valid radio device. Disabling radio\n' % self.opt_dict['radio_device'])
self.opt_dict['radio_cardtype'] = None
self.opt_dict['radio_device'] = None
self.opt_dict['video_device'] = None
self.opt_dict['radio_out'] = None
else:
self.opt_dict['radio_cardtype'] = None
self.opt_dict['radio_device'] = None
self.opt_dict['video_device'] = None
self.opt_dict['radio_out'] = None
if self.opt_dict['radio_cardtype'] != None:
if self.args.video_device != None:
self.opt_dict['video_device'] = self.args.video_device
udevpath = rfcalls().query_udev_path( self.opt_dict['video_device'], 'video4linux')
if autodetect_card['udevpath'] != udevpath:
log('%s is not the corresponding video device. Setting to %s\n' % (self.opt_dict['video_device'], autodetect_card['video_device']))
self.opt_dict['video_device'] = autodetect_card['video_device']
if self.args.radio_out != None:
self.opt_dict['radio_out'] = self.args.radio_out
if self.opt_dict['radio_cardtype'] == 0:
udevpath = rfcalls().query_udev_path( self.opt_dict['radio_out'], 'video4linux')
if autodetect_card['udevpath'] != udevpath:
log('%s is not the corresponding radio-out device. Setting to %s\n' % (self.opt_dict['radio_out'], autodetect_card['radio_out']))
self.opt_dict['radio_out'] = autodetect_card['radio_out']
elif self.opt_dict['radio_cardtype'] == 1:
if autodetect_card['radio_out'] != self.opt_dict['radio_out']:
log('%s is not the corresponding alsa device. Setting to %s\n' % (self.opt_dict['radio_out'], autodetect_card['radio_out']))
self.opt_dict['radio_out'] = autodetect_card['radio_out']
elif self.opt_dict['radio_cardtype'] == 2 and self.opt_dict['radio_out'] == self.select_card:
log(self.select_card)
else:
self.opt_dict['radio_cardtype'] = -1
self.opt_dict['radio_device'] = None
self.opt_dict['radio_out'] = None
self.opt_dict['video_device'] = None
if self.args.audio_card != None:
if self.args.audio_card in rfcalls().get_alsa_cards():
self.opt_dict['audio_card'] = self.args.audio_card
else:
log('%s is not a recognized audiocard\n' % self.args.audio_card, 1)
if not self.opt_dict['audio_card'] in rfcalls().get_alsa_cards():
log('%s is not a recognized audiocard\n' % self.opt_dict['audio_card'], 1)
self.opt_dict['audio_card'] = rfcalls().get_alsa_cards(0)
cardid = rfcalls().get_cardid(self.opt_dict['audio_card'])
if self.args.audio_mixer != None:
if self.args.audio_mixer in rfcalls().get_alsa_mixers(cardid):
self.opt_dict['audio_mixer'] = self.args.audio_mixer
else:
log('%s is not a recognized audiomixer]n' % self.args.audio_mixer, 1)
if not self.opt_dict['audio_mixer'] in rfcalls().get_alsa_mixers(cardid):
log('%s is not a recognized audiomixer\n' % self.opt_dict['audio_mixer'], 1)
self.opt_dict['audio_card'] = rfcalls().get_alsa_mixers(cardid, 0)
self.write_opts_to_log()
if self.args.configure:
if self.opt_dict['radio_device'] == None:
log('You need an accesible radio-device to configure\n')
self.write_config(False)
return(1)
else:
self.write_config(True)
return(0)
elif self.opt_dict['radio_out'] == self.select_card:
self.opt_dict['radio_out'] = None
if self.args.save_options:
self.write_config(False)
return(0)
if len(rfconf.channels) == 0 and self.opt_dict['radio_device'] != None:
log('There are no channels defined! Exiting!\n', 0)
log('Run with --card-type -1 to disable radio support!\n', 0)
log('or with --configure to probe for available frequencies!\n', 0)
return(1)
rfconf.opt_dict = self.opt_dict
if self.opt_dict['radio_cardtype'] != None and 0 <= self.opt_dict['radio_cardtype'] <= 2:
if not rfconf.set_mixer():
log('Error setting the mixer\n')
return(1)
# end validate_commandline()
def open_fifo_filehandles(self):
# Checking out the fifo file
try:
tmpval = os.umask(0115)
for f in (self.opt_dict['fifo_file'],):
if os.access(f, os.F_OK):
if not S_ISFIFO(os.stat(f).st_mode):
os.remove(f)
os.mkfifo(f, 0662)
if not os.access(f, os.R_OK):
os.chmod(f, 0662)
else:
os.mkfifo(f, 0662)
except:
log('Error creating fifo-file: %s\n' % self.opt_dict['fifo_file'],0)
os.umask(tmpval)
# Opening the read handle to the fifo
try:
self.fifo_read = config.open_file(self.opt_dict['fifo_file'], mode = 'rb', buffering = None)
except:
log('Error reading fifo-file: %s\n' % self.opt_dict['fifo_file'],0)
return(1)
# Opening the write handle to the fifo
try:
self.fifo_write = config.open_file(self.opt_dict['fifo_file'], mode = 'wb', buffering = None)
except:
log('Error writing to fifo-file: %s\n' % self.opt_dict['fifo_file'],0)
return(1)
# end open_fifo_filehandles()
def start_ircat(self):
if call(['pgrep', 'lircd']) != 0:
log('No lirc daemon found, so not starting ircat\n', 1)
else:
self.ircat_pid = Popen(["/usr/bin/ircat", self.opt_dict['lirc_id']], stdout = self.fifo_write, stderr = rfconf.log_output)
# end start_ircat()
def detect_radiodevice(self):
video_devs = []
for f in os.listdir('/dev/'):
if f[:5] == 'video':
video_devs.append(f)
audio_cards = {}
for id in range(len(rfcalls().get_alsa_cards())):
audio_cards[id] = rfcalls().query_udev_path(u'/dev/snd/controlC%s' % id, 'sound')
self.radio_devs = []
for f in os.listdir('/dev/'):
if f[:5] == 'radio':
devno = int(f[5:])
radio_card = {}
radio_card['radio_device'] = u'/dev/%s' % f
radio_card['udevpath'] = rfcalls().query_udev_path('/dev/%s' % f, 'video4linux')
if 'video%s' % devno in video_devs:
radio_card['video_device'] = u'/dev/video%s' % devno
else:
radio_card['video_device'] = None
if 'video%s' % (devno + 24) in video_devs:
radio_card['radio_out'] = u'/dev/video%s' % (devno + 24)
radio_card['radio_cardtype'] = 0
self.radio_devs.append(radio_card)
continue
if radio_card['udevpath'] == None:
radio_card['radio_out'] = None
radio_card['radio_cardtype'] = 2
self.radio_devs.append(radio_card)
continue
for id in range(len(rfcalls().get_alsa_cards())):
if audio_cards[id] == radio_card['udevpath']:
radio_card['radio_out'] = rfcalls().get_alsa_cards(id)
radio_card['radio_cardtype'] = 1
break
else:
radio_card['radio_out'] = self.select_card
radio_card['radio_cardtype'] = 2
self.radio_devs.append(radio_card)
# end detect_radiodevice()
def write_opts_to_log(self):
"""
Save the the used options to the logfile
"""
if rfconf.log_output == None:
return(0)
log(u'',1, 2)
log(u'Starting lircradio',1, 2)
log(u'Python versie: %s.%s.%s' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]),1, 2)
log(u'The Netherlands (%s)' % self.version(True), 1, 2)
log(u'The Netherlands (%s)' % rfconf.version(True), 1, 2)
log(u'log level = %s' % (rfconf.log_level), 1, 2)
log(u'config_file = %s' % (self.args.config_file), 1, 2)
log(u'verbose = %s\n' % self.opt_dict['verbose'], 1, 2)
log(u'fifo_file = %s\n' % self.opt_dict['fifo_file'], 1, 2)
log(u'lirc_id = %s\n' % self.opt_dict['lirc_id'], 1, 2)
log(u'case_sensitive = %s\n' % self.opt_dict['case_sensitive'], 1, 2)
log(u'radio_cardtype = %s\n' % self.opt_dict['radio_cardtype'], 1, 2)
log(u'radio_device = %s\n' % self.opt_dict['radio_device'], 1, 2)
log(u'radio_out = %s\n' % self.opt_dict['radio_out'], 1, 2)
log(u'video_device = %s\n' % self.opt_dict['video_device'], 1, 2)
log(u'myth_backend = %s\n' % self.opt_dict['myth_backend'], 1, 2)
log(u'audio_card = %s\n' % self.opt_dict['audio_card'], 1, 2)
log(u'audio_mixer = %s\n' % self.opt_dict['audio_mixer'], 1, 2)
log(u'source_switch = %s\n' % self.opt_dict['source_switch'], 1, 2)
log(u'source = %s\n' % self.opt_dict['source'], 1, 2)
#~ log(u'source_mixer = %s\n' % self.opt_dict['source_mixer'], 1, 2)
log(u'',1, 2)