def run(self):
        self.args = self.build_parser().parse_args()
        self.gdb_server_settings = self.get_gdb_server_settings(self.args)
        self.setup_logging(self.args)

        self.process_commands(self.args.commands)

        gdb = None
        if self.args.list_all == True:
            MbedBoard.listConnectedBoards()
        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:
                    # Boost speed with deferred transfers
                    board.transport.setDeferredTransfer(True)
                    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
Exemple #2
0
def main():
    args = parser.parse_args()
    setup_logging(args)

    # 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)
        with board_selected as board:
            flash = board.flash
            transport = board.transport

            # Boost speed with deferred transfers
            transport.setDeferredTransfer(True)

            progress = print_progress
            if args.hide_progress:
                progress = None

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

            # 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
            if 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)
Exemple #3
0
def main():
    args = parser.parse_args()
    gdb_server_settings = get_gdb_server_settings(args)
    setup_logging(args)

    gdb = None
    if args.list_all == True:
        MbedBoard.listConnectedBoards()
    else:
        try:
            board_selected = MbedBoard.chooseBoard(
                board_id=args.board_id,
                target_override=args.target_override,
                frequency=args.frequency)
            with board_selected as board:
                # Boost speed with deferred transfers
                board.transport.setDeferredTransfer(True)
                gdb = GDBServer(board, args.port_number, 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()
Exemple #4
0
def getAdapter():
    '''
    Get a CMSIS DAP debug adapter
    '''
    interfaces = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
    if interfaces == None:
        print "Not find a mbed interface"
        sys.exit(1)

    first_interface = interfaces[0]
    adapter = MbedBoard("target_lpc1768", "flash_lpc1768", first_interface)
    adapter.init()
    return adapter
Exemple #5
0
def _launchPyOCDGDBServer(msg_queue):
    logger.info('starting PyOCD gdbserver...')
    # ignore Ctrl-C, so we don't interrupt the GDB server when the
    # being-debugged program is being stopped:
    signal.signal(signal.SIGINT, _ignoreSignal);
    from pyOCD.gdbserver import GDBServer
    from pyOCD.board import MbedBoard
    gdb = None
    try:
        board_selected = MbedBoard.chooseBoard()
        with board_selected as board:
            gdb = GDBServer(
                board, 3333, {
                     'break_at_hardfault': True,
                    'step_into_interrupt': False,
                         'break_on_reset': False,
                }
            )
            if gdb.isAlive():
                msg_queue.put('alive')
                while gdb.isAlive():
                    gdb.join(timeout = 0.5)
                    # check for a "kill" message from the parent process:
                    try:
                        msg = msg_queue.get(False)
                        if msg == 'kill':
                            gdb.stop()
                            break
                    except Queue.Empty:
                        pass
    except Exception as e:
        if gdb != None:
            gdb.stop()
        raise
    msg_queue.put('dead')
Exemple #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
Exemple #7
0
    def list_boards(self):
        self.disable_logging()

        try:
            all_mbeds = MbedBoard.getAllConnectedBoards(close=True, blocking=False)
            status = 0
            error = ""
        except Exception as e:
            all_mbeds = []
            status = 1
            error = str(e)
            if not self.args.output_json:
                raise

        if self.args.output_json:
            boards = []
            obj = {
                'pyocd_version' : __version__,
                'version' : { 'major' : 1, 'minor' : 0 },
                'status' : status,
                'boards' : boards,
                }

            if status != 0:
                obj['error'] = error

            for mbed in all_mbeds:
                d = {
                    'unique_id' : mbed.unique_id,
                    'info' : mbed.getInfo(),
                    'board_name' : mbed.getBoardName(),
                    'target' : mbed.getTargetType(),
                    'vendor_name' : '',
                    'product_name' : '',
                    }

                # Reopen the link so we can access the USB vendor and product names from the inteface.
                # If it's not a USB based link, then we don't attempt this.
                if isinstance(mbed.link, DAPAccessUSB):
                    try:
                        mbed.link.open()
                        d['vendor_name'] = mbed.link._interface.vendor_name
                        d['product_name'] = mbed.link._interface.product_name
                        mbed.link.close()
                    except Exception:
                        pass
                boards.append(d)

            print json.dumps(obj, indent=4) #, sys.stdout)
        else:
            index = 0
            if len(all_mbeds) > 0:
                for mbed in all_mbeds:
                    print("%d => %s boardId => %s" % (index, mbed.getInfo().encode('ascii', 'ignore'), mbed.unique_id))
                    index += 1
            else:
                print("No available boards are connected")
Exemple #8
0
def main():
    log_file = "automated_test_result.txt"
    summary_file = "automated_test_summary.txt"

    parser = argparse.ArgumentParser(description='pyOCD automated testing')
    parser.add_argument('-d', '--debug',
                        action="store_true", help='Enable debug logging')
    args = parser.parse_args()

    # Setup logging
    if os.path.exists(log_file):
        os.remove(log_file)
    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=level)
    logger = Logger(log_file)
    sys.stdout = logger
    sys.stderr = logger

    test_list = []
    board_list = []
    result_list = []

    # Put together list of tests
    test = Test("Basic Test", lambda board: basic_test(board, None))
    test_list.append(test)
    test_list.append(GdbServerJsonTest())
    test_list.append(SpeedTest())
    test_list.append(CortexTest())
    test_list.append(FlashTest())
    test_list.append(GdbTest())

    # Put together list of boards to test
    board_list = MbedBoard.getAllConnectedBoards(close=True, blocking=False)

    start = time()
    for board in board_list:
        print("--------------------------")
        print("TESTING BOARD %s" % board.getUniqueID())
        print("--------------------------")
        for test in test_list:
            test_start = time()
            result = test.run(board)
            test_stop = time()
            result.time = test_stop - test_start
            result_list.append(result)
    stop = time()
    test_time = (stop - start)

    print_summary(test_list, result_list, test_time)
    with open(summary_file, "wb") as output_file:
        print_summary(test_list, result_list, test_time, output_file)

    exit_val = 0 if Test.all_tests_pass(result_list) else -1
    exit(exit_val)
Exemple #9
0
    def list_boards(self):
        self.disable_logging()

        try:
            all_mbeds = MbedBoard.getAllConnectedBoards(close=True, blocking=False)
            status = 0
            error = ""
        except Exception as e:
            all_mbeds = []
            status = 1
            error = str(e)
            if not self.args.output_json:
                raise

        if self.args.output_json:
            boards = []
            obj = {
                'pyocd_version' : __version__,
                'version' : { 'major' : 1, 'minor' : 0 },
                'status' : status,
                'boards' : boards,
                }

            if status != 0:
                obj['error'] = error

            for mbed in all_mbeds:
                d = {
                    'unique_id' : mbed.unique_id,
                    'info' : mbed.getInfo(),
                    'board_name' : mbed.getBoardName(),
                    'target' : mbed.getTargetType(),
                    'vendor_name' : mbed.interface.vendor_name,
                    'product_name' : mbed.interface.product_name,
                    }
                boards.append(d)

            print json.dumps(obj, indent=4) #, sys.stdout)
        else:
            index = 0
            if len(all_mbeds) > 0:
                for mbed in all_mbeds:
                    print("%d => %s boardId => %s" % (index, mbed.getInfo().encode('ascii', 'ignore'), mbed.unique_id))
                    index += 1
            else:
                print("No available boards are connected")
Exemple #10
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
            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
        except InvalidArgumentError as e:
            self.parser.error(e)
            return 1
Exemple #11
0
def _launchPyOCDGDBServer(msg_queue):
    logger.info('preparing PyOCD gdbserver...')
    from pyOCD.gdbserver import GDBServer
    from pyOCD.board import MbedBoard
    gdb = None
    try:
        logger.info('finding connected board...')
        board_selected = MbedBoard.chooseBoard(blocking=False)
        if board_selected is not None:
            with board_selected as board:
                logger.info('starting PyOCD gdbserver...')
                gdb = GDBServer(
                    board, 3333, {
                         'break_at_hardfault': True,
                        'step_into_interrupt': False,
                             'break_on_reset': False,
                    }
                )
                if gdb.isAlive():
                    msg_queue.put('alive')
                    while gdb.isAlive():
                        gdb.join(timeout = 0.5)
                        # check for a "kill" message from the parent process:
                        try:
                            msg = msg_queue.get(False)
                            if msg == 'kill':
                                gdb.stop()
                                break
                        except Queue.Empty:
                            pass
        else:
            logger.error('failed to find a connected board')
    except Exception as e:
        logger.error('exception in GDB server thread: %s', e)
        if gdb != None:
            gdb.stop()
        raise
    msg_queue.put('dead')
Exemple #12
0
    def validate_boards(data):
        did_pass = True

        print 'boards',
        p = data.has_key('boards') and type(data['boards']) is list
        if p:
            b = data['boards']
        if p:
            print "PASSED"
        else:
            did_pass = False
            print"FAILED"

        try:
            all_mbeds = MbedBoard.getAllConnectedBoards(close=True, blocking=False)
            p = len(all_mbeds) == len(b)
            matching_boards = 0
            if p:
                for mbed in all_mbeds:
                    for brd in b:
                        if mbed.unique_id == brd['unique_id']:
                            matching_boards += 1
                            p = brd.has_key('info') and brd.has_key('target') and brd.has_key('board_name')
                            if not p:
                                break
                    if not p:
                        break
                p = matching_boards == len(all_mbeds)
            if p:
                print "PASSED"
            else:
                did_pass = False
                print"FAILED"
        except Exception:
            print "FAILED"
            did_pass = False

        return did_pass
build_type = build_types[0].strip().split("=")[1]
if build_type != "Debug":
    raise Exception("CMAKE_BUILD_TYPE was '%s', expected 'Debug'. Rebuild with `yt build -d`." % build_type)

# create crashdump folder
mkdir_p("crashdump")

# copy over AXF file
potential_axf = [f for f in os.listdir(yotta_build_path) if isfile(join(yotta_build_path, f)) and "." not in f]
if len(potential_axf) != 1:
    raise Exception("Found %d files without extension in %s, expected 1" % (len(potential_axf), yotta_build_path))
copyfile(join(yotta_build_path, potential_axf[0]), "crashdump/" + potential_axf[0] + ".axf")

print "[2/6] Build verified. Connecting to board..."

with MbedBoard.chooseBoard(frequency=10000000) as board:

    memory_map = board.target.getMemoryMap()
    ram_regions = [region for region in memory_map if region.type == 'ram']
    ram_region = ram_regions[0]
    rom_region = memory_map.getBootMemory()
    target_type = board.getTargetType()

    print "[3/6] Board recognized as %s. Downloading ROM..." % target_type

    addr = rom_region.start
    size = rom_region.length
    data = board.target.readBlockMemoryUnaligned8(addr, size)
    data = bytearray(data)
    with open("crashdump/rom.bin", 'wb') as f:
        f.write(data)
