Compare commits

...

2 Commits

Author SHA1 Message Date
08990a7a93 keepalive is called by mqtt poll
manual keepliave not needed anymore
2025-05-17 15:17:13 +02:00
061a084f1d keepalive mqtt message by loops, not by time
faster during runtime, calculation not needed
2025-05-17 15:06:48 +02:00

View File

@ -35,19 +35,12 @@ struct device {
struct device devices[] = {
{ 0x08, "Heading Speed", {'H', 'D', 'G'}, HEADING_SIM_UP, HEADING_SIM_DOWN, {'S', 'P', 'D'}, AIRSPEED_SIM_UP, AIRSPEED_SIM_DOWN }
};
int numDevices = -1;
int numDevices = -1; // gets calculated in setup()
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char broker[] = "openhab.sugarland.lan";
int port = 1883;
const char topic[] = MQTT_SIM_VALUE_TOPIC;
EthernetClient client;
char localIP[16];
MqttClient mqttClient(client);
unsigned long mqttLastKeepAlive = millis();
void onMqttMessage(int messageSize) {
// // we received a message, print out the topic and contents
@ -99,6 +92,7 @@ void setup() {
while (1);
}
// print your local IP address:
char localIP[16];
sprintf(localIP, "%d.%d.%d.%d", Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]);
Serial.println(localIP);
@ -106,7 +100,7 @@ void setup() {
mqttClient.setUsernamePassword(MQTT_USER, MQTT_PASS);
// MQTT connection
if (!mqttClient.connect(broker, port)) {
if (!mqttClient.connect(MQTT_SERVER, MQTT_PORT)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
@ -118,8 +112,8 @@ void setup() {
// subscribe to MQTT topic
mqttClient.onMessage(onMqttMessage);
mqttClient.subscribe(topic);
mqttClient.setKeepAliveInterval(10 * 1000L);
mqttClient.subscribe(MQTT_SIM_VALUE_TOPIC);
mqttClient.setKeepAliveInterval(MQTT_KEEPALIVE_INTERVAL_MS);
// start I2C
Wire.begin();
@ -174,10 +168,7 @@ void loop() {
}
}
// transmit MQTT keepalive message if MQTT_KEEPALIVE_INTERVAL_MS is reached
// or millis() is wrapping to 0
if (mqttLastKeepAlive + MQTT_KEEPALIVE_INTERVAL_MS < millis() || mqttLastKeepAlive > millis()) {
sendMqttMessage(MQTT_SIM_DEVICE_TOPIC, 1, localIP);
mqttLastKeepAlive = millis();
}
// call poll() regularly to allow the library to receive MQTT messages and
// send MQTT keep alives which avoids being disconnected by the broker
mqttClient.poll();
}