Ejemplo n.º 1
0
def send_tts():
    if conf.get_protocol_type() == 3:
        tts_ = e_tts.get()
        tts_flag_ = e_tts_flag.get()
        if tts_:
            if tts_flag_:
                tts_flag_ = num2big(int(tts_flag_), 1)
            else:
                tts_flag_ = '08'
            msg_body = tts_flag_ + byte2str(tts_.encode('gbk'))
            body = '8300' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + \
                   num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            send_queue.put(data)
    elif conf.get_protocol_type() == 4:
        tts_ = e_tts.get()
        if tts_:
            msg_flag = '08'
            msg_content = byte2str(tts_.encode('utf-8'))
            if len(msg_content) > 2048:
                msg_content = msg_content[:2048]
            else:
                n = 2048 - len(msg_content)
                msg_content += '0' * n
            msg_body = msg_flag + msg_content
            service = num2big((9 << 6) + (4 << 1), 2) + calc_lens_sf(msg_body)
            timestamp = num2big(int(round(time.time() * 1000)), 8)
            pro_id = num2big(1744, 2)
            other = '800000'
            body = other + timestamp + pro_id + service + msg_body
            data = '55' + '41' + calc_lens_sf(body) + body + '55'
            send_queue.put(data)
Ejemplo n.º 2
0
    def replace_all_face(self):
        logger.debug('—————— 替换所有人脸 ——————')
        if conf.get_protocol_type() == 1:
            mask = 0b00000000
            send_face_thread = SendFace('【 Data Server 】 SendFace Thread Start ...', 0, mask, self.face_case_path)
            send_face_thread.start()

        elif conf.get_protocol_type() == 5:
            if self.face_case_path:
                face_case_name = self.face_case_path
            else:
                face_case_name = r'.\TestData\Face_suter\全替换人脸.xls'
            rs = xlrd.open_workbook(face_case_name)
            table = rs.sheets()[0]
            cols = table.ncols
            face_num = (cols+1)//4
            face_info_list = ''
            for n in range(1, cols + 1, 4):
                data_len = table.col_values(n)[1:]
                data_content = table.col_values(n + 1)[1:]
                deal_data = list(map(read_value, data_content))
                data = list(map(data2hex, deal_data, data_len))
                face_info_list += ''.join(data)
            msg_body = '00' + num2big(face_num, 1) + face_info_list
            body = '8E11' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            send_queue.put(data)
Ejemplo n.º 3
0
    def handle(self):
        time.sleep(0.5)
        address, port = self.client_address
        logger.debug('【 Data Server 】 Connected by {} {} ...'.format(address, port))
        TCPRequestHandler.isAlive = True
        logger.debug('【 Data Server 】 Producer Thread Start ...')
        send_thread = SendData('【 Data Server 】 Send Thread Start ...', self)
        send_thread.setDaemon(True)
        send_thread.start()

        if conf.get_protocol_type() == 1:
            if conf.get_sync_flag():
                from Util.Sync_SU import SyncThread
                sync_thread = SyncThread('【 Data Server 】 Sync Thread Start ...', self)
                sync_thread.setDaemon(True)
                sync_thread.start()
            global fetch_media_flag
            fetch_media_flag = True
        elif conf.get_protocol_type() == 5:
            dog_thread = DogThread('【 Data Server 】 Dog Thread Start ...', self)
            dog_thread.setDaemon(True)
            dog_thread.start()

        while True:
            try:
                buf = b''
                if self.remain:
                    self.remain = ParseData.produce(buf, self.remain)
                try:
                    buf = self.request.recv(1024)
                except TimeoutError:
                    self.isAlive = False
                    time.sleep(0.3)
                    logger.debug('【 Data Server 】 Receiving ack timeout,connection is interrupted.')
                except ConnectionResetError:
                    self.isAlive = False
                    time.sleep(0.3)
                    logger.debug('【 Data Server 】 ConnectionResetError,connection is interrupted.')
                except ConnectionAbortedError:
                    self.isAlive = False
                    time.sleep(0.3)
                    logger.debug('【 Data Server 】 ConnectionAbortedError,connection is interrupted.')
                except Exception as e:
                    logger.error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
                    logger.error(e)

            except socket.timeout:
                self.isAlive = False
                time.sleep(0.3)
                logger.debug('【 Data Server 】 Receiving data timeout,connection is interrupted.')
                break
            if not buf:
                self.isAlive = False
                time.sleep(0.3)
                logger.debug('【 Data Server 】 Receive empty data,connection is interrupted.')
                break
            self.remain = ParseData.produce(buf, self.remain)
            time.sleep(0.001)
Ejemplo n.º 4
0
def rec_translate(data):
    if conf.get_protocol_type() == 1 or conf.get_protocol_type(
    ) == 3 or conf.get_protocol_type() == 5:
        data = re.subn(b'\x7d\x02', b'\x7e', data)[0]
        data = re.subn(b'\x7d\x01', b'\x7d', data)[0]
    elif conf.get_protocol_type() == 4:
        data = re.subn(b'\x54\x01', b'\x55', data)[0]
        data = re.subn(b'\x54\x00', b'\x54', data)[0]
    return data
Ejemplo n.º 5
0
def send_translate(data):
    trans_data = data[1:-1]
    if conf.get_protocol_type() == 1 or conf.get_protocol_type(
    ) == 3 or conf.get_protocol_type() == 5:
        trans_data = re.subn(b'\x7d', b'\x7d\x01', trans_data)[0]
        trans_data = re.subn(b'\x7e', b'\x7d\x02', trans_data)[0]
    elif conf.get_protocol_type() == 4:
        trans_data = re.subn(b'\x54', b'\x54\x00', trans_data)[0]
        trans_data = re.subn(b'\x55', b'\x54\x01', trans_data)[0]
    return data[0:1] + trans_data + data[-1:]
Ejemplo n.º 6
0
def start_upgrade():
    global upgrade_filename
    software_ = e_software.get()
    fragment_ = e_fragment.get()
    if conf.get_protocol_type() == 1:
        if fragment_ and upgrade_filename:
            upgrade_su(upgrade_filename, int(fragment_))
    elif conf.get_protocol_type() == 4:
        if fragment_ and upgrade_filename and software_:
            upgrade_task_sf(filename, software_, int(fragment_))
Ejemplo n.º 7
0
 def query_face(self):
     logger.debug('—————— 驾驶员身份信息库查询 ——————')
     if conf.get_protocol_type() == 1:
         # 数据内容拼接:厂商编码 + 外设编号 + 功能码 + 设置类型
         msg_body = '033D' + '65' + 'E4'
         # 报文格式拼接
         data = '7E' + calc_check_code(msg_body) + num2big(GlobalVar.get_serial_no()) + msg_body + '7E'
         # 发文发送
         send_queue.put(data)
     elif conf.get_protocol_type() == 5:
         msg_body = ''
         body = '8E12' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body
         data = '7E' + body + calc_check_code(body) + '7E'
         send_queue.put(data)
Ejemplo n.º 8
0
def query_pro():
    logger.debug('—————— 查询终端属性 ——————')
    if conf.get_protocol_type() == 3 or conf.get_protocol_type() == 5:
        body = '8107' + '0000' + GlobalVar.DEVICEID + num2big(
            GlobalVar.get_serial_no())
        data = '7E' + body + calc_check_code(body) + '7E'
        send_queue.put(data)
    elif conf.get_protocol_type() == 4:
        msg_body = ''
        service = num2big((12 << 6) + (4 << 1), 2) + calc_lens_sf(msg_body)
        timestamp = num2big(int(round(time.time() * 1000)), 8)
        pro_id = num2big(1744, 2)
        other = '800000'
        body = other + timestamp + pro_id + service
        data = '55' + '41' + calc_lens_sf(body) + body + '55'
        send_queue.put(data)
Ejemplo n.º 9
0
 def setup(self):
     if conf.get_protocol_type() == 1:
         self.timeOut = None
     else:
         self.timeOut = 20
     self.remain = b''
     self.isAlive = True
     self.request.settimeout(self.timeOut)
