Ejemplo n.º 1
0
 def ReadReaderID(self):
     result = {
         "statusCode":0x3F, 
         "readerIdBytes":bytes([]), 
         "readerID":-1
     }
     readReaderIdCmd       = b'\x01\xF6\x00' #SOH, ReaderID Command byte, Parameter length = 0
     readReaderIdCmd = readReaderIdCmd + CRC16.CalculateCRC(readReaderIdCmd)
     
     if self.__isConnected:
         self.__portConnection.ClearReceiveBuffer()
         if self.__portConnection.WriteBytesToPort(readReaderIdCmd) == len(readReaderIdCmd):
             answer = self.__ReadAndCheckReceivedAnswer(500)
             if answer["receiveOk"]:
                 answerBytes = answer["receivedBytes"]
                 result["statusCode"] = answerBytes[1]
                 if answerBytes[1]  != 0x00:
                     return result
                 
                 #if answer OK, save reader ID bytes in answer. Last byte to save from answer is: answer length - 2 (CRC)
                 readerIdBytes = answerBytes[3:len(answerBytes)-2]
                 #calculate reader ID
                 serialNumber = 0
                 if (answerBytes[10] & 0x80) != 0:
                     serialNumber |= answerBytes[5] << 16 | answerBytes[4] << 8 | answerBytes[3]
                 else:
                     serialNumber |= answerBytes[4] << 8 | answerBytes[3]
                 
                 result["readerIdBytes"] = readerIdBytes
                 result["readerID"] = serialNumber
     return result
