Пример #1
0
def test_valid_data(data):
    """Test the incoming data for validity."""
    # pylint: disable=too-many-return-statements
    if data is None:
        return False

    if len(data) > 302 or len(data) < 180:
        _LOGGER.debug("Invalid packet size %s", len(data))
        return False

    if not data[0] and data[-1] == FRAME_FLAG:
        _LOGGER.debug(
            "%s Received %s bytes of %s data",
            datetime.now().isoformat(),
            len(data),
            False,
        )
        return False

    header_checksum = CrcX25.calc(bytes(data[1:6]))
    read_header_checksum = data[7] << 8 | data[6]

    if header_checksum != read_header_checksum:
        _LOGGER.debug("Invalid header CRC check")
        return False

    frame_checksum = CrcX25.calc(bytes(data[1:-3]))
    read_frame_checksum = data[-2] << 8 | data[-3]

    if frame_checksum != read_frame_checksum:
        _LOGGER.debug("Invalid frame CRC check")
        return False

    if data[8:12] != DATA_FLAG:
        _LOGGER.debug("Data does not start with %s: %s", DATA_FLAG,
                      data[8:12])
        return False

    packet_size = len(data)
    read_packet_size = ((data[1] & 0x0F) << 8 | data[2]) + 2

    if packet_size != read_packet_size:
        _LOGGER.debug(
            "Packet size does not match read packet size: %s : %s",
            packet_size,
            read_packet_size,
        )
        return False

    return True
    def test_valid_data(self, data):
        """Test the incoming data for validity."""
        # pylint: disable=too-many-return-statements
        self.valid_data = True
        if len(data) > 302 or len(data) < 180:
            _LOGGER.warning('Invalid packet size %s', len(data))
            self.valid_data = False
            return self.valid_data

        if not data[0] and data[-1] == FRAME_FLAG:
            _LOGGER.warning("%s Recieved %s bytes of %s data",
                            datetime.datetime.now().isoformat(), len(data),
                            False)
            self.valid_data = False
            return self.valid_data

        header_checksum = CrcX25.calc(bytes(data[1:6]))
        read_header_checksum = (data[7] << 8 | data[6])

        if header_checksum != read_header_checksum:
            _LOGGER.warning('Invalid header CRC check')
            self.valid_data = False
            return self.valid_data

        frame_checksum = CrcX25.calc(bytes(data[1:-3]))
        read_frame_checksum = (data[-2] << 8 | data[-3])

        if frame_checksum != read_frame_checksum:
            _LOGGER.warning('Invalid frame CRC check')
            self.valid_data = False
            return self.valid_data

        if data[8:12] != DATA_FLAG:
            _LOGGER.warning('Data does not start with %s: %s', DATA_FLAG,
                            data[8:12])
            self.valid_data = False
            return self.valid_data

        packet_size = len(data)
        read_packet_size = ((data[1] & 0x0F) << 8 | data[2]) + 2

        if packet_size != read_packet_size:
            _LOGGER.warning(
                'Packet size does not match read packet size: %s : %s',
                packet_size, read_packet_size)
            self.valid_data = False
            return self.valid_data
        return self.valid_data
Пример #3
0
 def test_data(self, data):
     # Preform Crc x25 check on data.
     x = bytearray.fromhex(data[0])
     y = CrcX25.calchex(data=x, byteorder="little")
     if str.upper(y) == data[1]:
         logger.debug("%s Recieved %s bytes of true data" %
                      (datetime.datetime.now().isoformat(), len(data[0])))
         return True
     logger.warning("%s Recieved %s bytes of false data" %
                    (datetime.datetime.now().isoformat(), len(data[0])))
     return False
Пример #4
0
def convert_install_code(code):
    if len(code) not in (8, 10, 14, 18):
        return None

    real_crc = bytes(code[-2:])
    crc = CrcX25()
    crc.process(code[:-2])
    if real_crc != crc.finalbytes(byteorder="little"):
        return None

    return aes_mmo_hash(code)
