Пример #1
0
def main(args):
    np.random.seed(0x1337)
    spi = spidev.SpiDev()
    spi.open(args.bus, args.device)
    spi.max_speed_hz = args.speed
    spi.bits_per_word = 16
    dt = np.dtype(np.uint16)
    dt = dt.newbyteorder('>')

    if args.send:
        data = np.array(
            [48713, 25935, 32857, 42796, 38931, 10992, 61444], dtype=np.uint16
        )  #np.random.randint(0, 0xffff, size=7, dtype=dt) #np.arange(1, 8, dtype=dt)
        print(data)
        crc = 0xffff if args.crcerr else crc16.crc16xmodem(data.tobytes())
        data = np.append(data, crc)
        data = data.astype(dt).tobytes()
        spi.writebytes(data)
        print(f"written {len(data)} bytes ({crc})")
    else:
        raw = bytes(spi.readbytes(16))
        msg = np.frombuffer(raw, dtype=dt)
        crc = crc16.crc16xmodem(raw[:-2])
        print(crc)

        if crc == msg[-1]:
            print(f"received {msg[:-1]} ({len(raw)} bytes) [OK]")
        else:
            print(f"crc error: {crc} != {msg[-1]} [FAIL]")

    spi.close()
Пример #2
0
def encodePacket(linenr, cmd, payload):

    assert (linenr > 0)
    assert (cmd > 0)

    result = nullByte

    header = struct.pack("<BBB", linenr, cmd, len(payload) + 0x01)

    result += header
    checksum = crc16.crc16xmodem(header)

    result += payload
    checksum = crc16.crc16xmodem(payload, checksum)

    # print "cflags, c1: 0x%x, 0x%x" % (cflags, checksum)
    cflags = 0x1
    if checksum == 0:
        cflags = 0x4
        checksum = 0x0101
    elif (checksum & 0xFF00) == 0:
        cflags = 0x2
        checksum = 0x0100 | (checksum & 0xFf)
    elif (checksum & 0x00FF) == 0:
        cflags = 0x3
        checksum = 0x0001 | (checksum & 0xFF00)

    # print "c1 adjusted: 0x%x" % checksum

    result += struct.pack("<BH", cflags, checksum)

    return result
Пример #3
0
def callbackmotor1(data):

	vel_1 = motormath(data.data)

	if vel_1 < 0: 
		vel_1_hex = hex((abs(vel_1) ^ 0xffffffff) +1)[2:].strip( 'L' )
	else:
		vel_1_hex = hex(vel_1)[2:].zfill(8)

	vel_1_hex_int = int(vel_1_hex,16)

	# Converts the velocity hex value into the little endien format and puts it into the
	# proper hex format and gets the CRC value
	vel_1_final = struct.pack('<q', vel_1_hex_int).encode('hex')[:8]

        chk_sum_data = hex(crc16.crc16xmodem(binascii.a2b_hex(vel_1_final))).strip('0x').zfill(4)
 		
	# Generates the word number value and calculates the CRC
	#cmd_word_count = "{0:0>2}".format(hex(int(math.floor(len(vel_1_final.rstrip('0'))/2))).strip( '0x' ))
	cmd_word_count = struct.pack('h', int(math.floor(len(vel_1_final.rstrip('0'))/2))).encode('hex')[:2]

	chk_sum_cmd = hex(crc16.crc16xmodem(vel_mode + binascii.a2b_hex(cmd_word_count))).strip('0x')	
	
	motor_command_1 = binascii.b2a_hex(vel_mode) + chk_sum_cmd + vel_1_final + chk_sum_data

	print "Motor 1 Command:"	
	print motor_command_1
Пример #4
0
def parse_tcp(packet_len, ip_packet, ts):
    source = socket.inet_ntoa(ip_packet['src'])  #server
    dest = socket.inet_ntoa(ip_packet['dst'])  #client
    global TIMEOUT
    global TABLE_SIZE

    key = dest + source
    if key in netassayTable:
        d = netassayTable[key]
        knownlistDict[d][1] = knownlistDict[d][1] + 1
        knownlistDict[d][2] = knownlistDict[d][2] + packet_len

        serverIP32 = np.uint32(
            int.from_bytes(socket.inet_aton(source), byteorder='big'))
        clientIP32 = np.uint32(
            int.from_bytes(socket.inet_aton(dest), byteorder='big'))
        salt1 = np.uint32(134140211)
        salt2 = np.uint32(187182238)

        hash1 = crc16.crc16xmodem(
            np.uint32(serverIP32 + clientIP32 + salt1)) % TABLE_SIZE
        hash2 = crc16.crc16xmodem(
            np.uint32(serverIP32 + clientIP32 + salt2)) % TABLE_SIZE

        if hash1 in usedHash1 and usedHash1[hash1][1] == key:
            usedHash1[hash1][0] = ts
        elif hash2 in usedHash2 and usedHash2[hash2][1] == key:
            usedHash2[hash2][0] = ts
        else:
            print("error in hash storage")
            exit(-1)
Пример #5
0
def calc_crc(data):
    assert len(data) >= 16

    crc = crc16xmodem(data[:4])
    crc = crc16xmodem(b"\0\0", crc)
    crc = crc16xmodem(data[6:], crc)
    return crc
Пример #6
0
    def __init__(self, numeroTramas, numeroTrama, BitsPorTrama, longitudCU,
                 cargaUtil):

        self.numeroTramas = self.aBinario(numeroTramas, 8)
        self.numeroTrama = self.aBinario(numeroTrama, 8)
        self.cargaUtil = cargaUtil
        self.longitudCU = self.aBinario(cargaUtil.size, longitudCU)
        self.bitsRelleno = BitsPorTrama - cargaUtil.size
        self.CRC = self.aBinario(crc16.crc16xmodem(self.cargaUtil), 16)

        f = open('tramas.txt', 'a')
        f.write(
            '\n\n*****************************************************************\n'
        )
        f.write('Tramas: ' + str(numeroTramas) + str(self.numeroTramas) +
                'Longitud:' + str(self.numeroTramas.size) + '\n')
        f.write('Numero de trama: ' + str(numeroTrama) +
                str(self.numeroTrama) + 'Longitud:' +
                str(self.numeroTrama.size) + '\n')
        f.write('Longitud carga util: ' + str(self.longitudCU.size) +
                str(self.longitudCU) + '\n')
        f.write('Carga util: ' + str(self.cargaUtil.size) +
                str(type(self.cargaUtil)) + str(type(self.cargaUtil[2])) +
                '\n')
        f.write(str(self.cargaUtil) + '\n')
        f.write('Relleno: ' + str(self.bitsRelleno) + '\n')
        f.write('CRC: ' + str(crc16.crc16xmodem(self.cargaUtil)) +
                str(self.CRC) + str(type(self.CRC)) + str(self.CRC.dtype) +
                '\n\n')
        f.close()
