MQTT Publish Subscribe
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.
INPUT DEMO DEPLOYMENT IMAGE HERE
1) Install "paho-mqtt" package according to instructions outlined in the Programmer's Guide
2) Create a free account at http://2lemetry.com
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
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"
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: try: 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 finally: time.sleep(1)
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 == 'RELAY': try: dsal = LtrxDsal() if msglist == 'on': dsal.setRelay(1, True) print 'Relay 1 is turned on...' elif msglist == 'off': dsal.setRelay(1, False) print 'Relay 1 is turned off...' except: print 'Failed to turn on relay 1...'