MQTT with Mosquitto

Using Mosquitto as a Message Broker

Updated: 03 September 2023

MQTT makes use of a publish/subscribe model in which a client will either publish messages to a topic or subscribe to messages on the topic

Help

We can run the following to get the mosquitto help menus

General

Terminal window
1
> mosquitto --help
2
3
mosquitto version 1.5.4
4
5
mosquitto is an MQTT v3.1.1 broker.
6
7
Usage: mosquitto [-c config_file] [-d] [-h] [-p port]
8
9
-c : specify the broker config file.
10
-d : put the broker into the background after starting.
11
-h : display this help.
12
-p : start the broker listening on the specified port.
13
Not recommended in conjunction with the -c option.
14
-v : verbose mode - enable all logging types. This overrides
15
any logging options given in the config file.
16
17
See http://mosquitto.org/ for more information.

Publisher

Terminal window
1
> mosquitto_pub --help
2
3
mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.
4
mosquitto_pub version 1.5.4 running on libmosquitto 1.5.4.
5
6
Usage: mosquitto_pub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL}
7
{-f file | -l | -n | -m message}
8
[-c] [-k keepalive] [-q qos] [-r]
9
[-A bind_address]
10
[-i id] [-I id_prefix]
11
[-d] [--quiet]
12
[-M max_inflight]
13
[-u username [-P password]]
14
[--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
15
[{--cafile file | --capath dir} [--cert file] [--key file]
16
[--ciphers ciphers] [--insecure]]
17
[--psk hex-key --psk-identity identity [--ciphers ciphers]]
18
[--proxy socks-url]
19
mosquitto_pub --help
20
21
...

Subscriber

Terminal window
1
> mosquitto_sub --help
2
3
mosquitto_sub is a simple mqtt client that will subscribe to a set of topics and print all messages it receives.
4
mosquitto_sub version 1.5.4 running on libmosquitto 1.5.4.
5
6
Usage: mosquitto_sub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL [-t topic]}
7
[-c] [-k keepalive] [-q qos]
8
[-C msg_count] [-R] [--retained-only] [-T filter_out] [-U topic ...]
9
[-F format]
10
[-A bind_address]
11
[-i id] [-I id_prefix]
12
[-d] [-N] [--quiet] [-v]
13
[--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
14
[{--cafile file | --capath dir} [--cert file] [--key file]
15
[--ciphers ciphers] [--insecure]]
16
[--psk hex-key --psk-identity identity [--ciphers ciphers]]
17
[--proxy socks-url]
18
mosquitto_sub --help
19
20
...

Starting a Server

We can start an MQTT Broker Server with mosquitto in verbose mode as follows

Terminal window
1
mosquitto -v

This will allow us to publish and subscribe message

Subscribe to a Topic

We can subscribe to a topic with the following

Terminal window
1
mosquitto_sub -t "hello" -v

Publish to a Topic

We can publish messages to a topic with the following

Terminal window
1
mosquitto_pub -t "hello" -m "Hello World!"