示例#1
0
def main(file, port, baud, start, delay, run, entry, compact):
    """
    Send a code file to an ELF computer with MAX binary loader.

    The specified file is sent to an attached ELF computer over
    the named serial port. The input file can be an Intel 8-bit
    HEX file or a binary file. For a binary file, the starting
    address may be specified by the 'start' option.
    """
    intel_hex = IntelHex()
    try:
        intel_hex.loadhex(file)
    except (IntelHexError, UnicodeDecodeError):
        intel_hex.loadbin(file, offset=start)

    delay /= 1000

    with serial.serial_for_url(port) as ser:
        ser.baudrate = baud

        send_segments(intel_hex, ser, delay, compact)

        if run:
            if entry is None:
                entry = intel_hex.segments()[0][0]
            run_program(ser, entry, delay)
        else:
            end_transfer(ser)
示例#2
0
    def replace_image_body(self, orig, repl, padding):
        """
        Replaces original image with the replacement image
        :param orig: The image to be replaced
        :param repl: The image to replace with
        :param padding: Padding value
        """
        orig_ih = IntelHex()
        orig_ih.padding = padding
        orig_ih.loadhex(orig)

        repl_ih = IntelHex()
        repl_ih.padding = padding
        repl_ih.loadhex(repl)
        minaddr = repl_ih.minaddr()
        maxaddr = repl_ih.maxaddr()

        # This adds padding if the image is not aligned to 16 Bytes
        pad_len = (maxaddr - minaddr + self.header_size) % 16
        if pad_len > 0:
            pad_len = 16 - pad_len

        for i in range(repl_ih.minaddr(), repl_ih.maxaddr() + pad_len):
            orig_ih[i] = repl_ih[i]

        orig_ih.tofile(orig, pathlib.Path(orig).suffix[1:])
    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
示例#4
0
class Driver(FirmwareBase):
    def __init__(self, filename):
        FirmwareBase.__init__(self)

        self.__ih = IntelHex()
        self.__ih.loadhex(filename)

        cs = crc.crc16()
        for each in range(self.__ih.minaddr(), self.__ih.maxaddr()+1):
            cs.addByte(self.__ih[each])
        self.__size = self.__ih.maxaddr()+1
        self.__checksum = cs.getResult()


    def download(self):
        progress = 0.0
        self.sendStatus("Starting Download to Node " + str(self.destNode))
        while True:
            if self.kill==True:
                self.sendProgress(0.0)
                self.sendStatus("Download Stopped")
                return
            time.sleep(0.1)
            self.sendProgress(progress)
            progress = progress + 0.01
            if progress > 1: break
        self.sendProgress(1.0)
        self.sendStatus("Download Successful")
示例#5
0
    def upload(self, filename):
        print("> uploading file '%s'" % (filename))

        #identify chip
        self.identify_chip()

        #read hex file
        ih = IntelHex()
        ih.loadhex(filename)

        #send autobaud training character
        self.send_autobaud_training()

        #enable flash access
        self.enable_flash_access()

        #erase pages where we are going to write
        self.erase_pages_ih(ih)

        #write all data bytes
        self.write_pages_ih(ih)
        self.verify_pages_ih(ih)

        if not self.run_app():
            sys.exit("ERROR: device reset failed")
示例#6
0
    def binary_hook(t_self, resources, _, binf):
        """Hook that merges the soft device with the bin file"""
        # Scan to find the actual paths of soft device
        sdf = None
        for softdevice_and_offset_entry\
            in t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS:
            for hexf in resources.hex_files:
                if hexf.find(softdevice_and_offset_entry['name']) != -1:
                    t_self.notify.debug("SoftDevice file found %s." %
                                        softdevice_and_offset_entry['name'])
                    sdf = hexf

                if sdf is not None:
                    break
            if sdf is not None:
                break

        if sdf is None:
            t_self.notify.debug("Hex file not found. Aborting.")
            return

        # Look for bootloader file that matches this soft device or bootloader
        # override image
        blf = None
        if t_self.target.MERGE_BOOTLOADER is True:
            for hexf in resources.hex_files:
                if hexf.find(t_self.target.OVERRIDE_BOOTLOADER_FILENAME) != -1:
                    t_self.notify.debug(
                        "Bootloader file found %s." %
                        t_self.target.OVERRIDE_BOOTLOADER_FILENAME)
                    blf = hexf
                    break
                elif hexf.find(softdevice_and_offset_entry['boot']) != -1:
                    t_self.notify.debug("Bootloader file found %s." %
                                        softdevice_and_offset_entry['boot'])
                    blf = hexf
                    break

        # Merge user code with softdevice
        from intelhex import IntelHex
        binh = IntelHex()
        _, ext = os.path.splitext(binf)
        if ext == ".hex":
            binh.loadhex(binf)
        elif ext == ".bin":
            binh.loadbin(binf, softdevice_and_offset_entry['offset'])

        if t_self.target.MERGE_SOFT_DEVICE is True:
            t_self.notify.debug("Merge SoftDevice file %s" %
                                softdevice_and_offset_entry['name'])
            sdh = IntelHex(sdf)
            binh.merge(sdh)

        if t_self.target.MERGE_BOOTLOADER is True and blf is not None:
            t_self.notify.debug("Merge BootLoader file %s" % blf)
            blh = IntelHex(blf)
            binh.merge(blh)

        with open(binf.replace(".bin", ".hex"), "w") as fileout:
            binh.write_hex_file(fileout, write_start_addr=False)
