summaryrefslogtreecommitdiffstats
path: root/abs/core-testing/LinHES-config-SVN/autocard.py
blob: 03eecac71303b376fd772b32e30d6b0738140f9d (plain)
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
#!/usr/bin/python
# import MySQL module
#jm
import MySQLdb
import sys
import getopt
import socket
import os
import time
import string
import glob
from string import letters
from string import digits
def INSERTNULL_SOURCE(name,xmltvgrabber,userid,freqtable,lineupid,password,useeit):
    cursor = db.cursor()
    cursor.execute("INSERT INTO videosource(name,xmltvgrabber,userid,freqtable,lineupid,password,useeit) VALUES(%s,%s,%s,%s,%s,%s,%s);",(name,xmltvgrabber,userid,freqtable,lineupid,password,useeit))

def INSERTCARD_INTOMYTH(Device,Driver,Cardvendor):
    global currenthostname
    print Device
    print Driver,
    print Cardvendor
    cursor = db.cursor()
    insert = "false"
    if Driver == "ivtv" :
        cardtype="MPEG"
        defaultinput="Tuner 1"
        insert="true"
    if Cardvendor ==  "pcHDTV HD3000 HDTV":
        insert="false"
        cardtype ="whocares"

        #print insert
    if insert == "true" :
        cursor.execute("INSERT INTO capturecard (videodevice,cardtype,defaultinput,hostname) VALUES(%s,%s,%s,%s);",(Device,cardtype,defaultinput,currenthostname))

def INSERTHDR_INTOMYTH(deviceid,tuner_number):
    cardtype='HDHOMERUN'
    defaultinput='MPEG2TS'
    global currenthostname
    print deviceid
    print cardtype
    print defaultinput
    print tuner_number
    cursor = db.cursor()
   #print insert
    cursor.execute("INSERT INTO capturecard (videodevice,cardtype,defaultinput,dbox2_port ,hostname) VALUES(%s,%s,%s,%s,%s);",(deviceid,cardtype,defaultinput,tuner_number,currenthostname))

def INSERTAUTOCARD():
    global cardlist
    global currenthostname
    # create a cursor
    cursor = db.cursor()


    for i in range( 1 , len(cardlist)):
        insert = "false"
#        print cardlist[i]
        Device=cardlist[i][0]
        Driver=cardlist[i][1]
        Cardvendor=cardlist[i][2]
        Businfo=cardlist[i][3]
        if Driver == "ivtv" :
            insert="true"
            devicestatus="unused"
        if Cardvendor ==  "pcHDTV HD3000 HDTV":
            insert="false"
            cardtype ="whocares"
        if Driver == "hdr":
            insert="true"
            devicestatus="unused"

        if insert == "true" :
            cursor.execute("delete from autocard where uniqid=%s;",(Businfo))
            if Driver=="hdr":
                Cardvendor="HDHOMERUN Tuner 1"
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))
                Cardvendor="HDHOMERUN Tuner 2"
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))

            else:
                cursor.execute("INSERT INTO autocard (dev,driver,description,uniqid,devicestatus,hostname) VALUES(%s,%s,%s,%s,%s,%s);",(Device,Driver,Cardvendor,Businfo,devicestatus,currenthostname))



def PRINTINFO():
    global cardlist

    for list in cardlist:
        if  list != "_placeholder_":
            print list
            #print "-------------"

def GATHER_HDR():
    global cardlist
    command="/usr/bin/hdhomerun_config --discover"
    results=os.popen(command,'r')
    line=results.readline()
    if line.strip().split()[0] == "no":
        print "HDHOMERUN not detected"
    else:
        print line
        hdrdevice=line.strip().split()[2]
        print hdrdevice
        Driver="hdr"
        Device=hdrdevice
        Cardtype="HDHOMERUN"
        Businfo=hdrdevice
        cardprops =  [Device,Driver , Cardtype , Businfo]
        cardlist.append(cardprops)


def GATHER_v4l_CARDS():
    global cardlist
    cardlist=["_placeholder_"]
   # print "Looking for v4l cards"
    try:
        filelist = os.listdir('/dev/v4l/')
    except OSError:
        filelist=" "
        #fakelist=['/dev/v4l/video3', 'ivtv', 'WinTV PVR 500 (unit #2)', '0000:04:09.0']
        #cardlist.append(fakelist)
    try:
        filelist = glob.glob("/dev/v4l/video?")
        Driver=""
        Cardtype=""
        Businfo=""
        numcards  = 0
        for Device in filelist:
            #print card
            numcards = numcards+1
            cmd = 'v4l2-ctl -D -d' + Device
            for line in os.popen(cmd).readlines():
                #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()

            #print Device,Driver , Cardtype , Businfo,numcards
            cardprops =  [Device,Driver , Cardtype , Businfo]
            cardlist.append(cardprops)
    except IOError:
        print "no v4l cards found"
        sys.exit(2)