Пример #5
0
def convert_install_code(code):
    if len(code) < 8:
        return None

    real_crc = bytes([code[-1], code[-2]])
    crc = CrcX25()
    crc.process(code[:len(code) - 2])
    if real_crc != crc.finalbytes():
        return None

    return aes_mmo_hash(code)
Пример #6
0
    def is_ax5043_crc_valid(self, rx_radio_packet):
        if (rx_radio_packet == b'') or (rx_radio_packet is None):
            return False

        received_crc = rx_radio_packet[-2:]
        crc = CrcX25.calc(rx_radio_packet[:-2])
        if crc == int.from_bytes(received_crc,
                                 byteorder='little',
                                 signed=False):
            return True
        else:
            return False
Пример #7
0
def _crc(bytes_in: bytes) -> bytes:
    """
    Generate an X.25_ checksum for the specified byte sequence.

    ..  _X.25:
        https://en.wikipedia.org/wiki/X.25

    :param bytes_in:
        the bytes to generate the checksum for.

    :return:
        a two-byte :class:`bytes` sequence in the order expected by the display.
    """
    return struct.pack('<H', CrcX25.calc(bytes_in))
Пример #8
0
    def run(self):
        while(1):
            # Listen to ZMQ Port to get CSP PAcket Data
            self.tx_buffer = self.subscriber.recv()
            self.tx_buffer = (len(self.tx_buffer) + 1).to_bytes(1, 'big') + self.tx_buffer
            # Compute CheckSum
            crc = CrcX25.calc(self.tx_buffer)
            crc_b1 = bytes([0x00FF & crc])
            crc_b2 = bytes([(0xFF00 & crc) >> 8])
            self.tx_buffer += crc_b1 + crc_b2

            print("\033[0;36m["+datetime.utcnow().isoformat()+"+UTC]","[send_csp_frame]\033[0m", "Sending {} bytes of data: {}".format(len(self.tx_buffer), self.tx_buffer.hex()))
            self.transmit_preamble()
            self.transmit_asm()
            self.transmit_packet()
            self.transmit_postamble()
            self.transmit_frame()
Пример #9
0
 def __init__(self, crc_secret=DEFAULT_CRC_SECRET):
     self.crc_secret = crc_secret.encode('ascii')
     self.protocol = Struct(
         "start" / OneOf(Bytes(2), [b"\x78\x78", b"\x79\x79"]),
         "fields" / RawCopy(
             Struct(
                 "length" /
                 IfThenElse(this._.start == b"\x78\x78", Int8ub, Int16ub),
                 "protocol" / Enum(Byte,
                                   login=0x01,
                                   heartbeat=0x23,
                                   response=0x21,
                                   location=0x32,
                                   alarm=0x33,
                                   command=0x80,
                                   information=0x98,
                                   metrics=0xFD,
                                   default=Pass),
                 "data" / Switch(this.protocol, {
                     "login": self.login,
                     "heartbeat": self.heartbeat,
                     "response": self.response,
                     "location": self.location,
                     "alarm": self.location,
                     "information": self.information,
                     "metrics": self.metrics,
                 },
                                 default=Bytes(this.length - 1 - 2 - 2)),
                 "serial" / Int16ub,
             )),
         "crc" / Checksum(
             BytesInteger(2), lambda data: CrcX25.calc(data),
             lambda ctx: ctx.fields.data + self.crc_secret
             if ctx.fields.value.protocol == 'login' else ctx.fields.data),
         #"crc" / BytesInteger(2),
         "end" / Const(b"\x0d\x0a"))
