MeshCore API Reference

June 19, 2026 ยท View on GitHub

The MeshCore framework provides the low-level protocol implementation for MeshCore mesh networking devices.

Note: This document covers the primary public APIs. The full API surface includes 80+ additional methods for advanced use cases like signing, custom variables, telemetry, and device configuration.

Package Information

  • Location: MeshCore/
  • Type: Swift Package (MeshCore library plus a MeshCoreTestSupport library target)
  • Dependencies: No runtime dependencies (a swift-docc-plugin build/documentation dependency only)

MeshCoreSession (public, actor)

File: MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift

The primary entry point for communicating with a MeshCore device. Serializes all device communication through actor isolation.

Lifecycle

MethodDescription
init(transport:configuration:clock:)Initializes a session with the given transport, optional configuration (defaults to .default), and optional clock for testing
start() async throwsConnects to the device and initializes the session
stop() asyncStops the session and disconnects the transport

Core Properties

PropertyTypeDescription
currentSelfInfoSelfInfo?Returns the device's self info after session start, populated after start() completes
cachedContacts[MeshContact]Returns currently cached contacts without making a device request
cachedPendingContacts[MeshContact]Returns pending contacts awaiting confirmation
deviceTimeDate?Returns the last known device time, or nil if not yet queried
isContactsDirtyBoolIndicates whether the contact cache needs refreshing
connectionStateAsyncStream<ConnectionState>Stream reflecting the current connection state

Events

MethodDescription
events() async -> AsyncStream<MeshEvent>Returns a stream of all incoming events from the device
waitForEvent(matching:timeout:) async -> MeshEvent?Waits for a specific event type with optional filtering and timeout
waitForEvent(filter:timeout:) async -> MeshEvent?Waits for an event matching an EventFilter with timeout
sendAndWait(_:matching:timeout:) async throws -> TSends a command and waits for a matching response, avoiding race conditions

Messaging

MethodDescription
sendMessage(to:text:timestamp:) async throws -> MessageSentInfoSends a direct message to a contact (6-byte public key prefix or Destination)
sendMessageWithRetry(to:text:timestamp:maxAttempts:floodAfter:maxFloodAttempts:timeout:) async throws -> MessageSentInfo?Sends with automatic retry and flood fallback (requires 32-byte key)
sendChannelMessage(channel:text:timestamp:) async throwsBroadcasts to a channel slot (0-15)
sendCommand(to:command:timestamp:) async throws -> MessageSentInfoSends a command message to a remote node
sendAdvertisement(flood:) async throwsSends an advertisement broadcast, optionally using flood routing
sendLogin(to:password:) async throws -> MessageSentInfoSends a login request to a remote node (accepts Data or Destination)
sendLogout(to:) async throwsSends a logout request to a remote node
sendKeepAlive(to:syncSince:) async throws -> MessageSentInfoSends a keep-alive to a room server with sync watermark
sendStatusRequest(to:) async throws -> MessageSentInfoRequests status information from a remote node
sendTelemetryRequest(to:) async throws -> MessageSentInfoRequests telemetry data from a remote node
sendPathDiscovery(to:) async throws -> MessageSentInfoInitiates path discovery to a remote node
sendTrace(tag:authCode:flags:path:) async throws -> MessageSentInfoSends a trace packet through the mesh network for debugging
getMessage(timeout:) async throws -> MessageResultFetches next pending message from device queue
startAutoMessageFetching() asyncBegins automatically fetching messages on notifications
stopAutoMessageFetching()Stops automatic message fetching

Contact Management

MethodDescription
public func getContacts(since lastModified: Date? = nil) async throws -> [MeshContact]Fetches contacts from device, optionally filtering to contacts modified since a date
getContact(publicKey:) async throws -> MeshContact?Fetches a single contact by full public key
ensureContacts(force:) async throws -> [MeshContact]Ensures contacts are loaded, fetching from device if needed or if cache is dirty
getContactByName(_:exactMatch:) -> MeshContact?Finds a contact by advertised name with optional exact matching
getContactByKeyPrefix(_:) -> MeshContact?Finds a contact by public key prefix (accepts String hex or Data)
popPendingContact(publicKey:) -> MeshContact?Removes and returns a pending contact by hex string public key
flushPendingContacts()Removes all pending contacts from the cache
setAutoUpdateContacts(_:)Enables or disables automatic contact updates on advertisements
addContact(_:) async throwsAdds a contact to the device's contact list
updateContact(publicKey:type:flags:outPathLength:outPath:advertisedName:lastAdvertisement:latitude:longitude:) async throwsLow-level method to update or create a contact with full details
changeContactPath(_:path:) async throwsChanges the routing path for a contact while preserving other info
changeContactFlags(_:flags:) async throwsChanges the flags for a contact while preserving other info
removeContact(publicKey:) async throwsRemoves a contact from the device's contact list
resetPath(publicKey:) async throwsResets routing path for a contact, forcing route rediscovery
shareContact(publicKey:) async throwsShares a contact with nearby devices via broadcast
exportContact(publicKey:) async throws -> StringExports a contact as a shareable URI string (nil for self)
importContact(cardData:) async throwsImports a contact from encoded contact card data