示例#7
0
def main():
    sys.excepthook = lambda exctype, exc, traceback: print("{}: {}".format(
        exctype.__name__, exc))
    parser = argparse.ArgumentParser(description="Simple command line"
                                     " interface for UPDI programming")
    parser.add_argument(
        "-c",
        "--comport",
        required=True,
        help="Com port to use (Windows: COMx | *nix: /dev/ttyX)")
    parser.add_argument("-b", "--baudrate", type=int, default=500000)
    parser.add_argument("-f", "--flash", help="Intel HEX file to flash.")
    parser.add_argument("-i", "--id", help="Remote radio ID")
    parser.add_argument("-s", "--setid", help="Reprogram remote radio ID")
    parser.add_argument("-v",
                        "--verbose",
                        action='store_true',
                        help="Verbose output")
    args = parser.parse_args(sys.argv[1:])
    prog = Stk500(args.comport, args.baudrate, args.verbose)
    if args.id:
        prog.sendcommand(b'*cfg\n')
        prog.sendcommand(b'id %s\n' % args.id.encode('utf-8'))
    if args.setid:
        if not args.id:
            prog.sendcommand(b'*cfg\n')
        prog.sendcommand(b'setid %s\n' % args.setid.encode('utf-8'))
    if args.flash:
        ih = IntelHex()
        ih.loadhex(args.flash)
        prog.connect()
        for start, end in ih.segments():
            prog.program(start, ih.tobinarray(start, end))
        prog.close()
        print("Done!")
示例#8
0
    def load_ihex(self, filename):
        """
            Load from intel hex format
        """
        self.logger.info("Loading from hexfile '{}'".format(filename))
        from intelhex import IntelHex

        ih = IntelHex()
        ih.loadhex(filename)
        data = ih.tobinarray()
        start_address = ih.minaddr()
        self.logger.info(
            "Loaded {0:d} bytes from ihex starting at address 0x{1:04X}".
            format(len(data), start_address))

        # Size check
        if len(data) > self.device.flash_size:
            raise Exception("ihex too large for flash")

        # Offset to actual flash start
        if start_address < self.device.flash_start:
            self.logger.info(
                "Adjusting flash offset to address 0x{:04X}".format(
                    self.device.flash_start))
            start_address += self.device.flash_start

        return data, start_address
示例#9
0
class Driver(FirmwareBase):
    def __init__(self, filename, node, vcode, conn):
        FirmwareBase.__init__(self, filename, node, vcode, conn)

        self.__ih = IntelHex()
        self.__ih.loadhex(filename)

        cs = crc.crc16()
        for each in range(self.__ih.minaddr(), self.__ih.maxaddr()+1):
            cs.addByte(self.__ih[each])
        self.__size = self.__ih.maxaddr()+1
        self.__checksum = cs.getResult()


    def download(self):
        progress = 0.0
        self.sendStatus("Starting Download to Node " + str(self.destNode))
        while True:
            if self.kill==True:
                self.sendProgress(0.0)
                self.sendStatus("Download Stopped")
                return
            time.sleep(0.1)
            self.sendProgress(progress)
            progress = progress + 0.01
            if progress > 1: break
        self.sendProgress(1.0)
        self.sendStatus("Download Successful")
示例#10
0
def load_hex():
    """
    Load hex or binary file.
    :return:    intelhex object
    """
    if args.verbose:
        print("Loading %s..." % args.source)

    try:
        ih = IntelHex()

        if args.format == "hex":
            ih.loadhex(args.source)
        else:
            ih.loadbin(args.source, args.start_addr)

    except Exception as e:
        print(e)
        exit(1)

    if args.verbose:
        print("  Start: 0x%08x" % ih.minaddr())
        print("  End  : 0x%08x" % ih.maxaddr())

    return ih
