Runnable MicroPython Examples

SDK Example Programs (18 Complete Apps)

100% MicroPython-compatible scripts tested in CI. Run locally with pylotos-sim or deploy straight to /apps/ via App Studio or the LAN AI MCP Bridge.

m5stack_dial

Smart Thermostat (smart_thermostat.py)

Download .py

Adaptive 8-display climate dashboard with reactive State, Gauge, Sparkline, Slider & @app.every.

pylotos-sim examples/smart_thermostat.py --board m5stack_dial --port 8080
"""Smart Thermostat showcase dashboard built with `pylotos.ui`.

Runs identically on:
- M5Stack Cardputer ADV (240x135 + QWERTY)
- M5Stack Core2 / CoreS3 / CYD (320x240 + Touchscreen)
- M5Stack Dial (240x240 Round GC9A01 + Rotary Encoder + Touch)
- M5Stack AtomS3 (128x128 + 1-Button)
- Heltec V3 (128x64 1-bit OLED) & ESP32-C3 0.42" (72x40 micro OLED)
- Headless boards (NanoC6 / XIAO) via Desktop, Tablet, and Mobile Web UI (`:80`/`:443`)
"""

import pylotos.ui as ui

st = ui.State(
    temp=22.4,
    target=22.0,
    humidity=48,
    heat=True,
    mode="Auto",
    room="Living Room",
    hist=[21.2, 21.5, 21.9, 22.1, 22.4],
)


def _boost():
    st.target = 25.0
    st.heat = True
    app.toast("Boost -> 25C")


