#include <WiFi.h>
#include <stdlib.h>
#include "WiFiClientSecure.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <ArduinoJson.h>
#define WLAN_SSID "xxx"
#define WLAN_PASS "xxx"
//#define WLAN_SSID "xxx"
//#define WLAN_PASS "xxx"
#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_0/ctl");
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());
}
void loop() {
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!"));
}
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
标签:laser,esp32,mqtt,测试通过,MQTT,println,Serial,define From: https://www.cnblogs.com/aker-whale/p/17616179.html