Ejemplo n.º 10
0
def data2hex(data, lens):
    if conf.get_protocol_type() == 1 or conf.get_protocol_type(
    ) == 3 or conf.get_protocol_type() == 5:
        if isinstance(data, int):
            return num2big(data, lens)
        elif isinstance(data, str):
            return data[2:]
        elif isinstance(data, bytes):
            if len(data) < lens:
                return byte2str(data) + (int(lens) - len(data)) * '00'
            else:
                return byte2str(data)
        else:
            return str2hex(data, lens)
    elif conf.get_protocol_type() == 2:
        if isinstance(data, int):
            return num2small(data, lens)
        elif isinstance(data, str):
            return str2hex(data, lens)
Ejemplo n.º 11
0
 def run(self):
     logger.debug(threading.current_thread().getName())
     while True:
         try:
             data, command = rec_alarm_queue.get_nowait()
         except queue.Empty:
             data = None
         if data:
             if conf.get_protocol_type() == 1:
                 func = parse_type_su.get(command)
                 if func:
                     func(data)
             elif conf.get_protocol_type() == 2:
                 func = parse_type.get(command)
                 if func:
                     func(data)
             elif conf.get_protocol_type() == 3 or conf.get_protocol_type(
             ) == 5:
                 GetMediaThread.parse_media_upload(data)
         time.sleep(0.001)
Ejemplo n.º 12
0
def calc_check_code(data):
    if conf.get_protocol_type() == 1:
        data_list = [data[x:x + 2] for x in range(0, len(data), 2)]
        data_list = [int(x, 16) for x in data_list]
        check_code = hex(sum(data_list))[-2:]
        return check_code.upper()
    elif conf.get_protocol_type() == 2:
        data_list = [data[x:x + 2] for x in range(0, len(data), 2)]
        data_list = [int(x, 16) for x in data_list]
        check_code = hex((0 - sum(data_list) + (1 << 64)) % (1 << 64))
        return check_code[-2:].upper()
    elif conf.get_protocol_type() == 3 or conf.get_protocol_type() == 5:
        data = ''.join(data.split())
        data = list(bytes.fromhex(data))
        if data:
            s = reduce(lambda x, y: x ^ y, data)
            code = str(hex(s))
            if len(code) > 3:
                return code[-2:].upper()
            else:
                return '0' + code[-1].upper()
Ejemplo n.º 13
0
def read_value(val):
    if isinstance(val, float):
        if val.is_integer():
            if val >= 0:
                res = int(val)
            else:
                res = int(val) & 0xFF
        else:
            res = float(val)
    elif isinstance(val, str):
        if not val:
            res = 0
        elif val[:2] == '0b' or val[:2] == '0B':
            res = int(val, 2)
        elif val[:2] == '0x' or val[:2] == '0X':
            res = int(val, 16)
        elif val[:4] == 'time':
            if conf.get_protocol_type() == 1:
                res = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                res = res
            elif conf.get_protocol_type() == 2:
                res = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        else:
            if conf.get_protocol_type() == 3 or conf.get_protocol_type() == 5:
                if not val[:2] == '0s':
                    res = val.encode('gbk')
                else:
                    res = val
            elif conf.get_protocol_type() == 1:
                if not val[:2] == '0s':
                    res = val.encode('utf-8')
                else:
                    res = val

    elif isinstance(val, int):
        res = val
    else:
        res = 0
    return res
Ejemplo n.º 14
0
 def run(self):
     if conf.get_protocol_type() == 1:
         logger.debug(threading.current_thread().getName())
         conf_path = os.path.join('TestData', '苏标外设实时同步数据.xls')
         while self.rec_obj.isAlive:
             table = GetTestData(conf_path)
             table.open()
             test_point, data = table.get_excel_data()
             if ' ' in data:
                 data = ''.join(data.split())
             lock.acquire()
             send_queue.put(data)
             lock.release()
             time.sleep(0.5)
