@@ -66,6 +66,10 @@ void WebSocketsClient::begin(const char *host, uint16_t port, const char * url,
6666 _client.plainAuthorization = " " ;
6767 _client.isSocketIO = false ;
6868
69+ _client.lastPing = 0 ;
70+ _client.pongReceived = false ;
71+ _client.pongTimeoutCount = 0 ;
72+
6973#ifdef ESP8266
7074 randomSeed (RANDOM_REG32);
7175#else
@@ -170,6 +174,12 @@ void WebSocketsClient::loop(void) {
170174 }
171175 } else {
172176 handleClientData ();
177+
178+ if (_client.status == WSC_CONNECTED){
179+ handleHBPing ();
180+ handleHBTimeout (&_client);
181+ }
182+
173183 }
174184}
175185#endif
@@ -243,7 +253,10 @@ bool WebSocketsClient::sendBIN(const uint8_t * payload, size_t length) {
243253 */
244254bool WebSocketsClient::sendPing (uint8_t * payload, size_t length) {
245255 if (clientIsConnected (&_client)) {
246- return sendFrame (&_client, WSop_ping, payload, length);
256+ bool sent = sendFrame (&_client, WSop_ping, payload, length);
257+ if (sent)
258+ _client.lastPing = millis ();
259+ return sent;
247260 }
248261 return false ;
249262}
@@ -715,7 +728,7 @@ void WebSocketsClient::connectedCb() {
715728}
716729
717730void WebSocketsClient::connectFailedCb () {
718- DEBUG_WEBSOCKETS (" [WS-Client] connection to %s:%u Faild \n " , _host.c_str (), _port);
731+ DEBUG_WEBSOCKETS (" [WS-Client] connection to %s:%u Failed \n " , _host.c_str (), _port);
719732}
720733
721734#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
@@ -761,3 +774,36 @@ void WebSocketsClient::asyncConnect() {
761774}
762775
763776#endif
777+
778+ /* *
779+ * send heartbeat ping to server in set intervals
780+ */
781+ void WebSocketsClient::handleHBPing (){
782+ if (_client.pingInterval == 0 ) return ;
783+ uint32_t pi = millis () - _client.lastPing ;
784+ if (pi > _client.pingInterval ){
785+ DEBUG_WEBSOCKETS (" [WS-Client] sending HB ping\n " );
786+ if (sendPing ()) {
787+ _client.lastPing = millis ();
788+ _client.pongReceived = false ;
789+ }
790+ }
791+
792+ }
793+
794+ /* *
795+ * enable ping/pong heartbeat process
796+ * @param pingInterval uint32_t how often ping will be sent
797+ * @param pongTimeout uint32_t millis after which pong should timout if not received
798+ * @param disconnectTimeoutCount uint8_t how many timeouts before disconnect, 0=> do not disconnect
799+ */
800+ void WebSocketsClient::enableHeartbeat (uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount){
801+ WebSockets::enableHeartbeat (&_client, pingInterval, pongTimeout, disconnectTimeoutCount);
802+ }
803+
804+ /* *
805+ * disable ping/pong heartbeat process
806+ */
807+ void WebSocketsClient::disableHeartbeat (){
808+ _client.pingInterval = 0 ;
809+ }
0 commit comments