我正在尝试与我的m建立联系通过ESP01 8266连接蚊子服务器。我在电脑上安装了mosquito,然后用Brew启动它。
问题是ESP01没有连接到"localhost:1833";(这应该是我的蚊子地址)。我不知道该怎么做,我错过了什么吗?
这一行可能是问题所在?我没有在NodeRed上设置客户端名称------->如果(mqttClient.connect("ESP8266Client")
ESP草图:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "WifiNetworkname";
const char* password = "password";
const char* mqttServer = "localhost:1833";
const int mqttPort = 1883;
#define PUB_GPIO2_STATUS "state"
#define SUB_GPIO2_ACTION "state"
#define GPIO2_LED 2
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void loop() {
mqttClient.loop();
}
void initWifiStation() {
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
Serial.print("nConnecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println(String("nConnected to the WiFi network (") + ssid + ")" );
}
void initMQTTClient() {
// Connecting to MQTT server
mqttClient.setServer(mqttServer, mqttPort);
while (!mqttClient.connected()) {
Serial.println(String("Connecting to MQTT (") + mqttServer + ")...");
if (mqttClient.connect("ESP8266Client")) {
Serial.println("MQTT client connected");
} else {
Serial.print("nFailed with state ");
Serial.println(mqttClient.state());
if (WiFi.status() != WL_CONNECTED) {
initWifiStation();
}
delay(2000);
}
}
// Declare Pub/Sub topics
mqttClient.publish(PUB_GPIO2_STATUS, "Hello");
mqttClient.subscribe(SUB_GPIO2_ACTION);
}
void setup() {
Serial.begin(115200);
// GPIO2 is set OUTPUT
pinMode(GPIO2_LED, OUTPUT);
initWifiStation();
initMQTTClient();
}
Localhost
在您的ESP代码是ESP本身。您正在尝试从ESP连接到ESP。
Localhost
总是指"这台计算机",就像IP地址127.0.0.1一样。
"这computer"从ESP上的代码中看到的是ESP本身,而不是运行MQTT服务器的计算机。
假设语法正确:在const char* mqttServer = "localhost:1833";
行中,您需要输入运行MQTT服务器的计算机的IP地址(或名称),而不是localhost
。我不知道你是否也需要更改端口。