示例#11
0
    def _load_ihex(self, filename, mem_size, mem_start):
        """
            Load from intel hex format
        """
        self.logger.info("Loading from hexfile '{}'".format(filename))
        from intelhex import IntelHex

        ih = IntelHex()
        ih.loadhex(filename)
        data = ih.tobinarray()

        start_address = ih.minaddr()
        if start_address is None:
            # This happens if an empty file is loaded.
            start_address = 0

        self.logger.info("Loaded {0:d} bytes from ihex starting at address 0x{1:04X}".format(len(data), start_address))

        # Size check
        if len(data) > mem_size:
            raise Exception("ihex too large for flash")

        # Offset to actual flash start
        if start_address < mem_start:
            self.logger.info("Adjusting offset to address 0x{:04X}".format(mem_start))
            start_address += mem_start

        return data, start_address
示例#12
0
文件: __init__.py 项目: SoCM/ELEC143
    def binary_hook(t_self, resources, _, binf):
        """Hook that merges the soft device with the bin file"""
        # Scan to find the actual paths of soft device
        sdf = None
        for softdevice_and_offset_entry\
            in t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS:
            for hexf in resources.hex_files:
                if hexf.find(softdevice_and_offset_entry['name']) != -1:
                    t_self.debug("SoftDevice file found %s."
                                 % softdevice_and_offset_entry['name'])
                    sdf = hexf

                if sdf is not None:
                    break
            if sdf is not None:
                break

        if sdf is None:
            t_self.debug("Hex file not found. Aborting.")
            return

        # Look for bootloader file that matches this soft device or bootloader
        # override image
        blf = None
        if t_self.target.MERGE_BOOTLOADER is True:
            for hexf in resources.hex_files:
                if hexf.find(t_self.target.OVERRIDE_BOOTLOADER_FILENAME) != -1:
                    t_self.debug("Bootloader file found %s."
                                 % t_self.target.OVERRIDE_BOOTLOADER_FILENAME)
                    blf = hexf
                    break
                elif hexf.find(softdevice_and_offset_entry['boot']) != -1:
                    t_self.debug("Bootloader file found %s."
                                 % softdevice_and_offset_entry['boot'])
                    blf = hexf
                    break

        # Merge user code with softdevice
        from intelhex import IntelHex
        binh = IntelHex()
        _, ext = os.path.splitext(binf)
        if ext == ".hex":
            binh.loadhex(binf)
        elif ext == ".bin":
            binh.loadbin(binf, softdevice_and_offset_entry['offset'])

        if t_self.target.MERGE_SOFT_DEVICE is True:
            t_self.debug("Merge SoftDevice file %s"
                         % softdevice_and_offset_entry['name'])
            sdh = IntelHex(sdf)
            binh.merge(sdh)

        if t_self.target.MERGE_BOOTLOADER is True and blf is not None:
            t_self.debug("Merge BootLoader file %s" % blf)
            blh = IntelHex(blf)
            binh.merge(blh)

        with open(binf.replace(".bin", ".hex"), "w") as fileout:
            binh.write_hex_file(fileout, write_start_addr=False)
示例#13
0
class FormatIntelHex(FormatReader, FormatWriter):
    def __init__(self):
        self.hexinstance = IntelHex()


    def load_file(self, filename=None):
        if filename is None:
            raise FormatError("Filename not specified.")

        file_extension = os.path.splitext(filename)[1][1 : ].lower()

        try:
            if file_extension == "bin":
                self.hexinstance.loadbin(filename)
            else:
                self.hexinstance.loadhex(filename)
        except:
            raise FormatError("Could not open %s file \"%s\"." %
                              (file_extension.upper(), filename))


    def save_file(self, filename):
        if filename is None:
            raise FormatError("Filename not specified.")

        file_extension = os.path.splitext(filename)[1][1 : ].lower()

        try:
            if file_extension == "bin":
                self.hexinstance.tofile(filename, format="bin")
            else:
                self.hexinstance.tofile(filename, format="hex")
        except:
            raise FormatError("Could not save %s file \"%s\"." %
                              (file_extension.upper(), filename))


    def add_section(self, start, data):
        self.hexinstance[start : start + len(data)] = data


    def get_sections(self):
        sections = dict()

        if self.hexinstance.minaddr() is not None:
            sections[None] = FormatIntelHex_Section(self.hexinstance)

        return sections


    @staticmethod
    def get_name():
        return "Intel HEX File Parser"


    @staticmethod
    def get_extensions():
        return ["hex", "eep"]
