diff --git a/src/modules/ESP8266.cpp b/src/modules/ESP8266.cpp index 489f7d09..a942b3f0 100644 --- a/src/modules/ESP8266.cpp +++ b/src/modules/ESP8266.cpp @@ -582,6 +582,38 @@ uint8_t ESP8266::MqttUnsubscribe(const char* topicFilter) { return(ERR_RESPONSE_MALFORMED); } +uint8_t ESP8266::MqttPing() { + // build the PINGREQ packet + uint8_t packet[2]; + + // fixed header + packet[0] = (MQTT_PINGREQ << 4) | 0b0000; + packet[1] = 0x00; + + // send MQTT packet + uint8_t state = send(packet, 2); + if(state != ERR_NONE) { + return(state); + } + + // get the response length (MQTT PINGRESP response has to be 2 bytes long) + uint16_t numBytes = getNumBytes(); + if(numBytes != 2) { + return(ERR_RESPONSE_MALFORMED_AT); + } + + // read the response + uint8_t* response = new uint8_t[numBytes]; + receive(response, numBytes); + if((response[0] == MQTT_PINGRESP << 4) && (response[1] == 0)) { + delete[] response; + return(ERR_NONE); + } + + delete[] response; + return(ERR_RESPONSE_MALFORMED); +} + uint8_t ESP8266::send(const char* data) { // build AT command char lenStr[8]; diff --git a/src/modules/ESP8266.h b/src/modules/ESP8266.h index ed4e74e6..c252d3b9 100644 --- a/src/modules/ESP8266.h +++ b/src/modules/ESP8266.h @@ -48,6 +48,7 @@ class ESP8266 { uint8_t MqttPublish(const char* topic, const char* message); uint8_t MqttSubscribe(const char* topicFilter); uint8_t MqttUnsubscribe(const char* topicFilter); + uint8_t MqttPing(); // Transport layer methods uint8_t openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive = 0); @@ -64,7 +65,7 @@ class ESP8266 { size_t MqttEncodeLength(uint32_t len, uint8_t* encoded); uint32_t MqttDecodeLength(uint8_t* encoded); - uint16_t getNumBytes(uint32_t timeout = 10000); + uint16_t getNumBytes(uint32_t timeout = 10000, size_t minBytes = 10); }; #endif