@@ -66,6 +66,10 @@ void WebSocketsClient::begin(const char *host, uint16_t port, const char * url,
66
66
_client.plainAuthorization = " " ;
67
67
_client.isSocketIO = false ;
68
68
69
+ _client.lastPing = 0 ;
70
+ _client.pongReceived = false ;
71
+ _client.pongTimeoutCount = 0 ;
72
+
69
73
#ifdef ESP8266
70
74
randomSeed (RANDOM_REG32);
71
75
#else
@@ -170,6 +174,12 @@ void WebSocketsClient::loop(void) {
170
174
}
171
175
} else {
172
176
handleClientData ();
177
+
178
+ if (_client.status == WSC_CONNECTED){
179
+ handleHBPing ();
180
+ handleHBTimeout (&_client);
181
+ }
182
+
173
183
}
174
184
}
175
185
#endif
@@ -243,7 +253,10 @@ bool WebSocketsClient::sendBIN(const uint8_t * payload, size_t length) {
243
253
*/
244
254
bool WebSocketsClient::sendPing (uint8_t * payload, size_t length) {
245
255
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;
247
260
}
248
261
return false ;
249
262
}
@@ -715,7 +728,7 @@ void WebSocketsClient::connectedCb() {
715
728
}
716
729
717
730
void 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);
719
732
}
720
733
721
734
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
@@ -761,3 +774,36 @@ void WebSocketsClient::asyncConnect() {
761
774
}
762
775
763
776
#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