Exemple #14
0
def flash_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        def print_progress(progress):
            assert progress >= 0.0
            assert progress <= 1.0
            assert (progress == 0 and print_progress.prev_progress
                    == 1.0) or (progress >= print_progress.prev_progress)

            # Reset state on 0.0
            if progress == 0.0:
                print_progress.prev_progress = 0
                print_progress.backwards_progress = False
                print_progress.done = False

            # Check for backwards progress
            if progress < print_progress.prev_progress:
                print_progress.backwards_progress = True
            print_progress.prev_progress = progress

            # print progress bar
            if not print_progress.done:
                sys.stdout.write('\r')
                i = int(progress * 20.0)
                sys.stdout.write("[%-20s] %3d%%" %
                                 ('=' * i, round(progress * 100)))
                sys.stdout.flush()

            # Finish on 1.0
            if progress >= 1.0:
                if not print_progress.done:
                    print_progress.done = True
                    sys.stdout.write("\n")
                    if print_progress.backwards_progress:
                        print("Progress went backwards during flash")

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]

        ram_start = ram_region.start
        ram_size = ram_region.length

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

        flash_info = flash.getFlashInfo()

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        test_pass_count = 0
        test_count = 0
        result = FlashTestResult()

        # Test each flash region separately.
        for rom_region in memory_map.getRegionsOfType('flash'):
            if not rom_region.isTestable:
                continue
            rom_start = rom_region.start
            rom_size = rom_region.length

            print(
                "\r\n\r\n===== Testing flash region '%s' from 0x%08x to 0x%08x ===="
                % (rom_region.name, rom_region.start, rom_region.end))

            print_progress.prev_progress = 0

            binary_file = os.path.join(parentdir, 'binaries',
                                       board.getTestBinary())
            with open(binary_file, "rb") as f:
                data = f.read()
            data = struct.unpack("%iB" % len(data), data)
            unused = rom_size - len(data)

            # Make sure data doesn't overflow this region.
            if unused < 0:
                data = data[:rom_size]
                unused = 0

            addr = rom_start
            size = len(data)

            # Turn on extra checks for the next 4 tests
            flash.setFlashAlgoDebug(True)

            print("\r\n\r\n------ Test Basic Page Erase ------")
            info = flash.flashBlock(addr,
                                    data,
                                    False,
                                    False,
                                    progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(addr, size)
            if same(data_flashed, data
                    ) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Basic Chip Erase ------")
            info = flash.flashBlock(addr,
                                    data,
                                    False,
                                    True,
                                    progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(addr, size)
            if same(data_flashed, data
                    ) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Smart Page Erase ------")
            info = flash.flashBlock(addr,
                                    data,
                                    True,
                                    False,
                                    progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(addr, size)
            if same(data_flashed, data
                    ) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Smart Chip Erase ------")
            info = flash.flashBlock(addr,
                                    data,
                                    True,
                                    True,
                                    progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(addr, size)
            if same(data_flashed, data
                    ) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            flash.setFlashAlgoDebug(False)

            print(
                "\r\n\r\n------ Test Basic Page Erase (Entire region) ------")
            new_data = list(data)
            new_data.extend(unused * [0x77])
            info = flash.flashBlock(addr,
                                    new_data,
                                    False,
                                    False,
                                    progress_cb=print_progress)
            if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
                result.page_erase_rate = float(len(new_data)) / float(
                    info.program_time)
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Fast Verify ------")
            info = flash.flashBlock(addr,
                                    new_data,
                                    progress_cb=print_progress,
                                    fast_verify=True)
            if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Offset Write ------")
            addr = rom_start + rom_size / 2
            page_size = flash.getPageInfo(addr).size
            new_data = [0x55] * page_size * 2
            info = flash.flashBlock(addr, new_data, progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(
                addr, len(new_data))
            if same(data_flashed, new_data
                    ) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Multiple Block Writes ------")
            addr = rom_start + rom_size / 2
            page_size = flash.getPageInfo(addr).size
            more_data = [0x33] * page_size * 2
            addr = (rom_start + rom_size / 2) + 1  #cover multiple pages
            fb = flash.getFlashBuilder()
            fb.addData(rom_start, data)
            fb.addData(addr, more_data)
            fb.program(progress_cb=print_progress)
            data_flashed = target.readBlockMemoryUnaligned8(
                rom_start, len(data))
            data_flashed_more = target.readBlockMemoryUnaligned8(
                addr, len(more_data))
            if same(data_flashed, data) and same(data_flashed_more, more_data):
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Overlapping Blocks ------")
            test_pass = False
            addr = (rom_start + rom_size / 2)  #cover multiple pages
            page_size = flash.getPageInfo(addr).size
            new_data = [0x33] * page_size
            fb = flash.getFlashBuilder()
            fb.addData(addr, new_data)
            try:
                fb.addData(addr + 1, new_data)
            except ValueError as e:
                print("Exception: %s" % e)
                test_pass = True
            if test_pass:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Empty Block Write ------")
            # Freebee if nothing asserts
            fb = flash.getFlashBuilder()
            fb.program()
            print("TEST PASSED")
            test_pass_count += 1
            test_count += 1

            print("\r\n\r\n------ Test Missing Progress Callback ------")
            # Freebee if nothing asserts
            addr = rom_start
            flash.flashBlock(rom_start, data, True)
            print("TEST PASSED")
            test_pass_count += 1
            test_count += 1

            # Only run test if the reset handler can be programmed (rom start at address 0)
            if rom_start == 0:
                print("\r\n\r\n------ Test Non-Thumb reset handler ------")
                non_thumb_data = list(data)
                # Clear bit 0 of 2nd word - reset handler
                non_thumb_data[4] = non_thumb_data[4] & ~1
                flash.flashBlock(rom_start, non_thumb_data)
                flash.flashBlock(rom_start, data)
                print("TEST PASSED")
                test_pass_count += 1
                test_count += 1

            # Note - The decision based tests below are order dependent since they
            # depend on the previous state of the flash

            if rom_start == flash_info.rom_start:
                print("\r\n\r\n------ Test Chip Erase Decision ------")
                new_data = list(data)
                new_data.extend([0xff] * unused)  # Pad with 0xFF
                info = flash.flashBlock(addr,
                                        new_data,
                                        progress_cb=print_progress)
                if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
                    print("TEST PASSED")
                    test_pass_count += 1
                    result.chip_erase_rate_erased = float(
                        len(new_data)) / float(info.program_time)
                else:
                    print("TEST FAILED")
                test_count += 1

                print("\r\n\r\n------ Test Chip Erase Decision 2 ------")
                new_data = list(data)
                new_data.extend([0x00] * unused)  # Pad with 0x00
                info = flash.flashBlock(addr,
                                        new_data,
                                        progress_cb=print_progress)
                if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
                    print("TEST PASSED")
                    test_pass_count += 1
                    result.chip_erase_rate = float(len(new_data)) / float(
                        info.program_time)
                else:
                    print("TEST FAILED")
                test_count += 1

            print("\r\n\r\n------ Test Page Erase Decision ------")
            new_data = list(data)
            new_data.extend([0x00] * unused)  # Pad with 0x00
            info = flash.flashBlock(addr, new_data, progress_cb=print_progress)
            if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
                result.page_erase_rate_same = float(len(new_data)) / float(
                    info.program_time)
                result.analyze = info.analyze_type
                result.analyze_time = info.analyze_time
                result.analyze_rate = float(len(new_data)) / float(
                    info.analyze_time)
            else:
                print("TEST FAILED")
            test_count += 1

            print("\r\n\r\n------ Test Page Erase Decision 2 ------")
            new_data = list(data)
            size_same = unused * 5 / 6
            size_differ = unused - size_same
            new_data.extend([0x00] *
                            size_same)  # Pad 5/6 with 0x00 and 1/6 with 0xFF
            new_data.extend([0x55] * size_differ)
            info = flash.flashBlock(addr, new_data, progress_cb=print_progress)
            if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
                print("TEST PASSED")
                test_pass_count += 1
            else:
                print("TEST FAILED")
            test_count += 1

        print("\r\n\r\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
Exemple #15
0
    def list_boards(self):
        self.disable_logging()

        try:
            all_mbeds = MbedBoard.getAllConnectedBoards(close=True,
                                                        blocking=False)
            status = 0
            error = ""
        except Exception as e:
            all_mbeds = []
            status = 1
            error = str(e)
            if not self.args.output_json:
                raise

        if self.args.output_json:
            boards = []
            obj = {
                'pyocd_version': __version__,
                'version': {
                    'major': 1,
                    'minor': 0
                },
                'status': status,
                'boards': boards,
            }

            if status != 0:
                obj['error'] = error

            for mbed in all_mbeds:
                d = {
                    'unique_id': mbed.unique_id,
                    'info': mbed.getInfo(),
                    'board_name': mbed.getBoardName(),
                    'target': mbed.getTargetType(),
                    'vendor_name': '',
                    'product_name': '',
                }

                # Reopen the link so we can access the USB vendor and product names from the inteface.
                # If it's not a USB based link, then we don't attempt this.
                if isinstance(mbed.link, DAPAccessCMSISDAP):
                    try:
                        mbed.link.open()
                        d['vendor_name'] = mbed.link._interface.vendor_name
                        d['product_name'] = mbed.link._interface.product_name
                        mbed.link.close()
                    except Exception:
                        pass
                boards.append(d)

            print(json.dumps(obj, indent=4))
        else:
            index = 0
            if len(all_mbeds) > 0:
                for mbed in all_mbeds:
                    print("%d => %s boardId => %s" %
                          (index, mbed.getInfo().encode(
                              'ascii', 'ignore'), mbed.unique_id))
                    index += 1
            else:
                print("No available boards are connected")
def connect_test(board):
    board_id = board.getUniqueID()
    binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())
    print("binary file: %s" % binary_file)

    test_pass_count = 0
    test_count = 0
    result = ConnectTestResult()

    # Install binary.
    live_board = MbedBoard.chooseBoard(board_id=board_id, frequency=1000000)
    memory_map = board.target.getMemoryMap()
    rom_region = memory_map.getBootMemory()
    rom_start = rom_region.start

    def test_connect(halt_on_connect, expected_state, resume):
        print("Connecting with halt_on_connect=%s" % halt_on_connect)
        live_board = MbedBoard.chooseBoard(board_id=board_id,
                                           frequency=1000000,
                                           init_board=False)
        live_board.target.setHaltOnConnect(halt_on_connect)
        live_board.init()
        print("Verifying target is", STATE_NAMES.get(expected_state,
                                                     "unknown"))
        actualState = live_board.target.getState()
        if actualState == expected_state:
            passed = 1
            print("TEST PASSED")
        else:
            passed = 0
            print("TEST FAILED (state={}, expected={})".format(
                STATE_NAMES.get(actualState, "unknown"),
                STATE_NAMES.get(expected_state, "unknown")))
        print("Disconnecting with resume=%s" % resume)
        live_board.uninit(resume)
        live_board = None
        return passed

    # TEST CASE COMBINATIONS
    test_cases = [
        #                <prev_exit> <halt_on_connect> <expected_state> <disconnect_resume> <exit_state>
        ConnectTestCase(RUNNING, False, RUNNING, False, RUNNING),
        ConnectTestCase(RUNNING, True, HALTED, False, HALTED),
        ConnectTestCase(HALTED, True, HALTED, True, RUNNING),
        ConnectTestCase(RUNNING, True, HALTED, True, RUNNING),
        ConnectTestCase(RUNNING, False, RUNNING, True, RUNNING),
        ConnectTestCase(RUNNING, True, HALTED, False, HALTED),
        ConnectTestCase(HALTED, False, HALTED, False, HALTED),
        ConnectTestCase(HALTED, True, HALTED, False, HALTED),
        ConnectTestCase(HALTED, False, HALTED, True, RUNNING),
        ConnectTestCase(RUNNING, False, RUNNING, False, RUNNING),
    ]

    print("\n\n----- FLASH NEW BINARY -----")
    live_board.flash.flashBinary(binary_file, rom_start)
    live_board.target.reset()
    test_count += 1
    print("Verifying target is running")
    if live_board.target.isRunning():
        test_pass_count += 1
        print("TEST PASSED")
    else:
        print("TEST FAILED")
    print("Disconnecting with resume=True")
    live_board.uninit(resume=True)
    live_board = None
    # Leave running.

    # Run all the cases.
    for case in test_cases:
        test_count += 1
        did_pass = test_connect(halt_on_connect=case.halt_on_connect,
                                expected_state=case.expected_state,
                                resume=case.disconnect_resume)
        test_pass_count += did_pass
        case.passed = did_pass

    print("\n\nTest Summary:")
    print("\n{:<4}{:<12}{:<19}{:<12}{:<21}{:<11}{:<10}".format(
        "#", "Prev Exit", "Halt on Connect", "Expected", "Disconnect Resume",
        "Exit", "Passed"))
    for i, case in enumerate(test_cases):
        print("{:<4}{:<12}{:<19}{:<12}{:<21}{:<11}{:<10}".format(
            i, STATE_NAMES[case.prev_exit_state],
            repr(case.halt_on_connect), STATE_NAMES[case.expected_state],
            repr(case.disconnect_resume), STATE_NAMES[case.exit_state],
            "PASS" if case.passed else "FAIL"))
    print("\nPass count %i of %i tests" % (test_pass_count, test_count))
    if test_pass_count == test_count:
        print("CONNECT TEST SCRIPT PASSED")
    else:
        print("CONNECT TEST SCRIPT FAILED")

    result.passed = (test_count == test_pass_count)
    return result
Exemple #17
0
def speed_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "kl25z":
            ram_start = 0x1ffff000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        elif target_type == "kl28z":
            ram_start = 0x1fffa000
            ram_size = 96 * 1024
            rom_start = 0x00000000
            rom_size = 512 * 1024
        elif target_type == "kl46z":
            ram_start = 0x1fffe000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "k22f":
            ram_start = 0x1fff0000
            ram_size = 0x20000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "k64f":
            ram_start = 0x1FFF0000
            ram_size = 0x40000
            rom_start = 0x00000000
            rom_size = 0x100000
        elif target_type == "lpc11u24":
            ram_start = 0x10000000
            ram_size = 0x2000
            rom_start = 0x00000000
            rom_size = 0x8000
        elif target_type == "lpc1768":
            ram_start = 0x10000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "lpc800":
            ram_start = 0x10000000
            ram_size = 0x1000
            rom_start = 0x00000000
            rom_size = 0x4000
        elif target_type == "lpc4330":
            ram_start = 0x10000000
            ram_size = 0x20000
            rom_start = 0x14000000
            rom_size = 0x100000
        elif target_type == "nrf51":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x40000
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        elif target_type == "maxwsnenv":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "max32600mbed":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "w7500":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        else:
            raise Exception("The board is not supported by this test script.")

        target = board.target
        link = board.link

        test_pass_count = 0
        test_count = 0
        result = SpeedTestResult()

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        print "\r\n\r\n------ TEST RAM READ / WRITE SPEED ------"
        test_addr = ram_start
        test_size = ram_size
        data = [randrange(1, 50) for x in range(test_size)]
        start = time()
        target.writeBlockMemoryUnaligned8(test_addr, data)
        target.flush()
        stop = time()
        diff = stop - start
        result.write_speed = test_size / diff
        print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed))
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        result.read_speed = test_size / diff
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed))
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])
        if error:
            print "TEST FAILED"
        else:
            print "TEST PASSED"
            test_pass_count += 1
        test_count += 1

        print "\r\n\r\n------ TEST ROM READ SPEED ------"
        test_addr = rom_start
        test_size = rom_size
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff))
        print "TEST PASSED"
        test_pass_count += 1
        test_count += 1

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #18
0
parser.add_option("-b", "--board", dest = "board_id", default = None, help = "Write the board id you want to connect")
parser.add_option("-l", "--list", action = "store_true", dest = "list_all", default = False, help = "List all the connected board")
parser.add_option("-d", "--debug", dest = "debug_level", default = 'info', help = "Set the level of system logging output, the available value for DEBUG_LEVEL: debug, info, warning, error, critical" )
parser.add_option("-t", "--target", dest = "target_override", default = None, help = "Override target to debug" )
parser.add_option("-n", "--nobreak", dest = "break_at_hardfault", default = True, action="store_false", help = "Disable halt at hardfault handler." )
parser.add_option("-r", "--reset-break", dest = "break_on_reset", default = False, action="store_true", help = "Halt the target when reset." )
parser.add_option("-s", "--step-int", dest = "step_into_interrupt", default = False, action="store_true", help = "Allow single stepping to step into interrupts." )
parser.add_option("-f", "--frequency", dest = "debug_clock_frequency", default = 1000000, type="int", help = "SWD clock frequency in Hz." )
parser.add_option("-o", "--persist", dest = "persist", default = False, action="store_true", help = "Keep GDB server running even after remote has detached.")
(option, args) = parser.parse_args()

gdb = None
level = LEVELS.get(option.debug_level, logging.NOTSET)
logging.basicConfig(level=level)
if option.list_all == True:
    MbedBoard.listConnectedBoards()
