2024年5月18日 星期六

ESP32 — MQTT 基本範例 (MQTT Box)

 ESP32 — MQTT 基本範例 (MQTT Box)

介紹

本課程展示WOKWI ESP32 模擬的基本MQTT協定使用。

  • 每兩秒向主題“alex9ufo/outTopic”發布“hello world”。
  • 訂閱主題“alex9ufo/inTopic”,列印收到的所有訊息。
  • 它假設接收到的有效負載是字串而不是二進位。
  • 如果訂閱的訊息為“ON”,則點亮板載LED。
  • 如果訂閱的訊息為“OFF”,則熄滅板載LED。

準備:

  • https://wokwi.com/projects/new/esp32 。 wokwi 註冊


  • MQTTbox 下載 安裝

WOKWI設定:
  • sketch.ion程式。
#include <WiFi.h>
#include "PubSubClient.h"
// WiFi
char ssid[]="Wokwi-GUEST";
char pass[]="";
// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";//"broker.emqx.io";//Public Broker
const char *mqtt_username = "hivemqtt";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
// App Protcol ---> Port
const char *topic_publish = "alex9ufo/outTopic";//Topic ESP32 Pusblish
const char *topic_subsrcibe = "alex9ufo/inTopic";//Topic ESp32 Subscribe

WiFiClient hamada;//WIFI Opject
PubSubClient client(hamada);//OOP

void callback(char *topic, byte *payload, unsigned int length);
#define LED 2
bool ledState=false;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish(topic_publish, "Hello world.....");
      client.subscribe(topic_subsrcibe);
    } 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(){
   // Setting LED pin as output
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);  // Turn off the LED initially
    //Open a serial connection to display program results and establish a connection to the Wi-Fi network.
    // Set software serial baud to 115200;
    Serial.begin(115200);
    // Connecting to a Wi-Fi network
    WiFi.begin(ssid, pass);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi..");
    }
        Serial.println("Connected to the Wi-Fi network");
    // Utilize PubSubClient to establish a connection with the MQTT broker.
    //connecting to a mqtt broker
    Serial.println("Before Connect MQTT");
    //Broker Configuration
    client.setServer(mqtt_broker, mqtt_port);
   
   while (!client.connected()) {
        String client_id = "esp32-client-";
        client_id =client_id+ String(WiFi.macAddress());
        //consloe.log("x"+"y");//xy

        //ESP32-ID -----> esp32-client-macaddress
        //variable.c_str()--->char [] , String
        Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("Public MQTT broker connected");
        } else {
            Serial.print("failed with state ");
            Serial.print(client.state());//1 , 2 , 5
            delay(2000);
        }
    }
    Serial.println("After Connect MQTT");
    client.publish(topic_publish, "Hello world.....");
    client.subscribe(topic_subsrcibe);
    client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 10000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish(topic_publish, msg);
  }
}



void callback(char* topic, byte* message, unsigned int length) {
  printPayload(topic, message, length);  
}

void printPayload(char* topic, byte* message, unsigned int length) {
  // Printing Received Message
  Serial.print("Message received on topic: ");
  Serial.println(topic);

  String messageTemp;
  for(int i=0; i<length; i+=1) {
    messageTemp += (char)message[i];
  }
  if(String(topic) == "alex9ufo/inTopic"){
      Serial.println("alex9ufo/inTopic");
      if(messageTemp=="ON"){
        Serial.println("Led ON");
        digitalWrite(LED,HIGH);
      }
      if(messageTemp=="OFF"){
        Serial.println("Led OFF");
        digitalWrite(LED,LOW);
      }
  }
  Serial.println(messageTemp);
}




  • diagram.json程式 (電路圖)。
{
  "version": 1,
  "author": "Anonymous maker",
  "editor": "wokwi",
  "parts": [
    { "type": "wokwi-esp32-devkit-v1", "id": "esp", "top": -321.7, "left": -168.2, "attrs": {} },
    {
      "type": "wokwi-resistor",
      "id": "r1",
      "top": -225.6,
      "left": 37.85,
      "rotate": 90,
      "attrs": { "value": "1000" }
    },
    {
      "type": "wokwi-led",
      "id": "led1",
      "top": -310.8,
      "left": 32.6,
      "attrs": { "color": "red" }
    }
  ],
  "connections": [
    [ "esp:TX0", "$serialMonitor:RX", "", [] ],
    [ "esp:RX0", "$serialMonitor:TX", "", [] ],
    [ "led1:C", "esp:GND.1", "black", [ "v0" ] ],
    [ "r1:1", "led1:A", "red", [ "h0" ] ],
    [ "esp:D2", "r1:2", "red", [ "h0" ] ]
  ],
  "dependencies": {}
}




  • Library manager --> Project Libaries --> Installed Libraries  




MQTTBox設定:


broker.mqtt-dashboard.com:1883/ws

mqtt / tcp










沒有留言:

張貼留言

WOKWI ESP32 LED Control , Node-Red MQTT SQLITE  

WOKWI ESP32 LED Control ,  Node-Red  MQTT SQLITE   const char broker[] = "test.mosquitto.org" ; //const char broker[] = "br...