コード例 #1
0
    def send_request(self, input_payload):

        from PyCRC.CRC16 import CRC16
        crc = CRC16(modbus_flag=True).calculate(bytes(input_payload))

        # first byte is length, +2 for CRC16
        request_payload = bytearray([len(input_payload) + 2, 0x00])
        request_payload.extend(input_payload)

        # append CRC
        request_payload.append(crc & 0xFF)
        request_payload.append((crc >> 8) & 0xFF)

        # send to device
        response = self.send_packet(0x6a, request_payload)

        # check for error
        err = response[0x22] | (response[0x23] << 8)
        if err:
            raise ValueError('broadlink_response_error', err)

        response_payload = bytearray(self.decrypt(bytes(response[0x38:])))

        # experimental check on CRC in response (first 2 bytes are len, and trailing bytes are crc)
        response_payload_len = response_payload[0]
        if response_payload_len + 2 > len(response_payload):
            raise ValueError('hysen_response_error', 'first byte of response is not length')
        crc = CRC16(modbus_flag=True).calculate(bytes(response_payload[2:response_payload_len]))
        if (response_payload[response_payload_len] == crc & 0xFF) and (
                response_payload[response_payload_len + 1] == (crc >> 8) & 0xFF):
            return response_payload[2:response_payload_len]
        raise ValueError('hysen_response_error', 'CRC check on response failed')
コード例 #2
0
ファイル: client.py プロジェクト: slimkaki/CamadaFisica
 def getCRCValue(self, payload = b'',lastPack = False):
   if (lastPack == False):
     crcValue = CRC16().calculate(self.txBuffer[self.byteSlice:self.byteSlice+128])
     # Forçando um erro para checar o funcionamento:
     #crcValue = 39232
   else:
     crcValue = CRC16().calculate(payload)
   return crcValue
コード例 #3
0
ファイル: __init__.py プロジェクト: ntrteam/ak2ifirm
def inject_firm(blowfish, firm, buf):
    # secure block order will shuffled using 0xFFFFE184
    # ref: 0xFFFF9B70
    # zero fill will avoid encryption; gbatek.htm#dscartridgesecurearea
    # 0x7E00(0x9E00): firm header offset
    decrypted = b'\x00' * 0xE00
    decrypted += firm[:0x200]
    secure = decrypted * 4
    secure_crc = CRC16(modbus_flag=True).calculate(secure)

    flags = [
        # normal card control register settings
        (
            0
            | (1 << 27)  # NTRCARD_CLK_SLOW
            #| (1 << 22)     # NTRCARD_SEC_CMD
            #| (0x18 << 16)  # NTRCARD_DELAY2(0x18)
            #| (1 << 14)     # NTRCARD_SEC_EN
            #| (1 << 13)     # NTRCARD_SEC_DAT
            | 0x18  # NTRCARD_DELAY1(0x18)
        ),
        # secure card control register settings
        (
            0
            | (1 << 27)  # NTRCARD_CLK_SLOW
            | (0x18 << 16)  # NTRCARD_DELAY2(0x18)
            | 0x8F8  # NTRCARD_DELAY1(0x8F8)
        ),
        #0, # icon banner offset
        struct.unpack(
            '<I', buf[AK2I_HEADER_OFFSET + 0x68:AK2I_HEADER_OFFSET + 0x68 + 4])
        [0],
        #0, # low: secure area crc, high: secure transfer timeout
        (0x0D7E << 16) | secure_crc,
    ]

    firm_sections = firm[0x200:]

    header = (buf[AK2I_HEADER_OFFSET:AK2I_HEADER_OFFSET + 0x60] +
              int_list_to_buf(flags) +
              buf[AK2I_HEADER_OFFSET + 0x70:AK2I_HEADER_OFFSET + 0x15E])
    header += struct.pack('<H', CRC16(modbus_flag=True).calculate(header))

    buf = buf_to_int_list(
        buf[:AK2I_BLOWFISH_OFFSET] + blowfish +
        buf[AK2I_BLOWFISH_OFFSET + 0x1048:AK2I_HEADER_OFFSET] + header +
        buf[AK2I_HEADER_OFFSET + 0x160:AK2I_1ST_BLOWFISH_OFFSET] + buf[:0x48] +
        buf[AK2I_1ST_BLOWFISH_OFFSET + 0x48:AK2I_2ND_BLOWFISH_OFFSET] +
        buf[0x48:0x48 + 0xBF0] +
        buf[AK2I_2ND_BLOWFISH_OFFSET + 0xBF0:AK2I_SEC_OFFSET] + secure +
        buf[AK2I_SEC_END_OFFSET:AK2I_DATA_OFFSET] + firm_sections +
        buf[AK2I_DATA_OFFSET + len(firm) - 0x200:])
    return int_list_to_buf(buf)
