BLE GATT (NUS) ESP32-S3 Zero MicroPython FastAPI REST Paho MQTT

Building a Responsive BLE, REST, and MQTT RGB Controller with an ESP32-S3 Zero

Félix Pupo Pérez Félix Pupo Pérez
September 4, 2026
24 min read
Embedded & IoT Engineering
fpupoperez/esp32_ble_rgb_led Open Source

Companion open-source repository featuring the full MicroPython GATT firmware for the ESP32-S3 Zero, the persistent async FastAPI REST service with Bleak, the Paho MQTT-to-BLE asynchronous bridge, and an automated standard-library test suite.

MicroPython Python 3.10+ FastAPI Paho MQTT Bleak
View on GitHub

Controlling a light is a small problem with surprisingly rich engineering lessons behind it. This project turns the ESP32-S3 Zero's built-in WS2812 RGB LED into a Bluetooth Low Energy peripheral that can be controlled locally via REST or remotely through MQTT. More importantly, it keeps the control path responsive: long-running BLE discovery and connection operations are handled asynchronously, while HTTP and MQTT remain available for the next command.

This is a simple, beginner-friendly guide aimed at introducing ESP32 BLE development with small examples you can flash and run today. Each piece is kept deliberately compact so you can read the whole thing end to end. Once the basics click, the structure is easy to extend toward sensors, relays, displays, or a larger NeoPixel strip—the same BLE pattern carries over with minimal changes.

To keep things focused, this article concentrates on the code that does the actual work—the GATT peripheral logic, the FastAPI async locking, and the MQTT threadsafe coroutine scheduling. Let's dive straight into the system architecture.


01. Executive summary & system architecture

The architecture is structured around three cooperating components sharing one standardized BLE transport:

  • esp/main.py runs on the ESP32-S3 Zero. It starts a BLE GATT server at boot, receives RGB commands, updates the onboard LED on GPIO 21, and exposes the latest RGB value for reads.
  • api/main.py runs on a computer or server. It provides a FastAPI REST API that discovers, connects to, writes to, reads from, and disconnects from the ESP32 over BLE using Bleak.
  • mqtt/mqtt_control.py runs on a computer or server. It subscribes to MQTT commands, maintains a persistent BLE connection in the background, and publishes the current LED state when requested.
Component Runtime Key Technology Core Responsibility
Peripheral ESP32-S3 MicroPython bluetooth.BLE, neopixel GATT NUS server, RGB validation, GPIO 21 WS2812 PWM driving.
REST Gateway CPython 3.10+ FastAPI, Uvicorn, Bleak, Pydantic Async HTTP endpoints, connection serialization with asyncio.Lock.
MQTT Bridge CPython 3.10+ Paho MQTT, Asyncio, Bleak Threadsafe coroutine scheduling, background self-healing reconnection.
Test Client CPython Standard Lib urllib.request, json Zero-dependency end-to-end integration and smoke testing.
Project Repository Structure
├── POST.md                 Technical design documentation
├── README.md               Setup and operational reference
├── esp/
│   └── main.py             MicroPython firmware deployed to the ESP32
├── api/
│   ├── main.py             FastAPI BLE controller
│   ├── test_client.py      Standard-library smoke & integration test suite
│   └── README.md           API quick reference
└── mqtt/
    └── mqtt_control.py     MQTT-to-BLE bridge

02. The hardware: Waveshare ESP32-S3 Zero

The Waveshare ESP32-S3 Zero includes a single WS2812 RGB LED. Its data input is wired internally to GPIO 21, so there are no signal wires, resistors, or external breadboards required for the base project. Power the board through USB-C and the firmware drives the LED through that internal connection.

Waveshare ESP32-S3 Zero board with illuminated onboard WS2812 RGB LED
Waveshare ESP32-S3 Zero with Onboard WS2812 RGB LED (GPIO 21)
Internal Wiring Schematic
                 USB-C
                   │
                   │ power + serial / flashing
                   │
        ┌──────────+────────────┐
        │     ESP32-S3 Zero     │
        │                       │
        │  GPIO 21 ─────────────┼──── data ────┐
        │                       │              │
        │  3.3 V ───────────────┼──── power ───┤
        │  GND ─────────────────┼──── ground ──┤
        └───────────────────────┘              │
                                               │
                                        Onboard WS2812
                                      (one RGB NeoPixel)

