2023年9月29日 星期五

ESP32 MQTT & MQTT Box Control ESP32 build LED on or off

 ESP32 MQTT & MQTT Box  Control ESP32 build LED on or off

系統圖


MQTT Box 設定的畫面

const char *mqtt_server = "broker.mqtt-dashboard.com";
const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
const char *topic1 = "alex9ufo/ESP32/LED_output";
const char *topic2 = "alex9ufo/ESP32/LED_status";







ESP32 Arduino 程式

#include <WiFi.h>
#include <PubSubClient.h>

// Replace the next variables with your SSID/Password combination
//const char* ssid = "XXXXXXXXX";
//const char* password = "XXXXXXXXX";
const char* ssid = "alex9ufo"; // Enter your Wi-Fi name
const char* password = "alex9981";  // Enter Wi-Fi password


// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "broker.mqtt-dashboard.com";
const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;


WiFiClient espClient;
PubSubClient client(espClient);
char msg[50];
const char *topic1 = "alex9ufo/ESP32/LED_output";
const char *topic2 = "alex9ufo/ESP32/LED_status";

// LED Pin
#define BUILTIN_LED 2
String json = "";     //client.publish("alex9ufo/led/led_status",
char jsonChar1[20];
bool Send = false;  //true

//宣告任務Task1
TaskHandle_t Task1;
//===========================================================
//任務1副程式Task1_senddata
void Task1_senddata(void * pvParameters ) {
  //無窮迴圈
  for (;;) {
   
  if (client.connected()) {        
    if (Send) {
      // Convert JSON string to character array
      json.toCharArray(jsonChar1, json.length()+1);
      Serial.print("Publish message: ");
      Serial.println(json);
      // Publish JSON character array to MQTT topic
      client.publish(topic2,jsonChar1); //"alex9ufo/esp32/led_status";
    }
      Send = false;    
  }
  else
  {
    if (WiFi.status() != WL_CONNECTED)  {
      Serial.println("Reconnecting to WiFi...");
      WiFi.disconnect();
       WiFi.reconnect();
    }
  }

  //Task1休息,delay(X)不可省略
  delay(1000);
  }
}
//==========================================
void setup() {
  Serial.begin(115200);
  // default settings
  delay(500);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "esp32-client-";
    client_id += String(WiFi.macAddress());
    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 HiveMQ MQTT broker (broker.mqtt-dashboard.com) connected");
    } else {
        Serial.print("Failed with state ");
        Serial.print(client.state());
        delay(2000);
    }
  }

  // Publish and subscribe
  client.subscribe(topic1);

  pinMode(BUILTIN_LED, OUTPUT);


  //在核心0啟動任務1
  xTaskCreatePinnedToCore(
  Task1_senddata, /*任務實際對應的Function*/
    "Task1",        /*任務名稱*/
    10000,          /*堆疊空間*/
    NULL,           /*無輸入值*/
    0,              /*優先序0*/
    &Task1,         /*對應的任務變數位址*/
    0);             /*指定在核心0執行 */

}
//==========================================
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("ESP32 WiFi connected to ");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//==========================================
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
 
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
  // Changes the output state according to the message
  if (String(topic) == "alex9ufo/ESP32/LED_output")
  {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(BUILTIN_LED, HIGH);
      json ="LED ON";
      Send = true ;
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(BUILTIN_LED, LOW);
      json ="LED OFF";
      Send = true ;
    }
   
  }

}
//==========================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe(topic1);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//==========================================
void loop()
{
  if (!client.connected()) {
    reconnect();
    Serial.print(" client not connected  reconnect ");
    delay(200);
  }
  client.loop();

}
//=====================================================

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...