app = ui.App(
    "Thermostat",
    state=st,
    screens=[
        ui.Screen(
            "Overview",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Room", st.bind("temp"), unit="C", accent="cyan"),
                        ui.Gauge("Target", st.bind("target"), min=16, max=30, unit="C", accent="gold"),
                    ],
                ),
                ui.Sparkline("History", st.bind("hist"), unit="C", accent="cyan"),
                ui.StatusBadge(
                    "Heater",
                    lambda: "ACTIVE" if st.heat else "IDLE",
                    tone=lambda: "ok" if st.heat else "muted",
                ),
            ],
        ),
        ui.Screen(
            "Controls",
            children=[
                ui.Card(
                    "Climate",
                    children=[
                        ui.Switch("Heating", st.bind("heat")),
                        ui.Slider("Target", st.bind("target"), min=16, max=30, step=0.5, unit="C"),
                        ui.Select("Mode", st.bind("mode"), options=["Auto", "Eco", "Comfort"]),
                        ui.TextField("Room Name", st.bind("room")),
                        ui.Button("Boost 25C", on_click=_boost, shortcut="b"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _sample_temp():
    delta = 0.2 if (st.heat and st.temp < st.target) else -0.1
    st.temp = round(st.temp + delta, 1)
    hist = list(st.hist)
    hist.append(st.temp)
    if len(hist) > 20:
        hist = hist[-20:]
    st.hist = hist


async def run(cv):
    await app.run_async(cv)
m5stack_core2

HMI Themes, Fonts & Alerts (hmi_themes_and_alerts.py)

Download .py

Runtime ThemeManager (dark/light/high_contrast), priority NotificationManager, RLE fonts & 20 icons.

pylotos-sim examples/hmi_themes_and_alerts.py --board m5stack_core2 --port 8080
"""HMI Showcase: Themes, Priority Notifications, RLE Fonts & Semantic Icons.

Demonstrates Phase 3A `pylotos.ui` capabilities:
- Live runtime theme switching (`dark` Aviator, `light`, `high_contrast`) synced across LCD & Web
- Priority-queued `NotificationManager` (`info`, `ok`, `warn`, `err` preemption + unread badges)
- Proportional 5x7 / RLE bitmap typography (`sm`, `md`, `lg`, `xl`)
- 20 semantic 16x16 / 24x24 monochrome icons rendered inside a `CanvasBox`

Run locally:
    pylotos-sim examples/hmi_themes_and_alerts.py --board m5stack_core2 --port 8080
"""

import pylotos.ui as ui

st = ui.State(
    theme_name="dark",
    icon_size=16,
    font_preset="md",
    sample_text="PylotOS 2B-2",
    unread=0,
)


def _apply_theme(val):
    ui.theme_manager.set_theme(val)
    app.notify("Theme -> " + str(val), level="info", icon="settings")


def _push_level(lvl, msg, ic):
    app.notify(msg, level=lvl, icon=ic, duration_ms=2800)
    st.unread = app.notifications.unread_count


def _draw_showcase(cv, x, y, w, h):
    pal = cv.palette
    cv.rect(x, y, w, h, pal["border"])
    icons_row = ("wifi", "ble", "bolt", "cpu", "shield", "bell")
    sz = int(st.icon_size)
    ix = x + 6
    iy = y + 6
    for idx, name in enumerate(icons_row):
        if ix + sz > x + w - 4:
            break
        col = pal["gold"] if (idx % 2 == 1) else pal["cyan"]
        ui.draw_icon(cv, name, ix, iy, col=col, size=sz)
        ix += sz + 6

    ty = iy + sz + 6
    if ty + 10 <= y + h:
        ui.draw_text(
            cv,
            st.sample_text,
            x + 6,
            ty,
            col=pal["white"],
            font=str(st.font_preset),
            max_width=max(24, w - 12),
        )


app = ui.App(
    "HMI Studio",
    state=st,
    screens=[
        ui.Screen(
            "Themes & Fonts",
            icon="settings",
            children=[
                ui.CanvasBox(height=54, draw=_draw_showcase, label="RLE Font & Icon Atlas"),
                ui.Card(
                    "Appearance",
                    children=[
                        ui.Select(
                            "Theme",
                            st.bind("theme_name"),
                            options=["dark", "light", "high_contrast"],
                            on_change=_apply_theme,
                        ),
                        ui.Select(
                            "Font Size",
                            st.bind("font_preset"),
                            options=["sm", "md", "lg", "xl"],
                        ),
                        ui.Select(
                            "Icon Scale",
                            st.bind("icon_size"),
                            options=[12, 16, 24],
                        ),
                        ui.TextField("Banner Text", st.bind("sample_text")),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "Alerts",
            icon="bell",
            children=[
                ui.StatusBadge(
                    "Queue",
                    lambda: "{} unread".format(app.notifications.unread_count),
                    tone=lambda: "warn" if app.notifications.unread_count > 0 else "ok",
                ),
                ui.Card(
                    "Priority Preemption",
                    children=[
                        ui.Button(
                            "Info Toast",
                            on_click=lambda: _push_level("info", "Telemetry synced", "cloud"),
                            shortcut="i",
                        ),
                        ui.Button(
                            "Success Alert",
                            on_click=lambda: _push_level("ok", "Boot confirmed (asym-v1)", "check"),
                            shortcut="o",
                        ),
                        ui.Button(
                            "Warning Alert",
                            on_click=lambda: _push_level("warn", "EU868 duty at 80%", "warn"),
                            shortcut="w",
                        ),
                        ui.Button(
                            "Critical Error (Preempts!)",
                            on_click=lambda: _push_level("err", "Bus fault recovered", "error"),
                            shortcut="e",
                        ),
                        ui.Button(
                            "Mark All Read",
                            on_click=lambda: (
                                app.notifications.mark_all_read(),
                                setattr(st, "unread", 0),
                                app.mark_dirty(),
                            ),
                        ),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    await app.run_async(cv)
m5stack_cardputer_adv

OS EventBus & Services (pubsub_service_monitor.py)

Download .py

Typed pylotos.events PubSub bus, background services status, Asymmetric OTA & heap monitor.

pylotos-sim examples/pubsub_service_monitor.py --board m5stack_cardputer_adv --port 8080
"""OS PubSub EventBus, Background Services & Asymmetric OTA Monitor.

Demonstrates Phase 1 & Phase 3B OS integration:
- Subscribing to typed `pylotos.events` topics (`wifi.changed`, `power.battery`, custom topics)
- Inspecting declarative background services (`pylotos.services`)
- Reading live Asymmetric Recovery-OTA health (`sys_ota.status()`) & heap headroom (`hal.mem_info()`)

Run locally:
    pylotos-sim examples/pubsub_service_monitor.py --board m5stack_cardputer_adv --port 8080
"""

import hal
import pylotos.ui as ui
import sys_ota
from pylotos.events import TOPIC_POWER_BATTERY, TOPIC_WIFI_CHANGED, events
from pylotos.services import services

st = ui.State(
    heap_kb=0,
    batt_pct=100,
    wifi_ip="0.0.0.0",
    ota_schema="asym-v1",
    svc_running=0,
    events_rx=0,
    last_event="ready",
)


def _refresh_telemetry():
    mem = hal.mem_info()
    st.heap_kb = int(mem.get("heap_free_bytes", 0)) // 1024
    ota = sys_ota.status()
    st.ota_schema = str(ota.get("ota_schema", "asym-v1"))
    svc_stat = services.status()
    st.svc_running = int(svc_stat.get("running", 0))
    wifi = events.last(TOPIC_WIFI_CHANGED, {}) or {}
    if isinstance(wifi, dict) and wifi.get("ip"):
        st.wifi_ip = str(wifi["ip"])
    pwr = events.last(TOPIC_POWER_BATTERY, {}) or {}
    if isinstance(pwr, dict) and "battery_pct" in pwr:
        st.batt_pct = int(pwr["battery_pct"])


def _on_bus_event(topic, payload):
    st.events_rx = st.events_rx + 1
    st.last_event = "{}: {}".format(topic, payload)
    _refresh_telemetry()


events.subscribe("app.ping", _on_bus_event)
events.subscribe(TOPIC_WIFI_CHANGED, _on_bus_event)
events.subscribe(TOPIC_POWER_BATTERY, _on_bus_event)
_refresh_telemetry()


def _emit_ping():
    n = st.events_rx + 1
    events.publish("app.ping", {"seq": n})
    app.notify("Published app.ping #{}".format(n), level="ok", icon="bolt")


app = ui.App(
    "OS Monitor",
    state=st,
    screens=[
        ui.Screen(
            "System",
            icon="cpu",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Free Heap", st.bind("heap_kb"), unit="KB", accent="cyan"),
                        ui.Metric("Battery", st.bind("batt_pct"), unit="%", accent="gold"),
                    ],
                ),
                ui.Card(
                    "OS & OTA State",
                    children=[
                        ui.KeyValue("OTA Schema", st.bind("ota_schema")),
                        ui.KeyValue("Wi-Fi IP", st.bind("wifi_ip")),
                        ui.KeyValue("Active Services", st.bind("svc_running")),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "EventBus",
            icon="apps",
            children=[
                ui.StatusBadge(
                    "PubSub",
                    lambda: "{} events".format(st.events_rx),
                    tone="ok",
                ),
                ui.Card(
                    "Live Bus",
                    children=[
                        ui.KeyValue("Last Event", st.bind("last_event")),
                        ui.Button("Publish app.ping", on_click=_emit_ping, shortcut="p"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _poll_sys():
    _refresh_telemetry()


async def run(cv):
    await app.run_async(cv)
m5stack_atoms3

Background Service Daemon (background_env_service.py)

Download .py

Dual-mode /apps/services/ SERVICE_MANIFEST daemon + foreground live CO2/Lux telemetry preview.

pylotos-sim examples/background_env_service.py --board m5stack_atoms3 --port 8080
"""Declarative Background Service + Live Telemetry Dashboard (`SERVICE_MANIFEST`).

Can be installed in TWO ways on PylotOS:
1. Copy to `/apps/services/background_env_service.py` -> runs headless in the background
   via `SERVICE_MANIFEST` and `run_service(stop_event)`, publishing `sensor.env` onto `pylotos.events`!
2. Run directly as a foreground app or in `pylotos-sim`:
       pylotos-sim examples/background_env_service.py --board m5stack_atoms3 --port 8080
"""

import asyncio

import pylotos.ui as ui
from pylotos.events import events

SERVICE_MANIFEST = {
    "name": "env_sampler",
    "version": "1.0.0",
    "autostart": True,
    "caps": ["i2c"],
    "restart_on_crash": True,
}

st = ui.State(co2_ppm=440, lux=320, samples=0)


def _sample_once():
    st.co2_ppm = 420 + ((st.co2_ppm + 19) % 480)
    st.lux = 150 + ((st.lux + 45) % 650)
    st.samples = st.samples + 1
    events.publish("sensor.env", {"co2_ppm": st.co2_ppm, "lux": st.lux, "seq": st.samples})


async def run_service(stop_event):
    """Entry point invoked automatically by `pylotos.services` when placed in `/apps/services/`."""
    while not stop_event.is_set():
        _sample_once()
        await asyncio.sleep(2)


app = ui.App(
    "Env Service",
    state=st,
    screens=[
        ui.Screen(
            "Daemon",
            icon="chart",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("CO2", st.bind("co2_ppm"), unit="ppm", accent="cyan"),
                        ui.Metric("Light", st.bind("lux"), unit="lx", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Service Publisher",
                    children=[
                        ui.KeyValue("Samples Emitted", st.bind("samples")),
                        ui.Button("Sample & Publish Now", on_click=_sample_once, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _tick():
    _sample_once()


async def run(cv):
    await app.run_async(cv)
m5stack_core2

App Config, Policy & Quota (app_config_and_policy_demo.py)

Download .py

3-layer per-device app_config, runtime policy gate (ALLOW/ASK/DENY) & VFS storage quota check.

pylotos-sim examples/app_config_and_policy_demo.py --board m5stack_core2 --port 8080
"""3-Layer Per-Device `app_config`, Runtime `policy` Gate & VFS Quota Demo.

Demonstrates Phase 2A & Phase 3B security and fleet configuration APIs:
- Loading & saving per-device overrides via `pylotos.app_config`
- Testing `pylotos.policy.evaluate()` (`ALLOW` vs `ASK` vs non-overridable `DENY` on secrets)
- Checking LittleFS `/apps` storage quota via `pylotos.app_store.check_quota()`

Run locally:
    pylotos-sim examples/app_config_and_policy_demo.py --board m5stack_core2 --port 8080
"""

import pylotos.ui as ui
from pylotos import app_config, app_store, policy

cfg = app_config.load(
    defaults={"node_label": "Lab-Node-01", "quota_kb": 512},
    app_name="fleet_node",
)
quota = app_store.check_quota(extra_bytes=4096, quota_kb=int(cfg.get("quota_kb", 512)))

st = ui.State(
    node_label=str(cfg.get("node_label", "Lab-Node-01")),
    quota_kb=int(cfg.get("quota_kb", 512)),
    used_kb=int(quota.get("used_bytes", 0)) // 1024,
    last_decision="ALLOW (ready)",
)


def _save_cfg():
    app_config.save(
        {"node_label": st.node_label, "quota_kb": int(st.quota_kb)},
        app_name="fleet_node",
    )
    app.notify("Saved /apps/.config/fleet_node.json", level="ok", icon="check")


def _probe_policy(action, target):
    dec, reason = policy.evaluate(action, target=target, source="lan")
    st.last_decision = "{}: {}".format(dec.upper(), reason)
    lvl = "err" if dec == policy.DENY else ("warn" if dec == policy.ASK else "ok")
    app.notify("{} -> {}".format(action, dec.upper()), level=lvl, icon="lock")


app = ui.App(
    "Policy & Config",
    state=st,
    screens=[
        ui.Screen(
            "Policy Gate",
            icon="lock",
            children=[
                ui.StatusBadge(
                    "Decision",
                    st.bind("last_decision"),
                    tone=lambda: "err" if st.last_decision.startswith("DENY") else "info",
                ),
                ui.Card(
                    "Simulate LAN / MCP Request",
                    children=[
                        ui.Button(
                            "Test ALLOW (board.describe)",
                            on_click=lambda: _probe_policy("board.describe", None),
                            shortcut="1",
                        ),
                        ui.Button(
                            "Test ASK (apps.write)",
                            on_click=lambda: _probe_policy("apps.write", "demo.py"),
                            shortcut="2",
                        ),
                        ui.Button(
                            "Test DENY (nvs.get wifi_pass)",
                            on_click=lambda: _probe_policy("nvs.get", "wifi_pass"),
                            shortcut="3",
                        ),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "App Config",
            icon="settings",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Used VFS", st.bind("used_kb"), unit="KB", accent="cyan"),
                        ui.Metric("Quota", st.bind("quota_kb"), unit="KB", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Per-Device Override",
                    children=[
                        ui.TextField("Node Label", st.bind("node_label")),
                        ui.Slider("Quota KB", st.bind("quota_kb"), min=128, max=2048, step=128, unit="KB"),
                        ui.Button("Save Device Config", on_click=_save_cfg, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    await app.run_async(cv)
m5stack_cardputer_adv

Asym-OTA & CoreDump Diag (ota_and_coredump_diagnostics.py)

Download .py

Asymmetric Recovery-OTA (asym-v1) status, confirm_boot() & 0x13000 Flash ELF CoreDump inspector.

pylotos-sim examples/ota_and_coredump_diagnostics.py --board m5stack_cardputer_adv --port 8080
"""Asymmetric Recovery-OTA (`asym-v1`) & Flash ELF Core Dump Diagnostics.

Demonstrates Phase 1 & Phase 2A OS resilience APIs:
- Inspecting `sys_ota.status()` (`ota_schema`, `running_partition`, `boot_confirmed`, `boot_fails`)
- Inspecting Flash ELF Core Dump (`0x13000`) status via `hal.coredump_info()` & `coredump_erase()`
- Checking microSD offline recovery readiness (`hal.sd_info()`)

Run locally:
    pylotos-sim examples/ota_and_coredump_diagnostics.py --board m5stack_cardputer_adv --port 8080
"""

import hal
import pylotos.ui as ui
import sys_ota

st = ui.State(
    schema="asym-v1",
    slot="ota_0",
    confirmed="YES",
    boot_fails=0,
    cd_state="CLEAN",
    sd_ready="NO",
)


def _refresh():
    ota = sys_ota.status()
    st.schema = str(ota.get("ota_schema", "asym-v1"))
    st.slot = str(ota.get("running_partition", "ota_0"))
    st.confirmed = "YES" if ota.get("boot_confirmed", True) else "PENDING"
    st.boot_fails = int(ota.get("boot_fails", 0))

    cd = hal.coredump_info()
    if cd.get("present"):
        st.cd_state = "ELF ({} B)".format(cd.get("size", 0))
    else:
        st.cd_state = "CLEAN"

    sd = hal.sd_info()
    st.sd_ready = "MOUNTED" if sd.get("mounted") else "ABSENT"


def _confirm_now():
    sys_ota.confirm_boot()
    _refresh()
    app.notify("Boot health confirmed (ota_0)", level="ok", icon="check")


def _clear_coredump():
    hal.coredump_erase()
    _refresh()
    app.notify("Flash coredump partition erased", level="info", icon="shield")


_refresh()

app = ui.App(
    "OTA & Crash Diag",
    state=st,
    screens=[
        ui.Screen(
            "Asym-OTA",
            icon="cloud",
            children=[
                ui.StatusBadge(
                    "Boot Gate",
                    st.bind("confirmed"),
                    tone=lambda: "ok" if st.confirmed == "YES" else "warn",
                ),
                ui.Card(
                    "Partition State",
                    children=[
                        ui.KeyValue("Schema", st.bind("schema")),
                        ui.KeyValue("Active Slot", st.bind("slot")),
                        ui.KeyValue("Boot Fails", st.bind("boot_fails")),
                        ui.KeyValue("SD Recovery", st.bind("sd_ready")),
                        ui.Button("Confirm Boot Health", on_click=_confirm_now, shortcut="c"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "CoreDump",
            icon="shield",
            children=[
                ui.StatusBadge(
                    "0x13000 ELF",
                    st.bind("cd_state"),
                    tone=lambda: "ok" if st.cd_state == "CLEAN" else "err",
                ),
                ui.Card(
                    "Crash Partition (52 KiB)",
                    children=[
                        ui.Button("Refresh Status", on_click=_refresh, shortcut="r"),
                        ui.Button("Erase CoreDump", on_click=_clear_coredump, shortcut="e"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    await app.run_async(cv)
m5stack_stickc_plus2

esp_pm Sleep & ULP Monitor (power_sleep_and_ulp_monitor.py)

Download .py

Dynamic Frequency Scaling, Tickless Light Sleep, smooth backlight dim & ULP shared RTC RAM.

pylotos-sim examples/power_sleep_and_ulp_monitor.py --board m5stack_stickc_plus2 --port 8080
"""Power Management (`esp_pm`), Tickless Light Sleep & ULP Coprocessor Monitor.

Demonstrates Phase 2B & Phase 4B ultra-low-power features:
- Dynamic Frequency Scaling (DFS) & Automatic Tickless Light Sleep (`hal.pm_configure`)
- Smooth backlight dimming (`hal.display_backlight`) & PMIC battery telemetry (`hal.power_status`)
- ULP-RISC-V (ESP32-S3) / LP-Core (ESP32-C6) shared RTC memory (`hal.ulp_*`)

Run locally:
    pylotos-sim examples/power_sleep_and_ulp_monitor.py --board m5stack_stickc_plus2 --port 8080
"""

import hal
import pylotos.ui as ui

pwr = hal.power_status()
ulp = hal.ulp_info()
hal.ulp_write_shared(0, 420)  # Wake threshold in RTC slow RAM

st = ui.State(
    batt_pct=int(pwr.get("battery_pct", 100)),
    batt_mv=int(pwr.get("battery_mv", 4100)),
    max_mhz=240,
    min_mhz=80,
    tickless=True,
    backlight=80,
    ulp_arch=str(ulp.get("arch", "none")),
    ulp_thresh=hal.ulp_read_shared(0),
)


def _apply_pm():
    hal.pm_configure(int(st.max_mhz), int(st.min_mhz), bool(st.tickless))
    hal.display_backlight(int(st.backlight))
    hal.ulp_write_shared(0, int(st.ulp_thresh))
    app.notify(
        "PM {}-{} MHz, sleep={}".format(st.min_mhz, st.max_mhz, st.tickless),
        level="ok",
        icon="battery",
    )


def _nap_test():
    slept = hal.light_sleep(50)
    app.toast("Woke after {} ms light sleep".format(slept))


app = ui.App(
    "Power & ULP",
    state=st,
    screens=[
        ui.Screen(
            "esp_pm & Battery",
            icon="battery",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Battery", st.bind("batt_pct"), unit="%", accent="gold"),
                        ui.Metric("Voltage", st.bind("batt_mv"), unit="mV", accent="cyan"),
                    ],
                ),
                ui.Card(
                    "Tickless Governor",
                    children=[
                        ui.Switch("Auto Light Sleep", st.bind("tickless")),
                        ui.Select("Max CPU MHz", st.bind("max_mhz"), options=[80, 160, 240]),
                        ui.Slider("Backlight", st.bind("backlight"), min=10, max=100, step=10, unit="%"),
                        ui.Button("Apply Governor", on_click=_apply_pm, shortcut="a"),
                        ui.Button("50 ms Light Sleep Nap", on_click=_nap_test, shortcut="n"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "ULP RTC RAM",
            icon="cpu",
            children=[
                ui.KeyValue("Coprocessor", st.bind("ulp_arch")),
                ui.Card(
                    "Shared Wake Threshold",
                    children=[
                        ui.NumberField("RTC Reg[0]", st.bind("ulp_thresh"), min=100, max=2000, step=20),
                        ui.Button("Sync to ULP", on_click=_apply_pm, shortcut="u"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    await app.run_async(cv)
lilygo_t_deck

LoRa SX1262 Zero-Copy Mesh (lora_mesh_messenger.py)

Download .py

hal.rf SX1262 + Cap LoRa attach, EU868 1% duty-cycle budget, replay-protected MIC framing & recv_into.

pylotos-sim examples/lora_mesh_messenger.py --board lilygo_t_deck --port 8080
"""LoRa SX1262 Zero-Copy Messenger with EU868 1% Duty-Cycle & Replay Guard.

Demonstrates Phase 4W-1 `hal.rf` & `pylotos.wireless`:
- Opening onboard `SX1262` (`heltec_wifi_lora_32_v3`, `lilygo_t_deck`) or runtime `attach()`
- Regional `EU868` band & 1% sliding-window duty-cycle inspection (`hal.rf.duty_info()`)
- Replay-protected authenticated packet framing (`pack_frame` / `unpack_frame`)
- Zero-allocation packet reception into a pre-allocated `bytearray` (`hal.rf.recv_into`)

Run locally:
    pylotos-sim examples/lora_mesh_messenger.py --board heltec_wifi_lora_32_v3 --port 8080
    pylotos-sim examples/lora_mesh_messenger.py --board lilygo_t_deck --port 8080
"""

import hal
import pylotos.ui as ui
from pylotos import wireless

SHARED_KEY = b"pylotos-lora-key"
_rx_buf = bytearray(256)
_rx_meta = {}

st = ui.State(
    freq_mhz=868.1,
    sf=7,
    tx_seq=0,
    rx_seq=0,
    last_msg="(none)",
    rssi=0,
    snr=0,
    duty_rem_s=36.0,
    draft="Hello Mesh!",
)


def _init_radio():
    try:
        hal.rf.open()
    except OSError:
        # Fallback for expansion-port boards (e.g. Cardputer ADV Cap LoRa-1262)
        hal.rf.attach(
            "sx1262",
            port="ext_cap",
            rf_sw_port=0,
            rf_sw_addr=0x43,
            rf_sw_pin=0,
            dio2_sw=False,
        )
    hal.rf.set_region("EU868")
    hal.rf.set_freq(int(st.freq_mhz * 1000000))
    hal.rf.set_power(14)
    hal.rf.set_param("sf", int(st.sf))
    hal.rf.start_rx(0)
    _sync_duty()


def _sync_duty():
    info = hal.rf.duty_info()
    used = int(info.get("used_ms", 0))
    budget = int(info.get("budget_ms", 36000))
    st.duty_rem_s = round(max(0, budget - used) / 1000.0, 1)


def _send_frame():
    seq = st.tx_seq + 1
    frame = wireless.pack_frame(SHARED_KEY, seq, st.draft.encode("utf-8"))
    try:
        hal.rf.send(frame)
        st.tx_seq = seq
        _sync_duty()
        app.notify("TX #{} ({} B)".format(seq, len(frame)), level="ok", icon="wifi")
    except OSError as exc:
        app.notify("TX blocked: {}".format(exc), level="warn", icon="warn")


def _on_sf_change(val):
    hal.rf.set_param("sf", int(val))
    app.toast("LoRa SF{}".format(val))


_init_radio()

app = ui.App(
    "LoRa Mesh",
    state=st,
    screens=[
        ui.Screen(
            "Transceiver",
            icon="wifi",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("RSSI", st.bind("rssi"), unit="dBm", accent="cyan"),
                        ui.Metric("Air Budget", st.bind("duty_rem_s"), unit="s", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Compose & Loopback",
                    children=[
                        ui.KeyValue("Last RX", st.bind("last_msg")),
                        ui.TextField("Message", st.bind("draft")),
                        ui.Select("Spreading", st.bind("sf"), options=[7, 8, 9, 10, 12], on_change=_on_sf_change),
                        ui.Button("Transmit Signed Frame", on_click=_send_frame, shortcut="t"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(150)
def _poll_rx():
    n = hal.rf.recv_into(_rx_buf, _rx_meta)
    if n <= 0:
        return
    try:
        seq, plain = wireless.unpack_frame(SHARED_KEY, memoryview(_rx_buf)[:n], min_seq=st.rx_seq + 1)
        st.rx_seq = seq
        st.rssi = int(_rx_meta.get("rssi", 0))
        st.snr = int(_rx_meta.get("snr", 0))
        st.last_msg = "#{} {}".format(seq, plain.decode("utf-8", "replace"))
    except ValueError as exc:
        app.notify("Dropped frame: {}".format(exc), level="err", icon="shield")


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.rf.sleep(True)
lilygo_t_embed

Sub-GHz CC1101 & Overlays (subghz_cc1101_and_overlays.py)

Download .py

Declarative hardware overlays (Cap LoRa-1262, Grove units) & pin-guarded CC1101 Sub-GHz transceiver.

pylotos-sim examples/subghz_cc1101_and_overlays.py --board lilygo_t_embed --port 8080
"""Declarative Hardware Overlays (`pylotos.overlays`) & Sub-GHz `CC1101` Transceiver.

Demonstrates Phase 4W-2 runtime expansion-port hardware attachment:
- Inspecting & applying built-in overlays (`cardputer_adv_cap_lora1262`, `grove_nfc_ws1850s`, `grove_gnss_uart`)
- Runtime pin-guarded `hal.rf.attach("cc1101", ...)` for 433.92 / 868.35 MHz Sub-GHz FSK/OOK packets

Run locally:
    pylotos-sim examples/subghz_cc1101_and_overlays.py --board lilygo_t_embed --port 8080
"""

import hal
import pylotos.ui as ui
from pylotos import overlays

available = sorted(overlays.load_overlays().keys())
_rx_buf = bytearray(64)

st = ui.State(
    selected_overlay=available[0] if available else "cardputer_adv_cap_lora1262",
    active_driver="cc1101",
    freq_khz=868350,
    packets_tx=0,
    last_rx="(listening)",
)


def _attach_cc1101():
    hal.rf.attach("cc1101", port="ext_cap")
    hal.rf.set_region("EU868")
    hal.rf.set_freq(int(st.freq_khz) * 1000)
    st.active_driver = "cc1101"
    app.notify("Attached CC1101 @ {} kHz".format(st.freq_khz), level="ok", icon="wifi")


def _apply_selected_overlay():
    doc = overlays.apply_overlay(str(st.selected_overlay), persist=False)
    st.active_driver = str(doc.get("driver", "overlay"))
    app.notify("Applied " + str(st.selected_overlay), level="ok", icon="check")


def _tx_subghz_burst():
    hal.rf.set_freq(int(st.freq_khz) * 1000)
    hal.rf.send(b"PYLOT-SUBGHZ-PING")
    st.packets_tx = st.packets_tx + 1
    n = hal.rf.recv_into(_rx_buf)
    if n > 0:
        st.last_rx = bytes(_rx_buf[:n]).decode("utf-8", "replace")


app = ui.App(
    "Sub-GHz & Overlays",
    state=st,
    screens=[
        ui.Screen(
            "CC1101 RF",
            icon="wifi",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Freq", st.bind("freq_khz"), unit="kHz", accent="cyan"),
                        ui.Metric("Bursts", st.bind("packets_tx"), accent="gold"),
                    ],
                ),
                ui.Card(
                    "Sub-GHz Transceiver",
                    children=[
                        ui.KeyValue("Last RX", st.bind("last_rx")),
                        ui.Select("Channel kHz", st.bind("freq_khz"), options=[868100, 868350, 869525]),
                        ui.Button("Send Sub-GHz Burst", on_click=_tx_subghz_burst, shortcut="t"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "Overlays",
            icon="apps",
            children=[
                ui.KeyValue("Active Driver", st.bind("active_driver")),
                ui.Card(
                    "Pin-Guarded Expansion",
                    children=[
                        ui.Select("Overlay", st.bind("selected_overlay"), options=available),
                        ui.Button("Apply Overlay", on_click=_apply_selected_overlay, shortcut="o"),
                        ui.Button("Re-Attach CC1101", on_click=_attach_cc1101),
                    ],
                ),
            ],
        ),
    ],
)

_attach_cc1101()


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.rf.detach()
m5stack_nanoc6

ESP-NOW P2P Swarm Radar (espnow_swarm_radar.py)

Download .py

Connectionless 2.4 GHz peer broadcast/unicast, zero-copy recv_into, binary telemetry & RSSI Sparkline.

pylotos-sim examples/espnow_swarm_radar.py --board m5stack_nanoc6 --port 8080
"""ESP-NOW Zero-Copy Swarm Telemetry Radar (`hal.espnow`).

Demonstrates Phase 4W-1 connectionless 2.4 GHz peer-to-peer messaging across all
ESP32 / S3 / C3 / C6 boards without requiring an external Wi-Fi router:
- Broadcast + unicast peer registration (`hal.espnow.add_peer`)
- Zero-copy `hal.espnow.recv_into(buf, meta)` reception with RSSI history sparkline
- Authenticated frame sequence verification (`pylotos.wireless`)

Run locally:
    pylotos-sim examples/espnow_swarm_radar.py --board m5stack_nanoc6 --port 8080
    pylotos-sim examples/espnow_swarm_radar.py --board m5stack_atoms3 --port 8080
"""

import struct

import hal
import pylotos.ui as ui
from pylotos import wireless

BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
SWARM_KEY = b"pylotos-swarm-01"
_rx_buf = bytearray(250)
_rx_meta = {}

hal.espnow.open()
hal.espnow.add_peer(BROADCAST_MAC, 0)

st = ui.State(
    tx_count=0,
    rx_count=0,
    last_rssi=-40,
    peer_temp=23.5,
    rssi_hist=[-48, -45, -42, -40],
)


def _send_beacon():
    seq = st.tx_count + 1
    payload = struct.pack("<hH", int(st.peer_temp * 10), 88)
    pkt = wireless.pack_frame(SWARM_KEY, seq, payload)
    hal.espnow.send(BROADCAST_MAC, pkt)
    st.tx_count = seq


app = ui.App(
    "ESP-NOW Radar",
    state=st,
    screens=[
        ui.Screen(
            "Swarm",
            icon="wifi",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Peers RX", st.bind("rx_count"), accent="cyan"),
                        ui.Metric("RSSI", st.bind("last_rssi"), unit="dBm", accent="gold"),
                    ],
                ),
                ui.Sparkline("Link RSSI", st.bind("rssi_hist"), unit="dBm", accent="cyan"),
                ui.Card(
                    "Beacon Control",
                    children=[
                        ui.Slider("Sim Temp", st.bind("peer_temp"), min=15.0, max=40.0, step=0.5, unit="C"),
                        ui.Button("Broadcast Beacon", on_click=_send_beacon, shortcut="b"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(200)
def _poll_espnow():
    n = hal.espnow.recv_into(_rx_buf, _rx_meta)
    if n <= 0:
        return
    try:
        _seq, body = wireless.unpack_frame(SWARM_KEY, memoryview(_rx_buf)[:n])
        if len(body) >= 4:
            t_d10, _batt = struct.unpack("<hH", body[:4])
            st.peer_temp = round(t_d10 / 10.0, 1)
        rssi = int(_rx_meta.get("rssi", -40))
        st.last_rssi = rssi
        st.rx_count = st.rx_count + 1
        hist = list(st.rssi_hist)
        hist.append(rssi)
        st.rssi_hist = hist[-16:]
    except ValueError:
        pass


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.espnow.close()
waveshare_esp32c6_lcd_147

C6 Wi-Fi 6 iTWT & 802.15.4 (c6_wifi6_twt_and_802154.py)

Download .py

ESP32-C6 triple-radio 2.4 GHz esp_coex, Wi-Fi 6 iTWT, NimBLE Coded PHY (S=8) & raw IEEE 802.15.4.

pylotos-sim examples/c6_wifi6_twt_and_802154.py --board waveshare_esp32c6_lcd_147 --port 8080
"""ESP32-C6 Wi-Fi 6 `iTWT`, NimBLE 5.3 Coded PHY & `IEEE 802.15.4` Node.

Demonstrates the triple-radio 2.4 GHz `esp_coex` capabilities on ESP32-C6 boards
(`m5stack_nanoc6`, `waveshare_esp32c6_lcd_147`, `seeed_xiao_esp32c6`):
- `hal.net.twt()` Individual Target Wake Time (`802.11ax`) & `hal.net.coex()` arbiter
- `hal.ble.coded_phy()` Long-Range S=8 BLE 5.3 advertising/link configuration
- `hal.ieee802154` raw `802.15.4` MAC frame TX (`--wireless-profile 802154`)

Run locally:
    pylotos-sim examples/c6_wifi6_twt_and_802154.py --board waveshare_esp32c6_lcd_147 --port 8080
"""

import struct

import hal
import pylotos.ui as ui

st = ui.State(
    coex_mode="balance",
    twt_on=True,
    twt_wake_ms=2000,
    coded_s8=True,
    zig_ch=15,
    frames_tx=0,
)

hal.ieee802154.open(15, 0x1234, 0x0001)


def _apply_radio_cfg():
    hal.net.coex(str(st.coex_mode))
    hal.net.twt(bool(st.twt_on), int(st.twt_wake_ms), 12)
    hal.ble.coded_phy(bool(st.coded_s8), True)
    app.notify("Synced Wi-Fi 6 iTWT + BLE Coded PHY", level="ok", icon="wifi")


def _send_802154():
    seq = (st.frames_tx + 1) & 0xFF
    # Minimal IEEE 802.15.4 data frame header + sensor payload
    hdr = struct.pack("<HBHHH", 0x8861, seq, 0x1234, 0xFFFF, 0x0001)
    hal.ieee802154.open(int(st.zig_ch), 0x1234, 0x0001)
    hal.ieee802154.send(hdr + b"pylot-c6")
    st.frames_tx = st.frames_tx + 1
    app.toast("802.15.4 Ch{} TX #{}".format(st.zig_ch, st.frames_tx))


app = ui.App(
    "C6 Triple-Radio",
    state=st,
    screens=[
        ui.Screen(
            "Wi-Fi 6 & BLE",
            icon="wifi",
            children=[
                ui.Card(
                    "2.4 GHz Coex & iTWT",
                    children=[
                        ui.Select("Coex Priority", st.bind("coex_mode"), options=["balance", "wifi", "ble"]),
                        ui.Switch("Wi-Fi 6 iTWT", st.bind("twt_on")),
                        ui.Slider("Wake Interval", st.bind("twt_wake_ms"), min=500, max=5000, step=500, unit="ms"),
                        ui.Switch("BLE Coded PHY (S=8)", st.bind("coded_s8")),
                        ui.Button("Apply Radio Policy", on_click=_apply_radio_cfg, shortcut="a"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "802.15.4 MAC",
            icon="ble",
            children=[
                ui.Metric("PAN 0x1234 TX", st.bind("frames_tx"), accent="gold"),
                ui.Card(
                    "IEEE 802.15.4 Raw",
                    children=[
                        ui.Select("Channel", st.bind("zig_ch"), options=[11, 15, 20, 25, 26]),
                        ui.Button("Broadcast 802.15.4 Frame", on_click=_send_802154, shortcut="z"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.ieee802154.close()
m5stack_dial

NFC / RFID & NDEF Scanner (nfc_badge_scanner.py)

Download .py

M5Stack Dial WS1850S & Grove RFID2/PN532 UID scan, block 4 read & pure-Python NDEF URI/Text decoder.

pylotos-sim examples/nfc_badge_scanner.py --board m5stack_dial --port 8080
"""NFC / RFID Badge & NDEF Scanner (`hal.nfc` + `pylotos.wireless`).

Ideal for the round `240x240` **M5Stack Dial** (onboard `WS1850S @ 0x28`) or any board
with a Grove RFID2 (`WS1850S`) / `PN532` / `MFRC522` expansion unit:
- Non-blocking ISO14443A tag UID polling (`hal.nfc.poll_tag_into`)
- Block 4 NTAG / MIFARE read + pure-Python NDEF URI/Text decoding (`decode_ndef_record`)
- Audible chime (`hal.beep`) on badge tap

Run locally:
    pylotos-sim examples/nfc_badge_scanner.py --board m5stack_dial --port 8080
"""

import sys

import hal
import pylotos.ui as ui
from pylotos import wireless

_uid_buf = bytearray(10)
_blk_buf = bytearray(16)

try:
    hal.nfc.open()
except OSError:
    hal.nfc.attach("ws1850s", port="grove_a", addr=0x28)

st = ui.State(
    scans=0,
    last_uid="(tap card)",
    ndef_val="(waiting)",
    access="READY",
)


def _format_hex(mv):
    return ":".join("{:02X}".format(b) for b in mv)


def _simulate_tap():
    # Convenient helper when previewing in `pylotos-sim` on desktop
    sim_mod = sys.modules.get("pylotos_sim.mock_hal")
    if sim_mod is not None:
        # Push a fresh simulated UID onto the mock NFC queue if available
        hal_nfc = getattr(hal, "nfc", None)
        if hal_nfc is not None:
            st.last_uid = "04:CA:FE:42"
            hal.nfc.read_block(4, _blk_buf)
            rec = wireless.decode_ndef_record(_blk_buf)
            st.ndef_val = str(rec.get("value", ""))
            st.scans = st.scans + 1
            st.access = "GRANTED"
            hal.beep(1320, 45, 50)
            app.notify("Simulated tag " + st.last_uid, level="ok", icon="check")


app = ui.App(
    "NFC Access",
    state=st,
    screens=[
        ui.Screen(
            "Scanner",
            icon="shield",
            children=[
                ui.Metric("Badges Read", st.bind("scans"), accent="gold"),
                ui.StatusBadge(
                    "Gate",
                    st.bind("access"),
                    tone=lambda: "ok" if st.access == "GRANTED" else "info",
                ),
                ui.Card(
                    "Last Tag",
                    children=[
                        ui.KeyValue("UID", st.bind("last_uid")),
                        ui.KeyValue("NDEF", st.bind("ndef_val")),
                        ui.Button("Simulate Card Tap", on_click=_simulate_tap, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(150)
def _poll_tag():
    ulen = hal.nfc.poll_tag_into(_uid_buf)
    if ulen <= 0:
        return
    uid_hex = _format_hex(memoryview(_uid_buf)[:ulen])
    st.last_uid = uid_hex
    st.scans = st.scans + 1
    st.access = "GRANTED"
    if hal.nfc.read_block(4, _blk_buf) > 0:
        try:
            rec = wireless.decode_ndef_record(_blk_buf)
            st.ndef_val = str(rec.get("value", rec.get("type", "raw")))
        except ValueError:
            st.ndef_val = "(raw block)"
    hal.beep(1320, 45, 50)
    app.notify("UID " + uid_hex, level="ok", icon="shield")


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.nfc.sleep()
m5stack_cardputer_adv

RMT IR Remote & GNSS (ir_universal_remote.py)

Download .py

38 kHz hardware-carrier ESP-IDF RMT v2 NEC remote paired with fixed-point C NMEA/UBX GNSS fix viewer.

pylotos-sim examples/ir_universal_remote.py --board m5stack_cardputer_adv --port 8080
"""Hardware RMT v2 Infrared Universal Remote & GNSS Field Companion.

Demonstrates Phase 4 `hal.ir` (38 kHz hardware-carrier NEC TX without CPU bit-banging)
and `hal.gnss` (streaming C NMEA/UBX fixed-point satellite fix parser):
- Works out of the box on `m5stack_cardputer_adv`, `m5stack_cardputer`,
  `m5stack_stickc_plus2`, `m5stack_atoms3`, and `m5stack_nanoc6`!

Run locally:
    pylotos-sim examples/ir_universal_remote.py --board m5stack_cardputer_adv --port 8080
"""

import hal
import pylotos.ui as ui

hal.ir.open(carrier_hz=38000)
hal.gnss.open(baudrate=9600)

st = ui.State(
    ir_addr=0x04,
    ir_sent=0,
    last_cmd="IDLE",
    sats=0,
    lat_deg="0.00000",
    lon_deg="0.00000",
    alt_m=0,
)


def _send_nec(label, cmd):
    hal.ir.tx_nec(int(st.ir_addr) & 0xFF, int(cmd) & 0xFF)
    st.ir_sent = st.ir_sent + 1
    st.last_cmd = "{} (0x{:02X})".format(label, cmd)
    hal.beep(980, 25, 35)
    app.toast("IR TX: " + st.last_cmd)


app = ui.App(
    "IR & GNSS",
    state=st,
    screens=[
        ui.Screen(
            "IR Remote",
            icon="bolt",
            children=[
                ui.StatusBadge("Last IR", st.bind("last_cmd"), tone="info"),
                ui.Card(
                    "NEC 38 kHz Controls",
                    children=[
                        ui.NumberField("NEC Address", st.bind("ir_addr"), min=0, max=255, step=1),
                        ui.Button("Power Toggle", on_click=lambda: _send_nec("POWER", 0x08), shortcut="p"),
                        ui.Button("Volume +", on_click=lambda: _send_nec("VOL+", 0x02), shortcut="+"),
                        ui.Button("Volume -", on_click=lambda: _send_nec("VOL-", 0x03), shortcut="-"),
                        ui.Button("Mute", on_click=lambda: _send_nec("MUTE", 0x09), shortcut="m"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "GNSS Fix",
            icon="cloud",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Satellites", st.bind("sats"), accent="cyan"),
                        ui.Metric("Altitude", st.bind("alt_m"), unit="m", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Coordinates (Fixed-Point e7)",
                    children=[
                        ui.KeyValue("Latitude", st.bind("lat_deg")),
                        ui.KeyValue("Longitude", st.bind("lon_deg")),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(1000)
def _poll_gnss():
    fix = hal.gnss.poll()
    if fix.get("valid"):
        st.sats = int(fix.get("sats", 0))
        st.lat_deg = "{:.5f}".format(int(fix.get("lat_e7", 0)) / 10000000.0)
        st.lon_deg = "{:.5f}".format(int(fix.get("lon_e7", 0)) / 10000000.0)
        st.alt_m = int(fix.get("alt_mm", 0)) // 1000


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.ir.close()
        hal.gnss.close()
m5stack_cores3

Core 0 DMA Audio, ULP & CAN (audio_synth_and_industrial.py)

Download .py

16 kHz PCM sine synthesizer on Core 0 I2S DMA, ULP shared RTC memory & CAN 2.0B / TWAI loopback.

pylotos-sim examples/audio_synth_and_industrial.py --board m5stack_cores3 --port 8080
"""Core 0 DMA I2S Audio Synthesizer, ULP Coprocessor & CAN Bus Inspector.

Demonstrates Phase 4B & 4C hardware subsystems:
- Non-blocking Core 0 DMA 16-bit PCM audio streaming (`hal.audio_open` / `hal.audio_write`)
- ULP-RISC-V (ESP32-S3) / LP-Core (ESP32-C6) shared RTC memory (`hal.ulp_write_shared` / `ulp_read_shared`)
- Industrial CAN 2.0B / TWAI frame transmission & zero-copy receive (`hal.can_send` / `can_recv_into`)

Run locally:
    pylotos-sim examples/audio_synth_and_industrial.py --board m5stack_cores3 --port 8080
"""

import math
import struct

import hal
import pylotos.ui as ui

_can_rx = bytearray(8)
_pcm_buf = bytearray(640)  # 320 mono 16-bit samples = 20 ms @ 16 kHz

hal.audio_open(sample_rate=16000, channels=1, enable_rx=False, volume_pct=70)
hal.can_init(tx_gpio=2, rx_gpio=1, bitrate_bps=500000)
hal.ulp_write_shared(0, 1)

st = ui.State(
    freq_hz=440,
    volume=70,
    tones_played=0,
    ulp_counter=1,
    can_tx=0,
    last_can="(idle)",
)


def _play_chord():
    f = float(st.freq_hz)
    for i in range(320):
        sample = int(12000.0 * math.sin(2.0 * math.pi * f * (i / 16000.0)))
        struct.pack_into("<h", _pcm_buf, i * 2, sample)
    hal.audio_set_volume(int(st.volume))
    hal.audio_write(_pcm_buf)
    st.tones_played = st.tones_played + 1
    app.toast("DMA PCM burst @ {} Hz".format(int(f)))


def _step_ulp_and_can():
    nxt = hal.ulp_read_shared(0) + 1
    hal.ulp_write_shared(0, nxt)
    st.ulp_counter = hal.ulp_read_shared(0)

    payload = struct.pack(">II", st.ulp_counter, int(st.freq_hz))
    hal.can_send(0x123, payload)
    st.can_tx = st.can_tx + 1

    rx = hal.can_recv_into(_can_rx)
    if rx is not None:
        arb_id, dlc, _ext = rx
        st.last_can = "0x{:03X} [{}B]".format(arb_id, dlc)


app = ui.App(
    "Audio & CAN",
    state=st,
    screens=[
        ui.Screen(
            "DMA Audio",
            icon="play",
            children=[
                ui.Metric("PCM Bursts", st.bind("tones_played"), accent="cyan"),
                ui.Card(
                    "Core 0 I2S Synthesizer",
                    children=[
                        ui.Slider("Pitch", st.bind("freq_hz"), min=220, max=1760, step=55, unit="Hz"),
                        ui.Slider("Volume", st.bind("volume"), min=0, max=100, step=5, unit="%"),
                        ui.Button("Stream 20 ms Sine", on_click=_play_chord, shortcut="p"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "ULP & CAN",
            icon="cpu",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("ULP Reg[0]", st.bind("ulp_counter"), accent="gold"),
                        ui.Metric("CAN Frames", st.bind("can_tx"), accent="cyan"),
                    ],
                ),
                ui.Card(
                    "Industrial TWAI Bus",
                    children=[
                        ui.KeyValue("Last CAN RX", st.bind("last_can")),
                        ui.Button("Send CAN 0x123 + Step ULP", on_click=_step_ulp_and_can, shortcut="c"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.audio_close()
        hal.can_deinit()
m5stack_dial

MQTT + Home Assistant (mqtt_home_assistant_dashboard.py)

Download .py

Zero-dependency async MQTT 3.1.1 client with automatic Home Assistant sensor discovery from hal.describe().

pylotos-sim examples/mqtt_home_assistant_dashboard.py --board m5stack_dial --port 8080
"""MQTT 3.1.1 + Home Assistant Auto-Discovery Smart Home Node (`pylotos.mqtt_ha`).

Demonstrates Phase 4C zero-dependency Smart Home integration:
- Inspecting auto-generated `homeassistant/sensor/pylotos_<node>/*/config` discovery payloads
- Connecting & publishing retained discovery + live JSON state via `MqttHaService`

Run locally:
    pylotos-sim examples/mqtt_home_assistant_dashboard.py --board m5stack_dial --port 8080
"""

import json

import hal
import pylotos.ui as ui
from pylotos.mqtt_ha import MqttHaService, build_ha_discovery_messages

disc_msgs = build_ha_discovery_messages()

st = ui.State(
    broker="192.168.1.10",
    entities=len(disc_msgs),
    published=0,
    status="READY",
)


async def _sync_ha():
    svc = MqttHaService(host=str(st.broker), port=1883)
    try:
        await svc.connect()
        cnt = await svc.publish_discovery()
        mem = hal.mem_info()
        payload = json.dumps(
            {
                "heap_free": mem.get("heap_free_bytes", 0),
                "uptime_s": (st.published + 1) * 10,
                "battery_pct": hal.power_status().get("battery_pct", 100),
            }
        )
        await svc.publish("pylotos/" + svc.node_id + "/state", payload)
        await svc.close()
        st.entities = cnt
        st.published = st.published + 1
        st.status = "SYNCED"
        app.notify("Published {} HA entities + state".format(cnt), level="ok", icon="home")
    except Exception as exc:
        st.status = "OFFLINE"
        app.notify("Broker error: {}".format(exc), level="warn", icon="warn")


app = ui.App(
    "Home Assistant",
    state=st,
    screens=[
        ui.Screen(
            "MQTT Bridge",
            icon="home",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("HA Entities", st.bind("entities"), accent="cyan"),
                        ui.Metric("Publishes", st.bind("published"), accent="gold"),
                    ],
                ),
                ui.StatusBadge(
                    "Broker",
                    st.bind("status"),
                    tone=lambda: "ok" if st.status == "SYNCED" else "info",
                ),
                ui.Card(
                    "Auto-Discovery",
                    children=[
                        ui.TextField("MQTT Host", st.bind("broker")),
                        ui.Button("Publish Discovery & State", on_click=_sync_ha, shortcut="m"),
                    ],
                ),
            ],
        ),
    ],
)


async def run(cv):
    await app.run_async(cv)
m5stack_core2

Modbus RTU/TCP & CAN PLC (modbus_plc_and_can_gateway.py)

Download .py

Industrial Modbus RTU CRC-16 frame builder/verifier & 500 kbps CAN 2.0B / TWAI PDO gateway.

pylotos-sim examples/modbus_plc_and_can_gateway.py --board m5stack_core2 --port 8080
"""Industrial Modbus RTU/TCP (`pylotos.modbus`) & CAN 2.0B / TWAI Gateway.

Demonstrates Phase 4C industrial automation protocols:
- Building CRC-16 verified Modbus RTU Function `0x03` Holding Register requests
- Transmitting & receiving CAN 2.0B / TWAI frames zero-copy (`hal.can_send` / `can_recv_into`)

Run locally:
    pylotos-sim examples/modbus_plc_and_can_gateway.py --board m5stack_core2 --port 8080
"""

import struct

import hal
import pylotos.ui as ui
from pylotos import modbus

_can_buf = bytearray(8)
hal.can_init(tx_gpio=26, rx_gpio=36, bitrate_bps=500000)

st = ui.State(
    unit_id=1,
    reg_addr=16,
    reg_count=2,
    rtu_hex="(none)",
    can_id=0x180,
    can_frames=0,
    can_rx_str="(waiting)",
)


def _build_modbus():
    pdu = modbus.build_read_holding_pdu(int(st.reg_addr), int(st.reg_count))
    frame = modbus.build_rtu_frame(int(st.unit_id), 0x03, pdu)
    st.rtu_hex = " ".join("{:02X}".format(b) for b in frame)
    app.notify("RTU CRC-16 frame ready ({} B)".format(len(frame)), level="ok", icon="terminal")


def _send_can_pdo():
    data = struct.pack(">HHHH", int(st.unit_id), int(st.reg_addr), int(st.reg_count), st.can_frames + 1)
    hal.can_send(int(st.can_id), data)
    st.can_frames = st.can_frames + 1
    rx = hal.can_recv_into(_can_buf)
    if rx is not None:
        arb_id, dlc, _ext = rx
        st.can_rx_str = "0x{:03X} ({}B)".format(arb_id, dlc)


app = ui.App(
    "Modbus & CAN",
    state=st,
    screens=[
        ui.Screen(
            "Modbus RTU",
            icon="terminal",
            children=[
                ui.Card(
                    "FC 0x03 Read Holding",
                    children=[
                        ui.KeyValue("RTU Frame", st.bind("rtu_hex")),
                        ui.NumberField("Slave Unit ID", st.bind("unit_id"), min=1, max=247, step=1),
                        ui.NumberField("Start Register", st.bind("reg_addr"), min=0, max=9999, step=1),
                        ui.Button("Build CRC-16 Frame", on_click=_build_modbus, shortcut="b"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "CAN / TWAI",
            icon="cpu",
            children=[
                ui.Metric("CAN PDO TX", st.bind("can_frames"), accent="gold"),
                ui.Card(
                    "500 kbps TWAI Bus",
                    children=[
                        ui.KeyValue("Last Loopback", st.bind("can_rx_str")),
                        ui.Button("Transmit CAN PDO", on_click=_send_can_pdo, shortcut="c"),
                    ],
                ),
            ],
        ),
    ],
)

_build_modbus()


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.can_deinit()
m5stack_cores3

Ethernet Failover & USB-NCM (ethernet_failover_and_usb_ncm.py)

Download .py

OS-owned hal.net W5500 SPI Ethernet + ESP32-S3 USB-NCM hot-plug failover, static IP & Bridge policy.

pylotos-sim examples/ethernet_failover_and_usb_ncm.py --board m5stack_cores3 --port 8080
"""Wired Network Failover & USB-NCM Console — PylotOS Wired C HAL (`hal.net`).

Demonstrates:
- OS-owned `hal.net` multi-interface routing (`eth_spi` W5500 -> `usb_ncm` -> `wifi_sta`)
- Deterministic hot-plug failover and manual route priority tuning
- Restricting the `:8266` AI Bridge / OTA server to wired interfaces (`set_bridge_ifaces`)
- Static IPv4 assignment without breaking Wi-Fi fallback

Run locally:
    pylotos-sim examples/ethernet_failover_and_usb_ncm.py --board m5stack_cores3
"""

import hal
import pylotos.ui as ui

st = ui.State(
    route="wifi_sta",
    eth_ip="0.0.0.0",
    ncm_ip="0.0.0.0",
    wifi_ip="192.168.1.42",
    bridge_mode="All (Eth + Wi-Fi)",
    failovers=0,
    status="Ready — Wi-Fi STA active",
)


def _refresh():
    ifaces = hal.net.interfaces()
    desc = hal.describe().get("wired", {})
    st.route = hal.net.active_route()
    st.eth_ip = ifaces.get("eth_spi", {}).get("ip", "0.0.0.0")
    st.ncm_ip = ifaces.get("usb_ncm", {}).get("ip", "0.0.0.0")
    st.wifi_ip = ifaces.get("wifi_sta", {}).get("ip", "0.0.0.0")
    st.failovers = int(desc.get("failover_count", 0))


def attach_w5500():
    try:
        hal.net.attach_eth("w5500", port="mbus", spi_host=1, cs=5, irq=35, rst=33, dhcp=True)
        _refresh()
        st.status = "W5500 Ethernet UP -> primary route"
        app.notify("Ethernet UP: %s" % st.eth_ip, level="ok")
    except OSError as exc:
        st.status = "W5500 attach failed: %s" % exc
        app.notify("W5500 unavailable on board", level="warn")


def detach_w5500():
    hal.net.detach_eth()
    _refresh()
    st.status = "Ethernet unplugged -> failover to %s" % st.route
    app.notify("Failover -> %s" % st.route, level="warn")


def enable_usb_ncm():
    try:
        hal.net.attach_usb_ncm()
        _refresh()
        st.status = "USB-NCM NIC UP (%s)" % st.ncm_ip
        app.notify("USB-NCM active: %s" % st.ncm_ip, level="ok")
    except OSError:
        st.status = "USB-NCM requires ESP32-S3 USB-OTG"
        app.notify("USB-NCM requires ESP32-S3", level="warn")


def lock_bridge_wired_only():
    hal.net.set_bridge_ifaces(["eth_spi", "eth_rmii", "usb_ncm"])
    st.bridge_mode = "Wired Only (Zero Wi-Fi Bridge)"
    st.status = "Bridge :8266 locked to wired NICs"
    app.notify("Bridge restricted to wired NICs", level="info")


def assign_static_eth():
    hal.net.set_static_ip("eth_spi", "10.20.30.40", "255.255.255.0", "10.20.30.1")
    _refresh()
    st.status = "Static IP applied on eth_spi"
    app.notify("Static IP: 10.20.30.40", level="ok")


route_screen = ui.Screen(
    "Wired Routing",
    [
        ui.Grid(
            [
                ui.Metric("Active Route", st.bind("route"), accent="cyan"),
                ui.Metric("Failovers", st.bind("failovers"), accent="gold"),
            ],
            cols=2,
        ),
        ui.Card(
            "Interface Table (HAL_OWNER_OS)",
            [
                ui.KeyValue("W5500 SPI Eth", st.bind("eth_ip")),
                ui.KeyValue("USB-NCM (S3)", st.bind("ncm_ip")),
                ui.KeyValue("Wi-Fi STA", st.bind("wifi_ip")),
                ui.KeyValue("Bridge Policy", st.bind("bridge_mode")),
            ],
        ),
        ui.Row(
            [
                ui.Button("Attach W5500", attach_w5500, shortcut="1"),
                ui.Button("Unplug Eth", detach_w5500, shortcut="2"),
            ]
        ),
        ui.Row(
            [
                ui.Button("USB-NCM", enable_usb_ncm, shortcut="3"),
                ui.Button("Lock Bridge", lock_bridge_wired_only, shortcut="4"),
            ]
        ),
        ui.Button("Set Static Eth IP (10.20.30.40)", assign_static_eth, shortcut="5"),
        ui.StatusBadge("Status", st.bind("status"), tone="ok"),
    ],
)

app = ui.App("Wired Net Failover", [route_screen], state=st)
_refresh()


async def run(cv):
    await app.run_async(cv)
m5stack_core2

RS-485 DE/RE, DMX512 & CAN OBD-II (rs485_modbus_and_dmx512.py)

Download .py

Hardware DE/RE hal.rs485 Modbus RTU, ANSI E1.11 DMX512 break/MAB & filtered hal.can OBD-II decoder.

pylotos-sim examples/rs485_modbus_and_dmx512.py --board m5stack_core2 --port 8080
"""RS-485 Hardware DE/RE, DMX512 Lighting & Filtered CAN OBD-II — PylotOS Wired C HAL.

Demonstrates:
- Hardware DE/RE `hal.rs485` half-duplex UART for zero-jitter Modbus RTU & DMX512
- `hal.rs485.tx_break(92, 12)` ANSI E1.11 DMX512 break + MAB + `pylotos.wired.pack_dmx512_frame()`
- `hal.can` unified TWAI/MCP2515 API with acceptance filter (`0x7E8`, mask `0x7F8`)
- `pylotos.wired.decode_obd2_pid()` & `format_can_frame()` zero-copy reception

Run locally:
    pylotos-sim examples/rs485_modbus_and_dmx512.py --board m5stack_core2
"""

import hal
import pylotos.modbus as modbus
import pylotos.ui as ui
import pylotos.wired as wired

st = ui.State(
    dmx_ch1=180,
    dmx_ch2=96,
    dmx_frames=0,
    rtu_bytes=0,
    obd_rpm=0,
    obd_speed=0,
    last_can="---",
    status="Wired fieldbuses initialized",
)

_rx_rs485 = bytearray(64)
_rx_can = bytearray(64)


def init_buses():
    hal.rs485.open(uart=1, tx=17, rx=16, de=21, baudrate=250000, stop_bits=2, port="grove_c")
    hal.can.open("twai", tx=26, rx=36, bitrate=500000, port="grove_b")
    hal.can.set_filter(0x7E8, 0x7F8)


def send_dmx_frame():
    frame = wired.pack_dmx512_frame([int(st.dmx_ch1), int(st.dmx_ch2), 255, 64])
    hal.rs485.tx_break(92, 12)
    written = hal.rs485.write(frame, 50)
    st.dmx_frames = int(st.dmx_frames) + 1
    st.status = "DMX512 TX %d B (CH1=%d, CH2=%d)" % (written, int(st.dmx_ch1), int(st.dmx_ch2))
    app.notify("DMX512 universe refreshed", level="ok")


def poll_modbus_rtu():
    pdu = modbus.build_read_holding_pdu(0x0010, 4)
    req = modbus.build_rtu_frame(1, 0x03, pdu)
    hal.rs485.write(req, 50)
    got = hal.rs485.read_into(_rx_rs485, 20)
    st.rtu_bytes = int(st.rtu_bytes) + got
    st.status = "RS-485 Modbus RTU loopback %d B" % got


def poll_obd2_can():
    # Simulated ECU Mode 0x01 responses on 0x7E8: RPM=2450 ((0x26<<8|0x48)//4) & Speed=84 km/h
    hal.can.send(0x7E8, bytes((4, 0x41, 0x0C, 0x26, 0x48, 0, 0, 0)))
    hal.can.send(0x7E8, bytes((3, 0x41, 0x0D, 84, 0, 0, 0, 0)))
    # Non-matching CAN ID 0x123 is dropped by the 0x7E8/0x7F8 acceptance filter
    hal.can.send(0x123, bytes((1, 2, 3, 4)))

    while True:
        res = hal.can.recv_into(_rx_can, 0)
        if res is None:
            break
        aid, n, ext = res
        payload = bytes(_rx_can[:n])
        st.last_can = wired.format_can_frame(aid, payload, ext)
        if aid == 0x7E8 and n >= 4:
            dec = wired.decode_obd2_pid(payload)
            if dec["name"] == "engine_rpm":
                st.obd_rpm = dec["value"]
            elif dec["name"] == "vehicle_speed":
                st.obd_speed = dec["value"]
    st.status = "CAN OBD-II: %d rpm / %d km/h" % (int(st.obd_rpm), int(st.obd_speed))


dmx_screen = ui.Screen(
    "RS-485 & DMX512",
    [
        ui.Slider("DMX Ch1 (Warm)", st.bind("dmx_ch1"), 0, 255, step=15),
        ui.Slider("DMX Ch2 (Cool)", st.bind("dmx_ch2"), 0, 255, step=15),
        ui.Grid(
            [
                ui.Metric("DMX Frames", st.bind("dmx_frames"), accent="gold"),
                ui.Metric("RTU Bytes", st.bind("rtu_bytes"), accent="cyan"),
            ],
            cols=2,
        ),
        ui.Row(
            [
                ui.Button("Send DMX512", send_dmx_frame, shortcut="1"),
                ui.Button("Poll RTU", poll_modbus_rtu, shortcut="2"),
            ]
        ),
        ui.StatusBadge("Bus", st.bind("status"), tone="ok"),
    ],
)

can_screen = ui.Screen(
    "CAN OBD-II",
    [
        ui.Grid(
            [
                ui.Gauge("Engine RPM", st.bind("obd_rpm"), 0, 6000, unit="rpm"),
                ui.Gauge("Speed", st.bind("obd_speed"), 0, 200, unit="km/h"),
            ],
            cols=2,
        ),
        ui.KeyValue("Last Frame", st.bind("last_can")),
        ui.Button("Poll OBD-II (0x7E8 Filter)", poll_obd2_can, shortcut="3"),
    ],
)

app = ui.App("RS-485 / DMX / CAN", [dmx_screen, can_screen], state=st)
init_buses()
poll_obd2_can()


async def run(cv):
    await app.run_async(cv)