示例#14
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}
示例#15
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
示例#16
0
 def load_hexfile(self, hexfile: str) -> None:
     ih = IntelHex()
     ih.loadhex(hexfile)
     for (beg, end) in ih.segments():
         try:
             mem = bytes(ih.gets(beg, end - beg))
             self.emu.mem_write(beg, mem)
         except:
             print('Error loading %s at 0x%08x (%d bytes):' %
                   (hexfile, beg, len(mem)))
             raise
示例#17
0
 def load_hexfile(self, hexfile: str) -> None:
     ih = IntelHex()
     ih.loadhex(hexfile)
     beg = ih.minaddr()
     end = ih.maxaddr() + 1
     mem = bytes(ih.gets(beg, end - beg))
     try:
         self.emu.mem_write(beg, mem)
     except:
         print('Error loading %s at 0x%08x (%d bytes):' %
               (hexfile, beg, len(mem)))
         raise
示例#18
0
def intelhex_offset(filename, offset):
    """Load a hex or bin file at a particular offset"""
    _, inteltype = splitext(filename)
    ih = IntelHex()
    if inteltype == ".bin":
        ih.loadbin(filename, offset=offset)
    elif inteltype == ".hex":
        ih.loadhex(filename)
    else:
        raise ToolException("File %s does not have a known binary file type" %
                            filename)
    return ih
示例#19
0
文件: utils.py 项目: sg-/mbed-os
def intelhex_offset(filename, offset):
    """Load a hex or bin file at a particular offset"""
    _, inteltype = splitext(filename)
    ih = IntelHex()
    if inteltype == ".bin":
        ih.loadbin(filename, offset=offset)
    elif inteltype == ".hex":
        ih.loadhex(filename)
    else:
        raise ToolException("File %s does not have a known binary file type"
                            % filename)
    return ih
示例#20
0
def main(file, append, port, baud):
    """
    Receive a code file from an attached ELF with MAX binary sender.

    The program reads a MAX-format binary file from the specified
    serial port and stores in the given file.
    """
    class State(Enum):
        DATA = auto()
        ESCAPE = auto()
        ADDR_HI = auto()
        ADDR_LO = auto()
        DONE = auto()

    state = State.DATA
    address = 0

    intel_hex = IntelHex()

    if append:
        intel_hex.loadhex(file)

    with serial.serial_for_url(port) as ser:
        ser.baudrate = baud
        ser.write(constants.START_RECV)
        while state != State.DONE:
            data = ser.read(ser.in_waiting)
            for byte in data:
                if state == State.DATA:
                    if byte == constants.ESCAPE:
                        state = State.ESCAPE
                    elif byte == constants.END_OF_FILE:
                        state = State.DONE
                    elif byte == constants.NEW_ADDRESS:
                        state = State.ADDR_HI
                    else:
                        intel_hex[address] = byte
                        address += 1
                elif state == State.ESCAPE:
                    intel_hex[address] = byte ^ 0x20
                    address += 1
                    state = State.DATA
                elif state == State.ADDR_HI:
                    address = byte << 8
                    state = State.ADDR_LO
                elif state == State.ADDR_LO:
                    address |= byte
                    state = State.DATA

    intel_hex.write_hex_file(file)
示例#21
0
def read_hex_file(filename):
    """
    -Richter 2021
    Reads a hex file and generates flashable elements like with a dfu file
    """
    print("File: {}".format(filename))
    ih = IntelHex()
    ih.loadhex(filename)
    segments = ih.segments()
    print("Segments:", segments)
    elements = []
    for segId, segment in enumerate(segments):
        size = segment[1] - segment[0]
        dat = [ih[i] for i in range(segment[0], segment[1])]
        elem = {"addr": segment[0], "size": size, "num": segId, "data": dat}
        elements.append(elem)
    return elements