コード例 #4
0
ファイル: parsers.py プロジェクト: Smeedy/dsmr_parser
    def validate_checksum(telegram):
        """
        :param str telegram:
        :raises ParseError:
        :raises InvalidChecksumError:
        """

        # Extract the part for which the checksum applies.
        checksum_contents = re.search(r'\/.+\!', telegram, re.DOTALL)

        # Extract the hexadecimal checksum value itself.
        # The line ending '\r\n' for the checksum line can be ignored.
        checksum_hex = re.search(r'((?<=\!)[0-9A-Z]{4})+', telegram)

        if not checksum_contents:
            raise ParseContentError(
                'Failed to perform CRC validation because the telegram is '
                'incomplete: The content value is missing.')
        elif checksum_contents and not checksum_hex:
            raise NoChecksumError(
                'Failed to perform CRC validation because the telegram is '
                'incomplete: The CRC is missing.')

        calculated_crc = CRC16().calculate(checksum_contents.group(0))
        expected_crc = int(checksum_hex.group(0), base=16)

        if calculated_crc != expected_crc:
            raise InvalidChecksumError(
                "Invalid telegram. The CRC checksum '{}' does not match the "
                "expected '{}'".format(calculated_crc, expected_crc))
コード例 #5
0
ファイル: receivePacket.py プロジェクト: Rotron/ip-minimodem
    def unpackData(self, inPacket):
        crcCalculator = CRC16()
        packetValid = False

        try:
            correctedPacket = self.rs.decode(inPacket)[0]
            packet = cobs.decode(correctedPacket)

            crc = crcCalculator.calculate(bytes(packet[:-2]))

            # Check CRC validity
            if ((crc & 0xFF00) >> 8) == packet[-2] and (crc
                                                        & 0xFF) == packet[-1]:
                packetValid = True
            # Get packet length
            packetLen = packet[6] << 8 | packet[7]

            # Origin callsign
            originCallsign = packet[0:6].decode('utf-8').strip()

            # Check for missing packets
            if packetValid:
                expectedSequenceId = (self.sequenceId + 1) & 0xFFFF
                packetSequenceId = packet[8] << 8 | packet[9]
                if expectedSequenceId != packetSequenceId:
                    self.packetLost += 1
                self.sequenceId = packetSequenceId
                payload = packet[10:-2]
                return (originCallsign, packetLen, packetSequenceId, payload)
        except Exception as e:
            #print('Decode error '+str(e)+'\n'+str(inPacket))
            return None
コード例 #6
0
ファイル: packet.py プロジェクト: Rotron/ip-minimodem
    def createPacket(self, data=b''):
        packet = bytearray()

        # Header (1 byte - added after padding)
        # Callsign (6 bytes)
        packet += self.callsign

        # Length (2 bytes)
        dataLen = len(data)
        packet += bytes([(dataLen & 0xFF00) >> 8, dataLen & 0xFF])

        # Sequence ID (2 bytes)
        packet += bytes([(self.sequenceId & 0xFF00) >> 8,
                         self.sequenceId & 0xFF])
        self.sequenceId = (self.sequenceId + 1) & 0xFFFF

        # payload (unknown length)
        packet += data

        # CRC and footer (CRC MSB, CRC LSB) (2 bytes)
        crcCalculator = CRC16()
        crc = crcCalculator.calculate(bytes(packet))
        packet += bytes([(crc & 0xFF00) >> 8, crc & 0xFF])

        cobs_packet = cobs.encode(packet)
        encoded_packet = self.rs.encode(cobs_packet)
        return bytes([0]) + encoded_packet + bytes([0])