Device Configuration

MethodDescription
sendAppStart() async throws -> SelfInfoSends the app-start command to initialize communication (usually called by start())
queryDevice() async throws -> DeviceCapabilitiesQueries hardware capabilities and firmware
getBattery() async throws -> BatteryInfoRequests battery level and voltage
getTime() async throws -> DateGets the current device time
setTime(_:) async throwsSets the device's current time
setName(_:) async throwsSets the device's advertised name (max 32 bytes UTF-8)
setCoordinates(latitude:longitude:) async throwsSets device GPS coordinates for advertisements
setTxPower(_:) async throwsSets radio transmission power level in dBm
setRadio(frequency:bandwidth:spreadingFactor:codingRate:) async throwsConfigures LoRa radio parameters
setTuning(rxDelay:af:) async throwsConfigures radio timing parameters for fine-tuning
setOtherParams(manualAddContacts:telemetryModeEnvironment:telemetryModeLocation:telemetryModeBase:advertisementLocationPolicy:multiAcks:) async throwsSets miscellaneous device parameters (low-level, use granular setters instead)
setTelemetryModeBase(_:) async throwsSets base telemetry mode (0-3), preserving other settings
setTelemetryModeLocation(_:) async throwsSets location telemetry mode (0-3), preserving other settings
setTelemetryModeEnvironment(_:) async throwsSets environment telemetry mode (0-3), preserving other settings
setManualAddContacts(_:) async throwsSets manual contact approval mode, preserving other settings
setMultiAcks(_:) async throwsSets multi-acks count, preserving other settings
setAdvertisementLocationPolicy(_:) async throwsSets advertisement location policy, preserving other settings
getAutoAddConfig() async throws -> AutoAddConfigReturns auto-add config (bitmask plus max-hops) (v1.12+)
setAutoAddConfig(_:) async throwsSets auto-add config (v1.12+)
setDevicePin(_:) async throwsSets the device PIN for administrative access (4-digit as UInt32)
reboot() async throwsReboots the device (session will be disconnected)

Telemetry and Statistics

MethodDescription
getSelfTelemetry() async throws -> TelemetryResponseRetrieves telemetry data from the local device
getStatsCore() async throws -> CoreStatsRetrieves core device statistics including uptime and system metrics
getStatsRadio() async throws -> RadioStatsRetrieves radio statistics including RSSI, SNR, and transmission counts
getStatsPackets() async throws -> PacketStatsRetrieves packet statistics including sent, received, and dropped counts

Custom Variables

MethodDescription
getCustomVars() async throws -> [String: String]Retrieves all custom variables stored on the device
setCustomVar(key:value:) async throwsSets a custom variable on the device (key max 32 bytes, value max 256 bytes)

Cryptographic Keys

MethodDescription
exportPrivateKey() async throws -> DataExports the device's 32-byte private key (sensitive operation)
importPrivateKey(_:) async throwsImports a 64-byte expanded private key, replacing the device's identity

Channels

MethodDescription
getChannel(index:) async throws -> ChannelInfoRetrieves configuration for a channel (index 0-15)
setChannel(index:name:secret:) async throwsConfigures a channel with name and PSK secret data (16 bytes)
setChannel(index:name:secret:) async throwsConfigures a channel with automatic secret derivation (accepts ChannelSecret, default: .deriveFromName)
setFloodScope(scopeKey:) async throwsSets the flood scope using a raw 32-byte scope key
setFloodScope(_:) async throwsSets the flood scope using a FloodScope enum

Signing

MethodDescription
signStart() async throws -> IntBegins a signing operation, returns maximum data size in bytes
signData(_:) async throwsSends a data chunk for signing (typically up to 120 bytes)
signFinish(timeout:) async throws -> DataFinalizes signing and retrieves the signature (default 3x timeout)
sign(_:chunkSize:timeout:) async throws -> DataSigns data using the device's private key (handles complete workflow)

