MqttX.Client.Connection (MqttX v0.13.0)

Copy Markdown View Source

MQTT client connection GenServer.

Manages a connection to an MQTT broker with automatic reconnection.

Usage

{:ok, pid} = MqttX.Client.Connection.start_link(
  host: "localhost",
  port: 1883,
  client_id: "my_client",
  handler: MyHandler,
  handler_state: %{}
)

:ok = MqttX.Client.Connection.subscribe(pid, "test/#", qos: 1)
:ok = MqttX.Client.Connection.publish(pid, "test/topic", "hello", qos: 0)

TLS/SSL Support

To connect using TLS/SSL:

{:ok, pid} = MqttX.Client.Connection.start_link(
  host: "broker.example.com",
  port: 8883,
  client_id: "my_client",
  transport: :ssl,
  ssl_opts: [verify: :verify_peer, cacerts: :public_key.cacerts_get()]
)

The :transport option defaults to :tcp for backward compatibility.

Summary

Functions

Check if connected.

Disconnect from the broker.

Start a client connection.

Subscribe to topics.

Unsubscribe from topics.

Types

t()

@type t() :: %MqttX.Client.Connection{
  ack_count: term(),
  ack_out: term(),
  alias_to_topic: term(),
  backoff: term(),
  buffer: term(),
  clean_session: term(),
  client_id: term(),
  connack_ref: term(),
  connack_timer: term(),
  connect_properties: term(),
  connect_telemetry: term(),
  connect_waiters: term(),
  connected: term(),
  connected_at: term(),
  connecting: term(),
  handler: term(),
  handler_has_handle_mqtt_event: term(),
  handler_state: term(),
  host: term(),
  inbound_error: term(),
  inflight_rx_count: term(),
  inflight_tx_count: term(),
  keepalive: term(),
  keepalive_timer: term(),
  max_inflight: term(),
  max_packet_size: term(),
  next_alias: term(),
  opener: term(),
  packet_id: term(),
  password: term(),
  pending_acks: term(),
  pending_seq: term(),
  pending_subs: term(),
  pingresp_timer: term(),
  port: term(),
  protocol_version: term(),
  proxy: term(),
  receive_maximum: term(),
  reconnect_timer: term(),
  resend_backlog: term(),
  send_timeout: term(),
  server_maximum_packet_size: term(),
  server_maximum_qos: term(),
  server_retain_available: term(),
  server_topic_alias_maximum: term(),
  session_expiry_interval: term(),
  session_key: term(),
  session_store: term(),
  session_store_state: term(),
  socket: term(),
  ssl_opts: term(),
  subscriptions: term(),
  topic_alias_maximum: term(),
  topic_to_alias: term(),
  transport: term(),
  username: term(),
  will: term(),
  ws_buffer: term(),
  ws_close_pending: term(),
  ws_frag: term(),
  ws_path: term()
}

Functions

connected?(pid)

@spec connected?(GenServer.server()) :: boolean()

Check if connected.

disconnect(pid, opts \\ [])

@spec disconnect(GenServer.server(), keyword()) :: :ok

Disconnect from the broker.

Options (MQTT 5.0)

  • :reason_code - Disconnect reason code (default: 0x00 Normal)
  • :properties - Disconnect properties map, e.g. %{session_expiry_interval: 0}

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

@spec publish(GenServer.server(), binary(), term(), keyword()) ::
  :ok | {:error, term()}

Publish a message.

Options

  • :qos - QoS level 0, 1, or 2 (default: 0)
  • :retain - Retain flag (default: false)
  • :properties - PUBLISH properties map (MQTT 5.0)
  • :codec - a MqttX.Payload module. payload is then a term, encoded with the codec in the calling process, and the codec's metadata/0 (Payload Format Indicator, Content Type) is merged into :properties underneath any given explicitly. An encoding failure returns {:error, {:codec, reason}} without touching the connection.

Returns

:ok once the packet is written to the socket, or {:error, reason}:

  • :not_connected - no live session (the call does not queue)
  • :invalid_qos - :qos is not 0, 1 or 2
  • :qos_not_supported - :qos is above the Maximum QoS the broker advertised in CONNACK (MQTT 5.0 §3.2.2.3.4, MQTT-3.2.2-11). The QoS is not lowered silently; publish again at the supported level.
  • :retain_not_supported - retain: true but the broker advertised Retain Available = 0 in CONNACK (§3.2.2.3.5, MQTT-3.2.2-14)
  • :flow_control - the in-flight QoS 1/2 window is full
  • :packet_too_large - larger than the broker's Maximum Packet Size
  • {:codec, reason} - the :codec could not encode payload

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()

Start a client connection.

Options

  • :host - Broker hostname (required)
  • :port - Broker port (default: 1883 for TCP, 8883 for SSL)
  • :client_id - Client identifier (required)
  • :username - Optional username
  • :password - Optional password
  • :clean_session - Clean session flag (default: true)
  • :keepalive - Keepalive interval in seconds (default: 60)
  • :handler - Module to receive callbacks
  • :handler_state - Initial state for handler
  • :transport - Transport type: :tcp, :ssl, :ws, or :wss (default: :tcp)
  • :ssl_opts - SSL options when transport is :ssl or :wss (e.g., [verify: :verify_peer])
  • :ws_path - WebSocket path when transport is :ws or :wss (default: "/mqtt")
  • :send_timeout - Milliseconds a socket write may block before the connection is closed and reconnected (default: 30000)
  • :proxy - HTTP CONNECT proxy for any transport, e.g. [host: "proxy.corp", port: 3128, auth: {"user", "pass"}] (:port defaults to 3128, :auth is optional Basic auth). TLS is negotiated with the target host through the tunnel, so certificate verification and SNI are unaffected by the proxy.
  • :retry_interval - Deprecated and ignored since 0.12.0: unacknowledged QoS 1/2 publishes are re-sent only when a session is resumed, never on a live connection (§4.4)
  • :max_inflight - Maximum pending QoS 1/2 messages before backpressure (default: 100)
  • :will_topic - Will message topic (enables Last Will & Testament)
  • :will_payload - Will message payload (default: "")
  • :will_qos - Will message QoS: 0, 1, or 2 (default: 0)
  • :will_retain - Will message retain flag (default: false)
  • :will_properties - Will message properties map (MQTT 5.0, default: %{})
  • :connect_properties - CONNECT packet properties (MQTT 5.0), e.g. %{session_expiry_interval: 3600}
  • :session_store - Session store module or {module, opts} for session persistence

Raises ArgumentError if :will_qos is not 0, 1 or 2 (§3.1.2.6): a bad Will QoS would make every CONNECT a Malformed Packet.

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

@spec subscribe(GenServer.server(), binary() | [binary()], keyword()) ::
  {:ok, [integer()]} | {:error, term()}

Subscribe to topics.

Options

  • :qos - QoS level 0, 1, or 2 (default: 0)
  • :no_local - Don't receive own publishes (MQTT 5.0, default: false)
  • :retain_as_published - Keep original retain flag (MQTT 5.0, default: false)
  • :retain_handling - Retained message behavior: 0=send on subscribe, 1=send if new, 2=don't send (MQTT 5.0, default: 0)
  • :properties - SUBSCRIBE packet properties map (MQTT 5.0), e.g. %{subscription_identifier: 1}

Returns

{:ok, granted_qos_list} once the SUBACK arrives, or {:error, reason}:

  • :not_connected - no live session
  • :invalid_qos - :qos is not 0, 1 or 2 (§3.8.3.1). Requesting a QoS above the broker's Maximum QoS is allowed; the broker grants a lower one.
  • :invalid_retain_handling - :retain_handling is not 0, 1 or 2 (§3.8.3.1)
  • :no_local_on_shared_subscription - no_local: true on a $share/... filter, a Protocol Error (MQTT-3.8.3-4)
  • {:subscription_refused, acks} - the broker rejected at least one filter

Option errors are detected before anything is sent, so an invalid option never puts a malformed SUBSCRIBE on the wire.

unsubscribe(pid, topics)

@spec unsubscribe(GenServer.server(), binary() | [binary()]) :: :ok | {:error, term()}

Unsubscribe from topics.