User Tools

Site Tools


c4ta:iot-workshop:mqtt

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
c4ta:iot-workshop:mqtt [2024/09/11 00:38] – created harley.larac4ta:iot-workshop:mqtt [2024/09/13 18:10] (current) – [3. Our first MQTT Publish] harley.lara
Line 88: Line 88:
  
 <file c++ mqtt-publish.ino> <file c++ mqtt-publish.ino>
-/* 
- Basic ESP8266 MQTT example 
- This sketch demonstrates the capabilities of the pubsub library in combination 
- with the ESP8266 board/library. 
- It connects to an MQTT server then: 
-  - publishes "hello world" to the topic defined as outTopic every two seconds 
- It will reconnect to the server if the connection is lost using a blocking 
- reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to 
- achieve the same result without blocking the main loop. 
-*/ 
- 
 #include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
 +//#include <WiFiClientSecure.h>
 +#include <WiFiClient.h>
 #include <PubSubClient.h> #include <PubSubClient.h>
 +#include <ArduinoJson.h>
 +
 +const uint16_t HTTP_PORT = 80; // Use 443 for HTTPS and 80 for HTTP
  
-#define MSG_BUFFER_SIZE (50)+// Replace with your WiFi credentials 
 +const char* SSID = "iotlab-mobile"; // [USER INPUT] 
 +const char* PASSWORD = "iotlab18"; // [USER INPUT]
  
-// Update these with values suitable for your network and mqtt broker+// Create an instance of WiFiClientSecure 
 +WiFiClient wifi_client;
  
-const char* ssid ""; +// =================== 
-const char* password ""; +// MQTT 
-const char* mqtt_server "broker.hivemq.com";+// ===================
  
-const char* outTopic = "unicaes/workshop/2023/jan"; +#define MQTT_MSG_BUFFER_SIZE 50 // [USER INPUT] 
-const char* inTopic = "unicaes/workshop/2023/to-jan";+StaticJsonDocument<MQTT_MSG_BUFFER_SIZE> doc;
  
-// Set up of some needed variables+const uint8_t PERIOD_MINUTES = 1;
  
-WiFiClient espClient+const char* MQTT_SERVER = "192.168.1.1"// [USER INPUT] 
-PubSubClient client(espClient);+const uint16_t MQTT_PORT = 1883; // TLS TCP PORT for HTTPS connections, otherwise use 1883 
 +const char* MQTT_OUTPUT_TOPIC = "colmayor/workshop/2024/harley"; // [USER INPUT] 
 +const char* MQTT_INPUT_TOPIC = "colmayor/workshop/2024/to-harley"; // [USER INPUT] 
 + 
 +PubSubClient mqtt_client(wifi_client);
 unsigned long lastMsg = 0; unsigned long lastMsg = 0;
-char msg[MSG_BUFFER_SIZE]+char msg[MQTT_MSG_BUFFER_SIZE];
-int value = 0;+
  