Control and Discovery

MethodDescription
sendControlData(type:payload:) async throwsSends control data to the mesh network
sendNodeDiscoverRequest(filter:prefixOnly:tag:since:) async throws -> UInt32Sends a node discovery request, returns the tag for correlating responses
factoryReset() async throwsPerforms a factory reset (irreversible, erases all data)

Remote Node Queries (Binary Protocol)

MethodDescription
requestStatus(from:) async throws -> StatusResponseRequests status from a remote node (accepts Data or Destination)
requestTelemetry(from:) async throws -> TelemetryResponseRequests telemetry from a remote node (accepts Data or Destination)
requestMMA(from:start:end:) async throws -> MMAResponseRequests Min-Max-Average data for a time range from a remote node
requestACL(from:) async throws -> ACLResponseRequests the Access Control List from a remote node
requestNeighbours(from:count:offset:orderBy:pubkeyPrefixLength:) async throws -> NeighboursResponseRequests neighbor list from a remote node with pagination
fetchAllNeighbours(from:orderBy:pubkeyPrefixLength:) async throws -> NeighboursResponseFetches complete neighbor table from a remote node with automatic pagination

MeshTransport (public, protocol)

File: MeshCore/Sources/MeshCore/Transport/MeshTransport.swift

Abstraction for underlying transport layers, enabling different implementations for production and testing. The protocol itself is not an actor, but implementations should be actors or otherwise thread-safe (conforming to Sendable).

public protocol MeshTransport: Sendable {
    var receivedData: AsyncStream<Data> { get async }
    var isConnected: Bool { get async }
    func connect() async throws
    func disconnect() async
    func send(_ data: Data) async throws
    // Unacknowledged write (ATT Write Command); default impl routes to send(_:).
    func sendWithoutResponse(_ data: Data) async throws
    // Capability flags; default to false / supportsWriteWithoutResponse.
    var supportsWriteWithoutResponse: Bool { get async }
    var supportsPipelinedReads: Bool { get async }
}

Implementations

TypeDescription
WiFiTransport (public, actor)Network framework-based transport for WiFi devices
MockTransport (public, actor)Deterministic transport for unit testing

Bluetooth Low Energy is implemented at the app layer: iOSBLETransport in MC1Services conforms to MeshTransport over CoreBluetooth.

WiFi Transport Implementation

WiFi transport provides connection to MeshCore devices over TCP/IP networks.

File: MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift

Connection Characteristics:

  • Protocol: TCP over WiFi
  • Port: Configurable (the MeshCore One app UI defaults to 5000)
  • Timeout: 10 seconds (see WiFiTransport.connectionTimeout)
  • Framing: Length-prefixed frames (see WiFiFrameCodec)
  • Keep-Alive / Auto-Reconnect: Not implemented in WiFiTransport itself; higher layers can reconnect as needed

WiFi-Specific Behavior:

AspectDescription
ThroughputHigher than BLE (~1KB/sec vs ~250 bytes/sec)
LatencyHigher than BLE (~100-200ms vs ~50-100ms)
RangeLonger than BLE (~100-300m vs ~10-50m)
PowerConstant power supply (not battery-dependent)
DiscoveryManual host/port configuration
Use CasesFixed installations, repeaters, room servers

WiFi vs BLE Transport Decision:

// Configure before connecting
let transport = WiFiTransport()
await transport.setConnectionInfo(host: host, port: port)
try await transport.connect()

Error Handling:

  • connect() throws WiFiTransportError (e.g., .notConfigured, .connectionTimeout, .connectionFailed(...))
  • send(_:) throws WiFiTransportError.notConnected / .sendFailed(...)

EventDispatcher (public, actor)

File: MeshCore/Sources/MeshCore/Events/EventDispatcher.swift

Broadcasts MeshEvents to multiple subscribers via AsyncStream. Manages event distribution from the session to all listeners. Uses bounded buffering (100 events) to prevent memory issues.

Methods

MethodDescription
subscribe() -> AsyncStream<MeshEvent>Returns a new unfiltered stream for receiving all events
subscribe(filter:) -> AsyncStream<MeshEvent>Returns a filtered stream that only yields matching events
dispatch(_:)Synchronously broadcasts an event to all subscribers (not async)

MeshEvent (public, enum)

File: MeshCore/Sources/MeshCore/Events/MeshEvent.swift

Represents any event received from the device. Events are organized into categories.

Connection Lifecycle

