Example #1
0
 def load_image(self, path):
     retst = True
     self.data_buffer = bytearray()
     if path.lower().endswith(".bin"):
         with open(path, "rb") as f:
             self.data_buffer = f.read()
             f.close()
     elif path.lower().endswith(".hex"):
         ihex = IntelHex()
         try:
             ihex.loadfile(path, format="hex")
         except Exception as e:
             wx.MessageBox("Could not read from file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             dhex = ihex.todict()
             self.data_buffer = bytearray([0xFF] * (max(dhex.keys()) + 1))
             for i, val in dhex.items():
                 self.data_buffer[i] = val
     elif path.lower().endswith((".s19", ".srec")):
         srec = SRecFile()
         try:
             srec.open(path)
         except Exception as e:
             wx.MessageBox("Could not read from file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             self.data_buffer = srec.data
     else:
         retst = False
         wx.MessageBox("Not supported file Type !", "ERROR", wx.OK | wx.ICON_ERROR)
     return retst
    def test_hex(self):
        # IntelHex library is used to check correctness of the function
        # load_hex_file_to_dict()
        from intelhex import IntelHex

        import pprint
        here = os.path.dirname(os.path.abspath(__file__))

        f = 'Master_Tinting-boot-nodipswitch.hex'

        fn = os.path.join(here, f)

        print("loading mplab table...")
        dict1 = HexUtils.load_mplab_table(
            os.path.join(here, 'TABLE_from_MPLAB_IPE.txt'))

        with open(fn, 'r') as f:
            file_content = f.read()

            print("loading hex with IntelHex lib...")
            ih = IntelHex()
            ih.loadhex(fn)
            dict2 = ih.todict()

            print("loading hex with my funct...")
            dict3 = HexUtils.load_hex_to_dict(file_content)

            print("converting arrays...")
            array1 = HexUtils.dict_to_array(dict1, len(dict1))
            array2 = HexUtils.dict_to_array(dict2, len(dict1))
            array3 = HexUtils.dict_to_array(dict3, len(dict1))

            assert array1 == array2
            assert array2 == array3
Example #3
0
def load_hex(firmwareFile, keystr, portName):
    if keystr is None:
        key = None
    else:
        key = binascii.unhexlify(keystr)

    print('Reading target file: "%s"' % firmwareFile)
    if os.path.isfile(firmwareFile):
        ih = IntelHex(firmwareFile)
    else:
        raise Exception('Target file is not exists "%s"' % firmwareFile)

    hexItems = ih.todict()

    print('Start address: 0x%08x' % ih.minaddr())
    print('End address: 0x%08x' % ih.maxaddr())
    print('Total code size: %u bytes' % (len(hexItems) - 1))
    client = BootInit(portName)
    Connect(client)

    print('Device name: %s' % GetDeviceName(client))
    print('CPU name: %s' % GetMcuName(client))
    print('MCU ID: %x' % GetMcuId(client))
    print('Bootloader version: %d' % GetBootVersionCount(client))
    pageCount = GetPageCount(client)
    print('Flash page count: %u (%u)' % pageCount)
    print('Total Flash size: %u' % (GetFlashSize(client)))

    # for i in range(0, pageCount[0]):
    # 	pageSize = GetPageSize(client, i)
    # 	print ("page %i size = %i" % (i, pageSize))

    page = 0
    pageSize = GetPageSize(client, page)
    pageEnd = GetPageAddress(client, page) + pageSize
    pageData = []

    for addr, value in hexItems.items():
        if not isinstance(addr, int):
            continue
        while addr >= pageEnd:
            if len(pageData) > 0:
                BootPrettyWritePage(client, pageData, page, 0, key)
            page += 1
            pageSize = GetPageSize(client, page)
            pageEnd = GetPageAddress(client, page) + pageSize
            pageData = []
        pageData.append(value)

    # align data to be written on 8 byte boundary
    align = (8 - (len(pageData) & 7)) & 7
    for i in range(align):
        pageData.append(0)

    # write last page
    BootPrettyWritePage(client, pageData, page, 0, key)
    print("Success")
    print("Reseting system")
    Reset(client)
Example #4
0
    def writeImage(self, filename):
        #Sends an CMD_WRITE to the bootloader
        #This is method is a generator, that returns its progresses to the caller.
        #In this way, it's possible for the caller to live-print messages about
        #writing progress
        ih = IntelHex()
        ih.loadhex(filename)
        yield {"saddr": ih.minaddr(), "eaddr": ih.maxaddr()}
        global sad
        addr = ih.minaddr()
        sad = addr
        content = ih.todict()
        abort = False
        resend = 0
        while addr <= ih.maxaddr():
            if not resend:
                data = []
                saddr = addr
                for i in range(16):
                    try:
                        data.append(content[addr])
                    except KeyError:
                        #if the HEX file doesn't contain a value for the given address
                        #we "pad" it with 0xFF, which corresponds to the erase value
                        data.append(0xFF)
                    addr += 1
            try:
                if resend >= 3:
                    abort = True
                    break

                self.serial.flushInput()
                self.serial.write(
                    self._create_cmd_message(
                        [CMD_WRITE] + map(ord, struct.pack("I", saddr))))
                ret = self.serial.read(1)
                if len(ret) == 1:
                    if struct.unpack("b", ret)[0] != ACK:
                        raise ProgramModeError("Write abort")
                else:
                    raise TimeoutError("Timeout error")
                encdata = data  # self._encryptMessage(data)
                self.serial.flushInput()
                self.serial.write(self._create_cmd_message(data))
                ret = self.serial.read(1)
                if len(ret) == 1:
                    if struct.unpack("b", ret)[0] != ACK:
                        raise ProgramModeError("Write abort")
                else:
                    raise TimeoutError("Timeout error")

                yield {"loc": saddr, "resend": resend}
                resend = 0
            except (TimeoutError, ProgramModeError):
                resend += 1

        yield {"success": not abort}
Example #5
0
def firmware_upload(i2c_addr, filename, size, log):
        global total_retries_count
	ih = IntelHex()
	ih.loadhex(filename)
	ihd = ih.todict()     # dump contents to pydict
	skiprange = False
	for a in range(0,size, flash_write_block*2): # PIC16F
		skiprange = True
		for aa in range(a,a+flash_write_block*2):
			if aa in ihd:
				skiprange = False
		if skiprange:
			continue;
                # only 14bit data with leading high byte, mask unused bits away, if hex file had no entry for some byte them, put zeres
                d = [(ihd[aa] if aa in ihd else 0) for aa in range(a,a+flash_write_block*2)]
		
		aw = a/2 # config space is mapped AS-IS

		if aw >= 0x8000: # skip programming of config space
			continue;
                if aw >= 0x4000:
                        raise IOError('hex file is too large to fit into memory range')

		if aw < 0x80000: # skip programming of config space
			print >>log, "programming block @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in d))
			_flash_upload(i2c_addr, aw, [c for c in d])		
		aw += flash_write_block

        skiprange = False
        for a in range(0,size, flash_write_block*2): # PIC16F
                skiprange = True
                for aa in range(a,a+flash_write_block*2):
                        if aa in ihd:
                                skiprange = False
                if skiprange:
                        continue;
		# only 14bit data with leading high byte, mask unused bits away, if hex file had no entry for some byte them, put zeres
                d = [(ihd[aa] if aa in ihd else 0) & 0x3f if a % 2 == 1 else (ihd[aa] if aa in ihd else 0)  for aa in range(a,a+flash_write_block*2)]

                aw = a/2 # config space is mapped AS-IS
		if aw >= 0x8000:
			# skip verification of config space
			continue

                print >>log, "verifying block (expected) @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in d)),
		dd = _flash_download(i2c_addr, aw)
		#print "verifying block (actual  ) @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in dd))
                aw += flash_write_block		
		for av in range(a,a+flash_write_block*2,2):
			if (av in ihd) and ((dd[av - a] != d[av - a]) or dd[av - a + 1] & 0x3f != d[av - a + 1]):
				fa = aw-flash_write_block + av/2				
				raise IOError("device flash data is different from expected @"+hex(aw-flash_write_block)+\
							", it is:"+hex(dd[av-a])+","+hex(dd[av-a+1])+" while should be:"+hex(d[av-a])+","+hex(d[av-a+1]))
		print >>log, "OK"
	return total_retries_count
Example #6
0
    def load_program(self):
        """
        Loads the program.

        :return: successful read
        :rtype: bool
        """
        ih = IntelHex(self.program)
        pydict = ih.todict()
        for address in pydict:
            self.memory[address:address + 1] = pydict[address].to_bytes(
                1, byteorder="big")
def main():
    if len(sys.argv) > 1:
        currentworkdir = os.path.abspath(os.path.dirname(sys.argv[0]))
        evenfilepath = str(os.path.abspath(sys.argv[1]))
        oddfilepath  = str(os.path.abspath(sys.argv[2]))
        newfilepath = os.path.join(currentworkdir , "output.hex")
        tempfileeven = open(evenfilepath, "r")
        tempfileodd = open(oddfilepath, "r")
        evenfile = IntelHex()
        evenfile.loadfile(tempfileeven,evenfilepath.split(".")[-1])
        #evenfile = IntelHex(evenfilepath)
        oddfile = IntelHex()
        oddfile.loadfile(tempfileodd,oddfilepath.split(".")[-1])
        #oddfile = IntelHex(oddfilepath)
        evendict = evenfile.todict()
        odddict = oddfile.todict()
        newdict = {}
        newindex = 0
        if evenfile.maxaddr() >= oddfile.maxaddr():
            maxaddr = evenfile.maxaddr()
        else:
            maxaddr = oddfile.maxaddr()
        #for i in range(len(evendict)):
        for i in range(0,maxaddr+1): #Evtl immer bei 0 und nicht bei inputfile.minaddr() anfangen
            try:
                newdict[newindex] = evendict[i]
            except KeyError: #Leere Adressen werden manchmal beim Speichern übersprungen
                #newdicteven[newindex] = 0xFF
                pass
            newindex+=1
            try:
                newdict[newindex] = odddict[i]
            except KeyError: #Leere Adressen werden manchmal beim Speichern übersprungen
                #newdicteven[newindex] = 0xFF
                pass
            newindex+=1
        newhex = IntelHex(newdict)
        output = open(newfilepath, 'w')
        newhex.write_hex_file(output)
        output.close()
Example #8
0
def write(addr, offset, file):

    if file.lower().endswith('.bin'):
        with open(file, "rb") as f:
            data = f.read()
            f.close()
    elif file.lower().endswith('.hex'):
        ihex = IntelHex()
        try:
            ihex.loadfile(file, format='hex')
        except Exception as e:
            raise Exception('Could not read from file: %s \n [%s]' % (file, str(e)))
        else:
            dhex = ihex.todict()
            data = bytearray([0xFF]*(max(dhex.keys()) + 1))
            for i, val in dhex.items():
                data[i] = val
    else:
        srec = kboot.SRecFile()
        try:
            srec.open(file)
        except Exception as e:
            raise Exception('Could not read from file: %s \n [%s]' % (file, str(e)))
        else:
            data = srec.data
            if addr ==  0:
                addr = srec.start_addr

    if offset < len(data):
        data = data[offset:]

    click.echo('\n Writing into MCU memory, please wait !\n')

    # Read Flash Sector Size of connected MCU
    flashSectorSize = KBOOT.get_property(kboot.Property.FlashSectorSize)['raw_value']

    # Align Erase Start Address and Len to Flash Sector Size
    saddr = (addr & ~(flashSectorSize - 1))
    slen = (len(data) & ~(flashSectorSize - 1))
    if (len(data) % flashSectorSize) > 0:
        slen += flashSectorSize

    # Erase specified region in MCU Flash memory
    KBOOT.flash_erase_region(saddr, slen)

    # Write data into MCU Flash memory
    KBOOT.write_memory(addr, data)

    # Disconnect KBoot device
    KBOOT.disconnect()

    click.secho(" Done Successfully. \n")
Example #9
0
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);
Example #10
0
 def load_image(self, path):
     retst = True
     self.data_buffer = bytearray()
     if path.lower().endswith('.bin'):
         with open(path, "rb") as f:
             self.data_buffer = f.read()
             f.close()
     elif path.lower().endswith('.hex'):
         ihex = IntelHex()
         try:
             ihex.loadfile(path, format='hex')
         except Exception as e:
             wx.MessageBox(
                 "Could not read from file: %s\n\n%s" % (path, str(e)),
                 'ERROR', wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             dhex = ihex.todict()
             self.data_buffer = bytearray([0xFF] * (max(dhex.keys()) + 1))
             for i, val in dhex.items():
                 self.data_buffer[i] = val
     elif path.lower().endswith(('.s19', '.srec')):
         srec = SRecFile()
         try:
             srec.open(path)
         except Exception as e:
             wx.MessageBox(
                 "Could not read from file: %s\n\n%s" % (path, str(e)),
                 'ERROR', wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             self.data_buffer = srec.data
     else:
         retst = False
         wx.MessageBox('Not supported file Type !', 'ERROR',
                       wx.OK | wx.ICON_ERROR)
     return retst
Example #11
0
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')
Example #12
0
class HexViewer(QtGui.QMainWindow):
    
    def __init__(self, parent, file_path):
        #QtGui.QMainWindow.__init__(self)
        super(HexViewer, self).__init__()
        #self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint |
                            #QtCore.Qt.WindowSystemMenuHint |
                            #QtCore.Qt.WindowStaysOnTopHint)        
        
        self.hex_viewer = Ui_HexViewer()
        self.hex_viewer.setupUi(self)
        self.main = parent
        
        self.setStyleSheet("""
        font-family: ubuntu regular;
        font-weight: normal;
        
        """)
        
        self.setWindowTitle(os.getenv("NAME")+" - "+self.windowTitle())
        
        self.original_filename = file_path
        
        self.hex_obj = IntelHex(open(file_path, "r"))
        
        try:
            self.update_viewer()
        except MemoryError:
            Dialogs.error_message(self, QtGui.QApplication.translate("Dialogs", "Impossible show 32-bit hex files."))
            self.deleteLater()
            #FIXME: deleteLater is not good solution here
            #self.close()  #not work, why?
        
        self.connect(self.hex_viewer.comboBox_view, QtCore.SIGNAL("currentIndexChanged(QString)"), self.update_viewer)
        self.connect(self.hex_viewer.tableWidget_viewer, QtCore.SIGNAL("itemChanged(QTableWidgetItem*)"), lambda :self.hex_viewer.pushButton_save_changes.setEnabled(True))
        self.connect(self.hex_viewer.pushButton_close, QtCore.SIGNAL("clicked()"), self.close)
        self.connect(self.hex_viewer.pushButton_save_changes, QtCore.SIGNAL("clicked()"), self.save_changes)     
        
        self.centrar()

    #----------------------------------------------------------------------
    def centrar(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
        
        
    #----------------------------------------------------------------------
    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 get_table_dict(self):
        
        dict_ = {}
        rows = self.hex_viewer.tableWidget_viewer.rowCount()
        
        space = 0
        for index in range(rows):
            
            for j in range(0x18):
                item = self.hex_viewer.tableWidget_viewer.item(index, j)
                if item:
                    value = self.get_dec_item(item.text())
                    if not value is None: dict_[space] = value
                    space += 1
        
        return dict_
        
        
    #----------------------------------------------------------------------
    def update_viewer(self, format_=None):
        
        hex_dict = self.hex_obj.todict()
        rows = int(ceil(max(hex_dict.keys()) / float(0x18)))

        if rows > 1e6: raise MemoryError
        
        self.hex_viewer.tableWidget_viewer.setRowCount(rows)
        
        space = 0
        for index in range(rows):
            
            item = QtGui.QTableWidgetItem()
            item.setText(hex(space)[hex(space).find("x")+1:].upper().rjust(6, "0"))
            self.hex_viewer.tableWidget_viewer.setVerticalHeaderItem(index, item) 
            
            for j in range(0x18):
                self.hex_viewer.tableWidget_viewer.setItem(index, j, QtGui.QTableWidgetItem())
                
                if index == rows - 1:
                    value = hex_dict.get(space, "FINISH")
                    if value == "FINISH":
                        self.update_width()
                        return
                else:
                    value = hex_dict.get(space, None)
                
                item = self.hex_viewer.tableWidget_viewer.item(index, j)
                item.setText(self.get_representation(value, format_))
                item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
                
                font = item.font()
                font.setFamily("mono")
                font.setPointSize(9)
                item.setFont(font)
                
                space += 1
                
        self.update_width()
        
    #----------------------------------------------------------------------
    def update_width(self):
        
        value = self.hex_viewer.tableWidget_viewer.item(0, 0).text()
        self.hex_viewer.tableWidget_viewer.horizontalHeader().setDefaultSectionSize(len(value)*12)
        self.hex_viewer.tableWidget_viewer.verticalHeader().setDefaultSectionSize(20)
        
                
    #----------------------------------------------------------------------
    def get_representation(self, value, format_):
        
        if value is None:
            value = 255
        
        if format_ is None:
            format_ = self.hex_viewer.comboBox_view.currentText()
        
        if format_ == "HEX (0xFF)":
            hex_ = hex(value)
            n_value = "0x"+hex_[hex_.find("x")+1:].upper().rjust(2, "0")
            
        elif format_ == "HEX (FF)":
            value = hex(value)
            n_value = value[value.find("x")+1:].upper().rjust(2, "0")
            
        elif format_ == "DEC":
            value = str(value)
            n_value = value[value.find("x")+1:].upper().rjust(2, "0")

        return n_value
    
    #----------------------------------------------------------------------
    def get_dec_item(self, value):
        
        value = value.replace(" ", "")
        if not value: return None
            
        format_ = self.hex_viewer.comboBox_view.currentText()
    
        if format_ == "HEX (0xFF)":
            n_value = eval(value)
            
        elif format_ == "HEX (FF)":
            n_value = n_value = eval("0x"+value)
            
        elif format_ == "DEC":
            n_value = int(value)
        
        return n_value
Example #13
0
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
		2'b01: DO = ROM_TABLE_1[address_q[12:0]];
		2'b10: DO = ROM_TABLE_2[address_q[12:0]];
		2'b11: DO = ROM_TABLE_3[address_q[12:0]];
		// 3'b100: DO = ROM_TABLE_4[address_q[12:0]];
		// 3'b101: DO = ROM_TABLE_5[address_q[12:0]];
		// 3'b110: DO = ROM_TABLE_6[address_q[12:0]];
		// 3'b111: DO = ROM_TABLE_7[address_q[12:0]];
	endcase
end

endmodule
"""

verilog_out_path = sys.argv[2]

d = ih.todict()


def linetoverilog(totalLines, linestring):
    ROMindex = int(totalLines // singleROMsize)

    myStr = ""

    if ((totalLines % singleROMsize) != 0):
        myStr += ",\n"

    else:
        # if not the first line in total close the brackets first
        if (totalLines != 0):
            myStr += "\n};\n\n"
        myStr += newRom.format(ROMindex)
Example #15
0
    def create_encrypted_image(self, hex_file, aes_key_file, aes_header,
                               host_key_id, dev_key_id, out_file_encrypt,
                               padding_value=0):
        """
        Creates encrypted image for encrypted programming
        Format:
        Row 1 - keys ID (byte 1 - host key ID, byte 2 - dev key ID)
        Row 2 - AES header
        Other - encrypted image data
        """
        # Write keys ID and AES header
        out_file_path = os.path.abspath(out_file_encrypt)
        with open(out_file_path, 'w') as f:
            f.write(str(host_key_id).zfill(2))
            f.write(str(dev_key_id).zfill(2) + '\n')
            f.write(aes_header + '\n')

        ih = IntelHex(hex_file)
        hex_data_dict = ih.todict()
        if 'start_addr' in hex_data_dict:
            del hex_data_dict['start_addr']
        logger.debug(f'hex_data_dict={hex_data_dict}')

        # Add padding
        ih.padding = padding_value
        data_to_program = dict()
        file_len = ih.maxaddr() - ih.minaddr()
        if file_len % FLASH_ROW_SIZE != 0:
            address_offset = (file_len // FLASH_ROW_SIZE + 1) * FLASH_ROW_SIZE
            max_address = ih.minaddr() + address_offset
        else:
            max_address = ih.maxaddr()
        for i in range(ih.minaddr(), max_address):
            data_to_program[i] = ih[i]

        sorted_address_keys = sorted(data_to_program)
        for key in sorted_address_keys:
            logger.debug('0x%08X: %02X' % (key, data_to_program[key]))

        logger.debug('Data bytes length: %s' % len(sorted_address_keys))
        if len(sorted_address_keys) % FLASH_ROW_SIZE != 0:
            logger.error('Data bytes length is not multiple '
                         'by FLASH_ROW_SIZE (%s)' % FLASH_ROW_SIZE)
            return

        sorted_bytes_values = []
        for key in sorted_address_keys:
            sorted_bytes_values.append(data_to_program[key])

        logger.debug('-' * 30 + ' Virgin rows ' + '-' * 30)
        address_row_bytes_dict = {}
        rows_of_bytes = list(AesHeaderStrategy.chunks_list(sorted_bytes_values,
                                                           FLASH_ROW_SIZE))
        flash_addresses = list(AesHeaderStrategy.chunks_list(
            sorted_address_keys, FLASH_ROW_SIZE))
        for i in range(len(flash_addresses)):
            flash_addresses[i] = flash_addresses[i][0]
            address_row_bytes_dict[flash_addresses[i]] = rows_of_bytes[i]
            out_data = '0x%08X %s' % (flash_addresses[i], ''.join(
                map(AesHeaderStrategy.hex_str_wo_header, rows_of_bytes[i])))
            logger.debug(out_data)

        logger.debug('-' * 30 + ' Encrypted rows ' + '-' * 30)
        addr_rows_bin = {}
        aes_key, aes_iv = read_key_from_file(aes_key_file)
        aes = AESCipherCBC(aes_key, aes_iv)
        with open(out_file_path, 'a') as encrypted_rows_out:
            for i in range(len(flash_addresses)):
                rows_in_binary_format = bytes(rows_of_bytes[i])
                encrypted_row = aes.encrypt(rows_in_binary_format)
                encrypted_row = bytes(list(encrypted_row))

                addr_rows_bin[flash_addresses[i]] = encrypted_row
                out_data = '%08X%s' % (flash_addresses[i],
                                       addr_rows_bin[flash_addresses[i]].hex())
                logger.debug(out_data)
                encrypted_rows_out.write(out_data + '\n')
        logger.info(f'Created encrypted image \'{out_file_path}\'')
Example #16
0

def getData(importedhex, startAddress, Size):
    retstr = ""
    for index in range(Size):
        retstr += str(importedhex[startAddress + index])
        if index + 1 < Size:
            retstr += (',')
    return retstr


def createArrayStr(importedhex, arrayName, startAddress, Size):
    retstr = TYPEDEF + ' ' + arrayName + '[] ' + OPENARRAY + getData(
        hexDict, startAddress, Size) + CLOSEARRAY
    return retstr


f = open(filename, mode='w')
importedHexFile = IntelHex(inputFile)

hexDict = importedHexFile.todict()
print(hexDict)
f.write("hex file converted from " + inputFile + "\n")
for memoryIndex in range(len(names)):

    f.write(
        createArrayStr(hexDict, names[memoryIndex], locations[memoryIndex],
                       datasizes[memoryIndex]))

f.close()
Example #17
0
	print "Usage: ihex2carr.py file.hex prefix [arrayname]"
	print "Converts PIC intel hex file to a c array + config word"
	print "Uses prefix as array name if arrayname is not specified"
	print "Config word is the array name _config"
	sys.exit()

infilename = sys.argv[1]
fprefix = sys.argv[2]
if 3 in sys.argv:
	arrayname = sys.argv[3]
else:
	arrayname = os.path.basename(infilename).replace('.', '_')

# Read in ihex file and remove config word at 0xFFF
ih_config = IntelHex(infilename)
ihdict_config = ih_config.todict()

# Remove upper nibble of addresses
data_config = dict()
for addr in ihdict_config:
	data_config[(addr & 0xFFF)] = ihdict_config[addr]

configword = ((data_config[0xFFF] if 0xFFF in data_config else 0) << 8 ) | (data_config[0xFFE] if 0xFFE in data_config else 0)
del data_config[0xFFE]
del data_config[0xFFF]

# Create a new ihex object without the config word getting in the way
ih = IntelHex(data_config)
data = ih.todict()

header = open( fprefix + ".h", "w" )
import serial
import time
from intelhex import IntelHex


def get_byte():
    return (int.from_bytes(ser.read(), byteorder='big'))


start_addr = 0xe200
end_addr = 0xffff - 1

ih = IntelHex()  # create empty object
ih.fromfile('hex.hex', format='hex')  # load from hex

hex_dict = ih.todict()

hex_lenght = ih.maxaddr()
#print (ih.minaddr())

hex_list = [0] * (hex_lenght + 1)
for key, value in hex_dict.items():
    hex_list[key] = value

hex_list = hex_list[start_addr:end_addr]

#print (hex_list[0])
#print (hex(len(hex_list)))
ser = serial.Serial('COM4', 115200, timeout=1)
while (get_byte() != 123):
    continue
from intelhex import IntelHex

input_string = input("Enter filename of intel hex file:")

lh = IntelHex()
lh.loadfile(input_string, format='hex')

f = open("h.txt", 'w')

f.write("uint8_t array[")
f.write(str(len(lh)))
f.write("] = { ")

pydict = lh.todict()

for line in pydict.values():
    f.write(str(hex(line)))
    f.write(", ")

f.seek(f.tell() - 2, 0)
f.write(" };")

f.close()
Example #20
0
from intelhex import IntelHex
from datetime import datetime

# -----------------------------------------------------------------------------
if __name__ == '__main__':

    # ...
    sp = serial.Serial(port=sys.argv[1], baudrate=999999999, timeout=0.0001)
    if (sp.isOpen() == True):
        sp.close()
    sp.open()

    # ..
    ih = IntelHex()
    ih.loadbin(sys.argv[2])
    binbuff = ih.todict()

    # ...
    TEST_LEN = 128
    buf = [0] * TEST_LEN
    tmpbuf = [0] * TEST_LEN
    buf = bytearray(buf)
    tmpbuf = bytearray(tmpbuf)

    # Start the process
    tmpbuf[0] = 2
    sp.write(tmpbuf)
    rbuf = sp.read(64)

    # ...
    bin_offset = 0
Example #21
0
                candidate = True
            else:
                candidate = False
                break
        if candidate:
            possible_matches.append((instr, prefix_len, args))
    # Matches sorted by greatest length.
    possible_matches = sorted(possible_matches, key=(lambda x: x[1]), reverse=True)
    if len(possible_matches) > 0:
        return [possible_matches[0][0], possible_matches[0][2]] # Longest match, instr.
    else:
        return None


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print usage
        exit(1)
    else:
        ih = IntelHex(sys.argv[1])
        mem_layout = ih.todict()
        instrs = []
        for i in range(0, 2200, 2):
            value = c_uint()
            value = (ih[i] << 8) | ih[i+1]
            instrs.append(value)
            #print "%6d %3d %3d" % (value, ih[i], ih[i+1])
        for instr in instrs:
            print prefix_match(isa, bin2str(instr))
        #pprint.pprint(instrs)
Example #22
0
class HexViewer(QtGui.QMainWindow):
    def __init__(self, parent, file_path):
        #QtGui.QMainWindow.__init__(self)
        super(HexViewer, self).__init__()
        #self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint |
        #QtCore.Qt.WindowSystemMenuHint |
        #QtCore.Qt.WindowStaysOnTopHint)

        self.hex_viewer = Ui_HexViewer()
        self.hex_viewer.setupUi(self)
        self.main = parent

        self.setStyleSheet("""
        font-family: ubuntu regular;
        font-weight: normal;
        
        """)

        self.setWindowTitle(os.getenv("NAME") + " - " + self.windowTitle())

        self.original_filename = file_path

        self.hex_obj = IntelHex(open(file_path, "r"))

        try:
            self.update_viewer()
        except MemoryError:
            Dialogs.error_message(
                self,
                QtGui.QApplication.translate(
                    "Dialogs", "Impossible show 32-bit hex files."))
            self.deleteLater()
            #FIXME: deleteLater is not good solution here
            #self.close()  #not work, why?

        self.connect(self.hex_viewer.comboBox_view,
                     QtCore.SIGNAL("currentIndexChanged(QString)"),
                     self.update_viewer)
        self.connect(
            self.hex_viewer.tableWidget_viewer,
            QtCore.SIGNAL("itemChanged(QTableWidgetItem*)"),
            lambda: self.hex_viewer.pushButton_save_changes.setEnabled(True))
        self.connect(self.hex_viewer.pushButton_close,
                     QtCore.SIGNAL("clicked()"), self.close)
        self.connect(self.hex_viewer.pushButton_save_changes,
                     QtCore.SIGNAL("clicked()"), self.save_changes)

        self.centrar()

    #----------------------------------------------------------------------
    def centrar(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    #----------------------------------------------------------------------
    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 get_table_dict(self):

        dict_ = {}
        rows = self.hex_viewer.tableWidget_viewer.rowCount()

        space = 0
        for index in range(rows):

            for j in range(0x18):
                item = self.hex_viewer.tableWidget_viewer.item(index, j)
                if item:
                    value = self.get_dec_item(item.text())
                    if not value is None: dict_[space] = value
                    space += 1

        return dict_

    #----------------------------------------------------------------------
    def update_viewer(self, format_=None):

        hex_dict = self.hex_obj.todict()
        rows = int(ceil(max(hex_dict.keys()) / float(0x18)))

        if rows > 1e6: raise MemoryError

        self.hex_viewer.tableWidget_viewer.setRowCount(rows)

        space = 0
        for index in range(rows):

            item = QtGui.QTableWidgetItem()
            item.setText(
                hex(space)[hex(space).find("x") + 1:].upper().rjust(6, "0"))
            self.hex_viewer.tableWidget_viewer.setVerticalHeaderItem(
                index, item)

            for j in range(0x18):
                self.hex_viewer.tableWidget_viewer.setItem(
                    index, j, QtGui.QTableWidgetItem())

                if index == rows - 1:
                    value = hex_dict.get(space, "FINISH")
                    if value == "FINISH":
                        self.update_width()
                        return
                else:
                    value = hex_dict.get(space, None)

                item = self.hex_viewer.tableWidget_viewer.item(index, j)
                item.setText(self.get_representation(value, format_))
                item.setTextAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)

                font = item.font()
                font.setFamily("mono")
                font.setPointSize(9)
                item.setFont(font)

                space += 1

        self.update_width()

    #----------------------------------------------------------------------
    def update_width(self):

        value = self.hex_viewer.tableWidget_viewer.item(0, 0).text()
        self.hex_viewer.tableWidget_viewer.horizontalHeader(
        ).setDefaultSectionSize(len(value) * 12)
        self.hex_viewer.tableWidget_viewer.verticalHeader(
        ).setDefaultSectionSize(20)

    #----------------------------------------------------------------------
    def get_representation(self, value, format_):

        if value is None:
            value = 255

        if format_ is None:
            format_ = self.hex_viewer.comboBox_view.currentText()

        if format_ == "HEX (0xFF)":
            hex_ = hex(value)
            n_value = "0x" + hex_[hex_.find("x") + 1:].upper().rjust(2, "0")

        elif format_ == "HEX (FF)":
            value = hex(value)
            n_value = value[value.find("x") + 1:].upper().rjust(2, "0")

        elif format_ == "DEC":
            value = str(value)
            n_value = value[value.find("x") + 1:].upper().rjust(2, "0")

        return n_value

    #----------------------------------------------------------------------
    def get_dec_item(self, value):

        value = value.replace(" ", "")
        if not value: return None

        format_ = self.hex_viewer.comboBox_view.currentText()

        if format_ == "HEX (0xFF)":
            n_value = eval(value)

        elif format_ == "HEX (FF)":
            n_value = n_value = eval("0x" + value)

        elif format_ == "DEC":
            n_value = int(value)

        return n_value
Example #23
0
def main(argv):

    fp = open('flashmap.bin', 'wb')
    flist = argv[3:]
    try:
        flashaddr = eval(argv[1])
        tag = 'DFL:'.encode()
        fp.write(tag)
        lval = [0, 0, 0, 0]
        lval[0] = len(flist) & 0xff
        fp.write(bytes(lval))
        lval = [1, 0, 0, 0]
        fp.write(bytes(lval))
        lval = [0x00, 0, 0, 0]
        fp.write(bytes(lval))
        lval = [0xff, 0xff, 0xff, 0xff]
        fp.write(bytes(lval))

        for i in range(11):
            print(i)
            lval = [0x1f, 0xff, 0xff, 0xff]
            fp.write(bytes(lval))
    except:
        print('usage:\n	dfl_packer.py flashaddr pattern0 pattern1 ...')

    flashaddr = 144 * 4
    packinfo = []
    datatable = []

    emptytable = []
    for i in range(512):
        emptytable = emptytable + [0xff]

    print(flist)
    for fname in flist:
        #try:
        ih = IntelHex(fname)
        dih = ih.todict()
        ldih = list(dih)
        ldihv = list(dih.values())
        ldihv = ldihv[:-1]
        datasize = len(ldihv) + 3
        ldihv = ldihv + [0, 0, 0, 0, 0, 0, 0, 0]
        datasize = (datasize - (datasize % 4))
        ldihv = ldihv[:datasize]
        runaddr = ldih[0]
        lflashaddr = [
            flashaddr & 0xff, (flashaddr >> 8) & 0xff,
            (flashaddr >> 16) & 0xff, (flashaddr >> 24) & 0xff
        ]
        lrunaddr = [
            runaddr & 0xff, (runaddr >> 8) & 0xff, (runaddr >> 16) & 0xff,
            (runaddr >> 24) & 0xff
        ]
        lrunaddr = [
            runaddr & 0xff, (runaddr >> 8) & 0xff, (runaddr >> 16) & 0xff,
            (runaddr >> 24) & 0xff
        ]
        ldatasize = [
            datasize & 0xff, (datasize >> 8) & 0xff, (datasize >> 16) & 0xff,
            (datasize >> 24) & 0xff
        ]
        #print(ldihv)
        crc = crc16(0, ldihv)
        lcrc = [
            crc & 0xff, (crc >> 8) & 0xff, (crc >> 16) & 0xff,
            (crc >> 24) & 0xff
        ]
        packinfo = packinfo + lflashaddr + lrunaddr + ldatasize + lcrc
        #print('pack info')
        #print(packinfo)

        datatable += ldihv
        flashaddr += datasize
        #except:
        #	print('Create symble version error!')
        #	print('usage:\n	dfl_packer.py flashaddr pattern0 pattern1 ...')
    packinfo = packinfo + emptytable
    packinfo = packinfo[:32 * 4 * 4]
    fp.write(bytes(packinfo))
    fp.write(bytes(datatable))
Example #24
0
from intelhex import IntelHex

# CONFIGURATIONS
_BUFFER_SIZE = 256

# IntelHex Object Initiation

intelHex = IntelHex()

# HEX FILE SELECTION

_file_name = str(input("HEX File Name to be uploaded:"))

# Get Data From HEX File
intelHex.fromfile(_file_name + ".hex", format='hex')  # Read Hex File
hex_dict = intelHex.todict()  # Dump into DICT Object

hex_byte_list = list(hex_dict.values())  # Convert to list
hex_byte_list.pop()  # POP: {'EIP': 134218121}
print("FILE-Decimal Bytes:", hex_byte_list)  # All bytes in decimal form

hex_chunk_list = [
    hex_byte_list[i:i + _BUFFER_SIZE]  # Creating new list: Chunk List
    for i in range(0, len(hex_byte_list), _BUFFER_SIZE)
]  # Each containing specified many

print("\nChunks:", hex_chunk_list)  # See Chunks
print('\n1st Chunk (HEX): [{}]'.format(
    ', '  # See First Chunk in HEX
    .join(hex(x) for x in hex_chunk_list[0])))  # HEX Conversion (CHECKING)
Example #25
0
    elif len(sys.argv) is 1:
        HexFile = ''
    else:
        print 'Usage: %s file.hex' % sys.argv[0]
        quit()

## load hex file if it exist
FileData = IntelHex()
if len(HexFile) > 0:
    try:
        FileData.loadhex(HexFile)
    except IOError:
        print 'Error in file "', HexFile, '"'
        quit()

PicData = FileData.todict()
print 'File "', HexFile, '" loaded'
#set GPIO MODE

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)

GPIO.setup(PIC_MCLR, GPIO.OUT)
GPIO.setup(PIC_CLK, GPIO.IN)
GPIO.setup(PIC_DATA, GPIO.IN)

#enter Program Mode

#Set_VPP()
#sleep(0.1)
#get cpu id
Example #26
0
import smbus
import os
import time
from intelhex import IntelHex

ih1 = IntelHex()
ih1.loadhex("capsens.X.production.hex")
ih1d = ih1.todict()     # dump contents to pydict
for a in range(0,0x800,16):
	d = [(hex(ih1d[aa]) if aa in ih1d else "0xXX") for aa in range(a,a+16)]
        print "mem @:"+hex(a/2) + " data:"+str(d)

ih2 = IntelHex()
ih2.loadhex("memory.hex")
ih2d = ih2.todict()     # dump contents to pydict

for a in range(0,0x200,16):
	aw = a / 2
	d = [(ih2d[aa] if aa in ih2d else 0) for aa in range(a,a+16)]
	dd = [(ih2d[aa] if aa in ih2d else 0) for aa in range(a+0x400,a+0x400+16)]
	print "verifying block (expected) @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in d))
	print "verifying block (actual  ) @:"+hex(aw+0x200) + " data:"+(':'.join("%02x" % c for c in dd))
	for aa in range(0,16):
		if (a + aa in ih2d) and d[aa] != dd[aa]:
			raise IOError('Data Differs')
Example #27
0
    HexFile = ''
  else:
    print 'Usage: %s file.hex' % sys.argv[0]
    quit()


## load hex file if it exist
FileData =  IntelHex()
if len(HexFile) > 0 :
   try:
     FileData.loadhex(HexFile)
   except IOError:
     print 'Error in file "', HexFile, '"'
     quit()

PicData = FileData.todict()       
print 'File "', HexFile, '" loaded'


#try to figure out the CpuId by scanning all available Cpu family
IO.Setup_Interface()

CpuId=0
print "Scan CPU "

for l in AllCpuFamily:
  CpuTag = l.ScanCpuTag()
  if(CpuTag!=0):
    #found the correct cpu
    print "Cpu Id   =", hex(l.CpuId)
    print "Revision = ", hex(l.CpuRevision)
Example #28
0
    s += "WIDTH = %d;\n" % data_width
    s += "ADDRESS_RADIX = %s;\n" % addr_radix
    s += "DATA_RADIX = %s;\n" % data_radix
    return s


def mif_data(data={}, minaddr=MIN_ADDR, maxaddr=MAX_ADDR, gap_fill=GAP_FILL):
    s = "CONTENT\n"
    s += "BEGIN\n"
    s += "[%x..%x] : %x;\n" % (minaddr, maxaddr - 1, gap_fill)
    for k in data.keys():
        if isinstance(k, Number):
            s += "%x : %x;\n" % (k, data[k])
    s += "END;\n"
    return s


if __name__ == "__main__":
    ih = IntelHex()
    ih.fromfile(sys.stdin, format="hex")
    data = ih.todict()

    for a in range(0, 4096, 4):
        if data.has_key(a):
            d = data[a] + (data[a + 1] << 8) + (data[a + 2] << 16) + (data[a + 3] << 24)
            del data[a], data[a + 1], data[a + 2], data[a + 3]
            data[a] = d

    print mif_header(32, 0, 4096)
    print mif_data(data, 0, 4096, 0x00000013)