
Examples: IOT protocols with transparent mode
Get started with MQTT
Digi XBee® 3 Cellular LTE-M/NB-IoT Global Smart Modem User Guide
76
client.loop_forever()
# Start networking daemon
Note
You can easily copy and paste code from the
. Use caution with the
PDF version, as it may not maintain essential indentations.
The first line imports the library functions for MQTT.
The functions
on_connect
and
on_message
are callback functions which are automatically called by
the client upon connection to the broker and upon receiving a message, respectively.
The
on_connect
function prints the result of the connection attempt, and performs the subscription.
It is wise to do this in the callback function as it guarantees the attempt to subscribe happens only
after the client is connected to the broker.
The
on_message
function prints the received message when it comes in, as well as the topic it was
published under.
In the body of the code, we:
n
Instantiate a client object with the client ID
digi_mqtt_test
.
n
Define the callback functions to use upon connection and upon message receipt.
n
Connect to an MQTT broker at
m2m.eclipse.org
, on port
1883
(the default MQTT port, or 8883
for MQTT over TLS) with a keepalive of 60 seconds (this is how often the client pings the broker
to keep the connection alive).
The last line starts a network daemon that runs in the background and handles data transactions and
messages, as well as keeping the socket open, until the script ends.
Use MQTT over the XBee Cellular Modem with a PC
To use this MQTT library over an XBee Smart Modem, you need a basic proxy that transfers a payload
received via the MQTT client’s socket to the serial or COM port that the XBee Smart Modem is active
on, as well as the reverse; transfer of a payload received on the XBee Smart Modem’s serial or COM
port to the socket of the MQTT client. This is simplest with the XBee Smart Modem in Transparent
mode, as it does not require code to parse or create API frames, and not using API frames means
there is no need for them to be queued for processing.
1. To put the XBee Cellular Modem in Transparent mode, set
AP
to
0
.
2. Set
DL
to the IP address of the broker you want to use.
3. Set
DE
to the port to use, the default is 1883 (0x75B). This sets the XBee Smart Modem to
communicate directly with the broker, and can be performed in XCTU as described in
.
4. You can make the proxy with a dual-threaded Python script, a simple version follows:
import threading
import serial
import socket
def setup():
"""
This function sets up the variables needed, including the serial port,
and it's speed/port settings, listening socket, and localhost adddress.
"""