Hi All,
I wrote this sketch:
#include <PubSubClient.h>
#include <Ethernet.h>
IPAddress mqtt_ip(192, 168, 1, 61);
IPAddress client_ip(192, 168, 1, 35);
IPAddress dns_gw_ip(192, 168, 1, 1);
byte mac[] = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }; //physical mac address
const char* mqttUser = "XXXX";
const char* mqttPassword = "XXXXX";
EthernetClient espClient;
PubSubClient client(espClient);
const char *REC = "rec46/onoff";
//FUNZIONE CHE RICEVE I MESSAGGI MQTT
void callback(char* topic, byte* payload, unsigned int length) {
String response;
String topicStr = topic;
for (int i = 0; i < length; i++) {response += (char)payload[i]; }
Serial.print("Message arrived [");
Serial.print(topicStr);
Serial.print("] ");
Serial.println(response);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("arduinonanorec46",mqttUser, mqttPassword,"rec46/will", 0, false, "offline")) {
Serial.println("connected");
client.subscribe(REC); //comando rec
} else {
Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
delay(100);
Serial.println("Starting Ethernet...");
Ethernet.begin(mac,client_ip);
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
client.setServer(mqtt_ip, 1883);
client.setCallback(callback);// Initialize the callback routine
delay(1000);
}
void loop()
{
if (Ethernet.linkStatus() == LinkON) {if (!client.connected()) { reconnect(); }}
else {Serial.println("Ethernet link is down. Attempting to reconnect...");
Ethernet.begin(mac,client_ip);
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
delay(5000);
}
client.loop();
delay(500);
}
the objective is to ensure that the card must always be connected to the ethernet network and to the mqtt broker.
I found the MQTT reconnection in various examples, but the ethernet reconnection is done by IA....
Can I have suggestions if there are errors?