我有以下问题:
我想在 Adafruit Huzzah ESP6288 上创建一个 MQTT 客户端,并将 MAC 地址设置为 clientID。
这是我的代码:
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WLAN_SSID "Jupiter"
#define WLAN_PASS "wilano123"
#define SERVER "192.168.178.134"
#define CLIENTID "abcde123456789"
#define SERVERPORT 1883
WiFiClient client;
void MQTT_connect();
Adafruit_MQTT_Client mqtt;
void setup() {
Serial.begin(115200);
delay(10);
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
String mac = WiFi.macAddress();
int length = mac.length() + 1;
char macArray[length];
mac.toCharArray(macArray, length);
mqtt = Adafruit_MQTT_Client(&client, SERVER, SERVERPORT, macArray, "root", "pass");
}
void loop() {
MQTT_connect();
sendTemperature(12.5, "Werkstatt");
String s = WiFi.macAddress();
Serial.println(s);
delay(5000);
}
void sendTemperature(double temperature, String sensorID) {
.....
mqtt.publish("ds18b20",char_array,0);
}
void MQTT_connect() {
int8_t ret;
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
while (1);
}
}
Serial.println("MQTT Connected!");
}
我是 C 新手,我认为不可能初始化Adafruit_MQTT_Client mqtt
变量并将其设置在设置循环中。
希望有人可以提供帮助,所以我可以Adafruit_MQTT_Client
使用 MAC 地址作为 clientID 创建一个。