Add repeater protocol and device firmware features
This commit is contained in:
@@ -4,7 +4,33 @@ idf_component_register(
|
||||
"sx126x.c"
|
||||
"wmbus.c"
|
||||
"repeater.c"
|
||||
"duty_ledger.c"
|
||||
"console.c"
|
||||
"led.c"
|
||||
"cfg_store.c"
|
||||
"ui.c"
|
||||
"debug_history.c"
|
||||
"wifi_debug.c"
|
||||
"settings.c"
|
||||
"settings_http.c"
|
||||
"wifi_qr.c"
|
||||
"vendor/qrcodegen.c"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES driver esp_timer esp_lcd esp_wifi esp_netif esp_event esp_http_server
|
||||
nvs_flash bootloader_support json
|
||||
)
|
||||
|
||||
# Ship compressed assets to retain the existing app/NVS partition layout.
|
||||
# Python and gzip are host build tools only; ESP32 serves these bytes directly.
|
||||
foreach(asset index.html dashboard.css dashboard.js identity.js manufacturers.js)
|
||||
set(source "${CMAKE_CURRENT_SOURCE_DIR}/web/${asset}")
|
||||
set(compressed "${CMAKE_CURRENT_BINARY_DIR}/web/${asset}.gz")
|
||||
add_custom_command(
|
||||
OUTPUT "${compressed}"
|
||||
COMMAND "${PYTHON}" "${CMAKE_CURRENT_SOURCE_DIR}/../../tools/compress_web_asset.py"
|
||||
"${source}" "${compressed}"
|
||||
DEPENDS "${source}" "${CMAKE_CURRENT_SOURCE_DIR}/../../tools/compress_web_asset.py"
|
||||
VERBATIM
|
||||
)
|
||||
target_add_binary_data(${COMPONENT_LIB} "${compressed}" BINARY)
|
||||
endforeach()
|
||||
|
||||
@@ -37,3 +37,15 @@
|
||||
|
||||
// Overcurrent protection value from RNode 1.86 ("OCP_TUNED 0x28")
|
||||
#define BOARD_SX1262_OCP 0x28
|
||||
|
||||
// SSD1306 OLED (128x64, I2C 0x3C) + PRG button.
|
||||
// Pins verified against RTNode-HeltecV4 Display.h / Boards.h for this exact
|
||||
// board revision (docs/FUTURE_UI.md). Vext is an ACTIVE-LOW external rail
|
||||
// that powers the display; set once at boot, never toggled mid-TX.
|
||||
#define BOARD_OLED_SDA 17
|
||||
#define BOARD_OLED_SCL 18
|
||||
#define BOARD_OLED_RST 21
|
||||
#define BOARD_VEXT 36
|
||||
// GPIO0 is the BOOT strap pin: input only, sampled well after boot,
|
||||
// debounced. No boot-time gestures (docs/FUTURE_UI.md constraint 3).
|
||||
#define BOARD_BTN_PRG 0
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// Persistence for the SHORT LIST of config keys allowed to survive power
|
||||
// cycles: duty_budget_ppm and repeat_delay_ms. Battery-standalone testing
|
||||
// needs settings that outlive reboots (no host to re-send commands).
|
||||
// Everything else in g_cfg stays deliberately RAM-only.
|
||||
//
|
||||
// Persisted values are restored at boot and logged as a cfg_restore
|
||||
// event; the OLED config page shows the effective values. A device with a
|
||||
// persisted duty_budget_ppm of 0 (guard disabled) stays non-compliant
|
||||
// until explicitly set back -- docs/STANDARDS_GAPS.md.
|
||||
#include "cfg_store.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include "nvs_flash.h"
|
||||
#include "nvs.h"
|
||||
|
||||
#define NS "repeater"
|
||||
|
||||
static bool s_ready;
|
||||
|
||||
void cfg_store_init(void)
|
||||
{
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
if (nvs_flash_erase() != ESP_OK) return;
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
s_ready = (err == ESP_OK);
|
||||
if (!s_ready) {
|
||||
printf("{\"event\":\"cfg_store\",\"ok\":false,\"err\":%d}\n", (int)err);
|
||||
fflush(stdout);
|
||||
}
|
||||
}
|
||||
|
||||
bool cfg_store_load_u32(const char *key, uint32_t *out)
|
||||
{
|
||||
if (!s_ready) return false;
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) return false;
|
||||
uint32_t v = 0;
|
||||
esp_err_t err = nvs_get_u32(h, key, &v);
|
||||
nvs_close(h);
|
||||
if (err != ESP_OK) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cfg_store_save_u32(const char *key, uint32_t v)
|
||||
{
|
||||
if (!s_ready) return false;
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NS, NVS_READWRITE, &h) != ESP_OK) return false;
|
||||
esp_err_t err = nvs_set_u32(h, key, v);
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
return err == ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// NVS persistence for a SHORT LIST of config keys (see cfg_store.c).
|
||||
// Current keys: "duty_ppm" (duty_budget_ppm), "delay_ms" (repeat_delay_ms).
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define CFG_KEY_DUTY_PPM "duty_ppm"
|
||||
#define CFG_KEY_DELAY_MS "delay_ms"
|
||||
|
||||
void cfg_store_init(void);
|
||||
bool cfg_store_load_u32(const char *key, uint32_t *out); // true if present
|
||||
bool cfg_store_save_u32(const char *key, uint32_t v); // true only after commit
|
||||
+106
-73
@@ -1,13 +1,16 @@
|
||||
// Line-based scriptable serial console on USB-Serial-JTAG.
|
||||
// Commands (one per line):
|
||||
// status | stats | clear_stats | radio_status | radio_reset | test_tx
|
||||
// status | stats | clear_stats | radio_status | radio_reset | test_tx | test_tx_t1
|
||||
// set repeat_delay_ms N | set tx_power N | set repeat_enabled 0|1
|
||||
// set verbose 0|1 | set whitelist ID[,ID...] | set whitelist clear
|
||||
// set beacon_period_ms N (0=off, uses test_lfield) | set duty_budget_ppm N
|
||||
// set fem_rx_csd 0|1 | set preamble_bits 0|8|16|24|32 | set test_lfield N
|
||||
// reboot
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_system.h"
|
||||
@@ -15,7 +18,7 @@
|
||||
#include "driver/usb_serial_jtag_vfs.h"
|
||||
|
||||
#include "repeater.h"
|
||||
#include "sx126x.h"
|
||||
#include "settings.h"
|
||||
|
||||
static void ack(const char *cmd, bool ok, const char *detail)
|
||||
{
|
||||
@@ -25,81 +28,100 @@ static void ack(const char *cmd, bool ok, const char *detail)
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
static bool parse_integer(const char *text, int32_t *out)
|
||||
{
|
||||
const char *digits = text;
|
||||
if (*digits == '-' || *digits == '+') digits++;
|
||||
if (!*digits) return false;
|
||||
for (const char *p = digits; *p; p++) {
|
||||
if (*p < '0' || *p > '9') return false;
|
||||
}
|
||||
char *end;
|
||||
errno = 0;
|
||||
long value = strtol(text, &end, 10);
|
||||
if (errno == ERANGE || *end || value < INT32_MIN || value > INT32_MAX) return false;
|
||||
*out = (int32_t)value;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool parse_whitelist(const char *text, settings_change_t *change)
|
||||
{
|
||||
if (strcmp(text, "clear") == 0) return true;
|
||||
for (;;) {
|
||||
if (change->whitelist_len == 8) return false;
|
||||
uint32_t id = 0;
|
||||
for (unsigned i = 0; i < 8; i++) {
|
||||
unsigned char c = (unsigned char)*text++;
|
||||
unsigned digit;
|
||||
if (c >= '0' && c <= '9') digit = c - '0';
|
||||
else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10;
|
||||
else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10;
|
||||
else return false;
|
||||
id = (id << 4) | digit;
|
||||
}
|
||||
change->whitelist[change->whitelist_len++] = id;
|
||||
if (!*text) return true;
|
||||
if (*text++ != ',' || !*text) return false;
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_set(char *args)
|
||||
{
|
||||
char *key = strtok(args, " ");
|
||||
char *val = strtok(NULL, " ");
|
||||
if (!key || !val) { ack("set", false, "usage"); return; }
|
||||
|
||||
if (strcmp(key, "repeat_delay_ms") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
if (v < 20 || v > 200) { ack("set", false, "range 20..200"); return; }
|
||||
g_cfg.repeat_delay_ms = (uint32_t)v;
|
||||
ack("set repeat_delay_ms", true, NULL);
|
||||
} else if (strcmp(key, "tx_power") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
if (v < -9 || v > 14) { ack("set", false, "range -9..14"); return; }
|
||||
g_cfg.tx_power_dbm = (int8_t)v;
|
||||
repeater_request_radio_reset();
|
||||
ack("set tx_power", true, "radio reinit queued");
|
||||
} else if (strcmp(key, "repeat_enabled") == 0) {
|
||||
g_cfg.repeat_enabled = (val[0] == '1');
|
||||
ack("set repeat_enabled", true, NULL);
|
||||
} else if (strcmp(key, "duty_budget_ppm") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
if (v < 0 || v > 100000) { ack("set", false, "range 0..100000 ppm"); return; }
|
||||
g_cfg.duty_budget_ppm = (uint32_t)v;
|
||||
ack("set duty_budget_ppm", true, v == 0 ? "guard disabled" : NULL);
|
||||
} else if (strcmp(key, "beacon_period_ms") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
if (v != 0 && (v < 250 || v > 600000)) { ack("set", false, "0 or 250..600000 ms"); return; }
|
||||
g_cfg.beacon_period_ms = (uint32_t)v;
|
||||
ack("set beacon_period_ms", true, v == 0 ? "beacon off" : NULL);
|
||||
} else if (strcmp(key, "preamble_bits") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
uint8_t code;
|
||||
switch (v) {
|
||||
case 0: code = 0x00; break;
|
||||
case 8: code = 0x04; break;
|
||||
case 16: code = 0x05; break;
|
||||
case 24: code = 0x06; break;
|
||||
case 32: code = 0x07; break;
|
||||
default: ack("set", false, "use 0|8|16|24|32"); return;
|
||||
}
|
||||
sx126x_set_preamble_detect(code);
|
||||
repeater_request_radio_reset();
|
||||
ack("set preamble_bits", true, "radio reinit queued");
|
||||
} else if (strcmp(key, "pa_low") == 0) {
|
||||
sx126x_set_pa_low(val[0] == '1');
|
||||
repeater_request_radio_reset();
|
||||
ack("set pa_low", true, "radio reinit queued");
|
||||
} else if (strcmp(key, "test_lfield") == 0) {
|
||||
long v = strtol(val, NULL, 10);
|
||||
if (v < 19 || v > 200) { ack("set", false, "range 19..200"); return; }
|
||||
repeater_set_test_lfield((uint8_t)v);
|
||||
ack("set test_lfield", true, NULL);
|
||||
} else if (strcmp(key, "fem_rx_csd") == 0) {
|
||||
fem_set_rx_csd(val[0] == '1');
|
||||
ack("set fem_rx_csd", true, "applies at next RX entry");
|
||||
} else if (strcmp(key, "verbose") == 0) {
|
||||
g_cfg.verbose = (val[0] == '1');
|
||||
ack("set verbose", true, NULL);
|
||||
} else if (strcmp(key, "whitelist") == 0) {
|
||||
if (strcmp(val, "clear") == 0) {
|
||||
g_cfg.whitelist_len = 0;
|
||||
ack("set whitelist", true, "cleared");
|
||||
char *save;
|
||||
char *key = strtok_r(args, " \t", &save);
|
||||
char *val = strtok_r(NULL, " \t", &save);
|
||||
if (!key || !val || strtok_r(NULL, " \t", &save)) {
|
||||
ack("set", false, "usage: set KEY VALUE");
|
||||
return;
|
||||
}
|
||||
int n = 0;
|
||||
for (char *tok = strtok(val, ","); tok && n < 8; tok = strtok(NULL, ",")) {
|
||||
// meter ID as printed (BCD hex digits) -> stored LE uint32
|
||||
uint32_t id = (uint32_t)strtoul(tok, NULL, 16);
|
||||
g_cfg.whitelist[n++] = id;
|
||||
}
|
||||
g_cfg.whitelist_len = n;
|
||||
ack("set whitelist", true, NULL);
|
||||
} else {
|
||||
static const struct {
|
||||
const char *name;
|
||||
settings_key_t key;
|
||||
const char *range;
|
||||
} keys[] = {
|
||||
{"repeat_delay_ms", SETTINGS_REPEAT_DELAY_MS, "integer 20..1000"},
|
||||
{"tx_power", SETTINGS_TX_POWER, "integer -9..2"},
|
||||
{"repeat_enabled", SETTINGS_REPEAT_ENABLED, "use 0|1"},
|
||||
{"verbose", SETTINGS_VERBOSE, "use 0|1"},
|
||||
{"fem_rx_csd", SETTINGS_FEM_RX_CSD, "use 0|1"},
|
||||
{"preamble_bits", SETTINGS_PREAMBLE_BITS, "use 0|8|16|24|32"},
|
||||
{"duty_budget_ppm", SETTINGS_DUTY_BUDGET_PPM, "integer 0..100000 ppm"},
|
||||
{"test_lfield", SETTINGS_TEST_LFIELD, "integer 19..200"},
|
||||
{"whitelist", SETTINGS_WHITELIST, "clear or 1..8 unique eight-hex-digit IDs"},
|
||||
{"beacon_period_ms", SETTINGS_BEACON_PERIOD_MS, "integer 0 or 250..600000 ms"},
|
||||
};
|
||||
const size_t count = sizeof(keys) / sizeof(keys[0]);
|
||||
size_t index = 0;
|
||||
while (index < count && strcmp(key, keys[index].name) != 0) index++;
|
||||
if (index == count) {
|
||||
ack("set", false, "unknown key");
|
||||
return;
|
||||
}
|
||||
settings_change_t change = {.key = keys[index].key};
|
||||
bool parsed;
|
||||
if (change.key == SETTINGS_WHITELIST) {
|
||||
parsed = parse_whitelist(val, &change);
|
||||
} else if (change.key == SETTINGS_REPEAT_ENABLED || change.key == SETTINGS_VERBOSE
|
||||
|| change.key == SETTINGS_FEM_RX_CSD) {
|
||||
parsed = strcmp(val, "0") == 0 || strcmp(val, "1") == 0;
|
||||
change.value = val[0] == '1';
|
||||
} else {
|
||||
parsed = parse_integer(val, &change.value);
|
||||
}
|
||||
settings_result_t result = parsed ? settings_update(&change, 0, NULL) : SETTINGS_INVALID;
|
||||
char command[48];
|
||||
snprintf(command, sizeof(command), "set %s", keys[index].name);
|
||||
switch (result) {
|
||||
case SETTINGS_OK:
|
||||
ack(command, true,
|
||||
change.key == SETTINGS_REPEAT_DELAY_MS || change.key == SETTINGS_DUTY_BUDGET_PPM
|
||||
? "persisted; accepted for radio loop boundary"
|
||||
: "accepted for radio loop boundary");
|
||||
break;
|
||||
case SETTINGS_INVALID: ack(command, false, keys[index].range); break;
|
||||
case SETTINGS_CONFLICT: ack(command, false, "settings changed; reload status"); break;
|
||||
case SETTINGS_STORAGE_ERROR: ack(command, false, "storage failed; settings unchanged"); break;
|
||||
case SETTINGS_BUSY: ack(command, false, "settings busy; unchanged"); break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +134,13 @@ static void console_task(void *arg)
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
continue;
|
||||
}
|
||||
if (!strpbrk(line, "\r\n")) {
|
||||
// Never apply the valid-looking prefix of an oversized command.
|
||||
int c;
|
||||
while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {}
|
||||
ack("set", false, "line too long");
|
||||
continue;
|
||||
}
|
||||
line[strcspn(line, "\r\n")] = 0;
|
||||
if (line[0] == 0) continue;
|
||||
|
||||
@@ -144,13 +173,17 @@ static void console_task(void *arg)
|
||||
repeater_request_test_tx();
|
||||
ack("test_tx", true, "queued");
|
||||
}
|
||||
else if (strcmp(line, "test_tx_t1") == 0) {
|
||||
repeater_request_test_tx_t1();
|
||||
ack("test_tx_t1", true, "queued");
|
||||
}
|
||||
else if (strncmp(line, "set ", 4) == 0) handle_set(line + 4);
|
||||
else if (strcmp(line, "reboot") == 0) {
|
||||
ack("reboot", true, NULL);
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
esp_restart();
|
||||
}
|
||||
else ack(line, false, "unknown command");
|
||||
else ack("unknown", false, "unknown command");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
#include "debug_history.h"
|
||||
|
||||
#include <string.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
|
||||
// One radio writer; HTTP readers only copy under this lock. Every critical
|
||||
// section is bounded by one row/status copy, never a traversal or formatting.
|
||||
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
static debug_record_t s_rows[DEBUG_HISTORY_CAPACITY];
|
||||
static debug_status_t s_status;
|
||||
static uint32_t s_latest;
|
||||
|
||||
static uint32_t oldest_id(uint32_t latest)
|
||||
{
|
||||
return latest > DEBUG_HISTORY_CAPACITY
|
||||
? latest - DEBUG_HISTORY_CAPACITY + 1 : 1;
|
||||
}
|
||||
|
||||
void debug_history_record(const debug_record_t *record)
|
||||
{
|
||||
// Classify outside the critical section. These boot-lifetime counters are
|
||||
// independent of the resettable console/OLED statistics and ring eviction.
|
||||
const bool received = strcmp(record->source, "rx") == 0;
|
||||
const bool completed = strcmp(record->outcome, "ok") == 0
|
||||
|| strcmp(record->outcome, "ok_polled") == 0;
|
||||
const bool failed = strcmp(record->outcome, "encode_failed") == 0
|
||||
|| strcmp(record->outcome, "start_failed") == 0
|
||||
|| strcmp(record->outcome, "radio_timeout") == 0
|
||||
|| strcmp(record->outcome, "irq_timeout") == 0;
|
||||
const bool skipped = strcmp(record->outcome, "repeat_disabled") == 0
|
||||
|| strcmp(record->outcome, "whitelist") == 0
|
||||
|| strcmp(record->outcome, "duplicate") == 0
|
||||
|| strcmp(record->outcome, "duty_cycle") == 0
|
||||
|| strcmp(record->outcome, "hop_policy") == 0;
|
||||
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
const uint32_t id = ++s_latest;
|
||||
debug_record_t *slot = &s_rows[(id - 1) % DEBUG_HISTORY_CAPACITY];
|
||||
*slot = *record;
|
||||
slot->id = id;
|
||||
if (received) {
|
||||
if (record->crc_ok) {
|
||||
s_status.rx_valid++;
|
||||
s_status.last_rx_us = record->timestamp_us;
|
||||
if (completed) s_status.repeats_completed++;
|
||||
else if (failed) s_status.tx_failed++;
|
||||
else if (skipped) s_status.skipped++;
|
||||
} else {
|
||||
s_status.rx_rejected++;
|
||||
}
|
||||
}
|
||||
// Synthetic TX is visible in the last-TX age, never in RX/repeat totals.
|
||||
if (completed) s_status.last_tx_us = record->tx_done_us;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
void debug_history_publish_status(const debug_status_t *status)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
// Deliberately do not overwrite counters or last-event timestamps owned
|
||||
// by record(), even if this health sample predates a finalized RX.
|
||||
s_status.sampled_at_us = status->sampled_at_us;
|
||||
s_status.heartbeat_us = status->heartbeat_us;
|
||||
s_status.duty_used_us = status->duty_used_us;
|
||||
s_status.duty_budget_us = status->duty_budget_us;
|
||||
s_status.recoveries = status->recoveries;
|
||||
s_status.repeat_delay_ms = status->repeat_delay_ms;
|
||||
s_status.chip_mode = status->chip_mode;
|
||||
s_status.config_intact = status->config_intact;
|
||||
s_status.repeat_enabled = status->repeat_enabled;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
void debug_history_snapshot(uint32_t after, debug_snapshot_t *out)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
out->cursor = s_latest;
|
||||
out->status = s_status;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
|
||||
out->oldest_id = out->cursor ? oldest_id(out->cursor) : 0;
|
||||
out->evicted = out->cursor > DEBUG_HISTORY_CAPACITY
|
||||
? out->cursor - DEBUG_HISTORY_CAPACITY : 0;
|
||||
out->reset = after > out->cursor
|
||||
|| (after != 0 && after < out->evicted);
|
||||
out->count = 0;
|
||||
if (!out->cursor) return;
|
||||
|
||||
uint32_t id = after == 0 || out->reset ? out->oldest_id : after + 1;
|
||||
// cursor fixes the upper bound at entry, so a busy producer cannot make
|
||||
// this read unbounded. The immutable ID is a slot-generation guard: an
|
||||
// overwritten slot must never be returned as the originally requested RX.
|
||||
while (id != 0 && id <= out->cursor) {
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
const debug_record_t *slot = &s_rows[(id - 1) % DEBUG_HISTORY_CAPACITY];
|
||||
const bool present = slot->id == id;
|
||||
if (present) out->rows[out->count] = *slot;
|
||||
const uint32_t oldest = present ? 0 : oldest_id(s_latest);
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
|
||||
if (present) {
|
||||
out->count++;
|
||||
id++;
|
||||
} else {
|
||||
// Concurrent eviction: discard the copied prefix and return only
|
||||
// a contiguous surviving suffix of the entry-time window. A fully
|
||||
// evicted window returns no rows; the next cursor request catches
|
||||
// up normally. Never retry or hold the producer while copying 256
|
||||
// rows. oldest_id/evicted now describe the observed loss boundary.
|
||||
out->reset = true;
|
||||
out->count = 0;
|
||||
out->oldest_id = oldest;
|
||||
out->evicted = oldest - 1;
|
||||
id = oldest;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define DEBUG_HISTORY_CAPACITY 256
|
||||
|
||||
// Immutable final outcome. String pointers must refer to static literals.
|
||||
// Identity is the link-layer sender, never an inferred transport-layer meter.
|
||||
typedef struct {
|
||||
uint32_t id;
|
||||
int64_t timestamp_us;
|
||||
int64_t tx_start_us;
|
||||
int64_t tx_done_us;
|
||||
uint32_t meter_id;
|
||||
uint32_t hash;
|
||||
uint16_t manufacturer;
|
||||
uint16_t length;
|
||||
uint8_t version;
|
||||
uint8_t device_type;
|
||||
int8_t rssi_dbm;
|
||||
bool identity_present;
|
||||
bool crc_ok;
|
||||
const char *source; // rx, beacon, test
|
||||
const char *mode; // C1, T1, unknown
|
||||
const char *format; // A, B, unknown
|
||||
const char *reception; // ok, crc_failed, bad_length, undecodable,
|
||||
// t1_too_long, rx_read_failed, not_applicable
|
||||
const char *outcome; // ok, ok_polled, crc_failed, bad_length, undecodable,
|
||||
// t1_too_long, rx_read_failed, repeat_disabled,
|
||||
// whitelist, duplicate, duty_cycle, hop_policy,
|
||||
// encode_failed, start_failed, radio_timeout, irq_timeout
|
||||
} debug_record_t;
|
||||
|
||||
typedef struct {
|
||||
int64_t sampled_at_us;
|
||||
int64_t heartbeat_us;
|
||||
int64_t last_rx_us; // last CRC-valid reception
|
||||
int64_t last_tx_us; // last completed transmission (includes synthetic)
|
||||
uint64_t rx_valid;
|
||||
uint64_t rx_rejected;
|
||||
uint64_t repeats_completed;
|
||||
uint64_t tx_failed; // received repeats only
|
||||
uint64_t skipped; // valid received frames intentionally not repeated
|
||||
uint64_t duty_used_us;
|
||||
uint64_t duty_budget_us; // zero means disabled
|
||||
uint32_t recoveries;
|
||||
uint32_t repeat_delay_ms;
|
||||
uint8_t chip_mode;
|
||||
bool config_intact;
|
||||
bool repeat_enabled;
|
||||
} debug_status_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t cursor;
|
||||
uint32_t oldest_id;
|
||||
uint32_t evicted;
|
||||
bool reset; // caller must discard retained rows before merging
|
||||
size_t count;
|
||||
debug_status_t status;
|
||||
debug_record_t rows[DEBUG_HISTORY_CAPACITY]; // ascending id
|
||||
} debug_snapshot_t;
|
||||
|
||||
// Single writer: radio task. No allocation, formatting, or network operations.
|
||||
void debug_history_record(const debug_record_t *record);
|
||||
// Radio publishes health/config/duty; record() owns counters and last-event ages.
|
||||
void debug_history_publish_status(const debug_status_t *status);
|
||||
// HTTP task owns the output buffer. No lock held while formatting or sending.
|
||||
void debug_history_snapshot(uint32_t after, debug_snapshot_t *out);
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "duty_ledger.h"
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
uint64_t duty_ledger_used(const duty_ledger_t *ledger, int64_t now_us)
|
||||
{
|
||||
if (now_us < 0) return 0;
|
||||
|
||||
const uint64_t now = (uint64_t)now_us;
|
||||
const bool has_full_window = now >= DUTY_LEDGER_WINDOW_US;
|
||||
const uint64_t cutoff = has_full_window ? now - DUTY_LEDGER_WINDOW_US : 0;
|
||||
uint64_t sum = 0;
|
||||
|
||||
for (int i = 0; i < DUTY_LEDGER_BUCKETS; i++) {
|
||||
const duty_ledger_bucket_t *bucket = &ledger->buckets[i];
|
||||
if (bucket->minute_key == 0) continue;
|
||||
|
||||
const uint64_t minute = bucket->minute_key - 1;
|
||||
const uint64_t start = minute * DUTY_LEDGER_BUCKET_US;
|
||||
if (start > now) continue;
|
||||
if (has_full_window && start + DUTY_LEDGER_BUCKET_US <= cutoff) continue;
|
||||
|
||||
if (UINT64_MAX - sum < bucket->airtime_us) return UINT64_MAX;
|
||||
sum += bucket->airtime_us;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
void duty_ledger_record(duty_ledger_t *ledger, int64_t now_us,
|
||||
uint32_t airtime_us)
|
||||
{
|
||||
if (now_us < 0 || airtime_us == 0) return;
|
||||
|
||||
const uint64_t minute = (uint64_t)now_us / DUTY_LEDGER_BUCKET_US;
|
||||
duty_ledger_bucket_t *bucket = &ledger->buckets[minute % DUTY_LEDGER_BUCKETS];
|
||||
const uint64_t key = minute + 1;
|
||||
if (bucket->minute_key != key) {
|
||||
bucket->minute_key = key;
|
||||
bucket->airtime_us = 0;
|
||||
}
|
||||
|
||||
if (UINT64_MAX - bucket->airtime_us < airtime_us) {
|
||||
bucket->airtime_us = UINT64_MAX;
|
||||
} else {
|
||||
bucket->airtime_us += airtime_us;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define DUTY_LEDGER_BUCKET_US 60000000ULL
|
||||
#define DUTY_LEDGER_WINDOW_US 3600000000ULL
|
||||
#define DUTY_LEDGER_BUCKETS 61
|
||||
|
||||
typedef struct {
|
||||
uint64_t minute_key; // uptime minute + 1; zero means unused
|
||||
uint64_t airtime_us;
|
||||
} duty_ledger_bucket_t;
|
||||
|
||||
typedef struct {
|
||||
duty_ledger_bucket_t buckets[DUTY_LEDGER_BUCKETS];
|
||||
} duty_ledger_t;
|
||||
|
||||
// Minute buckets conservatively include the whole oldest overlapping minute.
|
||||
// The result can over-count by less than one minute, but never drops airtime
|
||||
// that may still be inside the rolling-hour window.
|
||||
uint64_t duty_ledger_used(const duty_ledger_t *ledger, int64_t now_us);
|
||||
void duty_ledger_record(duty_ledger_t *ledger, int64_t now_us,
|
||||
uint32_t airtime_us);
|
||||
@@ -0,0 +1,110 @@
|
||||
// Classic public-domain 5x7 bitmap font, ASCII 0x20..0x7E.
|
||||
// Each glyph is 5 column bytes; bit 0 = top pixel row. Rendered into a
|
||||
// 6x8 cell (1 blank spacer column, 1 blank pixel row).
|
||||
// Host-verified by firmware/test/test_font_render.c (ASCII-art dump).
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define FONT5X7_FIRST 0x20
|
||||
#define FONT5X7_LAST 0x7E
|
||||
#define FONT5X7_W 5
|
||||
#define FONT5X7_H 7
|
||||
|
||||
static const uint8_t font5x7[95][5] = {
|
||||
{0x00, 0x00, 0x00, 0x00, 0x00}, // ' '
|
||||
{0x00, 0x00, 0x5F, 0x00, 0x00}, // '!'
|
||||
{0x00, 0x07, 0x00, 0x07, 0x00}, // '"'
|
||||
{0x14, 0x7F, 0x14, 0x7F, 0x14}, // '#'
|
||||
{0x24, 0x2A, 0x7F, 0x2A, 0x12}, // '$'
|
||||
{0x23, 0x13, 0x08, 0x64, 0x62}, // '%'
|
||||
{0x36, 0x49, 0x55, 0x22, 0x50}, // '&'
|
||||
{0x00, 0x05, 0x03, 0x00, 0x00}, // '\''
|
||||
{0x00, 0x1C, 0x22, 0x41, 0x00}, // '('
|
||||
{0x00, 0x41, 0x22, 0x1C, 0x00}, // ')'
|
||||
{0x14, 0x08, 0x3E, 0x08, 0x14}, // '*'
|
||||
{0x08, 0x08, 0x3E, 0x08, 0x08}, // '+'
|
||||
{0x00, 0x50, 0x30, 0x00, 0x00}, // ','
|
||||
{0x08, 0x08, 0x08, 0x08, 0x08}, // '-'
|
||||
{0x00, 0x60, 0x60, 0x00, 0x00}, // '.'
|
||||
{0x20, 0x10, 0x08, 0x04, 0x02}, // '/'
|
||||
{0x3E, 0x51, 0x49, 0x45, 0x3E}, // '0'
|
||||
{0x00, 0x42, 0x7F, 0x40, 0x00}, // '1'
|
||||
{0x42, 0x61, 0x51, 0x49, 0x46}, // '2'
|
||||
{0x21, 0x41, 0x45, 0x4B, 0x31}, // '3'
|
||||
{0x18, 0x14, 0x12, 0x7F, 0x10}, // '4'
|
||||
{0x27, 0x45, 0x45, 0x45, 0x39}, // '5'
|
||||
{0x3C, 0x4A, 0x49, 0x49, 0x30}, // '6'
|
||||
{0x01, 0x71, 0x09, 0x05, 0x03}, // '7'
|
||||
{0x36, 0x49, 0x49, 0x49, 0x36}, // '8'
|
||||
{0x06, 0x49, 0x49, 0x29, 0x1E}, // '9'
|
||||
{0x00, 0x36, 0x36, 0x00, 0x00}, // ':'
|
||||
{0x00, 0x56, 0x36, 0x00, 0x00}, // ';'
|
||||
{0x08, 0x14, 0x22, 0x41, 0x00}, // '<'
|
||||
{0x14, 0x14, 0x14, 0x14, 0x14}, // '='
|
||||
{0x00, 0x41, 0x22, 0x14, 0x08}, // '>'
|
||||
{0x02, 0x01, 0x51, 0x09, 0x06}, // '?'
|
||||
{0x32, 0x49, 0x79, 0x41, 0x3E}, // '@'
|
||||
{0x7E, 0x11, 0x11, 0x11, 0x7E}, // 'A'
|
||||
{0x7F, 0x49, 0x49, 0x49, 0x36}, // 'B'
|
||||
{0x3E, 0x41, 0x41, 0x41, 0x22}, // 'C'
|
||||
{0x7F, 0x41, 0x41, 0x22, 0x1C}, // 'D'
|
||||
{0x7F, 0x49, 0x49, 0x49, 0x41}, // 'E'
|
||||
{0x7F, 0x09, 0x09, 0x09, 0x01}, // 'F'
|
||||
{0x3E, 0x41, 0x49, 0x49, 0x7A}, // 'G'
|
||||
{0x7F, 0x08, 0x08, 0x08, 0x7F}, // 'H'
|
||||
{0x00, 0x41, 0x7F, 0x41, 0x00}, // 'I'
|
||||
{0x20, 0x40, 0x41, 0x3F, 0x01}, // 'J'
|
||||
{0x7F, 0x08, 0x14, 0x22, 0x41}, // 'K'
|
||||
{0x7F, 0x40, 0x40, 0x40, 0x40}, // 'L'
|
||||
{0x7F, 0x02, 0x0C, 0x02, 0x7F}, // 'M'
|
||||
{0x7F, 0x04, 0x08, 0x10, 0x7F}, // 'N'
|
||||
{0x3E, 0x41, 0x41, 0x41, 0x3E}, // 'O'
|
||||
{0x7F, 0x09, 0x09, 0x09, 0x06}, // 'P'
|
||||
{0x3E, 0x41, 0x51, 0x21, 0x5E}, // 'Q'
|
||||
{0x7F, 0x09, 0x19, 0x29, 0x46}, // 'R'
|
||||
{0x46, 0x49, 0x49, 0x49, 0x31}, // 'S'
|
||||
{0x01, 0x01, 0x7F, 0x01, 0x01}, // 'T'
|
||||
{0x3F, 0x40, 0x40, 0x40, 0x3F}, // 'U'
|
||||
{0x1F, 0x20, 0x40, 0x20, 0x1F}, // 'V'
|
||||
{0x3F, 0x40, 0x38, 0x40, 0x3F}, // 'W'
|
||||
{0x63, 0x14, 0x08, 0x14, 0x63}, // 'X'
|
||||
{0x07, 0x08, 0x70, 0x08, 0x07}, // 'Y'
|
||||
{0x61, 0x51, 0x49, 0x45, 0x43}, // 'Z'
|
||||
{0x00, 0x7F, 0x41, 0x41, 0x00}, // '['
|
||||
{0x02, 0x04, 0x08, 0x10, 0x20}, // '\\'
|
||||
{0x00, 0x41, 0x41, 0x7F, 0x00}, // ']'
|
||||
{0x04, 0x02, 0x01, 0x02, 0x04}, // '^'
|
||||
{0x40, 0x40, 0x40, 0x40, 0x40}, // '_'
|
||||
{0x00, 0x01, 0x02, 0x04, 0x00}, // '`'
|
||||
{0x20, 0x54, 0x54, 0x54, 0x78}, // 'a'
|
||||
{0x7F, 0x48, 0x44, 0x44, 0x38}, // 'b'
|
||||
{0x38, 0x44, 0x44, 0x44, 0x20}, // 'c'
|
||||
{0x38, 0x44, 0x44, 0x48, 0x7F}, // 'd'
|
||||
{0x38, 0x54, 0x54, 0x54, 0x18}, // 'e'
|
||||
{0x08, 0x7E, 0x09, 0x01, 0x02}, // 'f'
|
||||
{0x0C, 0x52, 0x52, 0x52, 0x3E}, // 'g'
|
||||
{0x7F, 0x08, 0x04, 0x04, 0x78}, // 'h'
|
||||
{0x00, 0x44, 0x7D, 0x40, 0x00}, // 'i'
|
||||
{0x20, 0x40, 0x44, 0x3D, 0x00}, // 'j'
|
||||
{0x7F, 0x10, 0x28, 0x44, 0x00}, // 'k'
|
||||
{0x00, 0x41, 0x7F, 0x40, 0x00}, // 'l'
|
||||
{0x7C, 0x04, 0x18, 0x04, 0x78}, // 'm'
|
||||
{0x7C, 0x08, 0x04, 0x04, 0x78}, // 'n'
|
||||
{0x38, 0x44, 0x44, 0x44, 0x38}, // 'o'
|
||||
{0x7C, 0x14, 0x14, 0x14, 0x08}, // 'p'
|
||||
{0x08, 0x14, 0x14, 0x18, 0x7C}, // 'q'
|
||||
{0x7C, 0x08, 0x04, 0x04, 0x08}, // 'r'
|
||||
{0x48, 0x54, 0x54, 0x54, 0x20}, // 's'
|
||||
{0x04, 0x3F, 0x44, 0x40, 0x20}, // 't'
|
||||
{0x3C, 0x40, 0x40, 0x20, 0x7C}, // 'u'
|
||||
{0x1C, 0x20, 0x40, 0x20, 0x1C}, // 'v'
|
||||
{0x3C, 0x40, 0x30, 0x40, 0x3C}, // 'w'
|
||||
{0x44, 0x28, 0x10, 0x28, 0x44}, // 'x'
|
||||
{0x0C, 0x50, 0x50, 0x50, 0x3C}, // 'y'
|
||||
{0x44, 0x64, 0x54, 0x4C, 0x44}, // 'z'
|
||||
{0x00, 0x08, 0x36, 0x41, 0x00}, // '{'
|
||||
{0x00, 0x00, 0x7F, 0x00, 0x00}, // '|'
|
||||
{0x00, 0x41, 0x36, 0x08, 0x00}, // '}'
|
||||
{0x08, 0x04, 0x08, 0x10, 0x08}, // '~'
|
||||
};
|
||||
@@ -5,6 +5,10 @@
|
||||
#include "esp_timer.h"
|
||||
#include "repeater.h"
|
||||
#include "led.h"
|
||||
#include "ui.h"
|
||||
#include "cfg_store.h"
|
||||
#include "settings.h"
|
||||
#include "wifi_debug.h"
|
||||
|
||||
void console_start(void);
|
||||
|
||||
@@ -14,6 +18,10 @@ void app_main(void)
|
||||
"\"reset_reason\":%d}\n", __DATE__, __TIME__, (int)esp_reset_reason());
|
||||
fflush(stdout);
|
||||
led_init(); // solid ON = powered, initialising
|
||||
cfg_store_init();
|
||||
settings_init();
|
||||
console_start();
|
||||
repeater_start(); // led_boot_done() fires once the radio is in RX
|
||||
wifi_debug_init(); // control task only; AP is off until OLED enables it
|
||||
ui_start(); // OLED + button; non-fatal if absent
|
||||
}
|
||||
|
||||
+483
-120
@@ -3,6 +3,9 @@
|
||||
#include "wmbus.h"
|
||||
#include "board.h"
|
||||
#include "led.h"
|
||||
#include "duty_ledger.h"
|
||||
#include "debug_history.h"
|
||||
#include "settings.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
@@ -35,63 +38,129 @@ repeater_cfg_t g_cfg = {
|
||||
#else
|
||||
.verbose = false,
|
||||
#endif
|
||||
.fem_rx_csd = true,
|
||||
.preamble_bits = 8,
|
||||
.test_lfield = 19,
|
||||
.whitelist = {0},
|
||||
.whitelist_len = 0,
|
||||
};
|
||||
repeater_stats_t g_stats;
|
||||
repeater_ui_t g_ui;
|
||||
|
||||
static TaskHandle_t s_task;
|
||||
static volatile int64_t s_irq_ts;
|
||||
static volatile bool s_want_radio_reset;
|
||||
static volatile bool s_want_test_tx;
|
||||
static volatile bool s_want_test_tx_t1;
|
||||
static volatile bool s_want_probe;
|
||||
static volatile bool s_want_test_burst;
|
||||
static volatile int s_inject; // 1 = standby, 2 = sleep (config loss)
|
||||
static uint8_t s_test_access_nr;
|
||||
static uint8_t s_test_lfield = 19;
|
||||
static uint32_t s_seq;
|
||||
static int64_t s_last_beacon;
|
||||
|
||||
static struct { uint32_t hash; int64_t ts; } s_dup[DUP_RING];
|
||||
static int s_dup_idx;
|
||||
|
||||
// Rolling-hour TX airtime ledger for the duty-cycle guard. At 0.1 % and
|
||||
// ~13 ms per repeat the hourly ceiling is ~270 transmissions, so this ring
|
||||
// cannot overflow within the window.
|
||||
#define DUTY_RING 384
|
||||
#define DUTY_WINDOW_US 3600000000LL
|
||||
static struct { int64_t ts; uint32_t airtime_us; } s_duty[DUTY_RING];
|
||||
static int s_duty_idx;
|
||||
// Minute buckets retain every transmission in the rolling hour without an
|
||||
// event-count limit. The oldest partial minute is included in full, so the
|
||||
// compliance guard can over-count slightly but cannot silently under-count.
|
||||
static duty_ledger_t s_duty;
|
||||
|
||||
// Cached radio-task health. heartbeat_us is the last existing hardware probe;
|
||||
// sampled_at_us also advances on idle loops without any new SPI/UI queries.
|
||||
// Recovery count is boot-lifetime, independent of clear_stats.
|
||||
static debug_status_t s_debug_status;
|
||||
|
||||
static void publish_debug_status(void)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
s_debug_status.sampled_at_us = now;
|
||||
s_debug_status.duty_used_us = duty_ledger_used(&s_duty, now);
|
||||
s_debug_status.duty_budget_us = (uint64_t)g_cfg.duty_budget_ppm
|
||||
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
|
||||
s_debug_status.repeat_delay_ms = g_cfg.repeat_delay_ms;
|
||||
s_debug_status.repeat_enabled = g_cfg.repeat_enabled;
|
||||
debug_history_publish_status(&s_debug_status);
|
||||
}
|
||||
|
||||
static debug_record_t debug_record_init(const char *source, const char *mode,
|
||||
const char *format, int64_t timestamp_us)
|
||||
{
|
||||
// Zero timestamps mean no TX attempt; zero identity fields are absent
|
||||
// unless identity_present is set. Synthetic RSSI/CRC are not measurements.
|
||||
return (debug_record_t) {
|
||||
.timestamp_us = timestamp_us,
|
||||
.source = source,
|
||||
.mode = mode,
|
||||
.format = format,
|
||||
.reception = "not_applicable",
|
||||
.outcome = "encode_failed",
|
||||
};
|
||||
}
|
||||
|
||||
static void debug_identity(debug_record_t *record, const uint8_t *frame, int length)
|
||||
{
|
||||
// Link-layer L,C,M,A header only, before any hop mutation. Rejected
|
||||
// frames may carry an untrusted identity, but never read beyond capture.
|
||||
if (length < 10) return;
|
||||
record->manufacturer = (uint16_t)frame[2] | ((uint16_t)frame[3] << 8);
|
||||
record->meter_id = (uint32_t)frame[4] | ((uint32_t)frame[5] << 8)
|
||||
| ((uint32_t)frame[6] << 16) | ((uint32_t)frame[7] << 24);
|
||||
record->version = frame[8];
|
||||
record->device_type = frame[9];
|
||||
record->identity_present = true;
|
||||
}
|
||||
|
||||
static void debug_frame(debug_record_t *record, const uint8_t *frame, int length)
|
||||
{
|
||||
record->length = (uint16_t)length;
|
||||
record->hash = wmbus_hash(frame, (size_t)length);
|
||||
debug_identity(record, frame, length);
|
||||
}
|
||||
|
||||
static void debug_rx_rejected(debug_record_t *record, const char *reason,
|
||||
const uint8_t *bytes, int length)
|
||||
{
|
||||
record->reception = reason;
|
||||
record->outcome = reason;
|
||||
// Undecoded captures hash their available physical bytes; decoded rows
|
||||
// hash the original complete frame including CRCs, excluding mode bytes.
|
||||
// length always counts the bytes hashed, not an untrusted declared size.
|
||||
if (length > 0) {
|
||||
record->length = (uint16_t)length;
|
||||
record->hash = wmbus_hash(bytes, (size_t)length);
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t tx_airtime_us(int payload_bytes)
|
||||
{
|
||||
// 48-bit preamble + 16-bit sync + payload at 100 kbps.
|
||||
return (uint32_t)(payload_bytes * US_PER_BYTE + 640);
|
||||
}
|
||||
|
||||
static uint64_t duty_used_us(int64_t now)
|
||||
{
|
||||
uint64_t sum = 0;
|
||||
for (int i = 0; i < DUTY_RING; i++) {
|
||||
if (s_duty[i].airtime_us && now - s_duty[i].ts < DUTY_WINDOW_US) {
|
||||
sum += s_duty[i].airtime_us;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
return duty_ledger_used(&s_duty, now);
|
||||
}
|
||||
|
||||
static void duty_record(int64_t now, uint32_t airtime_us)
|
||||
uint64_t repeater_duty_used_us(void)
|
||||
{
|
||||
s_duty[s_duty_idx].ts = now;
|
||||
s_duty[s_duty_idx].airtime_us = airtime_us;
|
||||
s_duty_idx = (s_duty_idx + 1) % DUTY_RING;
|
||||
return duty_ledger_used(&s_duty, esp_timer_get_time());
|
||||
}
|
||||
|
||||
// Would transmitting `bytes` now exceed the configured rolling-hour budget?
|
||||
static bool duty_would_exceed(int64_t now, int bytes, uint64_t *used_out,
|
||||
uint64_t *budget_out)
|
||||
{
|
||||
uint64_t budget_us = (uint64_t)g_cfg.duty_budget_ppm * 3600000000ULL / 1000000ULL;
|
||||
uint64_t budget_us = (uint64_t)g_cfg.duty_budget_ppm
|
||||
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
|
||||
uint64_t used = duty_used_us(now);
|
||||
uint32_t want = (uint32_t)(bytes * US_PER_BYTE + 640);
|
||||
uint32_t want = tx_airtime_us(bytes);
|
||||
if (used_out) *used_out = used;
|
||||
if (budget_out) *budget_out = budget_us;
|
||||
if (g_cfg.duty_budget_ppm == 0) return false;
|
||||
return (used + want) > budget_us;
|
||||
return used > budget_us || want > budget_us - used;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ logging
|
||||
@@ -116,6 +185,11 @@ static void irq_cb(int64_t ts)
|
||||
portYIELD_FROM_ISR(hp);
|
||||
}
|
||||
|
||||
static uint8_t preamble_detect_code(uint8_t bits)
|
||||
{
|
||||
return bits ? (uint8_t)(bits / 8 + 3) : 0;
|
||||
}
|
||||
|
||||
static bool radio_full_init(void)
|
||||
{
|
||||
sx126x_diag_t diag;
|
||||
@@ -137,6 +211,9 @@ static bool radio_full_init(void)
|
||||
diag.device_errors, diag.chip_mode,
|
||||
(int)g_cfg.tx_power_dbm,
|
||||
cfg_ok ? "ok" : "fail");
|
||||
s_debug_status.chip_mode = diag.chip_mode;
|
||||
s_debug_status.config_intact = cfg_ok;
|
||||
publish_debug_status();
|
||||
return cfg_ok;
|
||||
}
|
||||
|
||||
@@ -145,6 +222,7 @@ static bool radio_full_init(void)
|
||||
static bool recover(const char *reason, int level)
|
||||
{
|
||||
g_stats.recoveries++;
|
||||
s_debug_status.recoveries++;
|
||||
led_notify_fault();
|
||||
bool ok = false;
|
||||
switch (level) {
|
||||
@@ -174,6 +252,9 @@ static bool recover(const char *reason, int level)
|
||||
ok = radio_full_init() && sx126x_set_rx() && sx126x_config_intact();
|
||||
break;
|
||||
default:
|
||||
s_debug_status.chip_mode = 0;
|
||||
s_debug_status.config_intact = false;
|
||||
publish_debug_status();
|
||||
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
|
||||
"\"result\":\"mcu_reset\"", reason, level);
|
||||
fflush(stdout);
|
||||
@@ -182,6 +263,10 @@ static bool recover(const char *reason, int level)
|
||||
}
|
||||
LOGJ("\"event\":\"radio_recovery\",\"reason\":\"%s\",\"level\":%d,"
|
||||
"\"result\":\"%s\"", reason, level, ok ? "rx_restored" : "failed");
|
||||
// Reuse the ladder's existing observations; zero means unknown on failure.
|
||||
s_debug_status.chip_mode = ok ? 0x5 : 0;
|
||||
s_debug_status.config_intact = ok;
|
||||
publish_debug_status();
|
||||
return ok;
|
||||
}
|
||||
|
||||
@@ -221,15 +306,6 @@ static bool whitelist_pass(const uint8_t *frame)
|
||||
return false;
|
||||
}
|
||||
|
||||
// Wait for DIO1 with timeout; returns IRQ mask (0 on timeout).
|
||||
static uint16_t wait_irq(uint32_t timeout_ms)
|
||||
{
|
||||
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(timeout_ms)) == 0) return 0;
|
||||
uint16_t irq = sx126x_get_irq();
|
||||
sx126x_clear_irq(irq);
|
||||
return irq;
|
||||
}
|
||||
|
||||
static void precise_delay_until(int64_t target_us)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
@@ -240,18 +316,26 @@ static void precise_delay_until(int64_t target_us)
|
||||
|
||||
// ------------------------------------------------------------------ TX
|
||||
|
||||
// Transmit mode bytes + frame. Returns result string for logging.
|
||||
static const char *do_tx(const uint8_t *payload, int payload_len,
|
||||
int64_t *tx_start_us, int64_t *tx_done_us)
|
||||
// Transmit a physical radio payload. For C-mode that is mode bytes +
|
||||
// frame; for T-mode the 3-of-6 coded stream. Returns result string.
|
||||
static const char *do_tx_raw(const uint8_t *payload, int payload_len,
|
||||
bool t1, int64_t *tx_start_us, int64_t *tx_done_us,
|
||||
debug_record_t *record)
|
||||
{
|
||||
g_stats.tx_attempts++;
|
||||
// Software TX-operation start includes the driver's SPI setup. Completion
|
||||
// is the actual IRQ timestamp or the time polling observes the result,
|
||||
// never a delay/airtime estimate. No RF-start timestamp is exposed by SPI.
|
||||
*tx_start_us = esp_timer_get_time();
|
||||
if (!sx126x_start_tx(payload, (uint8_t)payload_len)) {
|
||||
*tx_done_us = *tx_start_us;
|
||||
record->tx_start_us = *tx_start_us;
|
||||
if (!sx126x_start_tx_mode(payload, (uint8_t)payload_len, t1)) {
|
||||
record->tx_done_us = esp_timer_get_time();
|
||||
g_stats.tx_failures++;
|
||||
return "start_failed";
|
||||
}
|
||||
// airtime: 48 bit preamble + 16 bit sync + payload -> ~80us/byte + 640
|
||||
uint32_t airtime_ms = (payload_len * US_PER_BYTE + 640) / 1000;
|
||||
const uint32_t airtime_us = tx_airtime_us(payload_len);
|
||||
const uint32_t airtime_ms = (airtime_us + 999) / 1000;
|
||||
// Instrumented wait: poll IRQ flags, DIO1 level and chip mode while
|
||||
// also honoring the ISR notification. Gives ground truth about the
|
||||
// TX sequence even when the interrupt path is broken.
|
||||
@@ -270,6 +354,12 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
}
|
||||
*tx_done_us = notify_seen ? s_irq_ts : esp_timer_get_time();
|
||||
// Leave legacy log/delay inputs unchanged, but do not attach a stale or
|
||||
// unrelated RX notification timestamp to this record's TX completion.
|
||||
record->tx_done_us = !notify_seen
|
||||
|| ((irq & (SX126X_IRQ_TX_DONE | SX126X_IRQ_TIMEOUT))
|
||||
&& *tx_done_us >= *tx_start_us)
|
||||
? *tx_done_us : esp_timer_get_time();
|
||||
fem_set_tx(false);
|
||||
sx126x_clear_irq(SX126X_IRQ_ALL);
|
||||
#ifdef CONFIG_WMBUS_TX_DIAG_ALWAYS
|
||||
@@ -287,9 +377,8 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
|
||||
if (irq & SX126X_IRQ_TX_DONE) {
|
||||
g_stats.tx_success++;
|
||||
led_notify_tx();
|
||||
if (*tx_done_us > *tx_start_us) {
|
||||
g_stats.tx_airtime_us += (uint64_t)(*tx_done_us - *tx_start_us);
|
||||
}
|
||||
g_stats.tx_airtime_us += airtime_us;
|
||||
duty_ledger_record(&s_duty, *tx_start_us, airtime_us);
|
||||
return notify_seen ? "ok" : "ok_polled";
|
||||
}
|
||||
if (irq & SX126X_IRQ_TIMEOUT) {
|
||||
@@ -300,17 +389,31 @@ static const char *do_tx(const uint8_t *payload, int payload_len,
|
||||
return "irq_timeout";
|
||||
}
|
||||
|
||||
static void log_tx(const char *result, uint32_t hash, int len,
|
||||
int64_t rx_ts, int64_t tx_start, int64_t tx_done,
|
||||
const uint8_t *payload, int payload_len)
|
||||
static const char *do_tx(const uint8_t *payload, int payload_len, bool t1,
|
||||
int64_t *tx_start_us, int64_t *tx_done_us,
|
||||
debug_record_t *record)
|
||||
{
|
||||
const char *res = do_tx_raw(payload, payload_len, t1,
|
||||
tx_start_us, tx_done_us, record);
|
||||
record->outcome = res;
|
||||
// UI snapshot: single writer (this task), lock-free readers.
|
||||
strlcpy(g_ui.tx_result, res, sizeof(g_ui.tx_result));
|
||||
g_ui.tx_ts_us = *tx_done_us;
|
||||
return res;
|
||||
}
|
||||
|
||||
static void log_tx(const char *result, uint32_t hash, int len, int phys_len,
|
||||
const char *mode, int64_t rx_ts, int64_t tx_start,
|
||||
int64_t tx_done, const uint8_t *payload, int payload_len)
|
||||
{
|
||||
printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_tx\",\"timestamp_us\":%lld,"
|
||||
"\"source_rx_timestamp_us\":%lld,\"delay_us\":%lld,"
|
||||
"\"length\":%d,\"hash\":\"%08" PRIx32 "\","
|
||||
"\"configured_tx_dbm\":%d,\"airtime_us\":%lld,\"result\":\"%s\"",
|
||||
"\"length\":%d,\"mode\":\"%s\",\"hash\":\"%08" PRIx32 "\","
|
||||
"\"configured_tx_dbm\":%d,\"airtime_us\":%" PRIu32 ","
|
||||
"\"tx_operation_us\":%lld,\"result\":\"%s\"",
|
||||
s_seq++, (long long)tx_start, (long long)rx_ts,
|
||||
(long long)(tx_start - rx_ts), len, hash,
|
||||
(int)g_cfg.tx_power_dbm,
|
||||
(long long)(tx_start - rx_ts), len, mode, hash,
|
||||
(int)g_cfg.tx_power_dbm, tx_airtime_us(phys_len),
|
||||
(long long)(tx_done > tx_start ? tx_done - tx_start : 0), result);
|
||||
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
|
||||
if (payload && payload_len > 0) {
|
||||
@@ -327,24 +430,68 @@ static void log_tx(const char *result, uint32_t hash, int len,
|
||||
|
||||
static void run_test_tx(void)
|
||||
{
|
||||
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
|
||||
uint8_t frame[256];
|
||||
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
|
||||
s_test_lfield);
|
||||
if (n < 0) return;
|
||||
g_cfg.test_lfield);
|
||||
if (n < 0) {
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
static uint8_t payload[258];
|
||||
payload[0] = WMBUS_MODE_BYTE_A_HI;
|
||||
payload[1] = WMBUS_MODE_BYTE_A_LO;
|
||||
memcpy(payload + 2, frame, n);
|
||||
uint32_t hash = wmbus_hash(frame, n);
|
||||
debug_frame(&record, frame, n);
|
||||
uint32_t hash = record.hash;
|
||||
|
||||
int64_t t0, t1;
|
||||
const char *res = do_tx(payload, n + 2, &t0, &t1);
|
||||
log_tx(res, hash, n, t0, t0, t1, NULL, 0);
|
||||
const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
|
||||
log_tx(res, hash, n, n + 2, "C1", t0, t0, t1, NULL, 0);
|
||||
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"lfield\":%u,\"raw\":\"",
|
||||
s_seq++, s_test_lfield);
|
||||
s_seq++, g_cfg.test_lfield);
|
||||
print_hex(frame, n);
|
||||
printf("\"}\n");
|
||||
fflush(stdout);
|
||||
record.timestamp_us = t0;
|
||||
debug_history_record(&record);
|
||||
|
||||
sx126x_restore_rx_payload_len();
|
||||
if (!sx126x_set_rx()) recover_ladder("test_tx_rx_restore");
|
||||
}
|
||||
|
||||
// Synthetic T1 transmission: the same OMS test frame, 3-of-6 coded and
|
||||
// sent with T-mode deviation. Proves the T TX chain against rtl_wmbus
|
||||
// ("T1;..." decode of SLN 00000001) without needing T-mode meter traffic.
|
||||
static void run_test_tx_t1(void)
|
||||
{
|
||||
debug_record_t record = debug_record_init("test", "T1", "A", esp_timer_get_time());
|
||||
uint8_t frame[192];
|
||||
uint8_t lf = g_cfg.test_lfield > 140 ? 140 : g_cfg.test_lfield; // coded <= 255
|
||||
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++, lf);
|
||||
if (n < 0) {
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
debug_frame(&record, frame, n);
|
||||
static uint8_t coded[300];
|
||||
int clen = wmbus_3of6_encode(frame, n, coded, sizeof(coded));
|
||||
if (clen < 0 || clen > 255) {
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
uint32_t hash = record.hash;
|
||||
|
||||
int64_t t0, t1;
|
||||
const char *res = do_tx(coded, clen, true, &t0, &t1, &record);
|
||||
log_tx(res, hash, n, clen, "T1", t0, t0, t1, NULL, 0);
|
||||
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_tx_frame\",\"mode\":\"T1\","
|
||||
"\"lfield\":%u,\"coded_len\":%d,\"raw\":\"", s_seq++, lf, clen);
|
||||
print_hex(frame, n);
|
||||
printf("\"}\n");
|
||||
fflush(stdout);
|
||||
record.timestamp_us = t0;
|
||||
debug_history_record(&record);
|
||||
|
||||
sx126x_restore_rx_payload_len();
|
||||
if (!sx126x_set_rx()) recover_ladder("test_tx_rx_restore");
|
||||
@@ -355,16 +502,23 @@ static void run_test_tx(void)
|
||||
// Respects the duty guard; suppressed beacons skip to the next period.
|
||||
static void run_beacon(void)
|
||||
{
|
||||
debug_record_t record = debug_record_init("beacon", "C1", "A", esp_timer_get_time());
|
||||
uint8_t frame[256];
|
||||
uint8_t acc = s_test_access_nr++;
|
||||
int n = wmbus_build_test_frame(frame, sizeof(frame), acc, s_test_lfield);
|
||||
if (n < 0) return;
|
||||
int n = wmbus_build_test_frame(frame, sizeof(frame), acc, g_cfg.test_lfield);
|
||||
if (n < 0) {
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
uint64_t duty_used = 0, duty_budget = 0;
|
||||
if (duty_would_exceed(esp_timer_get_time(), n + 2, &duty_used, &duty_budget)) {
|
||||
g_stats.tx_suppressed_duty++;
|
||||
LOGJ("\"event\":\"beacon_suppressed\",\"reason\":\"duty_cycle\","
|
||||
"\"used_us\":%llu,\"budget_us\":%llu",
|
||||
(unsigned long long)duty_used, (unsigned long long)duty_budget);
|
||||
debug_frame(&record, frame, n);
|
||||
record.outcome = "duty_cycle";
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
static uint8_t payload[258];
|
||||
@@ -373,11 +527,13 @@ static void run_beacon(void)
|
||||
memcpy(payload + 2, frame, n);
|
||||
|
||||
int64_t t0, t1;
|
||||
const char *res = do_tx(payload, n + 2, &t0, &t1);
|
||||
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
|
||||
const char *res = do_tx(payload, n + 2, false, &t0, &t1, &record);
|
||||
LOGJ("\"event\":\"beacon\",\"acc\":%u,\"lfield\":%u,\"result\":\"%s\","
|
||||
"\"timestamp_us\":%lld,\"tx_done_us\":%lld",
|
||||
acc, s_test_lfield, res, (long long)t0, (long long)t1);
|
||||
acc, g_cfg.test_lfield, res, (long long)t0, (long long)t1);
|
||||
debug_frame(&record, frame, n);
|
||||
record.timestamp_us = t0;
|
||||
debug_history_record(&record);
|
||||
|
||||
sx126x_restore_rx_payload_len();
|
||||
if (!sx126x_set_rx()) recover_ladder("beacon_rx_restore");
|
||||
@@ -389,33 +545,45 @@ static void run_beacon(void)
|
||||
// from anything in the RX path.
|
||||
static void run_test_burst(void)
|
||||
{
|
||||
debug_record_t record = debug_record_init("test", "C1", "A", esp_timer_get_time());
|
||||
uint8_t frame[256];
|
||||
int n = wmbus_build_test_frame(frame, sizeof(frame), s_test_access_nr++,
|
||||
s_test_lfield);
|
||||
if (n < 0) return;
|
||||
g_cfg.test_lfield);
|
||||
if (n < 0) {
|
||||
debug_history_record(&record);
|
||||
return;
|
||||
}
|
||||
static uint8_t payload[258];
|
||||
payload[0] = WMBUS_MODE_BYTE_A_HI;
|
||||
payload[1] = WMBUS_MODE_BYTE_A_LO;
|
||||
memcpy(payload + 2, frame, n);
|
||||
uint32_t hash = wmbus_hash(frame, n);
|
||||
debug_frame(&record, frame, n);
|
||||
uint32_t hash = record.hash;
|
||||
debug_record_t second = record;
|
||||
|
||||
printf("{\"seq\":%" PRIu32 ",\"event\":\"test_burst_frame\",\"lfield\":%u,"
|
||||
"\"delay_ms\":%" PRIu32 ",\"raw\":\"",
|
||||
s_seq++, s_test_lfield, g_cfg.repeat_delay_ms);
|
||||
s_seq++, g_cfg.test_lfield, g_cfg.repeat_delay_ms);
|
||||
print_hex(frame, n);
|
||||
printf("\"}\n");
|
||||
fflush(stdout);
|
||||
|
||||
int64_t t0, t1;
|
||||
const char *r1 = do_tx(payload, n + 2, &t0, &t1);
|
||||
const char *r1 = do_tx(payload, n + 2, false, &t0, &t1, &record);
|
||||
int64_t first_end = t1 > t0 ? t1 : esp_timer_get_time();
|
||||
log_tx(r1, hash, n, t0, t0, t1, NULL, 0);
|
||||
log_tx(r1, hash, n, n + 2, "C1", t0, t0, t1, NULL, 0);
|
||||
|
||||
precise_delay_until(first_end + (int64_t)g_cfg.repeat_delay_ms * 1000);
|
||||
|
||||
int64_t t2, t3;
|
||||
const char *r2 = do_tx(payload, n + 2, &t2, &t3);
|
||||
log_tx(r2, hash, n, first_end, t2, t3, NULL, 0);
|
||||
const char *r2 = do_tx(payload, n + 2, false, &t2, &t3, &second);
|
||||
log_tx(r2, hash, n, n + 2, "C1", first_end, t2, t3, NULL, 0);
|
||||
// Publish both immutable synthetic outcomes after the second TX, so no
|
||||
// history lock or extra serial output intrudes on the inter-burst delay.
|
||||
record.timestamp_us = t0;
|
||||
debug_history_record(&record);
|
||||
second.timestamp_us = t2;
|
||||
debug_history_record(&second);
|
||||
|
||||
sx126x_restore_rx_payload_len();
|
||||
if (!sx126x_set_rx()) recover_ladder("test_burst_rx_restore");
|
||||
@@ -432,6 +600,7 @@ static void hexdump_json(const char *key, const uint8_t *d, int n)
|
||||
// Scripted low-level diagnostic with raw SPI response dumps.
|
||||
static void run_probe(void)
|
||||
{
|
||||
debug_record_t record = debug_record_init("test", "C1", "A", 0);
|
||||
uint8_t r[16];
|
||||
|
||||
printf("{\"event\":\"probe\",");
|
||||
@@ -453,16 +622,29 @@ static void run_probe(void)
|
||||
|
||||
// small TX: 8 byte payload
|
||||
uint8_t pkt[8] = {0x54, 0xCD, 0xAA, 0x55, 0xDE, 0xAD, 0xBE, 0xEF};
|
||||
sx126x_start_tx(pkt, 8);
|
||||
record.tx_start_us = esp_timer_get_time();
|
||||
record.timestamp_us = record.tx_start_us;
|
||||
bool started = sx126x_start_tx(pkt, 8);
|
||||
record.outcome = started ? "irq_timeout" : "start_failed";
|
||||
if (!started) record.tx_done_us = esp_timer_get_time();
|
||||
printf("\"txpoll\":[");
|
||||
for (int i = 0; i < 12; i++) {
|
||||
vTaskDelay(pdMS_TO_TICKS(2));
|
||||
uint8_t s2[2], q[4];
|
||||
sx126x_raw(0xC0, NULL, 0, s2, 2);
|
||||
sx126x_raw(0x12, NULL, 0, q, 4);
|
||||
bool irq_read = sx126x_raw(0x12, NULL, 0, q, 4);
|
||||
// Observe the probe's existing polls without changing its diagnostic
|
||||
// window or injecting normal TX waits/duty policy into this command.
|
||||
uint16_t irq = irq_read ? ((uint16_t)q[2] << 8) | q[3] : 0;
|
||||
if (started && record.tx_done_us == 0
|
||||
&& (irq & (SX126X_IRQ_TX_DONE | SX126X_IRQ_TIMEOUT))) {
|
||||
record.tx_done_us = esp_timer_get_time();
|
||||
record.outcome = irq & SX126X_IRQ_TX_DONE ? "ok_polled" : "radio_timeout";
|
||||
}
|
||||
printf("\"%02X-%02X%02X%02X%02X\"%s", s2[1], q[0], q[1], q[2], q[3],
|
||||
i < 11 ? "," : "");
|
||||
}
|
||||
if (record.tx_done_us == 0) record.tx_done_us = esp_timer_get_time();
|
||||
printf("],");
|
||||
fem_set_tx(false);
|
||||
|
||||
@@ -474,6 +656,8 @@ static void run_probe(void)
|
||||
sx126x_set_rx();
|
||||
printf("\"done\":true}\n");
|
||||
fflush(stdout);
|
||||
debug_frame(&record, pkt + 2, sizeof(pkt) - 2);
|
||||
debug_history_record(&record);
|
||||
}
|
||||
|
||||
|
||||
@@ -481,52 +665,126 @@ static void run_probe(void)
|
||||
|
||||
static void handle_rx(int64_t rxdone_ts)
|
||||
{
|
||||
debug_record_t record = debug_record_init("rx", "unknown", "unknown", rxdone_ts);
|
||||
bool restore_rx = false;
|
||||
bool read_failed = false;
|
||||
static uint8_t buf[RX_PAYLOAD_LEN];
|
||||
int8_t rssi = 0;
|
||||
int n = sx126x_read_rx(buf, sizeof(buf), &rssi);
|
||||
record.rssi_dbm = rssi;
|
||||
if (n < 3) {
|
||||
recover_ladder("rx_read_failed");
|
||||
return;
|
||||
debug_rx_rejected(&record, "rx_read_failed", buf, n);
|
||||
read_failed = true;
|
||||
goto done;
|
||||
}
|
||||
g_stats.rx_candidates++;
|
||||
g_stats.rx_bytes += n;
|
||||
|
||||
// Classify: C-mode announces itself with two NRZ mode bytes right
|
||||
// after the shared 0x543D access code; T-mode continues with 3-of-6
|
||||
// coded data directly, so a T1 frame's L-field is the first decoded
|
||||
// byte of the capture. T1 uses format A framing only.
|
||||
wmbus_frame_fmt_t fmt = wmbus_frame_format(buf[0], buf[1]);
|
||||
if (fmt == WMBUS_FRAME_UNKNOWN) {
|
||||
g_stats.rx_not_c1++;
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"not_c1\","
|
||||
"\"mode_bytes\":\"%02X%02X\",\"rssi_dbm\":%d", buf[0], buf[1], rssi);
|
||||
}
|
||||
return;
|
||||
}
|
||||
bool t1 = false;
|
||||
bool identity_available = true;
|
||||
uint8_t *frame;
|
||||
int total;
|
||||
int onair_len; // physical radio-payload bytes on air
|
||||
bool crc_ok;
|
||||
static uint8_t t1frame[192]; // decoded T1 frame; coded fits 255 => total <= 170
|
||||
|
||||
int total = wmbus_frame_total_len(fmt, buf[2]);
|
||||
if (fmt != WMBUS_FRAME_UNKNOWN) {
|
||||
record.mode = "C1";
|
||||
record.format = fmt == WMBUS_FRAME_A ? "A" : "B";
|
||||
total = wmbus_frame_total_len(fmt, buf[2]);
|
||||
if (total < 0 || total + 2 > n) {
|
||||
g_stats.rx_len_invalid++;
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"bad_length\","
|
||||
"\"lfield\":%u,\"rssi_dbm\":%d", buf[2], rssi);
|
||||
}
|
||||
return;
|
||||
debug_rx_rejected(&record, "bad_length", buf + 2, n - 2);
|
||||
debug_identity(&record, buf + 2, n - 2);
|
||||
goto done;
|
||||
}
|
||||
frame = buf + 2;
|
||||
onair_len = total + 2;
|
||||
crc_ok = wmbus_check_crc(fmt, frame, total);
|
||||
} else {
|
||||
int lfield = wmbus_3of6_first_byte(buf, (size_t)n);
|
||||
total = lfield >= 9
|
||||
? wmbus_frame_total_len(WMBUS_FRAME_A, (uint8_t)lfield) : -1;
|
||||
if (total < 0) {
|
||||
g_stats.rx_not_c1++;
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"not_c1\","
|
||||
"\"mode_bytes\":\"%02X%02X\",\"rssi_dbm\":%d",
|
||||
buf[0], buf[1], rssi);
|
||||
}
|
||||
debug_rx_rejected(&record, "undecodable", buf, n);
|
||||
goto done;
|
||||
}
|
||||
record.mode = "T1";
|
||||
record.format = "A";
|
||||
onair_len = wmbus_3of6_coded_len(total);
|
||||
if (onair_len > n || total > (int)sizeof(t1frame)) {
|
||||
g_stats.rx_len_invalid++;
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"wmbus_rx_drop\",\"reason\":\"t1_too_long\","
|
||||
"\"lfield\":%d,\"rssi_dbm\":%d", lfield, rssi);
|
||||
}
|
||||
debug_rx_rejected(&record, "t1_too_long", buf, n);
|
||||
// A truncated T1 capture can still have a complete clean header.
|
||||
uint8_t header[10];
|
||||
if (wmbus_3of6_decode(buf, (size_t)n, header, sizeof(header)) == 0)
|
||||
debug_identity(&record, header, sizeof(header));
|
||||
goto done;
|
||||
}
|
||||
int bad = wmbus_3of6_decode(buf, (size_t)n, t1frame, total);
|
||||
t1 = true;
|
||||
fmt = WMBUS_FRAME_A;
|
||||
frame = t1frame;
|
||||
g_stats.rx_t1++;
|
||||
crc_ok = bad == 0 && wmbus_check_crc(WMBUS_FRAME_A, frame, total);
|
||||
// Invalid 3-of-6 symbols remain CRC-rejected as in the radio parser;
|
||||
// decoded replacement nibbles must never become a successful repeat.
|
||||
if (bad != 0) {
|
||||
uint8_t header[10];
|
||||
identity_available = wmbus_3of6_decode(buf, (size_t)n, header,
|
||||
sizeof(header)) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t *frame = buf + 2;
|
||||
bool crc_ok = wmbus_check_crc(fmt, frame, total);
|
||||
if (crc_ok) g_stats.rx_valid++; else g_stats.rx_crc_fail++;
|
||||
|
||||
if (crc_ok) led_notify_rx();
|
||||
uint32_t hash = wmbus_hash(frame, total);
|
||||
// RxDone fires after the fixed 255-byte capture; the frame actually
|
||||
// ended earlier. Reconstruct the real end-of-frame time.
|
||||
int64_t frame_end_ts = rxdone_ts - (int64_t)(RX_PAYLOAD_LEN - (total + 2)) * US_PER_BYTE;
|
||||
// ended earlier. Reconstruct the real end-of-frame time from the
|
||||
// physical on-air length (coded for T1, mode bytes + frame for C).
|
||||
int64_t frame_end_ts = rxdone_ts - (int64_t)(RX_PAYLOAD_LEN - onair_len) * US_PER_BYTE;
|
||||
record.timestamp_us = frame_end_ts;
|
||||
record.length = (uint16_t)total;
|
||||
record.hash = hash;
|
||||
record.crc_ok = crc_ok;
|
||||
record.reception = crc_ok ? "ok" : "crc_failed";
|
||||
record.outcome = crc_ok ? "repeat_disabled" : "crc_failed";
|
||||
if (identity_available) debug_identity(&record, frame, total);
|
||||
|
||||
g_ui.rx_meter_id = (uint32_t)frame[4] | ((uint32_t)frame[5] << 8)
|
||||
| ((uint32_t)frame[6] << 16) | ((uint32_t)frame[7] << 24);
|
||||
g_ui.rx_hash = hash;
|
||||
g_ui.rx_len = (int16_t)total;
|
||||
g_ui.rx_rssi_dbm = rssi;
|
||||
g_ui.rx_format = t1 ? 'T' : (fmt == WMBUS_FRAME_A ? 'A' : 'B');
|
||||
g_ui.rx_crc_ok = crc_ok;
|
||||
g_ui.rx_ts_us = frame_end_ts;
|
||||
|
||||
printf("{\"seq\":%" PRIu32 ",\"event\":\"wmbus_rx\",\"timestamp_us\":%lld,"
|
||||
"\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"format\":\"%c\","
|
||||
"\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s,"
|
||||
"\"rxdone_us\":%lld,\"frequency_hz\":868950000,\"mode\":\"%s\","
|
||||
"\"format\":\"%c\",\"length\":%d,\"rssi_dbm\":%d,\"crc_ok\":%s,"
|
||||
"\"hash\":\"%08" PRIx32 "\"",
|
||||
s_seq++, (long long)frame_end_ts, (long long)rxdone_ts,
|
||||
fmt == WMBUS_FRAME_A ? 'A' : 'B', total, rssi,
|
||||
t1 ? "T1" : "C1", fmt == WMBUS_FRAME_A ? 'A' : 'B', total, rssi,
|
||||
crc_ok ? "true" : "false", hash);
|
||||
#ifdef CONFIG_WMBUS_LOG_RAW_FRAMES
|
||||
printf(",\"raw\":\"");
|
||||
@@ -536,10 +794,11 @@ static void handle_rx(int64_t rxdone_ts)
|
||||
printf("}\n");
|
||||
fflush(stdout);
|
||||
|
||||
if (!g_cfg.repeat_enabled || !crc_ok) return;
|
||||
if (!g_cfg.repeat_enabled || !crc_ok) goto done;
|
||||
if (!whitelist_pass(frame)) {
|
||||
g_stats.tx_suppressed_whitelist++;
|
||||
return;
|
||||
record.outcome = "whitelist";
|
||||
goto done;
|
||||
}
|
||||
int64_t now = esp_timer_get_time();
|
||||
if (is_dup(hash, now)) {
|
||||
@@ -547,32 +806,67 @@ static void handle_rx(int64_t rxdone_ts)
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"dup\",\"hash\":\"%08" PRIx32 "\"", hash);
|
||||
}
|
||||
return;
|
||||
record.outcome = "duplicate";
|
||||
goto done;
|
||||
}
|
||||
|
||||
uint64_t duty_used = 0, duty_budget = 0;
|
||||
if (duty_would_exceed(now, total + 2, &duty_used, &duty_budget)) {
|
||||
if (duty_would_exceed(now, onair_len, &duty_used, &duty_budget)) {
|
||||
g_stats.tx_suppressed_duty++;
|
||||
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"duty_cycle\","
|
||||
"\"hash\":\"%08" PRIx32 "\",\"used_us\":%llu,\"budget_us\":%llu",
|
||||
hash, (unsigned long long)duty_used,
|
||||
(unsigned long long)duty_budget);
|
||||
return;
|
||||
record.outcome = "duty_cycle";
|
||||
goto done;
|
||||
}
|
||||
|
||||
// ---- repeat ----
|
||||
static uint8_t txbuf[RX_PAYLOAD_LEN + 2];
|
||||
// RX logging/hash above describe the original. TX carries only the
|
||||
// standard H-bit change and repaired CRC; ciphertext is untouched.
|
||||
if (!wmbus_mark_repeated(fmt, frame, total)) {
|
||||
if (g_cfg.verbose) {
|
||||
LOGJ("\"event\":\"tx_suppressed\",\"reason\":\"hop_policy\","
|
||||
"\"hash\":\"%08" PRIx32 "\"", hash);
|
||||
}
|
||||
record.outcome = "hop_policy";
|
||||
goto done;
|
||||
}
|
||||
|
||||
// ---- repeat: rebuild the physical payload in the source mode ----
|
||||
static uint8_t txbuf[300];
|
||||
int phys;
|
||||
if (t1) {
|
||||
phys = wmbus_3of6_encode(frame, total, txbuf, sizeof(txbuf));
|
||||
if (phys < 0 || phys > 255) {
|
||||
record.outcome = "encode_failed";
|
||||
goto done;
|
||||
}
|
||||
} else {
|
||||
txbuf[0] = buf[0];
|
||||
txbuf[1] = buf[1];
|
||||
memcpy(txbuf + 2, frame, total);
|
||||
phys = total + 2;
|
||||
}
|
||||
|
||||
precise_delay_until(frame_end_ts + (int64_t)g_cfg.repeat_delay_ms * 1000);
|
||||
|
||||
int64_t t0, t1;
|
||||
const char *res = do_tx(txbuf, total + 2, &t0, &t1);
|
||||
if (t1 > t0) duty_record(t0, (uint32_t)(t1 - t0));
|
||||
int64_t t0, t1_done;
|
||||
const char *res = do_tx(txbuf, phys, t1, &t0, &t1_done, &record);
|
||||
remember_dup(hash, esp_timer_get_time());
|
||||
log_tx(res, hash, total, frame_end_ts, t0, t1, txbuf, total + 2);
|
||||
log_tx(res, hash, total, phys, t1 ? "T1" : "C1",
|
||||
frame_end_ts, t0, t1_done, txbuf, phys);
|
||||
restore_rx = true;
|
||||
|
||||
done:
|
||||
// Exactly one final record per RX candidate, before recovery can reboot.
|
||||
// Keep existing serial events unchanged: an additional blocking printf/
|
||||
// fflush per row would extend deaf time even after a decision or TX.
|
||||
debug_history_record(&record);
|
||||
if (read_failed) {
|
||||
recover_ladder("rx_read_failed");
|
||||
return;
|
||||
}
|
||||
if (!restore_rx) return;
|
||||
|
||||
// Always return to RX
|
||||
sx126x_restore_rx_payload_len();
|
||||
@@ -588,6 +882,47 @@ static void handle_rx(int64_t rxdone_ts)
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_irq(uint16_t irq)
|
||||
{
|
||||
sx126x_clear_irq(irq);
|
||||
if (irq & SX126X_IRQ_RX_DONE) handle_rx(s_irq_ts);
|
||||
// TIMEOUT in RX continuous should not happen; TX_DONE is consumed
|
||||
// by do_tx's instrumented wait. Anything unexpected: just note it.
|
||||
if (g_cfg.verbose && (irq & ~SX126X_IRQ_RX_DONE)) {
|
||||
LOGJ("\"event\":\"irq_other\",\"mask\":%u", irq);
|
||||
}
|
||||
}
|
||||
|
||||
static void apply_pending_settings(void)
|
||||
{
|
||||
if (!settings_radio_pending()) return;
|
||||
// Only settings changes add an IRQ probe. Drain the old capture using its
|
||||
// old configuration before copying a new coherent snapshot. A latched sync
|
||||
// without RxDone means the fixed-length capture is still in progress.
|
||||
uint16_t irq = sx126x_get_irq();
|
||||
if (irq & SX126X_IRQ_RX_DONE) {
|
||||
ulTaskNotifyTake(pdTRUE, 0);
|
||||
handle_irq(irq);
|
||||
irq = sx126x_get_irq();
|
||||
}
|
||||
if (irq & (SX126X_IRQ_SYNCWORD_VALID | SX126X_IRQ_RX_DONE)) return;
|
||||
|
||||
int8_t old_tx_power = g_cfg.tx_power_dbm;
|
||||
uint8_t old_preamble = g_cfg.preamble_bits;
|
||||
bool old_fem_rx_csd = g_cfg.fem_rx_csd;
|
||||
if (!settings_radio_apply(&g_cfg)) return;
|
||||
// Driver desired values are radio-owned too. No driver access takes place
|
||||
// under the settings spinlock, or from USB/HTTP/OLED writer tasks.
|
||||
sx126x_set_preamble_detect(preamble_detect_code(g_cfg.preamble_bits));
|
||||
fem_set_rx_csd(g_cfg.fem_rx_csd);
|
||||
if (old_tx_power != g_cfg.tx_power_dbm || old_preamble != g_cfg.preamble_bits) {
|
||||
s_want_radio_reset = true;
|
||||
} else if (old_fem_rx_csd != g_cfg.fem_rx_csd) {
|
||||
// Apply the RX pin without a full modem reinitialization.
|
||||
fem_set_tx(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ task
|
||||
|
||||
static void repeater_task(void *arg)
|
||||
@@ -596,27 +931,38 @@ static void repeater_task(void *arg)
|
||||
s_task = xTaskGetCurrentTaskHandle();
|
||||
sx126x_set_irq_callback(irq_cb);
|
||||
esp_task_wdt_add(NULL);
|
||||
settings_radio_apply(&g_cfg);
|
||||
sx126x_set_preamble_detect(preamble_detect_code(g_cfg.preamble_bits));
|
||||
fem_set_rx_csd(g_cfg.fem_rx_csd);
|
||||
|
||||
if (!radio_full_init()) {
|
||||
// keep retrying with full ladder rather than dying
|
||||
recover_ladder("boot_init_failed");
|
||||
}
|
||||
if (!sx126x_set_rx()) recover_ladder("boot_rx_failed");
|
||||
s_debug_status.chip_mode = 0x5;
|
||||
publish_debug_status();
|
||||
led_boot_done();
|
||||
|
||||
int64_t last_heartbeat = 0;
|
||||
for (;;) {
|
||||
esp_task_wdt_reset();
|
||||
apply_pending_settings();
|
||||
|
||||
if (s_want_radio_reset) {
|
||||
s_want_radio_reset = false;
|
||||
g_stats.radio_reinit++;
|
||||
if (!radio_full_init() || !sx126x_set_rx()) recover_ladder("manual_reset");
|
||||
else s_debug_status.chip_mode = 0x5;
|
||||
}
|
||||
if (s_want_test_tx) {
|
||||
s_want_test_tx = false;
|
||||
run_test_tx();
|
||||
}
|
||||
if (s_want_test_tx_t1) {
|
||||
s_want_test_tx_t1 = false;
|
||||
run_test_tx_t1();
|
||||
}
|
||||
if (s_want_test_burst) {
|
||||
s_want_test_burst = false;
|
||||
run_test_burst();
|
||||
@@ -640,14 +986,7 @@ static void repeater_task(void *arg)
|
||||
}
|
||||
|
||||
if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(1000)) > 0) {
|
||||
uint16_t irq = sx126x_get_irq();
|
||||
sx126x_clear_irq(irq);
|
||||
if (irq & SX126X_IRQ_RX_DONE) handle_rx(s_irq_ts);
|
||||
// TIMEOUT in RX continuous should not happen; TX_DONE is consumed
|
||||
// by do_tx's wait_irq. Anything unexpected: just note it.
|
||||
if (g_cfg.verbose && (irq & ~(SX126X_IRQ_RX_DONE))) {
|
||||
LOGJ("\"event\":\"irq_other\",\"mask\":%u", irq);
|
||||
}
|
||||
handle_irq(sx126x_get_irq());
|
||||
}
|
||||
if (g_cfg.beacon_period_ms) {
|
||||
int64_t bnow = esp_timer_get_time();
|
||||
@@ -667,16 +1006,25 @@ static void repeater_task(void *arg)
|
||||
uint8_t st = sx126x_get_status();
|
||||
uint8_t mode = (st >> 4) & 0x7;
|
||||
bool cfg_ok = sx126x_config_intact();
|
||||
int8_t rssi_now = sx126x_get_rssi_inst();
|
||||
g_ui.chip_mode = mode;
|
||||
g_ui.config_intact = cfg_ok;
|
||||
g_ui.rssi_dbm = rssi_now;
|
||||
g_ui.hb_ts_us = now;
|
||||
s_debug_status.heartbeat_us = now;
|
||||
s_debug_status.chip_mode = mode;
|
||||
s_debug_status.config_intact = cfg_ok;
|
||||
LOGJ("\"event\":\"heartbeat\",\"uptime_us\":%lld,\"chip_mode\":%u,"
|
||||
"\"config_intact\":%s,\"rssi_dbm\":%d",
|
||||
(long long)now, mode, cfg_ok ? "true" : "false",
|
||||
sx126x_get_rssi_inst());
|
||||
(int)rssi_now);
|
||||
if (mode != 0x5) {
|
||||
recover_ladder("not_in_rx");
|
||||
} else if (!cfg_ok) {
|
||||
recover_ladder("config_lost");
|
||||
}
|
||||
}
|
||||
publish_debug_status();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -687,8 +1035,8 @@ void repeater_start(void)
|
||||
|
||||
void repeater_request_radio_reset(void) { s_want_radio_reset = true; }
|
||||
void repeater_request_test_tx(void) { s_want_test_tx = true; }
|
||||
void repeater_request_test_tx_t1(void) { s_want_test_tx_t1 = true; }
|
||||
void repeater_request_probe(void) { s_want_probe = true; }
|
||||
void repeater_set_test_lfield(uint8_t l) { s_test_lfield = l; }
|
||||
void repeater_request_test_burst(void) { s_want_test_burst = true; }
|
||||
void repeater_inject_fault(int what) { s_inject = what; }
|
||||
|
||||
@@ -696,22 +1044,35 @@ void repeater_inject_fault(int what) { s_inject = what; }
|
||||
|
||||
void repeater_print_status(void)
|
||||
{
|
||||
settings_snapshot_t snapshot;
|
||||
settings_get_snapshot(&snapshot);
|
||||
const repeater_cfg_t *cfg = &snapshot.values;
|
||||
char whitelist[8 * 11] = "";
|
||||
size_t used = 0;
|
||||
for (int i = 0; i < cfg->whitelist_len; i++) {
|
||||
used += (size_t)snprintf(whitelist + used, sizeof(whitelist) - used,
|
||||
"%s\"%08" PRIx32 "\"", i ? "," : "", cfg->whitelist[i]);
|
||||
}
|
||||
// Settings describe the accepted state, which may be pending. The applied
|
||||
// revision acknowledges only the radio's copy, not hardware/RF success.
|
||||
LOGJ("\"event\":\"status\",\"uptime_us\":%lld,"
|
||||
"\"repeat_delay_ms\":%" PRIu32 ",\"configured_tx_dbm\":%d,"
|
||||
"\"repeat_enabled\":%s,\"verbose\":%s,\"whitelist_len\":%d,"
|
||||
"\"preamble_detect_code\":%u,\"duty_budget_ppm\":%" PRIu32 ","
|
||||
"\"beacon_period_ms\":%" PRIu32 ","
|
||||
"\"duty_used_us\":%llu,\"reset_reason\":%d",
|
||||
"\"duty_used_us\":%llu,\"reset_reason\":%d,"
|
||||
"\"fem_rx_csd\":%s,\"preamble_bits\":%u,\"test_lfield\":%u,"
|
||||
"\"whitelist\":[%s],\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32,
|
||||
(long long)esp_timer_get_time(),
|
||||
g_cfg.repeat_delay_ms, (int)g_cfg.tx_power_dbm,
|
||||
g_cfg.repeat_enabled ? "true" : "false",
|
||||
g_cfg.verbose ? "true" : "false",
|
||||
g_cfg.whitelist_len,
|
||||
sx126x_get_preamble_detect(),
|
||||
g_cfg.duty_budget_ppm,
|
||||
g_cfg.beacon_period_ms,
|
||||
cfg->repeat_delay_ms, (int)cfg->tx_power_dbm,
|
||||
cfg->repeat_enabled ? "true" : "false",
|
||||
cfg->verbose ? "true" : "false",
|
||||
cfg->whitelist_len, preamble_detect_code(cfg->preamble_bits),
|
||||
cfg->duty_budget_ppm, cfg->beacon_period_ms,
|
||||
(unsigned long long)duty_used_us(esp_timer_get_time()),
|
||||
(int)esp_reset_reason());
|
||||
(int)esp_reset_reason(),
|
||||
cfg->fem_rx_csd ? "true" : "false", cfg->preamble_bits, cfg->test_lfield,
|
||||
whitelist, snapshot.revision, snapshot.applied_revision);
|
||||
}
|
||||
|
||||
void repeater_print_stats(void)
|
||||
@@ -719,7 +1080,8 @@ void repeater_print_stats(void)
|
||||
LOGJ("\"event\":\"stats\",\"uptime_us\":%lld,"
|
||||
"\"rx_candidates\":%" PRIu32 ",\"rx_valid\":%" PRIu32 ","
|
||||
"\"rx_crc_fail\":%" PRIu32 ",\"rx_not_c1\":%" PRIu32 ","
|
||||
"\"rx_len_invalid\":%" PRIu32 ",\"rx_bytes\":%" PRIu32 ","
|
||||
"\"rx_len_invalid\":%" PRIu32 ",\"rx_t1\":%" PRIu32 ","
|
||||
"\"rx_bytes\":%" PRIu32 ","
|
||||
"\"tx_attempts\":%" PRIu32 ",\"tx_success\":%" PRIu32 ","
|
||||
"\"tx_timeout\":%" PRIu32 ",\"tx_failures\":%" PRIu32 ","
|
||||
"\"tx_suppressed_dup\":%" PRIu32 ",\"tx_suppressed_whitelist\":%" PRIu32 ","
|
||||
@@ -729,7 +1091,8 @@ void repeater_print_stats(void)
|
||||
"\"tx_duty_cycle_ppm\":%llu",
|
||||
(long long)esp_timer_get_time(),
|
||||
g_stats.rx_candidates, g_stats.rx_valid, g_stats.rx_crc_fail,
|
||||
g_stats.rx_not_c1, g_stats.rx_len_invalid, g_stats.rx_bytes,
|
||||
g_stats.rx_not_c1, g_stats.rx_len_invalid, g_stats.rx_t1,
|
||||
g_stats.rx_bytes,
|
||||
g_stats.tx_attempts, g_stats.tx_success, g_stats.tx_timeout,
|
||||
g_stats.tx_failures, g_stats.tx_suppressed_dup,
|
||||
g_stats.tx_suppressed_whitelist, g_stats.tx_suppressed_duty,
|
||||
|
||||
@@ -9,6 +9,7 @@ typedef struct {
|
||||
uint32_t rx_crc_fail;
|
||||
uint32_t rx_not_c1; // sync matched but not C-mode (e.g. T1)
|
||||
uint32_t rx_len_invalid;
|
||||
uint32_t rx_t1; // receptions classified as T-mode (any CRC state)
|
||||
uint32_t rx_bytes;
|
||||
uint32_t tx_attempts;
|
||||
uint32_t tx_success;
|
||||
@@ -24,24 +25,55 @@ typedef struct {
|
||||
} repeater_stats_t;
|
||||
|
||||
typedef struct {
|
||||
uint32_t repeat_delay_ms; // 20..200
|
||||
uint32_t duty_budget_ppm; // rolling-hour TX airtime cap, 0 = disabled
|
||||
uint32_t repeat_delay_ms; // 20..1000; persisted (cfg_store)
|
||||
uint32_t duty_budget_ppm; // rolling-hour TX airtime cap, 0 = disabled; persisted
|
||||
uint32_t beacon_period_ms; // periodic synthetic test frame, 0 = off
|
||||
int8_t tx_power_dbm; // configured SX1262 level, not radiated power
|
||||
bool repeat_enabled;
|
||||
bool verbose;
|
||||
uint32_t whitelist[8]; // A-field ID (4 bytes LE as uint32), 0 = empty slot
|
||||
bool fem_rx_csd; // experimental FEM CSD level in RX
|
||||
uint8_t preamble_bits; // 0, 8, 16, 24 or 32 detected bits
|
||||
uint8_t test_lfield; // 19..200, synthetic frame payload length
|
||||
uint32_t whitelist[8]; // A-field ID (4 bytes LE as uint32)
|
||||
int whitelist_len;
|
||||
} repeater_cfg_t;
|
||||
|
||||
// Radio-owned applied configuration after boot; other tasks may display it,
|
||||
// but all mutations must go through settings_update.
|
||||
extern repeater_cfg_t g_cfg;
|
||||
extern repeater_stats_t g_stats;
|
||||
|
||||
// Last-event snapshot published by the radio task for the local UI.
|
||||
// Written only from the radio task; read from the UI task without locks.
|
||||
// Races tear at most one displayed frame and are deliberately accepted --
|
||||
// the UI must never block or query the radio (docs/FUTURE_UI.md).
|
||||
typedef struct {
|
||||
int64_t rx_ts_us; // 0 = no reception yet
|
||||
uint32_t rx_meter_id; // A-field ID, LE uint32 (prints as meter number)
|
||||
uint32_t rx_hash;
|
||||
int16_t rx_len;
|
||||
int8_t rx_rssi_dbm;
|
||||
char rx_format; // 'A' / 'B'
|
||||
bool rx_crc_ok;
|
||||
int64_t tx_ts_us; // 0 = no TX yet
|
||||
char tx_result[16]; // includes full "radio_timeout" + terminator
|
||||
int64_t hb_ts_us; // last heartbeat probe
|
||||
uint8_t chip_mode;
|
||||
bool config_intact;
|
||||
int8_t rssi_dbm;
|
||||
} repeater_ui_t;
|
||||
|
||||
extern repeater_ui_t g_ui;
|
||||
|
||||
// Rolling-hour duty usage right now. Pure memory reads (ledger + monotonic
|
||||
// clock); safe to call from the UI task.
|
||||
uint64_t repeater_duty_used_us(void);
|
||||
|
||||
void repeater_start(void);
|
||||
void repeater_request_radio_reset(void);
|
||||
void repeater_request_test_tx(void);
|
||||
void repeater_request_test_tx_t1(void);
|
||||
void repeater_request_probe(void);
|
||||
void repeater_set_test_lfield(uint8_t l);
|
||||
void repeater_request_test_burst(void);
|
||||
void repeater_inject_fault(int what); // 1 = standby, 2 = sleep
|
||||
void repeater_print_status(void);
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
#include "settings.h"
|
||||
#include "cfg_store.h"
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/semphr.h"
|
||||
|
||||
// The writer mutex spans validation against the current revision, NVS and
|
||||
// publication. The radio never takes it. The spinlock only protects small
|
||||
// in-memory snapshots; no logging, SPI, NVS or blocking calls run underneath it.
|
||||
static SemaphoreHandle_t s_writer;
|
||||
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
static settings_snapshot_t s_desired;
|
||||
|
||||
static bool valid_change(const settings_change_t *change)
|
||||
{
|
||||
if (!change) return false;
|
||||
int32_t v = change->value;
|
||||
switch (change->key) {
|
||||
case SETTINGS_REPEAT_DELAY_MS: return v >= 20 && v <= 1000;
|
||||
case SETTINGS_TX_POWER: return v >= -9 && v <= 2;
|
||||
case SETTINGS_REPEAT_ENABLED:
|
||||
case SETTINGS_VERBOSE:
|
||||
case SETTINGS_FEM_RX_CSD: return v == 0 || v == 1;
|
||||
case SETTINGS_PREAMBLE_BITS:
|
||||
return v == 0 || v == 8 || v == 16 || v == 24 || v == 32;
|
||||
case SETTINGS_DUTY_BUDGET_PPM: return v >= 0 && v <= 100000;
|
||||
case SETTINGS_TEST_LFIELD: return v >= 19 && v <= 200;
|
||||
case SETTINGS_BEACON_PERIOD_MS: return v == 0 || (v >= 250 && v <= 600000);
|
||||
case SETTINGS_WHITELIST:
|
||||
if (change->whitelist_len > 8) return false;
|
||||
for (unsigned i = 0; i < change->whitelist_len; i++) {
|
||||
for (unsigned j = 0; j < i; j++) {
|
||||
if (change->whitelist[i] == change->whitelist[j]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
void settings_init(void)
|
||||
{
|
||||
s_writer = xSemaphoreCreateMutex();
|
||||
configASSERT(s_writer);
|
||||
repeater_cfg_t initial = g_cfg;
|
||||
uint32_t value;
|
||||
bool restored = false;
|
||||
if (cfg_store_load_u32(CFG_KEY_DUTY_PPM, &value)) {
|
||||
if (value <= 100000) {
|
||||
initial.duty_budget_ppm = value;
|
||||
restored = true;
|
||||
} else {
|
||||
printf("{\"event\":\"cfg_restore_invalid\",\"key\":\"duty_budget_ppm\",\"value\":%" PRIu32 "}\n", value);
|
||||
}
|
||||
}
|
||||
if (cfg_store_load_u32(CFG_KEY_DELAY_MS, &value)) {
|
||||
if (value >= 20 && value <= 1000) {
|
||||
initial.repeat_delay_ms = value;
|
||||
restored = true;
|
||||
} else {
|
||||
printf("{\"event\":\"cfg_restore_invalid\",\"key\":\"repeat_delay_ms\",\"value\":%" PRIu32 "}\n", value);
|
||||
}
|
||||
}
|
||||
// No tasks have started: initialize the legacy display snapshot as well.
|
||||
g_cfg = initial;
|
||||
s_desired.values = initial;
|
||||
s_desired.revision = 1;
|
||||
s_desired.applied_revision = 0;
|
||||
if (restored) {
|
||||
printf("{\"event\":\"cfg_restore\",\"duty_budget_ppm\":%" PRIu32 ","
|
||||
"\"repeat_delay_ms\":%" PRIu32 "}\n",
|
||||
initial.duty_budget_ppm, initial.repeat_delay_ms);
|
||||
}
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
void settings_get_snapshot(settings_snapshot_t *out)
|
||||
{
|
||||
if (!out) return;
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
*out = s_desired;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
settings_result_t settings_update(const settings_change_t *change,
|
||||
uint32_t expected_revision,
|
||||
settings_snapshot_t *out)
|
||||
{
|
||||
if (!valid_change(change)) {
|
||||
settings_get_snapshot(out);
|
||||
return SETTINGS_INVALID;
|
||||
}
|
||||
if (!s_writer || xSemaphoreTake(s_writer, pdMS_TO_TICKS(1000)) != pdTRUE) {
|
||||
settings_get_snapshot(out);
|
||||
return SETTINGS_BUSY;
|
||||
}
|
||||
settings_snapshot_t next;
|
||||
settings_get_snapshot(&next);
|
||||
settings_result_t result = SETTINGS_OK;
|
||||
if (expected_revision && expected_revision != next.revision) {
|
||||
result = SETTINGS_CONFLICT;
|
||||
goto done;
|
||||
}
|
||||
// Never wrap into revision 0 (unconditional) or reuse a stale revision.
|
||||
if (next.revision == UINT32_MAX) {
|
||||
result = SETTINGS_BUSY;
|
||||
goto done;
|
||||
}
|
||||
switch (change->key) {
|
||||
case SETTINGS_REPEAT_DELAY_MS: next.values.repeat_delay_ms = (uint32_t)change->value; break;
|
||||
case SETTINGS_TX_POWER: next.values.tx_power_dbm = (int8_t)change->value; break;
|
||||
case SETTINGS_REPEAT_ENABLED: next.values.repeat_enabled = change->value != 0; break;
|
||||
case SETTINGS_VERBOSE: next.values.verbose = change->value != 0; break;
|
||||
case SETTINGS_FEM_RX_CSD: next.values.fem_rx_csd = change->value != 0; break;
|
||||
case SETTINGS_PREAMBLE_BITS: next.values.preamble_bits = (uint8_t)change->value; break;
|
||||
case SETTINGS_DUTY_BUDGET_PPM: next.values.duty_budget_ppm = (uint32_t)change->value; break;
|
||||
case SETTINGS_TEST_LFIELD: next.values.test_lfield = (uint8_t)change->value; break;
|
||||
case SETTINGS_BEACON_PERIOD_MS: next.values.beacon_period_ms = (uint32_t)change->value; break;
|
||||
case SETTINGS_WHITELIST:
|
||||
memset(next.values.whitelist, 0, sizeof(next.values.whitelist));
|
||||
memcpy(next.values.whitelist, change->whitelist,
|
||||
change->whitelist_len * sizeof(change->whitelist[0]));
|
||||
next.values.whitelist_len = change->whitelist_len;
|
||||
break;
|
||||
default:
|
||||
result = SETTINGS_INVALID;
|
||||
goto done;
|
||||
}
|
||||
const char *store_key = change->key == SETTINGS_REPEAT_DELAY_MS ? CFG_KEY_DELAY_MS
|
||||
: change->key == SETTINGS_DUTY_BUDGET_PPM ? CFG_KEY_DUTY_PPM
|
||||
: NULL;
|
||||
if (store_key && !cfg_store_save_u32(store_key, (uint32_t)change->value)) {
|
||||
result = SETTINGS_STORAGE_ERROR;
|
||||
goto done;
|
||||
}
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
s_desired.values = next.values;
|
||||
s_desired.revision = next.revision + 1;
|
||||
// applied_revision may have advanced while NVS was committing; retain it.
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
|
||||
done:
|
||||
settings_get_snapshot(out);
|
||||
xSemaphoreGive(s_writer);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool settings_radio_pending(void)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
bool pending = s_desired.revision != s_desired.applied_revision;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
return pending;
|
||||
}
|
||||
|
||||
bool settings_radio_apply(repeater_cfg_t *active)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
bool pending = s_desired.revision != s_desired.applied_revision;
|
||||
if (pending) {
|
||||
*active = s_desired.values;
|
||||
// This acknowledges the coherent copy, not successful hardware/RF operation.
|
||||
s_desired.applied_revision = s_desired.revision;
|
||||
}
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
return pending;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "repeater.h"
|
||||
|
||||
typedef struct {
|
||||
uint32_t revision;
|
||||
uint32_t applied_revision;
|
||||
repeater_cfg_t values;
|
||||
} settings_snapshot_t;
|
||||
|
||||
typedef enum {
|
||||
SETTINGS_REPEAT_DELAY_MS,
|
||||
SETTINGS_TX_POWER,
|
||||
SETTINGS_REPEAT_ENABLED,
|
||||
SETTINGS_VERBOSE,
|
||||
SETTINGS_FEM_RX_CSD,
|
||||
SETTINGS_PREAMBLE_BITS,
|
||||
SETTINGS_DUTY_BUDGET_PPM,
|
||||
SETTINGS_TEST_LFIELD,
|
||||
SETTINGS_WHITELIST,
|
||||
SETTINGS_BEACON_PERIOD_MS,
|
||||
} settings_key_t;
|
||||
|
||||
typedef struct {
|
||||
settings_key_t key;
|
||||
int32_t value;
|
||||
uint32_t whitelist[8];
|
||||
uint8_t whitelist_len;
|
||||
} settings_change_t;
|
||||
|
||||
typedef enum {
|
||||
SETTINGS_OK,
|
||||
SETTINGS_INVALID,
|
||||
SETTINGS_CONFLICT,
|
||||
SETTINGS_STORAGE_ERROR,
|
||||
SETTINGS_BUSY,
|
||||
} settings_result_t;
|
||||
|
||||
// Boot only, after cfg_store_init and before starting any consumer tasks.
|
||||
// Restores the two persisted keys after range validation, keeping defaults otherwise.
|
||||
void settings_init(void);
|
||||
void settings_get_snapshot(settings_snapshot_t *out);
|
||||
// expected_revision == 0 is unconditional (local console); network callers use >= 1.
|
||||
// On failure the accepted values and revision are unchanged; out may be NULL.
|
||||
settings_result_t settings_update(const settings_change_t *change,
|
||||
uint32_t expected_revision,
|
||||
settings_snapshot_t *out);
|
||||
|
||||
// Radio owner only, at an RX/processing loop boundary. Never waits on NVS or a mutex.
|
||||
bool settings_radio_pending(void);
|
||||
bool settings_radio_apply(repeater_cfg_t *active);
|
||||
@@ -0,0 +1,286 @@
|
||||
// Settings transport: WPA2 AP access plus same-origin, per-AP CSRF protection.
|
||||
// The settings coordinator owns validation, persistence and radio handoff.
|
||||
#include "settings_http.h"
|
||||
#include "settings.h"
|
||||
#include "wifi_debug.h"
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_random.h"
|
||||
|
||||
static char s_boot[9];
|
||||
static char s_token[33];
|
||||
|
||||
static void response_headers(httpd_req_t *req)
|
||||
{
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
|
||||
httpd_resp_set_hdr(req, "X-Content-Type-Options", "nosniff");
|
||||
httpd_resp_set_hdr(req, "Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'");
|
||||
}
|
||||
|
||||
static esp_err_t error_response(httpd_req_t *req, const char *status, const char *message)
|
||||
{
|
||||
char body[256];
|
||||
int n = snprintf(body, sizeof(body), "{\"error\":\"%s\"}", message);
|
||||
response_headers(req);
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_hdr(req, "Connection", "close");
|
||||
if (n > 0 && (size_t)n < sizeof(body)) httpd_resp_send(req, body, n);
|
||||
// Some failures precede reading the body. Close rather than leave unread
|
||||
// bytes on a keep-alive connection or spend time draining an oversized body.
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
static bool trusted_request(httpd_req_t *req, bool writing)
|
||||
{
|
||||
char value[80];
|
||||
if (httpd_req_get_hdr_value_str(req, "Host", value, sizeof(value)) != ESP_OK ||
|
||||
(strcmp(value, "192.168.4.1") && strcmp(value, "192.168.4.1:80"))) return false;
|
||||
if (httpd_req_get_hdr_value_len(req, "Origin")) {
|
||||
if (httpd_req_get_hdr_value_str(req, "Origin", value, sizeof(value)) != ESP_OK ||
|
||||
(strcmp(value, "http://192.168.4.1") && strcmp(value, "http://192.168.4.1:80"))) return false;
|
||||
}
|
||||
if (httpd_req_get_hdr_value_len(req, "Sec-Fetch-Site")) {
|
||||
if (httpd_req_get_hdr_value_str(req, "Sec-Fetch-Site", value, sizeof(value)) != ESP_OK ||
|
||||
(strcmp(value, "same-origin") && strcmp(value, "none"))) return false;
|
||||
}
|
||||
if (!writing) return true;
|
||||
if (httpd_req_get_hdr_value_str(req, "X-CSRF-Token", value, sizeof(value)) != ESP_OK ||
|
||||
strcmp(value, s_token)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static esp_err_t send_snapshot(httpd_req_t *req, const settings_snapshot_t *snapshot)
|
||||
{
|
||||
const repeater_cfg_t *v = &snapshot->values;
|
||||
char ids[88];
|
||||
size_t used = 0;
|
||||
ids[0] = 0;
|
||||
for (int i = 0; i < v->whitelist_len; i++) {
|
||||
int n = snprintf(ids + used, sizeof(ids) - used, "%s\"%08" PRIX32 "\"",
|
||||
i ? "," : "", v->whitelist[i]);
|
||||
if (n < 0 || (size_t)n >= sizeof(ids) - used) return ESP_FAIL;
|
||||
used += (size_t)n;
|
||||
}
|
||||
char body[1024];
|
||||
int n = snprintf(body, sizeof(body),
|
||||
"{\"boot_id\":\"%s\",\"revision\":%" PRIu32 ",\"applied_revision\":%" PRIu32
|
||||
",\"csrf_token\":\"%s\",\"settings\":{"
|
||||
"\"repeat_delay_ms\":%" PRIu32 ",\"tx_power\":%d,\"repeat_enabled\":%s,"
|
||||
"\"verbose\":%s,\"fem_rx_csd\":%s,\"preamble_bits\":%u,"
|
||||
"\"duty_budget_ppm\":%" PRIu32 ",\"test_lfield\":%u,\"whitelist\":[%s],"
|
||||
"\"beacon_period_ms\":%" PRIu32 "}}",
|
||||
s_boot, snapshot->revision, snapshot->applied_revision, s_token,
|
||||
v->repeat_delay_ms, (int)v->tx_power_dbm, v->repeat_enabled ? "true" : "false",
|
||||
v->verbose ? "true" : "false", v->fem_rx_csd ? "true" : "false", v->preamble_bits,
|
||||
v->duty_budget_ppm, v->test_lfield, ids, v->beacon_period_ms);
|
||||
if (n < 0 || (size_t)n >= sizeof(body)) return ESP_FAIL;
|
||||
response_headers(req);
|
||||
return httpd_resp_send(req, body, n);
|
||||
}
|
||||
|
||||
static esp_err_t get_settings(httpd_req_t *req)
|
||||
{
|
||||
if (!trusted_request(req, false))
|
||||
return error_response(req, "403 Forbidden", "Einstellungen nur unter http://192.168.4.1 öffnen.");
|
||||
settings_snapshot_t snapshot;
|
||||
settings_get_snapshot(&snapshot);
|
||||
return send_snapshot(req, &snapshot);
|
||||
}
|
||||
|
||||
// cJSON is recursive. Valid requests need only a root object and a whitelist
|
||||
// array, so reject deeper nesting before parsing. Embedded NUL escapes would
|
||||
// otherwise make C-string comparisons accept truncated keys or values.
|
||||
static bool shallow_json(const char *body, size_t len)
|
||||
{
|
||||
bool quoted = false;
|
||||
int depth = 0;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
unsigned char c = (unsigned char)body[i];
|
||||
if (!c) return false;
|
||||
if (quoted) {
|
||||
if (c < 0x20) return false;
|
||||
if (c == '\\') {
|
||||
if (++i >= len) return false;
|
||||
if (body[i] == 'u' && i + 4 < len && !memcmp(body + i + 1, "0000", 4)) return false;
|
||||
} else if (c == '"') quoted = false;
|
||||
} else if (c == '"') quoted = true;
|
||||
else if (c == '{' || c == '[') { if (++depth > 2) return false; }
|
||||
else if (c == '}' || c == ']') { if (--depth < 0) return false; }
|
||||
}
|
||||
return !quoted && depth == 0;
|
||||
}
|
||||
|
||||
static cJSON *receive_body(httpd_req_t *req)
|
||||
{
|
||||
char type[64];
|
||||
if (httpd_req_get_hdr_value_str(req, "Content-Type", type, sizeof(type)) != ESP_OK ||
|
||||
strncasecmp(type, "application/json", 16) || (type[16] && type[16] != ';')) {
|
||||
error_response(req, "415 Unsupported Media Type", "Die Anfrage muss JSON enthalten.");
|
||||
return NULL;
|
||||
}
|
||||
if (!req->content_len || req->content_len > 512 || httpd_req_get_hdr_value_len(req, "Transfer-Encoding")) {
|
||||
error_response(req, "400 Bad Request", "Die Anfrage ist leer, zu groß oder nicht unterstützt.");
|
||||
return NULL;
|
||||
}
|
||||
char body[513];
|
||||
size_t received = 0;
|
||||
while (received < req->content_len) {
|
||||
int n = httpd_req_recv(req, body + received, req->content_len - received);
|
||||
if (n <= 0) {
|
||||
error_response(req, "408 Request Timeout", "Die Anfrage wurde nicht vollständig empfangen.");
|
||||
return NULL;
|
||||
}
|
||||
received += (size_t)n;
|
||||
}
|
||||
body[received] = 0;
|
||||
cJSON *root = shallow_json(body, received)
|
||||
? cJSON_ParseWithLengthOpts(body, received + 1, NULL, true) : NULL;
|
||||
if (!cJSON_IsObject(root)) {
|
||||
cJSON_Delete(root);
|
||||
error_response(req, "400 Bad Request", "Ungültige JSON-Anfrage.");
|
||||
return NULL;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
static bool exact_fields(const cJSON *root, const char *const *names, size_t count)
|
||||
{
|
||||
unsigned seen = 0;
|
||||
for (const cJSON *item = root->child; item; item = item->next) {
|
||||
size_t i = 0;
|
||||
while (i < count && strcmp(item->string, names[i])) i++;
|
||||
if (i == count || (seen & (1u << i))) return false;
|
||||
seen |= 1u << i;
|
||||
}
|
||||
return seen == (1u << count) - 1;
|
||||
}
|
||||
|
||||
static bool correct_boot(const cJSON *root)
|
||||
{
|
||||
const cJSON *boot = cJSON_GetObjectItemCaseSensitive(root, "boot_id");
|
||||
return cJSON_IsString(boot) && !strcmp(boot->valuestring, s_boot);
|
||||
}
|
||||
|
||||
typedef enum { VALUE_NUMBER, VALUE_BOOL, VALUE_IDS } value_kind_t;
|
||||
static const struct {
|
||||
const char *name;
|
||||
settings_key_t key;
|
||||
value_kind_t kind;
|
||||
} keys[] = {
|
||||
{"repeat_delay_ms", SETTINGS_REPEAT_DELAY_MS, VALUE_NUMBER},
|
||||
{"tx_power", SETTINGS_TX_POWER, VALUE_NUMBER},
|
||||
{"repeat_enabled", SETTINGS_REPEAT_ENABLED, VALUE_BOOL},
|
||||
{"verbose", SETTINGS_VERBOSE, VALUE_BOOL},
|
||||
{"fem_rx_csd", SETTINGS_FEM_RX_CSD, VALUE_BOOL},
|
||||
{"preamble_bits", SETTINGS_PREAMBLE_BITS, VALUE_NUMBER},
|
||||
{"duty_budget_ppm", SETTINGS_DUTY_BUDGET_PPM, VALUE_NUMBER},
|
||||
{"test_lfield", SETTINGS_TEST_LFIELD, VALUE_NUMBER},
|
||||
{"whitelist", SETTINGS_WHITELIST, VALUE_IDS},
|
||||
{"beacon_period_ms", SETTINGS_BEACON_PERIOD_MS, VALUE_NUMBER},
|
||||
};
|
||||
|
||||
static bool parse_change(const cJSON *root, settings_change_t *change)
|
||||
{
|
||||
const cJSON *key = cJSON_GetObjectItemCaseSensitive(root, "key");
|
||||
const cJSON *value = cJSON_GetObjectItemCaseSensitive(root, "value");
|
||||
if (!cJSON_IsString(key)) return false;
|
||||
size_t i = 0;
|
||||
while (i < sizeof(keys) / sizeof(keys[0]) && strcmp(keys[i].name, key->valuestring)) i++;
|
||||
if (i == sizeof(keys) / sizeof(keys[0])) return false;
|
||||
memset(change, 0, sizeof(*change));
|
||||
change->key = keys[i].key;
|
||||
if (keys[i].kind == VALUE_BOOL) {
|
||||
if (!cJSON_IsBool(value)) return false;
|
||||
change->value = cJSON_IsTrue(value);
|
||||
return true;
|
||||
}
|
||||
if (keys[i].kind == VALUE_NUMBER) {
|
||||
if (!cJSON_IsNumber(value) || !(value->valuedouble >= INT32_MIN && value->valuedouble <= INT32_MAX)) return false;
|
||||
change->value = (int32_t)value->valuedouble;
|
||||
return value->valuedouble == change->value;
|
||||
}
|
||||
if (!cJSON_IsArray(value) || cJSON_GetArraySize(value) > 8) return false;
|
||||
for (const cJSON *id = value->child; id; id = id->next) {
|
||||
if (!cJSON_IsString(id) || strlen(id->valuestring) != 8) return false;
|
||||
uint32_t parsed = 0;
|
||||
for (const char *p = id->valuestring; *p; p++) {
|
||||
unsigned digit;
|
||||
if (*p >= '0' && *p <= '9') digit = *p - '0';
|
||||
else if (*p >= 'a' && *p <= 'f') digit = *p - 'a' + 10;
|
||||
else if (*p >= 'A' && *p <= 'F') digit = *p - 'A' + 10;
|
||||
else return false;
|
||||
parsed = (parsed << 4) | digit;
|
||||
}
|
||||
change->whitelist[change->whitelist_len++] = parsed;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static esp_err_t post_settings(httpd_req_t *req)
|
||||
{
|
||||
if (!trusted_request(req, true))
|
||||
return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden.");
|
||||
cJSON *root = receive_body(req);
|
||||
if (!root) return ESP_FAIL;
|
||||
static const char *const fields[] = {"boot_id", "revision", "key", "value"};
|
||||
const cJSON *revision = cJSON_GetObjectItemCaseSensitive(root, "revision");
|
||||
settings_change_t change;
|
||||
bool valid = exact_fields(root, fields, 4) && cJSON_IsNumber(revision) &&
|
||||
revision->valuedouble >= 1 && revision->valuedouble <= UINT32_MAX &&
|
||||
revision->valuedouble == (uint32_t)revision->valuedouble && parse_change(root, &change);
|
||||
bool boot_ok = correct_boot(root);
|
||||
uint32_t expected = valid ? (uint32_t)revision->valuedouble : 0;
|
||||
cJSON_Delete(root);
|
||||
if (!valid) return error_response(req, "400 Bad Request", "Ungültige Einstellung, Kennung oder Wertart.");
|
||||
if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden.");
|
||||
settings_snapshot_t snapshot;
|
||||
switch (settings_update(&change, expected, &snapshot)) {
|
||||
case SETTINGS_OK: return send_snapshot(req, &snapshot);
|
||||
case SETTINGS_INVALID: return error_response(req, "400 Bad Request", "Wert außerhalb des erlaubten Bereichs oder doppelte Kennung.");
|
||||
case SETTINGS_CONFLICT: return error_response(req, "409 Conflict", "Einstellungen wurden inzwischen geändert. Neu laden und prüfen.");
|
||||
case SETTINGS_STORAGE_ERROR: return error_response(req, "503 Service Unavailable", "Speichern fehlgeschlagen. Die Einstellung wurde nicht übernommen.");
|
||||
case SETTINGS_BUSY: return error_response(req, "503 Service Unavailable", "Eine andere Änderung läuft. Neu laden und erneut versuchen.");
|
||||
default: return error_response(req, "500 Internal Server Error", "Die Einstellung konnte nicht übernommen werden.");
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t disable_wifi(httpd_req_t *req)
|
||||
{
|
||||
if (!trusted_request(req, true))
|
||||
return error_response(req, "403 Forbidden", "Zugriff abgelehnt. Einstellungen neu laden.");
|
||||
cJSON *root = receive_body(req);
|
||||
if (!root) return ESP_FAIL;
|
||||
static const char *const fields[] = {"boot_id"};
|
||||
bool valid = exact_fields(root, fields, 1);
|
||||
bool boot_ok = correct_boot(root);
|
||||
cJSON_Delete(root);
|
||||
if (!valid) return error_response(req, "400 Bad Request", "Ungültige WLAN-Anfrage.");
|
||||
if (!boot_ok) return error_response(req, "409 Conflict", "Das Gerät wurde neu gestartet. Einstellungen neu laden.");
|
||||
response_headers(req);
|
||||
esp_err_t err = httpd_resp_send(req, "{\"ok\":true}", HTTPD_RESP_USE_STRLEN);
|
||||
if (err == ESP_OK) wifi_debug_disable();
|
||||
return err;
|
||||
}
|
||||
|
||||
esp_err_t settings_http_register(httpd_handle_t server, uint32_t boot_id)
|
||||
{
|
||||
snprintf(s_boot, sizeof(s_boot), "%08" PRIx32, boot_id);
|
||||
uint8_t random[16];
|
||||
esp_fill_random(random, sizeof(random)); // Wi-Fi hardware entropy is active.
|
||||
for (size_t i = 0; i < sizeof(random); i++) snprintf(s_token + i * 2, 3, "%02x", random[i]);
|
||||
const httpd_uri_t routes[] = {
|
||||
{.uri = "/api/settings", .method = HTTP_GET, .handler = get_settings},
|
||||
{.uri = "/api/settings", .method = HTTP_POST, .handler = post_settings},
|
||||
{.uri = "/api/wifi/disable", .method = HTTP_POST, .handler = disable_wifi},
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) {
|
||||
esp_err_t err = httpd_register_uri_handler(server, &routes[i]);
|
||||
if (err != ESP_OK) return err;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_http_server.h"
|
||||
|
||||
// Register after starting Wi-Fi so a fresh CSRF token has hardware entropy.
|
||||
esp_err_t settings_http_register(httpd_handle_t server, uint32_t boot_id);
|
||||
+36
-14
@@ -55,8 +55,8 @@ static spi_device_handle_t s_spi;
|
||||
static sx126x_irq_cb_t s_irq_cb;
|
||||
static uint8_t s_rx_payload_len = 255;
|
||||
static int8_t s_tx_dbm = -9;
|
||||
static bool s_tx_fdev_t1; // deviation currently programmed for T-mode TX
|
||||
static SemaphoreHandle_t s_lock; // serializes SPI access across tasks
|
||||
static bool s_pa_low = true; // true = +10 dBm-optimal PA row (lowest output)
|
||||
// Preamble detector length. Shorter = more sensitive but more false syncs,
|
||||
// and every false sync costs one fixed-255-byte RX window (~12 ms).
|
||||
// SX126x codes: 0x00 off, 0x04 = 8 bits, 0x05 = 16, 0x06 = 24, 0x07 = 32.
|
||||
@@ -308,15 +308,11 @@ bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len)
|
||||
uint8_t f[4] = {frf >> 24, frf >> 16, frf >> 8, frf};
|
||||
ok &= cmd(OP_SET_RF_FREQUENCY, f, 4);
|
||||
|
||||
// PA config. SX1262 datasheet table 13-21 documents optimal settings
|
||||
// per target power; we deliberately use the +10 dBm-optimal row
|
||||
// (paDutyCycle=0x01, hpMax=0x00) because it yields the lowest output
|
||||
// this chip supports, and the external KCT8103L PA adds gain after it.
|
||||
// s_pa_low=false selects the +14 dBm row for comparison experiments.
|
||||
ok &= s_pa_low
|
||||
? cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x01, 0x00, 0x00, 0x01}, 4)
|
||||
: cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x02, 0x02, 0x00, 0x01}, 4);
|
||||
ok &= sx126x_set_tx_power(s_tx_dbm);
|
||||
// SX1262 datasheet table 13-21: +14 dBm is the lowest valid optimal
|
||||
// PA row for SX1262. The superficially lower (0x01, 0x00) row is the
|
||||
// +10 dBm SX1261 row and selecting it with deviceSel=SX1262 costs about
|
||||
// 32 dB on this board. The external KCT8103L supplies the remaining gain.
|
||||
ok &= cmd(OP_SET_PA_CONFIG, (uint8_t[]){0x02, 0x02, 0x00, 0x01}, 4);
|
||||
|
||||
// OCP
|
||||
uint8_t ocp = BOARD_SX1262_OCP;
|
||||
@@ -337,6 +333,7 @@ bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len)
|
||||
0x00, 0xB8, 0x52, // fdev
|
||||
};
|
||||
ok &= cmd(OP_SET_MODULATION, mod, 8);
|
||||
s_tx_fdev_t1 = false;
|
||||
|
||||
// Sync word = wM-Bus T/C access code 0x543D. The two C-mode "mode bytes"
|
||||
// (54CD = frame A, 543D = frame B) are received/sent as payload so that
|
||||
@@ -384,7 +381,7 @@ bool sx126x_restore_rx_payload_len(void)
|
||||
bool sx126x_set_tx_power(int8_t dbm)
|
||||
{
|
||||
if (dbm < -9) dbm = -9;
|
||||
if (dbm > 14) dbm = 14; // deliberately capped: external FEM adds gain
|
||||
if (dbm > 2) dbm = 2; // KCT8103L follows; known-good V4.3 firmware uses +2
|
||||
s_tx_dbm = dbm;
|
||||
uint8_t tp[2] = {(uint8_t)dbm, 0x02}; // ramp 40 us
|
||||
return cmd(OP_SET_TX_PARAMS, tp, 2);
|
||||
@@ -423,10 +420,32 @@ bool sx126x_set_rx(void)
|
||||
return cmd(OP_SET_RX, (uint8_t[]){0xFF, 0xFF, 0xFF}, 3);
|
||||
}
|
||||
|
||||
bool sx126x_start_tx(const uint8_t *buf, uint8_t len)
|
||||
// C and T transmit differ only in FSK deviation: 45 kHz (C) vs 50 kHz (T).
|
||||
// RX is unaffected (deviation is a TX-only GFSK parameter; the 234.3 kHz
|
||||
// RX bandwidth covers both), so the swap is done lazily per TX.
|
||||
static bool set_tx_deviation(bool t1)
|
||||
{
|
||||
if (t1 == s_tx_fdev_t1) return true;
|
||||
// fdev(C) = 45e3 * 2^25 / 32e6 = 47186 = 0x00B852
|
||||
// fdev(T) = 50e3 * 2^25 / 32e6 = 52429 = 0x00CCCD
|
||||
uint8_t mod[8] = {
|
||||
0x00, 0x28, 0x00, // bitrate 100 kbps
|
||||
0x00, // no pulse shaping
|
||||
0x0A, // RX BW 234.3 kHz
|
||||
0x00,
|
||||
t1 ? 0xCC : 0xB8,
|
||||
t1 ? 0xCD : 0x52,
|
||||
};
|
||||
if (!cmd(OP_SET_MODULATION, mod, 8)) return false;
|
||||
s_tx_fdev_t1 = t1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sx126x_start_tx_mode(const uint8_t *buf, uint8_t len, bool t1_deviation)
|
||||
{
|
||||
if (!sx126x_standby()) return false;
|
||||
sx126x_clear_irq(SX126X_IRQ_ALL);
|
||||
if (!set_tx_deviation(t1_deviation)) return false;
|
||||
if (!set_packet_params(len)) return false;
|
||||
|
||||
// WriteBuffer needs op + offset + payload in one transaction
|
||||
@@ -445,6 +464,11 @@ bool sx126x_start_tx(const uint8_t *buf, uint8_t len)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sx126x_start_tx(const uint8_t *buf, uint8_t len)
|
||||
{
|
||||
return sx126x_start_tx_mode(buf, len, false);
|
||||
}
|
||||
|
||||
uint16_t sx126x_get_irq(void)
|
||||
{
|
||||
uint8_t st[2] = {0, 0};
|
||||
@@ -519,7 +543,5 @@ uint8_t sx126x_get_status(void)
|
||||
return rx[1];
|
||||
}
|
||||
|
||||
void sx126x_set_pa_low(bool low) { s_pa_low = low; }
|
||||
|
||||
void sx126x_set_preamble_detect(uint8_t code) { s_preamble_det = code; }
|
||||
uint8_t sx126x_get_preamble_detect(void) { return s_preamble_det; }
|
||||
|
||||
@@ -31,7 +31,7 @@ bool sx126x_init(sx126x_diag_t *diag);
|
||||
// rx_payload_len is the fixed RX capture length (we truncate in software).
|
||||
bool sx126x_config_wmbus_c1(uint32_t freq_hz, uint8_t rx_payload_len);
|
||||
|
||||
bool sx126x_set_tx_power(int8_t dbm); // -9 .. +14 (PA config capped)
|
||||
bool sx126x_set_tx_power(int8_t dbm); // -9 .. +2 (external FEM follows)
|
||||
bool sx126x_set_rx(void); // continuous RX, FEM to RX path
|
||||
bool sx126x_standby(void);
|
||||
bool sx126x_config_intact(void); // sync-word readback still correct
|
||||
@@ -40,7 +40,9 @@ bool sx126x_inject_sleep(void); // fault injection: SLEEP, config lost
|
||||
// Transmit buf as GFSK payload (sync word prepended by radio).
|
||||
// Handles FEM CTX switching. Blocking until commands issued; TX-done is
|
||||
// signalled via DIO1/IRQ. timeout handled by caller.
|
||||
bool sx126x_start_tx(const uint8_t *buf, uint8_t len);
|
||||
bool sx126x_start_tx(const uint8_t *buf, uint8_t len); // C-mode deviation
|
||||
// t1_deviation = true selects 50 kHz FSK deviation (T-mode); C uses 45 kHz
|
||||
bool sx126x_start_tx_mode(const uint8_t *buf, uint8_t len, bool t1_deviation);
|
||||
// Restore fixed RX payload length after a TX (packet params are shared).
|
||||
bool sx126x_restore_rx_payload_len(void);
|
||||
|
||||
@@ -59,10 +61,9 @@ bool sx126x_raw(uint8_t op, const uint8_t *args, size_t n_tx,
|
||||
// FEM control (exposed for diagnostics)
|
||||
void fem_set_tx(bool tx);
|
||||
void fem_power(bool on);
|
||||
// Desired FEM/preamble settings are mutated only by the radio owner at a loop boundary.
|
||||
void fem_set_rx_csd(bool en); // LNA experiment: FEM CSD level in RX
|
||||
void sx126x_set_pa_low(bool low); // PA table: true = lowest documented output
|
||||
void sx126x_set_preamble_detect(uint8_t code); // 0x00 off, 0x04=8b, 0x05=16b, 0x06=24b, 0x07=32b
|
||||
uint8_t sx126x_get_preamble_detect(void);
|
||||
|
||||
// Registered by caller before init; invoked from DIO1 GPIO ISR.
|
||||
typedef void (*sx126x_irq_cb_t)(int64_t timestamp_us);
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
// Local status UI: SSD1306 128x64 over I2C + PRG button.
|
||||
// Implements docs/FUTURE_UI.md within its constraints:
|
||||
// - separate low-priority task on core 0 (radio task is pinned to core 1);
|
||||
// rendering can be starved without consequence
|
||||
// - never touches the SX1262: reads g_stats / g_cfg / g_ui snapshots only
|
||||
// - GPIO0 (BOOT strap) is sampled only after boot, debounced
|
||||
// - Vext is driven once at init and never toggled; blanking uses the
|
||||
// panel's display-off command
|
||||
// - every button action that changes behaviour emits a JSON event so the
|
||||
// serial log stays the source of truth
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_timer.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "driver/i2c_master.h"
|
||||
#include "esp_lcd_panel_io.h"
|
||||
#include "esp_lcd_panel_ops.h"
|
||||
#include "esp_lcd_panel_vendor.h"
|
||||
|
||||
#include "board.h"
|
||||
#include "repeater.h"
|
||||
#include "settings.h"
|
||||
#include "duty_ledger.h"
|
||||
#include "wifi_debug.h"
|
||||
#include "wifi_qr.h"
|
||||
#include "font5x7.h"
|
||||
|
||||
#define UI_W 128
|
||||
#define UI_H 64
|
||||
#define UI_COLS 21 // 128 / 6px cell
|
||||
#define UI_ROWS 8 // 64 / 8px cell
|
||||
#define UI_PAGES 6
|
||||
#define UI_TICK_MS 20
|
||||
#define UI_RENDER_TICKS 25 // 500 ms refresh
|
||||
#define UI_DEBOUNCE_TICKS 2 // 40 ms
|
||||
#define UI_LONG_PRESS_MS 1500
|
||||
#define UI_SLEEP_US (180 * 1000000LL)
|
||||
#define UI_BEACON_PERIOD_MS 3000 // long-press toggle value; 907 ppm at L=19
|
||||
|
||||
static esp_lcd_panel_handle_t s_panel;
|
||||
static uint8_t s_fb[UI_W * UI_H / 8];
|
||||
static char s_text[UI_ROWS][UI_COLS + 1];
|
||||
static int s_page;
|
||||
static bool s_on = true;
|
||||
static int64_t s_last_activity;
|
||||
static uint8_t s_wifi_qr[WIFI_QR_BYTES];
|
||||
static bool s_qr_ready;
|
||||
static bool s_show_qr;
|
||||
static const char *s_settings_error;
|
||||
static int64_t s_settings_error_until;
|
||||
|
||||
static void ui_log(const char *cmd, uint32_t value)
|
||||
{
|
||||
printf("{\"event\":\"ui_action\",\"cmd\":\"%s\",\"value\":%" PRIu32 "}\n",
|
||||
cmd, value);
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- rendering
|
||||
|
||||
static void put(int row, const char *fmt, ...)
|
||||
{
|
||||
if (row < 0 || row >= UI_ROWS) return;
|
||||
char buf[UI_COLS + 1];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
snprintf(s_text[row], sizeof(s_text[row]), "%s", buf);
|
||||
}
|
||||
|
||||
static void blit(void)
|
||||
{
|
||||
memset(s_fb, 0, sizeof(s_fb));
|
||||
for (int row = 0; row < UI_ROWS; row++) {
|
||||
for (int col = 0; s_text[row][col] && col < UI_COLS; col++) {
|
||||
unsigned c = (unsigned char)s_text[row][col];
|
||||
if (c < FONT5X7_FIRST || c > FONT5X7_LAST) c = '?';
|
||||
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
|
||||
uint8_t *dst = &s_fb[row * UI_W + col * 6];
|
||||
for (int x = 0; x < FONT5X7_W; x++) dst[x] = g[x];
|
||||
}
|
||||
}
|
||||
if (s_show_qr) {
|
||||
for (int page = 0; page < WIFI_QR_SIDE / 8; page++)
|
||||
memcpy(&s_fb[page * UI_W], &s_wifi_qr[page * WIFI_QR_SIDE], WIFI_QR_SIDE);
|
||||
}
|
||||
esp_lcd_panel_draw_bitmap(s_panel, 0, 0, UI_W, UI_H, s_fb);
|
||||
}
|
||||
|
||||
static void fmt_age(int64_t ts_us, char *out, size_t n)
|
||||
{
|
||||
if (ts_us <= 0) {
|
||||
snprintf(out, n, "--");
|
||||
return;
|
||||
}
|
||||
int64_t s64 = (esp_timer_get_time() - ts_us) / 1000000LL;
|
||||
unsigned s = s64 < 0 ? 0
|
||||
: (s64 > 359999 ? 359999u : (unsigned)s64); // cap 99h
|
||||
if (s < 100) snprintf(out, n, "%us", s);
|
||||
else if (s < 6000) snprintf(out, n, "%um", s / 60);
|
||||
else snprintf(out, n, "%uh", s / 3600);
|
||||
}
|
||||
|
||||
static void fmt_uptime(char *out, size_t n)
|
||||
{
|
||||
int64_t s64 = esp_timer_get_time() / 1000000LL;
|
||||
unsigned s = s64 > 3599999 ? 3599999u : (unsigned)s64; // cap 999h
|
||||
if (s < 3600) snprintf(out, n, "%um%02us", s / 60, s % 60);
|
||||
else snprintf(out, n, "%uh%02um", s / 3600, (s % 3600) / 60);
|
||||
}
|
||||
|
||||
static const char *tx_result_text(const char *result)
|
||||
{
|
||||
if (strcmp(result, "ok") == 0) return "OK";
|
||||
if (strcmp(result, "ok_polled") == 0) return "OK Abfrage";
|
||||
if (strcmp(result, "start_failed") == 0) return "Startfehler";
|
||||
if (strcmp(result, "radio_timeout") == 0) return "Zeitlimit";
|
||||
if (strcmp(result, "irq_timeout") == 0) return "Kein Ende";
|
||||
return "Unbekannt";
|
||||
}
|
||||
|
||||
static void page_status(void)
|
||||
{
|
||||
char up[12], rx_age[8], tx_age[8];
|
||||
fmt_uptime(up, sizeof(up));
|
||||
fmt_age(g_ui.rx_ts_us, rx_age, sizeof(rx_age));
|
||||
fmt_age(g_ui.tx_ts_us, tx_age, sizeof(tx_age));
|
||||
|
||||
put(0, "wM-Bus 868.95 MHz");
|
||||
put(1, "Seit %-7s Wdh %s", up, g_cfg.repeat_enabled ? "EIN" : "AUS");
|
||||
put(2, "RX %-5" PRIu32 " GUT %" PRIu32,
|
||||
g_stats.rx_candidates, g_stats.rx_valid);
|
||||
put(3, "TX %" PRIu32 "/%" PRIu32 " Test %" PRIu32,
|
||||
g_stats.tx_success, g_stats.tx_attempts, g_cfg.beacon_period_ms);
|
||||
if (g_ui.rx_ts_us) {
|
||||
put(4, "Empf. %ddBm %s", (int)g_ui.rx_rssi_dbm, rx_age);
|
||||
} else {
|
||||
put(4, "Empf. --");
|
||||
}
|
||||
if (g_ui.tx_ts_us) {
|
||||
put(5, "TX %s %s", tx_result_text(g_ui.tx_result), tx_age);
|
||||
} else {
|
||||
put(5, "TX --");
|
||||
}
|
||||
|
||||
uint64_t budget = (uint64_t)g_cfg.duty_budget_ppm
|
||||
* DUTY_LEDGER_WINDOW_US / 1000000ULL;
|
||||
if (budget) {
|
||||
uint64_t used = repeater_duty_used_us();
|
||||
unsigned pct = (unsigned)(used * 100 / budget);
|
||||
if (pct > 100) pct = 100;
|
||||
char bar[10];
|
||||
unsigned fill = pct * 9 / 100;
|
||||
for (unsigned i = 0; i < 9; i++) bar[i] = i < fill ? '#' : ' ';
|
||||
bar[9] = 0;
|
||||
put(6, "Sende%3u%% [%s]", pct, bar);
|
||||
} else {
|
||||
put(6, "Sendelimit AUS");
|
||||
}
|
||||
if (g_ui.hb_ts_us) {
|
||||
put(7, "Funk %s Konfig %s",
|
||||
g_ui.chip_mode == 5 ? "RX" : "!!", g_ui.config_intact ? "OK" : "!!");
|
||||
} else {
|
||||
put(7, "Funk --");
|
||||
}
|
||||
}
|
||||
|
||||
static void page_health(void)
|
||||
{
|
||||
put(0, "FUNKZUSTAND");
|
||||
put(1, "Erholt %" PRIu32 " Neu %" PRIu32,
|
||||
g_stats.recoveries, g_stats.radio_reinit + g_stats.fem_reinit);
|
||||
put(2, "CRC-Fehl %" PRIu32 " Lng %" PRIu32,
|
||||
g_stats.rx_crc_fail, g_stats.rx_len_invalid);
|
||||
put(3, "T1 %" PRIu32 " Kein-C1 %" PRIu32,
|
||||
g_stats.rx_t1, g_stats.rx_not_c1);
|
||||
put(4, "Doppelt %" PRIu32 " Limit %" PRIu32,
|
||||
g_stats.tx_suppressed_dup, g_stats.tx_suppressed_duty);
|
||||
put(5, "TX-Frist %" PRIu32 " Fehl %" PRIu32,
|
||||
g_stats.tx_timeout, g_stats.tx_failures);
|
||||
if (g_ui.hb_ts_us) put(6, "Pegel %ddBm", (int)g_ui.rssi_dbm);
|
||||
else put(6, "Pegel --");
|
||||
put(7, "Halten: Zaehler null");
|
||||
}
|
||||
|
||||
static void page_last(void)
|
||||
{
|
||||
put(0, "LETZTES TELEGRAMM");
|
||||
if (!g_ui.rx_ts_us) {
|
||||
put(1, "Noch kein Empfang");
|
||||
for (int i = 2; i < UI_ROWS; i++) put(i, "%s", "");
|
||||
return;
|
||||
}
|
||||
char age[8];
|
||||
fmt_age(g_ui.rx_ts_us, age, sizeof(age));
|
||||
put(1, "Zaehler %08" PRIX32, g_ui.rx_meter_id);
|
||||
put(2, "Laenge %d Format %c", (int)g_ui.rx_len, g_ui.rx_format);
|
||||
put(3, "CRC %s %ddBm",
|
||||
g_ui.rx_crc_ok ? "OK" : "FALSCH", (int)g_ui.rx_rssi_dbm);
|
||||
put(4, "Kennwert %08" PRIx32, g_ui.rx_hash);
|
||||
put(5, "Alter %s", age);
|
||||
put(6, "TX: %s", g_ui.tx_ts_us ? tx_result_text(g_ui.tx_result) : "--");
|
||||
put(7, "%s", "");
|
||||
}
|
||||
|
||||
static void page_config(void)
|
||||
{
|
||||
put(0, "EINSTELLUNGEN");
|
||||
put(1, "Warte %" PRIu32 "ms TX %d",
|
||||
g_cfg.repeat_delay_ms, (int)g_cfg.tx_power_dbm);
|
||||
put(2, "Funklimit %" PRIu32 "ppm", g_cfg.duty_budget_ppm);
|
||||
if (g_cfg.beacon_period_ms) put(3, "Testsignal %" PRIu32 "ms", g_cfg.beacon_period_ms);
|
||||
else put(3, "Testsignal AUS");
|
||||
put(4, "Wiederholen %s", g_cfg.repeat_enabled ? "EIN" : "AUS");
|
||||
put(5, "Erlaubte IDs %d", g_cfg.whitelist_len);
|
||||
put(6, "%s", "");
|
||||
put(7, "Halten: Test ein/aus");
|
||||
}
|
||||
|
||||
static void page_wifi(void)
|
||||
{
|
||||
wifi_debug_status_t wifi;
|
||||
wifi_debug_status(&wifi);
|
||||
for (int i = 0; i < UI_ROWS; i++) put(i, "%s", "");
|
||||
put(0, "WLAN-DIAGNOSE");
|
||||
switch (wifi.state) {
|
||||
case WIFI_DEBUG_ON:
|
||||
put(1, "EIN - kein Internet");
|
||||
put(2, "%s", wifi.ssid);
|
||||
put(3, "Passwort %s", wifi.password);
|
||||
put(4, "http://192.168.4.1");
|
||||
put(6, "Weiter: WLAN-QR-Code");
|
||||
put(7, "Halten: WLAN aus");
|
||||
break;
|
||||
case WIFI_DEBUG_STARTING:
|
||||
put(2, "Startet...");
|
||||
break;
|
||||
case WIFI_DEBUG_STOPPING:
|
||||
put(2, "Wird beendet...");
|
||||
break;
|
||||
case WIFI_DEBUG_ERROR:
|
||||
put(2, "Fehler 0x%" PRIX32, (uint32_t)wifi.error);
|
||||
put(7, "Halten: Neu versuchen");
|
||||
break;
|
||||
default:
|
||||
put(2, "AUS");
|
||||
put(4, "Diagnose per Handy");
|
||||
put(7, "Halten: WLAN ein");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void page_wifi_qr(void)
|
||||
{
|
||||
wifi_debug_status_t wifi;
|
||||
wifi_debug_status(&wifi);
|
||||
if (wifi.state != WIFI_DEBUG_ON) {
|
||||
page_wifi();
|
||||
return;
|
||||
}
|
||||
// Credentials are generated once and cannot change through the UI/API.
|
||||
if (!s_qr_ready) s_qr_ready = wifi_qr_bitmap(wifi.ssid, wifi.password, s_wifi_qr);
|
||||
if (!s_qr_ready) {
|
||||
page_wifi();
|
||||
put(6, "QR defekt: Passwort");
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < UI_ROWS; i++) put(i, "%s", "");
|
||||
put(0, " WLAN: QR");
|
||||
put(1, " scannen");
|
||||
put(3, " Oeffnen:");
|
||||
put(4, " 192.168.");
|
||||
put(5, " 4.1");
|
||||
put(7, " Halten:AUS");
|
||||
s_show_qr = true;
|
||||
}
|
||||
|
||||
static void render(void)
|
||||
{
|
||||
s_show_qr = false;
|
||||
switch (s_page) {
|
||||
case 0: page_status(); break;
|
||||
case 1: page_health(); break;
|
||||
case 2: page_last(); break;
|
||||
case 3: page_config(); break;
|
||||
case 4: page_wifi(); break;
|
||||
default: page_wifi_qr(); break;
|
||||
}
|
||||
if (s_settings_error && esp_timer_get_time() < s_settings_error_until)
|
||||
put(6, "%s", s_settings_error);
|
||||
blit();
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- actions
|
||||
|
||||
static void toggle_setting(settings_key_t key)
|
||||
{
|
||||
settings_result_t result = SETTINGS_CONFLICT;
|
||||
settings_change_t change = {.key = key};
|
||||
// Toggle the accepted state, not g_cfg (which may still be pending).
|
||||
// Revision CAS prevents an intervening web/USB edit from being overwritten.
|
||||
for (unsigned attempt = 0; attempt < 3; attempt++) {
|
||||
settings_snapshot_t snapshot;
|
||||
settings_get_snapshot(&snapshot);
|
||||
change.value = key == SETTINGS_REPEAT_ENABLED
|
||||
? !snapshot.values.repeat_enabled
|
||||
: (snapshot.values.beacon_period_ms ? 0 : UI_BEACON_PERIOD_MS);
|
||||
result = settings_update(&change, snapshot.revision, NULL);
|
||||
if (result != SETTINGS_CONFLICT) break;
|
||||
}
|
||||
const char *command = key == SETTINGS_REPEAT_ENABLED
|
||||
? "set repeat_enabled" : "set beacon_period_ms";
|
||||
if (result == SETTINGS_OK) {
|
||||
s_settings_error = NULL;
|
||||
ui_log(command, (uint32_t)change.value);
|
||||
return;
|
||||
}
|
||||
switch (result) {
|
||||
case SETTINGS_CONFLICT: s_settings_error = "Geaendert: neu halten"; break;
|
||||
case SETTINGS_STORAGE_ERROR: s_settings_error = "Speichern gescheitert"; break;
|
||||
case SETTINGS_INVALID: s_settings_error = "Wert ungueltig"; break;
|
||||
default: s_settings_error = "Belegt: neu halten"; break;
|
||||
}
|
||||
s_settings_error_until = esp_timer_get_time() + 5000000LL;
|
||||
printf("{\"event\":\"ui_action\",\"cmd\":\"%s\",\"ok\":false,\"error\":\"%s\"}\n",
|
||||
command, s_settings_error);
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
static void long_action(void)
|
||||
{
|
||||
switch (s_page) {
|
||||
case 0:
|
||||
toggle_setting(SETTINGS_REPEAT_ENABLED);
|
||||
break;
|
||||
case 1:
|
||||
memset(&g_stats, 0, sizeof(g_stats));
|
||||
ui_log("clear_stats", 1);
|
||||
break;
|
||||
case 3:
|
||||
toggle_setting(SETTINGS_BEACON_PERIOD_MS);
|
||||
break;
|
||||
case 4:
|
||||
case 5:
|
||||
ui_log("wifi_debug_toggle", 1);
|
||||
wifi_debug_toggle();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void set_display(bool on)
|
||||
{
|
||||
if (on == s_on) return;
|
||||
s_on = on;
|
||||
esp_lcd_panel_disp_on_off(s_panel, on);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ bring-up
|
||||
|
||||
static bool hw_init(void)
|
||||
{
|
||||
// External rail on (active low), then let it settle before touching
|
||||
// the panel. Never toggled again (docs/FUTURE_UI.md constraint 4).
|
||||
gpio_config_t vext = {
|
||||
.pin_bit_mask = 1ULL << BOARD_VEXT,
|
||||
.mode = GPIO_MODE_OUTPUT,
|
||||
};
|
||||
if (gpio_config(&vext) != ESP_OK) return false;
|
||||
gpio_set_level(BOARD_VEXT, 0);
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
|
||||
gpio_config_t btn = {
|
||||
.pin_bit_mask = 1ULL << BOARD_BTN_PRG,
|
||||
.mode = GPIO_MODE_INPUT,
|
||||
.pull_up_en = GPIO_PULLUP_ENABLE,
|
||||
};
|
||||
if (gpio_config(&btn) != ESP_OK) return false;
|
||||
|
||||
i2c_master_bus_config_t bus_cfg = {
|
||||
.i2c_port = I2C_NUM_0,
|
||||
.sda_io_num = BOARD_OLED_SDA,
|
||||
.scl_io_num = BOARD_OLED_SCL,
|
||||
.clk_source = I2C_CLK_SRC_DEFAULT,
|
||||
.glitch_ignore_cnt = 7,
|
||||
.flags.enable_internal_pullup = true,
|
||||
};
|
||||
i2c_master_bus_handle_t bus;
|
||||
if (i2c_new_master_bus(&bus_cfg, &bus) != ESP_OK) return false;
|
||||
|
||||
esp_lcd_panel_io_i2c_config_t io_cfg = {
|
||||
.dev_addr = 0x3C,
|
||||
.scl_speed_hz = 400000,
|
||||
.control_phase_bytes = 1,
|
||||
.lcd_cmd_bits = 8,
|
||||
.lcd_param_bits = 8,
|
||||
.dc_bit_offset = 6,
|
||||
};
|
||||
esp_lcd_panel_io_handle_t io;
|
||||
if (esp_lcd_new_panel_io_i2c(bus, &io_cfg, &io) != ESP_OK) return false;
|
||||
|
||||
esp_lcd_panel_ssd1306_config_t ssd_cfg = { .height = UI_H };
|
||||
esp_lcd_panel_dev_config_t panel_cfg = {
|
||||
.bits_per_pixel = 1,
|
||||
.reset_gpio_num = BOARD_OLED_RST,
|
||||
.vendor_config = &ssd_cfg,
|
||||
};
|
||||
if (esp_lcd_new_panel_ssd1306(io, &panel_cfg, &s_panel) != ESP_OK) return false;
|
||||
if (esp_lcd_panel_reset(s_panel) != ESP_OK) return false;
|
||||
if (esp_lcd_panel_init(s_panel) != ESP_OK) return false;
|
||||
// Heltec mounts the module rotated 180 degrees; matches the vendor
|
||||
// examples' flipScreenVertically().
|
||||
esp_lcd_panel_mirror(s_panel, true, true);
|
||||
return esp_lcd_panel_disp_on_off(s_panel, true) == ESP_OK;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- task
|
||||
|
||||
static void ui_task(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
// The radio task owns boot; give it time to bring the RF path up
|
||||
// before the I2C bus starts drawing current and printing.
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
bool ok = hw_init();
|
||||
printf("{\"event\":\"ui_init\",\"ok\":%s}\n", ok ? "true" : "false");
|
||||
fflush(stdout);
|
||||
if (!ok) vTaskDelete(NULL);
|
||||
|
||||
s_last_activity = esp_timer_get_time();
|
||||
int render_div = 0;
|
||||
int held_ticks = 0;
|
||||
bool long_fired = false;
|
||||
bool was_off_at_press = false;
|
||||
render();
|
||||
|
||||
for (;;) {
|
||||
vTaskDelay(pdMS_TO_TICKS(UI_TICK_MS));
|
||||
bool pressed = gpio_get_level(BOARD_BTN_PRG) == 0;
|
||||
|
||||
if (pressed) {
|
||||
if (held_ticks == 0) was_off_at_press = !s_on;
|
||||
held_ticks++;
|
||||
if (!long_fired
|
||||
&& held_ticks * UI_TICK_MS >= UI_LONG_PRESS_MS) {
|
||||
long_fired = true;
|
||||
s_last_activity = esp_timer_get_time();
|
||||
set_display(true);
|
||||
if (!was_off_at_press) long_action();
|
||||
render();
|
||||
}
|
||||
} else {
|
||||
if (held_ticks >= UI_DEBOUNCE_TICKS && !long_fired) {
|
||||
s_last_activity = esp_timer_get_time();
|
||||
if (s_on && !was_off_at_press) {
|
||||
s_page = (s_page + 1) % UI_PAGES;
|
||||
}
|
||||
set_display(true);
|
||||
render();
|
||||
}
|
||||
held_ticks = 0;
|
||||
long_fired = false;
|
||||
}
|
||||
|
||||
if (s_on && esp_timer_get_time() - s_last_activity > UI_SLEEP_US) {
|
||||
set_display(false);
|
||||
}
|
||||
if (s_on && ++render_div >= UI_RENDER_TICKS) {
|
||||
render_div = 0;
|
||||
render();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ui_start(void)
|
||||
{
|
||||
xTaskCreatePinnedToCore(ui_task, "ui", 4096, NULL, 3, NULL, 0);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Local SSD1306 + PRG-button status UI (docs/FUTURE_UI.md).
|
||||
// Non-fatal: if the display is absent or I2C init fails, the task logs
|
||||
// {"event":"ui_init","ok":false} and exits; the repeater is unaffected.
|
||||
#pragma once
|
||||
|
||||
void ui_start(void);
|
||||
Vendored
+1022
File diff suppressed because it is too large
Load Diff
Vendored
+385
@@ -0,0 +1,385 @@
|
||||
/*
|
||||
* QR Code generator library (C)
|
||||
*
|
||||
* Copyright (c) Project Nayuki. (MIT License)
|
||||
* https://www.nayuki.io/page/qr-code-generator-library
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* This library creates QR Code symbols, which is a type of two-dimension barcode.
|
||||
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
|
||||
* A QR Code structure is an immutable square grid of dark and light cells.
|
||||
* The library provides functions to create a QR Code from text or binary data.
|
||||
* The library covers the QR Code Model 2 specification, supporting all versions (sizes)
|
||||
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
|
||||
*
|
||||
* Ways to create a QR Code object:
|
||||
* - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary().
|
||||
* - Low level: Custom-make the list of segments and call
|
||||
* qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced().
|
||||
* (Note that all ways require supplying the desired error correction level and various byte buffers.)
|
||||
*/
|
||||
|
||||
|
||||
/*---- Enum and struct types----*/
|
||||
|
||||
/*
|
||||
* The error correction level in a QR Code symbol.
|
||||
*/
|
||||
enum qrcodegen_Ecc {
|
||||
// Must be declared in ascending order of error protection
|
||||
// so that an internal qrcodegen function works properly
|
||||
qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords
|
||||
qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords
|
||||
qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords
|
||||
qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* The mask pattern used in a QR Code symbol.
|
||||
*/
|
||||
enum qrcodegen_Mask {
|
||||
// A special value to tell the QR Code encoder to
|
||||
// automatically select an appropriate mask pattern
|
||||
qrcodegen_Mask_AUTO = -1,
|
||||
// The eight actual mask patterns
|
||||
qrcodegen_Mask_0 = 0,
|
||||
qrcodegen_Mask_1,
|
||||
qrcodegen_Mask_2,
|
||||
qrcodegen_Mask_3,
|
||||
qrcodegen_Mask_4,
|
||||
qrcodegen_Mask_5,
|
||||
qrcodegen_Mask_6,
|
||||
qrcodegen_Mask_7,
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* Describes how a segment's data bits are interpreted.
|
||||
*/
|
||||
enum qrcodegen_Mode {
|
||||
qrcodegen_Mode_NUMERIC = 0x1,
|
||||
qrcodegen_Mode_ALPHANUMERIC = 0x2,
|
||||
qrcodegen_Mode_BYTE = 0x4,
|
||||
qrcodegen_Mode_KANJI = 0x8,
|
||||
qrcodegen_Mode_ECI = 0x7,
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* A segment of character/binary/control data in a QR Code symbol.
|
||||
* The mid-level way to create a segment is to take the payload data
|
||||
* and call a factory function such as qrcodegen_makeNumeric().
|
||||
* The low-level way to create a segment is to custom-make the bit buffer
|
||||
* and initialize a qrcodegen_Segment struct with appropriate values.
|
||||
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
|
||||
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
|
||||
* Moreover, the maximum allowed bit length is 32767 because
|
||||
* the largest QR Code (version 40) has 31329 modules.
|
||||
*/
|
||||
struct qrcodegen_Segment {
|
||||
// The mode indicator of this segment.
|
||||
enum qrcodegen_Mode mode;
|
||||
|
||||
// The length of this segment's unencoded data. Measured in characters for
|
||||
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
|
||||
// Always zero or positive. Not the same as the data's bit length.
|
||||
int numChars;
|
||||
|
||||
// The data bits of this segment, packed in bitwise big endian.
|
||||
// Can be null if the bit length is zero.
|
||||
uint8_t *data;
|
||||
|
||||
// The number of valid data bits used in the buffer. Requires
|
||||
// 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8.
|
||||
// The character count (numChars) must agree with the mode and the bit buffer length.
|
||||
int bitLength;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*---- Macro constants and functions ----*/
|
||||
|
||||
#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard
|
||||
#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard
|
||||
|
||||
// Calculates the number of bytes needed to store any QR Code up to and including the given version number,
|
||||
// as a compile-time constant. For example, 'uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];'
|
||||
// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16).
|
||||
// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX.
|
||||
#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) ((((n) * 4 + 17) * ((n) * 4 + 17) + 7) / 8 + 1)
|
||||
|
||||
// The worst-case number of bytes needed to store one QR Code, up to and including
|
||||
// version 40. This value equals 3918, which is just under 4 kilobytes.
|
||||
// Use this more convenient value to avoid calculating tighter memory bounds for buffers.
|
||||
#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX)
|
||||
|
||||
|
||||
|
||||
/*---- Functions (high level) to generate QR Codes ----*/
|
||||
|
||||
/*
|
||||
* Encodes the given text string to a QR Code, returning true if successful.
|
||||
* If the data is too long to fit in any version in the given range
|
||||
* at the given ECC level, then false is returned.
|
||||
*
|
||||
* The input text must be encoded in UTF-8 and contain no NULs.
|
||||
* Requires 1 <= minVersion <= maxVersion <= 40.
|
||||
*
|
||||
* The smallest possible QR Code version within the given range is automatically
|
||||
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
|
||||
* may be higher than the ecl argument if it can be done without increasing the
|
||||
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
|
||||
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
|
||||
*
|
||||
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
|
||||
* - Before calling the function:
|
||||
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
|
||||
* reading and writing; hence each array must have a length of at least len.
|
||||
* - The two ranges must not overlap (aliasing).
|
||||
* - The initial state of both ranges can be uninitialized
|
||||
* because the function always writes before reading.
|
||||
* - After the function returns:
|
||||
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
|
||||
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
|
||||
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
|
||||
*
|
||||
* If successful, the resulting QR Code may use numeric,
|
||||
* alphanumeric, or byte mode to encode the text.
|
||||
*
|
||||
* In the most optimistic case, a QR Code at version 40 with low ECC
|
||||
* can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string
|
||||
* up to 4296 characters, or any digit string up to 7089 characters.
|
||||
* These numbers represent the hard upper limit of the QR Code standard.
|
||||
*
|
||||
* Please consult the QR Code specification for information on
|
||||
* data capacities per version, ECC level, and text encoding mode.
|
||||
*/
|
||||
bool qrcodegen_encodeText(const char *text, uint8_t tempBuffer[], uint8_t qrcode[],
|
||||
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
|
||||
|
||||
|
||||
/*
|
||||
* Encodes the given binary data to a QR Code, returning true if successful.
|
||||
* If the data is too long to fit in any version in the given range
|
||||
* at the given ECC level, then false is returned.
|
||||
*
|
||||
* Requires 1 <= minVersion <= maxVersion <= 40.
|
||||
*
|
||||
* The smallest possible QR Code version within the given range is automatically
|
||||
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
|
||||
* may be higher than the ecl argument if it can be done without increasing the
|
||||
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
|
||||
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
|
||||
*
|
||||
* About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion):
|
||||
* - Before calling the function:
|
||||
* - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow
|
||||
* reading and writing; hence each array must have a length of at least len.
|
||||
* - The two ranges must not overlap (aliasing).
|
||||
* - The input array range dataAndTemp[0 : dataLen] should normally be
|
||||
* valid UTF-8 text, but is not required by the QR Code standard.
|
||||
* - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len]
|
||||
* can be uninitialized because the function always writes before reading.
|
||||
* - After the function returns:
|
||||
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
|
||||
* - dataAndTemp contains no useful data and should be treated as entirely uninitialized.
|
||||
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
|
||||
*
|
||||
* If successful, the resulting QR Code will use byte mode to encode the data.
|
||||
*
|
||||
* In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte
|
||||
* sequence up to length 2953. This is the hard upper limit of the QR Code standard.
|
||||
*
|
||||
* Please consult the QR Code specification for information on
|
||||
* data capacities per version, ECC level, and text encoding mode.
|
||||
*/
|
||||
bool qrcodegen_encodeBinary(uint8_t dataAndTemp[], size_t dataLen, uint8_t qrcode[],
|
||||
enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl);
|
||||
|
||||
|
||||
/*---- Functions (low level) to generate QR Codes ----*/
|
||||
|
||||
/*
|
||||
* Encodes the given segments to a QR Code, returning true if successful.
|
||||
* If the data is too long to fit in any version at the given ECC level,
|
||||
* then false is returned.
|
||||
*
|
||||
* The smallest possible QR Code version is automatically chosen for
|
||||
* the output. The ECC level of the result may be higher than the
|
||||
* ecl argument if it can be done without increasing the version.
|
||||
*
|
||||
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
|
||||
* - Before calling the function:
|
||||
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
|
||||
* reading and writing; hence each array must have a length of at least len.
|
||||
* - The two ranges must not overlap (aliasing).
|
||||
* - The initial state of both ranges can be uninitialized
|
||||
* because the function always writes before reading.
|
||||
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
|
||||
* - After the function returns:
|
||||
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
|
||||
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
|
||||
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
|
||||
* must be treated as having invalid values in that array.
|
||||
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
|
||||
*
|
||||
* Please consult the QR Code specification for information on
|
||||
* data capacities per version, ECC level, and text encoding mode.
|
||||
*
|
||||
* This function allows the user to create a custom sequence of segments that switches
|
||||
* between modes (such as alphanumeric and byte) to encode text in less space.
|
||||
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
|
||||
*/
|
||||
bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len,
|
||||
enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]);
|
||||
|
||||
|
||||
/*
|
||||
* Encodes the given segments to a QR Code, returning true if successful.
|
||||
* If the data is too long to fit in any version in the given range
|
||||
* at the given ECC level, then false is returned.
|
||||
*
|
||||
* Requires 1 <= minVersion <= maxVersion <= 40.
|
||||
*
|
||||
* The smallest possible QR Code version within the given range is automatically
|
||||
* chosen for the output. Iff boostEcl is true, then the ECC level of the result
|
||||
* may be higher than the ecl argument if it can be done without increasing the
|
||||
* version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or
|
||||
* qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow).
|
||||
*
|
||||
* About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX):
|
||||
* - Before calling the function:
|
||||
* - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow
|
||||
* reading and writing; hence each array must have a length of at least len.
|
||||
* - The two ranges must not overlap (aliasing).
|
||||
* - The initial state of both ranges can be uninitialized
|
||||
* because the function always writes before reading.
|
||||
* - The input array segs can contain segments whose data buffers overlap with tempBuffer.
|
||||
* - After the function returns:
|
||||
* - Both ranges have no guarantee on which elements are initialized and what values are stored.
|
||||
* - tempBuffer contains no useful data and should be treated as entirely uninitialized.
|
||||
* - Any segment whose data buffer overlaps with tempBuffer[0 : len]
|
||||
* must be treated as having invalid values in that array.
|
||||
* - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule().
|
||||
*
|
||||
* Please consult the QR Code specification for information on
|
||||
* data capacities per version, ECC level, and text encoding mode.
|
||||
*
|
||||
* This function allows the user to create a custom sequence of segments that switches
|
||||
* between modes (such as alphanumeric and byte) to encode text in less space.
|
||||
* This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary().
|
||||
*/
|
||||
bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl,
|
||||
int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint8_t tempBuffer[], uint8_t qrcode[]);
|
||||
|
||||
|
||||
/*
|
||||
* Tests whether the given string can be encoded as a segment in numeric mode.
|
||||
* A string is encodable iff each character is in the range 0 to 9.
|
||||
*/
|
||||
bool qrcodegen_isNumeric(const char *text);
|
||||
|
||||
|
||||
/*
|
||||
* Tests whether the given string can be encoded as a segment in alphanumeric mode.
|
||||
* A string is encodable iff each character is in the following set: 0 to 9, A to Z
|
||||
* (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
|
||||
*/
|
||||
bool qrcodegen_isAlphanumeric(const char *text);
|
||||
|
||||
|
||||
/*
|
||||
* Returns the number of bytes (uint8_t) needed for the data buffer of a segment
|
||||
* containing the given number of characters using the given mode. Notes:
|
||||
* - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal
|
||||
* calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767).
|
||||
* - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096.
|
||||
* - It is okay for the user to allocate more bytes for the buffer than needed.
|
||||
* - For byte mode, numChars measures the number of bytes, not Unicode code points.
|
||||
* - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned.
|
||||
* An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
|
||||
*/
|
||||
size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars);
|
||||
|
||||
|
||||
/*
|
||||
* Returns a segment representing the given binary data encoded in
|
||||
* byte mode. All input byte arrays are acceptable. Any text string
|
||||
* can be converted to UTF-8 bytes and encoded as a byte mode segment.
|
||||
*/
|
||||
struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]);
|
||||
|
||||
|
||||
/*
|
||||
* Returns a segment representing the given string of decimal digits encoded in numeric mode.
|
||||
*/
|
||||
struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]);
|
||||
|
||||
|
||||
/*
|
||||
* Returns a segment representing the given text string encoded in alphanumeric mode.
|
||||
* The characters allowed are: 0 to 9, A to Z (uppercase only), space,
|
||||
* dollar, percent, asterisk, plus, hyphen, period, slash, colon.
|
||||
*/
|
||||
struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]);
|
||||
|
||||
|
||||
/*
|
||||
* Returns a segment representing an Extended Channel Interpretation
|
||||
* (ECI) designator with the given assignment value.
|
||||
*/
|
||||
struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]);
|
||||
|
||||
|
||||
/*---- Functions to extract raw data from QR Codes ----*/
|
||||
|
||||
/*
|
||||
* Returns the side length of the given QR Code, assuming that encoding succeeded.
|
||||
* The result is in the range [21, 177]. Note that the length of the array buffer
|
||||
* is related to the side length - every 'uint8_t qrcode[]' must have length at least
|
||||
* qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1).
|
||||
*/
|
||||
int qrcodegen_getSize(const uint8_t qrcode[]);
|
||||
|
||||
|
||||
/*
|
||||
* Returns the color of the module (pixel) at the given coordinates, which is false
|
||||
* for light or true for dark. The top left corner has the coordinates (x=0, y=0).
|
||||
* If the given coordinates are out of bounds, then false (light) is returned.
|
||||
*/
|
||||
bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,212 @@
|
||||
/* Lokale Oberfläche ohne externe Schriften oder Ressourcen. */
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--page: #f2f5f5; --surface: #fff; --ink: #173039; --muted: #52666d;
|
||||
--line: #d9e2e3; --accent: #126b69; --accent-soft: #e7f3ef;
|
||||
--warn: #815211; --warn-bg: #fff5df; --bad: #a13034; --bad-bg: #fff0ef;
|
||||
--header: #102f37; --focus: #007baf; --shade: #f7f9f9;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 16px; line-height: 1.5;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--page); color: var(--ink); }
|
||||
button, input { font: inherit; color: inherit; }
|
||||
button, input[type="search"], .file-picker { border: 1px solid var(--line); border-radius: 7px; background: var(--surface); }
|
||||
button, .file-picker { cursor: pointer; min-height: 44px; padding: 9px 12px; font-size: .875rem; font-weight: 600; overflow-wrap: anywhere; }
|
||||
button:hover:not(:disabled), .file-picker:hover { border-color: var(--accent); background: var(--accent-soft); }
|
||||
button[aria-pressed="true"] { color: var(--warn); border-color: var(--warn); background: var(--warn-bg); }
|
||||
button:disabled { cursor: not-allowed; opacity: .5; }
|
||||
:focus-visible, .file-input:focus-visible + .file-picker { outline: 3px solid var(--focus); outline-offset: 3px; }
|
||||
a { color: var(--accent); text-underline-offset: 3px; }
|
||||
input[type="search"] { display: block; width: 100%; min-width: 0; min-height: 44px; padding: 9px 10px; }
|
||||
input[type="checkbox"] { accent-color: var(--accent); width: 20px; height: 20px; margin: 0; flex: 0 0 auto; }
|
||||
label { font-size: .875rem; font-weight: 600; }
|
||||
h1, h2, h3, p, dl { margin: 0; }
|
||||
h1 { font-size: clamp(1.5rem, 4vw, 2rem); letter-spacing: -.035em; line-height: 1.15; }
|
||||
h2 { font-size: 1.08rem; letter-spacing: -.02em; }
|
||||
h3 { font-size: .875rem; font-weight: 600; }
|
||||
p, h2, h3, summary { overflow-wrap: anywhere; }
|
||||
.shell { width: min(1200px, calc(100% - 40px)); margin: 0 auto; }
|
||||
.masthead { background: var(--header); color: #f2faf9; padding: 16px 0; border-bottom: 3px solid #4caaa0; }
|
||||
.heading-row, .section-heading, .table-meta, .footer { display: flex; justify-content: space-between; gap: 12px; align-items: center; }
|
||||
.heading-row > *, .section-heading > *, .button-row > * { min-width: 0; max-width: 100%; }
|
||||
.heading-with-help { display: flex; align-items: center; gap: 3px; min-width: 0; }
|
||||
.heading-with-help > :first-child { min-width: 0; }
|
||||
.eyebrow { color: #acd4ce; font-size: .68rem; letter-spacing: .1em; font-weight: 700; margin-bottom: 4px; }
|
||||
.connection-box { display: flex; align-items: flex-end; flex-direction: column; gap: 4px; text-align: right; }
|
||||
.connection-box .small { color: #bed1d5; }
|
||||
main { padding-top: 12px; }
|
||||
.small { font-size: .8rem; color: var(--muted); line-height: 1.5; }
|
||||
.mono, .metric, .counters dd, .activity dd { font-variant-numeric: tabular-nums; }
|
||||
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; overflow-wrap: anywhere; }
|
||||
.notice { padding: 10px 12px; border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: 6px; background: var(--surface); font-size: .85rem; margin-bottom: 12px; overflow-wrap: anywhere; }
|
||||
.notice.warning { border-left-color: var(--warn); color: var(--warn); background: var(--warn-bg); }
|
||||
.notice.danger { border-left-color: var(--bad); color: var(--bad); background: var(--bad-bg); }
|
||||
.operation { padding: 0 2px 14px; }
|
||||
#operation-state { font-weight: 600; font-size: .95rem; }
|
||||
#operation-detail { margin-top: 2px; }
|
||||
.section-heading { margin-bottom: 12px; flex-wrap: wrap; }
|
||||
.health-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
|
||||
.card { padding: 14px; background: var(--surface); border: 1px solid var(--line); border-radius: 9px; min-width: 0; }
|
||||
.card h3 { color: var(--muted); }
|
||||
.metric { font-size: 1.35rem; line-height: 1.25; font-weight: 650; letter-spacing: -.025em; margin: 4px 0 9px; }
|
||||
.card .small + .small { margin-top: 3px; }
|
||||
.good-text { color: var(--accent); }
|
||||
.warning-text { color: var(--warn); }
|
||||
.danger-text { color: var(--bad); }
|
||||
progress { width: 100%; height: 7px; appearance: none; border: 0; border-radius: 6px; display: block; margin: 12px 0; background: var(--line); accent-color: var(--accent); overflow: hidden; }
|
||||
progress::-webkit-progress-bar { background: var(--line); }
|
||||
progress::-webkit-progress-value { background: var(--accent); border-radius: 6px; }
|
||||
progress::-moz-progress-bar { background: var(--accent); border-radius: 6px; }
|
||||
.activity { margin: 7px 0 12px; font-size: .85rem; }
|
||||
.activity div { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 10px; margin-bottom: 6px; }
|
||||
.activity dd { margin: 0; font-weight: 650; }
|
||||
.activity dt { color: var(--muted); }
|
||||
.counters-heading { margin: 14px 0 8px; }
|
||||
.counters { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 10px; }
|
||||
.counters > div { border-left: 2px solid var(--line); padding: 5px 10px; min-width: 0; overflow-wrap: anywhere; }
|
||||
.counters dd { font-size: 1.35rem; font-weight: 650; margin: 0; }
|
||||
.counters dt { font-size: .75rem; color: var(--muted); }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; margin-bottom: 16px; }
|
||||
.panel-heading { padding: 10px 16px; border-bottom: 1px solid var(--line); }
|
||||
.button-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.event-tools { padding: 10px 16px 0; }
|
||||
.filters { display: flex; align-items: center; gap: 16px; padding: 10px 16px; }
|
||||
.search-field { flex: 1; min-width: 0; }
|
||||
.checkbox, .filter-errors { display: flex; align-items: center; gap: 8px; min-height: 44px; }
|
||||
.checkbox { cursor: pointer; }
|
||||
.filter-errors { gap: 0; flex: 0 0 auto; }
|
||||
.panel > .notice { margin: 0 16px 10px; }
|
||||
.table-meta { font-size: .75rem; color: var(--muted); padding: 0 16px 8px; flex-wrap: wrap; overflow-wrap: anywhere; }
|
||||
.table-wrap { width: 100%; }
|
||||
table { width: 100%; border-collapse: collapse; table-layout: fixed; text-align: left; }
|
||||
th { color: var(--muted); font-size: .75rem; background: var(--shade); font-weight: 650; overflow-wrap: anywhere; }
|
||||
th, td { padding: 10px 16px; vertical-align: top; border-top: 1px solid var(--line); }
|
||||
th { vertical-align: middle; }
|
||||
th.time-col { width: 16%; }
|
||||
th.radio-col { width: 18%; }
|
||||
th:last-child { width: 27%; }
|
||||
td { font-size: .85rem; overflow-wrap: anywhere; }
|
||||
td .sub { display: block; font-size: .75rem; color: var(--muted); margin-top: 3px; }
|
||||
td .mobile-radio { display: none; }
|
||||
.sender-label { display: block; font-weight: 650; white-space: pre-wrap; overflow-wrap: anywhere; margin-bottom: 3px; }
|
||||
.sender-id { font-size: .9rem; font-weight: 600; }
|
||||
.badge { display: inline-block; max-width: 100%; border: 1px solid transparent; padding: 3px 7px; border-radius: 5px; font-size: .75rem; font-weight: 650; line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.badge.good { color: var(--accent); background: var(--accent-soft); }
|
||||
.badge.warning { color: var(--warn); background: var(--warn-bg); }
|
||||
.badge.danger { color: var(--bad); background: var(--bad-bg); }
|
||||
.badge.neutral { color: var(--muted); background: var(--shade); border-color: var(--line); }
|
||||
.row-flag { color: var(--warn) !important; }
|
||||
.detail-toggle { display: block; min-height: 44px; max-width: 100%; padding: 6px 0; margin-top: 3px; background: transparent; border: 0; font-size: .75rem; color: var(--accent); text-decoration: underline; text-underline-offset: 3px; text-align: left; }
|
||||
.detail-toggle:hover:not(:disabled) { background: transparent; }
|
||||
.detail-row > td { padding: 14px 16px; background: var(--shade); border-top-style: dashed; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 13px 20px; }
|
||||
.detail-grid > div { min-width: 0; }
|
||||
.detail-grid dt { color: var(--muted); font-size: .75rem; margin-bottom: 3px; }
|
||||
.detail-grid dd { margin: 0; white-space: pre-wrap; font-size: .8rem; overflow-wrap: anywhere; }
|
||||
.detail-row .notice { margin: 12px 0 0; }
|
||||
.detail-explanation { margin: 13px 0 0; }
|
||||
.empty { text-align: center; padding: 28px 16px; font-size: .9rem; color: var(--muted); }
|
||||
.panel-footer { border-top: 1px solid var(--line); background: var(--shade); padding: 10px 16px; border-radius: 0 0 10px 10px; }
|
||||
.diagnostic-content, .label-content { padding: 12px 16px 16px; }
|
||||
.label-content p { margin-top: 8px; }
|
||||
.label-content .button-row { margin-top: 12px; }
|
||||
#label-result { white-space: pre-wrap; }
|
||||
.settings-content { padding: 12px 16px 16px; }
|
||||
.settings-draft-note { margin-top: 6px; }
|
||||
#settings-status { margin: 12px 0 6px; }
|
||||
#settings-revision { overflow-wrap: anywhere; }
|
||||
.settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 14px; }
|
||||
.setting-field { min-width: 0; border: 1px solid var(--line); border-radius: 8px; padding: 12px; }
|
||||
.setting-field .heading-with-help { justify-content: space-between; }
|
||||
.setting-field h3 { font-size: 1rem; }
|
||||
.setting-storage { margin-bottom: 8px; }
|
||||
.setting-accepted { margin: 8px 0; font-size: .875rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.setting-field label:not(.checkbox) { display: block; margin: 8px 0 4px; }
|
||||
.setting-input { width: 100%; min-width: 0; min-height: 44px; padding: 9px 10px; border: 1px solid var(--line); border-radius: 7px; background: var(--surface); color: var(--ink); font: inherit; font-size: 16px; }
|
||||
textarea.setting-input { resize: vertical; min-height: 100px; }
|
||||
.setting-input[aria-invalid="true"] { border-color: var(--bad); }
|
||||
.setting-field .button-row { margin-top: 10px; }
|
||||
.setting-field .button-row > button { flex: 1 1 150px; }
|
||||
.setting-draft, .setting-message { margin-top: 8px; overflow-wrap: anywhere; }
|
||||
.setting-review { padding: 8px; margin-top: 8px; border: 1px solid var(--warn); border-radius: 6px; background: var(--warn-bg); color: var(--warn); }
|
||||
.settings-expert { margin-top: 16px; border: 1px solid var(--line); border-radius: 8px; }
|
||||
.settings-expert-content { padding: 12px; }
|
||||
.settings-expert-content > .notice { margin-bottom: 0; }
|
||||
.settings-wifi { margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
.settings-wifi > button { margin-top: 12px; }
|
||||
.settings-wifi > .small { margin-top: 6px; }
|
||||
.danger-action { border-color: var(--bad); color: var(--bad); }
|
||||
summary { cursor: pointer; min-height: 48px; padding: 12px 16px; font-size: .9rem; font-weight: 600; }
|
||||
details[open] > summary { border-bottom: 1px solid var(--line); }
|
||||
.about { font-size: .8rem; color: var(--muted); margin-bottom: 12px; }
|
||||
.about summary { color: var(--ink); padding-left: 2px; }
|
||||
.about p { margin-bottom: 12px; max-width: 95ch; }
|
||||
.about > div { padding: 10px 2px; }
|
||||
.footer { border-top: 1px solid var(--line); padding: 14px 0 20px; color: var(--muted); font-size: .75rem; flex-wrap: wrap; }
|
||||
.help-button { display: inline-flex; justify-content: center; align-items: center; flex: 0 0 44px; width: 44px; min-width: 44px; min-height: 44px; padding: 0; border-color: transparent; background: transparent; color: var(--accent); font-size: .9rem; }
|
||||
.help-button::first-letter { font-weight: 700; }
|
||||
.help-button[aria-expanded="true"] { border-color: var(--accent); background: var(--accent-soft); }
|
||||
.help-popover { position: fixed; z-index: 20; right: max(12px, env(safe-area-inset-right)); bottom: max(12px, env(safe-area-inset-bottom)); width: min(26rem, calc(100% - 24px)); max-height: 60vh; max-height: 60dvh; overflow-y: auto; border: 2px solid var(--accent); border-radius: 10px; background: var(--surface); color: var(--ink); padding: 12px 16px 16px; box-shadow: 0 8px 35px #0005; }
|
||||
.help-heading { display: flex; gap: 8px; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; position: sticky; top: -12px; background: var(--surface); padding-bottom: 4px; }
|
||||
.help-heading h2 { font-size: 1rem; padding-top: 9px; }
|
||||
.help-heading button { flex: 0 0 auto; color: var(--accent); }
|
||||
#help-text { font-size: .9rem; line-height: 1.6; white-space: pre-line; }
|
||||
.skip-link { position: absolute; top: -100px; left: 12px; min-height: 44px; padding: 10px; z-index: 30; background: var(--surface); }
|
||||
.skip-link:focus { top: 10px; }
|
||||
.about a { display: inline-flex; align-items: center; min-height: 44px; max-width: 100%; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
[hidden] { display: none !important; }
|
||||
@media (max-width: 900px) {
|
||||
.health-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.counters { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
th, td { padding: 10px; }
|
||||
.detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.shell { width: calc(100% - 20px); }
|
||||
.masthead { padding: 12px 0; }
|
||||
.heading-row { gap: 8px; }
|
||||
.connection-box { max-width: 54%; }
|
||||
.connection-box .small { font-size: .7rem; }
|
||||
.card { padding: 10px; }
|
||||
.health-grid { gap: 8px; }
|
||||
.metric { font-size: 1.15rem; }
|
||||
.activity { font-size: .8rem; }
|
||||
.counters > div { padding: 3px 7px; }
|
||||
.counters dd { font-size: 1.2rem; }
|
||||
.panel-heading, .diagnostic-content, .label-content, .settings-content { padding-right: 10px; padding-left: 10px; }
|
||||
.event-tools { padding: 8px 10px 0; }
|
||||
.event-tools .button-row { gap: 2px; }
|
||||
.event-tools button:not(.help-button) { font-size: .75rem; padding: 8px 7px; }
|
||||
.filters { align-items: stretch; flex-direction: column; gap: 0; padding: 8px 10px; }
|
||||
.panel > .notice { margin-right: 10px; margin-left: 10px; }
|
||||
.table-meta { padding: 0 10px 8px; gap: 3px; }
|
||||
#display-boot { display: none; }
|
||||
.radio-col { display: none; }
|
||||
td .mobile-radio { display: block; }
|
||||
th, td { padding: 8px 6px; }
|
||||
th.time-col { width: 19%; }
|
||||
th:last-child { width: 32%; }
|
||||
.sender-id { font-size: .78rem; }
|
||||
td { font-size: .8rem; }
|
||||
.badge { padding: 3px 5px; font-size: .7rem; }
|
||||
.detail-row > td { padding: 12px 10px; }
|
||||
.detail-grid { grid-template-columns: minmax(0, 1fr); gap: 10px; }
|
||||
.detail-grid dt { display: flex; align-items: center; }
|
||||
.panel-footer { padding: 10px; }
|
||||
.settings-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.setting-field, .settings-expert-content { padding: 10px; }
|
||||
.settings-expert summary { padding: 12px 10px; }
|
||||
.help-popover { right: 10px; width: calc(100% - 20px); padding: 10px 12px 14px; }
|
||||
.footer { gap: 4px; }
|
||||
}
|
||||
@media (max-width: 350px) {
|
||||
.health-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.event-tools .button-row { display: grid; grid-template-columns: minmax(0, 1fr) 44px; gap: 4px; }
|
||||
.event-tools button:not(.help-button) { text-align: left; }
|
||||
th .heading-with-help { flex-wrap: wrap; gap: 0; }
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --page: #101b20; --surface: #17262c; --ink: #dce8e9; --muted: #a6b9be; --line: #32444b; --accent: #89d2c5; --accent-soft: #193d39; --warn: #efc27b; --warn-bg: #3b3020; --bad: #ffabab; --bad-bg: #44282d; --shade: #1a2b31; --focus: #8cd4ff; }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Independent header-only identification; no third-party decoder code.
|
||||
* Factual medium/type codes and documented TCH exceptions cross-referenced
|
||||
* against wmbusmeters src/wmbus.cc, mediaType(), retrieved 2026-09-09:
|
||||
* https://github.com/wmbusmeters/wmbusmeters/blob/master/src/wmbus.cc
|
||||
* That reference project is GPL-3.0-or-later (Fredrik Öhrström and contributors);
|
||||
* no implementation is copied here. No payload, driver or model decoding.
|
||||
* FLAG/company registration facts are sourced separately in manufacturers.js.
|
||||
*/
|
||||
import { manufacturers } from './manufacturers.js';
|
||||
|
||||
export function hex(value, width = 2) {
|
||||
return Number.isInteger(value) && value >= 0
|
||||
? `0x${value.toString(16).toUpperCase().padStart(width, '0')}` : 'nicht verfügbar';
|
||||
}
|
||||
|
||||
export function manufacturerInfo(value) {
|
||||
if (!Number.isInteger(value) || value < 0 || value > 0xFFFF) {
|
||||
return { code: '', name: 'Hersteller nicht verfügbar', raw: hex(value, 4), warning: 'Kein gültiges Herstellerfeld vorhanden' };
|
||||
}
|
||||
const letters = [(value >> 10) & 31, (value >> 5) & 31, value & 31];
|
||||
const valid = letters.every(letter => letter >= 1 && letter <= 26);
|
||||
const code = valid ? String.fromCharCode(...letters.map(letter => letter + 64)) : '';
|
||||
return {
|
||||
code,
|
||||
name: code ? (manufacturers[code] || 'Nicht registrierter / unbekannter Hersteller') : 'Ungültiger Herstellercode',
|
||||
raw: hex(value, 4),
|
||||
warning: !valid ? 'Das Herstellerfeld enthält keine gültige Kennung aus drei Buchstaben (A–Z)'
|
||||
: value & 0x8000 ? 'Das höchste Bit im Herstellerfeld ist gesetzt; die Suche im FLAG-Herstellerverzeichnis nutzt nur die unteren 15 Bits' : '',
|
||||
};
|
||||
}
|
||||
|
||||
const media = {
|
||||
0x00: 'Sonstiges', 0x01: 'Ölzähler', 0x02: 'Stromzähler', 0x03: 'Gaszähler',
|
||||
0x04: 'Wärmezähler', 0x05: 'Dampfzähler', 0x06: 'Warmwasserzähler (30–90 °C)',
|
||||
0x07: 'Wasserzähler', 0x08: 'Heizkostenverteiler', 0x09: 'Druckluftzähler',
|
||||
0x0A: 'Kältevolumen am Auslass', 0x0B: 'Kältevolumen am Einlass',
|
||||
0x0C: 'Wärmevolumen am Einlass', 0x0D: 'Wärme- / Kältelastzähler',
|
||||
0x0E: 'Bus- / Systemkomponente', 0x0F: 'Unbekanntes Messmedium',
|
||||
0x15: 'Heißwasserzähler (≥90 °C)', 0x16: 'Kaltwasserzähler',
|
||||
0x17: 'Heiß- / Kaltwasserzähler', 0x18: 'Druckmesser', 0x19: 'Analog-Digital-Wandler',
|
||||
0x1A: 'Rauchmelder', 0x1B: 'Raumtemperatur- / Luftfeuchtesensor',
|
||||
0x1C: 'Gasmelder', 0x20: 'Stromschalter', 0x21: 'Gas- / Wasserventil',
|
||||
0x25: 'Kundenanzeige', 0x28: 'Abwasser', 0x29: 'Abfall',
|
||||
0x2A: 'Für Kohlendioxid reserviert', 0x31: 'Für Kommunikationssteuerungen reserviert',
|
||||
0x32: 'Für Einweg-Funkweiterleiter reserviert', 0x33: 'Für Zweiweg-Funkweiterleiter reserviert',
|
||||
0x36: 'Funkkonverter (Systemseite)', 0x37: 'Funkkonverter (Zählerseite)',
|
||||
};
|
||||
const techemMedia = {
|
||||
0x43: 'Wärmezähler', 0x62: 'Warmwasser', 0x72: 'Kaltwasser',
|
||||
0x80: 'Heizkostenverteiler', 0xC3: 'Wärmezähler', 0xF0: 'Rauchmelder',
|
||||
};
|
||||
|
||||
export function mediumInfo(value, manufacturer) {
|
||||
const raw = hex(value);
|
||||
if (!Number.isInteger(value) || value < 0 || value > 255) {
|
||||
return { name: 'Gerätetyp nicht verfügbar', raw, scoped: false };
|
||||
}
|
||||
let name = media[value];
|
||||
// Only this exact manufacturer has these documented non-standard meanings.
|
||||
const scoped = manufacturer === 0x5068 && Object.hasOwn(techemMedia, value);
|
||||
if (scoped) name = techemMedia[value];
|
||||
if (!name) {
|
||||
if (value >= 0x1D && value <= 0x1F) name = 'Für Sensoren reserviert';
|
||||
else if (value >= 0x22 && value <= 0x24) name = 'Für Schaltgeräte reserviert';
|
||||
else if (value >= 0x26 && value <= 0x27) name = 'Für Kundengeräte reserviert';
|
||||
else if (value >= 0x2B && value <= 0x2F) name = 'Für Umweltmessgeräte reserviert';
|
||||
else if (value >= 0x30 && value <= 0x3F) name = 'Für Systemgeräte reserviert';
|
||||
else name = 'Unbekannter / reservierter Gerätetyp';
|
||||
}
|
||||
return { name, raw, scoped };
|
||||
}
|
||||
|
||||
export function senderIdentity(row) {
|
||||
const rawId = typeof row.meter_id === 'string' ? row.meter_id : '';
|
||||
const id = /^[0-9A-Fa-f]{8}$/.test(rawId) ? rawId.toUpperCase() : '';
|
||||
const trusted = row.source === 'rx' && row.crc_ok === true && row.reception === 'ok';
|
||||
const manufacturer = manufacturerInfo(row.manufacturer);
|
||||
const medium = mediumInfo(row.device_type, row.manufacturer);
|
||||
const warnings = [];
|
||||
if (!trusted) warnings.push('Keine empfangene Kennung mit gültiger CRC-Prüfsumme; eigene Namen und Geräteerkennung werden nicht verwendet');
|
||||
if (rawId && !id) warnings.push('Ungültige ID: erwartet werden genau acht Hexadezimalstellen (0–9, A–F)');
|
||||
if (id && !/^[0-9]{8}$/.test(id)) warnings.push('ID nicht im BCD-Ziffernformat: Die Hexadezimalkennung bleibt unverändert. Sie darf nicht als dezimale Zählernummer gelesen werden');
|
||||
if (trusted && manufacturer.warning) warnings.push(manufacturer.warning);
|
||||
return {
|
||||
id, rawId, trusted, labelEligible: trusted && Boolean(id), manufacturer, medium, warnings,
|
||||
key: `${id}/${row.manufacturer}/${row.version}/${row.device_type}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="theme-color" content="#102f37">
|
||||
<title>Heltec · Zählerfunk</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<link rel="stylesheet" href="/dashboard.css">
|
||||
<script type="module" src="/dashboard.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#events">Zu den Funknachrichten</a>
|
||||
<header class="masthead">
|
||||
<div class="shell heading-row">
|
||||
<div><p class="eyebrow">HELTEC / wM-Bus</p><h1>Zählerfunk</h1></div>
|
||||
<div class="connection-box"><span id="connection" class="badge neutral" role="status">Verbindung wird aufgebaut</span><span id="connection-age" class="small">Warte auf das Gerät</span></div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="shell">
|
||||
<noscript><p class="notice danger">Diese Seite benötigt JavaScript, aber kein Internet.</p></noscript>
|
||||
<p id="connection-notice" class="notice" role="status">Verbindung zum Gerät wird aufgebaut.</p>
|
||||
<section class="operation" aria-labelledby="operation-title">
|
||||
<div class="heading-with-help"><h2 id="operation-title">Jetzt am Gerät</h2><button type="button" class="help-button" data-help="flow" aria-label="Hilfe: Empfangen und Weiterleiten" aria-controls="help-popover" aria-expanded="false">?</button></div>
|
||||
<p id="operation-state">Warte auf den Gerätestatus.</p>
|
||||
<p id="operation-detail" class="small">Noch keine Daten verfügbar.</p>
|
||||
</section>
|
||||
|
||||
<section id="events" class="panel" aria-labelledby="events-title">
|
||||
<div class="panel-heading"><div class="heading-with-help"><h2 id="events-title">Letzte Funknachrichten</h2><button type="button" class="help-button" data-help="history" aria-label="Hilfe: Verlauf und Neustart" aria-controls="help-popover" aria-expanded="false">?</button></div><p class="small">Neueste zuerst · je ein Signal mit abschließendem Ergebnis</p></div>
|
||||
<div class="event-tools"><div class="button-row"><button id="pause" type="button" aria-pressed="false">Nur Anzeige pausieren</button><button type="button" class="help-button" data-help="pause" aria-label="Hilfe: Nur die Anzeige pausieren" aria-controls="help-popover" aria-expanded="false">?</button><button id="download-events" type="button" disabled>Verlauf als CSV</button><button type="button" class="help-button" data-help="export" aria-label="Hilfe: Verlauf herunterladen" aria-controls="help-popover" aria-expanded="false">?</button></div></div>
|
||||
<div class="filters"><div class="search-field"><label class="sr-only" for="filter">Nach Kennung, eigenem Namen oder Hersteller filtern</label><input id="filter" type="search" placeholder="Kennung, Name oder Hersteller suchen" autocomplete="off" maxlength="200"></div><div class="filter-errors"><label class="checkbox" for="failures"><input id="failures" type="checkbox">Nur Fehler</label><button type="button" class="help-button" data-help="outcomes" aria-label="Hilfe: Fehler und ausgelassene Signale" aria-controls="help-popover" aria-expanded="false">?</button></div></div>
|
||||
<p id="pause-notice" class="notice warning" hidden></p>
|
||||
<p id="ambiguity-notice" class="notice warning" role="status" hidden></p>
|
||||
<div class="table-meta"><span id="row-count">0 Funknachrichten</span><span id="display-boot" class="mono"></span></div>
|
||||
<div class="table-wrap"><table id="event-table"><caption class="sr-only">Empfangene Funknachrichten und Sendeergebnisse, neueste zuerst. Unter Einzelheiten stehen die vollständige Absenderkennung, Rohwerte und Zeitangaben.</caption><thead><tr><th scope="col" class="time-col">Zeit</th><th scope="col"><span class="heading-with-help">Absender<button type="button" class="help-button" data-help="identity" aria-label="Hilfe: Absender und Zählerkennung" aria-controls="help-popover" aria-expanded="false">?</button></span></th><th scope="col" class="radio-col"><span class="heading-with-help">Funk<button type="button" class="help-button" data-help="signal" aria-label="Hilfe: Signalstärke und Funkformat" aria-controls="help-popover" aria-expanded="false">?</button></span></th><th scope="col">Ergebnis</th></tr></thead><tbody id="event-rows"></tbody></table></div>
|
||||
<p id="empty-state" class="empty">Warte auf den ersten Verlauf …</p>
|
||||
<div class="panel-footer"><p id="retention" class="small">Bis zu 256 abgeschlossene Funknachrichten seit dem Gerätestart.</p></div>
|
||||
</section>
|
||||
|
||||
<details id="diagnostics" class="panel diagnostics">
|
||||
<summary>Diagnose: Summen und Funkstatus</summary>
|
||||
<div class="diagnostic-content">
|
||||
<div class="section-heading"><div class="heading-with-help"><h2 id="health-title">Gerät im Detail</h2><button type="button" class="help-button" data-help="diagnostics" aria-label="Hilfe: Aktualität der Diagnose" aria-controls="help-popover" aria-expanded="false">?</button></div><span id="uptime" class="small">Laufzeit —</span></div>
|
||||
<div class="health-grid">
|
||||
<article class="card"><div class="heading-with-help"><h3>Funkzustand</h3><button type="button" class="help-button" data-help="diagnostics" aria-label="Hilfe: Funkzustand und Prüfintervall" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="radio-state" class="metric">—</p><p id="radio-detail" class="small">Warte auf Messdaten</p><p id="heartbeat" class="small">Funkprüfung —</p></article>
|
||||
<article class="card"><div class="heading-with-help"><h3>Weiterleiten</h3><button type="button" class="help-button" data-help="policy" aria-label="Hilfe: Regeln fürs Weiterleiten" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="repeat-state" class="metric">—</p><p id="repeat-detail" class="small">Wartezeit —</p><p id="recovery-detail" class="small">Funk-Reparaturversuche —</p></article>
|
||||
<article class="card"><div class="heading-with-help"><h3>Sendezeit</h3><button type="button" class="help-button" data-help="duty" aria-label="Hilfe: Zulässige Sendezeit" aria-controls="help-popover" aria-expanded="false">?</button></div><p id="duty-state" class="metric">—</p><progress id="duty-meter" max="100" value="0" aria-label="Anteil des verbrauchten Sendezeitbudgets"></progress><p id="duty-detail" class="small">Warte auf Messdaten</p></article>
|
||||
<article class="card"><div class="heading-with-help"><h3>Letzte Aktivität</h3><button type="button" class="help-button" data-help="activity" aria-label="Hilfe: Empfang und abgeschlossenes Senden" aria-controls="help-popover" aria-expanded="false">?</button></div><dl class="activity"><div><dt>Lesbar empfangen</dt><dd id="last-rx">—</dd></div><div><dt>Senden beendet</dt><dd id="last-tx">—</dd></div></dl></article>
|
||||
</div>
|
||||
<div class="heading-with-help counters-heading"><h3>Summen seit Gerätestart</h3><button type="button" class="help-button" data-help="counters" aria-label="Hilfe: Empfangs- und Sendezähler" aria-controls="help-popover" aria-expanded="false">?</button></div>
|
||||
<dl class="counters">
|
||||
<div><dd id="count-rx">—</dd><dt>Lesbar empfangen</dt></div><div><dd id="count-rejected">—</dd><dt>Nicht lesbar</dt></div><div><dd id="count-repeats">—</dd><dt>Weitergesendet</dt></div><div><dd id="count-skipped">—</dd><dt>Ausgelassen</dt></div><div><dd id="count-failed">—</dd><dt>Sendefehler</dt></div><div><dd id="count-recoveries">—</dd><dt>Funk-Reparaturversuche</dt></div>
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details id="settings-panel" class="panel">
|
||||
<summary>Einstellungen am Heltec-Gerät ändern</summary>
|
||||
<div class="settings-content">
|
||||
<div class="section-heading">
|
||||
<div class="heading-with-help"><h2>Geräteeinstellungen</h2><button type="button" class="help-button" data-help="settings" aria-label="Hilfe: Einstellungen, Entwürfe und Speicherung" aria-controls="help-popover" aria-expanded="false">?</button></div>
|
||||
<button id="settings-reload" type="button">Gerätewerte neu laden</button>
|
||||
</div>
|
||||
<p class="small">Jedes Feld wird einzeln und erst mit „Übernehmen“ an das Heltec-Gerät gesendet. Gerätewert und lokaler Entwurf sind getrennt. Nur Wartezeit und Sendezeitbudget bleiben nach einem Geräteneustart erhalten; alle anderen Werte gelten nur im Arbeitsspeicher (RAM).</p>
|
||||
<p class="small settings-draft-note">Ungesendete Entwürfe bleiben beim Nachladen erhalten, aber nicht beim Neuladen oder Schließen dieses Browser-Tabs.</p>
|
||||
<p id="settings-status" class="notice" role="status">Noch keine Einstellungen geladen. Zum Laden diesen Bereich öffnen.</p>
|
||||
<p id="settings-revision" class="small"></p>
|
||||
<div id="settings-common" class="settings-grid"></div>
|
||||
<details id="settings-expert" class="settings-expert">
|
||||
<summary>Experteneinstellungen: Funkexperimente und eigene Signale</summary>
|
||||
<div class="settings-expert-content">
|
||||
<p class="notice warning">FEM-CSD und Präambelerkennung sind Empfangsexperimente und können den Empfang verschlechtern. Kennungssignale erzeugen zusätzlichen Funkverkehr. Im Zweifel die vorhandenen Werte beibehalten.</p>
|
||||
<div id="settings-advanced" class="settings-grid"></div>
|
||||
</div>
|
||||
</details>
|
||||
<section class="settings-wifi" aria-labelledby="settings-wifi-title">
|
||||
<div class="heading-with-help"><h3 id="settings-wifi-title">WLAN des Heltec-Geräts</h3><button type="button" class="help-button" data-help="settings_wifi" aria-label="Hilfe: Heltec-WLAN ausschalten" aria-controls="help-popover" aria-expanded="false">?</button></div>
|
||||
<p class="small">Ausschalten trennt diese Verbindung. Die Funkweiterleitung läuft gemäß ihren Einstellungen weiter. Das WLAN kann danach nicht über diese Seite wieder eingeschaltet werden.</p>
|
||||
<button id="settings-wifi-disable" type="button" class="danger-action" disabled>Heltec-WLAN ausschalten …</button>
|
||||
<p id="settings-wifi-result" class="small" role="status"></p>
|
||||
</section>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details id="labels" class="panel">
|
||||
<summary>Optional: eigene Namen für Zähler</summary>
|
||||
<div class="label-content">
|
||||
<div class="section-heading"><div class="heading-with-help"><h2 id="labels-title">Eigene Zählernamen</h2><button type="button" class="help-button" data-help="labels" aria-label="Hilfe: Eigene Namen und Absenderkennung" aria-controls="help-popover" aria-expanded="false">?</button></div><span id="label-count" class="badge neutral">0 Namen</span></div>
|
||||
<p id="label-help" class="small">Nur für diesen Browser-Tab. Die Datei bleibt auf deinem Gerät.</p>
|
||||
<div class="button-row"><input id="label-file" class="file-input sr-only" type="file" accept=".csv,text/csv" aria-label="CSV-Datei mit eigenen Zählernamen auswählen" aria-describedby="label-help label-result"><label class="file-picker" for="label-file">CSV-Datei auswählen</label><button type="button" class="help-button" data-help="csv" aria-label="Hilfe: CSV-Datei und führende Nullen" aria-controls="help-popover" aria-expanded="false">?</button><button id="sample-labels" type="button">Vorlage herunterladen</button><button id="export-labels" type="button" disabled>Kennungen und Namen als CSV</button><button id="clear-labels" type="button" disabled>Namen entfernen</button></div>
|
||||
<p id="label-result" class="small" role="status">Keine Namen geladen. Neuladen oder Schließen der Seite entfernt alle eigenen Namen.</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="about">
|
||||
<summary>Datenschutz, Zuordnung und Quellen</summary>
|
||||
<div>
|
||||
<div class="heading-with-help"><h2>Wie wird ein Absender erkannt?</h2><button type="button" class="help-button" data-help="identity" aria-label="Hilfe: Grenzen der Absenderzuordnung" aria-controls="help-popover" aria-expanded="false">?</button></div>
|
||||
<p>Hersteller und Gerätetyp werden im Browser zugeordnet. Nutzdaten werden weder entschlüsselt noch als Zählerstände ausgewertet. Die Versionsnummer dient nicht zur Erkennung eines Modells oder Treibers.</p>
|
||||
<p>Alle Skripte, Stile und Herstellerdaten liegen auf dem Heltec-Gerät. Bestätigte Einstellungsänderungen werden an dieses Gerät gesendet; das Ausschalten seines WLANs trennt die Verbindung. CSV-Dateien und eigene Zählernamen werden dagegen nur im Browser verarbeitet: ohne Hochladen, Cookies oder dauerhafte Browser-Speicherung. Dateien werden nur auf deinen Wunsch heruntergeladen.</p>
|
||||
<p id="registry-note">Herstellernamen: mitgelieferter Stand des offiziellen FLAG-ID-Verzeichnisses der DLMS User Association.</p>
|
||||
<p>Quellen (nur das Öffnen dieser Links benötigt Internet): <a href="https://www.dlms.com/flag-id-directory/" target="_blank" rel="noreferrer noopener">Offizielles DLMS-Verzeichnis</a> · <a href="https://github.com/wmbusmeters/wmbusmeters/blob/master/src/wmbus.cc" target="_blank" rel="noreferrer noopener">Gerätetyp-Codes bei wmbusmeters</a>.</p>
|
||||
<p>Die Zuordnungslogik ist eigenständig implementiert. Bedeutungen der Gerätetyp-Codes und dokumentierte Herstellerausnahmen wurden mit wmbusmeters abgeglichen (GPL-3.0-or-later, Fredrik Öhrström und Mitwirkende); dessen Dekodierung ist nicht enthalten. Die Verzeichnisdaten stammen von der DLMS User Association. JavaScript, HTML und CSS werden als nicht minimierter Quelltext ausgeliefert.</p>
|
||||
</div>
|
||||
</details>
|
||||
<footer class="footer"><span>Heltec-Funkweiterleitung</span><span>Lokal am Gerät · ohne Cloud</span></footer>
|
||||
</main>
|
||||
<aside id="help-popover" class="help-popover" role="dialog" aria-modal="false" aria-labelledby="help-title" aria-describedby="help-text" hidden>
|
||||
<div class="help-heading"><h2 id="help-title"></h2><button id="help-close" type="button" aria-label="Hilfe schließen">Schließen</button></div>
|
||||
<p id="help-text"></p>
|
||||
</aside>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,346 @@
|
||||
// On-demand debug AP. Only this task owns Wi-Fi/HTTP lifecycle; the OLED
|
||||
// and settings endpoint request transitions without stopping their own server.
|
||||
#include "wifi_debug.h"
|
||||
#include "debug_history.h"
|
||||
#include "settings_http.h"
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_http_server.h"
|
||||
#include "esp_mac.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_wifi_default.h"
|
||||
#include "bootloader_random.h"
|
||||
#include "nvs.h"
|
||||
|
||||
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||
static wifi_debug_status_t s_status;
|
||||
static TaskHandle_t s_task;
|
||||
static esp_netif_t *s_ap;
|
||||
static httpd_handle_t s_http;
|
||||
static bool s_wifi_initialized;
|
||||
static bool s_network_initialized;
|
||||
static debug_snapshot_t *s_snapshot;
|
||||
static uint32_t s_boot_id;
|
||||
|
||||
#define REQUEST_TOGGLE 1u
|
||||
#define REQUEST_DISABLE 2u
|
||||
|
||||
void wifi_debug_status(wifi_debug_status_t *out)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
*out = s_status;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
}
|
||||
|
||||
static void publish(wifi_debug_state_t state, esp_err_t error)
|
||||
{
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
s_status.state = state;
|
||||
s_status.error = error;
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
// Credentials are displayed physically, never included in serial telemetry.
|
||||
printf("{\"event\":\"wifi_debug\",\"state\":%d,\"error\":%d}\n", state, error);
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
static esp_err_t credentials(void)
|
||||
{
|
||||
uint8_t mac[6];
|
||||
esp_err_t err = esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
|
||||
if (err != ESP_OK) return err;
|
||||
wifi_debug_status_t status;
|
||||
wifi_debug_status(&status);
|
||||
snprintf(status.ssid, sizeof(status.ssid), "Heltec-Repeater-%02X%02X", mac[4], mac[5]);
|
||||
|
||||
nvs_handle_t nvs;
|
||||
err = nvs_open("wifi_debug", NVS_READWRITE, &nvs);
|
||||
if (err != ESP_OK) return err;
|
||||
size_t len = sizeof(status.password);
|
||||
err = nvs_get_str(nvs, "password", status.password, &len);
|
||||
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||
// No Wi-Fi/ADC is running here. Enable the hardware entropy source,
|
||||
// rather than derive a publicly guessable password from the MAC.
|
||||
uint8_t random[12];
|
||||
static const char alphabet[] = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
_Static_assert(sizeof(alphabet) == 33, "password alphabet must have 32 symbols");
|
||||
bootloader_random_enable();
|
||||
esp_fill_random(random, sizeof(random));
|
||||
bootloader_random_disable();
|
||||
for (size_t i = 0; i < sizeof(random); i++) status.password[i] = alphabet[random[i] & 31];
|
||||
status.password[12] = 0;
|
||||
err = nvs_set_str(nvs, "password", status.password);
|
||||
if (err == ESP_OK) err = nvs_commit(nvs);
|
||||
} else if (err == ESP_OK && (len != sizeof(status.password) || strlen(status.password) != 12)) {
|
||||
err = ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
nvs_close(nvs);
|
||||
if (err != ESP_OK) return err;
|
||||
portENTER_CRITICAL(&s_lock);
|
||||
memcpy(s_status.ssid, status.ssid, sizeof(status.ssid));
|
||||
memcpy(s_status.password, status.password, sizeof(status.password));
|
||||
portEXIT_CRITICAL(&s_lock);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
#define ASSET(name, symbol) \
|
||||
extern const uint8_t symbol##_start[] asm("_binary_" name "_start"); \
|
||||
extern const uint8_t symbol##_end[] asm("_binary_" name "_end")
|
||||
ASSET("index_html_gz", index_html);
|
||||
ASSET("dashboard_css_gz", dashboard_css);
|
||||
ASSET("dashboard_js_gz", dashboard_js);
|
||||
ASSET("identity_js_gz", identity_js);
|
||||
ASSET("manufacturers_js_gz", manufacturers_js);
|
||||
|
||||
typedef struct {
|
||||
const uint8_t *start;
|
||||
const uint8_t *end;
|
||||
const char *type;
|
||||
} asset_t;
|
||||
|
||||
static const asset_t s_assets[] = {
|
||||
{index_html_start, index_html_end, "text/html; charset=utf-8"},
|
||||
{dashboard_css_start, dashboard_css_end, "text/css; charset=utf-8"},
|
||||
{dashboard_js_start, dashboard_js_end, "text/javascript; charset=utf-8"},
|
||||
{identity_js_start, identity_js_end, "text/javascript; charset=utf-8"},
|
||||
{manufacturers_js_start, manufacturers_js_end, "text/javascript; charset=utf-8"},
|
||||
};
|
||||
|
||||
static void headers(httpd_req_t *req)
|
||||
{
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
|
||||
httpd_resp_set_hdr(req, "X-Content-Type-Options", "nosniff");
|
||||
httpd_resp_set_hdr(req, "Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; "
|
||||
"object-src 'none'; base-uri 'none'; frame-ancestors 'none'");
|
||||
httpd_resp_set_hdr(req, "Referrer-Policy", "no-referrer");
|
||||
}
|
||||
|
||||
static esp_err_t asset_handler(httpd_req_t *req)
|
||||
{
|
||||
const asset_t *asset = req->user_ctx;
|
||||
headers(req);
|
||||
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
|
||||
httpd_resp_set_type(req, asset->type);
|
||||
return httpd_resp_send(req, (const char *)asset->start, asset->end - asset->start);
|
||||
}
|
||||
|
||||
static esp_err_t events_handler(httpd_req_t *req)
|
||||
{
|
||||
uint32_t after = 0;
|
||||
size_t query_len = httpd_req_get_url_query_len(req);
|
||||
if (query_len) {
|
||||
char query[64], value[16];
|
||||
if (query_len >= sizeof(query) ||
|
||||
httpd_req_get_url_query_str(req, query, sizeof(query)) != ESP_OK ||
|
||||
httpd_query_key_value(query, "after", value, sizeof(value)) != ESP_OK || !value[0]) {
|
||||
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Expected after=unsigned integer");
|
||||
}
|
||||
uint64_t parsed = 0;
|
||||
for (const char *p = value; *p; p++) {
|
||||
if (*p < '0' || *p > '9') return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid cursor");
|
||||
parsed = parsed * 10 + (unsigned)(*p - '0');
|
||||
if (parsed > UINT32_MAX) return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid cursor");
|
||||
}
|
||||
after = (uint32_t)parsed;
|
||||
}
|
||||
debug_history_snapshot(after, s_snapshot);
|
||||
const debug_status_t *s = &s_snapshot->status;
|
||||
headers(req);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
char chunk[1400];
|
||||
int n = snprintf(chunk, sizeof(chunk),
|
||||
"{\"boot_id\":\"%08" PRIx32 "\",\"cursor\":%" PRIu32 ",\"oldest_id\":%" PRIu32
|
||||
",\"evicted\":%" PRIu32 ",\"reset\":%s,\"now_us\":%lld,\"capacity\":%u,\"status\":{"
|
||||
"\"sampled_at_us\":%lld,\"heartbeat_us\":%lld,\"last_rx_us\":%lld,\"last_tx_us\":%lld,"
|
||||
"\"rx_valid\":%llu,\"rx_rejected\":%llu,\"repeats_completed\":%llu,\"tx_failed\":%llu,"
|
||||
"\"skipped\":%llu,\"duty_used_us\":%llu,\"duty_budget_us\":%llu,\"recoveries\":%" PRIu32
|
||||
",\"repeat_delay_ms\":%" PRIu32 ",\"chip_mode\":%u,\"config_intact\":%s,\"repeat_enabled\":%s},\"rows\":[",
|
||||
s_boot_id, s_snapshot->cursor, s_snapshot->oldest_id, s_snapshot->evicted,
|
||||
s_snapshot->reset ? "true" : "false", (long long)esp_timer_get_time(), DEBUG_HISTORY_CAPACITY,
|
||||
(long long)s->sampled_at_us, (long long)s->heartbeat_us,
|
||||
(long long)s->last_rx_us, (long long)s->last_tx_us,
|
||||
(unsigned long long)s->rx_valid, (unsigned long long)s->rx_rejected,
|
||||
(unsigned long long)s->repeats_completed, (unsigned long long)s->tx_failed,
|
||||
(unsigned long long)s->skipped, (unsigned long long)s->duty_used_us,
|
||||
(unsigned long long)s->duty_budget_us, s->recoveries, s->repeat_delay_ms,
|
||||
s->chip_mode, s->config_intact ? "true" : "false", s->repeat_enabled ? "true" : "false");
|
||||
if (n < 0 || n >= sizeof(chunk)) return ESP_FAIL;
|
||||
esp_err_t err = httpd_resp_send_chunk(req, chunk, n);
|
||||
for (size_t i = 0; err == ESP_OK && i < s_snapshot->count; i++) {
|
||||
const debug_record_t *r = &s_snapshot->rows[i];
|
||||
char meter[12] = "null", manufacturer[8] = "null", version[8] = "null", type[8] = "null";
|
||||
if (r->identity_present) {
|
||||
snprintf(meter, sizeof(meter), "\"%08" PRIX32 "\"", r->meter_id);
|
||||
snprintf(manufacturer, sizeof(manufacturer), "%u", r->manufacturer);
|
||||
snprintf(version, sizeof(version), "%u", r->version);
|
||||
snprintf(type, sizeof(type), "%u", r->device_type);
|
||||
}
|
||||
n = snprintf(chunk, sizeof(chunk),
|
||||
"%s{\"id\":%" PRIu32 ",\"timestamp_us\":%lld,\"tx_start_us\":%lld,\"tx_done_us\":%lld,"
|
||||
"\"meter_id\":%s,\"hash\":\"%08" PRIx32 "\",\"manufacturer\":%s,\"length\":%u,"
|
||||
"\"version\":%s,\"device_type\":%s,\"rssi_dbm\":%d,\"crc_ok\":%s,"
|
||||
"\"source\":\"%s\",\"mode\":\"%s\",\"format\":\"%s\",\"reception\":\"%s\",\"outcome\":\"%s\"}",
|
||||
i ? "," : "", r->id, (long long)r->timestamp_us,
|
||||
(long long)r->tx_start_us, (long long)r->tx_done_us,
|
||||
meter, r->hash, manufacturer, r->length, version, type, r->rssi_dbm,
|
||||
r->crc_ok ? "true" : "false", r->source, r->mode, r->format, r->reception, r->outcome);
|
||||
if (n < 0 || n >= sizeof(chunk)) return ESP_FAIL;
|
||||
err = httpd_resp_send_chunk(req, chunk, n);
|
||||
}
|
||||
if (err == ESP_OK) err = httpd_resp_send_chunk(req, "]}", 2);
|
||||
if (err == ESP_OK) err = httpd_resp_send_chunk(req, NULL, 0);
|
||||
return err;
|
||||
}
|
||||
|
||||
static esp_err_t start_http(void)
|
||||
{
|
||||
s_snapshot = calloc(1, sizeof(*s_snapshot));
|
||||
if (!s_snapshot) return ESP_ERR_NO_MEM;
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
config.core_id = 0;
|
||||
config.task_priority = 2;
|
||||
config.stack_size = 6144;
|
||||
config.max_open_sockets = 3;
|
||||
config.max_uri_handlers = 10;
|
||||
config.lru_purge_enable = true;
|
||||
config.recv_wait_timeout = 2;
|
||||
config.send_wait_timeout = 2;
|
||||
esp_err_t err = httpd_start(&s_http, &config);
|
||||
if (err != ESP_OK) return err;
|
||||
static const char *paths[] = {"/", "/dashboard.css", "/dashboard.js", "/identity.js", "/manufacturers.js"};
|
||||
for (size_t i = 0; i < sizeof(s_assets) / sizeof(s_assets[0]); i++) {
|
||||
const httpd_uri_t uri = {.uri = paths[i], .method = HTTP_GET, .handler = asset_handler, .user_ctx = (void *)&s_assets[i]};
|
||||
err = httpd_register_uri_handler(s_http, &uri);
|
||||
if (err != ESP_OK) return err;
|
||||
}
|
||||
const httpd_uri_t index = {.uri = "/index.html", .method = HTTP_GET, .handler = asset_handler, .user_ctx = (void *)&s_assets[0]};
|
||||
err = httpd_register_uri_handler(s_http, &index);
|
||||
if (err != ESP_OK) return err;
|
||||
const httpd_uri_t events = {.uri = "/api/events", .method = HTTP_GET, .handler = events_handler};
|
||||
err = httpd_register_uri_handler(s_http, &events);
|
||||
if (err != ESP_OK) return err;
|
||||
return settings_http_register(s_http, s_boot_id);
|
||||
}
|
||||
|
||||
static esp_err_t stop_network(void)
|
||||
{
|
||||
if (s_http) {
|
||||
esp_err_t err = httpd_stop(s_http);
|
||||
if (err != ESP_OK) return err;
|
||||
s_http = NULL;
|
||||
}
|
||||
free(s_snapshot);
|
||||
s_snapshot = NULL;
|
||||
if (s_wifi_initialized) {
|
||||
esp_err_t err = esp_wifi_stop();
|
||||
if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_STARTED) return err;
|
||||
err = esp_wifi_deinit();
|
||||
if (err != ESP_OK) return err;
|
||||
s_wifi_initialized = false;
|
||||
}
|
||||
if (s_ap) {
|
||||
esp_netif_destroy_default_wifi(s_ap);
|
||||
s_ap = NULL;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t start_network(void)
|
||||
{
|
||||
esp_err_t err = credentials();
|
||||
if (err != ESP_OK) return err;
|
||||
if (!s_network_initialized) {
|
||||
err = esp_netif_init();
|
||||
if (err != ESP_OK) return err;
|
||||
err = esp_event_loop_create_default();
|
||||
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) return err;
|
||||
s_network_initialized = true;
|
||||
}
|
||||
// The convenience create_default helper aborts on allocation/attach
|
||||
// failure. Debug networking must fail without resetting the repeater.
|
||||
esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_WIFI_AP();
|
||||
s_ap = esp_netif_new(&netif_config);
|
||||
if (!s_ap) return ESP_ERR_NO_MEM;
|
||||
err = esp_netif_attach_wifi_ap(s_ap);
|
||||
if (err != ESP_OK) return err;
|
||||
err = esp_wifi_set_default_wifi_ap_handlers();
|
||||
if (err != ESP_OK) return err;
|
||||
wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
|
||||
err = esp_wifi_init(&init);
|
||||
if (err != ESP_OK) return err;
|
||||
s_wifi_initialized = true;
|
||||
err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
|
||||
if (err != ESP_OK) return err;
|
||||
wifi_debug_status_t status;
|
||||
wifi_debug_status(&status);
|
||||
wifi_config_t config = {0};
|
||||
memcpy(config.ap.ssid, status.ssid, strlen(status.ssid));
|
||||
config.ap.ssid_len = strlen(status.ssid);
|
||||
memcpy(config.ap.password, status.password, strlen(status.password));
|
||||
config.ap.channel = 1;
|
||||
config.ap.max_connection = 2;
|
||||
config.ap.authmode = WIFI_AUTH_WPA2_PSK;
|
||||
config.ap.pmf_cfg.capable = true;
|
||||
err = esp_wifi_set_mode(WIFI_MODE_AP);
|
||||
if (err == ESP_OK) err = esp_wifi_set_config(WIFI_IF_AP, &config);
|
||||
if (err == ESP_OK) err = esp_wifi_start();
|
||||
if (err == ESP_OK) err = start_http();
|
||||
return err;
|
||||
}
|
||||
|
||||
static void control_task(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
uint32_t requests;
|
||||
xTaskNotifyWait(0, UINT32_MAX, &requests, portMAX_DELAY);
|
||||
wifi_debug_status_t status;
|
||||
wifi_debug_status(&status);
|
||||
if ((requests & REQUEST_DISABLE) && status.state == WIFI_DEBUG_OFF) continue;
|
||||
if ((requests & REQUEST_DISABLE) || status.state == WIFI_DEBUG_ON) {
|
||||
publish(WIFI_DEBUG_STOPPING, ESP_OK);
|
||||
esp_err_t err = stop_network();
|
||||
publish(err == ESP_OK ? WIFI_DEBUG_OFF : WIFI_DEBUG_ERROR, err);
|
||||
} else {
|
||||
publish(WIFI_DEBUG_STARTING, ESP_OK);
|
||||
esp_err_t err = stop_network(); // also cleans a previous partial failure
|
||||
if (err == ESP_OK) err = start_network();
|
||||
if (err != ESP_OK) {
|
||||
esp_err_t cleanup = stop_network();
|
||||
if (cleanup != ESP_OK) err = cleanup;
|
||||
}
|
||||
publish(err == ESP_OK ? WIFI_DEBUG_ON : WIFI_DEBUG_ERROR, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_debug_toggle(void)
|
||||
{
|
||||
wifi_debug_status_t status;
|
||||
wifi_debug_status(&status);
|
||||
if (s_task && status.state != WIFI_DEBUG_STARTING && status.state != WIFI_DEBUG_STOPPING) {
|
||||
xTaskNotify(s_task, REQUEST_TOGGLE, eSetBits);
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_debug_disable(void)
|
||||
{
|
||||
if (s_task) xTaskNotify(s_task, REQUEST_DISABLE, eSetBits);
|
||||
}
|
||||
|
||||
void wifi_debug_init(void)
|
||||
{
|
||||
s_boot_id = esp_random(); // Session discriminator, not a secret.
|
||||
if (xTaskCreatePinnedToCore(control_task, "wifi_debug", 6144, NULL, 2, &s_task, 0) != pdPASS) {
|
||||
publish(WIFI_DEBUG_ERROR, ESP_ERR_NO_MEM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef enum {
|
||||
WIFI_DEBUG_OFF,
|
||||
WIFI_DEBUG_STARTING,
|
||||
WIFI_DEBUG_ON,
|
||||
WIFI_DEBUG_STOPPING,
|
||||
WIFI_DEBUG_ERROR,
|
||||
} wifi_debug_state_t;
|
||||
|
||||
typedef struct {
|
||||
wifi_debug_state_t state;
|
||||
char ssid[22];
|
||||
char password[13];
|
||||
int32_t error;
|
||||
} wifi_debug_status_t;
|
||||
|
||||
// Starts only the control task. Wi-Fi remains off until an OLED request.
|
||||
void wifi_debug_init(void);
|
||||
void wifi_debug_toggle(void);
|
||||
void wifi_debug_disable(void); // idempotent, queued outside the HTTP task
|
||||
void wifi_debug_status(wifi_debug_status_t *out);
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "wifi_qr.h"
|
||||
#include "vendor/qrcodegen.h"
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
// Nayuki QR Code generator v1.8.0, vendored unchanged under its MIT license.
|
||||
// https://github.com/nayuki/QR-Code-generator/tree/v1.8.0/c
|
||||
#define MAX_VERSION 5
|
||||
|
||||
static bool append_field(char **dst, const char *end, const char *text)
|
||||
{
|
||||
for (; *text; text++) {
|
||||
// ZXing/iOS Wi-Fi join syntax escapes special field characters.
|
||||
if (strchr("\\;,:\"", *text)) {
|
||||
if (*dst == end) return false;
|
||||
*(*dst)++ = '\\';
|
||||
}
|
||||
if (*dst == end) return false;
|
||||
*(*dst)++ = *text;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool wifi_qr_bitmap(const char *ssid, const char *password, uint8_t out[WIFI_QR_BYTES])
|
||||
{
|
||||
char payload[96] = "WIFI:T:WPA;S:";
|
||||
char *dst = payload + strlen(payload);
|
||||
const char *end = payload + sizeof(payload) - 1;
|
||||
if (!append_field(&dst, end, ssid) || end - dst < 3) return false;
|
||||
memcpy(dst, ";P:", 3);
|
||||
dst += 3;
|
||||
if (!append_field(&dst, end, password) || end - dst < 2) return false;
|
||||
*dst++ = ';';
|
||||
*dst++ = ';';
|
||||
*dst = 0;
|
||||
uint8_t work[qrcodegen_BUFFER_LEN_FOR_VERSION(MAX_VERSION)];
|
||||
uint8_t qr[qrcodegen_BUFFER_LEN_FOR_VERSION(MAX_VERSION)];
|
||||
if (!qrcodegen_encodeText(payload, work, qr, qrcodegen_Ecc_LOW,
|
||||
1, MAX_VERSION, qrcodegen_Mask_AUTO, true)) return false;
|
||||
const int size = qrcodegen_getSize(qr);
|
||||
const int scale = WIFI_QR_SIDE / (size + 8);
|
||||
if (scale < 1) return false;
|
||||
const int origin = (WIFI_QR_SIDE - size * scale) / 2;
|
||||
// OLED lit pixels are the light modules. Do not invert the QR or truncate
|
||||
// its quiet zone just to fit a 2x scale on this 64-pixel-high panel.
|
||||
memset(out, 0xff, WIFI_QR_BYTES);
|
||||
for (int y = 0; y < size; y++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
if (!qrcodegen_getModule(qr, x, y)) continue;
|
||||
for (int dy = 0; dy < scale; dy++) {
|
||||
int py = origin + y * scale + dy;
|
||||
for (int dx = 0; dx < scale; dx++) {
|
||||
int px = origin + x * scale + dx;
|
||||
out[(py / 8) * WIFI_QR_SIDE + px] &= (uint8_t)~(1u << (py % 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define WIFI_QR_SIDE 64
|
||||
#define WIFI_QR_BYTES (WIFI_QR_SIDE * WIFI_QR_SIDE / 8)
|
||||
|
||||
// Standard WIFI: WPA join payload, rendered as SSD1306 page-order pixels.
|
||||
// Bright background, dark modules, integer scaling and >=4-module quiet zone.
|
||||
// Called only when credentials change, never from the radio task.
|
||||
bool wifi_qr_bitmap(const char *ssid, const char *password, uint8_t out[WIFI_QR_BYTES]);
|
||||
@@ -103,6 +103,81 @@ bool wmbus_check_crc(wmbus_frame_fmt_t fmt, const uint8_t *frame, int total_len)
|
||||
return false;
|
||||
}
|
||||
|
||||
// Map a CRC-free logical byte offset to its position in the raw frame.
|
||||
// Header fields can straddle a format A block boundary.
|
||||
static int raw_offset(wmbus_frame_fmt_t fmt, int offset)
|
||||
{
|
||||
if (fmt == WMBUS_FRAME_A)
|
||||
return offset < 10 ? offset : offset + 2 + 2 * ((offset - 10) / 16);
|
||||
return offset + 2 * (offset / 126);
|
||||
}
|
||||
|
||||
bool wmbus_mark_repeated(wmbus_frame_fmt_t fmt, uint8_t *frame, int total_len)
|
||||
{
|
||||
if (total_len < 12 || wmbus_frame_total_len(fmt, frame[0]) != total_len)
|
||||
return false;
|
||||
if (fmt == WMBUS_FRAME_B && total_len % 128 != 0 && total_len % 128 < 3)
|
||||
return false;
|
||||
int data_len = fmt == WMBUS_FRAME_A ? frame[0] + 1
|
||||
: total_len - 2 * ((total_len + 127) / 128);
|
||||
if (data_len <= 10 || (frame[1] != 0x44 && frame[1] != 0x46))
|
||||
return false;
|
||||
|
||||
uint8_t ci = frame[raw_offset(fmt, 10)];
|
||||
int control;
|
||||
uint8_t hop_mask;
|
||||
if (ci == 0x8C || ci == 0x8E) {
|
||||
// Require the complete ELL and a following CI. Its contents remain
|
||||
// opaque: this link control field is outside the secured payload.
|
||||
int header_len = ci == 0x8C ? 3 : 11;
|
||||
if (data_len <= 10 + header_len) return false;
|
||||
control = raw_offset(fmt, 11);
|
||||
hop_mask = 0x10;
|
||||
} else {
|
||||
int header_len;
|
||||
switch (ci) {
|
||||
// OMS uplink CI values with short / long transport headers.
|
||||
case 0x67: case 0x6E: case 0x74: case 0x7A: case 0x7D:
|
||||
case 0x7F: case 0x88: case 0x8A: case 0x9E: case 0xC1:
|
||||
case 0xC4:
|
||||
header_len = 5;
|
||||
break;
|
||||
case 0x68: case 0x6F: case 0x72: case 0x75: case 0x7C:
|
||||
case 0x7E: case 0x87: case 0x8B: case 0x9F: case 0xC2:
|
||||
case 0xC5:
|
||||
header_len = 13;
|
||||
break;
|
||||
default:
|
||||
// Do not guess through unknown or secured encapsulations.
|
||||
return false;
|
||||
}
|
||||
if (data_len < 10 + header_len) return false;
|
||||
int cf = 10 + header_len - 2;
|
||||
uint8_t mode = frame[raw_offset(fmt, cf + 1)] & 0x1F;
|
||||
if (mode != 0 && mode != 5) return false;
|
||||
control = raw_offset(fmt, cf);
|
||||
hop_mask = 0x01;
|
||||
}
|
||||
// Modern OMS has separate H and R bits, not a two-bit hop count.
|
||||
if (frame[control] & (hop_mask | 0x02)) return false;
|
||||
|
||||
frame[control] |= hop_mask;
|
||||
int start, count;
|
||||
if (fmt == WMBUS_FRAME_A) {
|
||||
start = 12 + 18 * ((control - 12) / 18);
|
||||
count = total_len - start - 2;
|
||||
if (count > 16) count = 16;
|
||||
} else {
|
||||
start = 128 * (control / 128);
|
||||
count = total_len - start - 2;
|
||||
if (count > 126) count = 126;
|
||||
}
|
||||
uint16_t crc = wmbus_crc16(frame + start, (size_t)count);
|
||||
frame[start + count] = crc >> 8;
|
||||
frame[start + count + 1] = crc & 0xFF;
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t wmbus_hash(const uint8_t *data, size_t len)
|
||||
{
|
||||
uint32_t h = 2166136261u;
|
||||
@@ -161,3 +236,92 @@ int wmbus_build_test_frame(uint8_t *out, size_t maxlen, uint8_t access_nr,
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ---- T-mode "3 of 6" codec --------------------------------------------
|
||||
|
||||
// nibble -> 6-bit code (EN 13757-4 table 3; inverse of the rtl-wmbus
|
||||
// LOW_NIBBLE_3OUTOF6 lookup)
|
||||
static const uint8_t enc3of6[16] = {
|
||||
0x16, 0x0D, 0x0E, 0x0B, 0x1C, 0x19, 0x1A, 0x13,
|
||||
0x2C, 0x25, 0x26, 0x23, 0x34, 0x31, 0x32, 0x29,
|
||||
};
|
||||
|
||||
// 6-bit code -> nibble, 0xFF invalid (rtl-wmbus LOW_NIBBLE_3OUTOF6)
|
||||
static const uint8_t dec3of6[64] = {
|
||||
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||
0xFF, 0xFF, 0xFF, 0x03, 0xFF, 0x01, 0x02, 0xFF,
|
||||
0xFF, 0xFF, 0xFF, 0x07, 0xFF, 0xFF, 0x00, 0xFF,
|
||||
0xFF, 0x05, 0x06, 0xFF, 0x04, 0xFF, 0xFF, 0xFF,
|
||||
0xFF, 0xFF, 0xFF, 0x0B, 0xFF, 0x09, 0x0A, 0xFF,
|
||||
0xFF, 0x0F, 0xFF, 0xFF, 0x08, 0xFF, 0xFF, 0xFF,
|
||||
0xFF, 0x0D, 0x0E, 0xFF, 0x0C, 0xFF, 0xFF, 0xFF,
|
||||
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||
};
|
||||
|
||||
int wmbus_3of6_coded_len(int total_len)
|
||||
{
|
||||
return (total_len * 12 + 7) / 8;
|
||||
}
|
||||
|
||||
static unsigned get6(const uint8_t *b, size_t len, size_t bitpos)
|
||||
{
|
||||
size_t byte = bitpos >> 3;
|
||||
unsigned shift = (unsigned)(bitpos & 7);
|
||||
unsigned w = (unsigned)b[byte] << 8;
|
||||
if (byte + 1 < len) w |= b[byte + 1];
|
||||
return (w >> (10 - shift)) & 0x3F;
|
||||
}
|
||||
|
||||
int wmbus_3of6_decode(const uint8_t *coded, size_t coded_len,
|
||||
uint8_t *out, int total_len)
|
||||
{
|
||||
if (total_len < 0 || (size_t)total_len * 12 > coded_len * 8) return -1;
|
||||
int bad = 0;
|
||||
size_t bit = 0;
|
||||
for (int i = 0; i < total_len; i++) {
|
||||
uint8_t hi = dec3of6[get6(coded, coded_len, bit)];
|
||||
uint8_t lo = dec3of6[get6(coded, coded_len, bit + 6)];
|
||||
bit += 12;
|
||||
if (hi == 0xFF) { hi = 0; bad++; }
|
||||
if (lo == 0xFF) { lo = 0; bad++; }
|
||||
out[i] = (uint8_t)((hi << 4) | lo);
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
int wmbus_3of6_first_byte(const uint8_t *coded, size_t coded_len)
|
||||
{
|
||||
if (coded_len < 2) return -1;
|
||||
uint8_t hi = dec3of6[get6(coded, coded_len, 0)];
|
||||
uint8_t lo = dec3of6[get6(coded, coded_len, 6)];
|
||||
if (hi == 0xFF || lo == 0xFF) return -1;
|
||||
return (hi << 4) | lo;
|
||||
}
|
||||
|
||||
int wmbus_3of6_encode(const uint8_t *data, int total_len,
|
||||
uint8_t *coded, size_t maxlen)
|
||||
{
|
||||
int coded_len = wmbus_3of6_coded_len(total_len);
|
||||
if (total_len < 0 || (size_t)coded_len > maxlen) return -1;
|
||||
|
||||
uint32_t acc = 0;
|
||||
int acc_bits = 0;
|
||||
size_t pos = 0;
|
||||
for (int i = 0; i < 2 * total_len; i++) {
|
||||
uint8_t nib = (i & 1) ? (data[i >> 1] & 0x0F)
|
||||
: (data[i >> 1] >> 4);
|
||||
acc = (acc << 6) | enc3of6[nib];
|
||||
acc_bits += 6;
|
||||
while (acc_bits >= 8) {
|
||||
coded[pos++] = (uint8_t)(acc >> (acc_bits - 8));
|
||||
acc_bits -= 8;
|
||||
}
|
||||
}
|
||||
if (acc_bits > 0) {
|
||||
// pad the tail to the byte boundary with 01 postamble chips
|
||||
uint8_t tail = (uint8_t)(acc << (8 - acc_bits));
|
||||
tail |= (uint8_t)(0x55 & (0xFF >> acc_bits));
|
||||
coded[pos++] = tail;
|
||||
}
|
||||
return (int)pos;
|
||||
}
|
||||
|
||||
+34
-1
@@ -1,4 +1,4 @@
|
||||
// Wireless M-Bus C-mode frame helpers (EN 13757-4).
|
||||
// Wireless M-Bus C/T-mode frame helpers (EN 13757-4).
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
@@ -28,6 +28,13 @@ bool wmbus_check_crc(wmbus_frame_fmt_t fmt, const uint8_t *frame, int total_len)
|
||||
// CRC-16 EN 13757 (poly 0x3D65, init 0, complemented result).
|
||||
uint16_t wmbus_crc16(const uint8_t *data, size_t len);
|
||||
|
||||
// Mark an eligible OMS uplink as repeated in place, repairing its block CRC.
|
||||
// Caller must first validate all CRCs. Supports ELL 8C/8E or a direct short/
|
||||
// long uplink TPL header in security mode 0/5. ELL takes precedence.
|
||||
// Returns false, leaving frame unchanged, for unsupported/malformed headers,
|
||||
// non-SND_NR/SND_IR C-fields, H=1 or R=1. No payload decryption is performed.
|
||||
bool wmbus_mark_repeated(wmbus_frame_fmt_t fmt, uint8_t *frame, int total_len);
|
||||
|
||||
// Build a valid C-mode format A test frame with our test manufacturer/ID.
|
||||
// Returns total frame length written to out (>= 12), or -1 if payload_len
|
||||
// does not fit. out[0] = L-field.
|
||||
@@ -36,3 +43,29 @@ int wmbus_build_test_frame(uint8_t *out, size_t maxlen, uint8_t access_nr,
|
||||
|
||||
// 32-bit FNV-1a hash used to correlate RX/TX events in the logs.
|
||||
uint32_t wmbus_hash(const uint8_t *data, size_t len);
|
||||
|
||||
// ---- T-mode "3 of 6" codec (EN 13757-4) -------------------------------
|
||||
// Chips travel MSB-first: the first received chip is bit 7 of coded[0].
|
||||
// T1 shares the 0x543D access code with C-mode; after it, T1 sends coded
|
||||
// data directly (no mode bytes). Tables verified against rtl-wmbus
|
||||
// t1_c1_packet_decoder.h (HIGH/LOW_NIBBLE_3OUTOF6).
|
||||
|
||||
// Coded on-air byte count for a decoded byte count: ceil(total * 12 / 8).
|
||||
int wmbus_3of6_coded_len(int total_len);
|
||||
|
||||
// Decode total_len bytes (2 * total_len six-bit codes) from coded[].
|
||||
// Invalid codes decode as 0x0 nibbles so the CRC can still judge the
|
||||
// frame. Returns the number of invalid codes (0 = clean), or -1 if
|
||||
// coded_len holds fewer than total_len * 12 bits.
|
||||
int wmbus_3of6_decode(const uint8_t *coded, size_t coded_len,
|
||||
uint8_t *out, int total_len);
|
||||
|
||||
// Decode only the first byte (the T1 L-field). Returns 0..255, or -1 if
|
||||
// either 6-bit code is invalid or fewer than 2 bytes are available.
|
||||
int wmbus_3of6_first_byte(const uint8_t *coded, size_t coded_len);
|
||||
|
||||
// Encode total_len bytes into 3-of-6 chips, padding the final partial
|
||||
// byte with 01 postamble chips. Returns coded byte count, or -1 if it
|
||||
// does not fit maxlen.
|
||||
int wmbus_3of6_encode(const uint8_t *data, int total_len,
|
||||
uint8_t *coded, size_t maxlen);
|
||||
|
||||
@@ -19,3 +19,7 @@ CONFIG_ESP_TASK_WDT_PANIC=y
|
||||
# Keep bootloader/app log noise low; all HIL-relevant output is JSON lines
|
||||
CONFIG_LOG_DEFAULT_LEVEL_WARN=y
|
||||
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
|
||||
|
||||
# Keep network processing off the timing-sensitive radio task's core.
|
||||
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
|
||||
CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0=y
|
||||
|
||||
@@ -14,3 +14,22 @@ trap 'rm -rf "$OUT"' EXIT
|
||||
-o "$OUT/test_wmbus" test_wmbus.c ../main/wmbus.c
|
||||
|
||||
"$OUT/test_wmbus"
|
||||
|
||||
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
|
||||
-fsanitize=address,undefined -fno-omit-frame-pointer \
|
||||
-I../main -o "$OUT/test_duty_ledger" \
|
||||
test_duty_ledger.c ../main/duty_ledger.c
|
||||
|
||||
"$OUT/test_duty_ledger"
|
||||
|
||||
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
|
||||
-fsanitize=address,undefined -fno-omit-frame-pointer \
|
||||
-I../main -o "$OUT/test_t1_long" \
|
||||
test_t1_long.c ../main/wmbus.c
|
||||
|
||||
"$OUT/test_t1_long"
|
||||
|
||||
"$CC" -std=c11 -O1 -g -Wall -Wextra -Werror \
|
||||
-I../main -o "$OUT/test_font_render" test_font_render.c
|
||||
|
||||
"$OUT/test_font_render" | tail -1
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "duty_ledger.h"
|
||||
|
||||
static void test_accumulates_without_event_limit(void)
|
||||
{
|
||||
duty_ledger_t ledger = {0};
|
||||
for (int i = 0; i < 10000; i++) {
|
||||
duty_ledger_record(&ledger, 1000000, 100);
|
||||
}
|
||||
assert(duty_ledger_used(&ledger, 2000000) == 1000000);
|
||||
}
|
||||
|
||||
static void test_retains_every_overlapping_minute(void)
|
||||
{
|
||||
duty_ledger_t ledger = {0};
|
||||
for (int minute = 0; minute <= 60; minute++) {
|
||||
duty_ledger_record(&ledger, (int64_t)minute * DUTY_LEDGER_BUCKET_US, 100);
|
||||
}
|
||||
|
||||
// The oldest partially overlapping minute is deliberately included.
|
||||
assert(duty_ledger_used(&ledger,
|
||||
60 * DUTY_LEDGER_BUCKET_US + DUTY_LEDGER_BUCKET_US / 2) == 6100);
|
||||
|
||||
// Reusing the ring slot at minute 61 cannot discard in-window airtime.
|
||||
duty_ledger_record(&ledger, 61 * DUTY_LEDGER_BUCKET_US, 200);
|
||||
assert(duty_ledger_used(&ledger, 61 * DUTY_LEDGER_BUCKET_US) == 6200);
|
||||
}
|
||||
|
||||
static void test_expires_whole_old_buckets(void)
|
||||
{
|
||||
duty_ledger_t ledger = {0};
|
||||
duty_ledger_record(&ledger, 0, 123);
|
||||
assert(duty_ledger_used(&ledger, DUTY_LEDGER_WINDOW_US) == 123);
|
||||
assert(duty_ledger_used(&ledger,
|
||||
DUTY_LEDGER_WINDOW_US + DUTY_LEDGER_BUCKET_US) == 0);
|
||||
}
|
||||
|
||||
static void test_rejects_invalid_records(void)
|
||||
{
|
||||
duty_ledger_t ledger = {0};
|
||||
duty_ledger_record(&ledger, -1, 100);
|
||||
duty_ledger_record(&ledger, 1, 0);
|
||||
assert(duty_ledger_used(&ledger, 1) == 0);
|
||||
assert(duty_ledger_used(&ledger, -1) == 0);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
test_accumulates_without_event_limit();
|
||||
test_retains_every_overlapping_minute();
|
||||
test_expires_whole_old_buckets();
|
||||
test_rejects_invalid_records();
|
||||
puts("duty ledger tests: PASS");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Host-side visual check of the 5x7 font: renders representative UI text
|
||||
// as ASCII art so the glyph table can be reviewed without hardware, and
|
||||
// asserts basic structural invariants.
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "font5x7.h"
|
||||
|
||||
static void render_line(const char *text)
|
||||
{
|
||||
char rows[FONT5X7_H][128];
|
||||
int cols = 0;
|
||||
memset(rows, 0, sizeof(rows));
|
||||
for (const char *p = text; *p && cols + 6 < 120; p++) {
|
||||
unsigned c = (unsigned char)*p;
|
||||
if (c < FONT5X7_FIRST || c > FONT5X7_LAST) c = '?';
|
||||
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
|
||||
for (int x = 0; x < FONT5X7_W; x++) {
|
||||
for (int y = 0; y < FONT5X7_H; y++) {
|
||||
rows[y][cols + x] = (g[x] >> y) & 1 ? '#' : ' ';
|
||||
}
|
||||
}
|
||||
for (int y = 0; y < FONT5X7_H; y++) rows[y][cols + 5] = ' ';
|
||||
cols += 6;
|
||||
}
|
||||
for (int y = 0; y < FONT5X7_H; y++) {
|
||||
rows[y][cols] = 0;
|
||||
printf("|%s|\n", rows[y]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
// Every printable glyph except space must have at least one pixel.
|
||||
for (int c = FONT5X7_FIRST + 1; c <= FONT5X7_LAST; c++) {
|
||||
int bits = 0;
|
||||
for (int x = 0; x < FONT5X7_W; x++) {
|
||||
const uint8_t *g = font5x7[c - FONT5X7_FIRST];
|
||||
for (int y = 0; y < FONT5X7_H; y++) bits += (g[x] >> y) & 1;
|
||||
assert((g[x] & 0x80) == 0); // 7 rows only
|
||||
}
|
||||
assert(bits > 0);
|
||||
}
|
||||
|
||||
render_line("WMBUS RPT 868.95 C1");
|
||||
render_line("RX 389 TX 381 OK");
|
||||
render_line("DUTY [####-] 0.09%");
|
||||
render_line("0123456789 +-/:=.#%");
|
||||
render_line("ABCDEFGHIJKLM");
|
||||
render_line("NOPQRSTUVWXYZ");
|
||||
puts("font render test: PASS (inspect art above)");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// T-mode 3-of-6 codec + long-frame CRC path tests (host, sanitizers).
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "wmbus.h"
|
||||
|
||||
static void test_codec_roundtrip_all_values(void)
|
||||
{
|
||||
uint8_t data[256], coded[512], back[256];
|
||||
for (int i = 0; i < 256; i++) data[i] = (uint8_t)i;
|
||||
int clen = wmbus_3of6_encode(data, 256, coded, sizeof(coded));
|
||||
assert(clen == wmbus_3of6_coded_len(256));
|
||||
assert(clen == 384); // 256 * 1.5
|
||||
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 256) == 0);
|
||||
assert(memcmp(data, back, 256) == 0);
|
||||
assert(wmbus_3of6_first_byte(coded, (size_t)clen) == 0x00);
|
||||
}
|
||||
|
||||
static void test_codec_detects_any_single_chip_flip(void)
|
||||
{
|
||||
// 3-of-6 codes have constant weight 3: one flipped chip changes the
|
||||
// weight, so every single-bit corruption inside the coded payload
|
||||
// must surface as an invalid code.
|
||||
uint8_t data[32], coded[64], back[32];
|
||||
for (int i = 0; i < 32; i++) data[i] = (uint8_t)(i * 37 + 5);
|
||||
int clen = wmbus_3of6_encode(data, 32, coded, sizeof(coded));
|
||||
assert(clen == 48);
|
||||
for (int bit = 0; bit < 32 * 12; bit++) {
|
||||
coded[bit >> 3] ^= (uint8_t)(0x80u >> (bit & 7));
|
||||
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 32) > 0);
|
||||
coded[bit >> 3] ^= (uint8_t)(0x80u >> (bit & 7));
|
||||
}
|
||||
assert(wmbus_3of6_decode(coded, (size_t)clen, back, 32) == 0);
|
||||
}
|
||||
|
||||
static void test_codec_bounds(void)
|
||||
{
|
||||
uint8_t coded[8] = {0};
|
||||
uint8_t out[8];
|
||||
assert(wmbus_3of6_decode(coded, 2, out, 2) == -1); // 24 bits > 16
|
||||
assert(wmbus_3of6_first_byte(coded, 1) == -1);
|
||||
assert(wmbus_3of6_first_byte(coded, 2) == -1); // 000000 invalid
|
||||
uint8_t d[4] = {0};
|
||||
assert(wmbus_3of6_encode(d, 4, coded, 5) == -1); // needs 6
|
||||
}
|
||||
|
||||
static void test_t1_frame_roundtrip(void)
|
||||
{
|
||||
uint8_t frame[256], coded[512], back[256];
|
||||
int total = wmbus_build_test_frame(frame, sizeof(frame), 42, 100);
|
||||
assert(total > 0);
|
||||
int clen = wmbus_3of6_encode(frame, total, coded, sizeof(coded));
|
||||
assert(clen == wmbus_3of6_coded_len(total));
|
||||
assert(wmbus_3of6_first_byte(coded, (size_t)clen) == frame[0]);
|
||||
assert(wmbus_3of6_decode(coded, (size_t)clen, back, total) == 0);
|
||||
assert(memcmp(frame, back, total) == 0);
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_A, back, total));
|
||||
}
|
||||
|
||||
static void build_b_frame(uint8_t *out, uint8_t lfield)
|
||||
{
|
||||
int total = 1 + lfield;
|
||||
out[0] = lfield;
|
||||
for (int i = 1; i < total; i++) out[i] = (uint8_t)(i * 73 + 11);
|
||||
if (total > 128) {
|
||||
// two chunks: CRC over first 126 at [126..127], rest at the tail
|
||||
int rem = total - 128;
|
||||
assert(rem >= 3);
|
||||
uint16_t c = wmbus_crc16(out, 126);
|
||||
out[126] = c >> 8; out[127] = c & 0xFF;
|
||||
c = wmbus_crc16(out + 128, rem - 2);
|
||||
out[total - 2] = c >> 8; out[total - 1] = c & 0xFF;
|
||||
} else {
|
||||
uint16_t c = wmbus_crc16(out, total - 2);
|
||||
out[total - 2] = c >> 8; out[total - 1] = c & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
static void test_format_b_long(void)
|
||||
{
|
||||
uint8_t f[256];
|
||||
// > 128 bytes: two CRC chunks
|
||||
build_b_frame(f, 200);
|
||||
assert(wmbus_frame_total_len(WMBUS_FRAME_B, 200) == 201);
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 201));
|
||||
// corruption in either chunk must fail
|
||||
f[50] ^= 1;
|
||||
assert(!wmbus_check_crc(WMBUS_FRAME_B, f, 201));
|
||||
f[50] ^= 1;
|
||||
f[150] ^= 1;
|
||||
assert(!wmbus_check_crc(WMBUS_FRAME_B, f, 201));
|
||||
f[150] ^= 1;
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 201));
|
||||
// exactly one full chunk
|
||||
build_b_frame(f, 127);
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 128));
|
||||
// short frame
|
||||
build_b_frame(f, 20);
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 21));
|
||||
// maximum that fits the radio payload
|
||||
build_b_frame(f, 252);
|
||||
assert(wmbus_frame_total_len(WMBUS_FRAME_B, 252) == 253);
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_B, f, 253));
|
||||
}
|
||||
|
||||
static void test_format_a_long(void)
|
||||
{
|
||||
uint8_t frame[256];
|
||||
int total = wmbus_build_test_frame(frame, sizeof(frame), 7, 200);
|
||||
assert(total == 227); // 1 + 200 + 2 * (1 + ceil(191/16))
|
||||
assert(wmbus_check_crc(WMBUS_FRAME_A, frame, total));
|
||||
frame[220] ^= 1;
|
||||
assert(!wmbus_check_crc(WMBUS_FRAME_A, frame, total));
|
||||
// beyond the fixed radio capture: must be rejected, not truncated
|
||||
assert(wmbus_frame_total_len(WMBUS_FRAME_A, 255) == -1);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
test_codec_roundtrip_all_values();
|
||||
test_codec_detects_any_single_chip_flip();
|
||||
test_codec_bounds();
|
||||
test_t1_frame_roundtrip();
|
||||
test_format_b_long();
|
||||
test_format_a_long();
|
||||
puts("t1 + long-frame tests: PASS");
|
||||
return 0;
|
||||
}
|
||||
+210
-1
@@ -162,9 +162,213 @@ static void test_builder_roundtrip(void)
|
||||
"builder must refuse a buffer that cannot hold the frame");
|
||||
}
|
||||
|
||||
// Pack cooked bytes independently of the production raw-frame walker. Only
|
||||
// the CRC primitive is shared (anchored by the captured known-answer test).
|
||||
static int pack_hop_frame(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
|
||||
uint8_t *raw)
|
||||
{
|
||||
assert(len >= 10 && len <= 200);
|
||||
int total = fmt == WMBUS_FRAME_A
|
||||
? len + 2 * (1 + (len - 10 + 15) / 16)
|
||||
: len + (len > 126 ? 4 : 2);
|
||||
cooked[0] = (uint8_t)(fmt == WMBUS_FRAME_A ? len - 1 : total - 1);
|
||||
int src = 0, dst = 0;
|
||||
while (src < len) {
|
||||
int block = fmt == WMBUS_FRAME_A ? (src == 0 ? 10 : 16) : 126;
|
||||
if (block > len - src) block = len - src;
|
||||
memcpy(raw + dst, cooked + src, (size_t)block);
|
||||
uint16_t crc = wmbus_crc16(cooked + src, (size_t)block);
|
||||
raw[dst + block] = (uint8_t)(crc >> 8);
|
||||
raw[dst + block + 1] = (uint8_t)crc;
|
||||
src += block;
|
||||
dst += block + 2;
|
||||
}
|
||||
assert(dst == total);
|
||||
return total;
|
||||
}
|
||||
|
||||
static void init_hop_frame(uint8_t *cooked, int len, uint8_t ci)
|
||||
{
|
||||
for (int i = 0; i < len; i++) cooked[i] = (uint8_t)(i * 73 + 11);
|
||||
cooked[1] = 0x44;
|
||||
cooked[10] = ci;
|
||||
}
|
||||
|
||||
static void check_hop_mark(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
|
||||
int h_offset, uint8_t h_mask)
|
||||
{
|
||||
uint8_t raw[300], expected[300];
|
||||
memset(raw, 0xA5, sizeof(raw));
|
||||
memset(expected, 0xA5, sizeof(expected));
|
||||
int total = pack_hop_frame(fmt, cooked, len, raw);
|
||||
CHECK(wmbus_check_crc(fmt, raw, total), "invalid hop input fixture");
|
||||
cooked[h_offset] |= h_mask;
|
||||
pack_hop_frame(fmt, cooked, len, expected);
|
||||
cooked[h_offset] &= (uint8_t)~h_mask;
|
||||
|
||||
CHECK(wmbus_mark_repeated(fmt, raw, total),
|
||||
"fmt=%d CI=%02X: unmarked frame refused", fmt, cooked[10]);
|
||||
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
|
||||
"fmt=%d CI=%02X: bytes other than H and its CRC changed",
|
||||
fmt, cooked[10]);
|
||||
CHECK(wmbus_check_crc(fmt, raw, total), "marked frame has invalid CRC");
|
||||
CHECK(!wmbus_mark_repeated(fmt, raw, total), "second hop accepted");
|
||||
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
|
||||
"refused second hop changed frame");
|
||||
|
||||
if (fmt == WMBUS_FRAME_A) {
|
||||
uint8_t coded[450], decoded[300];
|
||||
int coded_len = wmbus_3of6_encode(raw, total, coded, sizeof(coded));
|
||||
CHECK(coded_len > 0, "marked T1 frame did not encode");
|
||||
if (coded_len > 0) {
|
||||
CHECK(wmbus_3of6_first_byte(coded, (size_t)coded_len) == raw[0],
|
||||
"marked T1 frame lost L-field");
|
||||
CHECK(wmbus_3of6_decode(coded, (size_t)coded_len, decoded, total) == 0,
|
||||
"marked T1 frame did not decode");
|
||||
CHECK(memcmp(decoded, expected, (size_t)total) == 0,
|
||||
"T1 roundtrip lost hop mark or changed payload");
|
||||
CHECK(wmbus_check_crc(fmt, decoded, total),
|
||||
"decoded marked T1 frame has invalid CRC");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void check_hop_refused(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len)
|
||||
{
|
||||
uint8_t raw[300], before[300];
|
||||
memset(raw, 0xA5, sizeof(raw));
|
||||
int total = pack_hop_frame(fmt, cooked, len, raw);
|
||||
memcpy(before, raw, sizeof(raw));
|
||||
CHECK(wmbus_check_crc(fmt, raw, total), "invalid refusal fixture");
|
||||
CHECK(!wmbus_mark_repeated(fmt, raw, total),
|
||||
"fmt=%d CI=%02X: unsupported/repeated frame accepted",
|
||||
fmt, cooked[10]);
|
||||
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
|
||||
"refused frame changed bytes");
|
||||
}
|
||||
|
||||
static void test_hop_tpl(void)
|
||||
{
|
||||
static const uint8_t short_ci[] = {
|
||||
0x67, 0x6E, 0x74, 0x7A, 0x7D, 0x7F, 0x88, 0x8A, 0x9E, 0xC1, 0xC4,
|
||||
};
|
||||
static const uint8_t long_ci[] = {
|
||||
0x68, 0x6F, 0x72, 0x75, 0x7C, 0x7E, 0x87, 0x8B, 0x9F, 0xC2, 0xC5,
|
||||
};
|
||||
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
|
||||
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
|
||||
for (int long_header = 0; long_header <= 1; long_header++) {
|
||||
const uint8_t *cis = long_header ? long_ci : short_ci;
|
||||
int cf = long_header ? 21 : 13;
|
||||
uint8_t cooked[200];
|
||||
for (size_t i = 0; i < sizeof(short_ci); i++) {
|
||||
// Long bodies cross A's 16-byte blocks and B's 126-byte
|
||||
// first block; exact comparison protects all ciphertext.
|
||||
for (int mode = 0; mode <= 5; mode += 5) {
|
||||
init_hop_frame(cooked, sizeof(cooked), cis[i]);
|
||||
cooked[1] = i % 2 ? 0x46 : 0x44;
|
||||
cooked[cf] = 0xA4;
|
||||
cooked[cf + 1] = (uint8_t)(0xE0 | mode);
|
||||
check_hop_mark(fmt, cooked, sizeof(cooked), cf, 0x01);
|
||||
}
|
||||
}
|
||||
init_hop_frame(cooked, sizeof(cooked), cis[0]);
|
||||
cooked[cf] = 0xA4;
|
||||
cooked[cf + 1] = 7;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
cooked[cf + 1] = 5;
|
||||
cooked[cf] |= 0x01;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
cooked[cf] = 0xA6;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
|
||||
// A complete transport header needs no application payload,
|
||||
// but every shorter prefix must be refused without mutation.
|
||||
cooked[cf] = 0xA4;
|
||||
cooked[1] = 0x54; // not a masked variant of SND_NR
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
cooked[1] = 0x44;
|
||||
check_hop_mark(fmt, cooked, cf + 2, cf, 0x01);
|
||||
for (int len = 11; len < cf + 2; len++)
|
||||
check_hop_refused(fmt, cooked, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void test_hop_ell(void)
|
||||
{
|
||||
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
|
||||
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
|
||||
for (int long_header = 0; long_header <= 1; long_header++) {
|
||||
uint8_t cooked[200];
|
||||
int inner = long_header ? 21 : 13;
|
||||
init_hop_frame(cooked, sizeof(cooked), long_header ? 0x8E : 0x8C);
|
||||
cooked[11] = 0xE5; // preserve every non-H/R CC bit
|
||||
cooked[inner] = 0x72;
|
||||
cooked[inner + 11] = 0x03; // inner TPL already H=R=1
|
||||
cooked[inner + 12] = 7; // encrypted/authenticated inner TPL
|
||||
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
|
||||
// Exactly full and one-byte-over CRC blocks. For long ELL the
|
||||
// inner TPL crosses A's block boundary; it must remain opaque.
|
||||
int boundary = fmt == WMBUS_FRAME_A ? 26 : 126;
|
||||
check_hop_mark(fmt, cooked, boundary, 11, 0x10);
|
||||
check_hop_mark(fmt, cooked, boundary + 1, 11, 0x10);
|
||||
cooked[inner] = 0x90; // AFL is opaque beneath a usable ELL
|
||||
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
|
||||
cooked[inner] = 0x78;
|
||||
cooked[1] = 0x46;
|
||||
check_hop_mark(fmt, cooked, inner + 1, 11, 0x10);
|
||||
for (int len = 11; len <= inner; len++)
|
||||
check_hop_refused(fmt, cooked, len);
|
||||
cooked[11] |= 0x10;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
cooked[11] = 0xE7;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void test_hop_invalid_headers(void)
|
||||
{
|
||||
static const uint8_t unsupported_ci[] = {0x78, 0x8D, 0x8F, 0x90, 0x00, 0xFF};
|
||||
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
|
||||
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
|
||||
uint8_t cooked[40], raw[300], before[300];
|
||||
for (size_t i = 0; i < sizeof(unsupported_ci); i++) {
|
||||
init_hop_frame(cooked, sizeof(cooked), unsupported_ci[i]);
|
||||
cooked[11] = 0;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
}
|
||||
init_hop_frame(cooked, sizeof(cooked), 0x8C);
|
||||
cooked[11] = 0;
|
||||
// Only these two exact C-fields are valid, not masked variants.
|
||||
for (int c = 0; c <= 255; c++) {
|
||||
if (c == 0x44 || c == 0x46) continue;
|
||||
cooked[1] = (uint8_t)c;
|
||||
check_hop_refused(fmt, cooked, sizeof(cooked));
|
||||
}
|
||||
cooked[1] = 0x44;
|
||||
check_hop_refused(fmt, cooked, 10); // no CI; A has only block 1
|
||||
memset(raw, 0xA5, sizeof(raw));
|
||||
int total = pack_hop_frame(fmt, cooked, sizeof(cooked), raw);
|
||||
memcpy(before, raw, sizeof(raw));
|
||||
for (int len = -1; len <= total + 1; len++) {
|
||||
if (len == total) continue;
|
||||
CHECK(!wmbus_mark_repeated(fmt, raw, len),
|
||||
"mismatched raw length %d accepted (actual %d)", len, total);
|
||||
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
|
||||
"invalid raw length changed frame");
|
||||
}
|
||||
CHECK(!wmbus_mark_repeated(WMBUS_FRAME_UNKNOWN, raw, total),
|
||||
"unknown format accepted");
|
||||
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
|
||||
"unknown format changed frame");
|
||||
}
|
||||
}
|
||||
|
||||
// Adversarial input: random bytes with a length that disagrees with the
|
||||
// L-field, exactly what a corrupted reception looks like. Under ASan this
|
||||
// proves the CRC walk never indexes outside the buffer.
|
||||
// proves the CRC and hop-header walks never index outside the buffer.
|
||||
static void test_fuzz_bounds(void)
|
||||
{
|
||||
srand(12345);
|
||||
@@ -183,8 +387,10 @@ static void test_fuzz_bounds(void)
|
||||
int total = wmbus_frame_total_len(fmt, buf[0]);
|
||||
if (total > 0 && total <= n) {
|
||||
(void)wmbus_check_crc(fmt, buf, total);
|
||||
(void)wmbus_mark_repeated(fmt, buf, total);
|
||||
}
|
||||
(void)wmbus_check_crc(fmt, buf, n);
|
||||
(void)wmbus_mark_repeated(fmt, buf, n);
|
||||
(void)wmbus_hash(buf, (size_t)n);
|
||||
free(buf);
|
||||
}
|
||||
@@ -211,6 +417,9 @@ int main(void)
|
||||
test_length_formulas();
|
||||
test_frame_format_detection();
|
||||
test_builder_roundtrip();
|
||||
test_hop_tpl();
|
||||
test_hop_ell();
|
||||
test_hop_invalid_headers();
|
||||
test_fuzz_bounds();
|
||||
|
||||
if (failures) {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Host tool: feed captured post-sync payload bytes (hex on argv[1]) through
|
||||
// the firmware's T1 classification/decode path exactly as handle_rx does.
|
||||
// Prints the decode result for cross-checking against a known transmitted
|
||||
// frame. Not part of run_tests.sh; used by ad-hoc RF verification.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "wmbus.h"
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc != 2) { fprintf(stderr, "usage: %s HEXBYTES\n", argv[0]); return 2; }
|
||||
size_t hexlen = strlen(argv[1]);
|
||||
static uint8_t buf[512];
|
||||
size_t n = hexlen / 2;
|
||||
if (n > sizeof(buf)) n = sizeof(buf);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
unsigned v;
|
||||
if (sscanf(argv[1] + 2 * i, "%2x", &v) != 1) return 2;
|
||||
buf[i] = (uint8_t)v;
|
||||
}
|
||||
|
||||
int lfield = wmbus_3of6_first_byte(buf, n);
|
||||
printf("lfield=%d\n", lfield);
|
||||
if (lfield < 9) return 1;
|
||||
int total = wmbus_frame_total_len(WMBUS_FRAME_A, (uint8_t)lfield);
|
||||
printf("total=%d coded_len=%d have=%zu\n",
|
||||
total, total > 0 ? wmbus_3of6_coded_len(total) : -1, n);
|
||||
if (total < 0 || wmbus_3of6_coded_len(total) > (int)n) return 1;
|
||||
static uint8_t frame[512];
|
||||
int bad = wmbus_3of6_decode(buf, n, frame, total);
|
||||
int crc = wmbus_check_crc(WMBUS_FRAME_A, frame, total);
|
||||
printf("bad_codes=%d crc_ok=%d\nframe=", bad, crc);
|
||||
for (int i = 0; i < total; i++) printf("%02X", frame[i]);
|
||||
printf("\n");
|
||||
return crc ? 0 : 1;
|
||||
}
|
||||
Reference in New Issue
Block a user