Development & Scripting

Using the MeshCore Python API

Build custom applications and scripts with the official meshcore Python library for automation, monitoring and integrations

What is the MeshCore Python API?

The meshcore Python library gives you programmatic access to MeshCore companion radio nodes. You can send messages, manage contacts, read telemetry, and build custom applications. Perfect for automation, monitoring, and IoT integrations.

The Python API communicates with your node via serial (USB), Bluetooth Low Energy (BLE) or TCP/IP. The library is fully async-based and uses an event-driven architecture. Open source and actively maintained.

In this guide you'll learn how to install the meshcore library, perform basic operations, and build practical scripts. The API makes it easy to integrate MeshCore into your Python projects.

Installing meshcore

Install the library via pip (Python 3.10+ required):

# Install meshcore library
pip install meshcore

# Or via pipx (recommended for CLI tools)
pipx install meshcore-cli

# Verify installation
python -c "import meshcore; print('meshcore installed!')"

On Linux you may need extra permissions for serial port access. Add yourself to the dialout group: sudo usermod -a -G dialout $USER (and log in again). For BLE you need to pair your device first via bluetoothctl.

Basic usage

The meshcore library is async-based. Here's a simple example to connect and send a message:

import asyncio
from meshcore import MeshCore, EventType

async def main():
    # Connect via USB serial
    meshcore = await MeshCore.create_serial("/dev/ttyUSB0")

    # Get device info
    result = await meshcore.commands.send_device_query()
    if result.type != EventType.ERROR:
        print(f"Connected to: {result.payload}")

    # Get contacts
    contacts = await meshcore.commands.get_contacts()
    print(f"Number of contacts: {len(contacts.payload)}")

    # Send message to first contact
    if contacts.payload:
        contact = contacts.payload[0]
        await meshcore.commands.send_msg(contact, "Hello from Python!")

    # Close connection
    await meshcore.disconnect()

asyncio.run(main())

This script connects via USB, retrieves device info and contacts, and sends a message. All commands are async and return an Event object with type and payload.

Practical applications

๐Ÿค–

Chatbots

Build a bot that automatically responds to messages. For example a weather bot, info bot, or admin bot for network management.

๐Ÿ“Š

Monitoring dashboards

Collect telemetry from all nodes and visualize in Grafana, InfluxDB, or custom dashboard. Real-time network health monitoring.

๐Ÿ””

Alert systems

Send notifications to email, Telegram, Discord when certain events happen. For example: low battery, node offline, sensor alarm.

๐Ÿ 

Home automation

Integrate MeshCore with Home Assistant, Node-RED, or Domoticz. Trigger automations based on mesh messages.

๐Ÿ“ก

Gateway scripts

Bridge between MeshCore and other systems: MQTT broker, REST API, database. Centralize data from multiple nodes.

๐Ÿงช

Testing & debugging

Automated tests for network range, latency, packet loss. Debug tools for troubleshooting.

Code examples

1. Event-based message receiving

Subscribe to events to receive real-time messages:

import asyncio
from meshcore import MeshCore, EventType

async def handle_message(event):
    """Callback for incoming messages"""
    msg = event.payload.get("text", "")
    sender = event.payload.get("pubkey_prefix", "unknown")
    print(f"[{sender}]: {msg}")

async def main():
    meshcore = await MeshCore.create_serial("/dev/ttyUSB0")

    # Subscribe to messages
    meshcore.subscribe(EventType.CONTACT_MSG_RECV, handle_message)

    # Start auto message fetching
    await meshcore.start_auto_message_fetching()

    print("Listening for messages... (Ctrl+C to stop)")
    try:
        while True:
            await asyncio.sleep(1)
    except KeyboardInterrupt:
        await meshcore.disconnect()

asyncio.run(main())

2. Connect via different methods

The library supports Serial, BLE and TCP connections:

from meshcore import MeshCore

# Via USB Serial
meshcore = await MeshCore.create_serial("/dev/ttyUSB0", 115200)

# Via Bluetooth Low Energy
meshcore = await MeshCore.create_ble("12:34:56:78:90:AB")
# With PIN pairing
meshcore = await MeshCore.create_ble("12:34:56:78:90:AB", pin="123456")

# Via TCP/IP (if node runs TCP server)
meshcore = await MeshCore.create_tcp("192.168.1.100", 4000)

3. Manage contacts

Retrieve contacts and search by name or key:

import asyncio
from meshcore import MeshCore, EventType

async def main():
    meshcore = await MeshCore.create_serial("/dev/ttyUSB0")

    # Get all contacts
    result = await meshcore.commands.get_contacts()
    if result.type == EventType.ERROR:
        print(f"Error: {result.payload}")
        return

    contacts = result.payload
    print(f"=== {len(contacts)} Contacts ===")

    for contact in contacts:
        print(f"  - {contact.name} ({contact.pubkey_prefix})")

    # Find contact by name
    contact = meshcore.get_contact_by_name("MyNode")
    if contact:
        await meshcore.commands.send_msg(contact, "Hello!")

    await meshcore.disconnect()

asyncio.run(main())

Benefits of the meshcore library

๐Ÿ

Modern Python

Fully async/await based with Python 3.10+. Clean API design with type hints and good IDE support.

๐Ÿ”Œ

Multiple connections

Connect via Serial, BLE or TCP. Automatic reconnect with exponential backoff on connection loss.

๐Ÿ“š

Event-driven

Subscribe to specific events with filters. React real-time to messages, advertisements, ACKs and more.

๐Ÿ”„

Active development

Library is actively maintained by the MeshCore community. Open source on GitHub.

๐ŸŒ

Integration possibilities

Easy to integrate with other async Python libraries, databases, and web frameworks.

โšก

Reliable

Commands return Event objects with clear error handling. Auto message fetching for reliable reception.

Frequently asked questions

Which Python version do I need?

Python 3.10 or higher is required. Check with python --version or python3 --version. Download Python from python.org if you have an older version.

How do I connect via Bluetooth?

First pair your device via bluetoothctl on Linux. Then use MeshCore.create_ble("MAC:ADDRESS"). For devices with PIN use the pin parameter.

Why are all methods async?

The meshcore library uses asyncio for non-blocking communication. This makes it possible to execute multiple operations simultaneously and efficiently wait for responses without blocking.

How do I handle errors?

All commands return an Event object. Check result.type == EventType.ERROR to detect errors. The result.payload then contains the error message.

Can I control multiple nodes simultaneously?

Yes! Create multiple MeshCore instances, each connected to a different node. Thanks to async you can use them in parallel.

Where can I find more documentation?

Check the GitHub repo: github.com/meshcore-dev/meshcore_py. The README has extensive examples. Also the meshcore-cli source code is a good reference.

Start with Python development

Ready to build custom MeshCore applications? Install the meshcore library and start experimenting.