An Elixir MQTT client library supporting both MQTT 3.1.1 and MQTT 5.0.
Separates Sans-I/O protocol serialization, QoS state tracking, pluggable
transports (mqtt://, mqtts://, ws://, wss://), and a :gen_statem
connection process with active: :once backpressure.
Quick Example
{:ok, client} =
ExMqtt.start_link(
uri: "mqtt://127.0.0.1:1883",
protocol_version: :"5.0",
client_id: "demo_client"
)
{:ok, connack} = ExMqtt.connect(client)
{:ok, suback} = ExMqtt.subscribe(client, {"sensors/#", 1})
:ok = ExMqtt.publish(client, "sensors/temp", "23.5", qos: 1)
receive do
{:ex_mqtt, ^client, {:publish, msg}} ->
IO.inspect({msg.topic, msg.payload, msg.properties})
end
:ok = ExMqtt.disconnect(client)Supported URI Schemes
mqtt://host:1883(ExMqtt.Transport.TCP)mqtts://host:8883(ExMqtt.Transport.TLS)ws://host:80/mqtt(ExMqtt.Transport.WebSocket)wss://host:443/mqtt(ExMqtt.Transport.WebSocketwithtls: true)
Telemetry
Built-in :telemetry instrumentation is provided by ExMqtt.Telemetry:
ExMqtt.Telemetry.attach_default_logger(level: :info)
Summary
Functions
Sends an MQTT 5.0 AUTH packet (for enhanced authentication or re-authentication).
Returns {:error, :auth_unsupported_in_v311} on MQTT 3.1.1 connections.
Child spec for placing an ExMqtt client under a Supervisor.
Synchronously connects to the broker and waits for CONNACK.
Gracefully disconnects from the broker.
Sends a PINGREQ and waits for PINGRESP.
Manually sends a PUBACK (when auto_ack: false).
Manually sends a PUBCOMP (when auto_ack: false).
Publishes a message to topic.
Publishes a message asynchronously without blocking for QoS 1/2 broker ACKs.
Manually sends a PUBREC (when auto_ack: false).
Manually sends a PUBREL.
Initiates MQTT 5.0 re-authentication on an established connection.
Starts a linked MQTT client process.
Returns current connection status and negotiated parameters.
Subscribes to one or more topic filters.
Returns the map of currently active subscriptions (%{topic_filter => %Subscription{}}).
Unsubscribes from one or more topic filters.
Types
@type client() :: GenServer.server()
Functions
Sends an MQTT 5.0 AUTH packet (for enhanced authentication or re-authentication).
Returns {:error, :auth_unsupported_in_v311} on MQTT 3.1.1 connections.
Child spec for placing an ExMqtt client under a Supervisor.
@spec connect(client(), timeout()) :: {:ok, ExMqtt.Protocol.Packet.Connack.t()} | {:error, term()}
Synchronously connects to the broker and waits for CONNACK.
Gracefully disconnects from the broker.
Sends a PINGREQ and waits for PINGRESP.
Manually sends a PUBACK (when auto_ack: false).
Manually sends a PUBCOMP (when auto_ack: false).
Publishes a message to topic.
Options
:qos-0,1, or2(default0):retain- boolean (defaultfalse):properties- MQTT 5.0 PUBLISH properties map (default%{}):timeout- call timeout in ms (default5_000)
@spec publish_async(client(), String.t(), binary(), keyword()) :: :ok | {:ok, 1..65535} | {:error, term()}
Publishes a message asynchronously without blocking for QoS 1/2 broker ACKs.
- For QoS 0, returns
:ok. - For QoS 1/2, immediately returns
{:ok, packet_id}once transmitted. When the broker ACK arrives, either invokes:callback(if provided as a 1-arity function receiving{:ok, packet_id}or{:error, packet_id, reason_code}) or sends{:ex_mqtt, client, {:puback | :pubcomp, packet_id, reason_code}}to the calling process.
Manually sends a PUBREC (when auto_ack: false).
Manually sends a PUBREL.
@spec reauthenticate(client(), String.t(), binary() | nil, map(), timeout()) :: :ok | {:error, term()}
Initiates MQTT 5.0 re-authentication on an established connection.
@spec start_link(keyword()) :: :gen_statem.start_ret()
Starts a linked MQTT client process.
Options
:uri- Optional connection URI (mqtt://,mqtts://,ws://,wss://). Explicit options override URI fields.:uris- Optional list of failover URIs tried in round-robin order (supports:shuffle_hosts):host- Broker hostname or IP string (required unless:uri,:uris, or:hostsis provided):hosts- Optional list of{host, port}failover endpoints:shuffle_hosts- Shuffle:hosts/:urison startup (defaultfalse):port- Broker port (default1883for TCP,8883for TLS):transport- Transport module implementingExMqtt.Transport(defaultExMqtt.Transport.TCP):protocol_version-:"3.1.1"(:v311,4) or:"5.0"(:v5,5). Defaults to:"5.0".:client_id- Client identifier string (auto-generated if omitted):clean_start/:clean_session- Boolean (defaulttrue):keep_alive- Keep-alive interval in seconds (default60):username/:password- Optional credentials (password is wrapped viaExMqtt.Secretso it never leaks in logs/state dumps):will- Optional%ExMqtt.Protocol.Packet.Will{}or keyword list:properties- MQTT 5.0 CONNECT properties map (ignored in 3.1.1):handler- Optional{HandlerModule, arg}implementingExMqtt.Handler:owner- Process receiving{:ex_mqtt, pid, event}when:handleris omitted (defaultself()):auto_connect- Automatically connect on startup (defaultfalse):auto_ack- Automatically send PUBACK/PUBREC/PUBCOMP for inbound QoS 1/2 packets (defaulttrue):auto_resubscribe- Automatically re-subscribe to previous subscriptions when reconnecting withsession_present: false(defaultfalse):max_inflight- Client-side maximum concurrent QoS 1/2 publishes (default65_535, combined with serverreceive_maximumviamin/2):retry_interval- Optional periodic inflight retransmission interval in ms (defaultnil):reconnect- Automatically reconnect with exponential backoff on unexpected disconnect (defaultfalse):reconnect_interval- Initial reconnect delay in ms (default1_000):reconnect_max_interval- Maximum reconnect backoff delay in ms (default30_000):auto_topic_alias- Automatically compress outbound PUBLISH topics using MQTT 5.0 Topic Aliases (defaultfalse):connect_timeout- Socket & CONNACK timeout in ms (default5_000):name- Optional process registration name
Returns current connection status and negotiated parameters.
@spec subscribe( client(), String.t() | {String.t(), term()} | ExMqtt.Protocol.Packet.Subscription.t() | list(), keyword() ) :: {:ok, ExMqtt.Protocol.Packet.Suback.t()} | {:error, term()}
Subscribes to one or more topic filters.
topics may be a single filter or a list of:
"topic/filter"(QoS 0){"topic/filter", qos}{"topic/filter", qos: 1, no_local: true, retain_as_published: false, retain_handling: 0}%ExMqtt.Protocol.Packet.Subscription{}
@spec subscriptions(client()) :: %{ optional(String.t()) => ExMqtt.Protocol.Packet.Subscription.t() }
Returns the map of currently active subscriptions (%{topic_filter => %Subscription{}}).
@spec unsubscribe(client(), String.t() | [String.t()], keyword()) :: {:ok, ExMqtt.Protocol.Packet.Unsuback.t()} | {:error, term()}
Unsubscribes from one or more topic filters.