示例#22
0
    def merge_secure(t_self, resources, ns_elf, ns_hex):
        t_self.notify.info("Merging non-secure image with secure image")
        configured_secure_image_filename = t_self.target.secure_image_filename
        t_self.notify.info("Non-secure elf image %s" % ns_elf)
        t_self.notify.info("Non-secure hex image %s" % ns_hex)
        t_self.notify.info("Finding secure image %s" % configured_secure_image_filename)
        s_hex = find_secure_image(
            t_self.notify,
            resources,
            ns_hex,
            configured_secure_image_filename,
            FileType.HEX
        )
        t_self.notify.info("Found secure image %s" % s_hex)

        _, ext = os.path.splitext(s_hex)
        if ext != ".hex":
            t_self.notify.debug("Secure image %s must be in Intel HEX format" % s_hex)
            return
        if not os.path.isfile(s_hex):
            t_self.notify.debug("Secure image %s must be regular file" % s_hex)
            return

        ns_main, ext = os.path.splitext(ns_hex)
        if ext != ".hex":
            t_self.notify.debug("Non-secure image %s must be in Intel HEX format" % s_hex)
            return
        if not os.path.isfile(ns_hex):
            t_self.notify.debug("Non-secure image %s must be regular file" % s_hex)
            return

        # Keep original non-secure before merge with secure
        ns_nosecure_hex = ns_main + "_no-secure-merge" + ext
        t_self.notify.info("Keep no-secure-merge image %s" % ns_nosecure_hex)
        shutil.copy2(ns_hex, ns_nosecure_hex)

        # Merge secure and non-secure and save to non-secure (override it)
        from intelhex import IntelHex
        s_ih = IntelHex()
        s_ih.loadhex(s_hex)
        ns_ih = IntelHex()
        ns_ih.loadhex(ns_hex)
        ns_ih.start_addr = None
        s_ih.merge(ns_ih)
        s_ih.tofile(ns_hex, 'hex')
示例#23
0
def load_hex():
    """
    Load hex or binary file.
    :return:    intelhex object
    """
    if args.verbose:
        print "Loading %s..." % args.source

    try:
        ih = IntelHex()

        if args.format == "hex":
            ih.loadhex(args.source)
        else:
            ih.loadbin(args.source, args.start_addr)

    except Exception, e:
        print e
        exit(1)
示例#24
0
def ihexsize(ihexf, granularity=1):
    ih = IntelHex()
    ih.loadhex(ihexf)
    all_sections = ih.segments()
    low_addr = all_sections[0][0]
    high_addr = all_sections[0][1]
    logging.debug("input hex file sections:")
    for sec in all_sections:
        logging.debug("0x%08X 0x%08X" % (sec[0], sec[1] - 1))
        low_addr = min(low_addr, sec[0])
        high_addr = max(high_addr, sec[1])

    logging.debug("low_addr =0x%x" % low_addr)
    logging.debug("high_addr=0x%x" % high_addr)
    size = high_addr - low_addr
    part = size % granularity
    if 0 != part:
        size += granularity - part
    return size
示例#25
0
def load_hex():
    """
    Load hex or binary file.
    :return:    intelhex object
    """
    if args.verbose:
        print "Loading %s..." % args.source

    try:
        ih = IntelHex()

        if args.format == "hex":
            ih.loadhex(args.source)
        else:
            ih.loadbin(args.source, args.start_addr)

    except Exception, e:
        print e
        exit(1)
示例#26
0
    def __init__(self,
                 fw: Union[bytearray, bytes, str, BinaryIO],
                 be: Optional[bool] = None) -> None:
        self.base = None  # type: Optional[int]
        if isinstance(fw, str):
            if fw.lower().endswith('.hex'):
                ih = IntelHex()
                ih.loadhex(fw)
                self.base = ih.minaddr()
                self.fw = bytearray(ih.tobinstr())
            else:
                with open(fw, 'rb') as f:
                    self.fw = bytearray(f.read())
        elif isinstance(fw, bytes):
            self.fw = bytearray(fw)
        elif isinstance(fw, bytearray):
            self.fw = fw
        else:
            self.fw = bytearray(fw.read())

        self.size = len(self.fw)
        if self.size < 8 or (self.size & 3) != 0:
            raise ValueError('invalid firmware length')

        self.crc = crc32(self.fw[8:])

        if be is None:
            (lcrc, lsz) = struct.unpack_from('<II', self.fw)
            (bcrc, bsz) = struct.unpack_from('>II', self.fw)
            if (lcrc == self.crc
                    and lsz == self.size) or lsz == Firmware.SIZE_MAGIC:
                self.be = False
            elif (bcrc == self.crc
                  and bsz == self.size) or bsz == Firmware.SIZE_MAGIC:
                self.be = True
            else:
                raise ValueError('could not determine firmware endianness')
        else:
            self.be = be
        self.ep = '>' if be else '<'

        (self.hcrc, self.hsize) = struct.unpack_from(self.ep + 'II', self.fw)
示例#27
0
def read_from_file(file_path):
    if file_path.lower().endswith('.hex'):
        try:
            from intelhex import IntelHex
        except ImportError:
            print(
                'To open HEX files install IntelHex library:\npip install IntelHex\npip3 install IntelHex'
            )
            sys.exit(3)
        ih = IntelHex()
        ih.loadhex(file_path)
        logging.info('Was readed 0x{0:X} ({0}) byte(s): 0x{1:X}..{2:X}'.format(
            ih.maxaddr() - ih.minaddr() + 1, ih.minaddr(), ih.maxaddr()))
        return bytearray(ih.gets(ih.minaddr(),
                                 ih.maxaddr() - ih.minaddr() + 1))
    logging.info('Read from binary file "{0}"'.format(file_path))
    f = BinFormat()
    f.read(file_path)
    logging.info('Was readed 0x{0:X} ({0}) byte(s)'.format(len(f.data)))
    return f.data
