2023年7月8日 星期六

ESP32 MQTT – Publish and Subscribe with Arduino IDE

 ESP32 MQTT – Publish and Subscribe with Arduino IDE

參考來源 https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

















[{"id":"f0d37edca8bd827a","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"濕度","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"65","seg2":"75","className":"","x":370,"y":440,"wires":[]},{"id":"2858a2ae8ebe4d8f","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":140,"y":80,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"9e48ae5668dd1d79","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"off","payloadType":"str","topic":"","topicType":"str","x":140,"y":120,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"f20d6295bed43e34","type":"mqtt out","z":"17c01e65ea7d6deb","name":"Control LED","topic":"alex9ufo/esp32/output","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":390,"y":180,"wires":[]},{"id":"7451665529bc4d94","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開關反向","tooltip":"","color":"blue","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","topicType":"str","x":160,"y":160,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"88929da799604451","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開5秒鐘","tooltip":"","color":"purple","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","topicType":"str","x":150,"y":240,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"1848f7d50b01e54d","type":"comment","z":"17c01e65ea7d6deb","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":270,"y":280,"wires":[]},{"id":"9861fa8e41cac265","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"yellow","bgcolor":"","className":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","topicType":"str","x":140,"y":200,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"4411678fdec67d84","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":400,"y":240,"wires":[]},{"id":"9610c96e24aa9818","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":120,"wires":[]},{"id":"b9d0a81d2ded2e3a","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","voice":"en-US","always":"","x":380,"y":320,"wires":[]},{"id":"8d3c364c24da2ae4","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Humidity","topic":"alex9ufo/esp32/humidity","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":160,"y":460,"wires":[["f0d37edca8bd827a","b9d0a81d2ded2e3a","4136d882ef1c9ca1"]]},{"id":"c9459b13380fcebf","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Temperature","topic":"alex9ufo/esp32/temperature","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":170,"y":380,"wires":[["1c1b88400941a7c1","b9d0a81d2ded2e3a","54c0f79e889b0aac"]]},{"id":"1c1b88400941a7c1","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"溫度","label":"℃","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"26","seg2":"50","className":"","x":370,"y":360,"wires":[]},{"id":"61b5589a2c26df1d","type":"mqtt in","z":"17c01e65ea7d6deb","name":"LED Status","topic":"alex9ufo/Esp32/output_status","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":150,"y":40,"wires":[["050db70fc3c0868a"]]},{"id":"050db70fc3c0868a","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"ESP32發行到MQTT的LED狀態","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":40,"wires":[]},{"id":"54c0f79e889b0aac","type":"debug","z":"17c01e65ea7d6deb","name":"debug 91","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":380,"y":400,"wires":[]},{"id":"4136d882ef1c9ca1","type":"debug","z":"17c01e65ea7d6deb","name":"debug 92","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":380,"y":480,"wires":[]},{"id":"d783cb980c3979fc","type":"ui_group","name":"Demo","tab":"0449b3b1fea99d52","order":1,"disp":true,"width":"6","collapse":false},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"Storing IOT Data ","tab":"eeb8e179.a47a4","order":1,"disp":true,"width":"6","collapse":true},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"0449b3b1fea99d52","type":"ui_tab","name":"Demo","icon":"dashboard","disabled":false,"hidden":false},{"id":"eeb8e179.a47a4","type":"ui_tab","name":"eWeLink","icon":"dashboard","disabled":false,"hidden":false}]

Installing the PubSubClient Library

The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT (basically allows your ESP32 to talk with Node-RED).

  1. Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get pubsubclient-master folder
  3. Rename your folder from pubsubclient-master to pubsubclient
  4. Move the pubsubclient folder to your Arduino IDE installation libraries folder
  5. Then, re-open your Arduino IDE

The library comes with a number of example sketches. See File >Examples > PubSubClient within the Arduino IDE software.



/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/
#include <WiFiManager.h>         // https://github.com/tzapu/WiFiManager
//#include <WiFiClientSecure.h>

#include <PubSubClient.h>
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 27     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment the type of sensor in use:
//#define DHTTYPE    DHT11     // DHT 11
#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "broker.mqtt-dashboard.com";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
String json = "";    
char jsonChar1[100];  //client.publish("alex9ufo/Esp32/temperature"
char jsonChar2[100];  //client.publish("alex9ufo/Esp32/humidity"

// LED Pin
const int ledPin = 2;   //Build in LED
//======================================================
void autoconnect() {
  // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  // it is a good practice to make sure your code sets wifi mode how you want it.

  // put your setup code here, to run once:
  delay(1000);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  //===================================================  
  // WiFiManager
  // Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
 
  // Uncomment and run it once, if you want to erase all the stored information
  //wifiManager.resetSettings();
 
  // set custom ip for portal
  //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  // fetches ssid and pass from eeprom and tries to connect
  // if it does not connect it starts an access point with the specified name
  // here  "AutoConnectAP"
  // and goes into a blocking loop awaiting configuration
  //=================================================
  Serial.println("Configuring your Mobile WiFi to esp32ap...");
  Serial.println("Configuring another WiFi SSID,PWD...");
  //===================================================  
  wifiManager.autoConnect("AutoConnectAP");
  // or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();
 
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");

  Serial.println("Configuring ESP32...");
 
}

//================================================
void setup() {
  Serial.begin(115200);
  //================================================
  autoconnect();
   //================================================================
  //espClient.setInsecure();//ESP32核心 1.0.6以上  
  // 會遇到「Connection Failed」的問題,主要是因為ESP32的1.0.6的核心會強迫使用SSL認證,
  //此時可以先透過在Setup()內加上「client.setInsecure();」語法來解決
  //================================================================
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
  // default settings
  dht.begin();
  Serial.println(F("DHTxx Unified Sensor Example"));
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.println(F("Temperature Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
  Serial.println(F("------------------------------------"));
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println(F("Humidity Sensor"));
  Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("%"));
  Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("%"));
  Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("%"));
  Serial.println(F("------------------------------------"));
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;
  pinMode(ledPin, OUTPUT);
}

//================================================
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/output") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin, LOW);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin, HIGH);
    }
  }
}
//================================================
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("alex9ufo/esp32/output");
    } 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();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 15000) {
    lastMsg = now;
    dht.begin();
    // Delay between measurements.
    delay(delayMS);
    // Get temperature event and print its value.
    sensors_event_t event;
    // Temperature in Celsius
    dht.temperature().getEvent(&event);
    if (isnan(event.temperature)) {
      Serial.println(F("Error reading temperature!"));
    }
    else {
      Serial.print(F("Temperature: "));
      Serial.print(event.temperature);
      Serial.println(F("°C"));
         
      String json1 =String(event.temperature);
      // Convert JSON string to character array
      json1.toCharArray(jsonChar1, json1.length()+1);
      client.publish("alex9ufo/esp32/temperature", jsonChar1);
    }
 
      // Get humidity event and print its value.
    dht.humidity().getEvent(&event);
    if (isnan(event.relative_humidity)) {
      Serial.println(F("Error reading humidity!"));
    }
    else {
      Serial.print(F("Humidity: "));
      Serial.print(event.relative_humidity);
      Serial.println(F("%"));

      String json2=String(event.relative_humidity);  
      // Convert the value to a char array
      json2.toCharArray(jsonChar2, json2.length()+1);
      client.publish("alex9ufo/esp32/humidity", jsonChar2);
    }  
  }
}

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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