Пример #10
0
 def test_login_response_packet(self):
     # 0C 01 11 03 14 08 38 39 00 00 39 # 95 70
     packet = b'\x0C\x01\x11\x03\x14\x08\x38\x39\x00\x00\x39'  # \x95\x70
     self.assertEqual(CrcX25.calc(packet), 38256)
 def calculate_checksum(data):
     data = bytearray.fromhex(
         data[4:-8]
     )  # Returns a new bytearray object initialized from a string of hex numbers.
     crc = hex(CrcX25.calc(data))
     return crc
Пример #12
0
def crc(input):
    crcinst = CrcX25()
    crcinst.process(input)
    return crcinst.final().to_bytes(2, byteorder='little', signed=False)
Пример #13
0
from crccheck.crc import CrcX25

data = bytearray([0x04, 0x00, 0x02, 0x00, 0xff, 0xff])
x25_crc = str(hex(CrcX25.calc(data)))[2:].upper()
if len(x25_crc) < 4:
    x25_crc = (4 - len(x25_crc)) * '0' + x25_crc
x25_crc = x25_crc[2:4] + x25_crc[0:2]
print(x25_crc)
Пример #14
0
 def calculate_checksum(data):
     from crccheck.crc import CrcX25
     data = bytearray.fromhex(data[4:-8])
     crc = hex(CrcX25.calc(data))
     return crc
Пример #15
0
 def test_login_packet_with_weird_secret(self):
     # 11 01 08 68 12 01 48 37 35 71 36 05 32 02 00 39 # DE F7
     packet = b'\x11\x01\x08\x68\x12\x01\x48\x37\x35\x71\x36\x05\x32\x02\x00\x39'
     secret = b'xinsiwei&concox'
     packet = packet + secret
     self.assertEqual(CrcX25.calc(packet), 57079)