def WRITEUDEV_IVTV():
    global insertmyth
    cursor = db.cursor()
    #add ivtv,cid lookup loop through until empty.
    cursor.execute("select distinct(uniqid) from autocard where driver='ivtv' and devicestatus='will-add'")
    cidrows = cursor.fetchall()
    for row in cidrows:
        cid=row[0]
        cursor.execute("select dev,driver,description,devicestatus,hostname from  autocard where uniqid=%s limit 1;",(cid))
        result = cursor.fetchone()
        description=result[2]
        driver='DRIVERS==\"ivtv\"'
        ATTRNAME='ATTR{name}=="ivtv? encoder MPG"'
        KERNELS='KERNELS==\"'
        KERNELS+=cid
        KERNELS+="\""
        #filter out non digit or chars
        keep=letters.join(digits)
        description=filter(lambda c: c in keep, description)
        devnode="ivtv/"
        #devnode+=description + "_"
        udevcid=cid.partition(":")
        devnode+=udevcid[2]
        devnode+="_video"
        UDEV_RULE=driver +', '+ATTRNAME+', '+ KERNELS +', ' + 'NAME=\"' + devnode + '"'
        print "Here is the udev rule"
        print UDEV_RULE
        filename='/etc/udev/rules.d/11-ivtv-'+cid+'.rules'
        file = open(filename,'w')
        file.write(UDEV_RULE)
        if ( insertmyth == "true"):
            devnode="/dev/"+devnode
            INSERTCARD_INTOMYTH(devnode,"ivtv",description)
            cursor.execute("update autocard set devicestatus='done' where uniqid=%s;",(cid))
#now insert HDR
    cursor.execute("select distinct(uniqid),description from autocard where driver='hdr' and devicestatus='will-add'")
    cidrows = cursor.fetchall()
    for row in cidrows:
              if ( insertmyth == "true"):
                  deviceid=row[0]
                  #cardtype="HDHOMRUN"
                  #defaultinput="MPEG2TS"
                  dbox2_port=row[1]
                  tuner_number=dbox2_port.rpartition(' ')[2]
                  INSERTHDR_INTOMYTH(deviceid,tuner_number)
                  cursor.execute("update autocard set devicestatus='done' where uniqid=%s and description=%s;",(deviceid,dbox2_port))



def CLEARAUTOCARD():
    cursor = db.cursor()
    cursor.execute("delete from autocard")

def RELOADUDEV():
        print "relaoding udev rules"
        os.system('udevcontrol reload_rules')
        os.system('rmmod ivtv')
        os.system('udevtrigger')


def usage():
    print " -h   help"
    print " -g   gather and print out the found cards"
    print " -w   write out the udev rules"
    print " -i   insert cards into myth that are marked will-add(only used with -w)"
    print " -r   reload udev rules"
    print " -c   clear the autocard db"

def main(argv):
    global db
    global cardlist
    global currenthostname
    currenthostname=""
    writeudev="false"
    global insertmyth
    insertmyth ="false"

    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    try:
        cursor = db.cursor()
        cursor.execute("describe autocard;")
    except  MySQLdb.Error, e:
        cursor.execute("create table autocard(dev varchar(50),driver varchar(50),description varchar(50),uniqid varchar(50), devicestatus varchar(50),hostname varchar(50));")
        print "table created"

    if ( currenthostname == "" ):
         currenthostname = socket.gethostname()


    try:
        opts, args = getopt.getopt(argv, "hgwircd", ["help", "gathercards",  "writeudev" ,"insert" , "reloadudev" , "clearautocard"] )
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
             usage()
             sys.exit()
        elif opt in ( "-g" , "--gathercards"):
             GATHER_v4l_CARDS()
             GATHER_HDR()
             INSERTAUTOCARD()
             PRINTINFO()
        elif opt in ("-w", "--writeudev"):
             writeudev="true"
        elif opt in ("-i", "--insert"):
             insertmyth="true"
        elif opt in ( "-r" , "--reloadudev"):
             RELOADUDEV()
        elif opt in ( "-c" , "--clearautocard"):
             CLEARAUTOCARD()
        elif opt in ( "-d" ):
             INSERTCARD_INTOMYTH("file:/myth/video/TripThe1939.mpeg","ivtv","Dummy tuner")
             INSERTNULL_SOURCE("dummy","/bin/true","","default","NULL","NULL","0")

    if ( writeudev == "true"):
        WRITEUDEV_IVTV()






if __name__ == "__main__":
    main(sys.argv[1:])





#mysql>  create table autocard(dev varchar(50),driver varchar(50),description varchar(50),uniqid varchar(50), devicestatus varchar(50),hostname varchar(50));
#Query OK, 0 rows affected (0.14 sec)

#mysql> describe autocard;
#+--------------+-------------+------+-----+---------+-------+
#| Field        | Type        | Null | Key | Default | Extra |
#+--------------+-------------+------+-----+---------+-------+
#| dev          | varchar(50) | YES  |     | NULL    |       |
#| driver       | varchar(50) | YES  |     | NULL    |       |
#| description  | varchar(50) | YES  |     | NULL    |       |
#| uniqid       | varchar(50) | YES  |     | NULL    |       |
#| devicestatus | varchar(50) | YES  |     | NULL    |       |
#| hostname     | varchar(50) | YES  |     | NULL    |       |
#+--------------+-------------+------+-----+---------+-------+