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 provides 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 EMPloys an event-driven architecture. Open source and actively maintained.
This guide explains how to install the MeshCore library, perform basic operations, and build practical scripts. The API makes it straightforward 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 additional 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 is 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 visualise in Grafana, InfluxDB, or custom dashboard. Real-time network health monitoring.
Alert systems
Send notifications to email, Telegram, Discord when certain events occur. 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. Centralise 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 in real-time to messages, advertisements, ACKs, and more.
Active development
Library is actively maintained by the MeshCore community. Open source on GitHub.
Integration possibilities
Simple 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 enables multiple operations to execute 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. Owing 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. The MeshCore-cli source code is also a good reference.
Start with python development
Ready to build custom MeshCore applications? Install the MeshCore library and start experimenting.