I am trying to use MQTT data via home LAN on my Arduino Uno device.
Sometimes the client connects on the first try, sometimes it doesn't even connect after an hour. It's completely unpredictable.
Nothing helps: Opening the web site at https://vrm.victronenergy.com/ (the data is updated), via the mobile app; turning off and then on Modbus TCP via remote console doesn't help either.
Neither MQTT-Explorer nor my .NET application will connect.
What could it be?
Next day, the same code works like a charm... :-(
#include <UIPEthernet.h> #include <PubSubClient.h> #include <ArduinoJson.h> // nastavení MAC adresy byte mac[] = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; IPAddress localIP(192, 168, 1, 110); IPAddress mqttIPAddress(192, 168, 1, 111); EthernetClient ethernetClient; PubSubClient mqttClient(ethernetClient); long nextKeepAlive = char* topics = "#"; float batterySOC = 0; float fvePower[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; void setup() { Serial.begin(9600); Ethernet.begin(mac, localIP); Serial.println("Starting... ----------------------------"); Serial.println(Ethernet.localIP()); Serial.println(Ethernet.gatewayIP()); Serial.println(Ethernet.dnsServerIP()); Serial.println(""); mqttClient.setServer(mqttIPAddress, 1883); mqttClient.setCallback(ReceiveMQTT); connectToMQTT(); } void loop() { if (millis() >= nextKeepAlive) { sendKeepAlive(); } mqttClient.loop(); } void connectToMQTT() { Serial.println("Connecting to MQTT broker..."); while (!mqttClient.connect("victronMQTT")) { Serial.println("Connecting to MQTT broker..."); delay(1000); } Serial.println("Connected to MQTT broker."); mqttClient.subscribe(topics); Serial.print("Subscribed to topic: "); Serial.println(topics); nextKeepAlive = millis() + 50000; } void sendKeepAlive() { if (mqttClient.state() == 0) { Serial.println("Sending keepAlive..."); mqttClient.publish("R/d<secretID>/keepalive", ""); nextKeepAlive = millis() + 10000; } else { connectToMQTT(); } } void ReceiveMQTT(char* topic, byte* bytePayload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); String payload = ""; for (int i = 0; i < length; i++) { payload.concat((char)bytePayload[i]); } Serial.println(payload); ProcessMessage(topic, payload); } void ProcessMessage(String topic, String payload) { if (topic == "N/<secretID>/system/0/Dc/Pv/Power") { float value = readJsonValue(payload); int index = (int)((millis() / 60000) % 10); Serial.print("Updating FVE power. Index = "); Serial.print(index); Serial.print("; value = "); Serial.println(value); fvePower[index] = value; } if (topic == "N/<secretID>/battery/512/Soc") { batterySOC = readJsonValue(payload); } } float readJsonValue(String payload) { DynamicJsonDocument doc(1024); deserializeJson(doc, payload); return doc["value"]; }