### Initialize and Use MQTT Bridge Source: https://context7.com/meshtastic/firmware/llms.txt MQTT is initialized in setup() via mqttInit(). Configuration is managed via moduleConfig.mqtt. Use onSend() to publish packets and publish() for custom topics. Check connection status with isConnectedDirectly() and trigger reconnects with start(). ```cpp // MQTT is initialized in setup() via mqttInit() // Configuration is in moduleConfig.mqtt (set via phone app or admin RPC) // Default broker credentials (from Default.h) // address: "mqtt.meshtastic.org" // username: "meshdev" // password: "large4cats" // root: "msh" // Topic format: msh/2/e// // JSON topic: msh/2/json// // Map topic: msh/2/map/ // Publish a packet to the broker (called automatically by MeshService on tx) mqtt->onSend(encryptedPacket, decodedPacket, channelIndex); // Manually publish a custom topic bool published = mqtt->publish( "msh/2/json/LongFast/!ab3c1234", R"({\"from\":2872709684,\"type\":\"text\",\"payload\":\"hello\"})", /*retained=*/false ); // Check connection status if (mqtt->isConnectedDirectly()) { LOG_INFO("MQTT connected to %s", default_mqtt_address); } // Check if map reporting is active (publishes node location to meshtastic.liamcottle.net map) if (moduleConfig.mqtt.map_reporting_enabled) { LOG_INFO("Reporting to map every %us", moduleConfig.mqtt.map_publish_interval_secs); } // Trigger immediate reconnect / re-subscribe mqtt->start(); ``` -------------------------------- ### Build Native macOS Host Binary Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Builds the native macOS host binary. Ensure Homebrew is installed and CH341 LoRa setup is configured in `variants/native/portduino/platformio.ini`. ```bash pio run -e native-macos ``` -------------------------------- ### Meshtastic Firmware Setup Sequence Source: https://context7.com/meshtastic/firmware/llms.txt Illustrative C++ code showing the initialization sequence within the `setup()` function in `src/main.cpp`. This sequence initializes various subsystems in a specific order. ```cpp // src/main.cpp (illustrative sequence, not a direct call) void setup() { powerHAL_init(); // Init power HAL; gate on low-battery check waitUntilPowerLevelSafe(); // Block boot if battery is dangerously low (blink LED x3) earlyInitVariant(); // Board-specific early GPIO (defined per-variant) OSThread::setup(); // Prepare cooperative thread scheduler fsInit(); // Mount LittleFS / SPIFFS power = new Power(); // Power management (PMU, charge detection) power->setup(); // Auto-detect I2C devices: screen, RTC, accelerometer, keyboards, sensors auto i2cScanner = std::unique_ptr(new ScanI2CTwoWire()); i2cScanner->scanPort(ScanI2C::I2CPort::WIRE); nodeDB = new NodeDB; // Load device state, config, node list from flash router = new ReliableRouter(); // Packet router with ACK/NAK reliable delivery gps = GPS::createGps(); // Create GPS thread (probes for NMEA chip on UART) gpsStatus->observe(&gps->newStatus); service = new MeshService(); // Central hub: BLE/serial phone API ↔ router service->init(); setupModules(); // Instantiate all enabled feature modules auto rIf = initLoRa(); // Bring up RadioLib LoRa interface router->addInterface(std::move(rIf)); mqttInit(); // Start MQTT bridge if configured initWifi(); // Connect WiFi (ESP32 only) PowerFSM_setup(); // Power finite-state machine (ON/DARK/NB/SLEEP) } ``` -------------------------------- ### Install Meshtastic MCP Server Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Install the Meshtastic MCP Server and its dependencies using Python's virtual environment and pip. Ensure PlatformIO Core is installed and accessible. ```bash cd /mcp-server python3 -m venv .venv .venv/bin/pip install -e . ``` -------------------------------- ### Install UI Tier Extras Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Install the necessary Python extras for the UI test tier. This includes dependencies like opencv-python-headless, numpy, easyocr, and Pillow. ```bash pip install -e 'mcp-server/.[ui]' ``` -------------------------------- ### Install MCP Server Dependencies Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Installs the necessary Python dependencies for the MCP server, including testing dependencies. This command should be run from the `mcp-server/` directory. ```bash cd mcp-server && python3 -m venv .venv && .venv/bin/pip install -e '.[test]' ``` -------------------------------- ### Install and Configure MCP Server Source: https://context7.com/meshtastic/firmware/llms.txt Install the MCP server using pip and register it in ~/.claude/settings.json. Set the MESHTASTIC_FIRMWARE_ROOT environment variable. The server is typically run via Claude Code, not directly. ```bash # Install MCP server cd mcp-server python3 -m venv .venv .venv/bin/pip install -e '.[test]' # Set firmware root (auto-detected from cwd if omitted) export MESHTASTIC_FIRMWARE_ROOT=/path/to/firmware # Verify server starts (blocks on stdin — use via Claude Code, not directly) .venv/bin/python -m meshtastic_mcp ``` -------------------------------- ### Install Native Build System Dependencies Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Install essential system libraries required for the native build on Ubuntu/Debian systems. Ensure these are installed before attempting to build or run native tests. ```bash sudo apt-get install -y \ libbluetooth-dev libgpiod-dev libyaml-cpp-dev openssl libssl-dev \ libulfius-dev liborcania-dev libusb-1.0-0-dev libi2c-dev libuv1-dev ``` -------------------------------- ### Build Meshtastic Firmware with PlatformIO Source: https://context7.com/meshtastic/firmware/llms.txt Use PlatformIO CLI to install, build, clean, and flash the Meshtastic firmware for various hardware targets. Ensure PlatformIO is installed via pip. ```bash pip install platformio ``` ```bash pio run -e rak4631 ``` ```bash pio run -e heltec-v3 ``` ```bash pio run -e heltec-v3 -t clean && pio run -e heltec-v3 ``` ```bash pio run -e heltec-v3 -t upload --upload-port /dev/ttyUSB0 ``` ```bash pio test -e native ``` ```bash pio run -e native-macos ``` ```bash ~/.meshtasticd/meshtasticd ``` -------------------------------- ### Install Meshtastic UI Tier Extras Source: https://context7.com/meshtastic/firmware/llms.txt Installs optional extras for the UI tier of the Meshtastic hardware tests, including camera and OCR support for OLED screen validation. Sets the camera device index. ```bash pip install -e 'mcp-server/.[ui]' export MESHTASTIC_UI_CAMERA_DEVICE_ESP32S3=0 # USB webcam index aimed at OLED ./mcp-server/run-tests.sh tests/ui -v ``` -------------------------------- ### Setup NicheGraphics E-Ink Driver Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/Drivers/EInk/README.md Demonstrates how to initialize the SPI interface and the E-Ink driver for a specific display model. Ensure SPI pins and driver-specific pins (DC, CS, BUSY) are correctly defined. ```cpp void setupNicheGraphics() { using namespace NicheGraphics; // An imaginary UI YourCustomUI *yourUI = new YourCustomUI(); // Setup SPI SPIClass *hspi = new SPIClass(HSPI); hspi->begin(PIN_EINK_SCLK, -1, PIN_EINK_MOSI, PIN_EINK_CS); // Setup EInk driver Drivers::EInk *driver = new Drivers::DEPG0290BNS800; driver->begin(hspi, PIN_EINK_DC, PIN_EINK_CS, PIN_EINK_BUSY); // Pass the driver to your UI YourUI::driver = driver; } ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Install the Meshtastic MCP server with test dependencies. This command ensures all necessary packages for running the test suite are available. ```bash cd mcp-server pip install -e ".[test]" ``` -------------------------------- ### Verify Meshtastic MCP Server Installation Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Verify the installation by running the Meshtastic MCP server module. The server will block on stdin, indicating it's ready to receive MCP commands. Press Ctrl-C to exit. ```bash MESHTASTIC_FIRMWARE_ROOT= .venv/bin/python -m meshtastic_mcp ``` -------------------------------- ### Delete Persisted State Files in setUp Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md To prevent filesystem state from leaking between tests, delete relevant state files at the start of the setUp() function. This ensures each test begins with a clean state. ```cpp void setUp(void) { // ... #ifdef FSCom FSCom.remove("/prefs/your_module.bin"); #endif } ``` -------------------------------- ### Example Metadata Structure in YAML Source: https://github.com/meshtastic/firmware/blob/develop/bin/config.d/README.md Illustrates the 'Meta' section within a meshtasticd configuration file, defining the configuration's name, support level, and compatible platforms. ```yaml Meta: name: MeshAdv-Pi E22-900M30S # A unique identifier for this configuration. support: community # community, official, or deprecated; determined by Meshtastic Leads. compatible: # A list of compatible products or platforms. - raspberry-pi ``` -------------------------------- ### Run Specific Test File Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Execute a single test file, for example, 'test_traceroute.py' within the 'mesh' directory. This allows for highly focused testing. ```bash ./mcp-server/run-tests.sh tests/mesh/test_traceroute.py ``` -------------------------------- ### Representative MCP Tool Calls Source: https://context7.com/meshtastic/firmware/llms.txt Examples of MCP tool calls for device discovery, build/flash operations, and serial session management. These are typically used by AI agents and not called directly. ```python # Representative MCP tool calls (used by Claude Code / agents, not called directly) # Discovery list_devices() # → [{"port": "/dev/ttyACM0", "vid": "0x239A", "likely_meshtastic": True, "role": "nrf52"}] list_boards(arch="esp32s3", level="supported") # → [{"env": "heltec-v3", "custom_meshtastic_variant": "heltec_v3", ...}, ...] # Build and flash build(env="heltec-v3") # → {"returncode": 0, "stdout": "...", "firmware": ".pio/build/heltec-v3/firmware.bin"} pio_flash(env="heltec-v3", port="/dev/ttyUSB0", confirm=True) # → {"returncode": 0, "stdout": "Uploading..."} erase_and_flash(env="heltec-v3", port="/dev/ttyUSB0", confirm=True) # Factory erase + flash for ESP32 # Serial log session session = serial_open(port="/dev/ttyUSB0", env="heltec-v3") ``` -------------------------------- ### Force Device Rebake Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Force a complete re-bake of devices at the start of the test session. Use this when firmware, seeds, or profiles have changed. ```bash pytest tests/ --force-bake --html=report.html ``` -------------------------------- ### Manage Global Singleton Lifecycle in Tests Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Manage the global pointer for modules during test setup and teardown. Ensure the pointer is nullified in tearDown to prevent dangling pointers between tests. ```cpp void setUp(void) { // ... setup ... } void tearDown(void) { yourModule = nullptr; // prevent dangling pointer between tests } void test_something() { auto shim = std::unique_ptr(new YourModuleTestShim()); yourModule = shim.get(); // ... test ... yourModule = nullptr; } ``` -------------------------------- ### Build Firmware Variant Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Use this command to build a specific firmware variant for a target environment. Replace `` with the desired environment name. ```bash pio run -e ``` -------------------------------- ### Run Full Test Suite with Force Bake Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Run the entire test suite, forcing a re-bake of devices if issues arise. This is useful for mesh formation timeouts or provisioning errors. ```bash pytest tests/ --force-bake ``` -------------------------------- ### Run Native Firmware Unit Tests Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Executes the native firmware unit tests. This command is used for testing the firmware on the host machine. ```bash pio test -e native ``` -------------------------------- ### Get Meshtastic Device Information Source: https://context7.com/meshtastic/firmware/llms.txt Retrieves information about a Meshtastic device. Ensure no active serial session is running for the specified port. ```python info = device_info(port="/dev/ttyUSB0") # → {"my_node_num": 2872709684, "long_name": "Base Node", "firmware_version": "2.7.23", ...} ``` -------------------------------- ### Run Simulator Integration Check Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Perform a simulator integration check by first building the native environment and then running the simulator script. This ensures compatibility between native components and the simulator. ```bash pio run -e native && ./bin/test-simulator.sh ``` -------------------------------- ### Control Jitter for Deterministic Tests Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Add a static enable/disable flag for randomness or jitter in the module. Disable it in test setUp() and re-enable it in tearDown() to ensure reproducible test results. ```cpp // Module header: static void setJitter(bool enabled) { s_jitterEnabled = enabled; } // Test setUp: YourModule::setJitter(false); // Test tearDown: YourModule::setJitter(true); ``` -------------------------------- ### Run Hardware Test Suite with Force Flash Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Run the hardware test suite, forcing a reflash of the connected devices before testing begins. Use this when you need to ensure a clean firmware state. ```bash ./mcp-server/run-tests.sh --force-bake ``` -------------------------------- ### MockNodeDB for Test Node Injection Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md A mock implementation of NodeDB used in tests to inject nodes with controlled hop distances and ages. Set `nodeDB = mockNodeDB;` in `setUp()` to use it. ```cpp class MockNodeDB : public NodeDB { public: void clearTestNodes() { testNodes.clear(); numMeshNodes = 0; } void addTestNode(NodeNum num, uint8_t hopsAway, bool hasHops, uint32_t ageSecs, bool viaMqtt = false) { meshtastic_NodeInfoLite node = meshtastic_NodeInfoLite_init_zero; node.num = num; node.has_hops_away = hasHops; node.hops_away = hopsAway; node.via_mqtt = viaMqtt; node.last_heard = getTime() - ageSecs; testNodes.push_back(node); meshNodes = &testNodes; numMeshNodes = testNodes.size(); } std::vector testNodes; }; static MockNodeDB *mockNodeDB = nullptr; ``` -------------------------------- ### Build Native Release Artifact Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Compile a release-ready artifact for the native environment and place it in the ./release/ directory. This is typically used for deployment or distribution. ```bash ./bin/build-native.sh native ``` -------------------------------- ### Run Tests with Pytest Name Filter Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Execute tests that match a specific keyword using pytest's name filtering. This example filters for tests related to 'telemetry'. ```bash ./mcp-server/run-tests.sh -k telemetry ``` -------------------------------- ### Run All Native Tests Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Execute all defined test suites in the native environment using PlatformIO. Use `-f` to specify a single test suite. ```bash pio test -e native ``` ```bash pio test -e native -f test_your_module ``` ```bash pio test -e native -f test_your_module -vvv ``` -------------------------------- ### Run All Tests with HTML Report Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Execute all tests, including hardware-dependent ones, and generate an HTML report. The first run will bake the devices; subsequent runs can skip this if the `--assume-baked` flag is used. ```bash pytest tests/ --html=report.html ``` -------------------------------- ### Build and Run Meshtastic Daemon via TCP Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Builds a headless meshtasticd binary for the host and runs it. Point the MCP server at this daemon using the MESHTASTIC_MCP_TCP_HOST environment variable. ```bash # 1. Build + run a daemon on this host (see variants/native/portduino/platformio.ini # for full Homebrew prereqs and CH341 LoRa-adapter setup). pio run -e native-macos ~/.meshtasticd/meshtasticd ``` ```bash # 2. Point the MCP server at it. export MESHTASTIC_MCP_TCP_HOST=localhost # or host:port, default port 4403 ``` -------------------------------- ### Request Display Updates Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md Call `requestUpdate()` when your applet has new information to display. This method signals InkHUD to redraw the screen. The example shows requesting an update when a new text message is received. ```cpp // We configured the Module API to call this method when we receive a new text message ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_MeshPacket &mp) { // Abort if applet fully deactivated // Don't waste time: we wouldn't be rendered anyway if (!isActive()) return ProcessMessage::CONTINUE; // Check that this is an incoming message // Outgoing messages (sent by us) will also call handleReceived if (!isFromUs(&mp)) { // Store the sender's nodenum // We need to keep this information, so we can re-use it anytime render() is called haveMessage = true; fromWho = mp.from; // Tell InkHUD that we have something new to show on the screen requestUpdate(); } // Tell Module API to continue informing other firmware components about this message // We're not the only component which is interested in new text messages return ProcessMessage::CONTINUE; } ``` -------------------------------- ### Build and Run Meshtasticd Natively Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Build and execute the meshtasticd application directly on the host machine. This is useful for local development and debugging. ```bash ./bin/native-run.sh ``` -------------------------------- ### E-Ink Image Data Formatting and Pixel Manipulation Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/Drivers/EInk/README.md Illustrates how to format image data for the E-Ink display and set individual pixels. The image data is a 1-bit format where X-pixels are 8-per-byte, with the MSB representing the leftmost pixel. This example shows manual bit manipulation for setting pixels. ```cpp uint16_t w = driver::width(); uint16_t h = driver::height(); uint8_t image[ (w/8) * h ]; // X pixels are 8-per-byte image[0] |= (1 << 7); // Set pixel x=0, y=0 image[0] |= (1 << 0); // Set pixel x=7, y=0 image[1] |= (1 << 7); // Set pixel x=8, y=0 uint8_t x = 12; uint8_t y = 2; uint8_t yBytes = y * (w/8); uint8_t xBytes = x / 8; uint8_t xBits = (7-x) % 8; image[yByte + xByte] |= (1 << xBits); // Set pixel x=12, y=2 ``` -------------------------------- ### Manage Channels with Channels Singleton Source: https://context7.com/meshtastic/firmware/llms.txt Manages the channel table, PSK-to-hash mapping, and active crypto key selection. Use `setActiveByIndex` to activate a channel for sending. ```cpp // Get the primary channel settings const meshtastic_ChannelSettings &primary = channels.getPrimary(); LOG_INFO("Primary channel: %s", channels.getName(channels.getPrimaryIndex())); // Activate a channel for sending (sets crypto key from channel PSK) ChannelIndex chIdx = 0; int16_t hash = channels.setActiveByIndex(chIdx); if (hash < 0) { LOG_ERROR("Channel %d is disabled", chIdx); } // Select decryption key for an incoming packet's channel hash bool found = channels.decryptForHash(chIdx, incomingPacket.channel); // Check if any channel has MQTT uplink/downlink enabled if (channels.anyMqttEnabled()) { LOG_DEBUG("MQTT bridge active"); } // Check if this node can be reached via the public default mesh if (channels.hasDefaultChannel()) { LOG_INFO("Node is reachable on the default public channel"); } ``` -------------------------------- ### Run Bake Test Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Execute the bake test to ensure devices are properly prepared before running other tests. Use --force-bake to re-bake if necessary. ```bash pytest tests/test_00_bake.py ``` -------------------------------- ### Implement Applet Rendering Logic Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md The `onRender` method is where all drawing operations occur. Use `printAt` to display text at specific coordinates. Ensure drawing is relative to the applet's size for scalability. ```cpp // All drawing happens here // Our basic example doesn't do anything useful. It just passively prints some text. void InkHUD::BasicExampleApplet::onRender(bool full) { printAt(0, 0, "Hello, world!"); } ``` -------------------------------- ### Run Hardware Test Suite Assuming Baked Devices Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Execute the hardware test suite without reflashing devices. This option assumes the devices are already in the correct baked state. ```bash ./mcp-server/run-tests.sh --assume-baked ``` -------------------------------- ### Run UI Test Tier with Verbosity Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Execute the UI test tier with verbose output enabled. This command also assumes the necessary camera environment variable has been exported. ```bash ./run-tests.sh tests/ui -v ``` -------------------------------- ### Clean and Rebuild Firmware Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Performs a clean build of the firmware for a specified environment. This command first cleans the build artifacts and then rebuilds the firmware. ```bash pio run -e -t clean && pio run -e ``` -------------------------------- ### Run Live TUI Meshtastic Test Runner Source: https://context7.com/meshtastic/firmware/llms.txt Launches the live Textual-based User Interface (TUI) test runner for Meshtastic hardware tests, targeting the 'mesh' tier. ```bash .venv/bin/meshtastic-mcp-test-tui tests/mesh ``` -------------------------------- ### Format Code Before Commit Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Formats the codebase according to project conventions. This command should be run before committing changes. ```bash trunk fmt ``` -------------------------------- ### Run Tests Assuming Devices are Baked Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Execute tests without reflashing devices, useful for rapid development loops. This assumes the devices are already configured with the session profile. ```bash pytest tests/ --assume-baked --html=report.html ``` -------------------------------- ### Add Applet to InkHUD Configuration Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md To incorporate a new applet, include its header file and add an instance to InkHUD using `inkhud->addApplet()`. This should be done in the variant's `nicheGraphics.h` file. ```cpp // #include your applet // inkhud->addApplet("My Applet", new InkHUD::MyApplet); ``` -------------------------------- ### List Meshtastic Devices Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Use this command to list available Meshtastic devices, helpful for diagnosing hub detection issues. ```python from meshtastic import devices print(devices.list_devices()) ``` -------------------------------- ### Export UI Camera Device Environment Variable Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/README.md Export the environment variable to specify which USB webcam index to use for the UI tests. Replace '0' with the correct index found. ```bash export MESHTASTIC_UI_CAMERA_DEVICE_ESP32S3=0 ``` -------------------------------- ### Run Unit Tests Source: https://github.com/meshtastic/firmware/blob/develop/mcp-server/tests/README.md Execute only the unit tests for the MCP server. This is a quick way to verify core parsing and filtering logic without hardware. ```bash pytest tests/unit -v ``` -------------------------------- ### Publishing and Subscribing to Events with Observer/Observable Source: https://context7.com/meshtastic/firmware/llms.txt Use Observable to broadcast events and CallbackObserver to subscribe to them. Observers automatically unregister when destroyed. ```cpp // --- In the emitter class --- class MySubsystem { public: Observable newStatus; void publishUpdate(const MyStatus *s) { newStatus.notifyObservers(s); // calls onNotify on all registered observers } }; // --- Subscribing with CallbackObserver --- class MyConsumer { CallbackObserver statusObserver{ this, &MyConsumer::handleStatusUpdate }; int handleStatusUpdate(const MyStatus *s) { LOG_INFO("Status updated: value=%d", s->value); return 0; // 0 = continue notifying other observers; non-zero = abort chain } public: void init(MySubsystem *sub) { statusObserver.observe(&sub->newStatus); // register } ~MyConsumer() { // Observer auto-unregisters in ~Observer() via observables list cleanup } }; // --- Real-world example from main.cpp --- // GPS status observer wired to gpsStatus singleton gpsStatus->observe(&gps->newStatus); // Node count observer wired to NodeDB nodeStatus->observe(&nodeDB->newStatus); ``` -------------------------------- ### Instantiate AppletFont with Encoding Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md Construct an AppletFont instance specifying the font data and its encoding. This is necessary for 8-bit extended-ASCII fonts. ```cpp InkHUD::AppletFont(FreeSans9pt_Win1250, InkHUD::AppletFont::WINDOWS_1250); ``` -------------------------------- ### Flash Device Firmware Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Uploads the compiled firmware to a connected device. Specify the target environment and the serial port. Alternatively, use the `pio_flash` MCP tool. ```bash pio run -e -t upload --upload-port ``` -------------------------------- ### Build and Run with GDBServer Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Compile and run the meshtasticd application under gdbserver on localhost, port 2345. This enables remote debugging capabilities. ```bash ./bin/native-gdbserver.sh ``` -------------------------------- ### Simulate Elapsed Time for Time-Dependent Logic Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md Expose the timestamp via friend access in the test shim and simulate realistic elapsed time to avoid time-dependent logic collapsing to zero. This is crucial for rolling averages and interval-based accumulators. ```cpp // In test shim: void setWindowStartMs(uint32_t ms) { windowStartMs = ms; } // In test: shim.setWindowStartMs(millis() - 3600000UL); // pretend 1 hour elapsed ``` -------------------------------- ### Live TUI Test Runner Source: https://github.com/meshtastic/firmware/blob/develop/AGENTS.md Launches the live Text User Interface (TUI) test runner for the MCP server. This provides an interactive way to run tests. ```bash mcp-server/.venv/bin/meshtastic-mcp-test-tui ``` -------------------------------- ### Device Configuration and Control Source: https://context7.com/meshtastic/firmware/llms.txt Functions for modifying device settings, sending messages, and performing actions like rebooting. ```APIDOC ## set_owner ### Description Sets the owner information for the device. ### Parameters - **port** (string) - Required - The serial port the device is connected to. - **long_name** (string) - Required - The new long name for the device. - **short_name** (string) - Required - The new short name for the device. - **confirm** (boolean) - Required - Must be `True` to confirm the destructive write. ### Response #### Success Response (200) - (No specific response body detailed) ``` ```APIDOC ## set_config ### Description Sets a specific configuration field for the device. ### Parameters - **port** (string) - Required - The serial port the device is connected to. - **field** (string) - Required - The configuration field to set (e.g., "lora.region", "device.role"). - **value** (string) - Required - The new value for the configuration field. - **confirm** (boolean) - Required - Must be `True` to confirm the destructive write. ### Response #### Success Response (200) - (No specific response body detailed) ``` ```APIDOC ## send_text ### Description Sends a text message to the mesh network. ### Parameters - **port** (string) - Required - The serial port the device is connected to. - **message** (string) - Required - The text message to send. - **confirm** (boolean) - Required - Must be `True` to confirm the destructive write. ### Response #### Success Response (200) - (No specific response body detailed) ``` ```APIDOC ## reboot ### Description Reboots the Meshtastic device. ### Parameters - **port** (string) - Required - The serial port the device is connected to. - **secs** (integer) - Optional - The number of seconds to delay the reboot. - **confirm** (boolean) - Required - Must be `True` to confirm the destructive write. ### Response #### Success Response (200) - (No specific response body detailed) ``` ```APIDOC ## factory_reset ### Description Resets the device to factory default settings. ### Parameters - **port** (string) - Required - The serial port the device is connected to. - **full** (boolean) - Optional - If `True`, performs a full reset; if `False` (default), preserves keys. - **confirm** (boolean) - Required - Must be `True` to confirm the destructive write. ### Response #### Success Response (200) - (No specific response body detailed) ``` -------------------------------- ### Configure Meshtastic Device Role Source: https://context7.com/meshtastic/firmware/llms.txt Sets the device role (e.g., ROUTER) for a Meshtastic device. Requires confirmation. ```python set_config(port="/dev/ttyUSB0", field="device.role", value="ROUTER", confirm=True) ``` -------------------------------- ### Define a Basic Applet Class Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md Inherit from `InkHUD::Applet` and implement the `onRender` method for drawing. The `onRender` method is called whenever the display needs to be redrawn. ```cpp class BasicExampleApplet : public Applet { public: // You must have an onRender() method // All drawing happens here void onRender(bool full) override; }; ``` -------------------------------- ### C++ Unit Test File Skeleton Source: https://github.com/meshtastic/firmware/blob/develop/test/README.md A template for creating a new C++ unit test suite using the Unity framework. Includes necessary headers, test output helpers, and Unity lifecycle functions. ```cpp #include "MeshTypes.h" // Include BEFORE TestUtil.h (provides NodeNum, etc.) #include "TestUtil.h" // initializeTestEnvironment(), testDelay() #include #if YOUR_FEATURE_GUARD // Same #if guard as the module under test #include "FSCommon.h" #include "gps/RTC.h" #include "mesh/NodeDB.h" #include "modules/YourModule.h" #include #include #include // --- Test output helpers --- // Unity swallows printf/stdout. Only TEST_MESSAGE() output appears in results. #define MSG_BUF_LEN 200 #define TEST_MSG_FMT(fmt, ...) do { \ char _buf[MSG_BUF_LEN]; \ snprintf(_buf, sizeof(_buf), fmt, __VA_ARGS__); \ TEST_MESSAGE(_buf); \ } while(0) // --- Tests --- void test_example() { TEST_MESSAGE("=== Example test ==="); TEST_ASSERT_TRUE(true); } // --- Unity lifecycle --- void setUp(void) { /* runs before every test */ } void tearDown(void) { /* runs after every test */ } void setup() { initializeTestEnvironment(); // MUST call — sets up RTC, OSThread, console UNITY_BEGIN(); RUN_TEST(test_example); exit(UNITY_END()); // exit() required — Unity runner expects it } void loop() {} #else // !YOUR_FEATURE_GUARD void setUp(void) {} void tearDown(void) {} void setup() { initializeTestEnvironment(); UNITY_BEGIN(); exit(UNITY_END()); } void loop() {} #endif ``` -------------------------------- ### GPS Module Initialization and Control Source: https://context7.com/meshtastic/firmware/llms.txt Initialize the GPS module using a factory function and wire up its status observer. Control GPS power states for power saving and check fix status. ```cpp // GPS is created via factory (detects chip model, configures UART) // In setup(): gps = GPS::createGps(); if (gps) { gpsStatus->observe(&gps->newStatus); // wire up the status observer } else { LOG_WARN("No GPS found"); } // Control GPS power state for power saving gps->setPowerState(GPS_ACTIVE); // wake and start seeking a fix gps->setPowerState(GPS_SOFTSLEEP, 0); // soft sleep (chip still powered) gps->setPowerState(GPS_HARDSLEEP, 60000);// hard power-off for 60 s // Check fix status if (gps->hasLock()) { LOG_INFO("GPS locked: lat=%d, lon=%d, alt=%d", gps->p.latitude_i, gps->p.longitude_i, gps->p.altitude); } // Manual enable/disable cycle gps->disable(); gps->enable(); gps->toggleGpsMode(); // toggle between enabled/disabled // Read raw position struct meshtastic_Position &pos = gps->p; // pos.latitude_i — latitude × 1e7 (integer degrees) // pos.longitude_i — longitude × 1e7 // pos.altitude — meters above sea level // pos.time — Unix epoch seconds (from GPS or RTC) ``` -------------------------------- ### Instantiate AppletFont with Custom Line Height Source: https://github.com/meshtastic/firmware/blob/develop/src/graphics/niche/InkHUD/docs/README.md Construct an AppletFont instance with custom padding for line height. This can resolve issues with tall characters in extended-ASCII fonts. ```cpp // -2 px of padding above, +1 px of padding below InkHUD::AppletFont(FreeSans9pt7b, ASCII, -2, 1); ```