ExMqtt (ex_mqtt_uv v0.1.0)

Copy Markdown View Source

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

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

client()

@type client() :: GenServer.server()

Functions

auth(client, reason_code, properties \\ %{}, timeout \\ 5000)

@spec auth(client(), atom() | byte(), map(), timeout()) :: :ok | {:error, term()}

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(opts)

Child spec for placing an ExMqtt client under a Supervisor.

connect(client, timeout \\ 5000)

@spec connect(client(), timeout()) ::
  {:ok, ExMqtt.Protocol.Packet.Connack.t()} | {:error, term()}

Synchronously connects to the broker and waits for CONNACK.

disconnect(client, opts \\ [])

@spec disconnect(client(), keyword()) :: :ok

Gracefully disconnects from the broker.

ping(client, timeout \\ 5000)

@spec ping(client(), timeout()) :: :ok | {:error, term()}

Sends a PINGREQ and waits for PINGRESP.

puback(client, packet_id, opts \\ [])

@spec puback(client(), 1..65535, keyword()) :: :ok | {:error, term()}

Manually sends a PUBACK (when auto_ack: false).

pubcomp(client, packet_id, opts \\ [])

@spec pubcomp(client(), 1..65535, keyword()) :: :ok | {:error, term()}

Manually sends a PUBCOMP (when auto_ack: false).

publish(client, topic, payload, opts \\ [])

@spec publish(client(), String.t(), binary(), keyword()) :: :ok | {:error, term()}

Publishes a message to topic.

Options

  • :qos - 0, 1, or 2 (default 0)
  • :retain - boolean (default false)
  • :properties - MQTT 5.0 PUBLISH properties map (default %{})
  • :timeout - call timeout in ms (default 5_000)

publish_async(client, topic, payload, opts \\ [])

@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.

pubrec(client, packet_id, opts \\ [])

@spec pubrec(client(), 1..65535, keyword()) :: :ok | {:error, term()}

Manually sends a PUBREC (when auto_ack: false).

pubrel(client, packet_id, opts \\ [])

@spec pubrel(client(), 1..65535, keyword()) :: :ok | {:error, term()}

Manually sends a PUBREL.

reauthenticate(client, method, auth_data \\ nil, extra_props \\ %{}, timeout \\ 5000)

@spec reauthenticate(client(), String.t(), binary() | nil, map(), timeout()) ::
  :ok | {:error, term()}

Initiates MQTT 5.0 re-authentication on an established connection.

start_link(opts)

@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 :hosts is provided)
  • :hosts - Optional list of {host, port} failover endpoints
  • :shuffle_hosts - Shuffle :hosts / :uris on startup (default false)
  • :port - Broker port (default 1883 for TCP, 8883 for TLS)
  • :transport - Transport module implementing ExMqtt.Transport (default ExMqtt.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 (default true)
  • :keep_alive - Keep-alive interval in seconds (default 60)
  • :username / :password - Optional credentials (password is wrapped via ExMqtt.Secret so 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} implementing ExMqtt.Handler
  • :owner - Process receiving {:ex_mqtt, pid, event} when :handler is omitted (default self())
  • :auto_connect - Automatically connect on startup (default false)
  • :auto_ack - Automatically send PUBACK/PUBREC/PUBCOMP for inbound QoS 1/2 packets (default true)
  • :auto_resubscribe - Automatically re-subscribe to previous subscriptions when reconnecting with session_present: false (default false)
  • :max_inflight - Client-side maximum concurrent QoS 1/2 publishes (default 65_535, combined with server receive_maximum via min/2)
  • :retry_interval - Optional periodic inflight retransmission interval in ms (default nil)
  • :reconnect - Automatically reconnect with exponential backoff on unexpected disconnect (default false)
  • :reconnect_interval - Initial reconnect delay in ms (default 1_000)
  • :reconnect_max_interval - Maximum reconnect backoff delay in ms (default 30_000)
  • :auto_topic_alias - Automatically compress outbound PUBLISH topics using MQTT 5.0 Topic Aliases (default false)
  • :connect_timeout - Socket & CONNACK timeout in ms (default 5_000)
  • :name - Optional process registration name

status(client)

@spec status(client()) :: map()

Returns current connection status and negotiated parameters.

subscribe(client, topics, opts \\ [])

@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{}

subscriptions(client)

@spec subscriptions(client()) :: %{
  optional(String.t()) => ExMqtt.Protocol.Packet.Subscription.t()
}

Returns the map of currently active subscriptions (%{topic_filter => %Subscription{}}).

unsubscribe(client, topics, opts \\ [])

@spec unsubscribe(client(), String.t() | [String.t()], keyword()) ::
  {:ok, ExMqtt.Protocol.Packet.Unsuback.t()} | {:error, term()}

Unsubscribes from one or more topic filters.