コード例 #7
0
    def validate_telegram_checksum(line_values):
        """
        :type line_values: list
        :raises ParseError:
        :raises InvalidChecksumError:
        """

        full_telegram = ''.join(line_values)

        # Extract the bytes that count towards the checksum.
        checksum_contents = re.search(r'\/.+\!', full_telegram, re.DOTALL)

        # Extract the hexadecimal checksum value itself.
        checksum_hex = re.search(r'((?<=\!)[0-9A-Z]{4}(?=\r\n))+',
                                 full_telegram)

        if not checksum_contents or not checksum_hex:
            raise ParseError(
                'Failed to perform CRC validation because the telegram is '
                'incomplete. The checksum and/or content values are missing.')

        calculated_crc = CRC16().calculate(checksum_contents.group(0))
        expected_crc = checksum_hex.group(0)
        expected_crc = int(expected_crc, base=16)

        if calculated_crc != expected_crc:
            raise InvalidChecksumError(
                "Invalid telegram. The CRC checksum '{}' does not match the "
                "expected '{}'".format(calculated_crc, expected_crc))
コード例 #8
0
    def saveP(self):

        atual, lenatual = self.com.getData(16)

        self.tipo = atual[1]
        self.np = atual[2:6]
        #print("Numero atual do pack"+str(int.from_bytes(self.np,byteorder='little')))
        TamPack = atual[10:14]

        TamPack = int.from_bytes(TamPack, byteorder='little')

        self.crc = atual[14:]
        self.crc = int.from_bytes(self.crc, byteorder='little')

        print("crc - client... {0}".format(self.crc))
        self.resto = TamPack % 128

        self.corpo, lencorpo = self.com.getData(132)
        payload = self.corpo[:128]
        self.Localcrc = CRC16().calculate(payload)

        #self.Localcrc = int.from_bytes(Localcrc,byteorder='little')
        print("Local-crc-inicial... {0}".format(self.Localcrc))

        self.find = self.corpo.find(self.EoP)
コード例 #9
0
ファイル: crc.py プロジェクト: wwkkww1983/pythonwork
def __crc16_check(check_list):
    """
    CRC校验
    :param check_list: 待校验的列表
    :return:CRC校验值 2*8位 (list)
    """
    check_byte = b''
    check_len = len(check_list)

    # 将列表中的值提取出来组成一串新的位串
    for i in range(check_len):
        temporary_var = check_list[i]
        # 转换成相同的字符串即'0x11'
        temporary_var = hex(temporary_var)
        # 截取掉'0x'
        temporary_var = "{:0>2s}".format(temporary_var[2:])
        temporary_var = binascii.a2b_hex(temporary_var)
        check_byte += temporary_var

    # 调用CRC16校验库函数进行校验
    check_num = hex(CRC16(modbus_flag=True).calculate(check_byte))
    check_num_list = []
    check_num = "{:0>4s}".format(check_num[2:])
    check_num_list.append(int(check_num[0:2], 16))
    check_num_list.append(int(check_num[2:4], 16))

    return check_num_list
コード例 #10
0
ファイル: packer.py プロジェクト: gabrielztk/Camadas2019.2
 def __init__(self):
     
     self.payload = []
     self.header = Header()
     self.eop = EOP()
     self.stuffing = Stuffing()
     self.crc = CRC16()