The diagram describes an internal board connection, not an extra external circuit to build. If a different ESP32-S3 board is used, check its schematic and change NEOPIXEL_PIN in esp/main.py before flashing.

Real Hardware Verification

Below are real bench captures showing the physical response of the onboard WS2812 LED when issued discrete RGB commands over Bluetooth Low Energy:

ESP32-S3 LED Off State
State: OFF
RGB (0, 0, 0)
ESP32-S3 LED Red State
State: RED
RGB (255, 0, 0)
ESP32-S3 LED Green State
State: GREEN
RGB (0, 255, 0)
ESP32-S3 LED Blue State
State: BLUE
RGB (0, 0, 255)

03. Firmware design: MicroPython on ESP32-S3

The firmware is intentionally self-starting. When copied to the device as /main.py, MicroPython executes it automatically upon reset. The program initializes the BLE radio, registers the GATT service, sets the LED to a known initial state (black/off), begins advertising as S3NeoBLE, and then enters a low-overhead loop.

Why MicroPython is a great fit here

MicroPython keeps the hardware abstraction compact and direct:

  • machine.Pin configures GPIO 21 as an output pin.
  • neopixel.NeoPixel generates the timing-sensitive 800 kHz WS2812 waveform directly in hardware.
  • bluetooth.BLE exposes a low-level BLE peripheral and GATT server stack.
  • utime.sleep_ms() suspends the main loop while BLE events are dispatched asynchronously through interrupt callbacks.
  • micropython.const() optimizes numeric constants into bytecodes, eliminating heap allocation.
Important Design Note: MicroPython's BLE documentation specifies that the required _IRQ_* and _FLAG_* constants should be declared locally by the application rather than imported from bluetooth.

Dual RGB command handling: ASCII and Binary

The RX characteristic accepts two payload formats:

Supported Payload Encodings
ASCII command:   255 0 128
Binary command:  0xFF 0x00 0x80

ASCII is used by the REST and MQTT controllers because it is immediately readable in BLE sniffers, terminal logs, and serial debuggers. Binary input remains supported for constrained clients. The firmware validates ASCII ranges (0–255 per channel) before updating the LED, then writes the resulting three-byte RGB state into both the RX and TX characteristics.

04. BLE design: Nordic UART Service (NUS)

The project uses the standard Nordic UART Service (NUS) 128-bit UUID family. This is an intentional architectural choice: generic BLE mobile tools (e.g., nRF Connect, LightBlue) recognize NUS out of the box, while its RX/TX transport is general enough to carry arbitrary telemetry and actuation frames.

GATT Service & Characteristic Hierarchy
Peripheral Advertised Name: S3NeoBLE

NUS Service
└── 6e400001-b5a3-f393-e0a9-e50e24dcca9e
    ├── RX: 6e400002-b5a3-f393-e0a9-e50e24dcca9e
    │   └── Client writes RGB commands here (WRITE / WRITE_NO_RESPONSE / READ).
    └── TX: 6e400003-b5a3-f393-e0a9-e50e24dcca9e
        └── Client reads current RGB state here (READ / NOTIFY).

In conventional NUS usage, clients write to RX and receive unsolicited data streams via TX notifications. In this architecture, the TX characteristic is registered with _FLAG_READ | _FLAG_NOTIFY. This allows REST or MQTT clients to synchronously query the present LED state on demand without having to manage an asynchronous notification subscription.

05. REST control plane: FastAPI & Bleak

The REST service in api/main.py uses FastAPI for the web server and Bleak for asynchronous Bluetooth Low Energy central communications.

Why two connection modes?

