Example #1
0
    def run(self, args=None):
        self.args = self.build_parser().parse_args(args)
        self.gdb_server_settings = self.get_gdb_server_settings(self.args)
        self.setup_logging(self.args)
        DAPAccess.set_args(self.args.daparg)

        self.process_commands(self.args.commands)

        gdb = None
        if self.args.list_all == True:
            self.list_boards()
        elif self.args.list_targets == True:
            self.list_targets()
        else:
            try:
                board_selected = MbedBoard.chooseBoard(
                    board_id=self.args.board_id,
                    target_override=self.args.target_override,
                    frequency=self.args.frequency)
                with board_selected as board:
                    gdb = GDBServer(board, self.args.port_number, self.gdb_server_settings)
                    while gdb.isAlive():
                        gdb.join(timeout=0.5)
            except KeyboardInterrupt:
                if gdb != None:
                    gdb.stop()
            except Exception as e:
                print "uncaught exception: %s" % e
                traceback.print_exc()
                if gdb != None:
                    gdb.stop()
                return 1

        # Successful exit.
        return 0
Example #2
0
    def run(self, args=None):
        self.args = self.build_parser().parse_args(args)
        self.gdb_server_settings = self.get_gdb_server_settings(self.args)
        self.setup_logging(self.args)
        DAPAccess.set_args(self.args.daparg)

        self.process_commands(self.args.commands)

        gdb = None
        if self.args.list_all == True:
            self.list_boards()
        elif self.args.list_targets == True:
            self.list_targets()
        else:
            try:
                board_selected = MbedBoard.chooseBoard(
                    board_id=self.args.board_id,
                    target_override=self.args.target_override,
                    frequency=self.args.frequency)
                with board_selected as board:
                    gdb = GDBServer(board, self.args.port_number, self.gdb_server_settings)
                    while gdb.isAlive():
                        gdb.join(timeout=0.5)
            except KeyboardInterrupt:
                if gdb != None:
                    gdb.stop()
            except Exception as e:
                print "uncaught exception: %s" % e
                traceback.print_exc()
                if gdb != None:
                    gdb.stop()
                return 1

        # Successful exit.
        return 0
Example #3
0
def parallel_test():
    """Test that devices can be found and opened in parallel"""
    device_list = DAPAccess.get_connected_devices()
    id_list = [device.get_unique_id() for device in device_list]
    id_list.sort()

    if len(id_list) < 2:
        print("Need at least 2 boards to run the parallel test")
        exit(-1)

    # Goal of this file is to test that:
    # -The process of listing available boards does not interfere
    #  with other processes enumerating, opening, or using boards
    # -Opening and using a board does not interfere with another process
    #  processes which is enumerating, opening, or using boards as
    # long as that is not the current board

    print("Listing board from multiple threads at the same time")
    args_list = [(id_list,) for _ in range(5)]
    run_in_parallel(list_boards, args_list)

    print("Listing board from multiple processes at the same time")
    run_in_processes(list_boards, args_list)

    print("Opening same board from multiple threads at the same time")
    device = DAPAccess.get_device(id_list[0])
    device.open()
    open_already_opened(id_list[0])
    args_list = [(id_list[0],) for _ in range(5)]
    run_in_parallel(open_already_opened, args_list)
    device.close()

    print("Opening same board from multiple processes at the same time")
    device = DAPAccess.get_device(id_list[0])
    device.open()
    open_already_opened(id_list[0])
    args_list = [(id_list[0],) for _ in range(5)]
    run_in_processes(open_already_opened, args_list)
    device.close()

    print("Opening different boards from different threads")
    args_list = [(board_id,) for board_id in id_list]
    run_in_parallel(search_and_lock, args_list)

    print("Opening different boards from different processes")
    run_in_processes(search_and_lock, args_list)

    print("Test passed")