示例#28
0
def main():
    parser = argparse.ArgumentParser(description="Bootloader CRC patcher")
    parser.add_argument('filename', help='Intel HEX file to patch')
    args = parser.parse_args()

    if not args.filename.lower().endswith('.hex'):
        print("Not a .hex file?")
        return

    ih = IntelHex()
    ih.loadhex(args.filename)
    data = ih.tobinstr(start=0, size=0x100)
    offset = data.find(b'\xCC\xCC')
    if offset < 0:
        return
    crc = fixcrc16pos(data, offset)
    print('Patching with CRC of %04X' % crc)
    ih[offset] = crc >> 8
    ih[offset + 1] = crc & 255
    #data = ih.tobinstr(start=0, size=0x100)
    #print('Final CRC = %04X' % crc16(data))
    ih.write_hex_file(args.filename)
示例#29
0
def sbl_demo_main():
    args_min = 2
    args_max = 2
    if (len(sys.argv) > (args_max + 1)) | (len(sys.argv) < (args_min + 1)):
        print("ERROR: incorrect arguments")
        print("Usage:")
        print("name <device> <ihex file>")
        exit()

    device = sys.argv[1]
    ihexf = sys.argv[2]

    ser = serial.Serial(device, baudrate=115200, exclusive=True)
    ser.reset_input_buffer()
    #print(SBL.hexstr(ser.read(215)))
    sbl = SBL(ser)
    ih = IntelHex()
    ih.loadhex(ihexf)
    sbl.load_ihex(ih)
    sbl.verify_ihex(ih)

    #append the start address info on 4 bytes, little endian
    if ih.start_addr is None:
        print("ERROR: no start address defined in the hex file")
        exit(-1)

    try:
        start = ih.start_addr['EIP']
    except:
        start = ih.start_addr['IP'] + (ih.start_addr['CS'] << 4)
    #print(ih.start_addr)
    #print("start=0x%08x"%start)

    print(SBL.hexstr(sbl.exec(address=start, rxsize=32, waitack=False)))

    sys.stdout.flush()
示例#30
0
async def file_service():  # config r/w
    for cfg in os.listdir('configs'):
        if cfg.endswith('.json'):
            csa['cfgs'].append(cfg)

    sock = CDWebSocket(ws_ns, 'file')
    while True:
        dat, src = await sock.recvfrom()
        logger.debug(f'file ser: {dat}')

        if dat['action'] == 'get_cfgs':
            await sock.sendto(csa['cfgs'], src)

        elif dat['action'] == 'get_cfg':
            with open(os.path.join('configs', dat['cfg'])) as c_file:
                c = json5.load(c_file)
                await sock.sendto(c, src)

        elif dat['action'] == 'get_ihex':
            ret = []
            ih = IntelHex()
            try:
                ih.loadhex(dat['path'])
                segs = ih.segments()
                logger.info(
                    f'parse ihex file, segments: {[list(map(hex, l)) for l in segs]} (end addr inclusive)'
                )
                for seg in segs:
                    s = [seg[0], ih.tobinstr(seg[0], size=seg[1] - seg[0])]
                    ret.append(s)
            except Exception as err:
                logger.error(f'parse ihex file error: {err}')
            await sock.sendto(ret, src)

        else:
            await sock.sendto('err: file: unknown cmd', src)
#coding: UTF-8

# Prerequisite: pip install IntelHex

from intelhex import IntelHex
import struct
import sys
import os

args = sys.argv

if (len(args) != 3):
    print("Usage: python " + args[0] + " [input hex] [output hex]")
    sys.exit()

s = args[1]

ih = IntelHex()
ih.loadhex(args[1])
ih.write_hex_file(args[2], byte_count=16)
示例#32
0
#============ MAIN ==============

if __name__ == '__main__':
    if len(sys.argv) is 2:
        HexFile = sys.argv[1]
    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)
示例#33
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')
                      ('SD_FWID',    0x0C, lambda x, y: hex(_read_u16(x,y))),
                      ('SD_ID',      0x10, lambda x, y: str(_read_u32(x,y))),
                      ('SD_VERSION', 0x14, _read_sd_version))


if ("__main__" == __name__):
    if (2 == len(sys.argv)):
        file_name = sys.argv[1]
    else:
        print "ERROR: Usage is 'python sd_info_struct.py <file_name>'."
        sys.exit(-1)

    ih = IntelHex()
    try:
        if (file_name.lower().endswith('.hex')):
            ih.loadhex(file_name)
        else:
            ih.loadbin(file_name)
    except:
        print "ERROR: Could not open the data file."
        sys.exit(-1)

    magic_number = _read_u32(ih, (SOFTDEVICE_INFO_STRUCT_ADDRESS + SD_MAGIC_NUMBER_OFFSET))
    if (SD_MAGIC_NUMBER_VALUE != magic_number):
        print "ERROR: SD magic number not found."
        sys.exit(-1)

    print "\nSoftDevice information structure for '%s':" % os.path.basename(file_name)
    for t in INFO_STRUCT_TUPLES:
        print '  {0:<12}{1}'.format(t[0] + ':', t[2](ih, (SOFTDEVICE_INFO_STRUCT_ADDRESS + t[1])))
示例#35
0
class Driver(FirmwareBase):
    def __init__(self, filename, can):
        FirmwareBase.__init__(self)
        self.__ih = IntelHex()
        self.__ih.loadhex(filename)
        self.can = can
        
        cs = crc.crc16()
        for each in range(self.__ih.minaddr(), self.__ih.maxaddr()+1):
            cs.addByte(self.__ih[each])
        self.__size = self.__ih.maxaddr()+1
        self.__checksum = cs.getResult()
        self.__progress = 0.0
        self.__blocksize = 128
        self.__blocks = self.__size / self.__blocksize + 1
        self.__currentblock = 0


    def __fillBuffer(self, ch, address, data):
        sframe = canbus.Frame(1760 + ch, [0x01, address & 0xFF, (address & 0xFF00) >> 8, 128])
        self.can.sendFrame(sframe)
        endtime = time.time() + 0.5
        while True: # Channel wait loop
            try:
                rframe = self.can.recvFrame()
            except canbus.DeviceTimeout:
                pass
            else:
                if rframe.id == sframe.id+1 and \
                    rframe.data == sframe.data: break
                now = time.time()
                if now > endtime:
                    return False
        for n in range(self.__blocksize / 8):
            #print data[address + (8*n):address + (8*n) + 8]
            sframe.data = data[address + (8*n):address + (8*n) + 8]
            self.can.sendFrame(sframe)
            #time.sleep(0.3)
            # TODO Need to deal with the abort from the uC somewhere
        return True

    def __erasePage(self, ch, address):
        sframe = canbus.Frame(1760 + ch, [0x02, address & 0xFF, (address & 0xFF00) >> 8, 64])
        self.can.sendFrame(sframe)
        endtime = time.time() + 0.5
        while True: # Channel wait loop
            try:
                rframe = self.can.recvFrame()
            except canbus.DeviceTimeout:
                pass
            else:
                if rframe.id == sframe.id+1 and \
                    rframe.data == sframe.data: break
                now = time.time()
                if now > endtime: return False

    def __writePage(self, ch, address):
        sframe = canbus.Frame(1760 + ch, [0x03, address & 0xFF, (address & 0xFF00) >> 8])
        self.can.sendFrame(sframe)
        endtime = time.time() + 0.5
        while True: # Channel wait loop
            try:
                rframe = self.can.recvFrame()
            except canbus.DeviceTimeout:
                pass
            else:
                if rframe.id == sframe.id+1 and \
                    rframe.data == sframe.data: break
                now = time.time()
                if now > endtime: return False

    def __sendComplete(self, ch):
        sframe = canbus.Frame(1760 + ch, [0x05, self.__checksum & 0xFF, (self.__checksum & 0xFF00) >> 8, \
                            self.__size & 0xFF, (self.__size & 0xFF00) >> 8])
        self.can.sendFrame(sframe)
        endtime = time.time() + 0.5
        while True: # Channel wait loop
            try:
                rframe = self.can.recvFrame()
            except canbus.DeviceTimeout:
                pass
            else:
                if rframe.id == sframe.id+1 and \
                    rframe.data == sframe.data: break
                now = time.time()
                if now > endtime: return False

    def download(self, node):
        data=[]
        channel = FirmwareBase.start_download(self, node)
        for n in range(self.__blocks * self.__blocksize):
            data.append(self.__ih[n])
        for block in range(self.__blocks):
            address = block * 128
            #print "Buffer Fill at %d" % (address)
            self.sendStatus("Writing Block %d of %d" % (block, self.__blocks))
            self.sendProgress(float(block) / float(self.__blocks))
            self.__currentblock = block
            while(self.__fillBuffer(channel, address, data)==False):
                if self.kill:
                    self.sendProgress(0.0)
                    self.sendStatus("Download Stopped")
                    return
                    #raise firmware.FirmwareError("Canceled")
            
            # Erase Page
            #print "Erase Page Address =", address
            self.__erasePage(channel ,address)
            
            # Write Page
            #print "Write Page Address =", address
            self.__writePage(channel ,address)
            
        #self.__progress = 1.0
        #print "Download Complete Checksum", hex(self.__checksum), "Size", self.__size
        self.__sendComplete(channel)
        self.sendStatus("Download Complete Checksum 0x%X, Size %d" % (self.__checksum, self.__size))
        self.sendProgress(1.0)
        #FirmwareBase.end_download()
