MQTT Publish Subscribe

From Lantronix Developer Wiki
Revision as of 19:16, 17 November 2014 by Vlkd2103 (Talk | contribs)

Jump to: navigation, search



The sample application demonstrates how two PWXC HSPA+ devices connected to a cloud service can send/receive messages between each other.

With “paho-mqtt” python packaged installed, HSPA+ can easily connect to a cloud service. The MQTT protocol is a machine-to-machine (M2M) connectivity protocol. With the lightweight publish/subscribe messaging transport, it is very useful for connections when the devices are in remote locations. In this demo, one of the devices has a switch connected to its digital input with DC power while the other one has an LED connected to its relay. By turning the switch on the device to on or off, we can alter the state of LED of the other device.



  1. Install "paho-mqtt" package according to instructions outlined in the Programmer's Guide
  2. Create a free account at
  3. Upload the scripts shown below to the device using the procedures outlined in the Programmer's Guide
  4. Two PremierWave XC HSPA+ devices as shown in the image above

Demo Procedure

  1. Start the MQTT scripts after the device boots up
  2. Logon to the cloud website and monitor the traffic
  3. Turn the switch on the first device to "on" or "off" position
  4. The LED on the second device should turn "on" or "off"

Sample Code

Code for Device #1

### device 1
# polling the state of the digital input
# publish a corresponding message when the state is changed.
 def poll_di_status(c):
    print 'Digital Input 1'
    dsal = LtrxDsal()
    global static_state
    static_state  = dsal.readDigitalInput(1)
    while True:
            state = dsal.readDigitalInput(1)
            if state != static_state:
                print 'Digital Input state changed from ' + static_state + ' to ' + state
                if state == 'high':
                    c.publish(PUB_TOPIC, 'RELAY:on', QOS)
                elif state == 'low':
                    c.publish(PUB_TOPIC, 'RELAY:off', QOS)
            static_state = state
        except LtrxDsalError, e:
            print e.errmsg

Code fore Device #2

### device 2
# Parse the messages received from device 1.
# Set the relay on or off based on the command.
def on_message(client, userdata, message):
    print("Received message on topic " + str(message.topic) + " (QOS " + str(message.qos) + "): " + str(message.payload))
    msglist = message.payload.split(':')
    if len(msglist) > 1:
        if msglist[0] == 'RELAY':
                dsal = LtrxDsal()
                if msglist[1] == 'on':
                    dsal.setRelay(1, True)
                    print 'Relay 1 is turned on...'
                elif msglist[1] == 'off':
                    dsal.setRelay(1, False)
                    print 'Relay 1 is turned off...'
                print 'Failed to turn on relay 1...'
Personal tools