コード例 #11
0
    def validate_checksum(telegram):
        """
        :param str telegram:
        :raises ParseError:
        :raises InvalidChecksumError:
        """

        # Extract the part for which the checksum applies.
        checksum_contents = re.search(r'\/.+\!', telegram, re.DOTALL)

        # Extract the hexadecimal checksum value itself.
        # The line ending '\r\n' for the checksum line can be ignored.
        checksum_hex = re.search(r'((?<=\!)[0-9A-Z]{4})+', telegram)

        if not checksum_contents or not checksum_hex:
            raise ParseError(
                'Failed to perform CRC validation because the telegram is '
                'incomplete. The checksum and/or content values are missing.')

        calculated_crc = CRC16().calculate(checksum_contents.group(0))
        expected_crc = int(checksum_hex.group(0), base=16)
        calculated_crc_hex = '{:0>4}'.format(hex(calculated_crc)[2:].upper())
        expected_crc_hex = '{:0>4}'.format(hex(expected_crc)[2:].upper())

        if calculated_crc != expected_crc:
            raise InvalidChecksumError(
                "Invalid telegram CRC. The calculated checksum '{}' ({}) does not match the "
                "telegram checksum '{}' ({})".format(calculated_crc,
                                                     calculated_crc_hex,
                                                     expected_crc,
                                                     expected_crc_hex))
コード例 #12
0
ファイル: pyUI.py プロジェクト: itada1997/pyUI
    def checkValidData(self, client, userdata, message):
        try:
            array_message = ""
            array_message = str(message.payload.decode())
            if len(array_message) != 41:
                raise Exception

            self.__crcChecksum = int(array_message[-5:])
            self.__crcChecksum_new = CRC16().calculate(str(array_message[:-5]))
            print(self.__crcChecksum_new)
            if (self.__crcChecksum_new != self.__crcChecksum):
                raise Exception
            self.__idMachine_mgs = int(array_message[1:11])
            if (self.__idMachine_mgs != self.idMachine):
                raise Exception
            self.__amoutOfProducts_mgs = int(array_message[31:36])
            if (self.amoutOfProducts == self.__amoutOfProducts_mgs):
                raise Exception
            self.__idhr_mgs = int(array_message[11:21])
            self.__wls_mgs = int(array_message[21:31])
            #print(" CheckValidData: OK")
            #print("ID: %d\nIDHR: %d\nWls: %d" %
            #(self.__idMachine_mgs,self.__idhr_mgs, self.__wls_mgs))
            self.amoutOfProducts = self.__amoutOfProducts_mgs
            self.countTimeDown = 0
            self.onConnect = True
            qty.e
            self.insertIntoMySQL()
        except Exception:
            #print("error")
            pass
            #print(" CheckValidData: FAILED ID:%d GROUP:%d LINE:%s"
            #      %(self.idMachine, self.group, self.line))
        except:
            pass
コード例 #13
0
def node_crc(arg1, arg2, arg3):
    data = serial.to_bytes([arg1, arg2, arg3])
    crc_result = CRC16().calculate(data)
    status = crc_result
    lowbyte = status & 0xff
    highbyte = (status & 0xff00) >> 8
    data = serial.to_bytes([arg1, arg2, arg3, lowbyte, highbyte, 0x0A])
    ser.write(data)
コード例 #14
0
def check_crc(response):
    crcbytes = map(ord, response[-2:])
    resp = response[0:-2]
    crc = hex_to_hexarr(CRC16(True).calculate(resp))

    if crc == crcbytes:
        return True
    return False
コード例 #15
0
def prepare_command(net_number, code):
    request = ['0']
    x = string_to_list(net_number)  # '266608'
    next = request + x + [code]  # '28'
    lst = map(lambda x: int(x, 16), next)
    arr = array.array('B', lst).tostring()
    crc = CRC16(True).calculate(arr)
    return lst + hex_to_hexarr(crc)
コード例 #16
0
ファイル: enlaceRx.py プロジェクト: manucirne/camadaFcomp
def CRCrecebe(data: bytes):
    '''
    CRC-16-ModBus Algorithm
    '''
    resto = CRC16().calculate(data)
    # print("Resto no CRC (calculado):       ", resto)

    return resto
コード例 #17
0
 def verify_crc(self):
     # Get received CRC from last last of telegram
     crc_received = self.telegram[len(self.telegram)-1][1:]  # Remove EOT_CHAR from received CRC
     # Compute CRC from received data
     crc = "0x{:04x}".format(CRC16().calculate(self.crc_data+'!'))
     crc = crc[2:].upper()
     # Return verified CRC
     return crc == crc_received
コード例 #18
0
ファイル: server.py プロジェクト: liuqun/my_pyqt5_project
    def handle(self):

        crc16calc = CRC16(modbus_flag=True)
        recv_buf = bytearray(DEFAULT_PACKET_LEN)

        n = 0
        while True:
            view = memoryview(recv_buf)[n:]
            while n < DEFAULT_PACKET_LEN:
                tmp = self.request.recv_into(view)
                if tmp <= 0:
                    print('Warning: Client has shutdown the connection!')
                    return
                n += tmp
                view = view[tmp:]

            pkt = first_match_from_buf(recv_buf)
            n = len(pkt)
            if 0 == n:
                continue
            if 0 < n < DEFAULT_PACKET_LEN:
                recv_buf[:n] = pkt  # 数据包不完整(有头无尾), 需将包头回写进收缓冲区
                continue
            n = 0 if DEFAULT_PACKET_LEN == n else n - DEFAULT_PACKET_LEN
            # # TODO: 假如遇到超长的数据包,需要将超长部分回写进收缓冲区
            # if n > len(recv_buf):  # This should NEVER happen!
            #     n = 0
            #     continue
            # elif 0 < n <= DEFAULT_PACKET_LEN:
            #     recv_buf[:n] = pkt[DEFAULT_PACKET_LEN:DEFAULT_PACKET_LEN + n]

            # 拆包
            src_dev_addr, cmd, cnt, raw_data, crc_checksum = \
                struct.unpack('>HbH12sH', pkt[2:DEFAULT_PACKET_LEN - 2])  # 不需要解析起始/终止符

            # 计算并对比 CRC16 校验和是否一致
            crc = crc16calc.calculate(pkt[:DEFAULT_PACKET_LEN - 4])
            if crc != crc_checksum:
                print('Checksum error:',
                      'Received {:04X},'.format(crc_checksum),
                      'but should be {:04X}.'.format(crc))
                continue

            if self.debug:
                # 调试信息
                client_ip_addr, client_port = self.request.getpeername()
                print('Client ip={}, port={}, device_id={:04X}'.format(
                    client_ip_addr, client_port, src_dev_addr))
                hex_str = hexlify(pkt).decode('ascii').upper()
                formatted_str = ' '.join([
                    hex_str[i:i + 2] for i in range(0, len(hex_str), 2)
                ])  # 添加空格便于阅读
                print(formatted_str)
            if self.debug_send_back:
                # Just send back the same data
                self.request.sendall(pkt)
コード例 #19
0
	def send_file(self, file_path):
		if self.socket.isValid() and self.socket.state() == QtNetwork.QAbstractSocket.ConnectedState:
			file_content = None
			with open(file_path, mode='rb') as file:
			    file_content = file.read()
			crc16 = hex(CRC16().calculate(file_content))[2:].upper()
			self.send_packet('I', False, len(file_content), '0', '0', GET_DATE(), GET_TIME(), 'dt.jpg', crc16)
			self.socket.write(file_content)
		else:
			self.log('Failed to send file. Socket state is {}'.format(self.socket.state()))
コード例 #20
0
    def checkCrc(self):
        """
        Checks if message is correct
        """

        crc = CRC16().calculate(bytes(self.payload))
        if crc != 0:
            self.log("[ERROR] Wrong CRC.", "server")
            self.sendType6()
            return
コード例 #21
0
	def send_packet(self, packet_type, calc_crc, *args):
		if self.socket.isValid() and self.socket.state() == QtNetwork.QAbstractSocket.ConnectedState:
			packet_header = '#' + packet_type + '#'
			packet_body = ';'.join('NA' if not arg else str(arg) for arg in args)
			if calc_crc:
				packet_body = packet_body + ';'
				crc16 = CRC16().calculate(packet_body.encode())
				packet_body = packet_body + hex(crc16)[2:].upper()
			packet = packet_header + packet_body + '\r\n'
			self.log(packet)
			self.socket.write(packet.encode())
		else:
			self.log('Failed to send packet. Socket state is {}'.format(self.socket.state()))
コード例 #22
0
ファイル: com_monitor.py プロジェクト: LRTME/Martin_SAPF
    def handle_packet(self, data):
        self._object_ref.bytes_received = self._object_ref.bytes_received + len(
            data) + 1
        try:
            decoded_packet = cobs.decode(data)
        except:
            self._object_ref.decode_error_count = self._object_ref.decode_error_count + 1
        else:
            # ce pa dobim korekten podatek, pogledam po seznamu handlerjev in klicem ustrezen callback
            length_of_packet = len(decoded_packet)
            # potegnem ven kodo
            code = decoded_packet[0:2]
            # in podatke
            packet_data = decoded_packet[2:length_of_packet - 2]

            code_and_data = decoded_packet[0:length_of_packet - 2]
            # in na koncu se CRC
            crc_received = int.from_bytes(decoded_packet[length_of_packet -
                                                         2:length_of_packet],
                                          byteorder='little')

            # sedaj naredim se CRC nad podatki in ukazom
            crc_of_data = CRC16(True).calculate(bytes(code_and_data))

            # ce sta CRC-ja enaka, potem nadaljujem, sicer pa kar odneham
            if crc_of_data == crc_received:
                # uspesno prejet paket
                self._object_ref.packets_received = self._object_ref.packets_received + 1
                # handlerji po novo
                try:
                    index = self._object_ref.rx_code_list.index(code)
                    callback = self._object_ref.rx_handler_list[index]
                    # poklicem handler
                    if packet_data == None:
                        callback.rx_handler()
                    else:
                        callback.rx_handler(packet_data)
                except:
                    self._object_ref.non_registered_packets_received = self._object_ref.non_registered_packets_received + 1
                    pass

            else:
                # povecam stevec CRC napak
                self._object_ref.crc_error_count = self._object_ref.crc_error_count + 1
                # ce je CRC handler registriran potem
                if self._object_ref.crc_handler_function != False:
                    # dam stevec na vrsto
                    self._object_ref.crc_data.put(
                        self._object_ref.crc_error_count)
                    # in preko signala klicem sistem
                    self._object_ref.crc_print_signal.emit()
コード例 #23
0
ファイル: Client.py プロジェクト: VFermat/CamadaFisica
    def sendFile(self):
        """
        Sends the file to the server using a TYPE 3 message.
        """

        while self.currentPacket <= self.numberOfPackets:
            # Slicing the file to create the payload
            self.payload = self.fileBA[(self.currentPacket - 1) *
                                       126:self.currentPacket * 126]

            # Calculate and add crc to the payload
            crc = CRC16().calculate(bytes(self.payload))
            self.payload = self.payload + crc.to_bytes(2, "little")

            # Building the header
            self.buildHead()

            # Assemble the packet.
            self.packet = self.head + self.payload + self.eop

            startTime = time.time()
            self.receivedResponse = False
            while not self.receivedResponse:
                # Send the data.
                self.com.sendData(self.packet)

                # Wait for the data to be sent.
                while (self.com.tx.getIsBussy()):
                    pass

                self.log(
                    f"Sent TYPE3. Packet {self.currentPacket}/{self.numberOfPackets}.",
                    "client")

                # Wait for response
                self.log(f"Waiting for TYPE4.", "client")
                self.response, self.responseSize = self.com.getData(
                    16 + 0 + len(self.eop), 5)

                if self.responseSize != 0:
                    self.parseResponse()
                    self.receivedResponse = True

                # Get current timer
                now = time.time()

                # Checking if we had a timeout
                if now - startTime >= 20:
                    self.sendType5(self.currentPacket, self.numberOfPackets)
                    self.com.disable()
                    exit()
コード例 #24
0
def check_crc_n7(rcv):
    rez = bytearray(rcv)
    crc16 = CRC16(modbus_flag=True).calculate(rcv[0:5])
    if len(rez) == 7:
        crc = rez[6] * 256 + rez[5]
        if crc == crc16:
            res = 256 * rez[3] + rez[4]
            if res > 1600:
                return TEMPERATURE_ERROR_MSG
            else:
                return res
        else:
            return CRC_ERROR_MSG
    else:
        return PKG_SIZE_ERROR_MSG
