Design, build, and connect wired or wireless node(s) with network or bus addresses
For this week’s assignment, we’ve chosen to have two Xiao ESP32C3s communicate with each other. These two electronic boards will use WiFi as a means of communication, using the MQTT protocol.
The implementation of an MQTT server with a Raspberry pi 3¶
MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport, ideal for connecting remote devices with a small code footprint and minimal network bandwidth. for more details click here
Before moving on to the implementation of the MQTT server, here is a graphic that summarizes the communication topology.
For the MQTT server we chose the open source option mosquitto. The server will be hosted on a rapberry pi 3.
For the installation of the server we first proceeded to the installation of the operating system raspberry pi OS.
We downloaded and installed Raspberry Pi OS.
Then we inserted the SD card of the Raspberry Pi in our computer and proceeded to the installation of the operating system as shown below.
Since we used the lite version of raspebrry pi os, we need to communicate with the pi using the ssh protocol from where we configured the ssh connection settings as shown below.
To finish the installation we inserted the SD card in the raspberry pi 3, we connected it to the network of our Fablab thanks to an Ethernet RJ45 cable and we powered it as indicated below.
To connect to the raspberry pi with ssh we used windows powershell.
connection to the Raspberry pi
1234
ssh <username>@<host_ip_address> -P <port_number>
# For example
ssh pi@192.168.1.210 -P 1022
results
now that we are connected to the raspberry pi we will update the pi before any other command.
12
sudo apt-get update
sudo apt-get upgrade
Installation of mosquitto
1
sudo apt-get install mosquitto
Now that our mosquitto server is installed we need to move on to its configuration. To do this we will enter command lines to modify the connection parameters to the server for more details click here
Run the following command, but replace “YOUR_USERNAME” with the username you want to use
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
per_listener_settings true
pid_file /run/mosquitto/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
allow_anonymous false
listener 1883
password_file /etc/mosquitto/passwd
Press CTRL-X, then Y, and finally press Enter to exit and save the changes.
Restart Mosquitto for the changes to take effect.
1
sudo systemctl restart mosquitto
Now that we are done we will check if our server works as shown below
1
sudo systemctl status mosquitto
the commissioning of our mqtt server is finished we move to the programming of our MCU (mqtt clients).
For programming our MCU, we will use Arduino IDE with the PubSubClient library. The PubSubClient library provides a client to perform simple publishing and subscription operations with a server that supports MQTT.
For the operation, we’ll write two programs, one for XIAO 1 and the other for XIAO 2. XIA 1 will send messages to XIAO 2 via a topic.
For the different codes, you have to modify the code with your own SSID, password and Raspberry Pi IP address.
#include<WiFi.h>#include<PubSubClient.h>// Replace the next variables with your SSID/Password combinationconstchar*ssid="REPLACE_WITH_YOUR_SSID";constchar*password="REPLACE_WITH_YOUR_PASSWORD";// Add your MQTT Broker IP address, example://const char* mqtt_server = "192.168.1.144";constchar*mqtt_server="YOUR_MQTT_BROKER_IP_ADDRESS";WiFiClientespClient;PubSubClientclient(espClient);unsignedlonglastMsg=0;#define MSG_BUFFER_SIZE (50)charmsg[MSG_BUFFER_SIZE];intvalue=0;voidsetup_wifi(){delay(10);// We start by connecting to a WiFi networkSerial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.mode(WIFI_STA);WiFi.begin(ssid,password);while(WiFi.status()!=WL_CONNECTED){delay(500);Serial.print(".");}randomSeed(micros());Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());}voidreconnect(){// Loop until we're reconnectedwhile(!client.connected()){Serial.print("Attempting MQTT connection...");// Create a random client IDStringclientId="ESP32Client-";clientId+=String(random(0xffff),HEX);// Attempt to connectif(client.connect("ESP32","YOUR_USERNAME","PASSWORD")){Serial.println("connected");}else{Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}}voidsetup(){Serial.begin(115200);setup_wifi();client.setServer(mqtt_server,1883);}voidloop(){if(!client.connected()){reconnect();}client.loop();unsignedlongnow=millis();if(now-lastMsg>2000){lastMsg=now;++value;snprintf(msg,MSG_BUFFER_SIZE,"hello world #%ld",value);Serial.print("Publish message: ");Serial.println(msg);client.publish("cmd_mpass",msg);}}
#include<PubSubClient.h>// Update these with values suitable for your network.constchar*ssid="........";constchar*password="........";constchar*mqtt_server="broker.mqtt-dashboard.com";WiFiClientespClient;PubSubClientclient(espClient);voidsetup_wifi(){delay(10);// We start by connecting to a WiFi networkSerial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.mode(WIFI_STA);WiFi.begin(ssid,password);while(WiFi.status()!=WL_CONNECTED){delay(500);Serial.print(".");}randomSeed(micros());Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());}voidcallback(char*topic,byte*payload,unsignedintlength){Serial.print("Message arrived [");Serial.print(topic);Serial.print("] ");for(inti=0;i<length;i++){Serial.print((char)payload[i]);}Serial.println();}voidreconnect(){// Loop until we're reconnectedwhile(!client.connected()){Serial.print("Attempting MQTT connection...");// Create a random client IDStringclientId="ESP8266Client-";clientId+=String(random(0xffff),HEX);// Attempt to connectif(client.connect("ESP01","YOUR_USERNAME","PASSWORD")){Serial.println("connected");client.subscribe("cmd_mpass");}else{Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}}voidsetup(){Serial.begin(115200);setup_wifi();client.setServer(mqtt_server,1883);client.setCallback(callback);}voidloop(){if(!client.connected()){reconnect();}client.loop();}
Explanation of the essential elements of the program
The first step in the program is to connect to the Wifi network and to the mqtt server with the lines below by specifying the ssid, the password of the Wifi network and the IP address of the Mqtt server.
to publish a message on the topic of our choice we use the function client.publish(topic_name, message). note: the variable message must be of type char.
After following all the steps below, we were able to get two XIAO ESP32C3s to communicate using the MQTT protocol and Wifi as the communication medium. As you can see below, we have serial monitors for the two ESP32C3s showing the messages they exchange.
we’re using this communication program for my final project.