Example: Use Python to generate a CoAP message

This example illustrates how the CoAP protocol can perform GET/POST/PUT/DELETE requests similarly to the HTTP protocol and how to do this using the XBee Cellular Modem. In this example, the XBee Cellular Modem talks to a CoAP Digi Server. You can use this client code to provide an abstract wrapper to generate a CoAP message that commands the XBee Cellular Modem to talk to the remote CoAP server.

Note It is crucial to configure the XBee Cellular Modem settings. See Configure the device and follow the steps. You can target the IP address to a different CoAP public server.

  1. Install Python 2.7. The Installation guide is located at: python.org/downloads/.
  2. Download and install the CoAPthon library in the python environment from pypi.python.org/pypi/CoAPthon.
  3. Download these two .txt files: Coap.txt and CoapParser.txt. After you download them, open the files in a text editor and save them as .py files.
  4. In the folder that you place the Coap.py and CoapParser.py files, press Shift + right-click and then click Open command window.
  5. At the command prompt, type python Coap.py and press Enter to run the program.
  6. Type the USB port number that the XBee Cellular Modem is connected to and press Enter. Only the port number is required, so if the port is COM19, type 19.

Note If you do not know the port number, open XCTU and look at the XBee Cellular Modem in the Radio Modules list. This view provides the port number and baud rate, as in the figure below where the baud rate is 9600 b/s.

  1. Type the baud rate and press Enter. You must match the device's current baud rate. XCTU provides the current baud rate in the BD Baud Rate field. In this example you would type 9600.
  2. Press Y if you want an auto-generated example. Press Enter to build your own CoAP request.
  3. If you press Y it generates a message with:
    • Method: POST
    • URI: example
    • payload: hello world
    • token: test

The send and receive message must match the same token and message id. Otherwise, the client re-attempts the connection by sending out the request.

In the following figure, the payload contains the server response to the query. It shows the results for when you press Enter rather than Y.