Пример #16
0
 def test_crc16(self):
     data = b'\x05\x01\x00\x03'
     self.assertEqual(CrcX25.calc(data), 0xface)
    def handle(self):
        def calculate_checksum(data):
            data = bytearray.fromhex(
                data[4:-8]
            )  # Returns a new bytearray object initialized from a string of hex numbers.
            crc = hex(CrcX25.calc(data))
            return crc

        history_data_update_flag = False
        inc = 1

        time_start_count = time.time()

        history_data_update_flag = False
        inc = 1

        time_start_count = time.time()
        dev_ip_ = {}

        while (True):

            # self.request.settimeout(1)

            # print('{} - Incoming connection from {}'.format(time.strftime('%d.%m.%Y %H:%M:%S', time.localtime()),
            #                                                 self.client_address))

            thread = current_thread()
            # print("\n")
            # Print device ip
            client_address = self.client_address[0]
            # print("{} wrote: ".format(self.client_address[0]))
            # print("Current Thread: %s " % thread)

            # ETS 300 or BW09 Data Format
            # data_new= "78780d0108680030311961450010e2b90d0a" #Login msg
            # data_new= "78780a130401040002001176820d0a"#Status Msg
            # data_new = "78782112130b0d111a26c7028d068e09b1ea2c0014b101d6005222002760000000d67abd0d0a"
            # client_address='182.143.112.234'

            # self.request.send(response_hex)
            # print("Response send for energy meter device-DZS100-1P: ", str(response))

            data = self.request.recv(76)

            # data_hex= data.hex();
            # Python2
            # data_new = codecs.encode(data,"hex_codec");
            # print(data_new)

            # Python3
            data_new = data.hex()
            # data_new = data.decode()
            # print(data_new)
            # print("Response from GPS Tracker:", data_new)
            if data_new == "":
                time.sleep(3)

            # print(type(data_new))
            # print(len(data_new))

            if len(data_new) > 10:
                data_chk = data_new.split("0d0a")[0] + "0d0a"
                chk = calculate_checksum(data_chk)

                # if chk[2:] == data_chk[-8:-4]:
                #     print("Checksum is okay")

                if data_new[0:4] == "7878" and data_new[-4:].lower() == "0d0a":
                    # print("Message is from ET-300 or BW09")
                    if data_new[6:8] == "01":
                        # print("Login Message is from ET-300 or BW09")
                        start_bit = data_new[0:4]
                        packet_length = data_new[4:6]
                        protocol_no = data_new[6:8]

                        # print(protocol_no)
                        terminal_id = data_new[8:24]
                        equipment_id = terminal_id
                        serial_no = data_new[24:28]
                        error_chk = data_new[28:32]
                        stop_bit = data_new[32:36]

                        equip_serial = {equipment_id: serial_no}
                        # print(equip_serial)
                        error_chk = calculate_checksum(data_new)
                        # Checking checksum

                        inter_data = "0501" + serial_no
                        response_pkt = start_bit + "0501" + serial_no + error_chk[
                            2:] + stop_bit
                        response_pkt = response_pkt.lower()
                        data = bytearray.fromhex(inter_data)
                        crc = hex(CrcX25.calc(data))
                        response_pkt = start_bit + inter_data + crc[
                            2:] + stop_bit
                        # print(response_pkt)
                        # response_pkt = "0x780x780x050x010x000x010xD90xDC0x0D0x0A"
                        # For Python2
                        # res_hex = codecs.decode(response_pkt, "hex_codec")
                        # print(res_hex)
                        # For Python3
                        res_hex = codecs.decode(response_pkt, "hex_codec")
                        # print(res_hex)

                        dev_ip_[equipment_id] = client_address
                        # print(dev_ip_)

                        self.request.send(res_hex)
                        # print("Response send for GPS Tracker: ", str(response_pkt))
                        time.sleep(5)
                    elif protocol_no == "13":
                        # print(protocol_no)
                        # print("Status(Heart-beat) packet from BW-09 or ET300")
                        # print("-----------------")
                        # print("Serial NO")

                        start_bit = "7878"
                        pakt_lenghth = "05"
                        protocol_no = "13"
                        serial_no = data_new[-12:-8]
                        # print(serial_no)
                        # print("-----------------")

                        for item in equip_serial:
                            # print(item, equip_serial[item])
                            if int(equip_serial[item],
                                   16) == int(serial_no, 16) - 1:
                                equip_serial[item] = serial_no
                                # print("####################")
                                # print("Serial Increment")
                                # print("####################")

                        error_control = calculate_checksum(data_new)
                        error_control = error_control[2:]
                        stop_bit = "0d0a"
                        response_pkt = start_bit + pakt_lenghth + protocol_no + serial_no + error_control + stop_bit
                        # print(response_pkt)

                        self.request.send(response_pkt)
                        # print("Status Response send for GPS Tracker: ", str(response_pkt))

            for item in dev_ip_:
                # print(dev_ip_[item])

                if dev_ip_[item] == client_address:
                    equipment_id = item
                else:
                    equipment_id = ''
            # print("--------------------")
            # print(dev_ip_)
            # print("--------------------")

            # ----------------------------For BW21-----------------------
            if len(data) == 31 or len(data) == 30:
                # ata ="["
                data = data.split("*")[0] + "*" + data.split(
                    "*")[1] + "*" + "0002" + "*" + "LK]"
                # ata = data.split(",")[0] + ']'
                # ata =
                # print(data)
                if len(data) > 0:
                    self.request.send(data)
                    # print("Response send for BW GPS Tracker: ", str(data))

            # ---------------------------------------
            # Create an object for processing data(BW09 or BW906)
            new_object = Query()

            # Pass received data stream as an argument of function store_raw_date
            new_object.store_raw_date("RAW_DATA", data_new)
            # Pass received data stream as an argument of function device_data_process
            new_object.device_data_process(data_new, equipment_id,
                                           client_address)

            del new_object

            # ---------------------------------------
            # Create an object for processing data(BW21)
            new_object2 = Query2()

            # Pass received data stream as an argument of function device_data_process
            new_object2.device_data_process(data_new)

            del new_object2