Files
nanopsx/firmware/src/net_influx.c
T
admin 2352075c58 refactor: entkopple mDNS-Discovery, Status-Flags und WiFi-Manager
- net_mdns: Autostart + Discovery-Retry stabilisiert (Forward-Declarations, Task-Start bei GOT_IP)
- sys_status: EventGroup zentralisiert; Statusbits nicht mehr aus net_mdns gesetzt
- main: Integration von net_mdns Autostart/Discovery und UI-Status-Update vorbereitet
- wifi_mgr: mDNS-Discovery-Logik entfernt/vereinheitlicht, damit keine doppelte Discovery läuft
- net_influx: Anpassungen an neue Discovery/Storage-Semantik
2026-01-22 13:45:15 +01:00

318 lines
11 KiB
C

// File: src/net_influx.c
#include "esp_http_client.h"
#include "esp_err.h"
#include "esp_log.h"
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <stdlib.h>
#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};
/* ---------------- 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);
}
}
/* ---------------- 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;
}
/* ---------------- 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,
...)
{
// --- Neu: 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[400];
int off = 0;
off += snprintf(line + off, sizeof(line) - off, "%s", measurement);
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; } // <—
}
// 3) 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);
// 4) Pfad (Tipp: URL-encoding wenn org/bucket Sonderzeichen haben könnten)
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);
// 5) HTTP-Client
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,
// Optional: stabiler auf schlechten Links
.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");
// Optional hilfreich:
// esp_http_client_set_header(h, "Accept", "application/json");
// esp_http_client_set_header(h, "Connection", "close");
// Body
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;
}
// 6) Request
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): <kein Body>", status);
}
} else {
ESP_LOGE(TAG, "perform: %s", esp_err_to_name(err));
}
esp_http_client_cleanup(h);
// --- Wichtig: Flag NACH allem zentral setzen ---
ok = (err == ESP_OK && status == 204);
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?)");
// Du kannst hier optional einen Default setzen oder ESP_ERR_NOT_FOUND zurückgeben
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;
}