Ejemplo n.º 1
0
def get_fs_info(caption="D:"):
    '''
    获取磁盘信息
    '''
    if uname != 'Windows':
        return True

    try:
        # 有可能不在 d:
        sectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters = win32file.GetDiskFreeSpace(
            caption)
        freespace = (numFreeClusters * sectorsPerCluster *
                     bytesPerSector) / (1024 * 1024 * 1024)
    except:
        log("can't stat disk space of %s" % caption,
            project='recording',
            level=2)
        freespace = 16

    log('get_fs_info ret free space %d' % freespace,
        project='recording',
        level=4)

    if freespace < 15:  #小于10G的时候开始清理空间
        return True
    else:
        return False
Ejemplo n.º 2
0
def wait():
    time.sleep(3 * 60)  # 此处无条件等待3分钟
    return  # 不再检查 cardlive.exe 进程了
    pythoncom.CoInitialize()
    w = wmi.WMI()

    while True:
        cs = [(ps.Name, ps.ThreadCount) for ps in w.Win32_Process()]

        f = None

        for c in cs:
            if c[0].lower() == PNAME.lower():
                f = c
                break

        if f is None:
            print 'Warning: %s NOT running ...' % PNAME
            log('%s NOT running...' % PNAME, project='dm', level=2)
        else:
            print 'INFO: %s is running, thread count: %d' % (PNAME, f[1])
            log('%s is running, thread count=%d' % (PNAME, f[1]),
                project='dm',
                level=3)

        if f and f[1] > 30:
            print 'OK: cardlive.exe has %d threads' % f[1]
            break

        time.sleep(10.0)
Ejemplo n.º 3
0
    def __start_service(self, sd):
        ''' 启动服务, 首先检查是否已经启动 ??. 

            总是使用 subprocess.Popen class ..
            TODO:  if !fork 直接启动 py 脚本?是否能在 arm 上节省点内存? ..
        '''

        log('ServicesManager.__start_service: to start %s' % sd['name'], \
                project = 'dm', level = 3)

        for s in self.__activated:
            if s[1]['name'] == sd['name']:
                return None # 已经启动 ..

        args = shlex.split(sd['path'])

        path = self.__get_startpath(args[1]) # FIXME: 要求第二个参数,必须是目标 python 文件
        currpath = os.getcwd()
        os.chdir(path)
        p = subprocess.Popen(args)
        os.chdir(currpath)

        psu = (p, sd, self.__fix_url(sd['url']))
        self.__activated.append(psu)
        return psu 
Ejemplo n.º 4
0
    def __start_service(self, sd):
        ''' 启动服务, 首先检查是否已经启动 ??. 

            总是使用 subprocess.Popen class ..
            TODO:  if !fork 直接启动 py 脚本?是否能在 arm 上节省点内存? ..
        '''

        log('ServicesManager.__start_service: to start %s' % sd['name'], \
                project = 'dm', level = 3)

        for s in self.__activated:
            if s[1]['name'] == sd['name']:
                return None  # 已经启动 ..

        args = shlex.split(sd['path'])

        path = self.__get_startpath(args[1])  # FIXME: 要求第二个参数,必须是目标 python 文件
        currpath = os.getcwd()
        os.chdir(path)
        p = subprocess.Popen(args)
        os.chdir(currpath)

        psu = (p, sd, self.__fix_url(sd['url']))
        self.__activated.append(psu)
        return psu
Ejemplo n.º 5
0
def wait():
    time.sleep(3 * 60) # 此处无条件等待3分钟
    return # 不再检查 cardlive.exe 进程了
    pythoncom.CoInitialize()
    w = wmi.WMI()

    while True:
        cs = [(ps.Name, ps.ThreadCount) for ps in w.Win32_Process()]
    
        f = None
    
        for c in cs:
            if c[0].lower() == PNAME.lower():
                f = c
                break
    
        if f is None:
            print 'Warning: %s NOT running ...' % PNAME
            log('%s NOT running...'%PNAME, project='dm', level=2)
        else:
            print 'INFO: %s is running, thread count: %d' % (PNAME, f[1])
            log('%s is running, thread count=%d' % (PNAME, f[1]), project='dm', level=3)
    
        if f and f[1] > 30:
            print 'OK: cardlive.exe has %d threads' % f[1]
            break

        time.sleep(10.0)
