Get Started

After installing it, run mqttx on the terminal.

Quick Start

Connect

mqttx conn -h 'broker.emqx.io' -p 1883 -u 'admin' -P 'public'

Subscribe

mqttx sub -t 'hello' -h 'broker.emqx.io' -p 1883

Publish

# Publish a single message
mqttx pub -t 'hello' -h 'broker.emqx.io' -p 1883 -m 'from MQTTX CLI'

# Publish multiple messages (multiline)
mqttx pub -t 'hello' -h 'broker.emqx.io' -p 1883 -s -M

Benchmark

# Connect Benchmark
mqttx bench conn -c 5000

# Subscribe Benchmark
mqttx bench sub -c 5000 -t bench/%i

# Publish Benchmark
mqttx bench pub -c 5000 -t bench/%i

Simulate

# Specify a local built-in scenario and start the simulation
mqttx simulate -sc tesla -c 10

# Specify a scenario file and start the simulation
mqttx simulate -f <scenario file path> -c 10

# List the built-in scenarios
mqttx ls -sc

Version Check

mqttx check

Basic Usage

mqttx --help
OptionsDescription
-v, --versionOutput the version number
-h, --helpDisplay help for command
CommandDescription
checkCheck for updates
initInitialize the configuration file
connCreate a connection and connect to MQTT Broker
pubPublish a message to a topic
subSubscribes to one or multiple topics
benchMQTT Benchmark in performance testing
simulateSimulate publishing scenario-specific MQTT messages

Connection

mqttx conn --help
OptionsDescription
-V, --mqtt-version <5/3.1.1/3.1>the MQTT version (default: 5)
-h, --hostname <HOST>the broker host (default: "localhost")
-p, --port <PORT>the broker port
-i, --client-id <ID>the client id
--no-cleanset the clean session flag to false (default: true)
-k, --keepalive <SEC>send a ping every SEC seconds (default: 30)
-u, --username <USER>the username
-P, --password <PASS>the password
-l, --protocol <PROTO>the protocol to use, mqtt, mqtts, ws, or wss (default: mqtt)
--path <PATH>the path of websocket (default: /mqtt)
--key <PATH>path to the key file
--cert <PATH>path to the cert file
--ca <PATH>path to the ca certificate
--insecuredo not verify the server certificate
--alpn <PROTO...>set one or multiple ALPN (Application Layer Protocol Negotiation) protocols
-rp, --reconnect-period <MILLISECONDS>interval between two reconnections, disable auto reconnect by setting to 0 (default: 1000ms)
--maximum-reconnect-times <NUMBER>the maximum reconnect times (default: 10)
-up, --user-properties <USERPROPERTIES...>the user properties of MQTT 5.0 (e.g. -up "name: mqttx cli")
-Wt, --will-topic <TOPIC>the will topic
-Wm, --will-message <BODY>the will message
-Wq, --will-qos <0/1/2>the will qos
-Wr, --will-retainsend a will retained message (default: false)
-Wd, --will-delay-interval <SECONDS>the will delay interval in seconds
-Wpf, --will-payload-format-indicatorwill message is UTF-8 encoded character data or not
-We, --will-message-expiry-interval <SECONDS>lifetime of the will message in seconds
-Wct, --will-content-type <CONTENTTYPE>description of the will message’s content
-Wrt, --will-response-topic <TOPIC>topic name for a response message
-Wcd, --will-correlation-data <DATA>correlation data for the response message
-Wup, --will-user-properties <USERPROPERTIES...>the user properties of will message
-se, --session-expiry-interval <SECONDS>the session expiry interval in seconds
--rcv-max, --receive-maximum <NUMBER>the receive maximum value
--maximum-packet-size <NUMBER>the maximum packet size the client is willing to accept
--topic-alias-maximum <NUMBER>the topic alias maximum value
--req-response-infothe client requests response information from the server
--no-req-problem-infothe client requests problem information from the server
-so, --save-options [PATH]save the parameters to the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
-lo, --load-options [PATH]load the parameters from the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
--debugenable debug mode for MQTT.js (default: false)
--helpdisplay help for conn command

Subscribe

mqttx sub --help
OptionsDescription
-V, --mqtt-version <5/3.1.1/3.1>the MQTT version (default: 5)
-h, --hostname <HOST>the broker host (default: "localhost")
-p, --port <PORT>the broker port
-i, --client-id <ID>the client id
-q, --qos <0/1/2>the QoS of the message (default: 0)
--no-cleanset the clean session flag to false (default: true)
-t, --topic <TOPIC>the message topic
-k, --keepalive <SEC>send a ping every SEC seconds (default: 30)
-u, --username <USER>the username
-P, --password <PASS>the password
-l, --protocol <PROTO>the protocol to use, mqtt, mqtts, ws, or wss (default: mqtt)
--path <PATH>the path of websocket (default: /mqtt)
-nl, --no_localthe no local MQTT 5.0 flag
-rap, --retain-as-publishedthe retain as published MQTT 5.0 flag
-rh, --retain-handling <0/1/2>the retain handling MQTT 5.0
--key <PATH>path to the key file
--cert <PATH>path to the cert file
--capath to the ca certificate
--insecuredo not verify the server certificate
--alpn <PROTO...>set one or multiple ALPN (Application Layer Protocol Negotiation) protocols
-rp, --reconnect-period <MILLISECONDS>interval between two reconnections, disable auto reconnect by setting to 0 (default: 1000ms)
--maximum-reconnect-times <NUMBER>the maximum reconnect times (default: 10)
-up, --user-properties <USERPROPERTIES...>the user properties of MQTT 5.0 (e.g. -up "name: mqttx cli")
-f, --format <TYPE>format the message body, support base64, json, hex, binary and cbor
-v, --verboseturn on verbose mode to display incoming MQTT packets
--output-mode <default/clean>choose between the default and clean mode, which outputs the complete MQTT packet data, allowing users to pipe the output as they wish
--file-save <PATH>Save the received message as a file
--file-write <PATH>continuously write the received message into a specified file
--delimiter [CHARACTER]append a delimiter to the end of each message, default is "\n"
-Wt, --will-topic <TOPIC>the will topic
-Wm, --will-message <BODY>the will message
-Wq, --will-qos <0/1/2>the will qos
-Wr, --will-retainsend a will retained message (default: false)
-Wd, --will-delay-interval <SECONDS>the will delay interval in seconds
-Wpf, --will-payload-format-indicatorwill message is UTF-8 encoded character data or not
-We, --will-message-expiry-interval <SECONDS>lifetime of the will message in seconds
-Wct, --will-content-type <CONTENTTYPE>description of the will message’s content
-Wrt, --will-response-topic <TOPIC>topic name for a response message
-Wcd, --will-correlation-data <DATA>correlation data for the response message
-Wup, --will-user-properties <USERPROPERTIES...>the user properties of will message
-se, --session-expiry-interval <SECONDS>the session expiry interval in seconds
-si, --subscription-identifier <NUMBER>the identifier of the subscription
--rcv-max, --receive-maximum <NUMBER>the receive maximum value
--maximum-packet-size <NUMBER>the maximum packet size the client is willing to accept
--topic-alias-maximum <NUMBER>the topic alias maximum value
--req-response-infothe client requests response information from the server
--no-req-problem-infothe client requests problem information from the server
-Cup, --conn-user-properties <USERPROPERTIES...>the connect user properties of MQTT 5.0 (e.g. -Cup "name: mqttx cli")
-so, --save-options [PATH]save the parameters to the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
-lo, --load-options [PATH]load the parameters from the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
--helpdisplay help for sub command
-Pp, --protobuf-path <PATH>the path to the .proto file that defines the message format for Protocol Buffers (protobuf)
-Pmn, --protobuf-message-name <NAME>the name of the protobuf message type (must exist in the .proto file)
--debugenable debug mode for MQTT.js (default: false)

Note: If you are subscribing to topics with a $ prefix, such as shared subscriptions like $share/test/test, you need to add quotes around "$share/test/test". $share in shell would be recognized as a variable, leading to a failure in subscription.

Publish

mqttx pub --help
OptionsDescription
-V, --mqtt-version <5/3.1.1/3.1>the MQTT version (default: 5)
-h, --hostname <HOST>the broker host (default: "localhost")
-p, --port <PORT>the broker port
-i, --client-id <ID>the client id
-q, --qos <0/1/2>the QoS of the message (default: 0)
-t, --topic <TOPIC>the message topic
-m, --message<MSG>the message body (default: "Hello From MQTTX CLI")
-r, --retainsend a retained message (default: false)
-s, --stdinread the message body from stdin
-M, --multilineread lines from stdin as multiple messages
--file-read <PATH>read the message body from a file
-u, --username <USER>the username
-P, --password <PASS>the password
-f, --format <TYPE>the format type of the input message, support base64, json, hex, bianry and cbor
-l, --protocol <PROTO>the protocol to use, mqtt, mqtts, ws, or wss (default: mqtt)
--path <PATH>the path of websocket (default: /mqtt)
--key <PATH>path to the key file
--cert <PATH>path to the cert file
--capath to the ca certificate
--insecuredo not verify the server certificate
--alpn <PROTO...>set one or multiple ALPN (Application Layer Protocol Negotiation) protocols
-rp, --reconnect-period <MILLISECONDS>interval between two reconnections, disable auto reconnect by setting to 0 (default: 1000ms)
--maximum-reconnect-times <NUMBER>the maximum reconnect times (default: 10)
-up, --user-properties <USERPROPERTIES...>the user properties of MQTT 5.0 (e.g. -up "name: mqttx cli")
-pf, --payload-format-indicatorthe payload format indicator of the publish message
-e, --message-expiry-interval <NUMBER>the lifetime of the publish message in seconds
-ta, --topic-alias <NUMBER>value that is used to identify the topic instead of using the topic name
-rt, --response-topic <TOPIC>string which is used as the topic name for a response message
-cd, --correlation-data <DATA>used by the sender of the request message to identify which request the response message is for when it is received
-si, --subscription-identifier <NUMBER>the identifier of the subscription
-ct, --content-type <TYPE>a description of the content of the publish message
-Wt, --will-topic <TOPIC>the will topic
-Wm, --will-message <BODY>the will message
-Wq, --will-qos <0/1/2>the will qos
-Wr, --will-retainsend a will retained message (default: false)
-Wd, --will-delay-interval <SECONDS>the will delay interval in seconds
-Wpf, --will-payload-format-indicatorwill message is UTF-8 encoded character data or not
-We, --will-message-expiry-interval <SECONDS>lifetime of the will message in seconds
-Wct, --will-content-type <CONTENTTYPE>description of the will message’s content
-Wrt, --will-response-topic <TOPIC>topic name for a response message
-Wcd, --will-correlation-data <DATA>correlation data for the response message
-Wup, --will-user-properties <USERPROPERTIES...>the user properties of will message
-se, --session-expiry-interval <SECONDS>the session expiry interval in seconds
--rcv-max, --receive-maximum <NUMBER>the receive maximum value
--maximum-packet-size <NUMBER>the maximum packet size the client is willing to accept
--topic-alias-maximum <NUMBER>the topic alias maximum value
--req-response-infothe client requests response information from the server
--no-req-problem-infothe client requests problem information from the server
-Cup, --conn-user-properties <USERPROPERTIES...>the connect user properties of MQTT 5.0 (e.g. -Cup "name: mqttx cli")
-so, --save-options [PATH]save the parameters to the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
-lo, --load-options [PATH]load the parameters from the local configuration file, which supports json and yaml format, default path is ./mqttx-cli-options.json
--helpdisplay help for pub command
-Pp, --protobuf-path <PATH>the path to the .proto file that defines the message format for Protocol Buffers (protobuf)
-Pmn, --protobuf-message-name <NAME>the name of the protobuf message type (must exist in the .proto file)
--debugenable debug mode for MQTT.js (default: false)