else:
    try:
        board_selected = MbedBoard.chooseBoard(board_id = option.board_id, target_override = option.target_override, frequency = option.debug_clock_frequency)
        with board_selected as board:
            gdb = GDBServer(board, int(option.port_number), {'break_at_hardfault' : option.break_at_hardfault, 
                'step_into_interrupt' : option.step_into_interrupt, 'break_on_reset' : option.break_on_reset,
                'persist' : option.persist})
            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()
Exemple #19
0
def cortex_test(board_id):
    with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board:
        addr = 0
        size = 0
        f = None
        binary_file = "l1_"

        interface = None

        target_type = board.getTargetType()

        binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())

        addr_bin = 0x00000000
        test_clock = 10000000
        addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty
        if target_type == "lpc1768":
            addr = 0x10000000
            size = 0x1102
            addr_flash = 0x10000
        elif target_type == "lpc11u24":
            addr = 0x10000000
            size = 0x502
            addr_flash = 0x4000
        elif target_type == "kl25z":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "kl28z":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k64f":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k22f":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k20d50m":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "kl46z":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "lpc800":
            addr = 0x10000000
            size = 0x502
            addr_flash = 0x2000
        elif target_type == "nrf51":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x20000
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        elif target_type == "lpc4330":
            addr = 0x10000000
            size = 0x1102
            addr_flash = 0x14010000
            addr_bin = 0x14000000
        elif target_type == "maxwsnenv":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "max32600mbed":
            addr = 0x20000000
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "w7500":
            addr = 0x20000000
            size = 0x1102
            addr_flash = 0x00000000
        else:
            raise Exception("A board is not supported by this test script.")


        target = board.target
        transport = board.transport
        flash = board.flash
        interface = board.interface

        transport.setClock(test_clock)
        transport.setDeferredTransfer(True)

        test_pass_count = 0
        test_count = 0
        result = CortexTestResult()

        print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----"
        flash.flashBinary(binary_file, addr_bin)
        # Let the target run for a bit so it
        # can initialize the watchdog if it needs to
        target.resume()
        sleep(0.2)
        target.halt()

        print "PROGRAMMING COMPLETE"


        print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----"
        test_time = test_function(board, target.getTResponse)
        print("Function getTResponse time: %f" % test_time)

        # Step
        test_time = test_function(board, target.step)
        print("Function step time: %f" % test_time)

        # Breakpoint
        def set_remove_breakpoint():
            target.setBreakpoint(0)
            target.removeBreakpoint(0)
        test_time = test_function(board, set_remove_breakpoint)
        print("Add and remove breakpoint: %f" % test_time)

        # getRegisterContext
        test_time = test_function(board, target.getRegisterContext)
        print("Function getRegisterContext: %f" % test_time)

        # setRegisterContext
        context = target.getRegisterContext()
        def set_register_context():
            target.setRegisterContext(context)
        test_time = test_function(board, set_register_context)
        print("Function setRegisterContext: %f" % test_time)

        # Run / Halt
        def run_halt():
            target.resume()
            target.halt()
        test_time = test_function(board, run_halt)
        print("Resume and halt: %f" % test_time)

        # GDB stepping
        def simulate_step():
            target.step()
            target.getTResponse()
            target.setBreakpoint(0)
            target.resume()
            target.halt()
            target.getTResponse()
            target.removeBreakpoint(0)
        test_time = test_function(board, simulate_step)
        print("Simulated GDB step: %f" % test_time)

        # Test passes if there are no exceptions
        test_pass_count += 1
        test_count += 1
        print("TEST PASSED")


        print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------"
        memory_access_pass = True
        try:
            target.readBlockMemoryUnaligned8(addr_invalid, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except TransferError:
            pass

        try:
            target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except TransferError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except TransferError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid + 1, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except TransferError:
            pass

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        if same(data, block):
            print "Aligned access pass"
        else:
            print("Memory read does not match memory written")
            memory_access_pass = False

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr + 1, data)
        block = target.readBlockMemoryUnaligned8(addr + 1, size)
        if same(data, block):
            print "Unaligned access pass"
        else:
            print("Unaligned memory read does not match memory written")
            memory_access_pass = False

        test_count += 1
        if memory_access_pass:
            test_pass_count += 1
            print "TEST PASSED"
        else:
            print "TEST FAILED"

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #20
0
 def _setup(self):
     board = MbedBoard.chooseBoard()
     return board
Exemple #21
0
from time import sleep
from random import randrange
import math

parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)

import pyOCD
from pyOCD.board import MbedBoard
import logging

logging.basicConfig(level=logging.INFO)

print("\n\n------ Test attaching to locked board ------")
for i in range(0, 10):
    with MbedBoard.chooseBoard() as board:
        # Erase and then reset - This locks Kinetis devices
        board.flash.init()
        board.flash.eraseAll()
        board.target.reset()

print("\n\n------ Testing Attaching to board ------")
for i in range(0, 100):
    with MbedBoard.chooseBoard() as board:
        board.target.halt()
        sleep(0.01)
        board.target.resume()
        sleep(0.01)

print("\n\n------ Flashing new code ------")
with MbedBoard.chooseBoard() as board:
def main():
    log_file = "automated_test_result.txt"
    summary_file = "automated_test_summary.txt"

    parser = argparse.ArgumentParser(description='pyOCD automated testing')
    parser.add_argument('-d',
                        '--debug',
                        action="store_true",
                        help='Enable debug logging')
    parser.add_argument('-q',
                        '--quiet',
                        action="store_true",
                        help='Hide test progress for 1 job')
    parser.add_argument(
        '-j',
        '--jobs',
        action="store",
        default=1,
        type=int,
        metavar="JOBS",
        help='Set number of concurrent board tests (default is 1)')
    args = parser.parse_args()

    # Setup logging
    if os.path.exists(log_file):
        os.remove(log_file)
    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=level)
    logger = Logger(log_file)
    sys.stdout = logger
    sys.stderr = logger

    test_list = []
    board_list = []
    result_list = []

    # Put together list of tests
    test_list.append(BasicTest())
    test_list.append(GdbServerJsonTest())
    test_list.append(ConnectTest())
    test_list.append(SpeedTest())
    test_list.append(CortexTest())
    test_list.append(FlashTest())
    test_list.append(GdbTest())

    # Put together list of boards to test
    board_list = MbedBoard.getAllConnectedBoards(close=True, blocking=False)

    start = time()
    for board in board_list:
        print("--------------------------")
        print("TESTING BOARD %s" % board.getUniqueID())
        print("--------------------------")
        for test in test_list:
            test_start = time()
            result = test.run(board)
            test_stop = time()
            result.time = test_stop - test_start
            result_list.append(result)
    stop = time()
    test_time = (stop - start)

    print_summary(test_list, result_list, test_time)
    with open(summary_file, "w") as output_file:
        print_summary(test_list, result_list, test_time, output_file)
    generate_xml_results(result_list)

    exit_val = 0 if Test.all_tests_pass(result_list) else -1
    exit(exit_val)
Exemple #23
0
def flash_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "kl25z":
            ram_start = 0x1ffff000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        elif target_type == "kl28z":
            ram_start = 0x1fffa000
            ram_size = 96 * 1024
            rom_start = 0x00000000
            rom_size = 512 * 1024
        elif target_type == "kl46z":
            ram_start = 0x1fffe000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "k22f":
            ram_start = 0x1fff0000
            ram_size = 0x20000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "k64f":
            ram_start = 0x1FFF0000
            ram_size = 0x40000
            rom_start = 0x00000000
            rom_size = 0x100000
        elif target_type == "lpc11u24":
            ram_start = 0x10000000
            ram_size = 0x2000
            rom_start = 0x00000000
            rom_size = 0x8000
        elif target_type == "lpc1768":
            ram_start = 0x10000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "lpc4330":
            ram_start = 0x10000000
            ram_size = 0x20000
            rom_start = 0x14000000
            rom_size = 0x100000
        elif target_type == "lpc800":
            ram_start = 0x10000000
            ram_size = 0x1000
            rom_start = 0x00000000
            rom_size = 0x4000
        elif target_type == "nrf51":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x40000
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        elif target_type == "maxwsnenv":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "max32600mbed":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "w7500":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        else:
            raise Exception("The board is not supported by this test script.")

        target = board.target
        transport = board.transport
        flash = board.flash
        interface = board.interface

        transport.setClock(test_clock)
        transport.setDeferredTransfer(True)

        test_pass_count = 0
        test_count = 0
        result = FlashTestResult()

        def print_progress(progress):
            assert progress >= 0.0
            assert progress <= 1.0
            assert (progress == 0 and print_progress.prev_progress
                    == 1.0) or (progress >= print_progress.prev_progress)

            # Reset state on 0.0
            if progress == 0.0:
                print_progress.prev_progress = 0
                print_progress.backwards_progress = False
                print_progress.done = False

            # Check for backwards progress
            if progress < print_progress.prev_progress:
                print_progress.backwards_progress = True
            print_progress.prev_progress = progress

            # print progress bar
            if not print_progress.done:
                sys.stdout.write('\r')
                i = int(progress * 20.0)
                sys.stdout.write("[%-20s] %3d%%" %
                                 ('=' * i, round(progress * 100)))
                sys.stdout.flush()

            # Finish on 1.0
            if progress >= 1.0:
                if not print_progress.done:
                    print_progress.done = True
                    sys.stdout.write("\n")
                    if print_progress.backwards_progress:
                        print("Progress went backwards during flash")

        print_progress.prev_progress = 0

        binary_file = os.path.join(parentdir, 'binaries',
                                   board.getTestBinary())
        with open(binary_file, "rb") as f:
            data = f.read()
        data = struct.unpack("%iB" % len(data), data)
        unused = rom_size - len(data)

        addr = rom_start
        size = len(data)

        # Turn on extra checks for the next 4 tests
        flash.setFlashAlgoDebug(True)

        print "\r\n\r\n------ Test Basic Page Erase ------"
        info = flash.flashBlock(addr,
                                data,
                                False,
                                False,
                                progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed,
                data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Basic Chip Erase ------"
        info = flash.flashBlock(addr,
                                data,
                                False,
                                True,
                                progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed,
                data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Smart Page Erase ------"
        info = flash.flashBlock(addr,
                                data,
                                True,
                                False,
                                progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed,
                data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Smart Chip Erase ------"
        info = flash.flashBlock(addr,
                                data,
                                True,
                                True,
                                progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed,
                data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        flash.setFlashAlgoDebug(False)

        print "\r\n\r\n------ Test Basic Page Erase (Entire chip) ------"
        new_data = list(data)
        new_data.extend(unused * [0x77])
        info = flash.flashBlock(0,
                                new_data,
                                False,
                                False,
                                progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.page_erase_rate = float(len(new_data)) / float(
                info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Fast Verify ------"
        info = flash.flashBlock(0,
                                new_data,
                                progress_cb=print_progress,
                                fast_verify=True)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Offset Write ------"
        addr = rom_start + rom_size / 2
        page_size = flash.getPageInfo(addr).size
        new_data = [0x55] * page_size * 2
        info = flash.flashBlock(addr, new_data, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data))
        if same(data_flashed, new_data
                ) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Multiple Block Writes ------"
        addr = rom_start + rom_size / 2
        page_size = flash.getPageInfo(addr).size
        more_data = [0x33] * page_size * 2
        addr = (rom_start + rom_size / 2) + 1  #cover multiple pages
        fb = flash.getFlashBuilder()
        fb.addData(rom_start, data)
        fb.addData(addr, more_data)
        fb.program(progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data))
        data_flashed_more = target.readBlockMemoryUnaligned8(
            addr, len(more_data))
        if same(data_flashed, data) and same(data_flashed_more, more_data):
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Overlapping Blocks ------"
        test_pass = False
        addr = (rom_start + rom_size / 2)  #cover multiple pages
        page_size = flash.getPageInfo(addr).size
        new_data = [0x33] * page_size
        fb = flash.getFlashBuilder()
        fb.addData(addr, new_data)
        try:
            fb.addData(addr + 1, new_data)
        except ValueError as e:
            print("Exception: %s" % e)
            test_pass = True
        if test_pass:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Empty Block Write ------"
        # Freebee if nothing asserts
        fb = flash.getFlashBuilder()
        fb.program()
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        print "\r\n\r\n------ Test Missing Progress Callback ------"
        # Freebee if nothing asserts
        addr = rom_start
        flash.flashBlock(rom_start, data, True)
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        # Only run test if the reset handler can be programmed (rom start at address 0)
        if rom_start == 0:
            print "\r\n\r\n------ Test Non-Thumb reset handler ------"
            non_thumb_data = list(data)
            # Clear bit 0 of 2nd word - reset handler
            non_thumb_data[4] = non_thumb_data[4] & ~1
            flash.flashBlock(rom_start, non_thumb_data)
            flash.flashBlock(rom_start, data)
            print("TEST PASSED")
            test_pass_count += 1
            test_count += 1

        # Note - The decision based tests below are order dependent since they
        # depend on the previous state of the flash

        print "\r\n\r\n------ Test Chip Erase Decision ------"
        new_data = list(data)
        new_data.extend([0xff] * unused)  # Pad with 0xFF
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.chip_erase_rate_erased = float(len(new_data)) / float(
                info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Chip Erase Decision 2 ------"
        new_data = list(data)
        new_data.extend([0x00] * unused)  # Pad with 0x00
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.chip_erase_rate = float(len(new_data)) / float(
                info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Page Erase Decision ------"
        new_data = list(data)
        new_data.extend([0x00] * unused)  # Pad with 0x00
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.page_erase_rate_same = float(len(new_data)) / float(
                info.program_time)
            result.analyze = info.analyze_type
            result.analyze_time = info.analyze_time
            result.analyze_rate = float(len(new_data)) / float(
                info.analyze_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Page Erase Decision 2 ------"
        new_data = list(data)
        size_same = unused * 5 / 6
        size_differ = unused - size_same
        new_data.extend([0x00] *
                        size_same)  # Pad 5/6 with 0x00 and 1/6 with 0xFF
        new_data.extend([0x55] * size_differ)
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print("\r\n\r\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
Exemple #24
0
parser.add_option(
    "-n",
    "--nobreak",
    dest="break_at_hardfault",
    default=True,
    action="store_false",
    help=
    "Disable breakpoint at hardfault handler. Required for nrf51 chip with SoftDevice based application."
)
(option, args) = parser.parse_args()

gdb = None
level = LEVELS.get(option.debug_level, logging.NOTSET)
logging.basicConfig(level=level)
if option.list_all == True:
    MbedBoard.listConnectedBoards()
else:
    try:
        board_selected = MbedBoard.chooseBoard(
            board_id=option.board_id, target_override=option.target_override)
        if board_selected != None:
            try:
                gdb = GDBServer(
                    board_selected, int(option.port_number),
                    {'break_at_hardfault': option.break_at_hardfault})
                while gdb.isAlive():
                    gdb.join(timeout=0.5)
            except ValueError:
                logging.error("Port number error!")
    except KeyboardInterrupt:
        if gdb != None:
Exemple #25
0
        }

print "Welcome to the PyOCD GDB Server Beta Version " 

parser = OptionParser()
parser.add_option("-p", "--port", dest = "port_number", default = 3333, help = "Write the port number that GDB server will open")
parser.add_option("-b", "--board", dest = "board_id", default = None, help = "Write the board id you want to connect")
parser.add_option("-l", "--list", action = "store_true", dest = "list_all", default = False, help = "List all the connected board")
parser.add_option("-d", "--debug", dest = "debug_level", default = 'info', help = "Set the level of system logging output, the available value for DEBUG_LEVEL: debug, info, warning, error, critical" )
(option, args) = parser.parse_args()

gdb = None
level = LEVELS.get(option.debug_level, logging.NOTSET)
logging.basicConfig(level=level)
if option.list_all == True:
    MbedBoard.listConnectedBoards()
else:
    try:
        board_selected = MbedBoard.chooseBoard(board_id = option.board_id)
        if board_selected != None:
            try:
                gdb = GDBServer(board_selected, int(option.port_number))
                while gdb.isAlive():
                    gdb.join(timeout = 0.5)
            except ValueError:
                logging.error("Port number error!")
    except KeyboardInterrupt:
        if gdb != None:
            gdb.shutdown_event.set()
            #gdb.stop()       
    except Exception as e:
Exemple #26
0
def speed_test(board_id):
    with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "kl25z":
            ram_start = 0x1ffff000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        elif target_type == "kl28z":
            ram_start = 0x1fffa000
            ram_size = 96*1024
            rom_start = 0x00000000
            rom_size = 512*1024
        elif target_type == "kl46z":
            ram_start = 0x1fffe000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "k22f":
            ram_start = 0x1fff0000
            ram_size = 0x20000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "k64f":
            ram_start = 0x1FFF0000
            ram_size = 0x40000
            rom_start = 0x00000000
            rom_size = 0x100000
        elif target_type == "lpc11u24":
            ram_start = 0x10000000
            ram_size = 0x2000
            rom_start = 0x00000000
            rom_size = 0x8000
        elif target_type == "lpc1768":
            ram_start = 0x10000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "lpc800":
            ram_start = 0x10000000
            ram_size = 0x1000
            rom_start = 0x00000000
            rom_size = 0x4000
        elif target_type == "lpc4330":
            ram_start = 0x10000000
            ram_size = 0x20000
            rom_start = 0x14000000
            rom_size = 0x100000
        elif target_type == "nrf51":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x40000
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        elif target_type == "maxwsnenv":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "max32600mbed":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "w7500":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        else:
            raise Exception("The board is not supported by this test script.")

        target = board.target
        transport = board.transport
        flash = board.flash
        interface = board.interface

        test_pass_count = 0
        test_count = 0
        result = SpeedTestResult()

        transport.setClock(test_clock)
        transport.setDeferredTransfer(True)

        print "\r\n\r\n------ TEST USB TRANSFER SPEED ------"
        max_packets = interface.getPacketCount()
        data_to_write = [0x80] + [0x00] * 63
        start = time()
        packet_count = USB_TEST_XFER_COUNT
        while packet_count > 0:
                interface.write(data_to_write)
                interface.read()
                packet_count = packet_count - 1
        stop = time()
        result.usb_speed = USB_TEST_XFER_COUNT * 64 / (stop-start)
        print "USB transfer rate %f B/s" % result.usb_speed

        print "\r\n\r\n------ TEST OVERLAPPED USB TRANSFER SPEED ------"
        max_packets = interface.getPacketCount()
        print("Concurrent packets: %i" % max_packets)
        data_to_write = [0x80] + [0x00] * 63
        start = time()
        packet_count = USB_TEST_XFER_COUNT
        reads_pending = 0
        while packet_count > 0 or reads_pending > 0:
            # Make sure the transmit buffer stays saturated
            while packet_count > 0 and reads_pending < max_packets:
                interface.write(data_to_write)
                packet_count = packet_count - 1
                reads_pending = reads_pending + 1

            # Read data
            if reads_pending > 0:
                interface.read()
                reads_pending = reads_pending - 1
        stop = time()
        result.usb_overlapped = USB_TEST_XFER_COUNT * 64 / (stop-start)
        print "USB transfer rate %f B/s" % result.usb_overlapped

        print "\r\n\r\n------ TEST RAM READ / WRITE SPEED ------"
        test_addr = ram_start
        test_size = ram_size
        data = [randrange(1, 50) for x in range(test_size)]
        start = time()
        target.writeBlockMemoryUnaligned8(test_addr, data)
        stop = time()
        diff = stop-start
        result.write_speed = test_size / diff
        print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff,  result.write_speed))
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        stop = time()
        diff = stop-start
        result.read_speed = test_size / diff
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff,  result.read_speed))
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])
        if error:
            print "TEST FAILED"
        else:
            print "TEST PASSED"
            test_pass_count += 1
        test_count += 1

        print "\r\n\r\n------ TEST ROM READ SPEED ------"
        test_addr = rom_start
        test_size = rom_size
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        stop = time()
        diff = stop-start
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff,  test_size / diff))
        print "TEST PASSED"
        test_pass_count += 1
        test_count += 1

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #27
0
 def handle_list(self, args):
     MbedBoard.listConnectedBoards()
Exemple #28
0
def cortex_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())

        test_clock = 10000000
        addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        addr = ram_region.start + 1
        size = 0x502
        addr_bin = rom_region.start

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

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        test_pass_count = 0
        test_count = 0
        result = CortexTestResult()

        debugContext = target.getTargetContext()
        gdbFacade = pyOCD.gdbserver.context_facade.GDBDebugContextFacade(debugContext)

        print("\n\n----- FLASH NEW BINARY BEFORE TEST -----")
        flash.flashBinary(binary_file, addr_bin)
        # Let the target run for a bit so it
        # can initialize the watchdog if it needs to
        target.resume()
        sleep(0.2)
        target.halt()

        print("PROGRAMMING COMPLETE")


        print("\n\n----- TESTING CORTEX-M PERFORMANCE -----")
        test_time = test_function(board, gdbFacade.getTResponse)
        print("Function getTResponse time: %f" % test_time)

        # Step
        test_time = test_function(board, target.step)
        print("Function step time: %f" % test_time)

        # Breakpoint
        def set_remove_breakpoint():
            target.setBreakpoint(0)
            target.removeBreakpoint(0)
        test_time = test_function(board, set_remove_breakpoint)
        print("Add and remove breakpoint: %f" % test_time)

        # getRegisterContext
        test_time = test_function(board, gdbFacade.getRegisterContext)
        print("Function getRegisterContext: %f" % test_time)

        # setRegisterContext
        context = gdbFacade.getRegisterContext()
        def set_register_context():
            gdbFacade.setRegisterContext(context)
        test_time = test_function(board, set_register_context)
        print("Function setRegisterContext: %f" % test_time)

        # Run / Halt
        def run_halt():
            target.resume()
            target.halt()
        test_time = test_function(board, run_halt)
        print("Resume and halt: %f" % test_time)

        # GDB stepping
        def simulate_step():
            target.step()
            gdbFacade.getTResponse()
            target.setBreakpoint(0)
            target.resume()
            target.halt()
            gdbFacade.getTResponse()
            target.removeBreakpoint(0)
        test_time = test_function(board, simulate_step)
        print("Simulated GDB step: %f" % test_time)

        # Test passes if there are no exceptions
        test_pass_count += 1
        test_count += 1
        print("TEST PASSED")


        print("\n\n------ Testing Invalid Memory Access Recovery ------")
        memory_access_pass = True
        try:
            target.readBlockMemoryUnaligned8(addr_invalid, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        try:
            target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid + 1, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        if same(data, block):
            print("Aligned access pass")
        else:
            print("Memory read does not match memory written")
            memory_access_pass = False

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr + 1, data)
        block = target.readBlockMemoryUnaligned8(addr + 1, size)
        if same(data, block):
            print("Unaligned access pass")
        else:
            print("Unaligned memory read does not match memory written")
            memory_access_pass = False

        test_count += 1
        if memory_access_pass:
            test_pass_count += 1
            print("TEST PASSED")
        else:
            print("TEST FAILED")

        print("\n\n------ Testing Software Breakpoints ------")
        test_passed = True
        orig8x2 = target.readBlockMemoryUnaligned8(addr, 2)
        orig8 = target.read8(addr)
        orig16 = target.read16(addr & ~1)
        orig32 = target.read32(addr & ~3)
        origAligned32 = target.readBlockMemoryAligned32(addr & ~3, 1)

        def test_filters():
            test_passed = True
            filtered = target.readBlockMemoryUnaligned8(addr, 2)
            if same(orig8x2, filtered):
                print("2 byte unaligned passed")
            else:
                print("2 byte unaligned failed (read %x-%x, expected %x-%x)" % (filtered[0], filtered[1], orig8x2[0], orig8x2[1]))
                test_passed = False

            for now in (True, False):
                filtered = target.read8(addr, now)
                if not now:
                    filtered = filtered()
                if filtered == orig8:
                    print("8-bit passed [now=%s]" % now)
                else:
                    print("8-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig8))
                    test_passed = False

                filtered = target.read16(addr & ~1, now)
                if not now:
                    filtered = filtered()
                if filtered == orig16:
                    print("16-bit passed [now=%s]" % now)
                else:
                    print("16-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig16))
                    test_passed = False

                filtered = target.read32(addr & ~3, now)
                if not now:
                    filtered = filtered()
                if filtered == orig32:
                    print("32-bit passed [now=%s]" % now)
                else:
                    print("32-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig32))
                    test_passed = False

            filtered = target.readBlockMemoryAligned32(addr & ~3, 1)
            if same(filtered, origAligned32):
                print("32-bit aligned passed")
            else:
                print("32-bit aligned failed (read %x, expected %x)" % (filtered[0], origAligned32[0]))
                test_passed = False
            return test_passed

        print("Installed software breakpoint at 0x%08x" % addr)
        target.setBreakpoint(addr, pyOCD.core.target.Target.BREAKPOINT_SW)
        test_passed = test_filters() and test_passed

        print("Removed software breakpoint")
        target.removeBreakpoint(addr)
        test_passed = test_filters() and test_passed

        test_count += 1
        if test_passed:
            test_pass_count += 1
            print("TEST PASSED")
        else:
            print("TEST FAILED")

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #29
0
def speed_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == "ram"]
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        ram_start = ram_region.start
        ram_size = ram_region.length
        rom_start = rom_region.start
        rom_size = rom_region.length

        target = board.target
        link = board.link

        test_pass_count = 0
        test_count = 0
        result = SpeedTestResult()

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        print("\r\n\r\n------ TEST RAM READ / WRITE SPEED ------")
        test_addr = ram_start
        test_size = ram_size
        data = [randrange(1, 50) for x in range(test_size)]
        start = time()
        target.writeBlockMemoryUnaligned8(test_addr, data)
        target.flush()
        stop = time()
        diff = stop - start
        result.write_speed = test_size / diff
        print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed))
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        result.read_speed = test_size / diff
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed))
        error = False
        for i in range(len(block)):
            if block[i] != data[i]:
                error = True
                print("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]))
        if error:
            print("TEST FAILED")
        else:
            print("TEST PASSED")
            test_pass_count += 1
        test_count += 1

        print("\r\n\r\n------ TEST ROM READ SPEED ------")
        test_addr = rom_start
        test_size = rom_size
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff))
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #30
0
def test_gdb(board_id=None):
    result = GdbTestResult()
    with MbedBoard.chooseBoard(board_id=board_id) as board:
        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()
        target_type = board.getTargetType()
        binary_file = os.path.join(parentdir, 'binaries',
                                   board.getTestBinary())
        if board_id is None:
            board_id = board.getUniqueID()
        test_clock = 10000000
        test_port = 3334
        error_on_invalid_access = True
        # Hardware breakpoints are not supported above 0x20000000 on
        # CortexM devices
        ignore_hw_bkpt_result = 1 if ram_region.start >= 0x20000000 else 0
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
            # Reading invalid ram returns 0 or nrf51
            error_on_invalid_access = False
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        # Program with initial test image
        board.flash.flashBinary(binary_file, rom_region.start)
        board.uninit(False)

    # Write out the test configuration
    test_params = {}
    test_params["rom_start"] = rom_region.start
    test_params["rom_length"] = rom_region.length
    test_params["ram_start"] = ram_region.start
    test_params["ram_length"] = ram_region.length
    test_params["invalid_start"] = 0x3E000000
    test_params["invalid_length"] = 0x1000
    test_params["expect_error_on_invalid_access"] = error_on_invalid_access
    test_params["ignore_hw_bkpt_result"] = ignore_hw_bkpt_result
    with open(TEST_PARAM_FILE, "wb") as f:
        f.write(json.dumps(test_params))

    # Run the test
    gdb = [PYTHON_GDB, "--command=gdb_script.py"]
    with open("output.txt", "wb") as f:
        program = Popen(gdb, stdin=PIPE, stdout=f, stderr=STDOUT)
        args = ['-p=%i' % test_port, "-f=%i" % test_clock, "-b=%s" % board_id]
        server = GDBServerTool()
        server.run(args)
        program.wait()

    # Read back the result
    with open(TEST_RESULT_FILE, "rb") as f:
        test_result = json.loads(f.read())

    # Print results
    if set(TEST_RESULT_KEYS).issubset(test_result):
        print("----------------Test Results----------------")
        print("HW breakpoint count: %s" % test_result["breakpoint_count"])
        print("Watchpoint count: %s" % test_result["watchpoint_count"])
        print("Average instruction step time: %s" %
              test_result["step_time_si"])
        print("Average single step time: %s" % test_result["step_time_s"])
        print("Average over step time: %s" % test_result["step_time_n"])
        print("Failure count: %i" % test_result["fail_count"])
        result.passed = test_result["fail_count"] == 0
    else:
        result.passed = False

    # Cleanup
    os.remove(TEST_RESULT_FILE)
    os.remove(TEST_PARAM_FILE)

    return result