CasePayloadDescription
.connectionStateChangedConnectionStateConnection state has changed

Command Responses

CasePayloadDescription
.okvalue: UInt32?Command completed successfully
.errorcode: UInt8?Command failed with error

Device Information

CasePayloadDescription
.selfInfoSelfInfoDevice self-information received
.deviceInfoDeviceCapabilitiesDevice capabilities received
.batteryBatteryInfoBattery status received
.currentTimeDateCurrent device time received
.customVars[String: String]Custom variables received
.channelInfoChannelInfoChannel configuration received
.statsCoreCoreStatsCore statistics received
.statsRadioRadioStatsRadio statistics received
.statsPacketsPacketStatsPacket statistics received
.autoAddConfigAutoAddConfigAuto-add configuration received (v1.12+)
.defaultFloodScopeDefaultFloodScope?Persisted default flood scope (firmware v11+); nil = none persisted
.allowedRepeatFreq[FrequencyRange]Allowed repeat frequency ranges (v9+ firmware)

Contact Management

CasePayloadDescription
.contactsStartcount: IntContact list transfer started
.contactMeshContactA contact was received
.contactsEndlastModified: DateContact list transfer completed
.newContactMeshContactA new contact was discovered
.contactDeletedpublicKey: DataA contact was auto-deleted by the device (storage limit)
.contactsFull-The device's contact storage is full
.contactURIStringContact URI was received

Messaging

CasePayloadDescription
.messageSentMessageSentInfoMessage was queued for sending
.contactMessageReceivedContactMessageDirect message received from a contact
.channelMessageReceivedChannelMessageChannel broadcast message received
.channelDataReceivedChannelDatagramBinary datagram received on a channel (firmware v11+)
.noMoreMessages-No more messages waiting
.messagesWaiting-Messages are waiting to be fetched

Network Events

CasePayloadDescription
.advertisementpublicKey: DataAdvertisement received from a node
.pathUpdatepublicKey: DataRouting path was updated
.acknowledgementcode: Data, tripTime: UInt32?Message delivery acknowledgement (tripTime is firmware round-trip ms, if available)
.traceDataTraceInfoTrace route data received
.pathResponsePathInfoPath discovery response

Authentication

CasePayloadDescription
.loginSuccessLoginInfoLogin succeeded
.loginFailedpublicKeyPrefix: Data?Login failed

Binary Protocol Responses

CasePayloadDescription
.statusResponseStatusResponseStatus response from remote node
.telemetryResponseTelemetryResponseTelemetry response from remote node
.binaryResponsetag: Data, data: DataGeneric binary protocol response
.mmaResponseMMAResponseMin/Max/Average telemetry response
.aclResponseACLResponseAccess control list response
.neighboursResponseNeighboursResponseNeighbours list response

Cryptographic Signing

CasePayloadDescription
.signStartmaxLength: IntSigning session started
.signatureDataCryptographic signature generated
.disabledreason: StringFeature is disabled

Raw Data and Logging

CasePayloadDescription
.rawDataRawDataInfoRaw radio data received
.rxLogDataParsedRxLogDataEmitted when low-level radio log data is successfully parsed into structured packet information
.logDataLogDataInfoEmitted for diagnostic logs and malformed RX payloads that failed parsing
.controlDataControlDataInfoControl protocol data received
.discoverResponseDiscoverResponseNode discovery response
.advertPathResponseAdvertPathResponseAdvertisement path response (0x16)
.tuningParamsResponseTuningParamsResponseTuning parameters response (0x17)

Key Management

CasePayloadDescription
.privateKeyDataPrivate key was exported

Debug and Diagnostics

CasePayloadDescription
.parseFailuredata: Data, reason: StringPacket parsing failed

Models

MeshContact (public, struct)

File: MeshCore/Sources/MeshCore/Models/Contact.swift

Represents a contact in the mesh network.

PropertyTypeDescription
idStringUnique identifier (hex string of the public key)
publicKeyData32-byte public key
typeContactTypeNode type: .chat (0x01), .repeater (0x02), .room (0x03)
typeRawValueUInt8Raw 1-byte wire type, preserved for types not modeled by ContactType
flagsContactFlagsContact flags
outPathLengthUInt8Encoded path-length byte (0xFF = flood; upper 2 bits = hash-size mode, lower 6 bits = hop count)
outPathDataRouting information
advertisedNameStringDisplay name from advertisement
lastAdvertisementDateLast advertisement timestamp
latitudeDoubleLocation latitude
longitudeDoubleLocation longitude
lastModifiedDateLast modification timestamp