-void setup_wifi() {+// count the number of msg 
 +uint value = 0;
  
-  delay(10); +void setup_wifi() { 
-  // We start by connecting to a WiFi network +  // Connect to Wi-Fi 
-  Serial.println(); +  WiFi.begin(SSID, PASSWORD);
-  Serial.print("Connecting to "); +
-  Serial.println(ssid);+
  
-  WiFi.mode(WIFI_STA); +  Serial.print("\n\nConnecting to "); 
-  WiFi.begin(ssid, password);+  Serial.print(SSID);
  
   while (WiFi.status() != WL_CONNECTED) {   while (WiFi.status() != WL_CONNECTED) {
-    delay(500);+    delay(1000);
     Serial.print(".");     Serial.print(".");
   }   }
  
-  randomSeed(micros()); +  Serial.println("\nConnected to WiFi"); 
- +  Serial.print("IP address: ");
-  Serial.println(""); +
-  Serial.println("WiFi connected"); +
-  Serial.println("IP address: ");+
   Serial.println(WiFi.localIP());   Serial.println(WiFi.localIP());
-} 
  
-void reconnect() { +  // Set the client to verify the server's certificate 
-  // Loop until we're reconnected +  //wifi_client.setInsecure();
-  while (!client.connected()) { +
-    Serial.print("Attempting MQTT connection..."); +
-    // Create a random client ID +
-    String clientId = "ESP8266Client-"; +
-    clientId += String(random(0xffff), HEX); +
-    // Attempt to connect +
-    if (client.connect(clientId.c_str())) { +
-      Serial.println("connected"); +
-      // Once connected, publish an announcement... +
-      client.publish(outTopic, "hello world"); +
-    } else { +
-      Serial.print("failed, rc="); +
-      Serial.print(client.state()); +
-      Serial.println(" try again in 5 seconds"); +
-      // Wait 5 seconds before retrying +
-      delay(5000); +
-    } +
-  } +
-}+
  
-void setup() { +  // Give the client a chance to perform the handshake 
-  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output +  delay(1000);
-  Serial.begin(115200); +
-  setup_wifi(); +
-  client.setServer(mqtt_server, 1883); +
-+
- +
-void loop() { +
- +
-  if (!client.connected()) { +
-    reconnect(); +
-  } +
-  client.loop(); +
- +
-  unsigned long now = 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(outTopic, msg); +
-  } +
-+
-</file> +
- +
-===== 4. Subscribe ===== +
-Now, let's move on to an essential aspect of our workshop. We'll guide you through the process of subscribing to an MQTT topic. This step is practical gateway to interactive IoT applications. You'll learn how to exchange MQTT messages between devices, potentially triggering actions like LED reactions or serial outputs. While we'll provide initial guidance, feel free to explore further and experiment with this dynamic feature. +
- +
-<file c++ mqtt-subscribe-example.ino> +
-/* +
- Basic ESP8266 MQTT example +
- This sketch demonstrates the capabilities of the pubsub library in combination +
- with the ESP8266 board/library. +
- It connects to an MQTT server then: +
-  - publishes "hello world" to the topic defined as outTopic every two seconds +
-  - subscribes to the topic defined as inTopic, printing out any messages +
-    it receives. NB - it assumes the received payloads are strings not binary +
-  - If the first character of the topic defined as inTopic is an 1, switch ON the ESP Led, +
-    else switch it off +
- It will reconnect to the server if the connection is lost using a blocking +
- reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to +
- achieve the same result without blocking the main loop. +
-*/ +
- +
-#include <ESP8266WiFi.h> +
-#include <PubSubClient.h> +
- +
-// Update these with values suitable for your network and mqtt broker +
- +
-const char* ssid = ""; +
-const char* password = ""; +
-const char* mqtt_server = "broker.hivemq.com"; +
- +
-const char* outTopic = "unicaes/workshop/2023/jan"; +
-const char* inTopic = "unicaes/workshop/2023/to-jan"; +
- +
-// Set up of some needed variables +
- +
-WiFiClient espClient; +
-PubSubClient client(espClient); +
-unsigned long lastMsg = 0; +
-#define MSG_BUFFER_SIZE (50) +
-char msg[MSG_BUFFER_SIZE]; +
-int value = 0; +
- +
-void setup_wifi() { +
- +
-  delay(10); +
-  // We start by connecting to a WiFi network +
-  Serial.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());+
 } }
  
 void callback(char* topic, byte* payload, unsigned int length) { void callback(char* topic, byte* payload, unsigned int length) {
 +  // RAW payload
   Serial.print("Message arrived [");   Serial.print("Message arrived [");
   Serial.print(topic);   Serial.print(topic);
Line 266: Line 157:
   Serial.println();   Serial.println();
  
-  // Switch on the LED if an 1 was received as first character +  // JSON formated payload 
-  if ((char)payload[0] == '1') { +  //deserializeJson(doc, (const byte*)payload, length); 
-    digitalWrite(BUILTIN_LEDLOW);   // Turn the LED on (Note that LOW is the voltage level +  //serializeJson(docSerial);
-    // but actually the LED is on; this is because +
-    // it is active low on the ESP-01) +
-  } else { +
-    digitalWrite(BUILTIN_LEDHIGH);  // Turn the LED off by making the voltage HIGH +
-  } +
 } }
  
