Digi International Inc XB3C1 Manual Do Utilizador

Página de 146
Getting started with the XBee Smart Modem Development Kit
Get started with MQTT
Digi XBee3 Cellular LTE Cat 1 Smart Modem User Guide
35
Print a received msg
client = mqtt.Client("digi_mqtt_test")
# Create instance of client with
client ID “digi_mqtt_test”
client.on_connect = on_connect
# Define callback function for successful
connection
client.on_message = on_message
# Define callback function for receipt of a
message
# client.connect("m2m.eclipse.org", 1883, 60)
# Connect to (broker, port,
keepalive-time)
client.connect('127.0.0.1', 17300)
client.loop_forever()
# Start networking daemon
Note
You can easily copy and paste code from the online version of this Guide. 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 SSL) 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: