5#include <ArduinoJson.h>
7#include <esp_http_client.h>
13#ifdef SENSESP_SSL_SUPPORT
14#include <mbedtls/pem.h>
15#include <mbedtls/sha256.h>
16#include <mbedtls/ssl.h>
17#include <mbedtls/x509_crt.h>
26#include "elapsedMillis.h"
27#include "esp_arduino_version.h"
49static const char* kRequestPermission =
"readwrite";
51#ifdef SENSESP_SSL_SUPPORT
53static void sha256_to_hex(
const uint8_t* sha256,
char* hex) {
54 for (
int i = 0; i < 32; i++) {
55 sprintf(hex + (i * 2),
"%02x", sha256[i]);
61static String cert_fingerprint(
const mbedtls_x509_crt* crt) {
63 mbedtls_sha256_context ctx;
64 mbedtls_sha256_init(&ctx);
65 mbedtls_sha256_starts(&ctx, 0);
66 mbedtls_sha256_update(&ctx, crt->raw.p, crt->raw.len);
67 mbedtls_sha256_finish(&ctx, sha256);
68 mbedtls_sha256_free(&ctx);
70 sha256_to_hex(sha256, hex);
75static constexpr size_t kMaxPinCnLen = 64;
80static String cert_common_name(
const mbedtls_x509_crt* crt) {
82 int len = mbedtls_x509_dn_gets(dn,
sizeof(dn), &crt->subject);
86 const char* cn = strstr(dn,
"CN=");
92 for (
size_t i = 0; i < kMaxPinCnLen && cn[i] !=
'\0' && cn[i] !=
','; i++) {
94 if (c >= 0x20 && c < 0x7f && c !=
'"' && c !=
'\\') {
106static String cert_to_pem(
const mbedtls_x509_crt* crt) {
113 constexpr size_t kPemBufSize = 4096;
114 std::unique_ptr<unsigned char[]> pem_buf(
115 new (std::nothrow)
unsigned char[kPemBufSize]);
117 ESP_LOGE(
"SKWSClient",
"TOFU: PEM buffer allocation failed");
121 int r = mbedtls_pem_write_buffer(
122 "-----BEGIN CERTIFICATE-----\n",
"-----END CERTIFICATE-----\n",
123 crt->raw.p, crt->raw.len, pem_buf.get(), kPemBufSize, &olen);
125 ESP_LOGE(
"SKWSClient",
"TOFU: PEM encode failed (-0x%x)", -r);
128 return String(
reinterpret_cast<const char*
>(pem_buf.get()));
136static String cert_dns_sans(
const mbedtls_x509_crt* crt) {
137 std::set<String> names;
138 for (
const mbedtls_x509_sequence* cur = &crt->subject_alt_names;
139 cur !=
nullptr && cur->buf.p !=
nullptr; cur = cur->next) {
140 mbedtls_x509_subject_alternative_name san;
141 memset(&san, 0,
sizeof(san));
142 if (mbedtls_x509_parse_subject_alt_name(&cur->buf, &san) != 0) {
145 if (san.type == MBEDTLS_X509_SAN_DNS_NAME &&
146 san.san.unstructured_name.p !=
nullptr &&
147 san.san.unstructured_name.len > 0) {
148 size_t n = san.san.unstructured_name.len;
154 for (
size_t i = 0; i < n; i++) {
155 char c =
static_cast<char>(san.san.unstructured_name.p[i]);
156 if (c >=
'A' && c <=
'Z') {
157 c =
static_cast<char>(c + (
'a' -
'A'));
163 mbedtls_x509_free_subject_alt_name(&san);
166 for (
const String& s : names) {
167 if (!out.isEmpty()) {
178static int tofu_verify_callback(
void* ctx, mbedtls_x509_crt* crt,
int depth,
180 SKWSClient* client =
static_cast<SKWSClient*
>(ctx);
181 if (client ==
nullptr) {
182 ESP_LOGW(
"SKWSClient",
"TOFU: no client context, allowing connection");
187 if (!client->is_tofu_enabled()) {
196 if (client->has_tofu_ca()) {
198 ESP_LOGE(
"SKWSClient",
"TOFU: certificate failed CA validation (0x%lx)",
199 (
unsigned long)*flags);
200 client->flag_cert_error();
201 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
207 if (depth == 0 && !client->get_tofu_san().isEmpty()) {
208 if (cert_dns_sans(crt) != client->get_tofu_san()) {
209 ESP_LOGE(
"SKWSClient",
"TOFU: leaf identity (SAN) mismatch, rejecting");
210 client->flag_cert_error();
211 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
231 bool is_ca = crt->MBEDTLS_PRIVATE(ca_istrue) != 0;
232 if (is_ca && !client->has_pending_ca()) {
233 String ca_pem = cert_to_pem(crt);
236 if (!ca_pem.isEmpty()) {
237 client->stash_pending_ca(ca_pem, cert_common_name(crt));
245 String leaf_fp = cert_fingerprint(crt);
246 String leaf_san = cert_dns_sans(crt);
248 client->has_tofu_fingerprint() && client->get_tofu_fingerprint() == leaf_fp;
250 client->has_tofu_fingerprint(), leaf_matches, client->has_pending_ca(),
251 !leaf_san.isEmpty());
255 ESP_LOGE(
"SKWSClient",
"TOFU: leaf fingerprint mismatch, rejecting");
256 client->flag_cert_error();
257 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
259 ESP_LOGI(
"SKWSClient",
"TOFU: first use, pinning leaf %s", leaf_fp.c_str());
260 client->stash_pending_leaf(leaf_fp, cert_common_name(crt));
263 ESP_LOGI(
"SKWSClient",
"TOFU: first use, pinning issuing CA (identity %s)",
265 client->set_pending_san(leaf_san);
271 client->clear_pending_tofu();
282static esp_err_t tofu_crt_bundle_attach(
void* conf) {
283 mbedtls_ssl_config* ssl_conf =
static_cast<mbedtls_ssl_config*
>(conf);
286 if (client !=
nullptr && client->is_tofu_enabled() && client->has_tofu_ca()) {
288 static mbedtls_x509_crt pinned_ca;
289 static bool pinned_ca_inited =
false;
290 if (pinned_ca_inited) {
291 mbedtls_x509_crt_free(&pinned_ca);
293 mbedtls_x509_crt_init(&pinned_ca);
294 pinned_ca_inited =
true;
295 const String& pem = client->get_tofu_ca();
296 int r = mbedtls_x509_crt_parse(
297 &pinned_ca,
reinterpret_cast<const unsigned char*
>(pem.c_str()),
300 mbedtls_ssl_conf_ca_chain(ssl_conf, &pinned_ca,
nullptr);
302 ESP_LOGD(
"SKWSClient",
"TOFU: pinned CA installed as trust anchor");
308 ESP_LOGE(
"SKWSClient",
309 "TOFU: stored CA failed to parse (-0x%x); connections will fail "
315 mbedtls_ssl_conf_authmode(ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
318 mbedtls_ssl_conf_verify(ssl_conf, tofu_verify_callback, client);
323static void websocket_event_handler(
void* handler_args,
324 esp_event_base_t base,
325 int32_t event_id,
void* event_data) {
330 static_cast<uint32_t
>(
reinterpret_cast<uintptr_t
>(handler_args)) !=
334 esp_websocket_event_data_t* data = (esp_websocket_event_data_t*)event_data;
336 case WEBSOCKET_EVENT_CONNECTED:
339 case WEBSOCKET_EVENT_DISCONNECTED:
342 case WEBSOCKET_EVENT_DATA:
345 if (data->op_code <= 0x2) {
349 case WEBSOCKET_EVENT_ERROR:
356#ifdef SENSESP_SSL_SUPPORT
366 std::shared_ptr<SKDeltaQueue> sk_delta_queue,
367 const String& server_address, uint16_t server_port,
370 conf_server_address_{server_address},
371 conf_server_port_{server_port},
373 sk_delta_queue_{sk_delta_queue} {
393 ESP_LOGD(__FILENAME__,
"Starting SKWSClient");
406 MDNS.addService(
"signalk-sensesp",
"tcp", 80);
427 return ssl_enabled && handshake_status == kHttpUnauthorized;
439 ESP_LOGW(__FILENAME__,
"Token rejected (%d), requesting new access",
445 ESP_LOGW(__FILENAME__,
"Websocket client error.");
462 ESP_LOGI(__FILENAME__,
"Subscribing to Signal K listeners...");
473 bool output_available =
false;
474 JsonDocument subscription;
475 subscription[
"context"] =
"vessels.self";
480 if (listeners.size() > 0) {
481 output_available =
true;
482 JsonArray subscribe = subscription[
"subscribe"].to<JsonArray>();
490 std::map<String, int> path_period;
491 for (
size_t i = 0; i < listeners.size(); i++) {
492 auto* listener = listeners.at(i);
493 const String& sk_path = listener->get_sk_path();
494 int listen_delay = listener->get_listen_delay();
495 auto it = path_period.find(sk_path);
496 if (it == path_period.end() || listen_delay < it->second) {
497 path_period[sk_path] = listen_delay;
500 for (
const auto& [sk_path, listen_delay] : path_period) {
501 JsonObject subscribe_path = subscribe.add<JsonObject>();
502 subscribe_path[
"path"] = sk_path;
503 subscribe_path[
"period"] = listen_delay;
504 ESP_LOGI(__FILENAME__,
"Adding %s subscription with listen_delay %d\n",
505 sk_path.c_str(), listen_delay);
510 if (output_available &&
514 serializeJson(subscription, json_message);
515 ESP_LOGI(__FILENAME__,
"Subscription JSON message:\n %s",
516 json_message.c_str());
517 int result = esp_websocket_client_send_text(
518 client_.load(), json_message.c_str(), json_message.length(),
521 ESP_LOGE(__FILENAME__,
"Subscription send failed (result=%d)", result);
535 constexpr size_t kMaxWsMessageSize = 4096;
536 if (length > kMaxWsMessageSize) {
537 ESP_LOGW(__FILENAME__,
"WebSocket message too large (%u bytes), dropping",
541 std::unique_ptr<char[]> buf(
new char[length + 1]);
542 memcpy(buf.get(), payload, length);
545#ifdef SIGNALK_PRINT_RCV_DELTA
546 ESP_LOGD(__FILENAME__,
"Websocket payload received: %s", buf.get());
549 JsonDocument message;
550 auto error = deserializeJson(message, buf.get());
553 if (message[
"updates"].is<JsonVariant>()) {
557 if (message[
"put"].is<JsonVariant>()) {
562 if (message[
"requestId"].is<JsonVariant>() &&
563 !message[
"put"].is<JsonVariant>()) {
567 ESP_LOGE(__FILENAME__,
"deserializeJson error: %s", error.c_str());
580 JsonArray updates = message[
"updates"];
586 bool has_meta_listener =
false;
589 if (listener->wants_meta()) {
590 has_meta_listener =
true;
597 for (
size_t i = 0; i < updates.size(); i++) {
598 JsonObject update = updates[i];
600 JsonArray values = update[
"values"];
602 for (
size_t vi = 0; vi < values.size(); vi++) {
608 ru.
doc.set(values[vi]);
618 if (has_meta_listener) {
619 JsonArray meta_entries = update[
"meta"];
620 for (
size_t mi = 0; mi < meta_entries.size(); mi++) {
621 JsonObject entry = meta_entries[mi];
622 if (entry[
"path"].isNull() || entry[
"value"].isNull())
continue;
649 const bool is_meta = update.is_meta;
650 const size_t cap = is_meta ? kMaxReceivedMeta : kMaxReceivedValues;
652 size_t kind_count = 0;
654 if (ru.is_meta == is_meta) kind_count++;
657 while (kind_count >= cap) {
661 if (it->is_meta == is_meta) {
667 ESP_LOGW(__FILENAME__,
"Dropping oldest received %s update (queue full)",
668 is_meta ?
"meta" :
"value");
684 const std::vector<SKPutListener*>& put_listeners =
697 String path = ru.
doc[
"path"].as<String>();
701 std::shared_ptr<const JsonDocument> meta_doc =
702 std::make_shared<const JsonDocument>(std::move(ru.
doc));
703 for (
size_t i = 0; i < listeners.size(); i++) {
711 const char* path = ru.
doc[
"path"];
712 JsonObject value = ru.
doc.as<JsonObject>();
714 for (
size_t i = 0; i < listeners.size(); i++) {
721 for (
size_t i = 0; i < put_listeners.size(); i++) {
745 JsonArray puts = message[
"put"];
746 bool all_matched =
true;
747 for (
size_t i = 0; i < puts.size(); i++) {
748 JsonObject value = puts[i];
749 const char* path = value[
"path"];
750 bool matched =
false;
753 const std::vector<SKPutListener*>& listeners =
755 for (
size_t j = 0; j < listeners.size(); j++) {
776 JsonDocument put_response;
777 put_response[
"requestId"] = message[
"requestId"];
779 put_response[
"state"] =
"COMPLETED";
780 put_response[
"statusCode"] = 200;
782 put_response[
"state"] =
"FAILED";
783 put_response[
"statusCode"] = 405;
785 String response_text;
786 serializeJson(put_response, response_text);
787 int result = esp_websocket_client_send_text(
788 client_.load(), response_text.c_str(), response_text.length(),
791 ESP_LOGE(__FILENAME__,
"PUT response send failed (result=%d)", result);
805 int result = esp_websocket_client_send_text(
808 ESP_LOGE(__FILENAME__,
"sendTXT failed (result=%d)", result);
814 uint16_t& server_port) {
817 int num = MDNS.queryService(
"signalk-wss",
"tcp");
821 ESP_LOGI(__FILENAME__,
"Found Signal K server via mDNS (signalk-wss)");
824 num = MDNS.queryService(
"signalk-ws",
"tcp");
831 ESP_LOGI(__FILENAME__,
"Found Signal K server via mDNS (signalk-ws)");
834#if ESP_ARDUINO_VERSION_MAJOR < 3
835 server_address = MDNS.IP(0).toString();
837 server_address = MDNS.address(0).toString();
839 server_port = MDNS.port(0);
840 ESP_LOGI(__FILENAME__,
"Found server %s (port %d)", server_address.c_str(),
846static esp_err_t detect_ssl_event_handler(esp_http_client_event_t* evt) {
847 if (evt->event_id == HTTP_EVENT_ON_HEADER) {
849 if (strcasecmp(evt->header_key,
"Location") == 0) {
850 String* location =
static_cast<String*
>(evt->user_data);
851 *location = evt->header_value;
863 ESP_LOGD(__FILENAME__,
"Probing for SSL redirect at %s", url.c_str());
867 esp_http_client_config_t config = {};
868 config.url = url.c_str();
869 config.disable_auto_redirect =
true;
870 config.timeout_ms = 10000;
871 config.event_handler = detect_ssl_event_handler;
872 config.user_data = &location;
874 esp_http_client_handle_t client = esp_http_client_init(&config);
875 if (client ==
nullptr) {
876 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
880 esp_err_t err = esp_http_client_perform(client);
881 int status_code = esp_http_client_get_status_code(client);
882 esp_http_client_cleanup(client);
885 ESP_LOGD(__FILENAME__,
"HTTP request failed: %s", esp_err_to_name(err));
889 if ((status_code == 301 || status_code == 302 ||
890 status_code == 307 || status_code == 308) &&
891 location.startsWith(
"https://")) {
892 ESP_LOGI(__FILENAME__,
"SSL redirect detected, enabling HTTPS/WSS");
919 if (
client_.load() !=
nullptr) {
940 if (!provisioner || !provisioner->is_connected()) {
941 ESP_LOGI(__FILENAME__,
942 "Network is not yet up. SignalK client connection will be "
943 "initiated when the link comes up.");
956 ESP_LOGE(__FILENAME__,
"connect worker spawn failed");
965 self->auth_job_running_.store(
false);
966 vTaskDelete(
nullptr);
970 ESP_LOGI(__FILENAME__,
"Initiating websocket connection with server...");
974 ESP_LOGE(__FILENAME__,
975 "No Signal K server found in network when using mDNS service!");
977 ESP_LOGI(__FILENAME__,
978 "Signal K server has been found at address %s:%d by mDNS.",
987 ESP_LOGD(__FILENAME__,
988 "Websocket is connecting to Signal K server on address %s:%d",
997 ESP_LOGD(__FILENAME__,
998 "Websocket is not connecting to Signal K server because host and "
999 "port are not defined.");
1004 if (this->
polling_href_.length() > 0 && this->polling_href_.startsWith(
"/")) {
1013 ESP_LOGD(__FILENAME__,
"No prior authorization token present.");
1019#ifdef SENSESP_SSL_SUPPORT
1041#ifndef SENSESP_SSL_SUPPORT
1043 const uint16_t server_port) {
1044 String url = String(
"http://") + server_address +
":" + server_port +
1045 "/signalk/v1/stream";
1046 ESP_LOGD(__FILENAME__,
"Testing token with url %s", url.c_str());
1048 const String full_token = String(
"Bearer ") +
auth_token_;
1049 ESP_LOGD(__FILENAME__,
"Authorization: %.8s...[redacted]", full_token.c_str());
1051 esp_http_client_config_t config = {};
1052 config.url = url.c_str();
1053 config.timeout_ms = 10000;
1055 esp_http_client_handle_t client = esp_http_client_init(&config);
1056 if (client ==
nullptr) {
1057 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1062 esp_http_client_set_header(client,
"Authorization", full_token.c_str());
1065 esp_err_t err = esp_http_client_open(client, 0);
1066 if (err != ESP_OK) {
1067 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s",
1068 esp_err_to_name(err));
1069 esp_http_client_cleanup(client);
1074 int content_length = esp_http_client_fetch_headers(client);
1075 int http_code = esp_http_client_get_status_code(client);
1077 ESP_LOGD(__FILENAME__,
"Testing resulted in http status %d", http_code);
1081 if (content_length > 0 && content_length < 4096) {
1082 char* buffer =
new char[content_length + 1];
1083 int read_len = esp_http_client_read(client, buffer, content_length);
1084 buffer[read_len > 0 ? read_len : 0] =
'\0';
1085 payload = String(buffer);
1091 while ((read_len = esp_http_client_read(client, buffer,
1092 sizeof(buffer) - 1)) > 0) {
1093 buffer[read_len] =
'\0';
1094 payload += String(buffer);
1095 if (payload.length() > 4096)
break;
1099 esp_http_client_close(client);
1100 esp_http_client_cleanup(client);
1102 if (payload.length() > 0) {
1103 ESP_LOGD(__FILENAME__,
"Returned payload (%d bytes): %s", payload.length(),
1107 if (http_code == 426) {
1110 ESP_LOGD(__FILENAME__,
"Attempting to connect to Signal K Websocket...");
1111 this->
connect_ws(server_address, server_port);
1112 }
else if (http_code == kHttpUnauthorized) {
1115 ESP_LOGW(__FILENAME__,
"Token rejected (401), requesting new access");
1119 }
else if (http_code > 0) {
1122 ESP_LOGE(__FILENAME__,
"HTTP request failed with code %d", http_code);
1129 const uint16_t server_port) {
1130 ESP_LOGD(__FILENAME__,
"Sending access request (client_id=%s, ssl=%d)",
1141 doc[
"description"] =
1143 doc[
"permissions"] = kRequestPermission;
1144 String json_req =
"";
1145 serializeJson(doc, json_req);
1147 ESP_LOGD(__FILENAME__,
"Access request: %s", json_req.c_str());
1149 String protocol =
ssl_enabled_ ?
"https://" :
"http://";
1150 String url = protocol + server_address +
":" + server_port +
1151 "/signalk/v1/access/requests";
1152 ESP_LOGD(__FILENAME__,
"Access request url: %s", url.c_str());
1154 esp_http_client_config_t config = {};
1155 config.url = url.c_str();
1156 config.method = HTTP_METHOD_POST;
1157 config.timeout_ms = 10000;
1158#ifdef SENSESP_SSL_SUPPORT
1160 config.crt_bundle_attach = tofu_crt_bundle_attach;
1161 config.skip_cert_common_name_check =
true;
1165 esp_http_client_handle_t client = esp_http_client_init(&config);
1166 if (client ==
nullptr) {
1167 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1173 esp_http_client_set_header(client,
"Content-Type",
"application/json");
1176 esp_err_t err = esp_http_client_open(client, json_req.length());
1177 if (err != ESP_OK) {
1178 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s", esp_err_to_name(err));
1179 esp_http_client_cleanup(client);
1184 int write_len = esp_http_client_write(client, json_req.c_str(), json_req.length());
1185 if (write_len < 0 || write_len != (
int)json_req.length()) {
1186 ESP_LOGE(__FILENAME__,
"Failed to write request body (wrote %d of %d bytes)",
1187 write_len, json_req.length());
1188 esp_http_client_close(client);
1189 esp_http_client_cleanup(client);
1194 int content_length = esp_http_client_fetch_headers(client);
1195 int http_code = esp_http_client_get_status_code(client);
1197 ESP_LOGD(__FILENAME__,
"HTTP response: code=%d, content_length=%d", http_code, content_length);
1203 while ((read_len = esp_http_client_read(client, buffer,
sizeof(buffer) - 1)) > 0) {
1204 buffer[read_len] =
'\0';
1205 payload += String(buffer);
1206 if (payload.length() > 4096)
break;
1208 ESP_LOGD(__FILENAME__,
"Response payload (%d bytes): %s",
1209 payload.length(), payload.c_str());
1211 esp_http_client_close(client);
1212 esp_http_client_cleanup(client);
1215 deserializeJson(doc, payload.c_str());
1216 String state = doc[
"state"].is<
const char*>() ? doc[
"state"].as<String>() :
"";
1217 String href = doc[
"href"].is<
const char*>() ? doc[
"href"].as<String>() :
"";
1218 String message = doc[
"message"].is<
const char*>() ? doc[
"message"].as<String>() :
"";
1220 ESP_LOGD(__FILENAME__,
"Access request response: http=%d, state=%s, href=%s",
1221 http_code, state.c_str(), href.c_str());
1222 if (message.length() > 0) {
1223 ESP_LOGI(__FILENAME__,
"Server message: %s", message.c_str());
1228 if (http_code == 400 && href.length() > 0 && href.startsWith(
"/")) {
1229 ESP_LOGI(__FILENAME__,
"Existing request found, will poll href: %s", href.c_str());
1238 if (http_code == 202 && href.length() > 0 && href.startsWith(
"/")) {
1247 if (http_code == 404) {
1248 ESP_LOGI(__FILENAME__,
1249 "Server security disabled (404 on access request) — connecting "
1252 this->
connect_ws(server_address, server_port);
1257 ESP_LOGW(__FILENAME__,
"Cannot handle response: http=%d, state=%s", http_code, state.c_str());
1262 const uint16_t server_port,
1263 const String href) {
1264 ESP_LOGD(__FILENAME__,
"Polling SK Server for authentication token");
1266 String protocol =
ssl_enabled_ ?
"https://" :
"http://";
1267 String url = protocol + server_address +
":" + server_port + href;
1269 esp_http_client_config_t config = {};
1270 config.url = url.c_str();
1271 config.timeout_ms = 10000;
1272#ifdef SENSESP_SSL_SUPPORT
1274 config.crt_bundle_attach = tofu_crt_bundle_attach;
1275 config.skip_cert_common_name_check =
true;
1279 esp_http_client_handle_t client = esp_http_client_init(&config);
1280 if (client ==
nullptr) {
1281 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1287 esp_err_t err = esp_http_client_open(client, 0);
1288 if (err != ESP_OK) {
1289 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s", esp_err_to_name(err));
1290 esp_http_client_cleanup(client);
1295 int content_length = esp_http_client_fetch_headers(client);
1296 int http_code = esp_http_client_get_status_code(client);
1300 if (content_length > 0 && content_length < 4096) {
1301 char* buffer =
new char[content_length + 1];
1302 int read_len = esp_http_client_read(client, buffer, content_length);
1303 buffer[read_len > 0 ? read_len : 0] =
'\0';
1304 payload = String(buffer);
1310 while ((read_len = esp_http_client_read(client, buffer,
sizeof(buffer) - 1)) > 0) {
1311 buffer[read_len] =
'\0';
1312 payload += String(buffer);
1313 if (payload.length() > 4096)
break;
1320 ESP_LOGD(__FILENAME__,
"Poll response: http=%d, %d bytes", http_code,
1321 static_cast<int>(payload.length()));
1323 esp_http_client_close(client);
1324 esp_http_client_cleanup(client);
1326 if (http_code == 200 || http_code == 202) {
1328 auto error = deserializeJson(doc, payload.c_str());
1330 ESP_LOGW(__FILENAME__,
"WARNING: Could not deserialize http payload.");
1331 ESP_LOGW(__FILENAME__,
"DeserializationError: %s", error.c_str());
1335 String state = doc[
"state"];
1336 ESP_LOGD(__FILENAME__,
"%s", state.c_str());
1337 if (state ==
"PENDING") {
1341 if (state ==
"COMPLETED") {
1342 JsonObject access_req = doc[
"accessRequest"];
1343 String permission = access_req[
"permission"];
1348 if (permission ==
"DENIED") {
1349 ESP_LOGW(__FILENAME__,
"Permission denied");
1354 if (permission ==
"APPROVED") {
1355 ESP_LOGI(__FILENAME__,
"Permission granted");
1356 String token = access_req[
"token"];
1359 this->
connect_ws(server_address, server_port);
1364 if (http_code == 404 || http_code == 500) {
1369 ESP_LOGD(__FILENAME__,
1370 "Got %d polling access request — clearing stale href.",
1378 ESP_LOGW(__FILENAME__,
1379 "Can't handle response %d to pending access request.\n",
1395 ESP_LOGW(__FILENAME__,
"connect_ws: prior client not reaped; deferring");
1409 String path =
"/signalk/v1/stream?subscribe=none";
1411 String url = protocol +
"://" + host +
":" + String(port) + path;
1413 ESP_LOGD(__FILENAME__,
"Connecting WebSocket to %s", url.c_str());
1418 auth_header = String(
"Authorization: Bearer ") +
auth_token_ +
"\r\n";
1422 esp_websocket_client_config_t config = {};
1423 config.uri = url.c_str();
1426 if (auth_header.length() > 0) {
1427 config.headers = auth_header.c_str();
1430#ifdef SENSESP_SSL_SUPPORT
1434 config.crt_bundle_attach = tofu_crt_bundle_attach;
1435 config.skip_cert_common_name_check =
true;
1439 esp_websocket_client_handle_t h = esp_websocket_client_init(&config);
1441 ESP_LOGE(__FILENAME__,
"Failed to initialize WebSocket client");
1450 esp_websocket_register_events(
1451 h, WEBSOCKET_EVENT_ANY, websocket_event_handler,
1452 reinterpret_cast<void*
>(
1456 esp_err_t err = esp_websocket_client_start(h);
1457 if (err != ESP_OK) {
1458 ESP_LOGE(__FILENAME__,
"Failed to start WebSocket client: %s",
1459 esp_err_to_name(err));
1462 esp_websocket_client_destroy(h);
1467 ESP_LOGD(__FILENAME__,
"WebSocket client started, waiting for connection...");
1475struct WsTeardownArg {
1482 auto* a =
static_cast<WsTeardownArg*
>(arg);
1486 esp_websocket_client_stop(a->handle);
1487 esp_websocket_client_destroy(a->handle);
1488 a->self->teardown_in_progress_.store(
false);
1490 vTaskDelete(
nullptr);
1494 if (old ==
nullptr) {
1497 auto* arg =
new WsTeardownArg{old,
this};
1499 nullptr) == pdPASS) {
1511 ESP_LOGW(__FILENAME__,
"teardown task spawn failed; will retry next cycle");
1517 esp_websocket_client_handle_t old =
client_.exchange(
nullptr);
1518 if (old ==
nullptr) {
1538 std::vector<String> deltas;
1541 for (
const auto& delta : deltas) {
1553 uint32_t now = millis();
1556 ESP_LOGW(__FILENAME__,
1557 "Delta too large (%u B > %u buffer); dropped to keep the "
1558 "connection alive -- raise SENSESP_SK_WS_BUFFER_SIZE",
1559 (
unsigned)delta.length(),
1566 int send_result = esp_websocket_client_send_text(
1568 if (send_result < 0) {
1583 ESP_LOGW(__FILENAME__,
1584 "Delta send incomplete (result=%d); dropping rest of batch",
1618 if (config[
"sk_address"].is<String>()) {
1621 if (config[
"sk_port"].is<int>()) {
1624 if (config[
"use_mdns"].is<bool>()) {
1625 this->
use_mdns_ = config[
"use_mdns"].as<
bool>();
1627 if (config[
"token"].is<String>()) {
1630 if (config[
"client_id"].is<String>()) {
1631 this->
client_id_ = config[
"client_id"].as<String>();
1633 if (config[
"polling_href"].is<String>()) {
1634 String href = config[
"polling_href"].as<String>();
1639 if (config[
"ssl_enabled"].is<bool>()) {
1642 if (config[
"tofu_enabled"].is<bool>()) {
1648 if (config[
"tofu_fingerprint"].is<String>()) {
1651 if (config[
"tofu_ca_pem"].is<String>()) {
1652 this->
tofu_ca_pem_ = config[
"tofu_ca_pem"].as<String>();
1654 if (config[
"tofu_san"].is<String>()) {
1655 this->
tofu_san_ = config[
"tofu_san"].as<String>();
1657 if (config[
"tofu_pin_cn"].is<String>()) {
1658 this->
tofu_pin_cn_ = config[
"tofu_pin_cn"].as<String>();
1660 if (config[
"tofu_pin_is_ca"].is<bool>()) {
1663 if (config[
"send_meta_enabled"].is<bool>()) {
1679 return "Authorizing with SignalK";
1683 return "Connecting";
1685 return "Disconnected";
1687 return "Certificate verification failed";
virtual bool load() override
Load and populate the object from a persistent storage.
virtual bool save() override
Save the object to a persistent storage.
virtual void set(const C &input) override final
int attach(std::function< void()> observer)
Attach an observer callback.
An Obervable class that listens for Signal K stream deltas and notifies any observers of value change...
static bool take_semaphore(uint64_t timeout_ms=0)
static void release_semaphore()
virtual void parse_value(const JsonObject &json)
virtual bool matches(const String &path) const
virtual void parse_meta(const std::shared_ptr< const JsonDocument > &meta_doc)
static const std::vector< SKListener * > & get_listeners()
virtual bool wants_meta() const
An Obervable class that listens for Signal K PUT requests coming over the websocket connection and no...
static const std::vector< SKPutListener * > & get_listeners()
virtual void parse_value(const JsonObject &put)=0
static void handle_response(JsonDocument &response)
The websocket connection to the Signal K server.
void commit_pending_tofu()
Persist a stashed anchor after a successful (authenticated) connection. Called from on_connected().
void poll_access_request(const String host, const uint16_t port, const String href)
SKWSClient(const String &config_path, std::shared_ptr< SKDeltaQueue > sk_delta_queue, const String &server_address, uint16_t server_port, bool use_mdns=true)
void schedule_reconnect()
void on_receive_delta(uint8_t *payload, size_t length)
Called when the websocket receives a delta.
void process_received_updates()
Loop through the received updates and process them.
std::atomic< esp_websocket_client_handle_t > pending_teardown_
bool is_connect_due() const
std::atomic< bool > auth_job_running_
void connect_ws(const String &host, const uint16_t port)
Integrator< int, int > delta_tx_count_producer_
TaskQueueProducer< SKWSConnectionState > connection_state_
SKWSConnectionState get_connection_state()
std::atomic< bool > teardown_in_progress_
void on_receive_put(JsonDocument &message)
Called when a PUT event is received.
uint32_t client_generation() const
Generation tag of the currently-valid client. The event handler compares the generation it was regist...
void release_received_updates_semaphore()
void run_connect_attempt()
The (blocking) connect attempt — mDNS resolve, SSL detect, and the access-request / poll / connect_ws...
void send_access_request(const String host, const uint16_t port)
std::atomic< uint32_t > client_generation_
void on_error(int handshake_status)
Integrator< int, int > delta_rx_count_producer_
void clear_pending_tofu()
std::list< ReceivedUpdate > received_updates_
virtual bool to_json(JsonObject &root) override final
void detach_teardown()
Hand client_ to a detached one-shot task that stops+destroys it, so the blocking teardown never runs ...
void enqueue_received_update(ReceivedUpdate &&update)
Push a received delta entry onto the queue, enforcing a per-kind budget so a metadata burst (one meta...
void sendTXT(String &payload)
Send some processed data to the websocket.
uint32_t last_oversize_log_ms_
millis() timestamp of the last oversize-delta-drop warning, used to rate-limit it when a device keeps...
bool get_mdns_service(String &server_address, uint16_t &server_port)
std::atomic< esp_websocket_client_handle_t > client_
void on_disconnected()
Called when the websocket connection is disconnected.
void reap_async(esp_websocket_client_handle_t old)
Spawn the detached reaper for old; on spawn failure (OOM) stash it in pending_teardown_ for a later r...
void subscribe_listeners()
Subscribes the SK delta paths to the websocket.
void on_receive_updates(JsonDocument &message)
Called when a delta update is received.
uint16_t conf_server_port_
void test_token(const String host, const uint16_t port)
void set_connection_state(SKWSConnectionState state)
bool take_received_updates_semaphore(unsigned long int timeout_ms=0)
virtual bool from_json(const JsonObject &config) override final
String get_connection_status()
Get a String representation of the current connection state.
static void connect_worker(void *arg)
TaskQueueProducer< int > delta_tx_tick_producer_
Emits the number of deltas sent since last report.
static void teardown_task(void *arg)
Body of the detached teardown task (stop+destroy+self-delete).
void reset_reconnect_interval()
std::shared_ptr< SKDeltaQueue > sk_delta_queue_
String conf_server_address_
void restart()
Drop the current connection (detached, non-blocking teardown) and let the reconnect path rebuild it.
void on_connected()
Called when the websocket connection is established.
static std::shared_ptr< SensESPApp > get()
Get the singleton instance of the SensESPApp.
static String get_hostname()
Get the current hostname.
virtual void set(const T &value) override
virtual const T & get() const
void emit(const SKWSConnectionState &new_value)
std::enable_if< std::is_base_of< ValueConsumer< typenameVConsumer::input_type >, VConsumer >::value &&std::is_convertible< T, typenameVConsumer::input_type >::value, std::shared_ptr< VConsumer > >::type connect_to(std::shared_ptr< VConsumer > consumer)
Connect a producer to a transform with a different input type.
std::shared_ptr< reactesp::EventLoop > event_loop()
String generate_uuid4()
Generate a random UUIDv4 string.
constexpr int kWsClientTaskStackSize
bool sk_delta_exceeds_ws_buffer(size_t delta_length, size_t buffer_size)
True if a delta is too large to hand to esp_websocket_client as a single tx chunk,...
bool should_clear_token_on_status(bool ssl_enabled, int handshake_status)
Called when the websocket connection encounters an error.
constexpr TickType_t kWsSendTimeoutTicks
constexpr uint32_t kOversizeDropLogIntervalMs
constexpr int kWsTransportTaskStackSize
TofuCaptureDecision tofu_decide_capture(bool has_leaf_anchor, bool leaf_matches_anchor, bool ca_present, bool leaf_has_identity)
TofuCaptureDecision
Capture-mode decision for TOFU certificate pinning.
@ kCaptureLeaf
first use, no usable CA in the chain: pin the leaf
@ kAccept
leaf matches the stored fingerprint; nothing to capture
@ kCaptureCa
first use, usable CA present: pin the CA
@ kReject
leaf does not match the stored fingerprint
constexpr TickType_t kWsDeltaSendTimeoutTicks
esp_websocket_client_handle_t handle
#define SENSESP_SK_WS_BUFFER_SIZE
#define SENSESP_MAX_RECEIVED_META_UPDATES
#define SENSESP_MAX_RECEIVED_VALUE_UPDATES
A single received delta entry awaiting dispatch on the main task.