Ejemplo n.º 2
0
def encodePayload(ftype, payload):
    tmpbuf = ftype + pk('<H', len(payload))
    tmpbuf += payload
    crc = CRC16.calcString(tmpbuf, CRC16.INITIAL_MODBUS)
    tmpbuf += pk('<H', crc)
    tmpbuf += pk('B', FRAME_TAIL)
    return tmpbuf
    def Read_ISO18000_6C_UII(self):
        result = {
            "statusCode": 0x3F,
            "uiiBytes": bytes([]),
        }
        readISO18000UiiCmd = bytes([])
        readISO18000UiiCmd = readISO18000UiiCmd + b'\x02'  #SOH
        readISO18000UiiCmd = readISO18000UiiCmd + self.GetNextSeqNum()  #SeqNum
        readISO18000UiiCmd = readISO18000UiiCmd + b'\x00\x07\x30\x10\xFF\x01\x01'  #Length, CMD Group, CMD Codes, Parameter bytes
        readISO18000UiiCmd = readISO18000UiiCmd + CRC16.CalculateCRC(
            readISO18000UiiCmd)

        if self.__isConnected:
            self.__portConnection.ClearReceiveBuffer()
            if self.__portConnection.WriteBytesToPort(
                    readISO18000UiiCmd) == len(readISO18000UiiCmd):
                answer = self.__ReadAndCheckReceivedAnswer(500)
                if answer["receiveOk"]:
                    answerBytes = answer["receivedBytes"]
                    result["statusCode"] = answerBytes[4]
                    if answerBytes[4] != 0x00:
                        return result

                    #if answer OK, save received bytes in answer. Last byte to save from answer is: answer length - 2 (CRC)
                    uiiBytes = answerBytes[5:len(answerBytes) - 2]

                    result["uiiBytes"] = uiiBytes
        return result
    def Write_ISO18000_6C_Word(self, _pageNum, _wordAddr, _dataToWrite):
        result = {
            "statusCode": 0x3F,
        }
        if len(_dataToWrite) != 2:
            return result  #Not supported! Only write 1x word possible
        writeISO18000WordsCmd = bytes([])
        writeISO18000WordsCmd = writeISO18000WordsCmd + b'\x02'  #SOH
        writeISO18000WordsCmd = writeISO18000WordsCmd + self.GetNextSeqNum(
        )  #SeqNum
        writeISO18000WordsCmd = writeISO18000WordsCmd + b'\x00\x0C\x30\x14\xFF\x00'  #Length, CMD Group, CMD Codes, Parameter bytes
        writeISO18000WordsCmd = writeISO18000WordsCmd + bytes([_pageNum])
        writeISO18000WordsCmd = writeISO18000WordsCmd + bytes(
            [(_wordAddr & 0xFF0000) >> 16, (_wordAddr & 0xFF00) >> 8,
             (_wordAddr & 0xFF)])
        writeISO18000WordsCmd = writeISO18000WordsCmd + _dataToWrite[0:2]
        writeISO18000WordsCmd = writeISO18000WordsCmd + CRC16.CalculateCRC(
            writeISO18000WordsCmd)

        if self.__isConnected:
            self.__portConnection.ClearReceiveBuffer()
            if self.__portConnection.WriteBytesToPort(
                    writeISO18000WordsCmd) == len(writeISO18000WordsCmd):
                answer = self.__ReadAndCheckReceivedAnswer(500)
                if answer["receiveOk"]:
                    answerBytes = answer["receivedBytes"]
                    result["statusCode"] = answerBytes[4]
        return result
    def Read_ISO18000_6C_Words(self, _pageNum, _wordAddr, _wordCount):
        result = {
            "statusCode": 0x3F,
            "dataBytes": bytes([]),
        }
        readISO18000WordsCmd = bytes([])
        readISO18000WordsCmd = readISO18000WordsCmd + b'\x02'  #SOH
        readISO18000WordsCmd = readISO18000WordsCmd + self.GetNextSeqNum(
        )  #SeqNum
        readISO18000WordsCmd = readISO18000WordsCmd + b'\x00\x0B\x30\x12\xFF\x01'  #Length, CMD Group, CMD Codes, Parameter bytes
        readISO18000WordsCmd = readISO18000WordsCmd + bytes([_pageNum])
        readISO18000WordsCmd = readISO18000WordsCmd + bytes(
            [(_wordAddr & 0xFF0000) >> 16, (_wordAddr & 0xFF00) >> 8,
             (_wordAddr & 0xFF)])
        readISO18000WordsCmd = readISO18000WordsCmd + bytes([_wordCount])
        readISO18000WordsCmd = readISO18000WordsCmd + CRC16.CalculateCRC(
            readISO18000WordsCmd)

        if self.__isConnected:
            self.__portConnection.ClearReceiveBuffer()
            if self.__portConnection.WriteBytesToPort(
                    readISO18000WordsCmd) == len(readISO18000WordsCmd):
                answer = self.__ReadAndCheckReceivedAnswer(500)
                if answer["receiveOk"]:
                    answerBytes = answer["receivedBytes"]
                    result["statusCode"] = answerBytes[4]
                    if answerBytes[4] != 0x00:
                        return result

                    #if answer OK, save received bytes in answer. Last byte to save from answer is: answer length - 2 (CRC)
                    dataBytes = answerBytes[5:len(answerBytes) - 2]

                    result["dataBytes"] = dataBytes
        return result