コード例 #25
0
def write_SV(sv):
    req_save_SV[4] = int(sv) // 256
    req_save_SV[5] = int(sv) % 256
    crc16 = CRC16(modbus_flag=True).calculate(str(req_save_SV[0:6]))
    req_save_SV[6] = crc16 % 256
    req_save_SV[7] = crc16 // 256

    print "try to write_SV ", sv
    rcv = open_port_and_read(req_save_SV, 8)
    if rcv == False:
        return PORT_ERROR_MSG
    else:
        rez = bytearray(rcv)
        if rez != req_save_SV:
            #print "Error send SV = ", sv
            return False
    return True
コード例 #26
0
def write_max_output_value(sv):
    req_save_MV[4] = int(sv) // 256
    req_save_MV[5] = int(sv) % 256
    crc16 = CRC16(modbus_flag=True).calculate(str(req_save_MV[0:6]))
    req_save_MV[6] = crc16 % 256
    req_save_MV[7] = crc16 // 256

    print "try to write_output_power MV ", sv
    rcv = open_port_and_read(req_save_MV, 8)
    if rcv == False:
        return PORT_ERROR_MSG

    rez = bytearray(rcv)
    if rez == req_save_MV:
        return True
    else:
        #print "Error send MV = ", sv
        return False
コード例 #27
0
def crc(input_date):
    """

    :param input_date:
    :return:
    """
    crc_tool = CRC16(modbus_flag=True)
    try:
        data_b = bytes.fromhex(input_date)
    except (ValueError, TypeError):
        print('参数错误')
    except Exception:
        print(' ')
    else:
        crc_code = crc_tool.calculate(data_b)
        crc_high = hex(crc_code >> 8)[2:]
        crc_low = hex(crc_code & 0x00ff)[2:]
        result = input_date + ' ' + crc_low + ' ' + crc_high
        return result.upper()
コード例 #28
0
    def checkPackage(self, messageType3, payloadSize):
        if self.checkEopPayload(messageType3, payloadSize):
            crcCaculated = CRC16().calculate(bytes(messageType3[:payloadSize]))
            if crcCaculated == self.crcReceived:
                self.packagesReceived.append(messageType3[:payloadSize])
                self.setMessageType(4)
                self.messageType4()
                print("")
                print("CRC CORRETO.")
                print("===========================================")
                print("Mensagem tipo 4 enviada.")
                print("===========================================")
                print("")
                self.counter += 1

        else:
            self.setMessageType(6)
            self.messageType6()
            print("Mensagem tipo 6 enviada.")
コード例 #29
0
    def type3(data, total_of_packages, data_stuffed, max_package_size,
              current_package):

        type_msg = 3
        server_id = 1

        #while current_package <= total_of_packages:
        payload = data_stuffed[max_package_size *
                               (current_package - 1):max_package_size *
                               (current_package)]
        payload = bytes(payload)

        crc = CRC16().calculate(payload)

        head_payload = head(payload, total_of_packages, current_package,
                            type_msg, server_id, crc)

        package = add_eop(head_payload)

        com.sendData(package)
コード例 #30
0
ファイル: com_monitor.py プロジェクト: LRTME/Martin_SAPF
 def send_packet(self, code, data):
     if data is None:
         packet_out = (struct.pack('<h', code))
     else:
         packet_out = (struct.pack('<h', code)) + data
     # ce je port odprt
     if self.ser.isOpen() == True:
         # pripravim za posiljanje
         crc_of_data = CRC16(True).calculate(bytes(packet_out))
         crc_of_data_bytes = struct.pack("<H", crc_of_data)
         packet_array = bytearray(packet_out)
         packet_array.append(crc_of_data_bytes[0])
         packet_array.append(crc_of_data_bytes[1])
         # zakodiram
         cobs_encoded = cobs.encode(bytes(packet_array))
         # dodam se 0x00 za konec paketa
         cobs_encoded.append(0)
         # posljem, tx_threadu
         self.tx_queue.put(cobs_encoded)
         pass