源自於 https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
WOKWI程式
#include <Adafruit_Sensor.h>
#include <DHT_U.h>
#include <WiFi.h>
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST "broker.mqtt-dashboard.com"
//#define MQTT_HOST "broker.hivemq.com"
#define MQTT_HOST "test.mosquitto.org" // Broker address
//#define MQTT_HOST "broker.mqttgo.io"
#define MQTT_PORT 1883
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
#define LEDPIN 12
#define DHT22PIN 13
#define DHTTYPE DHT22 // DHT 11
DHT_Unified dht(DHT22PIN, DHTTYPE);
float temp, hum;
const char *SubTopic1 = "alex9ufo/esp32/output";
const char *PubTopic2 = "alex9ufo/esp32/temperature";
const char *PubTopic3 = "alex9ufo/esp32/humidity";
//================================================================
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
//================================================================
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
//================================================================
void WiFiEvent(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_WIFI_READY:
Serial.println("WiFi ready");
break;
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("WiFi STA starting");
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("WiFi STA connected");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
Serial.println("WiFi lost IP");
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#endif
default:
break;
}
}
//================================================================
void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub1 = mqttClient.subscribe(SubTopic1 , 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub1);
//uint16_t packetIdSub2 = mqttClient.subscribe(SubTopic2, 2);
//Serial.print("Subscribing at QoS 2, packetId: ");
//Serial.println(packetIdSub2);
}
//================================================================
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}
//================================================================
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
//================================================================
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
//================================================================
void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
//================================================================
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
String messageTemp;
for (int i = 0; i < len; i++) {
Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}
if (strcmp(topic, SubTopic1) == 0) {
// If the relay is on turn it off (and vice-versa)
Serial.println();
Serial.println(messageTemp);
if (messageTemp == "on") {
digitalWrite(LEDPIN,LOW);
Serial.print("LED ON");
}
if (messageTemp == "off") {
digitalWrite(LEDPIN,HIGH);
Serial.print("LED OFF");
}
}
}
//================================================================
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(LEDPIN, OUTPUT);
Serial.println("Hello, ESP32!");
dht.begin();
// Get temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
dht.humidity().getSensor(&sensor);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage); //callback
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
//mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
connectToWifi();
}
//================================================================
void loop()
{
// publish message
static uint32_t prev_ms = millis();
if (millis() > prev_ms + 5500) {
prev_ms = millis();
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
}
else {
Serial.print(F("Temperature: "));
temp = event.temperature;
Serial.print(temp);
Serial.println(F("°C"));
}
// 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: "));
hum = event.relative_humidity;
Serial.print(hum);
Serial.println(F("%"));
}
String temp1 = String(temp,1); // 2nd param is decimal digits
String hum1 = String(hum,1); // 2nd param is decimal digits
uint16_t packetIdPub1 = mqttClient.publish(PubTopic2, 1, true, temp1.c_str());
Serial.printf("Temperature Published", PubTopic2, packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic3, 1, true, hum1.c_str());
Serial.printf("Temperature Published", PubTopic3, packetIdPub2);
}
}
Node-Red程式
[{"id":"edcdf66afba74e02","type":"function","z":"298903d582b0a8f0","name":"on or off --> true false","func":"var temp1=msg.payload;\n\nif (temp1==\"on\")\n msg.payload=true;\n\nif (temp1 == \"off\")\n msg.payload = false;\n\nreturn msg;","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":340,"y":80,"wires":[["31960506d7539aba"]]},{"id":"898751db073163c0","type":"mqtt out","z":"298903d582b0a8f0","name":"LED","topic":"alex9ufo/esp32/output","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"21957383cfd8785a","x":330,"y":160,"wires":[]},{"id":"d1c14c01b813d786","type":"ui_button","z":"298903d582b0a8f0","name":"","group":"be83571bbd73adfb","order":1,"width":3,"height":1,"passthru":false,"label":"ON","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"on","payloadType":"str","topic":"topic","topicType":"msg","x":110,"y":80,"wires":[["edcdf66afba74e02","898751db073163c0"]]},{"id":"e8955355fa5a65e8","type":"ui_button","z":"298903d582b0a8f0","name":"","group":"be83571bbd73adfb","order":2,"width":3,"height":1,"passthru":false,"label":"OFF","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"off","payloadType":"str","topic":"topic","topicType":"msg","x":110,"y":160,"wires":[["898751db073163c0","edcdf66afba74e02"]]},{"id":"31960506d7539aba","type":"ui_led","z":"298903d582b0a8f0","order":3,"group":"be83571bbd73adfb","width":6,"height":3,"label":"","labelPlacement":"left","labelAlignment":"left","colorForValue":[{"color":"#ff0000","value":"false","valueType":"bool"},{"color":"#008000","value":"true","valueType":"bool"}],"allowColorForValueInMessage":false,"shape":"circle","showGlow":true,"name":"","x":510,"y":80,"wires":[]},{"id":"c67a0254ea2f709c","type":"mqtt in","z":"298903d582b0a8f0","name":"溫度","topic":"alex9ufo/esp32/temperature","qos":"2","datatype":"auto-detect","broker":"21957383cfd8785a","nl":false,"rap":true,"rh":0,"inputs":0,"x":130,"y":260,"wires":[["4a1fb2e7c81430fb"]]},{"id":"85c9e5e4119902ff","type":"ui_gauge","z":"298903d582b0a8f0","name":"","group":"674d62f755096bd3","order":2,"width":0,"height":0,"gtype":"gage","title":"gauge","label":"units","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"40","seg2":"65","className":"","x":350,"y":320,"wires":[]},{"id":"c02324fad71be86b","type":"mqtt in","z":"298903d582b0a8f0","name":"濕度","topic":"alex9ufo/esp32/humidity","qos":"2","datatype":"auto-detect","broker":"21957383cfd8785a","nl":false,"rap":true,"rh":0,"inputs":0,"x":130,"y":320,"wires":[["85c9e5e4119902ff"]]},{"id":"4a1fb2e7c81430fb","type":"ui_chart","z":"298903d582b0a8f0","name":"","group":"674d62f755096bd3","order":1,"width":0,"height":0,"label":"溫度","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"-40","ymax":"80","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"60","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"className":"","x":350,"y":260,"wires":[[]]},{"id":"21957383cfd8785a","type":"mqtt-broker","name":"test.mosquitto.org","broker":"test.mosquitto.org","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closeRetain":"false","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"be83571bbd73adfb","type":"ui_group","name":"LED","tab":"3ebc826f2071e289","order":4,"disp":true,"width":"6","collapse":false,"className":""},{"id":"674d62f755096bd3","type":"ui_group","name":"溫溼度","tab":"3ebc826f2071e289","order":2,"disp":true,"width":"6","collapse":false,"className":""},{"id":"3ebc826f2071e289","type":"ui_tab","name":"ESP32 MQTT","icon":"dashboard","disabled":false,"hidden":false}]
沒有留言:
張貼留言