Ejemplo n.º 6
0
 def __ReadAndCheckReceivedAnswer(self, _timeoutMs):
     result = {
         "receiveOk":False, 
         "receivedBytes":bytes([]), 
         "receivedBytesLength":0
     }
     
     startTime = time.perf_counter()
     availableBytes = 0
     bytesBuffer = bytes([])
     
     availableBytes = self.__portConnection.CheckBytesInBuffer()
     while (time.perf_counter() - startTime) < (_timeoutMs / 1000):
         if availableBytes >= 5:
             break
         availableBytes = self.__portConnection.CheckBytesInBuffer()
     
     if availableBytes >= 5:
         #First 5 bytes are available --> read them & save
         bytesBuffer = self.__portConnection.ReadBytesFromPort(availableBytes)
         
         #To continue, at least 3 bytes are needed
         if len(bytesBuffer) < 3:
             return result
         #Check SOH received
         if bytesBuffer[0] != 0x01:
             return result
         #Calculate total answer length: SOH + status + length byte + Data(length provided in LengthByte) + CRC
         answerTotalLength = 3 + bytesBuffer[2] + 2; 
         bytesToRead = answerTotalLength - len(bytesBuffer)
         if bytesToRead > 0:
             #Wait for the rest of the answer
             availableBytes = self.__portConnection.CheckBytesInBuffer()
             while (time.perf_counter() - startTime) < (_timeoutMs / 1000):
                 if availableBytes >= bytesToRead:
                     break
                 availableBytes = self.__portConnection.CheckBytesInBuffer()
             
             if bytesToRead >= availableBytes:
                 #At least expected bytes available --> read them
                 bytesBuffer = bytesBuffer + self.__portConnection.ReadBytesFromPort(bytesToRead)
         
         #Now all bytes should be read --> check length
         if len(bytesBuffer) != answerTotalLength:
             return result
         #Check CRC
         crc = CRC16.CalculateCRC(bytesBuffer)
         if crc[0] != 0:
             return result
         if crc[1] != 0:
             return result
         
         #CRC is OK --> set variables and return
         result["receivedBytes"] = bytesBuffer
         result["receivedBytesLength"] = len(bytesBuffer)
         result["receiveOk"] = True
         return result
     else:
         return result
Ejemplo n.º 7
0
    def computeAndWriteAppCheckSumBin(self, version_tuple, destinationfilename = 'Output\code.bin'):
        DebugOut( 'Memory.computeAndWriteAppCheckSum' )
        FW_CRC32_LOCATION = 0x0
        FW_SIZE_LOCATION  = 0x4
        FW_DATE_LOCATION  = 0xC
        FW_VERSION_LOCATION  = 0x8
        FW_CRC16_LOCATION = 0x1C
        FW_CODE_LOCATION  = 0x20
        
        FW_size = len(self.__data)-FW_CODE_LOCATION
        FW_version = filter
        FW_date = int((datetime.now() - datetime(1970,1,1)).total_seconds())

        #Write code size
        self.__data[FW_SIZE_LOCATION+3] = chr((FW_size >> 24) & 0xFF)
        self.__data[FW_SIZE_LOCATION+2] = chr((FW_size >> 16) & 0xFF)
        self.__data[FW_SIZE_LOCATION+1] = chr((FW_size >> 8) & 0xFF)
        self.__data[FW_SIZE_LOCATION]   = chr(FW_size & 0xFF)

        #Write code date
        self.__data[FW_DATE_LOCATION+3] = chr((FW_date >> 24) & 0xFF)
        self.__data[FW_DATE_LOCATION+2] = chr((FW_date  >> 16) & 0xFF)
        self.__data[FW_DATE_LOCATION+1] = chr((FW_date  >> 8) & 0xFF)
        self.__data[FW_DATE_LOCATION]   = chr(FW_date  & 0xFF)

        #Write code version
        print 'ver: ', version_tuple
        self.__data[FW_VERSION_LOCATION+3] = chr(version_tuple[3])
        self.__data[FW_VERSION_LOCATION+2] = chr(version_tuple[2])
        self.__data[FW_VERSION_LOCATION+1] = chr(version_tuple[1])
        self.__data[FW_VERSION_LOCATION]   = chr(version_tuple[0])
        
        # Compute Checksum 
        codebuff = self.__data[FW_CODE_LOCATION : len(self.__data)]
        nCRC16val = CRC16.computeCRC(0xFFFF, codebuff, len(codebuff))
        
        # Write checksum back into memory location little endian
        self.__data[FW_CRC16_LOCATION+1] = chr((nCRC16val >> 8) & 0xFF)
        self.__data[FW_CRC16_LOCATION]   = chr(nCRC16val & 0xFF)

        # calculate CRC32 starting after the CRC32 value to the end of the code
        codebuff = self.__data[FW_SIZE_LOCATION : len(self.__data)]
        codebuffstr = ''.join(codebuff)
        FW_crc32 = zlib.crc32(codebuffstr)
        
        print 'Code sz: ', hex(FW_size), 'crc16: ', hex(nCRC16val)
        print 'date: ', '0x{:08x}'.format(FW_date)
        print 'CRC32: ', '0x{:08x}'.format(FW_crc32 & 0xFFFFFFFF), 'size', FW_size, 'sz2 ',len(codebuff)

        # Write code CRC32
        self.__data[FW_CRC32_LOCATION+3] = chr((FW_crc32 >> 24) & 0xFF)
        self.__data[FW_CRC32_LOCATION+2] = chr((FW_crc32 >> 16) & 0xFF)
        self.__data[FW_CRC32_LOCATION+1] = chr((FW_crc32 >> 8) & 0xFF)
        self.__data[FW_CRC32_LOCATION]   = chr(FW_crc32 & 0xFF)

        codeHeaderstr = ''.join(self.__data)
        file = open(destinationfilename, 'wb')
        file.write(codeHeaderstr)
        file.close()
