Hi,
I am working on a big sketch so I created multiple tabs en libraries to keep the main sketch as clean as possible. So far so good.
I am at the point to add mqtt.
I added the pubsubclient library and started with the nonblocking example sketch and changed is a bit for esp32 with WiFi.
when I add this to void setup and void loop it works, but I would like to clean it up.
I tried to make a function in a new tab, but as soon as I take some part out of the main tab I get the error message " 'client' was not declared in this scope in the new tab.
When I put the same new function in the main tab it works. I did not had this problem before with other libraries.
Any ideas how I can put the reconnect part in a new tab.
In best case I can make a state machine to add more control and debug possibilities.
Thanks ![]()
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "your_ssid";
const char* password = "your_password";
const char* mqtt_server = "your_IPadress";
WiFiClient espClient;
PubSubClient client(espClient);
char msg[50];
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect("arduinoClient")) {
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
}
return client.connected();
}
void setup()
{
client.setServer(mqtt_server, 1883);
connect_WiFi();
}
void loop()
{
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected
client.loop();
}
}