// File: src/net_influx.c #include "esp_http_client.h" #include "esp_err.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include #include #include #include #include #include #include "sys_status.h" #include "storage.h" #include "net_influx.h" static const char* TAG = "net_influx"; /* ---------------- State (mit internen Kopien!) ---------------- */ typedef struct { char url_base[128]; char org[64]; char bucket[64]; char token[512]; // lang genug für Influx Token bool use_tls; const char* ca_cert_pem; int http_timeout_ms; } net_influx_state_t; static net_influx_state_t s = {0}; /* ---------------- Worker Runtime State (asynchrones Submit) ---------------- */ typedef struct { uint16_t queue_len; uint32_t task_stack; UBaseType_t task_prio; uint32_t init_retry_ms; uint32_t backoff_start_ms; uint32_t backoff_max_ms; uint8_t fails_before_reinit; const char* ca_cert_pem_opt; int http_timeout_ms; } net_influx_runtime_cfg_i_t; static QueueHandle_t s_q = NULL; static TaskHandle_t s_task = NULL; static bool s_run = false; static net_influx_runtime_cfg_i_t s_rt = { .queue_len = 16, .task_stack = 6144, .task_prio = 5, .init_retry_ms = 1000, .backoff_start_ms = 2000, .backoff_max_ms = 300000, .fails_before_reinit = 5, .ca_cert_pem_opt = NULL, .http_timeout_ms = 3000, }; /* ---------------- Utils ---------------- */ static void trim_inplace(char* p) { if (!p) return; size_t len = strlen(p); size_t a = 0, b = len; while (a < b && (isspace((unsigned char)p[a]) || p[a] == '\"')) a++; while (b > a && (isspace((unsigned char)p[b-1]) || p[b-1] == '\"' || p[b-1] == '/')) b--; if (a || b != len) { memmove(p, p + a, b - a); p[b - a] = 0; } } static void safe_copy(char* dst, size_t dst_sz, const char* src) { if (!dst || dst_sz == 0) return; if (!src) { dst[0] = 0; return; } strncpy(dst, src, dst_sz - 1); dst[dst_sz - 1] = 0; } typedef struct { bool tls; // http=false, https=true char host[64]; int port; // -1 = nicht angegeben } base_parts_t; // erwartet: "http://host:port" oder "host:port" oder "host" static bool parse_base_url(const char* in, base_parts_t* out) { if (!in || !*in || !out) return false; char buf[128]; safe_copy(buf, sizeof(buf), in); trim_inplace(buf); const char* p = buf; out->tls = false; out->port = -1; memset(out->host, 0, sizeof(out->host)); if (strncasecmp(p, "http://", 7) == 0) { p += 7; out->tls = false; } else if (strncasecmp(p, "https://", 8) == 0) { p += 8; out->tls = true; } const char* colon = strchr(p, ':'); if (colon) { size_t host_len = (size_t)(colon - p); if (host_len == 0 || host_len >= sizeof(out->host)) return false; memcpy(out->host, p, host_len); out->host[host_len] = 0; const char* port_str = colon + 1; if (!*port_str) return false; int port = 0; while (*port_str && isdigit((unsigned char)*port_str)) { port = port * 10 + (*port_str - '0'); port_str++; } if (*port_str != 0) return false; // kein weiterer Kram erlaubt out->port = port; } else { size_t host_len = strlen(p); if (host_len == 0 || host_len >= sizeof(out->host)) return false; memcpy(out->host, p, host_len); out->host[host_len] = 0; } return true; } static void mask_token(const char* token, char* out, size_t out_len) { if (!token || !out || out_len < 8) return; size_t n = strlen(token); if (n <= 8) { snprintf(out, out_len, "****"); } else { size_t keep = 4; snprintf(out, out_len, "%.*s****%.*s", (int)keep, token, (int)keep, token + n - keep); } } static char* dup0(const char* str) { if (!str) return NULL; size_t n = strlen(str) + 1; char* p = (char*)malloc(n); if (!p) return NULL; memcpy(p, str, n); return p; } /* Minimal escaping für measurement/key: spaces/commas */ static size_t esc_copy(char* dst, size_t cap, const char* src, bool escape_equals) { size_t pos = 0; if (!dst || cap == 0) return 0; dst[0] = 0; if (!src) return 0; for (const char* p = src; *p; ++p) { char c = *p; bool esc = (c == ' ' || c == ',' || (escape_equals && c == '=')); if (esc) { if (pos + 2 >= cap) break; dst[pos++] = '\\'; dst[pos++] = c; } else { if (pos + 1 >= cap) break; dst[pos++] = c; } } dst[(pos < cap) ? pos : (cap - 1)] = 0; return pos; } /* ---------------- HTTP Event Handler (IDF-kompatibel) ---------------- */ static esp_err_t http_evt(esp_http_client_event_t* evt) { switch (evt->event_id) { case HTTP_EVENT_ERROR: ESP_LOGE(TAG, "HTTP_EVENT_ERROR"); break; case HTTP_EVENT_ON_CONNECTED: ESP_LOGI(TAG, "HTTP_EVENT_ON_CONNECTED"); break; case HTTP_EVENT_HEADER_SENT: ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); break; case HTTP_EVENT_ON_HEADER: ESP_LOGD(TAG, "HDR: %s: %s", evt->header_key ? evt->header_key : "(null)", evt->header_value ? evt->header_value : "(null)"); break; case HTTP_EVENT_ON_DATA: ESP_LOGV(TAG, "DATA chunk len=%d", evt->data_len); break; case HTTP_EVENT_ON_FINISH: ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); break; case HTTP_EVENT_DISCONNECTED: ESP_LOGW(TAG, "HTTP_EVENT_DISCONNECTED"); break; default: break; } return ESP_OK; } /* ---------------- Internal: HTTP send "line protocol" ---------------- */ static esp_err_t net_influx_write_line(const char* line) { bool ok = false; if (!line || !*line) { sys_status_set_influx_ok(false); return ESP_ERR_INVALID_ARG; } if (s.url_base[0] == 0 || s.org[0] == 0 || s.bucket[0] == 0 || s.token[0] == 0) { sys_status_set_influx_ok(false); return ESP_ERR_INVALID_STATE; } // Base parse → host/port/tls base_parts_t bp; if (!parse_base_url(s.url_base, &bp)) { ESP_LOGE(TAG, "Base-URL ungueltig: \"%s\"", s.url_base); sys_status_set_influx_ok(false); return ESP_ERR_INVALID_ARG; } if (s.use_tls) bp.tls = true; int port = (bp.port > 0) ? bp.port : (bp.tls ? 443 : 8086); // Pfad char path[192]; snprintf(path, sizeof(path), "/api/v2/write?org=%s&bucket=%s&precision=ms", s.org, s.bucket); ESP_LOGI(TAG, "HTTP cfg: host=%s, port=%d, path=%s, tls=%d", bp.host, port, path, (int)bp.tls); ESP_LOGD(TAG, "Line: %s", line); esp_http_client_config_t cfg = { .host = bp.host, .port = port, .path = path, .timeout_ms = s.http_timeout_ms, .cert_pem = bp.tls ? s.ca_cert_pem : NULL, .method = HTTP_METHOD_POST, .event_handler = http_evt, .transport_type = bp.tls ? HTTP_TRANSPORT_OVER_SSL : HTTP_TRANSPORT_OVER_TCP, .disable_auto_redirect = false, }; esp_http_client_handle_t h = esp_http_client_init(&cfg); if (!h) { ESP_LOGE(TAG, "http_client_init: no mem"); sys_status_set_influx_ok(false); return ESP_ERR_NO_MEM; } // Header size_t auth_len = strlen(s.token) + 7; // "Token " + '\0' char* auth = (char*)malloc(auth_len); if (!auth) { ESP_LOGE(TAG, "malloc auth header: no mem"); esp_http_client_cleanup(h); sys_status_set_influx_ok(false); return ESP_ERR_NO_MEM; } snprintf(auth, auth_len, "Token %s", s.token); esp_http_client_set_header(h, "Authorization", auth); free(auth); esp_http_client_set_header(h, "Content-Type", "text/plain; charset=utf-8"); esp_err_t err = esp_http_client_set_post_field(h, line, (int)strlen(line)); if (err != ESP_OK) { ESP_LOGE(TAG, "set_post_field: %s", esp_err_to_name(err)); esp_http_client_cleanup(h); sys_status_set_influx_ok(false); return err; } err = esp_http_client_perform(h); int status = -1; if (err == ESP_OK) { status = esp_http_client_get_status_code(h); int64_t cl = esp_http_client_get_content_length(h); ESP_LOGI(TAG, "HTTP status=%d, content_length=%lld", status, (long long)cl); if (status != 204) { char resp[256] = {0}; int n = esp_http_client_read_response(h, resp, sizeof(resp)-1); if (n > 0) ESP_LOGW(TAG, "Resp(%d): %.*s", status, n, resp); else ESP_LOGW(TAG, "Resp(%d): ", status); } } else { ESP_LOGE(TAG, "perform: %s", esp_err_to_name(err)); } esp_http_client_cleanup(h); ok = (err == ESP_OK && status == 204); sys_status_set_influx_ok(ok); return ok ? ESP_OK : ESP_FAIL; } /* ---------------- Generic Point/Fields → Line Protocol ---------------- */ static bool field_is_valid(const net_influx_field_t* f) { if (!f || !f->key || !*f->key) return false; if (f->type == NET_INFLUX_F_FLOAT) return isfinite(f->v.f); if (f->type == NET_INFLUX_F_STRING) return (f->v.s != NULL); return true; } static esp_err_t build_line_protocol(const net_influx_point_t* p, char* out, size_t out_cap) { if (!p || !p->measurement || !p->fields || p->num_fields == 0 || !out || out_cap < 64) { return ESP_ERR_INVALID_ARG; } size_t off = 0; // measurement escaped (space/comma) char meas[96]; esc_copy(meas, sizeof(meas), p->measurement, false); off += snprintf(out + off, out_cap - off, "%s", meas); if (off >= out_cap) return ESP_FAIL; // tags: passthrough (caller liefert "k=v,k2=v2") if (p->tags && *p->tags) { off += snprintf(out + off, out_cap - off, ",%s", p->tags); if (off >= out_cap) return ESP_FAIL; } off += snprintf(out + off, out_cap - off, " "); if (off >= out_cap) return ESP_FAIL; bool first = true; for (size_t i = 0; i < p->num_fields; ++i) { const net_influx_field_t* f = &p->fields[i]; if (!field_is_valid(f)) continue; char key[64]; esc_copy(key, sizeof(key), f->key, false); if (!first) { off += snprintf(out + off, out_cap - off, ","); if (off >= out_cap) return ESP_FAIL; } first = false; switch (f->type) { case NET_INFLUX_F_FLOAT: { int prec = (f->precision >= 0 && f->precision <= 9) ? f->precision : 3; char fmt[24]; snprintf(fmt, sizeof(fmt), "%%s=%%.%df", prec); off += snprintf(out + off, out_cap - off, fmt, key, f->v.f); break; } case NET_INFLUX_F_INT: off += snprintf(out + off, out_cap - off, "%s=%lldi", key, (long long)f->v.i); break; case NET_INFLUX_F_UINT: off += snprintf(out + off, out_cap - off, "%s=%llui", key, (unsigned long long)f->v.u); break; case NET_INFLUX_F_BOOL: off += snprintf(out + off, out_cap - off, "%s=%s", key, f->v.b ? "true" : "false"); break; case NET_INFLUX_F_STRING: { off += snprintf(out + off, out_cap - off, "%s=\"", key); if (off >= out_cap) return ESP_FAIL; const char* s0 = f->v.s ? f->v.s : ""; for (const char* sp = s0; *sp; ++sp) { if (off + 2 >= out_cap) return ESP_FAIL; if (*sp == '\"' || *sp == '\\') out[off++] = '\\'; out[off++] = *sp; } if (off + 2 >= out_cap) return ESP_FAIL; out[off++] = '\"'; out[off] = 0; break; } default: return ESP_ERR_INVALID_ARG; } if (off >= out_cap) return ESP_FAIL; } if (first) return ESP_ERR_INVALID_STATE; // keine validen Felder if (p->ts_ms != 0) { off += snprintf(out + off, out_cap - off, " %llu", (unsigned long long)p->ts_ms); if (off >= out_cap) return ESP_FAIL; } return ESP_OK; } /* ---------------- Async Queue Message (deep copy) ---------------- */ typedef struct { char* measurement; char* tags; // optional uint64_t ts_ms; size_t num_fields; net_influx_field_t* fields; // deep-copied array; keys and string-values are duplicated } influx_msg_t; static void free_msg(influx_msg_t* m) { if (!m) return; if (m->measurement) free(m->measurement); if (m->tags) free(m->tags); if (m->fields) { for (size_t i = 0; i < m->num_fields; ++i) { if (m->fields[i].type == NET_INFLUX_F_STRING && m->fields[i].v.s) { free((void*)m->fields[i].v.s); } if (m->fields[i].key) free((void*)m->fields[i].key); } free(m->fields); } memset(m, 0, sizeof(*m)); } /* ---------------- Init/Backoff (im Worker) ---------------- */ static bool influx_init_blocking(void) { while (s_run) { if (net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms) == ESP_OK) { ESP_LOGI(TAG, "Influx ready (from NVS)."); return true; } ESP_LOGW(TAG, "Influx nicht bereit – retry in %u ms", (unsigned)s_rt.init_retry_ms); vTaskDelay(pdMS_TO_TICKS(s_rt.init_retry_ms)); } return false; } static bool influx_reinit_with_backoff(uint32_t* backoff_ms) { if (!backoff_ms) return false; uint32_t wait_ms = (*backoff_ms == 0) ? s_rt.backoff_start_ms : *backoff_ms; ESP_LOGW(TAG, "Re-Init Influx in %u ms", (unsigned)wait_ms); vTaskDelay(pdMS_TO_TICKS(wait_ms)); bool ok = (net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms) == ESP_OK); if (ok) { ESP_LOGI(TAG, "Influx Re-Init OK"); *backoff_ms = s_rt.backoff_start_ms; return true; } if (wait_ms < s_rt.backoff_max_ms) { uint32_t next = wait_ms * 2; *backoff_ms = (next > s_rt.backoff_max_ms) ? s_rt.backoff_max_ms : next; } return false; } /* ---------------- Worker Task ---------------- */ static void net_influx_worker(void* arg) { (void)arg; ESP_LOGI(TAG, "Influx worker started."); if (!influx_init_blocking()) { ESP_LOGE(TAG, "Worker beendet (Influx init fatal)."); vTaskDelete(NULL); return; } int fail_count = 0; uint32_t backoff_ms = s_rt.backoff_start_ms; while (s_run) { influx_msg_t msg = {0}; if (xQueueReceive(s_q, &msg, portMAX_DELAY) != pdTRUE) continue; net_influx_point_t p = { .measurement = msg.measurement, .tags = msg.tags, .ts_ms = msg.ts_ms, .fields = msg.fields, .num_fields = msg.num_fields, }; char line[512]; esp_err_t b = build_line_protocol(&p, line, sizeof(line)); if (b == ESP_ERR_INVALID_STATE) { ESP_LOGW(TAG, "Skipping write: no valid fields."); free_msg(&msg); continue; } if (b != ESP_OK) { ESP_LOGW(TAG, "Line build failed: %s", esp_err_to_name(b)); free_msg(&msg); continue; } esp_err_t e = net_influx_write_line(line); if (e == ESP_OK) { if (fail_count) ESP_LOGI(TAG, "Influx write recovered."); fail_count = 0; backoff_ms = s_rt.backoff_start_ms; } else { ESP_LOGW(TAG, "Influx write failed: %s", esp_err_to_name(e)); if (++fail_count >= (int)s_rt.fails_before_reinit) { (void)influx_reinit_with_backoff(&backoff_ms); fail_count = 0; } } free_msg(&msg); } ESP_LOGI(TAG, "Influx worker stopping."); vTaskDelete(NULL); } /* ---------------- Public API ---------------- */ esp_err_t net_influx_init(const net_influx_cfg_t* cfg) { if (!cfg || !cfg->url_base || !cfg->org || !cfg->bucket || !cfg->token) { return ESP_ERR_INVALID_ARG; } safe_copy(s.url_base, sizeof(s.url_base), cfg->url_base); safe_copy(s.org, sizeof(s.org), cfg->org); safe_copy(s.bucket, sizeof(s.bucket), cfg->bucket); safe_copy(s.token, sizeof(s.token), cfg->token); trim_inplace(s.url_base); s.use_tls = cfg->use_tls; s.ca_cert_pem = cfg->ca_cert_pem; s.http_timeout_ms = (cfg->http_timeout_ms > 0) ? cfg->http_timeout_ms : 3000; char tok[32] = {0}; mask_token(s.token, tok, sizeof(tok)); ESP_LOGI(TAG, "init: base=\"%s\", org=\"%s\", bucket=\"%s\", tls=%d, timeout=%dms, token=%s", s.url_base, s.org, s.bucket, (int)s.use_tls, s.http_timeout_ms, tok); sys_status_set_influx_ok(false); return ESP_OK; } esp_err_t net_influx_write_fields(const char* measurement, const char* tags, uint64_t ts_ms, const char* fields_fmt, ...) { // --- pessimistisch starten --- bool ok = false; if (!measurement || !fields_fmt) { sys_status_set_influx_ok(false); return ESP_ERR_INVALID_ARG; } if (s.url_base[0] == 0 || s.org[0] == 0 || s.bucket[0] == 0 || s.token[0] == 0) { sys_status_set_influx_ok(false); return ESP_ERR_INVALID_STATE; } // 1) Fields formatieren char fields[256]; va_list ap; va_start(ap, fields_fmt); vsnprintf(fields, sizeof(fields), fields_fmt, ap); va_end(ap); // 2) Line Protocol char line[512]; int off = 0; // measurement escaping (space/comma) char meas[96]; esc_copy(meas, sizeof(meas), measurement, false); off += snprintf(line + off, sizeof(line) - off, "%s", meas); if (off < 0 || off >= (int)sizeof(line)) { sys_status_set_influx_ok(false); return ESP_FAIL; } if (tags && *tags) { off += snprintf(line + off, sizeof(line) - off, ",%s", tags); if (off < 0 || off >= (int)sizeof(line)) { sys_status_set_influx_ok(false); return ESP_FAIL; } } off += snprintf(line + off, sizeof(line) - off, " %s", fields); if (off < 0 || off >= (int)sizeof(line)) { sys_status_set_influx_ok(false); return ESP_FAIL; } if (ts_ms != 0) { off += snprintf(line + off, sizeof(line) - off, " %llu", (unsigned long long)ts_ms); if (off < 0 || off >= (int)sizeof(line)) { sys_status_set_influx_ok(false); return ESP_FAIL; } } esp_err_t err = net_influx_write_line(line); ok = (err == ESP_OK); sys_status_set_influx_ok(ok); return ok ? ESP_OK : ESP_FAIL; } // Aus NVS: URL (service_url), org/bucket/token → net_influx_init() esp_err_t net_influx_init_from_nvs(const char* ca_cert_pem_opt, int timeout_ms) { char *url = NULL, *org = NULL, *bucket = NULL, *token = NULL; if (!storage_load_service_url(&url)) { ESP_LOGW(TAG, "keine Service-URL in NVS gefunden (mDNS noch nicht fertig?)"); return ESP_ERR_NOT_FOUND; } if (!storage_get_effective_influx(&org, &bucket, &token)) { ESP_LOGE(TAG, "Influx-Konfiguration aus NVS nicht lesbar"); free(url); return ESP_FAIL; } net_influx_cfg_t cfg = { .url_base = url, // z.B. "http://192.168.1.10:8086" .org = org, .bucket = bucket, .token = token, .use_tls = false, // URL-Parser erkennt https automatisch; true erzwingt TLS .ca_cert_pem = ca_cert_pem_opt, .http_timeout_ms = (timeout_ms > 0) ? timeout_ms : 3000 }; esp_err_t err = net_influx_init(&cfg); free(url); free(org); free(bucket); free(token); return err; } /* ---------------- NEW: Start/Stop/Submit (generic, multi-sensor) ---------------- */ esp_err_t net_influx_start(const net_influx_runtime_cfg_t* rt) { if (s_task) return ESP_OK; // runtime cfg übernehmen (mit Defaults) if (rt) { s_rt.queue_len = rt->queue_len ? rt->queue_len : s_rt.queue_len; s_rt.task_stack = rt->task_stack ? rt->task_stack : s_rt.task_stack; s_rt.task_prio = rt->task_prio ? rt->task_prio : s_rt.task_prio; s_rt.init_retry_ms = rt->init_retry_ms ? rt->init_retry_ms : s_rt.init_retry_ms; s_rt.backoff_start_ms = rt->backoff_start_ms ? rt->backoff_start_ms : s_rt.backoff_start_ms; s_rt.backoff_max_ms = rt->backoff_max_ms ? rt->backoff_max_ms : s_rt.backoff_max_ms; s_rt.fails_before_reinit = rt->fails_before_reinit ? rt->fails_before_reinit : s_rt.fails_before_reinit; s_rt.ca_cert_pem_opt = rt->ca_cert_pem_opt; s_rt.http_timeout_ms = (rt->http_timeout_ms > 0) ? rt->http_timeout_ms : s_rt.http_timeout_ms; } s_q = xQueueCreate(s_rt.queue_len, sizeof(influx_msg_t)); if (!s_q) return ESP_ERR_NO_MEM; s_run = true; if (xTaskCreate(net_influx_worker, "influx_worker", s_rt.task_stack, NULL, s_rt.task_prio, &s_task) != pdPASS) { vQueueDelete(s_q); s_q = NULL; s_run = false; return ESP_FAIL; } return ESP_OK; } void net_influx_stop(void) { s_run = false; if (s_task) { vTaskDelete(s_task); s_task = NULL; } if (s_q) { influx_msg_t msg; while (xQueueReceive(s_q, &msg, 0) == pdTRUE) { free_msg(&msg); } vQueueDelete(s_q); s_q = NULL; } } esp_err_t net_influx_submit_point(const net_influx_point_t* p) { if (!p || !p->measurement || !*p->measurement || !p->fields || p->num_fields == 0) { return ESP_ERR_INVALID_ARG; } if (!s_q) return ESP_ERR_INVALID_STATE; influx_msg_t msg = {0}; msg.measurement = dup0(p->measurement); msg.tags = (p->tags && *p->tags) ? dup0(p->tags) : NULL; msg.ts_ms = p->ts_ms; msg.num_fields = p->num_fields; msg.fields = (net_influx_field_t*)calloc(p->num_fields, sizeof(net_influx_field_t)); if (!msg.measurement || !msg.fields) { free_msg(&msg); return ESP_ERR_NO_MEM; } for (size_t i = 0; i < p->num_fields; ++i) { msg.fields[i] = p->fields[i]; // deep copy key msg.fields[i].key = dup0(p->fields[i].key); if (!msg.fields[i].key) { free_msg(&msg); return ESP_ERR_NO_MEM; } // deep copy string value if needed if (p->fields[i].type == NET_INFLUX_F_STRING && p->fields[i].v.s) { msg.fields[i].v.s = dup0(p->fields[i].v.s); if (!msg.fields[i].v.s) { free_msg(&msg); return ESP_ERR_NO_MEM; } } } // Non-blocking enqueue; wenn voll: drop oldest if (xQueueSend(s_q, &msg, 0) != pdPASS) { influx_msg_t dump; if (xQueueReceive(s_q, &dump, 0) == pdTRUE) free_msg(&dump); if (xQueueSend(s_q, &msg, 0) != pdPASS) { free_msg(&msg); return ESP_FAIL; } } return ESP_OK; }