def save_changes(self): new_hex = IntelHex() new_hex.fromdict(self.get_table_dict()) save_filename = QtGui.QFileDialog.getSaveFileName(self, NAME+" - Save", os.path.join(QtCore.QDir.home().path(), self.original_filename.replace(".hex", "_copy.hex")), "Hex files (*.hex;;All Files (*)") if save_filename: new_hex.write_hex_file(save_filename[0])
def save_changes(self): new_hex = IntelHex() new_hex.fromdict(self.get_table_dict()) save_filename = QtGui.QFileDialog.getSaveFileName( self, NAME + " - Save", os.path.join(QtCore.QDir.home().path(), self.original_filename.replace(".hex", "_copy.hex")), "Hex files (*.hex;;All Files (*)") if save_filename: new_hex.write_hex_file(save_filename[0])
def test_read_flash_hex_non_zero_address(mock_read_flash): """Test read_flash_hex() with given address and count.""" data_bytes = bytes([x for x in range(128)]) data_dict = {x + 1024: x for x in range(256)} intel_hex = IntelHex() intel_hex.fromdict(data_dict) ihex_str = ihex_to_str(intel_hex) # Remove the last 128 bytes, 8 lines, 9 with EoF ihex_str = "\n".join(ihex_str.split()[:-9] + [INTEL_HEX_EOF]) mock_read_flash.return_value = (1024, data_bytes) result = cmds.read_flash_hex(address=1024, count=128) assert result == ihex_str
class HexTruth: #Class which takes a dict or CSV file and converts it into an Intel Hex file for ROM burning. def __init__(self, csvFilename, loadDict = None, hexFilename=None ): if hexFilename is None: hexFilename = csvFilename.split(".")[0]+ ".hex" self.csvFilename = csvFilename self.hexFilename = hexFilename self.ih= IntelHex() self.hexDict = {}; if loadDict is not None: self.hexDict = loadDict self.ih.fromdict(loadDict) self.writeFromIntelHex() def writeFromIntelHex(self): #Takes the IntelHex object and writes it to a hex file. f = open(self.hexFilename, 'w'); self.ih.write_hex_file(f) f.close() print("Hex file generated.") def importCSV(self): #Opens a given csv filename and returns it's values as a list of lists. #list of lists = rows of columns self.csvTruth = [] with open(self.csvFilename, newline='') as csvfile: csvReadingMachine = csv.reader(csvfile, delimiter=',', quotechar='"') for row in csvReadingMachine: self.csvTruth.append(row) if "#" in str(row):continue [addr, dat] = str(row).split("''") rangeIn = [0, addr.count(',') -1] if dat.count(",") is 1: rangeOut = [rangeIn[-1] + 2] else:rangeOut = [rangeIn[-1] + 2, rangeIn[-1] + 1 + dat.count(",")] binaryString = "" for j in range(rangeIn[0], rangeIn[-1] + 1): binaryString+=str(row[j]) #address = binaryString address = (int(binaryString,2)) binaryString = "" for j in range(rangeOut[0], rangeOut[-1] + 1): binaryString+=str(row[j]) #data = binaryString; data = (int(binaryString,2)) #print(str(address) + ":" + str(data)) self.hexDict[address] = data #print(row) return self.hexDict
def encrypt(): tmp=open(bootloader_dir+bootloaderName+"_encrypted.hex","w+"); ih=IntelHex(bootloader_dir+bootloaderName+".hex"); keyPos=0; dictionary=ih.todict(); addresses=dictionary.keys(); pages=-1; for b in addresses: #print hex(p)+":"+hex(dictionary[p]); if (b!="start_addr") and b>=initAddr and b<endAddr: #print b,hex(b); if (b%PAGE_SIZE)==0: pages=pages+1; keyPos=0 print; print; print "PAGE ",pages; print hex(b)+":"+hex(dictionary[b])+"^"+hex(key[keyPos])+"=", dictionary[b]=dictionary[b]^key[keyPos] print hex(dictionary[b])+" ", keyPos=keyPos+1; ih.fromdict(dictionary); ih.write_hex_file(tmp);
def main(argv): # Interpret parameters sensorConfig = "" hexFile = "../../build/artifacts/smartsensor_fw/opt/smartsensor_fw.hex" helpText = (argv[0] if len(argv)>0 else "generate.py") + \ " [-d] [-i <hex-file>] <sensor-type>" helpMore = "Supported sensor types:\n\t" + ", ".join(ss_type.allTypes()) try: opts, args = getopt.getopt(argv[1:],"hdi:") except getopt.GetoptError: print helpText sys.exit(2) for opt, arg in opts: if opt == '-h': print helpText print helpMore sys.exit() elif opt == "-i": hexFile = arg elif opt == "-d": if len(args)>0: try: ss_type.descriptor(args[0]) sys.exit(0) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) else: sys.exit("Enter a sensor type\n"+helpMore) if len(args)==0: print helpText print helpMore sys.exit(2) else: sensorConfig = args[0] try: descriptor = ss_type.descriptor(sensorConfig) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) # Decide the new sensor's ID try: firstType = descriptor["channels"][0]["type"] except IndexError: firstType = 0xFF # TODO(nikita): Proper ID generation idNew = array('B', [0, 0, 0, 0, 0, firstType, random.randint(0,255), random.randint(0,255), firstType]) # Create the new sensor's descriptor channelsStr = b"" for channel in descriptor["channels"]: # Pack each channel packer = struct.Struct( "<B%upB%us"%(len(channel["description"])+1,len(channel["additional"]))) channelsStr += packer.pack( packer.size, channel["description"], channel["type"], channel["additional"].tostring()) packer = struct.Struct( "<H%upBBB%usB"%(len(descriptor["description"])+1,len(channelsStr))) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, 0xC8) crc = crc8(0, array('B', descriptorStr)) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, crc) descriptorNew = array('B', descriptorStr) # Write the ID and descriptor to the hex file descriptorPlaceholder = \ b"Do not change this string. It is a placeholder that is replaced in the " + \ b"compiled hex file when the deploy script is run." idPlaceholder = "SENSORID" ih = IntelHex(hexFile) ihDict = ih.todict() ihArr = array('B', [ihDict[key] for key in sorted(ihDict)]) ihString = ihArr.tostring() try: descriptorIndex = ihArr.tostring().index(descriptorPlaceholder) except ValueError: sys.exit('Error: Descriptor placeholder not found in hex file.') try: idIndex = ihArr.tostring().index(idPlaceholder) except ValueError: sys.exit('Error: ID placeholder not found in hex file.') descriptorDict = {descriptorIndex+i: descriptorNew[i] for i in range(len(descriptorNew))} idDict = {idIndex+i: idNew[i] for i in range(len(idNew))} ihDict = dict(ihDict.items()+descriptorDict.items()+idDict.items()) newIh = IntelHex() newIh.fromdict(ihDict) newIh.tofile(sys.stdout, format='hex') # Print new hex file to stdout
if read_buffer is None: exit_by_error(msg="reading flash memory") if args.update: if read_buffer != ih.tobinarray(start=address, size=ab.cpu_page_size): exit_by_error(msg="file not match") elif args.read: for i in range(0, ab.cpu_page_size): dict_hex[address + i] = read_buffer[i] bar.update(address) bar.finish() if args.read: dict_hex["start_addr"] = 0 ih.fromdict(dict_hex) try: ih.tofile(args.filename, 'hex') except FileNotFoundError: exit_by_error(msg="the file cannot be created") print("\nflash done, thank you") prg.leave_bootloader() prg.close() else: print("error, could not connect with arduino board - baudrate: {}".format( args.baudrate))
def main(argv): # Interpret parameters sensorConfig = "" hexFile = "../../build/artifacts/smartsensor_fw/opt/smartsensor_fw.hex" helpText = (argv[0] if len(argv)>0 else "generate.py") + \ " [-d] [-i <hex-file>] <sensor-type>" helpMore = "Supported sensor types:\n\t" + ", ".join(ss_type.allTypes()) try: opts, args = getopt.getopt(argv[1:],"hdi:") except getopt.GetoptError: print helpText sys.exit(2) for opt, arg in opts: if opt == '-h': print helpText print helpMore sys.exit() elif opt == "-i": hexFile = arg elif opt == "-d": if len(args)>0: try: ss_type.descriptor(args[0]) sys.exit(0) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) else: sys.exit("Enter a sensor type\n"+helpMore) if len(args)==0: print helpText print helpMore sys.exit(2) else: sensorConfig = args[0] try: descriptor = ss_type.descriptor(sensorConfig) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) # Decide the new sensor's ID try: firstType = descriptor["channels"][0]["type"] if firstType == 0xFE: firstType = descriptor["channels"][1]["type"] except IndexError: firstType = 0xFF # TODO(nikita): Proper ID generation idNew = array('B', [0, 0, 0, 0, 0, firstType, random.randint(0,255), random.randint(0,255), firstType]) # Create the new sensor's descriptor channelsStr = b"" for channel in descriptor["channels"]: # Pack each channel packer = struct.Struct( "<B%upB%us"%(len(channel["description"])+1,len(channel["additional"]))) channelsStr += packer.pack( packer.size, channel["description"], channel["type"], channel["additional"].tostring()) packer = struct.Struct( "<H%upBBB%usB"%(len(descriptor["description"])+1,len(channelsStr))) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, 0xC8) crc = crc8(0, array('B', descriptorStr)) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, crc) descriptorNew = array('B', descriptorStr) # Write the ID and descriptor to the hex file descriptorPlaceholder = \ b"Do not change this string. It is a placeholder that is replaced in the " + \ b"compiled hex file when the deploy script is run." idPlaceholder = "SENSORID" ih = IntelHex(hexFile) ihDict = ih.todict() ihArr = array('B', [ihDict[key] for key in sorted(ihDict)]) ihString = ihArr.tostring() try: descriptorIndex = ihArr.tostring().index(descriptorPlaceholder) except ValueError: sys.exit('Error: Descriptor placeholder not found in hex file.') try: idIndex = ihArr.tostring().index(idPlaceholder) except ValueError: sys.exit('Error: ID placeholder not found in hex file.') descriptorDict = {descriptorIndex+i: descriptorNew[i] for i in range(len(descriptorNew))} idDict = {idIndex+i: idNew[i] for i in range(len(idNew))} ihDict = dict(ihDict.items()+descriptorDict.items()+idDict.items()) newIh = IntelHex() newIh.fromdict(ihDict) newIh.tofile(sys.stdout, format='hex') # Print new hex file to stdout idStr = '' for i, b in zip(range(len(idNew)), idNew.tolist()): if i < len(idNew)-1: idStr += '%02X' % b sys.stderr.write('Sensor ID: ' + idStr + '\n')