Ejemplo n.º 15
0
def send_queue_data(data):
    if data:
        if ' ' in data:
            data = ''.join(data.split(' '))
        data_bak = data
        if conf.get_protocol_type() == 1 or conf.get_protocol_type(
        ) == 3 or conf.get_protocol_type() == 5:
            data = send_translate(bytes.fromhex(data))
            send_data = data
        elif conf.get_protocol_type() == 2:
            data = bytes.fromhex(data)
            send_data = data
        elif conf.get_protocol_type() == 4:
            data = send_translate(bytes.fromhex(data))
            send_data = data
        else:
            logger.debug('读取协议类型错误。')

        if conf.get_protocol_type() == 1:
            if bytes.fromhex(data_bak)[7:8] == b'\x50':
                media_id = data[-5:-1]
                logger.debug('—————— 正在请求多媒体ID为 {} 的数据 ——————'.format(
                    byte2str(media_id)))

        text_hex = ' '.join(data_bak[i:i + 2]
                            for i in range(0, len(data_bak), 2))
        if len(text_hex) > 500:
            text_hex = text_hex[:500]
        if conf.get_protocol_type() == 1:
            if not data_bak[14:16] == '31':
                logger.debug('%s%s%s%s%s' %
                             ("SEND DATA:   ", 'lens: ',
                              str(int(len(data_bak) / 2)).ljust(
                                  5, ' '), '   data: || ', text_hex))
            else:
                serial_no_ = big2num(data_bak[4:8])
                if serial_no_ % 120 == 1:
                    logger.debug('—————— 实时数据同步信息 ——————')
                    logger.debug(
                        '%s%s%s%s%s' % ("SEND DATA:   ", 'lens: ',
                                        str(int(len(data_bak) / 2)).ljust(
                                            5, ' '), '   data: || ', text_hex))

        else:
            logger.debug(
                '%s%s%s%s%s' %
                ("SEND DATA:   ", 'lens: ', str(int(len(data_bak) / 2)).ljust(
                    5, ' '), '   data: || ', text_hex))
        return send_data
    def run(self):
        logger.debug(threading.current_thread().getName())
        if not os.path.exists('Result'):
            os.mkdir('Result')
        while True:
            if conf.get_protocol_type() == 1:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    if isinstance(data, bytes):
                        if data[7:8] == b"\x51":
                            media_data = data[17:-1]
                            self.buf += media_data
                            total = int(byte2str(data[13:15]), 16)
                            rec = int(byte2str(data[15:17]), 16)
                            if rec == total - 1:
                                media_id = byte2str(data[9:13])
                                if data[6:7] == b'\x65':
                                    event_type = alarm_type_code_su_dsm.get(
                                        media_alarm_code.get(media_id))
                                    dir_name = os.path.join(
                                        'Result', 'DSM_media')
                                else:
                                    event_type = alarm_type_code_su_adas.get(
                                        media_alarm_code.get(media_id))
                                    dir_name = os.path.join(
                                        'Result', 'ADAS_media')
                                t = time.strftime(r'%Y%m%d%H',
                                                  time.localtime())
                                dir_name = os.path.join(dir_name, t)
                                if not os.path.exists(dir_name):
                                    os.makedirs(dir_name)
                                media_type = byte2str(data[8:9])
                                if media_type == '00':
                                    self.media_name = r'告警ID{}_{}.jpg'.format(
                                        int(media_id, 16), event_type)
                                elif media_type == '02':
                                    self.media_name = r'告警ID{}_{}.mp4'.format(
                                        int(media_id, 16), event_type)
                                elif media_type == '01':
                                    self.media_name = r'告警ID{}_{}.mp3'.format(
                                        int(media_id, 16), event_type)
                                else:
                                    logger.error('未知的多媒体类型。')
                                file_name = os.path.join(
                                    dir_name, self.media_name)
                                if os.path.exists(file_name):
                                    file_name_list = file_name.split('.')
                                    file_name_list[0] += '_bak'
                                    file_name = '.'.join(file_name_list)
                                with open(file_name, 'ab') as f:
                                    f.write(self.buf)
                                    self.buf = b''
                                try:
                                    if media_alarm_code:
                                        media_alarm_code.pop(media_id)
                                except KeyError:
                                    logger.error(
                                        'media_id{}不存在。'.format(media_id))

                        # 有为协议人脸图片存储
                        elif data[7:8] == b"\xbd":
                            msg_body = data[8:-1]
                            status = byte2str(msg_body[1:2])
                            flag = byte2str(msg_body[2:3])
                            person_id = big2num(byte2str(msg_body[3:7]))
                            file_name = msg_body[7:39].decode('utf-8')
                            card_id = msg_body[39:59].decode('utf-8')
                            record_id = big2num(byte2str(msg_body[63:67]))
                            reco_gate = big2num(byte2str(msg_body[67:69]))
                            reco_rate = big2num(byte2str(msg_body[69:71]))
                            total_size = big2num(byte2str(msg_body[71:75]))
                            offset = big2num(byte2str(msg_body[75:79]))
                            size = big2num(byte2str(msg_body[79:81]))
                            media_data = msg_body[81:]
                            dir_name = os.path.join('Result', 'Face_Identify')
                            if not os.path.exists(dir_name):
                                os.makedirs(dir_name)
                            with open(os.path.join(dir_name, file_name),
                                      'ab') as f:
                                f.write(media_data)

                    # 瑞为协议人脸图片存储
                    elif isinstance(data, tuple):
                        face_name, offset, length, media_data = data
                        dir_name = os.path.join('Result', 'Face_Identify')
                        if not os.path.exists(dir_name):
                            os.makedirs(dir_name)
                        with open(os.path.join(dir_name, face_name),
                                  'ab') as f:
                            f.write(media_data)

            elif conf.get_protocol_type() == 3:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    total_pkg = big2num(byte2str(data[13:15]))
                    pkg_no = big2num(byte2str(data[15:17]))
                    path_dir = os.path.join('Result', 'Alarm_Media')
                    if not os.path.exists(path_dir):
                        os.mkdir(path_dir)
                    if pkg_no == 1:
                        img_data = data[53:-2]
                        self.buf += img_data
                        media_id_byte = data[17:21]
                        media_id = big2num(byte2str(media_id_byte))
                        media_type = big2num(byte2str(data[21:22]))
                        event_type = big2num(byte2str(data[23:24]))
                        channel = byte2str(data[24:25])
                        speed = big2num(byte2str(data[43:45]))
                        alarm_time = byte2str(data[47:53])

                        if media_type == 0:
                            self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                media_id,
                                alarm_type_code_jt808.get(event_type), channel,
                                str(speed), alarm_time, 'jpg')
                        elif media_type == 2:
                            self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                media_id,
                                alarm_type_code_jt808.get(event_type), channel,
                                str(speed), alarm_time, 'mp4')
                        if os.path.exists(
                                os.path.join(path_dir, self.media_name)):
                            file_name_list = self.media_name.split('.')
                            file_name_list[0] += '_bak'
                            self.media_name = '.'.join(file_name_list)
                    else:
                        img_data = data[17:-2]
                        self.buf += img_data
                        if total_pkg == pkg_no:
                            try:
                                with open(
                                        os.path.join(path_dir,
                                                     self.media_name),
                                        'ab') as f:
                                    f.write(self.buf)
                            except PermissionError:
                                logger.error(PermissionError)
                                with open(
                                        os.path.join(path_dir,
                                                     self.media_name),
                                        'ab') as f:
                                    f.write(self.buf)
                            except FileNotFoundError:
                                logger.error(FileNotFoundError)
                            self.buf = b''
                            self.media_name = ''
            elif conf.get_protocol_type() == 5:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    if data[0:4] == b'\x30\x31\x63\x64':
                        media_name = data[4:54].split(b'\x00')[0].decode(
                            'utf-8')
                        media_name_bak = media_name
                        media_size = name_size.get(media_name)
                        media_type = media_name.split('_')[2]
                        if media_type[:2] == '65':
                            media_type = alarm_type_code_su_ter_dsm.get(
                                bytes.fromhex(media_type[2:]))
                        elif media_type[:2] == '64':
                            media_type = alarm_type_code_su_ter_adas.get(
                                bytes.fromhex(media_type[2:]))
                        elif media_type[:2] == '67':
                            media_type = alarm_type_code_su_bsd.get(
                                bytes.fromhex(media_type[2:]))
                        else:
                            media_type = 'error'
                        media_name_list = media_name.split('_')
                        timeStamp = int(media_name_list[4][:16])
                        timeArray = time.localtime(timeStamp / 1000000)
                        otherStyleTime = time.strftime("%Y_%m_%d_%H_%M_%S",
                                                       timeArray)
                        media_name = otherStyleTime + '_' + media_type + '_' + '_'.join(
                            media_name_list)
                        # media_name = media_type + "_" + media_name
                        offset = big2num(byte2str(data[54:58]))
                        data_length = big2num(byte2str(data[58:62]))
                        data_content = data[62:62 + data_length]
                        self.buf += data_content
                        if offset + data_length == media_size:
                            path_dir = os.path.join('Result', 'Alarm_Media')
                            if not os.path.exists(path_dir):
                                os.mkdir(path_dir)
                            with open(os.path.join(path_dir, media_name),
                                      'ab') as f:
                                f.write(self.buf)
                                name_size.pop(media_name_bak)
                            self.buf = b''
                            self.media_name = ''
                    elif data[:2] == b'\x08\x01':
                        total_pkg = big2num(byte2str(data[12:14]))
                        pkg_no = big2num(byte2str(data[14:16]))
                        msg_body = data[16:-1]
                        path_dir = os.path.join('Result', 'Alarm_Media')
                        if not os.path.exists(path_dir):
                            os.mkdir(path_dir)
                        if pkg_no == 1:
                            img_data = msg_body[36:]
                            self.buf += img_data
                            media_id_byte = msg_body[0:4]
                            media_id = big2num(byte2str(media_id_byte))
                            media_type = big2num(byte2str(msg_body[4:5]))
                            event_type = msg_body[6:7]
                            event_type = event_type_su_ter.get(event_type)
                            if not event_type:
                                event_type = '未知抓拍事项'
                            channel = byte2str(msg_body[7:8])
                            if channel == '01':
                                channel = 'DSM'
                            elif channel == '02':
                                channel = 'ADAS'
                            else:
                                channel = '通道错误'
                            location_msg_body = msg_body[8:36]
                            speed = int(
                                big2num(byte2str(
                                    location_msg_body[18:20]))) // 10
                            alarm_time = byte2str(location_msg_body[22:28])

                            if media_type == 0:
                                self.media_name = r"告警ID{}_{}_{}_速度{}_时间{}.{}".format(
                                    media_id, event_type, channel, speed,
                                    alarm_time, 'jpg')
                            elif media_type == 2:
                                self.media_name = r"告警ID{}_{}_{}_速度{}_时间{}.{}".format(
                                    media_id, event_type, channel, speed,
                                    alarm_time, 'mp4')
                            if os.path.exists(
                                    os.path.join(path_dir, self.media_name)):
                                file_name_list = self.media_name.split('.')
                                file_name_list[0] += '_bak'
                                self.media_name = '.'.join(file_name_list)
                        else:
                            img_data = msg_body[:]
                            self.buf += img_data
                            if total_pkg == pkg_no:
                                try:
                                    with open(
                                            os.path.join(
                                                path_dir, self.media_name),
                                            'ab') as f:
                                        f.write(self.buf)
                                except PermissionError:
                                    logger.error(PermissionError)
                                    with open(
                                            os.path.join(
                                                path_dir, self.media_name),
                                            'ab') as f:
                                        f.write(self.buf)
                                except FileNotFoundError:
                                    logger.error(FileNotFoundError)
                                self.buf = b''
                                self.media_name = ''

                    elif data[:2] == b'\x0E\x10':
                        msg_body = data[16:-1]

                        result = byte2str(msg_body[0:1])
                        similarity_threshold = big2num(byte2str(msg_body[1:2]))
                        similarity = big2num(byte2str(msg_body[2:4]))
                        cp_type = byte2str(msg_body[4:5])
                        cp_face_id_len = big2num(byte2str(msg_body[5:6]))
                        cp_face_id = msg_body[6:6 +
                                              cp_face_id_len].decode("gbk")
                        if not cp_face_id:
                            cp_face_id = None
                        location_info = msg_body[6 + cp_face_id_len:6 +
                                                 cp_face_id_len + 28]
                        img_type = byte2str(msg_body[34 + cp_face_id_len:35 +
                                                     cp_face_id_len])
                        img_data = msg_body[35 + cp_face_id_len:]

                        alarm_flag = byte2str(location_info[0:4])
                        state = byte2str(location_info[4:8])
                        latitude = big2num(byte2str(location_info[8:12]))
                        longitude = big2num(byte2str(location_info[12:16]))
                        speed = big2num(byte2str(location_info[18:20])) / 10
                        alarm_time = byte2str(location_info[22:])

                        media_name = "告警时间_{}_结果_{}_相似度_{}_人脸id_{}.jpg".format(
                            alarm_time, result, similarity, cp_face_id)
                        path_dir = os.path.join('Result', 'Face_Identify')
                        if not os.path.exists(path_dir):
                            os.mkdir(path_dir)
                        with open(os.path.join(path_dir, media_name),
                                  'ab') as f:
                            f.write(img_data)

                time.sleep(0.001)
            time.sleep(0.5)
