Hello! So i have a problem with my NodeMcu board. I have setup a mosquitto mqtt broker on my PC (it is connected through a ethernet cable if that matters), that has the local ip 192.168.1.4. I use a conf file that has listener 1883 and allow_anonymous true so i allow all connections. I also have a OneWire DS18B20 sensor, but that is not an issue, it works fine. I have setup my NodeMcu to connect to Wi-Fi (on the same network), and using the PubSubClient library i try to connect to my broker to send the data from the one-wire sensor to it. Here is my code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Wi-Fi credentials
const char* ssid = "my_ssid";
const char* password = "my_password";
// MQTT broker details
const char* mqtt_server = "192.168.1.4";
const int mqtt_port = 1883;
// OneWire bus
const int oneWireBus = 4;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
sensors.begin();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
sensors.requestTemperatures();
float temperatureC = sensors.getTempCByIndex(0);
Serial.print("Temperature: ");
Serial.println(temperatureC);
char tempStr[8];
dtostrf(temperatureC, 1, 2, tempStr);
client.publish("home/temperature", tempStr);
delay(5000); // Delay between readings
}
But when i run it it always gives me "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds". It connects to Wi-Fi, gives me the ip (192.168.1.3) but still it fails to connect to the broker. I have setup a port forward in my router config to send it all from 1883 to my PC. I am really stuck here, any help would be very much appreciated!
Thanks in advance!