or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-mbed-ls

Python library that detects and lists mbed-enabled devices connected to the host computer

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mbed-ls@1.8.x

To install, run

npx @tessl/cli install tessl/pypi-mbed-ls@1.8.0

index.mddocs/

mbed-ls

mbed-ls is a Python library that detects and lists mbed-enabled devices connected to the host computer. It provides both a command-line interface and Python API for discovering connected development boards, providing detailed information including platform names, mount points, serial ports, target IDs, and DAPLink versions. The library supports multiple output formats, platform mocking capabilities for testing, and retargeting functionality for development workflows.

Package Information

  • Package Name: mbed-ls
  • Language: Python
  • Installation: pip install mbed-ls
  • Supported Platforms: Windows 7+, Linux, macOS (Darwin)

Core Imports

import mbed_lstools
from mbed_lstools import create

For enum constants:

from mbed_lstools.lstools_base import FSInteraction

For platform database access:

from mbed_lstools.platform_database import PlatformDatabase, DEFAULT_PLATFORM_DB

Basic Usage

Python API

import mbed_lstools

# Create platform-specific detector instance
mbeds = mbed_lstools.create()

# List all connected devices
devices = mbeds.list_mbeds(unique_names=True, read_details_txt=True)

for device in devices:
    print(f"Platform: {device['platform_name']}")
    print(f"Mount point: {device['mount_point']}")
    print(f"Serial port: {device['serial_port']}")
    print(f"Target ID: {device['target_id']}")
    print(f"DAPLink version: {device.get('daplink_version', 'unknown')}")
    print("---")

Command Line Interface

# List devices in table format (default)
mbedls

# Simple format without borders/headers
mbedls --simple

# JSON output with detailed information
mbedls --json

# List all supported platforms
mbedls --list

# Mock a platform (temporary rename)
mbedls --mock 0240:MY_CUSTOM_PLATFORM

Capabilities

Device Detection Factory

Creates a platform-specific device detection instance that can list and manage connected mbed-enabled devices.

def create(skip_retarget=False, list_unmounted=False, force_mock=False):
    """
    Create platform-specific MbedLsTools instance.
    
    Args:
        skip_retarget (bool): Skip retargeting step if True (default: False)
        list_unmounted (bool): Include unmounted platforms if True (default: False)
        force_mock (bool): Force mock mode if True (default: False)
    
    Returns:
        MbedLsToolsBase: Platform-specific detector instance or None if unsupported
    """

Device Listing and Detection

Lists all detected mbed-enabled devices with configurable detail levels and filtering options.

def list_mbeds(fs_interaction=FSInteraction.BeforeFilter, filter_function=None, unique_names=False, read_details_txt=False):
    """
    List all detected mbed-enabled devices.
    
    Args:
        fs_interaction (FSInteraction): Controls filesystem access behavior during detection.
            - FSInteraction.BeforeFilter: Access filesystem before filtering (most accurate, default)
            - FSInteraction.AfterFilter: Access filesystem after filtering (faster but potentially less accurate)
            - FSInteraction.Never: Never access filesystem (fastest but least accurate)
        filter_function (callable): Optional function to filter results based on device properties.
            Should return True to include device in results. Example: lambda m: m['platform_name'] == 'K64F'
        unique_names (bool): Generate unique platform names (e.g., 'K64F[0]', 'K64F[1]') if True
        read_details_txt (bool): Read additional device details from DETAILS.TXT file if True
    
    Returns:
        list: List of device dictionaries with device information including platform_name,
            mount_point, serial_port, target_id, and additional properties when read_details_txt=True
    """

Platform Mocking

Temporarily substitute platform IDs with custom platform names for testing and development purposes.

def mock_manufacture_id(mid, platform_name, oper='+'):
    """
    Mock/substitute platform ID to platform name mapping.
    
    Args:
        mid (str): First 4 characters of target_id to mock
        platform_name (str): New platform name to assign
        oper (str): '+' to enable mock, '-' to disable mock (default: '+')
    """

Platform Database Access

Retrieves supported platforms and platform database information for different device types.

def get_supported_platforms(device_type='daplink'):
    """
    Get supported platforms from database.
    
    Args:
        device_type (str): Device type to query (default: 'daplink')
    
    Returns:
        dict: Dictionary mapping platform IDs to platform names
    """

def list_manufacture_ids():
    """
    List all known manufacture IDs and platform names.
    
    Returns:
        dict: Platform database information
    """

Command Line Interface

Main entry point for the command-line interface application.

def mbedls_main():
    """
    Main entry point for CLI application.
    Handles command-line argument parsing and execution.
    """

Utility Functions

Version information and OS support detection utilities.

def get_version():
    """
    Get mbed-ls Python module version string.
    
    Returns:
        str: Package version string
    """