Ejemplo n.º 17
0
    def run(self):
        logger.debug(threading.current_thread().getName())
        if not os.path.exists('Result'):
            os.mkdir('Result')
        while True:
            if conf.get_protocol_type() == 1:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    media_data = data[17:-1]
                    self.buf += media_data
                    total = int(byte2str(data[13:15]), 16)
                    rec = int(byte2str(data[15:17]), 16)
                    if rec == total - 1:
                        media_id = byte2str(data[9:13])
                        if data[6:7] == b'\x65':
                            event_type = alarm_type_code_su_dsm.get(
                                media_alarm_code.get(media_id))
                            dir_name = os.path.join('Result', 'DSM_media')
                        else:
                            event_type = alarm_type_code_su_adas.get(
                                media_alarm_code.get(media_id))
                            dir_name = os.path.join('Result', 'ADAS_media')
                        t = time.strftime(r'%Y%m%d%H', time.localtime())
                        dir_name = os.path.join(dir_name, t)
                        if not os.path.exists(dir_name):
                            os.makedirs(dir_name)
                        media_type = byte2str(data[8:9])
                        if media_type == '00':
                            self.media_name = r'告警ID{}_{}.jpg'.format(
                                int(media_id, 16), event_type)
                        elif media_type == '02':
                            self.media_name = r'告警ID{}_{}.mp4'.format(
                                int(media_id, 16), event_type)
                        elif media_type == '01':
                            self.media_name = r'告警ID{}_{}.mp3'.format(
                                int(media_id, 16), event_type)
                        else:
                            logger.error('未知的多媒体类型。')
                        file_name = os.path.join(dir_name, self.media_name)
                        if os.path.exists(file_name):
                            file_name_list = file_name.split('.')
                            file_name_list[0] += '_bak'
                            file_name = '.'.join(file_name_list)
                        with open(file_name, 'ab') as f:
                            f.write(self.buf)
                            self.buf = b''
                        try:
                            if media_alarm_code:
                                media_alarm_code.pop(media_id)
                        except KeyError:
                            logger.error('media_id{}不存在。'.format(media_id))
            elif conf.get_protocol_type() == 3:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    total_pkg = big2num(byte2str(data[13:15]))
                    pkg_no = big2num(byte2str(data[15:17]))
                    path_dir = os.path.join('Result', 'Alarm_Media')
                    if not os.path.exists(path_dir):
                        os.mkdir(path_dir)
                    if pkg_no == 1:
                        img_data = data[53:-2]
                        self.buf += img_data
                        media_id_byte = data[17:21]
                        media_id = big2num(byte2str(media_id_byte))
                        media_type = big2num(byte2str(data[21:22]))
                        event_type = big2num(byte2str(data[23:24]))
                        channel = byte2str(data[24:25])
                        speed = big2num(byte2str(data[43:45]))
                        alarm_time = byte2str(data[47:53])

                        if media_type == 0:
                            self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                media_id,
                                alarm_type_code_jt808.get(event_type), channel,
                                str(speed), alarm_time, 'jpg')
                        elif media_type == 2:
                            self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                media_id,
                                alarm_type_code_jt808.get(event_type), channel,
                                str(speed), alarm_time, 'mp4')
                        if os.path.exists(
                                os.path.join(path_dir, self.media_name)):
                            file_name_list = self.media_name.split('.')
                            file_name_list[0] += '_bak'
                            self.media_name = '.'.join(file_name_list)
                    else:
                        img_data = data[17:-2]
                        self.buf += img_data
                        if total_pkg == pkg_no:
                            try:
                                with open(
                                        os.path.join(path_dir,
                                                     self.media_name),
                                        'ab') as f:
                                    f.write(self.buf)
                            except PermissionError:
                                logger.error(PermissionError)
                                with open(
                                        os.path.join(path_dir,
                                                     self.media_name),
                                        'ab') as f:
                                    f.write(self.buf)
                            except FileNotFoundError:
                                logger.error(FileNotFoundError)
                            self.buf = b''
                            self.media_name = ''
            elif conf.get_protocol_type() == 5:
                while not media_queue.empty():
                    data = media_queue.get(block=False)
                    if data[0:4] == b'\x30\x31\x63\x64':
                        media_name = data[4:54].split(b'\x00')[0].decode(
                            'utf-8')
                        media_name_bak = media_name
                        media_size = name_size.get(media_name)
                        media_type = media_name.split('_')[2]
                        if media_type[:2] == '65':
                            media_type = alarm_type_code_su_ter_dsm.get(
                                bytes.fromhex(media_type[2:]))
                        elif media_type[:2] == '64':
                            media_type = alarm_type_code_su_ter_adas.get(
                                bytes.fromhex(media_type[2:]))
                        else:
                            media_type = 'error'
                        media_name = media_name.replace(
                            '.', '_{}.'.format(media_type))
                        media_name_list = media_name.split('_')
                        media_name = media_name_list[4][:16] + '_' + '_'.join(
                            media_name_list)
                        # media_name = media_type + "_" + media_name
                        offset = big2num(byte2str(data[54:58]))
                        data_length = big2num(byte2str(data[58:62]))
                        data_content = data[62:62 + data_length]
                        self.buf += data_content
                        if offset + data_length == media_size:
                            path_dir = os.path.join('Result', 'Alarm_Media')
                            if not os.path.exists(path_dir):
                                os.mkdir(path_dir)
                            with open(os.path.join(path_dir, media_name),
                                      'ab') as f:
                                f.write(self.buf)
                                name_size.pop(media_name_bak)
                            self.buf = b''
                            self.media_name = ''
                    else:
                        total_pkg = big2num(byte2str(data[13:15]))
                        pkg_no = big2num(byte2str(data[15:17]))
                        path_dir = os.path.join('Result', 'Alarm_Media')
                        if not os.path.exists(path_dir):
                            os.mkdir(path_dir)
                        if pkg_no == 1:
                            img_data = data[53:-2]
                            self.buf += img_data
                            media_id_byte = data[17:21]
                            media_id = big2num(byte2str(media_id_byte))
                            media_type = big2num(byte2str(data[21:22]))
                            event_type = data[23:24]
                            channel = byte2str(data[24:25])
                            speed = int(big2num(byte2str(data[43:45]))) / 10
                            alarm_time = byte2str(data[47:53])

                            if media_type == 0:
                                self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                    media_id,
                                    event_type_su_ter.get(event_type), channel,
                                    speed, alarm_time, 'jpg')
                            elif media_type == 2:
                                self.media_name = r"告警ID{}_{}_通道{}_速度{}_{}.{}".format(
                                    media_id,
                                    event_type_su_ter.get(event_type), channel,
                                    speed, alarm_time, 'mp4')
                            if os.path.exists(
                                    os.path.join(path_dir, self.media_name)):
                                file_name_list = self.media_name.split('.')
                                file_name_list[0] += '_bak'
                                self.media_name = '.'.join(file_name_list)
                        else:
                            img_data = data[17:-2]
                            self.buf += img_data
                            if total_pkg == pkg_no:
                                try:
                                    with open(
                                            os.path.join(
                                                path_dir, self.media_name),
                                            'ab') as f:
                                        f.write(self.buf)
                                except PermissionError:
                                    logger.error(PermissionError)
                                    with open(
                                            os.path.join(
                                                path_dir, self.media_name),
                                            'ab') as f:
                                        f.write(self.buf)
                                except FileNotFoundError:
                                    logger.error(FileNotFoundError)
                                self.buf = b''
                                self.media_name = ''
                time.sleep(0.001)
            time.sleep(0.5)