Example #4
0
    def run(self, args=None):
        try:
            self.args = self.build_parser().parse_args(args)
            self.gdb_server_settings = self.get_gdb_server_settings(self.args)
            self.setup_logging(self.args)
            DAPAccess.set_args(self.args.daparg)

            self.process_commands(self.args.commands)

            gdb = None
            gdbs = []
            if self.args.list_all == True:
                self.list_boards()
            elif self.args.list_targets == True:
                self.list_targets()
            else:
                try:
                    board_selected = MbedBoard.chooseBoard(
                        board_id=self.args.board_id,
                        target_override=self.args.target_override,
                        frequency=self.args.frequency)
                    if board_selected is None:
                        print("No board selected")
                        return 1
                    with board_selected as board:
                        baseTelnetPort = self.gdb_server_settings['telnet_port']
                        for core_number, core in board.target.cores.iteritems():
                            self.gdb_server_settings['telnet_port'] = baseTelnetPort + core_number
                            gdb = GDBServer(board, self.args.port_number + core_number, self.gdb_server_settings, core=core_number)
                            gdbs.append(gdb)
                        gdb = gdbs[0]
                        while gdb.isAlive():
                            gdb.join(timeout=0.5)
                except KeyboardInterrupt:
                    for gdb in gdbs:
                        gdb.stop()
                except Exception as e:
                    print("uncaught exception: %s" % e)
                    traceback.print_exc()
                    for gdb in gdbs:
                        gdb.stop()
                    return 1

            # Successful exit.
            return 0
        except InvalidArgumentError as e:
            self.parser.error(e)
            return 1
Example #5
0
def open_already_opened(board_id):
    """Open a device that is already open to verify it gives an error"""
    device = DAPAccess.get_device(board_id)
    try:
        device.open()
        assert False
    except DAPAccess.DeviceError:
        pass
Example #6
0
def search_and_lock(board_id):
    """Repeatedly lock a board with the given ID"""
    for _ in range(0, 20):
        device = DAPAccess.get_device(board_id)
        device.open()
        device.close()
        with MbedBoard.chooseBoard(board_id=board_id):
            pass
Example #7
0
def list_boards(id_list):
    """List all connected DAPLink boards repeatedly

    Assert that they are the same as the id list passed in.
    """
    for _ in range(0, 20):
        device_list = DAPAccess.get_connected_devices()
        found_id_list = [device.get_unique_id() for device in device_list]
        found_id_list.sort()
        assert id_list == found_id_list, "Expected %s, got %s" % \
            (id_list, found_id_list)
Example #8
0
    def run(self):
        try:
            # Read command-line arguments.
            self.args = self.get_args()
            self.cmd = self.args.cmd
            if self.cmd:
                self.cmd = self.cmd.lower()

            # Set logging level
            self.configure_logging()
            DAPAccess.set_args(self.args.daparg)

            # Check for a valid command.
            if self.cmd and self.cmd not in self.command_list:
                print "Error: unrecognized command '%s'" % self.cmd
                return 1

            # List command must be dealt with specially.
            if self.cmd == 'list':
                self.handle_list([])
                return 0

            if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ:
                print "Setting SWD clock to %d kHz" % self.args.clock

            # Connect to board.
            self.board = MbedBoard.chooseBoard(
                board_id=self.args.board,
                target_override=self.args.target,
                init_board=False,
                frequency=(self.args.clock * 1000))
            self.board.target.setAutoUnlock(False)
            self.board.target.setHaltOnConnect(False)
            try:
                self.board.init()
            except Exception as e:
                print "Exception while initing board: %s" % e
                traceback.print_exc()
                self.exitCode = 1
                return self.exitCode

            self.target = self.board.target
            self.link = self.board.link
            self.flash = self.board.flash

            self.svd_device = self.target.svd_device
            self.peripherals = {}
            if self.svd_device:
                for p in self.svd_device.peripherals:
                    self.peripherals[p.name.lower()] = p

            # Halt if requested.
            if self.args.halt:
                self.handle_halt([])

            # Handle a device with flash security enabled.
            self.didErase = False
            if self.target.isLocked() and self.cmd != 'unlock':
                print "Error: Target is locked, cannot complete operation. Use unlock command to mass erase and unlock."
                if self.cmd and self.cmd not in ['reset', 'info']:
                    return 1

            # If no command, enter interactive mode.
            if not self.cmd:
                # Say what we're connected to.
                print "Connected to %s [%s]: %s" % (
                    self.target.part_number,
                    CORE_STATUS_DESC[self.target.getState()],
                    self.board.getUniqueID())

                # Remove list command that disrupts the connection.
                self.command_list.pop('list')
                COMMAND_INFO.pop('list')

                # Run the command line.
                console = PyOCDConsole(self)
                console.run()
            else:
                # Invoke action handler.
                result = self.command_list[self.cmd](self.args.args)
                if result is not None:
                    self.exitCode = result

        except ToolExitException:
            self.exitCode = 0
        except ValueError:
            print "Error: invalid argument"
        except DAPAccess.TransferError:
            print "Error: transfer failed"
            traceback.print_exc()
            self.exitCode = 2
        except ToolError as e:
            print "Error:", e
            self.exitCode = 1
        finally:
            if self.board != None:
                # Pass false to prevent target resume.
                self.board.uninit(False)

        return self.exitCode
Example #9
0
            else:
                print("TEST FAILED")
            test_count += 1

        print("\n\nTest Summary:")
        print("Pass count %i of %i tests" % (test_pass_count, test_count))
        if test_pass_count == test_count:
            print("FLASH TEST SCRIPT PASSED")
        else:
            print("FLASH TEST SCRIPT FAILED")

        target.reset()

        result.passed = test_count == test_pass_count
        return result

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='pyOCD flash test')
    parser.add_argument('-d', '--debug', action="store_true", help='Enable debug logging')
    parser.add_argument("-da", "--daparg", dest="daparg", nargs='+', help="Send setting to DAPAccess layer.")
    args = parser.parse_args()
    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=level)
    DAPAccess.set_args(args.daparg)
    # Set to debug to print some of the decisions made while flashing
    board = pyOCD.board.mbed_board.MbedBoard.getAllConnectedBoards(close=True)[0]
    test = FlashTest()
    result = [test.run(board)]
    test.print_perf_info(result)

Example #10
0
def main():
    args = parser.parse_args()
    setup_logging(args)
    DAPAccess.set_args(args.daparg)

    # Sanity checks before attaching to board
    if args.format == 'hex' and not intelhex_available:
        print("Unable to program hex file")
        print("Module 'intelhex' must be installed first")
        exit()

    if args.list_all:
        MbedBoard.listConnectedBoards()
    else:
        board_selected = MbedBoard.chooseBoard(board_id=args.board_id, target_override=args.target_override,
                                               frequency=args.frequency, blocking=False)
        if board_selected is None:
            print("Error: There is no board connected.")
            sys.exit(1)
        with board_selected as board:
            flash = board.flash
            link = board.link

            # Boost speed with deferred transfers
            link.set_deferred_transfer(True)

            progress = print_progress
            if args.hide_progress:
                progress = None

            has_file = args.file is not None

            chip_erase = None
            if args.chip_erase:
                chip_erase = True
            elif args.sector_erase:
                chip_erase = False

            if not has_file:
                if chip_erase:
                    print("Erasing chip...")
                    flash.init()
                    flash.eraseAll()
                    print("Done")
                elif args.sector_erase and args.address is not None:
                    flash.init()
                    page_addr = args.address
                    for i in range(args.count):
                        page_info = flash.getPageInfo(page_addr)
                        if not page_info:
                            break
                        # Align page address on first time through.
                        if i == 0:
                            delta = page_addr % page_info.size
                            if delta:
                                print("Warning: sector address 0x%08x is unaligned" % page_addr)
                                page_addr -= delta
                        print("Erasing sector 0x%08x" % page_addr)
                        flash.erasePage(page_addr)
                        page_addr += page_info.size
                else:
                    print("No operation performed")
                return

            # If no format provided, use the file's extension.
            if not args.format:
                args.format = os.path.splitext(args.file)[1][1:]

            # Binary file format
            if args.format == 'bin':
                # If no address is specified use the start of rom
                if args.address is None:
                    args.address = board.flash.getFlashInfo().rom_start

                with open(args.file, "rb") as f:
                    f.seek(args.skip, 0)
                    data = f.read()
                args.address += args.skip
                data = unpack(str(len(data)) + 'B', data)
                flash.flashBlock(args.address, data, chip_erase=chip_erase, progress_cb=progress,
                                 fast_verify=args.fast_program)

            # Intel hex file format
            elif args.format == 'hex':
                hex = IntelHex(args.file)
                addresses = hex.addresses()
                addresses.sort()

                flash_builder = flash.getFlashBuilder()

                data_list = list(ranges(addresses))
                for start, end in data_list:
                    size = end - start + 1
                    data = list(hex.tobinarray(start=start, size=size))
                    flash_builder.addData(start, data)
                flash_builder.program(chip_erase=chip_erase, progress_cb=progress, fast_verify=args.fast_program)

            else:
                print("Unknown file format '%s'" % args.format)
Example #11
0
    def run(self):
        try:
            # Read command-line arguments.
            self.args = self.get_args()
            self.cmd = self.args.cmd
            if self.cmd:
                self.cmd = self.cmd.lower()

            # Set logging level
            self.configure_logging()
            DAPAccess.set_args(self.args.daparg)

            # Check for a valid command.
            if self.cmd and self.cmd not in self.command_list:
                print "Error: unrecognized command '%s'" % self.cmd
                return 1

            # Handle certain commands without connecting.
            if self.cmd == 'list':
                self.handle_list([])
                return 0
            elif self.cmd == 'help':
                self.handle_help(self.args.args)
                return 0

            if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ:
                print "Setting SWD clock to %d kHz" % self.args.clock

            # Connect to board.
            self.board = MbedBoard.chooseBoard(board_id=self.args.board, target_override=self.args.target, init_board=False, frequency=(self.args.clock * 1000))
            self.board.target.setAutoUnlock(False)
            self.board.target.setHaltOnConnect(False)
            try:
                if not self.args.no_init:
                    self.board.init()
            except DAPAccess.TransferFaultError as e:
                if not self.board.target.isLocked():
                    print "Transfer fault while initing board: %s" % e
                    traceback.print_exc()
                    self.exitCode = 1
                    return self.exitCode
            except Exception as e:
                print "Exception while initing board: %s" % e
                traceback.print_exc()
                self.exitCode = 1
                return self.exitCode

            self.target = self.board.target
            self.link = self.board.link
            self.flash = self.board.flash

            self.svd_device = self.target.svd_device
            self.peripherals = {}
            if self.svd_device:
                for p in self.svd_device.peripherals:
                    self.peripherals[p.name.lower()] = p

            # Halt if requested.
            if self.args.halt:
                self.handle_halt([])

            # Handle a device with flash security enabled.
            self.didErase = False
            if not self.args.no_init and self.target.isLocked() and self.cmd != 'unlock':
                print "Warning: Target is locked, limited operations available. Use unlock command to mass erase and unlock."

            # If no command, enter interactive mode.
            if not self.cmd:
                if not self.args.no_init:
                    try:
                        # Say what we're connected to.
                        print "Connected to %s [%s]: %s" % (self.target.part_number,
                            CORE_STATUS_DESC[self.target.getState()], self.board.getUniqueID())
                    except DAPAccess.TransferFaultError:
                        pass

                # Run the command line.
                console = PyOCDConsole(self)
                console.run()
            else:
                # Invoke action handler.
                result = self.command_list[self.cmd](self.args.args)
                if result is not None:
                    self.exitCode = result

        except ToolExitException:
            self.exitCode = 0
        except ValueError:
            print "Error: invalid argument"
        except DAPAccess.TransferError:
            print "Error: transfer failed"
            traceback.print_exc()
            self.exitCode = 2
        except ToolError as e:
            print "Error:", e
            self.exitCode = 1
        finally:
            if self.board != None:
                # Pass false to prevent target resume.
                self.board.uninit(False)

        return self.exitCode
Example #12
0
def main():
    args = parser.parse_args()
    setup_logging(args)
    DAPAccess.set_args(args.daparg)

    # Sanity checks before attaching to board
    if args.format == 'hex' and not intelhex_available:
        print("Unable to program hex file")
        print("Module 'intelhex' must be installed first")
        exit()

    if args.list_all:
        MbedBoard.listConnectedBoards()
    else:
        board_selected = MbedBoard.chooseBoard(
            board_id=args.board_id,
            target_override=args.target_override,
            frequency=args.frequency,
            blocking=False)
        if board_selected is None:
            print("Error: There is no board connected.")
            sys.exit(1)
        with board_selected as board:
            flash = board.flash
            link = board.link

            progress = print_progress
            if args.hide_progress:
                progress = None

            has_file = args.file is not None

            chip_erase = None
            if args.chip_erase:
                chip_erase = True
            elif args.sector_erase:
                chip_erase = False

            if args.mass_erase:
                print("Mass erasing device...")
                if board.target.massErase():
                    print("Successfully erased.")
                else:
                    print("Failed.")
                return

            if not has_file:
                if chip_erase:
                    print("Erasing chip...")
                    flash.init()
                    flash.eraseAll()
                    print("Done")
                elif args.sector_erase and args.address is not None:
                    flash.init()
                    page_addr = args.address
                    for i in range(args.count):
                        page_info = flash.getPageInfo(page_addr)
                        if not page_info:
                            break
                        # Align page address on first time through.
                        if i == 0:
                            delta = page_addr % page_info.size
                            if delta:
                                print(
                                    "Warning: sector address 0x%08x is unaligned"
                                    % page_addr)
                                page_addr -= delta
                        print("Erasing sector 0x%08x" % page_addr)
                        flash.erasePage(page_addr)
                        page_addr += page_info.size
                else:
                    print("No operation performed")
                return

            # If no format provided, use the file's extension.
            if not args.format:
                args.format = os.path.splitext(args.file)[1][1:]

            # Binary file format
            if args.format == 'bin':
                # If no address is specified use the start of rom
                if args.address is None:
                    args.address = board.flash.getFlashInfo().rom_start

                with open(args.file, "rb") as f:
                    f.seek(args.skip, 0)
                    data = f.read()
                args.address += args.skip
                data = unpack(str(len(data)) + 'B', data)
                flash.flashBlock(args.address,
                                 data,
                                 chip_erase=chip_erase,
                                 progress_cb=progress,
                                 fast_verify=args.fast_program)

            # Intel hex file format
            elif args.format == 'hex':
                hex = IntelHex(args.file)
                addresses = hex.addresses()
                addresses.sort()

                flash_builder = flash.getFlashBuilder()

                data_list = list(ranges(addresses))
                for start, end in data_list:
                    size = end - start + 1
                    data = list(hex.tobinarray(start=start, size=size))
                    flash_builder.addData(start, data)
                flash_builder.program(chip_erase=chip_erase,
                                      progress_cb=progress,
                                      fast_verify=args.fast_program)

            else:
                print("Unknown file format '%s'" % args.format)
Example #13
0
def _ap_addr_to_reg(addr):
    return DAPAccess.REG(4 + ((addr & 0x0c) >> 2))