Software DEV. Group Project

A Git page for group work @ KMUTNB CprE. Software Development I

View on GitHub

«<—BACK


image

5.1) Write Arduino sketches to subscribe messages from the MQTT broker

After we already setup the MQTT Broker on our Raspberry Pi. Now we gonna try to connect arduino to MQTT Broker

Required Component

  • MQTT Broker ( Raspberry Pi )
  • ESP32 + Cable
  • Access Point Device

Required Software

  • Arduino IDE

REMARK ! ! ! :

From my exprience ESP32 device CANNOT CONNECT TO IOS DEVICE HOTSPOT ( Iphone 13, In this case )

Might works for others IDK.

image


image

(Didn’t know it’s already have V2.0)


Step 1 : Setting Up Your Arduino IDE

image

image


Step 2 : Install Library

image


Step 3 : Create arduino_secrets.h for including wifi and mqtt broker information to main code.

image


Step 4 : Demo Code for ESP32

image


#include <WiFiClientSecure.h> // used for TCP/MQTT ports 8883/8884 
#include <PubSubClient.h>     // https://github.com/knolleary/pubsubclient/
#include "arduino_secrets.h"

#define MQTT_BROKER    "test.mosquitto.org"
#define MQTT_PORT      (8883)

#define CLIENT_ID      "arduino_client"
#define SUB_TOPIC      "test/1234/#"
#define PUB_TOPIC      "test/1234/msg"
#define INTERVAL_MSEC  (5000)

WiFiClientSecure net;      // ESP32 WiFi client (Secure)
PubSubClient client(net);  // MQTT client
uint32_t last_pub_ts_msec = 0; 

void connect() {
  // connect the WiFi network first (if not already connected)
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
  Serial.print( "\n\nWiFi Connected: ");
  Serial.println( WiFi.localIP() ); // show the IP address

  // connect/reconnect the MQTT broker
  while ( !client.connect(CLIENT_ID, MQTT_USER, MQTT_PASS) ) {
    delay(1000);
  }
  client.subscribe( SUB_TOPIC );
}

// This is the callback function for the incoming MQTT message.
void onMessageReceived( char *topic, byte *payload, unsigned int length ) {
  uint32_t now_msec = millis(); // message reception timestamp
  ((char *)payload)[length] = '\0';
  Serial.printf( "Received: topic='%s', payload='%s', rtt=%lu msec\n",
         topic, (char *)payload, now_msec-last_pub_ts_msec );
  Serial.flush();
}

void setup() {
  Serial.begin( 115200 );  // initialize the Serial port
  WiFi.mode( WIFI_STA );   // WiFi Station mode
  WiFi.begin( WIFI_SSID, WIFI_PASS ); // start the WiFi client

#if  defined(MQTT_PORT) && (MQTT_PORT==8883 || MQTT_PORT==8884)
  net.setCACert( MOSQUITTO_CERT_CA );        // set the CA certificate
  #if (MQTT_PORT==8884)
    net.setCertificate( CLIENT_CERT_CRT );   // set client certificate
    net.setPrivateKey( CLIENT_PRIVATE_KEY ); // set private key 
  #endif
#endif

  // initialize the MQTT broker
  client.setServer( MQTT_BROKER, MQTT_PORT ); 
  // set the callback function
  client.setCallback( onMessageReceived ); 
  // set buffer size
  client.setBufferSize( 1024 );
  connect(); // connect the WiFi and the MQTT broker
}

void loop() {
  static uint32_t msg_cnt = 0; // published message count
  static char msg[32]; // message buffer (up to 32 chars)

  if ( !client.connected() ) { 
    connect();   // reconnect the WiFi and/or MQTT if disconnected
  }
  client.loop(); // process the MQTT event (non-blocking call)
  if ( millis() - last_pub_ts_msec >= INTERVAL_MSEC ) {
    sprintf( msg, "hello id=%lu", ++msg_cnt );
    Serial.printf( "Published: '%s'\n", msg );
    Serial.flush();
    // update message publishing timestamp
    last_pub_ts_msec = millis(); 
    // publish a message 
    client.publish( PUB_TOPIC, msg );
  }
}

«<—BACK