Ejemplo n.º 18
0
def set_para():
    if conf.get_protocol_type() == 3 or conf.get_protocol_type() == 5:
        txt = '修改参数 : '
        list_num = 0
        address_ = e_address.get()
        port_ = e_port.get()
        limit_speed_ = e_limit_speed.get()
        adas_speed_ = e_adas_speed.get()
        vol_ = e_vol.get()
        mode_ = e_mode.get()
        msg_body = ''
        if address_:
            list_num += 1
            ip_len = len(address_)
            msg_body += '00000013' + num2big(ip_len, 1) + str2hex(
                address_, ip_len)
            txt += '服务器 {} '.format(address_)
        if port_:
            list_num += 1
            msg_body += '00000018' + '04' + num2big(int(port_), 4)
            txt += '端口号 {} '.format(port_)
        if limit_speed_:
            list_num += 1
            msg_body += '00000055' + '04' + num2big(int(limit_speed_), 4)
            txt += '最高速度 {} '.format(limit_speed_)
        if adas_speed_:
            list_num += 1
            msg_body += '0000F091' + '01' + num2big(int(adas_speed_), 1)
            txt += 'ADAS激活速度 {} '.format(adas_speed_)
        if vol_:
            list_num += 1
            msg_body += '0000F092' + '01' + num2big(int(vol_), 1)
            txt += '告警音量 {} '.format(vol_)
        if mode_:
            list_num += 1
            msg_body += '0000F094' + '01' + num2big(int(mode_), 1)
            txt += '工作模式 {} '.format(mode_)
        if list_num:
            msg_body = num2big(list_num, 1) + msg_body
            body = '8103' + num2big(int(len(msg_body) / 2), 2) + GlobalVar.DEVICEID + \
                   num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            logger.debug('—————— 设置终端参数 ——————')
            logger.debug('—————— ' + txt + ' ——————')
            send_queue.put(data)
    elif conf.get_protocol_type() == 4:
        address_ = e_address.get()
        port_ = e_port.get()
        limit_speed_ = e_limit_speed.get()
        adas_speed_ = e_adas_speed.get()
        vol_ = e_vol.get()
        mode_ = e_mode.get()
        product_ = e_product.get()
        para_list = []
        para_dic = {}
        if address_:
            para_list.append({"1": address_})
        if port_:
            para_list.append({"2": port_})
        if product_:
            para_list.append({"3": product_})
        if limit_speed_:
            para_list.append({"4": limit_speed_})
        if adas_speed_:
            para_list.append({"5": adas_speed_})
        if vol_:
            para_list.append({"6": vol_})
        if mode_:
            para_list.append({"7": mode_})
        para_dic["TerminalParameter"] = para_list
        if para_dic:
            msg_body = str2hex(json.dumps(para_dic), 1024)
            service = num2big((11 << 6) + (4 << 1), 2) + calc_lens_sf(msg_body)
            timestamp = num2big(int(round(time.time() * 1000)), 8)
            pro_id = num2big(1744, 2)
            other = '800000'
            body = other + timestamp + pro_id + service + msg_body
            data = '55' + '41' + calc_lens_sf(body) + body + '55'
            send_queue.put(data)
