LinkIt Smart 7688 Duo: Subscribing to MQTT topic

The objective of this post is to explain how to connect to a MQTT broker and subscribing to a topic, using the LinkIt Smart Duo.


Introduction

The objective of this post is to explain how to connect to a MQTT broker and subscribing to a topic, using the LinkIt Smart Duo. This will be done on OpenWRT, the board’s Operating System.

The MQTT broker used will be CloudMQTT. You will need to register (there’s a free plan available) and create a broker instance. You will also need the credentials from the broker instance information page: address, port, user and password.

We will use Python and the paho-mqtt library, which we used before in previous posts. Please note that the actual Python coding will be the same of the mentioned post, so we will not cover everything in detail. You can check the functions in more detail in that Python post.

So, the first thing we need to do is to install the MQTT library on the LinkIt Smart. To do so, connect to the LinkIt Smart using Putty and run the following pip command:

pip install paho-mqtt

Check figure 1 for a descriptive image on how to do it.

LinkIt Smart install paho-mqtt

Figure 1 – Install paho-mqtt on the LinkIt Smart Duo.

Note that it may take a while until the installation starts.


The coding

As usual, we will be using WinSCP to upload the Python file with the code. So, as shown in figure 2, just connect to the LinkIt Smart using WinSCP and create a Python file. In this case, I called it MQTTsubscribe.py. Check here how to use WinSCP to upload files to the LinkIt Smart.

LinkIt Smart WinSCP MQTT file creation

Figure 2 – Creating the Python file.

Now, to create the script, double click on the file and the editor should pop. Start the code by including the previously installed python MQTT module. We will also need the time module, to access sleeping functions.

After that, we will declare some auxiliary variables. The first one will be a global variable indicating the state of the connection to the broker. Thus, it will be initialized with false.

The other variables will contain the broker connection information, previously mentioned in the introduction section.

import paho.mqtt.client as mqttClient
import time

Connected = False #global variable for the state of the connection

broker_address= "m11.cloudmqtt.com" #Broker address
port = 12948 #Broker port
user = "yourUserName" #Connection username
password = "yourPassowrd" #Connection password

Next, we will create a client instance. The constructor receives as argument a unique MQTT client identifier, as a string. We will call the client “Python”.

After this instantiation, we will call the username_pw_set method, in order to set username and password needed to connect to the MQTT broker.

After that, we will need to specify a on_connect callback function, which is executed when the broker responds to the connection request. We won’t be specifying the code for the function know, just assign it.

We will also need to specify a on_message callback function, which is executed when a message is received on a subscribed topic. We will also leave the actual implementation of the function for latter.

client = mqttClient.Client("Python") #create new instance
client.username_pw_set(user, password=password) #set username and password
client.on_connect= on_connect #attach function to callback
client.on_message= on_message #attach function to callback

Now, we will call the connect method, for establishing the connection to the MQTT broker. Note that this is a blocking method. As inputs, this method will receive the broker address and port.

Next, we will call the loop_start method. This method is very important since it will launch a background thread to handle the connection and the sending and receiving of messages. But, since the thread runs in background, it will not block the execution of our code.

Since the connection may take a while to be established, we will poll the previously declared Connected variable in a loop, until its value is set to true. This way, we won’t advance in our code until we know we are already connected to the MQTT broker. Please note that the Connected variable will be set to true in the on_connect handling function, which we still need to specify.

Once the connection is established, we will subscribe to a topic. To do so, we call the subscribe method, passing as argument the name of the topic that we want to subscribe. In this example, we will subscribe to the “python/test” topic. So, when a message is received on this topic, the on_message function, yet to be specified, will run.

client.connect(broker_address, port=port)          #connect to broker

client.loop_start()        #start the loop

while Connected != True:    #Wait for connection
    time.sleep(0.1)

client.subscribe("python/test")

Now, we will do an infinite loop with a small delay in each iteration, since the messages will be handled in the on_message callback function.

This loop will run inside a try-except block, where the except block will catch a keyboard interrupt. By doing so, we can easily terminate the loop by issuing a ctrl+C command to the LinkIt Smart.

Since the program will finish in the except block, when the exception is caught, we will need to disconnect from the broker and end the background thread started in the initialization. To do so, we call the disconnect method and loop_stop method, both in the except block.

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    print "exiting"
    client.disconnect()
    client.loop_stop()

Finally we need to specify the on_message callback function. As can be seen here, it receives 3 arguments. Nevertheless, we will only use the argument named message.

We will access a member of this class called payload, to obtain the message received from the previously subscribed topic. Then, we will print the message payload.

def on_message(client, userdata, message):
    print "Message received: "  + message.payload

Check the full source code bellow, ready to use with the on_connect callback function also implemented. Note that we check the rc (result code) argument, which indicates if there was an error on the connection. The value 0 means there was no error and the connection was established. In that case, we set the Connected variable to true.

import paho.mqtt.client as mqttClient
import time

def on_connect(client, userdata, flags, rc):

    if rc == 0:

        print("Connected to broker")

        global Connected                #Use global variable
        Connected = True                #Signal connection 

    else:

        print("Connection failed")

def on_message(client, userdata, message):
    print "Message received: "  + message.payload

Connected = False   #global variable for the state of the connection

broker_address=	"m11.cloudmqtt.com"  #Broker address
port = 12948                         #Broker port
user = "yourUserName"                #Connection username
password = "yourPassword"            #Connection password

client = mqttClient.Client("Python")               #create new instance
client.username_pw_set(user, password=password)    #set username and password
client.on_connect= on_connect                      #attach function to callback
client.on_message= on_message                      #attach function to callback

client.connect(broker_address, port=port)          #connect to broker

client.loop_start()        #start the loop

while Connected != True:    #Wait for connection
    time.sleep(0.1)

client.subscribe("python/test")

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    print "exiting"
    client.disconnect()
    client.loop_stop()


Testing the code

To test the code, just open the Putty terminal window again and navigate to the directory where you saved the previous code. There, give the following command:

python MQTTsubscribe.py

If you named the file differently, use the name of your file. The program should start running and once the connection is established, you should get the result indicated in figure 3.

LinkIt Smart connect to MQTT Broker

Figure 3 – Connection to the broker successful.

To send a message to the subscribed “python/test” topic, we will use an application called MQTTLens. It’s very easy to use, free and it has been the one used in previous tutorials. So, open MQTTLens, connect to the broker and publish a message to the topic, as indicated in figure 4.

MQTTLens send message to LinkIt Smart

Figure 4 – Publishing a message to the LinkIt Smart subscribed topic.

After sending the message, go back to Putty. The message sent should be printed in the console, as indicated in figure 5. In that case, we sent a second message, just for illustration purposes.

LinkIt Smart message from subscribed MQTT topic

Figure 5 – Printing the received MQTT messages.


Related posts

2 thoughts on “LinkIt Smart 7688 Duo: Subscribing to MQTT topic”

  1. Pingback: LinkIt Smart 7688 Duo: Publishing messages to MQTT topic | techtutorialsx

  2. Pingback: LinkIt Smart 7688 Duo: Publishing messages to MQTT topic | techtutorialsx

  3. Pingback: ESP32: Sending JSON messages over MQTT | techtutorialsx

  4. Pingback: ESP32: Sending JSON messages over MQTT | techtutorialsx

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading