Message Queuing Telemetry Transport Protocol

Network Protocol

A network protocol is a standardized set of rules procedures and conventions that govern how data is formatted transmitted and received between devices on a network These protocols ensure that devices regardless of their manufacturer operating system or hardware can communicate reliably and efficiently enabling the seamless exchange of information across networks.

Network protocols define several critical aspects of communication including how devices initiate and terminate connections how data is packaged into packets how errors are detected and corrected and how devices address each other to ensure messages reach the correct destination They also determine how devices respond in case of congestion interruptions or conflicting requests.

Examples of widely used network protocols include TCP/IP which underlies the internet and governs how data travels between computers HTTP/HTTPS which enables web communication FTP used for file transfers and SMTP which manages email transmission By following these standardized rules devices can understand each other interpret data correctly and maintain reliable and secure communication even across diverse networks or geographical locations.

Network protocols are the foundation of all digital communication ensuring that information flows smoothly accurately and securely between devices in both small local networks and vast global networks like the internet.


Message Queuing Telemetry Transport (MQTT)

MQTT is a publish-and-subscribe communication protocol designed for IoT devices, enabling them to communicate effectively in high-latency and low-bandwidth environments.

  • For Windows, use the MQTT installer
  • For Linux-bases or Mac OS, use brew install mosquitto
  • Go to terminal or command line and type mosquitto -v

Light switch & Mobile App MQTT Example

In a smart home, a light switch is equipped with the capability to send information to a home mobile app.

  • MQTT Broker: The MQTT broker serves as a central server that receives messages and distributes them to all clients subscribed to specific topics.
    • mosquitto -v
  • MQTT Subscriber: The home app acts as an MQTT subscriber. It subscribes to the topic smarthome/lights/office. When the smart light switch publishes an update, the home app receives the message and updates the light’s status accordingly
    • mosquitto_sub -t 'smarthome/lights/office'
  • MQTT Publisher: The smart light switch functions as an MQTT publisher. When you turn the light on or off, the switch sends a message to a specific topic on the MQTT broker, such as smarthome/lights/office.
    • mosquitto_pub -t 'smarthome/lights/office' -m 'ON'

Open 3 terminal windows or tabs and paste the following

Demo (Tab 1)

(RPi) mosquitto -v
1757318742: mosquitto version 2.0.22 starting
1757318742: Using default config.
1757318742: Starting in local only mode. Connections will only be possible from clients running on this machine.
1757318742: Create a configuration file which defines a listener to allow remote access.
1757318742: For more details see https://mosquitto.org/documentation/authentication-methods/
1757318742: Opening ipv4 listen socket on port 1883.
1757318742: Opening ipv6 listen socket on port 1883.
1757318742: mosquitto version 2.0.22 running

Demo (Tab 2)

(RPi) mosquitto_sub -t 'smarthome/lights/office'
ON

Demo (Tab 3)

(RPi) mosquitto_pub -t 'smarthome/lights/office' -m 'Hello, MQTT!'

You can also do the same thing using Python

Demo (Tab 1)

(RPi) mosquitto -v
1757318742: mosquitto version 2.0.22 starting
1757318742: Using default config.
1757318742: Starting in local only mode. Connections will only be possible from clients running on this machine.
1757318742: Create a configuration file which defines a listener to allow remote access.
1757318742: For more details see https://mosquitto.org/documentation/authentication-methods/
1757318742: Opening ipv4 listen socket on port 1883.
1757318742: Opening ipv6 listen socket on port 1883.
1757318742: mosquitto version 2.0.22 running

MQTT in Python

You can create an MQTT server in Python. In MQTT terminology, you can create an MQTT server in Python. In MQTT terminology, the server is called a broker, which receives messages from publishers and distributes them to subscribers. Python can be used either to run an MQTT broker (server) or to create MQTT clients, which are devices or programs that publish messages to topics or subscribe to topics to receive messages.

listener.py (Listens to one topic)

import paho.mqtt.client as mqtt_client # Import the Paho MQTT client library
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id=”client_1″) # Create MQTT client with API version 2 and client ID

def on_connect(client, userdata, flags, rc, properties): # Callback function triggered when the client connects to the broker
    print(f”Connected: reason_code={rc}”) # Print the connection result code

def on_message(client, userdata, msg): # Callback function triggered when a subscribed message is received
    print(f”{msg.topic}: {msg.payload.decode()}”) # Print the topic and decoded message payload

def on_disconnect(client, userdata, rc): # Callback function triggered when the client disconnects
    print(f”Disconnected: reason_code={rc}”) # Print the disconnection reason code

client.on_connect = on_connect # Assign the connection callback function
client.on_message = on_message # Assign the message callback function

if client.connect(“localhost”, 1883, 60) == 0: # Connect to the MQTT broker on localhost using port 1883 with 60s keepalive
    try:
        client.subscribe(“smarthome/lights/office”, qos=1) # Subscribe to the topic with Quality of Service level 1
        client.loop_forever() # Start the network loop and listen for messages continuously
    except Exception: # Catch any runtime errors
        print(“Error”) # Print error message if an exception occurs
    finally:
        client.disconnect() # Disconnect from the broker when the program exits

import paho.mqtt.client as mqtt_client

client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id="client_1")

def on_connect(client, userdata, flags, rc, properties):
    print(f"Connected: reason_code={rc}")
 
def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

def on_disconnect(client, userdata, rc):
    print(f"Disconnected: reason_code={rc}")

client.on_connect = on_connect
client.on_message = on_message

if client.connect("localhost", 1883, 60) == 0:
    try:
      client.subscribe("smarthome/lights/office", qos=1)
        client.loop_forever()
    except Exception:
        print("Error")
    finally:
        client.disconnect()

client.py (Publish to a topic)

import paho.mqtt.client as mqtt_client # Import the Paho MQTT client library

client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2) # Create an MQTT client using callback API version 2

def on_connect(client, userdata, flags, rc, properties): # Function called when the client connects to the broker
    print(f”Connected: reason_code={rc}”) # Print the connection result code

def on_disconnect(client, userdata, rc): # Function called when the client disconnects from the broker
    print(f”Disconnected: reason_code={rc}”) # Print the disconnection reason code

client.on_connect = on_connect # Assign the connect callback function to the client

if client.connect(“localhost”, 1883, 60) == 0: # Connect to the MQTT broker running on localhost using port 1883
    try:
        client.publish(“smarthome/lights/office”, “ON”, 0) # Publish the message “ON” to the topic with QoS level 0
    except Exception as e: # Catch any exceptions that occur during publishing
        print(e) # Print the error message
    finally:
        client.disconnect() # Disconnect from the MQTT broker

import paho.mqtt.client as mqtt_client

client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2)

def on_connect(client, userdata, flags, rc, properties):
    print(f"Connected: reason_code={rc}")

def on_disconnect(client, userdata, rc):
    print(f"Disconnected: reason_code={rc}")

client.on_connect = on_connect

if client.connect("localhost", 1883, 60) == 0:
    try:
      client.publish("smarthome/lights/office", "ON", 0)
    except Exception as e:
        print(e)
    finally:
        client.disconnect()

Output

Connected: reason_code=Success
smarthome/lights/office: ON