def start_work(self):

        ip_bind = (self.address, self.port)
        self.connection = socket.socket()
        self.connection.connect(ip_bind)
        log_data.debug('=' * 100)

        if self.conn_type == 1:
            log_data.debug('【 Data Server 】 {} {} Connected ...'.format(
                self.connection.getpeername(), self.connection.getsockname()))

            th1 = threading.Thread(target=self.recv_data, args=())
            th1.start()
            th2 = threading.Thread(target=self.parse_data, args=())
            th2.start()
            th3 = threading.Thread(target=self.send_data, args=())
            th3.start()
        elif self.conn_type == 2:
            log_file.debug('【 File Server 】 {} {} Connected ...'.format(
                self.connection.getpeername(), self.connection.getsockname()))

            th1 = threading.Thread(target=self.recv_data_file, args=())
            th1.start()
            th2 = threading.Thread(target=self.parse_data_file, args=())
            th2.start()
            th3 = threading.Thread(target=self.send_data_file, args=())
            th3.start()
    def parse_data_file(self):
        log_file.debug("【 File Server 】 Parse Thread start...")
        while not getattr(self.connection, '_closed', False):
            try:
                data = rec_queue_file.get_nowait()
            except queue.Empty:
                data = None
            if data:
                data_rec = data
                text = byte2str(data)
                text_hex = ' '.join(text[i:i + 2]
                                    for i in range(0, len(text), 2))
                if len(text_hex) > 500:
                    text_hex = text_hex[:500]
                log_file.debug(
                    '%s%s%s%s%s' %
                    ("RECV DATA:   ", 'lens: ', str(len(data_rec)).ljust(
                        5, ' '), '   data: || ', text_hex))

                # 进入解析过程
                command = data[1:3]
                func = parse_su_ter.parse_su_ter_command.get(command)
                if func:
                    func(data[1:-1])
            time.sleep(0.1)
    def alarm_file_info(self):
        device_id = str2hex(communication_id[-7:], 7)
        info_type = '00'
        attachment_num = '04'
        file_info_list = ''
        alarm_type = alarm_flag_alarm_type.get(self.alarm_flag)
        if alarm_type:
            alarm_flag_alarm_type.pop(self.alarm_flag)
        self.file_path = os.path.join(self.file_path, alarm_type)
        self.file_list = os.listdir(self.file_path)
        for file in self.file_list:
            name, file_type = file.split('.')
            name_list = name.split('_')
            name_list[1] = alarm_type[:2]
            name_list[2] = alarm_type
            name_list[-1] = bytes.fromhex(self.alarm_no).decode('gbk')
            new_file = '_'.join(name_list)
            new_file = new_file + '.' + file_type
            os.rename(os.path.join(self.file_path, file),
                      os.path.join(self.file_path, new_file))
            index = self.file_list.index(file)
            self.file_list[index] = new_file
            file_name_len = len(new_file)
            file_name = str2hex(new_file, file_name_len)
            file_size = os.path.getsize(os.path.join(self.file_path, new_file))
            file_info_list += num2big(file_name_len, 1) + file_name + num2big(
                file_size, 4)

        msg_body = device_id + self.alarm_flag + self.alarm_no + info_type + attachment_num + file_info_list
        body = '1210' + calc_length_su_ter(
            msg_body) + communication_id + num2big(get_serial_no()) + msg_body
        data = '7E' + body + calc_check_code(body) + '7E'
        log_file.debug('—————— 报警附件信息 ——————')
        send_queue_file.put(data)
    def close_conn(self):

        if self.conn_type == 1:
            log_data.debug('【 Data Server 】 {} {} Disconnected ...'.format(
                self.connection.getpeername(), self.connection.getsockname()))
        elif self.conn_type == 2:
            log_file.debug('【 File Server 】 {} {} Disconnected ...'.format(
                self.connection.getpeername(), self.connection.getsockname()))
        self.connection.close()
        time.sleep(0.5)
        log_data.debug('=' * 100)
    def file_info_upload(self, file):
        file_name_len = len(file)
        file_name = str2hex(file, file_name_len)
        file_type = os.path.splitext(file)[-1]
        if file_type == '.jpg':
            file_type = '00'
        elif file_type == '.mp4':
            file_type = '02'
        file_size = os.path.getsize(os.path.join(self.file_path, file))

        msg_body = num2big(file_name_len, 1) + file_name + file_type + num2big(
            file_size, 4)
        body = '1211' + calc_length_su_ter(
            msg_body) + communication_id + num2big(get_serial_no()) + msg_body
        data = '7E' + body + calc_check_code(body) + '7E'
        log_file.debug('—————— 文件信息上传 {} ——————'.format(file))
        send_queue_file.put(data)
