Example: Receive Messages (Subscribe) With Mqtt - Digi XBee 3 Cellular LTE-M User Manual

Smart modem
Table of Contents

Advertisement

Examples: IOT protocols with transparent mode
mqttc.loop_start()
mqttc.publish("digitest/test1", "Hello, World!")
"digitest /test1" topic
mqttc.loop_stop()
Note
You can easily copy and paste code from the
PDF version, as it may not maintain essential indentations.
This example imports the MQTT library, allowing you to use the MQTT protocol via APIs in the library,
such as the connect(), subscribe(), and publish() methods.
The second line creates an instance of the client, named mqttc. The client ID is the argument you
passed in: digitest (this is optional).
In line 3, the client connects to a public broker, in this case m2m.eclipse.org, on port 1883 (the default
MQTT port, or 8883 for MQTT over TLS). There are many publicly available brokers available, you can
find a list of them here: https://github.com/mqtt/mqtt.github.io/wiki/brokers.
Line 4 starts the networking daemon with client.loop_start() to handle the background
network/data tasks.
Finally, the client publishes its message Hello, World! to the broker under the topic
digitest/backlog/test1. Any nodes (devices, phones, computers, even microcontrollers) subscribed to
that same topic on the same broker receive the message.
Once no more messages need to be published, the last line stops the network daemon with
client.loop_stop().

Example: receive messages (subscribe) with MQTT

This example describes how a client would receive messages from within a specific topic on the
broker:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
client connects to the broker
print("Connected with result code {0}".format(str(rc)))
of connection attempt
client.subscribe("digitest/test1")
"digitest/test1", receive any messages published on it
def on_message(client, userdata, msg):
message is received from the server.
print("Message received-> " + msg.topic + " " + str(msg.payload))
Print a received msg
client = mqtt.Client("digi_mqtt_test")
client ID "digi_mqtt_test"
client.on_connect = on_connect
connection
client.on_message = on_message
message
# client.connect("m2m.eclipse.org", 1883, 60)
keepalive-time)
client.connect('127.0.0.1', 17300)
Digi XBee® 3 Cellular LTE-M/NB-IoT Global Smart Modem User Guide
# Start networking daemon
# Kill networking daemon
online version of this
# Define callback function for successful
# Define callback function for receipt of a
Get started with MQTT
# Publish message to
guide. Use caution with the
# The callback for when the
# Subscribe to the topic
# The callback for when a PUBLISH
# Create instance of client with
# Connect to (broker, port,
# Print result
#
75

Advertisement

Table of Contents
loading

This manual is also suitable for:

Xbee 3 cellular nb-iot

Table of Contents