Пример #7
0
 def key_hash(self):
     crc = 0
     for key in self.keys:
         crc = crc16.crc16xmodem(key, crc)
         crc = crc16.crc16xmodem(chr(0), crc)
     self.dbg("key hash %04X" % crc)
     return "%04X" % crc
Пример #8
0
def encodePacket(linenr, cmd, payload):

    assert(linenr > 0)
    assert(cmd > 0)
    
    result = nullByte

    header = struct.pack("<BBB", linenr, cmd, len(payload)+0x01)

    result += header
    checksum = crc16.crc16xmodem(header)

    result += payload
    checksum = crc16.crc16xmodem(payload, checksum)

    # print "cflags, c1: 0x%x, 0x%x" % (cflags, checksum)
    cflags = 0x1
    if checksum == 0:
        cflags = 0x4
        checksum = 0x0101
    elif (checksum & 0xFF00) == 0:
        cflags = 0x2
        checksum = 0x0100 | (checksum & 0xFf)
    elif (checksum & 0x00FF) == 0:
        cflags = 0x3
        checksum = 0x0001 | (checksum & 0xFF00)

    # print "c1 adjusted: 0x%x" % checksum

    result += struct.pack("<BH", cflags, checksum)

    return result
Пример #9
0
 def crc(self):
     b = self.bytes()
     # CRC is cal
     s = self.bytes_to_hex(b[2:])
     print("crc", s)
     print("crc", crc16.crc16xmodem(s.decode("hex")),
           hex(crc16.crc16xmodem(s.decode("hex"))))
     return crc16.crc16xmodem(s.decode("hex"))
Пример #10
0
	def _construct_cmd(self, _function_byte, _mode, _function_cmd='\x00'):

		# create function byte
		commands_struct._frame['function'] = commands_struct._function_code[_function_byte][0]
		
		# command mode
		if _mode not in commands_struct._function_code[_function_byte][1]:
			print "_mode not in commands_struct._function_code[_function_byte][1]\n"
			return False

		# create byte_count
		commands_struct._frame['byte_count'] = commands_struct._function_code[_function_byte][1][_mode]

		# Bytes 1 - 6
		bytes_1to6 = commands_struct._frame['pcode'] + commands_struct._frame['status'] + \
			     commands_struct._frame['reserved'] + commands_struct._frame['function'] + \
			     commands_struct._frame['byte_count']
			    
		# calculate crc1
		# crc16.crc16xmodem() returns int
		_crc1 = crc16.crc16xmodem(bytes_1to6)
		(_x, _y) = self.crc_to_hex(_crc1) 
		commands_struct._frame['crc1'] = _x + _y

		# Data byte (payload)
		if _mode == 'set':
			commands_struct._frame['data'] = commands_struct._function_code[_function_byte][2][_function_cmd]

		# Bytes 1 - N
		bytes_1toN = commands_struct._frame['pcode'] + commands_struct._frame['status'] + \
 			    commands_struct._frame['reserved'] + commands_struct._frame['function'] + \
			    commands_struct._frame['byte_count'] + commands_struct._frame['crc1'] + \
			    commands_struct._frame['data']

		print "bytes_1toN: \n"
		for i in commands_struct._frame:
			print i + " : " + commands_struct._frame[i].encode('hex')
		print "\n"

		# calculate crc2
		_crc2 = crc16.crc16xmodem(bytes_1toN)
		(_x, _y) = self.crc_to_hex(_crc2) 
		commands_struct._frame['crc2'] = _x + _y

		# assemble command
		_cmd = commands_struct._frame['pcode'] + commands_struct._frame['status'] + \
		       commands_struct._frame['reserved'] + commands_struct._frame['function'] + \
		       commands_struct._frame['byte_count'] + commands_struct._frame['crc1'] + \
		       commands_struct._frame['data'] + commands_struct._frame['crc2']		

		# Debug
		print "Resp: " + commands_struct._function_code[_function_byte][1]['resp'].encode('hex')
		print "Resp Int: " + str(int(commands_struct._function_code[_function_byte][1]['resp'].encode('hex')))

		return (_cmd, 10 + int(commands_struct._function_code[_function_byte][1]['resp'].encode('hex'))) 
Пример #11
0
def ReceiveFile():
    seqno = 0
    ackno = 0
    expectedSeqNo = 0
    #try:
    #filepath = filename
    filesize, ClientAddress = serverSocket.recvfrom(2048)
    #print(filesize)
    filesize = int(filesize)

    ReceivedBytes = 0
    file = open('testfile', 'wb')  # create local file in cwd
    while True:
        message, ClientAddress = serverSocket.recvfrom(
            2048)  # get up to 1K at a time

        #s = struct.Struct(RUPHeaderFormat)
        pktHeader, data = splitPacket(message)
        #print(checkSum(message))
        if expectedSeqNo == pktHeader[0] and checkSum(message):
            ReceivedBytes = ReceivedBytes + len(data)
            #print("Data len : " + str(len(data)))
            #print("ReceivedBytes len : " + str(ReceivedBytes))

            file.write(data)  # write data in local file

            dat = ""
            header = makeHeader(
                0, pktHeader[0], 0, 0,
                crc16.crc16xmodem(
                    str(dat) + str(0) + str(pktHeader[0]) + str(0) + str(0)))
            #print ("Sending ack with " , pktHeader[0])

            pkt = makePacket(header, dat)
            BadNet.transmit(serverSocket, pkt, ClientAddress[0],
                            ClientAddress[1])
            #BadNet.transmit(pkt,ClientAddress)
            expectedSeqNo = expectedSeqNo + 1
            if ReceivedBytes == filesize:
                break  # till file received fully
        else:
            dat = ""
            header = makeHeader(
                0, expectedSeqNo - 1, 0, 0,
                crc16.crc16xmodem(
                    str(dat) + str(0) + str(pktHeader[0]) + str(0) + str(0)))
            #print ("Sending dup ack with " , expectedSeqNo-1)
            pkt = makePacket(header, dat)
            BadNet.transmit(serverSocket, pkt, ClientAddress[0],
                            ClientAddress[1])

    file.close()
    print 'File Received.'
    return 0
 def Gen(self):
     r = self.header2 + self.pck(self.number_of_records, 4) + self.some_junk
     k = ''
     for i in self.file_records:
         t = i.Gen()
         r += t[0]
         k += t[1]
     data = r + '\x00' * (self.header_padding_size - 2)
     self.crc16_header = crc16xmodem(data[:-2])
     data += self.pck(self.crc16_header, 2) + k
     return self.header1 + self.pck(crc16xmodem(data), 2) + data
Пример #13
0
def main():
    data = open(sys.argv[1], 'rb').read()
    crc = crc16.crc16xmodem(data)
    # print(crc)

    padded = data + bytes([crc >> 8, crc & 0xFF])

    crc = crc16.crc16xmodem(padded)
    # print(crc)

    open(sys.argv[1], 'wb').write(padded)
Пример #14
0
    def readResponse(self):

        s = self.readWithTimeout(1) # SOH
