esp32 mqtt 局域网 通信 测试通过
#include <WiFi.h>
#include <stdlib.h>
#include "WiFiClientSecure.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <ArduinoJson.h>
#define WLAN_SSID "AMmakeF2"
#define WLAN_PASS "AMmake001"
//#define WLAN_SSID "AMmake F1"
//#define WLAN_PASS "AMmake11"
#define MQTT_SERVER "192.168.2.44"
#define MQTT_PORT 1883
#define MQTT_USERNAME ""
#define MQTT_PASSWORD ""
WiFiClient esp32Client;
Adafruit_MQTT_Client mqtt_client(&esp32Client, MQTT_SERVER, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD);
Adafruit_MQTT_Publish Publish_laser_state = Adafruit_MQTT_Publish(&mqtt_client, "AM/laser_0/state");
Adafruit_MQTT_Subscribe Subscribe_laser_ctl(&mqtt_client, "AM/laser/ctl");
StaticJsonDocument<200> doc;
void setup() {
Serial.begin(115200);
delay(10);
Serial.println(F("This esp gonna "));
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
delay(500);
WiFi.begin(WLAN_SSID, WLAN_PASS);
delay(500);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected !");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
mqtt_client.subscribe(&Subscribe_laser_ctl);
}
void loop() {
// mqtt_client.processPackets(10);
mqtt_client.ping();
char laser_state_sw[10] = "laser_on";
MQTT_connect();
if (! Publish_laser_state.publish(laser_state_sw)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("mqtt work OK!"));
}
// 检查是否有新的订阅消息
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt_client.readSubscription(100))) {
if (subscription == &Subscribe_laser_ctl) {
// 获取最新的订阅消息
char message[100];
strcpy(message, (char *)Subscribe_laser_ctl.lastread);
// 处理接收到的消息
Serial.print("Received message: ");
Serial.println(message);
deserializeJson(doc, message);
int laser0 = doc["laser0"];
int laser1 = doc["laser1"];
int laser2 = doc["laser2"];
int laser3 = doc["laser3"];
int laser4 = doc["laser4"];
int laser5 = doc["laser5"];
Serial.print("laser0: ");
Serial.println(laser0);
Serial.print("laser1: ");
Serial.println(laser1);
Serial.print("laser2: ");
Serial.println(laser2);
Serial.print("laser3: ");
Serial.println(laser3);
Serial.print("laser4: ");
Serial.println(laser4);
Serial.print("laser5: ");
Serial.println(laser5);
}
}
// delay(1000);
}
void MQTT_connect() {
int8_t ret;
if (mqtt_client.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt_client.connect()) != 0) {
Serial.println(mqtt_client.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt_client.disconnect();
delay(5000);
retries--;
if (retries == 0) {
ESP.restart();
}
}
Serial.println("MQTT Connected!");
}
注意打开专用网络
在线测试界面:链接 MQTT X Web