Ejemplo n.º 6
0
def StartLiving(ip,mac,hosttype):
    log('StartLiving calling, ip=%s, mac=%s, hosttype=%s' % (ip, mac, hosttype), project = 'recording', level = 3)
    rc = {}
    rc['result'] = 'ok'
    rc['info'] = ''
    rc = _rtmp_living(ip, mac, hosttype)
    return rc
Ejemplo n.º 7
0
def StartLiving(ip, mac, hosttype):
    log("StartLiving calling, ip=%s, mac=%s, hosttype=%s" % (ip, mac, hosttype), project="recording", level=3)
    rc = {}
    rc["result"] = "ok"
    rc["info"] = ""
    rc = _rtmp_living(ip, mac, hosttype)
    return rc
Ejemplo n.º 8
0
def start_card_server():
    global client
    wsdl_url = 'http://127.0.0.1:8086/UIServices?WSDL' 
    log('start_card_server: to get wsdl from %s' % wsdl_url, \
            project = 'recording')
    try:
        client = Client(wsdl_url)
    except:
        log('start_card_server: cannot get wsdl schema from %s' % wsdl_url, \
                project = 'recording', level = 1)
        print 'wsdl_url is disable!'
Ejemplo n.º 9
0
    def __asy_cmd0(self, callback, token, service_id):
        rc={}
        rc['result'] = 'ok'
        rc['info'] = ''
        ip = ''
        hosttype = None
        mac = ''
        global _tokens

        if token == '0':
            ip= '127.0.0.1'
            hosttype = 'x86'
            mac = _utils.mymac()
            print 'mac is', mac
        else:
            if token not in _tokens:
                rc['result'] = 'error'
                rc['info'] = 'the %sth host does not exit'%token
                callback(rc)
                return
            else:
                hosttype = _tokens[token]['hosttype']
                mac = _tokens[token]['mac']
                ip = _tokens[token]['ip']
                #print hosttype, mac, ip
                #ip_port = get_private_from_tokens(token,service_id,'recording',_tokens)
                #ip = ip_port['target_ip']

        cmd = self.get_argument('RecordCmd','nothing')        


        if cmd == 'RtspPreview':
            rc = _rcmd.preview(ip,hosttype)
        elif cmd == 'CardLiveLog':
            if ip == '127.0.0.1':
                rc = cardlive_log.cardlive_log()
        elif cmd == 'UpdateClassSchedule':
            rc = _class_schedule.analyse_json(ip,mac)
        elif cmd == 'RTMPLiving':
            rc = StartLiving(ip, mac, hosttype)
        else:
            args = (self.request.uri.split('?'))[1]
            rc=_rcmd.send_command(args,ip)

        try:
            # 记录所有收到的命令和执行结果
            cont ='token=%s, sid=%s, cmd=%s, result=%s, info=%s' % (token, service_id, cmd, rc['result'], rc['info']) 
            log(cont, project='recording', level=9)
        except Exception as e:
            pass

        callback(rc)
Ejemplo n.º 10
0
    def __asy_cmd0(self, callback, token, service_id):
        rc = {}
        rc['result'] = 'ok'
        rc['info'] = ''
        ip = ''
        hosttype = None
        mac = ''
        global _tokens

        if token == '0':
            ip = '127.0.0.1'
            hosttype = 'x86'
            mac = _utils.mymac()
            print 'mac is', mac
        else:
            if token not in _tokens:
                rc['result'] = 'error'
                rc['info'] = 'the %sth host does not exit' % token
                callback(rc)
                return
            else:
                hosttype = _tokens[token]['hosttype']
                mac = _tokens[token]['mac']
                ip = _tokens[token]['ip']
                #print hosttype, mac, ip
                #ip_port = get_private_from_tokens(token,service_id,'recording',_tokens)
                #ip = ip_port['target_ip']

        cmd = self.get_argument('RecordCmd', 'nothing')

        if cmd == 'RtspPreview':
            rc = _rcmd.preview(ip, hosttype)
        elif cmd == 'CardLiveLog':
            if ip == '127.0.0.1':
                rc = cardlive_log.cardlive_log()
        elif cmd == 'UpdateClassSchedule':
            rc = _class_schedule.analyse_json(ip, mac)
        elif cmd == 'RTMPLiving':
            rc = StartLiving(ip, mac, hosttype)
        else:
            args = (self.request.uri.split('?'))[1]
            rc = _rcmd.send_command(args, ip)

        try:
            # 记录所有收到的命令和执行结果
            cont = 'token=%s, sid=%s, cmd=%s, result=%s, info=%s' % (
                token, service_id, cmd, rc['result'], rc['info'])
            log(cont, project='recording', level=9)
        except:
            pass

        callback(rc)
Ejemplo n.º 11
0
def del_dir_schedule():
    thread = threading.Timer(600, del_dir_schedule) #10分钟执行一次
    thread.start()
    if get_fs_info():
        dir_list = dir_list_file()
        while get_fs_info():
            if len(dir_list)==0:
                return
            try:
                log('del dir: %s' % dir_list[0]['path'], project = 'recording', level = 2)
                shutil.rmtree(dir_list[0]['path'],True)
            except Exception as error:
                log('del dir: %s exception?: %s' % (dir_list[0]['path'], str(error)), project='recording', level=1)
            dir_list.remove(dir_list[0])
Ejemplo n.º 12
0
def log_info(content):
    """保存信息类日志

    """

    log(content, project="recording", level=3)

    debug = False
    if debug == True:
        date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        dir = "log/" + date
        if os.path.exists(dir):
            logging.basicConfig(filename=dir + "/log.log", level=logging.DEBUG)
        else:
            os.makedirs(dir)
            logging.basicConfig(filename=dir + "/log.log", level=logging.DEBUG)
        logging.info(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\0\0\0\0" + content)
Ejemplo n.º 13
0
def get_fs_info(caption = "D:"):
    '''
    获取磁盘信息
    '''
    try:
        # 有可能不在 d:
        sectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters = win32file.GetDiskFreeSpace(caption)
        freespace = (numFreeClusters * sectorsPerCluster * bytesPerSector) /(1024 * 1024 * 1024)
    except:
        log("can't stat disk space of %s" % caption, project = 'recording', level = 2)
        freespace = 16

    log('get_fs_info ret free space %d' % freespace, project='recording', level=4)

    if freespace < 15:#小于10G的时候开始清理空间
        return True
    else:
        return False
Ejemplo n.º 14
0
def log_info(content):
    '''保存信息类日志

    '''

    log(content, project='recording', level=3)

    debug = False
    if debug == True:
        date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        dir = 'log/' + date
        if os.path.exists(dir):
            logging.basicConfig(filename=dir + '/log.log', level=logging.DEBUG)
        else:
            os.makedirs(dir)
            logging.basicConfig(filename=dir + '/log.log', level=logging.DEBUG)
        logging.info(
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\0\0\0\0" +
            content)
Ejemplo n.º 15
0
def del_dir_schedule():
    thread = threading.Timer(600, del_dir_schedule)  #10分钟执行一次
    thread.start()
    if get_fs_info():
        dir_list = dir_list_file()
        while get_fs_info():
            if len(dir_list) == 0:
                return
            try:
                log('del dir: %s' % dir_list[0]['path'],
                    project='recording',
                    level=2)
                shutil.rmtree(dir_list[0]['path'], True)
            except Exception as error:
                log('del dir: %s exception?: %s' %
                    (dir_list[0]['path'], str(error)),
                    project='recording',
                    level=1)
            dir_list.remove(dir_list[0])
Ejemplo n.º 16
0
 def callback(self, token, name, method):
     ret = ''
     global _tokens
     if token == '0':
         ret = self.__exec_ptz_method(name, method, self.request.arguments)    
     else:
         if token not in _tokens:
             ret = {'result':'error', 'info': 'the %sth host does not exist'%token} 
         else:
             id_port = get_private_from_tokens(token, name, 'ptz', _tokens)
             # FIXME: 这里添加了是否找到 service id 的判断
             if 'ip' not in id_port:
                 ret = {'result': 'error', 'info': 'the service_id=%s NOT found' % name }
             else:
                 nm = id_port['name']
                 armcmd = ArmPtz.toArmStr(nm, method, self.request.arguments)
                 ret = ArmPtz.SendThenRecv(id_port['ip'], id_port['port'],armcmd)
     log('ret:%s'%(ret), 'ptz')
     self.set_header('Constent-Type', 'application/json')
     self.write(ret)
     self.finish()
Ejemplo n.º 17
0
def SendThenRecv(HOST, PORT, arm_command):
    # FIXME: 我感觉应该这样写才能支持连接超时:
    log('ArmPtz.py: ip = %s, port = %s'%(HOST,PORT), 'ptz')
    log('ArmPtz.py: send command = %s'%(arm_command), 'ptz')
    if arm_command == None:
        return {'result':'error', 'info': 'do not support this command'}

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    try:
        s.settimeout(2)
        s.connect((HOST, PORT))
        s.settimeout(None)
    except Exception as e:
        print e
        log('in ArmPtz.py, connect error:', 'ptz', 1)
        return {'result':'error', 'info':'not connect proxied hos'}
    s.sendall(arm_command) 
    try:
        s.settimeout(2)
        data = s.recv(1024)
        s.settimeout(None)
    except Exception as e:
        s.close()
        print e
        log('in ArmPtz.py, recv error:', 'ptz', 1)
        return {'result':'error', 'info': 'recv timeout or other reasons'}

    s.close()
    print 'recv data'
    print data
    log('ArmPtz.py: recv data %s'%(data), 'ptz')
    if 'ok' in data:
        return {'result':'ok', 'info':''}
    elif 'unsupported' in data:
        return {'result':'error', 'info':'do not support this command'}
    else:
        ret = data.split(',')
        result = ret[0].split(':')[1]
        info = ret[1].split(':')[1]
        return {'result': result, 'info': info} 
Ejemplo n.º 18
0
    def analyse_json(self, ip = '127.0.0.1', mac = ''):
        log('ClassSchedule.analyse_json: starting ..., ip=%s, mac=%s' % (ip, mac), project = 'recording')

        reload_thread = threading.Timer(3600, self.analyse_json, (ip, mac))#1小时重新获取一次课表信息
        reload_thread.start()
        print ip,mac
        rc = {}
        rc['result'] = 'ok'
        rc['info'] = ''
        try:      
            data = ''
            try:
                url = self.__mgrt_base_url+'curriculum?mac=' + mac 
                log('ClassSchedule.analyse: try download cs from %s' % url, project = 'recording')
                response = urllib2.urlopen(url, timeout = 3)
                data = json.load(response)
                with open(mac + 'CourseInfo.json','w') as savefile:
                    json.dump(data,savefile)
            except Exception as err:
                log('ClassSchedule.analyse: download cs err, just load local??', project = 'recording', level = 1)
                data = {}
                course_info_file = file(mac + 'CourseInfo.json')
                data = json.load(course_info_file)
            self._stop_execute_task(mac)
            self._analyse_data(data, ip, mac)
        except Exception as err:
            print err
            rc['result'] = 'error'
            rc['info'] = str(err)
            return rc
          
        return rc
Ejemplo n.º 19
0
    def analyse_json(self, ip = '127.0.0.1', mac = ''):
        log('ClassSchedule.analyse_json: starting ..., ip=%s, mac=%s' % (ip, mac), project = 'recording')

        reload_thread = threading.Timer(3600, self.analyse_json, (ip, mac))#1小时重新获取一次课表信息
        reload_thread.start()
        print ip,mac
        rc = {}
        rc['result'] = 'ok'
        rc['info'] = ''
        try:      
            data = ''
            try:
                url = self.__mgrt_base_url+'curriculum?mac=' + mac 
                log('ClassSchedule.analyse: try download cs from %s' % url, project = 'recording')
                response = urllib2.urlopen(url, timeout = 3)
                data = json.load(response)
                with open(mac + 'CourseInfo.json','w') as savefile:
                    json.dump(data,savefile)
            except Exception as err:
                log('ClassSchedule.analyse: download cs err, just load local??', project = 'recording', level = 1)
                data = {}
                course_info_file = file(mac + 'CourseInfo.json')
                data = json.load(course_info_file)
            self._stop_execute_task(mac)
            self._analyse_data(data, ip, mac)
        except Exception as err:
            print err
            rc['result'] = 'error'
            rc['info'] = str(err)
            return rc
          
        return rc
Ejemplo n.º 20
0
    def send_command(self, command, ip='127.0.0.1'):
        rc = {}
        rc['result'] = 'ok'
        rc['info'] = ''
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        log('RecordingCommand.send_command: ip=%s, port=%d, cmd=%s' % (ip, 1230, command), \
                project = 'recording')
        try:
            s.settimeout(2)
            host = ip
            port = 1230
            s.connect((host, port))
            s.settimeout(None)
            s.send(command + "\n")
            print command
            # utf8 BOM
            self.__recv_t(s, 3, 10.0)
            message = self.__recv_t(s, 512, 10.0)
            message = message.strip()
            rc['info'] = message
        except Exception as err:
            rc['result'] = 'error'
            rc['info'] = str(err)

        s.close()
        if rc['result'] == 'ok':
            log('    ok', project = 'recording')
        else:
            log('RecordingCommand.send_command: err, info=%s' % rc['info'], project = 'recording', level=1)
        return rc
Ejemplo n.º 21
0
def SendThenRecv(HOST, PORT, arm_command):
    # FIXME: 我感觉应该这样写才能支持连接超时:
    log('ArmPtz.py: ip = %s, port = %s' % (HOST, PORT), 'ptz')
    log('ArmPtz.py: send command = %s' % (arm_command), 'ptz')
    if arm_command == None:
        return {'result': 'error', 'info': 'do not support this command'}

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.settimeout(2)
        s.connect((HOST, PORT))
        s.settimeout(None)
    except Exception as e:
        print e
        log('in ArmPtz.py, connect error:', 'ptz', 1)
        return {'result': 'error', 'info': 'not connect proxied hos'}
    s.sendall(arm_command)
    try:
        s.settimeout(2)
        data = s.recv(1024)
        s.settimeout(None)
    except Exception as e:
        s.close()
        print e
        log('in ArmPtz.py, recv error:', 'ptz', 1)
        return {'result': 'error', 'info': 'recv timeout or other reasons'}

    s.close()
    print 'recv data'
    print data
    log('ArmPtz.py: recv data %s' % (data), 'ptz')
    if 'ok' in data:
        return {'result': 'ok', 'info': ''}
    elif 'unsupported' in data:
        return {'result': 'error', 'info': 'do not support this command'}
    else:
        ret = data.split(',')
        result = ret[0].split(':')[1]
        info = ret[1].split(':')[1]
        return {'result': result, 'info': info}
Ejemplo n.º 22
0
def start():
    app = make_app()
    app.listen(10006)

    log('recording srv starting, using port 10006',
        project='recording',
        level=3)

    global _rcmd
    _rcmd = RecordingCommand()

    global _utils
    _utils = zkutils()

    start_card_server()

    stype = 'recording'
    reglist = gather_sds('recording', '../common/tokens.json')

    #处理本机
    service_url = r'http://<ip>:10006/recording/0/recording'
    local_service_desc = {}
    local_service_desc['type'] = stype
    local_service_desc['id'] = 'recording'
    local_service_desc['url'] = service_url
    _utils = zkutils()
    mac = _utils.mymac()
    local_service_desc['mac'] = mac
    local_service_desc['ip'] = '127.0.0.1'

    reglist.append(local_service_desc)

    log('mac:%s, ip:%s' % (mac, _utils.myip()), project='recording', level=3)

    global _class_schedule
    _class_schedule = Schedule(None)
    for reg in reglist:
        _class_schedule.analyse_json(reg['ip'], reg['mac'])
    _class_schedule.restart_rtmp_living()
    _class_schedule.set_recording_dir()
    del_dir_schedule()

    global rh
    rh = RegHt(reglist)

    global _ioloop
    _ioloop = IOLoop.instance()
    log('running ...', project='recording', level=3)
    _ioloop.start()
    log('terminated!!!!!', project='recording', level=3)
Ejemplo n.º 23
0
def start():
    app = make_app()
    app.listen(10006)

    log('recording srv starting, using port 10006', project='recording', level = 3)

    global _rcmd
    _rcmd = RecordingCommand()

    global _utils
    _utils = zkutils()

    start_card_server()

    stype = 'recording'
    reglist = gather_sds('recording', '../common/tokens.json')

    #处理本机
    service_url = r'http://<ip>:10006/recording/0/recording'
    local_service_desc = {}
    local_service_desc['type'] = stype
    local_service_desc['id'] = 'recording'
    local_service_desc['url'] = service_url
    _utils = zkutils()
    mac = _utils.mymac()
    local_service_desc['mac'] = mac
    local_service_desc['ip'] = '127.0.0.1'
    
    reglist.append(local_service_desc)

    log('mac:%s, ip:%s' % (mac, _utils.myip()), project='recording', level = 3)

    global _class_schedule
    _class_schedule = Schedule(None)
    for reg in reglist:
        _class_schedule.analyse_json(reg['ip'],reg['mac'])
    _class_schedule.restart_rtmp_living()
    _class_schedule.set_recording_dir()
    del_dir_schedule()

    global rh
    rh = RegHt(reglist)

    global _ioloop
    _ioloop = IOLoop.instance()
    log('running ...', project='recording', level = 3)
    _ioloop.start()
    log('terminated!!!!!', project='recording', level=3)
Ejemplo n.º 24
0
def load_ptz(config):
    ''' 加载云台配置模块 '''
    ptz = {
        'name': config['name'],
        'serial': config['config']['serial'],
        'addr': config['config']['addr'],
        'ptz': None
    }

    if 'extent' in config['config']:
        ptz['cfgfile'] = config['config']['extent']

    # 此处打开 ...
    if True:
        is_ptz = False
        ptz['ptz'] = PtzWrap()
         # 来自 json 字符串都是 unicode, 需要首先转换为 string 交给 open 
        if 'cfgfile' in ptz:
            filename = ptz['cfgfile'].encode('ascii')
            print 'open with cfg:', filename
            is_ptz = ptz['ptz'].open_with_config(filename)
            if is_ptz == False:
                log('open %s failure'%(filename), 'ptz', 2)    
            else:
                log('open %s succeed'%(filename), 'ptz', 2)

        else:
            print 'open ptz:', ptz['serial'], 'addr:', ptz['addr']
            is_ptz = ptz['ptz'].open(ptz['serial'].encode('ascii'), int(ptz['addr']))
        if not is_ptz:
            ptz['ptz'] = None    
    else:
        ptz['ptz'] = None
        print 'open failure'

    return ptz
Ejemplo n.º 25
0
    def preview(self, ip, hosttype):
        rc = {}
        rc['result'] = 'ok'
        rc['info'] = ''
        log('RecordingCommand.preview: ip=%s, hosttype=%s' % (ip, hosttype), \
                project = 'recording')

        if hosttype == 'x86':
            rtsp_ip = self.send_command('BroadCastCmd=GetDeviceIP', ip)
            if(rtsp_ip['result'] == 'ok' and len(rtsp_ip['info']) > 0):            
                rtsp_ip = rtsp_ip['info']
                rtsp_ip = rtsp_ip[:-2]
                url = {}
                url['resource1'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session0.mpg'
                url['resource2'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session1.mpg'
                url['resource3'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session2.mpg'
                url['resource4'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session3.mpg'
                url['resource5'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session4.mpg'
                url['resource6'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session5.mpg'
                url['movie'] = 'rtsp://*****:*****@'+ rtsp_ip +':554/session6.mpg'
                rc['info'] = url
            else:
                rc['result'] = 'error'
                rc['info'] = rtsp_ip['info']
        else:
            response = self.send_command('RecordCmd=QueryRtspUrls',ip)
            if response['result'] == 'ok':
                url = {}
                infos = response['info'].split('&')
                i = 1
                for info in infos:
                    url['resource' + str(i)] = info
                    i = i+1
                rc['info'] = url
            else:
                rc['result'] = 'error'
                rc['info'] = response['info']

        if rc['result'] == 'ok':
            log('RecordingCommand.preview: ok', project = 'recording')
        else:
            log('RecordingCommand.preview: err, info=%s' % rc['info'], \
                    project = 'recording', level = 1)
        
        return rc
Ejemplo n.º 26
0
def log_info(info):
    log(log, project='recording')
Ejemplo n.º 27
0
def log_info(info):
    log(log, project="recording")
Ejemplo n.º 28
0
def StopLiving():
    log("StopLiving called", project="recording", level=3)
    _rcmd = RecordingCommand()
    rc = _rcmd.send_command("BroadCastCmd=StopBroadCast", ip)
    return rc
Ejemplo n.º 29
0
def _rtmp_living(ip, mac, hosttype):
    rc = {}
    rc["result"] = "ok"
    rc["info"] = ""

    log("_rtmp_living: starting ...., ip=%s, mac=%s, hosttype=%s" % (ip, mac, hosttype), project="recording")

    if hosttype == "x86":
        if not CardLive_Runing():
            log("_rtmp_living: cardlive.exe NOT prepared?", project="recording", level=2)
            rc["result"] = "error"
            rc["info"] = "cardlive.exe is not exit!"
            return rc

    try:
        log("_rtmp_living: try to get relay url", project="recording")
        middle_req = urllib2.urlopen(_load_base_url() + "getServerUrl?type=middle", timeout=2)
        middle_url = middle_req.read()
    except Exception as e:
        log("_rtmp_living: to get relay url fault! reason=%s" % e, project="recording", level=1)
        rc["result"] = "error"
        rc["info"] = str(e)
        return rc

    log("_rtmp_living: en, got relay url: %s" % middle_url, project="recording")

    try:
        log("_rtmp_living: to call relay of prepublishbatch", project="recording")
        req = urllib2.Request(middle_url + "/repeater/prepublishbatch")
        if hosttype == "x86":
            data = _x86_rtmp_living_data(mac)
        else:
            data = _arm_rtmp_living_data(ip, mac, hosttype)
        data = json.dumps(data)

        response = urllib2.urlopen(req, data)
        content = json.load(response)

        log("_rtmp_living: response_code=%s" % str(content["response_code"]), project="recording")

        if content["response_code"] != 0:
            rc = _error_code(content["response_code"], content)
            log("_rtmp_living: err: info=%s" % rc["info"], project="recording", level=1)
            return rc

        urls = []
        urls = content["content"]
        movie_url = rtmp_ip = port = app = ""
        infos = []

        for url in urls:
            info = {}
            info["uid"] = str(url["uid"])
            info["rtmp_repeater"] = str(url["rtmp_repeater"])
            if "teacher" in url["uid"]:
                info["card_info"] = "card0"
            if "teacher_full" in url["uid"]:
                info["card_info"] = "card1"
            if "student" in url["uid"]:
                info["card_info"] = "card2"
            if "student_full" in url["uid"]:
                info["card_info"] = "card3"
            if "vga" in url["uid"]:
                info["card_info"] = "card4"
            if "blackboard_writing" in url["uid"]:
                info["card_info"] = "card5"
            if "movie" in url["uid"]:
                info["card_info"] = "card6"

            str(info)

            infos.append(info)

            if "teacher" in url["rtmp_repeater"]:
                # movie_url = url['rtmp_repeater']
                # livingS(movie_url)
                url = url["rtmp_repeater"]
                url = url[7:]
                rtmp_ip = url.split(":")[0]
                url = url[len(rtmp_ip) + 1 :]
                port = url.split("/")[0]
                url = url[len(port) + 1 :]
                app = url.split("/")[0]

        _rcmd = RecordingCommand()
        if hosttype == "x86":
            ReslivingS(rtmp_ip, port, app)
        else:
            arm_arg = "BroadCastCmd=RtmpUrlS&"
            for info in infos:
                arm_arg = arm_arg + info["rtmp_repeater"] + "^"
            arm_arg = arm_arg[:-1]
            log_info(arm_arg)
            rc = _rcmd.send_command(arm_arg, ip)
            print rc

        time.sleep(1)
        rc = _rcmd.send_command("BroadCastCmd=StartBroadCast", ip)

        if rc["result"] == "ok":
            rc["info"] = infos

    except Exception as err:
        rc["result"] = "error"
        rc["info"] = str(err)
        log("_rtmp_living: exception info=%s" % rc["info"], project="recording", level=1)

    return rc
Ejemplo n.º 30
0
def _rtmp_living(ip, mac, hosttype):
    rc = {}
    rc['result'] = 'ok'
    rc['info'] = ''

    log('_rtmp_living: starting ...., ip=%s, mac=%s, hosttype=%s' % (ip, mac, hosttype), \
            project = 'recording')

    if hosttype == 'x86':
        if not CardLive_Runing():
            log('_rtmp_living: cardlive.exe NOT prepared?', project='recording', level = 2)
            rc['result'] = 'error'
            rc['info'] = 'cardlive.exe is not exit!'
            return rc

    try:
        log('_rtmp_living: try to get relay url', project = 'recording')
        middle_req = urllib2.urlopen(_load_base_url() + 'getServerUrl?type=middle', timeout = 2)
        middle_url = middle_req.read()
    except Exception as e:
        log('_rtmp_living: to get relay url fault! reason=%s' % e, project = 'recording', level = 1)
        rc['result'] = 'error'
        rc['info'] = str(e)
        return rc


    log('_rtmp_living: en, got relay url: %s' % middle_url, project = 'recording')

    try:
        log('_rtmp_living: to call relay of prepublishbatch', project = 'recording')
        req = urllib2.Request(middle_url+'/repeater/prepublishbatch')
        if hosttype == 'x86':
            data = _x86_rtmp_living_data(mac)
        else:
            data = _arm_rtmp_living_data(ip, mac, hosttype)
        data = json.dumps(data)

        response = urllib2.urlopen(req, data)
        content = json.load(response)

        log('_rtmp_living: response_code=%s' % str(content['response_code']), project = 'recording')    

        if content['response_code'] != 0:
            rc = _error_code(content['response_code'],content)
            log('_rtmp_living: err: info=%s' % rc['info'], project = 'recording', level = 1)
            return rc

        urls = []
        urls = content['content']
        movie_url = rtmp_ip = port = app = ''
        infos = []

        for url in urls:
            info = {}
            info['uid'] = str(url['uid'])
            info['rtmp_repeater'] = str(url['rtmp_repeater'])
            if 'teacher' in url['uid']:
                info['card_info'] = 'card0'
            if 'teacher_full' in url['uid']:   
                info['card_info'] = 'card1'
            if 'student' in url['uid']:
                info['card_info'] = 'card2'
            if 'student_full' in url['uid']:               
                info['card_info'] = 'card3'
            if 'vga' in url['uid']: 
                info['card_info'] = 'card4'
            if 'blackboard_writing' in url['uid']:
                info['card_info'] = 'card5'
            if 'movie' in url['uid']:   
                info['card_info'] = 'card6'

            str(info)

            infos.append(info)

            if 'teacher' in url['rtmp_repeater']:
                #movie_url = url['rtmp_repeater']
                #livingS(movie_url)
                url = url['rtmp_repeater']
                url = url[7:]
                rtmp_ip = url.split(':')[0]
                url = url[len(rtmp_ip)+1:]
                port = url.split('/')[0]
                url =url[len(port)+1:]
                app = url.split('/')[0]

        _rcmd = RecordingCommand()
        if hosttype == 'x86':
            ReslivingS(rtmp_ip,port,app)
        else:
            arm_arg = 'BroadCastCmd=RtmpUrlS&'
            for info in infos:
                arm_arg = arm_arg + info['rtmp_repeater'] +'^'
            arm_arg = arm_arg[:-1]
            log_info(arm_arg)
            rc = _rcmd.send_command(arm_arg,ip)
            print rc

        time.sleep(1)
        rc=_rcmd.send_command('BroadCastCmd=StartBroadCast',ip)

        if rc['result'] == 'ok':
            rc['info'] = infos

    except Exception as err:
        rc['result'] = 'error'
        rc['info'] = str(err)
        log('_rtmp_living: exception info=%s' % rc['info'], \
                project = 'recording', level = 1)

    return rc
Ejemplo n.º 31
0
def StopLiving():
    log('StopLiving called', project = 'recording', level = 3)
    _rcmd = RecordingCommand()
    rc=_rcmd.send_command('BroadCastCmd=StopBroadCast',ip)
    return rc
Ejemplo n.º 32
0
import portalocker

p = open('ptz.pid', 'w')
try:
    portalocker.lock(p, portalocker.LOCK_EX | portalocker.LOCK_NB)
except:
    print 'only one instance can be run!!!'
    sys.exit(0)

_all_config = { 'ptzs': {} }

if platform.uname()[0] == 'Windows':
    try:
        _all_config = json.load(io.open('./config.json', 'r', encoding='utf-8'))
    except:
        log('fail for loading ptz config.json', 'ptz', 0) 
        print 'faile for loading ptz config.json'
        sys.exit(0)


if os.path.isfile('./local.json'):
    _local_config = None
    try:
        _local_config = json.load(io.open('./local.json', 'r', encoding='utf-8'))
    except:
        log('fail for loading ptz local.json', 'ptz', 0)
        print 'fail for loading ptz local.json'
        sys.exit(0)
    _all_config.update(_local_config)

_tokens = load_tokens('../common/tokens.json')
Ejemplo n.º 33
0
 def get(self, token, name, method):
     ''' sid 指向云台,method_params 为 method?param1=value1&param2=value2& ....
     '''
     log('token:%s, name:%s, method:%s, arguments:%s'%(token,name,method,self.request.arguments), 'ptz')
     print token, name, method
     thread.start_new_thread(self.callback, (token, name, method))