def to_ihex(self, as_str=True): self._assemble() ihex = IHex() ihex.insert_data(self.offset, self._code_as_bytes()) if as_str: return ihex.write() else: return ihex
def opProgram(self, data, addr_start=0): addr_hi_prev = None addr = addr_start while data: addr_hi, addr_lo = divmod(addr, 0x10000) if addr_hi != addr_hi_prev: addr_hi_prev = addr_hi cmd = self._protocol.getCmd('select_memory_page', PPPP=addr_hi) self._opDotCmd(cmd) addr_end = addr_lo + len(data) if addr_end >= 0x10000: addr_end = 0xffff size = addr_end + 1 - addr_lo buf, data = data[:size], data[size:] cmd = self._protocol.getCmd('program_start', PPPP=addr_lo, QQQQ=addr_end) self._opDotCmd(cmd) self._wdelayHack() addr = addr + size # send data ihex = IHex() ihex.insert_data(addr_lo, buf) ihex.set_row_bytes(255) buf = ihex.write() # split to lines, remove, empty strings buf = [b for b in buf.splitlines() if b] # remove hex end if file buf = buf[:-1] for d in buf: self._opDotCmd(str(d, 'ascii').upper()) self._wdelayHack()
#!/usr/bin/python import sys from ihex import IHex # https://github.com/kierdavis/IHex id_value=0xFF; #stall_value=0x100; if (len(sys.argv)>=2): id_arg = int(sys.argv[1]); if (id_arg>=0 and id_arg<255): id_value=id_arg; #if (len(sys.argv)>=3): # stall_arg = int(sys.argv[2]); # if (stall_arg>=0 and stall_arg<255): # stall_value=stall_arg; #L = [id_value,id_value,id_value,stall_value,stall_value,stall_value]; L = [id_value,id_value,id_value]; str=''.join(chr(i) for i in L); ihex = IHex(); ihex.insert_data(0,str); ihex.write_file('controller_id_eeprom.hex');
def read(hex_filename): return IHex.read_file(hex_filename).areas[0]
help="Verfiy image after programming", action='store_true') args = parser.parse_args() msp = EZ430(args.uart) msp.open() # We need to call identify() to stop the MSP430 print "Identify" msp.identify() msp.identify2() # If we've specified a file name, then parse it & program it in if args.image: suffix = args.image[-4:].lower() if suffix == '.a43': prog = IHex(args.image) segments = prog.get_segments() elif suffix == '.txt': prog = TITxt(args.image) segments = prog.get_segments(32) else: raise SystemError, "Invalid HEX file suffix: %s" % (suffix) print "Erasing flash..." msp.erase_flash_all() print "Writing image..." msp.write_mem(segments) if args.verify: print "Verifying image..." if not msp.verify_mem(segments): raise SystemError, "Failed to verify memory"
def writeihex(ser, filename): h = IHex.read_file(filename) for addr in h.areas: data = h.areas[addr] for i in xrange(len(data)/4): writemem(ser, addr + i * 4 + 0x80000000, data[i*4:i*4+4])
class BatchISP: def __init__(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Linux remake of Atmel\'s BatchISP utility.') parser.add_argument('-baudrate', type=int, help="{ 9600 | 19200 | 38400 | 57600 | *115200* }") parser.add_argument('-device', type=str, required=True, help="Device type, ? for list.") parser.add_argument('-port', type=str, help="Port/interface to connect.") parser.add_argument('-hardware', type=str, help="{ RS232 | TODO }") parser.add_argument('-version', action='version', version='%(prog)s 0.0.0') parser.add_argument('-sync', type=int, default=1, choices=(1, 0), help="Synchronize protocol (for development only)") parser.add_argument('-operation', nargs=argparse.REMAINDER, help="<operation> <operation> ..., use help for help") #CANOPEN <node_number> #CANCLOSE <node_number> #SERIALIZE <dest_addr> <serial_number> <number | ascii | unicode> <step> #WAIT <Nsec> #FILLBUFFER <data> #ASSERT < PASS | fail > #RBOOTID1 [ expected_data ] #RBOOTID2 [ expected_data ] #WSBV <data> #RSBV [ expected_data ] #WBSB <data> #RBSB [ expected_data ] #WHWB <data> #RHWB [ expected_data ] #WEB <data> #REB [ expected_data ] #SSL1 #SSL2 #RSSB [ expected_data ] #RSIGB #WCRIS <data> #RCRIS [ expected data ] #WNNB <data> #RNNB [ expected data ] #WBTC1 <data> #RBTC1 [ expected data ] #WBTC2 <data> #RBTC2 [ expected data ] #WBTC3 <data> #RBTC3 [ expected data ] #WP1CFG <data> #RP1CFG [ expected data ] #WP3CFG <data> #RP3CFG [ expected data ] #WP4CFG <data> #RP4CFG [ expected data ] #ENAX2 #DISX2 #ENABLJB #DISBLJB #ENAOSC #DISOSC #ENASELBOOT #DISSELBOOT #INCLUDE <cmd_file> #ONFAIL < ASK | abort | retry | ignore > #ADDRANGE <start> <end> operations_help = """ BLANKCHECK ECHO "<your comment>" ERASE { F | <n> } LOADBUFFER <in_hexfile> MEMORY { FLASH | EEPROM | <id> } PROGRAM READ SAVEBUFFER <hex_file_name> { 386HEX | ? } START { RESET | NORESET } <address> VERIFY """ parser.epilog = operations_help self._args = parser.parse_args() self._parser = parser def _getIOByHardwareName(self, hardware): if hardware == 'RS232': if self._args.port is None: raise PrgError("Port not specified for RS232") if not self._args.baudrate is None: return SerialIO(self._args.port, self._args.baudrate) else: return SerialIO(self._args.port) else: raise PrgError("Unsupported hardware: %s" % hardware) def run(self): if self._args.device == '?': parts = Parts() parts = [part.getName() for part in parts.list()] parts.sort() print(parts) return 0 try: part = Parts().getPartByName(self._args.device) if not self._args.hardware is None: hw = sef._args.hardware else: hw = part.listHardware() if len(hw) != 1: raise PrgError("Cannot determine hardware select one of: %s" % hw) hw = hw[0] io = self._getIOByHardwareName(hw) self._operations = Operations(part, io, self._args.sync) return self._doOperations() except PgmError as e: print(e) return 1 def _doOperations(self): """Go trought all operations and try to execute them.""" if self._args.operation is None: return iop = iter(self._args.operation) self._buffer = IHex() try: while True: try: op = next(iop) time.sleep(1) except StopIteration: return 0 if op == 'BLANKCHECK': self._operations.opBlankCheck(0) elif op == 'ECHO': print(next(iop)) elif op == 'ERASE': op = next(iop) if op != 'F': raise PgmError("Expected 'F' not %s" % op) self._operations.opErase() elif op == 'LOADBUFFER': filename = next(iop) self._buffer = IHex.read_file(filename) elif op == 'PROGRAM': for start, data in self._buffer.areas.items(): self._operations.opProgram(data, start) elif op == 'MEMORY': self._operations.opMemory(next(iop)) self._addr_start = 0 self._addr_end = None elif op == 'READ': if self._addr_end is None: size = None #size = 1024 # debug only, set to None!!! else: size = self._addr_end - self._addr_start data = self._operations.opRead(self._addr_start, size) self._buffer.insert_data(self._addr_start, data) elif op == 'SAVEBUFFER': filename = next(iop) if next(iop) != '386HEX': raise PgmError("Invalid output format") self._buffer.write_file(filename) elif op == 'START': reset = next(iop) if reset == 'RESET': reset = True addr = next(iop) elif reset == 'NORESET': reset = False addr = next(iop) else: addr = reset reset = True addr = int(addr, 0) if addr != 0: raise PgmError("Only address 0 supported for START") self._operations.opStartAppl(reset) try: next(iop) except StopIteration: continue raise PgmError("START cannot be folowed by anny instruction!!!") elif op == 'VERIFY': for start, data in self._buffer.areas.items(): data_r = self._operations.opRead(start, len(data)) if data != data_r: while not data_r.startswith(data): data = data[:-1] addr = len(data) addr = addr + start raise PgmError("Verification failed at address: 0x%X" % addr) else: raise PgmError("Unknown or unsupported operation: %s" % op) except StopIteration: raise PgmError("Missing argument for cmd: %s" % cmd)
def _doOperations(self): """Go trought all operations and try to execute them.""" if self._args.operation is None: return iop = iter(self._args.operation) self._buffer = IHex() try: while True: try: op = next(iop) time.sleep(1) except StopIteration: return 0 if op == 'BLANKCHECK': self._operations.opBlankCheck(0) elif op == 'ECHO': print(next(iop)) elif op == 'ERASE': op = next(iop) if op != 'F': raise PgmError("Expected 'F' not %s" % op) self._operations.opErase() elif op == 'LOADBUFFER': filename = next(iop) self._buffer = IHex.read_file(filename) elif op == 'PROGRAM': for start, data in self._buffer.areas.items(): self._operations.opProgram(data, start) elif op == 'MEMORY': self._operations.opMemory(next(iop)) self._addr_start = 0 self._addr_end = None elif op == 'READ': if self._addr_end is None: size = None #size = 1024 # debug only, set to None!!! else: size = self._addr_end - self._addr_start data = self._operations.opRead(self._addr_start, size) self._buffer.insert_data(self._addr_start, data) elif op == 'SAVEBUFFER': filename = next(iop) if next(iop) != '386HEX': raise PgmError("Invalid output format") self._buffer.write_file(filename) elif op == 'START': reset = next(iop) if reset == 'RESET': reset = True addr = next(iop) elif reset == 'NORESET': reset = False addr = next(iop) else: addr = reset reset = True addr = int(addr, 0) if addr != 0: raise PgmError("Only address 0 supported for START") self._operations.opStartAppl(reset) try: next(iop) except StopIteration: continue raise PgmError("START cannot be folowed by anny instruction!!!") elif op == 'VERIFY': for start, data in self._buffer.areas.items(): data_r = self._operations.opRead(start, len(data)) if data != data_r: while not data_r.startswith(data): data = data[:-1] addr = len(data) addr = addr + start raise PgmError("Verification failed at address: 0x%X" % addr) else: raise PgmError("Unknown or unsupported operation: %s" % op) except StopIteration: raise PgmError("Missing argument for cmd: %s" % cmd)
parser.add_argument('-r', '--reset', help="Reset MSP when finished programming", action='store_true') parser.add_argument('-v', '--verify', help="Verfiy image after programming", action='store_true') args = parser.parse_args() msp = EZ430(args.uart) msp.open() # We need to call identify() to stop the MSP430 print "Identify" msp.identify() msp.identify2() # If we've specified a file name, then parse it & program it in if args.image: suffix = args.image[-4:].lower() if suffix == '.a43': prog = IHex(args.image) segments = prog.get_segments() elif suffix == '.txt': prog = TITxt(args.image) segments = prog.get_segments(32) else: raise SystemError, "Invalid HEX file suffix: %s" % (suffix) print "Erasing flash..." msp.erase_flash_all() print "Writing image..." msp.write_mem(segments) if args.verify: print "Verifying image..." if not msp.verify_mem(segments): raise SystemError, "Failed to verify memory"
class BatchISP: def __init__(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description='Linux remake of Atmel\'s BatchISP utility.') parser.add_argument('-baudrate', type=int, help="{ 9600 | 19200 | 38400 | 57600 | *115200* }") parser.add_argument('-device', type=str, required=True, help="Device type, ? for list.") parser.add_argument('-port', type=str, help="Port/interface to connect.") parser.add_argument('-hardware', type=str, help="{ RS232 | TODO }") parser.add_argument('-version', action='version', version='%(prog)s 0.0.0') parser.add_argument('-sync', type=int, default=1, choices=(1, 0), help="Synchronize protocol (for development only)") parser.add_argument( '-operation', nargs=argparse.REMAINDER, help="<operation> <operation> ..., use help for help") #CANOPEN <node_number> #CANCLOSE <node_number> #SERIALIZE <dest_addr> <serial_number> <number | ascii | unicode> <step> #WAIT <Nsec> #FILLBUFFER <data> #ASSERT < PASS | fail > #RBOOTID1 [ expected_data ] #RBOOTID2 [ expected_data ] #WSBV <data> #RSBV [ expected_data ] #WBSB <data> #RBSB [ expected_data ] #WHWB <data> #RHWB [ expected_data ] #WEB <data> #REB [ expected_data ] #SSL1 #SSL2 #RSSB [ expected_data ] #RSIGB #WCRIS <data> #RCRIS [ expected data ] #WNNB <data> #RNNB [ expected data ] #WBTC1 <data> #RBTC1 [ expected data ] #WBTC2 <data> #RBTC2 [ expected data ] #WBTC3 <data> #RBTC3 [ expected data ] #WP1CFG <data> #RP1CFG [ expected data ] #WP3CFG <data> #RP3CFG [ expected data ] #WP4CFG <data> #RP4CFG [ expected data ] #ENAX2 #DISX2 #ENABLJB #DISBLJB #ENAOSC #DISOSC #ENASELBOOT #DISSELBOOT #INCLUDE <cmd_file> #ONFAIL < ASK | abort | retry | ignore > #ADDRANGE <start> <end> operations_help = """ BLANKCHECK ECHO "<your comment>" ERASE { F | <n> } LOADBUFFER <in_hexfile> MEMORY { FLASH | EEPROM | <id> } PROGRAM READ SAVEBUFFER <hex_file_name> { 386HEX | ? } START { RESET | NORESET } <address> VERIFY """ parser.epilog = operations_help self._args = parser.parse_args() self._parser = parser def _getIOByHardwareName(self, hardware): if hardware == 'RS232': if self._args.port is None: raise PrgError("Port not specified for RS232") if not self._args.baudrate is None: return SerialIO(self._args.port, self._args.baudrate) else: return SerialIO(self._args.port) else: raise PrgError("Unsupported hardware: %s" % hardware) def run(self): if self._args.device == '?': parts = Parts() parts = [part.getName() for part in parts.list()] parts.sort() print(parts) return 0 try: part = Parts().getPartByName(self._args.device) if not self._args.hardware is None: hw = sef._args.hardware else: hw = part.listHardware() if len(hw) != 1: raise PrgError( "Cannot determine hardware select one of: %s" % hw) hw = hw[0] io = self._getIOByHardwareName(hw) self._operations = Operations(part, io, self._args.sync) return self._doOperations() except PgmError as e: print(e) return 1 def _doOperations(self): """Go trought all operations and try to execute them.""" if self._args.operation is None: return iop = iter(self._args.operation) self._buffer = IHex() try: while True: try: op = next(iop) time.sleep(1) except StopIteration: return 0 if op == 'BLANKCHECK': self._operations.opBlankCheck(0) elif op == 'ECHO': print(next(iop)) elif op == 'ERASE': op = next(iop) if op != 'F': raise PgmError("Expected 'F' not %s" % op) self._operations.opErase() elif op == 'LOADBUFFER': filename = next(iop) self._buffer = IHex.read_file(filename) elif op == 'PROGRAM': for start, data in self._buffer.areas.items(): self._operations.opProgram(data, start) elif op == 'MEMORY': self._operations.opMemory(next(iop)) self._addr_start = 0 self._addr_end = None elif op == 'READ': if self._addr_end is None: size = None #size = 1024 # debug only, set to None!!! else: size = self._addr_end - self._addr_start data = self._operations.opRead(self._addr_start, size) self._buffer.insert_data(self._addr_start, data) elif op == 'SAVEBUFFER': filename = next(iop) if next(iop) != '386HEX': raise PgmError("Invalid output format") self._buffer.write_file(filename) elif op == 'START': reset = next(iop) if reset == 'RESET': reset = True addr = next(iop) elif reset == 'NORESET': reset = False addr = next(iop) else: addr = reset reset = True addr = int(addr, 0) if addr != 0: raise PgmError("Only address 0 supported for START") self._operations.opStartAppl(reset) try: next(iop) except StopIteration: continue raise PgmError( "START cannot be folowed by anny instruction!!!") elif op == 'VERIFY': for start, data in self._buffer.areas.items(): data_r = self._operations.opRead(start, len(data)) if data != data_r: while not data_r.startswith(data): data = data[:-1] addr = len(data) addr = addr + start raise PgmError( "Verification failed at address: 0x%X" % addr) else: raise PgmError("Unknown or unsupported operation: %s" % op) except StopIteration: raise PgmError("Missing argument for cmd: %s" % cmd)
def _doOperations(self): """Go trought all operations and try to execute them.""" if self._args.operation is None: return iop = iter(self._args.operation) self._buffer = IHex() try: while True: try: op = next(iop) time.sleep(1) except StopIteration: return 0 if op == 'BLANKCHECK': self._operations.opBlankCheck(0) elif op == 'ECHO': print(next(iop)) elif op == 'ERASE': op = next(iop) if op != 'F': raise PgmError("Expected 'F' not %s" % op) self._operations.opErase() elif op == 'LOADBUFFER': filename = next(iop) self._buffer = IHex.read_file(filename) elif op == 'PROGRAM': for start, data in self._buffer.areas.items(): self._operations.opProgram(data, start) elif op == 'MEMORY': self._operations.opMemory(next(iop)) self._addr_start = 0 self._addr_end = None elif op == 'READ': if self._addr_end is None: size = None #size = 1024 # debug only, set to None!!! else: size = self._addr_end - self._addr_start data = self._operations.opRead(self._addr_start, size) self._buffer.insert_data(self._addr_start, data) elif op == 'SAVEBUFFER': filename = next(iop) if next(iop) != '386HEX': raise PgmError("Invalid output format") self._buffer.write_file(filename) elif op == 'START': reset = next(iop) if reset == 'RESET': reset = True addr = next(iop) elif reset == 'NORESET': reset = False addr = next(iop) else: addr = reset reset = True addr = int(addr, 0) if addr != 0: raise PgmError("Only address 0 supported for START") self._operations.opStartAppl(reset) try: next(iop) except StopIteration: continue raise PgmError( "START cannot be folowed by anny instruction!!!") elif op == 'VERIFY': for start, data in self._buffer.areas.items(): data_r = self._operations.opRead(start, len(data)) if data != data_r: while not data_r.startswith(data): data = data[:-1] addr = len(data) addr = addr + start raise PgmError( "Verification failed at address: 0x%X" % addr) else: raise PgmError("Unknown or unsupported operation: %s" % op) except StopIteration: raise PgmError("Missing argument for cmd: %s" % cmd)
def test_row_bytes(self): ihex = IHex() self.assertEqual(ihex.write(), ':00000001FF\r\n') ihex.insert_data(6, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuwvxyz') self.assertEqual(ihex.write(), ':100006004142434445464748494A4B4C4D4E4F5062\r\n' \ ':100016005152535455565758595A30313233343554\r\n' \ ':10002600363738396162636465666768696A6B6C1E\r\n' \ ':0E0036006D6E6F707172737475777678797A6B\r\n' \ ':00000001FF\r\n') ihex.set_row_bytes(8) self.assertEqual(ihex.write(), ':080006004142434445464748CE\r\n' \ ':08000E00494A4B4C4D4E4F5086\r\n' \ ':0800160051525354555657583E\r\n' \ ':08001E00595A303132333435F8\r\n' \ ':0800260036373839616263646A\r\n' \ ':08002E0065666768696A6B6C86\r\n' \ ':080036006D6E6F70717273743E\r\n' \ ':06003E0075777678797AEF\r\n' \ ':00000001FF\r\n') ihex.set_row_bytes(32) self.assertEqual(ihex.write(), ':200006004142434445464748494A4B4C4D4E4F505152535455565758595A303132333435CC\r\n' \ ':1E002600363738396162636465666768696A6B6C6D6E6F707172737475777678797ABF\r\n' \ ':00000001FF\r\n')
#!/usr/bin/python import sys from ihex import IHex # https://github.com/kierdavis/IHex id_value=0xFF; #stall_value=0x100; if (len(sys.argv)>=2): id_arg = int(sys.argv[1]); if (id_arg>=0 and id_arg<255): id_value=id_arg; #if (len(sys.argv)>=3): # stall_arg = int(sys.argv[2]); # if (stall_arg>=0 and stall_arg<255): # stall_value=stall_arg; #L = [id_value,id_value,id_value,stall_value,stall_value,stall_value]; L = [id_value,id_value,id_value]; str=''.join(chr(i) for i in L); ihex = IHex(); ihex.insert_data(0,str); ihex.write_file('ledsphere_id_eeprom.hex');