### Initialize and Start UnityTestRunner
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Example of initializing and starting the UnityTestRunner. This involves setting up the test suite, options, and project configuration before execution.
```python
from platformio.test.runners.unity import UnityTestRunner
from platformio.test.result import TestSuite
from platformio.test.runners.base import TestRunnerOptions
from platformio.project.config import ProjectConfig
suite = TestSuite(env_name="esp32", test_name="*")
options = TestRunnerOptions(verbose=1)
runner = UnityTestRunner(suite, ProjectConfig(), options)
runner.start(ctx)
```
--------------------------------
### Example: Initialize and Run a Test Suite
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Demonstrates how to create TestRunnerOptions, a TestSuite, and a specific runner (UnityTestRunner), then execute the test suite using the runner's start method.
```python
from platformio.test.runners.base import TestRunnerBase, TestRunnerOptions
from platformio.test.result import TestSuite
from platformio.project.config import ProjectConfig
# Create runner options
options = TestRunnerOptions(
verbose=1,
without_building=False,
without_uploading=False,
without_testing=False,
test_port="/dev/ttyUSB0"
)
# Create and run test suite
suite = TestSuite(env_name="esp32", test_name="tests/test_*.cpp")
config = ProjectConfig()
runner = UnityTestRunner(suite, config, options)
# Execute tests
runner.start(cmd_ctx)
```
--------------------------------
### Full Project Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
A comprehensive example showing how to load project configuration, retrieve specific values, parse multi-value options, and iterate through environments.
```python
from platformio.project.config import ProjectConfig
# Load configuration from default location
config = ProjectConfig()
# Get framework for esp32 environment
framework = config.get("env:esp32", "framework")
# Get multi-value option and parse it
lib_deps = config.get("env:esp32", "lib_deps")
lib_list = ProjectConfig.parse_multi_values(lib_deps)
# Iterate through all environments
for env in config.envs():
platform = config.get(f"env:{env}", "platform")
board = config.get(f"env:{env}", "board")
print(f"{env}: {board} ({platform})")
# Get all environments for default build
for env in config.default_envs():
print(f"Will build: {env}")
```
--------------------------------
### Start Test Suite Execution
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Initiates the full test pipeline including setup, building, uploading, and testing phases. Requires a Click command context for output handling.
```python
runner.start(cmd_ctx)
```
--------------------------------
### PlatformIO Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
A complete example of a platformio.ini file, demonstrating project-level settings and environment-specific configurations for development and production.
```ini
[platformio]
name = iot_firmware
description = IoT device firmware
default_envs = production
extra_configs = ci.ini
workspace_dir = ${PROJECT_DIR}/.build
build_dir = ${workspace_dir}/output
src_dir = ${PROJECT_DIR}/firmware
[env:development]
platform = espressif32
board = esp32-devkitc-1
framework = arduino
build_type = debug
build_flags = -g -O0 -DDEBUG=1
build_src_filter = +<*> -<.git/>
upload_port = /dev/ttyUSB0
upload_speed = 921600
monitor_port = /dev/ttyUSB0
monitor_speed = 115200
monitor_filters = esp32_exception_decoder, time
lib_deps =
ArduinoJson@6.19.4
WiFi
SPIFFS
test_framework = unity
[env:production]
extends = development
build_type = release
build_flags = -O3 -DPRODUCTION=1
upload_port = COM3
upload_protocol = espota
upload_flags = --port=3232 --auth=password
monitor_filters = esp32_exception_decoder
```
--------------------------------
### Get Platform Installation Directory
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Retrieves the installation path of the platform. This is useful for locating platform-specific files.
```python
platform_dir = platform.get_dir()
# Returns: "~/.platformio/platforms/espressif32"
```
--------------------------------
### Directory Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Customizes PlatformIO's core, build, source, and library directories.
```ini
[platformio]
core_dir = /opt/platformio
build_dir = ${PROJECT_DIR}/.build
src_dir = ${PROJECT_DIR}/source
lib_dir = ${PROJECT_DIR}/libraries
```
--------------------------------
### Load Project Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/INDEX.md
This example shows how to load the project's configuration file. It utilizes the `ProjectConfig` class from `platformio.project.config`.
```python
from platformio.project.config import ProjectConfig
config = ProjectConfig()
```
--------------------------------
### Global Configuration Options Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Illustrates setting global project metadata and specifying default environments and extra configuration files.
```ini
[platformio]
name = firmware_v2
description = Firmware for IoT device
default_envs = esp32, esp32-s3
extra_configs = extra.ini, boards/*.ini
```
--------------------------------
### Install tox
Source: https://github.com/platformio/platformio-core/blob/develop/CONTRIBUTING.md
Install the tox testing tool, which is required for setting up development environments and running tests.
```bash
pip install tox
```
--------------------------------
### Instantiate TestCaseSource
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/types.md
Example of creating a TestCaseSource object with a filename and line number.
```python
source = TestCaseSource("tests/test_main.cpp", line=42)
```
--------------------------------
### Debugging Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Configures the debugging tool, port, and speed. Use 'debug_tool', 'debug_port', and 'debug_speed' to set up the debugger.
```ini
[env:debugging]
debug_tool = openocd
debug_speed = 1000
debug_server_executable = openocd
```
--------------------------------
### Example: Configure Test Runner Options
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Shows how to instantiate TestRunnerOptions with specific settings, such as increased verbosity, specifying a test port, and skipping the build stage.
```python
from platformio.test.runners.base import TestRunnerOptions
options = TestRunnerOptions(
verbose=2,
test_port="/dev/ttyUSB0",
without_building=True # Skip rebuild if already compiled
)
```
--------------------------------
### Example: Setting Up Device Monitor Filters
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/device-monitor.md
Demonstrates how to set up and load both built-in and custom device monitor filters for a specific platform and project environment. Ensure necessary imports are present.
```python
from platformio.device.monitor.filters.base import register_filters, load_monitor_filters
from platformio.platform.factory import PlatformFactory
# Setup all filters
platform = PlatformFactory.from_env("esp32")
options = {"project_dir": "/my/project", "environment": "esp32"}
# Register platform and built-in filters
register_filters(platform, options)
# Also load custom filters from project
load_monitor_filters("/my/project/monitor", prefix="filter_", options=options)
```
--------------------------------
### Configuration Variable Expansion Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Demonstrates how configuration values can reference other variables using the ${section.option} syntax, including built-in variables like ${PROJECT_DIR}.
```ini
[platformio]
name = my_project
version = 1.0
build_dir = ${PROJECT_DIR}/.pio/build
[env:esp32]
platform = espressif32
build_flags = -DAPP_VERSION="${platformio.version}"
```
--------------------------------
### Board Build Customization Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Overrides default board settings for MCU, CPU frequency, flash frequency, and flash mode.
```ini
[env:esp32-oc]
board = esp32
board_build.f_cpu = 240000000L
board_build.f_flash = 80000000L
board_build.flash_mode = dio
```
--------------------------------
### Upload Configuration Examples
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Shows how to configure upload ports, protocols, and specific flags for different environments. Use 'upload_port', 'upload_protocol', and 'upload_flags' to manage the upload process.
```ini
[env:esp32-ota]
upload_port = 192.168.1.100
upload_protocol = espota
upload_flags =
--port=3232
--auth=MyPassword
[env:st-link]
upload_protocol = jlink
upload_speed = 4000
upload_resetmethod = stlink
```
--------------------------------
### Test Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Sets up parameters for running tests, including the communication port, speed, and the test framework to be used. Use 'test_port' and 'test_framework' to configure the testing environment.
```ini
[env:test]
test_port = /dev/ttyUSB0
test_speed = 921600
test_framework = unity
```
--------------------------------
### Get Platform and Check Framework Compatibility
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Retrieve a platform object for a given environment and check if a specific framework is supported.
```python
platform = PlatformFactory.from_env("esp32")
# Check compatibility
if "arduino" in platform.frameworks:
print("Arduino framework is supported")
```
--------------------------------
### Environment Inheritance Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Illustrates how environments can inherit settings from a base environment using the 'extends' option. This allows for code reuse and organized configuration.
```ini
[env:base]
platform = espressif32
framework = arduino
build_flags = -Wall -Werror
[env:esp32-dev]
extends = base
board = esp32-devkitc-1
build_flags = ${env:base.build_flags} -g
[env:esp32-prod]
extends = base
board = esp32
build_type = release
build_flags = ${env:base.build_flags} -O3
```
--------------------------------
### Get All Section Names
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves a list of all section names present in the configuration file.
```python
sections = config.sections()
# Returns: ['platformio', 'env:esp32', 'env:arduino']
```
--------------------------------
### Get All Environment Names
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves a list of all defined environment names within the project configuration.
```python
environments = config.envs()
# Returns: ['esp32', 'arduino']
```
--------------------------------
### Get ProjectConfig Instance
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Obtains the singleton instance of ProjectConfig. If no instance exists, it creates one.
```python
config = ProjectConfig.get_instance()
```
--------------------------------
### PlatformIO CLI Entry Points
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Illustrates the main entry points for the PlatformIO command-line interface. Shows the hierarchical structure starting from the main package.
```text
platformio # Main package
├── __init__.py # Package metadata
├── __main__.py # CLI entry points: main(), debug_gdb_main(), cli()
├── cli.py # PlatformioCLI command group
├── exception.py # Core exception classes
├── util.py # Utilities: get_systype(), decorators
├── fs.py # Filesystem: to_unix_path()
├── app.py # Application state
├── cache.py # Caching utilities
└── ...
```
--------------------------------
### Get Board Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Retrieve configuration details for a specific development board using its ID.
```python
board_config = platform.get_board_config("esp32-s3-devkitc-1")
print(f"Memory: {board_config.get('upload.size')}")
```
--------------------------------
### Build Configuration Examples
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Demonstrates different build types and flags for release, debug, and selective builds. Use 'build_type' to specify the configuration and 'build_flags' or 'build_src_filter' to customize compiler options and source file inclusion.
```ini
[env:release]
build_type = release
build_flags =
-O3
-DPRODUCTION=1
-Wno-deprecated-declarations
[env:debug]
build_type = debug
build_flags =
-g
-O0
-DDEBUG=1
build_unflags = -O2
[env:selective]
build_src_filter = + + -
```
--------------------------------
### Monitor Configuration Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Configures serial monitor settings including port, speed, and control lines. Use 'monitor_port', 'monitor_speed', 'monitor_rts', and 'monitor_dtr' to set up the serial monitor.
```ini
[env:monitoring]
monitor_port = /dev/ttyUSB0
monitor_speed = 115200
monitor_rts = 0
monitor_dtr = 1
monitor_filters = esp32_exception_decoder, time
```
--------------------------------
### Example Usage of TestCaseSource
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Shows how to create a TestCaseSource object and access its filename and line number properties. This is useful for reporting where tests are defined.
```python
from platformio.test.result import TestCaseSource
source = TestCaseSource("tests/test_main.cpp", line=42)
print(f"Test defined at {source.filename}:{source.line}")
```
--------------------------------
### Example Usage of TestCase
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Demonstrates creating TestCase instances for both passed and failed tests, including details like messages, stdout, and source information. Shows how to access test properties.
```python
from platformio.test.result import TestCase, TestStatus, TestCaseSource
# Create a passed test
test = TestCase(
name="test_initialization",
status=TestStatus.PASSED,
duration=0.125,
source=TestCaseSource("tests/test.cpp", 10)
)
# Create a failed test with details
test = TestCase(
name="test_calculation",
status=TestStatus.FAILED,
message="assert: 2 + 2 == 5 failed",
stdout="Calculation: 4\nExpected: 5",
source=TestCaseSource("tests/test.cpp", 25),
duration=0.003
)
print(f"{test.name}: {test.status.name} ({test.duration}s)")
```
--------------------------------
### Example Usage of TestStatus
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Demonstrates creating a TestStatus instance and parsing a status string. Shows how to access the status name and its corresponding ANSI color.
```python
from platformio.test.result import TestStatus
# Create and check status
status = TestStatus.PASSED
print(f"Test status: {status.name}") # "PASSED"
print(f"Color: {status.to_ansi_color()}") # "green"
# Parse from test framework output
test_result_str = "SUCCESS"
status = TestStatus.from_string(test_result_str)
```
--------------------------------
### Get Options for an Environment
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves all option names for a specific section or environment. Useful for inspecting available settings.
```python
# Get options for environment 'esp32'
options = config.options(env="esp32")
# Returns: ['platform', 'board', 'framework', ...]
```
--------------------------------
### Discover mDNS Services
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/device-management.md
Discovers mDNS (Bonjour/Zeroconf) services on the local network. Automatically installs the 'zeroconf' package if not available.
```python
from platformio.device.list.util import list_mdns_services
services = list_mdns_services()
for service in services:
print(f"Service: {service}")
```
--------------------------------
### PlatformIO Configuration Flow
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Illustrates the process of reading and accessing project configuration in PlatformIO. Starts with the `platformio.ini` file, parsed by `ProjectConfig.read()`, and accessed via `config.get()`.
```text
platformio.ini
↓ (parsed by)
ProjectConfig.read()
↓ (accessed via)
config.get("env:name", "option")
↓ (can include)
extra_configs, variable expansion, section inheritance
```
--------------------------------
### Get Default Environments
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves a list of environments that are set as defaults for building. These are typically specified in the 'default_envs' option.
```python
defaults = config.default_envs()
# Returns: ['esp32'] (from default_envs option)
```
--------------------------------
### Get Available Boards
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Retrieves a dictionary of all boards supported by the platform. The dictionary maps board IDs to their configuration details.
```python
boards = platform.get_boards()
for board_id, board_info in boards.items():
print(f"{board_id}: {board_info['name']}")
```
--------------------------------
### Get Default Project Config Path
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves the default path for the project configuration file. This is typically platformio.ini in the current directory.
```python
path = ProjectConfig.get_default_path()
# Returns: "/current/dir/platformio.ini" or custom path
```
--------------------------------
### Get Platform Information
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/INDEX.md
Retrieve information about a specific platform, such as 'esp32', using the `PlatformFactory`. This requires importing `PlatformFactory` from `platformio.platform.factory`.
```python
from platformio.platform.factory import PlatformFactory
platform = PlatformFactory.from_env("esp32")
```
--------------------------------
### PlatformFactory Static Method: from_env
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Factory method to load a platform for a given environment name. Supports automatic installation of the platform if it's not already present.
```python
from platformio.platform.factory import PlatformFactory
# Load platform for esp32 environment
platform = PlatformFactory.from_env("esp32")
# Load without auto-installation
platform = PlatformFactory.from_env("atmelavr", autoinstall=False)
```
--------------------------------
### Get Specific Board Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Fetches the configuration details for a particular board ID. This includes MCU, memory, and upload parameters.
```python
config = platform.get_board_config("esp32")
print(f"MCU: {config['mcu']}")
print(f"Memory: {config.get('upload_speed', 'default')}")
```
--------------------------------
### Start GDB Debugging Session
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
A convenience entry point to initiate a GDB-based debugging session. This function automatically configures the necessary options for GDB debugging.
```python
from platformio.__main__ import debug_gdb_main
# Start GDB debugging session
exit_code = debug_gdb_main()
```
--------------------------------
### Get Project Library Directories
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves a list of directories that are watched for library changes during development. Includes global, project, and environment-specific directories.
```python
from platformio.project.helpers import get_project_watch_lib_dirs
lib_dirs = get_project_watch_lib_dirs()
for dir in lib_dirs:
print(f"Watch directory: {dir}")
```
--------------------------------
### Logical Device Information Dictionary
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/types.md
This dictionary describes a mounted filesystem, including its mount path and volume label. It is returned by the `list_logical_devices` function and examples are provided for Windows, Linux, and macOS.
```python
{
"path": str, # Device mount path
"name": str | None # Volume label
}
```
```python
# Windows
{"path": "C:\\", "name": "System"}
```
```python
# Linux
{"path": "/media/user/usb_drive", "name": "usb_drive"}
```
```python
# macOS
{"path": "/Volumes/Data", "name": "Data"}
```
--------------------------------
### Get Object Members and Load Module
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/utilities.md
Combines loading a custom Python module with retrieving all its members using `get_object_members`. This example filters for callable members that are not private.
```python
from platformio.compat import get_object_members, load_python_module
# Load a custom module
filter_module = load_python_module(
"platformio.device.monitor.filters.custom",
"/project/monitor/filter_custom.py"
)
# Get all members
members = get_object_members(filter_module)
for name, obj in members:
if callable(obj) and not name.startswith("_"):
print(f"Function: {name}")
```
--------------------------------
### Custom Click Command Group with PlatformIO CLI
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
Example of creating a custom command group that inherits from PlatformioCLI, enabling dynamic command discovery and loading for your own CLI applications.
```python
from platformio.cli import PlatformioCLI
import click
# Custom command group inherits from PlatformioCLI
@click.command(cls=PlatformioCLI)
def my_cli():
pass
```
--------------------------------
### Get Project Configuration Options Schema
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves the schema definition for all available configuration options. This schema is an ordered dictionary mapping option keys to ConfigOption objects, which contain metadata about types, defaults, descriptions, and validation rules.
```python
from platformio.project.options import get_config_options_schema
schema = get_config_options_schema()
for key, option in schema.items():
print(f"{key}:")
print(f" Type: {option.type}")
print(f" Default: {option.default}")
print(f" Description: {option.description}")
```
--------------------------------
### MissedUdevRules Exception
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Indicates that required udev rules are not installed on a Linux system. Follow the provided steps to install them.
```python
class MissedUdevRules(InvalidUdevRules):
MESSAGE = (
"Warning! Please install `99-platformio-udev.rules`. \n"
"More details: "
"https://docs.platformio.org/en/latest/core/installation/udev-rules.html"
)
```
```bash
# Install udev rules
curl -fsSL https://raw.githubusercontent.com/platformio/platformio-core/develop/platformio/assets/system/99-platformio-udev.rules | sudo tee /etc/udev/rules.d/99-platformio-udev.rules
# Reload udev rules
sudo usermod -a -G dialout $USER
newgrp dialout
```
--------------------------------
### PlatformIO CLI Global Options and Usage
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
Demonstrates common ways to interact with the PlatformIO CLI using global options like version, help, and disabling ANSI colors. Also shows how to specify a caller ID for IDE integration.
```bash
# Version info
platformio --version
# Help for specific command
platformio run --help
# Disable colors
platformio --no-ansi run
# Caller tracking (for IDE integration)
platformio --caller=vscode run --environment esp32
```
--------------------------------
### OutdatedUdevRules Exception
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Signals that the installed udev rules on Linux are outdated. Update or reinstall them by following the instructions for `MissedUdevRules`.
```python
class OutdatedUdevRules(InvalidUdevRules):
MESSAGE = (
"Warning! Your `{0}` are outdated. Please update or reinstall them."
"\nMore details: "
"https://docs.platformio.org/en/latest/core/installation/udev-rules.html"
)
```
--------------------------------
### Load Platform from Project Environment
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Loads a platform instance based on a project environment name defined in platformio.ini. It can optionally auto-install the platform if it's missing.
```python
from platformio.platform.factory import PlatformFactory
# Load platform from project environment
platform = PlatformFactory.from_env("esp32")
print(f"Platform: {platform.title}")
print(f"Version: {platform.version}")
# Get available boards
boards = platform.get_boards()
for board_id in list(boards.keys())[:5]:
print(f" - {board_id}")
# Get specific board config
board = platform.get_board_config("esp32")
print(f"Board MCU: {board['mcu']}")
print(f"Upload Speed: {board.get('upload_speed')}")
```
--------------------------------
### Get Platform Configuration Schema
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Retrieves the schema for platform-specific configuration options. This can be used to understand or validate custom settings.
```python
schema = platform.config_options_schema()
```
--------------------------------
### Build Documentation
Source: https://github.com/platformio/platformio-core/blob/develop/CONTRIBUTING.md
Build the project documentation using tox. The generated HTML documentation will be located in the '_build' directory within the 'docs' folder.
```bash
tox -e docs
```
--------------------------------
### Run Tests
Source: https://github.com/platformio/platformio-core/blob/develop/CONTRIBUTING.md
Execute the test suite using the 'make test' command. This verifies the functionality of your changes and the overall project integrity.
```bash
make test
```
--------------------------------
### Variable Expansion in Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Demonstrates using built-in and custom variables for dynamic configuration values.
```ini
[platformio]
name = my_project
version = 1.0
build_dir = ${PROJECT_DIR}/.pio/build
[env:esp32]
build_flags = -DAPP_VERSION="${platformio.version}"
```
--------------------------------
### TimestampFilter Implementation
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/device-monitor.md
An example of a custom filter that adds a timestamp to each line of incoming data. It subclasses DeviceMonitorFilterBase and overrides the transform method.
```python
from platformio.device.monitor.filters.base import DeviceMonitorFilterBase
class TimestampFilter(DeviceMonitorFilterBase):
@property
def NAME(self):
return "timestamp"
def transform(self, text):
"""Transform incoming data"""
import time
timestamp = time.strftime("%H:%M:%S")
return f"[{timestamp}] {text}"
```
--------------------------------
### Custom Option Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Demonstrates how to define and use custom configuration options. Custom options must be prefixed with 'custom_' and can be accessed using the 'board_' prefix in the build environment.
```ini
[env:custom]
custom_my_option = some_value
custom_feature_flags = -DFEATURE_A=1 -DFEATURE_B=2
```
```ini
[env:use_custom]
custom_setting = debug_enabled
```
--------------------------------
### Get ANSI Color for TestStatus
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Retrieves the ANSI color code associated with a TestStatus member. This can be used for colored output in terminals.
```python
color = TestStatus.PASSED.to_ansi_color() # Returns "green"
color = TestStatus.FAILED.to_ansi_color() # Returns "red"
color = TestStatus.WARNED.to_ansi_color() # Returns "yellow"
```
--------------------------------
### Basic Project Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Defines global settings and two distinct environments for different development boards.
```ini
[platformio]
name = my_project
default_envs = esp32, arduino
[env:esp32]
platform = espressif32
board = esp32-devkitc-1
framework = arduino
build_flags = -DDEBUG=1
[env:arduino]
platform = atmelavr
board = uno
framework = arduino
```
--------------------------------
### Get Configuration Value
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Retrieves a specific configuration value from a given section and option. Supports fallback values if the option is not found.
```python
platform = config.get("env:esp32", "platform") # Returns: "espressif32"
build_flags = config.get("env:esp32", "build_flags") # May be multi-value
```
--------------------------------
### Run Development Environment with tox
Source: https://github.com/platformio/platformio-core/blob/develop/CONTRIBUTING.md
Navigate to the project root and run tox with a specific Python version environment (e.g., py39) to set up and enter the development environment.
```bash
tox -e py39
```
--------------------------------
### Manually Upgrade PlatformIO
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Installs or upgrades PlatformIO Core using pip. Use this when network issues prevent automatic updates or registry access.
```bash
# Update manually if network is unavailable
pip install --upgrade platformio
```
--------------------------------
### GetSerialPortsError Exception
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Thrown when PlatformIO cannot enumerate serial ports on the current platform. Ensure PySerial is installed and the platform supports serial port enumeration.
```python
class GetSerialPortsError(PlatformioException):
MESSAGE = "No implementation for your platform ('{0}') available"
```
```python
from platformio.device.list.util import list_serial_ports
from platformio.exception import GetSerialPortsError
try:
ports = list_serial_ports()
except GetSerialPortsError as e:
print(f"Cannot enumerate serial ports: {e}")
# Install PySerial or check platform support
```
--------------------------------
### List Available Commands
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
This snippet shows how to list all available commands in the PlatformIO CLI context.
```python
ctx = click.Context(my_cli)
commands = my_cli.list_commands(ctx)
print(f"Available commands: {commands}")
```
--------------------------------
### Main Entry Points
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Exposes CLI entry points for interacting with PlatformIO Core. Includes `main()`, `debug_gdb_main()`, and `cli()`, along with `PlatformioCLI` command group implementation.
```APIDOC
## Main Entry Points
### Description
Exposes CLI entry points for interacting with PlatformIO Core. Includes `main()`, `debug_gdb_main()`, and `cli()`, along with `PlatformioCLI` command group implementation.
### Entry Points
- `main()`: Primary CLI entry point.
- `debug_gdb_main()`: Entry point for GDB debugging.
- `cli()`: General CLI command entry point.
- `PlatformioCLI`: Command group implementation.
```
--------------------------------
### PlatformFactory.from_env
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/platform.md
Factory method for creating and managing platform instances. Loads a platform for a specific project environment.
```APIDOC
## Method: PlatformFactory.from_env
### Description
Factory for creating and managing platform instances. Loads a platform for a specific project environment.
### Signature
`from_env(env_name: str, autoinstall: bool = True) -> PlatformBase`
### Parameters
- `env_name` (str): Environment name from platformio.ini
- `autoinstall` (bool): Automatically install platform if not present (defaults to True)
### Returns
- `PlatformBase`: An instance of PlatformBase configured for the specified environment.
### Raises
- `UnknownPlatform`: If the specified platform is not found in the registry.
- `IncompatiblePlatform`: If the platform is incompatible with the current PlatformIO version.
### Example
```python
from platformio.platform.factory import PlatformFactory
# Load platform for esp32 environment
platform = PlatformFactory.from_env("esp32")
# Load without auto-installation
platform = PlatformFactory.from_env("atmelavr", autoinstall=False)
```
```
--------------------------------
### Load and Parse Project Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Loads the project configuration using `ProjectConfig` and iterates through environments to display the associated board and platform. This is useful for accessing project-specific settings.
```python
from platformio.project.config import ProjectConfig
config = ProjectConfig()
for env in config.envs():
platform = config.get(f"env:{env}", "platform")
board = config.get(f"env:{env}", "board")
print(f"{env}: {board} ({platform})")
```
--------------------------------
### Memoization Decorator Example
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/utilities.md
Demonstrates the use of the @memoized decorator to cache function results. The cache can be configured with an expiration time, and the cache can be manually reset.
```python
from platformio.util import memoized
@memoized(expire="5m")
def get_installed_boards():
# Expensive operation - cached for 5 minutes
return fetch_boards_from_registry()
```
--------------------------------
### PlatformIO Configuration Hierarchy: Global and Environment Settings
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Details the hierarchical structure of PlatformIO configuration settings, distinguishing between global `[platformio]` settings and environment-specific `[env:name]` settings.
```text
[platformio] # Global settings
├─ name # Project name
├─ directories # Paths to src/, lib/, etc.
└─ default_envs # Default build environments
[env:name] # Per-environment settings
├─ platform # Development platform
├─ board # Target board
├─ framework # Framework (Arduino, ESP-IDF, etc.)
├─ build_* # Build options
├─ upload_* # Upload options
└─ monitor_* # Monitor options
```
--------------------------------
### main
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
The main entry point for the PlatformIO Core CLI. It handles argument parsing, environment configuration, command execution, and exception handling, returning an integer exit code.
```APIDOC
## main
### Description
Main entry point for the PlatformIO Core CLI. It ensures a compatible Python runtime, configures the environment, parses and executes CLI commands, handles exceptions, and calls maintenance hooks.
### Method Signature
```python
def main(argv=None) -> int
```
### Parameters
#### Parameters
- **argv** (list) - Optional - Command-line arguments (sys.argv format). If None, uses actual sys.argv.
### Return Type
- **int**: Exit code (0 = success, non-zero = failure)
### Behavior
1. Ensures Python 3+ runtime.
2. Configures environment (disables urllib warnings, handles I/O issues).
3. Parses and executes CLI commands.
4. Handles exceptions and generates error messages.
5. Calls maintenance hooks for telemetry and cleanup.
### Exception Handling
- **SystemExit**: Extracts and returns the exit code.
- **PlatformioException**: Formats and displays user-friendly error message.
- **Other exceptions**: Shows full traceback and suggests troubleshooting steps.
### Environment Configuration
- Respects `PLATFORMIO_NO_ANSI` and `PLATFORMIO_DISABLE_COLOR` for disabling ANSI colors.
- Respects `PLATFORMIO_FORCE_ANSI` and `PLATFORMIO_FORCE_COLOR` for forcing colors.
- Handles Windows VSCode Terminal I/O issues.
### Example
```python
from platformio.__main__ import main
import sys
# Run platformio from Python code
exit_code = main(["platformio", "run", "--environment", "esp32"])
sys.exit(exit_code)
# Run from command line arguments
exit_code = main() # Uses sys.argv
```
```
--------------------------------
### Run Test Environment
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Executes the build process for a specific test environment. Use this to check for missing dependencies or compilation errors related to `UnitTestSuiteError`.
```bash
# Install test framework dependencies
platformio run --environment test-env
```
--------------------------------
### Get Test Communication Port
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Retrieves the serial port used for test communication. Priority is given to options, then project config, then platform defaults.
```python
port = runner.get_test_port()
# Returns: "/dev/ttyUSB0" or "COM3"
```
--------------------------------
### Get Test Communication Speed
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/test-framework.md
Retrieves the baud rate for test communication. The speed is determined by runner options, project configuration, or platform defaults.
```python
speed = runner.get_test_speed()
# Returns: 115200
```
--------------------------------
### List Available Boards
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Lists all available board IDs for a given platform. Use this command to find the correct board ID when encountering an `UnknownBoard` error.
```bash
# List available boards for platform
platformio boards espressif32
```
--------------------------------
### Python: InvalidSettingName Exception
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Raised when a configuration setting name does not exist. Use valid setting names like 'install_library' or 'check_version'.
```python
class InvalidSettingName(UserSideException):
MESSAGE = "Invalid setting with the name '{0}'"
```
```python
from platformio.exception import InvalidSettingName
try:
config.set("invalid_setting", "value")
except InvalidSettingName as e:
print(f"Error: {e}")
# Use valid setting names like 'install_library', 'check_version'
```
--------------------------------
### PlatformIO JSON Output
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
Utilize the --json-output flag to get machine-readable, JSON-formatted output from PlatformIO commands, suitable for external tool parsing.
```bash
platformio run --target=build --json-output
```
--------------------------------
### Environment Platform and Package Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Specifies the development platform and custom toolchain packages for an environment.
```ini
[env:esp32]
platform = espressif32
platform_packages =
toolchain-esp32 @ ^2.50.0
```
--------------------------------
### Downgrade PlatformIO Core
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Installs a specific older version of PlatformIO Core. Use this if a platform requires an older version of the core and causes an `IncompatiblePlatform` error.
```bash
# Or downgrade if platform is too new
pip install 'platformio<6.0'
```
--------------------------------
### Bash: CIBuildEnvsEmpty Resolution
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Provides bash commands to resolve the CIBuildEnvsEmpty exception by creating a platformio.ini file, specifying a build environment, or using a custom config file.
```bash
# Option 1: Create platformio.ini with environments
echo "[env:esp32]" >> platformio.ini
echo "platform = espressif32" >> platformio.ini
echo "board = esp32-devkitc-1" >> platformio.ini
# Option 2: Specify build environment explicitly
platformio run --environment esp32
# Option 3: Specify custom config file
platformio run --project-conf custom.ini
```
--------------------------------
### INI: InvalidProjectConfError Example Errors
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Illustrates common INI syntax errors in platformio.ini that trigger InvalidProjectConfError, such as missing values, malformed sections, or invalid interpolations.
```ini
# Missing value
[env:esp32]
platform = ; Error: empty value
# Malformed section
[env esp32] ; Error: missing colon
# Invalid interpolation
[env:test]
flag = ${undefined.option}
```
--------------------------------
### ProjectConfig Class
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
The ProjectConfig class manages the parsing and access of `platformio.ini` project configuration files. It allows loading configurations, retrieving options, and accessing environment-specific settings.
```APIDOC
## Class ProjectConfig
### Description
The main configuration manager for PlatformIO projects. Parses and manages `platformio.ini` project configuration files.
### Constructor
```python
ProjectConfig(path=None, parse_extra=True, expand_interpolations=True)
```
#### Constructor Parameters
- **path** (str, optional, default=None): Path to the `platformio.ini` file. If None, uses default project config path or PLATFORMIO_CONFIG environment variable.
- **parse_extra** (bool, optional, default=True): Whether to parse extra configuration files defined in `extra_configs` option.
- **expand_interpolations** (bool, optional, default=True): Whether to expand variable references (${variable}) in configuration values.
### Methods
#### read(path, parse_extra=True)
Load and parse a configuration file.
```python
config.read("platformio.ini", parse_extra=True)
```
#### options(section=None, env=None)
Get all option names for a section or environment.
```python
# Get options for environment 'esp32'
options = config.options(env="esp32")
# Returns: ['platform', 'board', 'framework', ...]
```
#### get(section, option, fallback=None)
Get a configuration value.
```python
platform = config.get("env:esp32", "platform") # Returns: "espressif32"
build_flags = config.get("env:esp32", "build_flags") # May be multi-value
```
#### sections()
Get all section names in configuration.
```python
sections = config.sections()
# Returns: ['platformio', 'env:esp32', 'env:arduino']
```
#### envs()
Get list of all environment names.
```python
environments = config.envs()
# Returns: ['esp32', 'arduino']
```
#### default_envs()
Get list of default environments to build.
```python
defaults = config.default_envs()
# Returns: ['esp32'] (from default_envs option)
```
#### get_default_path()
Get the default project configuration file path.
```python
path = ProjectConfig.get_default_path()
# Returns: "/current/dir/platformio.ini" or custom path
```
#### get_instance()
Get or create the singleton ProjectConfig instance.
```python
config = ProjectConfig.get_instance()
```
#### parse_multi_values(items)
Parse multi-line or comma-separated values from configuration.
```python
libs = ProjectConfig.parse_multi_values("lib1, lib2\nlib3")
# Returns: ['lib1', 'lib2', 'lib3']
```
### Configuration Variable References
Configuration supports variable expansion with the `${section.option}` syntax.
### Built-in Variables
- **${PROJECT_DIR}**: Absolute path to the project directory
- **${PROJECT_HASH}**: Hash of project name and path (10 chars)
- **${UNIX_TIME}**: Current Unix timestamp
```
--------------------------------
### Environment Board and Framework Configuration
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/configuration.md
Defines the target board and the primary framework to be used for an environment.
```ini
[env:esp32]
board = esp32-devkitc-1
framework = arduino
```
--------------------------------
### Get System Type
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/utilities.md
Retrieves the current system type identifier, which includes the operating system and architecture. Useful for conditional logic based on the execution environment.
```python
from platformio.util import get_systype
system = get_systype()
print(f"System type: {system}")
if system.startswith("linux"):
print("Running on Linux")
if "arm" in system:
print("Running on ARM Linux")
if "amd64" in system or "arm64" in system:
print("Running on 64-bit system")
```
--------------------------------
### Read Configuration File
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/project-configuration.md
Loads and parses a specified configuration file. Can optionally parse extra configuration files.
```python
config.read("platformio.ini", parse_extra=True)
```
--------------------------------
### Configure PlatformIO Environment
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/api-reference/main-entry-points.md
Call this function to set up the environment before using PlatformIO commands. It handles disabling warnings and patching terminal compatibility.
```python
from platformio.__main__ import configure
configure() # Setup environment
# Now safe to use PlatformIO
```
--------------------------------
### Define IncompatiblePlatform Exception
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Defines the exception raised when a platform is not compatible with the installed PlatformIO Core version. This is often due to version mismatches specified in the platform manifest.
```python
class IncompatiblePlatform(PlatformioException):
MESSAGE = "Platform incompatible with Core: {0}"
```
--------------------------------
### Specific Exception Handling for Serial Ports
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/errors.md
Shows how to catch a specific exception, `GetSerialPortsError`, when listing serial ports. It includes a helpful message suggesting the installation of the `PySerial` package.
```python
from platformio.device.list.util import list_serial_ports
from platformio.exception import GetSerialPortsError
try:
ports = list_serial_ports()
if not ports:
print("No serial ports found")
except GetSerialPortsError as e:
print(f"Cannot enumerate ports: {e}")
print("Make sure PySerial is installed: pip install pyserial")
```
--------------------------------
### Create Custom Monitor Filter
Source: https://github.com/platformio/platformio-core/blob/develop/_autodocs/README.md
Define a custom filter for the device monitor by subclassing `DeviceMonitorFilterBase`. This example adds a timestamp to each line of output. Requires importing the base class.
```python
from platformio.device.monitor.filters.base import DeviceMonitorFilterBase
class TimestampFilter(DeviceMonitorFilterBase):
@property
def NAME(self):
return "timestamp"
def transform(self, text):
import time
ts = time.strftime("%H:%M:%S")
return f"[{ts}] {text}"
```