### start_link/0 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Starts a new MQTT client process with default options. ```APIDOC ## start_link/0 ### Description Starts a new MQTT client process with default options. ### Returns - `{ok, Pid} | {error, Reason}` ### Example ```erlang {ok, Client} = emqtt:start_link(). ``` ``` -------------------------------- ### Message Handler Implementation Example Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Demonstrates configuring a message handler and starting an emqtt client. ```erlang Handler = #{ publish => fun(#{topic := Topic, payload := Payload}) -> io:format("Received: ~s = ~s~n", [Topic, Payload]) end, connected => fun(_Props) -> io:format("Connected~n") end, disconnected => fun({Code, _Props}) -> io:format("Disconnected with code: ~p~n", [Code]) end }, {ok, Client} = emqtt:start_link([ {host, "broker.local"}, {msg_handler, Handler} ]). ``` -------------------------------- ### start_link/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Starts a new MQTT client process with configuration options as either a map or property list. ```APIDOC ## start_link/1 ### Description Starts a new MQTT client process with configuration options as either a map or property list. ### Parameters - **Options** (`map() | [option()]`) - Required - Configuration options ### Returns - `{ok, Pid} | {error, Reason}` ### Example ```erlang Options = [ {host, "broker.example.com"}, {port, 1883}, {clientid, "my-client"}, {username, "user"}, {password, "pass"} ], {ok, Client} = emqtt:start_link(Options). ``` ``` -------------------------------- ### Subscribing to MQTT Topics Source: https://github.com/emqx/emqtt/blob/master/README.md Examples of performing standard and shared subscriptions. ```bash $ ./emqtt sub -t "hello" Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c subscribed to hello hello world ``` ```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 ``` -------------------------------- ### Command-line Syntax Examples Source: https://github.com/emqx/emqtt/blob/master/README.md Syntax patterns for short and long command-line options. ```text -e arg Single option 'e', argument "arg" ``` ```text --example=arg Single option 'example', argument "arg" --example arg Single option 'example', argument "arg" ``` -------------------------------- ### Initialize emqtt client with configuration Source: https://github.com/emqx/emqtt/blob/master/_autodocs/configuration.md Demonstrates starting an emqtt client using either a property list or a map format. ```erlang % Property list format {ok, Client} = emqtt:start_link([ {host, "broker.example.com"}, {port, 1883}, {clientid, "my-client"} ]). % Map format {ok, Client} = emqtt:start_link(#{ host => "broker.example.com", port => 1883, clientid => "my-client" }). ``` -------------------------------- ### Start MQTT client with default options Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initializes a new MQTT client process using default configuration settings. ```erlang {ok, Client} = emqtt:start_link(). ``` -------------------------------- ### Full MQTT client workflow example Source: https://github.com/emqx/emqtt/blob/master/README.md Demonstrates a complete lifecycle including connection, subscription, publishing, message reception, and disconnection. ```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">>, #{}, <<"Hello World!">>, [{qos, 0}]). {ok, _PktId} = emqtt:publish(ConnPid, <<"hello">>, #{}, <<"Hello World!">>, [{qos, 1}]). receive {disconnected, ReasonCode, Properties} -> io:format("Recv a DISONNECT packet - ReasonCode: ~p, Properties: ~p~n", [ReasonCode, Properties]); {publish, PUBLISH} -> io:format("Recv a PUBLISH packet: ~p~n", [PUBLISH]); {puback, {PacketId, ReasonCode, Properties}} -> io:format("Recv a PUBACK packet - PacketId: ~p, ReasonCode: ~p, Properties: ~p~n", [PacketId, ReasonCode, Properties]) end. {ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, <<"hello">>). ok = emqtt:disconnect(ConnPid). ok = emqtt:stop(ConnPid). ``` -------------------------------- ### Asynchronous Publish Examples Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Demonstrates asynchronous publishing using via routing or MQTT v5 properties. ```erlang % With Via routing ok = emqtt:publish_async(Client, default, <<"topic">>, <<"data">>, {my_module, callback, []}). % With properties ok = emqtt:publish_async(Client, <<"topic">>, #{}, <<"data">>, fun(Result) -> io:format("Result: ~p~n", [Result]) end). ``` -------------------------------- ### Start MQTT client with custom options Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initializes a new MQTT client process using a property list of configuration options. ```erlang Options = [ {host, "broker.example.com"}, {port, 1883}, {clientid, "my-client"}, {username, "user"}, {password, "pass"} ], {ok, Client} = emqtt:start_link(Options). ``` -------------------------------- ### Unsubscribe with Properties Example Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Demonstrates unsubscribing while providing MQTT v5 properties. ```erlang {ok, Props, Codes} = emqtt:unsubscribe(Client, #{}, <<"topic">>). ``` -------------------------------- ### Configure Clean Start Flag Source: https://github.com/emqx/emqtt/blob/master/_autodocs/configuration.md Sets the Clean Start flag for the MQTT CONNECT packet. ```erlang {clean_start, false} ``` -------------------------------- ### Connect with Full WSS Configuration Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md A comprehensive example combining SSL, transport options, custom headers, and active mode configuration. ```erlang {ok, WS} = emqtt_ws:connect([ {host, "mqtt.example.com"}, {port, 8883}, {path, "/mqtt"}, {ssl_options, [ {certfile, "/etc/certs/client.crt"}, {keyfile, "/etc/certs/client.key"}, {cacertfile, "/etc/certs/ca.crt"}, {verify, verify_peer}, {fail_if_no_peer_cert, true} ]}, {transport_options, [ {keepalive, true}, {nodelay, true} ]}, {headers, [ {"X-API-Key", "secret-key"} ]}, {active, once} ]). ``` -------------------------------- ### emqtt:start_link/0,1 Source: https://github.com/emqx/emqtt/blob/master/README.md Starts an MQTT client process. The function can be called without arguments or with a list of options to configure the connection, such as host, port, and authentication details. ```APIDOC ## emqtt:start_link/0,1 ### Description Starts the MQTT client process. If options are provided, they are used to configure the connection and client behavior. ### Signature - `emqtt:start_link() -> {ok, Pid} | ignore | {error, Reason}` - `emqtt:start_link(Options) -> {ok, Pid} | ignore | {error, Reason}` ### Parameters - **Options** (list of option()) - Optional - A list of configuration options including host, port, clientid, username, password, and various protocol settings. ### Returns - **{ok, Pid}** - Success, returns the process ID of the client. - **ignore** - Process start was ignored. - **{error, Reason}** - Failure, returns the error reason. ``` -------------------------------- ### Start QUIC data stream Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Creates a new QUIC data stream and uses it to publish a message. ```erlang {ok, Via} = emqtt:start_data_stream(Client, #{}), ok = emqtt:publish(Client, Via, <<"topic">>, <<"message">>). ``` -------------------------------- ### Publishing MQTT Messages Source: https://github.com/emqx/emqtt/blob/master/README.md Examples of publishing messages using different transport protocols. ```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 ``` ```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 ``` ```bash $ ./emqtt pub --enable-websocket=true -p 8083 -t "hello" --payload "hello world" Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent CONNECT Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent DISCONNECT ``` -------------------------------- ### open_connection/0 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Opens a QUIC connection without starting the MQTT protocol. This is a prerequisite for initiating an MQTT handshake. ```APIDOC ## open_connection() ### Description Opens a QUIC connection without starting MQTT protocol. Call mqtt_connect/1 on client after this to initiate MQTT handshake. ### Returns {ok, ConnectionHandle} | {error, Reason} ``` -------------------------------- ### Connect via QUIC Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Specifies the function signature for establishing a QUIC connection and opening a control stream, with a basic usage example. ```erlang -spec connect(gen_statem:start_ret()) -> {ok, quic_sock()} | {error, term()}. ``` ```erlang {ok, Client} = emqtt:start_link([{host, "mqtt"}]), {ok, _Props} = emqtt:quic_connect(Client). ``` -------------------------------- ### Define MQTT v5.0 Properties Map Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_props.md Example of an Erlang map structure used to represent MQTT v5.0 properties. ```erlang -type properties() :: #{atom() => term()}. % Example Properties = #{ 'Session-Expiry-Interval' => 3600, 'Message-Expiry-Interval' => 300, 'Content-Type' => <<"application/json">>, 'Correlation-Data' => <<"abc123">>, 'Subscription-Identifier' => 42 }. ``` -------------------------------- ### Connect with MQTT v5 properties Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_props.md Configures connection properties such as session expiry and receive maximum when starting an emqtt client. ```erlang ConnectProps = #{ 'Session-Expiry-Interval' => 3600, 'Receive-Maximum' => 100, 'Topic-Alias-Maximum' => 10 }, {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {proto_ver, v5}, {properties, ConnectProps} ]). ``` -------------------------------- ### emqtt:ws_connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a WebSocket connection for an initialized emqtt client. This function is used after starting the client with appropriate WebSocket configuration options. ```APIDOC ## emqtt:ws_connect/1 ### Description Establishes a WebSocket connection for an initialized emqtt client. This function is called after the client has been started with the necessary WebSocket host, port, and path configuration. ### Signature emqtt:ws_connect(Client) ### Parameters - **Client** (pid) - Required - The process identifier of the initialized emqtt client. ### Returns - **{ok, Props}** - Success response containing connection properties. - **{error, Reason}** - Error response if the connection fails. ``` -------------------------------- ### Open QUIC connection Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Specifies the function signature for opening a QUIC connection and provides a usage example for initiating an MQTT handshake. ```erlang -spec open_connection() -> {ok, quicer:connection_handle()} | {error, term()}. ``` ```erlang {ok, Client} = emqtt:start_link([...]), ok = emqtt:open_quic_connection(Client), ok = emqtt:quic_mqtt_connect(Client). ``` -------------------------------- ### emqtt:start_link/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/configuration.md Initializes an MQTT client connection with the specified configuration options. ```APIDOC ## emqtt:start_link/1 ### Description Starts an MQTT client process and connects to the broker using the provided configuration options. ### Parameters - **Options** (proplist | map) - Required - A list or map of configuration options including host, port, and network settings. ### Configuration Options - **host** (string | atom | binary | tuple) - Optional - Hostname or IP address of the MQTT broker. Default: "localhost". - **port** (integer) - Optional - Port number of the MQTT broker. Default: 1883 (or 8883 if SSL enabled). - **hosts** (list) - Optional - List of broker addresses for failover support. - **shuffle_hosts** (boolean) - Optional - Whether to randomize the order of hosts in the hosts list. Default: false. - **iface** (string) - Optional - Network interface or local IP address to bind outbound connections. ### Example {ok, Client} = emqtt:start_link(#{host => "broker.example.com", port => 1883}) ``` -------------------------------- ### Get maximum queue size Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_inflight.md Retrieve the configured maximum capacity of the queue. ```erlang MaxInflight = emqtt_inflight:max_size(Inflight), io:format("Max in-flight: ~p~n", [MaxInflight]). ``` -------------------------------- ### Get current queue length Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_inflight.md Retrieve the number of messages currently awaiting acknowledgment. ```erlang NumInflight = emqtt_inflight:len(Inflight), io:format("~p messages awaiting acknowledgment~n", [NumInflight]). ``` -------------------------------- ### View emqtt Help Source: https://github.com/emqx/emqtt/blob/master/README.md Display the help menu for the emqtt command line tool. ```bash $ ./emqtt --help Usage: emqtt pub | sub [--help] ``` -------------------------------- ### Validate Message-Expiry-Interval Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_props.md Example of validating the Message-Expiry-Interval property to ensure it is a non-negative integer within the allowed range. ```erlang validate_expiry(Props) -> case maps:get('Message-Expiry-Interval', Props, undefined) of undefined -> ok; % Optional N when is_integer(N), N >= 0, N =< 4294967295 -> ok; % Valid Invalid -> {error, {invalid_expiry, Invalid}} end. ``` -------------------------------- ### connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a WebSocket connection to an MQTT broker using a list of configuration options. ```APIDOC ## connect(Options) ### Description Establishes a WebSocket connection to an MQTT broker. ### Parameters - **Options** ([option()]) - Required - WebSocket connection options including host, port, path, and SSL/transport settings. ### Returns - **{ok, connection()}** - Success - **{error, term()}** - Error (e.g., econnrefused, timeout, http_error, tls_alert) ### Example {ok, WS} = emqtt_ws:connect([{host, "mqtt.example.com"}, {port, 8083}, {path, "/mqtt"}, {active, once}]); ``` -------------------------------- ### Get Serialization Functions Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_frame.md Retrieve a function object configured for serializing MQTT packets with specific version settings. ```erlang Serialize = emqtt_frame:serialize_fun(), Binary = erlang:iolist_to_binary(Serialize(ConnectPacket)). ``` ```erlang SerializeV5 = emqtt_frame:serialize_fun(#{version => 5}), Binary = erlang:iolist_to_binary(SerializeV5(AuthPacket)). ``` -------------------------------- ### Build project Source: https://github.com/emqx/emqtt/blob/master/README.md Compile the project using rebar3. ```bash $ rebar3 compile ``` -------------------------------- ### Configure EMQTT Client Source: https://github.com/emqx/emqtt/blob/master/_autodocs/configuration.md Initializes an EMQTT client with connection, security, protocol, and callback parameters. ```erlang {ok, Client} = emqtt:start_link([ % Connection {host, "mqtt.example.com"}, {port, 8883}, {clientid, "sensor-device-001"}, % Protocol {proto_ver, v5}, {clean_start, false}, % Authentication {username, "device_user"}, {password, "secure_password"}, % Security {ssl, true}, {ssl_opts, [ {certfile, "/etc/certs/client.crt"}, {keyfile, "/etc/certs/client.key"}, {cacertfile, "/etc/certs/ca.crt"}, {verify, verify_peer} ]}, % Will message {will_topic, "devices/sensor001/status"}, {will_payload, "offline"}, {will_qos, 1}, {will_retain, true}, % Timeouts {keepalive, 60}, {connect_timeout, 30}, {ack_timeout, 30}, % Reconnect {reconnect, 5}, {reconnect_timeout, 10}, {retry_calls_on_reconnect, true}, % QoS {max_inflight, 100}, {auto_ack, true}, % Callbacks {msg_handler, #{ publish => fun handle_message/1, connected => fun handle_connected/1, disconnected => fun handle_disconnected/1 }}, % Performance {force_ping, true}, % Process {name, mqtt_sensor_client}, {owner, self()} ]). ``` -------------------------------- ### Command-Line Interface Usage Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md Common CLI commands for publishing, subscribing, and testing broker connectivity. ```bash # Publish a message emqtt pub -h mqtt.example.com -t "sensors/temp" -q 1 --payload "25.5" # Subscribe to topics emqtt sub -h mqtt.example.com -t "sensors/+" --print as-string # Test connection emqtt connect -h mqtt.example.com --enable-ssl --verify true ``` -------------------------------- ### Configure QUIC Connection and Stream Options Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Pass connection and stream options via the quic_opts configuration key during client initialization. ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 14567}, {quic_opts, {ConnOpts, StreamOpts}}, ... ]), {ok, _Props} = emqtt:quic_connect(Client). ``` ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 14567}, {quic_opts, { #{}, % Connection options #{active => once} % Stream options }} ]). ``` -------------------------------- ### Send MQTT frame over QUIC Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Specifies the function signature for sending data and provides an example of extracting the socket components. ```erlang -spec send(quic_sock(), iodata()) -> ok | {error, term()}. ``` ```erlang {quic, Conn, Stream} = QuicSock, ok = emqtt_quic:send(QuicSock, MQTTFrame). ``` -------------------------------- ### emqtt:connect(Client) Source: https://github.com/emqx/emqtt/blob/master/README.md Establishes a connection to an MQTT server using the provided client configuration options. ```APIDOC ## emqtt:connect(Client) ### Description Connects to an MQTT server using the specified client configuration. Returns the connection properties on success or an error reason on failure. ### Parameters - **Client** (client()) - Required - A list of configuration options including hosts, port, authentication, and protocol settings. ### Response - **Success** ({ok, Properties}) - Connection established successfully. - **Error** ({error, Reason}) - Connection failed, where Reason can be timeout, an inet posix error, or other error types. ``` -------------------------------- ### Build emqtt Source: https://github.com/emqx/emqtt/blob/master/README.md Commands to compile the emqtt project from source. ```bash $ make ``` ```sh BUILD_WITHOUT_QUIC=1 make ``` -------------------------------- ### Erlang Library Usage Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md Demonstrates the lifecycle of an MQTT client including connection, subscription, publishing, and disconnection. ```erlang % Start MQTT client {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 1883}, {clientid, "my-device"}, {username, "user"}, {password, "pass"} ]). % Connect to broker {ok, Properties} = emqtt:connect(Client). % Subscribe to topic {ok, Props, ReasonCodes} = emqtt:subscribe(Client, [<<"topic/sensors">>, <<"topic/alerts">>], [{qos, 1}]). % Publish a message ok = emqtt:publish(Client, <<"topic/sensors">>, <<"data">>, [{qos, 1}]). % Disconnect ok = emqtt:disconnect(Client). ``` -------------------------------- ### emqtt:start_link/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Configures enhanced authentication by passing a custom_auth_callbacks map in the options list. ```APIDOC ## emqtt:start_link/1 ### Description Initializes the MQTT client with custom authentication callbacks to support enhanced authentication mechanisms. ### Parameters - **custom_auth_callbacks** (map) - Required - A map containing the authentication logic: - **init** (tuple) - {InitFunc :: function(), InitArgs :: list()} - **handle_auth** (function) - Function to handle authentication continuation ### Callback Signatures #### InitFunc Executed with InitArgs. Must return `{AuthProps, AuthState}`. - **AuthProps** (map) - Initial authentication properties including 'Authentication-Method' and 'Authentication-Data'. - **AuthState** (term) - State passed to subsequent steps. #### HandleAuth Accepts `(AuthState, Directive, AuthProps)`. Returns `{continue, {?RC_CONTINUE_AUTHENTICATION, AuthProps}, AuthState}` or `{stop, Reason}`. ``` -------------------------------- ### connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Establishes a QUIC connection and opens a control stream for MQTT communication. ```APIDOC ## connect(gen_statem:start_ret()) ### Description Establishes QUIC connection and opens control stream for MQTT. ### Parameters - **Client** (gen_statem:start_ret()) - Required - The client state reference. ### Returns {ok, quic_sock()} | {error, term()} ``` -------------------------------- ### connect/2 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a WebSocket connection to an MQTT broker using a host and port, defaulting to the /mqtt path. ```APIDOC ## connect(Host, Port) ### Description Connect with just host and port (default WS path: /mqtt). ### Parameters - **Host** (string() | inet:ip_address()) - Required - WebSocket server hostname - **Port** (inet:port_number()) - Required - WebSocket server port ### Returns - **{ok, connection()}** - Success - **{error, term()}** - Error ### Example {ok, WS} = emqtt_ws:connect("mqtt.example.com", 8083); ``` -------------------------------- ### connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initiates MQTT connection over TCP/TLS socket. ```APIDOC ## connect/1 ### Description Initiates MQTT connection over TCP/TLS socket. ### Parameters - **Client** (`client()`) - Required - Client PID or registered name ### Returns - `{ok, Properties} | {error, Reason}` ### Example ```erlang case emqtt:connect(Client) of {ok, _Props} -> io:format("Connected~n"); {error, Reason} -> io:format("Failed: ~p~n", [Reason]) end. ``` ``` -------------------------------- ### Publish Command Synopsis Source: https://github.com/emqx/emqtt/blob/master/README.md The full list of available options for the emqtt pub command. ```bash ./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 []] ``` -------------------------------- ### emqtt Command-Line Interface Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md The emqtt CLI tool allows for quick interaction with MQTT brokers directly from the terminal. ```APIDOC ## emqtt pub ### Description Publishes a message to a specified topic. ### Usage `emqtt pub -h -t -q --payload ` ## emqtt sub ### Description Subscribes to topics and prints received messages. ### Usage `emqtt sub -h -t --print as-string` ## emqtt connect ### Description Tests a connection to the broker with optional SSL/TLS settings. ### Usage `emqtt connect -h --enable-ssl --verify ` ``` -------------------------------- ### Define subopt() and pubopt() data types Source: https://github.com/emqx/emqtt/blob/master/README.md Options for subscription and publication. ```erlang subopt() = {rh, 0 | 1 | 2} | {rap, boolean()} | {nl, boolean()} | {qos, qos() | qos_name()} ``` ```erlang pubopt() = {retain, boolean()} | {qos, qos() | qos_name()} ``` -------------------------------- ### Configure Reliable IoT Device Client Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md Initializes an emqtt client with SSL, keepalive, and persistent session settings for reliable IoT communication. ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 8883}, {clientid, "device-001"}, {username, "iot_user"}, {password, get_password()}, {ssl, true}, {ssl_opts, [{verify, verify_peer}, {cacertfile, "/etc/certs/ca.crt"}]}, {keepalive, 60}, {max_inflight, 100}, {clean_start, false}, {reconnect, 10}, {will_topic, "devices/device-001/status"}, {will_payload, "offline"}, {will_qos, 1}, {will_retain, true} ]) ``` -------------------------------- ### connect/3 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_sock.md Establishes a standard TCP connection to an MQTT broker. ```APIDOC ## connect(Host, Port, Options) ### Description Establishes a TCP connection to the broker. ### Parameters - **Host** (inet:hostname() | inet:ip_address()) - Required - Broker hostname or IP - **Port** (inet:port_number()) - Required - Broker port (typically 1883) - **Options** ([option()]) - Required - Socket options ### Returns {ok, inet:socket()} | {error, term()} ### Example {ok, Socket} = emqtt_sock:connect("mqtt.example.com", 1883, [{timeout, 60000}]); ``` -------------------------------- ### ws_connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initiates MQTT connection over WebSocket (WS/WSS). ```APIDOC ## ws_connect/1 ### Description Initiates MQTT connection over WebSocket (WS/WSS). ### Parameters - **Client** (`client()`) - Required - Client PID or registered name ### Returns - `{ok, Properties} | {error, Reason}` ### Example ```erlang emqtt:ws_connect(Client). ``` ``` -------------------------------- ### start_data_stream/2 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Creates a new QUIC data stream for long-lived operations. ```APIDOC ## start_data_stream/2 ### Description Creates a new QUIC data stream for long-lived operations. QUIC only. ### Parameters - **Client** (`client()`) - Required - Client PID or registered name - **StreamOpts** (`quicer:stream_opts()`) - Required - QUIC stream options ### Returns - `{ok, Via} | {error, Reason}` ### Example ```erlang {ok, Via} = emqtt:start_data_stream(Client, #{}), ok = emqtt:publish(Client, Via, <<"topic">>, <<"message">>). ``` ``` -------------------------------- ### emqtt:start_data_stream/2 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Creates an additional data stream for concurrent MQTT operations over a QUIC connection. ```APIDOC ## emqtt:start_data_stream(Client, Options) ### Description Creates a new data stream on an existing QUIC connection to allow for parallel MQTT operations. ### Parameters - **Client** (pid) - Required - The MQTT client process identifier. - **Options** (map) - Required - Stream configuration options. ### Returns - **{ok, Via}** - Returns a stream identifier (Via) used for subsequent operations. ``` -------------------------------- ### Connect to MQTT broker via WebSocket Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a connection using a list of configuration options. ```erlang -spec connect([option()]) -> {ok, connection()} | {error, term()}. ``` ```erlang {ok, WS} = emqtt_ws:connect([ {host, "mqtt.example.com"}, {port, 8083}, {path, "/mqtt"}, {active, once} ]). ``` -------------------------------- ### Publish with QoS or options using emqtt:publish/3 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Supports specifying QoS levels as integers, atoms, or providing a list of publish options. ```erlang % Publish with QoS 1 ok = emqtt:publish(Client, <<"topic">>, <<"payload">>, 1). % Publish with QoS name ok = emqtt:publish(Client, <<"topic">>, <<"payload">>, at_least_once). % Publish with options Opts = [{qos, 1}, {retain, true}], ok = emqtt:publish(Client, <<"topic">>, <<"payload">>, Opts). ``` -------------------------------- ### Manage QUIC stream limits in Erlang Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Demonstrates how to check available streams and handle the stream limit error when creating a pool of data streams. ```erlang % Check available streams {ok, Client} = emqtt:start_link([...]), {ok, _} = emqtt:quic_connect(Client), % Create streams up to limit create_stream_pool(Client, NumStreams) -> create_stream_pool(Client, NumStreams, []). create_stream_pool(_Client, 0, Streams) -> Streams; create_stream_pool(Client, NumStreams, Acc) -> case emqtt:start_data_stream(Client, #{}) of {ok, Via} -> create_stream_pool(Client, NumStreams - 1, [Via | Acc]); {error, stream_limit_reached} -> io:format("Reached stream limit at ~p streams~n", [length(Acc)]), Acc; {error, Reason} -> io:format("Error: ~p~n", [Reason]), Acc end. ``` -------------------------------- ### Connect to MQTT broker with host and port Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Connects using default path settings with specified host and port. ```erlang -spec connect(host(), inet:port_number()) -> {ok, connection()} | {error, term()}. ``` ```erlang {ok, WS} = emqtt_ws:connect("mqtt.example.com", 8083). ``` -------------------------------- ### connect/4 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_sock.md Establishes a TCP connection to an MQTT broker with an explicit timeout override. ```APIDOC ## connect(Host, Port, Options, Timeout) ### Description TCP connection with explicit timeout override. ### Parameters - **Host** (inet:hostname() | inet:ip_address()) - Required - Broker hostname or IP - **Port** (inet:port_number()) - Required - Broker port - **Options** ([option()]) - Required - Socket options - **Timeout** (timeout()) - Required - Connection timeout in milliseconds ### Returns {ok, inet:socket()} | {error, term()} ### Example {ok, Socket} = emqtt_sock:connect("mqtt", 1883, [], 30000); ``` -------------------------------- ### Project File Organization Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md Visual representation of the emqtt source code directory structure. ```text emqtt/ ├── src/ │ ├── emqtt.erl # Main client (2658 lines) │ ├── emqtt_frame.erl # Frame parsing (786 lines) │ ├── emqtt_sock.erl # TCP/TLS socket (194 lines) │ ├── emqtt_ws.erl # WebSocket (107 lines) │ ├── emqtt_quic*.erl # QUIC support (3 modules) │ ├── emqtt_props.erl # MQTT v5 properties (176 lines) │ ├── emqtt_inflight.erl # Message queue (332 lines) │ ├── emqtt_cli.erl # CLI tools (437 lines) │ └── emqtt_secret.erl # Secret handling (43 lines) ├── include/ │ ├── emqtt.hrl # Protocol constants │ └── logger.hrl # Logging macros └── test/ # Test suite ``` -------------------------------- ### quic_connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initiates MQTT connection over QUIC transport. Creates connection and data stream atomically. ```APIDOC ## quic_connect/1 ### Description Initiates MQTT connection over QUIC transport. Creates connection and data stream atomically. ### Parameters - **Client** (`client()`) - Required - Client PID or registered name ### Returns - `{ok, Properties} | {error, Reason}` ### Example ```erlang emqtt:quic_connect(Client). ``` ``` -------------------------------- ### ssl_connect/3 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_sock.md Establishes a TLS/SSL encrypted connection to an MQTT broker. ```APIDOC ## ssl_connect(Host, Port, Options) ### Description Establishes a TLS/SSL encrypted connection. ### Parameters - **Host** (inet:hostname() | inet:ip_address()) - Required - Broker hostname or IP - **Port** (inet:port_number()) - Required - Broker port (typically 8883 for MQTT TLS) - **Options** ([option()]) - Required - Socket and SSL options ### Returns {ok, ssl:sslsocket()} | {error, term()} ### Example {ok, Socket} = emqtt_sock:ssl_connect("mqtt.example.com", 8883, [{ssl_opts, [{certfile, "/etc/certs/client.crt"}, {keyfile, "/etc/certs/client.key"}, {cacertfile, "/etc/certs/ca.crt"}, {verify, verify_peer}]}]); ``` -------------------------------- ### Define QUIC Connection Options Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Standard connection settings passed to the underlying quicer driver. ```erlang ConnOpts = #{ conn_callback => my_callback, idle_timeout => 300000, % milliseconds verify_peer => false } ``` -------------------------------- ### Connect via WebSocket and WSS Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes an MQTT connection over WebSocket or Secure WebSocket using emqtt:start_link and emqtt:ws_connect. ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 8083}, {ws_path, "/mqtt"}, {ws_headers, [ {"Authorization", "Bearer token"} ]} ]), % For HTTP WS {ok, _Props} = emqtt:ws_connect(Client). ``` ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 8883}, {ws_path, "/mqtt"}, {ssl, true}, {ssl_opts, [ {verify, verify_peer}, {cacertfile, "/etc/certs/ca.crt"} ]} ]), {ok, _Props} = emqtt:ws_connect(Client). ``` -------------------------------- ### Configure SSL/TLS Options Source: https://github.com/emqx/emqtt/blob/master/_autodocs/configuration.md Defines client certificates, keys, and verification settings for secure connections. ```erlang {ssl_opts, [ {certfile, "/path/to/client.crt"}, {keyfile, "/path/to/client.key"}, {cacertfile, "/path/to/ca.crt"}, {verify, verify_peer} ]} ``` -------------------------------- ### Connect with Multi-Stream Mode Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_quic.md Utilize start_data_stream/2 to create parallel streams for independent MQTT operations. ```erlang {ok, Client} = emqtt:start_link([{host, "mqtt"}]), {ok, _Props} = emqtt:quic_connect(Client), % Create additional data streams for parallelism {ok, Via1} = emqtt:start_data_stream(Client, #{}), {ok, Via2} = emqtt:start_data_stream(Client, #{}), % Subscribe on stream 1 {ok, _Props, _Codes} = emqtt:subscribe_via(Client, Via1, #{}, [{<<"sensors/temp">>, [{qos, 1}]}]), % Subscribe on stream 2 {ok, _Props, _Codes} = emqtt:subscribe_via(Client, Via2, #{}, [{<<"sensors/humidity">>, [{qos, 1}]}]), % Publish on stream 1 ok = emqtt:publish_via(Client, Via1, <<"sensors/pressure">>, <<"1013.25">>), % Publish on stream 2 ok = emqtt:publish_via(Client, Via2, <<"sensors/light">>, <<"75%">>). ``` -------------------------------- ### Configure TLS certificate validation in Erlang Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_sock.md Demonstrates setting up SSL options and handling specific TLS alert errors during connection. ```erlang setup_tls(Host, Port) -> SSLOpts = [ {certfile, "/etc/certs/client.crt"}, {keyfile, "/etc/certs/client.key"}, {cacertfile, "/etc/certs/ca.crt"}, {verify, verify_peer}, {fail_if_no_peer_cert, true} ], case emqtt_sock:ssl_connect(Host, Port, [{ssl_opts, SSLOpts}]) of {ok, Socket} -> {ok, Socket}; {error, {tls_alert, Alert}} -> case Alert of certificate_revoked -> io:format("Certificate revoked~n"); bad_certificate -> io:format("Bad certificate~n"); unknown_ca -> io:format("Unknown CA~n"); _ -> io:format("TLS alert: ~p~n", [Alert]) end, {error, tls_error}; {error, Reason} -> {error, Reason} end. ``` -------------------------------- ### Subscribe with Properties and QoS Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Subscribes using an explicit properties map, topic, and QoS/options. ```erlang Props = #{'Subscription-Identifier' => 456}, {ok, RetProps, Codes} = emqtt:subscribe(Client, Props, <<"topic/alerts">>, 2). ``` -------------------------------- ### Connect to MQTT broker Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Initiates a connection over TCP/TLS and handles the result using a case statement. ```erlang case emqtt:connect(Client) of {ok, _Props} -> io:format("Connected~n"); {error, Reason} -> io:format("Failed: ~p~n", [Reason]) end. ``` -------------------------------- ### emqtt_ws:connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Low-level function to initiate a WebSocket connection with specific configuration options including host, port, path, and SSL settings. ```APIDOC ## emqtt_ws:connect/1 ### Description Initiates a direct WebSocket connection using a list of configuration options. This is often used for custom connection logic or retry mechanisms. ### Signature emqtt_ws:connect(Options) ### Parameters - **Options** (list) - Required - A list of configuration tuples such as {host, string()}, {port, integer()}, {path, string()}, or {ssl_options, list()}. ### Returns - **{ok, WS}** - Success response containing the WebSocket connection handle. - **{error, Reason}** - Error response, which may include connection errors, HTTP errors, or TLS alerts. ``` -------------------------------- ### emqtt_ws:connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a WebSocket connection to an MQTT broker using the provided configuration options. ```APIDOC ## emqtt_ws:connect(Options) ### Description Establishes a WebSocket connection to an MQTT broker. Returns `{ok, WS}` on success. ### Parameters - **Options** (list) - A list of configuration tuples: - **host** (string) - The broker hostname. - **port** (integer) - The broker port. - **path** (string) - The WebSocket path. - **ssl_options** (list) - SSL/TLS configuration options. - **headers** (list) - Custom HTTP headers. - **transport_options** (list) - TCP transport settings (e.g., keepalive, nodelay). - **active** (atom) - Set to `once` for manual message delivery control. ``` -------------------------------- ### initial_parse_state/0 and initial_parse_state/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_frame.md Creates an initial parsing state for the MQTT frame parser, either with default options or custom configuration. ```APIDOC ## initial_parse_state/0 ### Description Creates initial parsing state with default options (version 4, max_size 256MB, strict_mode false). ### Returns - **parse_state()** - State object for use in parse/2 ## initial_parse_state/1 ### Description Creates initial parsing state with custom options. ### Parameters - **Options** (options()) - Required - Parsing configuration map ``` -------------------------------- ### QUIC connection, handshake, and subscription Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Performs a full QUIC connection sequence followed by an MQTT subscription. ```erlang ok = emqtt:open_quic_connection(Client), ok = emqtt:quic_mqtt_connect(Client), {ok, Properties} = emqtt:subscribe(Client, [<<"topic/1">>]). ``` -------------------------------- ### Configure Real-Time WebSocket Dashboard Source: https://github.com/emqx/emqtt/blob/master/_autodocs/README.md Sets up a WebSocket connection with custom message handlers for publish, connect, and disconnect events. ```erlang {ok, Client} = emqtt:start_link([ {host, "mqtt.example.com"}, {port, 8083}, {ws_path, "/mqtt"}, {msg_handler, #{ publish => fun update_dashboard/1, connected => fun init_subscriptions/1, disconnected => fun on_disconnect/1 }} ]), {ok, _} = emqtt:ws_connect(Client) ``` -------------------------------- ### emqtt_ws:connect/1 Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt_ws.md Establishes a WebSocket connection with specified options, including the active mode for message reception. ```APIDOC ## emqtt_ws:connect(Options) ### Description Establishes a WebSocket connection to the specified host and port. The `active` option determines how messages are received: `false` (passive), `once` (receive one then pause), or `true` (continuous). ### Parameters - **Options** (list) - Required - A list of tuples including host, port, and active mode settings. ### Example ```erlang {ok, WS} = emqtt_ws:connect([{host, "mqtt"}, {port, 8083}, {active, false}]). ``` ``` -------------------------------- ### Subscribe Command Synopsis Source: https://github.com/emqx/emqtt/blob/master/README.md The full list of available options for the subscribe command. ```bash ./emqtt sub [-h []] [-p ] [-I ] [-V []] [-u ] [-P ] [-C ] [-k []] [-t ] [-q []] [--help ] [--will-topic ] [--will-payload ] [--will-qos []] [--will-retain []] [--enable-websocket []] [--enable-quic []] [--enable-ssl []] [--tls-version []] [--CAfile ] [--cert ] [--key ] [--retain-as-publish []] [--retain-handling []] [--print [size]] ``` -------------------------------- ### emqtt:ws_connect/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Establishes a connection to the MQTT server over Websocket. ```APIDOC ## emqtt:ws_connect(Client) ### Description Connects to the MQTT server over Websocket and sends a CONNECT packet. ### Parameters - **Client** (client()) - Required - The client pid or name returned from start_link/1, 2. ### Response - **{ok, Properties}** - Connection established successfully. - **{error, Reason}** - Connection failed. ``` -------------------------------- ### Retrieve client info Source: https://github.com/emqx/emqtt/blob/master/_autodocs/api-reference/emqtt.md Returns general information about the client as a map. ```erlang -spec info(client()) -> map(). ``` ```erlang Info = emqtt:info(Client). ``` -------------------------------- ### emqtt:resume/1 Source: https://github.com/emqx/emqtt/blob/master/README.md Resumes a client process from a paused state. ```APIDOC ## emqtt:resume(Client) ### Description Resume a client process from a paused state. ### Parameters - **Client** (client()) - Required - The client process to resume. ```