Installing MQTT Broker(Mosquitto) on Raspberry Pi

--Resource --
--Resource --
--Resource --

MQTT (MQ Telemetry Transport)

MQTT is a lightweight, publish-subscribe network protocol that transports messages between devices. The protocol usually runs over TCP/IP, however, any network protocol that provides ordered, lossless, bi-directional connections can support MQTT.

An MQTT broker is an intermediary entity that enables MQTT clients to communicate. Specifically, an MQTT broker receives messages published by clients, filters the messages by topic, and distributes them to subscribers.

0.Remove


sudo apt remove mosquitto
sudo apt remove mosquitto-clients

1.Install


apt-get install mosquitto
apt-get install mosquitto-clients

2.0 Use (without authentication)


192.168.1.4 (IP of Raspberry Pi)

Open a Terminal and type it...
mosquitto_sub -h 192.168.1.4 -t sample_topic_name

Open another Terminal and type it...
mosquitto_pub -h 192.168.1.4 -t sample_topic_name -m "Hi this is test message"

2.2 Setup Authentication


sudo mosquitto_passwd -c /etc/mosquitto/passwd your_username

2.2 Use (with authentication)


192.168.1.4 (IP of Raspberry Pi)

Open a Terminal and type it...
mosquitto_sub -t "topic" -u "your_username" -P "your_password"

Open another Terminal and type it...
mosquitto_pub -t "topic" -m "message from mosquitto_pub client" -u "your_username" -P "your_password"

3.Usefull commands


sudo systemctl status mosquitto
sudo systemctl start mosquitto
sudo systemctl restart mosquitto
sudo systemctl stop mosquitto

4.Configuration file


sudo nano /etc/mosquitto/mosquitto.conf

4.1.Configuration file Content


    ##### CONFIGURATIOS (AUTHENTICATION NOT NEEDED) ######

    listener 1883
    pid_file /var/run/mosquitto.pid
    
    persistence true
    persistence_location /var/lib/mosquitto/
    
    log_dest file /var/log/mosquitto/mosquitto.log
    
    include_dir /etc/mosquitto/conf.d
    
    allow_anonymous true
    
    ................................................................................................
    
    ##### CONFIGURATIOS (NEED AUTHENTICATE) ######
    
    listener 1883
    #pid_file /var/run/mosquitto.pid
    
    persistence true
    persistence_location /var/lib/mosquitto/
    
    log_dest file /var/log/mosquitto/mosquitto.log
    
    include_dir /etc/mosquitto/conf.d
    allow_anonymous false
    password_file /etc/mosquitto/passwd