Hello,
I have an mqtt broker mosquitto running on localhost on my pc.
I have some external testing tools installed that can access my broker through ip 172.18.48.1
and my broker it's working, i can subscribe and publish to it.
Now I am trying to connect an ESP32 board, with the code below:
const char* ssid = "xxxxx";;
const char* password = "xxxxx";
#include <WiFi.h>
#include <PubSubClient.h>
const char* mqtt_server = "172.18.48.1";
const char* topic = "1";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 1000) {
lastMsg = now;
value = analogRead(A0);
if (value > 4000) {
value = 0;
}
else
{
value = 1;
}
snprintf (msg, 50, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
snprintf (msg, 50, "%ld", value);
client.publish(topic, msg);
}
}
I can connect the board to wi fi, but when i try to run to connect to ip
"172.18.48.1", i receive error "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
". When I switch mqtt_server to a public broker like "broker.mqtt-dashboard.com" it works.
I'm sure I'm missing something, I have no knowledge of networking and I assume the problem is somewhere there, but I have no idea what and how to make it work.