# xxx loop til 0x0 found
        assert(s == cobs.nullByte)

        rc = self.readWithTimeout(1) # read response code
        crc = crc16.crc16xmodem(rc)
        cmd = ord(rc)

        l = self.readWithTimeout(1) # read length byte
        crc = crc16.crc16xmodem(l, crc)

        length = ord(l) - 1
        self.gui.logRecv("Response 0x%x, reading %d b" % (cmd, length))

        payload = ""
        if length:
            payload = self.readWithTimeout(length) # read payload
            crc = crc16.crc16xmodem(payload, crc)

        (cflags, checkSum) = struct.unpack("<BH", self.readWithTimeout(3))

        if cflags == 0x2:
            checkSum -= 0x100;
        elif cflags == 0x3:
            checkSum -= 0x01;
        elif cflags == 0x4:
            checkSum -= 0x101;

        if checkSum != crc:
            print "RxChecksumError our: 0x%x, fw: 0x%x, payload: %s, cflags: 0x%x" % (crc, checkSum, (rc + l + payload).encode("hex"), cflags)
            """
            # Drain input
            try:
                s = self.read()
                print "RxChecksumError, drain input: %s" % s.encode("hex")
            except SerialException:
                pass

            while s:
                try:
                    s = self.read()
                    print "drain input: %s" % s.encode("hex")
                except SerialException:
                    pass
            """
            raise RxChecksumError()

        # Decode COBS encode payload
        payload = cobs.decodeCobs(payload)
        return (cmd, payload)
Пример #15
0
def account_from_secret(secret):
    """Returns account-id given the secret"""
    key = base64.b32decode(secret)
    checksum = struct.pack('H', crc16.crc16xmodem(key[0:-2]))
    keytype = binascii.a2b_hex(KEY_TYPES['seed'])
    if key[0] != keytype or key[-2:] != checksum:
        raise Exception('Invalid Secret Key')

    signing_key = ed25519.SigningKey(key[1:-2])
    payload = binascii.a2b_hex(
        KEY_TYPES['public']) + signing_key.get_verifying_key().to_bytes()
    checksum = crc16.crc16xmodem(payload)
    checksum = struct.pack('H', checksum)
    return base64.b32encode(payload + checksum)
Пример #16
0
def interpret_response (response, basic = False):
	"""
	Parse response from Aladdin pump.

	Returns a tuple (address, status, message)

	@param response: Message received. Should not include the 
	                 start / termination characters.
	@param basic: Parse in basic mode (no checksum).
	"""

	# Reject empty response
	if len(response) == 0:
		raise SyntaxError

	# Basic mode response in format:
	# <address, 2 chars><status, one char><message>
	if basic:
		address = int(response[0:2])
		status = response[2]
		msg = response[3:]

	# Safe mode response in format:
	# <address, 2 chars><status, one char><message><checksum, 2 chars>
	else:
		msg = response[:-2]
		crc = struct.unpack(">H", response[-2:])[0]

		# Check that the checksum is as expected
		if crc != crc16.crc16xmodem(msg):
			raise SyntaxError(
				"CRC does not match: %s, expected %s." % 
				(crc, crc16.crc16xmodem(msg))
			)

		address = int(msg[0:2])
		status = msg[2]
		msg = msg[3:]

	# Catch alarms
	if status == "A":
		raise Alarm(msg)

	# Catch errors
	if len(msg) > 0 and msg[0] == '?':
		raise CommandError(msg)

	return address, status, msg
Пример #17
0
    def from_upgrade_file(cls, file_or_bytes):
        """
        Factory method that creates a FirmwareFile from a FLIR Upgrade.bin.
        """

        bytes_in = cls._bytearray_from_file_or_bytes(file_or_bytes)

        source = io.BytesIO(bytes_in)
        target = io.BytesIO()

        for chunk in cls.__read_in_blocks(source, cls.UPGRADE_BIN_SIZE_WITH_METADATA):

            # Every data chunk starts with two bytes of CRC16, then
            # two bytes of padding. The remainder of a chunk is data.
            checksum = chunk[0:2]
            padding  = chunk[2:4]
            data     = chunk[4:]

            # Check to make sure our padding are always zeroes.
            if padding != b"\x00\x00":
                issue = repr(padding)
                raise IOError("Data format error! Expected 0x0000, got {}\n".format(issue))

            # Check to make sure the CRCs are valid.
            data_crc = crc16.crc16xmodem(data).to_bytes(2, byteorder='little')
            if checksum != data_crc:
                expected = repr(checksum)
                actual = repr(data_crc)
                raise IOError("CRC mismatch! Expected {}, got {}\n".format(expected, actual))

            # Copy the unpacked data into our target object.
            target.write(data)

        return FirmwareFile(target.getvalue())
    def __init__( self, messageType, session, payload=None ):
        MedtronicMessage.__init__( self, 0x05, session )

        # FIXME - make this not be hard coded
        seqNo = 0x80
        if messageType == 0x0403:
            seqNo = 2
        elif messageType == 0x0112:
            seqNo = 3
        elif messageType == 0x0115:
            seqNo = 4
        elif messageType == 0x0114:
            seqNo = 5
        elif messageType == 0x0200:
            seqNo = 6

        encryptedPayload = struct.pack( '>BH', seqNo, messageType )
        if payload:
            encryptedPayload += payload
        crc = crc16.crc16xmodem( encryptedPayload, 0xffff )
        encryptedPayload += struct.pack( '>H', crc & 0xffff )

        mmPayload = struct.pack( '<QBBB',
            self.session.pumpMAC,
            self.session.minimedSequenceNumber,
            0x10, # Unknown byte
            len( encryptedPayload )
        )
        mmPayload += self.encrypt( encryptedPayload )

        self.setPayload( mmPayload )
Пример #19
0
def processBuffer(buf, socket=None, channel=None, ser=None):
    bufTail = ""
    if len(buf) > 0:
#        print "Read %i bytes:" % (len(buf))
        pduPos = string.find(buf,cSSNSTART)
        currentPos = pduPos
        if ((pduPos >= 0) and (len(buf)-pduPos)>=14):
