Advertisement
Guest User

EpgDataCap_Bon network sample in Python

a guest
Oct 23rd, 2012
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.35 KB | None | 0 0
  1. import socket
  2. import struct
  3. import binascii
  4. import sys,os
  5. import re
  6. import datetime
  7.  
  8.  
  9. HOST = '192.168.1.101'
  10. PORT = 4510
  11.  
  12. CMD2_EPG_SRV_ENUM_RESERVE = 1011
  13. CMD2_EPG_SRV_GET_RESERVE = 1012
  14. CMD2_EPG_SRV_ADD_RESERVE = 1013
  15. CMD2_EPG_SRV_CHG_RESERVE = 1015
  16. CMD2_EPG_SRV_ENUM_SERVICE = 1021
  17. CMD2_EPG_SRV_GET_PG_INFO = 1023
  18. CMD2_EPG_SRV_SUSPEND = 1051
  19.  
  20. CMD_SUCCESS = 1
  21.  
  22. RECMODE_ALL = 0
  23. RECMODE_SERVICE = 1
  24. RECMODE_NO = 5
  25.  
  26. RESERVE_EXECUTE = 0
  27. RESERVE_PILED_UP = 1
  28. RESERVE_NO_EXECUTE = 2
  29.  
  30.  
  31. def readstr(buf, offset):
  32.   ll, = struct.unpack('<I', buf[offset:offset+4])
  33.   return (ll, buf[offset+4:offset+ll].decode('utf16', 'ignore')[:-1]) # remove NULL char
  34.  
  35.  
  36. def writestr(st):
  37.   buf = (st+'\0').encode('utf16', 'ignore')[2:] # remove BOM
  38.   return struct.pack('<I', len(buf)+4) + buf
  39.  
  40.  
  41. def readservicedat(buf, offset):
  42.   co = offset
  43.  
  44.   bsize, = struct.unpack('<I', buf[co:co+4])
  45.   co += 4
  46.  
  47.   netID,tsID,srvID = struct.unpack('<HHH', buf[co:co+6])
  48.   co += 6
  49.  
  50.   srvtype,partflg = struct.unpack('<BB', buf[co:co+2])
  51.   co += 2
  52.  
  53.   lsrvproname,srvproname = readstr(buf, co)
  54.   co += lsrvproname
  55.  
  56.   lsrvname,srvname = readstr(buf, co)
  57.   co += lsrvname
  58.  
  59.   lnetname,netname = readstr(buf, co)
  60.   co += lnetname
  61.  
  62.   ltsname,tsname = readstr(buf, co)
  63.   co += ltsname
  64.  
  65.   remoID, = struct.unpack('<B', buf[co:co+1])
  66.   co += 1
  67.  
  68.   return (bsize, (netID,tsID,srvID, srvproname, srvname, netname, tsname,
  69.                   remoID, srvtype,partflg))
  70.  
  71.  
  72. def readreservedat(buf, offset):
  73.   co = offset
  74.  
  75.   bsize, = struct.unpack('<I', buf[co:co+4])
  76.   co += 4
  77.  
  78.   ltitle,title = readstr(buf, co)
  79.   co += ltitle
  80.  
  81.   styear,stmonth,stdow,stday,sthour,stmin,stsec,stmsec = struct.unpack('<8H', buf[co:co+16])
  82.   co += 16
  83.   stdate = datetime.datetime(styear, stmonth, stday, sthour, stmin, stsec, stmsec)
  84.  
  85.   duration, = struct.unpack('<I', buf[co:co+4])
  86.   co += 4
  87.  
  88.   lservice,service = readstr(buf, co)
  89.   co += lservice
  90.  
  91.   netID,tsID,srvID,evID = struct.unpack('<HHHH', buf[co:co+8])
  92.   co += 8
  93.  
  94.   lcomm,comm = readstr(buf, co)
  95.   co += lcomm
  96.  
  97.   resrvID,waitFlg,ovlpMode = struct.unpack('<IBB', buf[co:co+6])
  98.   co += 6
  99.  
  100.   lfilepath,filepath = readstr(buf, co)
  101.   co += lfilepath
  102.  
  103.   # skip start time
  104.   co += 16
  105.  
  106.   ssize, = struct.unpack('<I', buf[co:co+4])
  107.   co += 4
  108.  
  109.   recmode,prio,tuiflg,srvmode = struct.unpack('<BBBI', buf[co:co+7])
  110.  
  111.   return (bsize, (resrvID, service, title,
  112.                   stdate,
  113.                   duration, netID,tsID,srvID,evID, waitFlg,ovlpMode,
  114.                   (recmode, prio, tuiflg, srvmode)) )
  115.  
  116.  
  117. def readepgevdat(buf, offset):
  118.   co = offset
  119.  
  120.   bsize, = struct.unpack('<I', buf[co:co+4])
  121.   co += 4
  122.  
  123.   netID,tsID,srvID,evID,stflg = struct.unpack('<HHHHB', buf[co:co+9])
  124.   co += 9
  125.  
  126.   styear,stmonth,stdow,stday,sthour,stmin,stsec,stmsec = struct.unpack('<8H', buf[co:co+16])
  127.   co += 16
  128.  
  129.   drflg,duration = struct.unpack('<BI', buf[co:co+5])
  130.   co += 5
  131.  
  132.   shsize, = struct.unpack('<I', buf[co:co+4])
  133.   levname,evname = readstr(buf, co+4)
  134.   ltxchar,txchar = readstr(buf, co+4+levname)
  135.   #lsrchev,srchev = readstr(buf, co+4+levname+ltxchar)
  136.   #lsrchtx,srchtx = readstr(buf, co+4+levname+ltxchar+lsrchev)
  137.   co += shsize
  138.  
  139.   exsize, = struct.unpack('<I', buf[co:co+4])
  140.   #lexchar,exchar = readstr(buf, co+4)
  141.   #lexsrch,exsrch = readstr(buf, co+4+lexchar)
  142.   co += exsize
  143.  
  144.   return (bsize, (netID,tsID,srvID,evID, evname, txchar))
  145.  
  146.  
  147. def writedefsetting():
  148.   buf = ''
  149.   buf += struct.pack('<BBBIB', 1, 2, 1, 0, 0) # recMode -> pittariFlag
  150.   buf += writestr('') # batFilePath
  151.   buf += struct.pack('<II', 8, 0) # recFolderList (empty list)
  152.   buf += struct.pack('<BBBIIBBI', 0, 0, 0, 0, 0, 0, 0, 0) # suspendMode -> tunerID
  153.   return struct.pack('<I', len(buf)+4) + buf
  154.  
  155.  
  156. def writereserve(netID, tsID, srvID, evID, stdate, title, service, duration, comment):
  157.   buf = ''
  158.   buf += writestr(title)
  159.   buf += struct.pack('<8H', stdate.year, stdate.month, stdate.isoweekday()%7,
  160.                      stdate.day, stdate.hour, stdate.minute,
  161.                      stdate.second, stdate.microsecond/1000) # startTime
  162.   buf += struct.pack('<I', duration)
  163.   buf += writestr(service)
  164.   buf += struct.pack('<HHHH', netID, tsID, srvID, evID)
  165.   buf += writestr(comment)
  166.   buf += struct.pack('<IBB', 0, 0, 0) # reserveID -> overlapMode
  167.   buf += writestr('') # recFilePath
  168.   buf += struct.pack('<8H', 0, 0, 0, 0, 0, 0, 0, 0) # startTimeEpg
  169.   buf += writedefsetting()
  170.   buf += struct.pack('<I', 0) # reserveStatus
  171.   return struct.pack('<I', len(buf)+4) + buf
  172.  
  173.  
  174. def sendcmd(sock, upcmd):
  175.   sock.connect((HOST, PORT))
  176.   sock.send(upcmd)
  177.   downcmd = sock.recv(8)
  178.   res,downsize = struct.unpack('<II', downcmd)
  179.  
  180.   if res != CMD_SUCCESS:
  181.     return (res, None)
  182.  
  183.   downdat = ''
  184.   while len(downdat) < downsize:
  185.     downdat += sock.recv(downsize - len(downdat))
  186.   return (res, downdat)
  187.  
  188.  
  189. def enumreserves():
  190.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  191.  
  192.   upcmd = struct.pack('<II', CMD2_EPG_SRV_ENUM_RESERVE, 0)
  193.   res,downdat = sendcmd(sock, upcmd)
  194.   lsize,llen = struct.unpack('<II', downdat[:8])
  195.  
  196.   ret = []
  197.  
  198.   offset = 8
  199.   for i in range(llen):
  200.     bsize,dat = readreservedat(downdat, offset)
  201.     ret.append(dat)
  202.     offset += bsize
  203.  
  204.   sock.close()
  205.   ret.sort(lambda r1,r2:cmp(r1[3],r2[3])) # stdate order
  206.   return ret
  207.  
  208.  
  209. def getreserve(id):
  210.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  211.   upcmd = struct.pack('<III', CMD2_EPG_SRV_GET_RESERVE, 4, id)
  212.   res,downdat = sendcmd(sock, upcmd)
  213.   resrv = readreservedat(downdat, 0)
  214.   sock.close()
  215.   return resrv
  216.  
  217.  
  218. def getproginfo(netID, tsID, srvID, evID):
  219.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  220.   upcmd = struct.pack('<IIHHHH', CMD2_EPG_SRV_GET_PG_INFO, 8,
  221.                       evID, srvID, tsID, netID)
  222.   res,downdat = sendcmd(sock, upcmd)
  223.   epgev = readepgevdat(downdat, 0)
  224.   sock.close()
  225.   return epgev
  226.  
  227.  
  228. def updateredmode(resrvID, recmode):
  229.   sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  230.   upcmd1 = struct.pack('<III', CMD2_EPG_SRV_GET_RESERVE, 4, resrvID)
  231.   res1,buf = sendcmd(sock1, upcmd1)
  232.   sock1.close()
  233.  
  234.   size, = struct.unpack('<I', buf[0:4])
  235.   offset = 4
  236.   offset += struct.unpack('<I', buf[offset:offset+4])[0] # title
  237.   offset += 20
  238.   offset += struct.unpack('<I', buf[offset:offset+4])[0] # service
  239.   offset += 8
  240.   offset += struct.unpack('<I', buf[offset:offset+4])[0] # comment
  241.   offset += 6
  242.   offset += struct.unpack('<I', buf[offset:offset+4])[0] # filepath
  243.   offset += 16
  244.   # start REC_SETTING_DATA
  245.   offset += 4
  246.   org = struct.unpack('<B', buf[offset:offset+1])
  247.  
  248.   lbuf = list(buf)
  249.   lbuf[offset:offset+1] = struct.pack('<B', recmode)
  250.   buf = ''.join(lbuf)
  251.  
  252.   sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  253.   # append header of list
  254.   size2 = len(buf)+8
  255.   upcmd2 = struct.pack('<IIII', CMD2_EPG_SRV_CHG_RESERVE, size2, size2, 1)
  256.   upcmd2 += buf
  257.   res2,_buf = sendcmd(sock2, upcmd2)
  258.   sock2.close()
  259.   return res2
  260.  
  261.  
  262. def addreserve(netID, tsID, srvID, evID, stdate, title, service, duration, comment):
  263.   buf = writereserve(netID, tsID, srvID, evID, stdate, title, service, duration, comment)
  264.  
  265.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  266.   # append header of list
  267.   size = len(buf)+8
  268.   upcmd = struct.pack('<IIII', CMD2_EPG_SRV_ADD_RESERVE, size, size, 1)
  269.   upcmd += buf
  270.   res,_buf = sendcmd(sock, upcmd)
  271.   sock.close()
  272.   return res
  273.  
  274.  
  275. def enumservices():
  276.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  277.   upcmd = struct.pack('<II', CMD2_EPG_SRV_ENUM_SERVICE, 0)
  278.   res,downdat = sendcmd(sock, upcmd)
  279.   lsize,llen = struct.unpack('<II', downdat[:8])
  280.  
  281.   ret = []
  282.  
  283.   offset = 8
  284.   for i in range(llen):
  285.     bsize,dat = readservicedat(downdat, offset)
  286.     ret.append(dat)
  287.     offset += bsize
  288.  
  289.   sock.close()
  290.   return ret
  291.  
  292.  
  293. def loadtvpid(filename):
  294.   fin = file(filename)
  295.   meta = []
  296.   for l in fin:
  297.     if len(l.strip()) == 0:
  298.       break
  299.     meta.append(l.decode('cp932').strip())
  300.   body = ''.join(fin).decode('cp932').strip()
  301.  
  302.   sep = re.compile(': *')
  303.   header = dict(map(lambda m:sep.split(m, 1), meta))
  304.  
  305.   alpha = re.compile('[A-Z]+')
  306.   typemap = {'DFS': (0x7880, 0x7FE8), 'BSDT': (4, 4), 'CSDT': (6, 7)}
  307.  
  308.   station = header['station']
  309.   m = alpha.match(station)
  310.   if not m is None and m.group(0) in typemap:
  311.     typebnd = typemap[m.group(0)]
  312.     srvID_ = int(station[m.end():])
  313.    
  314.     li = enumservices()
  315.  
  316.     srv = filter(lambda (netID,tsID,srvID, srvproname, srvname, netname, tsname,
  317.                          remoID, srvtype,partflg): \
  318.                  typebnd[0] <= netID and netID <= typebnd[1] and srvID_ == srvID,
  319.                  li)
  320.     if len(srv) > 0:
  321.       (netID,tsID,srvID, srvproname, srvname, netname, tsname,
  322.        remoID, srvtype,partflg) = srv[0]
  323.  
  324.       evID = int(header['program-id'])
  325.  
  326.       year = int(header['year'])
  327.       month = int(header['month'])
  328.       day = int(header['date'])
  329.       sh,sm = map(lambda i:int(i), header['start'].split(':'))
  330.       eh,em = map(lambda i:int(i), header['end'].split(':'))
  331.  
  332.       stdate = datetime.datetime(year, month, day, sh, sm, 0, 0)
  333.       endate = datetime.datetime(year, month, day, eh, em, 0, 0)
  334.       if endate < stdate:
  335.         endate = datetime.datetime(year, month, day+1, eh, em, 0, 0)
  336.       duration = (endate-stdate).seconds
  337.  
  338.       return (netID, tsID, srvID, evID, stdate,
  339.               header['program-title'], srvname, duration)
  340.   return None
  341.  
  342.  
  343. def printreserves():
  344.   li = enumreserves()
  345.   if len(li):
  346.     print "  ID  START            LEN     TITLE"
  347.   for resrv in li:
  348.     (resrvID, service, title,
  349.      stdate,
  350.      duration, netID,tsID,srvID,evID, waitFlg,ovlpMode,
  351.      (recmode, prio, tuiflg, srvmode)) = resrv
  352.    
  353.     stat = ' '
  354.     if recmode == RECMODE_NO:
  355.       stat = 'x'
  356.     elif ovlpMode != RESERVE_EXECUTE:
  357.       stat = '!'
  358.    
  359.     print "%s %03d %s %01d:%02d:%02d %s (%s)" \
  360.       % (stat, resrvID, stdate.strftime('%Y-%m-%d %H:%M'),
  361.          duration/60/60, duration/60%60, duration%60, title, service)
  362.  
  363.  
  364. def sendsuspend():
  365.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  366.   upcmd = struct.pack('<III', CMD2_EPG_SRV_SUSPEND, 4, 1)
  367.   res,downdat = sendcmd(sock, upcmd)
  368.   sock.close()
  369.   return res
  370.  
  371.  
  372. def printproginfo(resrvID):
  373.   bsize,resrv = getreserve(resrvID)
  374.   (resrvID, service, title,
  375.    stdate,
  376.    duration, netID,tsID,srvID,evID, waitFlg,ovlpMode,
  377.    (recmode, prio, tuiflg, srvmode)) = resrv
  378.   bsize,prog = getproginfo(netID, tsID, srvID, evID)
  379.   (netID,tsID,srvID,evID, evname, txchar) = prog
  380.   print "ID: %03d" % resrvID
  381.   print "Start: %s" % stdate.strftime('%Y-%m-%d %H:%M')
  382.   print "Duration: %01d:%02d:%02d" % (duration/60/60, duration/60%60, duration%60)
  383.   print "Channel: %s (0x%04x 0x%04x 0x%04x)" % (service, netID, tsID, srvID)
  384.   print "EV: 0x%04x" % (evID)
  385.   print "Title: %s" % (title)
  386.   print
  387.   print txchar
  388.  
  389.  
  390. def main():
  391.   if len(sys.argv) > 1 and sys.argv[1] == 'list':
  392.     printreserves()
  393.   elif len(sys.argv) > 2 and sys.argv[1] == 'enable':
  394.     id = int(sys.argv[2])
  395.     updateredmode(id, RECMODE_SERVICE)
  396.   elif len(sys.argv) > 2 and sys.argv[1] == 'disable':
  397.     id = int(sys.argv[2])
  398.     updateredmode(id, RECMODE_NO)
  399.   elif len(sys.argv) > 1 and sys.argv[1] == 'suspend':
  400.     sendsuspend()
  401.   elif len(sys.argv) > 2 and sys.argv[1] == 'info':
  402.     printproginfo(int(sys.argv[2]))
  403.   elif len(sys.argv) > 2 and sys.argv[1] == 'add':
  404.     prg = loadtvpid(sys.argv[2])
  405.     if not prg is None:
  406.       (netID, tsID, srvID, evID, stdate, title, service, duration) = prg
  407.       print "Start: %s" % stdate.strftime('%Y-%m-%d %H:%M')
  408.       print "Duration: %01d:%02d:%02d" % (duration/60/60, duration/60%60, duration%60)
  409.       print "Channel: %s (0x%04x 0x%04x 0x%04x)" % (service, netID, tsID, srvID)
  410.       print "Title: %s" % (title)
  411.       res = addreserve(netID, tsID, srvID, evID, stdate, title, service, duration, 'from PySample')
  412.       if res != CMD_SUCCESS:
  413.         print 'error: %d' % res
  414.   else:
  415.     print "Usage: python %s <command> <args...>" % sys.argv[0]
  416.     print "  Commands"
  417.     print "    list : list reservations"
  418.     print "    info <ID> : info of reservation of ID"
  419.     print "    enable <ID> : enable reservation of ID"
  420.     print "    disable <ID> : disable reservation of ID"
  421.     print "    suspend : suspend server"
  422.     print "    add <TVPID filepath> : add reservation by given TVPID file"
  423.  
  424. if __name__ == '__main__':
  425.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement