LinkIt Smart 7688 Duo: Publishing messages to MQTT topic

The objective of this post is to explain how to use the LinkIt Smart 7688 Duo to publish messages to a MQTT topic.


Introduction

The objective of this post is to explain how to use the LinkIt Smart 7688 Duo to publish messages to a MQTT topic. To do so, we will use a Python library called paho-mqtt. You can check in detail how to install it in this previous post, which also explains how to subscribe to a MQTT topic.

As MQTT broker, we will use CloudMQTT, which has a free plan account that we can use for testing purposes. If you haven’t done so yet, register and create a MQTT broker instance.


The code

First of all, use Putty to connect to the LinkIt Smart. Check here how to do it. Then, connect using WinSCP and create a file called MQTTpublish.py, as indicated in figure 1. If you need a guide on how to use WinSCP, check this previous post.

WinSCP creating Python MQTT publish file

Figure 1 – Creating the Python program file with WinSCP.

Most of the coding will be similar to the previous post that explains how to subscribe to a topic. So, we start by importing the paho-mqtt module and also the time module. Then we declare the global variables needed to control the state of the connection and to store the credentials needed for connecting to the broker. Please use the values on your CloudMQTT instance information page.

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 = "yourPassword" #Connection password

Then, we need to create a client instance, set the username and password needed to connect to the broker and specify a connection handling function, which will be executed after the broker responds to the connection request.

In order to establish the connection to the MQTT broker, we call the connect method. Then we call the loop_start method, which will run a thread to deal with the network connection and exchanging of data. This thread will run on the background, so it will not block the execution of our program. Check bellow the code for all the method calls.

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.connect(broker_address, port=port) #connect to broker

client.loop_start() #start the loop

Since the process of establishing the connection to the MQTT broker can take some time, we will perform a loop which will end when the Connected variable (which we previously declared) is set to true.

The setting of this control variable to true will be done in our callback function, that we will specify in a minute.

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

Next, we will run a loop inside a try except block, which will catch a keyboard interrupt. With this approach, we can end the loop by sending a ctrl+C command to the LinkIt Smart and know when to finish the program.

Inside the loop, we will use the raw_input function to get a string from the command line. We will use that string as the message to publish to the topic.

To publish a message to a topic, we call the publish method, passing as arguments the topic where we want to publish and the message. For illustration purposes, we will be publishing the message on the “python/test” topic. You can use other if you want, as long as you use it latter when reading the messages from a topic, in the test section

Since the program will finish when the keyboard exception is caught, we call the disconnect method, to disconnect from the broker, and the loop_stop method, to stop the previously launched background thread. Both these calls are done in the except block.

try:
    while True:

        value = raw_input('Enter the message:')
        client.publish("python/test",value)

except KeyboardInterrupt:

    client.disconnect()
    client.loop_stop()

Check the full code bellow, which already has the callback on_connect function implemented.

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")

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.connect(broker_address, port=port)          #connect to broker

client.loop_start()        #start the loop

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

try:
    while True:

        value = raw_input('Enter the message:')
        client.publish("python/test",value)

except KeyboardInterrupt:

    client.disconnect()
    client.loop_stop()


Testing the code

To test the code, go to the Putty terminal window and navigate to the directory where you saved the Python file. There, send the following command:

python MQTTpublish.py

If you named your file with a different value, use it instead. After this, the program should start running and print a “connected” message, indicating that it has connected to the MQTT broker.

In order to see the messages we are going to send, we will use MQTTLens, which allows us to subscribe to MQTT topics and check the messages received. So, open MQTTLens and subscribe to the “python/test” topic.

Go back to Putty, type a message and hit enter, as indicated in figure 2. The message should now be sent to the MQTT topic. In this case, I’ve sent 2 different messages, just for testing purposes.

LinkIt Smart Duo publish MQTT topic message

Figure 2 – Publishing messages to topic with the LinkIt Smart.

Now, go back to MQTTLens. The messages sent from the LinkIt Smart should now be available, as shown in figure 3.

MQTTLens message from LinkIt Smart.png

Figure 3 – Messages sent from the LinkIt Smart.


Related posts

Advertisements
This entry was posted in LinkIt Smart and tagged , , , , , , , , , , , , , . Bookmark the permalink.

One Response to LinkIt Smart 7688 Duo: Publishing messages to MQTT topic

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s