def main():
    args = parser.parse_args()
    setup_logging(args)

    # 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)
        with board_selected as board:
            flash = board.flash
            transport = board.transport

            # Boost speed with deferred transfers
            transport.setDeferredTransfer(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)
Exemple #32
0
 def read_target_memory(self, addr, size, resume=True):
     assert self.get_mode() == self.MODE_IF
     with MbedBoard.chooseBoard(board_id=self.get_unique_id()) as board:
         data = board.target.readBlockMemoryUnaligned8(addr, size)
         board.uninit(resume)
     return bytearray(data)
Exemple #33
0
def cortex_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())

        test_clock = 10000000
        addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        addr = ram_region.start + 1
        size = 0x502
        addr_bin = rom_region.start

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

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        test_pass_count = 0
        test_count = 0
        result = CortexTestResult()

        print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----"
        flash.flashBinary(binary_file, addr_bin)
        # Let the target run for a bit so it
        # can initialize the watchdog if it needs to
        target.resume()
        sleep(0.2)
        target.halt()

        print "PROGRAMMING COMPLETE"


        print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----"
        test_time = test_function(board, target.getTResponse)
        print("Function getTResponse time: %f" % test_time)

        # Step
        test_time = test_function(board, target.step)
        print("Function step time: %f" % test_time)

        # Breakpoint
        def set_remove_breakpoint():
            target.setBreakpoint(0)
            target.removeBreakpoint(0)
        test_time = test_function(board, set_remove_breakpoint)
        print("Add and remove breakpoint: %f" % test_time)

        # getRegisterContext
        test_time = test_function(board, target.getRegisterContext)
        print("Function getRegisterContext: %f" % test_time)

        # setRegisterContext
        context = target.getRegisterContext()
        def set_register_context():
            target.setRegisterContext(context)
        test_time = test_function(board, set_register_context)
        print("Function setRegisterContext: %f" % test_time)

        # Run / Halt
        def run_halt():
            target.resume()
            target.halt()
        test_time = test_function(board, run_halt)
        print("Resume and halt: %f" % test_time)

        # GDB stepping
        def simulate_step():
            target.step()
            target.getTResponse()
            target.setBreakpoint(0)
            target.resume()
            target.halt()
            target.getTResponse()
            target.removeBreakpoint(0)
        test_time = test_function(board, simulate_step)
        print("Simulated GDB step: %f" % test_time)

        # Test passes if there are no exceptions
        test_pass_count += 1
        test_count += 1
        print("TEST PASSED")


        print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------"
        memory_access_pass = True
        try:
            target.readBlockMemoryUnaligned8(addr_invalid, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        try:
            target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [0x00] * 0x1000
        try:
            target.writeBlockMemoryUnaligned8(addr_invalid + 1, data)
            target.flush()
            # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0
            if target_type != "nrf51":
                memory_access_pass = False
        except DAPAccess.TransferFaultError:
            pass

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        if same(data, block):
            print "Aligned access pass"
        else:
            print("Memory read does not match memory written")
            memory_access_pass = False

        data = [randrange(0, 255) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr + 1, data)
        block = target.readBlockMemoryUnaligned8(addr + 1, size)
        if same(data, block):
            print "Unaligned access pass"
        else:
            print("Unaligned memory read does not match memory written")
            memory_access_pass = False

        test_count += 1
        if memory_access_pass:
            test_pass_count += 1
            print "TEST PASSED"
        else:
            print "TEST FAILED"

        print "\r\n\r\n------ Testing Software Breakpoints ------"
        test_passed = True
        orig8x2 = target.readBlockMemoryUnaligned8(addr, 2)
        orig8 = target.read8(addr)
        orig16 = target.read16(addr & ~1)
        orig32 = target.read32(addr & ~3)
        origAligned32 = target.readBlockMemoryAligned32(addr & ~3, 1)

        def test_filters():
            test_passed = True
            filtered = target.readBlockMemoryUnaligned8(addr, 2)
            if same(orig8x2, filtered):
                print "2 byte unaligned passed"
            else:
                print "2 byte unaligned failed (read %x-%x, expected %x-%x)" % (filtered[0], filtered[1], orig8x2[0], orig8x2[1])
                test_passed = False

            for now in (True, False):
                filtered = target.read8(addr, now)
                if not now:
                    filtered = filtered()
                if filtered == orig8:
                    print "8-bit passed [now=%s]" % now
                else:
                    print "8-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig8)
                    test_passed = False

                filtered = target.read16(addr & ~1, now)
                if not now:
                    filtered = filtered()
                if filtered == orig16:
                    print "16-bit passed [now=%s]" % now
                else:
                    print "16-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig16)
                    test_passed = False

                filtered = target.read32(addr & ~3, now)
                if not now:
                    filtered = filtered()
                if filtered == orig32:
                    print "32-bit passed [now=%s]" % now
                else:
                    print "32-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig32)
                    test_passed = False

            filtered = target.readBlockMemoryAligned32(addr & ~3, 1)
            if same(filtered, origAligned32):
                print "32-bit aligned passed"
            else:
                print "32-bit aligned failed (read %x, expected %x)" % (filtered[0], origAligned32[0])
                test_passed = False
            return test_passed

        print "Installed software breakpoint at 0x%08x" % addr
        target.setBreakpoint(addr, pyOCD.target.target.Target.BREAKPOINT_SW)
        test_passed = test_filters() and test_passed

        print "Removed software breakpoint"
        target.removeBreakpoint(addr)
        test_passed = test_filters() and test_passed

        test_count += 1
        if test_passed:
            test_pass_count += 1
            print "TEST PASSED"
        else:
            print "TEST FAILED"

        target.reset()

        result.passed = test_count == test_pass_count
        return result
Exemple #34
0
def basic_test(board_id, file):
    with MbedBoard.chooseBoard(board_id=board_id) as board:
        addr = 0
        size = 0
        f = None
        binary_file = "l1_"

        interface = None

        target_type = board.getTargetType()

        if file is None:
            binary_file += target_type + ".bin"
            binary_file = os.path.join(parentdir, 'binaries', binary_file)
        else:
            binary_file = file

        print "binary file: %s" % binary_file

        addr_bin = 0x00000000

        if target_type == "lpc1768":
            addr = 0x10000001
            size = 0x1102
            addr_flash = 0x10000
        elif target_type == "lpc11u24":
            addr = 0x10000001
            size = 0x502
            addr_flash = 0x4000
        elif target_type == "kl25z":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k64f":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k22f":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "k20d50m":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "kl46z":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "lpc800":
            addr = 0x10000001
            size = 0x502
            addr_flash = 0x2000
        elif target_type == "nrf51822":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x20000
        elif target_type == "lpc4330":
            addr = 0x10000001
            size = 0x1102
            addr_flash = 0x14010000
            addr_bin = 0x14000000
        elif target_type == "maxwsnenv":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        elif target_type == "max32600mbed":
            addr = 0x20000001
            size = 0x502
            addr_flash = 0x10000
        else:
            raise Exception("A board is not supported by this test script.")

        target = board.target
        transport = board.transport
        flash = board.flash
        interface = board.interface

        print "\r\n\r\n------ GET Unique ID ------"
        print "Unique ID: %s" % board.getUniqueID()

        print "\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------"
        pc = target.readCoreRegister('pc')
        print "initial pc: 0x%X" % target.readCoreRegister('pc')
        # write in pc dummy value
        target.writeCoreRegister('pc', 0x3D82)
        print "now pc: 0x%X" % target.readCoreRegister('pc')
        # write initial pc value
        target.writeCoreRegister('pc', pc)
        print "initial pc value rewritten: 0x%X" % target.readCoreRegister(
            'pc')

        msp = target.readCoreRegister('msp')
        psp = target.readCoreRegister('psp')
        print "MSP = 0x%08x; PSP = 0x%08x" % (msp, psp)

        control = target.readCoreRegister('control')
        faultmask = target.readCoreRegister('faultmask')
        basepri = target.readCoreRegister('basepri')
        primask = target.readCoreRegister('primask')
        print "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (
            control, faultmask, basepri, primask)

        target.writeCoreRegister('primask', 1)
        newPrimask = target.readCoreRegister('primask')
        print "New PRIMASK = 0x%02x" % newPrimask
        target.writeCoreRegister('primask', primask)
        newPrimask = target.readCoreRegister('primask')
        print "Restored PRIMASK = 0x%02x" % newPrimask

        if target.has_fpu:
            s0 = target.readCoreRegister('s0')
            print "S0 = %g (0x%08x)" % (s0, float2int(s0))
            target.writeCoreRegister('s0', math.pi)
            newS0 = target.readCoreRegister('s0')
            print "New S0 = %g (0x%08x)" % (newS0, float2int(newS0))
            target.writeCoreRegister('s0', s0)
            newS0 = target.readCoreRegister('s0')
            print "Restored S0 = %g (0x%08x)" % (newS0, float2int(newS0))

        print "\r\n\r\n------ TEST HALT / RESUME ------"

        print "resume"
        target.resume()
        sleep(0.2)

        print "halt"
        target.halt()
        print "HALT: pc: 0x%X" % target.readCoreRegister('pc')
        sleep(0.2)

        print "\r\n\r\n------ TEST READ / WRITE MEMORY ------"
        target.halt()
        print "READ32/WRITE32"
        val = randrange(0, 0xffffffff)
        print "write32 0x%X at 0x%X" % (val, addr)
        target.writeMemory(addr, val)
        res = target.readMemory(addr)
        print "read32 at 0x%X: 0x%X" % (addr, res)
        if res != val:
            print "ERROR in READ/WRITE 32"

        print "\r\nREAD16/WRITE16"
        val = randrange(0, 0xffff)
        print "write16 0x%X at 0x%X" % (val, addr + 2)
        target.writeMemory(addr + 2, val, 16)
        res = target.readMemory(addr + 2, 16)
        print "read16 at 0x%X: 0x%X" % (addr + 2, res)
        if res != val:
            print "ERROR in READ/WRITE 16"

        print "\r\nREAD8/WRITE8"
        val = randrange(0, 0xff)
        print "write8 0x%X at 0x%X" % (val, addr + 1)
        target.writeMemory(addr + 1, val, 8)
        res = target.readMemory(addr + 1, 8)
        print "read8 at 0x%X: 0x%X" % (addr + 1, res)
        if res != val:
            print "ERROR in READ/WRITE 8"

        print "\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------"
        data = [randrange(1, 50) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                print "ERROR: 0x%X, 0x%X, 0x%X!!!" % (
                    (addr + i), block[i], data[i])
        if error:
            print "TEST FAILED"
        else:
            print "TEST PASSED"

        print "\r\n\r\n------ TEST RESET ------"
        target.reset()
        sleep(0.1)
        target.halt()

        for i in range(5):
            target.step()
            print "pc: 0x%X" % target.readCoreRegister('pc')

        print "\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------"
        # Fill 3 pages with 0x55
        fill = [0x55] * flash.page_size
        flash.init()
        for i in range(0, 3):
            flash.erasePage(addr_flash + flash.page_size * i)
            flash.programPage(addr_flash + flash.page_size * i, fill)
        # Erase the middle page
        flash.erasePage(addr_flash + flash.page_size)
        # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased
        data = target.readBlockMemoryUnaligned8(addr_flash,
                                                flash.page_size * 3)
        expected = fill + [0xFF] * flash.page_size + fill
        if data == expected:
            print "TEST PASSED"
        else:
            print "TEST FAILED"

        print "\r\n\r\n----- FLASH NEW BINARY -----"
        flash.flashBinary(binary_file, addr_bin)

        target.reset()
def speed_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        ram_start = ram_region.start
        ram_size = ram_region.length
        rom_start = rom_region.start
        rom_size = rom_region.length

        target = board.target
        link = board.link

        test_pass_count = 0
        test_count = 0
        result = SpeedTestResult()

        link.set_clock(test_clock)
        link.set_deferred_transfer(True)

        print("\r\n\r\n------ TEST RAM READ / WRITE SPEED ------")
        test_addr = ram_start
        test_size = ram_size
        data = [randrange(1, 50) for x in range(test_size)]
        start = time()
        target.writeBlockMemoryUnaligned8(test_addr, data)
        target.flush()
        stop = time()
        diff = stop - start
        result.write_speed = test_size / diff
        print("Writing %i byte took %s seconds: %s B/s" %
              (test_size, diff, result.write_speed))
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        result.read_speed = test_size / diff
        print("Reading %i byte took %s seconds: %s B/s" %
              (test_size, diff, result.read_speed))
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                print("ERROR: 0x%X, 0x%X, 0x%X!!!" %
                      ((addr + i), block[i], data[i]))
        if error:
            print("TEST FAILED")
        else:
            print("TEST PASSED")
            test_pass_count += 1
        test_count += 1

        print("\r\n\r\n------ TEST ROM READ SPEED ------")
        test_addr = rom_start
        test_size = rom_size
        start = time()
        block = target.readBlockMemoryUnaligned8(test_addr, test_size)
        target.flush()
        stop = time()
        diff = stop - start
        print("Reading %i byte took %s seconds: %s B/s" %
              (test_size, diff, test_size / diff))
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        target.reset()

        result.passed = test_count == test_pass_count
        return result
def basic_test(board_id, file):
    with MbedBoard.chooseBoard(board_id=board_id) as board:
        addr = 0
        size = 0
        f = None
        binary_file = "l1_"

        target_type = board.getTargetType()

        if file is None:
            binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())
        else:
            binary_file = file

        print "binary file: %s" % binary_file

        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        addr = ram_region.start + 1
        size = 0x502
        addr_bin = rom_region.start
        addr_flash = rom_region.start + rom_region.length // 2

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


        print "\r\n\r\n------ GET Unique ID ------"
        print "Unique ID: %s" % board.getUniqueID()

        print "\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------"
        pc = target.readCoreRegister('pc')
        print "initial pc: 0x%X" % target.readCoreRegister('pc')
        # write in pc dummy value
        target.writeCoreRegister('pc', 0x3D82)
        print "now pc: 0x%X" % target.readCoreRegister('pc')
        # write initial pc value
        target.writeCoreRegister('pc', pc)
        print "initial pc value rewritten: 0x%X" % target.readCoreRegister('pc')

        msp = target.readCoreRegister('msp')
        psp = target.readCoreRegister('psp')
        print "MSP = 0x%08x; PSP = 0x%08x" % (msp, psp)

        control = target.readCoreRegister('control')
        faultmask = target.readCoreRegister('faultmask')
        basepri = target.readCoreRegister('basepri')
        primask = target.readCoreRegister('primask')
        print "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask)

        target.writeCoreRegister('primask', 1)
        newPrimask = target.readCoreRegister('primask')
        print "New PRIMASK = 0x%02x" % newPrimask
        target.writeCoreRegister('primask', primask)
        newPrimask = target.readCoreRegister('primask')
        print "Restored PRIMASK = 0x%02x" % newPrimask

        if target.has_fpu:
            s0 = target.readCoreRegister('s0')
            print "S0 = %g (0x%08x)" % (s0, float32beToU32be(s0))
            target.writeCoreRegister('s0', math.pi)
            newS0 = target.readCoreRegister('s0')
            print "New S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))
            target.writeCoreRegister('s0', s0)
            newS0 = target.readCoreRegister('s0')
            print "Restored S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))


        print "\r\n\r\n------ TEST HALT / RESUME ------"

        print "resume"
        target.resume()
        sleep(0.2)

        print "halt"
        target.halt()
        print "HALT: pc: 0x%X" % target.readCoreRegister('pc')
        sleep(0.2)


        print "\r\n\r\n------ TEST STEP ------"

        print "reset and halt"
        target.resetStopOnReset()
        currentPC = target.readCoreRegister('pc')
        print "HALT: pc: 0x%X" % currentPC
        sleep(0.2)

        for i in range(4):
            print "step"
            target.step()
            newPC = target.readCoreRegister('pc')
            print "STEP: pc: 0x%X" % newPC
            currentPC = newPC
            sleep(0.2)


        print "\r\n\r\n------ TEST READ / WRITE MEMORY ------"
        target.halt()
        print "READ32/WRITE32"
        val = randrange(0, 0xffffffff)
        print "write32 0x%X at 0x%X" % (val, addr)
        target.writeMemory(addr, val)
        res = target.readMemory(addr)
        print "read32 at 0x%X: 0x%X" % (addr, res)
        if res != val:
            print "ERROR in READ/WRITE 32"

        print "\r\nREAD16/WRITE16"
        val = randrange(0, 0xffff)
        print "write16 0x%X at 0x%X" % (val, addr + 2)
        target.writeMemory(addr + 2, val, 16)
        res = target.readMemory(addr + 2, 16)
        print "read16 at 0x%X: 0x%X" % (addr + 2, res)
        if res != val:
            print "ERROR in READ/WRITE 16"

        print "\r\nREAD8/WRITE8"
        val = randrange(0, 0xff)
        print "write8 0x%X at 0x%X" % (val, addr + 1)
        target.writeMemory(addr + 1, val, 8)
        res = target.readMemory(addr + 1, 8)
        print "read8 at 0x%X: 0x%X" % (addr + 1, res)
        if res != val:
            print "ERROR in READ/WRITE 8"


        print "\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------"
        data = [randrange(1, 50) for x in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])
        if error:
            print "TEST FAILED"
        else:
            print "TEST PASSED"


        print "\r\n\r\n------ TEST RESET ------"
        target.reset()
        sleep(0.1)
        target.halt()

        for i in range(5):
            target.step()
            print "pc: 0x%X" % target.readCoreRegister('pc')

        print "\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------"
        # Fill 3 pages with 0x55
        page_size = flash.getPageInfo(addr_flash).size
        fill = [0x55] * page_size
        flash.init()
        for i in range(0, 3):
            address = addr_flash + page_size * i
            # Test only supports a location with 3 aligned
            # pages of the same size
            current_page_size = flash.getPageInfo(addr_flash).size
            assert page_size == current_page_size
            assert address % current_page_size == 0
            flash.erasePage(address)
            flash.programPage(address, fill)
        # Erase the middle page
        flash.erasePage(addr_flash + page_size)
        # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased
        data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3)
        expected = fill + [0xFF] * page_size + fill
        if data == expected:
            print "TEST PASSED"
        else:
            print "TEST FAILED"

        print "\r\n\r\n----- FLASH NEW BINARY -----"
        flash.flashBinary(binary_file, addr_bin)

        target.reset()