Configuration File

The configuration file stores the default values of various settings, providing a simplified and customizable experience for MQTTX CLI. After initialization, it will be stored in the user's home directory, with the path $HOME/.mqttx-cli/config.

Features

default:

  • output
    • text: Default mode, provides concise output with key information.
    • log: Displays detailed log output with date and time stamps.

mqtt:

  • host: Default is localhost.
  • port: Default is 1883.
  • max_reconnect_times: Default is 10.
  • username: Default is empty.
  • password: Default is empty.

The output setting in the default section controls the CLI output display. Users can choose different modes according to their needs. If you want to integrate with some logging scripts, the log mode is recommended.

In the mqtt section, if the command line does not provide these parameters, the configuration items from the configuration file will be used.

max_reconnect_times controls the number of reconnection attempts. Once this set number is reached, the connection will automatically close to prevent infinite reconnections. Note: This is an MQTTX configuration and not a part of the MQTT protocol.

If configuration items like username and password are not requried, they can be omitted from the configuration file.

Initializing Configuration

The configuration file is not provided by default. To create or update the configuration file, run the init command. This will prompt you to enter the desired values:

mqttx init
? Select MQTTX CLI output mode Text
? Enter the default MQTT broker host broker.emqx.io
? Enter the default MQTT port 1883
? Enter the maximum reconnect times for MQTT connection 5
? Enter the default username for MQTT connection authentication admin
? Enter the default password for MQTT connection authentication ******
Configuration file created/updated at /Users/.mqttx-cli/config

Example Configuration File

[default]
output = text

[mqtt]
host = broker.emqx.io
port = 1883
max_reconnect_times = 5
username = admin
password = public

Example CLI Output

  1. log
    mqttx conn
    [5/24/2024] [11:26:17 AM] › …  Connecting...
    [5/24/2024] [11:26:17 AM] › ✔  Connected
    
  2. text
    mqttx conn
    ✔ Connected
    

Benchmark

The bench command is used to test the performance of the broker. It has basically the same as the normal command options, the following will only list the new or changed options.

Connect Benchmark

mqttx bench conn --help
OptionsDescription
-c, --count <NUMBER>the number of connections (default: 1000)
-i, --interval <MILLISECONDS>interval of connecting to the broker (default: 10ms)
-I, --client-id <ID>the client id, support %i (index) variable

Subscribe Benchmark

mqttx bench sub --help
OptionsDescription
-c, --count <NUMBER>the number of connections (default: 1000)
-i, --interval <MILLISECONDS>interval of connecting to the broker (default: 10ms)
-I, --client-id <ID>the client id, support %i (index) variable
-t, --topic <TOPIC...>the message topic, support %u (username), %c (client id), %i (index) variables
-v, --verboseprint history received messages and rate

Publish Benchmark

mqttx bench pub --help
OptionsDescription
-c, --count <NUMBER>the number of connections (default: 1000)
-i, --interval <MILLISECONDS>interval of connecting to the broker (default: 10ms)
-im, --interval-message <MILLISECONDS>interval of publishing message to the broker (default: 1000ms)
-L, --limit <NUMBER>the number of messages to publish, 0 means unlimited (default: 0)
-I, --client-id <ID>the client id, support %i (index) variable
-t, --topic <TOPIC...>the message topic, support %u (username), %c (client id), %i (index) variables
-v, --verboseprint history received messages and rate
--file-read <PATH>read the message body from the file
--split [CHARACTER]split the input message in a single file by a specified character, default is "\n"
-s, --stdinread the message body from stdin
-M, --multilineread lines from stdin as multiple messages

Typical stress test scenario

Connection test

Create 10000 connections at a rate of one connection every 10ms, with client ID mqttx-bench-%i:

mqttx bench conn -c 10000 -i 10 -I "mqttx-bench-%i"

If you are using EMQX, you can check the number of connections in EMQX after all connections have been established via EMQX Dashboard or by running ./bin/emqx_ctl listeners to see the information about the number of connections in EMQX.

tcp:default
  listen_on       : :1883
  acceptors       : 16
  proxy_protocol  : false
  running         : true
  current_conn    : 10000
  max_conns       : 1024000

Throughput test

Start 500 clients, subscribe to topic mqttx/bench/t:

mqttx bench sub -c 500 -t mqttx/bench/t

Then start 20 publishers, publishing messages to the topic mqttx/bench/t at a rate of 10 messages per second with the message mqttx bench test:

mqttx bench pub -c 20 -im 100 -t mqttx/bench/t -m "mqttx bench test"

Then, go back to the subscribing client, you can see the total number of messages received and the real-time message rate:

Received total: 10989500, rate: 100000/s

Simulate

For simulating MQTT publish message in specific scenarios.

It has basically the same as the Publish Benchmark command options, the following will only list the new or changed options.

mqttx simulate --help
OptionsDescription
-sc, --scenario <SCENARIO>the name of the built-in scenario to simulate
-f, --file <SCENARIO FILE PATH>file path of a local custom scenario script
-t, --topic <TOPIC... >the message topic, optional, supports variables such as %u (username), %c (client id), %i (index), %sc (scenario). Default topic format is mqttx/simulate/%sc/%c

One of the --scenario and --file parameters must be specified, and if both are specified, the --file parameter is preferred.

Custom IoT Data Script

Example:

Note: The simulation file must use the CommonJS specification.

/**
 * MQTTX Scenario file example
 *
 * This script generates random temperature and humidity data.
 */
function generator(faker, options) {
  return {
    // If no topic is returned, use the topic in the command line parameters.
    // Topic format: 'mqttx/simulate/myScenario/' + clientId,
    message: JSON.stringify({
      temp: faker.number.int({ min: 20, max: 80 }), // Generate a random temperature between 20 and 80.
      hum: faker.number.int({ min: 40, max: 90 }), // Generate a random humidity between 40 and 90.
    })
  }
}
// Export the scenario module
module.exports = {
  name: 'myScenario', // Name of the scenario
  generator, // Generator function
}

Assuming we save the above JavaScript code as a tempAndHum.js file, we can then use the following command to simulate the generation of 10 MQTT messages:

mqttx simulate --file ./tempAndHum.js -c 10

For more examples and detailed editing guides, please refer to the scripts-example in the MQTTX GitHub repository, or see how to use faker.js to generate various types of random data.

Note: From v1.9.10 onwards, simulation scripts require faker.js v8 or above. If using older versions, update your code with the faker.js upgrade guide for compatibility.

Built-in Scenarios

MQTTX CLI has built-in some common scenarios, which can be specified by the --scenario parameter, for example:

mqttx simulate --scenario tesla

You can use the ls command to list all the built-in scenarios:

mqttx ls --scenarios

This command will output a table that shows the name and description of each built-in scenario. If you want to use one of them in the simulate command, simply specify the scenario name in the --scenario option:

mqttx simulate --scenario <SCENARIO_NAME>

List of built-in scenarios:

Scenario NameDescription
teslaSimulate Tesla vehicle data
IEMSimulation to generate Industrial Energy Monitoring data
smart_homeSimulation to generate Smart Home data
weatherSimulation to generate advanced weather station's data.

List

The list command provides an overview of available resources.

Currently, it supports listing built-in scenarios.

mqttx list --help
OptionsDescription
-sc, --scenarioslist the built-in scenarios

Options Management

Note: This feature was previously called "Configuration." As of v1.10.0, it has been renamed to "Options Management." The previous --config and --save commands have been updated to --load-options and --save-options.

MQTTX CLI supports importing and exporting options, allowing users to save command parameters to a local options file for future use. The options file supports json and yaml formats, with the default path being ./mqttx-cli-options.json.

The parameters for the conn, pub, sub, benchmark, and simulate commands can all be saved and loaded. Below are examples for exporting and importing options for the conn command:

Export Options

# Save to default path
mqttx conn --save-options

# Save to a specified path
mqttx conn --save-options ../custom/mqttx-cli-options.json

# Save to a specified path and specify the format as yaml
mqttx conn --save-options ../custom/mqttx-cli-options.yaml

Import Options

# Import options from the default path
mqttx conn --load-options

# Import options from a specified path
mqttx conn --load-options ../custom/mqttx-cli-options.json

# Import options from a specified path and specify the format as yaml
mqttx conn --load-options ../custom/mqttx-cli-options.yaml

Data Pipeline

MQTTX CLI provides a simple way to manage and pipeline MQTT data. Its clean mode and jq eliminate the need for complex coding to process MQTT data.

For example, to subscribe and extract an MQTT packet's payload or restructure data:

mqttx sub -t topic --output-mode clean | jq '.payload'

mqttx sub -t topic --output-mode clean | jq '{topic, payload, retain: .packet.retain, userProperties: .packet.properties.userProperties}'

This example shows how to leverage the functionality of MQTTX CLI, jq and other tools to quickly and efficiently build pipelines for acquiring and processing IoT data.

File Read and Write

MQTTX CLI offers file read and write capabilities to seamlessly handle message payloads as file inputs and outputs over MQTT, enhancing the ease of integration and automation in data workflows.

File Reading

Use the following command to read a message from a file:

mqttx pub -t topic --file-read path/to/file

Note: Files must not exceed 256MB due to MQTT protocol constraints. Verify the payload size limit of your MQTT Broker before transmitting.

File Writing

To write incoming messages to a file, use:

mqttx sub -t topic --file-write path/to/file

The --file-write option appends each message to a file, separated by a newline character (\n) by default, making it ideal for logging or accumulating text data. If you wish to change the delimiter, you can use the --delimiter option. For example, --delimiter ',' will separate each message with a comma.

For file transfer and to save messages as separate files, use:

mqttx sub -t topic --file-save path/to/file

Existing files will be automatically renumbered and saved to prevent overwrites.

Do not use --file-write and --file-save together.

Type Format

You can specify the file format for sending or saving; if not specified, it defaults to plaintext (utf-8) format.

mqttx pub -t topic --file-read path/to/file --format type

mqttx sub -t topic --file-save path/to/file --format type

Currently, we support the following data formats for output to file:

  • json
  • base64
  • hex
  • binary
  • cbor

When a user transfers a file with an extension in the following formats without specifying the --format parameter, it will automatically recognize the file format as binary. If the transferred file is not in the following formats and needs to be transmitted in binary format, you must manually specify the --format binary parameter.

ExtensionFile FormatDescription
.png, .jpg, .jpeg, .gif, .bmp, .ico, .tif, .tiffImageCommon image file formats for pictures and graphics.
.mp4, .avi, .mov, .mkv, .flv, .wmv, .mpeg, .3gpVideoStandard video file formats for movies and clips.
.mp3, .wav, .flac, .aac, .ogg, .wma, .m4a, .m4pAudioAudio file formats for music and sound recordings.
.zip, .gz, .rar, .tar, .7z, .bz2, .xz, .jarCompressedCompressed file formats for archive and data compression.
.bin, .exe, .dll, .so, .dmg, .iso, .imgBinaryBinary file formats for executables, system libraries, and disk images.
.pdf, .epubDocumentBinary formats for documents and ebooks.

Check for Update

The check command is used to check for the latest version of MQTTX CLI. This command will notify if a new version is available and provide a link to download the latest version.

Usage

Run the following command to check for updates:

mqttx check

Example Output

If a new version is available, the following message will be displayed:

A new version of MQTTX CLI is available: 1.9.8 → 1.9.10
https://github.com/emqx/MQTTX/releases/tag/v1.9.10

Download the latest version from the MQTTX Downloads page or the GitHub releases page. After downloading, replace the current version to stay up to date.