publish

suspend fun publish(message: MqttMessage)

Publish an MqttMessage to the broker.

Parameters

message

The message to publish, including topic, payload, QoS, and properties.

Throws

if not connected.

if the topic name is invalid.

on publish failure (QoS 1/2 only).


suspend fun publish(topic: String, payload: String, qos: QoS? = null, retain: Boolean? = null, properties: PublishProperties = PublishProperties())

Publish a message with a String payload and optional MQTT 5.0 properties.

This is the primary convenience overload for string payloads. For binary payloads, construct an MqttMessage directly with a ByteArray or ByteString.

When qos or retain are omitted (null), the client-level defaults from MqttConfig.defaultQos and MqttConfig.defaultRetain are used — similar to Ktor's defaultRequest {} pattern. This lets you configure publish defaults once at client creation:

val client = MqttClient("sensor") {
defaultQos = QoS.AT_LEAST_ONCE
defaultRetain = true
}
// All convenience publishes now default to QoS 1 + retain
client.publish("sensors/temp", "22.5")
// Override per-call when needed
client.publish("sensors/temp", "22.5", qos = QoS.AT_MOST_ONCE, retain = false)

For the MQTT 5.0 request/response pattern (§4.10), set PublishProperties.responseTopic and PublishProperties.correlationData in the properties parameter.

Parameters

topic

The topic to publish to.

payload

String payload (encoded as UTF-8).

qos

Quality of service level, or null to use MqttConfig.defaultQos.

retain

Whether the message should be retained, or null to use MqttConfig.defaultRetain.

properties

MQTT 5.0 publish properties (default: none).