5#include <ArduinoJson.h>
7#include <esp_http_client.h>
11#ifdef SENSESP_SSL_SUPPORT
12#include <mbedtls/pem.h>
13#include <mbedtls/sha256.h>
14#include <mbedtls/ssl.h>
15#include <mbedtls/x509_crt.h>
24#include "elapsedMillis.h"
25#include "esp_arduino_version.h"
47static const char* kRequestPermission =
"readwrite";
49#ifdef SENSESP_SSL_SUPPORT
51static void sha256_to_hex(
const uint8_t* sha256,
char* hex) {
52 for (
int i = 0; i < 32; i++) {
53 sprintf(hex + (i * 2),
"%02x", sha256[i]);
59static String cert_fingerprint(
const mbedtls_x509_crt* crt) {
61 mbedtls_sha256_context ctx;
62 mbedtls_sha256_init(&ctx);
63 mbedtls_sha256_starts(&ctx, 0);
64 mbedtls_sha256_update(&ctx, crt->raw.p, crt->raw.len);
65 mbedtls_sha256_finish(&ctx, sha256);
66 mbedtls_sha256_free(&ctx);
68 sha256_to_hex(sha256, hex);
73static constexpr size_t kMaxPinCnLen = 64;
78static String cert_common_name(
const mbedtls_x509_crt* crt) {
80 int len = mbedtls_x509_dn_gets(dn,
sizeof(dn), &crt->subject);
84 const char* cn = strstr(dn,
"CN=");
90 for (
size_t i = 0; i < kMaxPinCnLen && cn[i] !=
'\0' && cn[i] !=
','; i++) {
92 if (c >= 0x20 && c < 0x7f && c !=
'"' && c !=
'\\') {
104static String cert_to_pem(
const mbedtls_x509_crt* crt) {
111 constexpr size_t kPemBufSize = 4096;
112 std::unique_ptr<unsigned char[]> pem_buf(
113 new (std::nothrow)
unsigned char[kPemBufSize]);
115 ESP_LOGE(
"SKWSClient",
"TOFU: PEM buffer allocation failed");
119 int r = mbedtls_pem_write_buffer(
120 "-----BEGIN CERTIFICATE-----\n",
"-----END CERTIFICATE-----\n",
121 crt->raw.p, crt->raw.len, pem_buf.get(), kPemBufSize, &olen);
123 ESP_LOGE(
"SKWSClient",
"TOFU: PEM encode failed (-0x%x)", -r);
126 return String(
reinterpret_cast<const char*
>(pem_buf.get()));
134static String cert_dns_sans(
const mbedtls_x509_crt* crt) {
135 std::set<String> names;
136 for (
const mbedtls_x509_sequence* cur = &crt->subject_alt_names;
137 cur !=
nullptr && cur->buf.p !=
nullptr; cur = cur->next) {
138 mbedtls_x509_subject_alternative_name san;
139 memset(&san, 0,
sizeof(san));
140 if (mbedtls_x509_parse_subject_alt_name(&cur->buf, &san) != 0) {
143 if (san.type == MBEDTLS_X509_SAN_DNS_NAME &&
144 san.san.unstructured_name.p !=
nullptr &&
145 san.san.unstructured_name.len > 0) {
146 size_t n = san.san.unstructured_name.len;
152 for (
size_t i = 0; i < n; i++) {
153 char c =
static_cast<char>(san.san.unstructured_name.p[i]);
154 if (c >=
'A' && c <=
'Z') {
155 c =
static_cast<char>(c + (
'a' -
'A'));
161 mbedtls_x509_free_subject_alt_name(&san);
164 for (
const String& s : names) {
165 if (!out.isEmpty()) {
176static int tofu_verify_callback(
void* ctx, mbedtls_x509_crt* crt,
int depth,
178 SKWSClient* client =
static_cast<SKWSClient*
>(ctx);
179 if (client ==
nullptr) {
180 ESP_LOGW(
"SKWSClient",
"TOFU: no client context, allowing connection");
185 if (!client->is_tofu_enabled()) {
194 if (client->has_tofu_ca()) {
196 ESP_LOGE(
"SKWSClient",
"TOFU: certificate failed CA validation (0x%lx)",
197 (
unsigned long)*flags);
198 client->flag_cert_error();
199 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
205 if (depth == 0 && !client->get_tofu_san().isEmpty()) {
206 if (cert_dns_sans(crt) != client->get_tofu_san()) {
207 ESP_LOGE(
"SKWSClient",
"TOFU: leaf identity (SAN) mismatch, rejecting");
208 client->flag_cert_error();
209 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
229 bool is_ca = crt->MBEDTLS_PRIVATE(ca_istrue) != 0;
230 if (is_ca && !client->has_pending_ca()) {
231 String ca_pem = cert_to_pem(crt);
234 if (!ca_pem.isEmpty()) {
235 client->stash_pending_ca(ca_pem, cert_common_name(crt));
243 String leaf_fp = cert_fingerprint(crt);
244 String leaf_san = cert_dns_sans(crt);
246 client->has_tofu_fingerprint() && client->get_tofu_fingerprint() == leaf_fp;
248 client->has_tofu_fingerprint(), leaf_matches, client->has_pending_ca(),
249 !leaf_san.isEmpty());
253 ESP_LOGE(
"SKWSClient",
"TOFU: leaf fingerprint mismatch, rejecting");
254 client->flag_cert_error();
255 return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
257 ESP_LOGI(
"SKWSClient",
"TOFU: first use, pinning leaf %s", leaf_fp.c_str());
258 client->stash_pending_leaf(leaf_fp, cert_common_name(crt));
261 ESP_LOGI(
"SKWSClient",
"TOFU: first use, pinning issuing CA (identity %s)",
263 client->set_pending_san(leaf_san);
269 client->clear_pending_tofu();
280static esp_err_t tofu_crt_bundle_attach(
void* conf) {
281 mbedtls_ssl_config* ssl_conf =
static_cast<mbedtls_ssl_config*
>(conf);
284 if (client !=
nullptr && client->is_tofu_enabled() && client->has_tofu_ca()) {
286 static mbedtls_x509_crt pinned_ca;
287 static bool pinned_ca_inited =
false;
288 if (pinned_ca_inited) {
289 mbedtls_x509_crt_free(&pinned_ca);
291 mbedtls_x509_crt_init(&pinned_ca);
292 pinned_ca_inited =
true;
293 const String& pem = client->get_tofu_ca();
294 int r = mbedtls_x509_crt_parse(
295 &pinned_ca,
reinterpret_cast<const unsigned char*
>(pem.c_str()),
298 mbedtls_ssl_conf_ca_chain(ssl_conf, &pinned_ca,
nullptr);
300 ESP_LOGD(
"SKWSClient",
"TOFU: pinned CA installed as trust anchor");
306 ESP_LOGE(
"SKWSClient",
307 "TOFU: stored CA failed to parse (-0x%x); connections will fail "
313 mbedtls_ssl_conf_authmode(ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
316 mbedtls_ssl_conf_verify(ssl_conf, tofu_verify_callback, client);
321static void websocket_event_handler(
void* handler_args,
322 esp_event_base_t base,
323 int32_t event_id,
void* event_data) {
328 static_cast<uint32_t
>(
reinterpret_cast<uintptr_t
>(handler_args)) !=
332 esp_websocket_event_data_t* data = (esp_websocket_event_data_t*)event_data;
334 case WEBSOCKET_EVENT_CONNECTED:
337 case WEBSOCKET_EVENT_DISCONNECTED:
340 case WEBSOCKET_EVENT_DATA:
343 if (data->op_code <= 0x2) {
347 case WEBSOCKET_EVENT_ERROR:
354#ifdef SENSESP_SSL_SUPPORT
364 std::shared_ptr<SKDeltaQueue> sk_delta_queue,
365 const String& server_address, uint16_t server_port,
368 conf_server_address_{server_address},
369 conf_server_port_{server_port},
371 sk_delta_queue_{sk_delta_queue} {
391 ESP_LOGD(__FILENAME__,
"Starting SKWSClient");
404 MDNS.addService(
"signalk-sensesp",
"tcp", 80);
425 return ssl_enabled && handshake_status == kHttpUnauthorized;
437 ESP_LOGW(__FILENAME__,
"Token rejected (%d), requesting new access",
443 ESP_LOGW(__FILENAME__,
"Websocket client error.");
460 ESP_LOGI(__FILENAME__,
"Subscribing to Signal K listeners...");
471 bool output_available =
false;
472 JsonDocument subscription;
473 subscription[
"context"] =
"vessels.self";
478 if (listeners.size() > 0) {
479 output_available =
true;
480 JsonArray subscribe = subscription[
"subscribe"].to<JsonArray>();
482 for (
size_t i = 0; i < listeners.size(); i++) {
483 auto* listener = listeners.at(i);
484 String sk_path = listener->get_sk_path();
485 int listen_delay = listener->get_listen_delay();
487 JsonObject subscribe_path = subscribe.add<JsonObject>();
489 subscribe_path[
"path"] = sk_path;
490 subscribe_path[
"period"] = listen_delay;
491 ESP_LOGI(__FILENAME__,
"Adding %s subscription with listen_delay %d\n",
492 sk_path.c_str(), listen_delay);
497 if (output_available &&
501 serializeJson(subscription, json_message);
502 ESP_LOGI(__FILENAME__,
"Subscription JSON message:\n %s",
503 json_message.c_str());
504 int result = esp_websocket_client_send_text(
505 client_.load(), json_message.c_str(), json_message.length(),
508 ESP_LOGE(__FILENAME__,
"Subscription send failed (result=%d)", result);
522 constexpr size_t kMaxWsMessageSize = 4096;
523 if (length > kMaxWsMessageSize) {
524 ESP_LOGW(__FILENAME__,
"WebSocket message too large (%u bytes), dropping",
528 std::unique_ptr<char[]> buf(
new char[length + 1]);
529 memcpy(buf.get(), payload, length);
532#ifdef SIGNALK_PRINT_RCV_DELTA
533 ESP_LOGD(__FILENAME__,
"Websocket payload received: %s", buf.get());
536 JsonDocument message;
537 auto error = deserializeJson(message, buf.get());
540 if (message[
"updates"].is<JsonVariant>()) {
544 if (message[
"put"].is<JsonVariant>()) {
549 if (message[
"requestId"].is<JsonVariant>() &&
550 !message[
"put"].is<JsonVariant>()) {
554 ESP_LOGE(__FILENAME__,
"deserializeJson error: %s", error.c_str());
567 JsonArray updates = message[
"updates"];
573 bool has_meta_listener =
false;
576 if (listener->wants_meta()) {
577 has_meta_listener =
true;
584 for (
size_t i = 0; i < updates.size(); i++) {
585 JsonObject update = updates[i];
587 JsonArray values = update[
"values"];
589 for (
size_t vi = 0; vi < values.size(); vi++) {
595 ru.
doc.set(values[vi]);
605 if (has_meta_listener) {
606 JsonArray meta_entries = update[
"meta"];
607 for (
size_t mi = 0; mi < meta_entries.size(); mi++) {
608 JsonObject entry = meta_entries[mi];
609 if (entry[
"path"].isNull() || entry[
"value"].isNull())
continue;
636 const bool is_meta = update.is_meta;
637 const size_t cap = is_meta ? kMaxReceivedMeta : kMaxReceivedValues;
639 size_t kind_count = 0;
641 if (ru.is_meta == is_meta) kind_count++;
644 while (kind_count >= cap) {
648 if (it->is_meta == is_meta) {
654 ESP_LOGW(__FILENAME__,
"Dropping oldest received %s update (queue full)",
655 is_meta ?
"meta" :
"value");
671 const std::vector<SKPutListener*>& put_listeners =
684 String path = ru.
doc[
"path"].as<String>();
688 std::shared_ptr<const JsonDocument> meta_doc =
689 std::make_shared<const JsonDocument>(std::move(ru.
doc));
690 for (
size_t i = 0; i < listeners.size(); i++) {
698 const char* path = ru.
doc[
"path"];
699 JsonObject value = ru.
doc.as<JsonObject>();
701 for (
size_t i = 0; i < listeners.size(); i++) {
708 for (
size_t i = 0; i < put_listeners.size(); i++) {
732 JsonArray puts = message[
"put"];
733 bool all_matched =
true;
734 for (
size_t i = 0; i < puts.size(); i++) {
735 JsonObject value = puts[i];
736 const char* path = value[
"path"];
737 bool matched =
false;
740 const std::vector<SKPutListener*>& listeners =
742 for (
size_t j = 0; j < listeners.size(); j++) {
763 JsonDocument put_response;
764 put_response[
"requestId"] = message[
"requestId"];
766 put_response[
"state"] =
"COMPLETED";
767 put_response[
"statusCode"] = 200;
769 put_response[
"state"] =
"FAILED";
770 put_response[
"statusCode"] = 405;
772 String response_text;
773 serializeJson(put_response, response_text);
774 int result = esp_websocket_client_send_text(
775 client_.load(), response_text.c_str(), response_text.length(),
778 ESP_LOGE(__FILENAME__,
"PUT response send failed (result=%d)", result);
792 int result = esp_websocket_client_send_text(
795 ESP_LOGE(__FILENAME__,
"sendTXT failed (result=%d)", result);
801 uint16_t& server_port) {
804 int num = MDNS.queryService(
"signalk-wss",
"tcp");
808 ESP_LOGI(__FILENAME__,
"Found Signal K server via mDNS (signalk-wss)");
811 num = MDNS.queryService(
"signalk-ws",
"tcp");
818 ESP_LOGI(__FILENAME__,
"Found Signal K server via mDNS (signalk-ws)");
821#if ESP_ARDUINO_VERSION_MAJOR < 3
822 server_address = MDNS.IP(0).toString();
824 server_address = MDNS.address(0).toString();
826 server_port = MDNS.port(0);
827 ESP_LOGI(__FILENAME__,
"Found server %s (port %d)", server_address.c_str(),
833static esp_err_t detect_ssl_event_handler(esp_http_client_event_t* evt) {
834 if (evt->event_id == HTTP_EVENT_ON_HEADER) {
836 if (strcasecmp(evt->header_key,
"Location") == 0) {
837 String* location =
static_cast<String*
>(evt->user_data);
838 *location = evt->header_value;
850 ESP_LOGD(__FILENAME__,
"Probing for SSL redirect at %s", url.c_str());
854 esp_http_client_config_t config = {};
855 config.url = url.c_str();
856 config.disable_auto_redirect =
true;
857 config.timeout_ms = 10000;
858 config.event_handler = detect_ssl_event_handler;
859 config.user_data = &location;
861 esp_http_client_handle_t client = esp_http_client_init(&config);
862 if (client ==
nullptr) {
863 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
867 esp_err_t err = esp_http_client_perform(client);
868 int status_code = esp_http_client_get_status_code(client);
869 esp_http_client_cleanup(client);
872 ESP_LOGD(__FILENAME__,
"HTTP request failed: %s", esp_err_to_name(err));
876 if ((status_code == 301 || status_code == 302 ||
877 status_code == 307 || status_code == 308) &&
878 location.startsWith(
"https://")) {
879 ESP_LOGI(__FILENAME__,
"SSL redirect detected, enabling HTTPS/WSS");
906 if (
client_.load() !=
nullptr) {
927 if (!provisioner || !provisioner->is_connected()) {
928 ESP_LOGI(__FILENAME__,
929 "Network is not yet up. SignalK client connection will be "
930 "initiated when the link comes up.");
943 ESP_LOGE(__FILENAME__,
"connect worker spawn failed");
952 self->auth_job_running_.store(
false);
953 vTaskDelete(
nullptr);
957 ESP_LOGI(__FILENAME__,
"Initiating websocket connection with server...");
961 ESP_LOGE(__FILENAME__,
962 "No Signal K server found in network when using mDNS service!");
964 ESP_LOGI(__FILENAME__,
965 "Signal K server has been found at address %s:%d by mDNS.",
974 ESP_LOGD(__FILENAME__,
975 "Websocket is connecting to Signal K server on address %s:%d",
984 ESP_LOGD(__FILENAME__,
985 "Websocket is not connecting to Signal K server because host and "
986 "port are not defined.");
991 if (this->
polling_href_.length() > 0 && this->polling_href_.startsWith(
"/")) {
1000 ESP_LOGD(__FILENAME__,
"No prior authorization token present.");
1006#ifdef SENSESP_SSL_SUPPORT
1028#ifndef SENSESP_SSL_SUPPORT
1030 const uint16_t server_port) {
1031 String url = String(
"http://") + server_address +
":" + server_port +
1032 "/signalk/v1/stream";
1033 ESP_LOGD(__FILENAME__,
"Testing token with url %s", url.c_str());
1035 const String full_token = String(
"Bearer ") +
auth_token_;
1036 ESP_LOGD(__FILENAME__,
"Authorization: %.8s...[redacted]", full_token.c_str());
1038 esp_http_client_config_t config = {};
1039 config.url = url.c_str();
1040 config.timeout_ms = 10000;
1042 esp_http_client_handle_t client = esp_http_client_init(&config);
1043 if (client ==
nullptr) {
1044 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1049 esp_http_client_set_header(client,
"Authorization", full_token.c_str());
1052 esp_err_t err = esp_http_client_open(client, 0);
1053 if (err != ESP_OK) {
1054 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s",
1055 esp_err_to_name(err));
1056 esp_http_client_cleanup(client);
1061 int content_length = esp_http_client_fetch_headers(client);
1062 int http_code = esp_http_client_get_status_code(client);
1064 ESP_LOGD(__FILENAME__,
"Testing resulted in http status %d", http_code);
1068 if (content_length > 0 && content_length < 4096) {
1069 char* buffer =
new char[content_length + 1];
1070 int read_len = esp_http_client_read(client, buffer, content_length);
1071 buffer[read_len > 0 ? read_len : 0] =
'\0';
1072 payload = String(buffer);
1078 while ((read_len = esp_http_client_read(client, buffer,
1079 sizeof(buffer) - 1)) > 0) {
1080 buffer[read_len] =
'\0';
1081 payload += String(buffer);
1082 if (payload.length() > 4096)
break;
1086 esp_http_client_close(client);
1087 esp_http_client_cleanup(client);
1089 if (payload.length() > 0) {
1090 ESP_LOGD(__FILENAME__,
"Returned payload (%d bytes): %s", payload.length(),
1094 if (http_code == 426) {
1097 ESP_LOGD(__FILENAME__,
"Attempting to connect to Signal K Websocket...");
1098 this->
connect_ws(server_address, server_port);
1099 }
else if (http_code == kHttpUnauthorized) {
1102 ESP_LOGW(__FILENAME__,
"Token rejected (401), requesting new access");
1106 }
else if (http_code > 0) {
1109 ESP_LOGE(__FILENAME__,
"HTTP request failed with code %d", http_code);
1116 const uint16_t server_port) {
1117 ESP_LOGD(__FILENAME__,
"Sending access request (client_id=%s, ssl=%d)",
1128 doc[
"description"] =
1130 doc[
"permissions"] = kRequestPermission;
1131 String json_req =
"";
1132 serializeJson(doc, json_req);
1134 ESP_LOGD(__FILENAME__,
"Access request: %s", json_req.c_str());
1136 String protocol =
ssl_enabled_ ?
"https://" :
"http://";
1137 String url = protocol + server_address +
":" + server_port +
1138 "/signalk/v1/access/requests";
1139 ESP_LOGD(__FILENAME__,
"Access request url: %s", url.c_str());
1141 esp_http_client_config_t config = {};
1142 config.url = url.c_str();
1143 config.method = HTTP_METHOD_POST;
1144 config.timeout_ms = 10000;
1145#ifdef SENSESP_SSL_SUPPORT
1147 config.crt_bundle_attach = tofu_crt_bundle_attach;
1148 config.skip_cert_common_name_check =
true;
1152 esp_http_client_handle_t client = esp_http_client_init(&config);
1153 if (client ==
nullptr) {
1154 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1160 esp_http_client_set_header(client,
"Content-Type",
"application/json");
1163 esp_err_t err = esp_http_client_open(client, json_req.length());
1164 if (err != ESP_OK) {
1165 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s", esp_err_to_name(err));
1166 esp_http_client_cleanup(client);
1171 int write_len = esp_http_client_write(client, json_req.c_str(), json_req.length());
1172 if (write_len < 0 || write_len != (
int)json_req.length()) {
1173 ESP_LOGE(__FILENAME__,
"Failed to write request body (wrote %d of %d bytes)",
1174 write_len, json_req.length());
1175 esp_http_client_close(client);
1176 esp_http_client_cleanup(client);
1181 int content_length = esp_http_client_fetch_headers(client);
1182 int http_code = esp_http_client_get_status_code(client);
1184 ESP_LOGD(__FILENAME__,
"HTTP response: code=%d, content_length=%d", http_code, content_length);
1190 while ((read_len = esp_http_client_read(client, buffer,
sizeof(buffer) - 1)) > 0) {
1191 buffer[read_len] =
'\0';
1192 payload += String(buffer);
1193 if (payload.length() > 4096)
break;
1195 ESP_LOGD(__FILENAME__,
"Response payload (%d bytes): %s",
1196 payload.length(), payload.c_str());
1198 esp_http_client_close(client);
1199 esp_http_client_cleanup(client);
1202 deserializeJson(doc, payload.c_str());
1203 String state = doc[
"state"].is<
const char*>() ? doc[
"state"].as<String>() :
"";
1204 String href = doc[
"href"].is<
const char*>() ? doc[
"href"].as<String>() :
"";
1205 String message = doc[
"message"].is<
const char*>() ? doc[
"message"].as<String>() :
"";
1207 ESP_LOGD(__FILENAME__,
"Access request response: http=%d, state=%s, href=%s",
1208 http_code, state.c_str(), href.c_str());
1209 if (message.length() > 0) {
1210 ESP_LOGI(__FILENAME__,
"Server message: %s", message.c_str());
1215 if (http_code == 400 && href.length() > 0 && href.startsWith(
"/")) {
1216 ESP_LOGI(__FILENAME__,
"Existing request found, will poll href: %s", href.c_str());
1225 if (http_code == 202 && href.length() > 0 && href.startsWith(
"/")) {
1234 if (http_code == 404) {
1235 ESP_LOGI(__FILENAME__,
1236 "Server security disabled (404 on access request) — connecting "
1239 this->
connect_ws(server_address, server_port);
1244 ESP_LOGW(__FILENAME__,
"Cannot handle response: http=%d, state=%s", http_code, state.c_str());
1249 const uint16_t server_port,
1250 const String href) {
1251 ESP_LOGD(__FILENAME__,
"Polling SK Server for authentication token");
1253 String protocol =
ssl_enabled_ ?
"https://" :
"http://";
1254 String url = protocol + server_address +
":" + server_port + href;
1256 esp_http_client_config_t config = {};
1257 config.url = url.c_str();
1258 config.timeout_ms = 10000;
1259#ifdef SENSESP_SSL_SUPPORT
1261 config.crt_bundle_attach = tofu_crt_bundle_attach;
1262 config.skip_cert_common_name_check =
true;
1266 esp_http_client_handle_t client = esp_http_client_init(&config);
1267 if (client ==
nullptr) {
1268 ESP_LOGE(__FILENAME__,
"Failed to initialize HTTP client");
1274 esp_err_t err = esp_http_client_open(client, 0);
1275 if (err != ESP_OK) {
1276 ESP_LOGE(__FILENAME__,
"Failed to open HTTP connection: %s", esp_err_to_name(err));
1277 esp_http_client_cleanup(client);
1282 int content_length = esp_http_client_fetch_headers(client);
1283 int http_code = esp_http_client_get_status_code(client);
1287 if (content_length > 0 && content_length < 4096) {
1288 char* buffer =
new char[content_length + 1];
1289 int read_len = esp_http_client_read(client, buffer, content_length);
1290 buffer[read_len > 0 ? read_len : 0] =
'\0';
1291 payload = String(buffer);
1297 while ((read_len = esp_http_client_read(client, buffer,
sizeof(buffer) - 1)) > 0) {
1298 buffer[read_len] =
'\0';
1299 payload += String(buffer);
1300 if (payload.length() > 4096)
break;
1307 ESP_LOGD(__FILENAME__,
"Poll response: http=%d, %d bytes", http_code,
1308 static_cast<int>(payload.length()));
1310 esp_http_client_close(client);
1311 esp_http_client_cleanup(client);
1313 if (http_code == 200 || http_code == 202) {
1315 auto error = deserializeJson(doc, payload.c_str());
1317 ESP_LOGW(__FILENAME__,
"WARNING: Could not deserialize http payload.");
1318 ESP_LOGW(__FILENAME__,
"DeserializationError: %s", error.c_str());
1322 String state = doc[
"state"];
1323 ESP_LOGD(__FILENAME__,
"%s", state.c_str());
1324 if (state ==
"PENDING") {
1328 if (state ==
"COMPLETED") {
1329 JsonObject access_req = doc[
"accessRequest"];
1330 String permission = access_req[
"permission"];
1335 if (permission ==
"DENIED") {
1336 ESP_LOGW(__FILENAME__,
"Permission denied");
1341 if (permission ==
"APPROVED") {
1342 ESP_LOGI(__FILENAME__,
"Permission granted");
1343 String token = access_req[
"token"];
1346 this->
connect_ws(server_address, server_port);
1351 if (http_code == 404 || http_code == 500) {
1356 ESP_LOGD(__FILENAME__,
1357 "Got %d polling access request — clearing stale href.",
1365 ESP_LOGW(__FILENAME__,
1366 "Can't handle response %d to pending access request.\n",
1382 ESP_LOGW(__FILENAME__,
"connect_ws: prior client not reaped; deferring");
1396 String path =
"/signalk/v1/stream?subscribe=none";
1398 String url = protocol +
"://" + host +
":" + String(port) + path;
1400 ESP_LOGD(__FILENAME__,
"Connecting WebSocket to %s", url.c_str());
1405 auth_header = String(
"Authorization: Bearer ") +
auth_token_ +
"\r\n";
1409 esp_websocket_client_config_t config = {};
1410 config.uri = url.c_str();
1413 if (auth_header.length() > 0) {
1414 config.headers = auth_header.c_str();
1417#ifdef SENSESP_SSL_SUPPORT
1421 config.crt_bundle_attach = tofu_crt_bundle_attach;
1422 config.skip_cert_common_name_check =
true;
1426 esp_websocket_client_handle_t h = esp_websocket_client_init(&config);
1428 ESP_LOGE(__FILENAME__,
"Failed to initialize WebSocket client");
1437 esp_websocket_register_events(
1438 h, WEBSOCKET_EVENT_ANY, websocket_event_handler,
1439 reinterpret_cast<void*
>(
1443 esp_err_t err = esp_websocket_client_start(h);
1444 if (err != ESP_OK) {
1445 ESP_LOGE(__FILENAME__,
"Failed to start WebSocket client: %s",
1446 esp_err_to_name(err));
1449 esp_websocket_client_destroy(h);
1454 ESP_LOGD(__FILENAME__,
"WebSocket client started, waiting for connection...");
1462struct WsTeardownArg {
1469 auto* a =
static_cast<WsTeardownArg*
>(arg);
1473 esp_websocket_client_stop(a->handle);
1474 esp_websocket_client_destroy(a->handle);
1475 a->self->teardown_in_progress_.store(
false);
1477 vTaskDelete(
nullptr);
1481 if (old ==
nullptr) {
1484 auto* arg =
new WsTeardownArg{old,
this};
1486 nullptr) == pdPASS) {
1498 ESP_LOGW(__FILENAME__,
"teardown task spawn failed; will retry next cycle");
1504 esp_websocket_client_handle_t old =
client_.exchange(
nullptr);
1505 if (old ==
nullptr) {
1525 std::vector<String> deltas;
1528 for (
const auto& delta : deltas) {
1540 uint32_t now = millis();
1543 ESP_LOGW(__FILENAME__,
1544 "Delta too large (%u B > %u buffer); dropped to keep the "
1545 "connection alive -- raise SENSESP_SK_WS_BUFFER_SIZE",
1546 (
unsigned)delta.length(),
1553 int send_result = esp_websocket_client_send_text(
1555 if (send_result < 0) {
1570 ESP_LOGW(__FILENAME__,
1571 "Delta send incomplete (result=%d); dropping rest of batch",
1605 if (config[
"sk_address"].is<String>()) {
1608 if (config[
"sk_port"].is<int>()) {
1611 if (config[
"use_mdns"].is<bool>()) {
1612 this->
use_mdns_ = config[
"use_mdns"].as<
bool>();
1614 if (config[
"token"].is<String>()) {
1617 if (config[
"client_id"].is<String>()) {
1618 this->
client_id_ = config[
"client_id"].as<String>();
1620 if (config[
"polling_href"].is<String>()) {
1621 String href = config[
"polling_href"].as<String>();
1626 if (config[
"ssl_enabled"].is<bool>()) {
1629 if (config[
"tofu_enabled"].is<bool>()) {
1635 if (config[
"tofu_fingerprint"].is<String>()) {
1638 if (config[
"tofu_ca_pem"].is<String>()) {
1639 this->
tofu_ca_pem_ = config[
"tofu_ca_pem"].as<String>();
1641 if (config[
"tofu_san"].is<String>()) {
1642 this->
tofu_san_ = config[
"tofu_san"].as<String>();
1644 if (config[
"tofu_pin_cn"].is<String>()) {
1645 this->
tofu_pin_cn_ = config[
"tofu_pin_cn"].as<String>();
1647 if (config[
"tofu_pin_is_ca"].is<bool>()) {
1650 if (config[
"send_meta_enabled"].is<bool>()) {
1666 return "Authorizing with SignalK";
1670 return "Connecting";
1672 return "Disconnected";
1674 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 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.