-void reconnect() { +void mqtt_reconnect() { 
-  // Loop until we're reconnected +  while (!mqtt_client.connected()){ 
-  while (!client.connected()) { +    Serial.println("Attempting MQTT re-connection.."); 
-    Serial.print("Attempting MQTT connection...");+
     // Create a random client ID     // Create a random client ID
-    String clientId = "ESP8266Client-";+    String clientId = "ESP8266-";
     clientId += String(random(0xffff), HEX);     clientId += String(random(0xffff), HEX);
 +
     // Attempt to connect     // Attempt to connect
-    if (client.connect(clientId.c_str())) { +    if (mqtt_client.connect(clientId.c_str())) { 
-      Serial.println("connected");+      Serial.println("Successful reconnection.");
       // Once connected, publish an announcement...       // Once connected, publish an announcement...
-      client.publish(outTopic, "hello world"); +      //JsonDocument doc; 
-      // ... and resubscribe +      doc["msg"] = "hello world"
-      client.subscribe(inTopic);+      doc["count"] = value; 
 +      serializeJson(doc, msg); 
 +      mqtt_client.publish(MQTT_OUTPUT_TOPIC, msg); 
 +      mqtt_client.subscribe(MQTT_INPUT_TOPIC);
     } else {     } else {
       Serial.print("failed, rc=");       Serial.print("failed, rc=");
-      Serial.print(client.state()); +      Serial.print(mqtt_client.state()); 
-      Serial.println(" try again in seconds"); +      Serial.println(" try again in 10 seconds"); 
-      // Wait 5 seconds before retrying +      // Wait before retrying 
-      delay(5000);+      delay(10000);
     }     }
   }   }
Line 302: Line 191:
  
 void setup() { void setup() {
-  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output 
   Serial.begin(115200);   Serial.begin(115200);
 +
   setup_wifi();   setup_wifi();
-  client.setServer(mqtt_server1883); + 
-  client.setCallback(callback);+  // to generate a random client ID 
 +  // during reconnection with the 
 +  // mqtt server connection 
 +  randomSeed(micros());  
 +  mqtt_client.setServer(MQTT_SERVERMQTT_PORT); 
 +  mqtt_client.setCallback(callback);
 } }
  
 void loop() { void loop() {
- +  if (!mqtt_client.connected()) { 
-  if (!client.connected()) { +    mqtt_reconnect();
-    reconnect();+
   }   }
-  client.loop();+ 
 +  mqtt_client.loop();
  
   unsigned long now = millis();   unsigned long now = millis();
-  if (now - lastMsg > 2000) {+ 
 +  if (now - lastMsg > (PERIOD_MINUTES*(60*1000))) {
     lastMsg = now;     lastMsg = now;
     ++value;     ++value;
-    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value)+    // JsonDocument doc; 
-    Serial.print("Publish message: ")+    doc["msg"] = "hello world"; 
-    Serial.println(msg); +    doc["count"] = value
-    client.publish(outTopic, msg);+    serializeJson(doc, msg); 
 +    mqtt_client.publish(MQTT_OUTPUT_TOPIC, msg);
   }   }
-} 
  
 +
 +}
 </file> </file>
 +
 +===== 4. Subscribe =====
 +Now, let's move on to an essential aspect of our workshop. We'll guide you through the process of subscribing to an MQTT topic. This step is a practical gateway to interactive IoT applications. You'll learn how to exchange MQTT messages between devices, potentially triggering actions like LED reactions or serial outputs. While we'll provide initial guidance, feel free to explore further and experiment with this dynamic feature.
 +
 +TODO.
  
 ===== Recording ===== ===== Recording =====
c4ta/iot-workshop/mqtt.1726007892.txt.gz · Last modified: 2024/09/11 00:38 by harley.lara