### emqtt:start_link/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Starts an EMQTT client process with a specified list of options to configure connection and behavior. ```APIDOC ## emqtt:start_link/1 ### Description Starts an EMQTT client process with custom options for connection and behavior. ### Function Signature emqtt:start_link(Options) -> {ok, Pid} | ignore | {error, Reason} ### Parameters #### Options - `{name, Name}` (atom()): Register the gen_statem with a given name. - `{owner, Pid}` (pid()): The process to send disconnection messages to. - `{host, Host}` (string() | inet:hostname()): The hostname or IP address of the MQTT server. Defaults to `localhost`. - `{hosts, [{Host, Port}]}` (list({string() | inet:hostname(), pos_integer()})): A list of hosts and ports to attempt connection. Overrides the `host` option. - `{port, Port}` (pos_integer()): The port of the MQTT server. Defaults to 1883 (MQTT) or 8883 (MQTT over TLS). - `{tcp_opts, Options}` (list()): Additional options for `gen_tcp:connect/3`. - `{ssl, boolean()}`: Enable or disable SSL/TLS transport. Defaults to `false`. - `{ssl_opts, Options}` (list()): Additional options for `ssl:connect/3`. - `{ws_path, Path}` (string()): The WebSocket path. Defaults to `/mqtt`. - `{connect_timeout, Timeout}` (duration()): Maximum time to wait for a connection and CONNACK. Defaults to 60s. - `{bridge_mode, boolean()}`: Enable or disable bridge mode. Defaults to `false`. - `{clientid, ClientID}` (string()): The client identifier. If not provided, it's assigned by the server (v5) or generated internally (v3.x). - `{clean_start, CleanStart}` (boolean()): Whether to discard existing session and start a new one. Defaults to `true`. - `{username, Username}` (string()): Username for authentication. - `{password, Password}` (string()): Password for authentication. - `{proto_ver, ProtocolVersion}` (atom()): MQTT protocol version (e.g., `v4`). Defaults to `v4`. - `{keepalive, Keepalive}` (pos_integer()): Maximum time interval between control packets. May be overridden by server. - `{max_inflight, MaxInflight}` (non_neg_integer() | infinity): Maximum number of QoS 1 and 2 packets in flight. Defaults to `infinity`. - `{retry_interval, RetryInterval}` (duration()): Interval for retrying unacknowledged packets. Defaults to 30s. - `{will_topic, WillTopic}` (string()): Topic for the will message. - `{will_payload, WillPayload}` (binary()): Payload of the will message. - `{will_retain, WillRetain}` (boolean()): Whether the will message should be retained. Defaults to `false`. - `{will_qos, WillQoS}` (0..2): QoS level for the will message. Defaults to 0. - `{will_props, WillProperties}` (map()): Properties for the will message. - `{auto_ack, boolean()}`: Automatically send ACK packets for received messages. Defaults to `true`. - `{ack_timeout, AckTimeout}` (duration()): Maximum time to wait for a reply message. Defaults to 30s. - `{force_ping, boolean()}`: Always send ping packets, regardless of other traffic. Defaults to `false`. - `{low_mem, boolean()}`: Enable low memory usage mode. Defaults to `false`. - `{reconnect, infinity | non_neg_integer()}`: Maximum number of reconnection attempts. Defaults to 0 (no reconnection). - `{reconnect_timeout, pos_integer()}`: Time interval between reconnection attempts. Defaults to 5s. - `{properties, Properties}` (map()): Properties for the CONNECT packet. - `{custom_auth_callbacks, Callbacks}` (map()): Custom callback functions for enhanced authentication (MQTT v5). ### Return Values - `{ok, Pid}`: Successfully started client process, `Pid` is the process identifier. - `ignore`: The process was not started. - `{error, Reason}`: An error occurred during startup, `Reason` indicates the cause. ``` -------------------------------- ### Start emqtt Client Process Source: https://context7.com/emqx/emqtt/llms.txt Starts a new MQTT client gen_statem process. Options control connection and runtime behavior. Use for minimal or full configurations including TLS, will messages, and custom handlers. ```erlang %% Minimal: connect to localhost:1883 with MQTT v4, auto-generated client ID {ok, Client} = emqtt:start_link(), %% Full example: MQTT v5, TLS, will message, auto-reconnect, custom handler MsgHandler = #{ publish => fun(Msg) -> io:format("Received on ~s: ~s~n", [maps:get(topic, Msg), maps:get(payload, Msg)]) end, disconnected => fun({Reason, _Props}) -> io:format("Disconnected: ~p~n", [Reason]) end }, {ok, Client} = emqtt:start_link([ {name, my_mqtt_client}, {host, "broker.emqx.io"}, {port, 8883}, {proto_ver, v5}, {clientid, <<"my-erlang-client">>}, {username, "alice"}, {password, "secret"}, {ssl, true}, {ssl_opts, [{cacertfile, "certs/ca.pem"}, {certfile, "certs/client.pem"}, {keyfile, "certs/client.key"}, {versions, ['tlsv1.3']}]}, {keepalive, 30}, {clean_start, true}, {max_inflight, 100}, {retry_interval, 10}, {ack_timeout, 30}, {reconnect, infinity}, {reconnect_timeout, 5}, {will_topic, "lwt/my-erlang-client"}, {will_payload, "offline"}, {will_qos, 1}, {will_retain, true}, {msg_handler, MsgHandler}, {auto_ack, true}, {low_mem, false}, {with_qoe_metrics, false} ]). %% => {ok, <0.123.0>} ``` -------------------------------- ### Basic MQTT Operations with EMQTT Source: https://github.com/emqx/emqtt/blob/master/README.md Demonstrates basic MQTT client operations including starting a connection, subscribing to a topic, publishing messages with different QoS levels, and handling incoming packets. Ensure the client is properly started and connected before performing these operations. ```erlang {ok, ConnPid} = emqtt:start_link([{clientid, ClientId}]). {ok, _Props} = emqtt:connect(ConnPid). SubOpts = [{qos, 1}]. {ok, _Props, _ReasonCodes} = emqtt:subscribe(ConnPid, #{}, [{<<"hello">>, SubOpts}]). ok = emqtt:publish(ConnPid, <<"hello">>, #{}, << ``` -------------------------------- ### emqtt:start_link/0 Source: https://github.com/emqx/emqtt/blob/master/README.md Starts an EMQTT client process without any specific options. The client will attempt to connect using default settings. ```APIDOC ## emqtt:start_link/0 ### Description Starts an EMQTT client process with default options. ### Function Signature emqtt:start_link() -> {ok, Pid} | ignore | {error, Reason} ### Return Values - `{ok, Pid}`: Successfully started client process, `Pid` is the process identifier. - `ignore`: The process was not started. - `{error, Reason}`: An error occurred during startup, `Reason` indicates the cause. ``` -------------------------------- ### emqtt:start_link/0,1 Source: https://context7.com/emqx/emqtt/llms.txt Starts a new MQTT client gen_statem process. Options can be provided to configure connection parameters, message handlers, and other runtime behaviors. Returns `{ok, Pid}` on success. ```APIDOC ## `emqtt:start_link/0,1` — Start a client process Creates and links a new MQTT client `gen_statem` process. Options control every aspect of the connection and runtime behavior. Returns `{ok, Pid}` on success. ```erlang %% Minimal: connect to localhost:1883 with MQTT v4, auto-generated client ID {ok, Client} = emqtt:start_link(), %% Full example: MQTT v5, TLS, will message, auto-reconnect, custom handler MsgHandler = #{ publish => fun(Msg) -> io:format("Received on ~s: ~s~n", [maps:get(topic, Msg), maps:get(payload, Msg)]) end, disconnected => fun({Reason, _Props}) -> io:format("Disconnected: ~p~n", [Reason]) end }, {ok, Client} = emqtt:start_link([ {name, my_mqtt_client}, {host, "broker.emqx.io"}, {port, 8883}, {proto_ver, v5}, {clientid, <<"my-erlang-client">>}, {username, "alice"}, {password, "secret"}, {ssl, true}, {ssl_opts, [{cacertfile, "certs/ca.pem"}, {certfile, "certs/client.pem"}, {keyfile, "certs/client.key"}, {versions, ['tlsv1.3']}]}, {keepalive, 30}, {clean_start, true}, {max_inflight, 100}, {retry_interval, 10}, {ack_timeout, 30}, {reconnect, infinity}, {reconnect_timeout, 5}, {will_topic, "lwt/my-erlang-client"}, {will_payload, "offline"}, {will_qos, 1}, {will_retain, true}, {msg_handler, MsgHandler}, {auto_ack, true}, {low_mem, false}, {with_qoe_metrics, false} ]). %% => {ok, <0.123.0>} ``` ``` -------------------------------- ### Publish Simple Message via TCP Source: https://github.com/emqx/emqtt/blob/master/README.md Use this command to publish a simple message to a topic over a standard TCP connection. No special setup is required beyond having the emqtt client installed. ```bash $ ./emqtt pub -t "hello" --payload "hello world" Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent DISCONNECT ``` -------------------------------- ### Open QUIC Data Stream with emqtt:start_data_stream/2 Source: https://context7.com/emqx/emqtt/llms.txt Opens a new long-lived QUIC data stream on an existing QUIC connection. Use this for dedicated stream communication. Requires prior QUIC connection setup. ```erlang {ok, Client} = emqtt:start_link([{host, "broker.emqx.io"}, {port, 14567}]), {ok, _Props} = emqtt:quic_connect(Client), StreamOpts = #{active => 1, priority => 10}, {ok, StreamVia} = emqtt:start_data_stream(Client, StreamOpts), %% Publish on the dedicated stream ok = emqtt:publish_async(Client, StreamVia, <<"stream/data">>, #{} , <<"payload">>, [{qos, 0}], infinity, fun(R) -> io:format("Stream result: ~p~n", [R]) end). ``` -------------------------------- ### Subscribe to Topic (Non-shared) Source: https://github.com/emqx/emqtt/blob/master/README.md Subscribe to a topic to receive messages. This example demonstrates a non-shared subscription. ```bash $ ./emqtt sub -t "hello" Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c subscribed to hello hello world ``` -------------------------------- ### Publish Message over QUIC Transport Source: https://context7.com/emqx/emqtt/llms.txt Example of publishing a message using the QUIC transport with the emqtt CLI. Ensure QUIC support is enabled. ```bash ./emqtt pub -h localhost -p 14567 --enable-quic=true \ -V v5 -t "quic/test" --payload "quic message" ``` -------------------------------- ### Add EMQTT as rebar3 Dependency Source: https://github.com/emqx/emqtt/blob/master/README.md Add EMQTT as a dependency to your rebar3 project by including it in the `rebar.config` file. This example specifies a particular tag for the dependency. ```erlang ... {deps, [{emqtt, {git, "https://github.com/emqx/emqtt", {tag, "1.14.4"}}}]}. ... ``` -------------------------------- ### emqtt command-line syntax Source: https://github.com/emqx/emqtt/blob/master/README.md Illustrates the syntax for short and long options with arguments in the emqtt command-line tool. ```sh -e arg Single option 'e', argument "arg" ``` ```sh --example=arg Single option 'example', argument "arg" ``` ```sh --example arg Single option 'example', argument "arg" ``` -------------------------------- ### Show emqtt help Source: https://github.com/emqx/emqtt/blob/master/README.md Display the help message for the emqtt command-line tool to see available subcommands. ```sh ./emqtt --help ``` -------------------------------- ### Subscribe to Topic with QoS 0 Source: https://context7.com/emqx/emqtt/llms.txt Basic subscription to a topic using QoS level 0. Connects to the specified broker. ```bash ./emqtt sub -h broker.emqx.io -t "hello" ``` -------------------------------- ### Build emqtt Source: https://github.com/emqx/emqtt/blob/master/README.md Compile the emqtt project. Use BUILD_WITHOUT_QUIC=1 to disable QUIC support if compilation issues arise. ```makefile make ``` ```sh BUILD_WITHOUT_QUIC=1 make ``` -------------------------------- ### Subscribe with QoS 2 and Shared Subscription Source: https://context7.com/emqx/emqtt/llms.txt Subscribe to a topic with QoS level 2 and configure a shared subscription. Useful for distributing messages among multiple subscribers. ```bash ./emqtt sub -h broker.emqx.io -t '$share/group/sensors/#' -q 2 ``` -------------------------------- ### emqtt:connect/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Connects to the MQTT server over TCP or TLS. It sends a CONNECT packet with options specified in start_link/1, 2. The Client must be a pid returned from start_link/1, 2 or a name specified in start_link/1, 2. Returns {ok, Properties} on successful connection, where Properties are from the CONNACK packet, or {error, Reason} if the connection fails. ```APIDOC ## emqtt:connect/1 ### Description Connects to the MQTT server over TCP or TLS and sends a `CONNECT` packet with the options specified in `start_link/1, 2`. `Client` must be a pid returned from `start_link/1, 2` or a name specified in `start_link/1, 2`. ### Parameters #### Path Parameters - **Client** (client()) - Required - The client identifier or PID. ### Response #### Success Response - **{ok, Properties}** - Properties is propterties in CONNACK packet returned from MQTT server. #### Error Response - **{error, timeout}** - If connection can't be established within the specified time. - **{error, inet:posix()}** - A POSIX error value if something else goes wrong. - **{error, any()}** - Any other error reason. ``` -------------------------------- ### emqtt:ws_connect/1 Source: https://context7.com/emqx/emqtt/llms.txt Establishes an MQTT connection using the WebSocket transport. The default WebSocket path is `/mqtt`, but this can be customized using the `{ws_path, Path}` option in `start_link/1`. ```APIDOC ## `emqtt:ws_connect/1` — WebSocket MQTT connect Connects using the WebSocket transport (default path `/mqtt`). Use the `{ws_path, Path}` option in `start_link/1` to override the path. ```erlang {ok, Client} = emqtt:start_link([ {host, "broker.emqx.io"}, {port, 8083}, {ws_path, "/mqtt"} ]), {ok, _Props} = emqtt:ws_connect(Client). ``` ``` -------------------------------- ### emqtt pub CLI Source: https://context7.com/emqx/emqtt/llms.txt The `emqtt pub` command allows publishing a single message from the command line. It supports various options for specifying broker details, topics, payloads, QoS, retain flags, TLS, WebSockets, and message repetition. ```APIDOC ### CLI — `emqtt pub` — Publish a message The compiled `emqtt` binary publishes a single message and exits. ### Examples ```sh # Publish plain text over TCP ./emqtt pub -h broker.emqx.io -p 1883 -t "hello" --payload "hello world" # Publish with QoS 1, retained, custom client ID ./emqtt pub -h broker.emqx.io -C my-client -t "alerts/fire" \ -q 1 -r true --payload "FIRE" # Publish file content over TLS ./emqtt pub -h broker.emqx.io -p 8883 --enable-ssl=true \ --CAfile certs/ca.pem --cert certs/client.pem --key certs/client.key \ -t "firmware/update" --file firmware.bin # Publish 5 times with 2-second delay over WebSocket ./emqtt pub -h localhost -p 8083 --enable-websocket=true \ -t "heartbeat" --payload "ping" --repeat 5 --repeat-delay 2 ``` ``` -------------------------------- ### Publish Simple Message via TLS Source: https://github.com/emqx/emqtt/blob/master/README.md Publish a message securely using TLS. Ensure you have the necessary certificate files (CAfile, cert, key) configured correctly. ```bash $ ./emqtt pub --enable-ssl=true -t "hello" --payload "hello world" --CAfile=certs/cacert.pem --cert=certs/client-cert.pem --key=certs/client-key.pem Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent DISCONNECT ``` -------------------------------- ### Compile rebar3 Project Source: https://github.com/emqx/emqtt/blob/master/README.md Compile your rebar3 project after adding dependencies. This command will fetch and compile all project dependencies, including EMQTT. ```bash $ rebar3 compile ``` -------------------------------- ### Custom Authentication Callbacks Source: https://context7.com/emqx/emqtt/llms.txt Enables MQTT v5 enhanced authentication by providing `init` and `handle_auth` callbacks. This allows for custom logic during the AUTH packet exchange initiated by the server. ```APIDOC ### Custom authentication callbacks — MQTT v5 enhanced auth The `custom_auth_callbacks` option allows implementing MQTT v5 enhanced authentication (AUTH packet exchange) by providing `init` and `handle_auth` callbacks. ### Example ```erlang AuthCallbacks = #{ init => fun() -> %% Return initial auth properties (sent in CONNECT) InitProps = #{'Authentication-Method' => "SCRAM-SHA-256", 'Authentication-Data' => "initial-client-data"}, AuthState = #{step => 0}, {InitProps, AuthState} end, handle_auth => fun(AuthState, Reason, InProps) -> case maps:get(step, AuthState) of 0 -> OutProps = #{'Authentication-Method' => "SCRAM-SHA-256", 'Authentication-Data' => "client-proof"}, {continue, {16#18, OutProps}, AuthState#{step => 1}}; _ -> {stop, auth_failed} end end }, {ok, Client} = emqtt:start_link([ {host, "localhost"}, {proto_ver, v5}, {custom_auth_callbacks, AuthCallbacks} ]), {ok, _Props} = emqtt:connect(Client). ``` ``` -------------------------------- ### EMQTT Enhanced Authentication Callbacks Source: https://github.com/emqx/emqtt/blob/master/README.md Defines the structure for custom authentication callbacks in EMQTT. The `init` function sets up initial authentication properties and state, while `handle_auth` manages the continuation of the authentication process. These callbacks are provided as a `{custom_auth_callbacks, Callbacks}` option during client startup. ```erlang #{ init => {InitFunc :: function(), InitArgs :: list()}, handle_auth => HandleAuth :: function() }. ``` -------------------------------- ### emqtt:ws_connect/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Connects to the MQTT server over Websocket. It sends a CONNECT packet with options specified in start_link/1, 2. The Client must be a pid returned from start_link/1, 2 or a name specified in start_link/1, 2. Returns {ok, Properties} on successful connection, where Properties are from the CONNACK packet, or {error, Reason} if the connection fails. ```APIDOC ## emqtt:ws_connect/1 ### Description Connects to the MQTT server over Websocket and sends a `CONNECT` packet with the options specified in `start_link/1, 2`. `Client` must be a pid returned from `start_link/1, 2` or a name specified in `start_link/1, 2`. ### Parameters #### Path Parameters - **Client** (client()) - Required - The client identifier or PID. ### Response #### Success Response - **{ok, Properties}** - Properties is propterties in CONNACK packet returned from MQTT server. #### Error Response - **{error, timeout}** - If connection can't be established within the specified time. - **{error, inet:posix()}** - A POSIX error value if something else goes wrong. - **{error, any()}** - Any other error reason. ``` -------------------------------- ### emqtt:start_data_stream/2 Source: https://context7.com/emqx/emqtt/llms.txt Opens a QUIC data stream on an existing QUIC connection. This function is specific to QUIC connections and returns a stream identifier for subsequent publish operations on that stream. ```APIDOC ## emqtt:start_data_stream/2 — Open a QUIC data stream (QUIC only) Creates a new long-lived QUIC data stream on an existing QUIC connection. Returns `{ok, Via}` where `Via` is the stream identifier used in subsequent `publish_via` calls. ### Example ```erlang {ok, Client} = emqtt:start_link([{host, "broker.emqx.io"}, {port, 14567}]), {ok, _Props} = emqtt:quic_connect(Client), StreamOpts = #{active => 1, priority => 10}, {ok, StreamVia} = emqtt:start_data_stream(Client, StreamOpts), %% Publish on the dedicated stream ok = emqtt:publish_async(Client, StreamVia, <<"stream/data">>, #{}, <<"payload">>, [{qos, 0}], infinity, fun(R) -> io:format("Stream result: ~p~n", [R]) end). ``` ``` -------------------------------- ### emqtt:resume Source: https://github.com/emqx/emqtt/blob/master/README.md Resume a client process that has been paused. ```APIDOC ## emqtt:resume ### Description Resume a client process from a paused state. ### Method `emqtt:resume(Client) -> ok` ### Parameters #### Path Parameters - **Client** (Client) - Required - The client identifier. ### Return Value - **ok** - Indicates the client has been resumed successfully. ### Types - **Client**: client() ``` -------------------------------- ### Subscribe with MQTT v5 Retain Handling Source: https://context7.com/emqx/emqtt/llms.txt Subscribe to a topic with MQTT v5 specific retain handling options. Configures how retained messages are processed. ```bash ./emqtt sub -h localhost -t "config/#" \ --retain-as-publish true --retain-handling 1 -q 1 ``` -------------------------------- ### emqtt:quic_connect/1 Source: https://context7.com/emqx/emqtt/llms.txt Initiates an MQTT connection over the QUIC transport, which requires the `quicer` application. QUIC offers benefits such as multiplexed streams and built-in encryption. ```APIDOC ## `emqtt:quic_connect/1` — QUIC MQTT connect Connects using the QUIC transport (requires `quicer` application). QUIC provides multiplexed streams and built-in encryption. ```erlang {ok, Client} = emqtt:start_link([ {host, "broker.emqx.io"}, {port, 14567}, {enable_quic, true}, {proto_ver, v5} ]), {ok, _Props} = emqtt:quic_connect(Client). ``` ``` -------------------------------- ### Message Handler Callbacks Source: https://context7.com/emqx/emqtt/llms.txt Defines how to handle incoming messages by providing a `msg_handler` map to `start_link/1`. This allows callbacks to be invoked directly by the client process instead of receiving messages in the owner process. ```APIDOC ### Message handler callbacks — Receiving messages When a `msg_handler` map is passed to `start_link/1`, incoming messages are dispatched to these callbacks instead of being sent as Erlang messages to the owner process. ### Example ```erlang %% Without msg_handler: messages arrive as {publish, Msg} to owner process {ok, Client} = emqtt:start_link([{host, "localhost"}]), {ok, _} = emqtt:connect(Client), {ok, _, _} = emqtt:subscribe(Client, "test/#", 1), receive {publish, #{topic := T, payload := P, qos := Q, packet_id := Id}} -> io:format("~s (Q~p, ID=~p): ~s~n", [T, Q, Id, P]) after 5000 -> timeout end, %% With msg_handler: callbacks invoked by client process MsgHandler = #{ publish => fun(#{topic := T, payload := P}) -> io:format("[~s] ~s~n", [T, P]) end, connected => fun(Props) -> io:format("Connected with props: ~p~n", [Props]) end, disconnected => fun({Reason, Props}) -> io:format("Disconnected ~p ~p~n", [Reason, Props]) end }, {ok, Client2} = emqtt:start_link([{host, "localhost"}, {msg_handler, MsgHandler}]), {ok, _} = emqtt:connect(Client2). ``` ``` -------------------------------- ### emqtt:publish/5 Source: https://github.com/emqx/emqtt/blob/master/README.md Sends a PUBLISH packet to the MQTT server. It includes the topic, properties, payload, and optional publish options (like QoS and retain flag). Returns 'ok' for QoS 0, {ok, PacketId} for QoS 1/2, or {error, Reason} on failure. ```APIDOC ## emqtt:publish/5 ### Description Send a `PUBLISH` packet to the MQTT server. `Topic`, `Properties` and `Payload` specify topic, properties and payload for `PUBLISH` packet. `PubOpts` specifies qos and retain flag for `PUBLISH` packet, defaults to `[]`, equivalent to `[{qos, 0}, {retain, false}]`. ### Parameters #### Path Parameters - **Client** (client()) - Required - The client identifier or PID. - **Topic** (topic()) - Required - The topic to publish to. - **Properties** (properties()) - Optional - Properties for the PUBLISH packet. - **Payload** (payload()) - Required - The message payload. - **PubOpts** ([pubopt()]) - Optional - Publish options, defaults to `[{qos, 0}, {retain, false}]`. ### Response #### Success Response - **ok** - If a QoS 0 packet is sent. - **{ok, PacketId}** - If a QoS 1/2 packet is sent, the packet identifier will be returned. #### Error Response - **{error, Reason}** - If something goes wrong. ``` -------------------------------- ### Inspect Client State with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Retrieves internal client state information. Can return a full proplist or specific attributes like 'n_queued', 'n_inflight', or 'max_inflight'. ```erlang %% Full state dump (proplist) State = emqtt:info(Client), %% Specific attributes NInflight = emqtt:info(Client, n_inflight), NQueued = emqtt:info(Client, n_queued), MaxInflight = emqtt:info(Client, max_inflight), io:format("Inflight=~p Queued=~p Max=~p~n", [NInflight, NQueued, MaxInflight]). ``` -------------------------------- ### List Active Subscriptions with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Returns a list of active subscriptions, each represented as a {Topic, SubOpts} tuple. Useful for inspecting current subscription status. ```erlang Subs = emqtt:subscriptions(Client), %% => [{<< ``` ```erlang sensors/#>>, #{qos=>1,nl=>0,rap=>0,rh=>0}}, ...] lists:foreach(fun({Topic, Opts}) -> io:format("~s => ~p~n", [Topic, Opts]) end, Subs). ``` -------------------------------- ### emqtt:subscribe/2,3,4 — Subscribe to topics Source: https://context7.com/emqx/emqtt/llms.txt Subscribes to one or more topics. Blocks until a SUBACK is received. Returns `{ok, Properties, ReasonCodes}` where each reason code indicates the granted QoS or an error. ```APIDOC ## emqtt:subscribe/2,3,4 — Subscribe to topics ### Description Subscribes to one or more topics. Blocks until a SUBACK is received. Returns `{ok, Properties, ReasonCodes}` where each reason code indicates the granted QoS or an error. ### Method `emqtt:subscribe(Client, Topic)` `emqtt:subscribe(Client, Topic, Options)` `emqtt:subscribe(Client, Properties, Topic, Options)` ### Parameters #### Path Parameters - **Client**: The MQTT client instance. - **Topic**: The topic or a list of topics to subscribe to. Can be a string or a list of `{Topic, Options}` tuples. - **Options**: A list of subscription options, e.g., `[{qos, 1}]`. - **Properties**: MQTT v5 subscription properties, e.g., `#{'Subscription-Identifier' => 42}`. ### Response #### Success Response - **{ok, Properties, ReasonCodes}**: Where `Properties` are MQTT v5 properties and `ReasonCodes` is a list indicating the granted QoS or error for each topic. ### Request Example ```erlang %% Single topic, QoS 0 {ok, _Props, [0]} = emqtt:subscribe(Client, leaves(<< ``` -------------------------------- ### Subscribe to Topic (Shared) Source: https://github.com/emqx/emqtt/blob/master/README.md Subscribe to a topic using a shared subscription. This allows multiple clients to consume messages from the same topic. ```bash $ ./emqtt sub -t '$share/group/hello' Client emqtt-zhouzibodeMacBook-Pro-288e65bb3f4013d30249 sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-288e65bb3f4013d30249 subscribed to $share/group/hello hello world ``` -------------------------------- ### Add EMQTT as a rebar3 Git Dependency Source: https://context7.com/emqx/emqtt/llms.txt Configuration for `rebar.config` to add EMQTT as a project dependency using a Git repository and a specific tag. ```erlang %% rebar.config {erl_opts, [debug_info]}. {deps, [ {emqtt, {git, "https://github.com/emqx/emqtt", {tag, "1.14.4"}}} ]}. %% To disable QUIC support (simplifies compilation on some platforms): %% Set environment variable: BUILD_WITHOUT_QUIC=1 ``` -------------------------------- ### Synchronous Publish with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Publishes messages with varying Quality of Service (QoS) levels. QoS 0 is fire-and-forget, while QoS 1 and 2 return acknowledgment details. Supports MQTT v5 properties for advanced configurations. ```erlang %% QoS 0 — fire and forget ok = emqtt:publish(Client, << ``` ```erlang sensors/temp>>, << ``` ```erlang 22.5>>), %% QoS 1 with options {ok, Reply} = emqtt:publish(Client, << ``` ```erlang commands/led>>, << ``` ```erlang on>>, [{qos, 1}, {retain, false}]), io:format("PacketId=~p ReasonCode=~p~n", [maps:get(packet_id, Reply), maps:get(reason_code, Reply)]), %% QoS 2 with MQTT v5 properties {ok, _} = emqtt:publish(Client, << ``` ```erlang alerts/fire>>, #{'Message-Expiry-Interval' => 60, 'Content-Type' => << ``` ```erlang text/plain>>}, << ``` ```erlang FIRE ALARM>>, [{qos, 2}, {retain, true}]). ``` -------------------------------- ### emqtt:subscribe/3 Source: https://github.com/emqx/emqtt/blob/master/README.md Sends a SUBSCRIBE packet to the MQTT server. It includes optional properties and a list of topic filters with subscription options. Returns {ok, Properties, ReasonCodes} on success, or {error, Reason} on failure. ```APIDOC ## emqtt:subscribe/3 ### Description Send a `SUBSCRIBE` packet to the MQTT server. `Properties` specifies properties for `SUBSCRIBE` packet, defaults to `#{}` meaning no properties are attached. `Subscriptions` specifies pairs of topic filter and subscription options. The topic filter is requried, the subscription options can be `[]`, equivalent to `[{rh, 0}, {rap, 0}, {nl, 0}, {qos, 0}]`. ### Parameters #### Path Parameters - **Client** (client()) - Required - The client identifier or PID. - **Properties** (properties()) - Optional - Properties for the SUBSCRIBE packet. - **Subscriptions** (Subscriptions) - Required - A list of topic filters and their subscription options. ### Response #### Success Response - **{ok, Properties, ReasonCodes}** - Returns the properties and reason codes for each subscription. #### Error Response - **{error, Reason}** - Any error reason. ``` -------------------------------- ### emqtt:status/1 — Query connection state Source: https://context7.com/emqx/emqtt/llms.txt Returns the current state of the client state machine: `initialized | waiting_for_connack | connected | reconnect`. ```APIDOC ## emqtt:status/1 — Query connection state ### Description Returns the current state of the client state machine: `initialized | waiting_for_connack | connected | reconnect`. ### Method `emqtt:status(Client)` ### Parameters #### Path Parameters - **Client**: The MQTT client instance. ### Response #### Success Response - **State**: The current connection state (e.g., `connected`). ### Request Example ```erlang connected = emqtt:status(Client). ``` ``` -------------------------------- ### emqtt:info/1,2 — Inspect client state Source: https://context7.com/emqx/emqtt/llms.txt Returns internal state information. The 2-argument form accepts specific attribute keys: `n_queued`, `n_inflight`, or `max_inflight`. ```APIDOC ## emqtt:info/1,2 — Inspect client state ### Description Returns internal state information. The 2-argument form accepts specific attribute keys: `n_queued`, `n_inflight`, or `max_inflight`. ### Method `emqtt:info(Client)` `emqtt:info(Client, AttributeKey)` ### Parameters #### Path Parameters - **Client**: The MQTT client instance. - **AttributeKey**: The specific attribute to query (e.g., `n_queued`, `n_inflight`, `max_inflight`). ### Response #### Success Response - **State**: A proplist containing internal client state information. - **Value**: The value of the requested attribute. ### Request Example ```erlang %% Full state dump (proplist) State = emqtt:info(Client), %% Specific attributes NInflight = emqtt:info(Client, n_inflight), NQueued = emqtt:info(Client, n_queued), MaxInflight = emqtt:info(Client, max_inflight), io:format("Inflight=~p Queued=~p Max=~p\n", [NInflight, NQueued, MaxInflight]). ``` ``` -------------------------------- ### WebSocket MQTT Connect Source: https://context7.com/emqx/emqtt/llms.txt Connects using the WebSocket transport. The default path is /mqtt, but can be overridden using the {ws_path, Path} option in start_link/1. ```erlang {ok, Client} = emqtt:start_link([ {host, "broker.emqx.io"}, {port, 8083}, {ws_path, "/mqtt"} ]), {ok, _Props} = emqtt:ws_connect(Client). ``` -------------------------------- ### Publish MQTT message Source: https://github.com/emqx/emqtt/blob/master/README.md Synopsis for the emqtt pub command, detailing options for publishing a single message. ```sh ./emqtt pub [-h []] [-p ] [-I ] [-V []] [-u ] [-P ] [-C ] [-k []] [-t ] [-q []] [-r []] [--help ] [--will-topic ] [--will-payload ] [--will-qos []] [--will-retain []] [--enable-websocket []] [--enable-quic []] [--enable-ssl []] [--tls-version []] [--CAfile ] [--cert ] [--key ] [--payload ] [--file ] [--repeat []] [--repeat-delay []] ``` -------------------------------- ### Subscribe over TLS with Client Certificate Source: https://context7.com/emqx/emqtt/llms.txt Subscribe to a topic securely over TLS, providing CA certificate, client certificate, and client key for authentication. ```bash ./emqtt sub -h broker.emqx.io -p 8883 --enable-ssl=true \ --CAfile certs/ca.pem --cert certs/client.pem --key certs/client.key \ -t "secure/events" -q 1 ``` -------------------------------- ### emqtt:stop Source: https://github.com/emqx/emqtt/blob/master/README.md Stop a client process gracefully. ```APIDOC ## emqtt:stop ### Description Stop a client process. ### Method `emqtt:stop(Client) -> ok` ### Parameters #### Path Parameters - **Client** (Client) - Required - The client identifier. ### Return Value - **ok** - Indicates successful termination. ### Types - **Client**: client() ``` -------------------------------- ### Asynchronous Publish with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Sends publish requests without blocking the caller. Results are delivered to a specified callback function or MFA. Supports various QoS levels and timeouts. ```erlang %% Callback as fun/1 — result is ok | {ok, Reply} | {error, Reason} Callback = fun(Result) -> case Result of ok -> io:format("QoS 0 sent~n"); {ok, Reply} -> io:format("Acked: ~p~n", [Reply]); {error, Reason} -> io:format("Error: ~p~n", [Reason]) end end, %% Async publish QoS 1 with 5-second expiry timeout ok = emqtt:publish_async(Client, << ``` ```erlang telemetry/cpu>>, << ``` ```erlang 85>>, [{qos, 1}], timer:seconds(5), Callback), %% Callback as MFA — result appended as last arg ok = emqtt:publish_async(Client, _Via = default, << ``` ```erlang alerts>>, #{}, << ``` ```erlang critical>>, [{qos, 2}], timer:seconds(10), {my_module, handle_pub_result, [extra_arg]}). ``` -------------------------------- ### emqtt:subscriptions Source: https://github.com/emqx/emqtt/blob/master/README.md Retrieve all current subscriptions for a given client. ```APIDOC ## emqtt:subscriptions ### Description Return all subscriptions. ### Method `emqtt:subscriptions(Client) -> Subscriptions` ### Parameters #### Path Parameters - **Client** (Client) - Required - The client identifier. ### Return Value - **Subscriptions** (Subscriptions) - A list of topics and their subscription options. ### Types - **Client**: client() - **Subscriptions**: [{topic(), [subopt()]}]] ``` -------------------------------- ### Query Connection State with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Returns the current state of the client state machine, which can be one of: initialized, waiting_for_connack, connected, or reconnect. ```erlang connected = emqtt:status(Client). ``` -------------------------------- ### Subscribe and Print Payload Size Source: https://context7.com/emqx/emqtt/llms.txt Subscribe to a topic and configure the client to only print the size of the received payload, useful for large data transfers. ```bash ./emqtt sub -h localhost -t "large/data" --print size ``` -------------------------------- ### Subscribe to Topics with EMQTT Source: https://context7.com/emqx/emqtt/llms.txt Subscribes to one or more topics, blocking until a SUBACK is received. Returns granted QoS levels or error codes. Supports MQTT v5 subscription properties. ```erlang %% Single topic, QoS 0 {ok, _Props, [0]} = emqtt:subscribe(Client, << ``` ```erlang sensors/#>>) , %% Single topic, named QoS {ok, _Props, [GrantedQoS]} = emqtt:subscribe(Client, << ``` ```erlang alerts/+>>, qos2), %% Multiple topics in one SUBSCRIBE packet {ok, _Props, ReasonCodes} = emqtt:subscribe(Client, [ {<< ``` ```erlang telemetry/+/temp>>, [{qos, 1}]}, {<< ``` ```erlang commands/#>>, [{qos, 2}]}, {<< ``` ```erlang status>>, [{qos, 0}, {nl, true}, {rap, true}, {rh, 1}]} ]), io:format("Granted QoS values: ~p~n", [ReasonCodes]), %% With MQTT v5 subscription properties {ok, _Props, _RCs} = emqtt:subscribe(Client, #{'Subscription-Identifier' => 42}, << ``` ```erlang my/topic>>, [{qos, 1}]). ``` -------------------------------- ### Manual QoS Acknowledgments Source: https://context7.com/emqx/emqtt/llms.txt Provides functions for manually sending QoS acknowledgment packets (PUBACK, PUBREC, PUBREL, PUBCOMP). This is used when `auto_ack` is set to `false`, allowing the application to control the full QoS 1 and QoS 2 flow. ```APIDOC ## emqtt:puback/2..4, pubrec/2..4, pubrel/2..4, pubcomp/2..4 — Manual QoS acknowledgment These casts send QoS acknowledgment packets manually. Use when `{auto_ack, false}` is configured so the application controls the full QoS 1/2 flow. ### Example ```erlang {ok, Client} = emqtt:start_link([ {host, "localhost"}, {auto_ack, false}, {msg_handler, #{publish => fun(#{packet_id := PktId, qos := QoS} = Msg) -> %% Process message io:format("Got: ~s~n", [maps:get(payload, Msg)]), %% Manually acknowledge case QoS of 1 -> emqtt:puback(Client, PktId); 2 -> emqtt:pubrec(Client, PktId) end end}} ]), {ok, _} = emqtt:connect(Client), emqtt:subscribe(Client, "commands/#", 2), %% QoS 2 flow: pubrec -> then handle pubrel -> then pubcomp %% emqtt:pubrec(Client, PacketId) %% after receiving PUBLISH %% emqtt:pubcomp(Client, PacketId) %% after receiving PUBREL %% With reason code and properties emqtt:puback(Client, 42, 16#00, #{'Reason-String' => "ok"}). ``` ``` -------------------------------- ### emqtt:connect/1 Source: https://context7.com/emqx/emqtt/llms.txt Initiates an MQTT CONNECT handshake over a plain TCP socket. This function blocks until a CONNACK packet is received or the `connect_timeout` elapses. ```APIDOC ## `emqtt:connect/1` — TCP MQTT connect Initiates an MQTT CONNECT handshake over a plain TCP socket. Blocks until CONNACK is received or `connect_timeout` elapses. ```erlang {ok, Client} = emqtt:start_link([{host, "localhost"}, {port, 1883}]), case emqtt:connect(Client) of {ok, Properties} -> io:format("Connected. Server properties: ~p~n", [Properties]); {error, {not_authorized, _Props}} -> io:format("Auth failed~n"); {error, connack_timeout} -> io:format("Server did not respond in time~n") end. ``` ```