MQTT FTW

This blog post isn't really a proper post, more of a way in which I can remember how to use MQTT for future projects.
Feel free to refer to this and of course comment :)


What is MQTT?

MQTT: Message Queuing Telemetry Transport.
A lightweight machine to machine protocol for IoT devices.

alt

How can I install it on Linux / Raspberry Pi?

In a terminal

sudo apt update  
sudo apt install mosquitto mosquitto-clients  

To test

Run the mosquitto background service broker

sudo service mosquitto start  

Subscribe to a topic

One one computer which will react to a message (this was my Pocket Chip SBC)

alt

-d = debug, verbose mode

-t = topic, the subject that we are listening to, almost like a channel

mosquitto_sub -d -t hello/world  

Publish a message on the set topic On another computer, this was my laptop.
-d = debug, verbose mode

-t = topic, the subject that we are sending a message to, almost like a channel

-m = message, the message that we wish to send

-h = IP, the IP address to send a message to

mosquitto_pub -d -t hello/world -m "Is this thing on?"  

So what happens?

The laptop publishing a message on the hello/world topic will send its message that will be picked up by every device that is subscribing / listening to that topic.

To install MQTT for Python 3

sudo pip3 install paho-mqtt  

An example Python script that will listen and can post to topic.

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):  
        print("Connected with result code "+str(rc))
        client.subscribe("hello/world")

def on_message(client, userdata, msg):  
        message = str(msg.payload)
        message = message[2:(len(message))]
        print(message)
        if(message=="test"):
                print("I'm working!")

client = mqtt.Client()  
client.on_connect = on_connect  
client.on_message = on_message  
#connects to a certain IP address
client.connect("192.168.1.191", 1883, 60)

client.publish("hello/world","test")

client.loop_forever()