The API purposefully supports two operational paradigms:

  • One-Shot Mode (POST /color): Scans for the device, opens a BLE connection, writes the color, and immediately disconnects. Useful for stateless webhooks, cron jobs, or single triggers where maintaining an open socket is unnecessary.
  • Persistent Connection Mode (POST /connect → POST /rgb): Scans and holds an open connection. Subsequent color updates execute in sub-10ms timeframes without reconnection overhead:
Persistent Connection Flow
Client ──POST /connect      ──API scans and connects to S3NeoBLE
Client ──POST /rgb          ──API writes "R G B" immediately (<10ms)
Client ──GET  /rgb          ──API reads 3-byte current color from TX handle
Client ──POST /disconnect   ──API cleanly closes BLE session

REST API Endpoints

Method Path Parameters / Body Function
GET / None Healthcheck, API status, and default UUIDs.
GET /scan timeout: float = 4.0 Scans nearby BLE devices, returns address, name, RSSI, and UUIDs.
POST /connect {"name": "S3NeoBLE"} or {"id": "..."} Establishes a persistent BLE connection protected by async lock.
GET /connection/status None Returns active connection state (connected / disconnected).
POST /rgb {"r": 255, "g": 0, "b": 128} Writes RGB color over open BLE session.
GET /rgb None Reads present 3-byte state from TX characteristic.
POST /disconnect None Releases BLE peripheral connection cleanly.
POST /color {"r": 255, "g": 0, "b": 0} One-shot scan, connect, write, and disconnect.

Automated Smoke & Integration Testing

The project includes api/test_client.py, written strictly using Python's standard library (urllib.request). It exercises all endpoints sequentially:

Executing the Test Suite
python3 api/test_client.py

The test client verifies device discovery, connects to S3NeoBLE, verifies connected status, sets the LED to pure red (255, 0, 0), turns it off (0, 0, 0), reads back the status, and cleanly disconnects. Every assertion reports PASS/FAIL and exits non-zero if an error occurs.

06. MQTT control plane: Asynchronous bridge

The MQTT bridge in mqtt/mqtt_control.py adapts the BLE peripheral to an enterprise publish/subscribe event plane, enabling integration with Home Assistant, Node-RED, industrial message brokers, or distributed microservices.

Speaking MQTT means the light can be wired into larger automation platforms without writing any BLE code. Home Assistant can subscribe to the bridge's topics and control the LED from its dashboard, automations, or voice assistants, while Node-RED can route the same topics through flows that react to timers, sensors, or other events. Both are open-source, self-hosted solutions that connect to an MQTT broker directly, so the bridge itself is the only piece this project adds.

Threadsafe Asyncio Event Loop Bridging

A common pitfall in Python IoT systems is attempting to execute long-running or async BLE operations directly inside the Paho MQTT network thread callback (on_message). Doing so blocks Paho's internal socket loop, causing broker heartbeat timeouts and dropped packets.

The bridge decouples these concerns completely:

Threadsafe Coroutine Dispatch
def _schedule(self, coroutine):
    future = asyncio.run_coroutine_threadsafe(coroutine, self.loop)
    future.add_done_callback(report_result)

When an MQTT message arrives on led/control, Paho immediately delegates the work to the running asyncio loop via asyncio.run_coroutine_threadsafe and resumes processing network packets.

MQTT Payload Flexibility

The bridge accepts multiple JSON formats on led/control:

Accepted Command Formats
// Direct RGB
{"r": 255, "g": 0, "b": 128}

// Object color
{"color": {"r": 255, "g": 0, "b": 128}}

// Array color
{"color": [255, 0, 128]}

// Convenience state strings
{"state": "on"}   // Sets (255, 255, 255)
{"state": "off"}  // Sets (0, 0, 0)

// Query status
{"command": "status"}

When issued {"command": "status"}, the bridge reads the BLE TX characteristic asynchronously and publishes the result to led/status:

Published Status Output
{"status": "ok", "color": {"r": 255, "g": 0, "b": 128}}

07. Complete code walkthrough: MicroPython firmware

Source file: esp/main.py

Step 1: Imports, Constants, and Pin Definitions

Sets up imports and defines local BLE constants to avoid relying on unexported symbols from bluetooth.

