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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
|
#!/usr/bin/python2
import sys
import getopt
import socket
import os , re
import time
import string
import glob
from string import letters
from string import digits
from xml.dom.minidom import parseString
import errno, fcntl
import urllib2,urllib,json
#http://code.activestate.com/recipes/576891/
class ApplicationLock:
'''
Ensures application is running only once, by using a lock file.
Ensure call to lock works. Then call unlock at program exit.
You cannot read or write to the lock file, but for some reason you can
remove it. Once removed, it is still in a locked state somehow. Another
application attempting to lock against the file will fail, even though
the directory listing does not show the file. Mysterious, but we are glad
the lock integrity is upheld in such a case.
Instance variables:
lockfile -- Full path to lock file
lockfd -- File descriptor of lock file exclusively locked
'''
def __init__ (self, lockfile):
self.lockfile = lockfile
self.lockfd = None
def lock (self):
'''
Creates and holds on to the lock file with exclusive access.
Returns True if lock successful, False if it is not, and raises
an exception upon operating system errors encountered creating the
lock file.
'''
try:
#
# Create or else open and trucate lock file, in read-write mode.
#
# A crashed app might not delete the lock file, so the
# os.O_CREAT | os.O_EXCL combination that guarantees
# atomic create isn't useful here. That is, we don't want to
# fail locking just because the file exists.
#
# Could use os.O_EXLOCK, but that doesn't exist yet in my Python
#
self.lockfd = os.open (self.lockfile,
os.O_TRUNC | os.O_CREAT | os.O_RDWR)
# Acquire exclusive lock on the file, but don't block waiting for it
fcntl.flock (self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
# Writing to file is pointless, nobody can see it
os.write (self.lockfd, "My Lockfile")
return True
except (OSError, IOError), e:
# Lock cannot be acquired is okay, everything else reraise exception
if e.errno in (errno.EACCES, errno.EAGAIN):
return False
else:
raise
def unlock (self):
try:
# FIRST unlink file, then close it. This way, we avoid file
# existence in an unlocked state
os.unlink (self.lockfile)
# Just in case, let's not leak file descriptors
os.close (self.lockfd)
except (OSError, IOError), e:
# Ignore error destroying lock file. See class doc about how
# lockfile can be erased and everything still works normally.
pass
#------- START OF TUNER CLASSES-----------
class v4l_tuners():
def __init__(self, device):
self.device = device
self.full_attribs = self.find_full_attribs()
self.full_udev_attribs = self.find_full_udev_attribs()
self.description,self.driver = self.find_description()
self.udev_props = self.parse_full_udev()
self.tuner_hash = self.find_tuner_hash()
self.udev_rule = self.create_udev_rule()
#self.staticdevice is set in create_udev_rule
def find_full_attribs(self):
cmd = 'v4l2-ctl -D -d' + self.device
return os.popen(cmd).readlines()
def find_full_udev_attribs(self):
cmd = 'udevadm info -a -p $(udevadm info -q path -n %s)' %self.device
return os.popen(cmd).readlines()
def find_description(self):
for line in self.full_attribs:
#print line
pos = string.find(line,"Driver name")
if pos >=0:
splitline= line.split(':')
Driver=splitline[1].strip()
pos = string.find(line,"Card type")
if pos >=0:
splitline= line.split(':')
Cardtype=splitline[1].strip()
pos = string.find(line,"Bus info")
if pos >=0:
splitline= line.split(':',1)
Businfo=splitline[1].strip()
return Cardtype,Driver
def parse_full_udev(self):
udev_props = []
#ATTRS{serial}=="00A2023E"\n',
#SUBSYSTEMS=="usb"\n',
#SUBSYSTEM=="video4linux"\n',
#KERNELS=="0000:08:08.0"\n',
#DRIVERS=="hdpvr"\n'
#DRIVERS=="ivtv"\n',
#ATTR{index}=="0"
match = ['SUBSYSTEM',
'SUBSYSTEMS',
'DRIVERS',
'KERNELS',
'ATTRS{serial}',
'ATTR{name}',
'ATTR{index}'
]
for item in match:
regex = re.compile('%s.*$' %item)
for line in self.full_udev_attribs:
m = regex.search(line.strip())
if m:
#print line
udev_props.append(line.strip())
break
#throw out kernels for usb subsystems.
if 'SUBSYSTEMS=="usb"' in udev_props:
#print "found usb"
new_udev_props=[]
for index, item in enumerate(udev_props):
#print item,index
if item.startswith("DRIVERS=="):
continue
elif item.startswith("KERNELS=="):
continue
else:
new_udev_props.append(item)
udev_props = new_udev_props
return udev_props
def is_hdpvr(self):
if self.description == "Hauppauge HD PVR":
return True
return False
def is_mpeg(self):
if self.driver in ["ivtv","saa7164[0]","saa7164"]:
return True
return False
def find_tuner_hash(self):
#tuner hash will be driven by card_type pci id and index
i=''
k=''
tuner_hash=''
card_type = self.get_card_type()
if card_type == "v4l_hdpvr":
for index, item in enumerate(self.udev_props):
if item.startswith("ATTRS{serial}=="):
hex_serial=item.split("==")[1].strip('''"''')
serial = int(hex_serial, 16)
tuner_hash="hdpvr_%s" %serial
else:
for index, item in enumerate(self.udev_props):
if item.startswith("KERNELS=="):
k=item.split("==")[1].strip('''"''')
k=k.replace(":", "_")
k=k.replace("0", "")
k=k.replace(".", "")
if item.startswith("ATTR{index}=="):
i=item.split("==")[1].strip('''"''')
tuner_hash="%s%s%s" %(card_type,k,i)
return tuner_hash
def escapeSpecialCharacters ( self, text, characters ):
for character in characters:
text = text.replace( character, '\\' + character )
return text
def create_udev_rule(self):
#DRIVERS=="ivtv", ATTR{name}=="ivtv? encoder MPG", KERNELS=="0000:08:09.0" SYMLINK+="myth/aivtv2"
line = ','.join(self.udev_props)
line += ' SYMLINK+="vstatic/%s"' %(self.get_tuner_hash())
self.staticdevice = "/dev/vstatic/%s" %(self.get_tuner_hash())
return self.escapeSpecialCharacters(line,'[]')
def card_mpeg_values(self):
values = {
'CardType' : 'MPEG' ,
'VideoDevice' : self.staticdevice,
'Defaultinput' : 'Television',
'HostName' : self.localhostname,
'dvb_wait_for_seqstart' :'1',
'signal_timeout' :'1000',
'channel_timeout' :'12000',
'diseqcid' :'NULL',
'dvb_eitscan' :'1'
}
return values
def card_hdpvr_values(self):
values = {
'CardType' : 'HDPVR' ,
'VideoDevice' : self.staticdevice,
'Defaultinput' : 'Television',
'HostName' : self.localhostname,
'dvb_wait_for_seqstart' :'1',
'signal_timeout' :'1000',
'channel_timeout' :'12000',
'diseqcid' :'NULL',
'dvb_eitscan' :'1'
}
return values
def do_insert(self,values):
try:
header = { 'User-Agent' : "autocard" }
url="http://127.0.0.1:6544/Capture/AddCaptureCard/"
data = urllib.urlencode(values)
req = urllib2.Request(url, data, header)
self.response = urllib2.urlopen(req)
except:
print " **Insert of %s failed" %self.staticdevice
def insert_myth(self,myth_tuner_list):
#check if tuner is already in the db
if self.staticdevice in myth_tuner_list:
print " *%s %s already in mythdb" %(self.get_card_type(),self.staticdevice)
else:
#determine values to use based on card type
print " Inserting %s" %self.staticdevice
if self.is_hdpvr() == True:
values = self.card_hdpvr_values()
self.do_insert(values)
elif self.is_mpeg() == True:
values = self.card_mpeg_values()
self.do_insert(values)
else:
print " Unknown V4l type, not adding to myth database"
return
def set_hostname(self,hostname):
self.localhostname = hostname
def set_tuner_index(self,index):
#only used by dvb, but here to be complete
self.tuner_index = index
def get_dev_node(self):
return self.device
def get_full_attribs(self):
return self.full_attribs
def get_full_udev_attribs(self):
return self.full_udev_attribs
def get_card_type(self):
if self.is_hdpvr() == True :
rc = "v4l_hdpvr"
elif self.is_mpeg() == True:
rc = "v4l_mpeg"
else:
rc = "v4l"
return rc
def get_description(self):
return self.description
def get_udev_probs(self):
return self.udev_props
def get_tuner_hash(self):
return self.tuner_hash
def get_udev_rule(self):
return self.udev_rule
def get_static_device(self):
return self.staticdevice
#-----
class hdhr_tuners():
def __init__(self, device,ip):
self.device = device
self.ip = ip
self.description = self.find_description()
self.staticdevice = device
def find_description(self):
command = '/usr/bin/hdhomerun_config %s get /sys/hwmodel' %self.device
results=os.popen(command,'r')
return results.readline().strip()
def insert_myth(self,hdhr_list):
if self.device in hdhr_list:
print " *hdhr %s already in mythtdb" %self.device
else:
print " Inserting HDHR %s" %self.device
self.do_insert()
pass
def do_insert(self):
try:
header = { 'User-Agent' : "autocard" }
url="http://127.0.0.1:6544/Capture/AddCaptureCard/"
values = self.card_hdhr_values()
data = urllib.urlencode(values)
req = urllib2.Request(url, data, header)
self.response = urllib2.urlopen(req)
except:
print " **Insert of %s failed" %self.device
def card_hdhr_values(self):
values = {
'CardType' : 'HDHOMERUN' ,
'VideoDevice' : self.device,
'Defaultinput' : 'Television',
'HostName' : self.localhostname,
'dvb_wait_for_seqstart' :'1',
'signal_timeout' :'1000',
'channel_timeout' :'3000',
'diseqcid' :'NULL',
'dvb_eitscan' :'1'
}
return values
def set_hostname(self,hostname):
self.localhostname = hostname
def set_tuner_index(self,index):
#only used by dvb, but here to be complete
self.tuner_index = index
def get_dev_node(self):
return self.device
def get_card_type(self):
return "hdhr"
def get_description(self):
desc = "%s - %s" %(self.description,self.ip)
return desc
def get_udev_rule(self):
return
def get_tuner_hash(self):
return self.device
def get_static_device(self):
return self.staticdevice
#-----
class dvb_tuners():
def __init__(self, device):
self.device = device
self.tuner_index = 1
self.dvb_number = self.find_dvb_number()
self.description = self.find_description()
self.full_udev_attribs = self.find_full_udev_attribs()
self.udev_props = self.parse_full_udev()
self.tuner_hash = self.find_tuner_hash()
self.udev_rule = self.create_udev_rule()
#self.staticdevice is set in create_udev_rule
def find_description(self):
command = '/usr/bin/dvb-fe-tool -a %s' %self.dvb_number
results=os.popen(command,'r')
line = results.readline().strip()
d = line.split('''Frontend (''')
dd = d[0].split('''Device ''')
return dd[1]
def find_full_udev_attribs(self):
cmd = 'udevadm info -a -p $(udevadm info -q path -n %s)' %self.device
return os.popen(cmd).readlines()
def find_dvb_number(self):
#/dev/dvb/adapter2/frontend0
d=self.device.split("/")[3]
dvb_number=d.partition("adapter")[2]
return dvb_number
def parse_full_udev(self):
udev_props = ['KERNEL=="dvb?.frontend?"']
#ATTRS{serial}=="00A2023E"\n',
#SUBSYSTEMS=="usb"\n',
#SUBSYSTEM=="video4linux"\n',
#KERNELS=="0000:08:08.0"\n',
#DRIVERS=="hdpvr"\n'
#DRIVERS=="ivtv"\n',
#ATTR{index}=="0"
#KERNEL=="dvb1.frontend0"
match = ['SUBSYSTEM',
'SUBSYSTEMS',
'DRIVERS',
'KERNELS',
'ATTRS{serial}',
'ATTR{name}',
'ATTR{index}'
]
for item in match:
regex = re.compile('%s.*$' %item)
for line in self.full_udev_attribs:
m = regex.search(line.strip())
if m:
#print line
udev_props.append(line.strip())
break
#throw out kernels for usb subsystems.
if 'SUBSYSTEMS=="usb"' in udev_props:
#print "found usb"
new_udev_props=[]
for index, item in enumerate(udev_props):
#print item,index
if item.startswith("DRIVERS=="):
continue
elif item.startswith("KERNELS=="):
continue
else:
new_udev_props.append(item)
udev_props = new_udev_props
return udev_props
def find_tuner_hash(self):
#tuner hash will be driven by card_type pci id and index
i=''
k=''
tuner_hash=''
card_type = self.get_card_type()
for index, item in enumerate(self.udev_props):
if item.startswith("KERNELS=="):
k=item.split("==")[1].strip('''"''')
k=k.replace(":", "_")
k=k.replace("0", "")
k=k.replace(".", "")
if item.startswith("ATTR{index}=="):
i=item.split("==")[1].strip('''"''')
tuner_hash="%s%s%s" %(card_type,k,i)
return tuner_hash
def escapeSpecialCharacters ( self, text, characters ):
for character in characters:
text = text.replace( character, '\\' + character )
return text
def create_udev_rule(self):
line = ','.join(self.udev_props)
line += ' RUN+="/usr/MythVantage/bin/udev_link.sh %s $env{DEVNAME} "' %(self.get_tuner_hash())
self.staticdevice = "/dev/dvb/adapter_static_%s_%s/frontend0" %(self.get_tuner_hash(),self.tuner_index)
return self.escapeSpecialCharacters(line,'[]')
def insert_myth(self,myth_tuner_list):
if self.staticdevice in myth_tuner_list:
print " *dvb %s already in mythtdb" %self.staticdevice
else:
print " Inserting DVB Tuner %s" %self.staticdevice
self.do_insert()
pass
def do_insert(self):
try:
header = { 'User-Agent' : "autocard" }
url="http://127.0.0.1:6544/Capture/AddCaptureCard/"
values = self.card_dvb_values()
data = urllib.urlencode(values)
req = urllib2.Request(url, data, header)
self.response = urllib2.urlopen(req)
except:
print " **Insert of %s failed" %self.staticdevice
def card_dvb_values(self):
values = {
'CardType' : 'DVB' ,
'VideoDevice' : self.staticdevice,
'Defaultinput' : 'Television',
'HostName' : self.localhostname,
'dvb_wait_for_seqstart' :'1',
'signal_timeout' :'1000',
'channel_timeout' :'12000',
'diseqcid' :'NULL',
'dvb_on_demand' :'0',
'dvb_eitscan' :'1'
}
return values
def set_tuner_index(self,index):
self.tuner_index = index
self.tuner_hash = self.find_tuner_hash()
self.udev_rule = self.create_udev_rule()
def set_hostname(self,hostname):
self.localhostname = hostname
def get_dev_node(self):
return self.device
def get_card_type(self):
return "dvb"
def get_description(self):
return self.description
def get_full_udev_attribs(self):
return self.full_udev_attribs
def get_tuner_hash(self):
return self.tuner_hash
def get_udev_rule(self):
return self.udev_rule
def get_static_device(self):
return self.staticdevice
#--
class infinitv_tuner():
def __init__(self, tuner_number,ip):
self.tuner_number = tuner_number
self.ceton_defined_tuner = tuner_number + 1
self.ip = ip
self.serial_num = self.find_serial()
self.connection = self.find_connection()
self.description = self.find_description()
self.staticdevice = self.find_static()
def find_static(self):
static="%s-RTP.%s" %(self.ip,self.tuner_number)
return static
def find_connection(self):
uri='get_var.json?i=0&s=diag&v=Host_Connection'
try:
url="http://%s/%s" %(self.ip,uri)
req = urllib2.Request(url)
r = urllib2.urlopen(req).read()
response = r.split()[2].strip('''"''')
except:
response='unknown'
return response
def find_serial(self):
uri='get_var.json?i=0&s=diag&v=Host_Serial_Number'
try:
url="http://%s/%s" %(self.ip,uri)
req = urllib2.Request(url)
r = urllib2.urlopen(req).read()
response = r.split()[2].strip('''"''')
except:
response='unknown'
return response
def find_description(self):
desc="Ceton InfiniTV %s Tuner %s" %(self.connection,
self.ceton_defined_tuner)
return desc
def do_insert(self):
try:
header = { 'User-Agent' : "autocard" }
url="http://127.0.0.1:6544/Capture/AddCaptureCard/"
values = self.card_ceton_values()
data = urllib.urlencode(values)
req = urllib2.Request(url, data, header)
self.response = urllib2.urlopen(req)
except:
print " **Insert of %s failed" %self.staticdevice
def card_ceton_values(self):
values = {
'CardType' : 'CETON' ,
'VideoDevice' : self.staticdevice,
'Defaultinput' : 'Television',
'HostName' : self.localhostname,
'dvb_wait_for_seqstart' :'1',
'signal_timeout' :'1000',
'channel_timeout' :'3000',
'diseqcid' :'NULL',
'dvb_eitscan' :'1'
}
return values
def insert_myth(self,myth_tuner_list):
if self.staticdevice in myth_tuner_list:
print " *infinitv %s already in mythtdb" %self.staticdevice
else:
print " Inserting Ceton InfinitTV Tuner %s" %self.staticdevice
self.do_insert()
return
def write_proxy(self):
directory="/etc/ceton_proxy.d"
if not os.path.exists(directory):
os.makedirs(directory)
proxy_file = "%s/%s" %(directory,self.get_proxy_num())
try:
f = open(proxy_file,'w')
line="port=%s\n" %(self.get_proxy_num())
f.write(line)
line="ip=%s\n" %(self.ip)
f.write(line)
except:
print " *Problem creating proxy file %s" %proxy_file
return
def get_static_device(self):
return self.staticdevice
def get_tuner_hash(self):
return self.staticdevice
def set_proxy(self,proxy_num):
self.proxy_num = 7000 + proxy_num
return
def set_hostname(self,hostname):
self.localhostname = hostname
return
def set_tuner_index(self,index):
#only used by dvb, but here to be complete
self.tuner_index = index
return
def get_proxy_num(self):
return self.proxy_num
def get_udev_rule(self):
return
def get_card_type(self):
return "infinitv"
def get_description(self):
desc = "%s - %s" %(self.description,self.ip)
return desc
def get_serial_number(self):
return self.serial_num
#-- end infinitv
#------------------END TUNER CLASSES-----------------------
#------------------START OF TUNER GATHERING-----------------
def find_hdhr_tuner(hdhrdevice):
htuner_list=[]
command="/usr/bin/hdhomerun_config %s get /tuner%s/status"
#loop over 4 possible tuners
for i in range(4):
c=command %(hdhrdevice,i)
results=os.popen(c,'r')
lines=results.readlines()
try:
#if the first line starts with error, assume it's not a tuner and
#there are no more tuners for this device.
if lines[0].strip().startswith("ERROR"):
break
else:
t="%s-%s" %(hdhrdevice,i)
htuner_list.append(t)
except:
pass
return htuner_list
def gather_hdhr(tuner_list):
command="/usr/bin/hdhomerun_config --discover"
results=os.popen(command,'r')
lines=results.readlines()
try:
if lines[0].strip().split()[0] == "no":
print "HDHOMERUN not detected"
else:
for line in lines:
hdhrdevice=line.strip().split()[2]
hdhrip = line.strip().split()[5]
tuners = find_hdhr_tuner(hdhrdevice)
for t in tuners:
tuner_list.append(hdhr_tuners(t,hdhrip))
except:
print "Error finding HDHOMERUN"
return tuner_list
def gather_v4l(tuner_list):
try:
filelist = os.listdir('/dev/v4l/by-path/')
except OSError:
pass
#fakelist=['/dev/v4l/video3', 'ivtv', 'WinTV PVR 500 (unit #2)', '0000:04:09.0']
#cardlist.append(fakelist)
try:
p = re.compile('^/dev/video?\d$')
filelist = glob.glob("/dev/v4l/by-path/*video*")
for device in filelist:
Device=os.path.realpath(device)
if not p.search(Device):
continue
#print "real device node"
#print Device
tuner_list.append(v4l_tuners(Device))
except IOError:
print "no v4l cards found"
return tuner_list
def gather_dvb(tuner_list):
try:
filelist = os.listdir('/dev/dvb/')
except OSError:
pass
try:
for d in filelist:
if os.path.islink("/dev/dvb/"+d):
continue
Device=os.path.realpath("/dev/dvb/"+d+"/frontend0")
tuner_list.append(dvb_tuners(Device))
except:
print "no dvb cards found"
return tuner_list
def gather_ceton(tuner_list):
#find and configure ctn network interfaces
ceton_network_list = find_ceton_network_list()
#find all the cards on a network interface
for iface in ceton_network_list:
#command="cat /tmp/find_ceton.txt"
print "Scanning %s network for ceton infinitv" %iface
command="/usr/MythVantage/bin/discover_infinitv.py %s" %iface
results=os.popen(command,'r')
lines=results.readlines()
try:
print lines
if lines[0].strip().split()[0].lower() == "no":
print "Ceton not detected on %s" %iface
else:
for line in lines:
#Found InfiniTV. Location URL: http://192.168.200.1/description.xml
#cetondevice = line.strip().split()[0]
cetonip = line.strip().split("/")[2]
tuners = [0,1,2,3]
for t in tuners:
tuner_list.append(infinitv_tuner(t,cetonip))
except:
print "Error finding Ceton InfinitTV on %s" %iface
return tuner_list
#------------------END OF TUNER GATHERING-----------------
#----linhes specific for networking
def config_ctn_network(ctn_iface):
etcnetdir = "/etc/net/ifaces/%s" %ctn_iface
if not os.path.exists(etcnetdir):
print "Creating config for interface %s" %ctn_iface
os.mkdir(etcnetdir)
outline='''
TYPE=eth
DISABLED=no
BOOTPROTO=dhcp
ONBOOT=yes
CONFIG_WIRELESS=no
DHCP_ARGS="-C resolv.conf"
'''
optionfile="%s/options" %etcnetdir
f = open(optionfile, 'w')
f.write(outline)
f.close()
command="/etc/net/scripts/network.init start"
os.system(command)
else:
pass #config is present
def find_ceton_network_list():
import netifaces
netinterfaces = netifaces.interfaces()
ctnip=[]
for i in netinterfaces:
if i.startswith("ctn") or i.startswith("usb"):
#configure and start ctn network
try:
config_ctn_network(i)
#read ip
ctnip.append(netifaces.ifaddresses(i)
[netifaces.AF_INET][0]['addr'])
except:
print " * Error scanning network interface %s" %i
print " * Please check that the interface is ready and configured"
return ctnip
#--end of linhes specific
def gather_tuners():
tuner_list = []
tuner_list = gather_hdhr(tuner_list)
tuner_list = gather_v4l(tuner_list)
tuner_list = gather_dvb(tuner_list)
tuner_list = gather_ceton(tuner_list)
#set the number of times we have seen a specific tuner_hash
#This will be used by dvb when tuner_hashs conflict
tuner_count = {}
for i in tuner_list:
th = i.get_tuner_hash()
if th in tuner_count:
tuner_count[th] += 1
else:
tuner_count[th] = 1
i.set_tuner_index(tuner_count[th])
return tuner_list
def trigger_udev():
print "Reloading udev rules"
command = '/usr/bin/udevadm control --reload'
results=os.popen(command,'r')
print "Triggering udev events"
command = '/usr/bin/udevadm trigger'
results=os.popen(command,'r')
def write_udev_file(rule_list):
udevfile = '/etc/udev/rules.d/99-mv-persistent-video.rules'
try:
f = open(udevfile, 'w')
line = "#Do not edit this file, it is auto generated by autocard.py \n\n"
f.write(line)
for rule in rule_list:
if rule:
line = "%s \n" %(rule)
f.write(line)
f.close()
except:
print "Error creating %s" %udevfile
trigger_udev()
def write_udev_map(tuner_list):
udevfile = '/etc/udev/mv-persistent-video.description'
try:
f = open(udevfile, 'w')
line = "#Do not edit this file, it is auto generated by autocard.py \n"
f.write(line)
line = "#This file is used to generate the static tuner card web page\n"
f.write(line)
for i in tuner_list:
if i.get_card_type() == "hdhr":
pass
line="hdhr:%s:%s" %(i.get_description(),i.get_static_device())
f.write(line)
f.write("\n")
elif i.get_card_type() == "v4l_mpeg":
pass
line="V4L_mpeg:%s: %s " %(i.get_description(),i.get_static_device())
f.write(line)
f.write("\n")
elif i.get_card_type() == "v4l":
pass
line="V4L:%s:%s " %(i.get_description(),i.get_static_device())
f.write(line)
f.write("\n")
elif i.get_card_type() == "v4l_hdpvr":
pass
line="hdpvr:%s: %s " %(i.get_description(),i.get_static_device())
f.write(line)
f.write("\n")
elif i.get_card_type() == "dvb":
line="dvb:%s: %s " %(i.get_description(),i.get_static_device())
f.write(line)
f.write("\n")
elif i.get_card_type() == "infinitv":
line="infinitv:%s:%s:%s" %(i.get_description(),
i.get_static_device(),
i.get_proxy_num())
f.write(line)
f.write("\n")
else:
print i
line = i
f.write(line)
f.write("\n")
except:
print "Error creating %s" %udevfile
f.close()
def checkURL(url):
try:
connection = urllib2.urlopen(url,None,3)
code=connection.getcode()
connection.close()
if code == 200:
rc=0
#except urllib2.HTTPError, e:
except:
rc=1
return rc
def getURL(url):
dom = None
try:
connection = urllib2.urlopen(url,None,3)
data = connection.read()
connection.close()
dom = parseString(data)
#except urllib2.HTTPError, e:
except:
pass
return dom
def find_hdhr_in_use():
hdhr_list = []
url='http://127.0.0.1:6544/Capture/GetCaptureCardList?CardType=HDHOMERUN'
data = getURL(url)
if data:
xmlTags = data.getElementsByTagName('VideoDevice')
for i in xmlTags:
xmlTag=i.toxml()
xmlData=xmlTag.replace('<VideoDevice>','').replace('</VideoDevice>','')
hdhr_list.append(xmlData)
return hdhr_list
def find_in_use_card_list():
in_use_tuner_list=[]
url='http://127.0.0.1:6544/Capture/GetCaptureCardList?HostName=%s' %localhostname
data = getURL(url)
if data:
xmlTags = data.getElementsByTagName('VideoDevice')
for i in xmlTags:
xmlTag=i.toxml()
xmlData=xmlTag.replace('<VideoDevice>','').replace('</VideoDevice>','')
in_use_tuner_list.append(xmlData)
return in_use_tuner_list
def usuage():
help='''
autocard.py takes the guess work out of setting up tuner/capture cards.
Options:
help: This help screen.
print: Find and printout any detected capture cards, including
network based tuners like the HDHomeRun.
udev: Creates a set of static device nodes for local capture cards.
Rules are based on pci/usb path so moving the card into a
different expansion slot will nullify the udev rule.
HDPVR devices use the serial number as the primary key for
the udev rule list.
insertdb: Insert any detected cards into the MythTV database using the
static device generated by udev.
insertdb will also generate udev rules. Tuners that are
already defined will not be readded.
write_proxy: Write out the config used by the service ceton_proxy.
all: The same as using: print udev insertdb write_proxy
EX:
autocard.py print
autocard.py insertdb
'''
print help
def main(argv):
listcards = False
udev = False
insertdb = False
write_proxy = False
if argv==[] or "help" in argv:
usuage()
sys.exit(0)
if "print" in argv:
listcards = True
if "udev" in argv:
udev = True
write_proxy = True
if "insertdb" in argv:
insertdb = True
udev = True
write_proxy = True
if "write_proxy" in argv:
write_proxy = True
if "all" in argv:
udev = True
insertdb = True
listcards = True
write_proxy = True
tuner_list = gather_tuners()
rule_list = []
#setting the proxy port for ceton webpage
ceton_proxy = 1
for i in tuner_list:
if i.get_card_type() == "infinitv":
i.set_proxy(ceton_proxy)
ceton_proxy = ceton_proxy + 1
#setting the hostname for each tuner
i.set_hostname(localhostname)
rule_list.append(i.get_udev_rule())
if listcards == True:
print i.get_card_type()
print "----------------"
print "\t" , i.get_description()
print "\t" , i.get_static_device()
print("Writing out tuner map")
write_udev_map(tuner_list)
restart_proxy=False
if write_proxy == True:
for i in tuner_list:
if i.get_card_type() == "infinitv":
i.write_proxy()
restart_proxy=True
if restart_proxy == True:
command="add_service.sh cetonproxy"
os.system(command)
print" Restarting ceton proxy"
command="sv restart cetonproxy"
os.system(command)
if udev == True:
print("Writing out udev rules")
write_udev_file(rule_list)
if insertdb == True:
be_ready = False
i = 0
while i < 10 or be_ready :
if checkURL('http://127.0.0.1:6544') == 0:
be_ready = True
break
i = i + 1
print "Waiting for MythTV backend connection: %s/10" %i
time.sleep(5)
if be_ready == True :
#find all HDHR
in_use_hdhr_list = find_hdhr_in_use()
#find other cards local
in_use_local_card_list = find_in_use_card_list()
print "Adding cards to mythtv database"
for i in tuner_list:
if i.get_card_type() == "hdhr":
i.insert_myth(in_use_hdhr_list)
else:
i.insert_myth(in_use_local_card_list)
if __name__ == "__main__":
localhostname = socket.gethostname()
applock = ApplicationLock ('/var/run/autocard.lock')
if (applock.lock ()):
#print ("Obtained lock")
main(sys.argv[1:])
#print ("Unlocking")
applock.unlock ()
else:
print ("Unable to obtain lock, exiting")
|