# process SSN PDU
#/* -- SSN serial protocol description -----------------------------------------
# *
# * Format: "===ssn1DDDDSSSSTTLLLL...CCCC"
# *
# * ===ssn1 - start packet (protocol version 1)
# * DDDD - destination object (2 byte: hex chars - 0-9, A-F)
# * SSSS - source object (2 byte: hex chars - 0-9, A-F)
# * TT - message type (1 byte: hex chars - 0-9, A-F)
# * LLLL - packet length (2 byte: hex chars - 0-9, A-F)
# * ... data
# * CCCC - CRC16 (2 byte: hex chars - 0-9, A-F)
# *
# * data sending in ascii format
# * timeout = 2 sec
# *
# * */
            destObj, srcObj, msgType, packetLen = \
            struct.unpack_from('<4s4s2s4s', buf, pduPos + len(cSSNSTART))
            try:
            # convert to integers
                destObj = int(destObj, 16)
                srcObj = int(srcObj, 16)
                msgType = int(msgType, 16)
                packetLen = int(packetLen, 16)
                pduDataPos = pduPos + len(cSSNSTART)+14
                if ((pduDataPos+packetLen+4)<=len(buf)):
                    pduData = buf[pduDataPos:pduDataPos+packetLen]
                    pduCRC = struct.unpack_from('<4s', buf, pduDataPos+packetLen)[0]
                    calcCRC = crc16.crc16xmodem(pduData, 0xffff)
                    pduCRC = int(pduCRC, 16)
                    if (calcCRC == pduCRC):
                        tmpMsg = ssnMsg(destObj=destObj, srcObj=srcObj, msgType=msgType, msgID=None, msgData=pduData, msgChannel=channel, msgSocket=socket, msgSerial = ser)
                        routeMessage(tmpMsg)
                        currentPos = pduDataPos+packetLen+4
                    else:
                        logWrite("CRC Error! dest[{}] src[{}] msg[{}...]".format(destObj,srcObj,pduData[0:20]))
                        currentPos = pduDataPos+packetLen+4
                    # check buffer tail
                    if (currentPos < len(buf)):
                        logWrite("continue process buffer:"+buf[currentPos:])
                        bufTail = processBuffer(buf[currentPos:])
                    else:
                        bufTail = buf[currentPos:]
            except Exception, e:
                currentPos = pduPos + 14
                bufTail = buf[currentPos:]
                logWrite("Error processing SSN PDU"+str(e))
        else:
            if (currentPos < 0):
                bufTail = ""
            else:
                bufTail = buf[currentPos:]
Пример #20
0
    def add_mii():
        form = MiiUploadForm()
        if form.validate_on_submit():
            mii = form.mii.data
            if mii:
                data = mii.read()
                mii_length = len(data)

                # An uploaded Mii can be with or without its checksum.
                # We'll insert one ourselves all the same.
                if mii_length == 74 or mii_length == 76:
                    # If we do have a checksum, split it off.
                    real_data = data[:74]
                    checksum = crc16.crc16xmodem(real_data).to_bytes(
                        length=2, byteorder="big")

                    # Insert this to the database.
                    full_mii = real_data + checksum
                    insert_row = MiiData(data=full_mii)
                    db.session.add(insert_row)
                    db.session.commit()
                    return redirect(url_for("list_miis"))
                else:
                    flash("Invalid Mii uploaded")
            else:
                flash("Error uploading Mii")

        return render_template("add_mii.html", form=form)
Пример #21
0
    def check_if_packet(byte: bytes):
        self.bytes_received.append(byte)

        for start_index in self._get_all_start_bytes():
            length = 0
            try:
                length = self.bytes_received[start_index + 1]
                if (self.bytes_received[start_index + length + 4] !=
                        Macros.STOP_BYTE):
                    continue
            except IndexError:
                continue

            # Packet slice
            packet = self.bytes_received[start_index:start_index + 4 + length]

            # Get data
            data = packet[2:length + 2]

            # Get checksum
            checksum = packet[length + 2] << 8
            checksum = checksum | packet[length + 3]

            # Compare computed checksum with bytes_received
            if (crc16xmodem(packet[:length + 2]) == checksum):
                print(data)
                self.bytes_received = b''
Пример #22
0
    def encodeHeaderMessage(data, crcCalcDataArray):
        """
        The function encodes the arguments to a byte array with 8 bytes.

        Parameters
        ----------
        data                : dict
            instruction header dictionary
        crcCalcDataArray        : list
            data for the calculation of the crc value

        Returns
        -------
        headerMessage       : bytearray
            encoded header message

        """
        # provide raw header message
        headerMessage = bytearray(8)
        # Encode the UDT-Index
        headerMessage[0:2] = struct.pack('<H', data['UDT-Index'])
        # Encode the version number
        headerMessage[2:4] = struct.pack('<H', data['version'])
        # Encode the device ID
        headerMessage[4] = data['deviceId']
        # Encode the number of instructions
        headerMessage[5] = data['numberOfInstructions']
        # Calculate the crc value. Over instruction message 1-3 for all instructions. Header is ignored for CRC
        # calculation.
        initCrc = 0xFFFF
        calcCRC = crc16.crc16xmodem(bytes(crcCalcDataArray), initCrc)
        # Encode the crc value
        headerMessage[6:8] = struct.pack('<H', calcCRC)

        return headerMessage
    def __init__(self, messageType, session, payload=None):
        MedtronicMessage.__init__(self, 0x05, session)

        # FIXME - make this not be hard coded
        if messageType == 0x0412:
            seqNo = self.session.sendSequenceNumber | 0x80
        else:
            seqNo = self.session.sendSequenceNumber

        encryptedPayload = struct.pack('>BH', seqNo, messageType)
        if payload:
            encryptedPayload += payload
        crc = crc16.crc16xmodem(encryptedPayload, 0xffff)
        encryptedPayload += struct.pack('>H', crc & 0xffff)
        #print "### PAYLOAD"
        #print binascii.hexlify( encryptedPayload )

        mmPayload = struct.pack(
            '<QBBB',
            self.session.pumpMAC,
            self.session.minimedSequenceNumber,
            0x10,  # Unknown byte
            len(encryptedPayload))
        mmPayload += self.encrypt(encryptedPayload)

        self.setPayload(mmPayload)
        self.session.sendSequenceNumber += 1
Пример #24
0
    def send_packet(self, data: bytes) -> bool:
        length = len(data)

        # Check that data is less than or equal to 255 bytes
        if (length > 255):
            return False

        # Start byte
        self.byte_layer.send_byte(Macros.START_BYTE)

        # Length
        self.byte_layer.send_byte(length)

        # Data
        for b in data:
            print(str(chr(b)))
            self.byte_layer.send_byte(b)

        # Checksum
        crc = crc16xmodem(bytes([Macros.START_BYTE, length]) + data)
        crc_top = crc >> 8
        crc_bottom = crc & 0xFF
        self.byte_layer.send_byte(crc_top)
        self.byte_layer.send_byte(crc_bottom)

        # Stop byte
        self.byte_layer.send_byte(Macros.STOP_BYTE)

        return True
Пример #25
0
def build_send_str(string):

    str_arr = bytearray()
    dle = bool()

    crc = crc16.crc16xmodem(str(string), 0x0000)

    str_arr.append(STX)

    for c in string:
        if (c == DLE) | (c == STX) | (c == ETX):
            str_arr.append(DLE)
        str_arr.append(c)

    crcH = (crc >> 0 & 0xff)
    crcL = (crc >> 8 & 0xff)

    if (crcH == DLE) | (crcH == STX) | (crcH == ETX):
        str_arr.append(DLE)
    str_arr.append(crcH)

    if (crcL == DLE) | (crcL == STX) | (crcL == ETX):
        str_arr.append(DLE)
    str_arr.append(crcL)

    str_arr.append(ETX)

    #for c in str_arr:
    #print hex(c)

    return str_arr
