Initial commit for nanopsx
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
idf_component_register(
|
||||
SRCS
|
||||
"main.c"
|
||||
"lv_fs_port.c"
|
||||
"i2cdev.c"
|
||||
"sensirion_common.c"
|
||||
"sensirion_i2c.c"
|
||||
"sensirion_i2c_hal.c"
|
||||
"sen5x_i2c.c"
|
||||
"sen5x_app.c"
|
||||
"wifi_mgr.c"
|
||||
"http_portal.c"
|
||||
"storage.c"
|
||||
"dns_captive.c"
|
||||
"net_mdns.c"
|
||||
"net_influx.c"
|
||||
"sys_status.c"
|
||||
INCLUDE_DIRS
|
||||
"."
|
||||
REQUIRES
|
||||
driver
|
||||
freertos
|
||||
log
|
||||
)
|
||||
@@ -0,0 +1,138 @@
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_netif.h"
|
||||
|
||||
#include "lwip/udp.h"
|
||||
#include "lwip/sockets.h"
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "dns_captive.h"
|
||||
|
||||
static const char *TAG = "dns_captive";
|
||||
|
||||
// ---------- State ----------
|
||||
static TaskHandle_t s_dns_task_handle = NULL;
|
||||
static esp_netif_t *s_netif_ap = NULL;
|
||||
|
||||
// ---------- DNS Paketlayout ----------
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint16_t id, flags, qdcount, ancount, nscount, arcount;
|
||||
} dns_hdr_t;
|
||||
|
||||
// ---------- Internals ----------
|
||||
static void dns_task(void *arg) {
|
||||
(void)arg;
|
||||
|
||||
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (sock < 0) {
|
||||
ESP_LOGE(TAG, "socket() fehlgeschlagen");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr = {0};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(53);
|
||||
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
|
||||
if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
|
||||
ESP_LOGE(TAG, "bind(:53) fehlgeschlagen");
|
||||
close(sock);
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "DNS Server läuft auf :53");
|
||||
|
||||
for (;;) {
|
||||
uint8_t buf[512];
|
||||
struct sockaddr_in from; socklen_t fromlen = sizeof(from);
|
||||
int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen);
|
||||
if (n <= (int)sizeof(dns_hdr_t)) continue;
|
||||
|
||||
dns_hdr_t *h = (dns_hdr_t*)buf;
|
||||
uint16_t id = ntohs(h->id);
|
||||
uint16_t qd = ntohs(h->qdcount);
|
||||
if (qd == 0) continue;
|
||||
|
||||
int pos = sizeof(dns_hdr_t);
|
||||
for (int qi = 0; qi < qd; ++qi) {
|
||||
while (pos < n && buf[pos] != 0) {
|
||||
uint8_t l = buf[pos];
|
||||
pos += 1 + l;
|
||||
}
|
||||
pos += 1; // null label
|
||||
pos += 4; // type + class
|
||||
}
|
||||
if (pos + 16 > (int)sizeof(buf)) continue;
|
||||
|
||||
// Ziel-IP: AP-IP falls vorhanden, sonst 192.168.4.1
|
||||
ip4_addr_t ip = { .addr = 0 };
|
||||
if (s_netif_ap) {
|
||||
esp_netif_ip_info_t ipi;
|
||||
if (esp_netif_get_ip_info(s_netif_ap, &ipi) == ESP_OK) {
|
||||
ip.addr = ipi.ip.addr; // already network order
|
||||
}
|
||||
}
|
||||
if (ip.addr == 0) {
|
||||
struct in_addr tmp;
|
||||
inet_aton("192.168.4.1", &tmp);
|
||||
ip.addr = tmp.s_addr;
|
||||
}
|
||||
|
||||
uint8_t out[512];
|
||||
memcpy(out, buf, pos);
|
||||
dns_hdr_t *oh = (dns_hdr_t*)out;
|
||||
oh->id = htons(id);
|
||||
oh->flags = htons(0x8180); // Standard response / no error
|
||||
oh->qdcount = htons(qd);
|
||||
oh->ancount = htons(1);
|
||||
oh->nscount = 0;
|
||||
oh->arcount = 0;
|
||||
|
||||
int opos = pos;
|
||||
// Name-Pointer auf erste Frage (0x000c), A-Record, IN, TTL=30, RDLEN=4
|
||||
out[opos++] = 0xC0; out[opos++] = 0x0C;
|
||||
out[opos++] = 0x00; out[opos++] = 0x01;
|
||||
out[opos++] = 0x00; out[opos++] = 0x01;
|
||||
out[opos++] = 0x00; out[opos++] = 0x00; out[opos++] = 0x00; out[opos++] = 0x1E;
|
||||
out[opos++] = 0x00; out[opos++] = 0x04;
|
||||
|
||||
uint32_t ipbe = ip.addr;
|
||||
memcpy(&out[opos], &ipbe, 4); opos += 4;
|
||||
|
||||
(void)sendto(sock, out, opos, 0, (struct sockaddr*)&from, fromlen);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Public API ----------
|
||||
void dns_captive_set_ap_netif(esp_netif_t *netif_ap) {
|
||||
s_netif_ap = netif_ap;
|
||||
}
|
||||
|
||||
esp_err_t dns_captive_start(void) {
|
||||
if (s_dns_task_handle) {
|
||||
return ESP_OK;
|
||||
}
|
||||
BaseType_t ok = xTaskCreatePinnedToCore(dns_task, "dns", 4096, NULL, 4, &s_dns_task_handle, 0);
|
||||
if (ok != pdPASS) {
|
||||
s_dns_task_handle = NULL;
|
||||
return ESP_FAIL;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void dns_captive_stop(void) {
|
||||
if (s_dns_task_handle) {
|
||||
vTaskDelete(s_dns_task_handle);
|
||||
s_dns_task_handle = NULL;
|
||||
ESP_LOGI(TAG, "DNS Server gestoppt");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_netif.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Setzt das AP-Netif, aus dem die eigene IP für DNS-Antworten gelesen wird.
|
||||
* Darf NULL sein; dann wird 192.168.4.1 als Fallback genutzt.
|
||||
*/
|
||||
void dns_captive_set_ap_netif(esp_netif_t *netif_ap);
|
||||
|
||||
/**
|
||||
* Startet den minimalistischen DNS-Server (falls noch nicht aktiv).
|
||||
* Gibt ESP_OK zurück, wenn der Task läuft oder erfolgreich gestartet wurde.
|
||||
*/
|
||||
esp_err_t dns_captive_start(void);
|
||||
|
||||
/**
|
||||
* Stoppt den DNS-Server-Task (idempotent).
|
||||
*/
|
||||
void dns_captive_stop(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2019 Tomoyuki Sakurai <y@trombik.org>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#if !defined(__ESP_IDF_LIB_HELPERS__H__)
|
||||
#define __ESP_IDF_LIB_HELPERS__H__
|
||||
|
||||
/* XXX this header file does not need to include freertos/FreeRTOS.h.
|
||||
* but without it, ESP8266 RTOS SDK does not include `sdkconfig.h` in correct
|
||||
* order. as this header depends on sdkconfig.h, sdkconfig.h must be included
|
||||
* first. however, the SDK includes this header first, then includes
|
||||
* `sdkconfig.h` when freertos/FreeRTOS.h is not explicitly included. an
|
||||
* evidence can be found in `build/${COMPONENT}/${COMPONENT}.d` in a failed
|
||||
* build.
|
||||
*/
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <esp_idf_version.h>
|
||||
|
||||
#if !defined(ESP_IDF_VERSION) || !defined(ESP_IDF_VERSION_VAL)
|
||||
#error Unknown ESP-IDF/ESP8266 RTOS SDK version
|
||||
#endif
|
||||
|
||||
/* Minimal supported version for ESP32, ESP32S2 */
|
||||
#define HELPER_ESP32_MIN_VER ESP_IDF_VERSION_VAL(3, 3, 5)
|
||||
/* Minimal supported version for ESP8266 */
|
||||
#define HELPER_ESP8266_MIN_VER ESP_IDF_VERSION_VAL(3, 3, 0)
|
||||
|
||||
/* HELPER_TARGET_IS_ESP32
|
||||
* 1 when the target is esp32
|
||||
*/
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32S2) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32S3) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32C2) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32C3) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32C5) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32C6) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32P4) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32C61) \
|
||||
|| defined(CONFIG_IDF_TARGET_ESP32H2)
|
||||
#define HELPER_TARGET_IS_ESP32 (1)
|
||||
|
||||
/* HELPER_TARGET_IS_ESP8266
|
||||
* 1 when the target is esp8266
|
||||
*/
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP8266)
|
||||
#define HELPER_TARGET_IS_ESP8266 (1)
|
||||
#else
|
||||
#error BUG: cannot determine the target
|
||||
#endif
|
||||
|
||||
#if HELPER_TARGET_IS_ESP32 && ESP_IDF_VERSION < HELPER_ESP32_MIN_VER
|
||||
#error Unsupported ESP-IDF version. Please update!
|
||||
#endif
|
||||
|
||||
#if HELPER_TARGET_IS_ESP8266 && ESP_IDF_VERSION < HELPER_ESP8266_MIN_VER
|
||||
#error Unsupported ESP8266 RTOS SDK version. Please update!
|
||||
#endif
|
||||
|
||||
/* HELPER_SPI_HOST_DEFAULT
|
||||
*
|
||||
* The default SPI_HOST for spi_host_device_t
|
||||
*/
|
||||
#if CONFIG_IDF_TARGET_ESP32
|
||||
#define HELPER_SPI_HOST_DEFAULT HSPI_HOST
|
||||
#elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
|
||||
#define HELPER_SPI_HOST_DEFAULT SPI2_HOST
|
||||
#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C5 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32C61
|
||||
#define HELPER_SPI_HOST_DEFAULT SPI1_HOST
|
||||
#elif CONFIG_IDF_TARGET_ESP32H2
|
||||
#define HELPER_SPI_HOST_DEFAULT SPI1_HOST
|
||||
#elif CONFIG_IDF_TARGET_ESP32P4
|
||||
#define HELPER_SPI_HOST_DEFAULT SPI1_HOST
|
||||
#endif
|
||||
|
||||
/* show the actual values for debugging */
|
||||
#if DEBUG
|
||||
#define VALUE_TO_STRING(x) #x
|
||||
#define VALUE(x) VALUE_TO_STRING(x)
|
||||
#define VAR_NAME_VALUE(var) #var "=" VALUE(var)
|
||||
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32C3))
|
||||
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32H2))
|
||||
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32S2))
|
||||
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32))
|
||||
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP8266))
|
||||
#pragma message(VAR_NAME_VALUE(ESP_IDF_VERSION_MAJOR))
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
#if CONFIG_IDF_TARGET_ESP32
|
||||
#include <esp32/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32C2
|
||||
#include <esp32c2/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32C3
|
||||
#include <esp32c3/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32C5
|
||||
#include <esp32c5/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32C6
|
||||
#include <esp32c6/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32C61
|
||||
#include <esp32c61/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32H2
|
||||
#include <esp32h2/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32H4
|
||||
#include <esp32h4/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32S2
|
||||
#include <esp32s2/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32S3
|
||||
#include <esp32s3/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP32P4
|
||||
#include <esp32p4/rom/ets_sys.h>
|
||||
#elif CONFIG_IDF_TARGET_ESP8266
|
||||
#include <rom/ets_sys.h>
|
||||
#else
|
||||
#error "ets_sys: Unknown target"
|
||||
#endif
|
||||
@@ -0,0 +1,679 @@
|
||||
// File: src/http_portal.c
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_http_server.h"
|
||||
#include "esp_netif.h"
|
||||
|
||||
#include "http_portal.h"
|
||||
#include "storage.h"
|
||||
|
||||
// Diese beiden werden vom WiFi-Manager bereitgestellt (in wifi_mgr.c definiert)
|
||||
bool wifi_mgr_load_sta_creds(char **out_ssid, char **out_pass);
|
||||
void wifi_mgr_save_sta_creds_and_reconnect(const char* ssid, const char* pass);
|
||||
|
||||
static void __attribute__((unused)) log_one_hdr(httpd_req_t *req, const char* key) {
|
||||
size_t len = httpd_req_get_hdr_value_len(req, key);
|
||||
if (len == 0) return;
|
||||
if (len < 1024) {
|
||||
char *val = calloc(1, len + 1);
|
||||
if (val && httpd_req_get_hdr_value_str(req, key, val, len + 1) == ESP_OK) {
|
||||
ESP_LOGI("portal_http", " H %s (%u): %s", key, (unsigned)len, val);
|
||||
} else {
|
||||
ESP_LOGI("portal_http", " H %s (%u): <alloc/get failed>", key, (unsigned)len);
|
||||
}
|
||||
free(val);
|
||||
} else {
|
||||
ESP_LOGI("portal_http", " H %s LEN=%u (too long to print)", key, (unsigned)len);
|
||||
}
|
||||
}
|
||||
|
||||
// Geräteeigenschaften speichern (in wifi_mgr.c implementieren)
|
||||
void wifi_mgr_save_device_info(const char* devicename, const char* token, const char* bucket, const char* org);
|
||||
|
||||
static const char *TAG = "portal_http";
|
||||
|
||||
static httpd_handle_t s_http = NULL;
|
||||
static EventGroupHandle_t s_wifi_events = NULL;
|
||||
static EventBits_t s_BIT_GOTIP = 0;
|
||||
static EventBits_t s_BIT_FAIL = 0;
|
||||
static char s_ap_ssid[33] = {0};
|
||||
static bool s_force_captive = true; // true = Portal immer zeigen
|
||||
|
||||
// === Neue, feste Limits ===
|
||||
#define MAX_SSID_BYTES 32 // IEEE 802.11
|
||||
#define MIN_PASS_CHARS 8 // WPA2/3 Passphrase
|
||||
#define MAX_PASS_CHARS 63 // WPA2/3 Passphrase (nicht PSK)
|
||||
#define PSK_HEX_LEN 64 // 64-stellige Hex-PSK
|
||||
#define MAX_TOKEN_CHARS 256 // groß genug (88 Beispiel + Reserve)
|
||||
#define MAX_DEV_CHARS 63
|
||||
#define MAX_BUCKET_CHARS 128
|
||||
#define MAX_ORG_CHARS 128
|
||||
#define MAX_FORM_BYTES 16384 // max. Bodygröße akzeptieren
|
||||
|
||||
// --- Logging helpers ---
|
||||
static const char* method_str(httpd_method_t m) {
|
||||
switch (m) {
|
||||
case HTTP_GET: return "GET";
|
||||
case HTTP_POST: return "POST";
|
||||
case HTTP_PUT: return "PUT";
|
||||
case HTTP_DELETE: return "DELETE";
|
||||
case HTTP_HEAD: return "HEAD";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
static void log_req_basic(httpd_req_t *req, const char* where) {
|
||||
ESP_LOGI("portal_http", "[%s] %s %s", where, method_str(req->method), req->uri);
|
||||
// Einige typische Header auslesen (nur wenn vorhanden)
|
||||
const char* keys[] = { "Host", "User-Agent", "Accept", "Accept-Language", "Connection" };
|
||||
for (size_t i = 0; i < sizeof(keys)/sizeof(keys[0]); ++i) {
|
||||
size_t len = httpd_req_get_hdr_value_len(req, keys[i]);
|
||||
if (len > 0 && len < 512) {
|
||||
char *val = calloc(1, len + 1);
|
||||
if (val) {
|
||||
if (httpd_req_get_hdr_value_str(req, keys[i], val, len + 1) == ESP_OK) {
|
||||
ESP_LOGI("portal_http", " H %s: %s", keys[i], val);
|
||||
}
|
||||
free(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void log_resp_basic(const char* where, const char* status, const char* type, int content_len) {
|
||||
ESP_LOGI("portal_http", "[%s] RESP %s, type=%s, len=%d", where, status ? status : "?", type ? type : "?", content_len);
|
||||
}
|
||||
|
||||
// ---------- Helfer ----------
|
||||
static char* html_escape(const char* s) {
|
||||
if (!s) return strdup("");
|
||||
size_t len = 0;
|
||||
for (const char* p = s; *p; ++p) {
|
||||
switch(*p){ case '&': len+=5; break; case '<': case '>': len+=4; break; case '"': case '\'': len+=6; break; default: len+=1; }
|
||||
}
|
||||
char* out = (char*)malloc(len+1); if(!out) return NULL;
|
||||
char* o = out;
|
||||
for (const char* p = s; *p; ++p) {
|
||||
switch(*p){
|
||||
case '&': memcpy(o,"&",5); o+=5; break;
|
||||
case '<': memcpy(o,"<",4); o+=4; break;
|
||||
case '>': memcpy(o,">",4); o+=4; break;
|
||||
case '"': memcpy(o,""",6);o+=6; break;
|
||||
case '\'':memcpy(o,"'",5); o+=5; break;
|
||||
default: *o++ = *p;
|
||||
}
|
||||
}
|
||||
*o = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
// Sehr simpler JSON-Escape (für SSIDs in /scan)
|
||||
static void json_escape(const char* in, char* out, size_t outlen) {
|
||||
size_t j = 0;
|
||||
for (size_t i = 0; in && in[i] && j + 2 < outlen; ++i) {
|
||||
unsigned char c = (unsigned char)in[i];
|
||||
if (c == '"' || c == '\\') {
|
||||
if (j + 2 < outlen) { out[j++]='\\'; out[j++]=c; }
|
||||
} else if (c <= 0x1F) {
|
||||
if (j + 6 < outlen) {
|
||||
j += (size_t)snprintf(out + j, outlen - j, "\\u%04x", c);
|
||||
} else break;
|
||||
} else {
|
||||
out[j++] = (char)c;
|
||||
}
|
||||
}
|
||||
out[j] = '\0';
|
||||
}
|
||||
|
||||
// === Neue kleine Helfer ===
|
||||
static inline bool is_hex(char c){
|
||||
return (c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F');
|
||||
}
|
||||
static bool is_hex_string(const char* s, size_t n){
|
||||
for(size_t i=0;i<n;i++) if(!is_hex(s[i])) return false;
|
||||
return true;
|
||||
}
|
||||
static char* dup_with_limit(const char* s, size_t max){
|
||||
size_t n = strnlen(s, max + 1);
|
||||
if (n > max) return NULL;
|
||||
char* r = (char*)malloc(n + 1);
|
||||
if (!r) return NULL;
|
||||
memcpy(r, s, n); r[n] = '\0';
|
||||
return r;
|
||||
}
|
||||
|
||||
// ---------- HTML (mit Platzhalter) ----------
|
||||
static const char form_html_tpl[] =
|
||||
"<!doctype html><html><head><meta charset='utf-8'/>"
|
||||
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
|
||||
"<title>Wi-Fi Setup</title>"
|
||||
"<style>body{font-family:system-ui,Arial;margin:2rem;line-height:1.4}"
|
||||
"label{display:block;margin-top:1rem}input,select{padding:.5rem;width:100%%;max-width:28rem}"
|
||||
"button{margin-top:1rem;padding:.6rem 1rem;border:0;border-radius:.6rem;background:#0b6cff;color:#fff;}"
|
||||
".card{max-width:32rem;padding:1rem 1.25rem;border:1px solid #e5e5e5;border-radius:1rem;box-shadow:0 2px 10px rgba(0,0,0,.04)}"
|
||||
".row{display:flex;gap:.5rem;align-items:center;max-width:28rem}"
|
||||
".muted{color:#666;font-size:.9em}</style>"
|
||||
"</head><body><div class='card'>"
|
||||
"<h1>Wi-Fi Configuration</h1>"
|
||||
"<p>Connected to <b>%s</b>. Choose your Wi-Fi network or enter it manually:</p>"
|
||||
"<div class='row'><select id='nets'></select><button id='refresh' type='button'>Refresh</button></div>"
|
||||
"<form method='POST' action='/save'>"
|
||||
"<label>SSID*<input id='ssid' name='ssid' required maxlength='32'></label>"
|
||||
"<label>Password*<input name='pass' type='password' required minlength='8' maxlength='63' pattern='.{8,63}|[0-9A-Fa-f]{64}'></label>"
|
||||
"<label>Device Name*<input id='dev' name='dev' required value='%s' maxlength='63' placeholder=''></label>"
|
||||
"<label>Organization (optional)<input id='org' name='org' placeholder='' value='%s' maxlength='128'></label>"
|
||||
"<label>Bucket (optional)<input id='bucket' name='bucket' placeholder='' value='%s' maxlength='128'></label>"
|
||||
"<label>Token<input id='token' name='token' placeholder='' maxlength='256'></label>"
|
||||
"<button type='submit'>Save & Connect</button>"
|
||||
"</form>"
|
||||
"<p class='muted'>After saving, the device will connect to your Wi-Fi network. "
|
||||
"The access point will automatically shut down shortly afterward.</p>"
|
||||
"</div>"
|
||||
"<script>"
|
||||
"async function load(){try{"
|
||||
" let r=await fetch('/scan'); if(!r.ok) throw 0; let a=await r.json();"
|
||||
" let s=document.getElementById('nets'); s.innerHTML='';"
|
||||
" a.sort((x,y)=>y.rssi-x.rssi);"
|
||||
" a.forEach(n=>{let o=document.createElement('option');"
|
||||
" o.value=n.ssid; o.textContent=n.ssid+' ('+n.rssi+' dBm)'; s.appendChild(o);});"
|
||||
" if(a.length && !document.getElementById('ssid').value){"
|
||||
" document.getElementById('ssid').value=a[0].ssid;}"
|
||||
"}catch(e){console.log(e);}}"
|
||||
"document.getElementById('refresh').onclick=load;"
|
||||
"document.getElementById('nets').onchange=function(){document.getElementById('ssid').value=this.value;};"
|
||||
"load();"
|
||||
"</script>"
|
||||
"</body></html>";
|
||||
|
||||
static const char saved_html[] =
|
||||
"<!doctype html><html><head><meta charset='utf-8'/>"
|
||||
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
|
||||
"<title>Saved</title></head><body>"
|
||||
"<h1>✔️ Saved</h1>"
|
||||
"<p>The credentials have been saved. The device is now connecting to your Wi-Fi…</p>"
|
||||
"<script>setTimeout(()=>location.href='/status',1500)</script>"
|
||||
"</body></html>";
|
||||
|
||||
static const char status_tpl[] =
|
||||
"<!doctype html><html><head><meta charset='utf-8'/>"
|
||||
"<meta name='viewport' content='width=device-width,initial-scale=1'/>"
|
||||
"<title>Status</title>"
|
||||
"<style>body{font-family:system-ui,Arial;margin:2rem} .ok{color:#0a0} .err{color:#b00} .muted{color:#666}</style>"
|
||||
"</head><body>"
|
||||
"<h1>Connection Status</h1>"
|
||||
"<p id='msg' class='muted'>⏳ Connecting...</p>"
|
||||
"<p><a href='/'>Back</a></p>"
|
||||
"<script>"
|
||||
"async function poll(){"
|
||||
" try{"
|
||||
" const r = await fetch('/status.json',{cache:'no-store'});"
|
||||
" if(!r.ok) throw 0; const j = await r.json();"
|
||||
" const m = document.getElementById('msg');"
|
||||
" if(j.state==='got_ip'){ m.textContent='✅ Connected'+(j.ip?(' (IP '+j.ip+')'):''); m.className='ok'; return; }"
|
||||
" if(j.state==='fail'){ m.textContent='❌ Connection failed. Please check your data.'; m.className='err'; return; }"
|
||||
" m.textContent='⏳ Connecting...'; m.className='muted';"
|
||||
" }catch(e){ /* ignore */ }"
|
||||
" setTimeout(poll, 1000);"
|
||||
"}"
|
||||
"poll();"
|
||||
"</script>"
|
||||
"</body></html>";
|
||||
|
||||
|
||||
// ---------- sehr simpler URL-Decoder ----------
|
||||
static int hexval(char c){ if(c>='0'&&c<='9')return c-'0'; if(c>='a'&&c<='f')return 10+c-'a'; if(c>='A'&&c<='F')return 10+c-'A'; return -1; }
|
||||
static void urldecode(char* s){
|
||||
char* o = s;
|
||||
for (char* i = s; *i; ++i) {
|
||||
if (*i == '+') { *o++ = ' '; }
|
||||
else if (*i == '%' && i[1] && i[2]) {
|
||||
int h1 = hexval(i[1]), h2 = hexval(i[2]);
|
||||
if (h1 >= 0 && h2 >= 0) { *o++ = (char)((h1<<4)|h2); i += 2; }
|
||||
else { *o++ = *i; } // ungültiges %, unverändert übernehmen
|
||||
} else { *o++ = *i; }
|
||||
}
|
||||
*o = '\0';
|
||||
}
|
||||
|
||||
// ---------- HTTP-Handler ----------
|
||||
static esp_err_t root_get(httpd_req_t *req) {
|
||||
// 1) Effektive Influx-Werte laden (fällt auf Defaults zurück)
|
||||
log_req_basic(req, "root_get");
|
||||
char *org = NULL, *bucket = NULL, *token = NULL;
|
||||
if (!storage_get_effective_influx(&org, &bucket, &token)) {
|
||||
org = strdup("");
|
||||
bucket = strdup("");
|
||||
token = strdup("");
|
||||
if (!org || !bucket || !token) {
|
||||
if (org) free(org);
|
||||
if (bucket) free(bucket);
|
||||
if (token) free(token);
|
||||
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Effektiven Devicenamen laden (fällt intern auf DEFAULT_DEVNAME zurück)
|
||||
char *dev_raw = NULL;
|
||||
if (!storage_get_effective_device_name(&dev_raw)) {
|
||||
dev_raw = strdup("");
|
||||
if (!dev_raw) {
|
||||
free(org); free(bucket); free(token);
|
||||
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
}
|
||||
}
|
||||
|
||||
// 3) HTML-escaping
|
||||
char *dev_esc = html_escape(dev_raw);
|
||||
char *org_esc = html_escape(org ? org : "");
|
||||
char *bucket_esc = html_escape(bucket ? bucket : "");
|
||||
char *ap_esc = html_escape(s_ap_ssid); // NEU: AP-SSID escapen
|
||||
if (!dev_esc || !org_esc || !bucket_esc || !ap_esc) {
|
||||
if (dev_esc) free(dev_esc);
|
||||
if (org_esc) free(org_esc);
|
||||
if (bucket_esc) free(bucket_esc);
|
||||
if (ap_esc) free(ap_esc);
|
||||
free(org);
|
||||
free(bucket);
|
||||
free(token);
|
||||
free(dev_raw);
|
||||
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
}
|
||||
|
||||
// 4) Seite rendern
|
||||
int need = snprintf(NULL, 0, form_html_tpl, ap_esc, dev_esc, org_esc, bucket_esc);
|
||||
if (need < 0) {
|
||||
free(org); free(bucket); free(token); free(dev_raw);
|
||||
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
|
||||
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "format error");
|
||||
}
|
||||
|
||||
char *page = (char*)malloc((size_t)need + 1);
|
||||
if (!page) {
|
||||
free(org); free(bucket); free(token); free(dev_raw);
|
||||
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
|
||||
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
}
|
||||
|
||||
snprintf(page, (size_t)need + 1, form_html_tpl, ap_esc, dev_esc, org_esc, bucket_esc);
|
||||
|
||||
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
log_resp_basic("root_get", "200 OK", "text/html; charset=utf-8", need);
|
||||
esp_err_t r = httpd_resp_send(req, page, HTTPD_RESP_USE_STRLEN);
|
||||
|
||||
// 5) Cleanup
|
||||
free(page);
|
||||
free(org); free(bucket); free(token);
|
||||
free(dev_raw);
|
||||
free(dev_esc); free(org_esc); free(bucket_esc); free(ap_esc);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
// Captive-Portal Endpunkte (Apple, Android, Windows)
|
||||
static void get_ap_ip_str(char ipstr[16]) {
|
||||
ipstr[0] = '\0';
|
||||
esp_netif_t *ap = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
|
||||
if (!ap) return;
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(ap, &ip) == ESP_OK) {
|
||||
snprintf(ipstr, 16, IPSTR, IP2STR(&ip.ip));
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t captive_ok(httpd_req_t *req) {
|
||||
log_req_basic(req, "captive_ok");
|
||||
|
||||
// Wenn wir nicht mehr "erzwingen" und STA schon online ist -> 204 (schließt Captive auf dem Handy)
|
||||
if (!s_force_captive) {
|
||||
EventBits_t bits = xEventGroupGetBits(s_wifi_events);
|
||||
if (bits & s_BIT_GOTIP) {
|
||||
httpd_resp_set_status(req, "204 No Content");
|
||||
httpd_resp_set_type(req, "text/plain");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
log_resp_basic("captive_ok", "204 No Content", "text/plain", 0);
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// >>> WICHTIG: Für Android/Apple/Windows lieber ein 302-Redirect auf das Portal
|
||||
char ipstr[16]; get_ap_ip_str(ipstr);
|
||||
char loc[64];
|
||||
if (ipstr[0]) snprintf(loc, sizeof(loc), "http://%s/", ipstr);
|
||||
else snprintf(loc, sizeof(loc), "/");
|
||||
|
||||
httpd_resp_set_status(req, "302 Found");
|
||||
httpd_resp_set_hdr(req, "Location", loc); // absolute URL ist am sichersten für manche ROMs
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
// KEIN Body → Content-Length: 0
|
||||
log_resp_basic("captive_ok", "302 Found", "redirect", 0);
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
static esp_err_t status_get(httpd_req_t *req) {
|
||||
log_req_basic(req, "status_get");
|
||||
|
||||
// Kein Formatieren nötig – Template enthält keine %s
|
||||
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
|
||||
int len = (int)strlen(status_tpl);
|
||||
log_resp_basic("status_get", "200 OK", "text/html; charset=utf-8", len);
|
||||
return httpd_resp_send(req, status_tpl, HTTPD_RESP_USE_STRLEN);
|
||||
}
|
||||
|
||||
|
||||
static esp_err_t favicon_get(httpd_req_t *req) {
|
||||
httpd_resp_set_status(req, "204 No Content");
|
||||
httpd_resp_set_type(req, "image/x-icon");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
static esp_err_t save_post(httpd_req_t *req) {
|
||||
log_req_basic(req, "save_post");
|
||||
ESP_LOGI("portal_http", "[save_post] content_len (req->content_len) = %d", (int)req->content_len);
|
||||
|
||||
// Body vollständig lesen (ggf. in mehreren recv-Aufrufen)
|
||||
size_t content_len = (size_t)req->content_len;
|
||||
|
||||
// Hartes Limit (gegen OOM/DoS)
|
||||
if (content_len == 0 || content_len > MAX_FORM_BYTES) {
|
||||
httpd_resp_set_status(req, "413 Request Entity Too Large");
|
||||
httpd_resp_set_type(req, "text/plain; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_send(req, "payload too large", HTTPD_RESP_USE_STRLEN);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
char *buf = (char*)calloc(1, content_len + 1);
|
||||
if (!buf) return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
|
||||
size_t received = 0;
|
||||
while (received < content_len) {
|
||||
int r = httpd_req_recv(req, buf + received, content_len - received);
|
||||
if (r == HTTPD_SOCK_ERR_TIMEOUT) continue; // nochmal versuchen
|
||||
if (r <= 0) { free(buf); return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "recv fail"); }
|
||||
received += (size_t)r;
|
||||
}
|
||||
buf[received] = '\0';
|
||||
|
||||
// ssid=...&pass=...&dev=...&token=...&bucket=...&org=...
|
||||
char *ssid = NULL, *pass = NULL, *dev = NULL, *token = NULL, *bucket = NULL, *org = NULL;
|
||||
|
||||
// Wir parsen in-place
|
||||
char *p = buf;
|
||||
while (p && *p) {
|
||||
char *key = p;
|
||||
char *eq = strchr(key, '=');
|
||||
if (!eq) break;
|
||||
*eq = 0;
|
||||
char *val = eq + 1;
|
||||
char *amp = strchr(val, '&');
|
||||
if (amp) { *amp = 0; p = amp + 1; } else p = NULL;
|
||||
|
||||
urldecode(val);
|
||||
if (!strcmp(key, "ssid")) { ssid = dup_with_limit(val, MAX_SSID_BYTES); }
|
||||
else if (!strcmp(key, "pass")) { pass = strdup(val); } // validieren wir später
|
||||
else if (!strcmp(key, "dev")) { dev = dup_with_limit(val, MAX_DEV_CHARS); }
|
||||
else if (!strcmp(key, "token")){ token = dup_with_limit(val, MAX_TOKEN_CHARS); }
|
||||
else if (!strcmp(key, "bucket")){bucket = dup_with_limit(val, MAX_BUCKET_CHARS); }
|
||||
else if (!strcmp(key, "org")) { org = dup_with_limit(val, MAX_ORG_CHARS); }
|
||||
}
|
||||
free(buf);
|
||||
|
||||
// Pflichtfelder prüfen + Längen/Format validieren
|
||||
if (!ssid || !pass || !dev || dev[0] == '\0') {
|
||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing ssid/pass/dev or invalid length");
|
||||
goto cleanup_bad;
|
||||
}
|
||||
|
||||
if (strlen(ssid) == 0 || strlen(ssid) > MAX_SSID_BYTES) {
|
||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "SSID too long (max 32 bytes)");
|
||||
goto cleanup_bad;
|
||||
}
|
||||
|
||||
size_t pn = strlen(pass);
|
||||
if (!((pn >= MIN_PASS_CHARS && pn <= MAX_PASS_CHARS) || (pn == PSK_HEX_LEN && is_hex_string(pass, pn)))) {
|
||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Password must be 8-63 chars or 64 hex");
|
||||
goto cleanup_bad;
|
||||
}
|
||||
|
||||
if (token && strlen(token) > MAX_TOKEN_CHARS) {
|
||||
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Token too long");
|
||||
goto cleanup_bad;
|
||||
}
|
||||
|
||||
// Seite sofort senden (UI reagiert schnell)
|
||||
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
|
||||
log_resp_basic("save_post", "200 OK", "text/html; charset=utf-8", (int)strlen(saved_html));
|
||||
httpd_resp_send(req, saved_html, HTTPD_RESP_USE_STRLEN);
|
||||
|
||||
// Geräteeigenschaften speichern
|
||||
wifi_mgr_save_device_info(
|
||||
dev,
|
||||
(token && token[0]) ? token : NULL, // NULL = nicht geändert
|
||||
(bucket && bucket[0]) ? bucket : NULL,
|
||||
(org && org[0]) ? org : NULL
|
||||
);
|
||||
|
||||
// STA-Creds speichern & reconnect
|
||||
wifi_mgr_save_sta_creds_and_reconnect(ssid, pass);
|
||||
s_force_captive = false; // Captive beenden; OS darf 204 sehen
|
||||
|
||||
// Cleanup (Erfolgsweg)
|
||||
free(ssid); free(pass); free(dev);
|
||||
if (token) free(token);
|
||||
if (bucket) free(bucket);
|
||||
if (org) free(org);
|
||||
|
||||
return ESP_OK;
|
||||
|
||||
cleanup_bad:
|
||||
if (ssid) free(ssid);
|
||||
if (pass) free(pass);
|
||||
if (dev) free(dev);
|
||||
if (token) free(token);
|
||||
if (bucket) free(bucket);
|
||||
if (org) free(org);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Hilfsfunktion: sicherstellen, dass STA-Scan erlaubt ist (AP|STA)
|
||||
static esp_err_t ensure_scan_capable_mode(void) {
|
||||
wifi_mode_t m = WIFI_MODE_NULL;
|
||||
esp_err_t er = esp_wifi_get_mode(&m);
|
||||
if (er != ESP_OK) return er;
|
||||
if (m == WIFI_MODE_STA || m == WIFI_MODE_APSTA) return ESP_OK;
|
||||
// Wenn nur AP aktiv ist → auf APSTA erweitern, damit Scans möglich sind
|
||||
if (m == WIFI_MODE_AP) {
|
||||
return esp_wifi_set_mode(WIFI_MODE_APSTA);
|
||||
}
|
||||
// Falls NULL oder anderes: versuche sicherheitshalber APSTA
|
||||
return esp_wifi_set_mode(WIFI_MODE_APSTA);
|
||||
}
|
||||
|
||||
static esp_err_t scan_get(httpd_req_t *req) {
|
||||
log_req_basic(req, "scan_get");
|
||||
|
||||
httpd_resp_set_type(req, "application/json; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
|
||||
// 0) Mode sicherstellen (damit Scan im AP-Portal funktioniert)
|
||||
esp_err_t er = ensure_scan_capable_mode();
|
||||
if (er != ESP_OK) {
|
||||
const char *msg = "{\"error\":\"wifi mode not scan-capable\",\"code\":1}";
|
||||
return httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
|
||||
}
|
||||
|
||||
// 1) Scan-Konfig
|
||||
wifi_scan_config_t cfg = {
|
||||
.ssid = NULL, .bssid = NULL,
|
||||
.channel = 0, .show_hidden = false,
|
||||
.scan_type = WIFI_SCAN_TYPE_ACTIVE,
|
||||
.scan_time = { .active = { .min = 100, .max = 300 } }
|
||||
};
|
||||
|
||||
// 2) Scan starten – bei Busy kurz retryen
|
||||
const int max_attempts = 5;
|
||||
int attempt = 0;
|
||||
while ((er = esp_wifi_scan_start(&cfg, true)) == ESP_ERR_WIFI_STATE && attempt < max_attempts) {
|
||||
vTaskDelay(pdMS_TO_TICKS(150)); // 150 ms warten und erneut
|
||||
attempt++;
|
||||
}
|
||||
if (er != ESP_OK) {
|
||||
ESP_LOGW("portal_http", "[scan_get] scan_start failed: %d", (int)er);
|
||||
const char *msg = "{\"error\":\"scan start failed\",\"code\":2}";
|
||||
return httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
|
||||
}
|
||||
|
||||
// 3) Ergebnisse
|
||||
uint16_t num = 0;
|
||||
esp_wifi_scan_get_ap_num(&num);
|
||||
ESP_LOGI("portal_http", "[scan_get] found %u APs", (unsigned)num);
|
||||
if (num == 0) {
|
||||
return httpd_resp_send(req, "[]", 2);
|
||||
}
|
||||
|
||||
wifi_ap_record_t *recs = (wifi_ap_record_t*)calloc(num, sizeof(wifi_ap_record_t));
|
||||
if (!recs) return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "oom");
|
||||
esp_wifi_scan_get_ap_records(&num, recs);
|
||||
|
||||
httpd_resp_sendstr_chunk(req, "[");
|
||||
int emitted = 0;
|
||||
for (uint16_t i = 0; i < num; ++i) {
|
||||
if (recs[i].ssid[0] == '\0') continue; // hidden skip
|
||||
char ssid_esc[96];
|
||||
json_escape((char*)recs[i].ssid, ssid_esc, sizeof(ssid_esc));
|
||||
char line[320]; // etwas größer
|
||||
// authmode als int ausgeben, wie zuvor
|
||||
snprintf(line, sizeof(line),
|
||||
"%s{\"ssid\":\"%s\",\"rssi\":%d,\"auth\":%d}",
|
||||
(emitted ? "," : ""),
|
||||
ssid_esc, recs[i].rssi, recs[i].authmode);
|
||||
httpd_resp_sendstr_chunk(req, line);
|
||||
emitted++;
|
||||
if (emitted >= 25) break; // Liste begrenzen
|
||||
}
|
||||
httpd_resp_sendstr_chunk(req, "]");
|
||||
httpd_resp_sendstr_chunk(req, NULL);
|
||||
free(recs);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
|
||||
static esp_err_t not_found_handler(httpd_req_t *req, httpd_err_code_t err) {
|
||||
log_req_basic(req, "404_redirect");
|
||||
char ipstr[16]; get_ap_ip_str(ipstr);
|
||||
char loc[64];
|
||||
if (ipstr[0]) snprintf(loc, sizeof(loc), "http://%s/", ipstr);
|
||||
else snprintf(loc, sizeof(loc), "/");
|
||||
|
||||
httpd_resp_set_status(req, "302 Found");
|
||||
httpd_resp_set_hdr(req, "Location", loc);
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
log_resp_basic("404_redirect", "302 Found", "redirect", 0);
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
static esp_err_t status_json_get(httpd_req_t *req) {
|
||||
EventBits_t bits = xEventGroupGetBits(s_wifi_events);
|
||||
const char *state = (bits & s_BIT_GOTIP) ? "got_ip"
|
||||
: (bits & s_BIT_FAIL) ? "fail"
|
||||
: "connecting";
|
||||
|
||||
// Optional: IP & SSID ausgeben (wenn verfügbar)
|
||||
char ipstr[16] = "";
|
||||
esp_netif_t *sta = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
|
||||
if (sta) {
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(sta, &ip) == ESP_OK) {
|
||||
snprintf(ipstr, sizeof(ipstr), IPSTR, IP2STR(&ip.ip));
|
||||
}
|
||||
}
|
||||
|
||||
httpd_resp_set_type(req, "application/json; charset=utf-8");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
char buf[160];
|
||||
int n = snprintf(buf, sizeof(buf),
|
||||
"{\"state\":\"%s\",\"ip\":\"%s\"}", state, ipstr);
|
||||
return httpd_resp_send(req, buf, n);
|
||||
}
|
||||
|
||||
|
||||
static httpd_handle_t start_http(void) {
|
||||
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
|
||||
cfg.server_port = 80;
|
||||
cfg.uri_match_fn = httpd_uri_match_wildcard; // optional: falls du später /foo/* brauchst
|
||||
cfg.recv_wait_timeout = 10; // Sekunden (default 5), hilft bei lahmen Clients
|
||||
cfg.send_wait_timeout = 10;
|
||||
cfg.lru_purge_enable = true;
|
||||
cfg.max_uri_handlers = 12;
|
||||
if (httpd_start(&s_http, &cfg) != ESP_OK) return NULL;
|
||||
|
||||
// Routen definieren (lokal)
|
||||
httpd_uri_t status_json_uri = { .uri="/status.json", .method=HTTP_GET, .handler=status_json_get };
|
||||
httpd_uri_t root_uri = { .uri="/", .method=HTTP_GET, .handler=root_get };
|
||||
httpd_uri_t g204_uri = { .uri="/generate_204", .method=HTTP_GET, .handler=captive_ok };
|
||||
httpd_uri_t hotsp_uri = { .uri="/hotspot-detect.html", .method=HTTP_GET, .handler=captive_ok };
|
||||
httpd_uri_t msncsi_uri = { .uri="/ncsi.txt", .method=HTTP_GET, .handler=captive_ok };
|
||||
httpd_uri_t status_uri = { .uri="/status", .method=HTTP_GET, .handler=status_get };
|
||||
httpd_uri_t save_uri = { .uri="/save", .method=HTTP_POST, .handler=save_post };
|
||||
httpd_uri_t fav_uri = { .uri="/favicon.ico", .method=HTTP_GET, .handler=favicon_get };
|
||||
httpd_uri_t scan_uri = { .uri="/scan", .method=HTTP_GET, .handler=scan_get };
|
||||
|
||||
httpd_register_uri_handler(s_http, &status_json_uri);
|
||||
httpd_register_uri_handler(s_http, &root_uri);
|
||||
httpd_register_uri_handler(s_http, &g204_uri);
|
||||
httpd_register_uri_handler(s_http, &hotsp_uri);
|
||||
httpd_register_uri_handler(s_http, &msncsi_uri);
|
||||
httpd_register_uri_handler(s_http, &status_uri);
|
||||
httpd_register_uri_handler(s_http, &save_uri);
|
||||
httpd_register_uri_handler(s_http, &fav_uri);
|
||||
httpd_register_uri_handler(s_http, &scan_uri);
|
||||
httpd_register_err_handler(s_http, HTTPD_404_NOT_FOUND, not_found_handler);
|
||||
|
||||
ESP_LOGI(TAG, "HTTP Server gestartet");
|
||||
return s_http;
|
||||
}
|
||||
|
||||
esp_err_t portal_http_start(EventGroupHandle_t wifi_events,
|
||||
EventBits_t bit_gotip,
|
||||
EventBits_t bit_fail,
|
||||
const char* ap_ssid)
|
||||
{
|
||||
if (s_http) return ESP_OK;
|
||||
s_wifi_events = wifi_events;
|
||||
s_BIT_GOTIP = bit_gotip;
|
||||
s_BIT_FAIL = bit_fail;
|
||||
|
||||
if (ap_ssid) {
|
||||
strncpy(s_ap_ssid, ap_ssid, sizeof(s_ap_ssid) - 1);
|
||||
s_ap_ssid[sizeof(s_ap_ssid)-1] = '\0';
|
||||
} else {
|
||||
strcpy(s_ap_ssid, "nanoPSX");
|
||||
}
|
||||
|
||||
s_force_captive = true; // immer beim Start erzwingen
|
||||
return (start_http() ? ESP_OK : ESP_FAIL);
|
||||
}
|
||||
|
||||
void portal_http_stop(void) {
|
||||
if (s_http) {
|
||||
httpd_stop(s_http);
|
||||
s_http = NULL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
// Startet den HTTP-Captive-Portal Server.
|
||||
// - wifi_events: EventGroup, die vom WiFi-Manager gepflegt wird
|
||||
// - bit_gotip: Bitmaske für "STA hat IP"
|
||||
// - bit_fail: Bitmaske für "STA Verbindung fehlgeschlagen"
|
||||
// - ap_ssid: SSID des SoftAP (für Anzeige im HTML)
|
||||
esp_err_t portal_http_start(EventGroupHandle_t wifi_events,
|
||||
EventBits_t bit_gotip,
|
||||
EventBits_t bit_fail,
|
||||
const char* ap_ssid);
|
||||
|
||||
// Stoppt den HTTP-Server (optional)
|
||||
void portal_http_stop(void);
|
||||
+920
@@ -0,0 +1,920 @@
|
||||
/*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2018 Ruslan V. Uss <unclerus@gmail.com>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file i2cdev.c
|
||||
*
|
||||
* ESP-IDF I2C master thread-safe functions for communication with I2C slave
|
||||
*
|
||||
* Copyright (C) 2018 Ruslan V. Uss <unclerus@gmail.com>
|
||||
* Updated 2025 by quinkq to use newer ESP-IDF I2C master driver API
|
||||
*
|
||||
* MIT Licensed as described in the file LICENSE
|
||||
*/
|
||||
// File: src/i2cdev.c
|
||||
#include "i2cdev.h"
|
||||
#include <driver/i2c_master.h>
|
||||
#include <esp_log.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <inttypes.h>
|
||||
#include <string.h>
|
||||
|
||||
static const char *TAG = "i2cdev";
|
||||
|
||||
// Fallback definition for platforms without 10-bit address support
|
||||
#ifndef I2C_ADDR_BIT_LEN_10
|
||||
#define I2C_ADDR_BIT_LEN_10 1
|
||||
#endif
|
||||
|
||||
#define I2C_DEFAULT_FREQ_HZ 400000
|
||||
#define I2C_MAX_RETRIES 3
|
||||
#define I2C_RETRY_BASE_DELAY_MS 20
|
||||
#define I2CDEV_MAX_STACK_ALLOC_SIZE 32 // Stack allocation threshold to avoid heap fragmentation for small buffers
|
||||
|
||||
typedef struct
|
||||
{
|
||||
SemaphoreHandle_t lock; // Mutex for exclusive access to this port's state
|
||||
i2c_master_bus_handle_t bus_handle; // Handle to the initialized I2C master bus
|
||||
bool installed; // Flag indicating if the bus for this port has been installed
|
||||
bool adopted;
|
||||
uint32_t ref_count; // Number of devices currently active on this bus port
|
||||
int sda_pin_current; // Actual SDA pin the bus was initialized with
|
||||
int scl_pin_current; // Actual SCL pin the bus was initialized with
|
||||
} i2c_port_state_t;
|
||||
|
||||
static i2c_port_state_t i2c_ports[I2C_NUM_MAX] = { 0 };
|
||||
static i2c_dev_t *active_devices[I2C_NUM_MAX][CONFIG_I2CDEV_MAX_DEVICES_PER_PORT] = { { NULL } };
|
||||
|
||||
esp_err_t i2cdev_adopt_bus(int port, i2c_master_bus_handle_t bus, int sda, int scl)
|
||||
{
|
||||
if (port < 0 || port >= I2C_NUM_MAX || !bus) return ESP_ERR_INVALID_ARG;
|
||||
i2c_port_state_t *st = &i2c_ports[port];
|
||||
if (!st->lock) st->lock = xSemaphoreCreateMutex();
|
||||
|
||||
xSemaphoreTake(st->lock, portMAX_DELAY);
|
||||
st->bus_handle = bus;
|
||||
st->installed = true; // <- wichtig
|
||||
st->adopted = true;
|
||||
st->sda_pin_current = sda; // <- du hattest bisher nur SCL gesetzt
|
||||
st->scl_pin_current = scl;
|
||||
// ref_count NICHT anfassen; das passiert beim Add/Remove von Devices
|
||||
xSemaphoreGive(st->lock);
|
||||
|
||||
ESP_LOGI(TAG, "[Port %d] Adopted external I2C bus (SDA=%d, SCL=%d, handle=%p)",
|
||||
port, sda, scl, bus);
|
||||
return ESP_OK;
|
||||
}
|
||||
// Helper to register a device
|
||||
static esp_err_t register_device(i2c_dev_t *dev)
|
||||
{
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
int port = dev->port;
|
||||
if (port >= I2C_NUM_MAX)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
// Note: Port mutex should be held by caller
|
||||
for (int i = 0; i < CONFIG_I2CDEV_MAX_DEVICES_PER_PORT; i++)
|
||||
{
|
||||
if (active_devices[port][i] == NULL)
|
||||
{
|
||||
active_devices[port][i] = dev;
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Registered device in slot %d", dev->addr, port, i);
|
||||
return ESP_OK;
|
||||
}
|
||||
}
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] No free slots to register device - limit reached", dev->addr, port);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
// Helper to deregister a device
|
||||
static void deregister_device(i2c_dev_t *dev)
|
||||
{
|
||||
if (!dev)
|
||||
return;
|
||||
int port = dev->port;
|
||||
if (port >= I2C_NUM_MAX)
|
||||
return;
|
||||
for (int i = 0; i < CONFIG_I2CDEV_MAX_DEVICES_PER_PORT; i++)
|
||||
{
|
||||
if (active_devices[port][i] == dev)
|
||||
{
|
||||
active_devices[port][i] = NULL;
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Deregistered device from slot %d", dev->addr, port, i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t i2cdev_init(void)
|
||||
{
|
||||
ESP_LOGV(TAG, "Initializing I2C subsystem...");
|
||||
memset(active_devices, 0, sizeof(active_devices));
|
||||
|
||||
for (int i = 0; i < I2C_NUM_MAX; i++) {
|
||||
if (!i2c_ports[i].lock) {
|
||||
i2c_ports[i].lock = xSemaphoreCreateMutex();
|
||||
if (!i2c_ports[i].lock) return ESP_ERR_NO_MEM;
|
||||
}
|
||||
// i2c_ports[i].installed = false;
|
||||
// i2c_ports[i].adopted = false;
|
||||
// i2c_ports[i].ref_count = 0;
|
||||
// i2c_ports[i].bus_handle = NULL;
|
||||
// i2c_ports[i].sda_pin_current = -1;
|
||||
// i2c_ports[i].scl_pin_current = -1;
|
||||
}
|
||||
ESP_LOGV(TAG, "I2C subsystem initialized.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_create_mutex(i2c_dev_t *dev)
|
||||
{
|
||||
#if !CONFIG_I2CDEV_NOLOCK
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Creating device mutex...", dev->addr, dev->port);
|
||||
if (dev->mutex)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] device mutex already exists (Handle: %p)", dev->addr, dev->port, dev->mutex);
|
||||
return ESP_OK; // Already created
|
||||
}
|
||||
|
||||
dev->mutex = xSemaphoreCreateMutex();
|
||||
if (!dev->mutex)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Could not create device mutex", dev->addr, dev->port);
|
||||
return ESP_ERR_NO_MEM; // Use ESP_ERR_NO_MEM for memory allocation failures
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device mutex created (Handle: %p)", dev->addr, dev->port, dev->mutex);
|
||||
|
||||
// Register the device for cleanup tracking (under port mutex for consistency)
|
||||
if (dev->port < I2C_NUM_MAX && i2c_ports[dev->port].lock)
|
||||
{
|
||||
if (xSemaphoreTake(i2c_ports[dev->port].lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) == pdTRUE)
|
||||
{
|
||||
esp_err_t reg_res = register_device(dev);
|
||||
if (reg_res != ESP_OK)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Failed to register device: %s - device will work but cleanup tracking disabled", dev->addr, dev->port, esp_err_to_name(reg_res));
|
||||
// Continue - device can still function without registration tracking
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device registered successfully for cleanup tracking", dev->addr, dev->port);
|
||||
}
|
||||
xSemaphoreGive(i2c_ports[dev->port].lock);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Could not take port mutex for device registration", dev->addr, dev->port);
|
||||
// Continue - device can still function without registration tracking
|
||||
}
|
||||
}
|
||||
|
||||
// Set default address bit length if not explicitly set
|
||||
if (dev->addr_bit_len != I2C_ADDR_BIT_LEN_7 && dev->addr_bit_len != I2C_ADDR_BIT_LEN_10)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Setting default 7-bit address format", dev->addr, dev->port);
|
||||
dev->addr_bit_len = I2C_ADDR_BIT_LEN_7;
|
||||
}
|
||||
#else
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Mutex creation skipped (CONFIG_I2CDEV_NOLOCK=1)", dev->addr, dev->port);
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_delete_mutex(i2c_dev_t *dev)
|
||||
{
|
||||
#if !CONFIG_I2CDEV_NOLOCK
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Deleting device mutex and cleaning up resources", dev->addr, dev->port);
|
||||
|
||||
// Remove device from bus if handle exists
|
||||
if (dev->dev_handle)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Removing device handle %p from bus", dev->addr, dev->port, dev->dev_handle);
|
||||
esp_err_t rm_res = i2c_master_bus_rm_device((i2c_master_dev_handle_t)dev->dev_handle);
|
||||
if (rm_res != ESP_OK)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Failed to remove device handle: %s", dev->addr, dev->port, esp_err_to_name(rm_res));
|
||||
// Continue with cleanup despite error
|
||||
}
|
||||
dev->dev_handle = NULL;
|
||||
}
|
||||
|
||||
// Deregister the device
|
||||
deregister_device(dev);
|
||||
|
||||
// Update port reference count if port is valid
|
||||
if (dev->port < I2C_NUM_MAX)
|
||||
{
|
||||
if (xSemaphoreTake(i2c_ports[dev->port].lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) == pdTRUE)
|
||||
{
|
||||
if (i2c_ports[dev->port].installed && i2c_ports[dev->port].ref_count > 0) {
|
||||
i2c_ports[dev->port].ref_count--;
|
||||
ESP_LOGV(TAG, "[Port %d] Decremented ref_count to %" PRIu32,
|
||||
dev->port, i2c_ports[dev->port].ref_count);
|
||||
|
||||
if (i2c_ports[dev->port].ref_count == 0) {
|
||||
if (i2c_ports[dev->port].adopted) {
|
||||
// ---> Bus gehört dem BSP; NICHT löschen, NICHT anfassen
|
||||
ESP_LOGI(TAG, "[Port %d] Last device removed, but bus is adopted; leaving bus intact",
|
||||
dev->port);
|
||||
// Hinweis: installed/bus_handle/adopted bleiben gesetzt,
|
||||
// damit später weitere Geräte ohne Re-Adopt hinzugefügt werden können.
|
||||
} else {
|
||||
// ---> Bus gehört i2cdev selbst; jetzt sauber löschen
|
||||
ESP_LOGI(TAG, "[Port %d] Last device removed, deleting this port's bus", dev->port);
|
||||
if (i2c_ports[dev->port].bus_handle) {
|
||||
ESP_LOGI(TAG, "[Port %d] Deleting bus handle %p",
|
||||
dev->port, i2c_ports[dev->port].bus_handle);
|
||||
esp_err_t del_bus_res = i2c_del_master_bus(i2c_ports[dev->port].bus_handle);
|
||||
if (del_bus_res != ESP_OK) {
|
||||
ESP_LOGE(TAG, "[Port %d] Failed to delete master bus: %s",
|
||||
dev->port, esp_err_to_name(del_bus_res));
|
||||
}
|
||||
}
|
||||
i2c_ports[dev->port].bus_handle = NULL;
|
||||
i2c_ports[dev->port].installed = false;
|
||||
i2c_ports[dev->port].sda_pin_current = -1;
|
||||
i2c_ports[dev->port].scl_pin_current = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(i2c_ports[dev->port].lock);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Could not take port mutex for ref_count update", dev->addr, dev->port);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the mutex itself last
|
||||
if (dev->mutex)
|
||||
{
|
||||
vSemaphoreDelete(dev->mutex);
|
||||
dev->mutex = NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device mutex was NULL, nothing to delete", dev->addr, dev->port);
|
||||
}
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_take_mutex(i2c_dev_t *dev)
|
||||
{
|
||||
#if !CONFIG_I2CDEV_NOLOCK
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Attempting to take device mutex (Handle: %p)...", dev->addr, dev->port, dev->mutex);
|
||||
if (!dev->mutex)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Attempt to take NULL device mutex!", dev->addr, dev->port);
|
||||
return ESP_ERR_INVALID_STATE; // Mutex doesn't exist
|
||||
}
|
||||
|
||||
TickType_t timeout_ticks = pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT);
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Taking device mutex with timeout %d ms (%lu ticks)", dev->addr, dev->port, CONFIG_I2CDEV_TIMEOUT, (unsigned long)timeout_ticks);
|
||||
if (!xSemaphoreTake(dev->mutex, timeout_ticks))
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Could not take device mutex (Timeout after %d ms)", dev->addr, dev->port, CONFIG_I2CDEV_TIMEOUT);
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device mutex taken successfully.", dev->addr, dev->port);
|
||||
#else
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Mutex take skipped (CONFIG_I2CDEV_NOLOCK=1)", dev->addr, dev->port);
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_give_mutex(i2c_dev_t *dev)
|
||||
{
|
||||
#if !CONFIG_I2CDEV_NOLOCK
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Giving device mutex (Handle: %p)...", dev->addr, dev->port, dev->mutex);
|
||||
if (!dev->mutex)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Attempt to give NULL device mutex!", dev->addr, dev->port);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
if (!xSemaphoreGive(dev->mutex))
|
||||
{
|
||||
// This case should ideally not happen if the mutex was taken correctly
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Could not give device mutex (Was it taken?) (Handle: %p)", dev->addr, dev->port, dev->mutex);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device mutex given successfully.", dev->addr, dev->port);
|
||||
#else
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Mutex give skipped (CONFIG_I2CDEV_NOLOCK=1)", dev->addr, dev->port);
|
||||
#endif
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// i2c_setup_port: Initializes the I2C master bus for a given port if not already done.
|
||||
// It uses pin configurations from dev->cfg.sda_io_num and dev->cfg.scl_io_num.
|
||||
// The pins for a port are fixed after the first device initializes it.
|
||||
static esp_err_t i2c_setup_port(i2c_dev_t *dev) // dev is non-const to update dev->sda_pin, dev->scl_pin
|
||||
{
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
if (dev->port >= I2C_NUM_MAX)
|
||||
{
|
||||
ESP_LOGE(TAG, "Invalid I2C port number: %d", dev->port);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
esp_err_t res = ESP_OK;
|
||||
i2c_port_state_t *port_state = &i2c_ports[dev->port];
|
||||
|
||||
ESP_LOGV(TAG, "[Port %d] Setup request for device 0x%02x", dev->port, dev->addr);
|
||||
if (xSemaphoreTake(port_state->lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) != pdTRUE)
|
||||
{
|
||||
ESP_LOGE(TAG, "[Port %d] Could not take port mutex for setup", dev->port);
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
|
||||
if (!port_state->installed)
|
||||
{
|
||||
if (port_state->adopted && port_state->bus_handle) {
|
||||
ESP_LOGI(TAG, "[Port %d] Using adopted I2C bus (SDA=%d, SCL=%d, handle=%p)",
|
||||
dev->port, port_state->sda_pin_current, port_state->scl_pin_current,
|
||||
port_state->bus_handle);
|
||||
port_state->installed = true; // wieder auf 'installed'
|
||||
dev->sda_pin = port_state->sda_pin_current;
|
||||
dev->scl_pin = port_state->scl_pin_current;
|
||||
xSemaphoreGive(port_state->lock);
|
||||
return ESP_OK; // KEIN i2c_new_master_bus()!
|
||||
}
|
||||
// Pin Selection Logic: Use device-specified pins, fallback to Kconfig defaults if -1
|
||||
gpio_num_t sda_pin = (dev->cfg.sda_io_num == (gpio_num_t)-1) ? (gpio_num_t)CONFIG_I2CDEV_DEFAULT_SDA_PIN : dev->cfg.sda_io_num;
|
||||
gpio_num_t scl_pin = (dev->cfg.scl_io_num == (gpio_num_t)-1) ? (gpio_num_t)CONFIG_I2CDEV_DEFAULT_SCL_PIN : dev->cfg.scl_io_num;
|
||||
|
||||
// Validate pins (basic check, gpio_is_valid_gpio could be used for more robust check)
|
||||
if (sda_pin < 0 || scl_pin < 0)
|
||||
{
|
||||
ESP_LOGE(TAG, "[Port %d] Invalid SCL/SDA pins: SDA=%d, SCL=%d. Check driver or Kconfig defaults.", dev->port, sda_pin, scl_pin);
|
||||
xSemaphoreGive(port_state->lock);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/*
|
||||
* OPTIONAL I2C PULLUP AUTO-CONFIGURATION
|
||||
*
|
||||
* By default: Uses whatever sda_pullup_en/scl_pullup_en you set (usually false)
|
||||
*
|
||||
* When CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS=y: If both pullup flags are false,
|
||||
* automatically change them to true to enable internal pullups (~45kΩ).
|
||||
*
|
||||
* Manual pullup configuration:
|
||||
* - Set sda_pullup_en=true, scl_pullup_en=true for internal pullups
|
||||
* - Set sda_pullup_en=false, scl_pullup_en=false for external pullups
|
||||
*/
|
||||
|
||||
// Read user's pullup configuration (default false if not set)
|
||||
bool sda_pullup = dev->cfg.sda_pullup_en;
|
||||
bool scl_pullup = dev->cfg.scl_pullup_en;
|
||||
|
||||
#if CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS
|
||||
// CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS=y: If user didn't configure pullups, enable them automatically
|
||||
if (!sda_pullup && !scl_pullup)
|
||||
{
|
||||
sda_pullup = true;
|
||||
scl_pullup = true;
|
||||
ESP_LOGI(TAG, "[Port %d] Auto-enabling internal pullups (CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS=y)", dev->port);
|
||||
}
|
||||
#endif
|
||||
|
||||
ESP_LOGI(TAG,
|
||||
"[Port %d] First initialization. Configuring bus with SDA=%d, SCL=%d (Pullups "
|
||||
"SCL:%d SDA:%d)",
|
||||
dev->port, sda_pin, scl_pin, scl_pullup, sda_pullup);
|
||||
|
||||
i2c_master_bus_config_t bus_config = {
|
||||
.i2c_port = dev->port,
|
||||
.sda_io_num = sda_pin,
|
||||
.scl_io_num = scl_pin,
|
||||
.clk_source = I2C_CLK_SRC_DEFAULT,
|
||||
.glitch_ignore_cnt = 7,
|
||||
.flags.enable_internal_pullup = (sda_pullup || scl_pullup),
|
||||
// Bus speed is not set here. It's per-device or a global target for the bus can be set
|
||||
// if desired, but i2c_master supports per-device speeds.
|
||||
};
|
||||
|
||||
res = i2c_new_master_bus(&bus_config, &port_state->bus_handle);
|
||||
if (res == ESP_OK)
|
||||
{
|
||||
port_state->installed = true;
|
||||
port_state->ref_count = 0; // Will be incremented when a device is successfully added
|
||||
port_state->sda_pin_current = sda_pin;
|
||||
port_state->scl_pin_current = scl_pin;
|
||||
dev->sda_pin = sda_pin; // Update dev struct with actual pins used
|
||||
dev->scl_pin = scl_pin;
|
||||
ESP_LOGI(TAG, "[Port %d] Successfully installed I2C master bus (Handle: %p).", dev->port, port_state->bus_handle);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGE(TAG, "[Port %d] Failed to create master bus: %d (%s)", dev->port, res, esp_err_to_name(res));
|
||||
port_state->installed = false;
|
||||
port_state->bus_handle = NULL;
|
||||
port_state->sda_pin_current = -1;
|
||||
port_state->scl_pin_current = -1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGV(TAG, "[Port %d] Port already installed (SDA=%d, SCL=%d, Handle: %p).", dev->port, port_state->sda_pin_current, port_state->scl_pin_current, port_state->bus_handle);
|
||||
// Pin Consistency Check: For subsequent devices, ensure pins match already-configured bus
|
||||
gpio_num_t sda_desired = (dev->cfg.sda_io_num == (gpio_num_t)-1) ? (gpio_num_t)port_state->sda_pin_current : dev->cfg.sda_io_num;
|
||||
gpio_num_t scl_desired = (dev->cfg.scl_io_num == (gpio_num_t)-1) ? (gpio_num_t)port_state->scl_pin_current : dev->cfg.scl_io_num;
|
||||
|
||||
if (sda_desired != port_state->sda_pin_current || scl_desired != port_state->scl_pin_current)
|
||||
{
|
||||
ESP_LOGE(TAG,
|
||||
"[Port %d] Pin mismatch for device 0x%02x! Bus on SDA=%d,SCL=%d. Device wants "
|
||||
"SDA=%d,SCL=%d",
|
||||
dev->port, dev->addr, port_state->sda_pin_current, port_state->scl_pin_current, sda_desired, scl_desired);
|
||||
res = ESP_ERR_INVALID_STATE; // Cannot change pins for an installed bus
|
||||
}
|
||||
else
|
||||
{
|
||||
dev->sda_pin = port_state->sda_pin_current; // Update dev struct with actual pins used
|
||||
dev->scl_pin = port_state->scl_pin_current;
|
||||
}
|
||||
// ref_count is managed by i2c_setup_device when adding/removing device handles
|
||||
}
|
||||
|
||||
xSemaphoreGive(port_state->lock);
|
||||
ESP_LOGV(TAG, "[Port %d] Port setup finished with res %d.", dev->port, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// i2c_setup_device: Ensures port is set up and adds the device to the bus if not already added.
|
||||
// It also registers the device in active_devices for cleanup purposes.
|
||||
static esp_err_t i2c_setup_device(i2c_dev_t *dev) // dev is non-const - modifies dev->dev_handle, dev->addr_bit_len
|
||||
{
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Setting up device context...", dev->addr, dev->port);
|
||||
|
||||
esp_err_t res = i2c_setup_port(dev);
|
||||
if (res != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Port setup failed during device setup: %d (%s)", dev->addr, dev->port, res, esp_err_to_name(res));
|
||||
return res;
|
||||
}
|
||||
|
||||
// If addr_bit_len is not set (e.g. 0, which is invalid for i2c_addr_bit_len_t enum), default to
|
||||
// 7-bit. Modified to conditionally check for I2C_ADDR_BIT_LEN_10 based on hardware support
|
||||
if (dev->addr_bit_len != I2C_ADDR_BIT_LEN_7
|
||||
#if SOC_I2C_SUPPORT_10BIT_ADDR
|
||||
&& dev->addr_bit_len != I2C_ADDR_BIT_LEN_10
|
||||
#endif
|
||||
)
|
||||
{
|
||||
ESP_LOGD(TAG, "[0x%02x at %d] addr_bit_len not explicitly set, defaulting to 7-bit.", dev->addr, dev->port);
|
||||
dev->addr_bit_len = I2C_ADDR_BIT_LEN_7;
|
||||
}
|
||||
|
||||
// Only warn about address size if the device is actually using 10-bit addressing
|
||||
if (dev->addr_bit_len == I2C_ADDR_BIT_LEN_7 && dev->addr > 0x7F)
|
||||
{
|
||||
ESP_LOGW(TAG,
|
||||
"[0x%02x at %d] Device address > 0x7F but addr_bit_len is 7-bit. Ensure address "
|
||||
"is correct.",
|
||||
dev->addr, dev->port);
|
||||
}
|
||||
|
||||
#if !defined(SOC_I2C_SUPPORT_10BIT_ADDR) || !SOC_I2C_SUPPORT_10BIT_ADDR
|
||||
// On platforms without 10-bit support, force 7-bit addressing regardless of user setting
|
||||
if (dev->addr_bit_len == I2C_ADDR_BIT_LEN_10)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] 10-bit addressing not supported on this platform, forcing 7-bit mode", dev->addr, dev->port);
|
||||
dev->addr_bit_len = I2C_ADDR_BIT_LEN_7;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (dev->dev_handle == NULL)
|
||||
{
|
||||
i2c_port_state_t *port_state = &i2c_ports[dev->port];
|
||||
if (xSemaphoreTake(port_state->lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) != pdTRUE)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Could not take port mutex for device add", dev->addr, dev->port);
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
|
||||
if (!port_state->installed || !port_state->bus_handle)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Cannot add device, bus for port %d not ready!", dev->addr, dev->port, dev->port);
|
||||
xSemaphoreGive(port_state->lock);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Adding device to bus (Bus Handle: %p)...", dev->addr, dev->port, port_state->bus_handle);
|
||||
|
||||
uint32_t effective_dev_speed = dev->cfg.master.clk_speed;
|
||||
if (effective_dev_speed == 0)
|
||||
{
|
||||
ESP_LOGW(TAG,
|
||||
"[0x%02x at %d] Device speed (dev->cfg.master.clk_speed) is 0, using default: "
|
||||
"%" PRIu32 " Hz",
|
||||
dev->addr, dev->port, (uint32_t)I2C_DEFAULT_FREQ_HZ);
|
||||
effective_dev_speed = I2C_DEFAULT_FREQ_HZ;
|
||||
}
|
||||
|
||||
i2c_device_config_t dev_config = {
|
||||
// Use the possibly modified addr_bit_len that respects hardware capabilities
|
||||
.dev_addr_length = dev->addr_bit_len,
|
||||
.device_address = dev->addr,
|
||||
.scl_speed_hz = effective_dev_speed,
|
||||
.flags.disable_ack_check = false,
|
||||
};
|
||||
|
||||
res = i2c_master_bus_add_device(port_state->bus_handle, &dev_config, (i2c_master_dev_handle_t *)&dev->dev_handle);
|
||||
if (res == ESP_OK)
|
||||
{
|
||||
ESP_LOGI(TAG, "[0x%02x at %d] Device added successfully (Device Handle: %p, Speed: %" PRIu32 " Hz).", dev->addr, dev->port, dev->dev_handle, effective_dev_speed);
|
||||
|
||||
// Increment the port reference count for each device successfully added
|
||||
port_state->ref_count++;
|
||||
ESP_LOGV(TAG, "[Port %d] Incremented ref_count to %" PRIu32, dev->port, port_state->ref_count);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Failed to add device to bus: %d (%s)", dev->addr, dev->port, res, esp_err_to_name(res));
|
||||
dev->dev_handle = NULL;
|
||||
}
|
||||
xSemaphoreGive(port_state->lock);
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device handle %p already exists. Skipping add.", dev->addr, dev->port, dev->dev_handle);
|
||||
res = ESP_OK;
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device context setup finished with res %d.", dev->addr, dev->port, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Helper function with retry mechanism for I2C operations
|
||||
static esp_err_t i2c_do_operation_with_retry(i2c_dev_t *dev, esp_err_t (*i2c_func)(i2c_master_dev_handle_t, const void *, size_t, void *, size_t, int), const void *write_buffer, size_t write_size,
|
||||
void *read_buffer, size_t read_size)
|
||||
{
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
esp_err_t res = ESP_FAIL;
|
||||
int retry = 0;
|
||||
int timeout_ms = CONFIG_I2CDEV_TIMEOUT;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Performing I2C operation (timeout %d ms)...", dev->addr, dev->port, timeout_ms);
|
||||
|
||||
while (retry <= I2C_MAX_RETRIES)
|
||||
{
|
||||
// Ensure device is set up before each attempt, in case handle became stale or bus was reset
|
||||
// This is more robust if issues like bus errors or device resets occur.
|
||||
res = i2c_setup_device(dev);
|
||||
if (res != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Device setup failed (Try %d): %d (%s). Retrying setup...", dev->addr, dev->port, retry, res, esp_err_to_name(res));
|
||||
// No point continuing this attempt if setup fails, but the loop will retry setup.
|
||||
vTaskDelay(pdMS_TO_TICKS(I2C_RETRY_BASE_DELAY_MS * (1 << (retry))));
|
||||
retry++;
|
||||
continue;
|
||||
}
|
||||
if (!dev->dev_handle)
|
||||
{
|
||||
ESP_LOGE(TAG,
|
||||
"[0x%02x at %d] Device handle is NULL after setup (Try %d)! Cannot perform "
|
||||
"operation.",
|
||||
dev->addr, dev->port, retry);
|
||||
// This indicates a persistent problem with adding the device to the bus.
|
||||
// No point retrying the i2c_func if handle is null.
|
||||
res = ESP_ERR_INVALID_STATE;
|
||||
vTaskDelay(pdMS_TO_TICKS(I2C_RETRY_BASE_DELAY_MS * (1 << (retry))));
|
||||
retry++;
|
||||
continue;
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Attempting I2C op (Try %d, Handle %p)", dev->addr, dev->port, retry, dev->dev_handle);
|
||||
res = i2c_func(dev->dev_handle, write_buffer, write_size, read_buffer, read_size, timeout_ms);
|
||||
|
||||
if (res == ESP_OK)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] I2C operation successful (Try %d).", dev->addr, dev->port, retry);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] I2C op failed (Try %d, Handle %p): %d (%s).", dev->addr, dev->port, retry, dev->dev_handle, res, esp_err_to_name(res));
|
||||
|
||||
// Only remove handle on errors that indicate handle corruption or permanent invalidity
|
||||
// Don't remove on temporary errors like ESP_ERR_TIMEOUT, ESP_FAIL (NACK), etc.
|
||||
bool should_remove_handle = false;
|
||||
switch (res)
|
||||
{
|
||||
case ESP_ERR_INVALID_ARG:
|
||||
// Handle was likely removed by another task or is corrupted
|
||||
should_remove_handle = true;
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Invalid argument error - handle may be corrupted", dev->addr, dev->port);
|
||||
break;
|
||||
case ESP_ERR_INVALID_STATE:
|
||||
// I2C driver is in invalid state, handle likely needs recreation
|
||||
should_remove_handle = true;
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Invalid state error - handle may need recreation", dev->addr, dev->port);
|
||||
break;
|
||||
default:
|
||||
// For other errors (timeout, NACK, bus busy, etc.), keep the handle
|
||||
// These are usually temporary and don't require handle recreation
|
||||
should_remove_handle = false;
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Temporary error - keeping handle for retry", dev->addr, dev->port);
|
||||
break;
|
||||
}
|
||||
|
||||
if (should_remove_handle && dev->dev_handle)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Removing potentially corrupted device handle %p after permanent error", dev->addr, dev->port, dev->dev_handle);
|
||||
// Try to remove the handle from the bus before nullifying
|
||||
esp_err_t rm_res = i2c_master_bus_rm_device(dev->dev_handle);
|
||||
if (rm_res != ESP_OK)
|
||||
{
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Failed to remove corrupted handle (expected): %s", dev->addr, dev->port, esp_err_to_name(rm_res));
|
||||
// This is expected if the handle was already invalid - continue cleanup
|
||||
}
|
||||
dev->dev_handle = NULL;
|
||||
}
|
||||
|
||||
retry++;
|
||||
if (retry <= I2C_MAX_RETRIES)
|
||||
{
|
||||
vTaskDelay(pdMS_TO_TICKS(I2C_RETRY_BASE_DELAY_MS * (1 << retry))); // Exponential backoff
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Retrying operation...", dev->addr, dev->port);
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] I2C operation failed after %d retries. Last error: %d (%s)", dev->addr, dev->port, I2C_MAX_RETRIES + 1, res, esp_err_to_name(res));
|
||||
return res;
|
||||
}
|
||||
|
||||
// Wrapper functions for the I2C master API to use with the retry mechanism
|
||||
// i2c_do_operation_with_retry() needs a unified function signature for all I2C operations
|
||||
static esp_err_t i2c_master_transmit_wrapper(i2c_master_dev_handle_t handle, const void *write_buffer, size_t write_size, void *read_buffer, size_t read_size, int timeout_ms)
|
||||
{
|
||||
return i2c_master_transmit(handle, write_buffer, write_size, timeout_ms);
|
||||
}
|
||||
|
||||
static esp_err_t i2c_master_receive_wrapper(i2c_master_dev_handle_t handle, const void *write_buffer, size_t write_size, void *read_buffer, size_t read_size, int timeout_ms)
|
||||
{
|
||||
return i2c_master_receive(handle, read_buffer, read_size, timeout_ms);
|
||||
}
|
||||
|
||||
static esp_err_t i2c_master_transmit_receive_wrapper(i2c_master_dev_handle_t handle, const void *write_buffer, size_t write_size, void *read_buffer, size_t read_size, int timeout_ms)
|
||||
{
|
||||
return i2c_master_transmit_receive(handle, write_buffer, write_size, read_buffer, read_size, timeout_ms);
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_read(const i2c_dev_t *dev, const void *out_data, size_t out_size, void *in_data, size_t in_size)
|
||||
{
|
||||
if (!dev || !in_data || !in_size)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_read called (out_size: %u, in_size: %u)", dev->addr, dev->port, out_size, in_size);
|
||||
|
||||
esp_err_t result = i2c_do_operation_with_retry((i2c_dev_t *)dev, // Cast to non-const for i2c_setup_device internal modifications
|
||||
out_data && out_size ? i2c_master_transmit_receive_wrapper : i2c_master_receive_wrapper, out_data, out_size, in_data, in_size);
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_read result: %s (%d)", dev->addr, dev->port, esp_err_to_name(result), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_write(const i2c_dev_t *dev, const void *out_reg, size_t out_reg_size, const void *out_data, size_t out_size)
|
||||
{
|
||||
if (!dev)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
if ((!out_reg || !out_reg_size) && (!out_data || !out_size))
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_write called (reg_size: %u, data_size: %u)", dev->addr, dev->port, out_reg_size, out_size);
|
||||
|
||||
esp_err_t res;
|
||||
if (out_reg && out_reg_size && out_data && out_size)
|
||||
{
|
||||
size_t total_write_size = out_reg_size + out_size;
|
||||
|
||||
// Check for overflow before proceeding
|
||||
if (total_write_size < out_reg_size || total_write_size < out_size)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Write size overflow: reg_size=%u + data_size=%u", dev->addr, dev->port, out_reg_size, out_size);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
// Use stack for small buffers to avoid heap fragmentation
|
||||
if (total_write_size <= I2CDEV_MAX_STACK_ALLOC_SIZE)
|
||||
{ // Use stack allocation for small buffers
|
||||
uint8_t stack_buf[I2CDEV_MAX_STACK_ALLOC_SIZE];
|
||||
memcpy(stack_buf, out_reg, out_reg_size);
|
||||
memcpy(stack_buf + out_reg_size, out_data, out_size);
|
||||
res = i2c_do_operation_with_retry((i2c_dev_t *)dev, i2c_master_transmit_wrapper, stack_buf, total_write_size, NULL, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
uint8_t *heap_buf = malloc(total_write_size);
|
||||
if (!heap_buf)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Failed to allocate %u bytes for write", dev->addr, dev->port, total_write_size);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(heap_buf, out_reg, out_reg_size);
|
||||
memcpy(heap_buf + out_reg_size, out_data, out_size);
|
||||
res = i2c_do_operation_with_retry((i2c_dev_t *)dev, i2c_master_transmit_wrapper, heap_buf, total_write_size, NULL, 0);
|
||||
free(heap_buf); // Free buffer regardless of operation result
|
||||
}
|
||||
}
|
||||
else if (out_reg && out_reg_size)
|
||||
{
|
||||
res = i2c_do_operation_with_retry((i2c_dev_t *)dev, i2c_master_transmit_wrapper, out_reg, out_reg_size, NULL, 0);
|
||||
}
|
||||
else if (out_data && out_size)
|
||||
{
|
||||
res = i2c_do_operation_with_retry((i2c_dev_t *)dev, i2c_master_transmit_wrapper, out_data, out_size, NULL, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ESP_ERR_INVALID_ARG; // Shouldn't reach here given the earlier check
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_write result: %s (%d)", dev->addr, dev->port, esp_err_to_name(res), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_read_reg(const i2c_dev_t *dev, uint8_t reg, void *data, size_t size)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_read_reg called (reg: 0x%02x, size: %u)", dev->addr, dev->port, reg, size);
|
||||
return i2c_dev_read(dev, ®, 1, data, size);
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_write_reg(const i2c_dev_t *dev, uint8_t reg, const void *data, size_t size)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] i2c_dev_write_reg called (reg: 0x%02x, size: %u)", dev->addr, dev->port, reg, size);
|
||||
return i2c_dev_write(dev, ®, 1, data, size);
|
||||
}
|
||||
|
||||
esp_err_t i2c_dev_check_present(const i2c_dev_t *dev_const)
|
||||
{
|
||||
if (!dev_const)
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Probing device presence...", dev_const->addr, dev_const->port);
|
||||
|
||||
// Cast to non-const for i2c_setup_port (which may modify internal state)
|
||||
i2c_dev_t *dev = (i2c_dev_t *)dev_const;
|
||||
|
||||
// Ensure the I2C port is set up before probing
|
||||
esp_err_t setup_res = i2c_setup_port(dev);
|
||||
if (setup_res != ESP_OK)
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Failed to setup port for probe: %s", dev_const->addr, dev_const->port, esp_err_to_name(setup_res));
|
||||
return setup_res;
|
||||
}
|
||||
|
||||
// Now probe using the initialized bus
|
||||
if (dev_const->port < I2C_NUM_MAX && i2c_ports[dev_const->port].lock)
|
||||
{
|
||||
if (xSemaphoreTake(i2c_ports[dev_const->port].lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) == pdTRUE)
|
||||
{
|
||||
if (i2c_ports[dev_const->port].installed && i2c_ports[dev_const->port].bus_handle)
|
||||
{
|
||||
// Use ESP-IDF's built-in probe function - completely non-intrusive
|
||||
esp_err_t probe_res = i2c_master_probe(i2c_ports[dev_const->port].bus_handle, dev_const->addr, CONFIG_I2CDEV_TIMEOUT);
|
||||
xSemaphoreGive(i2c_ports[dev_const->port].lock);
|
||||
|
||||
if (probe_res == ESP_OK)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device probe successful - device present", dev_const->addr, dev_const->port);
|
||||
return ESP_OK;
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Device probe failed: %s", dev_const->addr, dev_const->port, esp_err_to_name(probe_res));
|
||||
return probe_res;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
xSemaphoreGive(i2c_ports[dev_const->port].lock);
|
||||
ESP_LOGW(TAG, "[0x%02x at %d] Cannot probe - bus not ready on port %d", dev_const->addr, dev_const->port, dev_const->port);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Could not take port mutex for probe", dev_const->addr, dev_const->port);
|
||||
return ESP_ERR_TIMEOUT;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ESP_LOGE(TAG, "[0x%02x at %d] Invalid port or port not initialized", dev_const->addr, dev_const->port);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
}
|
||||
|
||||
// Compatibility wrapper for legacy code that still calls i2c_dev_probe
|
||||
// The new driver implementation uses i2c_master_probe which doesn't need operation_type
|
||||
esp_err_t i2c_dev_probe(const i2c_dev_t *dev, i2c_dev_type_t operation_type)
|
||||
{
|
||||
ESP_LOGV(TAG, "[0x%02x at %d] Legacy probe called (operation_type %d), redirecting to new implementation", dev->addr, dev->port, operation_type);
|
||||
|
||||
return i2c_dev_check_present(dev);
|
||||
}
|
||||
|
||||
// Clean up function to be called at application exit
|
||||
esp_err_t i2cdev_done(void)
|
||||
{
|
||||
esp_err_t result = ESP_OK;
|
||||
ESP_LOGV(TAG, "Cleaning up I2C subsystem (i2c_master)...");
|
||||
for (int i = 0; i < I2C_NUM_MAX; i++) {
|
||||
if (i2c_ports[i].lock) {
|
||||
if (xSemaphoreTake(i2c_ports[i].lock, pdMS_TO_TICKS(CONFIG_I2CDEV_TIMEOUT)) != pdTRUE) {
|
||||
ESP_LOGE(TAG, "[Port %d] Could not take port mutex for cleanup", i);
|
||||
result = ESP_FAIL;
|
||||
} else {
|
||||
if (i2c_ports[i].installed) {
|
||||
// 1) Alle bekannten Geräte-Handles vom Bus nehmen
|
||||
for (int j = 0; j < CONFIG_I2CDEV_MAX_DEVICES_PER_PORT; j++) {
|
||||
i2c_dev_t *dev = active_devices[i][j];
|
||||
if (dev && dev->dev_handle) {
|
||||
esp_err_t rm = i2c_master_bus_rm_device((i2c_master_dev_handle_t)dev->dev_handle);
|
||||
if (rm != ESP_OK) {
|
||||
ESP_LOGW(TAG, "[Port %d] rm_device failed for slot %d: %s",
|
||||
i, j, esp_err_to_name(rm));
|
||||
result = (result == ESP_OK) ? rm : result;
|
||||
}
|
||||
dev->dev_handle = NULL;
|
||||
}
|
||||
active_devices[i][j] = NULL;
|
||||
}
|
||||
|
||||
// 2) Bus nur löschen, wenn NICHT adoptiert
|
||||
if (!i2c_ports[i].adopted) {
|
||||
if (i2c_ports[i].bus_handle) {
|
||||
esp_err_t del_res = i2c_del_master_bus(i2c_ports[i].bus_handle);
|
||||
if (del_res != ESP_OK) {
|
||||
ESP_LOGW(TAG, "[Port %d] i2c_del_master_bus failed: %s",
|
||||
i, esp_err_to_name(del_res));
|
||||
result = (result == ESP_OK) ? del_res : result;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ESP_LOGI(TAG, "[Port %d] Bus is adopted; skipping bus deletion", i);
|
||||
}
|
||||
|
||||
// 3) Interne Zustände zurücksetzen
|
||||
i2c_ports[i].bus_handle = NULL;
|
||||
i2c_ports[i].installed = false;
|
||||
i2c_ports[i].ref_count = 0;
|
||||
i2c_ports[i].sda_pin_current = -1;
|
||||
i2c_ports[i].scl_pin_current = -1;
|
||||
i2c_ports[i].adopted = false;
|
||||
}
|
||||
xSemaphoreGive(i2c_ports[i].lock);
|
||||
}
|
||||
vSemaphoreDelete(i2c_ports[i].lock);
|
||||
i2c_ports[i].lock = NULL;
|
||||
memset(active_devices[i], 0, sizeof(active_devices[i]));
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGV(TAG, "I2C subsystem cleanup finished with result: %d", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* @file i2cdev.h
|
||||
* @defgroup i2cdev i2cdev
|
||||
* @{
|
||||
*
|
||||
* ESP-IDF I2C master thread-safe functions for communication with I2C slave
|
||||
*
|
||||
* This implementation uses the newer ESP-IDF I2C master driver (v5.0+).
|
||||
* For ESP-IDF versions using the legacy I2C driver, use i2cdev_legacy.c instead.
|
||||
*
|
||||
* Copyright (C) 2018 Ruslan V. Uss <unclerus@gmail.com>
|
||||
* Updated 2025 by quinkq to use newer ESP-IDF I2C master driver API
|
||||
*
|
||||
* MIT Licensed as described in the file LICENSE
|
||||
*
|
||||
* ============================================================================
|
||||
* OPTIONAL I2C PULLUP AUTO-CONFIGURATION
|
||||
* ============================================================================
|
||||
*
|
||||
* This library can optionally enable internal I2C pullups when no explicit
|
||||
* pullup configuration is provided. Feature is DISABLED by default for
|
||||
* backward compatibility (CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS=n).
|
||||
*
|
||||
* Optional auto-pullup (CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS=y):
|
||||
* - If both pullup flags are false (not set/default state), automatically enables internal pullups
|
||||
* - Only available on ESP32 family (modern driver)
|
||||
* - Legacy driver always uses explicit configuration
|
||||
*
|
||||
*
|
||||
* Example - Enable internal pullups:
|
||||
* i2c_dev_t sensor = {
|
||||
* .port = I2C_NUM_0,
|
||||
* .addr = 0x48,
|
||||
* .cfg = {
|
||||
* .sda_io_num = GPIO_NUM_21,
|
||||
* .scl_io_num = GPIO_NUM_22,
|
||||
* .sda_pullup_en = true, // Enable internal pullups
|
||||
* .scl_pullup_en = true, // Enable internal pullups
|
||||
* .master.clk_speed = 400000
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* ============================================================================
|
||||
*/
|
||||
|
||||
#ifndef __I2CDEV_H__
|
||||
#define __I2CDEV_H__
|
||||
|
||||
#include <driver/gpio.h>
|
||||
#include <driver/i2c.h>
|
||||
#include <esp_err.h>
|
||||
#include <esp_idf_lib_helpers.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
|
||||
// Define missing types for older ESP-IDF versions
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 2, 0)
|
||||
typedef enum {
|
||||
I2C_ADDR_BIT_LEN_7 = 0, /*!< I2C 7bit address for slave mode */
|
||||
I2C_ADDR_BIT_LEN_10, /*!< I2C 10bit address for slave mode */
|
||||
} i2c_addr_bit_len_t;
|
||||
#endif
|
||||
|
||||
/* ==== ESP-IDF I2C Header je nach Version ==== */
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
|
||||
#include <driver/i2c_types.h> // i2c_port_t, i2c_addr_bit_len_t
|
||||
#include <driver/i2c_master.h> // i2c_master_bus_handle_t etc.
|
||||
#else
|
||||
#include <driver/i2c.h> // ältere IDF: alles hier drin
|
||||
#endif
|
||||
|
||||
// Definition for I2CDEV_MAX_STRETCH_TIME
|
||||
#if HELPER_TARGET_IS_ESP8266
|
||||
#define I2CDEV_MAX_STRETCH_TIME 0xffffffff
|
||||
#else
|
||||
#include <soc/i2c_reg.h> // For I2C_TIME_OUT_VALUE_V, etc.
|
||||
#if defined(I2C_TIME_OUT_VALUE_V)
|
||||
#define I2CDEV_MAX_STRETCH_TIME I2C_TIME_OUT_VALUE_V
|
||||
#elif defined(I2C_TIME_OUT_REG_V)
|
||||
#define I2CDEV_MAX_STRETCH_TIME I2C_TIME_OUT_REG_V
|
||||
#else
|
||||
#define I2CDEV_MAX_STRETCH_TIME 0x00ffffff
|
||||
#endif
|
||||
#endif /* HELPER_TARGET_IS_ESP8266 */
|
||||
|
||||
#ifndef CONFIG_I2CDEV_TIMEOUT
|
||||
#define CONFIG_I2CDEV_TIMEOUT 1000 // Default 1 second timeout
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_I2CDEV_NOLOCK
|
||||
#define CONFIG_I2CDEV_NOLOCK 0 // Enable locking by default
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_I2CDEV_MAX_DEVICES_PER_PORT
|
||||
#define CONFIG_I2CDEV_MAX_DEVICES_PER_PORT 8 // Maximum devices per I2C port
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_I2CDEV_DEFAULT_SDA_PIN
|
||||
#define CONFIG_I2CDEV_DEFAULT_SDA_PIN 21 // Default SDA pin
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_I2CDEV_DEFAULT_SCL_PIN
|
||||
#define CONFIG_I2CDEV_DEFAULT_SCL_PIN 22 // Default SCL pin
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_FREERTOS_HZ
|
||||
#define CONFIG_FREERTOS_HZ 100 // Default value in most ESP-IDF configs
|
||||
#endif
|
||||
|
||||
#ifndef CONFIG_LOG_MAXIMUM_LEVEL
|
||||
#define CONFIG_LOG_MAXIMUM_LEVEL 3 // INFO level as default
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief I2C transaction type for legacy probe
|
||||
*/
|
||||
typedef enum {
|
||||
I2C_DEV_WRITE = 0, /**< Write operation for probe */
|
||||
I2C_DEV_READ /**< Read operation for probe */
|
||||
} i2c_dev_type_t;
|
||||
|
||||
/**
|
||||
* I2C device descriptor
|
||||
*
|
||||
* This structure supports both legacy ESP-IDF I2C driver and modern i2c_master driver.
|
||||
*
|
||||
* @note INITIALIZATION CHECKLIST - Set these fields before calling i2c_dev_create_mutex():
|
||||
*
|
||||
* ┌─── REQUIRED (Set by user) ───────────────────────────────────────────┐
|
||||
* │ - dev->port - I2C port number (e.g., I2C_NUM_0) │
|
||||
* │ - dev->addr - Device I2C address (e.g., 0x48) │
|
||||
* │ - dev->cfg.sda_io_num - SDA pin (-1 = use Kconfig default) │
|
||||
* │ - dev->cfg.scl_io_num - SCL pin (-1 = use Kconfig default) │
|
||||
* │ - dev->cfg.master.clk_speed - Clock speed in Hz (e.g., 400000) │
|
||||
* └──────────────────────────────────────────────────────────────────────┘
|
||||
*
|
||||
* ┌─── OPTIONAL (Set by user if needed) ─────────────────────────────────┐
|
||||
* │ - dev->addr_bit_len - Address format (defaults to 7-bit) - NEW │
|
||||
* │ - dev->cfg.sda_pullup_en - Enable internal SDA pullup │
|
||||
* │ - dev->cfg.scl_pullup_en - Enable internal SCL pullup │
|
||||
* │ - dev->timeout_ticks - Legacy driver timeout (legacy only) │
|
||||
* └──────────────────────────────────────────────────────────────────────┘
|
||||
*
|
||||
* ┌─── AUTO-POPULATED (library fills these) ─────────────────────────────┐
|
||||
* │ - dev->mutex - Device mutex handle │
|
||||
* │ - dev->dev_handle - I2C device handle (modern driver) - NEW │
|
||||
* │ - dev->sda_pin - Actual SDA pin used by bus │
|
||||
* │ - dev->scl_pin - Actual SCL pin used by bus │
|
||||
* └──────────────────────────────────────────────────────────────────────┘
|
||||
*
|
||||
* @note BACKWARD COMPATIBILITY DESIGN:
|
||||
* The custom 'cfg' structure mimics ESP-IDF's deprecated i2c_config_t layout
|
||||
* to maintain zero-change compatibility with existing device drivers.
|
||||
* ESP-IDF ≥5.2 deprecated i2c_config_t and split it into separate bus/device
|
||||
* configs, but this library preserves the familiar field paths like:
|
||||
* dev->cfg.sda_io_num, dev->cfg.scl_io_num, dev->cfg.master.clk_speed
|
||||
*/
|
||||
typedef struct
|
||||
{
|
||||
// ═══ Core Device Identity (REQUIRED) ═══
|
||||
i2c_port_t port; //!< I2C port number (e.g., I2C_NUM_0)
|
||||
uint16_t addr; //!< Device I2C address (e.g., 0x48 for 7-bit)
|
||||
i2c_addr_bit_len_t addr_bit_len; //!< Address format: I2C_ADDR_BIT_LEN_7 (default) or I2C_ADDR_BIT_LEN_10
|
||||
|
||||
// ═══ Library Internal State (AUTO-POPULATED) ═══
|
||||
SemaphoreHandle_t mutex; //!< Device mutex - Created by i2c_dev_create_mutex()
|
||||
void *dev_handle; //!< Device handle - Modern driver only, created lazily (when actual I2C operation is performed)
|
||||
int sda_pin; //!< Actual SDA pin used - Populated after port setup
|
||||
int scl_pin; //!< Actual SCL pin used - Populated after port setup
|
||||
|
||||
// ═══ Legacy Driver Compatibility ═══
|
||||
uint32_t timeout_ticks; //!< Clock stretching timeout - Legacy driver only
|
||||
|
||||
// ═══ User Configuration (REQUIRED) ═══
|
||||
// Configuration structure with i2c_config_t compatible field layout.
|
||||
struct
|
||||
{
|
||||
gpio_num_t sda_io_num; //!< Desired SDA pin (-1 = use Kconfig default)
|
||||
gpio_num_t scl_io_num; //!< Desired SCL pin (-1 = use Kconfig default)
|
||||
uint8_t sda_pullup_en; //!< Enable internal SDA pullup (optional)
|
||||
uint8_t scl_pullup_en; //!< Enable internal SCL pullup (optional)
|
||||
struct
|
||||
{
|
||||
uint32_t clk_speed; //!< Clock speed in Hz
|
||||
} master; //!< Master-specific config (mimics old i2c_config_t.master)
|
||||
} cfg; //!< Configuration set by device drivers (i2c_config_t compatible layout)
|
||||
} i2c_dev_t;
|
||||
|
||||
/**
|
||||
* @brief Initialize I2C subsystem (port mutexes and internal states)
|
||||
*
|
||||
* @note This should be called once at the beginning of your application
|
||||
* before any I2C devices are initialized.
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
*/
|
||||
esp_err_t i2cdev_init(void);
|
||||
|
||||
/**
|
||||
* @brief Release I2C subsystem (deletes all devices, buses, and mutexes)
|
||||
*
|
||||
* @note Call this when no more I2C operations will be performed
|
||||
* to clean up resources.
|
||||
*
|
||||
* @return ESP_OK on success
|
||||
*/
|
||||
esp_err_t i2cdev_done(void);
|
||||
|
||||
/**
|
||||
* @brief Create mutex for device descriptor and register device
|
||||
*
|
||||
* @note IMPORTANT: Before calling this function, you must properly initialize the i2c_dev_t
|
||||
* structure with device address, port, and pin settings. For ESP-IDF legacy driver,
|
||||
* set pins in dev->cfg.sda_io_num and dev->cfg.scl_io_num. For newer ESP-IDF version,
|
||||
* either method is compatible. See the structure documentation for details.
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_create_mutex(i2c_dev_t *dev);
|
||||
|
||||
/**
|
||||
* @brief Delete mutex for device descriptor and perform device cleanup
|
||||
*
|
||||
* @note This function performs cleanup tasks including removing the device from the
|
||||
* I2C bus, deregistering it, and deleting its mutex.
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_delete_mutex(i2c_dev_t *dev);
|
||||
|
||||
/**
|
||||
* @brief Take device mutex
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_take_mutex(i2c_dev_t *dev);
|
||||
|
||||
/**
|
||||
* @brief Give device mutex
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_give_mutex(i2c_dev_t *dev);
|
||||
|
||||
/**
|
||||
* @brief Check the availability of a device on the I2C bus (New Driver) - legacy's i2c_dev_probe function equivalent.
|
||||
*
|
||||
* This function attempts to communicate with the I2C device to see if it ACKs.
|
||||
* It is non-intrusive; if the device is found, any temporary setup for
|
||||
* the check is torn down. Uses the new I2C driver logic.
|
||||
*
|
||||
* @param dev Pointer to the device descriptor. Pins and address must be configured.
|
||||
* @return `ESP_OK` if the device ACKs (is present), an error code otherwise.
|
||||
*/
|
||||
esp_err_t i2c_dev_check_present(const i2c_dev_t *dev);
|
||||
|
||||
/**
|
||||
* @brief Check the availability of a device on the I2C bus (Legacy Driver).
|
||||
*
|
||||
* Issue an operation of `operation_type` to the I2C device then stops.
|
||||
* Primarily for use with the legacy i2cdev_legacy.c implementation.
|
||||
*
|
||||
* @param dev Device descriptor.
|
||||
* @param operation_type Operation type (I2C_DEV_WRITE or I2C_DEV_READ).
|
||||
* @return `ESP_OK` if device is available for the specified operation type.
|
||||
*/
|
||||
esp_err_t i2c_dev_probe(const i2c_dev_t *dev, i2c_dev_type_t operation_type);
|
||||
|
||||
/**
|
||||
* @brief Read from device
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @param[in] out_data Data to write before reading (can be NULL if out_size is 0)
|
||||
* @param out_size Size of data to write
|
||||
* @param[out] in_data Buffer to store data read
|
||||
* @param in_size Number of bytes to read
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_read(const i2c_dev_t *dev, const void *out_data, size_t out_size, void *in_data, size_t in_size);
|
||||
|
||||
/**
|
||||
* @brief Write to device
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @param[in] out_reg Register address to write to (can be NULL if out_reg_size is 0)
|
||||
* @param out_reg_size Size of register address
|
||||
* @param[in] out_data Data to write (can be NULL if out_size is 0)
|
||||
* @param out_size Size of data to write
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_write(const i2c_dev_t *dev, const void *out_reg, size_t out_reg_size, const void *out_data, size_t out_size);
|
||||
|
||||
/**
|
||||
* @brief Read from device register (8-bit register address)
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @param reg Command to write before reading
|
||||
* @param[out] data Buffer to store data
|
||||
* @param size Number of bytes to read
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_read_reg(const i2c_dev_t *dev, uint8_t reg, void *data, size_t size);
|
||||
|
||||
/**
|
||||
* @brief Write to device register (8-bit register address)
|
||||
*
|
||||
* @param dev Pointer to device descriptor
|
||||
* @param reg Command to write before writing data
|
||||
* @param data Buffer with data to write
|
||||
* @param size Number of bytes to write
|
||||
* @return `ESP_OK` on success
|
||||
*/
|
||||
esp_err_t i2c_dev_write_reg(const i2c_dev_t *dev, uint8_t reg, const void *data, size_t size);
|
||||
|
||||
/**
|
||||
* @brief Take device mutex with error checking
|
||||
*/
|
||||
#define I2C_DEV_TAKE_MUTEX(dev) \
|
||||
do \
|
||||
{ \
|
||||
esp_err_t __ = i2c_dev_take_mutex(dev); \
|
||||
if (__ != ESP_OK) \
|
||||
return __; \
|
||||
} \
|
||||
while (0)
|
||||
|
||||
/**
|
||||
* @brief Give device mutex with error checking
|
||||
*/
|
||||
#define I2C_DEV_GIVE_MUTEX(dev) \
|
||||
do \
|
||||
{ \
|
||||
esp_err_t __ = i2c_dev_give_mutex(dev); \
|
||||
if (__ != ESP_OK) \
|
||||
return __; \
|
||||
} \
|
||||
while (0)
|
||||
|
||||
/**
|
||||
* @brief Execute operation, assuming mutex is held. Gives mutex ONLY on error.
|
||||
*/
|
||||
#define I2C_DEV_CHECK(dev, X) \
|
||||
do \
|
||||
{ \
|
||||
esp_err_t ___ = X; /* Execute operation */ \
|
||||
if (___ != ESP_OK) \
|
||||
{ \
|
||||
/* Give mutex ONLY if error occurred */ \
|
||||
i2c_dev_give_mutex(dev); \
|
||||
return ___; \
|
||||
} \
|
||||
} \
|
||||
while (0)
|
||||
|
||||
/**
|
||||
* @brief Execute operation, assuming mutex is held. Gives mutex ONLY on error, logs error.
|
||||
*/
|
||||
#define I2C_DEV_CHECK_LOGE(dev, X, msg, ...) \
|
||||
do \
|
||||
{ \
|
||||
esp_err_t ___ = X; /* Execute operation */ \
|
||||
if (___ != ESP_OK) \
|
||||
{ \
|
||||
/* Give mutex ONLY if error occurred */ \
|
||||
i2c_dev_give_mutex(dev); \
|
||||
ESP_LOGE(TAG, msg, ##__VA_ARGS__); \
|
||||
return ___; \
|
||||
} \
|
||||
} \
|
||||
while (0)
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/**@}*/
|
||||
|
||||
esp_err_t i2cdev_adopt_bus(int port, i2c_master_bus_handle_t bus, int sda, int scl);
|
||||
|
||||
#endif /* __I2CDEV_H__ */
|
||||
@@ -0,0 +1,7 @@
|
||||
dependencies:
|
||||
idf: ">=5.1"
|
||||
lvgl/lvgl: "^8.4.0"
|
||||
espressif/esp_lcd_touch: "^1.1.2"
|
||||
espressif/esp_lvgl_port: "^2.5.0"
|
||||
espressif/button: "^4.1.0"
|
||||
espressif/mdns: "~1.8"
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* @file lv_fs_fatfs.c
|
||||
*
|
||||
*/
|
||||
|
||||
/*********************
|
||||
* INCLUDES
|
||||
*********************/
|
||||
#include "lvgl.h"
|
||||
|
||||
|
||||
#define FS_FATFS 1
|
||||
#if FS_FATFS
|
||||
#define FS_FATFS_LETTER 'S' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define FS_FATFS_CACHE_SIZE 20 * 1024 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
|
||||
#if FS_FATFS
|
||||
#include "ff.h"
|
||||
|
||||
/*********************
|
||||
* DEFINES
|
||||
*********************/
|
||||
|
||||
#if FS_FATFS_LETTER == '\0'
|
||||
#error "FS_FATFS_LETTER must be an upper case ASCII letter"
|
||||
#endif
|
||||
|
||||
/**********************
|
||||
* TYPEDEFS
|
||||
**********************/
|
||||
|
||||
/**********************
|
||||
* STATIC PROTOTYPES
|
||||
**********************/
|
||||
static void fs_init(void);
|
||||
|
||||
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode);
|
||||
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p);
|
||||
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br);
|
||||
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw);
|
||||
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence);
|
||||
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p);
|
||||
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path);
|
||||
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn);
|
||||
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p);
|
||||
|
||||
/**********************
|
||||
* STATIC VARIABLES
|
||||
**********************/
|
||||
|
||||
/**********************
|
||||
* MACROS
|
||||
**********************/
|
||||
|
||||
/**********************
|
||||
* GLOBAL FUNCTIONS
|
||||
**********************/
|
||||
|
||||
void lv_fs_fatfs_init(void)
|
||||
{
|
||||
/*----------------------------------------------------
|
||||
* Initialize your storage device and File System
|
||||
* -------------------------------------------------*/
|
||||
fs_init();
|
||||
|
||||
/*---------------------------------------------------
|
||||
* Register the file system interface in LVGL
|
||||
*--------------------------------------------------*/
|
||||
|
||||
/*Add a simple drive to open images*/
|
||||
static lv_fs_drv_t fs_drv; /*A driver descriptor*/
|
||||
lv_fs_drv_init(&fs_drv);
|
||||
|
||||
/*Set up fields...*/
|
||||
fs_drv.letter = FS_FATFS_LETTER;
|
||||
fs_drv.cache_size = FS_FATFS_CACHE_SIZE;
|
||||
|
||||
fs_drv.open_cb = fs_open;
|
||||
fs_drv.close_cb = fs_close;
|
||||
fs_drv.read_cb = fs_read;
|
||||
fs_drv.write_cb = fs_write;
|
||||
fs_drv.seek_cb = fs_seek;
|
||||
fs_drv.tell_cb = fs_tell;
|
||||
|
||||
fs_drv.dir_close_cb = fs_dir_close;
|
||||
fs_drv.dir_open_cb = fs_dir_open;
|
||||
fs_drv.dir_read_cb = fs_dir_read;
|
||||
|
||||
lv_fs_drv_register(&fs_drv);
|
||||
}
|
||||
|
||||
/**********************
|
||||
* STATIC FUNCTIONS
|
||||
**********************/
|
||||
|
||||
/*Initialize your Storage device and File system.*/
|
||||
static void fs_init(void)
|
||||
{
|
||||
/*Initialize the SD card and FatFS itself.
|
||||
*Better to do it in your code to keep this library untouched for easy updating*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a file
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt)
|
||||
* @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR
|
||||
* @return pointer to FIL struct or NULL in case of fail
|
||||
*/
|
||||
static void * fs_open(lv_fs_drv_t * drv, const char * path, lv_fs_mode_t mode)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
uint8_t flags = 0;
|
||||
|
||||
if(mode == LV_FS_MODE_WR) flags = FA_WRITE | FA_OPEN_ALWAYS;
|
||||
else if(mode == LV_FS_MODE_RD) flags = FA_READ;
|
||||
else if(mode == (LV_FS_MODE_WR | LV_FS_MODE_RD)) flags = FA_READ | FA_WRITE | FA_OPEN_ALWAYS;
|
||||
|
||||
FIL * f = (FIL *)lv_mem_alloc(sizeof(FIL));
|
||||
if(f == NULL) return NULL;
|
||||
|
||||
FRESULT res = f_open(f, path, flags);
|
||||
if(res == FR_OK) {
|
||||
return f;
|
||||
}
|
||||
else {
|
||||
lv_mem_free(f);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close an opened file
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param file_p pointer to a FIL variable. (opened with fs_open)
|
||||
* @return LV_FS_RES_OK: no error, the file is read
|
||||
* any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_close(lv_fs_drv_t * drv, void * file_p)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
f_close((FIL *)file_p);
|
||||
lv_mem_free(file_p);
|
||||
return LV_FS_RES_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from an opened file
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param file_p pointer to a FIL variable.
|
||||
* @param buf pointer to a memory block where to store the read data
|
||||
* @param btr number of Bytes To Read
|
||||
* @param br the real number of read bytes (Byte Read)
|
||||
* @return LV_FS_RES_OK: no error, the file is read
|
||||
* any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_read(lv_fs_drv_t * drv, void * file_p, void * buf, uint32_t btr, uint32_t * br)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
FRESULT res = f_read((FIL *)file_p, buf, btr, (UINT *)br);
|
||||
if(res == FR_OK) return LV_FS_RES_OK;
|
||||
else return LV_FS_RES_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write into a file
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param file_p pointer to a FIL variable
|
||||
* @param buf pointer to a buffer with the bytes to write
|
||||
* @param btw Bytes To Write
|
||||
* @param bw the number of real written bytes (Bytes Written). NULL if unused.
|
||||
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_write(lv_fs_drv_t * drv, void * file_p, const void * buf, uint32_t btw, uint32_t * bw)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
FRESULT res = f_write((FIL *)file_p, buf, btw, (UINT *)bw);
|
||||
if(res == FR_OK) return LV_FS_RES_OK;
|
||||
else return LV_FS_RES_UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the read write pointer. Also expand the file size if necessary.
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param file_p pointer to a FIL variable. (opened with fs_open )
|
||||
* @param pos the new position of read write pointer
|
||||
* @param whence only LV_SEEK_SET is supported
|
||||
* @return LV_FS_RES_OK: no error, the file is read
|
||||
* any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_seek(lv_fs_drv_t * drv, void * file_p, uint32_t pos, lv_fs_whence_t whence)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
switch(whence) {
|
||||
case LV_FS_SEEK_SET:
|
||||
f_lseek((FIL *)file_p, pos);
|
||||
break;
|
||||
case LV_FS_SEEK_CUR:
|
||||
f_lseek((FIL *)file_p, f_tell((FIL *)file_p) + pos);
|
||||
break;
|
||||
case LV_FS_SEEK_END:
|
||||
f_lseek((FIL *)file_p, f_size((FIL *)file_p) + pos);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return LV_FS_RES_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the position of the read write pointer
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param file_p pointer to a FIL variable.
|
||||
* @param pos_p pointer to to store the result
|
||||
* @return LV_FS_RES_OK: no error, the file is read
|
||||
* any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_tell(lv_fs_drv_t * drv, void * file_p, uint32_t * pos_p)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
*pos_p = f_tell((FIL *)file_p);
|
||||
return LV_FS_RES_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a 'DIR' variable for directory reading
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param path path to a directory
|
||||
* @return pointer to an initialized 'DIR' variable
|
||||
*/
|
||||
static void * fs_dir_open(lv_fs_drv_t * drv, const char * path)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
FF_DIR * d = (FF_DIR *)lv_mem_alloc(sizeof(FF_DIR));
|
||||
if(d == NULL) return NULL;
|
||||
|
||||
FRESULT res = f_opendir(d, path);
|
||||
if(res != FR_OK) {
|
||||
lv_mem_free(d);
|
||||
d = NULL;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the next filename from a directory.
|
||||
* The name of the directories will begin with '/'
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param dir_p pointer to an initialized 'DIR' variable
|
||||
* @param fn pointer to a buffer to store the filename
|
||||
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_dir_read(lv_fs_drv_t * drv, void * dir_p, char * fn)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
FRESULT res;
|
||||
FILINFO fno;
|
||||
fn[0] = '\0';
|
||||
|
||||
do {
|
||||
res = f_readdir((FF_DIR *)dir_p, &fno);
|
||||
if(res != FR_OK) return LV_FS_RES_UNKNOWN;
|
||||
|
||||
if(fno.fattrib & AM_DIR) {
|
||||
fn[0] = '/';
|
||||
strcpy(&fn[1], fno.fname);
|
||||
}
|
||||
else strcpy(fn, fno.fname);
|
||||
|
||||
} while(strcmp(fn, "/.") == 0 || strcmp(fn, "/..") == 0);
|
||||
|
||||
return LV_FS_RES_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the directory reading
|
||||
* @param drv pointer to a driver where this function belongs
|
||||
* @param dir_p pointer to an initialized 'DIR' variable
|
||||
* @return LV_FS_RES_OK or any error from lv_fs_res_t enum
|
||||
*/
|
||||
static lv_fs_res_t fs_dir_close(lv_fs_drv_t * drv, void * dir_p)
|
||||
{
|
||||
LV_UNUSED(drv);
|
||||
f_closedir((FF_DIR *)dir_p);
|
||||
lv_mem_free(dir_p);
|
||||
return LV_FS_RES_OK;
|
||||
}
|
||||
|
||||
#else /*FS_FATFS == 0*/
|
||||
|
||||
#if defined(FS_FATFS_LETTER) && FS_FATFS_LETTER != '\0'
|
||||
#warning "FS_FATFS is not enabled but FS_FATFS_LETTER is set"
|
||||
#endif
|
||||
|
||||
#endif /*LV_USE_FS_POSIX*/
|
||||
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
// File: main.c
|
||||
#include <string.h>
|
||||
#include <driver/i2c_types.h>
|
||||
#include <driver/i2c_master.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include "wifi_mgr.h"
|
||||
#include "sen5x_app.h"
|
||||
#include "storage.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_system.h" // esp_restart
|
||||
|
||||
#include "esp_lvgl_port.h"
|
||||
|
||||
#include "bsp_display.h"
|
||||
#include "bsp_touch.h"
|
||||
#include "bsp_i2c.h"
|
||||
#include "bsp_spi.h"
|
||||
#include "bsp_wifi.h"
|
||||
#include "bsp_sdcard.h"
|
||||
#include "bsp_battery.h"
|
||||
#include "bsp_qmi8658.h"
|
||||
|
||||
#include "iot_button.h"
|
||||
#include "button_gpio.h"
|
||||
|
||||
#include "demos/lv_demos.h"
|
||||
|
||||
#include "ui.h"
|
||||
#include "i2cdev.h"
|
||||
|
||||
#include "sys_status.h"
|
||||
|
||||
#include "images.h"
|
||||
#include "screens.h" // <-- Zugriff auf objects.* und tick_screen()
|
||||
|
||||
// Entfernt: extern lv_obj_t *ui_wifi/influx/mdns;
|
||||
|
||||
// ---------- Status-Icons updaten: nutzt die in screens.c erzeugten Objekte ----------
|
||||
static void ui_update_status_icons(void)
|
||||
{
|
||||
static bool first = true;
|
||||
static bool pw=false, pi=false, pm=false;
|
||||
|
||||
bool w = sys_status_get_wifi_ok();
|
||||
bool i = sys_status_get_influx_ok();
|
||||
bool m = sys_status_get_mdns_ok();
|
||||
|
||||
// WiFi
|
||||
if (first || w != pw) {
|
||||
if (objects.wifi_ok && objects.wifi_off) {
|
||||
if (w) {
|
||||
lv_obj_clear_flag(objects.wifi_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag (objects.wifi_off, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag (objects.wifi_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(objects.wifi_off, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
pw = w;
|
||||
}
|
||||
|
||||
// Influx
|
||||
if (first || i != pi) {
|
||||
if (objects.influx_ok && objects.influx_off) {
|
||||
if (i) {
|
||||
lv_obj_clear_flag(objects.influx_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag (objects.influx_off, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag (objects.influx_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(objects.influx_off, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
pi = i;
|
||||
}
|
||||
|
||||
// mDNS
|
||||
if (first || m != pm) {
|
||||
if (objects.mdns_ok && objects.mdns_off) {
|
||||
if (m) {
|
||||
lv_obj_clear_flag(objects.mdns_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag (objects.mdns_off, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag (objects.mdns_ok, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(objects.mdns_off, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
pm = m;
|
||||
}
|
||||
|
||||
first = false;
|
||||
}
|
||||
|
||||
#define EXAMPLE_DISPLAY_ROTATION 270
|
||||
|
||||
#if EXAMPLE_DISPLAY_ROTATION == 90 || EXAMPLE_DISPLAY_ROTATION == 270
|
||||
#define EXAMPLE_LCD_H_RES (320)
|
||||
#define EXAMPLE_LCD_V_RES (172)
|
||||
#else
|
||||
#define EXAMPLE_LCD_H_RES (172)
|
||||
#define EXAMPLE_LCD_V_RES (320)
|
||||
#endif
|
||||
|
||||
#define EXAMPLE_LCD_DRAW_BUFF_HEIGHT (50)
|
||||
#define EXAMPLE_LCD_DRAW_BUFF_DOUBLE (1)
|
||||
|
||||
static char *TAG = "app";
|
||||
|
||||
/* LCD IO and panel */
|
||||
static esp_lcd_panel_io_handle_t io_handle = NULL;
|
||||
static esp_lcd_panel_handle_t panel_handle = NULL;
|
||||
static esp_lcd_touch_handle_t touch_handle = NULL;
|
||||
|
||||
/* LVGL display and touch */
|
||||
static lv_display_t *lvgl_disp = NULL;
|
||||
static lv_indev_t *lvgl_touch_indev = NULL;
|
||||
|
||||
/* --- Button Handle global halten, falls benötigt --- */
|
||||
static button_handle_t g_btn = NULL;
|
||||
|
||||
/* Vorwärtsdeklarationen */
|
||||
void lv_fs_fatfs_init(void);
|
||||
static esp_err_t app_lvgl_init(void);
|
||||
static void button_init(void);
|
||||
static void touch_test(void);
|
||||
static void ui_tick_cb(lv_timer_t *t);
|
||||
|
||||
/* ==================== LVGL Setup (unverändert) ==================== */
|
||||
static esp_err_t app_lvgl_init(void)
|
||||
{
|
||||
/* Initialize LVGL */
|
||||
const lvgl_port_cfg_t lvgl_cfg = {
|
||||
.task_priority = 4,
|
||||
.task_stack = 1024 * 10,
|
||||
.task_affinity = -1,
|
||||
.task_max_sleep_ms = 500,
|
||||
.timer_period_ms = 5
|
||||
};
|
||||
ESP_RETURN_ON_ERROR(lvgl_port_init(&lvgl_cfg), TAG, "LVGL port initialization failed");
|
||||
|
||||
/* Add LCD screen */
|
||||
ESP_LOGD(TAG, "Add LCD screen");
|
||||
lvgl_port_display_cfg_t disp_cfg = {
|
||||
.io_handle = io_handle,
|
||||
.panel_handle = panel_handle,
|
||||
.buffer_size = EXAMPLE_LCD_H_RES * EXAMPLE_LCD_DRAW_BUFF_HEIGHT,
|
||||
.double_buffer = EXAMPLE_LCD_DRAW_BUFF_DOUBLE,
|
||||
.hres = EXAMPLE_LCD_H_RES,
|
||||
.vres = EXAMPLE_LCD_V_RES,
|
||||
.monochrome = false,
|
||||
.rotation = {
|
||||
.swap_xy = false,
|
||||
.mirror_x = false,
|
||||
.mirror_y = false,
|
||||
},
|
||||
.flags = {
|
||||
.buff_dma = true,
|
||||
#if LVGL_VERSION_MAJOR >= 9
|
||||
.swap_bytes = true,
|
||||
#endif
|
||||
}};
|
||||
#if EXAMPLE_DISPLAY_ROTATION == 90
|
||||
disp_cfg.rotation.swap_xy = true;
|
||||
disp_cfg.rotation.mirror_x = true;
|
||||
disp_cfg.rotation.mirror_y = false;
|
||||
ESP_ERROR_CHECK(esp_lcd_panel_set_gap(panel_handle, 0, 34));
|
||||
#elif EXAMPLE_DISPLAY_ROTATION == 180
|
||||
disp_cfg.rotation.swap_xy = false;
|
||||
disp_cfg.rotation.mirror_x = true;
|
||||
disp_cfg.rotation.mirror_y = true;
|
||||
ESP_ERROR_CHECK(esp_lcd_panel_set_gap(panel_handle, 34, 0));
|
||||
#elif EXAMPLE_DISPLAY_ROTATION == 270
|
||||
disp_cfg.rotation.swap_xy = true;
|
||||
disp_cfg.rotation.mirror_x = false;
|
||||
disp_cfg.rotation.mirror_y = true;
|
||||
ESP_ERROR_CHECK(esp_lcd_panel_set_gap(panel_handle, 0, 34));
|
||||
#else
|
||||
ESP_ERROR_CHECK(esp_lcd_panel_set_gap(panel_handle, 34, 0));
|
||||
#endif
|
||||
lvgl_disp = lvgl_port_add_disp(&disp_cfg);
|
||||
|
||||
/* Add touch input (for selected screen) */
|
||||
const lvgl_port_touch_cfg_t touch_cfg = {
|
||||
.disp = lvgl_disp,
|
||||
.handle = touch_handle,
|
||||
};
|
||||
lvgl_touch_indev = lvgl_port_add_touch(&touch_cfg);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void ui_tick_cb(lv_timer_t *t) {
|
||||
(void)t;
|
||||
if (lvgl_port_lock(0)) {
|
||||
ui_update_status_icons();
|
||||
tick_screen(0);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== Touch-Test (unverändert) ==================== */
|
||||
static bool touch_test_done = false;
|
||||
|
||||
static void button_event_cb(void *arg, void *data)
|
||||
{
|
||||
button_event_t event = iot_button_get_event((button_handle_t)arg);
|
||||
ESP_LOGI(TAG, "%s", iot_button_get_event_str(event));
|
||||
touch_test_done = true;
|
||||
}
|
||||
|
||||
static void touch_test(void)
|
||||
{
|
||||
uint16_t touchpad_x[1] = {0};
|
||||
uint16_t touchpad_y[1] = {0};
|
||||
uint8_t touchpad_cnt = 0;
|
||||
uint16_t color_arr[16] = {0};
|
||||
lv_obj_t *lable = NULL;
|
||||
|
||||
for (int i = 0; i < 16; i++) color_arr[i] = 0xf800;
|
||||
|
||||
if (lvgl_port_lock(0)) {
|
||||
lable = lv_label_create(lv_scr_act());
|
||||
lv_label_set_text(lable, "Touch testing mode \nExit with BOOT button");
|
||||
lv_obj_center(lable);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
if (lvgl_port_lock(0)) {
|
||||
while (!touch_test_done) {
|
||||
esp_lcd_touch_read_data(touch_handle);
|
||||
bool touchpad_pressed = esp_lcd_touch_get_coordinates(touch_handle, touchpad_x, touchpad_y, NULL, &touchpad_cnt, 1);
|
||||
if (touchpad_pressed && touchpad_cnt > 0) {
|
||||
if (touchpad_x[0] < 2) touchpad_x[0] = 2;
|
||||
else if (touchpad_x[0] > EXAMPLE_LCD_H_RES - 2 - 1) touchpad_x[0] = EXAMPLE_LCD_H_RES - 2 - 1;
|
||||
if (touchpad_y[0] < 2) touchpad_y[0] = 2;
|
||||
else if (touchpad_y[0] > EXAMPLE_LCD_V_RES - 2 - 1) touchpad_y[0] = EXAMPLE_LCD_V_RES - 2 - 1;
|
||||
|
||||
esp_lcd_panel_draw_bitmap(panel_handle, touchpad_x[0] - 2, touchpad_y[0] - 2, touchpad_x[0] + 2, touchpad_y[0] + 2, color_arr);
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
}
|
||||
lv_obj_del(lable);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== Factory-Reset per Long-Press ==================== */
|
||||
|
||||
static void longpress_feedback_show(const char *msg)
|
||||
{
|
||||
if (!lvgl_port_lock(0)) return;
|
||||
// einfache Overlay-Message
|
||||
lv_obj_t *box = lv_obj_create(lv_scr_act());
|
||||
lv_obj_set_size(box, EXAMPLE_LCD_H_RES - 20, 60);
|
||||
lv_obj_center(box);
|
||||
lv_obj_t *label = lv_label_create(box);
|
||||
lv_label_set_text(label, msg);
|
||||
lv_obj_center(label);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
static void reset_button_cb(void *arg, void *data)
|
||||
{
|
||||
button_event_t ev = iot_button_get_event((button_handle_t)arg);
|
||||
if (ev == BUTTON_LONG_PRESS_START) {
|
||||
ESP_LOGW(TAG, "Factory-Reset: LONG PRESS detected – hold to confirm...");
|
||||
longpress_feedback_show("Factory Reset...\nRelease to confirm");
|
||||
} else if (ev == BUTTON_LONG_PRESS_UP) {
|
||||
ESP_LOGW(TAG, "Factory-Reset: executing (erase NVS + reboot)!");
|
||||
// NVS löschen
|
||||
if (storage_factory_reset_all() == ESP_OK) {
|
||||
// kleine visuelle Rückmeldung
|
||||
longpress_feedback_show("Erase NVS\nReboot...");
|
||||
vTaskDelay(pdMS_TO_TICKS(300));
|
||||
}
|
||||
// harter Neustart
|
||||
esp_restart();
|
||||
}
|
||||
}
|
||||
|
||||
static void button_init(void)
|
||||
{
|
||||
button_config_t btn_cfg = {};
|
||||
// Optional: Long-Press-Dauer setzen (ms). Standard ist häufig ~1500 ms.
|
||||
// Einige Versionen des iot_button haben field "long_press_time".
|
||||
btn_cfg.long_press_time = 5000; // 5 Sekunden halten zum Reset
|
||||
|
||||
button_gpio_config_t btn_gpio_cfg = {};
|
||||
btn_gpio_cfg.gpio_num = GPIO_NUM_9; // dein BOOT/USER Button
|
||||
btn_gpio_cfg.active_level = 0;
|
||||
|
||||
ESP_ERROR_CHECK(iot_button_new_gpio_device(&btn_cfg, &btn_gpio_cfg, &g_btn));
|
||||
|
||||
// Kurzer Klick für Touch-Test (wie bisher)
|
||||
iot_button_register_cb(g_btn, BUTTON_SINGLE_CLICK, NULL, button_event_cb, NULL);
|
||||
|
||||
// Long-Press Feedback (Start)
|
||||
iot_button_register_cb(g_btn, BUTTON_LONG_PRESS_START, NULL, reset_button_cb, NULL);
|
||||
|
||||
// Beim Loslassen nach langem Drücken -> wirklich resetten
|
||||
iot_button_register_cb(g_btn, BUTTON_LONG_PRESS_UP, NULL, reset_button_cb, NULL);
|
||||
}
|
||||
|
||||
/* ==================== app_main (unverändert, plus Button-Reset) ==================== */
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
/*
|
||||
esp_log_level_set("storage", ESP_LOG_NONE);
|
||||
*/
|
||||
|
||||
esp_log_level_set("*", ESP_LOG_NONE);
|
||||
|
||||
sys_status_init();
|
||||
sys_status_set_wifi_ok(false);
|
||||
sys_status_set_influx_ok(false);
|
||||
sys_status_set_mdns_ok(false);
|
||||
|
||||
// 0) NVS zuerst
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
// --- Storage/WiFi wie gehabt ---
|
||||
ESP_ERROR_CHECK(storage_init());
|
||||
storage_debug_dump();
|
||||
wifi_mgr_init();
|
||||
wifi_mgr_start();
|
||||
|
||||
ESP_ERROR_CHECK(i2cdev_init());
|
||||
|
||||
// 1) I2C-Bus initialisieren (bsp_i2c.h)
|
||||
i2c_master_bus_handle_t i2c_bus_handle = bsp_i2c_init();
|
||||
|
||||
// 2) Diesen Bus von i2cdev "adoptieren", damit SEN5x denselben Bus nutzt
|
||||
ESP_ERROR_CHECK(i2cdev_adopt_bus(0, i2c_bus_handle, 18, 19)); // Port 0, SDA=18, SCL=19
|
||||
|
||||
// 3) Restliche Peripherie
|
||||
bsp_spi_init();
|
||||
bsp_battery_init();
|
||||
// bsp_qmi8658_init(i2c_bus_handle);
|
||||
bsp_display_init(&io_handle, &panel_handle, EXAMPLE_LCD_H_RES * EXAMPLE_LCD_DRAW_BUFF_HEIGHT);
|
||||
bsp_touch_init(&touch_handle, i2c_bus_handle, EXAMPLE_LCD_H_RES, EXAMPLE_LCD_V_RES, EXAMPLE_DISPLAY_ROTATION);
|
||||
bsp_sdcard_init();
|
||||
ESP_ERROR_CHECK(app_lvgl_init());
|
||||
lv_fs_fatfs_init();
|
||||
bsp_display_brightness_init();
|
||||
bsp_display_set_brightness(100);
|
||||
|
||||
// >>> Button inkl. Long-Press-Reset
|
||||
button_init();
|
||||
// touch_test(); // optional
|
||||
|
||||
if (lvgl_port_lock(0)) {
|
||||
ui_init(); // erzeugt auch die Objekte in screens.c
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
lv_timer_t *ui_timer = lv_timer_create(ui_tick_cb, 1000, NULL);
|
||||
(void)ui_timer;
|
||||
|
||||
// 4) SEN5x
|
||||
const sen5x_i2c_cfg_t cfg = {
|
||||
.addr = 0x69,
|
||||
.port = 0,
|
||||
.sda = 18,
|
||||
.scl = 19,
|
||||
.sda_pullup = true,
|
||||
.scl_pullup = true,
|
||||
.freq = 400000
|
||||
};
|
||||
ESP_ERROR_CHECK(sen5x_app_init(&cfg));
|
||||
|
||||
// 5) Task starten
|
||||
xTaskCreate(sen5x_app_task, "sen5x_task", 4096, NULL, 5, NULL);
|
||||
|
||||
for (;;) vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
// File: src/net_influx.c
|
||||
#include "storage.h"
|
||||
#include "net_influx.h"
|
||||
#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"
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// File: include/net_influx.h
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
typedef struct {
|
||||
const char* url_base; // "http://host:8086" oder "https://host"
|
||||
const char* org;
|
||||
const char* bucket;
|
||||
const char* token;
|
||||
bool use_tls; // optional; wenn true => TLS erzwingen
|
||||
const char* ca_cert_pem; // optional, bei https (kann NULL sein wenn Test)
|
||||
int http_timeout_ms; // z.B. 3000
|
||||
} net_influx_cfg_t;
|
||||
|
||||
esp_err_t net_influx_init(const net_influx_cfg_t* cfg);
|
||||
|
||||
// Convenience: lädt URL/org/bucket/token direkt aus NVS (storage.c)
|
||||
esp_err_t net_influx_init_from_nvs(const char* ca_cert_pem_opt, int timeout_ms);
|
||||
|
||||
// generisches Write (Line Protocol Felderformatierung via printf)
|
||||
esp_err_t net_influx_write_fields(const char* measurement,
|
||||
const char* tags, // "k=v,k2=v2" oder NULL
|
||||
uint64_t ts_ms, // 0 = Serverzeit
|
||||
const char* fields_fmt,
|
||||
...);
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_wifi.h" // <— wichtig für WIFI_EVENT
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "mdns.h"
|
||||
#include "net_mdns.h"
|
||||
#include "storage.h"
|
||||
|
||||
static const char* TAG = "net_mdns";
|
||||
static char g_hostname[33] = {0};
|
||||
static char g_instance[33] = {0};
|
||||
static volatile bool g_mdns_running = false;
|
||||
|
||||
esp_err_t net_mdns_autodiscover_and_store(const char *service, const char *proto,
|
||||
int enforce_port,
|
||||
const char *txt_key, const char *txt_value,
|
||||
uint32_t timeout_ms)
|
||||
{
|
||||
char url[96] = {0};
|
||||
bool ok = net_mdns_find_service_url(service, proto, enforce_port,
|
||||
txt_key, txt_value, timeout_ms, 5,
|
||||
url, sizeof(url));
|
||||
if (!ok) {
|
||||
ESP_LOGW(TAG, "Auto-Discover: kein Treffer für %s.%s", service, proto);
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
esp_err_t err = storage_save_service_url(url);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Auto-Discover: URL '%s' in NVS gespeichert.", url);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
static void mdns_start_if_needed(void) {
|
||||
if (g_mdns_running) return;
|
||||
esp_err_t err = mdns_init();
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "mdns_init failed: %s", esp_err_to_name(err));
|
||||
return;
|
||||
}
|
||||
if (g_hostname[0]) mdns_hostname_set(g_hostname);
|
||||
if (g_instance[0]) mdns_instance_name_set(g_instance);
|
||||
g_mdns_running = true;
|
||||
ESP_LOGI(TAG, "mDNS started (host=%s, inst=%s)", g_hostname, g_instance);
|
||||
}
|
||||
|
||||
static void mdns_stop_if_running(void) {
|
||||
if (!g_mdns_running) return;
|
||||
mdns_free();
|
||||
g_mdns_running = false;
|
||||
ESP_LOGI(TAG, "mDNS stopped");
|
||||
}
|
||||
|
||||
static void on_ip_event(void* arg, esp_event_base_t base, int32_t id, void* data) {
|
||||
if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
|
||||
mdns_start_if_needed();
|
||||
}
|
||||
}
|
||||
|
||||
static void on_wifi_event(void* arg, esp_event_base_t base, int32_t id, void* data) {
|
||||
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
mdns_stop_if_running();
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t net_mdns_autostart_init(const char* hostname, const char* instance_name) {
|
||||
if (hostname) {
|
||||
strncpy(g_hostname, hostname, sizeof(g_hostname)-1);
|
||||
g_hostname[sizeof(g_hostname)-1] = '\0';
|
||||
}
|
||||
if (instance_name) {
|
||||
strncpy(g_instance, instance_name, sizeof(g_instance)-1);
|
||||
g_instance[sizeof(g_instance)-1] = '\0';
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, on_wifi_event, NULL, NULL));
|
||||
|
||||
// Falls IP schon vorhanden:
|
||||
esp_netif_t* sta = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
|
||||
if (sta) {
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(sta, &ip) == ESP_OK && ip.ip.addr != 0) {
|
||||
mdns_start_if_needed();
|
||||
}
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
bool net_mdns_is_running(void) {
|
||||
return g_mdns_running;
|
||||
}
|
||||
|
||||
bool net_mdns_wait_started(uint32_t timeout_ms) {
|
||||
uint32_t waited = 0;
|
||||
const uint32_t step = 50;
|
||||
while (!g_mdns_running && waited < timeout_ms) {
|
||||
vTaskDelay(pdMS_TO_TICKS(step));
|
||||
waited += step;
|
||||
}
|
||||
return g_mdns_running;
|
||||
}
|
||||
|
||||
esp_err_t net_mdns_add_service(const char* service, const char* proto,
|
||||
uint16_t port, mdns_txt_item_t* txt, size_t txt_count) {
|
||||
if (!g_mdns_running) {
|
||||
mdns_start_if_needed();
|
||||
if (!g_mdns_running) return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
esp_err_t err = mdns_service_add(NULL, service, proto, port, txt, txt_count);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "mdns_service_add %s.%s:%u failed: %s", service, proto, port, esp_err_to_name(err));
|
||||
} else {
|
||||
ESP_LOGI(TAG, "mDNS service announced: %s.%s:%u", service, proto, port);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
bool net_mdns_find_service_url(const char* service, const char* proto,
|
||||
int enforce_port, const char* txt_key, const char* txt_value,
|
||||
uint32_t timeout_ms, int max_results,
|
||||
char* url_out, size_t url_out_size) {
|
||||
if (!service || !proto || !url_out || url_out_size < 16) return false;
|
||||
if (!g_mdns_running) {
|
||||
ESP_LOGW(TAG, "mDNS not running yet; waiting...");
|
||||
if (!net_mdns_wait_started(3000)) {
|
||||
ESP_LOGW(TAG, "mDNS still not running; abort query");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
mdns_result_t* results = NULL;
|
||||
esp_err_t err = mdns_query_ptr(service, proto, timeout_ms, max_results, &results);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "mdns_query_ptr error: %s", esp_err_to_name(err));
|
||||
return false;
|
||||
}
|
||||
if (!results) {
|
||||
ESP_LOGI(TAG, "mDNS query OK but no results for %s.%s", service, proto);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
for (mdns_result_t* r = results; r && !found; r = r->next) {
|
||||
bool txt_ok = true;
|
||||
if (txt_key && txt_value) {
|
||||
txt_ok = false;
|
||||
for (int i = 0; i < r->txt_count; ++i) {
|
||||
if (r->txt[i].key && r->txt[i].value &&
|
||||
strcmp(r->txt[i].key, txt_key) == 0 &&
|
||||
strcmp(r->txt[i].value, txt_value) == 0) {
|
||||
txt_ok = true; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!txt_ok) continue;
|
||||
|
||||
if (r->instance_name && strncmp(r->instance_name, "influxdb2-", 9) != 0) {
|
||||
continue; // falsche Instanz, weitersuchen
|
||||
}
|
||||
|
||||
for (mdns_ip_addr_t* a = r->addr; a && !found; a = a->next) {
|
||||
if (a->addr.type != ESP_IPADDR_TYPE_V4) continue;
|
||||
uint16_t port = r->port ? r->port : 80;
|
||||
if (enforce_port > 0 && port != (uint16_t)enforce_port) port = (uint16_t)enforce_port;
|
||||
snprintf(url_out, url_out_size, "http://" IPSTR ":%u", IP2STR(&a->addr.u_addr.ip4), (unsigned)port);
|
||||
ESP_LOGI(TAG, "mDNS URL: %s", url_out);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
mdns_query_results_free(results);
|
||||
return found;
|
||||
}
|
||||
|
||||
void net_mdns_stop(void) { mdns_stop_if_running(); }
|
||||
@@ -0,0 +1,25 @@
|
||||
// File: include/net_mdns.h
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include "esp_err.h"
|
||||
#include "mdns.h"
|
||||
|
||||
esp_err_t net_mdns_autostart_init(const char* hostname, const char* instance_name);
|
||||
bool net_mdns_is_running(void);
|
||||
bool net_mdns_wait_started(uint32_t timeout_ms);
|
||||
esp_err_t net_mdns_add_service(const char* service, const char* proto,
|
||||
uint16_t port, mdns_txt_item_t* txt, size_t txt_count);
|
||||
|
||||
bool net_mdns_find_service_url(const char* service, const char* proto,
|
||||
int enforce_port, const char* txt_key, const char* txt_value,
|
||||
uint32_t timeout_ms, int max_results,
|
||||
char* url_out, size_t url_out_size);
|
||||
|
||||
void net_mdns_stop(void);
|
||||
|
||||
// --- NEU: Auto-Discover + NVS persistieren ---
|
||||
esp_err_t net_mdns_autodiscover_and_store(const char *service, const char *proto,
|
||||
int enforce_port,
|
||||
const char *txt_key, const char *txt_value,
|
||||
uint32_t timeout_ms);
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
// File: src/sen5x_app.c
|
||||
|
||||
#include "sen5x_app.h"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/queue.h"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "sensirion_i2c_hal.h"
|
||||
#include "sensirion_i2c_esp32_config.h"
|
||||
#include "sen5x_i2c.h"
|
||||
|
||||
#include "net_influx.h"
|
||||
#include "storage.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <math.h> // NAN, isfinite, lround
|
||||
#include "vars.h"
|
||||
|
||||
// i2cdev API (aus i2cdev.c)
|
||||
esp_err_t i2cdev_init(void);
|
||||
esp_err_t i2cdev_done(void);
|
||||
|
||||
static const char* TAG = "sen5x_app";
|
||||
|
||||
/* ====================== Konfiguration ====================== */
|
||||
#define SEN5X_QUEUE_LEN 16 // Puffergröße für Samples
|
||||
#define SEN5X_PROD_STACK 4096
|
||||
#define SEN5X_CONS_STACK 6144
|
||||
#define SEN5X_PROD_PRIO 6 // Producer leicht höher priorisiert
|
||||
#define SEN5X_CONS_PRIO 5
|
||||
|
||||
#define INFLUX_INIT_RETRY_MS 1000 // Retry-Intervall bis Influx init
|
||||
#define INFLUX_FAILS_REDISCOVER 5 // Nach X Fehlern: Re-Init/Rediscovery
|
||||
#define INFLUX_BACKOFF_START_MS 2000
|
||||
#define INFLUX_BACKOFF_MAX_MS 300000
|
||||
|
||||
/* ====================== Typen & State ====================== */
|
||||
typedef struct {
|
||||
uint16_t pm1p0, pm2p5, pm4p0, pm10p0; // Rohwerte (x10)
|
||||
float temp_c, rh_pct; // skaliert
|
||||
int16_t voc_idx, nox_idx; // Rohwerte (x10)
|
||||
} sen5x_sample_t;
|
||||
|
||||
static bool g_inited = false;
|
||||
static bool g_run = false;
|
||||
static QueueHandle_t g_queue = NULL;
|
||||
static TaskHandle_t g_task_prod = NULL;
|
||||
static TaskHandle_t g_task_cons = NULL;
|
||||
|
||||
// Nur vom Consumer benutzt:
|
||||
static char* g_device_tag = NULL; // z.B. "device=xyz"
|
||||
|
||||
/* ====================== Helfer ====================== */
|
||||
#define CHECK_ESP_OR_RET(x) do { \
|
||||
esp_err_t __e = (x); \
|
||||
if (__e != ESP_OK) { \
|
||||
ESP_LOGE(TAG, "%s failed: %s", #x, esp_err_to_name(__e)); \
|
||||
return __e; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define CHECK_SEN_OR_RET(x) do { \
|
||||
int16_t __rc = (x); \
|
||||
if (__rc != 0) { \
|
||||
ESP_LOGE(TAG, "%s failed: %d", #x, (int)__rc); \
|
||||
return ESP_FAIL; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* ====================== Lokale Float-Wrapper (optional) ====================== */
|
||||
static int16_t sen5x_read_measured_values_float(float* pm1p0, float* pm2p5,
|
||||
float* pm4p0, float* pm10p0,
|
||||
float* rh, float* t,
|
||||
float* voc, float* nox) {
|
||||
uint16_t pm1_i=0, pm2_i=0, pm4_i=0, pm10_i=0;
|
||||
int16_t rh_i=0, t_i=0, voc_i=0, nox_i=0;
|
||||
int16_t err = sen5x_read_measured_values(&pm1_i, &pm2_i, &pm4_i, &pm10_i,
|
||||
&rh_i, &t_i, &voc_i, &nox_i);
|
||||
if (err) return err;
|
||||
|
||||
if (pm1p0) *pm1p0 = (pm1_i == 0xFFFF) ? NAN : pm1_i / 10.0f;
|
||||
if (pm2p5) *pm2p5 = (pm2_i == 0xFFFF) ? NAN : pm2_i / 10.0f;
|
||||
if (pm4p0) *pm4p0 = (pm4_i == 0xFFFF) ? NAN : pm4_i / 10.0f;
|
||||
if (pm10p0) *pm10p0 = (pm10_i == 0xFFFF) ? NAN : pm10_i / 10.0f;
|
||||
|
||||
if (rh) *rh = (rh_i == 0x7FFF) ? NAN : rh_i / 100.0f;
|
||||
if (t) *t = (t_i == 0x7FFF) ? NAN : t_i / 200.0f;
|
||||
if (voc) *voc = (voc_i == 0x7FFF) ? NAN : voc_i / 10.0f;
|
||||
if (nox) *nox = (nox_i == 0x7FFF) ? NAN : nox_i / 10.0f;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int16_t sen5x_read_measured_pm_values_float(float* pm1, float* pm2,
|
||||
float* pm4, float* pm10,
|
||||
float* n05, float* n10,
|
||||
float* n25, float* n40,
|
||||
float* n100, float* dtyp) {
|
||||
uint16_t pm1_i=0, pm2_i=0, pm4_i=0, pm10_i=0, n05_i=0, n10_i=0, n25_i=0, n40_i=0, n100_i=0, dtyp_i=0;
|
||||
int16_t err = sen5x_read_measured_pm_values(&pm1_i, &pm2_i, &pm4_i, &pm10_i,
|
||||
&n05_i, &n10_i, &n25_i, &n40_i, &n100_i, &dtyp_i);
|
||||
if (err) return err;
|
||||
|
||||
if (pm1) *pm1 = (pm1_i == 0xFFFF) ? NAN : pm1_i / 10.0f;
|
||||
if (pm2) *pm2 = (pm2_i == 0xFFFF) ? NAN : pm2_i / 10.0f;
|
||||
if (pm4) *pm4 = (pm4_i == 0xFFFF) ? NAN : pm4_i / 10.0f;
|
||||
if (pm10) *pm10 = (pm10_i == 0xFFFF) ? NAN : pm10_i / 10.0f;
|
||||
|
||||
if (n05) *n05 = (n05_i == 0xFFFF) ? NAN : n05_i / 10.0f;
|
||||
if (n10) *n10 = (n10_i == 0xFFFF) ? NAN : n10_i / 10.0f;
|
||||
if (n25) *n25 = (n25_i == 0xFFFF) ? NAN : n25_i / 10.0f;
|
||||
if (n40) *n40 = (n40_i == 0xFFFF) ? NAN : n40_i / 10.0f;
|
||||
if (n100) *n100 = (n100_i == 0xFFFF) ? NAN : n100_i / 10.0f;
|
||||
|
||||
if (dtyp) *dtyp = (dtyp_i == 0xFFFF) ? NAN : dtyp_i / 1000.0f; // µm
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ====================== Producer-Task ====================== */
|
||||
static void sen5x_task_producer(void* arg) {
|
||||
(void)arg;
|
||||
|
||||
const TickType_t period = pdMS_TO_TICKS(1000); // exakt 1 Hz
|
||||
TickType_t last_wake = xTaskGetTickCount();
|
||||
|
||||
ESP_LOGI(TAG, "Producer started (1 Hz).");
|
||||
|
||||
for (; g_run; ) {
|
||||
bool ready = false;
|
||||
int16_t rc = sen5x_read_data_ready(&ready);
|
||||
if (rc != 0) {
|
||||
ESP_LOGW(TAG, "sen5x_read_data_ready error: %d", (int)rc);
|
||||
} else if (ready) {
|
||||
uint16_t pm1p0=0, pm2p5=0, pm4p0=0, pm10p0=0;
|
||||
int16_t rh_raw=0, t_raw=0, voc_idx=0, nox_idx=0;
|
||||
|
||||
rc = sen5x_read_measured_values(&pm1p0, &pm2p5, &pm4p0, &pm10p0,
|
||||
&rh_raw, &t_raw, &voc_idx, &nox_idx);
|
||||
if (rc != 0) {
|
||||
ESP_LOGW(TAG, "sen5x_read_measured_values error: %d", (int)rc);
|
||||
} else {
|
||||
// Roh → Struct (wie bisher)
|
||||
sen5x_sample_t s = {
|
||||
.pm1p0 = pm1p0,
|
||||
.pm2p5 = pm2p5,
|
||||
.pm4p0 = pm4p0,
|
||||
.pm10p0 = pm10p0,
|
||||
.temp_c = ((float)t_raw) / 200.0f,
|
||||
.rh_pct = ((float)rh_raw) / 100.0f,
|
||||
.voc_idx = voc_idx,
|
||||
.nox_idx = nox_idx
|
||||
};
|
||||
|
||||
/* === GUI-Variablen jede Sekunde updaten (skaliert) === */
|
||||
char buf[24];
|
||||
float pm1f = (s.pm1p0 == 0xFFFF) ? NAN : s.pm1p0 / 10.0f;
|
||||
float pm2f = (s.pm2p5 == 0xFFFF) ? NAN : s.pm2p5 / 10.0f;
|
||||
float pm4f = (s.pm4p0 == 0xFFFF) ? NAN : s.pm4p0 / 10.0f;
|
||||
float pm10f = (s.pm10p0 == 0xFFFF) ? NAN : s.pm10p0 / 10.0f;
|
||||
float vocf = (s.voc_idx == 0x7FFF) ? NAN : s.voc_idx / 10.0f;
|
||||
// float noxf = (s.nox_idx == 0x7FFF) ? NAN : s.nox_idx / 10.0f; // bei Bedarf anzeigen
|
||||
|
||||
// Temperatur
|
||||
snprintf(buf, sizeof(buf), "%.1f", (double)s.temp_c);
|
||||
set_var_temp(buf);
|
||||
|
||||
// Feuchte
|
||||
snprintf(buf, sizeof(buf), "%.1f", (double)s.rh_pct);
|
||||
set_var_humidity(buf);
|
||||
|
||||
// VOC-Index (gerundet), falls NAN → "nan"
|
||||
if (!isfinite(vocf)) snprintf(buf, sizeof(buf), "nan");
|
||||
else snprintf(buf, sizeof(buf), "%d", (int)lround(vocf));
|
||||
set_var_voc_ind(buf);
|
||||
|
||||
// PM (µg/m³) mit einer Nachkommastelle
|
||||
if (!isfinite(pm10f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm10f);
|
||||
set_var_pm10p0(buf);
|
||||
if (!isfinite(pm4f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm4f);
|
||||
set_var_pm4p0(buf);
|
||||
if (!isfinite(pm2f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm2f);
|
||||
set_var_pm2p5(buf);
|
||||
if (!isfinite(pm1f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm1f);
|
||||
set_var_pm1p0(buf);
|
||||
|
||||
// Non-blocking enqueue; bei voller Queue: ältestes raus, neues rein
|
||||
if (xQueueSend(g_queue, &s, 0) != pdPASS) {
|
||||
sen5x_sample_t dump;
|
||||
(void)xQueueReceive(g_queue, &dump, 0); // drop oldest
|
||||
(void)xQueueSend(g_queue, &s, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vTaskDelayUntil(&last_wake, period); // präzise 1 Hz
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Producer stopping.");
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
/* ====================== Consumer-Task ====================== */
|
||||
static esp_err_t make_device_tag_once(void) {
|
||||
if (g_device_tag) return ESP_OK;
|
||||
|
||||
char* dev = NULL;
|
||||
if (storage_load_device_name(&dev) && dev && dev[0]) {
|
||||
size_t need = strlen("device=") + strlen(dev) + 1;
|
||||
g_device_tag = (char*)malloc(need);
|
||||
if (!g_device_tag) {
|
||||
if (dev) free(dev);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
snprintf(g_device_tag, need, "device=%s", dev);
|
||||
free(dev);
|
||||
return ESP_OK;
|
||||
}
|
||||
g_device_tag = strdup("device=unknown");
|
||||
return g_device_tag ? ESP_OK : ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
static bool influx_init_blocking(void) {
|
||||
// Warte/Retry bis Influx-Konfig aus NVS (oder Discovery via net_influx_* intern) bereit ist
|
||||
while (g_run) {
|
||||
if (net_influx_init_from_nvs(NULL, 3000) == ESP_OK) {
|
||||
if (make_device_tag_once() == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Influx ready, device tag: %s", g_device_tag);
|
||||
return true;
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Device-Tag allokation fehlgeschlagen");
|
||||
return false; // fatal → Task kann enden
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Influx nicht bereit – retry in %d ms", INFLUX_INIT_RETRY_MS);
|
||||
vTaskDelay(pdMS_TO_TICKS(INFLUX_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;
|
||||
if (wait_ms == 0) wait_ms = INFLUX_BACKOFF_START_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(NULL, 3000) == ESP_OK);
|
||||
if (ok) {
|
||||
ESP_LOGI(TAG, "Influx Re-Init OK");
|
||||
*backoff_ms = INFLUX_BACKOFF_START_MS;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Exponentielles Backoff bis Max
|
||||
if (wait_ms < INFLUX_BACKOFF_MAX_MS) {
|
||||
uint32_t next = wait_ms * 2;
|
||||
*backoff_ms = (next > INFLUX_BACKOFF_MAX_MS) ? INFLUX_BACKOFF_MAX_MS : next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Hilfsfunktion: Felder-String ohne NaNs bauen (Influx lehnt NaN/Inf ab) */
|
||||
static size_t append_field(char* dst, size_t cap, size_t pos, const char* key, double val, int precision) {
|
||||
if (!isfinite(val)) return pos; // skip NaN/Inf
|
||||
int n;
|
||||
if (pos > 0) {
|
||||
n = snprintf(dst + pos, (cap > pos) ? (cap - pos) : 0, ",");
|
||||
pos += (n > 0) ? n : 0;
|
||||
}
|
||||
char fmt[16];
|
||||
// z.B. "%.1f" oder "%.3f"
|
||||
snprintf(fmt, sizeof(fmt), "%%s=%%.%df", precision);
|
||||
n = snprintf(dst + pos, (cap > pos) ? (cap - pos) : 0, fmt, key, val);
|
||||
pos += (n > 0) ? n : 0;
|
||||
return pos;
|
||||
}
|
||||
|
||||
static void sen5x_task_consumer(void* arg) {
|
||||
(void)arg;
|
||||
|
||||
ESP_LOGI(TAG, "Consumer started.");
|
||||
|
||||
if (!influx_init_blocking()) {
|
||||
ESP_LOGE(TAG, "Consumer beendet (Influx init fatal gescheitert).");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
int fail_count = 0;
|
||||
uint32_t backoff_ms = INFLUX_BACKOFF_START_MS;
|
||||
|
||||
for (; g_run; ) {
|
||||
sen5x_sample_t s;
|
||||
if (xQueueReceive(g_queue, &s, portMAX_DELAY) != pdTRUE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skaliere (physikalische Einheiten)
|
||||
const double pm1 = (s.pm1p0 == 0xFFFF) ? NAN : ((double)s.pm1p0 / 10.0);
|
||||
const double pm2_5 = (s.pm2p5 == 0xFFFF) ? NAN : ((double)s.pm2p5 / 10.0);
|
||||
const double pm4 = (s.pm4p0 == 0xFFFF) ? NAN : ((double)s.pm4p0 / 10.0);
|
||||
const double pm10 = (s.pm10p0 == 0xFFFF) ? NAN : ((double)s.pm10p0 / 10.0);
|
||||
const double voc = (s.voc_idx == 0x7FFF) ? NAN : ((double)s.voc_idx / 10.0);
|
||||
const double nox = (s.nox_idx == 0x7FFF) ? NAN : ((double)s.nox_idx / 10.0);
|
||||
const double temp = (double)s.temp_c;
|
||||
const double rh = (double)s.rh_pct;
|
||||
|
||||
// Felder dynamisch ohne NaNs zusammenbauen
|
||||
char fields[256];
|
||||
size_t pos = 0;
|
||||
pos = append_field(fields, sizeof(fields), pos, "pm1", pm1, 1);
|
||||
pos = append_field(fields, sizeof(fields), pos, "pm2_5", pm2_5, 1);
|
||||
pos = append_field(fields, sizeof(fields), pos, "pm4", pm4, 1);
|
||||
pos = append_field(fields, sizeof(fields), pos, "pm10", pm10, 1);
|
||||
pos = append_field(fields, sizeof(fields), pos, "temp", temp, 3);
|
||||
pos = append_field(fields, sizeof(fields), pos, "rh", rh, 3);
|
||||
pos = append_field(fields, sizeof(fields), pos, "voc", voc, 1);
|
||||
pos = append_field(fields, sizeof(fields), pos, "nox", nox, 1);
|
||||
|
||||
if (pos == 0) {
|
||||
// Nichts valides → überspringen
|
||||
ESP_LOGW(TAG, "Skipping write: no finite fields.");
|
||||
continue;
|
||||
}
|
||||
fields[(pos < sizeof(fields)) ? pos : sizeof(fields) - 1] = '\0';
|
||||
|
||||
// Ohne Timestamp (0) → Influx vergibt Serverzeit. precision=ms im HTTP-Client ist ok.
|
||||
esp_err_t e = net_influx_write_fields(
|
||||
"air",
|
||||
g_device_tag ? g_device_tag : "device=unknown",
|
||||
0 /* ts_ms */,
|
||||
"%s",
|
||||
fields
|
||||
);
|
||||
|
||||
if (e == ESP_OK) {
|
||||
if (fail_count) ESP_LOGI(TAG, "Influx write recovered.");
|
||||
fail_count = 0;
|
||||
backoff_ms = INFLUX_BACKOFF_START_MS;
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Influx write failed: %s", esp_err_to_name(e));
|
||||
if (++fail_count >= INFLUX_FAILS_REDISCOVER) {
|
||||
(void)influx_reinit_with_backoff(&backoff_ms);
|
||||
fail_count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Consumer stopping.");
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
/* ====================== Öffentliche API ====================== */
|
||||
esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg) {
|
||||
if (g_inited) {
|
||||
ESP_LOGW(TAG, "already initialized");
|
||||
return ESP_OK;
|
||||
}
|
||||
if (!cfg) return ESP_ERR_INVALID_ARG;
|
||||
|
||||
ESP_LOGI(TAG, "Initializing SEN5x app...");
|
||||
|
||||
// 1) I2C-Subsystem
|
||||
CHECK_ESP_OR_RET(i2cdev_init());
|
||||
|
||||
// 2) HAL-Konfiguration
|
||||
struct esp32_i2c_config hal_cfg = {
|
||||
.addr = cfg->addr,
|
||||
.port = cfg->port,
|
||||
.sda = cfg->sda,
|
||||
.scl = cfg->scl,
|
||||
.sda_pullup = cfg->sda_pullup,
|
||||
.scl_pullup = cfg->scl_pullup,
|
||||
.freq = cfg->freq
|
||||
};
|
||||
CHECK_ESP_OR_RET(sensirion_i2c_config_esp32(&hal_cfg));
|
||||
|
||||
// 3) HAL init
|
||||
sensirion_i2c_hal_init();
|
||||
CHECK_ESP_OR_RET(sensirion_i2c_esp32_ok());
|
||||
|
||||
// 4) Messung starten
|
||||
CHECK_SEN_OR_RET(sen5x_start_measurement());
|
||||
ESP_LOGI(TAG, "Measurement started.");
|
||||
|
||||
// 5) Queue + Run-Flag
|
||||
g_queue = xQueueCreate(SEN5X_QUEUE_LEN, sizeof(sen5x_sample_t));
|
||||
if (!g_queue) {
|
||||
ESP_LOGE(TAG, "xQueueCreate failed");
|
||||
sen5x_stop_measurement();
|
||||
sensirion_i2c_hal_free();
|
||||
i2cdev_done();
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
g_run = true;
|
||||
g_inited = true;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void sen5x_app_deinit(void) {
|
||||
if (!g_inited) return;
|
||||
|
||||
ESP_LOGI(TAG, "Deinitializing SEN5x app...");
|
||||
|
||||
// Tasks stoppen
|
||||
g_run = false;
|
||||
|
||||
if (g_task_prod) {
|
||||
vTaskDelete(g_task_prod);
|
||||
g_task_prod = NULL;
|
||||
}
|
||||
if (g_task_cons) {
|
||||
vTaskDelete(g_task_cons);
|
||||
g_task_cons = NULL;
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (g_queue) {
|
||||
vQueueDelete(g_queue);
|
||||
g_queue = NULL;
|
||||
}
|
||||
|
||||
// Influx Tag
|
||||
if (g_device_tag) {
|
||||
free(g_device_tag);
|
||||
g_device_tag = NULL;
|
||||
}
|
||||
|
||||
// Sensor stoppen & HAL freigeben
|
||||
sen5x_stop_measurement();
|
||||
sensirion_i2c_hal_free();
|
||||
i2cdev_done();
|
||||
|
||||
g_inited = false;
|
||||
ESP_LOGI(TAG, "SEN5x app deinitialized.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Kompatibilität zur bisherigen main.c:
|
||||
* Diese Task fungiert nun als "Launcher": startet Producer & Consumer und beendet sich dann.
|
||||
* In main.c bleibt der Aufruf von xTaskCreate(sen5x_app_task, ...) unverändert.
|
||||
*/
|
||||
void sen5x_app_task(void* arg) {
|
||||
(void)arg;
|
||||
|
||||
if (!g_inited) {
|
||||
ESP_LOGE(TAG, "sen5x_app_task called before sen5x_app_init()");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
// Producer / Consumer starten
|
||||
if (xTaskCreate(sen5x_task_producer, "sen5x_prod", SEN5X_PROD_STACK, NULL, SEN5X_PROD_PRIO, &g_task_prod) != pdPASS) {
|
||||
ESP_LOGE(TAG, "Failed to create producer task");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
if (xTaskCreate(sen5x_task_consumer, "sen5x_cons", SEN5X_CONS_STACK, NULL, SEN5X_CONS_PRIO, &g_task_cons) != pdPASS) {
|
||||
ESP_LOGE(TAG, "Failed to create consumer task");
|
||||
vTaskDelete(g_task_prod);
|
||||
g_task_prod = NULL;
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Launcher done (producer+consumer started).");
|
||||
vTaskDelete(NULL); // Launcher beendet sich selbst
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
// Schlanke I2C/HAL-Konfiguration (wie zuvor genutzt)
|
||||
typedef struct {
|
||||
uint8_t addr; // 7-bit I2C-Adresse (0x69)
|
||||
int port; // I2C Port (0)
|
||||
int sda; // GPIO SDA
|
||||
int scl; // GPIO SCL
|
||||
bool sda_pullup; // interne Pullups
|
||||
bool scl_pullup; // interne Pullups
|
||||
uint32_t freq; // I2C Takt (Hz, z.B. 400000)
|
||||
} sen5x_i2c_cfg_t;
|
||||
|
||||
// Initialisiert I2C/Treiber/HAL und startet die Messung
|
||||
esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg);
|
||||
|
||||
// Endlosschleife (Pollt "data ready" und loggt Messwerte); als FreeRTOS-Task nutzbar
|
||||
void sen5x_app_task(void* arg);
|
||||
|
||||
// Stoppt Messung & gibt Ressourcen frei (optional aufzurufen z.B. bei Shutdown)
|
||||
void sen5x_app_deinit(void);
|
||||
+689
@@ -0,0 +1,689 @@
|
||||
/*
|
||||
* THIS FILE IS AUTOMATICALLY GENERATED
|
||||
*
|
||||
* I2C-Generator: 0.3.0
|
||||
* Yaml Version: 2.1.3
|
||||
* Template Version: 0.7.0-109-gb259776
|
||||
*/
|
||||
/*
|
||||
* Copyright (c) 2021, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
// File: src/sen5x_i2c.c
|
||||
#include "sen5x_i2c.h"
|
||||
#include "sensirion_common.h"
|
||||
#include "sensirion_i2c.h"
|
||||
#include "sensirion_i2c_hal.h"
|
||||
|
||||
#define SEN5X_I2C_ADDRESS 0x69
|
||||
|
||||
int16_t sen5x_start_measurement(void) {
|
||||
int16_t error;
|
||||
uint8_t buffer[2];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x21);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(50000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_start_measurement_without_pm(void) {
|
||||
int16_t error;
|
||||
uint8_t buffer[2];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x37);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(50000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_stop_measurement(void) {
|
||||
int16_t error;
|
||||
uint8_t buffer[2];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x104);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(200000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_data_ready(bool* data_ready) {
|
||||
int16_t error;
|
||||
uint8_t buffer[3];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x202);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 2);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*data_ready = buffer[1];
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_measured_values(uint16_t* mass_concentration_pm1p0,
|
||||
uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0,
|
||||
uint16_t* mass_concentration_pm10p0,
|
||||
int16_t* ambient_humidity,
|
||||
int16_t* ambient_temperature,
|
||||
int16_t* voc_index, int16_t* nox_index) {
|
||||
int16_t error;
|
||||
uint8_t buffer[24];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x3C4);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 16);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*mass_concentration_pm1p0 = sensirion_common_bytes_to_uint16_t(&buffer[0]);
|
||||
*mass_concentration_pm2p5 = sensirion_common_bytes_to_uint16_t(&buffer[2]);
|
||||
*mass_concentration_pm4p0 = sensirion_common_bytes_to_uint16_t(&buffer[4]);
|
||||
*mass_concentration_pm10p0 = sensirion_common_bytes_to_uint16_t(&buffer[6]);
|
||||
*ambient_humidity = sensirion_common_bytes_to_int16_t(&buffer[8]);
|
||||
*ambient_temperature = sensirion_common_bytes_to_int16_t(&buffer[10]);
|
||||
*voc_index = sensirion_common_bytes_to_int16_t(&buffer[12]);
|
||||
*nox_index = sensirion_common_bytes_to_int16_t(&buffer[14]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_measured_raw_values(int16_t* raw_humidity,
|
||||
int16_t* raw_temperature,
|
||||
uint16_t* raw_voc, uint16_t* raw_nox) {
|
||||
int16_t error;
|
||||
uint8_t buffer[12];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x3D2);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 8);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*raw_humidity = sensirion_common_bytes_to_int16_t(&buffer[0]);
|
||||
*raw_temperature = sensirion_common_bytes_to_int16_t(&buffer[2]);
|
||||
*raw_voc = sensirion_common_bytes_to_uint16_t(&buffer[4]);
|
||||
*raw_nox = sensirion_common_bytes_to_uint16_t(&buffer[6]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_measured_values_sen50(uint16_t* mass_concentration_pm1p0,
|
||||
uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0,
|
||||
uint16_t* mass_concentration_pm10p0) {
|
||||
int16_t error;
|
||||
|
||||
int16_t ambient_humidity_dummy;
|
||||
int16_t ambient_temperature_dummy;
|
||||
int16_t voc_index_dummy;
|
||||
int16_t nox_index_dummy;
|
||||
|
||||
error = sen5x_read_measured_values(
|
||||
mass_concentration_pm1p0, mass_concentration_pm2p5,
|
||||
mass_concentration_pm4p0, mass_concentration_pm10p0,
|
||||
&ambient_humidity_dummy, &ambient_temperature_dummy, &voc_index_dummy,
|
||||
&nox_index_dummy);
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_measured_pm_values(
|
||||
uint16_t* mass_concentration_pm1p0, uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0, uint16_t* mass_concentration_pm10p0,
|
||||
uint16_t* number_concentration_pm0p5, uint16_t* number_concentration_pm1p0,
|
||||
uint16_t* number_concentration_pm2p5, uint16_t* number_concentration_pm4p0,
|
||||
uint16_t* number_concentration_pm10p0, uint16_t* typical_particle_size) {
|
||||
int16_t error;
|
||||
uint8_t buffer[30];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x413);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 20);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*mass_concentration_pm1p0 = sensirion_common_bytes_to_uint16_t(&buffer[0]);
|
||||
*mass_concentration_pm2p5 = sensirion_common_bytes_to_uint16_t(&buffer[2]);
|
||||
*mass_concentration_pm4p0 = sensirion_common_bytes_to_uint16_t(&buffer[4]);
|
||||
*mass_concentration_pm10p0 = sensirion_common_bytes_to_uint16_t(&buffer[6]);
|
||||
*number_concentration_pm0p5 =
|
||||
sensirion_common_bytes_to_uint16_t(&buffer[8]);
|
||||
*number_concentration_pm1p0 =
|
||||
sensirion_common_bytes_to_uint16_t(&buffer[10]);
|
||||
*number_concentration_pm2p5 =
|
||||
sensirion_common_bytes_to_uint16_t(&buffer[12]);
|
||||
*number_concentration_pm4p0 =
|
||||
sensirion_common_bytes_to_uint16_t(&buffer[14]);
|
||||
*number_concentration_pm10p0 =
|
||||
sensirion_common_bytes_to_uint16_t(&buffer[16]);
|
||||
*typical_particle_size = sensirion_common_bytes_to_uint16_t(&buffer[18]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_start_fan_cleaning(void) {
|
||||
int16_t error;
|
||||
uint8_t buffer[2];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x5607);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_temperature_offset_parameters(int16_t temp_offset,
|
||||
int16_t slope,
|
||||
uint16_t time_constant) {
|
||||
int16_t error;
|
||||
uint8_t buffer[11];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60B2);
|
||||
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, temp_offset);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, slope);
|
||||
offset =
|
||||
sensirion_i2c_add_uint16_t_to_buffer(&buffer[0], offset, time_constant);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_temperature_offset_parameters(int16_t* temp_offset,
|
||||
int16_t* slope,
|
||||
uint16_t* time_constant) {
|
||||
int16_t error;
|
||||
uint8_t buffer[9];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60B2);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 6);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*temp_offset = sensirion_common_bytes_to_int16_t(&buffer[0]);
|
||||
*slope = sensirion_common_bytes_to_int16_t(&buffer[2]);
|
||||
*time_constant = sensirion_common_bytes_to_uint16_t(&buffer[4]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_warm_start_parameter(uint16_t warm_start) {
|
||||
int16_t error;
|
||||
uint8_t buffer[5];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60C6);
|
||||
|
||||
offset =
|
||||
sensirion_i2c_add_uint16_t_to_buffer(&buffer[0], offset, warm_start);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_warm_start_parameter(uint16_t* warm_start) {
|
||||
int16_t error;
|
||||
uint8_t buffer[3];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60C6);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 2);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*warm_start = sensirion_common_bytes_to_uint16_t(&buffer[0]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_voc_algorithm_tuning_parameters(
|
||||
int16_t index_offset, int16_t learning_time_offset_hours,
|
||||
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
|
||||
int16_t std_initial, int16_t gain_factor) {
|
||||
int16_t error;
|
||||
uint8_t buffer[20];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60D0);
|
||||
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, index_offset);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
learning_time_offset_hours);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
learning_time_gain_hours);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
gating_max_duration_minutes);
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, std_initial);
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, gain_factor);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_voc_algorithm_tuning_parameters(
|
||||
int16_t* index_offset, int16_t* learning_time_offset_hours,
|
||||
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
|
||||
int16_t* std_initial, int16_t* gain_factor) {
|
||||
int16_t error;
|
||||
uint8_t buffer[18];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60D0);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 12);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*index_offset = sensirion_common_bytes_to_int16_t(&buffer[0]);
|
||||
*learning_time_offset_hours = sensirion_common_bytes_to_int16_t(&buffer[2]);
|
||||
*learning_time_gain_hours = sensirion_common_bytes_to_int16_t(&buffer[4]);
|
||||
*gating_max_duration_minutes =
|
||||
sensirion_common_bytes_to_int16_t(&buffer[6]);
|
||||
*std_initial = sensirion_common_bytes_to_int16_t(&buffer[8]);
|
||||
*gain_factor = sensirion_common_bytes_to_int16_t(&buffer[10]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_nox_algorithm_tuning_parameters(
|
||||
int16_t index_offset, int16_t learning_time_offset_hours,
|
||||
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
|
||||
int16_t std_initial, int16_t gain_factor) {
|
||||
int16_t error;
|
||||
uint8_t buffer[20];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60E1);
|
||||
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, index_offset);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
learning_time_offset_hours);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
learning_time_gain_hours);
|
||||
offset = sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset,
|
||||
gating_max_duration_minutes);
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, std_initial);
|
||||
offset =
|
||||
sensirion_i2c_add_int16_t_to_buffer(&buffer[0], offset, gain_factor);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_nox_algorithm_tuning_parameters(
|
||||
int16_t* index_offset, int16_t* learning_time_offset_hours,
|
||||
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
|
||||
int16_t* std_initial, int16_t* gain_factor) {
|
||||
int16_t error;
|
||||
uint8_t buffer[18];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60E1);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 12);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*index_offset = sensirion_common_bytes_to_int16_t(&buffer[0]);
|
||||
*learning_time_offset_hours = sensirion_common_bytes_to_int16_t(&buffer[2]);
|
||||
*learning_time_gain_hours = sensirion_common_bytes_to_int16_t(&buffer[4]);
|
||||
*gating_max_duration_minutes =
|
||||
sensirion_common_bytes_to_int16_t(&buffer[6]);
|
||||
*std_initial = sensirion_common_bytes_to_int16_t(&buffer[8]);
|
||||
*gain_factor = sensirion_common_bytes_to_int16_t(&buffer[10]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_rht_acceleration_mode(uint16_t mode) {
|
||||
int16_t error;
|
||||
uint8_t buffer[5];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60F7);
|
||||
|
||||
offset = sensirion_i2c_add_uint16_t_to_buffer(&buffer[0], offset, mode);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_rht_acceleration_mode(uint16_t* mode) {
|
||||
int16_t error;
|
||||
uint8_t buffer[3];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x60F7);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 2);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*mode = sensirion_common_bytes_to_uint16_t(&buffer[0]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_voc_algorithm_state(const uint8_t* state,
|
||||
uint8_t state_size) {
|
||||
int16_t error;
|
||||
uint8_t buffer[14];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x6181);
|
||||
|
||||
offset = sensirion_i2c_add_bytes_to_buffer(&buffer[0], offset, state,
|
||||
state_size);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_voc_algorithm_state(uint8_t* state, uint8_t state_size) {
|
||||
int16_t error;
|
||||
uint8_t buffer[12];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x6181);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 8);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_common_copy_bytes(&buffer[0], state, state_size);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_set_fan_auto_cleaning_interval(uint32_t interval) {
|
||||
int16_t error;
|
||||
uint8_t buffer[8];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x8004);
|
||||
|
||||
offset = sensirion_i2c_add_uint32_t_to_buffer(&buffer[0], offset, interval);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_fan_auto_cleaning_interval(uint32_t* interval) {
|
||||
int16_t error;
|
||||
uint8_t buffer[6];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0x8004);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 4);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*interval = sensirion_common_bytes_to_uint32_t(&buffer[0]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_product_name(unsigned char* product_name,
|
||||
uint8_t product_name_size) {
|
||||
int16_t error;
|
||||
uint8_t buffer[48];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD014);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(50000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 32);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_common_copy_bytes(&buffer[0], product_name, product_name_size);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_serial_number(unsigned char* serial_number,
|
||||
uint8_t serial_number_size) {
|
||||
int16_t error;
|
||||
uint8_t buffer[48];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD033);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(50000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 32);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_common_copy_bytes(&buffer[0], serial_number, serial_number_size);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_get_version(uint8_t* firmware_major, uint8_t* firmware_minor,
|
||||
bool* firmware_debug, uint8_t* hardware_major,
|
||||
uint8_t* hardware_minor, uint8_t* protocol_major,
|
||||
uint8_t* protocol_minor) {
|
||||
int16_t error;
|
||||
uint8_t buffer[12];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD100);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 8);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*firmware_major = buffer[0];
|
||||
*firmware_minor = buffer[1];
|
||||
*firmware_debug = buffer[2];
|
||||
*hardware_major = buffer[3];
|
||||
*hardware_minor = buffer[4];
|
||||
*protocol_major = buffer[5];
|
||||
*protocol_minor = buffer[6];
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_device_status(uint32_t* device_status) {
|
||||
int16_t error;
|
||||
uint8_t buffer[6];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD206);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 4);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*device_status = sensirion_common_bytes_to_uint32_t(&buffer[0]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_read_and_clear_device_status(uint32_t* device_status) {
|
||||
int16_t error;
|
||||
uint8_t buffer[6];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD210);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
sensirion_i2c_hal_sleep_usec(20000);
|
||||
|
||||
error = sensirion_i2c_read_data_inplace(SEN5X_I2C_ADDRESS, &buffer[0], 4);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
*device_status = sensirion_common_bytes_to_uint32_t(&buffer[0]);
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sen5x_device_reset(void) {
|
||||
int16_t error;
|
||||
uint8_t buffer[2];
|
||||
uint16_t offset = 0;
|
||||
offset = sensirion_i2c_add_command_to_buffer(&buffer[0], offset, 0xD304);
|
||||
|
||||
error = sensirion_i2c_write_data(SEN5X_I2C_ADDRESS, &buffer[0], offset);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
sensirion_i2c_hal_sleep_usec(200000);
|
||||
return NO_ERROR;
|
||||
}
|
||||
+721
@@ -0,0 +1,721 @@
|
||||
/*
|
||||
* THIS FILE IS AUTOMATICALLY GENERATED
|
||||
*
|
||||
* I2C-Generator: 0.3.0
|
||||
* Yaml Version: 2.1.3
|
||||
* Template Version: 0.7.0-109-gb259776
|
||||
*/
|
||||
/*
|
||||
* Copyright (c) 2021, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SEN5X_I2C_H
|
||||
#define SEN5X_I2C_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include "sensirion_config.h"
|
||||
|
||||
/**
|
||||
* sen5x_start_measurement() - Starts a continuous measurement.
|
||||
*
|
||||
* After starting the measurement, it takes some time (~1s) until the first
|
||||
* measurement results are available. You could poll with the command
|
||||
* 0x0202 \"Read Data Ready\" to check when the results are ready to read.
|
||||
*
|
||||
* If the device is in measure mode without particulate matter (low-power)
|
||||
* and the firmware version is at least 2.0, this command enables PM
|
||||
* measurement without affecting the already running RH/T/VOC/NOx measurements
|
||||
* (except that the \"data ready\"-flag will be cleared). In previous firmware
|
||||
* versions, this command is supported only in idle mode.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_start_measurement(void);
|
||||
|
||||
/**
|
||||
* sen5x_start_measurement_without_pm() - Starts a continuous measurement
|
||||
* without PM. Only humidity, temperature, VOC and NOx are available in this
|
||||
* mode. Laser and fan are switched off to keep power consumption low.
|
||||
*
|
||||
* After starting the measurement, it takes some time (~1s) until the first
|
||||
* measurement results are available. You could poll with the command
|
||||
* 0x0202 \"Read Data Ready\" to check when the results are ready to read.
|
||||
*
|
||||
* If the device is in measure mode with particulate matter (normal measure
|
||||
* mode) and the firmware version is at least 2.0, this command disables PM
|
||||
* measurement without affecting the already running RH/T/VOC/NOx measurements
|
||||
* (except that the \"data ready\"-flag will be cleared). In previous firmware
|
||||
* versions, this command is supported only in idle mode.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_start_measurement_without_pm(void);
|
||||
|
||||
/**
|
||||
* sen5x_stop_measurement() - Stops the measurement and returns to idle mode.
|
||||
*
|
||||
* If the device is already in idle mode, this command has no effect.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_stop_measurement(void);
|
||||
|
||||
/**
|
||||
* sen5x_read_data_ready() - This command can be used to check if new
|
||||
* measurement results are ready to read. The data ready flag is automatically
|
||||
* reset after reading the measurement values with the 0x03.. \"Read Measured
|
||||
* Values\" commands.
|
||||
*
|
||||
* @note During fan (auto-)cleaning, no measurement data is available for
|
||||
* several seconds and thus this flag will not be set until cleaning has
|
||||
* finished. So please expect gaps of several seconds at any time if fan
|
||||
* auto-cleaning is enabled.
|
||||
*
|
||||
* @param padding Padding byte, always 0x00.
|
||||
*
|
||||
* @param data_ready True (0x01) if data is ready, False (0x00) if not. When no
|
||||
* measurement is running, False will be returned.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_data_ready(bool* data_ready);
|
||||
|
||||
/**
|
||||
* sen5x_read_measured_values() - Returns the measured values.
|
||||
*
|
||||
* The command 0x0202 \"Read Data Ready\" can be used to check if new
|
||||
* data is available since the last read operation. If no new data is
|
||||
* available, the previous values will be returned again. If no data is
|
||||
* available at all (e.g. measurement not running for at least one
|
||||
* second), all values will be at their upper limit (0xFFFF for `uint16`,
|
||||
* 0x7FFF for `int16`).
|
||||
*
|
||||
* @param mass_concentration_pm1p0 Value is scaled with factor 10:
|
||||
* PM1.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm2p5 Value is scaled with factor 10:
|
||||
* PM2.5 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm4p0 Value is scaled with factor 10:
|
||||
* PM4.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm10p0 Value is scaled with factor 10:
|
||||
* PM10.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param ambient_humidity Value is scaled with factor 100: RH [%] = value / 100
|
||||
* @note If this value is unknown, 0x7FFF is returned.*
|
||||
*
|
||||
* @param ambient_temperature Value is scaled with factor 200:
|
||||
* T [°C] = value / 200
|
||||
* @note If this value is unknown, 0x7FFF is returned.*
|
||||
*
|
||||
* @param voc_index Value is scaled with factor 10: VOC Index = value / 10
|
||||
* @note If this value is unknown, 0x7FFF is returned.*
|
||||
*
|
||||
* @param nox_index Value is scaled with factor 10: NOx Index = value / 10
|
||||
* @note If this value is unknown, 0x7FFF is returned. During
|
||||
* the first 10..11 seconds after power-on or device reset, this
|
||||
* value will be 0x7FFF as well.*
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_measured_values(uint16_t* mass_concentration_pm1p0,
|
||||
uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0,
|
||||
uint16_t* mass_concentration_pm10p0,
|
||||
int16_t* ambient_humidity,
|
||||
int16_t* ambient_temperature,
|
||||
int16_t* voc_index, int16_t* nox_index);
|
||||
|
||||
/**
|
||||
* sen5x_read_measured_raw_values() - Returns the measured raw values.
|
||||
|
||||
The command 0x0202 \"Read Data Ready\" can be used to check if new
|
||||
data is available since the last read operation. If no new data is
|
||||
available, the previous values will be returned again. If no data
|
||||
is available at all (e.g. measurement not running for at least one
|
||||
second), all values will be at their upper limit (0xFFFF for `uint16`,
|
||||
0x7FFF for `int16`).
|
||||
*
|
||||
* @param raw_humidity Value is scaled with factor 100: RH [%] = value / 100
|
||||
* @note If this value is unknown, 0x7FFF is returned.
|
||||
*
|
||||
* @param raw_temperature Value is scaled with factor 200: T [°C] = value / 200
|
||||
* @note If this value is unknown, 0x7FFF is returned.
|
||||
*
|
||||
* @param raw_voc Raw measured VOC ticks without scale factor.
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param raw_nox Raw measured NOx ticks without scale factor.
|
||||
* @note If this value is unknown, 0xFFFF is returned. During
|
||||
* the first 10..11 seconds after power-on or device reset, this
|
||||
* value will be 0xFFFF as well.*
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_measured_raw_values(int16_t* raw_humidity,
|
||||
int16_t* raw_temperature,
|
||||
uint16_t* raw_voc, uint16_t* raw_nox);
|
||||
|
||||
/**
|
||||
* sen5x_read_measured_values_sen50() - Returns the measured values for SEN50.
|
||||
*
|
||||
* The command 0x0202 \"Read Data Ready\" can be used to check if new
|
||||
* data is available since the last read operation. If no new data is
|
||||
* available, the previous values will be returned again. If no data is
|
||||
* available at all (e.g. measurement not running for at least one
|
||||
* second), all values will be at their upper limit (0xFFFF).
|
||||
*
|
||||
* @param mass_concentration_pm1p0 Value is scaled with factor 10:
|
||||
* PM1.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm2p5 Value is scaled with factor 10:
|
||||
* PM2.5 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm4p0 Value is scaled with factor 10:
|
||||
* PM4.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm10p0 Value is scaled with factor 10:
|
||||
* PM10.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_measured_values_sen50(uint16_t* mass_concentration_pm1p0,
|
||||
uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0,
|
||||
uint16_t* mass_concentration_pm10p0);
|
||||
|
||||
/**
|
||||
* sen5x_read_measured_pm_values() - Returns the measured particulate matter
|
||||
* values.
|
||||
*
|
||||
* The command 0x0202 \"Read Data Ready\" can be used to check if new
|
||||
* data is available since the last read operation. If no new data is
|
||||
* available, the previous values will be returned again. If no data
|
||||
* is available at all (e.g. measurement not running for at least one
|
||||
* second), all values will be 0xFFFF.
|
||||
*
|
||||
* @param mass_concentration_pm1p0 Value is scaled with factor 10:
|
||||
* PM1.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm2p5 Value is scaled with factor 10:
|
||||
* PM2.5 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm4p0 Value is scaled with factor 10:
|
||||
* PM4.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param mass_concentration_pm10p0 Value is scaled with factor 10:
|
||||
* PM10.0 [µg/m³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param number_concentration_pm0p5 Value is scaled with factor 10:
|
||||
* PM0.5 [#/cm³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param number_concentration_pm1p0 Value is scaled with factor 10:
|
||||
* PM1.0 [#/cm³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param number_concentration_pm2p5 Value is scaled with factor 10:
|
||||
* PM2.5 [#/cm³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param number_concentration_pm4p0 Value is scaled with factor 10:
|
||||
* PM4.0 [#/cm³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param number_concentration_pm10p0 Value is scaled with factor 10:
|
||||
* PM10.0 [#/cm³] = value / 10
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @param typical_particle_size Value is scaled with factor 1000:
|
||||
* Size [µm] = value / 1000
|
||||
* @note If this value is unknown, 0xFFFF is returned.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_measured_pm_values(
|
||||
uint16_t* mass_concentration_pm1p0, uint16_t* mass_concentration_pm2p5,
|
||||
uint16_t* mass_concentration_pm4p0, uint16_t* mass_concentration_pm10p0,
|
||||
uint16_t* number_concentration_pm0p5, uint16_t* number_concentration_pm1p0,
|
||||
uint16_t* number_concentration_pm2p5, uint16_t* number_concentration_pm4p0,
|
||||
uint16_t* number_concentration_pm10p0, uint16_t* typical_particle_size);
|
||||
|
||||
/**
|
||||
* sen5x_start_fan_cleaning() - Starts the fan cleaning manually. The \"data
|
||||
* ready\"-flag will be cleared immediately and during the next few seconds, no
|
||||
* new measurement results will be available (old values will be returned). Once
|
||||
* the cleaning is finished, the \"data ready\"-flag will be set and new
|
||||
* measurement results will be available.
|
||||
*
|
||||
* When executing this command while cleaning is already active, the
|
||||
* command does nothing.
|
||||
*
|
||||
* If you stop the measurement while fan cleaning is active, the cleaning
|
||||
* will be aborted immediately.
|
||||
*
|
||||
* @note This command is only available in measure mode with PM measurement
|
||||
* enabled, i.e. only if the fan is already running. In any other state, this
|
||||
* command does nothing.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_start_fan_cleaning(void);
|
||||
|
||||
/**
|
||||
* sen5x_set_temperature_offset_parameters() - Sets the temperature offset
|
||||
* parameters for the device.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param temp_offset Constant temperature offset scaled with factor 200 (T [°C]
|
||||
* = value / 200). The default value is 0.
|
||||
*
|
||||
* @param slope Normalized temperature offset slope scaled with factor 10000
|
||||
* (applied factor = value / 10000). The default value is 0.
|
||||
*
|
||||
* @param time_constant Time constant [s] how fast the new slope and offset will
|
||||
* be applied. After the specified value in seconds, 63% of the new slope and
|
||||
* offset are applied. A time constant of zero means the new values will be
|
||||
* applied immediately (within the next measure interval of 1 second).
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_temperature_offset_parameters(int16_t temp_offset,
|
||||
int16_t slope,
|
||||
uint16_t time_constant);
|
||||
|
||||
/**
|
||||
* sen5x_get_temperature_offset_parameters() - Gets the temperature offset
|
||||
* parameters from the device.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param temp_offset Constant temperature offset scaled with factor 200 (T [°C]
|
||||
* = value / 200).
|
||||
*
|
||||
* @param slope Normalized temperature offset slope scaled with factor 10000
|
||||
* (applied factor = value / 10000).
|
||||
*
|
||||
* @param time_constant Time constant [s] how fast the slope and offset are
|
||||
* applied. After the specified value in seconds, 63% of the new slope and
|
||||
* offset are applied.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_temperature_offset_parameters(int16_t* temp_offset,
|
||||
int16_t* slope,
|
||||
uint16_t* time_constant);
|
||||
|
||||
/**
|
||||
* sen5x_set_warm_start_parameter() - Sets the warm start parameter for the
|
||||
* device.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @note This parameter can be changed in any state of the device (and the
|
||||
* getter immediately returns the new value), but it is applied only the next
|
||||
* time starting a measurement, i.e. when sending a \"Start Measurement\"
|
||||
* command! So the parameter needs to be set *before* a warm-start measurement
|
||||
* is started.
|
||||
*
|
||||
* @param warm_start Warm start behavior as a value in the range from 0 (cold
|
||||
* start) to 65535 (warm start). The default value is 0.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_warm_start_parameter(uint16_t warm_start);
|
||||
|
||||
/**
|
||||
* sen5x_get_warm_start_parameter() - Gets the warm start parameter from the
|
||||
* device.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param warm_start Warm start behavior as a value in the range from 0 (cold
|
||||
* start) to 65535 (warm start).
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_warm_start_parameter(uint16_t* warm_start);
|
||||
|
||||
/**
|
||||
* sen5x_set_voc_algorithm_tuning_parameters() - Sets the tuning parameters of
|
||||
* the VOC algorithm.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @note This command is available only in idle mode. In measure mode, this
|
||||
* command has no effect. In addition, it has no effect if at least one
|
||||
* parameter is outside the specified range.
|
||||
*
|
||||
* @param index_offset VOC index representing typical (average) conditions.
|
||||
* Allowed values are in range 1..250. The default value is 100.
|
||||
*
|
||||
* @param learning_time_offset_hours Time constant to estimate the VOC algorithm
|
||||
* offset from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time. Allowed values are in range 1..1000. The default
|
||||
* value is 12 hours.
|
||||
*
|
||||
* @param learning_time_gain_hours Time constant to estimate the VOC algorithm
|
||||
* gain from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time. Allowed values are in range 1..1000. The default
|
||||
* value is 12 hours.
|
||||
*
|
||||
* @param gating_max_duration_minutes Maximum duration of gating in minutes
|
||||
* (freeze of estimator during high VOC index signal). Set to zero to disable
|
||||
* the gating. Allowed values are in range 0..3000. The default value is 180
|
||||
* minutes.
|
||||
*
|
||||
* @param std_initial Initial estimate for standard deviation. Lower value
|
||||
* boosts events during initial learning period, but may result in larger
|
||||
* device-to-device variations. Allowed values are in range 10..5000. The
|
||||
* default value is 50.
|
||||
*
|
||||
* @param gain_factor Gain factor to amplify or to attenuate the VOC index
|
||||
* output. Allowed values are in range 1..1000. The default value is 230.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_voc_algorithm_tuning_parameters(
|
||||
int16_t index_offset, int16_t learning_time_offset_hours,
|
||||
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
|
||||
int16_t std_initial, int16_t gain_factor);
|
||||
|
||||
/**
|
||||
* sen5x_get_voc_algorithm_tuning_parameters() - Gets the currently set tuning
|
||||
* parameters of the VOC algorithm.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param index_offset VOC index representing typical (average) conditions.
|
||||
*
|
||||
* @param learning_time_offset_hours Time constant to estimate the VOC algorithm
|
||||
* offset from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time.
|
||||
*
|
||||
* @param learning_time_gain_hours Time constant to estimate the VOC algorithm
|
||||
* gain from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time.
|
||||
*
|
||||
* @param gating_max_duration_minutes Maximum duration of gating in minutes
|
||||
* (freeze of estimator during high VOC index signal). Zero disables the gating.
|
||||
*
|
||||
* @param std_initial Initial estimate for standard deviation. Lower value
|
||||
* boosts events during initial learning period, but may result in larger
|
||||
* device-to-device variations.
|
||||
*
|
||||
* @param gain_factor Gain factor to amplify or to attenuate the VOC index
|
||||
* output.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_voc_algorithm_tuning_parameters(
|
||||
int16_t* index_offset, int16_t* learning_time_offset_hours,
|
||||
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
|
||||
int16_t* std_initial, int16_t* gain_factor);
|
||||
|
||||
/**
|
||||
* sen5x_set_nox_algorithm_tuning_parameters() - Sets the tuning parameters of
|
||||
* the NOx algorithm.
|
||||
*
|
||||
* Supported sensors: SEN55
|
||||
*
|
||||
* @note This command is available only in idle mode. In measure mode, this
|
||||
* command has no effect. In addition, it has no effect if at least one
|
||||
* parameter is outside the specified range.
|
||||
*
|
||||
* @param index_offset NOx index representing typical (average) conditions.
|
||||
* Allowed values are in range 1..250. The default value is 1.
|
||||
*
|
||||
* @param learning_time_offset_hours Time constant to estimate the NOx algorithm
|
||||
* offset from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time. Allowed values are in range 1..1000. The default
|
||||
* value is 12 hours.
|
||||
*
|
||||
* @param learning_time_gain_hours The time constant to estimate the NOx
|
||||
* algorithm gain from the history has no impact for NOx. This parameter is
|
||||
* still in place for consistency reasons with the VOC tuning parameters
|
||||
* command. This parameter must always be set to 12 hours.
|
||||
*
|
||||
* @param gating_max_duration_minutes Maximum duration of gating in minutes
|
||||
* (freeze of estimator during high NOx index signal). Set to zero to disable
|
||||
* the gating. Allowed values are in range 0..3000. The default value is 720
|
||||
* minutes.
|
||||
*
|
||||
* @param std_initial The initial estimate for standard deviation parameter has
|
||||
* no impact for NOx. This parameter is still in place for consistency reasons
|
||||
* with the VOC tuning parameters command. This parameter must always be set
|
||||
* to 50.
|
||||
*
|
||||
* @param gain_factor Gain factor to amplify or to attenuate the NOx index
|
||||
* output. Allowed values are in range 1..1000. The default value is 230.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_nox_algorithm_tuning_parameters(
|
||||
int16_t index_offset, int16_t learning_time_offset_hours,
|
||||
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
|
||||
int16_t std_initial, int16_t gain_factor);
|
||||
|
||||
/**
|
||||
* sen5x_get_nox_algorithm_tuning_parameters() - Gets the currently set tuning
|
||||
* parameters of the NOx algorithm.
|
||||
*
|
||||
* Supported sensors: SEN55
|
||||
*
|
||||
* @param index_offset NOx index representing typical (average) conditions.
|
||||
*
|
||||
* @param learning_time_offset_hours Time constant to estimate the NOx algorithm
|
||||
* offset from the history in hours. Past events will be forgotten after about
|
||||
* twice the learning time.
|
||||
*
|
||||
* @param learning_time_gain_hours The time constant to estimate the NOx
|
||||
* algorithm gain from the history has no impact for NOx. This parameter is
|
||||
* still in place for consistency reasons with the VOC tuning parameters
|
||||
* command.
|
||||
*
|
||||
* @param gating_max_duration_minutes Maximum duration of gating in minutes
|
||||
* (freeze of estimator during high NOx index signal). Zero disables the gating.
|
||||
*
|
||||
* @param std_initial The initial estimate for standard deviation has no impact
|
||||
* for NOx. This parameter is still in place for consistency reasons with the
|
||||
* VOC tuning parameters command.
|
||||
*
|
||||
* @param gain_factor Gain factor to amplify or to attenuate the NOx index
|
||||
* output.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_nox_algorithm_tuning_parameters(
|
||||
int16_t* index_offset, int16_t* learning_time_offset_hours,
|
||||
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
|
||||
int16_t* std_initial, int16_t* gain_factor);
|
||||
|
||||
/**
|
||||
* sen5x_set_rht_acceleration_mode() - Sets the RH/T acceleration mode.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @note This parameter can be changed in any state of the device (and the
|
||||
* getter immediately returns the new value), but it is applied only the next
|
||||
* time starting a measurement, i.e. when sending a \"Start Measurement\"
|
||||
* command. So the parameter needs to be set *before* a new measurement is
|
||||
* started.
|
||||
*
|
||||
* @param mode The new RH/T acceleration mode.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_rht_acceleration_mode(uint16_t mode);
|
||||
|
||||
/**
|
||||
* sen5x_get_rht_acceleration_mode() - Gets the RH/T acceleration mode.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param mode The current RH/T acceleration mode.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_rht_acceleration_mode(uint16_t* mode);
|
||||
|
||||
/**
|
||||
* sen5x_set_voc_algorithm_state() - Sets the VOC algorithm state previously
|
||||
* received with the \"Get VOC Algorithm State\" command.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @note This command is only available in idle mode and the state will be
|
||||
* applied only once when starting the next measurement. Any further
|
||||
* measurements (i.e. when stopping and restarting the measure mode) will reset
|
||||
* the state to initial values. In measure mode, this command has no effect.
|
||||
*
|
||||
* @param state VOC algorithm state to restore.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_voc_algorithm_state(const uint8_t* state, uint8_t state_size);
|
||||
|
||||
/**
|
||||
* sen5x_get_voc_algorithm_state() - Gets the current VOC algorithm state. This
|
||||
* data can be used to restore the state with the \"Set VOC Algorithm State\"
|
||||
* command after a short power cycle or device reset.
|
||||
*
|
||||
* This command can be used either in measure mode or in idle mode
|
||||
* (which will then return the state at the time when the measurement
|
||||
* was stopped). In measure mode, the state can be read each measure
|
||||
* interval to always have the latest state available, even in case of
|
||||
* a sudden power loss.
|
||||
*
|
||||
* Supported sensors: SEN54, SEN55
|
||||
*
|
||||
* @param state Current VOC algorithm state.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_voc_algorithm_state(uint8_t* state, uint8_t state_size);
|
||||
|
||||
/**
|
||||
* sen5x_set_fan_auto_cleaning_interval() - Sets the fan auto cleaning interval
|
||||
* for the device.
|
||||
*
|
||||
* @param interval Fan auto cleaning interval [s]. Set to zero to disable auto
|
||||
* cleaning.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_set_fan_auto_cleaning_interval(uint32_t interval);
|
||||
|
||||
/**
|
||||
* sen5x_get_fan_auto_cleaning_interval() - Gets the fan auto cleaning interval
|
||||
* from the device.
|
||||
*
|
||||
* @param interval Fan auto cleaning interval [s]. Zero means auto cleaning is
|
||||
* disabled.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_fan_auto_cleaning_interval(uint32_t* interval);
|
||||
|
||||
/**
|
||||
* sen5x_get_product_name() - Gets the product name from the device.
|
||||
*
|
||||
* @param product_name Null-terminated ASCII string containing the product name.
|
||||
* Up to 32 characters can be read from the device.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_product_name(unsigned char* product_name,
|
||||
uint8_t product_name_size);
|
||||
|
||||
/**
|
||||
* sen5x_get_serial_number() - Gets the serial number from the device.
|
||||
*
|
||||
* @param serial_number Null-terminated ASCII string containing the serial
|
||||
* number. Up to 32 characters can be read from the device.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_serial_number(unsigned char* serial_number,
|
||||
uint8_t serial_number_size);
|
||||
|
||||
/**
|
||||
* sen5x_get_version() - Gets the version information for the hardware, firmware
|
||||
* and communication protocol.
|
||||
*
|
||||
* @param firmware_major Firmware major version number.
|
||||
*
|
||||
* @param firmware_minor Firmware minor version number.
|
||||
*
|
||||
* @param firmware_debug Firmware debug state. If the debug state is set, the
|
||||
* firmware is in development.
|
||||
*
|
||||
* @param hardware_major Hardware major version number.
|
||||
*
|
||||
* @param hardware_minor Hardware minor version number.
|
||||
*
|
||||
* @param protocol_major Protocol major version number.
|
||||
*
|
||||
* @param protocol_minor Protocol minor version number.
|
||||
*
|
||||
* @param padding Padding byte, ignore this.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_get_version(uint8_t* firmware_major, uint8_t* firmware_minor,
|
||||
bool* firmware_debug, uint8_t* hardware_major,
|
||||
uint8_t* hardware_minor, uint8_t* protocol_major,
|
||||
uint8_t* protocol_minor);
|
||||
|
||||
/**
|
||||
* sen5x_read_device_status() - Reads the current device status.
|
||||
|
||||
* Use this command to get detailed information about the device status.
|
||||
* The device status is encoded in flags. Each device status flag
|
||||
* represents a single bit in a 32-bit integer value. If more than one
|
||||
* error is present, the device status register value is the sum of the
|
||||
* corresponding flag values. For details about the available flags,
|
||||
* refer to the device status flags documentation.
|
||||
*
|
||||
* @note The status flags of type \"Error\" are sticky, i.e. they are not
|
||||
* cleared automatically even if the error condition no longer exists. So they
|
||||
* can only be cleared manually with the command 0xD210 \"Read And Clear Device
|
||||
* Status\" or with a device reset. All other flags are not sticky, i.e. they
|
||||
* are cleared automatically if the trigger condition disappears.
|
||||
*
|
||||
* @param device_status Device status (32 flags as an integer value). For
|
||||
* details, please refer to the device status flags documentation.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_device_status(uint32_t* device_status);
|
||||
|
||||
/**
|
||||
* sen5x_read_and_clear_device_status() - Reads the current device status (like
|
||||
* command 0xD206 \"Read Device Status\") and afterwards clears all flags.
|
||||
*
|
||||
* @param device_status Device status (32 flags as an integer value) **before**
|
||||
* clearing it. For details, please refer to the device status flags
|
||||
* documentation.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_read_and_clear_device_status(uint32_t* device_status);
|
||||
|
||||
/**
|
||||
* sen5x_device_reset() - Executes a reset on the device. This has the same
|
||||
* effect as a power cycle.
|
||||
*
|
||||
* @return 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sen5x_device_reset(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SEN5X_I2C_H */
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
// File: src/sensirion_common.c
|
||||
#include "sensirion_common.h"
|
||||
#include "sensirion_config.h"
|
||||
|
||||
uint16_t sensirion_common_bytes_to_uint16_t(const uint8_t* bytes) {
|
||||
return (uint16_t)bytes[0] << 8 | (uint16_t)bytes[1];
|
||||
}
|
||||
|
||||
uint32_t sensirion_common_bytes_to_uint32_t(const uint8_t* bytes) {
|
||||
return (uint32_t)bytes[0] << 24 | (uint32_t)bytes[1] << 16 |
|
||||
(uint32_t)bytes[2] << 8 | (uint32_t)bytes[3];
|
||||
}
|
||||
|
||||
int16_t sensirion_common_bytes_to_int16_t(const uint8_t* bytes) {
|
||||
return (int16_t)sensirion_common_bytes_to_uint16_t(bytes);
|
||||
}
|
||||
|
||||
int32_t sensirion_common_bytes_to_int32_t(const uint8_t* bytes) {
|
||||
return (int32_t)sensirion_common_bytes_to_uint32_t(bytes);
|
||||
}
|
||||
|
||||
float sensirion_common_bytes_to_float(const uint8_t* bytes) {
|
||||
union {
|
||||
uint32_t u32_value;
|
||||
float float32;
|
||||
} tmp;
|
||||
|
||||
tmp.u32_value = sensirion_common_bytes_to_uint32_t(bytes);
|
||||
return tmp.float32;
|
||||
}
|
||||
|
||||
void sensirion_common_uint32_t_to_bytes(const uint32_t value, uint8_t* bytes) {
|
||||
bytes[0] = value >> 24;
|
||||
bytes[1] = value >> 16;
|
||||
bytes[2] = value >> 8;
|
||||
bytes[3] = value;
|
||||
}
|
||||
|
||||
void sensirion_common_uint16_t_to_bytes(const uint16_t value, uint8_t* bytes) {
|
||||
bytes[0] = value >> 8;
|
||||
bytes[1] = value;
|
||||
}
|
||||
|
||||
void sensirion_common_int32_t_to_bytes(const int32_t value, uint8_t* bytes) {
|
||||
bytes[0] = value >> 24;
|
||||
bytes[1] = value >> 16;
|
||||
bytes[2] = value >> 8;
|
||||
bytes[3] = value;
|
||||
}
|
||||
|
||||
void sensirion_common_int16_t_to_bytes(const int16_t value, uint8_t* bytes) {
|
||||
bytes[0] = value >> 8;
|
||||
bytes[1] = value;
|
||||
}
|
||||
|
||||
void sensirion_common_float_to_bytes(const float value, uint8_t* bytes) {
|
||||
union {
|
||||
uint32_t u32_value;
|
||||
float float32;
|
||||
} tmp;
|
||||
tmp.float32 = value;
|
||||
sensirion_common_uint32_t_to_bytes(tmp.u32_value, bytes);
|
||||
}
|
||||
|
||||
void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination,
|
||||
uint16_t data_length) {
|
||||
uint16_t i;
|
||||
for (i = 0; i < data_length; i++) {
|
||||
destination[i] = source[i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SENSIRION_COMMON_H
|
||||
#define SENSIRION_COMMON_H
|
||||
|
||||
#include "sensirion_config.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define NO_ERROR 0
|
||||
#define NOT_IMPLEMENTED_ERROR 31
|
||||
|
||||
#ifndef ARRAY_SIZE
|
||||
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
|
||||
#endif
|
||||
|
||||
#define SENSIRION_COMMAND_SIZE 2
|
||||
#define SENSIRION_WORD_SIZE 2
|
||||
#define SENSIRION_NUM_WORDS(x) (sizeof(x) / SENSIRION_WORD_SIZE)
|
||||
#define SENSIRION_MAX_BUFFER_WORDS 32
|
||||
|
||||
/**
|
||||
* sensirion_common_bytes_to_int16_t() - Convert an array of bytes to an int16_t
|
||||
*
|
||||
* Convert an array of bytes received from the sensor in big-endian/MSB-first
|
||||
* format to an int16_t value in the correct system-endianness.
|
||||
*
|
||||
* @param bytes An array of at least two bytes (MSB first)
|
||||
* @return The byte array represented as int16_t
|
||||
*/
|
||||
int16_t sensirion_common_bytes_to_int16_t(const uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_bytes_to_int32_t() - Convert an array of bytes to an int32_t
|
||||
*
|
||||
* Convert an array of bytes received from the sensor in big-endian/MSB-first
|
||||
* format to an int32_t value in the correct system-endianness.
|
||||
*
|
||||
* @param bytes An array of at least four bytes (MSB first)
|
||||
* @return The byte array represented as int32_t
|
||||
*/
|
||||
int32_t sensirion_common_bytes_to_int32_t(const uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_bytes_to_uint16_t() - Convert an array of bytes to an
|
||||
* uint16_t
|
||||
*
|
||||
* Convert an array of bytes received from the sensor in big-endian/MSB-first
|
||||
* format to an uint16_t value in the correct system-endianness.
|
||||
*
|
||||
* @param bytes An array of at least two bytes (MSB first)
|
||||
* @return The byte array represented as uint16_t
|
||||
*/
|
||||
uint16_t sensirion_common_bytes_to_uint16_t(const uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_bytes_to_uint32_t() - Convert an array of bytes to an
|
||||
* uint32_t
|
||||
*
|
||||
* Convert an array of bytes received from the sensor in big-endian/MSB-first
|
||||
* format to an uint32_t value in the correct system-endianness.
|
||||
*
|
||||
* @param bytes An array of at least four bytes (MSB first)
|
||||
* @return The byte array represented as uint32_t
|
||||
*/
|
||||
uint32_t sensirion_common_bytes_to_uint32_t(const uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_bytes_to_float() - Convert an array of bytes to a float
|
||||
*
|
||||
* Convert an array of bytes received from the sensor in big-endian/MSB-first
|
||||
* format to an float value in the correct system-endianness.
|
||||
*
|
||||
* @param bytes An array of at least four bytes (MSB first)
|
||||
* @return The byte array represented as float
|
||||
*/
|
||||
float sensirion_common_bytes_to_float(const uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_uint32_t_to_bytes() - Convert an uint32_t to an array of
|
||||
* bytes
|
||||
*
|
||||
* Convert an uint32_t value in system-endianness to big-endian/MBS-first
|
||||
* format to send to the sensor.
|
||||
*
|
||||
* @param value Value to convert
|
||||
* @param bytes An array of at least four bytes
|
||||
*/
|
||||
void sensirion_common_uint32_t_to_bytes(const uint32_t value, uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_uint16_t_to_bytes() - Convert an uint16_t to an array of
|
||||
* bytes
|
||||
*
|
||||
* Convert an uint16_t value in system-endianness to big-endian/MBS-first
|
||||
* format to send to the sensor.
|
||||
*
|
||||
* @param value Value to convert
|
||||
* @param bytes An array of at least two bytes
|
||||
*/
|
||||
void sensirion_common_uint16_t_to_bytes(const uint16_t value, uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_int32_t_to_bytes() - Convert an int32_t to an array of bytes
|
||||
*
|
||||
* Convert an int32_t value in system-endianness to big-endian/MBS-first
|
||||
* format to send to the sensor.
|
||||
*
|
||||
* @param value Value to convert
|
||||
* @param bytes An array of at least four bytes
|
||||
*/
|
||||
void sensirion_common_int32_t_to_bytes(const int32_t value, uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_int16_t_to_bytes() - Convert an int16_t to an array of bytes
|
||||
*
|
||||
* Convert an int16_t value in system-endianness to big-endian/MBS-first
|
||||
* format to send to the sensor.
|
||||
*
|
||||
* @param value Value to convert
|
||||
* @param bytes An array of at least two bytes
|
||||
*/
|
||||
void sensirion_common_int16_t_to_bytes(const int16_t value, uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_float_to_bytes() - Convert an float to an array of bytes
|
||||
*
|
||||
* Convert an float value in system-endianness to big-endian/MBS-first
|
||||
* format to send to the sensor.
|
||||
*
|
||||
* @param value Value to convert
|
||||
* @param bytes An array of at least four bytes
|
||||
*/
|
||||
void sensirion_common_float_to_bytes(const float value, uint8_t* bytes);
|
||||
|
||||
/**
|
||||
* sensirion_common_copy_bytes() - Copy bytes from one array to the other.
|
||||
*
|
||||
* @param source Array of bytes to be copied.
|
||||
* @param destination Array of bytes to be copied to.
|
||||
* @param data_length Number of bytes to copy.
|
||||
*/
|
||||
void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination,
|
||||
uint16_t data_length);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SENSIRION_COMMON_H */
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (c) 2019, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SENSIRION_CONFIG_H
|
||||
#define SENSIRION_CONFIG_H
|
||||
|
||||
/**
|
||||
* If your platform does not provide the library stdlib.h you have to remove the
|
||||
* include and define NULL yourself (see below).
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
|
||||
/**
|
||||
* #ifndef NULL
|
||||
* #define NULL ((void *)0)
|
||||
* #endif
|
||||
*/
|
||||
|
||||
/**
|
||||
* If your platform does not provide the library stdint.h you have to
|
||||
* define the integral types yourself (see below).
|
||||
*/
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* Typedef section for types commonly defined in <stdint.h>
|
||||
* If your system does not provide stdint headers, please define them
|
||||
* accordingly. Please make sure to define int64_t and uint64_t.
|
||||
*/
|
||||
/* typedef unsigned long long int uint64_t;
|
||||
* typedef long long int int64_t;
|
||||
* typedef long int32_t;
|
||||
* typedef unsigned long uint32_t;
|
||||
* typedef short int16_t;
|
||||
* typedef unsigned short uint16_t;
|
||||
* typedef char int8_t;
|
||||
* typedef unsigned char uint8_t;
|
||||
*/
|
||||
|
||||
#ifndef __cplusplus
|
||||
|
||||
/**
|
||||
* If your platform doesn't define the bool type we define it as int. Depending
|
||||
* on your system update the definition below.
|
||||
*/
|
||||
#if __STDC_VERSION__ >= 199901L
|
||||
#include <stdbool.h>
|
||||
#else
|
||||
|
||||
#ifndef bool
|
||||
#define bool int
|
||||
#define true 1
|
||||
#define false 0
|
||||
#endif /* bool */
|
||||
|
||||
#endif /* __STDC_VERSION__ */
|
||||
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* SENSIRION_CONFIG_H */
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
// File: src/sensirion_i2c.c
|
||||
#include "sensirion_i2c.h"
|
||||
#include "sensirion_common.h"
|
||||
#include "sensirion_config.h"
|
||||
#include "sensirion_i2c_hal.h"
|
||||
|
||||
uint8_t sensirion_i2c_generate_crc(const uint8_t* data, uint16_t count) {
|
||||
uint16_t current_byte;
|
||||
uint8_t crc = CRC8_INIT;
|
||||
uint8_t crc_bit;
|
||||
|
||||
/* calculates 8-Bit checksum with given polynomial */
|
||||
for (current_byte = 0; current_byte < count; ++current_byte) {
|
||||
crc ^= (data[current_byte]);
|
||||
for (crc_bit = 8; crc_bit > 0; --crc_bit) {
|
||||
if (crc & 0x80)
|
||||
crc = (crc << 1) ^ CRC8_POLYNOMIAL;
|
||||
else
|
||||
crc = (crc << 1);
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
int8_t sensirion_i2c_check_crc(const uint8_t* data, uint16_t count,
|
||||
uint8_t checksum) {
|
||||
if (sensirion_i2c_generate_crc(data, count) != checksum)
|
||||
return CRC_ERROR;
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_general_call_reset(void) {
|
||||
const uint8_t data = 0x06;
|
||||
return sensirion_i2c_hal_write(0, &data, (uint16_t)sizeof(data));
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_fill_cmd_send_buf(uint8_t* buf, uint16_t cmd,
|
||||
const uint16_t* args,
|
||||
uint8_t num_args) {
|
||||
uint8_t i;
|
||||
uint16_t idx = 0;
|
||||
|
||||
buf[idx++] = (uint8_t)((cmd & 0xFF00) >> 8);
|
||||
buf[idx++] = (uint8_t)((cmd & 0x00FF) >> 0);
|
||||
|
||||
for (i = 0; i < num_args; ++i) {
|
||||
buf[idx++] = (uint8_t)((args[i] & 0xFF00) >> 8);
|
||||
buf[idx++] = (uint8_t)((args[i] & 0x00FF) >> 0);
|
||||
|
||||
uint8_t crc = sensirion_i2c_generate_crc((uint8_t*)&buf[idx - 2],
|
||||
SENSIRION_WORD_SIZE);
|
||||
buf[idx++] = crc;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_read_words_as_bytes(uint8_t address, uint8_t* data,
|
||||
uint16_t num_words) {
|
||||
int16_t ret;
|
||||
uint16_t i, j;
|
||||
uint16_t size = num_words * (SENSIRION_WORD_SIZE + CRC8_LEN);
|
||||
uint16_t word_buf[SENSIRION_MAX_BUFFER_WORDS];
|
||||
uint8_t* const buf8 = (uint8_t*)word_buf;
|
||||
|
||||
ret = sensirion_i2c_hal_read(address, buf8, size);
|
||||
if (ret != NO_ERROR)
|
||||
return ret;
|
||||
|
||||
/* check the CRC for each word */
|
||||
for (i = 0, j = 0; i < size; i += SENSIRION_WORD_SIZE + CRC8_LEN) {
|
||||
|
||||
ret = sensirion_i2c_check_crc(&buf8[i], SENSIRION_WORD_SIZE,
|
||||
buf8[i + SENSIRION_WORD_SIZE]);
|
||||
if (ret != NO_ERROR)
|
||||
return ret;
|
||||
|
||||
data[j++] = buf8[i];
|
||||
data[j++] = buf8[i + 1];
|
||||
}
|
||||
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_read_words(uint8_t address, uint16_t* data_words,
|
||||
uint16_t num_words) {
|
||||
int16_t ret;
|
||||
uint8_t i;
|
||||
|
||||
ret = sensirion_i2c_read_words_as_bytes(address, (uint8_t*)data_words,
|
||||
num_words);
|
||||
if (ret != NO_ERROR)
|
||||
return ret;
|
||||
|
||||
for (i = 0; i < num_words; ++i) {
|
||||
const uint8_t* word_bytes = (uint8_t*)&data_words[i];
|
||||
data_words[i] = ((uint16_t)word_bytes[0] << 8) | word_bytes[1];
|
||||
}
|
||||
|
||||
return NO_ERROR;
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_write_cmd(uint8_t address, uint16_t command) {
|
||||
uint8_t buf[SENSIRION_COMMAND_SIZE];
|
||||
|
||||
sensirion_i2c_fill_cmd_send_buf(buf, command, NULL, 0);
|
||||
return sensirion_i2c_hal_write(address, buf, SENSIRION_COMMAND_SIZE);
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_write_cmd_with_args(uint8_t address, uint16_t command,
|
||||
const uint16_t* data_words,
|
||||
uint16_t num_words) {
|
||||
uint8_t buf[SENSIRION_MAX_BUFFER_WORDS];
|
||||
uint16_t buf_size;
|
||||
|
||||
buf_size =
|
||||
sensirion_i2c_fill_cmd_send_buf(buf, command, data_words, num_words);
|
||||
return sensirion_i2c_hal_write(address, buf, buf_size);
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_delayed_read_cmd(uint8_t address, uint16_t cmd,
|
||||
uint32_t delay_us, uint16_t* data_words,
|
||||
uint16_t num_words) {
|
||||
int16_t ret;
|
||||
uint8_t buf[SENSIRION_COMMAND_SIZE];
|
||||
|
||||
sensirion_i2c_fill_cmd_send_buf(buf, cmd, NULL, 0);
|
||||
ret = sensirion_i2c_hal_write(address, buf, SENSIRION_COMMAND_SIZE);
|
||||
if (ret != NO_ERROR)
|
||||
return ret;
|
||||
|
||||
if (delay_us)
|
||||
sensirion_i2c_hal_sleep_usec(delay_us);
|
||||
|
||||
return sensirion_i2c_read_words(address, data_words, num_words);
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_read_cmd(uint8_t address, uint16_t cmd,
|
||||
uint16_t* data_words, uint16_t num_words) {
|
||||
return sensirion_i2c_delayed_read_cmd(address, cmd, 0, data_words,
|
||||
num_words);
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_command_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint16_t command) {
|
||||
buffer[offset++] = (uint8_t)((command & 0xFF00) >> 8);
|
||||
buffer[offset++] = (uint8_t)((command & 0x00FF) >> 0);
|
||||
return offset;
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_uint32_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint32_t data) {
|
||||
buffer[offset++] = (uint8_t)((data & 0xFF000000) >> 24);
|
||||
buffer[offset++] = (uint8_t)((data & 0x00FF0000) >> 16);
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
buffer[offset++] = (uint8_t)((data & 0x0000FF00) >> 8);
|
||||
buffer[offset++] = (uint8_t)((data & 0x000000FF) >> 0);
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_int32_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
int32_t data) {
|
||||
return sensirion_i2c_add_uint32_t_to_buffer(buffer, offset, (uint32_t)data);
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_uint16_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint16_t data) {
|
||||
buffer[offset++] = (uint8_t)((data & 0xFF00) >> 8);
|
||||
buffer[offset++] = (uint8_t)((data & 0x00FF) >> 0);
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_int16_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
int16_t data) {
|
||||
return sensirion_i2c_add_uint16_t_to_buffer(buffer, offset, (uint16_t)data);
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_float_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
float data) {
|
||||
union {
|
||||
uint32_t uint32_data;
|
||||
float float_data;
|
||||
} convert;
|
||||
|
||||
convert.float_data = data;
|
||||
|
||||
buffer[offset++] = (uint8_t)((convert.uint32_data & 0xFF000000) >> 24);
|
||||
buffer[offset++] = (uint8_t)((convert.uint32_data & 0x00FF0000) >> 16);
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
buffer[offset++] = (uint8_t)((convert.uint32_data & 0x0000FF00) >> 8);
|
||||
buffer[offset++] = (uint8_t)((convert.uint32_data & 0x000000FF) >> 0);
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
uint16_t sensirion_i2c_add_bytes_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
const uint8_t* data,
|
||||
uint16_t data_length) {
|
||||
uint16_t i;
|
||||
|
||||
if (data_length % SENSIRION_WORD_SIZE != 0) {
|
||||
return BYTE_NUM_ERROR;
|
||||
}
|
||||
|
||||
for (i = 0; i < data_length; i += 2) {
|
||||
buffer[offset++] = data[i];
|
||||
buffer[offset++] = data[i + 1];
|
||||
|
||||
buffer[offset] = sensirion_i2c_generate_crc(
|
||||
&buffer[offset - SENSIRION_WORD_SIZE], SENSIRION_WORD_SIZE);
|
||||
offset++;
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_write_data(uint8_t address, const uint8_t* data,
|
||||
uint16_t data_length) {
|
||||
return sensirion_i2c_hal_write(address, data, data_length);
|
||||
}
|
||||
|
||||
int16_t sensirion_i2c_read_data_inplace(uint8_t address, uint8_t* buffer,
|
||||
uint16_t expected_data_length) {
|
||||
int16_t error;
|
||||
uint16_t i, j;
|
||||
uint16_t size = (expected_data_length / SENSIRION_WORD_SIZE) *
|
||||
(SENSIRION_WORD_SIZE + CRC8_LEN);
|
||||
|
||||
if (expected_data_length % SENSIRION_WORD_SIZE != 0) {
|
||||
return BYTE_NUM_ERROR;
|
||||
}
|
||||
|
||||
error = sensirion_i2c_hal_read(address, buffer, size);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
for (i = 0, j = 0; i < size; i += SENSIRION_WORD_SIZE + CRC8_LEN) {
|
||||
|
||||
error = sensirion_i2c_check_crc(&buffer[i], SENSIRION_WORD_SIZE,
|
||||
buffer[i + SENSIRION_WORD_SIZE]);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
buffer[j++] = buffer[i];
|
||||
buffer[j++] = buffer[i + 1];
|
||||
}
|
||||
|
||||
return NO_ERROR;
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SENSIRION_I2C_H
|
||||
#define SENSIRION_I2C_H
|
||||
|
||||
#include "sensirion_config.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define CRC_ERROR 1
|
||||
#define I2C_BUS_ERROR 2
|
||||
#define I2C_NACK_ERROR 3
|
||||
#define BYTE_NUM_ERROR 4
|
||||
|
||||
#define CRC8_POLYNOMIAL 0x31
|
||||
#define CRC8_INIT 0xFF
|
||||
#define CRC8_LEN 1
|
||||
|
||||
#define SENSIRION_COMMAND_SIZE 2
|
||||
#define SENSIRION_WORD_SIZE 2
|
||||
#define SENSIRION_NUM_WORDS(x) (sizeof(x) / SENSIRION_WORD_SIZE)
|
||||
#define SENSIRION_MAX_BUFFER_WORDS 32
|
||||
|
||||
uint8_t sensirion_i2c_generate_crc(const uint8_t* data, uint16_t count);
|
||||
|
||||
int8_t sensirion_i2c_check_crc(const uint8_t* data, uint16_t count,
|
||||
uint8_t checksum);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_general_call_reset() - Send a general call reset.
|
||||
*
|
||||
* @warning This will reset all attached I2C devices on the bus which support
|
||||
* general call reset.
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_general_call_reset(void);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_fill_cmd_send_buf() - create the i2c send buffer for a command
|
||||
* and a set of argument words. The output buffer interleaves argument words
|
||||
* with their checksums.
|
||||
* @buf: The generated buffer to send over i2c. Then buffer length must
|
||||
* be at least SENSIRION_COMMAND_LEN + num_args *
|
||||
* (SENSIRION_WORD_SIZE + CRC8_LEN).
|
||||
* @cmd: The i2c command to send. It already includes a checksum.
|
||||
* @args: The arguments to the command. Can be NULL if none.
|
||||
* @num_args: The number of word arguments in args.
|
||||
*
|
||||
* @return The number of bytes written to buf
|
||||
*/
|
||||
uint16_t sensirion_i2c_fill_cmd_send_buf(uint8_t* buf, uint16_t cmd,
|
||||
const uint16_t* args,
|
||||
uint8_t num_args);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_read_words() - read data words from sensor
|
||||
*
|
||||
* @address: Sensor i2c address
|
||||
* @data_words: Allocated buffer to store the read words.
|
||||
* The buffer may also have been modified in case of an error.
|
||||
* @num_words: Number of data words to read (without CRC bytes)
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_read_words(uint8_t address, uint16_t* data_words,
|
||||
uint16_t num_words);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_read_words_as_bytes() - read data words as byte-stream from
|
||||
* sensor
|
||||
*
|
||||
* Read bytes without adjusting values to the uP's word-order.
|
||||
*
|
||||
* @address: Sensor i2c address
|
||||
* @data: Allocated buffer to store the read bytes.
|
||||
* The buffer may also have been modified in case of an error.
|
||||
* @num_words: Number of data words(!) to read (without CRC bytes)
|
||||
* Since only word-chunks can be read from the sensor the size
|
||||
* is still specified in sensor-words (num_words = num_bytes *
|
||||
* SENSIRION_WORD_SIZE)
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_read_words_as_bytes(uint8_t address, uint8_t* data,
|
||||
uint16_t num_words);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_write_cmd() - writes a command to the sensor
|
||||
* @address: Sensor i2c address
|
||||
* @command: Sensor command
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_write_cmd(uint8_t address, uint16_t command);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_write_cmd_with_args() - writes a command with arguments to the
|
||||
* sensor
|
||||
* @address: Sensor i2c address
|
||||
* @command: Sensor command
|
||||
* @data: Argument buffer with words to send
|
||||
* @num_words: Number of data words to send (without CRC bytes)
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_write_cmd_with_args(uint8_t address, uint16_t command,
|
||||
const uint16_t* data_words,
|
||||
uint16_t num_words);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_delayed_read_cmd() - send a command, wait for the sensor to
|
||||
* process and read data back
|
||||
* @address: Sensor i2c address
|
||||
* @cmd: Command
|
||||
* @delay: Time in microseconds to delay sending the read request
|
||||
* @data_words: Allocated buffer to store the read data
|
||||
* @num_words: Data words to read (without CRC bytes)
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_delayed_read_cmd(uint8_t address, uint16_t cmd,
|
||||
uint32_t delay_us, uint16_t* data_words,
|
||||
uint16_t num_words);
|
||||
/**
|
||||
* sensirion_i2c_read_cmd() - reads data words from the sensor after a command
|
||||
* is issued
|
||||
* @address: Sensor i2c address
|
||||
* @cmd: Command
|
||||
* @data_words: Allocated buffer to store the read data
|
||||
* @num_words: Data words to read (without CRC bytes)
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_read_cmd(uint8_t address, uint16_t cmd,
|
||||
uint16_t* data_words, uint16_t num_words);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_command_to_buffer() - Add a command to the buffer at
|
||||
* offset. Adds 2 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param command Command to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_command_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint16_t command);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_uint32_t_to_buffer() - Add a uint32_t to the buffer at
|
||||
* offset. Adds 6 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data uint32_t to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_uint32_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint32_t data);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_int32_t_to_buffer() - Add a int32_t to the buffer at
|
||||
* offset. Adds 6 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data int32_t to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_int32_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
int32_t data);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_uint16_t_to_buffer() - Add a uint16_t to the buffer at
|
||||
* offset. Adds 3 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data uint16_t to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_uint16_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
uint16_t data);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_int16_t_to_buffer() - Add a int16_t to the buffer at
|
||||
* offset. Adds 3 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data int16_t to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_int16_t_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
int16_t data);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_float_to_buffer() - Add a float to the buffer at offset.
|
||||
* Adds 6 bytes to the buffer.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be prepared.
|
||||
* Caller needs to make sure that there is enough space after
|
||||
* offset left to write the data into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data float to be written into the buffer.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_float_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
float data);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_add_bytes_to_buffer() - Add a byte array to the buffer at
|
||||
* offset.
|
||||
*
|
||||
* @param buffer Pointer to buffer in which the write frame will be
|
||||
* prepared. Caller needs to make sure that there is
|
||||
* enough space after offset left to write the data
|
||||
* into the buffer.
|
||||
* @param offset Offset of the next free byte in the buffer.
|
||||
* @param data Pointer to data to be written into the buffer.
|
||||
* @param data_length Number of bytes to be written into the buffer. Needs to
|
||||
* be a multiple of SENSIRION_WORD_SIZE otherwise the
|
||||
* function returns BYTE_NUM_ERROR.
|
||||
*
|
||||
* @return Offset of next free byte in the buffer after writing the
|
||||
* data.
|
||||
*/
|
||||
uint16_t sensirion_i2c_add_bytes_to_buffer(uint8_t* buffer, uint16_t offset,
|
||||
const uint8_t* data,
|
||||
uint16_t data_length);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_write_data() - Writes data to the Sensor.
|
||||
*
|
||||
* @note This is just a wrapper for sensirion_i2c_hal_write() to
|
||||
* not need to include the HAL in the drivers.
|
||||
*
|
||||
* @param address I2C address to write to.
|
||||
* @param data Pointer to the buffer containing the data to write.
|
||||
* @param data_length Number of bytes to send to the Sensor.
|
||||
*
|
||||
* @return NO_ERROR on success, error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_write_data(uint8_t address, const uint8_t* data,
|
||||
uint16_t data_length);
|
||||
|
||||
/**
|
||||
* sensirion_i2c_read_data_inplace() - Reads data from the Sensor.
|
||||
*
|
||||
* @param address Sensor I2C address
|
||||
* @param buffer Allocated buffer to store data as bytes. Needs
|
||||
* to be big enough to store the data including
|
||||
* CRC. Twice the size of data should always
|
||||
* suffice.
|
||||
* @param expected_data_length Number of bytes to read (without CRC). Needs
|
||||
* to be a multiple of SENSIRION_WORD_SIZE,
|
||||
* otherwise the function returns BYTE_NUM_ERROR.
|
||||
*
|
||||
* @return NO_ERROR on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_read_data_inplace(uint8_t address, uint8_t* buffer,
|
||||
uint16_t expected_data_length);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SENSIRION_I2C_H */
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2023, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SENSIRION_I2C_ESP32_CONFIG_H
|
||||
#define SENSIRION_I2C_ESP32_CONFIG_H
|
||||
|
||||
#include <i2cdev.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef int esp_err_t;
|
||||
|
||||
struct esp32_i2c_config {
|
||||
uint32_t freq;
|
||||
uint8_t addr;
|
||||
i2c_port_t port;
|
||||
gpio_num_t sda;
|
||||
gpio_num_t scl;
|
||||
bool sda_pullup;
|
||||
bool scl_pullup;
|
||||
};
|
||||
|
||||
extern esp_err_t sensirion_i2c_config_esp32(struct esp32_i2c_config* cfg);
|
||||
extern esp_err_t sensirion_i2c_esp32_ok(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SENSIRION_I2C_ESP32_CONFIG_H */
|
||||
@@ -0,0 +1,159 @@
|
||||
// File: sensirion_i2c_hal.c
|
||||
#include "sensirion_i2c_hal.h"
|
||||
#include "sensirion_common.h"
|
||||
#include "sensirion_config.h"
|
||||
|
||||
#include <esp_log.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h> // für PRIu32
|
||||
|
||||
#include "sensirion_i2c_esp32_config.h"
|
||||
|
||||
static const char* TAG = "sensirion_i2c_hal";
|
||||
|
||||
#define SLEEP_MS(x) \
|
||||
vTaskDelay(((x) + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS)
|
||||
|
||||
// Lokaler I2C-Gerätekontext aus i2cdev
|
||||
static i2c_dev_t dev = {0};
|
||||
static struct esp32_i2c_config i2c_cfg = {0};
|
||||
static esp_err_t i2c_ok = ESP_OK;
|
||||
|
||||
int16_t sensirion_i2c_hal_select_bus(uint8_t bus_idx) {
|
||||
// Multi-Bus-Support: Port umschalten (optional, für Single-Bus reicht das so)
|
||||
dev.port = bus_idx;
|
||||
i2c_cfg.port = bus_idx;
|
||||
ESP_LOGI(TAG, "Selected I2C bus index/port: %u", (unsigned)bus_idx);
|
||||
return NO_ERROR; // 0
|
||||
}
|
||||
|
||||
esp_err_t sensirion_i2c_config_esp32(struct esp32_i2c_config* cfg) {
|
||||
if (cfg != NULL) {
|
||||
memcpy(&i2c_cfg, cfg, sizeof(*cfg));
|
||||
return ESP_OK;
|
||||
} else {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t sensirion_i2c_esp32_ok(void) {
|
||||
return i2c_ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all hard- and software components that are needed for the I2C
|
||||
* communication.
|
||||
*/
|
||||
void sensirion_i2c_hal_init(void) {
|
||||
memset(&dev, 0, sizeof(i2c_dev_t));
|
||||
|
||||
// Port & Pins/Frequenz aus der App-Konfiguration übernehmen
|
||||
dev.port = i2c_cfg.port;
|
||||
dev.cfg.sda_io_num = i2c_cfg.sda;
|
||||
dev.cfg.scl_io_num = i2c_cfg.scl;
|
||||
dev.cfg.sda_pullup_en = i2c_cfg.sda_pullup;
|
||||
dev.cfg.scl_pullup_en = i2c_cfg.scl_pullup;
|
||||
#if HELPER_TARGET_IS_ESP32
|
||||
dev.cfg.master.clk_speed = i2c_cfg.freq; // Gerätespezifische Busgeschwindigkeit
|
||||
#endif
|
||||
|
||||
// Mutex anlegen & Gerät registrieren (i2cdev kümmert sich um Bus-Setup on-demand)
|
||||
esp_err_t err = i2c_dev_create_mutex(&dev);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG,
|
||||
"Sensirion I2C HAL ready. Addr: 0x%02x Port: %d SDA: %d SCL: %d Freq: %" PRIu32 "Hz",
|
||||
i2c_cfg.addr, i2c_cfg.port, i2c_cfg.sda, i2c_cfg.scl,
|
||||
(uint32_t)i2c_cfg.freq);
|
||||
} else {
|
||||
ESP_LOGE(TAG,
|
||||
"Sensirion I2C HAL init error! Addr: 0x%02x Port: %d SDA: %d SCL: %d (err=%s)",
|
||||
i2c_cfg.addr, i2c_cfg.port, i2c_cfg.sda, i2c_cfg.scl,
|
||||
esp_err_to_name(err));
|
||||
}
|
||||
|
||||
i2c_ok = err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release all resources initialized by sensirion_i2c_hal_init().
|
||||
*/
|
||||
void sensirion_i2c_hal_free(void) {
|
||||
// Gibt Mutex frei, deregistriert Device & entfernt ggf. Bus-Handle wenn letztes Gerät (siehe i2cdev.c)
|
||||
esp_err_t err = i2c_dev_delete_mutex(&dev);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "i2c_dev_delete_mutex failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute one read transaction on the I2C bus, reading a given number of bytes.
|
||||
* If the device does not acknowledge the read command, an error shall be
|
||||
* returned.
|
||||
*
|
||||
* @param address 7-bit I2C address to read from
|
||||
* @param data pointer to the buffer where the data is to be stored
|
||||
* @param count number of bytes to read from I2C and store in the buffer
|
||||
* @returns 0 on success, error code otherwise
|
||||
*/
|
||||
int8_t sensirion_i2c_hal_read(uint8_t address, uint8_t* data, uint16_t count) {
|
||||
ESP_LOGD(TAG, "sensirion_i2c_hal_read: addr=0x%02x len=%u", address, (unsigned)count);
|
||||
dev.addr = address;
|
||||
|
||||
I2C_DEV_TAKE_MUTEX(&dev);
|
||||
esp_err_t err = i2c_dev_read(&dev, NULL, 0, data, count);
|
||||
I2C_DEV_GIVE_MUTEX(&dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "READ failed (addr=0x%02x, len=%u): %s", address, (unsigned)count, esp_err_to_name(err));
|
||||
return (int8_t)err; // non-zero -> Fehler
|
||||
}
|
||||
// ESP_LOGV(TAG, "READ OK");
|
||||
return (int8_t)NO_ERROR; // 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute one write transaction on the I2C bus, sending a given number of
|
||||
* bytes.
|
||||
*
|
||||
* @param address 7-bit I2C address to write to
|
||||
* @param data pointer to the buffer containing the data to write
|
||||
* @param count number of bytes to send over I2C
|
||||
* @returns 0 on success, error code otherwise
|
||||
*/
|
||||
int8_t sensirion_i2c_hal_write(uint8_t address, const uint8_t* data,
|
||||
uint16_t count) {
|
||||
ESP_LOGD(TAG, "sensirion_i2c_hal_write: addr=0x%02x len=%u", address, (unsigned)count);
|
||||
dev.addr = address;
|
||||
|
||||
I2C_DEV_TAKE_MUTEX(&dev);
|
||||
esp_err_t err = i2c_dev_write(&dev, NULL, 0, data, count);
|
||||
I2C_DEV_GIVE_MUTEX(&dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "WRITE failed (addr=0x%02x, len=%u): %s", address, (unsigned)count, esp_err_to_name(err));
|
||||
return (int8_t)err; // non-zero -> Fehler
|
||||
}
|
||||
// ESP_LOGV(TAG, "WRITE OK");
|
||||
return (int8_t)NO_ERROR; // 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep for a given number of microseconds. The function should delay the
|
||||
* execution for at least the given time, but may also sleep longer.
|
||||
*
|
||||
* Despite the unit, a <10 millisecond precision is sufficient.
|
||||
*
|
||||
* @param useconds the sleep time in microseconds
|
||||
*/
|
||||
void sensirion_i2c_hal_sleep_usec(uint32_t useconds) {
|
||||
ESP_LOGV(TAG, "sensirion_i2c_hal_sleep: %" PRIu32 " usec", useconds);
|
||||
// Tick-basiert schlafen (µs->ms), Genauigkeit im Bereich <10 ms ist ausreichend
|
||||
uint32_t ms = useconds / 1000U;
|
||||
if (ms == 0 && useconds > 0) {
|
||||
// Mindestens 1 Tick warten, wenn >0µs angefordert, um aktives Busy-Wait zu vermeiden
|
||||
ms = 1;
|
||||
}
|
||||
SLEEP_MS(ms);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Sensirion AG
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of Sensirion AG nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef SENSIRION_I2C_HAL_H
|
||||
#define SENSIRION_I2C_HAL_H
|
||||
|
||||
#include "sensirion_config.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
/**
|
||||
* Select the current i2c bus by index.
|
||||
* All following i2c operations will be directed at that bus.
|
||||
*
|
||||
* THE IMPLEMENTATION IS OPTIONAL ON SINGLE-BUS SETUPS (all sensors on the same
|
||||
* bus)
|
||||
*
|
||||
* @param bus_idx Bus index to select
|
||||
* @returns 0 on success, an error code otherwise
|
||||
*/
|
||||
int16_t sensirion_i2c_hal_select_bus(uint8_t bus_idx);
|
||||
|
||||
/**
|
||||
* Initialize all hard- and software components that are needed for the I2C
|
||||
* communication.
|
||||
*/
|
||||
void sensirion_i2c_hal_init(void);
|
||||
|
||||
/**
|
||||
* Release all resources initialized by sensirion_i2c_hal_init().
|
||||
*/
|
||||
void sensirion_i2c_hal_free(void);
|
||||
|
||||
/**
|
||||
* Execute one read transaction on the I2C bus, reading a given number of bytes.
|
||||
* If the device does not acknowledge the read command, an error shall be
|
||||
* returned.
|
||||
*
|
||||
* @param address 7-bit I2C address to read from
|
||||
* @param data pointer to the buffer where the data is to be stored
|
||||
* @param count number of bytes to read from I2C and store in the buffer
|
||||
* @returns 0 on success, error code otherwise
|
||||
*/
|
||||
int8_t sensirion_i2c_hal_read(uint8_t address, uint8_t* data, uint16_t count);
|
||||
|
||||
/**
|
||||
* Execute one write transaction on the I2C bus, sending a given number of
|
||||
* bytes. The bytes in the supplied buffer must be sent to the given address. If
|
||||
* the slave device does not acknowledge any of the bytes, an error shall be
|
||||
* returned.
|
||||
*
|
||||
* @param address 7-bit I2C address to write to
|
||||
* @param data pointer to the buffer containing the data to write
|
||||
* @param count number of bytes to read from the buffer and send over I2C
|
||||
* @returns 0 on success, error code otherwise
|
||||
*/
|
||||
int8_t sensirion_i2c_hal_write(uint8_t address, const uint8_t* data,
|
||||
uint16_t count);
|
||||
|
||||
/**
|
||||
* Sleep for a given number of microseconds. The function should delay the
|
||||
* execution approximately, but no less than, the given time.
|
||||
*
|
||||
* When using hardware i2c:
|
||||
* Despite the unit, a <10 millisecond precision is sufficient.
|
||||
*
|
||||
* When using software i2c:
|
||||
* The precision needed depends on the desired i2c frequency, i.e. should be
|
||||
* exact to about half a clock cycle (defined in
|
||||
* `SENSIRION_I2C_CLOCK_PERIOD_USEC` in `sensirion_sw_i2c_gpio.h`).
|
||||
*
|
||||
* Example with 400kHz requires a precision of 1 / (2 * 400kHz) == 1.25usec.
|
||||
*
|
||||
* @param useconds the sleep time in microseconds
|
||||
*/
|
||||
void sensirion_i2c_hal_sleep_usec(uint32_t useconds);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* SENSIRION_I2C_HAL_H */
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
// File: src/storage.c
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "nvs.h"
|
||||
|
||||
#include "storage.h"
|
||||
|
||||
#include "esp_system.h"
|
||||
|
||||
static const char *TAG = "storage";
|
||||
|
||||
// Namespace & Keys (intern)
|
||||
#define NVS_NAMESPACE "wifi"
|
||||
#define NVS_KEY_SSID "sta_ssid"
|
||||
#define NVS_KEY_PASS "sta_pass"
|
||||
#define NVS_KEY_DEVNAME "dev_name"
|
||||
#define NVS_KEY_INFLUX_TOKEN "influx_token"
|
||||
#define NVS_KEY_BUCKET "influx_bucket"
|
||||
#define NVS_KEY_ORG "org_id"
|
||||
#define NVS_KEY_SERVICE_URL "service_url"
|
||||
|
||||
// Werkseinstellungen
|
||||
#define DEFAULT_ORG_ID "myorg"
|
||||
#define DEFAULT_BUCKET "nanoPSX"
|
||||
#define DEFAULT_INFLUX_TOKEN "0946c41441a85088b38d39da6ed06d75a"
|
||||
#define DEFAULT_DEVNAME "Sensor"
|
||||
|
||||
static char* get_nvs_str(nvs_handle_t h, const char *key);
|
||||
|
||||
|
||||
bool storage_load_device_name(char **out_devname) {
|
||||
if (!out_devname) return false;
|
||||
*out_devname = NULL;
|
||||
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) != ESP_OK) return false;
|
||||
|
||||
char *name = get_nvs_str(h, NVS_KEY_DEVNAME);
|
||||
nvs_close(h);
|
||||
if (!name) return false;
|
||||
|
||||
*out_devname = name;
|
||||
return true;
|
||||
}
|
||||
|
||||
esp_err_t storage_save_service_url(const char *url) {
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
// Semantik wie bei anderen Feldern: "" => löschen
|
||||
if (url && url[0] != '\0') {
|
||||
err = nvs_set_str(h, NVS_KEY_SERVICE_URL, url);
|
||||
} else {
|
||||
esp_err_t e = nvs_erase_key(h, NVS_KEY_SERVICE_URL);
|
||||
err = (e == ESP_ERR_NVS_NOT_FOUND) ? ESP_OK : e;
|
||||
}
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Service-URL %s", (url && url[0]) ? "gespeichert" : "gelöscht");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Speichern Service-URL fehlgeschlagen: %s", esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
bool storage_load_service_url(char **out_url) {
|
||||
if (!out_url) return false;
|
||||
*out_url = NULL;
|
||||
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) != ESP_OK) return false;
|
||||
|
||||
char *url = get_nvs_str(h, NVS_KEY_SERVICE_URL);
|
||||
nvs_close(h);
|
||||
if (!url) return false;
|
||||
*out_url = url;
|
||||
return true;
|
||||
}
|
||||
|
||||
void storage_erase_service_url(void) {
|
||||
(void)storage_save_service_url("");
|
||||
}
|
||||
|
||||
// ---------- NVS Init ----------
|
||||
esp_err_t storage_init(void) {
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "NVS init OK");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "NVS init failed: %s", esp_err_to_name(ret));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// ---------- interne Helfer ----------
|
||||
static esp_err_t nvs_set_str_or_erase(nvs_handle_t h, const char *key, const char *val) {
|
||||
if (val && val[0] != '\0') {
|
||||
return nvs_set_str(h, key, val);
|
||||
} else {
|
||||
esp_err_t e = nvs_erase_key(h, key);
|
||||
return (e == ESP_ERR_NVS_NOT_FOUND) ? ESP_OK : e;
|
||||
}
|
||||
}
|
||||
|
||||
static char* get_nvs_str(nvs_handle_t h, const char *key) {
|
||||
size_t need = 0;
|
||||
if (nvs_get_str(h, key, NULL, &need) != ESP_OK || need == 0) return NULL;
|
||||
char *buf = (char*)malloc(need);
|
||||
if (!buf) return NULL;
|
||||
if (nvs_get_str(h, key, buf, &need) != ESP_OK) {
|
||||
free(buf);
|
||||
return NULL;
|
||||
}
|
||||
return buf; // inkl. Nullterminator
|
||||
}
|
||||
|
||||
static esp_err_t set_keep_or_erase(nvs_handle_t h, const char *key, const char *val) {
|
||||
if (val == NULL) return ESP_OK; // nicht geändert
|
||||
if (val[0] == '\0') { // explizit löschen -> fällt auf Default zurück
|
||||
esp_err_t e = nvs_erase_key(h, key);
|
||||
return (e == ESP_ERR_NVS_NOT_FOUND) ? ESP_OK : e;
|
||||
}
|
||||
return nvs_set_str(h, key, val); // neuen Wert setzen
|
||||
}
|
||||
|
||||
// ---------- WLAN-Creds ----------
|
||||
bool storage_load_wifi_creds(char **out_ssid, char **out_pass) {
|
||||
if (!out_ssid || !out_pass) return false;
|
||||
*out_ssid = *out_pass = NULL;
|
||||
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) != ESP_OK) return false;
|
||||
|
||||
size_t need = 0;
|
||||
|
||||
// SSID
|
||||
if (nvs_get_str(h, NVS_KEY_SSID, NULL, &need) != ESP_OK || need == 0) {
|
||||
nvs_close(h);
|
||||
return false;
|
||||
}
|
||||
char *ssid = (char*)malloc(need);
|
||||
if (!ssid) { nvs_close(h); return false; }
|
||||
if (nvs_get_str(h, NVS_KEY_SSID, ssid, &need) != ESP_OK) {
|
||||
free(ssid); nvs_close(h); return false;
|
||||
}
|
||||
|
||||
// PASS
|
||||
need = 0;
|
||||
if (nvs_get_str(h, NVS_KEY_PASS, NULL, &need) != ESP_OK || need == 0) {
|
||||
free(ssid); nvs_close(h); return false;
|
||||
}
|
||||
char *pass = (char*)malloc(need);
|
||||
if (!pass) { free(ssid); nvs_close(h); return false; }
|
||||
if (nvs_get_str(h, NVS_KEY_PASS, pass, &need) != ESP_OK) {
|
||||
free(ssid); free(pass); nvs_close(h); return false;
|
||||
}
|
||||
|
||||
nvs_close(h);
|
||||
*out_ssid = ssid;
|
||||
*out_pass = pass;
|
||||
return true;
|
||||
}
|
||||
|
||||
esp_err_t storage_save_wifi_creds(const char *ssid, const char *pass) {
|
||||
if (!ssid || !pass) return ESP_ERR_INVALID_ARG;
|
||||
|
||||
// idempotent schreiben
|
||||
char *cur_s = NULL, *cur_p = NULL;
|
||||
bool have = storage_load_wifi_creds(&cur_s, &cur_p);
|
||||
bool same = have && strcmp(cur_s, ssid) == 0 && strcmp(cur_p, pass) == 0;
|
||||
if (cur_s) free(cur_s);
|
||||
if (cur_p) free(cur_p);
|
||||
|
||||
if (same) {
|
||||
ESP_LOGI(TAG, "Creds identisch, kein erneutes Speichern.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str(h, NVS_KEY_SSID, ssid));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str(h, NVS_KEY_PASS, pass));
|
||||
|
||||
err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Creds gespeichert: SSID='%s' (Passwort %zu Zeichen)", ssid, strlen(pass));
|
||||
} else {
|
||||
ESP_LOGE(TAG, "nvs_commit failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
// ---------- Device/Influx-Infos (generisch speichern) ----------
|
||||
esp_err_t storage_save_device_info(const char *devicename,
|
||||
const char *token,
|
||||
const char *bucket,
|
||||
const char *org) {
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str_or_erase(h, NVS_KEY_DEVNAME, devicename));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str_or_erase(h, NVS_KEY_INFLUX_TOKEN, token));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str_or_erase(h, NVS_KEY_BUCKET, bucket));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_set_str_or_erase(h, NVS_KEY_ORG, org));
|
||||
|
||||
err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Deviceinfo gespeichert: name='%s', token_len=%d",
|
||||
devicename ? devicename : "",
|
||||
token ? (int)strlen(token) : 0);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "nvs_commit failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
// ---------- Werkseinstellung + effektive Influx-Konfig ----------
|
||||
bool storage_get_effective_influx(char **out_org, char **out_bucket, char **out_token) {
|
||||
if (!out_org || !out_bucket || !out_token) return false;
|
||||
*out_org = *out_bucket = *out_token = NULL;
|
||||
|
||||
nvs_handle_t h;
|
||||
bool have_nvs = (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) == ESP_OK);
|
||||
|
||||
char *org = NULL, *bucket = NULL, *token = NULL;
|
||||
if (have_nvs) {
|
||||
org = get_nvs_str(h, NVS_KEY_ORG);
|
||||
bucket = get_nvs_str(h, NVS_KEY_BUCKET);
|
||||
token = get_nvs_str(h, NVS_KEY_INFLUX_TOKEN);
|
||||
nvs_close(h);
|
||||
}
|
||||
|
||||
if (!org) org = strdup(DEFAULT_ORG_ID);
|
||||
if (!bucket) bucket = strdup(DEFAULT_BUCKET);
|
||||
if (!token) token = strdup(DEFAULT_INFLUX_TOKEN);
|
||||
|
||||
if (!org || !bucket || !token) {
|
||||
free(org); free(bucket); free(token);
|
||||
return false;
|
||||
}
|
||||
|
||||
*out_org = org; *out_bucket = bucket; *out_token = token;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Speichert nur, wenn sich mind. ein übergebenes Feld ändert
|
||||
// NULL = Feld nicht angefasst (behalten)
|
||||
// "" = löschen (fällt auf Werkseinstellung zurück)
|
||||
esp_err_t storage_save_influx_softap(const char *org, const char *bucket, const char *token) {
|
||||
char *cur_org = NULL, *cur_bucket = NULL, *cur_token = NULL;
|
||||
if (!storage_get_effective_influx(&cur_org, &cur_bucket, &cur_token)) {
|
||||
ESP_LOGE(TAG, "cannot get effective influx config");
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
// Wenn nichts übergeben wurde, ist nichts zu tun
|
||||
if (!org && !bucket && !token) {
|
||||
free(cur_org); free(cur_bucket); free(cur_token);
|
||||
ESP_LOGI(TAG, "SoftAP: keine geänderten Felder.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
bool changed = false;
|
||||
if (org != NULL && strcmp(org, cur_org) != 0) changed = true;
|
||||
if (bucket != NULL && strcmp(bucket, cur_bucket) != 0) changed = true;
|
||||
if (token != NULL && strcmp(token, cur_token) != 0) changed = true;
|
||||
|
||||
free(cur_org); free(cur_bucket); free(cur_token);
|
||||
|
||||
if (!changed) {
|
||||
ESP_LOGI(TAG, "SoftAP: keine Änderungen – nichts zu speichern.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(set_keep_or_erase(h, NVS_KEY_ORG, org));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(set_keep_or_erase(h, NVS_KEY_BUCKET, bucket));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(set_keep_or_erase(h, NVS_KEY_INFLUX_TOKEN, token));
|
||||
|
||||
err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "SoftAP: Influx-Konfig gespeichert.");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "nvs_commit failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
void storage_factory_reset_influx(void) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h) != ESP_OK) return;
|
||||
nvs_erase_key(h, NVS_KEY_ORG);
|
||||
nvs_erase_key(h, NVS_KEY_BUCKET);
|
||||
nvs_erase_key(h, NVS_KEY_INFLUX_TOKEN);
|
||||
nvs_commit(h);
|
||||
nvs_close(h);
|
||||
ESP_LOGI(TAG, "Influx-Keys gelöscht – Werkseinstellungen aktiv beim nächsten Use.");
|
||||
}
|
||||
|
||||
void storage_debug_dump(void) {
|
||||
// WLAN
|
||||
char *ssid = NULL, *pass = NULL;
|
||||
if (storage_load_wifi_creds(&ssid, &pass)) {
|
||||
ESP_LOGI(TAG, "DUMP WLAN: SSID='%s', PASS_LEN=%d",
|
||||
ssid ? ssid : "<null>", pass ? (int)strlen(pass) : -1);
|
||||
free(ssid); free(pass);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "DUMP WLAN: keine STA-Credentials gespeichert.");
|
||||
}
|
||||
|
||||
// Influx (effektiv = NVS oder Defaults)
|
||||
char *org = NULL, *bucket = NULL, *token = NULL;
|
||||
if (storage_get_effective_influx(&org, &bucket, &token)) {
|
||||
// Token maskieren
|
||||
const char *t = token ? token : "";
|
||||
int n = (int)strlen(t);
|
||||
char masked[80] = {0};
|
||||
if (n <= 8) {
|
||||
snprintf(masked, sizeof(masked), "%s", t);
|
||||
} else {
|
||||
int head = 4, tail = 4;
|
||||
int stars = n - head - tail;
|
||||
if (stars < 0) stars = 0;
|
||||
snprintf(masked, sizeof(masked), "%.*s%.*s%.*s",
|
||||
head, t,
|
||||
stars, "****************************************",
|
||||
tail, t + n - tail);
|
||||
}
|
||||
ESP_LOGI(TAG, "DUMP Influx: org='%s', bucket='%s', token='%s' (len=%d)",
|
||||
org ? org : "", bucket ? bucket : "", masked, n);
|
||||
free(org); free(bucket); free(token);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "DUMP Influx: konnte effektive Konfiguration nicht lesen.");
|
||||
}
|
||||
|
||||
// Device-Name + Service-URL in einem NVS-Handle lesen
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) == ESP_OK) {
|
||||
// Device-Name
|
||||
size_t need = 0;
|
||||
if (nvs_get_str(h, NVS_KEY_DEVNAME, NULL, &need) == ESP_OK && need > 0) {
|
||||
char *dev = (char*)malloc(need);
|
||||
if (dev && nvs_get_str(h, NVS_KEY_DEVNAME, dev, &need) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "DUMP Device: name='%s'", dev);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "DUMP Device: name=<read error>");
|
||||
}
|
||||
if (dev) free(dev);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "DUMP Device: name=<nicht gesetzt>");
|
||||
}
|
||||
|
||||
// Service-URL
|
||||
need = 0;
|
||||
if (nvs_get_str(h, NVS_KEY_SERVICE_URL, NULL, &need) == ESP_OK && need > 0) {
|
||||
char *url = (char*)malloc(need);
|
||||
if (url && nvs_get_str(h, NVS_KEY_SERVICE_URL, url, &need) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "DUMP Service: url='%s'", url);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "DUMP Service: url=<read error>");
|
||||
}
|
||||
if (url) free(url);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "DUMP Service: url=<nicht gesetzt>");
|
||||
}
|
||||
|
||||
nvs_close(h);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
esp_err_t storage_save_device_name(const char *devicename) {
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
// Semantik: NULL = nicht ändern, "" = löschen, sonst setzen
|
||||
if (devicename != NULL) {
|
||||
if (devicename[0] == '\0') {
|
||||
esp_err_t e = nvs_erase_key(h, NVS_KEY_DEVNAME);
|
||||
if (e != ESP_OK && e != ESP_ERR_NVS_NOT_FOUND) { nvs_close(h); return e; }
|
||||
} else {
|
||||
err = nvs_set_str(h, NVS_KEY_DEVNAME, devicename);
|
||||
if (err != ESP_OK) { nvs_close(h); return err; }
|
||||
}
|
||||
err = nvs_commit(h);
|
||||
} else {
|
||||
err = ESP_OK; // nichts geändert
|
||||
}
|
||||
nvs_close(h);
|
||||
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Device-Name %s",
|
||||
(devicename == NULL) ? "unverändert"
|
||||
: (devicename[0] == '\0') ? "gelöscht"
|
||||
: "gesetzt");
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
// ---------- Device-Name (effektiv mit Default) ----------
|
||||
bool storage_get_effective_device_name(char **out_devname) {
|
||||
if (!out_devname) return false;
|
||||
*out_devname = NULL;
|
||||
|
||||
char *name = NULL;
|
||||
if (!storage_load_device_name(&name)) {
|
||||
// kein Name im NVS -> Werkseinstellung nehmen
|
||||
name = strdup(DEFAULT_DEVNAME);
|
||||
if (!name) return false;
|
||||
}
|
||||
|
||||
*out_devname = name; // malloc-String zurückgeben
|
||||
return true;
|
||||
}
|
||||
|
||||
esp_err_t storage_factory_reset_all(void) {
|
||||
// Löscht die komplette NVS-Partition (alle Namespaces und Keys)
|
||||
esp_err_t err = nvs_flash_erase();
|
||||
if (err == ESP_OK) {
|
||||
// Direkt danach kann bei Bedarf wieder initialisiert werden – wir rebooten aber ohnehin
|
||||
ESP_LOGW(TAG, "FACTORY RESET: gesamte NVS-Partition gelöscht.");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "FACTORY RESET: nvs_flash_erase() fehlgeschlagen: %s", esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#ifndef STORAGE_H
|
||||
#define STORAGE_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** Initialisiert NVS (mit Auto-Recovery bei Versionswechsel) */
|
||||
esp_err_t storage_init(void);
|
||||
|
||||
/**
|
||||
* Lädt gespeicherte STA-Credentials aus NVS.
|
||||
* - Allokiert *out_ssid / *out_pass via malloc; Caller muss free() aufrufen.
|
||||
* - Gibt true zurück, wenn beide Strings erfolgreich gelesen wurden.
|
||||
*/
|
||||
bool storage_load_wifi_creds(char **out_ssid, char **out_pass);
|
||||
|
||||
/**
|
||||
* Speichert STA-Credentials idempotent in NVS.
|
||||
* - Schreibt nur, wenn sich Werte geändert haben.
|
||||
* - Gibt ESP_OK bei Erfolg zurück (auch wenn nichts zu schreiben war).
|
||||
*/
|
||||
esp_err_t storage_save_wifi_creds(const char *ssid, const char *pass);
|
||||
bool storage_get_effective_device_name(char **out_devname);
|
||||
|
||||
/**
|
||||
* Speichert Geräte-Infos (Name, Influx-Token, Bucket, Org) in NVS.
|
||||
* - Leere/NULL-Strings löschen den jeweiligen Key.
|
||||
*/
|
||||
|
||||
bool storage_get_effective_influx(char **out_org, char **out_bucket, char **out_token);
|
||||
esp_err_t storage_save_influx_softap(const char *org, const char *bucket, const char *token);
|
||||
void storage_factory_reset_influx(void);
|
||||
void storage_debug_dump(void);
|
||||
esp_err_t storage_save_device_name(const char *devicename); // NULL=kein Update, ""=löschen
|
||||
esp_err_t storage_factory_reset_all(void);
|
||||
|
||||
esp_err_t storage_save_service_url(const char *url); // url=="" löscht
|
||||
bool storage_load_service_url(char **out_url); // malloc'd, caller free
|
||||
void storage_erase_service_url(void);
|
||||
|
||||
bool storage_load_device_name(char **out_devname);
|
||||
|
||||
esp_err_t storage_save_device_info(const char *devicename,
|
||||
const char *token,
|
||||
const char *bucket,
|
||||
const char *org);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // STORAGE_H
|
||||
@@ -0,0 +1,21 @@
|
||||
#include "sys_status.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_check.h"
|
||||
|
||||
static EventGroupHandle_t s_status_group = NULL;
|
||||
|
||||
void sys_status_init(void)
|
||||
{
|
||||
if (!s_status_group) {
|
||||
s_status_group = xEventGroupCreate();
|
||||
/* Initial: alles auf 0 */
|
||||
xEventGroupClearBits(s_status_group, SYS_STATUS_WIFI_OK | SYS_STATUS_INFLUX_OK | SYS_STATUS_MDNS_OK);
|
||||
}
|
||||
}
|
||||
|
||||
EventGroupHandle_t sys_status_group(void)
|
||||
{
|
||||
if (!s_status_group) sys_status_init();
|
||||
return s_status_group;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Bits im EventGroup */
|
||||
#define SYS_STATUS_WIFI_OK (1 << 0)
|
||||
#define SYS_STATUS_INFLUX_OK (1 << 1)
|
||||
#define SYS_STATUS_MDNS_OK (1 << 2)
|
||||
|
||||
void sys_status_init(void);
|
||||
EventGroupHandle_t sys_status_group(void);
|
||||
|
||||
/* Convenience-Setter/Getter */
|
||||
static inline void sys_status_set_wifi_ok(bool ok) { EventGroupHandle_t g = sys_status_group(); if (ok) xEventGroupSetBits(g, SYS_STATUS_WIFI_OK); else xEventGroupClearBits(g, SYS_STATUS_WIFI_OK); }
|
||||
static inline void sys_status_set_influx_ok(bool ok) { EventGroupHandle_t g = sys_status_group(); if (ok) xEventGroupSetBits(g, SYS_STATUS_INFLUX_OK); else xEventGroupClearBits(g, SYS_STATUS_INFLUX_OK); }
|
||||
static inline void sys_status_set_mdns_ok(bool ok) { EventGroupHandle_t g = sys_status_group(); if (ok) xEventGroupSetBits(g, SYS_STATUS_MDNS_OK); else xEventGroupClearBits(g, SYS_STATUS_MDNS_OK); }
|
||||
|
||||
static inline bool sys_status_get_wifi_ok(void) { return (xEventGroupGetBits(sys_status_group()) & SYS_STATUS_WIFI_OK) != 0; }
|
||||
static inline bool sys_status_get_influx_ok(void) { return (xEventGroupGetBits(sys_status_group()) & SYS_STATUS_INFLUX_OK) != 0; }
|
||||
static inline bool sys_status_get_mdns_ok(void) { return (xEventGroupGetBits(sys_status_group()) & SYS_STATUS_MDNS_OK) != 0; }
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
// File: src/wifi_mgr.c
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_timer.h"
|
||||
|
||||
#include "lwip/netdb.h"
|
||||
|
||||
#include "http_portal.h"
|
||||
#include "wifi_mgr.h"
|
||||
#include "storage.h" // NVS-Zugriffe
|
||||
#include "net_mdns.h"
|
||||
#include "sys_status.h"
|
||||
|
||||
// Captive-DNS ist in http_portal.c implementiert:
|
||||
void dns_captive_start(void);
|
||||
void dns_captive_stop(void);
|
||||
|
||||
// ---------- Konfig ----------
|
||||
#define SOFTAP_SSID "nanoPSX"
|
||||
#define SOFTAP_PASS "" // leer => offenes WLAN
|
||||
#define SOFTAP_CHANNEL 1
|
||||
#define SOFTAP_MAX_CONN 4
|
||||
|
||||
static const char *TAG = "wifi_mgr";
|
||||
|
||||
// ---------- Globals ----------
|
||||
static esp_netif_t *netif_ap = NULL, *netif_sta = NULL;
|
||||
|
||||
static EventGroupHandle_t wifi_events;
|
||||
#define EVT_STA_GOTIP BIT0
|
||||
#define EVT_STA_FAIL BIT1
|
||||
#define EVT_STA_DISCONNECTED BIT2
|
||||
|
||||
// AP-Auto-Off / DNS start/stop
|
||||
static bool ap_is_on = true;
|
||||
|
||||
// AP-Auto-Off Timer
|
||||
static esp_timer_handle_t ap_off_timer = NULL;
|
||||
|
||||
// ---------- Vorwärtsdeklarationen ----------
|
||||
static void ap_enable(void);
|
||||
static void ap_disable(void);
|
||||
static void ap_set_dhcp_dns_to_self(void);
|
||||
static void mdns_discover_task(void *arg);
|
||||
|
||||
// Wi-Fi
|
||||
static void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data);
|
||||
static void wifi_start_ap_sta(void);
|
||||
|
||||
// Timer Callback
|
||||
static void ap_off_timer_cb(void *arg);
|
||||
|
||||
// ---------- Öffentliche Helfer (Wrapper um storage) ----------
|
||||
bool wifi_mgr_load_sta_creds(char **out_ssid, char **out_pass) {
|
||||
return storage_load_wifi_creds(out_ssid, out_pass);
|
||||
}
|
||||
|
||||
void wifi_mgr_save_sta_creds_and_reconnect(const char* ssid, const char* pass) {
|
||||
if (!ssid || !pass) return;
|
||||
|
||||
(void)storage_save_wifi_creds(ssid, pass);
|
||||
|
||||
// Status zurücksetzen
|
||||
xEventGroupClearBits(wifi_events, EVT_STA_GOTIP | EVT_STA_FAIL | EVT_STA_DISCONNECTED);
|
||||
|
||||
// 1) sauber trennen (asynchron)
|
||||
esp_err_t err = esp_wifi_disconnect();
|
||||
if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_CONNECT) {
|
||||
ESP_LOGW(TAG, "esp_wifi_disconnect: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
// 2) auf "disconnected" warten (kurz)
|
||||
(void)xEventGroupWaitBits(
|
||||
wifi_events,
|
||||
EVT_STA_DISCONNECTED,
|
||||
pdTRUE, // beim Eintreffen löschen
|
||||
pdFALSE,
|
||||
pdMS_TO_TICKS(1500) // 1.5 s Timeout – gern anpassen
|
||||
);
|
||||
|
||||
// (Optionaler Fallback falls Timeout: Treiber kurz stoppen/neu starten)
|
||||
// Das vermeidet 0x3006 bei hartnäckigen Races.
|
||||
wifi_mode_t mode = WIFI_MODE_APSTA;
|
||||
if (esp_wifi_set_mode(mode) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "set_mode(APSTA) failed pre-config");
|
||||
}
|
||||
|
||||
// 3) neue Creds setzen (MIT sicherer Kopie + Terminierung!)
|
||||
char *s = NULL, *pw = NULL;
|
||||
bool have = storage_load_wifi_creds(&s, &pw);
|
||||
if (have) {
|
||||
wifi_config_t sta = {0};
|
||||
|
||||
// WICHTIG: KEIN strncpy-Fallstrick → immer nullterminieren!
|
||||
strlcpy((char*)sta.sta.ssid, s, sizeof(sta.sta.ssid));
|
||||
strlcpy((char*)sta.sta.password, pw, sizeof(sta.sta.password));
|
||||
|
||||
#ifdef WPA3_SAE_PWE_BOTH
|
||||
sta.sta.pmf_cfg.required = true;
|
||||
sta.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
|
||||
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
|
||||
#else
|
||||
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
|
||||
#endif
|
||||
|
||||
err = esp_wifi_set_config(WIFI_IF_STA, &sta);
|
||||
if (err == ESP_ERR_WIFI_STATE) {
|
||||
// Harter Fallback: kurz stoppen, dann setzen.
|
||||
ESP_LOGW(TAG, "set_config: WIFI_STATE – stop/start fallback");
|
||||
ESP_ERROR_CHECK(esp_wifi_stop());
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta));
|
||||
} else {
|
||||
ESP_ERROR_CHECK(err);
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
}
|
||||
|
||||
if (s) free(s);
|
||||
if (pw) free(pw);
|
||||
}
|
||||
|
||||
|
||||
void wifi_mgr_save_device_info(const char* devicename,
|
||||
const char* token,
|
||||
const char* bucket,
|
||||
const char* org) {
|
||||
// 1) Devicename separat handhaben (NULL=kein Update, ""=löschen)
|
||||
(void)storage_save_device_name(devicename);
|
||||
|
||||
// 2) Influx-Teil mit SoftAP-Semantik (NULL=keep, ""=löschen, sonst setzen)
|
||||
(void)storage_save_influx_softap(org, bucket, token);
|
||||
|
||||
// 3) Debug: alles nochmal ausgeben
|
||||
storage_debug_dump();
|
||||
}
|
||||
|
||||
|
||||
// ---------- AP Toggle ----------
|
||||
static void ap_enable(void) {
|
||||
if (ap_is_on) return;
|
||||
|
||||
wifi_config_t ap = (wifi_config_t){0};
|
||||
strncpy((char*)ap.ap.ssid, SOFTAP_SSID, sizeof(ap.ap.ssid));
|
||||
ap.ap.ssid_len = strlen(SOFTAP_SSID);
|
||||
ap.ap.channel = SOFTAP_CHANNEL;
|
||||
ap.ap.max_connection = SOFTAP_MAX_CONN;
|
||||
if (strlen(SOFTAP_PASS) == 0) {
|
||||
ap.ap.authmode = WIFI_AUTH_OPEN;
|
||||
} else {
|
||||
strncpy((char*)ap.ap.password, SOFTAP_PASS, sizeof(ap.ap.password));
|
||||
ap.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
|
||||
}
|
||||
ap.ap.pmf_cfg.required = false;
|
||||
|
||||
esp_wifi_set_mode(WIFI_MODE_APSTA);
|
||||
esp_wifi_set_config(WIFI_IF_AP, &ap);
|
||||
ap_is_on = true;
|
||||
|
||||
// DNS/Captive einschalten
|
||||
(void)dns_captive_start();
|
||||
|
||||
// DHCP-DNS Option auf AP-IP setzen
|
||||
ap_set_dhcp_dns_to_self();
|
||||
|
||||
if (netif_ap) {
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(netif_ap, &ip) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "AP reaktiviert. IP " IPSTR, IP2STR(&ip.ip));
|
||||
} else {
|
||||
ESP_LOGI(TAG, "AP reaktiviert.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ap_disable(void) {
|
||||
if (!ap_is_on) return;
|
||||
|
||||
// DNS/Captive aus
|
||||
dns_captive_stop();
|
||||
|
||||
esp_wifi_set_mode(WIFI_MODE_STA); // nur STA aktiv
|
||||
ap_is_on = false;
|
||||
ESP_LOGI(TAG, "AP/DNS deaktiviert (nur STA aktiv).");
|
||||
|
||||
// (Optional) Portal mit abschalten, damit es nicht auf STA erreichbar bleibt:
|
||||
// portal_http_stop();
|
||||
}
|
||||
|
||||
// ---------- Timer Callback ----------
|
||||
static void ap_off_timer_cb(void *arg) {
|
||||
(void)arg;
|
||||
EventBits_t bits = xEventGroupGetBits(wifi_events);
|
||||
if (bits & EVT_STA_GOTIP) {
|
||||
ap_disable();
|
||||
} else {
|
||||
ESP_LOGW(TAG, "AP-Auto-Off abgebrochen (keine STA-IP mehr).");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Wi-Fi ----------
|
||||
static void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data) {
|
||||
(void)arg;
|
||||
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
|
||||
sys_status_set_wifi_ok(false);
|
||||
ESP_LOGI(TAG, "STA start");
|
||||
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
sys_status_set_wifi_ok(false);
|
||||
ESP_LOGW(TAG, "STA disconnected");
|
||||
xEventGroupClearBits(wifi_events, EVT_STA_GOTIP);
|
||||
xEventGroupSetBits(wifi_events, EVT_STA_FAIL | EVT_STA_DISCONNECTED);
|
||||
|
||||
if (ap_off_timer && esp_timer_is_active(ap_off_timer)) {
|
||||
esp_timer_stop(ap_off_timer);
|
||||
}
|
||||
ap_enable();
|
||||
esp_wifi_connect();
|
||||
|
||||
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
|
||||
sys_status_set_wifi_ok(true);
|
||||
ip_event_got_ip_t *e = (ip_event_got_ip_t*)data;
|
||||
ESP_LOGI(TAG, "STA got IP: " IPSTR, IP2STR(&e->ip_info.ip));
|
||||
xEventGroupSetBits(wifi_events, EVT_STA_GOTIP);
|
||||
|
||||
xTaskCreate(mdns_discover_task, "mdns_discover", 3072, NULL, 4, NULL);
|
||||
|
||||
if (ap_off_timer) {
|
||||
if (esp_timer_is_active(ap_off_timer)) esp_timer_stop(ap_off_timer);
|
||||
ESP_ERROR_CHECK(esp_timer_start_once(ap_off_timer, 10 * 1000 * 1000)); // 10 s
|
||||
ESP_LOGI(TAG, "AP-Auto-Off in 10s geplant…");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void wifi_start_ap_sta(void) {
|
||||
netif_ap = esp_netif_create_default_wifi_ap();
|
||||
netif_sta = esp_netif_create_default_wifi_sta();
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
|
||||
|
||||
wifi_config_t ap = (wifi_config_t){0};
|
||||
strncpy((char*)ap.ap.ssid, SOFTAP_SSID, sizeof(ap.ap.ssid));
|
||||
ap.ap.ssid_len = strlen(SOFTAP_SSID);
|
||||
ap.ap.channel = SOFTAP_CHANNEL;
|
||||
ap.ap.max_connection = SOFTAP_MAX_CONN;
|
||||
if (strlen(SOFTAP_PASS) == 0) {
|
||||
ap.ap.authmode = WIFI_AUTH_OPEN;
|
||||
} else {
|
||||
strncpy((char*)ap.ap.password, SOFTAP_PASS, sizeof(ap.ap.password));
|
||||
ap.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
|
||||
}
|
||||
ap.ap.pmf_cfg.required = false;
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
|
||||
|
||||
char *ssid = NULL, *pass = NULL;
|
||||
bool have = storage_load_wifi_creds(&ssid, &pass);
|
||||
if (have) {
|
||||
wifi_config_t sta = (wifi_config_t){0};
|
||||
strncpy((char*)sta.sta.ssid, ssid, sizeof(sta.sta.ssid));
|
||||
strncpy((char*)sta.sta.password, pass, sizeof(sta.sta.password));
|
||||
#ifdef WPA3_SAE_PWE_BOTH
|
||||
sta.sta.pmf_cfg.required = true;
|
||||
sta.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
|
||||
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
|
||||
#else
|
||||
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
|
||||
#endif
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta));
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
|
||||
// DHCP-DNS auf AP-IP setzen (erhöht Captive-Trefferquote)
|
||||
ap_set_dhcp_dns_to_self();
|
||||
|
||||
if (netif_ap) {
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(netif_ap, &ip) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "AP %s gestartet. IP " IPSTR, SOFTAP_SSID, IP2STR(&ip.ip));
|
||||
}
|
||||
}
|
||||
|
||||
if (have) {
|
||||
ESP_LOGI(TAG, "Versuche STA zu verbinden zu '%s' ...", ssid);
|
||||
esp_wifi_connect();
|
||||
}
|
||||
if (ssid) free(ssid);
|
||||
if (pass) free(pass);
|
||||
}
|
||||
|
||||
// ---------- Öffentliche API ----------
|
||||
void wifi_mgr_init(void) {
|
||||
// NVS (neu über storage)
|
||||
ESP_ERROR_CHECK(storage_init());
|
||||
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
wifi_events = xEventGroupCreate();
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
|
||||
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
|
||||
|
||||
const esp_timer_create_args_t targs = {
|
||||
.callback = ap_off_timer_cb,
|
||||
.arg = NULL,
|
||||
.dispatch_method = ESP_TIMER_TASK,
|
||||
.name = "ap_off_timer"
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_timer_create(&targs, &ap_off_timer));
|
||||
}
|
||||
|
||||
void wifi_mgr_start(void) {
|
||||
// AP+STA hochfahren
|
||||
wifi_start_ap_sta();
|
||||
|
||||
// HTTP-Portal starten (erzwingt Captive bis Save, s. http_portal.c)
|
||||
ESP_ERROR_CHECK(portal_http_start(wifi_events, EVT_STA_GOTIP, EVT_STA_FAIL, SOFTAP_SSID));
|
||||
|
||||
// DNS/Captive starten
|
||||
(void)dns_captive_start();
|
||||
|
||||
ESP_LOGI(TAG, "Bereit. Verbinde dich mit '%s' und öffne beliebige Seite – das Portal erscheint.", SOFTAP_SSID);
|
||||
}
|
||||
|
||||
// ---------- Hilfsfunktionen ----------
|
||||
static void ap_set_dhcp_dns_to_self(void) {
|
||||
if (!netif_ap) return;
|
||||
esp_netif_ip_info_t ip;
|
||||
if (esp_netif_get_ip_info(netif_ap, &ip) != ESP_OK) return;
|
||||
|
||||
// DHCP-Server neu konfigurieren: als DNS-Server die eigene AP-IP anbieten
|
||||
esp_netif_dhcps_stop(netif_ap);
|
||||
esp_netif_dhcps_option(netif_ap, ESP_NETIF_OP_SET,
|
||||
ESP_NETIF_DOMAIN_NAME_SERVER,
|
||||
&ip.ip, sizeof(ip.ip));
|
||||
esp_netif_dhcps_start(netif_ap);
|
||||
}
|
||||
|
||||
// Task für mDNS-Discover ---
|
||||
static void mdns_discover_task(void *arg) {
|
||||
// Start/ensure mDNS läuft
|
||||
(void)net_mdns_autostart_init(NULL, NULL);
|
||||
|
||||
const TickType_t kDelay = pdMS_TO_TICKS(60000); // 60 s
|
||||
for (;;) {
|
||||
// Erst offizieller Service, dann Fallback auf HTTP:8086
|
||||
esp_err_t err = net_mdns_autodiscover_and_store("_influxdb2", "_tcp", -1,
|
||||
NULL, NULL, 2000);
|
||||
if (err != ESP_OK) {
|
||||
err = net_mdns_autodiscover_and_store("_http", "_tcp", 8086,
|
||||
NULL, NULL, 2000);
|
||||
}
|
||||
|
||||
if (err == ESP_OK) {
|
||||
sys_status_set_mdns_ok(true);
|
||||
ESP_LOGI(TAG, "mDNS: Service gefunden und gespeichert. Beende Re-Try-Task.");
|
||||
vTaskDelete(NULL); // fertig, keine weiteren Versuche
|
||||
} else {
|
||||
sys_status_set_mdns_ok(false);
|
||||
ESP_LOGW(TAG, "mDNS: nichts gefunden – neuer Versuch in 60 s");
|
||||
vTaskDelay(kDelay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Initialisiert NVS, Netif, Eventloop, Wi-Fi, registriert Event-Handler und legt den AP-Auto-Off-Timer an.
|
||||
void wifi_mgr_init(void);
|
||||
|
||||
// Startet AP+STA, HTTP-Server und DNS-Server, und stößt ggf. eine STA-Verbindung an.
|
||||
void wifi_mgr_start(void);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
Reference in New Issue
Block a user