Transport Layer

AccessoryManager abstracts BLE, TCP/IP, and serial transports behind a single interface. Views and services interact only with AccessoryManager — never with transport implementations directly.

Transport Implementations

Transports live in Meshtastic/Accessory/Transports/:

File Protocol Notes
BLETransport.swift CoreBluetooth Standard BLE connection to radios
TCPTransport.swift Network.framework Wi-Fi / TCP/IP to radios with networking
SerialTransport.swift IOKit serial macOS only; USB-serial adapters

Each transport conforms to a MeshTransport protocol that exposes connect(), disconnect(), send(data:), and a received publisher.

BLETransport Status on Bluetooth State Changes

BLETransport.status mirrors CBManagerState via handleCentralState(_:central:). .poweredOn settles on .discovering, not .ready.ready is only assigned later, by stopScanning(), and only while Bluetooth is still powered on. Every other state — including .poweredOff — settles on .error(...). Concretely, when Bluetooth powers off, status becomes .error(BLETransport.poweredOffStatusMessage) ("Bluetooth is powered off") and stays there. This matches .unauthorized, .unsupported, .resetting, and .unknown, which all settle on .error(...) too.

status is actor-isolated state, so nothing outside BLETransport could observe it changing until statusUpdates() -> AsyncStream<TransportStatus> was added: it replays the current status to a new subscriber, then yields again on every subsequent change (a didSet on status drives the broadcast, guarded so an unchanged value never yields a duplicate). AccessoryManager.observeBLETransportStatus() is the sole subscriber — it consumes the stream for the app's lifetime and mirrors every value onto @Published var bleTransportStatus, from which the computed isBluetoothPoweredOff derives. The Connect tab reads isBluetoothPoweredOff to show an inline "Bluetooth is off" row in Available Radios, since the system "Bluetooth is turned off" alert is intentionally suppressed (CBCentralManagerOptionShowPowerAlertKey: false, see above) and would otherwise be the only in-app signal a BLE user gets.

AccessoryManager Extension Map

Extension Key Methods
+Discovery startScanning(), stopScanning(), peripheral(_:didDiscover:)
+Connect connect(peripheral:), disconnect(), centralManager(_:didConnect:)
+ToRadio sendPacket(_:), sendWantConfig(), sendWaypoint(_:)
+FromRadio handleFromRadio(_:), handleMeshPacket(_:)
+Position startLocationUpdates(), sendPosition(_:)
+MQTT connectMQTT(), publishPacket(_:), mqttClient(_:didReceiveMessage:)
+TAK handleATAKPluginPacket(_:), handleATAKPluginV2Packet(_:), handleATAKForwarderPacket(_:), sendTAKPacket(_:channel:), sendTAKV2Packet(_:channel:), sendCoTToMeshV2(_:channel:). See TAK Protocol for the V1/V2 wire format detail.

Packet Flow (Inbound)

Radio (BLE/TCP/Serial)
  → Transport.received publisher
  → AccessoryManager+FromRadio.handleFromRadio(_:)
  → Decode protobuf (MeshtasticProtobufs)
  → Route by packet type:
      MeshPacket  → handleMeshPacket(_:)
      NodeInfo    → updateNodeInfo(_:)
      MyNodeInfo  → updateMyNodeInfo(_:)
      Config      → updateConfig(_:)
      ...
  → Write to SwiftData via MeshPackets @ModelActor
  → Publish changes via @Published properties (UI updates)

Frame Decoding & Encoding Validation

Every transport turns raw inbound bytes into a FromRadio frame through one shared funnel, FromRadioDecoder.classify(_:) in Accessory/Protocols/Connection.swift, so BLE, TCP, and Serial handle a malformed frame identically instead of each rolling its own try? FromRadio(serializedBytes:). It returns a FromRadioDecodeOutcome:

Outcome Meaning Transport action
.decoded(FromRadio) Frame decoded cleanly Yield .data(_) to AccessoryManager
.skipInvalidUTF8(Error) A string field (e.g. a node's long_name) failed SwiftProtobuf's UTF-8 validation Log and skip the frame; the connection stays alive and keeps reading
.failed(Error) Genuine framing / wire corruption BLE & TCP call disconnect(withError:shouldReconnect:) and reconnect; Serial logs and skips

An invalid encoding in a single string field is a per-field content problem, not a transport failure, so it must not tear down an otherwise healthy stream. SwiftProtobuf validates UTF-8 during decode and throws BinaryDecodingError.invalidUTF8; FromRadioDecoder isolates that case so only genuine framing errors trigger a reconnect.

Packet Flow (Outbound)

View / Service
  → AccessoryManager+ToRadio.sendPacket(_:)
  → Encode to protobuf (ToRadio wrapper)
  → Transport.send(data:)
  → Radio

BLE Writes When the Radio Is Out of Buffers

All of this applies only to .withResponse writes. send picks the write type from the characteristic's properties, preferring .withoutResponse when the radio advertises it, and CoreBluetooth does not call didWriteValueFor for that type — performWrite resumes its continuation as soon as the value is handed to CoreBluetooth, so no ATT error can come back and there is nothing to retry. Radios that refuse writes this way advertise plain write, which is how the path below is reachable at all. A .withoutResponse radio running out of buffers is invisible to the app; that backpressure is not handled.

CBATTError.insufficientResources on a .withResponse TORADIO write means the peripheral could not allocate for that one write. The link is healthy and the next write usually succeeds, so it is handled like an invalid UTF-8 field above — a per-item failure that must not tear down the stream — rather than like genuine wire corruption. It shows up on larger admin messages (set_owner, config sets) while 8-33 byte writes on the same connection go through; it was observed on a Heltec V4 (ESP32-S3/NimBLE) refusing a 104 byte write with an ATT MTU of 255 negotiated, so it is buffer exhaustion, not the size limit.

Two places cooperate on that:

The retry loop is cancellation-correct: it calls Task.checkCancellation() before each attempt and lets Task.sleep(for:) throw during the backoff, so a cancelled send cannot put another write on the wire.

Every ToRadio write also logs its payload size against maximumWriteValueLength(for:). An over-limit payload and an out-of-buffers radio both surface at the peripheral as the same opaque "resources are insufficient", and nothing recorded which one it was. These lines are .error, not .debug/.info, deliberately: only notice-and-above are persisted to OSLogStore, which is what the in-app log viewer reads, so a .debug line here would be invisible in the field.

Connection Sequencing

AccessoryManager+Connect runs connection setup as a sequenced series of steps: transport connect, heartbeat, wantConfig, optional database retrieval, and version checks.

During an explicit radio switch from the Connect view, the app uses the same connect pipeline but enables an extra post-config refresh. Once sendWantConfig() completes for the newly selected device, the app first applies the bundled DeviceHardware.json catalog and bundled device images to SwiftData, then schedules MeshtasticAPI.shared.refreshDevicesAPIData() in the background. That network refresh updates the same locally cached hardware catalog from https://api.meshtastic.org/resource/deviceHardware without blocking the rest of the connection sequence.

This refresh is only enabled for the switch-radio flow. Automatic reconnects and ordinary connects continue using the standard transport handshake without forcing a hardware catalog refresh.

BLE Pairing PIN Handshake

A first-ever connection to an encrypted radio makes iOS present a 6-digit pairing PIN sheet. BLEConnection gates connect-completion on that bond so the sheet is not torn down before the user can respond:

TCP Connect and Send Continuation Safety

TCPConnection bridges NWConnection's callback API to async/await with checked continuations, and callbacks fire on the private tcp.connection queue while the continuation resumes on the actor. Two rules follow from that split:

Adding a New Packet Type

  1. Add the protobuf definition in the protobufs/ submodule.
  2. Run ./scripts/gen_protos.sh.
  3. Add a decode/dispatch case in AccessoryManager+FromRadio.handleFromRadio(_:).
  4. Add a send method in AccessoryManager+ToRadio.swift.
  5. Add a model property or SwiftData entity if the data needs to persist.
  6. Write unit tests against the encode/decode round-trip.

Concurrency Notes

AccessoryManager is not @MainActor. Its @Published properties are observed from SwiftUI views on the main actor. Use await MainActor.run { } when updating published properties from background tasks or CoreBluetooth delegate callbacks.

Background persistence writes must go through the MeshPackets @ModelActor, not the main ModelContext.