Exemple #6
0
def send_queue_data_file(data):
    if data:
        if ' ' in data:
            data = ''.join(data.split(' '))
        data_bak = data
        if data.startswith('7E'):
            data = send_translate(bytes.fromhex(data))
        else:
            data = bytes.fromhex(data)
        send_data = data

        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]
        log_file.debug(
            '%s%s%s%s%s' %
            ("SEND DATA:   ", 'lens: ', str(int(len(data_bak) / 2)).ljust(
                5, ' '), '   data: || ', text_hex))
        return send_data
 def send_data_file(self):
     log_file.debug("【 File Server 】 Send Thread start...")
     while not getattr(self.connection, '_closed', False):
         try:
             data = send_queue_file.get_nowait()
         except queue.Empty:
             data = None
         text = parse_data.send_queue_data_file(data)
         if text:
             try:
                 self.connection.sendall(text)
             except socket.timeout:
                 time.sleep(0.1)
                 log_file.debug(
                     '【 File Server 】 [Send Thread] Receiving data timeout,connection is interrupted.'
                 )
                 break
             except OSError:
                 time.sleep(0.1)
                 log_file.debug(
                     '【 File Server 】 [Send Thread] OSError,connection is interrupted.'
                 )
                 break
             except ConnectionResetError:
                 time.sleep(0.1)
                 log_file.debug(
                     '【 File Server 】 [Send Thread] ConnectionResetError,connection is interrupted.'
                 )
                 break
             except ConnectionAbortedError:
                 time.sleep(0.1)
                 log_file.debug(
                     '【 File Server 】 [Send Thread] ConnectionAbortedError,connection is interrupted.'
                 )
                 break
             except Exception as e:
                 log_file.error('[Send Thread] Unknown Error.')
                 log_file.error(e)
                 break
         time.sleep(0.1)
    def recv_data_file(self):
        log_file.debug("【 File Server 】 Recv Thread start...")
        while not getattr(self.connection, '_closed', False):
            buf = b''
            try:
                if self.remain:
                    self.remain = parse_data.produce_for_file(buf, self.remain)
                buf = self.connection.recv(1024)
            except socket.timeout:
                time.sleep(0.1)
                log_file.debug(
                    '【 File Server 】 [Recv Thread] Receiving data timeout,connection is interrupted.'
                )
                break
            except OSError:
                time.sleep(0.1)
                log_file.debug(
                    '【 File Server 】 [Recv Thread] OSError,connection is interrupted.'
                )
                break
            except ConnectionResetError:
                time.sleep(0.1)
                log_data.debug(
                    '【 Data Server 】 [Recv Thread] ConnectionResetError,connection is interrupted.'
                )
                break
            except ConnectionAbortedError:
                time.sleep(0.1)
                log_data.debug(
                    '【 Data Server 】 [Recv Thread] ConnectionAbortedError,connection is interrupted.'
                )
                break
            except Exception as e:
                log_data.error('[Recv Thread] Unknown Error.')
                log_data.error(e)
                break

            if not buf:
                time.sleep(0.1)
                log_file.debug(
                    '【 File Server 】 [Recv Thread] Receive empty data,connection is interrupted.'
                )
                break
            self.remain = parse_data.produce_for_file(buf, self.remain)
            time.sleep(0.1)
    def file_data_upload(self, file):
        file_size = os.path.getsize(os.path.join(self.file_path, file))
        piece = 65536
        n = file_size // piece
        r = file_size % piece
        with open(os.path.join(self.file_path, file), 'rb') as f:
            file_data = f.read()
        for x in range(n):
            offset = x * piece
            file_data_piece = file_data[offset:offset + piece]
            data = '30316364' + str2hex(file, 50) + num2big(
                offset, 4) + num2big(piece, 4) + byte2str(file_data_piece)
            log_file.debug('—————— 文件数据上传 {}   偏移量 {} 数据长度 {} ——————'.format(
                file, offset, piece))
            send_queue_file.put(data)
        offset = n * piece
        if r:
            piece = r
            file_data_piece = file_data[offset:offset + piece]

            data = '30316364' + str2hex(file, 50) + num2big(
                offset, 4) + num2big(piece, 4) + byte2str(file_data_piece)
            log_file.debug('—————— 文件数据上传 {}   偏移量 {} 数据长度 {} ——————'.format(
                file, offset, piece))
            send_queue_file.put(data)

        file_name_len = len(file)
        file_name = str2hex(file, file_name_len)
        file_type = os.path.splitext(file)[-1]
        if file_type == '.jpg':
            file_type = '00'
        elif file_type == '.mp4':
            file_type = '02'

        import time
        time.sleep(0.5)

        msg_body = num2big(file_name_len, 1) + file_name + file_type + num2big(
            file_size, 4)
        body = '1212' + calc_length_su_ter(
            msg_body) + communication_id + num2big(get_serial_no()) + msg_body
        data = '7E' + body + calc_check_code(body) + '7E'
        log_file.debug('—————— 文件上传完成 {} ——————'.format(file))
        send_queue_file.put(data)
Exemple #10
0
def parse_upload_finish_reply(data):
    msg_body = data[12:-1]
    file_name_len = big2num(byte2str(msg_body[0:1]))
    file_name = msg_body[1:1 + file_name_len].decode('gbk')
    file_type = byte2str(msg_body[1 + file_name_len:2 + file_name_len])
    result = byte2str(msg_body[2 + file_name_len:3 + file_name_len])
    retransmission_num = big2num(
        byte2str(msg_body[3 + file_name_len:4 + file_name_len]))
    log_file.debug('—————— 文件上传完成应答 ——————')
    log_file.debug('文件名称: {}'.format(file_name))
    log_file.debug('文件类型: {}'.format(file_type))
    log_file.debug('上传结果: {}'.format(result))
    log_file.debug('补传数量: {}'.format(retransmission_num))
    if not retransmission_num == 0:
        log_data.debug('补传内容: {}'.format(byte2str(msg_body[4 +
                                                           file_name_len:])))
    log_file.debug('—————— END ——————')
    event.set()