I saw a similar post to this but my problem is probably alot more difficult becaue i already tried the solutions that were proposed there and it didnt work for me. I've been stumped for a bit too long so could any kind soul please lend me some help ;-;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Wifi and MQTT details
const char* ssid = "*********"; // Wifi name
const char* password = "*********"; // Wifi Password
const char* mqttServer = "********"; //ipv4
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to Wifi");
}
if (WiFi.status() == WL_CONNECTED) {
delay(1000);
Serial.println("We are connected :D");
}
client.setServer(mqttServer, 1883);
while (!client.connected()) {
if (client.connect("kookokie")) { // Client ID
Serial.println("Connected to MQTT Broker!");
} else {
Serial.print("failed with state ");
Serial.println(client.state());
delay(2000);
}
}
}
void loop() {
if (client.connected()) {
// If connected to MQTT, publish "online"
client.publish("nodemcu/status", "online");
}
// Wait a bit before publishing again
delay(5000);
}
i've been trying to do a project where i can monitor if a NodeMCU ESP-12E is connected to a power supply or if it has been disconnected by visualising it on a dashboard using node-red.
so basically whenever i try to upload it the serial monitor returns a client.state() value of -2. The board was able to connect to the wifi for sure cuz it returned "We are connected :D".
The MQTT broker i am using (mosquitto), does not have username or password configured, and i was able to update the status displayed on the dashboard using the mosquitto_pub command on the command prompt so im quite sure the broker should be working fine. even the "MQTT in" node on node-red was able to connect to the broker. i also checked and made sure that port 1883 was listening.
FYI i am running the broker off of my personal laptop and i declared in the code that the variable mqttServer = my laptop ipv4 address.
my knowledge in iot is pretty mediocre so i was hoping that maybe the amazing people who are a part of this community could help me cuz ive been stumped on this for like almost a week now.
hopefully i didnt miss out any info haha once again thank you for the help i really need it hahahahahaa ;-;