def mbed_os_support():
    """
    Get supported operating system information.
    
    Returns:
        bool: True if OS is supported
    """

def mbed_lstools_os_info():
    """
    Get current operating system information.
    
    Returns:
        dict: OS information dictionary
    """

Types and Enums

FSInteraction Enum

Controls filesystem interaction behavior during device detection.

from enum import Enum

class FSInteraction(Enum):
    """Controls filesystem access behavior during device detection."""
    NEVER = "never"           # No filesystem access (fastest, least accurate)
    AfterFilter = "after"     # Filesystem access after filtering
    BeforeFilter = "before"   # Filesystem access before filtering (most accurate, default)

Device Data Structure

Device dictionaries returned by list_mbeds() contain these keys:

DeviceInfo = {
    'platform_name': str,           # Platform name (e.g., 'K64F')
    'platform_name_unique': str,    # Unique platform name (e.g., 'K64F[0]')
    'mount_point': str,            # Device mount point/drive
    'serial_port': str,            # Serial port identifier
    'target_id': str,              # Unique target identifier
    'target_id_mbed_htm': str,     # Target ID from MBED.HTM file
    'target_id_usb_id': str,       # Target ID from USB descriptor
    'daplink_version': str,        # DAPLink firmware version
    'vendor_id': str,              # USB Vendor ID
    'product_id': str,             # USB Product ID
    # Additional daplink_* properties when read_details_txt=True
    'daplink_auto_reset': str,     # Auto reset capability
    'daplink_automation_allowed': str, # Automation allowed flag
    'daplink_bootloader_version': str, # Bootloader version
    'daplink_git_sha': str,        # Git SHA of firmware
    'daplink_hic_id': str,         # Hardware interface circuit ID
    'daplink_interface_version': str, # Interface version
    'daplink_unique_id': str,      # Unique device identifier
    'daplink_usb_interfaces': str, # Available USB interfaces
}

Platform-Specific Classes

Base and platform-specific implementation classes.

class MbedLsToolsBase:
    """Base class for all platform implementations."""
    def list_mbeds(self, fs_interaction, filter_function, unique_names, read_details_txt): ...
    def mock_manufacture_id(self, mid, platform_name, oper): ...
    def get_supported_platforms(self, device_type): ...
    def list_manufacture_ids(self): ...

class MbedLsToolsWin7(MbedLsToolsBase):
    """Windows 7+ specific implementation."""

class MbedLsToolsLinuxGeneric(MbedLsToolsBase):
    """Linux generic implementation."""

class MbedLsToolsDarwin(MbedLsToolsBase):
    """macOS Darwin implementation."""

Platform Database Classes

Platform database management for device type mappings.

class PlatformDatabase:
    """Platform database management class for handling multiple database files.
    
    Represents a union of multiple platform database files with
    inter-process synchronization support.
    """
    def __init__(self, database_files, primary_database=None): ...
    def get(self, index, default=None, device_type='daplink', verbose_data=False): ...
    def add(self, id, platform_name, permanent=False, device_type='daplink'): ...
    def remove(self, id, permanent=False, device_type='daplink', verbose_data=False): ...
    def items(self, device_type='daplink'): ...
    def all_ids(self, device_type='daplink'): ...

# Constants
DEFAULT_PLATFORM_DB: dict  # Default platform database dictionary with device mappings
LOCAL_PLATFORM_DATABASE: str  # Local user-specific platform database file path
LOCAL_MOCKS_DATABASE: str     # Local user-specific mocks database file path

Exceptions

class CompatibleIDsNotFoundException(Exception):
    """Raised when compatible IDs cannot be found on Windows.
    
    This exception is specifically raised on Windows systems when the
    device detection process cannot locate compatible device IDs through
    the Windows registry or WMI queries.
    """

Retargeting Configuration

mbed-ls supports retargeting through a local mbedls.json configuration file:

{
    "<target_id>": {
        "<key>": "<value>"
    }
}

Example retargeting configuration:

{
    "0240000032044e4500257009997b00386781000097969900": {
        "serial_port": "COM99",
        "platform_name": "CUSTOM_K64F"
    }
}

This configuration file is automatically loaded from the current working directory and overrides returned device information for matching target IDs. Use skip_retarget=True or --skip-retarget flag to disable this behavior.

Error Handling

The library handles various error conditions:

  • Unsupported OS: create() returns None for unsupported operating systems
  • Permission Issues: Device detection may fail silently if filesystem access is restricted
  • Windows Driver Issues: Windows requires proper mbed serial port drivers
  • Mount Issues: Linux systems may need automounting configured for device detection

Always check return values and handle None results from create():

mbeds = mbed_lstools.create()
if mbeds is None:
    print("Platform not supported!")
    exit(1)