Ayla Mobile SDK - MQTT Based (nMQTT) Developer Guide
Component: iOS_AylaSDK & Android_AylaSDK › MQTT Based (nMQTT)
SDK Version: iOS 11.0.1 · Android 11.0.1
Platforms: iOS 16.0+ (Swift / Objective-C, Xcode 16+) · Android API 28+ (Java)
Table of Contents
- Overview
- Features
- Design Goals
- Collection of Metrics
- Getting Started
- Installation
- Sample APIs
- nMQTT LAN (LAN Mode v2 — Secure Tunnel)
- App-Specific Changes (Sample Apps: Aura, FastTrack + UsecaseLib)
- License
- Support
- Glossary
- Document Revision History
1. Overview
1.1 Who this guide is for
This guide is for iOS and Android developers integrating real-time device data into an app built on the Ayla Mobile SDK. By the end of this guide, you should understand how nMQTT fits into the SDK session, how to observe connection state and publish datapoints, how to install the component on each platform, how the nMQTT LAN (secure tunnel) path is selected, and where to find the underlying broker contract if you need to port the transport to another client platform.
1.2 What nMQTT is
MQTT based (nMQTT) is the real-time device-data transport of the Ayla mobile SDKs. It maintains a persistent, TLS-secured MQTT 5 session between the mobile app and the Ayla cloud MQTT broker, so property (datapoint) updates flow bidirectionally the moment they occur — without the latency and battery cost of HTTP polling.
nMQTT is implemented natively on both iOS and Android, against the same Ayla cloud broker interface. The two implementations differ only in language, MQTT client library, and local credential storage.
From SDK 10.0.2 onwards, nMQTT devices can also be controlled locally over the LAN using nMQTT LAN (LAN Mode v2 — Secure Tunnel): an encrypted MQTT 5 session directly to the device on the local network, using the same JSON envelope. See Section 8.
nMQTT is selected per device by the cloud. When the cloud marks a device as a native-MQTT device, the SDK sets AylaDeviceTransportType.NMQTT and routes its datapoint reads and writes over the native MQTT session (or the nMQTT LAN tunnel when it is active). Other transports (legacy MQTT/CMQTT, or HTTP) continue to use their existing paths, so nMQTT coexists with them in the same session.
1.3 How it's wired into the SDK
The transport is owned by AylaNMQTTManager on each platform — reachable from the session as AylaSessionManager.nmqttManager (iOS) or AylaSessionManager.getMqttManager() (Android). The SDK wires it up automatically on sign-in: it is created during session start, added as a device-manager listener, and started. Application code does not manage the transport's connect/subscribe/reconnect lifecycle and does not publish to it directly.
iOS 11.x change:
AylaSessionManager.nmqttManageris now declared asid<AylaNMQTTManagerProtocol>(a protocol "firewall" that breaks the ObjC↔Swift circular dependency required for Swift Package Manager support). The protocol's lifecycle and publish methods are for SDK use. To readconnectionState/isConnectedor setdelegate, cast to the concreteAylaNMQTTManagerclass (see Section 5.2).
App integration rule:
- Write datapoints only through the property/device APIs:
createDatapoint(single property) andcreateBatchDatapoint(iOS) /createDatapointBatch(Android) for several properties. - Receive updates only through property-change callbacks:
AylaDeviceListener.device(_:didObserve:)(iOS) /AylaDevice.DeviceChangeListener.deviceChanged(...)(Android). - Do not call the nMQTT manager's publish APIs from app code (
publishDatapoint…,publishGetPropertyRequest…,publishDataPoint(...)), and do not consume raw MQTT messages (addMessageListener). These are SDK-internal: the SDK calls them when it routes acreateDatapointto an nMQTT device.
1.4 End-to-end path through this guide
If you are integrating nMQTT for the first time, the sections below are ordered to match the work you'll actually do:
- Confirm your app meets the platform prerequisites (Section 5.1).
- Install the SDK dependency for your platform (Section 6).
- Reach the manager and observe connection state (Section 5.2–5.3).
- Write datapoints with
createDatapoint/ batch datapoint APIs (Section 5.4). - Receive property changes through device listener callbacks (Section 5.5).
- Understand the lifecycle the SDK manages for you (Section 5.6).
- Understand when the SDK switches an nMQTT device to the LAN tunnel (Section 8).
2. Features
| Feature | Description |
|---|---|
| MQTT 5 over TLS | Persistent, TLS-secured MQTT 5 session with at-least-once (QoS 1) delivery — on iOS via CocoaMQTT 2.3.x (CocoaMQTT5, Swift Package Manager), on Android via the HiveMQ MQTT client 1.4.0 (Mqtt5AsyncClient). |
| Bidirectional datapoints | Publish property changes to devices and receive device-originated datapoint updates and connection-status changes in real time. |
| Get-property (state sync) | Request the current state of one or more properties over MQTT and apply the response to the local AylaDevice model. |
| JWT-based authentication | Uses short-lived JWT-based credentials issued by the Ayla cloud, stored securely on the device and refreshed automatically before they expire. |
| Automatic reconnect & network awareness | Exponential-backoff auto-reconnect, plus network-path monitoring with debounce so Wi-Fi / cellular / captive-portal flaps are handled gracefully. |
| Reliable subscribe and publish | At-least-once delivery, subscription verification with retry, and datapoint publishes deferred (not dropped) while the transport reconnects. |
| Structured messages | A compact, versioned JSON message format supporting integer, string, boolean, decimal, and message datapoint types. |
| nMQTT LAN (secure tunnel) | Local control of nMQTT devices over an encrypted local tunnel. Preferred automatically over cloud when the tunnel is active (Section 8). |
| Native on iOS and Android | Swift/Objective-C on iOS (the manager is also usable from Objective-C) and Java on Android — both presenting the same AylaNMQTTManager concept off the session. |
3. Design Goals
| Goal | How nMQTT achieves it |
|---|---|
| Low-latency, push-based updates | Persistent MQTT 5 session replaces HTTP polling; device datapoints and status arrive as broker PUBLISH messages. |
| Coexistence, not replacement | Transport is chosen per device by the cloud. NMQTT, legacy CMQTT, and HTTPS devices run side-by-side in one session. |
| Local first when available | When the nMQTT LAN tunnel is active for a device, writes and property fetches go over the LAN; otherwise they go through the cloud broker. |
| Resilience on mobile networks | Auto-reconnect with backoff, network-path debounce, subscribe verification/retry, and deferred publishes during reconnect. |
| Secure by default | TLS to the broker, JWT-based authentication, credentials kept in secure platform storage and refreshed automatically. LAN traffic is encrypted end-to-end. |
| Zero-boilerplate for apps | Lifecycle (connect / subscribe / reconnect / teardown) is fully managed by the SDK session; apps publish datapoints and observe state only. Managers are torn down on sign-out. |
| Platform-neutral design | Built on open standards (MQTT 5, TLS, JWT, JSON). |
4. Collection of Metrics
nMQTT does not embed any third-party analytics or user-tracking. "Metrics" here means the operational and diagnostic signals the transport produces for observability and troubleshooting:
- Connection state. On iOS,
AylaNMQTTManager.connectionState(uninitialized|connecting|connected|disconnected) andisConnected, with state transitions delivered toAylaNMQTTManagerDelegate.mqttConnectionState(state:). On Android,getConnectionStatus()plusConnectionListener.onConnected()/OnDisconnected(Throwable). - Structured logging. All components log through the SDK log facility (
AylaLogD/AylaLogEon iOS, backed byAylaLogManager;AylaLogon Android), tagged per component. Connection, authentication, subscription and disconnect events are logged. - Subscribe summary. A per-session summary of subscribed / pending / failed topics is emitted so subscription health can be audited.
- Delivery confirmation. Each publish completes only when the broker acknowledges it.
On iOS, log verbosity is governed by the SDK's own log level. AylaMetricsManager is deprecated on iOS and is not used by nMQTT. On Android, diagnostics flow through AylaLog, with feature metrics reported through AylaMetricsManager. In both cases, nMQTT emits operational signals only — there is no third-party user analytics inside the transport.
5. Getting Started
5.1 Prerequisites
Before you start, confirm you have:
- An Ayla account with at least one device enabled for native MQTT (nMQTT) in the Ayla cloud.
- iOS: Xcode 16.0 or later with an iOS 16.0+ deployment target. The SDK is distributed only via Swift Package Manager from 11.0.0 — CocoaPods is no longer supported.
- Android: Android Studio with
minSdk 28(Android 9) or higher. SDK 11.0.1 builds withcompileSdk/targetSdk36. - No broker host, port, or credentials to configure yourself — nMQTT obtains its connection details and credentials from the Ayla cloud at runtime.
In normal use you do not create nMQTT yourself — the SDK session owns it. The typical flow follows.
5.2 Reach the manager
// Swift
import iOS_AylaSDK
// `nmqttManager` is typed as `any AylaNMQTTManagerProtocol`; cast to the concrete
// class to read state or set the delegate.
guard let nmqtt = sessionManager.nmqttManager as? AylaNMQTTManager else { return }
let state = nmqtt.connectionState // "connected", "connecting", ...
let live = nmqtt.isConnected // Bool5.3 Observe connection state
// Swift
final class Monitor: AylaNMQTTManagerDelegate {
func mqttConnectionState(state: AylaNMQTTConnectionState) {
print("nMQTT is now \(state.rawValue)")
}
}
nmqtt.delegate = monitor // weak reference — keep `monitor` aliveExpected result: your delegate receives mqttConnectionState(state:) callbacks as the session moves through uninitialized → connecting → connected, and back to disconnected on network loss or sign-out. Callbacks may arrive on a background queue — dispatch to the main queue before touching UI.
5.4 Write datapoints (createDatapoint and batch)
createDatapoint and batch)Use the property and device APIs to write values. The SDK picks the transport for each NMQTT device (nMQTT LAN when active, otherwise the cloud MQTT session), so the same code works for nMQTT, legacy MQTT, LAN, BLE and HTTP devices.
Single property — createDatapoint:
// Swift
let params = AylaDatapointParams()
params.value = 1
property.createDatapoint(params, success: { datapoint in
// Delivered over nMQTT LAN (if active) or the cloud MQTT session
}, failure: { error in
// e.g. device offline, missing OEM id, publish timeout
})Several properties in one request — createBatchDatapoint:
// Swift
let power = AylaDatapointParams(); power.value = 1
let mode = AylaDatapointParams(); mode.value = "eco"
let batch = [
AylaDatapointBatchRequest(datapoint: power, property: powerProperty),
AylaDatapointBatchRequest(datapoint: mode, property: modeProperty),
]
_ = device.createBatchDatapoint(batch, success: { responses in
for r in responses { print("\(r.propertyName) status=\(r.statusCode)") }
}, failure: { error in
// handle failure
})Routing for an NMQTT device:
- nMQTT LAN active (
device.isNMQTTLanModeActive()and the property supports local control) → sent over the LAN tunnel. - Otherwise → sent over the cloud nMQTT session. File base-type properties continue to use the HTTP cloud API.
- A write fails fast with
AylaRequestErrorCodePreconditionFailureif the device is offline or has no OEM id.
Do not call
AylaNMQTTManager.publishDatapoint(...)orpublishGetPropertyRequest(...)from app code. They are SDK-internal and bypass the property model, LAN routing and caching.
5.5 Receive property changes (callbacks)
Datapoints and status updates that arrive over nMQTT (cloud or LAN) are applied to the AylaDevice / AylaProperty model and delivered through the standard device listener. Register a listener on each device you display:
// Swift
final class DeviceObserver: NSObject, AylaDeviceListener {
func device(_ device: AylaDevice, didObserve change: AylaChange) {
if let propertyChange = change as? AylaPropertyChange {
let name = propertyChange.propertyName
let value = propertyChange.value
DispatchQueue.main.async { /* update UI for name/value */ }
}
}
func device(_ device: AylaDevice, didFail error: Error) { /* handle error */ }
}
device.add(observer) // [device addListener:observer]
// ...
device.remove(observer) // when the screen goes awayExpected result: each property update from the device triggers device(_:didObserve:) with an AylaPropertyChange, whichever transport delivered it.
5.6 Lifecycle (managed by the SDK)
nmqtt.resume() // start / resume when there are NMQTT devices
nmqtt.pause() // disconnect, keep listener (app background / DS pause)
nmqtt.shutDown() // disconnect, clear broker auth, remove listener (sign-out)The session calls resume on start, pause on background/data-stream pause, and shutDown on teardown, so most apps never call these directly. These three methods are also available directly on sessionManager.nmqttManager (they are part of AylaNMQTTManagerProtocol).
Expected result: you should not need to call resume(), pause(), or shutDown() from application code under normal use. If you find yourself calling them directly, confirm the session lifecycle isn't already handling the transition you're trying to make.
5.7 Android equivalents
// Android (Java)
// 1) Write a single property — SDK picks nMQTT LAN or the cloud nMQTT session
property.createDatapoint(value, /* metadata */ null,
datapoint -> { /* success */ },
error -> { /* failure */ });
// 2) Write several properties in one request
AylaDatapointBatchRequest[] batch = {
new AylaDatapointBatchRequest<>(1, powerProperty),
new AylaDatapointBatchRequest<>("eco", modeProperty)
};
device.createDatapointBatch(batch,
responses -> { /* success */ },
error -> { /* failure */ });
// 3) Receive property changes
device.addListener(new AylaDevice.DeviceChangeListener() {
@Override public void deviceChanged(AylaDevice d, Change change) {
if (change instanceof PropertyChange) {
PropertyChange<?> pc = (PropertyChange<?>) change;
String name = pc.getPropertyName();
Object value = pc.getValue();
// update UI on the main thread
}
}
@Override public void deviceError(AylaDevice d, AylaError error) { }
@Override public void deviceLanStateChanged(AylaDevice d, boolean lanEnabled, AylaError error) { }
});
// Optional: observe nMQTT connection state
AylaNMQTTManager nmqtt = sessionManager.getMqttManager();
boolean live = nmqtt.getConnectionStatus();
nmqtt.addConnectionListener(new AylaNMQTTConnection.ConnectionListener() {
@Override public void onConnected() { /* ... */ }
@Override public void OnDisconnected(@NonNull Throwable t) { /* ... */ }
});Lifecycle is driven by AylaNetworks.sharedInstance().onResume() / onPause(); apps do not call AylaNMQTTManager.onResume()/onPause()/shutDown() directly. Do not use publishDataPoint(...) or addMessageListener(...) from app code.
6. Installation
6.1 iOS (Swift Package Manager)
From 11.0.0, the Ayla iOS SDK is distributed exclusively via Swift Package Manager. iOS_AylaSDK.podspec, the Podfile, the .xcodeproj and the CocoaPods workspace have been removed. nMQTT ships inside the core iOS_AylaSDK product — there is no separate package to add.
In Xcode: File ▸ Add Package Dependencies… → enter the iOS_AylaSDK package URL → choose a rule (e.g. Up to Next Major Version, from 11.0.1) → add the iOS_AylaSDK product to your app target.
Via Package.swift:
dependencies: [
.package(url: "https://<path_to>/iOS_AylaSDK", from: "11.0.1")
],
targets: [
.target(
name: "MyApp",
dependencies: [
.product(name: "iOS_AylaSDK", package: "iOS_AylaSDK") // nMQTT is in the core product
]
)
]// iOS_AylaSDK Package.swift (relevant lines)
platforms: [.iOS(.v16)],
products: [
.library(name: "iOS_AylaSDK", targets: ["iOS_AylaSDK"]), // core (includes nMQTT)
.library(name: "iOS_AylaSDKAVS", targets: ["iOS_AylaSDKAVS"]), // optional video add-on
.library(name: "iOS_AylaSDKCopilot", targets: ["iOS_AylaSDKCopilot"]), // optional Copilot add-on
],
dependencies: [
.package(url: "https://github.com/emqx/CocoaMQTT.git", from: "2.3.0"), // MQTT 5 client
// ...
]Then import iOS_AylaSDK in any file that uses nMQTT. Import only the three public products — the underscore-prefixed ObjC targets (_iOS_AylaSDKObjC, …) are internal.
Requirements: iOS 16.0+, Xcode 16.0+. No broker host, port, or credentials need to be configured by the app — nMQTT obtains the broker host and JWT from the cloud at runtime.
Migrating from 10.x (CocoaPods): replace pod 'iOS_AylaSDK' with the SPM dependency above. import iOS_AylaSDK still exposes the full core API, so nMQTT call sites do not change, except that sessionManager.nmqttManager is now protocol-typed (cast as shown in Section 5.2). If the app also uses the Copilot add-on, add -ObjC to Other Linker Flags (see the SDK README, Firebase note).
Expected result: package resolution completes without conflicts, and AylaNMQTTManager, AylaNMQTTManagerDelegate, and AylaNMQTTConnectionState are available after import iOS_AylaSDK.
6.2 Android (Gradle)
On Android, nMQTT ships inside the Ayla Android SDK library module (package com.aylanetworks.aylasdk.mqtt, with nMQTT LAN in com.aylanetworks.aylasdk.localcontrol.nmqttlan). Add the SDK module (or the generated AylaSDK.aar) to your app:
// settings.gradle (app project)
include ':aylasdk'
project(':aylasdk').projectDir = new File('<path to>/Android_AylaSDK/library')
// app/build.gradle
dependencies {
implementation project(':aylasdk')
}// Android_AylaSDK/library/build.gradle (relevant lines, release 11.0.1)
android {
namespace "com.aylanetworks.aylasdk"
compileSdk 36
defaultConfig {
minSdk 28 // Android 9 (Pie) and newer
targetSdk 36
}
}
dependencies {
// MQTT 5 client used by nMQTT (and MDSS v2):
implementation 'com.hivemq:hivemq-mqtt-client:1.3.3'
}If you consume the .aar instead of the module, apply the SDK's dependencies.gradle in your project so transitive dependencies such as the HiveMQ client are on the classpath. The SDK version is reported by AylaNetworks.getVersion() ("11.0.1").
The SDK obtains broker host, port, and credentials from the cloud auth response at runtime — no manual broker configuration is required.
Expected result: the project syncs and builds with com.aylanetworks.aylasdk.mqtt.AylaNMQTTManager resolvable from your app module.
7. Sample APIs
App-facing APIs for nMQTT devices. Apps write datapoints through the property/device APIs and receive changes through device listener callbacks. The AylaNMQTTManager publish methods are SDK-internal and are not part of the app API.
7.1 iOS — write datapoints
// AylaProperty
- (nullable AylaConnectTask *)createDatapoint:(AylaDatapointParams *)datapointParams
success:(void (^)(AylaDatapoint *createdDatapoint))successBlock
failure:(void (^)(NSError *error))failureBlock;
// AylaDevice
- (nullable AylaConnectTask *)createBatchDatapoint:(NSArray<AylaDatapointBatchRequest *> *)datapointBatch
success:(void (^)(NSArray<AylaDatapointBatchResponse *> *datapoints))successBlock
failure:(void (^)(NSError *error))failureBlock;
// AylaDatapointBatchRequest
- (instancetype)initWithDatapoint:(AylaDatapointParams *)datapointParams
property:(AylaProperty *)property;7.2 iOS — receive property changes
@protocol AylaDeviceListener <NSObject>
- (void)device:(AylaDevice *)device didObserveChange:(AylaChange *)change; // AylaPropertyChange for property updates
- (void)device:(AylaDevice *)device didFail:(NSError *)error;
@end
// AylaDevice
- (void)addListener:(id<AylaDeviceListener>)listener;
- (void)removeListener:(id<AylaDeviceListener>)listener;
// AylaPropertyChange
@property (nonatomic, readonly) NSString *propertyName;
@property (nonatomic, readonly, nullable) id value;
@property (nonatomic, readonly, nullable) AylaDatapoint *datapoint;7.3 iOS — connection state (optional)
// Cast the protocol-typed session property to read state / set the delegate
let nmqtt = sessionManager.nmqttManager as? AylaNMQTTManager
nmqtt?.connectionState // "uninitialized" | "connecting" | "connected" | "disconnected"
nmqtt?.isConnected
nmqtt?.delegate = monitor // AylaNMQTTManagerDelegate
public protocol AylaNMQTTManagerDelegate: AnyObject {
func mqttConnectionState(state: AylaNMQTTConnectionState)
}
public enum AylaNMQTTConnectionState: String {
case uninitialized, connecting, connected, disconnected
}7.4 Android — write datapoints
// AylaProperty<T>
public AylaAPIRequest createDatapoint(T value, Map<String, String> metadata,
Response.Listener<AylaDatapoint<T>> successListener,
ErrorListener errorListener)
// AylaDevice
public AylaAPIRequest createDatapointBatch(AylaDatapointBatchRequest[] requests,
Response.Listener<AylaDatapointBatchResponse[]> successListener,
ErrorListener errorListener)
// AylaDatapointBatchRequest<T>
public AylaDatapointBatchRequest(T datapointValue, AylaProperty<T> property)7.5 Android — receive property changes
// AylaDevice
public void addListener(DeviceChangeListener listener)
public void removeListener(DeviceChangeListener listener)
public interface DeviceChangeListener {
void deviceChanged(AylaDevice device, Change change); // PropertyChange for property updates
void deviceError(AylaDevice device, AylaError error);
void deviceLanStateChanged(AylaDevice device, boolean lanModeEnabled, AylaError error);
}
// PropertyChange<T>
public String getPropertyName()
public T getValue()7.6 Android — connection state (optional)
AylaNMQTTManager nmqtt = sessionManager.getMqttManager();
public boolean getConnectionStatus()
public void addConnectionListener(AylaNMQTTConnection.ConnectionListener l)
public interface ConnectionListener { void onConnected(); void OnDisconnected(@NonNull Throwable t); }7.7 SDK-internal APIs (do not call from apps)
| Platform | API | Use instead |
|---|---|---|
| iOS | AylaNMQTTManager.publishDatapoint(withDsn:…) / publishDatapointWithDsn:… | AylaProperty.createDatapoint / AylaDevice.createBatchDatapoint |
| iOS | AylaNMQTTManager.publishGetPropertyRequest(…) | Property values on AylaDevice + AylaDeviceListener callbacks |
| iOS | AylaNMQTTManager.resume() / pause() / shutDown() | AylaNetworks.shared().resume() / pause() |
| Android | AylaNMQTTManager.publishDataPoint(...) | AylaProperty.createDatapoint / AylaDevice.createDatapointBatch |
| Android | AylaNMQTTManager.addMessageListener(...) / addSubscribeListener(...) | AylaDevice.DeviceChangeListener.deviceChanged |
| Android | AylaNMQTTManager.connect(...) / disconnect() / onResume() / onPause() / shutDown() | AylaNetworks.sharedInstance().onResume() / onPause() |
8. nMQTT LAN (LAN Mode v2 — Secure Tunnel)
Introduced in SDK 10.0.2 on both platforms. nMQTT LAN lets the app control an nMQTT device directly on the local network, in parallel with (and preferred over) the cloud broker path. It runs alongside the legacy HTTP LAN mode, which is still used for non-nMQTT devices.
8.1 How it is selected
- Only devices with
transportType == NMQTTuse nMQTT LAN; the same devicelocal_key/ local connection config as legacy LAN is used. - When the tunnel is active,
AylaProperty.createDatapointroutes to the LAN (iOS:createDatapointNMQTTLAN, gated bydevice.isNMQTTLanModeActive(); Android:createDatapointNMqttLan, gated bydevice.isLanModeActive()), and property fetches can useAylaDevice.fetchPropertiesNMQTTLAN(...)(iOS). - Updates received over the tunnel are tagged with data source
AylaDataSourceNMQTTLAN(iOS). - iOS: set
AylaSystemSettings.forceNMQTTLanDisable = YESto disable nMQTT LAN for development and testing.
9. App-Specific Changes (Sample Apps)
This section shows how two Ayla reference apps adopt nMQTT on SDK 11.x. Both apps follow the same rule: app code never drives the nMQTT transport directly. Apps change three things only — how they link the SDK, how they forward app lifecycle to the SDK session, and (optionally) how they present the active transport. Property writes keep using the high-level createDatapoint API, and the SDK routes them to nMQTT LAN, the nMQTT broker, or HTTP.
| App | Role | SDK integration | SDK release |
|---|---|---|---|
Aura (iOS_Aura / Android_Aura) | Direct SDK sample / test app | Calls the SDK directly | 11.0.1 |
FastTrack (iOS_Hybrid_FastTrack / Android_Hybrid_FastTrack) | Production-style sample app | Calls the SDK through UsecaseLib (UsecaseLib_iOS / UsecaseLib_Android) | 11.0.1 |
9.1 Summary of required app changes
| Change | Aura iOS | Aura Android | FastTrack + UClib iOS | FastTrack + UClib Android |
|---|---|---|---|---|
| SDK linking | SPM via local wrapper package AylaSDKKit | Gradle module :aylasdk | FT → UsecaseLib_iOS SPM package → iOS_AylaSDK | FT → :UsecaseLib_Android → :aylasdk modules |
| Min platform | iOS 16 | minSdk 28 / compile+target 36 | iOS 16 | FT minSdk 29 / compileSdk 36 (Config); UClib minSdk 28 / compileSdk 35 |
| Lifecycle → SDK | SceneDelegate → AylaNetworks.shared().pause()/resume() | MainActivity.onResume/onStop → AylaNetworks.sharedInstance().onResume()/onPause() | AppUsecase.updateDeviceManagerState(.pause/.resume) | ApplicationObserver → AppUsecaseImpl → WorkManager ApplicationPauseWorker |
| Onboarding (AP hop) | Pause session before joining device AP, resume after | — | — | — |
| Property write | AylaProperty.createDatapoint(_:success:failure:) | createDatapoint(value, metadata, …); batch uses createDatapointBatchLanMqtt for NMQTT | SdkInteractor → createDatapoint(_:success:failure:) | SdkInteractor.updateDeviceProperty → createDatapoint(value, echo, metadata, …) |
| State updates | AylaDeviceListener.device(_:didObserve:) | DeviceChangeListener.deviceChanged | SdkInteractor.device(_:didObserve:) → Rx deviceStateChangeSubject | SdkInteractor.deviceChanged → background processor |
| Transport display | Treats reported Offline as authoritative; checks isNMQTTLanModeActive() | isLanModeActive() | isOnline() in state consumers | isLanEnabled (echo handling) |
9.2 Aura — iOS
a) Link the SDK through SPM (no CocoaPods). Aura adds a small local package, AylaSDKKit, to the Xcode project. The package depends on the SDK release tag and re-exports the three SDK products:
// iOS_Aura/AylaSDKKit/Package.swift (abridged)
let package = Package(
name: "AylaSDKKit",
platforms: [.iOS(.v16)],
products: [.library(name: "AylaSDKKit", targets: ["AylaSDKKit"])],
dependencies: [
.package(url: "https://<path_to>/iOS_AylaSDK.git", from: "11.0.1")
],
targets: [
.target(name: "AylaSDKKit",
dependencies: [
.product(name: "iOS_AylaSDK", package: "iOS_AylaSDK"), // includes nMQTT
.product(name: "iOS_AylaSDKAVS", package: "iOS_AylaSDK"),
.product(name: "iOS_AylaSDKCopilot", package: "iOS_AylaSDK"),
],
path: "Sources/AylaSDKKit")
])
// iOS_Aura/AylaSDKKit/Sources/AylaSDKKit/AylaSDKKit.swift
@_exported import iOS_AylaSDK
@_exported import iOS_AylaSDKAVS
@_exported import iOS_AylaSDKCopilotb) Forward app lifecycle to the session. The session in turn calls nmqttManager.pause() / resume(). pause/resume are reference-counted in the SDK, so they compose with other pause holders:
// iOS_Aura/SceneDelegate.swift
func sceneDidEnterBackground(_ scene: UIScene) {
AylaNetworks.shared().pause() // pauses nMQTT, LAN and polling
}
func sceneWillEnterForeground(_ scene: UIScene) {
AylaNetworks.shared().resume() // nMQTT reconnects and re-subscribes
}c) Pause the session during the Wi-Fi setup AP hop. While the phone is joined to the device's setup hotspot there is no route to the broker. Aura pauses the session once, so nMQTT does not churn through disconnect/reconnect cycles, and releases the pause exactly once on success, failure, or abandonment:
// iOS_Aura/Setup/GuidedSetupModel.swift
private var didHoldSessionPauseForAPHop = false
private func pauseSessionForAPHopIfNeeded() {
guard !didHoldSessionPauseForAPHop else { return }
didHoldSessionPauseForAPHop = true
AylaLogD(tag: logTag, flag: 0, message: "AP-hop: pausing session (nMQTT/LAN/polling) before joining device AP")
AylaNetworks.shared().pause()
}
private func resumeSessionAfterAPHopIfNeeded() {
guard didHoldSessionPauseForAPHop else { return }
didHoldSessionPauseForAPHop = false
AylaLogD(tag: logTag, flag: 0, message: "AP-hop: resuming session (nMQTT/LAN/polling)")
AylaNetworks.shared().resume()
}
deinit { resumeSessionAfterAPHopIfNeeded() } // safety net if the flow is abandonedd) Write a property (unchanged API, SDK picks the transport).
// iOS_Aura/Device/Model/PropertyModel.swift
let dpParams = AylaDatapointParams()
dpParams.value = val
self.property.createDatapoint(dpParams, success: { (_: AylaDatapoint) in
DispatchQueue.main.async {
AylaLogD(tag: self.logTag, flag: 0, message: "Created datapoint.")
}
}, failure: { error in
DispatchQueue.main.async { error.displayAsAlertController() }
})e) Detect the nMQTT LAN path (test/diagnostic screens).
// iOS_Aura/Test/BatchDpTetsVC.swift
if device?.transportType == .NMQTT && device?.isNMQTTLanModeActive() == true {
sequencer.addTest("testCreateBatchDatapointNMQTTLAN") { [weak self] tc in self?.testCreateBatchDatapoint(tc) }
} else if device?.isLanModeActive() == true {
sequencer.addTest("testCreateBatchDatapointLAN") { [weak self] tc in self?.testCreateBatchDatapoint(tc) }
} else if device?.isBleModeActive() == true {
sequencer.addTest("testCreateBatchDatapoint BLE") { [weak self] tc in self?.testCreateBatchDatapoint(tc) }
} else {
sequencer.addTest("testCreateBatchDatapoint cloud") { [weak self] tc in self?.testCreateBatchDatapoint(tc) }
}
// Same batch call for every transport — the SDK routes it
_ = device.createBatchDatapoint(batchRequest, success: { responses in /* ... */ },
failure: { error in /* ... */ })
// iOS_Aura/Device/Test/NetworkProfilerModel.swift — include nMQTT LAN in "local" tests
if (device.isLanModeActive() || device.isNMQTTLanModeActive()) && lanTests { /* ... */ }f) Connection status display. nMQTT devices push connectionStatus promptly, while the LAN flag can stay true for a while after the device loses power. Aura therefore lets a reported Offline win:
// iOS_Aura/Utils.swift — extension AylaDevice
func getConnectionStatusDisplayString() -> String {
let connStatus = String.stringFromStringNumberOrNil(self.connectionStatus as AnyObject?)
// connectionStatus is authoritative once the SDK has reported it; a reported Offline
// must win over a possibly-stale LAN/BLE flag.
if self.connectionStatus != nil && connStatus == "Offline" {
return "Offline"
}
// ... otherwise show "(App -> Device via LAN/BLE)" or "(App -> Cloud -> Device)"
}Open item in Aura:
getViaConnectionStatus()labels only BLE and legacy LAN. An nMQTT LAN session currently shows as "(App -> Cloud -> Device)". Add anisNMQTTLanModeActive()branch if you want the label to say LAN.
9.3 Aura — Android
a) Link the SDK module and raise the SDK levels.
// Android_Aura/settings.gradle
include ':app', ':aylasdk'
project(':aylasdk').projectDir = new File('libraries/Android_AylaSDK/library')
// Android_Aura/app/build.gradle
android {
compileSdk 36
defaultConfig {
minSdk 28 // SDK 11.0.1 minimum
targetSdk 36
}
}
dependencies {
implementation project(':aylasdk')
}b) Forward lifecycle to the SDK. Aura resumes in onResume and pauses in onStop (not onPause, so short interruptions such as dialogs or permission prompts do not drop the nMQTT session):
// Android_Aura/.../MainActivity.java
@Override
protected void onPause() {
super.onPause();
// AylaNetworks.sharedInstance().onPause(); // intentionally moved to onStop()
}
@Override
protected void onResume() {
super.onResume();
AylaNetworks.sharedInstance().onResume(); // → AylaNMQTTManager.onResume()
}
@Override
protected void onStop() {
super.onStop();
AylaNetworks.sharedInstance().onPause(); // → AylaNMQTTManager.onPause()
}c) Write a property / batch. Single writes use the normal API. For batch writes over LAN, Aura picks the nMQTT LAN batch call for NMQTT devices:
// Single datapoint (LanDatapointTestCase.java)
customProp.createDatapoint(dpObject, /* metadata */ null, future, future);
// Batch (test/BatchDpTest.java)
if ("Cloud".equalsIgnoreCase(_selectedTransport)) {
device.createDatapointBatchCloud(requestsArray, future, future);
} else if ("LAN".equalsIgnoreCase(_selectedTransport)) {
if (device.getTransportType() == AylaDevice.AylaDeviceTransportType.NMQTT) {
device.createDatapointBatchLanMqtt(requestsArray, future, future); // nMQTT LAN
} else {
device.createDatapointBatchLAN(requestsArray, future, future); // legacy LAN
}
} else if ("BLE".equalsIgnoreCase(_selectedTransport)) {
device.createDatapointBatchBLE(requestsArray, future, future);
} else {
device.createDatapointBatch(requestsArray, future, future); // SDK decides
}9.4 FastTrack + UsecaseLib — iOS
FastTrack does not import the SDK for device control. It depends on the UsecaseLib_iOS Swift package, and UsecaseLib owns every SDK call (SdkInteractor). nMQTT adoption happens almost entirely inside UsecaseLib.
a) Dependency chain (SPM). FastTrack (Xtreme.xcodeproj) links the UsecaseLib_iOS product (https://<path_to>/UsecaseLib_iOS.git). UsecaseLib depends on the SDK by release tag:
// UsecaseLib_iOS/Package.swift (abridged)
let package = Package(
name: "UsecaseLib_iOS",
platforms: [.iOS(.v16)],
products: [.library(name: "UsecaseLib_iOS", targets: ["UsecaseLib_iOS"])],
dependencies: [
.package(url: "https://<path_to>/iOS_AylaSDK.git", exact: "11.0.1"),
/* RxSwift, Alamofire, ... */
],
...
)Pin UsecaseLib to SDK release 11.0.1 (or later) to pick up the latest nMQTT fixes.
b) Configure once from the app.
// iOS_Hybrid_FastTrack/Xtreme/App/AppModule/AppModule.swift
static func applyUsecaseLibrarySDKFromFTConfiguration(buildContext: AppBuildContext = .hybridFT) {
guard let root = FTConfiguration.shared.config else { return }
UsecaseLibraryModule.setupSDKConfig(
rootConfig: root.sdkConfig, // sessionName, appId, service location, ...
moduleConfigs: [ /* per-module feature flags */ ])
}c) Lifecycle → SDK (inside UsecaseLib). The app reports foreground/background to UsecaseLib, and UsecaseLib pauses or resumes the SDK session, which pauses or resumes nMQTT:
// UsecaseLib_iOS/.../Common/AppModule/Usecase/AppUsecase.swift
func updateDeviceManagerState(state: DeviceManagerUpdateState) {
switch state {
case .pause: AylaNetworks.shared().pause()
case .resume: AylaNetworks.shared().resume()
}
}d) Property write (inside UsecaseLib). The same createDatapoint call serves cloud, nMQTT broker and nMQTT LAN devices. 401 errors are surfaced as an auth challenge:
// UsecaseLib_iOS/.../Wrapper/Plugs/SdkInteractor+Plugs.swift (abridged)
let sessionManager = AylaNetworks.shared()
.getSessionManager(withName: UsecaseLibraryModule.shared.sdkConfig.sessionName)
guard let device = sessionManager?.deviceManager.devices[sourcePlugState.id] as? AylaDevice,
let property = device.properties?[PlugEditableProperty.outlet1.rawValue] as? AylaProperty
else { return }
let value = AylaDatapointParams()
value.value = sourcePlugState.outlet1 ? 1 : 0
property.createDatapoint(value) { _ in
completion(SignalingEvent(id: SignalingEventId(id: device.dsn ?? sourcePlugState.id,
signalingEventKey: .power), type: .response))
} failure: { [weak self] error in
if (error as NSError).ayla_httpStatusCode == HTTPStatusConstants.httpUnauthorized {
self?.isAuthenticatedSubject.onNext(.challenged)
}
completion(SignalingEvent(id: SignalingEventId(id: device.dsn ?? sourcePlugState.id,
signalingEventKey: .power), type: .error))
}e) Receive device updates (inside UsecaseLib). Datapoints and status that arrive over nMQTT reach UsecaseLib through the normal AylaDeviceListener callback. UsecaseLib serializes them on a barrier queue and publishes them to the UI as Rx events:
// UsecaseLib_iOS/.../Wrapper/Sdk/SdkInteractor/SdkInteractor.swift
func device(_ device: AylaDevice, didObserve change: AylaChange) {
GlobalQueues.shared.propertyChangesIn.queue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
self.deviceStateChangeSubject.onNext(DeviceWithChange(device: device, change: change))
}
}9.5 FastTrack + UsecaseLib — Android
a) Module chain and SDK levels.
// Android_Hybrid_FastTrack/settings.gradle
include ':app', ':aylasdk', ':UsecaseLib_Android', ':mesh'
project(':aylasdk').projectDir = new File('libraries/Android_AylaSDK/library')
project(':UsecaseLib_Android').projectDir = new File('libraries/UsecaseLib_Android/UsecaseLib_Android')
project(':mesh').projectDir = new File('libraries/UsecaseLib_Android/mesh')// Android_Hybrid_FastTrack/buildSrc/src/main/kotlin/Dependencies.kt
const val minSdkVersion = 29
const val compileSdkVersion = 36// UsecaseLib_Android/UsecaseLib_Android/build.gradle.kts
android {
compileSdk = 35
defaultConfig { minSdk = 28 }
}
dependencies {
if (project.findProject(":aylasdk") != null) {
api(project(mapOf("path" to ":aylasdk"))) // SDK (incl. nMQTT) exposed to the app
}
}b) Lifecycle → SDK. FastTrack reports process lifecycle to UsecaseLib. UsecaseLib defers the pause to a WorkManager job, so a quick app switch does not tear down nMQTT, and resumes only if a pause actually ran:
// Android_Hybrid_FastTrack/app/.../ApplicationObserver.kt
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
appUseCase.updateLifecycleEvent(AppLifecycleEvent.onPause)
appUseCase.createBackGroundTask(AppLifecycleEvent.onPause.toString(), owner)
}
// UsecaseLib_Android/.../common/appmodule/AppUsecaseImpl.kt
AppLifecycleEvent.onResume.name -> {
if (PreferenseUtils.getBoolean(PreferenseUtils.APP_PAUSE, false)) {
AylaNetworks.sharedInstance().onResume() // → AylaNMQTTManager.onResume()
PreferenseUtils.putBoolean(PreferenseUtils.APP_PAUSE, false)
}
workManager.cancelAllWorkByTag(LIFE_CYCLE_SESSION_TAG)
}
AppLifecycleEvent.onPause.name -> {
workManager.cancelAllWorkByTag(LIFE_CYCLE_SESSION_TAG)
workManager.enqueue(OneTimeWorkRequestBuilder<ApplicationPauseWorker>()
.addTag(LIFE_CYCLE_SESSION_TAG).build())
}
class ApplicationPauseWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
AylaNetworks.sharedInstance().onPause() // → AylaNMQTTManager.onPause()
// ... sets APP_PAUSE = true
return Result.success()
}
}c) Property write (inside UsecaseLib). One entry point for every transport. On LAN-enabled devices UsecaseLib sends echo = "none" when the UI does not need an echo:
// UsecaseLib_Android/.../wrapper/sdk/SdkInteractor.kt (abridged)
fun updateDeviceProperty(deviceId: String?, value: Any, property: String,
echo: Boolean, isCloudOnlyProperty: Boolean) {
val sessionManager = AylaNetworks.sharedInstance()
.getSessionManager(UsecaseLibraryModule.getSessionName())
val device = sessionManager?.deviceManager?.deviceWithDSN(deviceId)
val aylaProperty = device?.getProperty(property) ?: return
var metadata: Map<Any, Any>? = null
var echoString: String? = null
if (device.isLanEnabled && !echo) {
metadata = mapOf("echo" to "none"); echoString = "none"
}
if (isCloudOnlyProperty) {
aylaProperty.createDatapointCloud(value, metadata,
Response.Listener { /* success */ },
ErrorListener { error -> /* timeout → clear pending queue */ })
} else {
// SDK routes: nMQTT LAN (if active) → nMQTT broker (NMQTT devices) → LAN/BLE/cloud
aylaProperty.createDatapoint(value, echoString, metadata,
Response.Listener { /* success */ },
ErrorListener { error -> /* timeout → clear pending queue */ })
}
}Note:
createDatapointCloud(...)forces the HTTP cloud API and bypasses nMQTT. Use it only for properties that must be cloud-only. Everything else should go throughcreateDatapoint(...).
d) Receive device updates (inside UsecaseLib).
// UsecaseLib_Android/.../wrapper/sdk/SdkInteractor.kt
override fun deviceChanged(device: AylaDevice?, change: Change?) {
eventChangeBackGroundProcessor.startScheduledTask {
if (change?.type == Change.ChangeType.Property) {
val changeProp = change as PropertyChange<Any>
// reconcile with the pending-write queue, then emit state to the UI
}
}
}9.6 Checklist for other apps
- iOS: move from CocoaPods to SPM (
iOS_AylaSDK≥ 11.0.0); Android:minSdk28 (compile/target SDK 36). - Forward foreground/background to
AylaNetworkspause/resume (iOS) oronResume()/onPause()(Android). Do not callAylaNMQTTManagerlifecycle methods yourself. - Pause the session while the phone is on a device setup AP (recommended, as in Aura iOS).
- Write datapoints only with
createDatapoint/createBatchDatapoint(iOS) orcreateDatapoint/createDatapointBatch(Android). Never call the nMQTT manager's publish APIs. - Receive property changes through
AylaDeviceListener(iOS) /DeviceChangeListener(Android), not raw MQTT message listeners. - Avoid
createDatapointCloudunless the property must be cloud-only. - Treat a reported
connectionStatus = Offlineas authoritative over LAN/BLE flags when you show device status. - If you show the active transport, add
isNMQTTLanModeActive()(iOS) for nMQTT LAN. - Swift: if you need nMQTT connection state, cast
sessionManager.nmqttManager as? AylaNMQTTManager(Section 5.2).
10. License
Both the Ayla iOS SDK and the Ayla Android SDK, including the nMQTT component, are distributed under a commercial license. The LICENSE file in each repository states "Copyright 2026 Ayla Networks, all rights reserved" (iOS) and "Copyright 2026 Ayla Networks, all rights reserved" (Android LICENSE.md).
This is proprietary software, not open source. Use is governed by your commercial agreement with Ayla Networks. Third-party dependencies (for example, CocoaMQTT on iOS and the HiveMQ MQTT client on Android) retain their own respective licenses.
11. Support
nMQTT is maintained by Ayla Networks as part of the iOS_AylaSDK and Android_AylaSDK. For integration help, broker/OEM configuration, or defect reports, contact your Ayla technical account representative or Ayla developer support, and reference the platform and SDK version (iOS 11.0.1 / Android 11.0.1) and the nMQTT component (cloud or LAN).
When reporting an issue, capture SDK logs (enable verbose logging) and the connection-state transitions around the event.
Support email: [email protected]
For source code access: Open a new case with the Ayla Support team at [email protected], providing up to two Google accounts (either corporate or personal registered Google email addresses). Once received, the Ayla Support team will grant those accounts access to the SDK repositories and provide instructions for retrieving your files.
11.1 Troubleshooting
Start by capturing verbose SDK logs and the sequence of mqttConnectionState (iOS) or connection-listener (Android) transitions around the event, then check against the symptoms below.
| Symptom | Likely cause | Recommended action |
|---|---|---|
connectionState stuck at connecting | Broker unreachable, or cloud authentication failing | Confirm network reachability, then check the logged authentication results for the failure reason. |
| Frequent disconnect/reconnect cycles | Network-path flapping (Wi-Fi/cellular/captive portal) not yet debounced, or the idle session timing out | Review the reconnect and network-path debounce log entries; confirm the device isn't on a captive-portal network. |
| Datapoint publish never completes | Transport reconnecting (publish is deferred, not dropped) or broker acknowledgement not received | Check the publish logs; confirm isConnected before assuming the publish was dropped. |
| Publish fails immediately with a precondition error | Device offline, nMQTT manager not available, or device has no OEM id | Confirm device.isOnline() and that the device record has an OEM id. |
| Subscribe never confirms | Subscription not acknowledged by the broker (the SDK retries automatically) | Check the per-session subscribe summary (subscribed / pending / failed) for the device in question. |
| Device shows as an NMQTT device but updates aren't arriving | Device is not marked as a native-MQTT device in the cloud | Confirm the device's transport type in the cloud. |
| Writes go to cloud even though phone and device share a LAN | nMQTT LAN tunnel not active (device not discovered on the LAN, wrong local_key, or disabled) | Check NMQTTLanModule logs; on iOS confirm forceNMQTTLanDisable is NO and isNMQTTLanModeActive() returns YES. |
Swift: connectionState / delegate not found on sessionManager.nmqttManager | Property is protocol-typed since 11.0.0 | Cast: sessionManager.nmqttManager as? AylaNMQTTManager. |
12. Glossary
| Term | Meaning |
|---|---|
| nMQTT / MQTT Based | The SDK's MQTT 5 transport for real-time device data, in MQTT/NativeMQTT (iOS) / com.aylanetworks.aylasdk.mqtt (Android). |
| nMQTT LAN | LAN Mode v2 — encrypted MQTT 5 tunnel directly to an nMQTT device on the local network. |
| MQTT 5 | OASIS pub/sub messaging protocol; used here over TLS with QoS 1. |
| Broker | The cloud MQTT server the client connects to (its address is provided by the Ayla cloud at runtime). |
| DSN | Device Serial Number — unique per device. |
| OEM ID / OEM model | Identifiers for the device manufacturer and product model. |
| Datapoint | A single timestamped value of a device property (integer, string, boolean, decimal, file, or message). |
| Property (get-property) | A named device attribute; a "get-property" request asks for its current state over MQTT. |
| Passthrough property | A property of an nMQTT device flagged passthrough; the SDK exposes hasPassthrough: / hasPassthroughPropertyForString: (iOS) to detect them. |
| Uplink / Downlink | Uplink = device→app messages; Downlink = app→device messages. |
| JWT | JSON Web Token — the short-lived, cloud-issued credential used to authenticate the MQTT session. |
| Client ID | MQTT session identifier, stable per app install. |
| LWT | Last Will and Testament — message the broker publishes if the client drops ungracefully (not enabled in nMQTT yet). |
| QoS 1 | MQTT "at least once" delivery guarantee, used for cloud subscribe and publish. |
| Keep-alive | Interval after which the broker may drop an idle session; pings maintain liveness. |
| PUBACK / SUBACK | Broker acknowledgements for a publish / subscribe; used for delivery confirmation and retry. |
| Transport type | Cloud-assigned per device: NMQTT, legacy CMQTT or HTTPS (both platforms also have LAN and BLE). |
| CMQTT (legacy) | The earlier cloud MQTT (MDSS) transport; on Android now also on HiveMQ (Paho replaced in 10.0.2). Superseded per-device by nMQTT. |
| CocoaMQTT / HiveMQ client | The MQTT 5 client libraries nMQTT builds on — CocoaMQTT 2.3.x (iOS, via SPM) and hivemq-mqtt-client 1.4.0 (Android). |
| DSS | Data Stream Service — Ayla's server-side event stream; mDSS v1 was removed in 11.0.0 and DSSv2 (AylaDSManagerV2) is the data-stream layer alongside nMQTT. |
| SPM | Swift Package Manager — the only supported iOS distribution channel from 11.0.0. |
Updated about 1 month ago

