def put(self,file_name,out_name = None): '''put a file from local to the device''' if os.path.exists(file_name) == False: return file_name + " not found" try: if out_name == None: out_name = '/default/' + file_name with open(file_name,'rb') as file: file_buffer = file.read() transaction_id = struct.pack('>I',random.randint(0,0xffffffff)) total_size = len(file_buffer) block_size = self.storage['put_size'] total_blocks = math.ceil(total_size / block_size) total_crc16 = CRCCCITT().calculate(file_buffer) header = transaction_id + struct.pack('>IIH',total_size, block_size,total_crc16) self.pub('sensiml/storage/put/start' ,header + out_name.encode(), 1) self.resp() for i in range(total_blocks): block_number = struct.pack('>I', i) start = i* block_size stop = start + block_size if stop > total_size: stop = total_size actual_size = stop - start crc16 = CRCCCITT().calculate(file_buffer[start:stop]) header = transaction_id + struct.pack('>IHH', i, actual_size, crc16) self.pub('sensiml/storage/put/data',header + file_buffer[start:stop] ,1) time.sleep(0.5) self.resp() self.pub('sensiml/storage/put/stop',transaction_id,1) self.resp() except Exception as err: print(str(err.args))
def sendFrame(frame, ser): #print "Frame: " + formatHex(frame) assert len(frame) == FRAME_SIZE - 1 frame_crc = struct.pack(">H", CRCCCITT().calculate(frame)) frame = frame + frame_crc[1] txData = Tx_SOF for i in range(FRAME_SIZE): if frame[i] == b'\x7e': txData = txData + b'\x7d' txData = txData + b'\x5e' elif frame[i] == b'\x7d': txData = txData + b'\x7d' txData = txData + b'\x5d' else: txData = txData + frame[i] if debug: print "Sending: " + formatHex(txData) ser.write(txData) ser.flush() for i in range(20): rxData = ser.read(2 * MAX_FRAME_SIZE) if debug: print "Received: " + formatHex(rxData) #Discard our own sent data if present if len(rxData) > 2 and rxData[0:2] == Tx_SOF: rxData = rxData[len(txData):] if len(rxData) >= FRAME_SIZE: break if len(rxData) < 2: return '' if rxData[0:2] != Rx_SOF: return '' rxData = rxData[2:] if rxData[1] == PRIM_DATA_CRC_ERR: print "Device reported CRC error" i = 0 rxDataUnstuff = '' while (i < len(rxData)): if rxData[i] == b'\x7d': if rxData[i + 1] == b'\x5e': rxDataUnstuff = rxDataUnstuff + b'\x7e' i = i + 2 elif rxData[i + 1] == b'\x5d': rxDataUnstuff = rxDataUnstuff + b'\x7d' i = i + 2 else: rxDataUnstuff = rxDataUnstuff + rxData[i] i = i + 1 rxCRC = struct.pack(">H", CRCCCITT().calculate(rxDataUnstuff[0:7])) #print "RX Data Unstuff: " + formatHex(rxDataUnstuff) if rxCRC[0] != rxDataUnstuff[7]: print "Received CRC error" return rxDataUnstuff
def lerEntradaIMG(self): # Iniciando conexao serial self.comport = serial.Serial(self.listaPortas[0], self.comboBox1.currentText(), timeout=0.2, write_timeout=0.2) self.strIMAGE = [] #vetor que guardara o valor inteiro da imagem como um char #print len(self.R_envio_noise) #print len(self.R_envio) #print self.R list_check_CRC = [] for i in range(0, len(self.R_envio)): if(self.checkBox6.isChecked()): self.strIMAGE.append(hex(self.R_envio_noise[i])[2:]) if(hex(self.R_envio_noise[i])[2:] == '0'): self.strIMAGE.append(hex(self.R_envio_noise[i])[2:]) else: self.strIMAGE.append(hex(self.R_envio[i])[2:]) if(hex(self.R_envio[i])[2:] == '0'): self.strIMAGE.append(hex(self.R_envio[i])[2:]) list_check_CRC.append(hex(self.R_envio[i])[2:]) if(hex(self.R_envio[i])[2:] == '0'): list_check_CRC.append(hex(self.R_envio[i])[2:]) #print len(self.strIMAGE) #print ''.join(self.strIMAGE) value_CRC = CRCCCITT().calculate(str(''.join(list_check_CRC))) if(self.image_height <= 10 or self.image_width <= 10): PARAM_STRING = " " + ">" + str(value_CRC) + ">" + "0" + hex(self.image_height)[2:] + "0" + hex(self.image_width)[2:] + str(''.join(self.strIMAGE)) + "<" + " " else: PARAM_STRING = " " + ">" + str(value_CRC) + ">" + hex(self.image_height)[2:] + hex(self.image_width)[2:] + str(''.join(self.strIMAGE)) + "<" + " " #print PARAM_STRING if(len(PARAM_STRING) > 0): for i in range(0,len(PARAM_STRING)): self.enviaCaracter(PARAM_STRING[i]) # Fechando conexao serial self.comport.close()
def download_fwu(comms, fw_file_name, args): with open(fw_file_name, mode='rb') as file: #crc = binascii.crc32(file.read()) % (1<<32) content = file.read() if content.encode('hex')[6:8] != "20" and not args.force: fail("The firmware file does not seem valid, use --force to force upgrade") crc = CRCCCITT().calculate(content) print("Crc: %x" % crc) ret_dict = communicate(comms, create_fwu_download_start(len(content), crc), args) if ret_dict["status"] == 1: chunk_size = 16 counter = 0 for chunk in chunk_from_file(fw_file_name, chunk_size): counter += len(chunk) sys.stdout.write("\rDownload progress: %d%% " % (counter*1.0/len(content)*100.0) ) sys.stdout.flush() # print(" %d bytes" % (counter)) ret_dict = communicate(comms, create_fwu_download_data(chunk), args) status = ret_dict["status"] if status == 1: pass else: print("") fail("device reported an unknown error (%d)" % status) else: fail("Device rejected FWU") sys.exit(os.EX_OK)
def input(self): inTime = True hello = self._readline().decode('utf-8') if len(hello) == 0: return ("", False, False, False) crcState = True crcString = "" if hello[0] != '<': print("!! start character error") if hello[-1] != '>': print("!! end character error") if self.crc != cmulti_crc_constants_t.noCRC: crcString = hello[-5:-1] signString = hello[-6:-5] answerString = hello[1:-5] if crcString == ("%04x" % (CRCCCITT().calculate(answerString))): crcState = True else: crcState = False print("!! CRC error") answerString = answerString[0:-1] # das sign abtrennen else: answerString = hello[1:-2] signString = hello[-2:-1] if signString == '.': return (answerString, True, crcState, inTime) elif signString == '!': return (answerString, False, crcState, inTime) else: print("!! sign character error") return (answerString, False, crcState, inTime)
def input(self): inTime = True hello = self._readline().decode('utf-8') if len(hello) == 0: return ("", False, False, False) crcState = True crcString = "" if hello[0] != '#': print("!! start character error") if hello[-1] != '\n': print("!! end character error") if self.crc != False: crcString = hello[-6:-2] signString = hello[8] answerString = hello[13:-6] toCheckString = hello[0:-6] if len(answerString) > 0: answerString = answerString[ 0:-1] # das Parameterendekennzeichen '>' abtrennen #print(crcString,"--",signString,"--",answerString,"--",toCheckString) if crcString == ("%04x" % (CRCCCITT().calculate(toCheckString))): crcState = True else: crcState = False print("!! CRC error") else: answerString = hello[1:-2] signString = hello[-2:-1] if signString == 'R': return (answerString, True, crcState, inTime) elif signString == 'r': return (answerString, False, crcState, inTime) else: print("!! sign character error") return (answerString, False, crcState, inTime)
def sendStandard_tty(self, text, target, function, address, job, dataType, expectAnswer=True): # Mqtt/Quelle/Function/Address/Job/Target/Datatype # 0 1 2 3 4 5 6 # 10DCQCPSC0l?510e # 11DCPCQA719<b570 st = 'D' + target + self.source + 'S' + function + address + job + dataType + text if dataType != '?': st = st + '<' l = len(st) + 6 st = "#%02x" % l + st crcString = ("%04x" % (CRCCCITT().calculate(st))) st = st + crcString + "\r\n" print(st) self.outputTTY(st) if expectAnswer: result, resultBool, resultCRC, inTime = self.input() return resultBool, result
def transport(self, data): data = chr(self.header) + data dataLength = len(data.encode('utf-8')) if self.crc == True: dataLength += 5 data = ("%02x" % (dataLength)) + data if self.crc == True: data = data + ("<%04x" % (CRCCCITT().calculate(data))) return (data)
def sendCommandTTY(self, command, parameter, expectAnswer=True): crcstring = ("%04x" % (CRCCCITT().calculate(command)) ) # ************************ if self.crc != cmulti_crc_constants_t.noCRC: self.outputTTY("\\>" + command + "<" + crcstring + "\\") else: self.outputTTY("\\>" + command + "<\\") result, resultBool, resultCRC, inTime = self.input() return (resultBool, result)
def calcCRC(data, little_endian=False): format_char = ">H" crc = CRCCCITT("FFFF").calculate(bytes(data)) if little_endian: format_char = "<H" b = bytearray(struct.pack(format_char, crc)) return b
def test_read_id_command_frame(self): read_id_command = [ 0x15, # length 0x00, # subnet 0x6a, # DLL control 0x20, # D7ANP control 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, # Origin Access ID 0xa8, # D7ATP control 0xe9, # dialog ID 0x00, # transaction ID 0x05, # Tl 0x05, # Tc 0x01, # ALP control (read file data operation) 0x00, 0x00, 0x08, # file data request operand (file ID 0x00) 0x25, 0xDA # CRC ] (frames, info) = self.parser.parse(read_id_command) self.assertEqual(len(frames), 1) frame = frames[0] self.assertEqual(frame.length, 21) self.assertEqual(frame.subnet, 0) self.assertEqual(frame.control.id_type, IdType.NOID) self.assertEqual(frame.control.eirp_index, 42) self.assertEqual(len(frame.target_address), 0) self.assertEqual(frame.d7anp_frame.control.nls_method, NlsMethod.NONE) self.assertFalse(frame.d7anp_frame.control.has_hopping) self.assertFalse(frame.d7anp_frame.control.has_no_origin_access_id) self.assertEqual(frame.d7anp_frame.control.origin_id_type, IdType.UID) self.assertEqual(frame.d7anp_frame.origin_access_class, 0x01) self.assertEqual(frame.d7anp_frame.origin_access_id, [0, 0, 0, 0, 0, 0, 0, 1]) self.assertTrue(frame.d7anp_frame.d7atp_frame.control.is_dialog_start) self.assertTrue(frame.d7anp_frame.d7atp_frame.control.has_tl) self.assertFalse(frame.d7anp_frame.d7atp_frame.control.has_te) self.assertTrue(frame.d7anp_frame.d7atp_frame.control.is_ack_requested) self.assertFalse(frame.d7anp_frame.d7atp_frame.control.is_ack_not_void) self.assertFalse(frame.d7anp_frame.d7atp_frame.control.is_ack_record_requested) self.assertFalse(frame.d7anp_frame.d7atp_frame.control.has_agc) self.assertEqual(frame.d7anp_frame.d7atp_frame.dialog_id, 0xe9) self.assertEqual(frame.d7anp_frame.d7atp_frame.transaction_id, 0) self.assertEqual(frame.d7anp_frame.d7atp_frame.tl.exp, CT(exp=0, mant=5).exp) self.assertEqual(frame.d7anp_frame.d7atp_frame.tl.mant, CT(exp=0, mant=5).mant) self.assertEqual(frame.d7anp_frame.d7atp_frame.tc.exp, CT(exp=0, mant=5).exp) self.assertEqual(frame.d7anp_frame.d7atp_frame.tc.mant, CT(exp=0, mant=5).mant) self.assertEqual(len(frame.d7anp_frame.d7atp_frame.alp_command.actions), 1) alp_action = frame.d7anp_frame.d7atp_frame.alp_command.actions[0] self.assertEqual(type(alp_action.operation), ReadFileData) self.assertEqual(type(alp_action.operand), DataRequest) self.assertEqual(alp_action.operand.offset.id, 0) self.assertEqual(alp_action.operand.offset.offset.value, 0) self.assertEqual(alp_action.operand.length, 8) # TODO self.assertEqual(len(frame.payload), 16) hexstring = binascii.hexlify(bytearray(read_id_command[:-2])).decode('hex') # TODO there must be an easier way... self.assertEqual(frame.crc16, CRCCCITT(version='FFFF').calculate(hexstring))
def verify_ens_data(ens_data, ens_start=0): """ This will check the checksum and verify it is correct. :param ens_data: Ensemble data. :param ens_start: Start location in the ens_data """ try: # Ensemble Length ens_len = len(ens_data) # Verify at least the minimum number of bytes are available to verify the ensemble if ens_len <= Ensemble().HeaderSize + Ensemble().ChecksumSize: return False # Check Ensemble number ens_num = struct.unpack("I", ens_data[ens_start + 16:ens_start + 20]) # Check ensemble size payload_size = struct.unpack( "I", ens_data[ens_start + 24:ens_start + 28]) # Ensure the entire ensemble is in the buffer if ens_len >= ens_start + Ensemble( ).HeaderSize + payload_size[0] + Ensemble().ChecksumSize: # Check checksum checksum_loc = ens_start + Ensemble( ).HeaderSize + payload_size[0] checksum = struct.unpack( "I", ens_data[checksum_loc:checksum_loc + Ensemble().ChecksumSize]) # Calculate Checksum # Use only the payload for the checksum ens = ens_data[ens_start + Ensemble().HeaderSize:ens_start + Ensemble().HeaderSize + payload_size[0]] calc_checksum = CRCCCITT().calculate(input_data=bytes(ens)) # Verify checksum if checksum[0] == calc_checksum: logging.debug(ens_num[0]) return True else: return False else: #logging.warning("Not a complete ensemble.") return False except Exception as e: logging.error("Error verifying Ensemble. " + str(e)) return False return False
def getSSNPDU(self): try: crc = CRCCCITT(version="FFFF").calculate(self.msgData) buf = "{}{:04x}{:04x}{:02x}{:04x}{}{:04x}".format(cSSNSTART,self.destObj,\ self.srcObj, self.msgType, len(self.msgData), self.msgData, crc) # self.srcObj,self.msgType,len(self.msgData),self.msgData,crc16.crc16xmodem(self.msgData, 0xffff)) except Exception, e: print >> sys.stderr, "\ndest_obj: "+str(self.destObj)+" src_obj: " + str(self.srcObj) + " msgType: "\ +str(self.msgType)+ "CRC: ", + crc + " MSG: "+self.msgData print >> sys.stderr, "Error generating SSN PDU: " + str(e) buf = ""
def decode_ensemble(self, ensStart): """ Decode the raw ensemble data. This will check the checksum and verify it is correct, then decode each datasets. Then remove the data from the buffer. :param ensStart: Stare of the ensemble in the buffer. """ # Check Ensemble number ensNum = struct.unpack("I", self.buffer[ensStart + 16:ensStart + 20]) #logger.debug(print(ensNum[0])) #print(self.ones_complement(ensNumInv[0])) # Check ensemble size payloadSize = struct.unpack("I", self.buffer[ensStart + 24:ensStart + 28]) #print(payloadSize[0]) #payloadSizeInv = struct.unpack("I", self.buffer[ensStart+28:ensStart+32]) #print(self.ones_complement(payloadSizeInv[0])) # Ensure the entire ensemble is in the buffer if len(self.buffer) >= ensStart + Ensemble( ).HeaderSize + payloadSize[0] + Ensemble().ChecksumSize: # Check checksum checksumLoc = ensStart + Ensemble().HeaderSize + payloadSize[0] checksum = struct.unpack( "I", self.buffer[checksumLoc:checksumLoc + Ensemble().ChecksumSize]) # Calculate Checksum # Use only the payload for the checksum ens = self.buffer[ensStart + Ensemble().HeaderSize:ensStart + Ensemble().HeaderSize + payloadSize[0]] calcChecksum = CRCCCITT().calculate(input_data=bytes(ens)) #print("Calc Checksum: ", calcChecksum) #print("Checksum: ", checksum[0]) #print("Checksum good: ", calcChecksum == checksum[0]) if checksum[0] == calcChecksum: logger.debug(ensNum[0]) try: # Decode data ensemble = self.decode_data_sets( self.buffer[ensStart:ensStart + Ensemble().HeaderSize + payloadSize[0]]) # ************************ self.process_ensemble(ensemble) except Exception as e: logger.error("Error decoding ensemble. ", e) # Remove ensemble from buffer ensEnd = ensStart + Ensemble( ).HeaderSize + payloadSize[0] + Ensemble().ChecksumSize del self.buffer[0:ensEnd]
def make_block(filename: str, lda, exa, blkn, prot, empt, lblk, data): data_len = len(data) out = bytearray() out.extend(filename.encode()) out.append(0) out.extend(struct.pack("<L", lda)) out.extend(struct.pack("<L", exa)) out.extend(struct.pack("<H", blkn)) out.extend(struct.pack("<H", data_len)) out.append((1 & prot) + ((1 & empt) << 6) + ((1 & lblk) << 7)) out.extend([0, 0, 0, 0]) crc = CRCCCITT().calculate(bytes(out)) out.extend(struct.pack(">H", crc)) data_crc = CRCCCITT().calculate(bytes(data)) out.extend(data) out.extend(struct.pack(">H", data_crc)) return bytearray([0x2A]) + out
def on_message(client, userdata, msg): sep = msg.topic.split('/') st = 'D' + sep[5] + sep[1] + 'S' + sep[2] + sep[3] + sep[4] + sep[6] + ( msg.payload).decode('ascii') if sep[6] != '?': st = st + '<' l = len(st) + 6 st = "#%02x" % (l) + st crcString = ("%04x" % (CRCCCITT().calculate(st))) st = st + crcString + "\r\n" CmultiServer.write(st.encode('utf-8')) print("Write to CMultiServer: " + st)
def packFile(self): if self.filename == '': #print('file name is NUll') messagebox.showinfo('ERROR', '文件名为空\n file name is NULL') else: #print(self.filename) #创建新文件 if self.packFileNameSet.get() == '': onlyFileName = os.path.split(self.filename)[1] packFileName = onlyFileName + '.ry' #packFileObject = open(os.path.join(self.packFilePath,packFileName), 'wb') else: packFileName = self.packFileNameSet.get() + '.ry' packFileObject = open( os.path.join(self.packFilePath, packFileName), 'wb') #设置文件头部 #1.文件大小 fileObject = open(self.filename, 'rb') fileSize = fileObject.seek(0, os.SEEK_END) #print(fileSize) #tempbuf = buffer(self.fileHeaderBuf, 0, 4) packFileObject.write(bytes((c_uint32(fileSize)))) #2.设置数据起始位置 packFileObject.write(bytes((c_uint32(self.dataStartAddr)))) #3.设置类型 self.fileType = self.fileTypeitem[self.fileTypeSelection.get()] packFileObject.write(bytes((c_uint32(self.fileType)))) #4.设置CRC校验 fileObject.seek(0, os.SEEK_SET) self.crcValue = int(CRCCCITT().calculate(fileObject.read())) print(self.crcValue) if self.crcEnable.get() == TRUE: pass #进行CRC校验 packFileObject.write(bytes((c_uint32(self.crcValue)))) #5.设置版本号 self.getVersionNumber() packFileObject.write(bytes((c_uint32(self.versionNumber)))) #6.设置保留位 for x in range(self.reserveDataSize): packFileObject.write(b'0') #7.写入数据 fileObject.seek(0, os.SEEK_SET) packFileObject.write(fileObject.read())
def _validate_payload(payload, footer): """ Validates the payload using the footer. CorruptPacket is raised if the payload is corrupt or the terminator is not correct. :param payload: byte string :param footer: Footer object :return: void """ if CRCCCITT().calculate(payload) != footer.crc: raise CorruptPacket("Invalid checksum value.") if footer.terminator is not Footer.TERMINATOR: raise CorruptPacket("Invalid terminator: %u" % footer.terminator) return
def compute_checksum(self, header_block=None): """Compute checksum of header block. If header_block is None, it operates on the file on disk (pointed to by self.filename). Keyword arguments: header_block -- a bytes object containing the ISHNE header (typically bytes 10-522 of the file) """ if header_block == None: with open(self.filename, 'rb') as f: f.seek(10, os.SEEK_SET) header_block = np.fromfile(f, dtype=np.uint8, count=self.ecg_block_offset-10) header_block = header_block.tostring() # to make it a bytes object return np.uint16( CRCCCITT(version='FFFF').calculate(header_block) )
def crc(self, in_crc=None): """ Calculates the checksum of a given frame, if a checksum is given as parameter, the two are compared. :param in_crc: :return: int """ if self.CRC is None: self.CRC = CRCCCITT().calculate(input_data=self.compose(part=True)) # crc check # print(self.CRC) # print(in_crc) if in_crc is not None and in_crc != self.CRC: raise WrongChecksum
def run_upgrade(comms, fw_file_name, args): """ Run OpenDPS firmware upgrade """ with open(fw_file_name, mode='rb') as file: # crc = binascii.crc32(file.read()) % (1<<32) content = file.read() if codecs.encode(content, 'hex')[6:8] != b'20' and not args.force: fail( "The firmware file does not seem valid, use --force to force upgrade" ) crc = CRCCCITT().calculate(content) chunk_size = 1024 ret_dict = communicate(comms, create_upgrade_start(chunk_size, crc), args) if ret_dict["status"] == protocol.UPGRADE_CONTINUE: if chunk_size != ret_dict["chunk_size"]: print("Device selected chunk size {:d}".format( ret_dict["chunk_size"])) chunk_size = ret_dict["chunk_size"] counter = 0 for chunk in chunk_from_file(fw_file_name, chunk_size): counter += len(chunk) sys.stdout.write("\rDownload progress: {:d}% ".format( int(counter / len(content) * 100))) sys.stdout.flush() # print(" {:d} bytes".format(counter)) ret_dict = communicate(comms, create_upgrade_data(chunk), args) status = ret_dict["status"] if status == protocol.UPGRADE_CONTINUE: pass elif status == protocol.UPGRADE_CRC_ERROR: print("") fail("device reported CRC error") elif status == protocol.UPGRADE_ERASE_ERROR: print("") fail("device reported erasing error") elif status == protocol.UPGRADE_FLASH_ERROR: print("") fail("device reported flashing error") elif status == protocol.UPGRADE_OVERFLOW_ERROR: print("") fail("device reported firmware overflow error") elif status == protocol.UPGRADE_SUCCESS: print("") else: print("") fail("device reported an unknown error ({:d})".format(status)) else: fail("Device rejected firmware upgrade")
def get(self,file_name,save_name=None): '''get a file from the device and save it locally''' filename = file_name.split('/') file_exist = False if filename[1] == 'default' : for i in self.dir_default: if filename[2] == i[3]: file_exist = True file_size=i[1] break if file_exist != True: return file_name + " not found" try: transaction_id = struct.pack('>I',random.randint(0,0xffffffff)) block_size = self.storage['get_size'] header = transaction_id + struct.pack('>I', block_size) total_blocks = math.ceil(file_size / block_size) self.pub('sensiml/storage/get/start' ,header + file_name.encode(), 1) self.resp() if save_name == None: save_name = filename[2] with open(save_name,'wb') as file: for i in range(total_blocks): block_number = struct.pack('>I', i) self.pub( 'sensiml/storage/get/data/req', transaction_id + block_number , 1) time.sleep(0.5) while self.rec_queue.empty() == False: temp =self.rec_queue.get() (self.actual_size, self.crc16) = struct.unpack('>HH',temp.payload[8:12]) self.header = temp.payload[:12] self.byte_buffer = temp.payload[12:(12+self.actual_size)] if DEBUG == True: print('CRC size: ',self.actual_size, ' crc: ', self.crc16) print(self.header,self.byte_buffer) print(temp.payload) if transaction_id != temp.payload[0:4]: raise Exception('id error') if block_number != temp.payload[4:8]: raise Exception('block number error') if self.crc16 != CRCCCITT().calculate(self.byte_buffer): raise Exception(f'block {block_number} CRC16 error {self.crc16}') file.write(self.byte_buffer) # self.pub('sensiml/storage/get/stop', transaction_id,1) # self.resp() except Exception as err: print(str(err.args)) self.pub('sensiml/storage/get/stop', transaction_id,1) self.resp()
def interprete(data): data = data.decode("utf-8") if data[0] == "#" and data[-2:] == "\r\n": num = int(tdata[2:4], 16) coreData = data[4:-2] if len(coreData.encode('utf-8')) == num: if ord(coreData[0]) & CRC: crc = CRCCCITT().calculate(data[2:-7]) if crc == int(data[-6:-2], 16): print(coreData) else: print("CRC nicht in Ordnung") else: print("Datenlänge passt nicht") else: print("Anfangs- oder Endekennung fehlerhaft")
def lerEntrada(self): # Iniciando conexao serial self.comport = serial.Serial(self.listaPortas[0], self.comboBox1.currentText(), timeout=0.2, write_timeout=0.2) #PARAM_STRING="Ola como vai? Oi estou bem, e voce?" #recebe a entrada value_CRC = CRCCCITT().calculate(str(self.lineEdit1.text())) #calculando valor CRC if(self.checkBox6.isChecked()): PARAM_STRING = " " + ">" + str(value_CRC) + ">" + str(''.join(self.lista_ASCII_error)) + "<" + " " else: PARAM_STRING = " " + ">" + str(value_CRC) + ">" + str(self.lineEdit1.text()) + "<" + " " if(len(PARAM_STRING) > 0): for i in range(0,len(PARAM_STRING)): self.enviaCaracter(PARAM_STRING[i]) # Fechando conexao serial self.comport.close()
def run_upgrade(comms, fw_file_name, args): with open(fw_file_name, mode='rb') as file: #crc = binascii.crc32(file.read()) % (1<<32) content = file.read() if content.encode('hex')[6:8] != "20" and not args.force: fail( "The firmware file does not seem valid, use --force to force upgrade" ) crc = CRCCCITT().calculate(content) chunk_size = 1024 ret_dict = communicate(comms, create_upgrade_start(chunk_size, crc), args) if ret_dict["status"] == upgrade_continue: if chunk_size != ret_dict["chunk_size"]: print("Device selected chunk size %d" % (ret_dict["chunk_size"])) chunk_size = ret_dict["chunk_size"] counter = 0 for chunk in chunk_from_file(fw_file_name, chunk_size): counter += len(chunk) sys.stdout.write("\rDownload progress: %d%% " % (counter * 1.0 / len(content) * 100.0)) sys.stdout.flush() # print(" %d bytes" % (counter)) ret_dict = communicate(comms, create_upgrade_data(chunk), args) status = ret_dict["status"] if status == upgrade_continue: pass elif status == upgrade_crc_error: print("") fail("device reported CRC error") elif status == upgrade_erase_error: print("") fail("device reported erasing error") elif status == upgrade_flash_error: print("") fail("device reported flashing error") elif status == upgrade_overflow_error: print("") fail("device reported firmware overflow error") elif status == upgrade_success: print("") else: print("") fail("device reported an unknown error (%d)" % status) else: fail("Device rejected firmware upgrade") sys.exit(os.EX_OK)
def send(self, text, target, infoHeader, function, address, job, datatype): if self.crc == False: lengthMsg = len(text) + 10 else: lengthMsg = len(text) + 14 if ((infoHeader == 'S') | (infoHeader == 'R') | (infoHeader == 'r')): lengthMsg += 3 extraInfo = "{}{}{}{}".format(function, address, job, datatype) else: extraInfo = "" if len(text) > 0: text += "<" toSend = "#{0:02x}{1:s}{2:s}{3:s}{4:s}{5:s}{6:s}".format( lengthMsg, self.header, target, self.source, infoHeader, extraInfo, text) crcString = ("%04x" % (CRCCCITT().calculate(toSend))) toSend += crcString + "\r\n" #print(toSend) self.outputTTY(toSend)
def _read(self, cmd, fmt): cmd_bytes = struct.pack('>BB', self.address, cmd) try: # self.port.reset_input_buffer() # TODO: potential bug? with self.serial_lock: self.port.write(cmd_bytes) return_bytes = self.port.read(struct.calcsize(fmt) + 2) crc_actual = CRCCCITT().calculate(cmd_bytes + return_bytes[:-2]) crc_expect = struct.unpack('>H', return_bytes[-2:])[0] if crc_actual != crc_expect: logger.error('read crc failed') raise CRCException('CRC failed') return struct.unpack(fmt, return_bytes[:-2]) except serial.serialutil.SerialException: if self.auto_recover: self.recover_serial() else: logger.exception('roboclaw serial') raise
def _write(self, cmd, fmt, *data): cmd_bytes = struct.pack('>BB', self.address, cmd) data_bytes = struct.pack(fmt, *data) write_crc = CRCCCITT().calculate(cmd_bytes + data_bytes) crc_bytes = struct.pack('>H', write_crc) try: with self.serial_lock: self.port.write(cmd_bytes + data_bytes + crc_bytes) self.port.flush() verification = self.port.read(1) if 0xff != struct.unpack('>B', verification)[0]: logger.error('write crc failed') raise CRCException('CRC failed') except serial.serialutil.SerialException: if self.auto_recover: self.recover_serial() else: logger.exception('roboclaw serial') raise
def create_msg(frame_type, payload): index = 0 crc = 0 count = 0 # Determine the payload size packet_frame_length = 0 if not payload: packet_frame_length = len(payload) # Get the number of bytes count = packet_frame_length + PACKET_MIN_SIZE # Create a buffer buffer = [None]*count # Store the total len of the packet including the len # byteCount (2), the Frame ID (1), the data (len(data)), and the crc (2) # If no data is sent, the min len is 5 buffer[index] = count >> 8 index += 1 buffer[index] = count & 0xff index += 1 # Store the frame ID buffer[index] = frame_type # Add the payload if not payload: for i in range(payload): buffer[index] = payload[i] index += 1 # Compute the CRC crc = CRCCCITT().calculate(input_data=bytes(buffer)) buffer[index] = crc >> 8 index += 1 buffer[index] = crc & 0xFF index += 1
def read_data(): logger.info("Weather.Reader: Read Data") if initialize_communication(): DEVICE.write('LOOP 1\n') if DEVICE.read(2)[-1] == ACK: logger.info("Weather.Reader: Device ACK") data = DEVICE.read(99) if CRCCCITT().calculate(data) == 0: logger.info( "Weather.Reader: CRC is valid: {data}".format(data=data)) return Weather(data) else: logger.warning("Weather.Reader: CRC not valid") else: logger.warning("Weather.Reader: Device don't ACK") else: logger.warning('Weather.Reader: Initialization failed') return None