Пример #26
0
def check_crc(string):
    ''' 
    print "Komplette Daten:"
    for c in string:
        print "%#x" % ord(c)
    print "_________________________"
    print "Rohdaten:"
    for c in clean_data(string):
        print "%#x" % ord(c) '''

    crc = crc16.crc16xmodem(clean_data(string), 0x0000)
    crc_arr = bytearray()
    crc_arr.append(crc >> 0 & 0xff)
    crc_arr.append(crc >> 8 & 0xff)

    recv_str_w_CRC = clean_data_w_CRC(string)
    recv_crcH = recv_str_w_CRC[recv_str_w_CRC.__len__() - 1]
    recv_crcL = recv_str_w_CRC[recv_str_w_CRC.__len__() - 2]
    '''
    print "Empfangene CRC"
    print "%#x" % ord(recv_crcH)
    print "%#x" % ord(recv_crcL)
    
    print "Errechnete CRC"
    print "%#x" % crc_arr[0]
    print "%#x" % crc_arr[1]
    '''

    if (crc_arr[0] == ord(recv_crcL)) & (crc_arr[1] == ord(recv_crcH)):
        return 1
    else:
        return 0
Пример #27
0
 def __init__(self):
     with open(os.path.join(os.path.dirname(__file__), 'config.json'),
               'r',
               encoding='utf-8-sig') as file:
         _conf = json.load(file)
         uart_cfg = _conf.get('UART')
         uart_port_read = uart_cfg['port_read']
         uart_port_write = uart_cfg['port_write']
         uart_baudrate = uart_cfg['baudrate']
         uart_timeout = uart_cfg['timeout']
         socket_cfg = _conf.get('SOCKET')
         socket_port = socket_cfg['port']
         socket_ip = socket_cfg['ip']
     self.port = uart_port_read
     self.port_write = uart_port_write
     self.baudrate = uart_baudrate
     self.timeout = uart_timeout
     self.ser = serial.Serial(port=self.port,
                              baudrate=self.baudrate,
                              timeout=self.timeout)
     self.ser_write = serial.Serial(port=self.port_write,
                                    baudrate=self.baudrate,
                                    timeout=self.timeout)
     self.preamble = b'\x5A\x5A'
     self.size = 10
     self.device_type = 255
     self.device_id = 255
     self.mess = 0
     self.body = struct.pack('BBBB', self.size, self.device_type,
                             self.device_id, self.mess)
     self.crc = (crc16.crc16xmodem(self.body))
     self.postamble = b'\x7A\x7a'
Пример #28
0
def serial_transmit_message(msg):
    """Frame up and send a message to the badge

    The message should contain only printable characters.
    """
    crc = '{0:04x}'.format(crc16.crc16xmodem(msg)).encode('ascii')
    uart.send(frame_flag + msg + crc + frame_flag)
Пример #29
0
def format_command(address, command):
    """
	Format a command for transmission to Aladdin pump in Safe Mode.

	Result includes the length and checksum but not the 
	start / termination characters (\x02 and \x03).

	@param address: Numeric address of the pump, 0-99, or None.
	@param command: Textual command to send.
	"""

    # Confirm address parameter
    if address > 99:
        raise SyntaxError("Invalid Address: %s" % address)
    if address is not None:
        command = "{:02d}{:s}".format(address, command)

    # Account for the length byte, the two crc bytes
    # and the termination byte
    length = len(command) + 4

    if length > 255:
        raise SyntaxError("Command too long: %s" % command)

    crc = struct.pack(">H", crc16.crc16xmodem(command))
    return "{:c}{:s}{:s}".format(length, command, crc)
Пример #30
0
def read_rs232_packet():
	c = ser.read()
	if  c != b'\x00':
#		print("Not recv 00")
#		print(c)
		return None
	id = ser.read()
	if  id != b'\x50' and id != b'\x60' and id != b'\x70' :
		print("Not recv ID")
		print(id)
		return None
	len = struct.unpack('>B', ser.read())[0]
	if  len <= 2 :
		print("Len too short")
		return None
	packet = b'\x00'
	packet += id
	packet += struct.pack('>B', len)
	packet += ser.read(len-5)
	crc_recv = struct.unpack('>H', ser.read(2))[0]
	crc_calc = crc16.crc16xmodem(packet)
	if  crc_recv != crc_calc :
		print("CRC fail")
		print(crc_recv, " ", crc_calc)
		return None
#	print_in_hex(packet[3:])
	return packet+struct.pack('>H', crc_calc)
Пример #31
0
    def verify_match(self, header, offset):
        """Verify DDR4 specific bit fields."""
        # offset 0 is a candidate, no need to validate
        if self.blob_as_ord(offset + 1) == 0xff:
            return False
        if self.blob_as_ord(offset + 2) != 0x0c:
            return False
        if self.blob_as_ord(offset + 5) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 6) & 0xc > 0:
            return False
        if self.blob_as_ord(offset + 7) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 8) != 0:
            return False
        if self.blob_as_ord(offset + 9) & 0xf > 0:
            return False
        if self.verbose:
            print("%x: Looks like DDR4 SPD" % offset)

        crc = crc16.crc16xmodem(self.blob[offset:offset + 0x7d + 1])
        # Vendors ignore the endianness...
        crc_spd1 = self.blob_as_ord(offset + 0x7f)
        crc_spd1 |= (self.blob_as_ord(offset + 0x7e) << 8)
        crc_spd2 = self.blob_as_ord(offset + 0x7e)
        crc_spd2 |= (self.blob_as_ord(offset + 0x7f) << 8)
        if crc != crc_spd1 and crc != crc_spd2:
            if self.verbose:
                print("%x: CRC16 doesn't match" % offset)
            if not self.ignorecrc:
                return False

        return True
Пример #32
0
def format_command (address, command):
	"""
	Format a command for transmission to Aladdin pump in Safe Mode.

	Result includes the length and checksum but not the 
	start / termination characters (\x02 and \x03).

	@param address: Numeric address of the pump, 0-99, or None.
	@param command: Textual command to send.
	"""

	# Confirm address parameter
	if address > 99:
		raise SyntaxError("Invalid Address: %s" % address)
	if address is not None:
		command = "{:02d}{:s}".format(address, command)

	# Account for the length byte, the two crc bytes
	# and the termination byte
	length = len(command) + 4 

	if length > 255:
		raise SyntaxError("Command too long: %s" % command)

	crc = struct.pack(">H", crc16.crc16xmodem(command))
	return "{:c}{:s}{:s}".format(length, command, crc)