ContactMessage (public, struct)

File: MeshCore/Sources/MeshCore/Events/MessagingPayloads.swift

Represents a direct message from a contact.

PropertyTypeDescription
senderPublicKeyPrefixData6-byte sender key prefix
pathLengthUInt8Hop count
textTypeUInt8Message type (0=plain, 1=CLI, 2=signed)
senderTimestampDateSender's timestamp
signatureData?Optional message signature
textStringMessage content
snrDouble?Signal-to-noise ratio

ChannelMessage (public, struct)

File: MeshCore/Sources/MeshCore/Events/MessagingPayloads.swift

Represents a message received on a channel.

PropertyTypeDescription
channelIndexUInt8Channel slot
pathLengthUInt8Hop count
textTypeUInt8Message type
senderTimestampDateSender's timestamp
textStringMessage content (format: "NodeName: text")
snrDouble?Signal-to-noise ratio

Supporting Types

SessionConfiguration (public, struct)

File: MeshCore/Sources/MeshCore/Session/SessionConfiguration.swift

Configuration options for MeshCoreSession.

PropertyTypeDefaultDescription
defaultTimeoutTimeInterval5.0Default timeout for operations
clientIdentifierString"MeshCore-Swift"Client identifier string

OtherParamsConfig (public, struct)

File: MeshCore/Sources/MeshCore/Session/OtherParamsConfig.swift

Configuration for device "other params" settings. Used by granular configuration setters to implement read-modify-write pattern.

PropertyTypeDescription
manualAddContactsBoolWhether contacts require manual approval
telemetryModeBaseUInt8Base telemetry mode (0-3)
telemetryModeLocationUInt8Location telemetry mode (0-3)
telemetryModeEnvironmentUInt8Environment telemetry mode (0-3)
advertisementLocationPolicyUInt8Location advertising policy
multiAcksUInt8Number of acknowledgment retries

MessageResult (public, enum)

File: MeshCore/Sources/MeshCore/Session/SessionConfiguration.swift

Result of a message fetch operation.

CaseDescription
.contactMessage(ContactMessage)A contact message was received
.channelMessage(ChannelMessage)A channel message was received
.channelDatagram(ChannelDatagram)A binary datagram was received on a channel (firmware v11+)
.noMoreMessagesNo more messages available in queue

Destination (public, enum)

File: MeshCore/Sources/MeshCore/Models/Destination.swift

Represents the destination for a message. Can be specified as raw data, hex string, or contact object.

CasePayloadDescription
.data(Data)Raw bytesDirect message using raw public key data
.hexString(String)Hex stringDirect message using hex-encoded public key
.contact(MeshContact)Contact objectDirect message to a contact

Methods:

  • publicKey(prefixLength:) throws -> Data - Returns the public key prefix of specified length (default 6 bytes)
  • fullPublicKey() throws -> Data - Returns the full 32-byte public key

FloodScope (public, enum)

File: MeshCore/Sources/MeshCore/Models/Destination.swift

Defines the scope for flood routing in the mesh network.

CasePayloadDescription
.disabled-Flood routing is disabled
.channelName(String)Channel nameScope derived from channel name hash
.rawKey(Data)16-byte keyScope using explicit key
.region(String)Region nameScope from SHA256("#" + name).prefix(16); # prefix added automatically

Methods:

  • scopeKey() -> Data - Generates a 16-byte scope key

ChannelSecret (public, enum)

File: MeshCore/Sources/MeshCore/Models/Destination.swift

Defines the secret used for channel encryption.

CasePayloadDescription
.explicit(Data)16-byte secretExplicit secret key
.deriveFromName-Secret derived from channel name

Methods:

  • secretData(channelName:) -> Data - Generates 16-byte secret data

EventFilter (public, struct)

File: MeshCore/Sources/MeshCore/Events/EventFilter.swift

Provides type-safe event filtering for MeshEvent values. Use with EventDispatcher.subscribe(filter:) or waitForEvent(filter:timeout:).

Factory methods:

  • .acknowledgement(code:) - Filter for specific acknowledgement codes
  • .contactMessage(fromPrefix:) - Filter messages from a specific sender
  • .channelMessage(channel:) - Filter messages on a specific channel
  • .statusResponse(fromPrefix:) - Filter status responses from a node
  • .telemetryResponse(fromPrefix:) - Filter telemetry responses from a node
  • .advertisement(fromPrefix:) - Filter advertisements from a node
  • .pathUpdate(forPrefix:) - Filter path updates for a node
  • .ok - Filter for .ok responses
  • .error - Filter for .error responses
  • .noMoreMessages - Filter for no-more-messages events
  • .messagesWaiting - Filter for messages-waiting events

Combinators:

  • or(_:) - Combine with OR logic
  • and(_:) - Combine with AND logic
  • negated - Invert the filter

MeshCoreError (public, enum)

File: MeshCore/Sources/MeshCore/Session/SessionConfiguration.swift

Errors that can occur during mesh operations.

CaseDescription
.timeoutOperation timed out
.deviceError(code: UInt8)The device returned an error code
.parseError(String)Failed to parse data from the device
.notConnectedThe transport is not connected
.commandFailed(CommandCode, reason: String)A command failed on the device
.invalidResponse(expected: String, got: String)Received an unexpected response from the device
.contactNotFound(publicKeyPrefix: Data)Could not find the specified contact
.dataTooLarge(maxSize: Int, actualSize: Int)The data exceeds the device's maximum allowed size
.signingFailed(reason: String)Cryptographic signing failed
.invalidInput(String)Provided input is invalid
.unknown(String)An unknown error occurred
.bluetoothUnavailableBluetooth is unavailable on this device
.bluetoothUnauthorizedApp is not authorized to use Bluetooth
.bluetoothPoweredOffBluetooth is powered off
.connectionLost(underlying: Error?)The connection was lost
.sessionNotStartedThe session has not been started
.featureDisabledThe requested feature is disabled on the device

SelfInfo (public, struct)

File: MeshCore/Sources/MeshCore/Models/DeviceInfo.swift

Information about the local device, received after session start.

PropertyTypeDescription
advertisementTypeUInt8The type of advertisement used by the device
txPowerInt8The current transmit power level
maxTxPowerInt8The maximum supported transmit power level
publicKeyDataThe node's 32-byte public key
latitudeDoubleThe current latitude coordinate
longitudeDoubleThe current longitude coordinate
multiAcksUInt8Whether multiple acknowledgments are enabled
advertisementLocationPolicyUInt8The policy for location sharing in advertisements
telemetryModeEnvironmentUInt8The environment telemetry reporting mode
telemetryModeLocationUInt8The location telemetry reporting mode
telemetryModeBaseUInt8The base telemetry reporting mode
manualAddContactsBoolWhether contacts must be added manually
radioFrequencyDoubleThe radio center frequency in MHz
radioBandwidthDoubleThe radio bandwidth in kHz
radioSpreadingFactorUInt8The radio spreading factor
radioCodingRateUInt8The radio coding rate
nameStringThe user-defined name for this device

DeviceCapabilities (public, struct)

File: MeshCore/Sources/MeshCore/Models/DeviceInfo.swift

Hardware and firmware capabilities of the device.

PropertyTypeDescription
firmwareVersionUInt8Firmware version number
maxContactsIntMaximum contact storage
maxChannelsIntMaximum channels supported
blePinUInt32BLE PIN code
firmwareBuildStringFirmware build string
modelStringHardware model identifier
versionStringVersion string

BatteryInfo (public, struct)

File: MeshCore/Sources/MeshCore/Models/DeviceInfo.swift

Battery status information from the device.

PropertyTypeDescription
levelIntBattery level in millivolts
usedStorageKBInt?Used storage in kilobytes
totalStorageKBInt?Total storage in kilobytes

MessageSentInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/MessagingPayloads.swift

Information returned after successfully sending a message.

PropertyTypeDescription
routeUInt8Route flag from firmware: 1 = flood, 0 = direct
expectedAckDataExpected acknowledgment code for this message
suggestedTimeoutMsUInt32Suggested timeout in milliseconds for waiting for ACK

ChannelInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/ChannelPayloads.swift

Configuration information for a broadcast channel.

PropertyTypeDescription
indexUInt8Channel index (0-15)
nameStringHuman-readable channel name
secretDataSecret key data for channel encryption

CoreStats (public, struct)

File: MeshCore/Sources/MeshCore/Events/StatsPayloads.swift

Core device statistics from the local device.

PropertyTypeDescription
batteryMVUInt16Battery level in millivolts
uptimeSecondsUInt32Device uptime in seconds
errorsUInt16Total error count
queueLengthUInt8Current transmit queue length

RadioStats (public, struct)

File: MeshCore/Sources/MeshCore/Events/StatsPayloads.swift

Radio statistics from the local device.

PropertyTypeDescription
noiseFloorInt16Noise floor in dBm
lastRSSIInt8Last received signal strength in dBm
lastSNRDoubleLast signal-to-noise ratio in dB
txAirtimeSecondsUInt32Total transmit airtime in seconds
rxAirtimeSecondsUInt32Total receive airtime in seconds

PacketStats (public, struct)

File: MeshCore/Sources/MeshCore/Events/StatsPayloads.swift

Packet statistics from the local device.

PropertyTypeDescription
receivedUInt32Total packets received
sentUInt32Total packets sent
floodTxUInt32Total flood packets transmitted
directTxUInt32Total direct packets transmitted
floodRxUInt32Total flood packets received
directRxUInt32Total direct packets received

StatusResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/DevicePayloads.swift

Status response from a remote node via binary protocol.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of responding node
batteryIntBattery level in millivolts
txQueueLengthIntCurrent transmit queue length
noiseFloorIntNoise floor in dBm
lastRSSIIntLast RSSI in dBm
packetsReceivedUInt32Total packets received
packetsSentUInt32Total packets sent
airtimeUInt32Total TX airtime in seconds
uptimeUInt32Node uptime in seconds
sentFloodUInt32Flood packets sent
sentDirectUInt32Direct packets sent
receivedFloodUInt32Flood packets received
receivedDirectUInt32Direct packets received
fullEventsIntTotal full events recorded
lastSNRDoubleLast SNR in dB
directDuplicatesIntDirect duplicates received
floodDuplicatesIntFlood duplicates received
rxAirtimeUInt32Total RX airtime in seconds

TelemetryResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Telemetry response from a remote node via binary protocol.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of responding node
tagData?Optional correlation tag
rawDataDataRaw telemetry data payload
dataPoints[LPPDataPoint]Parsed Cayenne LPP data points (computed property)

MMAResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Min-Max-Average response from a remote node.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of responding node
tagDataCorrelation tag
data[MMAEntry]List of MMA entries

MMAEntry (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Single entry in MMA response data.

PropertyTypeDescription
channelUInt8Sensor channel
typeStringData type
minDoubleMinimum value
maxDoubleMaximum value
avgDoubleAverage value

ACLResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Access Control List response from a remote node.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of responding node
tagDataCorrelation tag
entries[ACLEntry]List of ACL entries

ACLEntry (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Single entry in ACL response data.

PropertyTypeDescription
keyPrefixDataPublic key prefix affected by this ACL entry
permissionsUInt8Permissions granted

NeighboursResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Neighbour list response from a remote node.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of responding node
tagDataCorrelation tag
totalCountIntTotal number of neighbours known to the node
neighbours[Neighbour]List of neighbours in this response

Neighbour (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Information about a neighbouring node.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of neighbour
secondsAgoIntSeconds since last seen
snrDoubleSignal-to-noise ratio of last communication

ConnectionState (public, enum)

File: MeshCore/Sources/MeshCore/Events/ConnectionState.swift

Represents the current connection state of a MeshCore session.

CasePayloadDescription
.disconnected-Session is disconnected
.connecting-Session is attempting to connect
.connected-Session is successfully connected
.reconnectingattempt: IntSession is attempting to reconnect after failure
.failedMeshTransportErrorConnection failed with error

MeshTransportError (public, enum)

File: MeshCore/Sources/MeshCore/Events/MeshTransportError.swift

Errors that can occur at the transport layer.

CasePayloadDescription
.notConnected-Transport is not connected
.connectionFailedStringConnection attempt failed with reason
.sendFailedStringSending data failed with reason
.deviceNotFound-Target device could not be found
.serviceNotFound-Required service not found on device
.characteristicNotFound-Required characteristic not found on device

TraceInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

Trace route information received from the mesh network.

PropertyTypeDescription
tagUInt32Request correlation tag
authCodeUInt32Authentication code for the trace request
flagsUInt8Configuration flags for the trace
pathLengthUInt8Length of the recorded path
path[TraceNode]List of nodes in the trace path

TraceNode (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

A node in a trace path.

PropertyTypeDescription
hashBytesData?Hash bytes of the node's public key (1, 2, 4, or 8 bytes per path_sz; nil for destination)
hashUInt8?Legacy accessor: first byte of hashBytes, or nil
snrDoubleSignal-to-noise ratio at this hop

PathInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

Path discovery information.

PropertyTypeDescription
publicKeyPrefixDataPublic key prefix of the destination node
outPathLengthUInt8Raw outbound path_len byte (upper 2 bits = hash mode, lower 6 = hop count)
outPathDataOutbound path data
inPathLengthUInt8Raw inbound path_len byte
inPathDataInbound path data

LoginInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/RemoteAdminPayloads.swift

Login success information.

PropertyTypeDescription
permissionsUInt8Permissions granted after login
isAdminBoolWhether the user has administrator privileges
publicKeyPrefixDataPublic key prefix of the node where login occurred

RawDataInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

Raw data received from the device.

PropertyTypeDescription
snrDoubleSignal-to-noise ratio of the received packet
rssiIntReceived signal strength indicator in dBm
payloadDataRaw payload data

LogDataInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

Log data received from the device.

PropertyTypeDescription
snrDouble?Optional signal-to-noise ratio
rssiInt?Optional received signal strength indicator
payloadDataRaw log payload data

ParsedRxLogData (public, struct)

File: MeshCore/Sources/MeshCore/Protocol/RxLogTypes.swift

Parsed RF packet data from rxLogData events.

PropertyTypeDescription
snrDouble?SNR in dB (0.25 dB resolution)
rssiInt?RSSI in dBm
rawPayloadDataOriginal unparsed payload bytes
routeTypeRouteTypeRouting method (flood, direct, tc_flood, tc_direct)
payloadTypePayloadTypeMessage type (header bits 2-5; values 12-14 map to .unknown, 15 maps to .rawCustom)
payloadVersionUInt8Protocol version (0-3)
transportCodeData?4-byte transport code if route type requires it
pathLengthUInt8Number of path nodes
pathNodes[UInt8]Path node identifiers (1 byte each) as emitted by firmware
packetPayloadDataPayload after header/path extraction
packetHashStringFirst 8 bytes of SHA-256 of packetPayload, as 16-char hex
senderPubkeyPrefixData?1-byte sender pubkey hash for direct text messages

ControlDataInfo (public, struct)

File: MeshCore/Sources/MeshCore/Events/DiagnosticsPayloads.swift

Control protocol data received from the device.

PropertyTypeDescription
snrDoubleSignal-to-noise ratio of the received packet
rssiIntReceived signal strength indicator in dBm
pathLengthUInt8Path length the control packet travelled
payloadTypeUInt8Type of control protocol payload
payloadDataRaw payload data

DiscoverResponse (public, struct)

File: MeshCore/Sources/MeshCore/Events/ContactPayloads.swift

Node discovery response.

PropertyTypeDescription
nodeTypeUInt8Type of the discovered node
snrInDoubleInbound signal-to-noise ratio
snrDoubleSignal-to-noise ratio
rssiIntReceived signal strength indicator in dBm
pathLengthUInt8Path length to the discovered node
tagDataRequest correlation tag
publicKeyDataFull public key of the discovered node

Utilities

PacketBuilder (public, enum)

File: MeshCore/Sources/MeshCore/Protocol/PacketBuilder.swift

Stateless enum for constructing binary protocol packets.

PacketParser (public, enum)

File: MeshCore/Sources/MeshCore/Protocol/PacketParser.swift

Stateless enum for parsing binary protocol packets into MeshEvents.

LPPDecoder (public, enum)

File: MeshCore/Sources/MeshCore/LPP/LPPDecoder.swift

Decodes Cayenne Low Power Payload (LPP) telemetry data.

MethodDescription
decode(_:) -> [LPPDataPoint]Decodes raw LPP bytes into data points

LPPDataPoint (public, struct)

File: MeshCore/Sources/MeshCore/LPP/LPPDecoder.swift

Represents a single decoded LPP data point.

PropertyTypeDescription
channelUInt8Channel identifier (application-specific)
typeLPPSensorTypeThe sensor type
valueLPPValueThe decoded value

LPPSensorType (public, enum)

File: MeshCore/Sources/MeshCore/LPP/LPPDecoder.swift

Cayenne LPP sensor types. Includes temperature, humidity, barometer, voltage, gps, and many more.

LPPValue (public, enum)

File: MeshCore/Sources/MeshCore/LPP/LPPDecoder.swift

Decoded LPP sensor values.

CasePayloadDescription
.digitalBoolBoolean value (digital I/O, presence, switch)
.integerIntInteger value (illuminance, percentage, direction)
.floatDoubleFloating-point value
.vector3x, y, z: Double3D vector (accelerometer, gyrometer)
.gpslatitude, longitude, altitude: DoubleGPS coordinates
.rgbred, green, blue: UInt8RGB colour
.timestampDateUnix timestamp

See Also