esp/main.py — Configuration & Constants
import utime
from bluetooth import BLE, UUID
from machine import Pin
from micropython import const
from neopixel import NeoPixel

# BLE event codes defined locally per MicroPython specification
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)

# GATT Characteristic permission flags
_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)

# ESP32-S3 Zero hardware definitions
NEOPIXEL_PIN = const(21)
LED_COUNT = const(1)
ADV_INTERVAL_US = const(100_000)  # 100 ms advertising cadence

DEVICE_NAME = "S3NeoBLE"
SERVICE_UUID = UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
CHARACTERISTIC_UUID = UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")  # RX
TX_CHARACTERISTIC_UUID = UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")  # TX

CHAR_FLAGS = _FLAG_READ | _FLAG_WRITE | _FLAG_WRITE_NO_RESPONSE

Step 2: Advertising Payload & NeoPixel Driver

Constructs raw BLE Type-Length-Value (TLV) advertising packets containing flags, the 128-bit service UUID, and the local device name.

esp/main.py — Advertising & LED Output
def _advertising_payload(name, service_uuid):
    payload = bytearray()
    flags = b""
    payload.extend(bytes((len(flags) + 1, 0x01)) + flags)

    service = bytes(service_uuid)
    payload.extend(bytes((len(service) + 1, 0x07)) + service)

    encoded_name = name.encode()
    payload.extend(bytes((len(encoded_name) + 1, 0x09)) + encoded_name)
    return payload

neo = NeoPixel(Pin(NEOPIXEL_PIN, Pin.OUT), LED_COUNT)

def set_led_color(r, g, b):
    neo[0] = (r, g, b)
    neo.write()

Step 3: BLEServer Initialization & Service Registration

Registers NUS services and acquires characteristic value handles.

esp/main.py — BLEServer Class
class BLEServer:
    def __init__(self):
        self.ble = BLE()
        self.connected = False
        self.connection_handle = None
        self.current_color = (0, 0, 0)

        self.ble.active(True)
        self.ble.irq(self._irq)

        service = (
            SERVICE_UUID,
            (
                (TX_CHARACTERISTIC_UUID, _FLAG_READ | _FLAG_NOTIFY),
                (CHARACTERISTIC_UUID, CHAR_FLAGS),
            ),
        )
        ((self.handle_tx, self.handle_rgb),) = self.ble.gatts_register_services((service,))

        self._set_color(0, 0, 0)
        self.start_advertising()

Step 4: State Synchronization & Dual Parser

Safely handles ASCII strings (e.g. "255 128 0") and 3-byte binary frames while rejecting malformed inputs.

esp/main.py — Parsing & State Updates
    def _set_color(self, r, g, b):
        self.current_color = (r, g, b)
        set_led_color(r, g, b)
        value = bytes((r, g, b))
        self.ble.gatts_write(self.handle_rgb, value)
        self.ble.gatts_write(self.handle_tx, value)

    def _parse_color(self, value):
        try:
            if b" " in value or b"	" in value or b"
" in value:
                parts = value.decode().strip().split()
                if len(parts) != 3:
                    return None
                red, green, blue = (int(part) for part in parts)
                if not (0 <= red <= 255 and 0 <= green <= 255 and 0 <= blue <= 255):
                    return None
                return red, green, blue
        except (ValueError, UnicodeError):
            return None

        if len(value) == 3:
            return value[0], value[1], value[2]
        return None

Step 5: IRQ Dispatch, Advertising, and Execution Loop

esp/main.py — IRQ Callback & Main Loop
    def _irq(self, event, data):
        if event == _IRQ_CENTRAL_CONNECT:
            self.connection_handle = data[0]
            self.connected = True
        elif event == _IRQ_CENTRAL_DISCONNECT:
            self.connection_handle = None
            self.connected = False
            self.start_advertising()
        elif event == _IRQ_GATTS_WRITE:
            _conn_handle, attr_handle = data
            if attr_handle != self.handle_rgb:
                return
            color = self._parse_color(self.ble.gatts_read(self.handle_rgb))
            if color is not None:
                self._set_color(*color)

    def start_advertising(self):
        adv_data = _advertising_payload(DEVICE_NAME, SERVICE_UUID)
        self.ble.gap_advertise(ADV_INTERVAL_US, adv_data=adv_data)

    def close(self):
        self.ble.gap_advertise(None)
        self.ble.active(False)

