upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/main/cvm_server.c
diff options
context:
space:
mode:
Diffstat (limited to 'main/cvm_server.c')
-rw-r--r--main/cvm_server.c49
1 files changed, 37 insertions, 12 deletions
diff --git a/main/cvm_server.c b/main/cvm_server.c
index dd04047..644738b 100644
--- a/main/cvm_server.c
+++ b/main/cvm_server.c
@@ -30,6 +30,9 @@ static void publish_announcements_via_ws(esp_tls_t *tls);
30#define CVM_WS_BUF_SIZE 8192 30#define CVM_WS_BUF_SIZE 8192
31#define CVM_MAX_RESPONSE_SIZE 4096 31#define CVM_MAX_RESPONSE_SIZE 4096
32#define CVM_RECONNECT_DELAY_MS 5000 32#define CVM_RECONNECT_DELAY_MS 5000
33#define CVM_WS_READ_TIMEOUT_MS 1000
34#define CVM_WS_PING_INTERVAL_S 30
35#define CVM_WS_MAX_CONSECUTIVE_TIMEOUTS 65
33 36
34static char *parse_ws_text_frame(const uint8_t *buf, int len) 37static char *parse_ws_text_frame(const uint8_t *buf, int len)
35{ 38{
@@ -553,25 +556,47 @@ static void cvm_relay_task(void *arg)
553 return; 556 return;
554 } 557 }
555 558
559 int64_t last_ping_time = (int64_t)esp_timer_get_time() / 1000000;
560 int consecutive_timeouts = 0;
561
556 while (g_running) { 562 while (g_running) {
557 int rlen = esp_tls_conn_read(tls, buf, CVM_WS_BUF_SIZE - 1); 563 int rlen = esp_tls_conn_read(tls, buf, CVM_WS_BUF_SIZE - 1);
558 if (rlen < 0) { 564 if (rlen < 0) {
559 ESP_LOGW(TAG, "Read error on %s (rlen=%d)", relay_url, rlen); 565 consecutive_timeouts++;
560 break; 566 if (consecutive_timeouts >= CVM_WS_MAX_CONSECUTIVE_TIMEOUTS) {
561 } 567 ESP_LOGW(TAG, "Read timeout on %s (%d consecutive)", relay_url, consecutive_timeouts);
562 if (rlen == 0) { 568 break;
569 }
570 } else if (rlen == 0) {
571 ESP_LOGW(TAG, "Connection closed by %s", relay_url);
563 break; 572 break;
564 } 573 } else {
565 574 consecutive_timeouts = 0;
566 if ((buf[0] & 0x0F) == 0x01) { 575 if ((buf[0] & 0x0F) == 0x01) {
567 char *text = parse_ws_text_frame(buf, rlen); 576 char *text = parse_ws_text_frame(buf, rlen);
568 if (text) { 577 if (text) {
569 if (strlen(text) > 0) { 578 if (strlen(text) > 0) {
570 process_relay_message(relay_url, text); 579 process_relay_message(tls, relay_url, text);
580 }
581 free(text);
571 } 582 }
572 free(text); 583 } else if ((buf[0] & 0x0F) == 0x09) {
584 ESP_LOGD(TAG, "Relay ping received, sending pong");
585 uint8_t pong[2] = {0x8A, 0x00};
586 esp_tls_conn_write(tls, pong, 2);
587 } else if ((buf[0] & 0x0F) == 0x08) {
588 ESP_LOGW(TAG, "Relay sent close frame");
589 break;
573 } 590 }
574 } 591 }
592
593 int64_t now = (int64_t)esp_timer_get_time() / 1000000;
594 if (now - last_ping_time >= CVM_WS_PING_INTERVAL_S) {
595 uint8_t ping[2] = {0x89, 0x00};
596 esp_tls_conn_write(tls, ping, 2);
597 last_ping_time = now;
598 ESP_LOGD(TAG, "Sent WS keepalive ping");
599 }
575 } 600 }
576 601
577 free(buf); 602 free(buf);