Skip to content

Commit

Permalink
Merge pull request #14 from uschindler/dev/fix_keep_alive
Browse files Browse the repository at this point in the history
Fix keepalive handling (various issues in original issue tracker)
  • Loading branch information
imbeacon authored Dec 9, 2024
2 parents 57f481f + 7000770 commit a1ef1c4
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/PubSubClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass
write(MQTTCONNECT,this->send_buffer,length-MQTT_MAX_HEADER_SIZE);

lastInActivity = lastOutActivity = millis();
pingOutstanding = false;

while (!_client->available()) {
unsigned long t = millis();
Expand All @@ -269,7 +270,6 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass
if (len == 4) {
if (receive_buffer[3] == 0) {
lastInActivity = millis();
pingOutstanding = false;
_state = MQTT_CONNECTED;
return true;
} else {
Expand Down Expand Up @@ -427,7 +427,9 @@ boolean PubSubClient::loop_read() {
if (_client->connected()) {
receive_buffer[0] = MQTTPINGRESP;
receive_buffer[1] = 0;
_client->write(receive_buffer,2);
if (_client->write(receive_buffer,2) != 0) {
lastOutActivity = t;
}
}
break;
}
Expand All @@ -450,15 +452,16 @@ boolean PubSubClient::loop() {
if (pingOutstanding) {
this->_state = MQTT_CONNECTION_TIMEOUT;
_client->stop();
pingOutstanding = false;
return false;
} else {
receive_buffer[0] = MQTTPINGREQ;
receive_buffer[1] = 0;
if (_client->write(receive_buffer,2) != 0) {
lastOutActivity = t;
lastInActivity = t;
pingOutstanding = true;
}
pingOutstanding = true;
}
}
return true;
Expand Down Expand Up @@ -626,6 +629,9 @@ boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
result = (rc == bytesToWrite);
bytesRemaining -= rc;
writeBuf += rc;
if (rc != 0) {
lastOutActivity = millis();
}
}
return result;
#else
Expand Down Expand Up @@ -698,6 +704,7 @@ void PubSubClient::disconnect() {
_client->flush();
_client->stop();
lastInActivity = lastOutActivity = millis();
pingOutstanding = false;
}

uint16_t PubSubClient::writeString(const char* string, uint8_t* buf, uint16_t pos) {
Expand Down

0 comments on commit a1ef1c4

Please sign in to comment.