Пример #33
0
def check_crc(string):
    ''' 
    print "Komplette Daten:"
    for c in string:
        print "%#x" % ord(c)
    print "_________________________"
    print "Rohdaten:"
    for c in clean_data(string):
        print "%#x" % ord(c) ''' 
   
    
    crc = crc16.crc16xmodem(clean_data(string), 0x0000)    
    crc_arr = bytearray()
    crc_arr.append(crc >> 0 & 0xff)
    crc_arr.append(crc >> 8 & 0xff)
    
    recv_str_w_CRC = clean_data_w_CRC(string)
    recv_crcH = recv_str_w_CRC[recv_str_w_CRC.__len__()-1]
    recv_crcL = recv_str_w_CRC[recv_str_w_CRC.__len__()-2]
    
    '''
    print "Empfangene CRC"
    print "%#x" % ord(recv_crcH)
    print "%#x" % ord(recv_crcL)
    
    print "Errechnete CRC"
    print "%#x" % crc_arr[0]
    print "%#x" % crc_arr[1]
    '''
    
    if (crc_arr[0] == ord(recv_crcL)) & (crc_arr[1] == ord(recv_crcH)):
        return 1
    else:
        return 0
Пример #34
0
def pos_range(filename):
    '''return min/max of lat/lon in a file'''
    fh = open(filename, 'rb')
    lat_min = None
    lat_max = None
    lon_min = None
    lon_max = None
    while True:
        buf = fh.read(IO_BLOCK_SIZE)
        if len(buf) != IO_BLOCK_SIZE:
            break
        (bitmap, lat, lon, crc, version, spacing) = struct.unpack("<QiiHHH", buf[:22])
        if (version != TERRAIN_GRID_FORMAT_VERSION):
            print("Bad version %u in %s" % (version, filename))
            break
        buf = buf[:16] + struct.pack("<H", 0) + buf[18:]
        crc2 = crc16.crc16xmodem(buf[:IO_BLOCK_DATA_SIZE])
        if crc2 != crc:
            print("Bad CRC in %s" % filename)
            break
        if lat_min is None:
            lat_min = lat
            lat_max = lat
            lon_min = lon
            lon_max = lon
        lat_min = min(lat_min, lat)
        lat_max = max(lat_max, lat)
        lon_min = min(lon_min, lon)
        lon_max = max(lon_max, lon)
    lat_min *= 1.0e-7
    lat_max *= 1.0e-7
    lon_min *= 1.0e-7
    lon_max *= 1.0e-7
    return lat_min, lat_max, lon_min, lon_max
Пример #35
0
def kill_app():
    
    print "--> Kill Application now"
    print "-----------------------------------------------"
    
    send_data = bytearray()
    send_data.append(0xff)
    send_data.append(0x03)
    send_data.append(0xf5)
    
    crc = crc16.crc16xmodem(str(send_data), 0xffff)
    
    send_data.append(crc >> 8 & 0xff)
    send_data.append(crc >> 0 & 0xff)

    
    s.send(send_data)
    try:
        recv_data = s.recv(BUFFER_SIZE)
    except socket.timeout:
        print "x"
        recv_data = ""
    
    
    if recv_data:
        print "Response from PIC:", recv_data
Пример #36
0
    def verify_match(self, header, offset):
        """Verify DDR4 specific bit fields."""
        # offset 0 is a candidate, no need to validate
        if self.blob_as_ord(offset + 1) == 0xff:
            return False
        if self.blob_as_ord(offset + 2) != 0x0c:
            return False
        if self.blob_as_ord(offset + 5) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 6) & 0xc > 0:
            return False
        if self.blob_as_ord(offset + 7) & 0xc0 > 0:
            return False
        if self.blob_as_ord(offset + 8) != 0:
            return False
        if self.blob_as_ord(offset + 9) & 0xf > 0:
            return False
        if self.verbose:
            print("%x: Looks like DDR4 SPD" % offset)

        crc = crc16.crc16xmodem(self.blob[offset:offset + 0x7d + 1])
        # Vendors ignore the endianness...
        crc_spd1 = self.blob_as_ord(offset + 0x7f)
        crc_spd1 |= (self.blob_as_ord(offset + 0x7e) << 8)
        crc_spd2 = self.blob_as_ord(offset + 0x7e)
        crc_spd2 |= (self.blob_as_ord(offset + 0x7f) << 8)
        if crc != crc_spd1 and crc != crc_spd2:
            if self.verbose:
                print("%x: CRC16 doesn't match" % offset)
            if not self.ignorecrc:
                return False

        return True
Пример #37
0
def mac_address_to_id(mac):
    """Converts a MAC address to an id used by the badges for the proximity pings.
    """
    # convert hex to bytes and reverse
    macstr = mac.replace(':', '').decode('hex')[::-1]
    crc = crc16.crc16xmodem(macstr, 0xFFFF)
    return crc
    def __init__(self, messageType, session, payload=None):
        MedtronicMessage.__init__(self, 0x05, session)

        # FIXME - make this not be hard coded
        seqNo = 0x80
        if messageType == 0x0403:
            seqNo = 2
        elif messageType == 0x0112:
            seqNo = 3

        encryptedPayload = struct.pack('>BH', seqNo, messageType)
        if payload:
            encryptedPayload += payload
        crc = crc16.crc16xmodem(encryptedPayload, 0xffff)
        encryptedPayload += struct.pack('>H', crc & 0xffff)

        mmPayload = struct.pack(
            '<QBBB',
            self.session.pumpMAC,
            self.session.minimedSequenceNumber,
            0x10,  # Unknown byte
            len(encryptedPayload))
        mmPayload += self.encrypt(encryptedPayload)

        self.setPayload(mmPayload)
Пример #39
0
def build_send_str(string):
    
    str_arr = bytearray()
    dle = bool()
    
    crc = crc16.crc16xmodem(str(string), 0x0000)
    
    str_arr.append(0x0f)
    
    for c in string:
        if (c == 0x05)|(c == 0x0f)|(c == 0x04):
            str_arr.append(0x05)
        str_arr.append(c)
    
    crcH = (crc >> 0 & 0xff)
    crcL = (crc >> 8 & 0xff) 

    if (crcH == 0x05)|(crcH == 0x0f)|(crcH == 0x04):
            str_arr.append(0x05)
    str_arr.append(crcH)

    if (crcL == 0x05)|(crcL == 0x0f)|(crcL == 0x04):
        str_arr.append(0x05)
    str_arr.append(crcL)



    str_arr.append(0x04)

        #for c in str_arr:
            #print hex(c)

    return str_arr
Пример #40
0
 def transfer_file(self):
   data = self.get_data_block()
   while len(data) > 0:
     crc = 0
     for x in data:
       crc = crc16.crc16xmodem(str(x), crc)
     tmp = bytearray(2)
     tmp[0] = crc & 0xFF
     tmp[1] = (crc & 0xFF00) >> 8
     result = 'NACK'
     while result == 'NACK':
       print "sending:BLK"
       self.port.write('BLK')
       print "sending data:",[str(x) for x in data]
       self.port.write(data)
       print "sending tmp:",[str(x) for x in tmp]
       self.port.write(tmp)
       result = self.wait_for_response()
     if result == 'PACK':
       data = self.get_data_block()
     else:
       #got something weird back, quit early
       return 'FAIL'
   self.port.write('EOF')
   return 'DONE'