示例#36
0
        "phyihex.py: format an ihex to match exactly physical memory map (pad with 0xFF)"
    )
    print("Usage:")
    print("phyihex.py <ihex> <start> <end> [<start> <end>]*")
    exit()

ihexf = sys.argv[1]
sections = []
for i in range(2, len(sys.argv), 2):
    start = int(sys.argv[i], 0)
    end = int(sys.argv[i + 1], 0)
    sections.append([start, end + 1])

ih = IntelHex()
iho = IntelHex()
ih.loadhex(ihexf)
all_sections = ih.segments()
print("input hex file sections:")
for sec in all_sections:
    print("0x%08X 0x%08X" % (sec[0], sec[1] - 1))

#copy all regular sections
for sec in sections:
    for i in range(sec[0], sec[1]):
        iho[i] = ih[i]

#copy start address
#print("start address: ",ih.start_addr)
iho.start_addr = ih.start_addr

iho.write_hex_file(ihexf + ".phy.ihex")
import sys
from intelhex import IntelHex

ih = IntelHex()
ih.loadhex(sys.argv[1])

singleROMsize = 8192
totalMemoryLocations = (4 * singleROMsize)

prefix = """`timescale 1ns/1ps

module CustomRom_8192X32
#(
	parameter ADDRESS_WIDTH  = 16,
	parameter ROM_ARRAY_PATH = ""
	)
(
		input logic 					CK,
		input logic						CSB,
		input logic	[ADDRESS_WIDTH-1:0]				A,
		output logic [31:0]		DO
);
localparam  ROMS = 8;

logic [ADDRESS_WIDTH-1:0] address_q;
"""

newRom = """const logic [0:8191] [31:0] ROM_TABLE_{} = {{\n"""

suffix = """};
示例#38
0
def decode(record):
    h = IntelHex()
    f = StringIO(record)
    h.loadhex(f)
    h.dump()
示例#39
0
if __name__ == '__main__':
  if len(sys.argv) is 2:
    HexFile = sys.argv[1]
  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'


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

CpuId=0
print "Scan CPU "

for l in AllCpuFamily:
示例#40
0
文件: send.py 项目: zzzzz00000/z88dk
def send(filename, device, delay=50):

    suffix = os.path.splitext(filename)[-1]

    f = serial.Serial(port=device,
                      baudrate=9600,
                      bytesize=EIGHTBITS,
                      parity=PARITY_NONE,
                      stopbits=STOPBITS_ONE,
                      timeout=None,
                      xonxoff=False,
                      rtscts=True,
                      write_timeout=None,
                      dsrdtr=False,
                      inter_byte_timeout=None)

    dat = []
    if suffix == ".ihx":
        app = IntelHex()
        app.loadhex(filename)
        sio = StringIO.StringIO()
        app[0x100::].write_hex_file(sio)
        dat = sio.getvalue().split('\n')

        maxaddr = app.maxaddr()
        print()
        print("Target: %s" % filename)
        print()
        print("Type your pocket-computer:")
        print()
        print(">MON")
        print("*USER%04X" % maxaddr)
        print("*R")
        print()
        print("please hit enter when you are ready.")
        input()

    elif suffix == ".txt":
        print()
        print("Target: %s" % filename)
        print()
        dat = open(filename).readlines().split('\n')
        print("please hit enter when you are ready.")
        input()

    else:
        print("cannot transfer %s file. use ihx or txt" % suffix)
        exit()

    print("Sending...")

    f.reset_output_buffer()

    for line in dat:
        if len(line) == 0:
            break
        if line[-1] == '\n':
            line = line[:-1]

        for x in line:
            puts(f, x.encode())
        puts(f, b'\r\n')  # CR LF

        #print(line+"\r\n", end="")
        sleep(0.001 * delay)

    puts(f, b'\x1a')  # End of File
    f.flush()
    f.close()