Ejemplo n.º 19
0
class FaceWindow(object):

    def __init__(self, face, face_youwei, face_su_ter):
        self.root_face = face
        self.face_mask = IntVar()
        self.certificate_mask = IntVar()
        self.name_mask = IntVar()

        self.face_case_path = ''
        self.face_image_path = ''
        self.face_path = ''


        self.root_face_youwei = face_youwei
        self.person_id_cont1 = tkinter.StringVar()
        self.person_id_cont2 = tkinter.StringVar()
        self.image_id_cont = tkinter.StringVar()

        self.root_face_su_ter = face_su_ter

    def face_func_window(self):

        # 人脸信息UI布局——吉标外设
        frame_su_replace_all = Button(self.root_face, text="全替换", command=self.replace_all_face, width=15, bd=5)
        frame_su_replace_all.grid(row=0, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_delete_all = Button(self.root_face, text="全删除", command=self.delete_all_face, width=15, bd=5)
        frame_su_delete_all.grid(row=1, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_delete_some = Button(self.root_face, text="删除指定", command=self.delete_some_face, width=15, bd=5)
        frame_su_delete_some.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_query = Button(self.root_face, text="身份库查询", command=self.query_face, width=15, bd=5)
        frame_su_query.grid(row=0, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        # 多选框
        frm_modify_mask = Frame(self.root_face)
        ck1_modify_mask = Checkbutton(frm_modify_mask, text='人脸图片', variable=self.face_mask, onvalue=1, offvalue=0)
        ck2_modify_mask = Checkbutton(frm_modify_mask, text='资格证', variable=self.certificate_mask, onvalue=1, offvalue=0)
        ck3_modify_mask = Checkbutton(frm_modify_mask, text='姓名', variable=self.name_mask, onvalue=1, offvalue=0)
        ck1_modify_mask.grid(row=0, column=0,sticky=W)
        ck2_modify_mask.grid(row=0, column=1, sticky=W)
        ck3_modify_mask.grid(row=0, column=2, sticky=W)
        frm_modify_mask.grid(row=2, column=0, sticky=W, columnspan=2)

        frame_su_delete_all = Button(self.root_face, text="修改", command=self.modify_info, width=15, bd=5)
        frame_su_delete_all.grid(row=3, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)


        self.frame_su_para_case = Label(self.root_face,text="人脸信息文件:")
        self.frame_su_para_case.grid(row=4, column=0, pady=15, sticky=W)
        self.frame_su_para_select = Button(self.root_face, text="选择文件", command=self.select_case_file, bd=5, width=15)
        self.frame_su_para_select.grid(row=5, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        # 有为人脸UI布局
        frame_add_person_youwei = Button(self.root_face_youwei, text="添加人员", command=self.add_person_youwei, width=15, bd=5)
        frame_add_person_youwei.grid(row=0, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_modify_person_youwei = Button(self.root_face_youwei, text="修改人员", command=self.modify_person_youwei, width=15, bd=5)
        frame_modify_person_youwei.grid(row=0, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_delete_person_youwei = Button(self.root_face_youwei, text="删除人员", command=self.delete_person_youwei, width=15, bd=5)
        frame_delete_person_youwei.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_delete_all_youwei = Button(self.root_face_youwei, text="删除所有", command=self.delete_all_youwei, width=15, bd=5)
        frame_delete_all_youwei.grid(row=1, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_query_person_youwei = Button(self.root_face_youwei, text="查询人员", command=self.query_person_youwei, width=15, bd=5)
        frame_query_person_youwei.grid(row=2, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_query_all_youwei = Button(self.root_face_youwei, text="查询所有", command=self.query_all_youwei, width=15, bd=5)
        frame_query_all_youwei.grid(row=2, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        self.frame_person_id_text1 = Label(self.root_face_youwei, text="人员ID:", width=13)
        self.frame_person_id_text1.grid(row=3, column=0, ipadx=20, ipady=5, pady=5, sticky=W)
        self.frame_person_id_cont1 = Entry(self.root_face_youwei, textvariable=self.person_id_cont1, bd=5, width=15)
        self.frame_person_id_cont1.grid(row=3, column=1, ipadx=20, ipady=5, pady=5, padx=5, sticky=W)

        frame_catch_photo_register_youwei = Button(self.root_face_youwei, text="抓拍注册", command=self.catch_photo_register_youwei, width=15, bd=5)
        frame_catch_photo_register_youwei.grid(row=4, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        self.frame_person_id_text2 = Label(self.root_face_youwei, text="人员ID:", width=13)
        self.frame_person_id_text2.grid(row=5, column=0, ipadx=20, ipady=5, pady=5, sticky=W)
        self.frame_person_id_cont2 = Entry(self.root_face_youwei, textvariable=self.person_id_cont2, bd=5, width=15)
        self.frame_person_id_cont2.grid(row=5, column=1, ipadx=20, ipady=5, pady=5, padx=5, sticky=W)

        self.frame_image_id_text2 = Label(self.root_face_youwei, text="人脸ID:", width=13)
        self.frame_image_id_text2.grid(row=6, column=0, ipadx=20, ipady=5, pady=5, sticky=W)
        self.frame_image_id_cont2 = Entry(self.root_face_youwei, textvariable=self.image_id_cont, bd=5, width=15)
        self.frame_image_id_cont2.grid(row=6, column=1, ipadx=20, ipady=5, pady=5, padx=5, sticky=W)

        self.frame_su_image_path = Label(self.root_face_youwei,text="图片路径:")
        self.frame_su_image_path.grid(row=7, column=0, ipadx=20, ipady=5, pady=5, sticky=W, columnspan=2)
        self.frame_su_image_select = Button(self.root_face_youwei, text="选择图片", command=self.select_image, bd=5, width=15)
        self.frame_su_image_select.grid(row=8, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_register_youwei = Button(self.root_face_youwei, text="图片注册", command=self.start_register_youwei, width=15, bd=5)
        frame_register_youwei.grid(row=8, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_delete_face_youwei = Button(self.root_face_youwei, text="删除人脸", command=self.delete_face_youwei, width=15, bd=5)
        frame_delete_face_youwei.grid(row=9, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_identify_youwei = Button(self.root_face_youwei, text="人脸识别", command=self.face_identify_youwei, width=15, bd=5)
        frame_identify_youwei.grid(row=9, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        self.frame_face_path = Label(self.root_face_youwei,text="人脸目录:")
        self.frame_face_path.grid(row=10, column=0, ipadx=20, ipady=5, pady=5, sticky=W, columnspan=2)

        frame_select_path = Button(self.root_face_youwei, text="选择目录", command=self.select_path, width=15, bd=5)
        frame_select_path.grid(row=11, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_register_all = Button(self.root_face_youwei, text="注册全部人脸", command=self.register_all_face_youwei, width=15, bd=5)
        frame_register_all.grid(row=11, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)


        # 人脸信息UI布局——吉标终端
        frame_su_replace_all = Button(self.root_face_su_ter, text="全替换", command=self.replace_all_face, width=15, bd=5)
        frame_su_replace_all.grid(row=0, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_query = Button(self.root_face_su_ter, text="修改", command=self.modify_info, width=15, bd=5)
        frame_su_query.grid(row=0, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_delete_all = Button(self.root_face_su_ter, text="全删除", command=self.delete_all_face, width=15, bd=5)
        frame_su_delete_all.grid(row=1, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)
        frame_su_delete_some = Button(self.root_face_su_ter, text="删除指定", command=self.delete_some_face, width=15, bd=5)
        frame_su_delete_some.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        frame_su_query = Button(self.root_face_su_ter, text="身份库查询", command=self.query_face, width=15, bd=5)
        frame_su_query.grid(row=2, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

        self.frame_su_para_case = Label(self.root_face_su_ter,text="人脸信息文件:")
        self.frame_su_para_case.grid(row=3, column=0, pady=15, sticky=W)
        self.frame_su_para_select = Button(self.root_face_su_ter, text="选择文件", command=self.select_case_file, bd=5, width=15)
        self.frame_su_para_select.grid(row=4, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)

    # 选择用例文件
    def select_case_file(self):
        self.casefile = tkinter.filedialog.askopenfilename()
        self.casefilename = os.path.split(self.casefile)[-1]
        if self.casefilename:
            self.frame_su_para_case.config(text="用例:" + self.casefilename)
            self.face_case_path = self.casefile

    # 选择人脸图片
    def select_image(self):
        self.casefile = tkinter.filedialog.askopenfilename()
        self.casefilename = os.path.split(self.casefile)[-1]
        if self.casefilename:
            self.frame_su_image_path.config(text="图片路径:" + self.casefilename)
            self.face_image_path = self.casefile


    def select_path(self):
        self.face_path = tkinter.filedialog.askdirectory()
        if self.face_path:
            self.frame_face_path.config(text="人脸目录:" + os.path.split(self.face_path)[-1])


    # 下发人脸信息列表-全替换
    def replace_all_face(self):
        logger.debug('—————— 替换所有人脸 ——————')
        if conf.get_protocol_type() == 1:
            mask = 0b00000000
            send_face_thread = SendFace('【 Data Server 】 SendFace Thread Start ...', 0, mask, self.face_case_path)
            send_face_thread.start()

        elif conf.get_protocol_type() == 5:
            if self.face_case_path:
                face_case_name = self.face_case_path
            else:
                face_case_name = r'.\TestData\Face_suter\全替换人脸.xls'
            rs = xlrd.open_workbook(face_case_name)
            table = rs.sheets()[0]
            cols = table.ncols
            face_num = (cols+1)//4
            face_info_list = ''
            for n in range(1, cols + 1, 4):
                data_len = table.col_values(n)[1:]
                data_content = table.col_values(n + 1)[1:]
                deal_data = list(map(read_value, data_content))
                data = list(map(data2hex, deal_data, data_len))
                face_info_list += ''.join(data)
            msg_body = '00' + num2big(face_num, 1) + face_info_list
            body = '8E11' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            send_queue.put(data)

    # 下发人脸信息列表-修改
    def modify_info(self):
        if conf.get_protocol_type() == 1:

            mask = 0b00000000

            if self.face_mask.get():
                mask = mask | 0b00000001
            if self.certificate_mask.get():
                mask = mask | 0b00000010
            if self.name_mask.get():
                mask = mask | 0b00000100

            if mask:
                logger.debug('—————— 修改人脸信息 ——————')
                send_face_thread = SendFace('【 Data Server 】 SendFace Thread Start ...', 3, mask, self.face_case_path)
                send_face_thread.start()
        elif conf.get_protocol_type() == 5:
            logger.debug('—————— 修改人脸信息 ——————')
            if self.face_case_path:
                face_case_name = self.face_case_path
            else:
                face_case_name = r'.\TestData\Face_suter\修改人脸.xls'
            rs = xlrd.open_workbook(face_case_name)
            table = rs.sheets()[0]
            cols = table.ncols
            face_num = (cols+1)//4
            face_info_list = ''
            for n in range(1, cols + 1, 4):
                data_len = table.col_values(n)[1:]
                data_content = table.col_values(n + 1)[1:]
                deal_data = list(map(read_value, data_content))
                data = list(map(data2hex, deal_data, data_len))
                face_info_list += ''.join(data)
            msg_body = '03' + num2big(face_num, 1) + face_info_list
            body = '8E11' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            send_queue.put(data)

    # 下发人脸信息列表-全删除
    def delete_all_face(self):
        logger.debug('—————— 删除所有人脸 ——————')
        if conf.get_protocol_type() == 1:

            # 数据内容拼接:厂商编码 + 外设编号 + 功能码 + 设置类型
            msg_body = '033D' + '65' + 'E9' + '01'
            # 报文格式拼接
            data = '7E' + calc_check_code(msg_body) + num2big(GlobalVar.get_serial_no()) + msg_body + '7E'
            # 发文发送
            send_queue.put(data)
        elif conf.get_protocol_type() == 5:
            msg_body = '01'
            body = '8E11' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body
            data = '7E' + body + calc_check_code(body) + '7E'
            send_queue.put(data)

    # 下发人脸信息列表-删除指定
    def delete_some_face(self):
        if conf.get_protocol_type() == 1:
            case = GetTestData(r'.\TestData\Face\删除指定人脸.xls')
        elif conf.get_protocol_type() == 5:
            case = GetTestData(r'.\TestData\Face_suter\删除指定人脸.xls')
Ejemplo n.º 20
0
    end_date_ = e_end_date.get()
    if start_date_ and end_date_:
        get_log_su(start_date_, end_date_)


address = Label(root, text='IP号:')
address.grid(row=0, sticky=W)
e_address = Entry(root)
e_address.grid(row=0, column=1, sticky=E)

product = Label(root, text='产品ID:')
product.grid(row=0, column=3, sticky=W)
e_product = Entry(root)
e_product.grid(row=0, column=4, sticky=E)

if conf.get_protocol_type() == 4:
    port = Label(root, text='文件地址:')
else:
    port = Label(root, text='端口号:')
port.grid(row=1, sticky=W)
e_port = Entry(root)
e_port.grid(row=1, column=1, sticky=E)

limit_speed = Label(root, text='最高速度:')
limit_speed.grid(row=2, sticky=W)
e_limit_speed = Entry(root)
e_limit_speed.grid(row=2, column=1, sticky=E)

adas_speed = Label(root, text='ADAS激活速度:')
adas_speed.grid(row=3, sticky=W)
e_adas_speed = Entry(root)
def main():
    HOST = conf.get_address()
    PORT = conf.get_port()

    server = ThreadedTCPServer((HOST, PORT), TCPRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    logger.debug('【 Data Server 】 Server starting, waiting for connection ...')
    if conf.get_protocol_type() == 5:
        FILE_HOST = conf.get_file_address_su_ter_local()
        FILE_PORT = conf.get_file_port_su_ter_local()
        file_server = ThreadedTCPServer((FILE_HOST, FILE_PORT), TCPRequestHandlerForFile)
        file_server_thread = threading.Thread(target=file_server.serve_forever)
        file_server_thread.daemon = True
        file_server_thread.start()
        logger.debug('【 File Server 】 Server starting, waiting for connection ...')
        if conf.get_instant_video_flag():
            VIDEO_HOST = conf.get_instant_video_address_local()
            VIDEO_PORT = conf.get_instant_video_port_local()
            file_server = ThreadedTCPServer((VIDEO_HOST, VIDEO_PORT), TCPRequestHandlerForVideo)
            file_server_thread = threading.Thread(target=file_server.serve_forever)
            file_server_thread.daemon = True
            file_server_thread.start()
            logger.debug('【 Video Server 】 Server starting, waiting for connection ...')
    if conf.get_protocol_type() == 1:
        while not query_msg_queue.empty():
            query_msg_queue.get(block=False)
        from SaveModel.SaveLogThread import SaveLogThread
        save_log_thread = SaveLogThread('【 Data Server 】 SaveLog Thread Start ...')
        save_log_thread.setDaemon(True)
        save_log_thread.start()

    elif conf.get_protocol_type() == 4:
        run_http_server_thread = threading.Thread(target=run_http_server, name='run_http_server', args=())
        run_http_server_thread.setDaemon(True)
        run_http_server_thread.start()
    consume_thread = Consumer('【 Data Server 】 Consumer Thread Start ...')
    consume_thread.setDaemon(True)
    consume_thread.start()
    save_thread = SaveMediaThread('【 Data Server 】 SaveMedia Thread Start ...')
    save_thread.setDaemon(True)
    save_thread.start()
    parse_thread = ParseComm('【 Data Server 】 Parse Thread Start ...')
    parse_thread.setDaemon(True)
    parse_thread.start()
    get_media_thread = GetMediaThread('【 Data Server 】 GetMedia Thread Start ...')
    get_media_thread.setDaemon(True)
    get_media_thread.start()

    if conf.get_gps_test():
        from Tool.Relay import rc
        rc.power_on()
        testLoop = threading.Thread(target=rc.testLoop)
        logger.debug('【 Data Server 】 Timer Thread Start ...')
        testLoop.start()

    MainWindow()
    try:
        while True:
            wake_event.wait()
            break
    except KeyboardInterrupt:
        logger.debug('捕捉到CTRL+C中断信号。')
Ejemplo n.º 22
0
 def delete_some_face(self):
     if conf.get_protocol_type() == 1:
         case = GetTestData(r'.\TestData\Face\删除指定人脸.xls')
Ejemplo n.º 23
0
def produce(buf, remain):
    if conf.get_protocol_type() == 1:
        data = remain + buf
        st_list = [m.start() for m in re.finditer(b"\x7e", data)]
        current = -1
        for x in range(len(st_list)):
            if st_list[x] <= current:
                continue
            if not st_list[x] == st_list[-1]:
                if st_list[x] + 1 == st_list[x + 1]:
                    continue
            for y in range(x + 1, len(st_list)):
                data_piece = rec_translate(data[st_list[x]:st_list[y] + 1])
                if byte2str(data_piece[1:2]) == calc_check_code(
                        byte2str(data_piece[4:-1])):
                    rec_queue.put(data_piece)
                    current = st_list[y]
                    break
                else:
                    print(calc_check_code(byte2str(data_piece[4:-1])))
                    logger.error("未能解析的7E数据" + byte2str(data_piece))
        remain = data[current + 1:]
        return remain
    # elif conf.get_protocol_type() == 2:
    #     data = remain + buf
    #     # 找出所有FB的位置
    #     st_list = [m.start() for m in re.finditer(b"\xfb", data)]
    #     # current 变量用于记录当前截取的有效报文末位的索引
    #     current = -1
    #     for x in range(len(st_list)):
    #         # 若FB位于 current之前,则忽略不处理
    #         if st_list[x] < current:
    #             continue
    #         # 判断剩余的报文是否满足报文的最短要求
    #         elif len(data[st_list[x]:]) >= 15:
    #             # 判断保留位是否为0
    #             if data[st_list[x] + 5:st_list[x] + 9] == b'\x00\x00\x00\x00':
    #                 len_start = st_list[x] + 1
    #                 len_end = st_list[x] + 5
    #                 length_hex = byte2str(data[len_start:len_end])
    #                 length = small2num(length_hex)
    #                 # 根据报文长度截出相应的报文
    #                 data_piece = data[st_list[x]:st_list[x] + length]
    #                 # 判断报文长度字段与实际报文长度是否一致
    #                 if len(data_piece) == length:
    #                     data_piece_hex = byte2str(data_piece)
    #                     calc_code = calc_check_code(data_piece_hex[:-2])
    #                     check_code = data_piece_hex[-2:]
    #                     # 判断校验码与实际校验字段是否一致
    #                     if calc_code == check_code:
    #                         rec_queue.put(data_piece)
    #                         current = st_list[x] + length
    #                     else:
    #                         logger.error(byte2str(data_piece))
    #     if current == -1:
    #         current = 0
    #     remain = data[current:]
    #     return remain
    elif conf.get_protocol_type() == 3 or conf.get_protocol_type() == 5:
        data = remain + buf
        st_list = [m.start() for m in re.finditer(b"\x7e", data)]
        current = -1
        for x in range(len(st_list)):
            if st_list[x] <= current:
                continue
            if not st_list[x] == st_list[-1]:
                if st_list[x] + 1 == st_list[x + 1]:
                    logger.info(data[st_list[x]:st_list[x] + 2])
                    continue
            for y in range(x + 1, len(st_list)):
                data_piece = data[st_list[x]:st_list[y] + 1]
                if len(data_piece) > 2 and b'\x7e' not in data_piece[1:-1]:
                    data_piece = rec_translate(data_piece)
                    # if byte2str(data_piece[-2:-1]) == calc_check_code(byte2str(data_piece[1:-2])):
                    rec_queue.put(data_piece)
                    current = st_list[y]
                    break
                else:
                    logger.error("未能解析的7E数据" + byte2str(data_piece))
        remain = data[current + 1:]
        return remain
    elif conf.get_protocol_type() == 4:
        data = remain + buf
        st_list = [m.start() for m in re.finditer(b"\x55", data)]
        current = -1
        for x in range(len(st_list)):
            if st_list[x] <= current:
                continue
            if not st_list[x] == st_list[-1]:
                if st_list[x] + 1 == st_list[x + 1]:
                    logger.info(data[st_list[x]:st_list[x] + 2])
                    continue
            for y in range(x + 1, len(st_list)):
                data_piece = rec_translate(data[st_list[x]:st_list[y] + 1])
                if len(data_piece) > 2:
                    rec_queue.put(data_piece)
                    current = st_list[y]
                    break
                else:
                    logger.error("未能解析的55数据" + byte2str(data_piece))
        remain = data[current + 1:]
        return remain
    def get_excel_data(self):
        ncol = self.table.ncols
        test_case_num = int((ncol + 1) / 4)
        for case in range(test_case_num):
            # 获取字段长度列和字段值列
            data_len_list = self.table.col_values(case * 4 + 1)
            while True:
                if data_len_list[-1] == '':
                    del data_len_list[-1]
                else:
                    break
            data_value_list = self.table.col_values(case * 4 + 2)
            while True:
                if len(data_value_list) > len(data_len_list):
                    del data_value_list[-1]
                else:
                    break
            # 获取测试编号和测试要点
            test_num = self.table.cell(0, case * 4).value
            test_point = self.table.cell(1, case * 4).value
            # 找出发送报文和接收报文的分割点
            send_start_index = data_value_list.index('发送报文字段值')
            expc_start_index = data_value_list.index('接收报文字段值')
            # 分割发送报文和接收报文的字段长度和字段值
            send_data_value_list = data_value_list[send_start_index +
                                                   1:expc_start_index]
            expc_data_value_list = data_value_list[expc_start_index + 1:]
            send_data_len_list = data_len_list[send_start_index +
                                               1:expc_start_index]
            expc_data_len_list = data_len_list[expc_start_index + 1:]
            # 判断是否读取苏标数据
            if conf.get_protocol_type() == 1:
                # 判断发送和期待报文的流水号是否为空
                if not send_data_value_list[2]:
                    send_data_value_list[2] = get_serial_no()
                if not expc_data_value_list[2]:
                    expc_data_value_list[2] = send_data_value_list[2]

                # 如果长度为Auto,则自动计算字段长度
                for x in range(len(send_data_len_list)):
                    if send_data_len_list[x] == 'Auto':
                        if send_data_value_list[x][:2] == '0s':
                            send_data_len_list[x] = int(
                                len(send_data_value_list[x][2:]) / 2)
                        else:
                            send_data_len_list[x] = len(
                                send_data_value_list[x])
                            send_data_value_list[x] = str(
                                send_data_value_list[x])
                        if not send_data_value_list[x - 1]:
                            send_data_value_list[x - 1] = send_data_len_list[x]

                for x in range(len(expc_data_len_list)):
                    if expc_data_len_list[x] == 'Auto':
                        if expc_data_value_list[x][:2] == '0s':
                            expc_data_len_list[x] = int(
                                len(expc_data_value_list[x][2:]) / 2)
                        else:
                            expc_data_len_list[x] = len(
                                expc_data_value_list[x])
                            expc_data_value_list[x] = str(
                                expc_data_value_list[x])
                        if not expc_data_value_list[x - 1]:
                            expc_data_value_list[x - 1] = expc_data_len_list[x]

                # 读取出每个excel单元格中的数据
                send_data_deal_list = list(
                    map(read_value, send_data_value_list))
                expc_data_deal_list = list(
                    map(read_value, expc_data_value_list))

                # 将字段值转化为十六进制
                send_data_list = list(
                    map(data2hex, send_data_deal_list, send_data_len_list))
                expc_data_list = list(
                    map(data2hex, expc_data_deal_list, expc_data_len_list))
                # 添加校验码
                if not send_data_value_list[1]:
                    send_data_list[1] = calc_check_code(''.join(
                        send_data_list[3:-1]))
                if not expc_data_value_list[1]:
                    expc_data_list[1] = calc_check_code(''.join(
                        expc_data_list[3:-1]))

            elif conf.get_protocol_type() == 3 or conf.get_protocol_type(
            ) == 5:
                # 判断发送和期待报文的流水号是否为空
                if not send_data_value_list[4]:
                    send_data_value_list[4] = get_serial_no()
                if not expc_data_value_list[4]:
                    expc_data_value_list[4] = send_data_value_list[4]
                # 判断消息体长度是否为空,为空则设置标志位,后期自动计算长度
                if not send_data_value_list[2]:
                    send_len_is_0 = True
                else:
                    send_len_is_0 = False
                if not expc_data_value_list[2]:
                    expc_len_is_0 = True
                else:
                    expc_len_is_0 = False

                # 如果长度为Auto,则自动计算字段长度
                for x in range(len(send_data_len_list)):
                    if send_data_len_list[x] == 'Auto':
                        if send_data_value_list[x][:2] == '0s':
                            send_data_len_list[x] = int(
                                len(send_data_value_list[x][2:]) / 2)
                        else:
                            send_data_len_list[x] = len(
                                send_data_value_list[x])
                            send_data_value_list[x] = str(
                                send_data_value_list[x])
                        # 若长度字段填写为Auto,且上一个字段内容为空,则自动计算Auto字段的长度填入上一字段
                        if not send_data_value_list[x - 1]:
                            send_data_value_list[x - 1] = send_data_len_list[x]
                for x in range(len(expc_data_len_list)):
                    if expc_data_len_list[x] == 'Auto':
                        if expc_data_value_list[x][:2] == '0s':
                            expc_data_len_list[x] = int(
                                len(expc_data_value_list[x][2:]) / 2)
                        else:
                            expc_data_len_list[x] = len(
                                expc_data_value_list[x])
                            expc_data_value_list[x] = str(
                                expc_data_value_list[x])
                        if not expc_data_value_list[x - 1]:
                            expc_data_value_list[x - 1] = expc_data_len_list[x]

                # 读取出每个excel单元格中的数据
                send_data_deal_list = list(
                    map(read_value, send_data_value_list))
                expc_data_deal_list = list(
                    map(read_value, expc_data_value_list))

                # 如果是0x8103报文的参数长度为空则自动计算
                if send_data_deal_list[1] == 33027:
                    if not send_data_deal_list[5]:
                        send_data_deal_list[5] = int(
                            len(send_data_deal_list[6:-2]) / 3)

                if send_len_is_0:
                    send_data_deal_list[2] = int(sum(send_data_len_list[5:-2]))
                if expc_len_is_0:
                    expc_data_deal_list[2] = int(sum(expc_data_len_list[5:-2]))

                # 将字段值转化为十六进制
                send_data_list = list(
                    map(data2hex, send_data_deal_list, send_data_len_list))
                expc_data_list = list(
                    map(data2hex, expc_data_deal_list, expc_data_len_list))

                if send_data_list[3] == '000000000000':
                    send_data_list[3] = DEVICEID
                if send_data_list[3] == '000000000000':
                    send_data_list[3] = DEVICEID
                # 添加校验码
                if not send_data_value_list[-2]:
                    send_data_list[-2] = calc_check_code(''.join(
                        send_data_list[1:-2]))
                if not expc_data_value_list[-2]:
                    expc_data_list[-2] = calc_check_code(''.join(
                        expc_data_list[1:-2]))

            send_data = ''.join(send_data_list)
            expc_data = ''.join(expc_data_list)
            return test_point, send_data
Ejemplo n.º 25
0
 def parse_alarm(data):
     if conf.get_protocol_type() == 1:
         peripheral = data[6:7]
         function_no = data[7:8]
         serial_num = data[2:4]
         alarm_return_body = '%s%s%s' % (COMPANY_NO, byte2str(peripheral),
                                         byte2str(function_no))
         alarm_return = '%s%s%s%s%s' % (
             SU_FLAG, calc_check_code(alarm_return_body),
             byte2str(serial_num), alarm_return_body, SU_FLAG)
         send_queue.put(alarm_return)
         num = int(byte2str(data[38:39]), 16)
         alarm_type = data[13:14]
         video_id = data[-5:-1]
         speed = data[19:20]
         height = data[20:22]
         latitude = data[22:26]
         longitude = data[26:30]
         alarm_time = data[30:36]
         state = data[36:38]
         if peripheral == b'\x65':
             logger.debug('')
             logger.debug('========== 收到DSM告警信息 ==========')
             logger.debug('')
             logger.debug(
                 '—————— 视频ID {} 告警类型 -------------------- {} ——————'.
                 format(byte2str(video_id),
                        alarm_type_code_su_dsm.get(alarm_type)))
         elif peripheral == b'\x64':
             logger.debug('')
             logger.debug('========== 收到ADAS告警信息 ==========')
             logger.debug('')
             logger.debug(
                 '—————— 视频ID {} 告警类型 -------------------- {} ——————'.
                 format(byte2str(video_id),
                        alarm_type_code_su_adas.get(alarm_type)))
         logger.debug(
             '—————— 速度 {} 高程 {} 纬度 {} 经度 {} 告警时间 {} 车辆状态 {} ——————'.format(
                 big2num(byte2str(speed)), big2num(byte2str(height)),
                 big2num(byte2str(latitude)), big2num(byte2str(longitude)),
                 byte2str(alarm_time), byte2str(state)))
         if conf.get_get_media_flag():
             for x in range(num):
                 media_id = byte2str(data[39 + x * 5 + 1:39 + x * 5 + 5])
                 media_type = byte2str(data[39 + x * 5:39 + x * 5 + 1])
                 media_alarm_code[media_id] = alarm_type
                 if data[6:8] == DSM_ALARM_SU:
                     if media_type == '00' or '02':
                         query_media_body = '%s%s%s%s' % (
                             COMPANY_NO, '6550', media_type, media_id)
                     else:
                         logger.error('数据解析出错{}'.format(byte2str(data)))
                 elif data[6:8] == ADAS_ALARM_SU:
                     if media_type == '00' or '02':
                         query_media_body = '%s%s%s%s' % (
                             COMPANY_NO, '6450', media_type, media_id)
                     else:
                         logger.error('数据解析出错{}'.format(byte2str(data)))
                 else:
                     logger.error('不存在的告警{}'.format(byte2str(data)))
                 query_media = '%s%s%s%s%s' % (
                     SU_FLAG, calc_check_code(query_media_body),
                     num2big(GlobalVar.get_serial_no()), query_media_body,
                     SU_FLAG)
                 query_msg_queue.put(query_media)
                 global fetch_media_flag
                 if fetch_media_flag:
                     fetch_media_flag = False
                     if not query_msg_queue.empty():
                         send_queue.put(query_msg_queue.get(block=False))