Пример #41
0
def check_filled(block, lat_int, lon_int, grid_spacing):
    '''check a block for validity'''
    if len(block) != IO_BLOCK_SIZE - 227:
        print("Bad size {0} of {1}".format(len(block), IO_BLOCK_SIZE))
        return False
    (bitmap, lat, lon, crc, version,
     spacing) = struct.unpack("<QiiHHH", block[:22])
    if (lat == 0 and lon == 0 and crc == 0 and version == 0 and spacing == 0):
        #print("Empty block")
        return True
    if (str(version) != str(TERRAIN_GRID_FORMAT_VERSION)):
        print("Bad version: " + str(version))
        return False
    if abs(lat_int - (lat / 1E7)) > 2 or abs(lon_int - (lon / 1E7)) > 2:
        print("Bad lat/lon: {0}, {1}".format((lat / 1E7), (lon / 1E7)))
        return False
    if spacing != 100:
        print("Bad spacing: " + str(spacing))
        return False
    if bitmap != (1 << 56) - 1:
        print("Bad bitmap")
        return False

    block = block[:16] + struct.pack("<H", 0) + block[18:]
    crc2 = crc16.crc16xmodem(block[:1821])
    if crc2 != crc:
        print("Bad CRC")
        return False

    # all is good, return lon/lat of block
    return (lat, lon)
Пример #42
0
    def to_upgrade_file(self, file_or_filename):
        """
            Packs a raw binary into a TG165 image.

            file_or_filename: The filename that should be written, or
                a file-like object to write to.
        """

        close_needed = False
        source = io.BytesIO(self.raw_bytes)

        if isinstance(file_or_filename, str):
            target = open(file_or_filename, 'wb')
            close_needed = True
        else:
            target = file_or_filename

        for data in self.__read_in_blocks(source, self.UPGRADE_BIN_DATA_SIZE):
            # Compute the CRC of the chunk.
            data_crc = crc16.crc16xmodem(data).to_bytes(2, byteorder='little')

            # Write the chunk with checksum in the FLIR-expected format.
            target.write(data_crc)
            target.write(b"\x00\x00")
            target.write(data)

        if close_needed:
            target.close()
Пример #43
0
def build_send_str(string):
    
    str_arr = bytearray()
    dle = bool()
    
    crc = crc16.crc16xmodem(str(string), 0x0000)
    
    str_arr.append(STX)
    
    for c in string:
        if (c == DLE)|(c == STX)|(c == ETX):
            str_arr.append(DLE)
        str_arr.append(c)
    
    crcH = (crc >> 0 & 0xff)
    crcL = (crc >> 8 & 0xff) 

    if (crcH == DLE)|(crcH == STX)|(crcH == ETX):
            str_arr.append(DLE)
    str_arr.append(crcH)

    if (crcL == DLE)|(crcL == STX)|(crcL == ETX):
        str_arr.append(DLE)
    str_arr.append(crcL)

    str_arr.append(ETX)

        #for c in str_arr:
            #print hex(c)

    return str_arr
Пример #44
0
 def send(self, value):
     packet = self.build_packet(value)
     byte_str = ''.join([chr(b) for b in packet])
     crc = crc16.crc16xmodem(byte_str)
     byte_str += struct.pack('H', crc)
     r = self.port.write(byte_str)
     self.port.flush()
     print 'Sent %s as %s bytes' % (value, r)
Пример #45
0
    def run(self):
        self.stream_data = True

        ps        = self.packet_size['ps']
        read_size = 300
        np        = 0
        data      = b''

        command = "wbaoms"
        res     = send_command(self.faros_socket, command, 7)

        command = "wbaom7"
        res     = send_command(self.faros_socket, command, 7)

        p_crc = Struct('packet_format', Array(1, ULInt16('crc')))

        self.faros_socket.setblocking(True)

        while (self.stream_data):
            data += self.faros_socket.recv(read_size)
            
            if len(data) >= ps:

                packet    = data[0:ps]
                data      = data[ps:]
                signature = packet[0:3]
                
                try:
                    crc_1     = p_crc.parse(packet[-2:])['crc'][0]
                    crc_2     = crc16.crc16xmodem(packet[:-2])
                except TypeError:
                    crc_1 = 0
                    crc_2 = 1

                if (signature == b'MEP') & (crc_1 == crc_2):

                    unpack_data(packet        = packet,
                                packet_size   = self.packet_size,

                                p_header      = self.p_header,
                                p_ecg         = self.p_ecg,
                                p_acc         = self.p_acc,
                                p_marker      = self.p_marker,
                                p_rr          = self.p_rr,
                                p_temp        = self.p_temp,

                                outlet_ecg    = self.outlet_ecg,
                                outlet_acc    = self.outlet_acc,
                                outlet_marker = self.outlet_marker,
                                outlet_rr     = self.outlet_rr,
                                outlet_temp   = self.outlet_temp)
                    # np += 1
                else:
                    while True:
                        tmp = self.faros_socket.recv(read_size)
                        if tmp[0:3] == b'MEP':
                            data = tmp
                            break
Пример #46
0
    def buildBinaryCommand(self, binCmd, binPayload=None):

        payloadSize = 0
        if binPayload:
            payloadSize = len(binPayload)
            # print "Send payload: %s" % binPayload.encode("hex")
            # print "Send payload: ", payloadSize, cobs.LenCobs
            assert(payloadSize <= cobs.LenCobs)

        #
        # Not block: SOH(1) line(1) cmd(1) size(4) [ data ] chksum(2) -> max payload = 254 (COBS) - 9 = 245
        # Block:     SOH(1) line(1) cmd(1) size(2) [ data ] chksum(2)
        #
        binary  = struct.pack("<B", SOH)

        header = struct.pack("<BBB", self.lineNr, binCmd, payloadSize+0x01)

        binary += header
        checksum = crc16.crc16xmodem(header)

        if binPayload:
            binary += binPayload
            checksum = crc16.crc16xmodem(binPayload, checksum)

        # print "cflags, c1: 0x%x, 0x%x" % (cflags, checksum)
        cflags = 0x1
        if checksum == 0:
            cflags = 0x4
            checksum = 0x0101
        elif (checksum & 0xFF00) == 0:
            cflags = 0x2
            checksum = 0x0100 | (checksum & 0xFf)
        elif (checksum & 0x00FF) == 0:
            cflags = 0x3
            checksum = 0x0001 | (checksum & 0xFF00)

        # self.gui.log("checkSum: ", checkSum, "0x%x" % checkSum)
        binary += struct.pack("<BH", cflags, checksum)

        # Store for later possible command resend
        self.lastCommands[self.lineNr] = binary

        self.incLineNumber()

        return binary
