Getting Started with MQTT on ESP32 實驗
參考來源 https://randomnerdtutorials.com/micropython-mqtt-esp32-esp8266/
[{"id":"6a82eae8e458e7cb","type":"ui_button","z":"972e6260e6a3d8bd","name":"","group":"6c9116b.b62d4e8","order":47,"width":"3","height":"1","passthru":false,"label":"publish : hello","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"hello","payloadType":"str","topic":"topic","topicType":"msg","x":240,"y":420,"wires":[["afa8db051fe63d6f","4a2d4166521cfd63"]]},{"id":"afa8db051fe63d6f","type":"mqtt out","z":"972e6260e6a3d8bd","name":"hello","topic":"alex9ufo/esp32/hello","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":430,"y":400,"wires":[]},{"id":"70bf58b349b6433f","type":"mqtt in","z":"972e6260e6a3d8bd","name":"notification","topic":"alex9ufo/esp32/notification","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":220,"y":500,"wires":[["b01ece174947bed5","2e38f776bb20ffc8","9f1d4a98cbfbb761"]]},{"id":"b01ece174947bed5","type":"ui_text","z":"972e6260e6a3d8bd","group":"6c9116b.b62d4e8","order":48,"width":"6","height":"1","name":"","label":"subscribe","format":"<font color={{red}}>{{msg.payload}}","layout":"row-right","className":"","x":640,"y":500,"wires":[]},{"id":"4a2d4166521cfd63","type":"debug","z":"972e6260e6a3d8bd","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":430,"y":460,"wires":[]},{"id":"2e38f776bb20ffc8","type":"debug","z":"972e6260e6a3d8bd","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":410,"y":540,"wires":[]},{"id":"9f1d4a98cbfbb761","type":"delay","z":"972e6260e6a3d8bd","name":"","pauseType":"delay","timeout":"5","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"allowrate":false,"outputs":1,"x":420,"y":580,"wires":[["1bc3de990cbcb7ff"]]},{"id":"1bc3de990cbcb7ff","type":"function","z":"972e6260e6a3d8bd","name":"function 83","func":"msg.payload=''\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":570,"y":580,"wires":[["b01ece174947bed5"]]},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"2023 Storing IOT Data ","tab":"6249073d2714bfd4","order":1,"disp":true,"width":"16","collapse":true,"className":""},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"compatmode":false,"protocolVersion":4,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6249073d2714bfd4","type":"ui_tab","name":"RFID Home","icon":"dashboard","disabled":false,"hidden":false}]
//Wifi + MQTT
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi
//const char *ssid = "alex9ufo"; // Enter your Wi-Fi name
//const char *password = "alex9981"; // Enter Wi-Fi password
const char *ssid = "TOTOLINK_A3002MU"; // Enter your Wi-Fi name
const char *password = "24063173"; // Enter Wi-Fi password
// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";
const char *topic1 = "alex9ufo/esp32/hello"; //subscribe
const char *topic2 = "alex9ufo/esp32/notification"; //publish
const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
bool Send = false; //true
String json = "";
char jsonChar1[50]; //client.publish("alex9ufo/Esp32/notification")
//宣告任務Task1
TaskHandle_t Task1;
// Wifi reconnect
unsigned long previousMillis = 0;
unsigned long interval = 30000;
//===========================================================
//任務1副程式Task1_senddata
void Task1_senddata(void * pvParameters ) {
//無窮迴圈
for (;;)
{
Serial.println("Process Publish message");
if (Send) //偵測上傳旗標是否為true
{ //received hello
json="ESP received hello message";
json.toCharArray(jsonChar1, json.length()+1);
if (client.connected())
{
Serial.print("Publish message: ");
Serial.println(json);
// Publish JSON character array to MQTT topic
client.publish(topic2,jsonChar1); //topic2 = "alex9ufo/esp32/notification"; //publish
Send=false; //設定旗標為false
}
else
{
Serial.print("MQTT not connected ");
}
}
else
{
Serial.println("Timed out waiting for a message");
}
//Task1休息,delay(X)不可省略
delay(1000);
}
}
//===========================================================
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("esp32-client-")) {
Serial.println("connected");
// Subscribe
client.subscribe("alex9ufo/esp32/hello");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Reconnecting to WiFi...");
WiFi.disconnect();
WiFi.reconnect();
}
}
}
}
//===========================================================
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message: ");
String message;
for (int i = 0; i < length; i++) {
message += (char) payload[i]; // Convert *byte to string
}
Serial.print(message);
if (message == "hello") {
Send=true;
}
Serial.println();
Serial.println("-----------------------");
}
//===========================================================
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
//===========================================================
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
delay(1000); // Delay for stability
initWiFi();
Serial.println("Connected to the WiFi network");
// Connecting to an MQTT broker
client.setServer(mqtt_broker, 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); //topic1 = "alex9ufo/esp32/hello";subscribe
//在核心0啟動任務1
xTaskCreatePinnedToCore(
Task1_senddata, /*任務實際對應的Function*/
"Task1", /*任務名稱*/
10000, /*堆疊空間*/
NULL, /*無輸入值*/
0, /*優先序0*/
&Task1, /*對應的任務變數位址*/
0); /*指定在核心0執行 */
}
//===========================================================
void loop() {
if (!client.connected()) {
reconnect();
Serial.print(" client not connected reconnect ");
delay(200);
}
client.loop();
unsigned long currentMillis = millis();
// if WiFi is down, try reconnecting
if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
Serial.print(millis());
Serial.println("Reconnecting to WiFi...");
WiFi.disconnect();
WiFi.reconnect();
previousMillis = currentMillis;
client.setCallback(callback);
}
}
//===========================================================
沒有留言:
張貼留言