In this lab we will use two communication protocols commonly used in IoT.
CoAP (Constrained Application Protocol) is a communication protocol that runs over the UDP/IP protocol, being used in domains with limited current resources (consumed power) and with possible loss of network packets (lossy networks).
There are a lot of software implementations of the CoAP protocol (Implementations), but in this lab we will use the ”CoAP simple library” for the Arduino IDE to run a CoAP server, and the CoAPthon Python implementation to run a CoAP client.
A Wireshark capture shows how the CoAP protocol runs over the UDP protocol:
MQTT is a protocol for transporting messages from a producer (publisher) to a consumer (subscriber). Unlike CoAP which has a client-server architecture, MQTT uses an intermediary (broker) to forward messages from producer to consumer.
Download the CoAP-simple-library and copy the files to the library directory in the Arduino IDE (usually in Documents/Arduino/libraries). A restart of the Arduino IDE is required after installing a library directly into that directory instead of using the Library Manager.
Open the example called “esp32” from the “CoAP simple library” and adjust the code so that the LED connected to GPIO25 is lit via CoAP. Note the IP obtained by the ESP32 to use from the CoAP client.
#define COAP_DEFAULT_PORT 5683
Then install the CoAPthon library from Python using the PIP utility:
pip install CoAPthon
Use the following command to turn the LED on/off:
/usr/local/bin/coapclient.py -o PUT -p "coap://$ESP32_BOARD_IP/light" -P "1"
After installing the “PubSubClient” library from the Arduino IDE's Library Manager, open the “mqtt_esp8266” example.
Even though it is written for ESP8266, we can run the program on ESP32 by modifying the following line:
- #include <ESP8266WiFi.h> + #include <WiFi.h>
The ESP32 board will use the MQTT client to register a “subscriber” to the “inTopic” topic, and from a computer we will install the “paho-mqtt” library to instantiate an MQTT client in “publisher” mode. To install “paho-mqtt”, use the following command:
pip install paho-mqtt
Use this Python program to turn off/on the LED on the ESP32 board.
We will use a public MQTT broker at “test.mosquitto.org” for both the ESP32 MQTT client and the Python client. For this reason, it is important to change the topic names in order not to receive messages from other devices on the Internet, which use the same public server.