Пример #47
0
def decodePacket(packet, decodePacketNr=True):

    ofs = 0

    assert(packet[ofs] == nullByte)
    ofs += 1

    line = 0
    if decodePacketNr:
        line = ord(packet[ofs])
        ofs += 1

    cmd = ord(packet[ofs])
    ofs += 1

    # n = ord(packet[3]) - 1
    n = struct.unpack("<B", packet[ofs:ofs+LenLen])[0] - 0x01
    ofs += LenLen

    if decodePacketNr:
        assert(len(packet) == n+LenHeader)
    else:
        if len(packet) != n+LenHeader-1:
            print "Packet len error: payload(0x%x)+HeaderSize(0x%x) 0x%x != packetLength(0x%x)" % (n, LenHeader-1, n+LenHeader-1, len(packet))
            assert(0)

    # print "line, cmd, n:", line, cmd, n

    result = packet[ofs:ofs+n]
    ofs += n

    cflags = ord(packet[ofs])
    ofs += 1

    # c1 = crc16.crc16xmodem(packet[1:n+LenHeader-4])
    c1 = crc16.crc16xmodem(packet[1:-3])

    (c2, ) = struct.unpack("<H", packet[ofs:ofs+2])

    assert (cflags in [0x1, 0x2, 0x3, 0x4])

    # print "cflags, c1, c2: 0x%x, 0x%x, 0x%x" % (cflags, c1, c2)

    # xxx
    if cflags == 0x2:
        c2 = c2 - 0x0100;
    elif cflags == 0x3:
        c2 = c2 - 0x1;
    elif cflags == 0x4:
        c2 = c2 - 0x0101;

    # print "c2 adjusted: 0x%x" % c2

    assert(c1 == c2)

    return (line, cmd, n, result)
Пример #48
0
    def check_CRC(self, message):
        '''
        Given a message with a checksum as the last two bytes, this will return True or False
        if the checksum matches the given message.
        '''
        msg_checksum = message[-2:]
        raw_message = message[:-2]
        crc = crc16.crc16xmodem(raw_message, 0xFFFF)

        # If the two match the message was correct
        if crc == struct.unpack('>H', msg_checksum)[0]:
            return True
        else:
            return False
Пример #49
0
def key2slot(key):
    """
    Calculate keyslot for a given key.

    This also works for binary keys that is used in python 3.
    """
    k = unicode(key)
    start = k.find("{")

    if start > -1:
        end = k.find("}", start + 1)
        if end > -1 and end != start + 1:
            k = k[start + 1:end]

    return crc16.crc16xmodem(k) % RedisClusterHashSlots
Пример #50
0
def check_crc(string):
    
    crc = crc16.crc16xmodem(clean_data(string), 0x0000)    
    crc_arr = bytearray()
    crc_arr.append(crc >> 0 & 0xff)
    crc_arr.append(crc >> 8 & 0xff)
    
    recv_crcH = string[string.__len__()-2]
    recv_crcL = string[string.__len__()-3]
    
    #print "%#x" % ord(recv_crcH)
    #print "%#x" % ord(recv_crcL)
    
    #print "%#x" % crc_arr[0]
    #print "%#x" % crc_arr[1]

    if (crc_arr[0] == ord(recv_crcL)) & (crc_arr[1] == ord(recv_crcH)):
        return 1
    else:
        return 0
Пример #51
0
    def serialize(self, message):
        final_message = list()

        # prefix message
        final_message.append(kamstrup_constants.RESPONSE_MAGIC)
        final_message.append(self.communication_address)

        # add the original content
        for c in message:
            final_message.append(c)

        # generate and append checksum
        crc = crc16.crc16xmodem(b''.join([chr_py3(item) for item in final_message[1:]]))
        final_message.append(crc >> 8)
        final_message.append(crc & 0xff)

        # trailing magic
        final_message.append(kamstrup_constants.EOT_MAGIC)

        escaped_message = self.escape(final_message)
        return escaped_message
Пример #52
0
    def build_packet(self, command, payload=None):
        #todo: In C#, they overload this function based on payload type. 
        # no payload: num=6
        # byte: num=7
        # short/ushort: num=8
        # int/uint: num=10
        # long/ulong: num=14
        # there's even a case for payload, payload2
        MaxPayloadLength = 1584
        MinPacketLength = 6
        MaxPacketLength = 1590

        packet = bytearray(1590)
        num = 6;
        packet[0] = 1
        packet[1] = num
        packet[3] = command
        
        crc = crc16.crc16xmodem(str(packet)[0:num-2])
        self.store_bytes(crc, packet, num-2)
        return packet
Пример #53
0
    def get_register(self, register):
        message = [kamstrup_constants.REQUEST_MAGIC, self.comm_address, 0x10, 0x01, register >> 8, register & 0xff]
        crc = crc16.crc16xmodem(''.join([chr(item) for item in message[1:]]))
        message.append(crc >> 8)
        message.append(crc & 0xff)
        message_length = len(message)
        y = 1
        while y < message_length:
            if message[y] in kamstrup_constants.NEED_ESCAPE:
                message[y] ^= 0xff
                message.insert(y, kamstrup_constants.ESCAPE)
                y += 1
                message_length += 1
            y += 1
        message.append(kamstrup_constants.EOT_MAGIC)

        received_data = None
        while received_data is None:
            try:
                self._sock.send(bytearray(message))
                received_data = self._sock.recv(1024)
                received_data = bytearray(received_data)
            except socket.error as socket_err:
                print('Error while communicating: {0}'.format(str(socket_err)))
                self._connect()
        data_length = len(received_data)

        # remove escaped bytes
        p = 0
        while p < data_length:
            if received_data[p] is kamstrup_constants.ESCAPE:
                del received_data[p]
                received_data[p] ^= 0xff
                data_length -= 1
            p += 1

        return received_data
Пример #54
0
    def _send_command(self, command):
        if self.safe_mode:
            encoded_command = command.encode('ascii')
            length = len(encoded_command) + 4
            check_sum = crc16.crc16xmodem(encoded_command).to_bytes(2, byteorder='big')
            to_send = bytes([2, length]) + encoded_command + check_sum + b'\x03'
            add = '{:0>2}'.format(n).encode('ascii')
            to_send_add = add + to_send
            self.serial.write(to_send)
            time.sleep(0.5)
            waiting = self.serial.inWaiting()
            reply = self.serial.read(waiting)

            # FIXME implement crc16 checksum check
            
            return reply.decode('ascii')
        else:
            formatted_command = command + "\r"
            self.serial.write(formatted_command.encode("ascii"))
            time.sleep(0.5)
            waiting = self.serial.inWaiting()
            reply = self.serial.read(waiting)
            reply_unicode = reply.decode("ascii")
            return reply_unicode[4:-1]
Пример #55
0
 def valid_crc(self, message):
     supplied_crc = message[-2] * 256 + message[-1]
     calculated_crc = crc16.crc16xmodem(''.join([chr(item) for item in message[:-2]]))
     return supplied_crc == calculated_crc
 def calculateCcitt( self, data ):
     crc = crc16.crc16xmodem( data, 0xffff )
     return crc & 0xffff
 def encode( self ):
     # Increment the Minimed Sequence Number
     self.session.minimedSequenceNumber += 1
     message = self.envelope + self.payload
     crc = struct.pack( '<H', crc16.crc16xmodem( message, 0xffff ) & 0xffff )
     return message + crc