Exemple #37
0
def test_hid(workspace, parent_test):
    test_info = parent_test.create_subtest("HID test")
    board = workspace.board
    with MbedBoard.chooseBoard(board_id=board.get_unique_id()) as mbed_board:
        binary_file = workspace.target.bin_path

        memory_map = mbed_board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()

        addr = ram_region.start + 1
        size = 0x502
        addr_bin = rom_region.start
        addr_flash = rom_region.start + rom_region.length // 2

        target = mbed_board.target
        flash = mbed_board.flash

        test_info.info("\r\n\r\n----- FLASH NEW BINARY -----")
        flash.flashBinary(binary_file, addr_bin)

        test_info.info("\r\n\r\n------ GET Unique ID ------")
        test_info.info("Unique ID: %s" % mbed_board.getUniqueID())

        test_info.info("\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------")
        pc = target.readCoreRegister('pc')
        test_info.info("initial pc: 0x%X" % target.readCoreRegister('pc'))
        # write in pc dummy value
        target.writeCoreRegister('pc', 0x3D82)
        test_info.info("now pc: 0x%X" % target.readCoreRegister('pc'))
        # write initial pc value
        target.writeCoreRegister('pc', pc)
        test_info.info("initial pc value rewritten: 0x%X" %
                       target.readCoreRegister('pc'))

        msp = target.readCoreRegister('msp')
        psp = target.readCoreRegister('psp')
        test_info.info("MSP = 0x%08x; PSP = 0x%08x" % (msp, psp))

        control = target.readCoreRegister('control')
        faultmask = target.readCoreRegister('faultmask')
        basepri = target.readCoreRegister('basepri')
        primask = target.readCoreRegister('primask')
        test_info.info(
            "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x"
            % (control, faultmask, basepri, primask))

        target.writeCoreRegister('primask', 1)
        newPrimask = target.readCoreRegister('primask')
        test_info.info("New PRIMASK = 0x%02x" % newPrimask)
        target.writeCoreRegister('primask', primask)
        newPrimask = target.readCoreRegister('primask')
        test_info.info("Restored PRIMASK = 0x%02x" % newPrimask)

        if target.has_fpu:
            s0 = target.readCoreRegister('s0')
            test_info.info("S0 = %g (0x%08x)" % (s0, float32beToU32be(s0)))
            target.writeCoreRegister('s0', math.pi)
            newS0 = target.readCoreRegister('s0')
            test_info.info("New S0 = %g (0x%08x)" %
                           (newS0, float32beToU32be(newS0)))
            target.writeCoreRegister('s0', s0)
            newS0 = target.readCoreRegister('s0')
            test_info.info("Restored S0 = %g (0x%08x)" %
                           (newS0, float32beToU32be(newS0)))

        test_info.info("\r\n\r\n------ TEST HALT / RESUME ------")

        test_info.info("resume")
        target.resume()
        sleep(0.2)

        test_info.info("halt")
        target.halt()
        test_info.info("HALT: pc: 0x%X" % target.readCoreRegister('pc'))
        sleep(0.2)

        test_info.info("\r\n\r\n------ TEST STEP ------")

        test_info.info("reset and halt")
        target.resetStopOnReset()
        currentPC = target.readCoreRegister('pc')
        test_info.info("HALT: pc: 0x%X" % currentPC)
        sleep(0.2)

        for i in range(4):
            test_info.info("step")
            target.step()
            newPC = target.readCoreRegister('pc')
            test_info.info("STEP: pc: 0x%X" % newPC)
            currentPC = newPC
            sleep(0.2)

        test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY ------")
        target.halt()
        test_info.info("READ32/WRITE32")
        val = randrange(0, 0xffffffff)
        test_info.info("write32 0x%X at 0x%X" % (val, addr))
        target.writeMemory(addr, val)
        res = target.readMemory(addr)
        test_info.info("read32 at 0x%X: 0x%X" % (addr, res))
        if res != val:
            test_info.failure("ERROR in READ/WRITE 32")

        test_info.info("\r\nREAD16/WRITE16")
        val = randrange(0, 0xffff)
        test_info.info("write16 0x%X at 0x%X" % (val, addr + 2))
        target.writeMemory(addr + 2, val, 16)
        res = target.readMemory(addr + 2, 16)
        test_info.info("read16 at 0x%X: 0x%X" % (addr + 2, res))
        if res != val:
            test_info.failure("ERROR in READ/WRITE 16")

        test_info.info("\r\nREAD8/WRITE8")
        val = randrange(0, 0xff)
        test_info.info("write8 0x%X at 0x%X" % (val, addr + 1))
        target.writeMemory(addr + 1, val, 8)
        res = target.readMemory(addr + 1, 8)
        test_info.info("read8 at 0x%X: 0x%X" % (addr + 1, res))
        if res != val:
            test_info.failure("ERROR in READ/WRITE 8")

        test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------")
        data = [randrange(1, 50) for _ in range(size)]
        target.writeBlockMemoryUnaligned8(addr, data)
        block = target.readBlockMemoryUnaligned8(addr, size)
        error = False
        for i in range(len(block)):
            if (block[i] != data[i]):
                error = True
                test_info.info("ERROR: 0x%X, 0x%X, 0x%X!!!" %
                               ((addr + i), block[i], data[i]))
        if error:
            test_info.failure("TEST FAILED")
        else:
            test_info.info("TEST PASSED")

        test_info.info("\r\n\r\n------ TEST RESET ------")
        target.reset()
        sleep(0.1)
        target.halt()

        for i in range(5):
            target.step()
            test_info.info("pc: 0x%X" % target.readCoreRegister('pc'))

        test_info.info("\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------")
        # Fill 3 pages with 0x55
        page_size = flash.getPageInfo(addr_flash).size
        fill = [0x55] * page_size
        flash.init()
        for i in range(0, 3):
            address = addr_flash + page_size * i
            # Test only supports a location with 3 aligned
            # pages of the same size
            current_page_size = flash.getPageInfo(addr_flash).size
            assert page_size == current_page_size
            assert address % current_page_size == 0
            flash.erasePage(address)
            flash.programPage(address, fill)
        # Erase the middle page
        flash.erasePage(addr_flash + page_size)
        # Verify the 1st and 3rd page were not erased, and that
        # the 2nd page is fully erased
        data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3)
        expected = fill + [0xFF] * page_size + fill
        if data == expected:
            test_info.info("TEST PASSED")
        else:
            test_info.failure("TEST FAILED")

        test_info.info("\r\n\r\n----- Restoring image -----")
        flash.flashBinary(binary_file, addr_bin)

        target.reset()
        test_info.info("HID test complete")
Exemple #38
0
        help="connect to board by board id, use -l to list all connected boards"
    )
    parser.add_argument("-l",
                        "--list",
                        action="count",
                        help="list all connected boards")

    args = parser.parse_args()

    if args.verbose == 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose == 1:
        logging.basicConfig(level=logging.INFO)

    if (args.list):
        print MbedBoard.listConnectedBoards()
        sys.exit(0)

    adapter = None
    try:
        adapter = None
        if (args.board_id):
            adapter = MbedBoard.chooseBoard(board_id=args.board_id)
        else:
            interfaces = INTERFACE[usb_backend].getAllConnectedInterface(
                VID, PID)
            if interfaces == None:
                print "Not find a mbed interface"
                sys.exit(1)

            # Use the first one
Exemple #39
0
    sys.stdout = logger
    sys.stderr = logger

    test_list = []
    board_list = []
    result_list = []

    # Put together list of tests
    test = Test("Basic Test", lambda board: basic_test(board, None))
    test_list.append(test)
    test_list.append(SpeedTest())
    test_list.append(CortexTest())
    test_list.append(FlashTest())

    # Put together list of boards to test
    board_list = MbedBoard.getAllConnectedBoards(close=True, blocking=False)

    start = time()
    for board in board_list:
        print("--------------------------")
        print("TESTING BOARD %s" % board.getUniqueID())
        print("--------------------------")
        for test in test_list:
            test_start = time()
            result = test.run(board)
            test_stop = time()
            result.time = test_stop - test_start
            result_list.append(result)
    stop = time()

    for test in test_list:
Exemple #40
0
f = None
binary_file = "l1_"

interface = None

import logging

logging.basicConfig(level=logging.INFO)

parser = argparse.ArgumentParser(description='A CMSIS-DAP python debugger')
parser.add_argument('-f', help='binary file', dest="file")
args = parser.parse_args()

try:

    board = MbedBoard.chooseBoard()
    target_type = board.getTargetType()

    if args.file is None:
        binary_file += target_type + ".bin"
        binary_file = os.path.join(parentdir, 'binaries', binary_file)
    else:
        binary_file = args.file

    print "binary file: %s" % binary_file

    if target_type == "lpc1768":
        addr = 0x10000001
        size = 0x1102
    elif target_type == "lpc11u24":
        addr = 0x10000001
Exemple #41
0
def test_gdb(board_id=None):
    result = GdbTestResult()
    with MbedBoard.chooseBoard(board_id=board_id) as board:
        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == "ram"]
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()
        target_type = board.getTargetType()
        binary_file = os.path.join(parentdir, "binaries", board.getTestBinary())
        if board_id is None:
            board_id = board.getUniqueID()
        test_clock = 10000000
        test_port = 3334
        error_on_invalid_access = True
        # Hardware breakpoints are not supported above 0x20000000 on
        # CortexM devices
        ignore_hw_bkpt_result = 1 if ram_region.start >= 0x20000000 else 0
        if target_type == "nrf51":
            # Override clock since 10MHz is too fast
            test_clock = 1000000
            # Reading invalid ram returns 0 or nrf51
            error_on_invalid_access = False

        # Program with initial test image
        board.flash.flashBinary(binary_file, rom_region.start)
        board.uninit(False)

    # Write out the test configuration
    test_params = {}
    test_params["rom_start"] = rom_region.start
    test_params["rom_length"] = rom_region.length
    test_params["ram_start"] = ram_region.start
    test_params["ram_length"] = ram_region.length
    test_params["invalid_start"] = 0xFFFF0000
    test_params["invalid_length"] = 0x1000
    test_params["expect_error_on_invalid_access"] = error_on_invalid_access
    test_params["ignore_hw_bkpt_result"] = ignore_hw_bkpt_result
    with open(TEST_PARAM_FILE, "wb") as f:
        f.write(json.dumps(test_params))

    # Run the test
    gdb = [PYTHON_GDB, "--command=gdb_script.py"]
    with open("output.txt", "wb") as f:
        program = Popen(gdb, stdin=PIPE, stdout=f, stderr=STDOUT)
        args = ["-p=%i" % test_port, "-f=%i" % test_clock, "-b=%s" % board_id]
        server = GDBServerTool()
        server.run(args)
        program.wait()

    # Read back the result
    with open(TEST_RESULT_FILE, "rb") as f:
        test_result = json.loads(f.read())

    # Print results
    if set(TEST_RESULT_KEYS).issubset(test_result):
        print("----------------Test Results----------------")
        print("HW breakpoint count: %s" % test_result["breakpoint_count"])
        print("Watchpoint count: %s" % test_result["watchpoint_count"])
        print("Average instruction step time: %s" % test_result["step_time_si"])
        print("Average single step time: %s" % test_result["step_time_s"])
        print("Average over step time: %s" % test_result["step_time_n"])
        print("Failure count: %i" % test_result["fail_count"])
        result.passed = test_result["fail_count"] == 0
    else:
        result.passed = False

    # Cleanup
    os.remove(TEST_RESULT_FILE)
    os.remove(TEST_PARAM_FILE)

    return result
from pyOCD.board import MbedBoard

#specific board used for OCD by setting board_id = '<board id of OCD reported by mbedls command>'. If you set to None, then it will search for one and ask for confirmation.
board_id = '10500000e062eef000000000000000000000000097969902'
#board_id = None

RIPPED_FILE = "rom.bin"  # name given to rom ripped from device

with MbedBoard.chooseBoard(target_override='k20d50m',
                           board_id=board_id) as board:
    addr = 0x00000000
    size = 128 * 1024  # K20 has 128 KB of flash. 1024 converts to KB
    data = board.target.readBlockMemoryUnaligned8(addr, size)
    data = bytearray(data)
    with open(RIPPED_FILE, 'wb') as f:
        f.write(data)
    print("Dump success. File " + RIPPED_FILE + " created")
Exemple #43
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()

            # 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:", e

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

            # 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"
            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
Exemple #44
0
    if args.verbose == 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose == 1:
        logging.basicConfig(level=logging.INFO)

    adapter = None
    try:
        interfaces = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
        if interfaces == None:
            print "Not find a mbed interface"
            sys.exit(1)

        # Use the first one
        first_interface = interfaces[0]
        adapter = MbedBoard("target_lpc1768", "flash_lpc1768", first_interface)
        adapter.init()
        target = adapter.target
        target.halt()

        if args.ihex:
            print 'flash hex file - %s to nrf51822' % args.ihex
            flashHex(target, args.ihex)

        offset = 0x14000
        if args.offset:
            offset = args.offset

        if args.bin:
            print 'flash binary file - %s to nrf51822' % args.bin
            flashBin(target, args.bin, offset)
Exemple #45
0
parser.add_option("-c", "--cmd-port", dest = "cmd_port", default = 4444, help = "Command port number. pyOCD doesn't open command port but it's required to be compatible with OpenOCD and Eclipse.")
parser.add_option("-b", "--board", dest = "board_id", default = None, help = "Write the board id you want to connect")
parser.add_option("-l", "--list", action = "store_true", dest = "list_all", default = False, help = "List all the connected board")
parser.add_option("-d", "--debug", dest = "debug_level", default = 'info', help = "Set the level of system logging output, the available value for DEBUG_LEVEL: debug, info, warning, error, critical" )
parser.add_option("-t", "--target", dest = "target_override", default = None, help = "Override target to debug" )
parser.add_option("-n", "--nobreak", dest = "break_at_hardfault", default = True, action="store_false", help = "Disable breakpoint at hardfault handler. Required for nrf51 chip with SoftDevice based application." )
parser.add_option("-s", "--skip", dest = "skip_bytes", default = False, help = "Skip N (hexidecimal) first bytes of flash (for example SoftDevice on nrf51 chip). " )
(option, args) = parser.parse_args()
if (option.skip_bytes):
    option.skip_bytes = int(option.skip_bytes, 16)

gdb = None
level = LEVELS.get(option.debug_level, logging.NOTSET)
logging.basicConfig(level=level)
if option.list_all == True:
    MbedBoard.listConnectedBoards()
else:
    try:
        board_selected = MbedBoard.chooseBoard(board_id = option.board_id, target_override = option.target_override)
        if board_selected != None:
            try:
                gdb = GDBServer(board_selected, int(option.port_number), {'skip_bytes' : option.skip_bytes, 'break_at_hardfault' : option.break_at_hardfault})
                while gdb.isAlive():
                    gdb.join(timeout = 0.5)
            except ValueError:
                logging.error("Port number error!")
    except KeyboardInterrupt:
        if gdb != None:
            gdb.stop()
    except Exception as e:
        print "uncaught exception: %s" % e
f = None
binary_file = "l1_"

interface = None

import logging

logging.basicConfig(level=logging.INFO)

parser = argparse.ArgumentParser(description="A CMSIS-DAP python debugger")
parser.add_argument("-f", help="binary file", dest="file")
args = parser.parse_args()

try:

    board = MbedBoard.chooseBoard()
    target_type = board.getTargetType()

    if args.file is None:
        binary_file += target_type + ".bin"
        binary_file = os.path.join(parentdir, "binaries", binary_file)
    else:
        binary_file = args.file

    print "binary file: %s" % binary_file

    if target_type == "lpc1768":
        addr = 0x10000001
        size = 0x1102
    elif target_type == "lpc11u24":
        addr = 0x10000001
Exemple #47
0
    def run(self):
        board = None
        exitCode = 0

        try:
            # Read command-line arguments.
            args = self.get_args()

            if args.verbose:
                logging.basicConfig(level=logging.INFO)

            # Print a list of all connected boards.
            if args.action == ACTION_LIST:
                MbedBoard.listConnectedBoards()
                sys.exit(0)

            board = MbedBoard.chooseBoard(board_id=args.board, target_override=args.target, init_board=False)
            board.target.setAutoUnlock(False)
            try:
                board.init()
            except Exception, e:
                print "Exception:", e

            target = board.target
            transport = board.transport
            flash = board.flash

            # Set specified SWD clock.
            if args.clock > 0:
                print "Setting SWD clock to %d kHz" % args.clock
                transport.setClock(args.clock * 1000)

            # Handle reset action first
            if args.action == ACTION_RESET:
                print "Resetting target"
                target.reset()
                sys.exit(0)

            # Handle a device with flash security enabled.
            didErase = False
            if target.isLocked() and args.action != ACTION_UNLOCK:
                print "Target is locked, cannot complete operation. Use --unlock to mass erase and unlock."

            # Handle actions.
            if args.action == ACTION_INFO:
                print "Unique ID: %s" % board.getUniqueID()
                print "Core ID:   0x%08x" % target.readIDCode()
                if isinstance(target, pyOCD.target.target_kinetis.Kinetis):
                    print "MDM-AP Control: 0x%08x" % transport.readAP(target_kinetis.MDM_CTRL)
                    print "MDM-AP Status:  0x%08x" % transport.readAP(target_kinetis.MDM_STATUS)
                status = target.getState()
                if status == pyOCD.target.cortex_m.TARGET_HALTED:
                    print "Core status:    Halted"
                    self.dumpRegisters(target)
                elif status == pyOCD.target.cortex_m.TARGET_RUNNING:
                    print "Core status:    Running"
            elif args.action == ACTION_READ:
                if args.width == 8:
                    data = target.readBlockMemoryUnaligned8(args.read, args.len)
                elif args.width == 16:
                    if args.read & 0x1:
                        raise ToolError("read address 0x%08x is not 16-bit aligned" % args.read)

                    byteData = target.readBlockMemoryUnaligned8(args.read, args.len * 2)
                    i = 0
                    data = []
                    while i < len(byteData):
                        data.append(byteData[i] | (byteData[i + 1] << 8))
                        i += 2
                elif args.width == 32:
                    if args.read & 0x3:
                        raise ToolError("read address 0x%08x is not 32-bit aligned" % args.read)

                    data = target.readBlockMemoryAligned32(args.read, args.len / 4)

                # Either print disasm or hex dump of output
                if args.disasm:
                    if args.width == 8:
                        code = bytearray(data)
                    elif args.width == 16:
                        code = bytearray(byteData)
                    elif args.width == 32:
                        byteData = []
                        for v in data:
                            byteData.extend([(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff])
                        code = bytearray(byteData)

                    self.disasm(str(code), args.read)
                else:
                    dumpHexData(data, args.read, width=args.width)
            elif args.action == ACTION_WRITE:
                if args.width == 8:
                    target.writeBlockMemoryUnaligned8(args.write, args.data)
                elif args.width == 16:
                    if args.write & 0x1:
                        raise ToolError("write address 0x%08x is not 16-bit aligned" % args.write)

                    print "16-bit writes are currently not supported"
                elif args.width == 32:
                    if args.write & 0x3:
                        raise ToolError("write address 0x%08x is not 32-bit aligned" % args.write)

                    target.writeBlockMemoryAligned32(args.write, args.data)
            elif args.action == ACTION_PROGRAM:
                if not os.path.exists(args.file):
                    raise ToolError("%s does not exist!" % args.file)

                print "Programming %s into flash..." % args.file
                flash.flashBinary(args.file)
            elif args.action == ACTION_ERASE:
                # TODO: change to be a complete chip erase that doesn't write FSEC to 0xfe.
                if not didErase:
                    target.massErase()
            elif args.action == ACTION_UNLOCK:
                # Currently the same as erase.
                if not didErase:
                    target.massErase()
            elif args.action == ACTION_GO:
                target.resume()
Exemple #48
0
from time import sleep
from random import randrange
import math

parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parentdir)

import pyOCD
from pyOCD.board import MbedBoard
import logging

logging.basicConfig(level=logging.INFO)

print "\r\n\r\n------ Test attaching to locked board ------"
for i in range(0, 10):
    with MbedBoard.chooseBoard() as board:
        # Erase and then reset - This locks Kinetis devices
        board.flash.init()
        board.flash.eraseAll()
        board.target.reset()

print "\r\n\r\n------ Testing Attaching to board ------"
for i in range(0, 100):
    with MbedBoard.chooseBoard() as board:
        board.target.halt()
        sleep(0.01)
        board.target.resume()
        sleep(0.01)

print "\r\n\r\n------ Flashing new code ------"
with MbedBoard.chooseBoard() as board:
    if args.verbose == 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose == 1:
        logging.basicConfig(level=logging.INFO)

    adapter = None
    try:
        interfaces = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
        if interfaces == None:
            print "Not find a mbed interface"
            sys.exit(1)

        # Use the first one
        first_interface = interfaces[0]
        adapter = MbedBoard(first_interface, "9009", "20151026")
        adapter.init()
        target = adapter.target
        target.halt()

        if args.erase:
            print 'erase all flash'
            eraseAll(target)

        if args.ihex:
            print 'flash hex file - %s to nrf51822' % args.ihex
            flashHex(target, args.ihex)

        offset = 0x14000
        if args.offset:
            offset = int(args.offset, 0)
from pyOCD.board import MbedBoard

#specific board used for OCD by setting board_id = '<board id of OCD reported by mbedls command>'. If you set to None, then it will search for one and ask for confirmation.
board_id = '10500000e062eef000000000000000000000000097969902'
#board_id = None

RECOVERY_FILE = "rom.bin"  # binary to write onto device

# to flash bootloader/interface firmware, set target_override='k20d50m'.  To flash application firmware to target, set target_override='<target board type>'.
with MbedBoard.chooseBoard(target_override='k20d50m',
                           board_id=board_id,
                           frequency=10000000) as board:
    print("Flashing " + RECOVERY_FILE + " to target")
    board.flash.flashBinary(RECOVERY_FILE)
    print("Recovery successful")
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

import logging

from pyOCD.gdbserver import GDBServer
from pyOCD.board import MbedBoard

logging.basicConfig(level=logging.INFO)

try:
    board_selected = MbedBoard.chooseBoard()
    if board_selected != None:
        gdb = GDBServer(board_selected, 3333)
        while gdb.isAlive():
            gdb.join(timeout = 0.5)

