keepalive mqtt message by loops, not by time

faster during runtime, calculation not needed
This commit is contained in:
2025-05-17 15:06:48 +02:00
parent 226f2a3e3f
commit 061a084f1d

View File

@ -19,7 +19,7 @@
#define MQTT_SIM_LOG_TOPIC "/xplane/meta/log" #define MQTT_SIM_LOG_TOPIC "/xplane/meta/log"
#define MQTT_SIM_VALUE_TOPIC "/xplane/rref/#" #define MQTT_SIM_VALUE_TOPIC "/xplane/rref/#"
#define MQTT_KEEPALIVE_INTERVAL_MS 15000 #define MQTT_KEEPALIVE_INTERVAL_LOOPS 60000
struct device { struct device {
byte address; // I2C address of device byte address; // I2C address of device
@ -47,7 +47,7 @@ const char topic[] = MQTT_SIM_VALUE_TOPIC;
EthernetClient client; EthernetClient client;
char localIP[16]; char localIP[16];
MqttClient mqttClient(client); MqttClient mqttClient(client);
unsigned long mqttLastKeepAlive = millis(); int mqttLastKeepAlive = 0;
void onMqttMessage(int messageSize) { void onMqttMessage(int messageSize) {
// // we received a message, print out the topic and contents // // we received a message, print out the topic and contents
@ -174,10 +174,11 @@ void loop() {
} }
} }
// transmit MQTT keepalive message if MQTT_KEEPALIVE_INTERVAL_MS is reached // transmit MQTT keepalive message every MQTT_KEEPALIVE_INTERVAL_LOOPS times
// or millis() is wrapping to 0 // running the loop
if (mqttLastKeepAlive + MQTT_KEEPALIVE_INTERVAL_MS < millis() || mqttLastKeepAlive > millis()) { mqttLastKeepAlive++;
if (mqttLastKeepAlive >= MQTT_KEEPALIVE_INTERVAL_LOOPS) {
sendMqttMessage(MQTT_SIM_DEVICE_TOPIC, 1, localIP); sendMqttMessage(MQTT_SIM_DEVICE_TOPIC, 1, localIP);
mqttLastKeepAlive = millis(); mqttLastKeepAlive = 0;
} }
} }