'MQTT connection through ESP01 8266
I'm trying to establish a connection with my mosquitto server through an ESP01 8266. I installed mosquitto on my computer and started it with brew.
The problem is that the ESP01 doesn't connect to the "localhost:1833" (that should be my mosquitto address). I dont' know what to do, am I missing something?
This line could be the problem? I didn't set a client name on NodeRed -------> if (mqttClient.connect("ESP8266Client"))
ESP sketch:
#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();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
