Recipes for embedding meshtastic-sdk in an application: dependencies, building a client, per-transport setup, storage, sending, admin, and testing. api-reference.md lists what exists and observability.md covers seeing what it does.
| Module | JVM | Android | iOS | JS, Wasm |
|---|---|---|---|---|
sdk-core, sdk-testing |
yes | yes | yes | yes |
sdk-transport-websocket |
yes | yes | yes | yes |
sdk-transport-tcp |
yes | yes | yes | no |
sdk-transport-ble |
yes | yes | yes | no |
sdk-transport-serial |
yes | yes | no | no |
sdk-storage-sqldelight |
yes | yes | yes | no |
Every Android artifact sets minSdk = 26 (Android 8.0). A web host runs the engine in the page, connects with WebSocketTransport, and stores state with InMemoryStorageProvider (ADR-017).
// settings.gradle.kts: Maven Central is the only repository needed
dependencyResolutionManagement {
repositories { mavenCentral() }
}
// build.gradle.kts
dependencies {
implementation(platform("org.meshtastic:sdk-bom:<VERSION>"))
implementation("org.meshtastic:sdk-core")
implementation("org.meshtastic:sdk-storage-sqldelight")
// The transports your app supports:
implementation("org.meshtastic:sdk-transport-tcp")
implementation("org.meshtastic:sdk-transport-ble")
implementation("org.meshtastic:sdk-transport-serial")
implementation("org.meshtastic:sdk-transport-websocket")
testImplementation("org.meshtastic:sdk-testing")
}Replace <VERSION> with a release from CHANGELOG.md. The BOM aligns every sdk-* artifact (bom/README.md).
import org.meshtastic.sdk.RadioClient
import org.meshtastic.sdk.storage.sqldelight.SqlDelightStorageProvider
import org.meshtastic.sdk.transport.tcp.TcpTransport
val client = RadioClient.Builder()
.transport(TcpTransport(host = "meshtastic.local", port = 4403))
.storage(SqlDelightStorageProvider(baseDir = "/var/data"))
.build()
client.connect() // throws MeshtasticException on failuretransport(...) and storage(...) are required; everything else has a default (api-reference.md, Construction). Pass .autoReconnect(AutoReconnectConfig()) for the engine to reconnect after a drop.
No platform setup. The node listens on TCP port 4403 when Wi-Fi or Ethernet is on; meshtasticd listens there too.
val transport = TcpTransport(host = "192.168.1.50", port = 4403)Radios advertise _meshtastic._tcp over mDNS. JvmTcpDiscovery(), AndroidTcpDiscovery(context), and IosTcpDiscovery() implement TcpDiscovery.discover(), a flow of TcpDiscoveryEvent.Found(radio) and Lost(serviceName); radio.toTransport() opens a TcpTransport.
Scan with BleScanner and build the transport from the result; this works on every target.
import kotlinx.coroutines.flow.first
import org.meshtastic.sdk.transport.ble.BleScanner
import org.meshtastic.sdk.transport.ble.BleTransport
val radio = BleScanner.scan().first()
val transport = BleTransport(radio)BleScanner.scan() filters on the Meshtastic service UUID; DiscoveredRadio carries name, rssi, and address. To pick a radio from a user-typed ble:NEEDLE, filter with bleAdvertisementMatches.
On Android, BleTransport(address = "AA:BB:CC:DD:EE:FF") connects by MAC address without a fresh scan, and bondedBleDevices(context) lists the host's bonded devices for a picker. BleResilience(bondFirst = true, autoConnectFallback = true, refreshStaleGattCache = true) turns on link recovery for difficult radios. refreshStaleGattCache reads two private Kable fields by reflection; the AAR ships the keep rules from transport-ble/consumer-rules.pro, so R8 keeps them in a minified build. BleTransport.deviceLogs() streams the radio's log (observability.md).
Platform requirements:
- Android: request
BLUETOOTH_SCANandBLUETOOTH_CONNECTon API 31 and later; addandroid:usesPermissionFlags="neverForLocation"toBLUETOOTH_SCANif you don't derive location from scans. API 30 and earlier needBLUETOOTH,BLUETOOTH_ADMIN, andACCESS_FINE_LOCATION. The SDK requests none of them. - iOS: set
NSBluetoothAlwaysUsageDescriptioninInfo.plist, and add thebluetooth-centralbackground mode for background use. - JVM: Linux needs BlueZ. On macOS and Windows, Bluetooth through Kable is best-effort.
JVM:
import org.meshtastic.sdk.transport.serial.JvmSerialPorts
val port = JvmSerialPorts.findMeshtastic().first() // List<SerialPortInfo>, filtered by USB vendor ID
val transport = JvmSerialPorts.open(port.name, baudRate = 115_200)On Linux, JvmSerialPorts.byIdPath(port.name) returns the stable /dev/serial/by-id/… path, which survives replugs; ttyACM numbers don't.
Android, with jSerialComm:
import org.meshtastic.sdk.transport.serial.AndroidSerialPorts
AndroidSerialPorts.init(applicationContext) // once, for example in Application.onCreate()
// After UsbManager.requestPermission(...) is granted:
val transport = AndroidSerialPorts.open(portName, baudRate = 115_200)Android, with usb-serial-for-android, the driver stack Meshtastic-Android uses. The SDK depends on it compileOnly because it's published on JitPack, so add the dependency and the repository:
// settings.gradle.kts
dependencyResolutionManagement.repositories {
maven("https://jitpack.io") { content { includeGroup("com.github.mik3y") } }
}
// build.gradle.kts
implementation("com.github.mik3y:usb-serial-for-android:3.12.0")import org.meshtastic.sdk.transport.serial.AndroidUsbSerialPorts
val ports = AndroidUsbSerialPorts.list(context) // devices a driver claims, permission or not
// After UsbManager.requestPermission(device, ...) is granted:
val transport = AndroidUsbSerialPorts.open(context, ports.first().name)Every open has an overload with onTextLine: (String) -> Unit, which receives the text the device prints between frames.
The host owns the USB permission flow:
- Declare
<uses-feature android:name="android.hardware.usb.host" />, and optionally a receiver forUSB_DEVICE_ATTACHEDwith ares/xml/device_filter.xmllisting the USB vendor and product IDs to match. - Call
UsbManager.requestPermission(device, pendingIntent)beforeopen. - Open the port when the permission broadcast reports
EXTRA_PERMISSION_GRANTED.
samples/cli has a complete JVM example. iOS has no serial transport; use TCP, Bluetooth, or WebSocket.
For nodes that serve the WebSocket phone API at /api/v1/ws. Firmware support is in open pull requests; the module's Module.md lists them.
import org.meshtastic.sdk.transport.websocket.WebSocketTransport
val transport = WebSocketTransport("ws://meshtastic.local") // path defaults to /api/v1/wsThe node serves one client at a time; a newer client displaces the older one, which ends with TransportState.Error(recoverable = false). A wss:// node with a self-signed certificate needs an HttpClient that trusts it, passed as the second argument, or, in a browser, trust granted in the browser. Module.md has the close codes and browser constraints. On Android, declare the INTERNET permission.
TransportTarget.parse("tcp:192.168.1.50") returns TransportTarget.Tcp(host, port), and likewise for ble:NEEDLE and serial:PORT[:BAUD], or null for anything else. Map the target to one of the transports in this section; the SDK leaves that step to the host so an app links only the transports it uses.
On API 34 and later, Bluetooth and USB connections stop in the background without a foreground service, and the SDK doesn't start one. Host the client in a Service with android:foregroundServiceType="connectedDevice", declare FOREGROUND_SERVICE and FOREGROUND_SERVICE_CONNECTED_DEVICE (and POST_NOTIFICATIONS for the notification), call startForeground(...) before connect(), and stop it after disconnect(). See the Android foreground service documentation.
SqlDelightStorageProvider(baseDir) keeps one SQLite database per radio under baseDir, shared by every transport that reaches the same node. baseDir = "" selects in-memory mode, lost on close. InMemoryStorageProvider() from sdk-core keeps everything in RAM on every target, including the web.
On Android, set the context holder once before the first connect():
import org.meshtastic.sdk.storage.sqldelight.AndroidContextHolder
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
AndroidContextHolder.context = applicationContext
}
}Then construct it as on other platforms, for example SqlDelightStorageProvider(baseDir = filesDir.absolutePath).
connect()suspends untilconnection.value == ConnectionState.Connectedand throwsMeshtasticExceptionon failure (error-taxonomy.md).connect()isn't idempotent: calling it while connected throwsAlreadyConnected. Checkclient.connection.valuefirst.nodes,packets,events, andfromRadioare hot flows that any number of collectors can share.nodesstarts every subscription with a snapshot; the others deliver only what arrives while you collect. A slow collector loses items rather than slowing the engine (api-reference.md, Streams).disconnect()is idempotent and never throws. A pendingMessageHandle.await()returnsSendOutcome.Failure(SendFailure.Disconnected).withConnection { … }connects, runs a block, and always disconnects.
Build one RadioClient per radio and hold it at app scope, for example as a DI singleton, so a screen or configuration change doesn't tear the session down. samples/parity-android-app is the compiled Android reference for building and connecting a client; it scopes its client to the activity to stay short.
val handle = client.sendText("hello mesh")
when (val outcome = handle.await()) {
SendOutcome.Success -> println("acked, or a relay was heard")
is SendOutcome.Failure -> println("failed: ${outcome.reason}")
}For progress, collect handle.state: Queued, Sent, then Acked, Delivered, or Failed(reason). consumer-guides/error-handling.md covers which failures to retry.
// Read a config section
when (val result = client.admin.getConfig(AdminMessage.ConfigType.LORA_CONFIG)) {
is AdminResult.Success -> println("LoRa region: ${result.value.lora?.region}")
AdminResult.Timeout -> println("timed out")
AdminResult.RateLimited -> println("rate limited; try again later")
else -> println("failed: $result")
}
// Change one field: the builder reads the current section, so the others keep their values
client.admin.setLoraConfig {
newBuilder().also { it.region = Config.LoRaConfig.RegionCode.US }.build()
}
// Write several sections in one transaction
val lora = client.configBundle.value?.configs?.firstNotNullOfOrNull { it.lora } ?: return
client.admin.editSettings {
setConfig(Config.Builder().also { it.lora = lora }.build())
setOwner(newOwner)
}
// Target another node
client.admin.forNode(NodeId(0x12345678)).reboot()A config builder reads the section from the targeted device before calling its block, and what the block returns replaces the whole section, so change only the fields you mean to. api-reference.md, AdminApi has every method; error-taxonomy.md explains each AdminResult.
The SDK is silent by default. Pass a LogSink to Builder.logger(...); for frame-level debugging add protocolLogging(...), which redacts payloads. observability.md also covers the raw fromRadio tap and device logs.
import org.meshtastic.sdk.InMemoryStorageProvider
import org.meshtastic.sdk.RadioClient
import org.meshtastic.sdk.TransportIdentity
import org.meshtastic.sdk.testing.FakeRadioTransport
val transport = FakeRadioTransport(identity = TransportIdentity("fake:test"), autoHandshake = true)
val client = RadioClient.Builder()
.transport(transport)
.storage(InMemoryStorageProvider())
.build()
client.connect() // the fake answers the handshake
transport.injectPacket(somePacket) // drive inbound traffic
val sent = transport.outboundPackets() // inspect what the client sentFakeRadioTransport also injects admin, telemetry, traceroute, and routing replies. testing/Module.md and core/src/commonTest/ have working patterns.
The node encrypts and decrypts direct messages with X25519 keys; the SDK never handles a private key (protocol.md §10).
- Inbound direct messages arrive on
packetsalready decoded. sendDirectMessageEncrypted(to, text)setspki_encrypted, so the node encrypts to the recipient's key.sendTextto a unicast destination also works when the node has the recipient's key.- Each node's key is
NodeInfo.user.public_key, and the local one is inownNode. To guard against impersonation, compare a peer's current key with one the user verified before sending, since the engine doesn't refuse the send. MeshEvent.SecurityWarning.DuplicatedPublicKeymeans the node saw a key it already holds for another node;LowEntropyKeymeans the local key is weak.- Firmware's key verification exchange runs over
KEY_VERIFICATION_APP: start it withadmin.keyVerification(...)and read replies withasKeyVerification().
When a node has MQTT on, packets that crossed MQTT arrive with MeshPacket.via_mqtt = true (also MeshPacket.transport == PacketTransport.Mqtt), and the node may publish what you send. Nothing on the client side needs configuring for that.
When mqtt.proxy_to_client_enabled is set, the node reaches the broker through the client instead: its MQTT traffic arrives as MeshEvent.MqttProxyMessage, the host publishes it, and broker traffic goes back through sendRaw as a ToRadio with mqttClientProxyMessage set. The SDK doesn't bundle an MQTT client (roadmap.md R-11). protocol.md §14 has the wire details.
- API reference: every public symbol
- Error taxonomy: which failures throw, return, or arrive as events
- Protocol notes: the wire behavior the SDK speaks
- Sample CLI: a reference consumer for TCP, Bluetooth, and serial
- ADR-005: why the API looks the way it does