Ejemplo n.º 8
0
def addCRC(myHex):
    #takes a hex string and adds a modbus CRC to it
    crc = CRC16.calcString(myHex, CRC16.INITIAL_MODBUS)
    flipped_res = "{0:#0{1}x}".format(crc, 6)
    res = flipped_res[4:6] + flipped_res[2:4]
    add_on = res.decode('hex')
    newHex = myHex + add_on
    return newHex
Ejemplo n.º 9
0
    def ExBusPacket(self, packet_ID):

        self.exbus_packet = bytearray()

        # toggles True and False
        self.get_new_sensor ^= True
        
        # send data and text messages for each sensor alternating
        if self.get_new_sensor:
            # get next sensor to send its data
            self.current_sensor = next(self.next_sensor)
            current_EX_type = 'data'
        else:     
            current_EX_type = 'text'
        
        # get the EX packet for the current sensor
        ex_packet = self.jetiex.ExPacket(self.current_sensor, current_EX_type)

        # EX bus header
        self.exbus_packet.extend(b'3B01')

        # EX bus packet length in bytes including the header and CRC
        exbus_packet_length = 8 + len(ex_packet)
        self.exbus_packet.extend('{:02x}'.format(exbus_packet_length))
        
        # packet ID (answer with same ID as by the request)
        # FIXME
        # FIXME check how this works with data and 2x text from EX values???
        # FIXME
        int_ID = int(str(packet_ID), 16)
        bin_ID = '{:02x}'.format(int_ID)
        self.exbus_packet.extend(bin_ID)
        
        # telemetry identifier
        self.exbus_packet.extend(b'3A')

        # packet length in bytes of EX packet
        ex_packet_length = len(ex_packet)
        self.exbus_packet.extend('{:02x}'.format(ex_packet_length))

        # add EX packet
        self.exbus_packet.extend(ex_packet)

        # calculate the crc for the packet
        crc = CRC16.crc16_ccitt(self.exbus_packet)

        # compile final telemetry packet
        self.exbus_packet.extend(crc[2:4])
        self.exbus_packet.extend(crc[0:2])

        # print('Ex Bus Packet (JetiExBus.py)', self.jetiex.bytes2hex(self.exbus_packet))
        # print('Ex Bus Packet (JetiExBus.py)', self.exbus_packet)

        return self.exbus_packet
Ejemplo n.º 10
0
def receive_Portdata():
    while 1:
    	sBytes=[]
    	sBytes=sData.generateData()
    	portStr=[]
    	ser.write(sBytes)
    	str1 = ser.readline()
    	if str1 and len(str1)==15 and str1[0]==0xAA and str1[1]==0x55 and CRC16.myVerify_CRC16_Check_Sum(str1,15) and rData.time==sData.time:
    		print(str1)
    		break
    	time.sleep(0.5)
Ejemplo n.º 11
0
    def checkCRC(self, packet, crc_check):
        '''Do a CRC check using CRC16-CCITT

        Args:
            packet (bytearray): packet of Jeti Ex Bus including the checksum
                                The last two bytes of the packet are LSB and
                                MSB of the checksum. 

        Returns:
            bool: True if the crc check is OK, False if NOT
        '''
        crc = CRC16.crc16_ccitt(packet)

        return crc == crc_check
Ejemplo n.º 12
0
    def computeAndWriteAppCheckSum(self):
        DebugOut( 'Memory.computeAndWriteAppCheckSum' )        

        #Create code buffer [0 - 0x3FF] and [0xA00 - 0xFFD] 
        codebuff = self.__data[0 : 0x400]
        codebuff += self.__data[0xA00 : 0xFFFE]

        #Compute Checksum [0 - 0x3FF] and [0xA00 - 0xFFD]
        nCRC16val = CRC16.computeCRC(0xFFFF, codebuff, len(codebuff))

        DebugOut( 'Memory.computeAndWriteAppCheckSum: nCRC16val = %s' % (nCRC16val) )   

        #Write checksum back into memory location
        LoCRC = nCRC16val & 0xFF
        HiCRC = (nCRC16val >> 8) & 0xFF
        
        self.__data[0xFFFE] = chr(HiCRC)
        self.__data[0xFFFF] = chr(LoCRC)
Ejemplo n.º 13
0
    def checkSpeed(self):
        '''Check the connection speed via CRC. This needs to be done by
        the sensor (slave). The speed is either 125000 (default) or 250000
            - if CRC ok, then speed is ok
            - if CRC is not ok, then speed has to be set to the
              respective 'other' speed

        Args:
            packet (bytes): one complete packet received from the
                            Jeti receiver (master)

        Returns:
            bool: information if speed check was ok or failed
        '''

        # do the same as in run_forever
        while True:
            self.exbus = self.serial.read(8)
            self.checkTelemetryRequest()
        
        # EX bus CRC starts with first byte of the packet
        offset = 0
        
        # packet to check is message without last 2 bytes
        packet = bytearray(self.telemetryRequest[:-2])

        # the last 2 bytes of the message makeup the crc value for the packet
        packet_crc = self.telemetryRequest[-2:]

        # calculate the crc16-ccitt value of the packet
        crc = CRC16.crc16_ccitt(packet)

        if crc == packet_crc:
            speed_changed = False
        else:
            # change speed if CRC check fails
            speed_changed = True
            if self.baudrate == 125000:
                self.baudrate = 250000
            elif self.baudrate == 250000:
                self.baudrate = 125000

        return speed_changed
Ejemplo n.º 14
0
 def Write_ISO15693_Block(self, _blockNum, _dataToWrite):
     result = {
         "statusCode":0x3F, 
     }
     if len(_dataToWrite) != 4:
         return result #Not supported by this sample code
     writeIso15693BlockCmd       = b'\x01\x61\x05' #SOH, ISO15693 Write Block Command byte, Parameter length = 5
     writeIso15693BlockCmd = writeIso15693BlockCmd + bytes([_blockNum])
     writeIso15693BlockCmd = writeIso15693BlockCmd + _dataToWrite[0:4]
     writeIso15693BlockCmd = writeIso15693BlockCmd + CRC16.CalculateCRC(writeIso15693BlockCmd)
     
     if self.__isConnected:
         self.__portConnection.ClearReceiveBuffer()
         if self.__portConnection.WriteBytesToPort(writeIso15693BlockCmd) == len(writeIso15693BlockCmd):
             answer = self.__ReadAndCheckReceivedAnswer(500)
             if answer["receiveOk"]:
                 answerBytes = answer["receivedBytes"]
                 result["statusCode"] = answerBytes[1]
     return result
Ejemplo n.º 15
0
 def Read_ISO15693_UID(self):
     result = {
         "statusCode":0x3F, 
         "uidBytes":bytes([])
     }
     readIso15693UidCmd       = b'\x01\x20\x00' #SOH, ISO15693 UID Command byte, Parameter length = 0
     readIso15693UidCmd = readIso15693UidCmd + CRC16.CalculateCRC(readIso15693UidCmd)
     
     if self.__isConnected:
         self.__portConnection.ClearReceiveBuffer()
         if self.__portConnection.WriteBytesToPort(readIso15693UidCmd) == len(readIso15693UidCmd):
             answer = self.__ReadAndCheckReceivedAnswer(500)
             if answer["receiveOk"]:
                 answerBytes = answer["receivedBytes"]
                 result["statusCode"] = answerBytes[1]
                 if answerBytes[1]  != 0x00:
                     return result
                 
                 #if answer OK, save reader ID bytes in answer. Last byte to save from answer is: answer length - 2 (CRC)
                 uidBytes = answerBytes[3:len(answerBytes)-2]
                 result["uidBytes"] = uidBytes
     return result
Ejemplo n.º 16
0
	def generateData(self):
		data=[]
		data.append(0xAA)
		data.append(0x55)
		data.append(self.tx2Statu)
		data.append(self.fps)
		data.append(self.time)
		data.append(self.distance>>8)
		data.append(self.distance-self.distance>>8<<8)
		u8=myFormat.floatToBytes(self.pitchAngle)
		data.append(u8[0])
		data.append(u8[1])
		data.append(u8[2])
		data.append(u8[3])
		u8=myFormat.floatToBytes(self.yawAngle)
		data.append(u8[0])
		data.append(u8[1])
		data.append(u8[2])
		data.append(u8[3])
		data.append(0)
		data.append(0)
		CRC16.Append_CRC16_Check_Sum(data,17)
		return data
    def ReadReaderID(self):
        result = {
            "statusCode": 0x3F,
            "readerIdBytes": bytes([]),
            "readerID": -1
        }
        readReaderIdCmd = bytes([])
        readReaderIdCmd = readReaderIdCmd + b'\x02'  #SOH
        readReaderIdCmd = readReaderIdCmd + self.GetNextSeqNum()  #SeqNum
        readReaderIdCmd = readReaderIdCmd + b'\x00\x06\x10\x10\xFF\x01'  #Length, CMD Group, CMD Codes, Parameter byte
        readReaderIdCmd = readReaderIdCmd + CRC16.CalculateCRC(readReaderIdCmd)

        if self.__isConnected:
            self.__portConnection.ClearReceiveBuffer()
            if self.__portConnection.WriteBytesToPort(readReaderIdCmd) == len(
                    readReaderIdCmd):
                answer = self.__ReadAndCheckReceivedAnswer(500)
                if answer["receiveOk"]:
                    answerBytes = answer["receivedBytes"]
                    result["statusCode"] = answerBytes[4]
                    if answerBytes[4] != 0x00:
                        return result

                    #if answer OK, save reader ID bytes in answer. Last byte to save from answer is: answer length - 2 (CRC)
                    readerIdBytes = answerBytes[5:len(answerBytes) - 2]
                    #calculate reader ID
                    serialNumber = 0
                    if (answerBytes[12] & 0x80) != 0:
                        serialNumber |= answerBytes[7] << 16 | answerBytes[
                            6] << 8 | answerBytes[5]
                    else:
                        serialNumber |= answerBytes[6] << 8 | answerBytes[5]

                    result["readerIdBytes"] = readerIdBytes
                    result["readerID"] = serialNumber
        return result
Ejemplo n.º 18
0
            0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
            0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
            0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
            0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
            0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
            0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
            0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
            0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
            0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
            0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
        ]

        crc_hi = 0xFF
        crc_lo = 0xFF

        for w in data:
            index = crc_lo ^ ord(w)
            crc_val = crc_table[index]
            crc_temp = crc_val / 256
            crc_val_low = crc_val - (crc_temp * 256)
            crc_lo = crc_val_low ^ crc_hi
            crc_hi = crc_temp
        crc = crc_hi * 256 + crc_lo
        return crc

    crc = CRC16.calc(data1)
    crc_hi = crc / 256
    crc_lo = crc & 0xFF
#    print(str(ord(address)))
print(str(hex(crc_lo)))
print(str(hex(crc_hi)))
Ejemplo n.º 19
0
def control(code):
    code = CRC16.crc(code)
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, e:
        print "Strange error creating socket: %s" % e