except KeyboardInterrupt:
    gdb.stop()
except Exception as e:
    print "uncaught exception: %s" % e
    gdb.stop()
Exemple #52
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)
Exemple #53
0
    sys.stderr = logger

    test_list = []
    board_list = []
    result_list = []

    # Put together list of tests
    test = Test("Basic Test", lambda board: basic_test(board, None))
    test_list.append(test)
    test_list.append(SpeedTest())
    test_list.append(CortexTest())
    test_list.append(FlashTest())
    test_list.append(GdbTest())

    # Put together list of boards to test
    board_list = MbedBoard.getAllConnectedBoards(close=True, blocking=False)

    start = time()
    for board in board_list:
        print("--------------------------")
        print("TESTING BOARD %s" % board.getUniqueID())
        print("--------------------------")
        for test in test_list:
            test_start = time()
            result = test.run(board)
            test_stop = time()
            result.time = test_stop - test_start
            result_list.append(result)
    stop = time()

    for test in test_list:
Exemple #54
0
def test_gdb(board_id=None, n=0):
    temp_test_elf_name = None
    result = GdbTestResult()
    with MbedBoard.chooseBoard(board_id=board_id) as board:
        memory_map = board.target.getMemoryMap()
        ram_regions = [region for region in memory_map if region.type == 'ram']
        ram_region = ram_regions[0]
        rom_region = memory_map.getBootMemory()
        target_type = board.getTargetType()
        binary_file = os.path.join(parentdir, 'binaries',
                                   board.getTestBinary())
        if board_id is None:
            board_id = board.getUniqueID()
        test_clock = 10000000
        test_port = 3333 + n
        telnet_port = 4444 + n
        error_on_invalid_access = True
        # Hardware breakpoints are not supported above 0x20000000 on
        # CortexM devices
        ignore_hw_bkpt_result = 1 if ram_region.start >= 0x20000000 else 0
        if target_type in ("nrf51", "nrf52", "nrf52840"):
            # Override clock since 10MHz is too fast
            test_clock = 1000000
            # Reading invalid ram returns 0 or nrf51
            error_on_invalid_access = False
        if target_type == "ncs36510":
            # Override clock since 10MHz is too fast
            test_clock = 1000000

        # Program with initial test image
        board.flash.flashBinary(binary_file, rom_region.start)
        board.uninit(False)

    # Generate an elf from the binary test file.
    temp_test_elf_name = tempfile.mktemp('.elf')
    objcopyOutput = check_output([
        OBJCOPY, "-v", "-I", "binary", "-O", "elf32-littlearm", "-B", "arm",
        "-S", "--set-start",
        "0x%x" % rom_region.start, binary_file, temp_test_elf_name
    ],
                                 stderr=STDOUT)
    print(to_str_safe(objcopyOutput))
    # Need to escape backslashes on Windows.
    if sys.platform.startswith('win'):
        temp_test_elf_name = temp_test_elf_name.replace('\\', '\\\\')

    # Write out the test configuration
    test_params = {
        "test_port": test_port,
        "rom_start": rom_region.start,
        "rom_length": rom_region.length,
        "ram_start": ram_region.start,
        "ram_length": ram_region.length,
        "invalid_start": 0x3E000000,
        "invalid_length": 0x1000,
        "expect_error_on_invalid_access": error_on_invalid_access,
        "ignore_hw_bkpt_result": ignore_hw_bkpt_result,
        "test_elf": temp_test_elf_name,
    }
    test_param_filename = "test_params%d.txt" % n
    with open(test_param_filename, "w") as f:
        f.write(json.dumps(test_params))

    # Run the test
    gdb = [PYTHON_GDB, "-ex", "set $testn=%d" % n, "--command=gdb_script.py"]
    output_filename = "output_%s_%d.txt" % (board.target_type, n)
    with open(output_filename, "w") as f:
        program = Popen(gdb, stdin=PIPE, stdout=f, stderr=STDOUT)
        args = [
            '-p=%i' % test_port,
            "-f=%i" % test_clock,
            "-b=%s" % board_id,
            "-T=%i" % telnet_port
        ]
        server = GDBServerTool()
        server.run(args)
        program.wait()

    # Read back the result
    test_result_filename = "test_results%d.txt" % n
    with open(test_result_filename, "r") as f:
        test_result = json.loads(f.read())

    # Print results
    if set(TEST_RESULT_KEYS).issubset(test_result):
        print("----------------Test Results----------------")
        print("HW breakpoint count: %s" % test_result["breakpoint_count"])
        print("Watchpoint count: %s" % test_result["watchpoint_count"])
        print("Average instruction step time: %s" %
              test_result["step_time_si"])
        print("Average single step time: %s" % test_result["step_time_s"])
        print("Average over step time: %s" % test_result["step_time_n"])
        print("Failure count: %i" % test_result["fail_count"])
        result.passed = test_result["fail_count"] == 0
    else:
        result.passed = False

    # Cleanup
    if temp_test_elf_name and os.path.exists(temp_test_elf_name):
        os.remove(temp_test_elf_name)
    os.remove(test_result_filename)
    os.remove(test_param_filename)

    return result
Exemple #55
0
    
    if args.verbose == 2:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose == 1:
        logging.basicConfig(level=logging.INFO)
    
    adapter = None
    try:
        interfaces = INTERFACE[usb_backend].getAllConnectedInterface(VID, PID)
        if interfaces == None:
            print "Not find a mbed interface"
            sys.exit(1)
            
        # Use the first one
        first_interface = interfaces[0]
        adapter = MbedBoard("target_lpc1768", "flash_lpc1768", first_interface)
        adapter.init()
        target = adapter.target
        target.halt()

        if args.ihex:
            print 'flash hex file - %s to nrf51822' % args.ihex
            flashHex(target, args.ihex)
        
        offset = 0x14000
        if args.offset:
            offset = args.offset
            
        if args.bin:
            print 'flash binary file - %s to nrf51822' % args.bin
            flashBin(target, args.bin, offset)
Exemple #56
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
Exemple #57
0
def flash_test(board_id):
    with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board:
        target_type = board.getTargetType()

        test_clock = 10000000
        if target_type == "kl25z":
            ram_start = 0x1ffff000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        elif target_type == "kl28z":
            ram_start = 0x1fffa000
            ram_size = 96 * 1024
            rom_start = 0x00000000
            rom_size = 512 * 1024
        elif target_type == "kl46z":
            ram_start = 0x1fffe000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "k22f":
            ram_start = 0x1fff0000
            ram_size = 0x20000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "k64f":
            ram_start = 0x1FFF0000
            ram_size = 0x40000
            rom_start = 0x00000000
            rom_size = 0x100000
        elif target_type == "lpc11u24":
            ram_start = 0x10000000
            ram_size = 0x2000
            rom_start = 0x00000000
            rom_size = 0x8000
        elif target_type == "lpc1768":
            ram_start = 0x10000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x80000
        elif target_type == "lpc4330":
            ram_start = 0x10000000
            ram_size = 0x20000
            rom_start = 0x14000000
            rom_size = 0x100000
        elif target_type == "lpc800":
            ram_start = 0x10000000
            ram_size = 0x1000
            rom_start = 0x00000000
            rom_size = 0x4000
        elif target_type == "nrf51":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x40000
            # Override clock since 10MHz is too fast
            test_clock = 1000000
        elif target_type == "maxwsnenv":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "max32600mbed":
            ram_start = 0x20000000
            ram_size = 0x8000
            rom_start = 0x00000000
            rom_size = 0x40000
        elif target_type == "w7500":
            ram_start = 0x20000000
            ram_size = 0x4000
            rom_start = 0x00000000
            rom_size = 0x20000
        else:
            raise Exception("The board is not supported by this test script.")

        target = board.target
        transport = board.transport
        flash = board.flash
        interface = board.interface

        transport.setClock(test_clock)
        transport.setDeferredTransfer(True)

        test_pass_count = 0
        test_count = 0
        result = FlashTestResult()

        def print_progress(progress):
            assert progress >= 0.0
            assert progress <= 1.0
            assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress)

            # Reset state on 0.0
            if progress == 0.0:
                print_progress.prev_progress = 0
                print_progress.backwards_progress = False
                print_progress.done = False

            # Check for backwards progress
            if progress < print_progress.prev_progress:
                print_progress.backwards_progress = True
            print_progress.prev_progress = progress

            # print progress bar
            if not print_progress.done:
                sys.stdout.write('\r')
                i = int(progress * 20.0)
                sys.stdout.write("[%-20s] %3d%%" % ('=' * i, round(progress * 100)))
                sys.stdout.flush()

            # Finish on 1.0
            if progress >= 1.0:
                if not print_progress.done:
                    print_progress.done = True
                    sys.stdout.write("\n")
                    if print_progress.backwards_progress:
                        print("Progress went backwards during flash")
        print_progress.prev_progress = 0

        binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary())
        with open(binary_file, "rb") as f:
            data = f.read()
        data = struct.unpack("%iB" % len(data), data)
        unused = rom_size - len(data)

        addr = rom_start
        size = len(data)

        # Turn on extra checks for the next 4 tests
        flash.setFlashAlgoDebug(True)

        print "\r\n\r\n------ Test Basic Page Erase ------"
        info = flash.flashBlock(addr, data, False, False, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Basic Chip Erase ------"
        info = flash.flashBlock(addr, data, False, True, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Smart Page Erase ------"
        info = flash.flashBlock(addr, data, True, False, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Smart Chip Erase ------"
        info = flash.flashBlock(addr, data, True, True, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, size)
        if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        flash.setFlashAlgoDebug(False)

        print "\r\n\r\n------ Test Basic Page Erase (Entire chip) ------"
        new_data = list(data)
        new_data.extend(unused * [0x77])
        info = flash.flashBlock(0, new_data, False, False, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.page_erase_rate = float(len(new_data)) / float(info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Fast Verify ------"
        info = flash.flashBlock(0, new_data, progress_cb=print_progress, fast_verify=True)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Offset Write ------"
        addr = rom_start + rom_size / 2
        page_size = flash.getPageInfo(addr).size
        new_data = [0x55] * page_size * 2
        info = flash.flashBlock(addr, new_data, progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data))
        if same(data_flashed, new_data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Multiple Block Writes ------"
        addr = rom_start + rom_size / 2
        page_size = flash.getPageInfo(addr).size
        more_data = [0x33] * page_size * 2
        addr = (rom_start + rom_size / 2) + 1 #cover multiple pages
        fb = flash.getFlashBuilder()
        fb.addData(rom_start, data)
        fb.addData(addr, more_data)
        fb.program(progress_cb=print_progress)
        data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data))
        data_flashed_more = target.readBlockMemoryUnaligned8(addr, len(more_data))
        if same(data_flashed, data) and same(data_flashed_more, more_data):
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Overlapping Blocks ------"
        test_pass = False
        addr = (rom_start + rom_size / 2) #cover multiple pages
        page_size = flash.getPageInfo(addr).size
        new_data = [0x33] * page_size
        fb = flash.getFlashBuilder()
        fb.addData(addr, new_data)
        try:
            fb.addData(addr + 1, new_data)
        except ValueError as e:
            print("Exception: %s" % e)
            test_pass = True
        if test_pass:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Empty Block Write ------"
        # Freebee if nothing asserts
        fb = flash.getFlashBuilder()
        fb.program()
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        print "\r\n\r\n------ Test Missing Progress Callback ------"
        # Freebee if nothing asserts
        addr = rom_start
        flash.flashBlock(rom_start, data, True)
        print("TEST PASSED")
        test_pass_count += 1
        test_count += 1

        # Only run test if the reset handler can be programmed (rom start at address 0)
        if rom_start == 0:
            print "\r\n\r\n------ Test Non-Thumb reset handler ------"
            non_thumb_data = list(data)
            # Clear bit 0 of 2nd word - reset handler
            non_thumb_data[4] = non_thumb_data[4] & ~1
            flash.flashBlock(rom_start, non_thumb_data)
            flash.flashBlock(rom_start, data)
            print("TEST PASSED")
            test_pass_count += 1
            test_count += 1

        # Note - The decision based tests below are order dependent since they
        # depend on the previous state of the flash

        print "\r\n\r\n------ Test Chip Erase Decision ------"
        new_data = list(data)
        new_data.extend([0xff] * unused) # Pad with 0xFF
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.chip_erase_rate_erased = float(len(new_data)) / float(info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Chip Erase Decision 2 ------"
        new_data = list(data)
        new_data.extend([0x00] * unused) # Pad with 0x00
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_CHIP_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.chip_erase_rate = float(len(new_data)) / float(info.program_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Page Erase Decision ------"
        new_data = list(data)
        new_data.extend([0x00] * unused) # Pad with 0x00
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
            result.page_erase_rate_same = float(len(new_data)) / float(info.program_time)
            result.analyze = info.analyze_type
            result.analyze_time = info.analyze_time
            result.analyze_rate = float(len(new_data)) / float(info.analyze_time)
        else:
            print("TEST FAILED")
        test_count += 1

        print "\r\n\r\n------ Test Page Erase Decision 2 ------"
        new_data = list(data)
        size_same = unused * 5 / 6
        size_differ = unused - size_same
        new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF
        new_data.extend([0x55] * size_differ)
        info = flash.flashBlock(0, new_data, progress_cb=print_progress)
        if info.program_type == FlashBuilder.FLASH_PAGE_ERASE:
            print("TEST PASSED")
            test_pass_count += 1
        else:
            print("TEST FAILED")
        test_count += 1

        print("\r\n\r\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
Exemple #58
0
 def handle_list(self, args):
     MbedBoard.listConnectedBoards()
Exemple #59
0
 def read_target_memory(self, addr, size, resume=True):
     assert self.get_mode() == self.MODE_IF
     with MbedBoard.chooseBoard(board_id=self.get_unique_id()) as board:
         data = board.target.readBlockMemoryUnaligned8(addr, size)
         board.uninit(resume)
     return bytearray(data)
Exemple #60
0
 def ids(self, args):
     MbedBoard.listConnectedBoards()