def main():
    server = BLEServer()
    try:
        while True:
            utime.sleep_ms(500)
    finally:
        server.close()

main()

08. Complete code walkthrough: FastAPI REST controller

Source file: api/main.py

Step 1: Lifespan Manager & Pydantic Schemas

Validates input payloads, defines UUID constants, and manages startup/shutdown hooks using FastAPI's modern async lifespan context.

api/main.py — Models & Lifespan
import asyncio
from contextlib import asynccontextmanager
from typing import Optional
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from bleak import BleakScanner, BleakClient

TARGET_NAMES = ["S3NeoBLE", "MPY ESP32"]
SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
CHAR_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
STATUS_CHAR_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"

class ConnectRequest(BaseModel):
    name: Optional[str] = Field(None)
    id: Optional[str] = Field(None)
    service_uuid: str = Field(SERVICE_UUID)
    char_uuid: str = Field(CHAR_UUID)

class RGBColor(BaseModel):
    r: int = Field(..., ge=0, le=255)
    g: int = Field(..., ge=0, le=255)
    b: int = Field(..., ge=0, le=255)

connected_client: Optional[BleakClient] = None
connected_device = None
connected_char_uuid = CHAR_UUID
connected_status_uuid = STATUS_CHAR_UUID
connection_lock = asyncio.Lock()

async def _close_connected_client() -> None:
    global connected_client, connected_device
    if connected_client is not None:
        try:
            if connected_client.is_connected:
                await connected_client.disconnect()
        finally:
            connected_client = None
            connected_device = None

@asynccontextmanager
async def lifespan(_: FastAPI):
    yield
    async with connection_lock:
        await _close_connected_client()

app = FastAPI(title="ESP32-S3 BLE NeoPixel Controller", lifespan=lifespan)

Step 2: Scanner & Persistent Connection Engine

Scans for target peripherals and maintains a single persistent BleakClient guarded by connection_lock.

api/main.py — Discovery & Connect Endpoints
async def _find_device(selector: ConnectRequest):
    discovered = await BleakScanner.discover(timeout=5.0, return_adv=True)
    wanted_id = selector.id.casefold() if selector.id else None
    wanted_name = selector.name.casefold() if selector.name else None

    for device, adv in discovered.values():
        name = adv.local_name or device.name
        if wanted_id and str(device.address).casefold() == wanted_id:
            return device
        if wanted_name and name and name.casefold() == wanted_name:
            return device
    return None

@app.get("/scan")
async def scan_devices(timeout: float = 4.0):
    discovered = await BleakScanner.discover(timeout=timeout, return_adv=True)
    results = [
        {
            "address": device.address,
            "name": adv.local_name or device.name,
            "rssi": adv.rssi,
            "service_uuids": adv.service_uuids,
        }
        for device, adv in discovered.values()
    ]
    return {"device_count": len(results), "devices": results}

@app.post("/connect")
async def connect_device(request: ConnectRequest):
    if not request.name and not request.id:
        raise HTTPException(status_code=422, detail="Provide either 'name' or 'id'.")
    if request.name and request.id:
        raise HTTPException(status_code=422, detail="Provide only one of 'name' or 'id'.")

    global connected_client, connected_device
    async with connection_lock:
        target = await _find_device(request)
        if not target:
            raise HTTPException(status_code=404, detail="Target BLE device not found.")
        await _close_connected_client()
        client = BleakClient(target.address, timeout=10.0)
        await client.connect()
        connected_client = client
        connected_device = target
        return {"status": "connected", "address": target.address}

Step 3: Fast RGB Writing, Status Reading & Cleanup

