Skip to content

Configuration

Learn how to configure Pulse MQTT for your application needs.

Bridge Configuration

The PulseMqttKitBridge interface provides dependencies and configuration to the library.

interface PulseMqttKitBridge {
    fun getLogger(): Logger?
    fun getAppGson(): Gson?
    fun getCustomCoroutineScope(): CoroutineScope
    fun getHealthMonitoringConfig(): HealthMonitoringConfig?
    fun getNetworkConfig(): NetworkMonitoringConfig
}

Logger Configuration

Provide a custom logger for library events:

override fun getLogger(): Logger = object : Logger {
    override fun debug(message: String) {
        // Debug logs
        if (BuildConfig.DEBUG) {
            Log.d("PulseMQTT", message)
        }
    }

    override fun info(message: String) {
        Log.i("PulseMQTT", message)
    }

    override fun error(message: String, throwable: Throwable?) {
        Log.e("PulseMQTT", message, throwable)
        // Send to crash reporting
        Crashlytics.log(message)
        throwable?.let { Crashlytics.recordException(it) }
    }

    override fun warning(message: String) {
        Log.w("PulseMQTT", message)
    }
}

Gson Configuration

Provide a configured Gson instance:

override fun getAppGson(): Gson = GsonBuilder()
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create()

Coroutine Scope

Specify the coroutine scope for operations:

override fun getCustomCoroutineScope(): CoroutineScope {
    // For UI-bound operations
    return MainScope()

    // OR for background operations
    return CoroutineScope(Dispatchers.IO + SupervisorJob())
}

Connection Options

Configure MQTT broker connection parameters:

val connectionOptions = ConnectionOptions(
    serverUri = "tcp://broker.example.com:1883",
    clientId = "unique-client-id",
    username = "user",
    password = "pass",

    // Session Management
    cleanSession = false,
    automaticReconnect = true,

    // Timeouts
    connectionTimeoutSeconds = 60,
    keepAliveIntervalSeconds = 30,

    // Last Will Testament (optional)
    willTopic = "devices/status",
    willMessage = """{"status":"offline"}""",
    willQos = 1,
    willRetain = true,

    // Auto-subscription (optional)
    autoSubscriptionConfig = AutoSubscriptionConfig(
        enabled = true,
        subscribeCommandRetryPolicy = RetryPolicy.exponential(3),
        subscribeCommandTimeout = 30_000L,
        subscriptionStore = hashMapOf(
            "topic/pattern" to TopicTypeConfig(
                messageType = MyData::class.java,
                qosLevel = QOSLevel.QOS_1
            )
        )
    )
)

Connection Parameters

Parameter Type Default Description
serverUri String Required MQTT broker URI (tcp://, ws://, wss://)
clientId String Required Unique client identifier
username String? null Authentication username
password String? null Authentication password
cleanSession Boolean true Start with clean session
automaticReconnect Boolean false Enable automatic reconnection
connectionTimeoutSeconds Int 30 Connection timeout
keepAliveIntervalSeconds Int 60 Keep-alive interval

Last Will Testament

Configure message sent when client disconnects unexpectedly:

connectionOptions = connectionOptions.copy(
    willTopic = "device/${deviceId}/status",
    willMessage = """{"status":"offline","timestamp":${System.currentTimeMillis()}}""",
    willQos = 1,
    willRetain = true
)

Health Monitoring

Configure automatic connection health checks:

override fun getHealthMonitoringConfig() = HealthMonitoringConfig(
    monitoringFreqSeconds = 30,  // Check every 30 seconds
    type = HealthMonitoringType.WORK_MANAGER,  // or ALARM_MANAGER
    healthCheck = null  // Use default check or provide custom
)

Monitoring Types

HealthMonitoringConfig(
    monitoringFreqSeconds = 30,
    type = HealthMonitoringType.WORK_MANAGER
)

Pros:

  • Battery efficient
  • Respects Doze mode
  • Survives app restarts

Cons:

  • Less precise timing
  • Minimum 15-minute interval
HealthMonitoringConfig(
    monitoringFreqSeconds = 10,
    type = HealthMonitoringType.ALARM_MANAGER
)

Pros:

  • Precise timing
  • Works in Doze mode (with permissions)
  • Shorter intervals possible

Cons:

  • Higher battery consumption
  • Requires additional permissions

Custom Health Check

Provide custom logic for health verification:

HealthMonitoringConfig(
    monitoringFreqSeconds = 30,
    type = HealthMonitoringType.WORK_MANAGER,
    healthCheck = {
        // Custom health verification logic
        if (!isAppInForeground()) return

        if (pulseMqttKit.isConnected() != true) {
            // Trigger reconnection
            pulseMqttKit.submitCommand(ConnectCommand(connectionOptions))
        }
    }
)

Network Monitoring

Enable automatic reconnection on network changes:

override fun getNetworkConfig() = NetworkMonitoringConfig(
    enabled = true
)

When enabled, the library:

  1. Monitors network state changes
  2. Notifies listeners via onInternetConnectionStatusChanged()
  3. Attempts reconnection when network is restored

Quality of Service (QoS)

Choose appropriate QoS levels for your use case:

enum class QOSLevel(val value: Int) {
    QOS_0(0),  // At most once delivery
    QOS_1(1),  // At least once delivery
    QOS_2(2)   // Exactly once delivery
}

QoS Selection Guide

Level Guarantee Use Case Performance
QoS 0 None Telemetry, high-frequency data Fastest
QoS 1 At least once Most messages, commands Balanced
QoS 2 Exactly once Critical data, transactions Slowest

Retry Policies

Configure retry behavior for commands:

Sequential Retry

RetryPolicy.sequential(
    maxRetries = 3,
    delayMillis = 1000
)

Exponential Backoff

RetryPolicy.exponential(
    maxRetries = 5,
    baseDelayMillis = 1000,
    maxDelayMillis = 120000,
    excludedExceptionCodes = hashSetOf(
        MqttExceptionCode.REASON_CODE_NOT_AUTHORIZED
    )
)

Jitter Retry

RetryPolicy.jitter(
    jitterFactor = 0.2,  // ±20% randomness
    basePolicy = RetryPolicy.exponential(3, 1000, 60000)
)

No Retry

RetryPolicy.none()

Next Steps