api/main.py — Actuation & Telemetry Endpoints
@app.post("/rgb")
async def send_rgb(color: RGBColor):
    async with connection_lock:
        if connected_client is None or not connected_client.is_connected:
            raise HTTPException(status_code=409, detail="No active BLE connection.")
        payload = f"{color.r} {color.g} {color.b}".encode("utf-8")
        await connected_client.write_gatt_char(connected_char_uuid, payload)
        return {"status": "sent", "color": color.model_dump()}

@app.get("/rgb")
async def get_rgb():
    async with connection_lock:
        if connected_client is None or not connected_client.is_connected:
            raise HTTPException(status_code=409, detail="No active BLE connection.")
        raw = await connected_client.read_gatt_char(connected_status_uuid)
        if len(raw) != 3:
            raise HTTPException(status_code=502, detail="Invalid status length from device.")
        return {"status": "ok", "color": {"r": raw[0], "g": raw[1], "b": raw[2]}}

@app.post("/disconnect")
async def disconnect_device():
    async with connection_lock:
        await _close_connected_client()
        return {"status": "disconnected"}

09. Complete code walkthrough: MQTT bridge

Source file: mqtt/mqtt_control.py

Step 1: BLEController with Auto-Reconnection

Maintains an active BLE link in the background and transparently retries failed writes once before erroring.

mqtt/mqtt_control.py — BLEController
import asyncio
import logging
from typing import Optional, Dict, Any
from bleak import BleakScanner, BleakClient

DEFAULT_TARGET_NAMES = ["S3NeoBLE", "MPY ESP32"]
DEFAULT_SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
DEFAULT_CHAR_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
DEFAULT_STATUS_CHAR_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"

class BLEController:
    def __init__(self):
        self.client: Optional[BleakClient] = None
        self._connection_lock = asyncio.Lock()
        self._write_lock = asyncio.Lock()
        self._stop_event = asyncio.Event()

    async def maintain_connection(self):
        while not self._stop_event.is_set():
            if self.client is None or not self.client.is_connected:
                await self.connect()
            await asyncio.sleep(2.0)

    async def send_color(self, r: int, g: int, b: int, **kwargs) -> bool:
        async with self._write_lock:
            payload = f"{r} {g} {b}".encode("utf-8")
            char_uuid = kwargs.get("char_uuid", DEFAULT_CHAR_UUID)
            for attempt in range(2):
                if self.client and self.client.is_connected:
                    try:
                        await self.client.write_gatt_char(char_uuid, payload)
                        return True
                    except Exception:
                        await self.disconnect()
                await self.connect()
            return False

Step 2: Paho MQTT Integration & Event Loop Bridging

Connects to the broker and uses asyncio.run_coroutine_threadsafe to bridge network callbacks to the async engine.

mqtt/mqtt_control.py — MqttControl
import json
import paho.mqtt.client as mqtt

class MqttControl:
    def __init__(self, device_id="esp32_mqtt_bridge", loop=None, ble_controller=None,
                 status_topic="led/status"):
        self.loop = loop
        self.ble_controller = ble_controller or BLEController()
        self.status_topic = status_topic
        self.mqtt_client = mqtt.Client(client_id=device_id)
        self.mqtt_client.on_connect = self.on_connect
        self.mqtt_client.on_message = self.on_message

    def on_connect(self, client, userdata, flags, rc, properties=None):
        logger.info("Connected to MQTT Broker successfully.")

    def on_message(self, client, userdata, msg):
        try:
            data = json.loads(msg.payload.decode("utf-8"))
            if str(data.get("command", "")).lower() in ("status", "get_status"):
                self._schedule(self._read_and_publish_status())
                return
            r, g, b = parse_rgb_channels(data)
            self._schedule(self.ble_controller.send_color(r, g, b))
        except Exception as exc:
            logger.error(f"Payload processing error: {exc}")

    def _schedule(self, coroutine):
        future = asyncio.run_coroutine_threadsafe(coroutine, self.loop)
        future.add_done_callback(lambda f: f.exception() and logger.error(f"Task failed: {f.exception()}"))

    async def _read_and_publish_status(self):
        color = await self.ble_controller.read_color()
        payload = {"status": "ok", "color": color} if color else {"status": "error"}
        self.mqtt_client.publish(self.status_topic, json.dumps(payload))

10. Installation, firmware flashing, and setup

Deploying the complete control plane requires three simple terminal steps:

Step 1: Flashing MicroPython Firmware with ampy

[ampy](https://pypi.org/project/adafruit-ampy/) (Adafruit MicroPython Tool) copies files directly to the board's flash over serial. Install ampy and flash esp/main.py:

Terminal — Ampy Installation & Firmware Upload
# Install Adafruit Ampy
python3 -m pip install --user adafruit-ampy

# On macOS (check /dev/cu.usbmodem*):
ampy --port /dev/cu.usbmodem1234 put esp/main.py /main.py

# Or export AMPY_PORT once:
export AMPY_PORT=/dev/cu.usbmodem1234
ampy put esp/main.py /main.py

Reset the board. The serial console prints Advertising as S3NeoBLE.

Step 2: Starting the FastAPI REST API

Terminal — REST Dependencies & Uvicorn Startup
# Install host dependencies
python3 -m pip install fastapi uvicorn bleak pydantic

# Run the API server
python3 -m uvicorn api.main:app --host 0.0.0.0 --port 8000

Interactive Swagger docs are immediately accessible at http://localhost:8000/docs.

Step 3: Starting the MQTT Bridge

Terminal — Paho MQTT & Bridge Launch
# Install Paho MQTT client
python3 -m pip install paho-mqtt

# Launch the bridge with custom broker parameters
python3 mqtt/mqtt_control.py   --broker localhost   --port 1883   --topic led/control   --status-topic led/status

11. End-to-end operational flow

The diagram below illustrates the unified control flow across both HTTP clients and MQTT event subscribers:

System Dataflow Architecture
                REST client                         MQTT publisher
                    │                                     │
                    │ HTTP POST /rgb                      │ JSON {"r":255,"g":0,"b":128}
                    │                                     │
            FastAPI + Bleak                         Paho + asyncio
                    │                                     │
                    └──────────── BLE central ────────────┘
                                      │
                                      │ Nordic UART Service (NUS)
                                      │
                          ESP32-S3 Zero / MicroPython
                                      │
                                      │
                              GPIO 21 → WS2812 LED
                            (One-Pixel NeoPixel Bus)

12. Security & production considerations

While this architecture is designed for local development and edge deployments, moving it into an enterprise production environment requires additional hardening:

  • MQTT Authentication & TLS: Encrypt broker traffic over port 8883 using mTLS or username/token authentication.
  • API Reverse Proxy & Bearer Tokens: Place FastAPI behind Nginx, Caddy, or Envoy with JWT/API-key validation.
  • BLE Bonding & Whitelisting: In high-density office environments, configure BLE PIN passkeys or whitelist central MAC addresses to prevent unauthorized actuation.
  • Hardware Watchdog: Enable MicroPython's machine.WDT to recover the MCU automatically if an unexpected heap fragmentation occurs.
  • Connection Exclusivity: Since BLE peripherals generally allow only one active central GATT connection at a time, enforce coordinator rules between the REST API and MQTT bridge.

13. Conclusion & extensible architecture

Controlling an onboard RGB LED proves the entire IoT control loop: a physical transducer, an efficient BLE GATT peripheral, a modern asynchronous REST interface, and an event-driven message queue all communicating over a shared, reusable contract.

The beauty of this design lies in its extensibility. Swap out the WS2812 driver for:

  • An optocoupled 230V solid-state relay,
  • A high-torque stepper motor or servo driver,
  • An industrial sensor reading analog voltages or 4–20 mA current loops,
  • An OLED / e-Paper display status badge.

The underlying BLE transport, FastAPI lock serialization, and MQTT threadsafe bridges remain completely identical.

14. Datasheets & official documentation

15. License & companion repository

All firmware, API gateways, MQTT bridges, and testing scripts are released under the open-source MIT License. You can clone the companion repository, inspect the tests, and adapt it for your embedded projects: