diff --git a/firmware/main/CMakeLists.txt b/firmware/main/CMakeLists.txt index c43a03a..416f93b 100644 --- a/firmware/main/CMakeLists.txt +++ b/firmware/main/CMakeLists.txt @@ -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() diff --git a/firmware/main/board.h b/firmware/main/board.h index a0e8359..898cff9 100644 --- a/firmware/main/board.h +++ b/firmware/main/board.h @@ -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 diff --git a/firmware/main/cfg_store.c b/firmware/main/cfg_store.c new file mode 100644 index 0000000..e13da5f --- /dev/null +++ b/firmware/main/cfg_store.c @@ -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 +#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; +} diff --git a/firmware/main/cfg_store.h b/firmware/main/cfg_store.h new file mode 100644 index 0000000..32bee35 --- /dev/null +++ b/firmware/main/cfg_store.h @@ -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 +#include + +#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 diff --git a/firmware/main/console.c b/firmware/main/console.c index bfae1c0..190f913 100644 --- a/firmware/main/console.c +++ b/firmware/main/console.c @@ -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 #include #include +#include +#include #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"); - 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 { + 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; + } + 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"); } } diff --git a/firmware/main/debug_history.c b/firmware/main/debug_history.c new file mode 100644 index 0000000..0b935ee --- /dev/null +++ b/firmware/main/debug_history.c @@ -0,0 +1,117 @@ +#include "debug_history.h" + +#include +#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; + } + } +} diff --git a/firmware/main/debug_history.h b/firmware/main/debug_history.h new file mode 100644 index 0000000..bb7da19 --- /dev/null +++ b/firmware/main/debug_history.h @@ -0,0 +1,70 @@ +#pragma once + +#include +#include +#include + +#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); diff --git a/firmware/main/duty_ledger.c b/firmware/main/duty_ledger.c new file mode 100644 index 0000000..17102f1 --- /dev/null +++ b/firmware/main/duty_ledger.c @@ -0,0 +1,48 @@ +#include "duty_ledger.h" + +#include +#include + +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; + } +} diff --git a/firmware/main/duty_ledger.h b/firmware/main/duty_ledger.h new file mode 100644 index 0000000..3ee0d04 --- /dev/null +++ b/firmware/main/duty_ledger.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +#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); diff --git a/firmware/main/font5x7.h b/firmware/main/font5x7.h new file mode 100644 index 0000000..ed2e9d7 --- /dev/null +++ b/firmware/main/font5x7.h @@ -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 + +#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}, // '~' +}; diff --git a/firmware/main/main.c b/firmware/main/main.c index e026455..509a4b1 100644 --- a/firmware/main/main.c +++ b/firmware/main/main.c @@ -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 } diff --git a/firmware/main/repeater.c b/firmware/main/repeater.c index c9d06ec..e5de903 100644 --- a/firmware/main/repeater.c +++ b/firmware/main/repeater.c @@ -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 #include @@ -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); + 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 + + 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); + } + 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; } - return; } - int 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; - } - - 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]; - txbuf[0] = buf[0]; - txbuf[1] = buf[1]; - memcpy(txbuf + 2, frame, total); + // 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, diff --git a/firmware/main/repeater.h b/firmware/main/repeater.h index 9c52c75..24f34cd 100644 --- a/firmware/main/repeater.h +++ b/firmware/main/repeater.h @@ -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); diff --git a/firmware/main/settings.c b/firmware/main/settings.c new file mode 100644 index 0000000..50e92b8 --- /dev/null +++ b/firmware/main/settings.c @@ -0,0 +1,170 @@ +#include "settings.h" +#include "cfg_store.h" + +#include +#include +#include +#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; +} diff --git a/firmware/main/settings.h b/firmware/main/settings.h new file mode 100644 index 0000000..f647b80 --- /dev/null +++ b/firmware/main/settings.h @@ -0,0 +1,53 @@ +#pragma once + +#include +#include +#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); diff --git a/firmware/main/settings_http.c b/firmware/main/settings_http.c new file mode 100644 index 0000000..b7852c5 --- /dev/null +++ b/firmware/main/settings_http.c @@ -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 +#include +#include +#include +#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; +} diff --git a/firmware/main/settings_http.h b/firmware/main/settings_http.h new file mode 100644 index 0000000..b591215 --- /dev/null +++ b/firmware/main/settings_http.h @@ -0,0 +1,7 @@ +#pragma once + +#include +#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); diff --git a/firmware/main/sx126x.c b/firmware/main/sx126x.c index 67a47bd..a65a97d 100644 --- a/firmware/main/sx126x.c +++ b/firmware/main/sx126x.c @@ -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; } diff --git a/firmware/main/sx126x.h b/firmware/main/sx126x.h index d3a279f..06372d4 100644 --- a/firmware/main/sx126x.h +++ b/firmware/main/sx126x.h @@ -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); diff --git a/firmware/main/ui.c b/firmware/main/ui.c new file mode 100644 index 0000000..dc82a7c --- /dev/null +++ b/firmware/main/ui.c @@ -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 +#include +#include +#include + +#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); +} diff --git a/firmware/main/ui.h b/firmware/main/ui.h new file mode 100644 index 0000000..815f6aa --- /dev/null +++ b/firmware/main/ui.h @@ -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); diff --git a/firmware/main/vendor/qrcodegen.c b/firmware/main/vendor/qrcodegen.c new file mode 100644 index 0000000..8617044 --- /dev/null +++ b/firmware/main/vendor/qrcodegen.c @@ -0,0 +1,1022 @@ +/* + * 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. + */ + +#include +#include +#include +#include +#include "qrcodegen.h" + +#ifndef QRCODEGEN_TEST + #define testable static // Keep functions private +#else + #define testable // Expose private functions +#endif + + +/*---- Forward declarations for private functions ----*/ + +// Regarding all public and private functions defined in this source file: +// - They require all pointer/array arguments to be not null unless the array length is zero. +// - They only read input scalar/array arguments, write to output pointer/array +// arguments, and return scalar values; they are "pure" functions. +// - They don't read mutable global variables or write to any global variables. +// - They don't perform I/O, read the clock, print to console, etc. +// - They allocate a small and constant amount of stack memory. +// - They don't allocate or free any memory on the heap. +// - They don't recurse or mutually recurse. All the code +// could be inlined into the top-level public functions. +// - They run in at most quadratic time with respect to input arguments. +// Most functions run in linear time, and some in constant time. +// There are no unbounded loops or non-obvious termination conditions. +// - They are completely thread-safe if the caller does not give the +// same writable buffer to concurrent calls to these functions. + +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen); + +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]); +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl); +testable int getNumRawDataModules(int ver); + +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]); +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]); +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y); + +testable void initializeFunctionModules(int version, uint8_t qrcode[]); +static void drawLightFunctionModules(uint8_t qrcode[], int version); +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]); +testable int getAlignmentPatternPositions(int version, uint8_t result[7]); +static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]); + +static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]); +static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask); +static long getPenaltyScore(const uint8_t qrcode[]); +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize); +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize); +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize); + +testable bool getModuleBounded(const uint8_t qrcode[], int x, int y); +testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark); +testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark); +static bool getBit(int x, int i); + +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars); +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version); +static int numCharCountBits(enum qrcodegen_Mode mode, int version); + + + +/*---- Private tables of constants ----*/ + +// The set of all legal characters in alphanumeric mode, where each character +// value maps to the index in the string. For checking text and encoding segments. +static const char *ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +// For generating error correction codes. +testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low + {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium + {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile + {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High +}; + +#define qrcodegen_REED_SOLOMON_DEGREE_MAX 30 // Based on the table above + +// For generating error correction codes. +testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low + {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium + {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile + {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High +}; + +// For automatic mask pattern selection. +static const int PENALTY_N1 = 3; +static const int PENALTY_N2 = 3; +static const int PENALTY_N3 = 40; +static const int PENALTY_N4 = 10; + + + +/*---- High-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +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) { + + size_t textLen = strlen(text); + if (textLen == 0) + return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + size_t bufLen = (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion); + + struct qrcodegen_Segment seg; + if (qrcodegen_isNumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeNumeric(text, tempBuffer); + } else if (qrcodegen_isAlphanumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeAlphanumeric(text, tempBuffer); + } else { + if (textLen > bufLen) + goto fail; + for (size_t i = 0; i < textLen; i++) + tempBuffer[i] = (uint8_t)text[i]; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, textLen); + if (seg.bitLength == -1) + goto fail; + seg.numChars = (int)textLen; + seg.data = tempBuffer; + } + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + +fail: + qrcode[0] = 0; // Set size to invalid value for safety + return false; +} + + +// Public function - see documentation comment in header file. +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) { + + struct qrcodegen_Segment seg; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, dataLen); + if (seg.bitLength == -1) { + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + seg.numChars = (int)dataLen; + seg.data = dataAndTemp; + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode); +} + + +// Appends the given number of low-order bits of the given value to the given byte-based +// bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits. +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen) { + assert(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0); + for (int i = numBits - 1; i >= 0; i--, (*bitLen)++) + buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7)); +} + + + +/*---- Low-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, + enum qrcodegen_Ecc ecl, uint8_t tempBuffer[], uint8_t qrcode[]) { + return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl, + qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode); +} + + +// Public function - see documentation comment in header file. +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[]) { + assert(segs != NULL || len == 0); + assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX); + assert(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = getTotalBits(segs, len, version); + if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) { // All versions in the range could not fit the given data + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + } + assert(dataUsedBits != -1); + + // Increase the error correction level while the data still fits in the current version number + for (int i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8) + ecl = (enum qrcodegen_Ecc)i; + } + + // Concatenate all segments to create the data bit string + memset(qrcode, 0, (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(qrcode[0])); + int bitLen = 0; + for (size_t i = 0; i < len; i++) { + const struct qrcodegen_Segment *seg = &segs[i]; + appendBitsToBuffer((unsigned int)seg->mode, 4, qrcode, &bitLen); + appendBitsToBuffer((unsigned int)seg->numChars, numCharCountBits(seg->mode, version), qrcode, &bitLen); + for (int j = 0; j < seg->bitLength; j++) { + int bit = (seg->data[j >> 3] >> (7 - (j & 7))) & 1; + appendBitsToBuffer((unsigned int)bit, 1, qrcode, &bitLen); + } + } + assert(bitLen == dataUsedBits); + + // Add terminator and pad up to a byte if applicable + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; + assert(bitLen <= dataCapacityBits); + int terminatorBits = dataCapacityBits - bitLen; + if (terminatorBits > 4) + terminatorBits = 4; + appendBitsToBuffer(0, terminatorBits, qrcode, &bitLen); + appendBitsToBuffer(0, (8 - bitLen % 8) % 8, qrcode, &bitLen); + assert(bitLen % 8 == 0); + + // Pad with alternating bytes until data capacity is reached + for (uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + appendBitsToBuffer(padByte, 8, qrcode, &bitLen); + + // Compute ECC, draw modules + addEccAndInterleave(qrcode, version, ecl, tempBuffer); + initializeFunctionModules(version, qrcode); + drawCodewords(tempBuffer, getNumRawDataModules(version) / 8, qrcode); + drawLightFunctionModules(qrcode, version); + initializeFunctionModules(version, tempBuffer); + + // Do masking + if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask + long minPenalty = LONG_MAX; + for (int i = 0; i < 8; i++) { + enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i; + applyMask(tempBuffer, qrcode, msk); + drawFormatBits(ecl, msk, qrcode); + long penalty = getPenaltyScore(qrcode); + if (penalty < minPenalty) { + mask = msk; + minPenalty = penalty; + } + applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR + } + } + assert(0 <= (int)mask && (int)mask <= 7); + applyMask(tempBuffer, qrcode, mask); // Apply the final choice of mask + drawFormatBits(ecl, mask, qrcode); // Overwrite old format bits + return true; +} + + + +/*---- Error correction code generation functions ----*/ + +// Appends error correction bytes to each block of the given data array, then interleaves +// bytes from the blocks and stores them in the result array. data[0 : dataLen] contains +// the input data. data[dataLen : rawCodewords] is used as a temporary work area and will +// be clobbered by this function. The final answer is stored in result[0 : rawCodewords]. +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]) { + // Calculate parameter numbers + assert(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [(int)ecl][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int dataLen = getNumDataCodewords(version, ecl); + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; + + // Split data into blocks, calculate ECC, and interleave + // (not concatenate) the bytes into a single sequence + uint8_t rsdiv[qrcodegen_REED_SOLOMON_DEGREE_MAX]; + reedSolomonComputeDivisor(blockEccLen, rsdiv); + const uint8_t *dat = data; + for (int i = 0; i < numBlocks; i++) { + int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); + uint8_t *ecc = &data[dataLen]; // Temporary storage + reedSolomonComputeRemainder(dat, datLen, rsdiv, blockEccLen, ecc); + for (int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data + if (j == shortBlockDataLen) + k -= numShortBlocks; + result[k] = dat[j]; + } + for (int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC + result[k] = ecc[j]; + dat += datLen; + } +} + + +// Returns the number of 8-bit codewords that can be used for storing data (not ECC), +// for the given version number and error correction level. The result is in the range [9, 2956]. +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl) { + int v = version, e = (int)ecl; + assert(0 <= e && e < 4); + return getNumRawDataModules(v) / 8 + - ECC_CODEWORDS_PER_BLOCK [e][v] + * NUM_ERROR_CORRECTION_BLOCKS[e][v]; +} + + +// Returns the number of data bits that can be stored in a QR Code of the given version number, after +// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. +// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. +testable int getNumRawDataModules(int ver) { + assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX); + int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; +} + + + +/*---- Reed-Solomon ECC generator functions ----*/ + +// Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree]. +// This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm. +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + memset(result, 0, (size_t)degree * sizeof(result[0])); + result[degree - 1] = 1; // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + uint8_t root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (int j = 0; j < degree; j++) { + result[j] = reedSolomonMultiply(result[j], root); + if (j + 1 < degree) + result[j] ^= result[j + 1]; + } + root = reedSolomonMultiply(root, 0x02); + } +} + + +// Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials. +// The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree]. +// All polynomials are in big endian, and the generator has an implicit leading 1 term. +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + memset(result, 0, (size_t)degree * sizeof(result[0])); + for (int i = 0; i < dataLen; i++) { // Polynomial division + uint8_t factor = data[i] ^ result[0]; + memmove(&result[0], &result[1], (size_t)(degree - 1) * sizeof(result[0])); + result[degree - 1] = 0; + for (int j = 0; j < degree; j++) + result[j] ^= reedSolomonMultiply(generator[j], factor); + } +} + +#undef qrcodegen_REED_SOLOMON_DEGREE_MAX + + +// Returns the product of the two given field elements modulo GF(2^8/0x11D). +// All inputs are valid. This could be implemented as a 256*256 lookup table. +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) { + // Russian peasant multiplication + uint8_t z = 0; + for (int i = 7; i >= 0; i--) { + z = (uint8_t)((z << 1) ^ ((z >> 7) * 0x11D)); + z ^= ((y >> i) & 1) * x; + } + return z; +} + + + +/*---- Drawing function modules ----*/ + +// Clears the given QR Code grid with light modules for the given +// version's size, then marks every function module as dark. +testable void initializeFunctionModules(int version, uint8_t qrcode[]) { + // Initialize QR Code + int qrsize = version * 4 + 17; + memset(qrcode, 0, (size_t)((qrsize * qrsize + 7) / 8 + 1) * sizeof(qrcode[0])); + qrcode[0] = (uint8_t)qrsize; + + // Fill horizontal and vertical timing patterns + fillRectangle(6, 0, 1, qrsize, qrcode); + fillRectangle(0, 6, qrsize, 1, qrcode); + + // Fill 3 finder patterns (all corners except bottom right) and format bits + fillRectangle(0, 0, 9, 9, qrcode); + fillRectangle(qrsize - 8, 0, 8, 9, qrcode); + fillRectangle(0, qrsize - 8, 9, 8, qrcode); + + // Fill numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) + fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode); + } + } + + // Fill version blocks + if (version >= 7) { + fillRectangle(qrsize - 11, 0, 3, 6, qrcode); + fillRectangle(0, qrsize - 11, 6, 3, qrcode); + } +} + + +// Draws light function modules and possibly some dark modules onto the given QR Code, without changing +// non-function modules. This does not draw the format bits. This requires all function modules to be previously +// marked dark (namely by initializeFunctionModules()), because this may skip redrawing dark function modules. +static void drawLightFunctionModules(uint8_t qrcode[], int version) { + // Draw horizontal and vertical timing patterns + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 7; i < qrsize - 7; i += 2) { + setModuleBounded(qrcode, 6, i, false); + setModuleBounded(qrcode, i, 6, false); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = abs(dx); + if (abs(dy) > dist) + dist = abs(dy); + if (dist == 2 || dist == 4) { + setModuleUnbounded(qrcode, 3 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, qrsize - 4 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, 3 + dx, qrsize - 4 + dy, false); + } + } + } + + // Draw numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)) + continue; // Don't draw on the three finder corners + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) + setModuleBounded(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0); + } + } + } + + // Draw version blocks + if (version >= 7) { + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + long bits = (long)version << 12 | rem; // uint18 + assert(bits >> 18 == 0); + + // Draw two copies + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 3; j++) { + int k = qrsize - 11 + j; + setModuleBounded(qrcode, k, i, (bits & 1) != 0); + setModuleBounded(qrcode, i, k, (bits & 1) != 0); + bits >>= 1; + } + } + } +} + + +// Draws two copies of the format bits (with its own error correction code) based +// on the given mask and error correction level. This always draws all modules of +// the format bits, unlike drawLightFunctionModules() which might skip dark modules. +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint8_t qrcode[]) { + // Calculate error correction code and pack bits + assert(0 <= (int)mask && (int)mask <= 7); + static const int table[] = {1, 0, 3, 2}; + int data = table[(int)ecl] << 3 | (int)mask; // errCorrLvl is uint2, mask is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >> 15 == 0); + + // Draw first copy + for (int i = 0; i <= 5; i++) + setModuleBounded(qrcode, 8, i, getBit(bits, i)); + setModuleBounded(qrcode, 8, 7, getBit(bits, 6)); + setModuleBounded(qrcode, 8, 8, getBit(bits, 7)); + setModuleBounded(qrcode, 7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setModuleBounded(qrcode, 14 - i, 8, getBit(bits, i)); + + // Draw second copy + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 0; i < 8; i++) + setModuleBounded(qrcode, qrsize - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setModuleBounded(qrcode, 8, qrsize - 15 + i, getBit(bits, i)); + setModuleBounded(qrcode, 8, qrsize - 8, true); // Always dark +} + + +// Calculates and stores an ascending list of positions of alignment patterns +// for this version number, returning the length of the list (in the range [0,7]). +// Each position is in the range [0,177), and are used on both the x and y axes. +// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. +testable int getAlignmentPatternPositions(int version, uint8_t result[7]) { + if (version == 1) + return 0; + int numAlign = version / 7 + 2; + int step = (version == 32) ? 26 : + (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2; + for (int i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step) + result[i] = (uint8_t)pos; + result[0] = 6; + return numAlign; +} + + +// Sets every module in the range [left : left + width] * [top : top + height] to dark. +static void fillRectangle(int left, int top, int width, int height, uint8_t qrcode[]) { + for (int dy = 0; dy < height; dy++) { + for (int dx = 0; dx < width; dx++) + setModuleBounded(qrcode, left + dx, top + dy, true); + } +} + + + +/*---- Drawing data modules and masking ----*/ + +// Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of +// the QR Code to be dark at function modules and light at codeword modules (including unused remainder bits). +static void drawCodewords(const uint8_t data[], int dataLen, uint8_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + int i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < qrsize; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + int x = right - j; // Actual x coordinate + bool upward = ((right + 1) & 2) == 0; + int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate + if (!getModuleBounded(qrcode, x, y) && i < dataLen * 8) { + bool dark = getBit(data[i >> 3], 7 - (i & 7)); + setModuleBounded(qrcode, x, y, dark); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i == dataLen * 8); +} + + +// XORs the codeword modules in this QR Code with the given mask pattern +// and given pattern of function modules. The codeword bits must be drawn +// before masking. Due to the arithmetic of XOR, calling applyMask() with +// the same mask value a second time will undo the mask. A final well-formed +// QR Code needs exactly one (not zero, two, etc.) mask applied. +static void applyMask(const uint8_t functionModules[], uint8_t qrcode[], enum qrcodegen_Mask mask) { + assert(0 <= (int)mask && (int)mask <= 7); // Disallows qrcodegen_Mask_AUTO + int qrsize = qrcodegen_getSize(qrcode); + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(functionModules, x, y)) + continue; + bool invert; + switch ((int)mask) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: assert(false); return; + } + bool val = getModuleBounded(qrcode, x, y); + setModuleBounded(qrcode, x, y, val ^ invert); + } + } +} + + +// Calculates and returns the penalty score based on state of the given QR Code's current modules. +// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. +static long getPenaltyScore(const uint8_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + long result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (int y = 0; y < qrsize; y++) { + bool runColor = false; + int runX = 0; + int runHistory[7] = {0}; + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } else { + finderPenaltyAddHistory(runX, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runX = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (int x = 0; x < qrsize; x++) { + bool runColor = false; + int runY = 0; + int runHistory[7] = {0}; + for (int y = 0; y < qrsize; y++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } else { + finderPenaltyAddHistory(runY, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runY = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < qrsize - 1; y++) { + for (int x = 0; x < qrsize - 1; x++) { + bool color = getModuleBounded(qrcode, x, y); + if ( color == getModuleBounded(qrcode, x + 1, y) && + color == getModuleBounded(qrcode, x, y + 1) && + color == getModuleBounded(qrcode, x + 1, y + 1)) + result += PENALTY_N2; + } + } + + // Balance of dark and light modules + int dark = 0; + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y)) + dark++; + } + } + int total = qrsize * qrsize; // Note that size is odd, so dark/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + int k = (int)((labs(dark * 20L - total * 10L) + total - 1) / total) - 1; + assert(0 <= k && k <= 9); + result += k * PENALTY_N4; + assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; +} + + +// Can only be called immediately after a light run is added, and +// returns either 0, 1, or 2. A helper function for getPenaltyScore(). +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize) { + int n = runHistory[1]; + assert(n <= qrsize * 3); (void)qrsize; + bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; + // The maximum QR Code size is 177, hence the dark run length n <= 177. + // Arithmetic is promoted to int, so n*4 will not overflow. + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); +} + + +// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize) { + if (currentRunColor) { // Terminate dark run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + currentRunLength = 0; + } + currentRunLength += qrsize; // Add light border to final run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + return finderPenaltyCountPatterns(runHistory, qrsize); +} + + +// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize) { + if (runHistory[0] == 0) + currentRunLength += qrsize; // Add light border to initial run + memmove(&runHistory[1], &runHistory[0], 6 * sizeof(runHistory[0])); + runHistory[0] = currentRunLength; +} + + + +/*---- Basic QR Code information ----*/ + +// Public function - see documentation comment in header file. +int qrcodegen_getSize(const uint8_t qrcode[]) { + assert(qrcode != NULL); + int result = qrcode[0]; + assert((qrcodegen_VERSION_MIN * 4 + 17) <= result + && result <= (qrcodegen_VERSION_MAX * 4 + 17)); + return result; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_getModule(const uint8_t qrcode[], int x, int y) { + assert(qrcode != NULL); + int qrsize = qrcode[0]; + return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModuleBounded(qrcode, x, y); +} + + +// Returns the color of the module at the given coordinates, which must be in bounds. +testable bool getModuleBounded(const uint8_t qrcode[], int x, int y) { + int qrsize = qrcode[0]; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int index = y * qrsize + x; + return getBit(qrcode[(index >> 3) + 1], index & 7); +} + + +// Sets the color of the module at the given coordinates, which must be in bounds. +testable void setModuleBounded(uint8_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0]; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int index = y * qrsize + x; + int bitIndex = index & 7; + int byteIndex = (index >> 3) + 1; + if (isDark) + qrcode[byteIndex] |= 1 << bitIndex; + else + qrcode[byteIndex] &= (1 << bitIndex) ^ 0xFF; +} + + +// Sets the color of the module at the given coordinates, doing nothing if out of bounds. +testable void setModuleUnbounded(uint8_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0]; + if (0 <= x && x < qrsize && 0 <= y && y < qrsize) + setModuleBounded(qrcode, x, y, isDark); +} + + +// Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14. +static bool getBit(int x, int i) { + return ((x >> i) & 1) != 0; +} + + + +/*---- Segment handling ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_isNumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (*text < '0' || *text > '9') + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_isAlphanumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (strchr(ALPHANUMERIC_CHARSET, *text) == NULL) + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars) { + int temp = calcSegmentBitLength(mode, numChars); + if (temp == -1) + return SIZE_MAX; + assert(0 <= temp && temp <= INT16_MAX); + return ((size_t)temp + 7) / 8; +} + + +// Returns the number of data bits needed to represent a segment +// containing the given number of characters using the given mode. Notes: +// - Returns -1 on failure, i.e. numChars > INT16_MAX or +// the number of needed bits exceeds INT16_MAX (i.e. 32767). +// - Otherwise, all valid results are in the range [0, INT16_MAX]. +// - 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 bits is returned. +// An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) { + // All calculations are designed to avoid overflow on all platforms + if (numChars > (unsigned int)INT16_MAX) + return -1; + long result = (long)numChars; + if (mode == qrcodegen_Mode_NUMERIC) + result = (result * 10 + 2) / 3; // ceil(10/3 * n) + else if (mode == qrcodegen_Mode_ALPHANUMERIC) + result = (result * 11 + 1) / 2; // ceil(11/2 * n) + else if (mode == qrcodegen_Mode_BYTE) + result *= 8; + else if (mode == qrcodegen_Mode_KANJI) + result *= 13; + else if (mode == qrcodegen_Mode_ECI && numChars == 0) + result = 3 * 8; + else { // Invalid argument + assert(false); + return -1; + } + assert(result >= 0); + if (result > INT16_MAX) + return -1; + return (int)result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]) { + assert(data != NULL || len == 0); + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_BYTE; + result.bitLength = calcSegmentBitLength(result.mode, len); + assert(result.bitLength != -1); + result.numChars = (int)len; + if (len > 0) + memcpy(buf, data, len * sizeof(buf[0])); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]) { + assert(digits != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(digits); + result.mode = qrcodegen_Mode_NUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != -1); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *digits != '\0'; digits++) { + char c = *digits; + assert('0' <= c && c <= '9'); + accumData = accumData * 10 + (unsigned int)(c - '0'); + accumCount++; + if (accumCount == 3) { + appendBitsToBuffer(accumData, 10, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 or 2 digits remaining + appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]) { + assert(text != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(text); + result.mode = qrcodegen_Mode_ALPHANUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != -1); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *text != '\0'; text++) { + const char *temp = strchr(ALPHANUMERIC_CHARSET, *text); + assert(temp != NULL); + accumData = accumData * 45 + (unsigned int)(temp - ALPHANUMERIC_CHARSET); + accumCount++; + if (accumCount == 2) { + appendBitsToBuffer(accumData, 11, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 character remaining + appendBitsToBuffer(accumData, 6, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]) { + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_ECI; + result.numChars = 0; + result.bitLength = 0; + if (assignVal < 0) + assert(false); + else if (assignVal < (1 << 7)) { + memset(buf, 0, 1 * sizeof(buf[0])); + appendBitsToBuffer((unsigned int)assignVal, 8, buf, &result.bitLength); + } else if (assignVal < (1 << 14)) { + memset(buf, 0, 2 * sizeof(buf[0])); + appendBitsToBuffer(2, 2, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)assignVal, 14, buf, &result.bitLength); + } else if (assignVal < 1000000L) { + memset(buf, 0, 3 * sizeof(buf[0])); + appendBitsToBuffer(6, 3, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal >> 10), 11, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal & 0x3FF), 10, buf, &result.bitLength); + } else + assert(false); + result.data = buf; + return result; +} + + +// Calculates the number of bits needed to encode the given segments at the given version. +// Returns a non-negative number if successful. Otherwise returns -1 if a segment has too +// many characters to fit its length field, or the total bits exceeds INT16_MAX. +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version) { + assert(segs != NULL || len == 0); + long result = 0; + for (size_t i = 0; i < len; i++) { + int numChars = segs[i].numChars; + int bitLength = segs[i].bitLength; + assert(0 <= numChars && numChars <= INT16_MAX); + assert(0 <= bitLength && bitLength <= INT16_MAX); + int ccbits = numCharCountBits(segs[i].mode, version); + assert(0 <= ccbits && ccbits <= 16); + if (numChars >= (1L << ccbits)) + return -1; // The segment's length doesn't fit the field's bit width + result += 4L + ccbits + bitLength; + if (result > INT16_MAX) + return -1; // The sum might overflow an int type + } + assert(0 <= result && result <= INT16_MAX); + return (int)result; +} + + +// Returns the bit width of the character count field for a segment in the given mode +// in a QR Code at the given version number. The result is in the range [0, 16]. +static int numCharCountBits(enum qrcodegen_Mode mode, int version) { + assert(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int i = (version + 7) / 17; + switch (mode) { + case qrcodegen_Mode_NUMERIC : { static const int temp[] = {10, 12, 14}; return temp[i]; } + case qrcodegen_Mode_ALPHANUMERIC: { static const int temp[] = { 9, 11, 13}; return temp[i]; } + case qrcodegen_Mode_BYTE : { static const int temp[] = { 8, 16, 16}; return temp[i]; } + case qrcodegen_Mode_KANJI : { static const int temp[] = { 8, 10, 12}; return temp[i]; } + case qrcodegen_Mode_ECI : return 0; + default: assert(false); return -1; // Dummy value + } +} diff --git a/firmware/main/vendor/qrcodegen.h b/firmware/main/vendor/qrcodegen.h new file mode 100644 index 0000000..6bbc157 --- /dev/null +++ b/firmware/main/vendor/qrcodegen.h @@ -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 +#include +#include + + +#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 diff --git a/firmware/main/web/dashboard.css b/firmware/main/web/dashboard.css new file mode 100644 index 0000000..18bfb31 --- /dev/null +++ b/firmware/main/web/dashboard.css @@ -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; } +} diff --git a/firmware/main/web/dashboard.js b/firmware/main/web/dashboard.js new file mode 100644 index 0000000..5d44603 --- /dev/null +++ b/firmware/main/web/dashboard.js @@ -0,0 +1,1015 @@ +/* Local dashboard: explicit device settings writes; CSV names stay in this tab. */ +import { hex, senderIdentity } from './identity.js'; +import { registryInfo } from './manufacturers.js'; + +const CAPACITY = 256; +const CSV_BYTES = 256 * 1024; +const CSV_ROWS = 4096; +const CSV_LABEL_LENGTH = 200; +const $ = id => document.getElementById(id); +const state = { + boot: null, cursor: 0, oldest: 0, evicted: 0, rows: [], status: null, + nowUs: 0, receivedAt: 0, lastSuccess: null, connected: false, inFlight: false, + timer: null, error: '', notice: '', paused: false, frozenRows: [], frozenBoot: null, + lastPollStart: -Infinity, + frozenAt: 0, newWhilePaused: 0, labels: new Map(), importGeneration: 0, +}; +const expanded = new Set(); +// Keep detail spans aligned with the radio column hidden by the phone CSS. +const compactTable = window.matchMedia('(max-width: 560px)'); +const outcomes = { + ok: ['good', 'Weitergesendet', 'Das Funkmodul meldet: Senden beendet (TX_DONE). Ob die Nachricht am Ziel angekommen ist, ist nicht bekannt.'], + ok_polled: ['good', 'Weitergesendet', 'Das Ende des Sendens (TX_DONE) wurde durch Abfragen des Funkmoduls erkannt, nicht über dessen Unterbrechungssignal. Ob die Nachricht am Ziel angekommen ist, ist nicht bekannt.'], + crc_failed: ['danger', 'Nicht lesbar · Prüfsumme', 'Die Fehlerprüfung (CRC) ist fehlgeschlagen. Der Absender ist nicht verlässlich lesbar; ein eigener Zählername wird deshalb nicht zugeordnet.'], + bad_length: ['danger', 'Nicht lesbar · Länge', 'Die empfangene Funknachricht hat eine ungültige Länge und wurde nicht weitergesendet.'], + undecodable: ['danger', 'Nicht lesbar · Kodierung', 'Die empfangene Funknachricht konnte nicht in lesbare Daten umgewandelt werden und wurde nicht weitergesendet.'], + t1_too_long: ['danger', 'Nicht lesbar · T1-Länge', 'Die T1-Funknachricht ist länger als vom Empfänger unterstützt und wurde nicht weitergesendet.'], + rx_read_failed: ['danger', 'Nicht lesbar · Funkzugriff', 'Die empfangenen Daten konnten nicht aus dem Funkmodul gelesen werden. Es liegt keine verlässliche Absenderkennung vor.'], + repeat_disabled: ['warning', 'Ausgelassen · ausgeschaltet', 'Die Nachricht wurde lesbar empfangen, aber das Weiterleiten war ausgeschaltet.'], + whitelist: ['warning', 'Ausgelassen · Absenderregel', 'Die Nachricht wurde lesbar empfangen. Der Absender ist laut eingestellter Freigabeliste nicht zum Weiterleiten zugelassen.'], + duplicate: ['warning', 'Ausgelassen · Wiederholung', 'Die Nachricht wurde lesbar empfangen, aber als bereits bekannte Wiederholung nicht noch einmal weitergeleitet.'], + duty_cycle: ['warning', 'Ausgelassen · Sendezeit', 'Die Nachricht wurde absichtlich nicht weitergeleitet, um das eingestellte Sendezeitbudget einzuhalten.'], + hop_policy: ['warning', 'Ausgelassen · Weiterleitungsregel', 'Die Nachricht wurde lesbar empfangen, aber wegen der Regeln zu bereits weitergeleiteten Nachrichten nicht erneut gesendet.'], + encode_failed: ['danger', 'Sendefehler · Vorbereitung', 'Die Daten konnten nicht zum Senden vorbereitet werden. Es wurde kein abgeschlossenes Senden aufgezeichnet.'], + start_failed: ['danger', 'Sendefehler · Start', 'Der Sendestart im Funkmodul ist fehlgeschlagen.'], + radio_timeout: ['danger', 'Sendefehler · Zeitlimit', 'Das Funkmodul meldete eine Zeitüberschreitung beim Senden. Ein abgeschlossenes Senden wurde nicht bestätigt.'], + irq_timeout: ['danger', 'Sendefehler · Bestätigung fehlt', 'Die Software erhielt innerhalb der Frist keine Bestätigung für das Sendeende (TX_DONE). Das beweist nicht, dass gar kein Funksignal ausgesendet wurde.'], +}; +const helpTopics = { + flow: ['Was macht das Gerät?', 'Es empfängt wM-Bus-Funknachrichten, wie sie Verbrauchszähler senden. Lesbare Nachrichten werden je nach eingestellten Regeln weitergeleitet. Unter „Einstellungen“ kannst du diese Regeln ausdrücklich ändern; die normale Anzeige verändert sie nicht.\n„Weitergesendet“ heißt: Das Funkmodul hat das Senden beendet. Eine Empfangsbestätigung vom Ziel gibt es hier nicht. Keine angezeigten Signale bedeutet nicht, dass keine Zähler vorhanden sind: Manche senden selten oder liegen außerhalb der Reichweite.'], + readable: ['Lesbar oder nicht lesbar?', 'Die Prüfsumme (CRC) hilft, beschädigte Funknachrichten zu erkennen. Nur erfolgreich geprüfte empfangene Nachrichten bekommen eine Absenderzuordnung und gegebenenfalls deinen eigenen Zählernamen.\n„Lesbar“ bezieht sich auf die Funknachricht, nicht auf den Verbrauchswert. Verschlüsselte Nutzdaten bleiben verschlüsselt. Bei einem Fehler wird nicht aus beschädigten Daten auf einen Zähler geschlossen.'], + signal: ['Wie stark ist das Signal?', 'dBm ist eine Einheit für die empfangene Funkleistung (RSSI). Weniger negativ ist stärker: −60 dBm ist stärker als −90 dBm. Es gibt hier keinen allgemeingültigen Grenzwert für guten Empfang; Störungen und Antenne spielen ebenfalls mit.\nDer Wert gehört zum empfangenen Signal. Er sagt nicht, wie gut das weitergesendete Signal beim Ziel ankommt.'], + formats: ['Was bedeuten C1 und T1?', 'C1 und T1 sind unterschiedliche wM-Bus-Übertragungsarten, die Zähler zum Senden verwenden. A und B bezeichnen den Aufbau der Funknachricht. Das sind keine Qualitätsstufen und keine Zählermodelle.\nDie Tabelle zeigt die Art und das Format des aufgezeichneten Signals. Ein Byte sind 8 Bit; die Länge ist keine Verbrauchsmenge. Unbekannt heißt: nicht sicher erkannt.'], + outcomes: ['Ausgelassen ist kein Sendefehler', '„Ausgelassen“ heißt: Die Nachricht wurde wegen einer Regel bewusst nicht weitergeleitet, etwa bei einer Wiederholung oder verbrauchtem Sendezeitbudget.\n„Nicht lesbar“ bedeutet einen Fehler beim Empfang oder Lesen. „Sendefehler“ bedeutet, dass das Senden nicht erfolgreich bestätigt wurde. „Nur Fehler“ zeigt diese beiden Gruppen, aber keine ausgelassenen Nachrichten.'], + policy: ['Warum nicht jedes Signal weiterleiten?', 'Eine Freigabeliste kann die erlaubten Absender begrenzen. Die Wiederholungserkennung verhindert mehrfaches Senden derselben Nachricht. Die Weiterleitungsregel (Hop-Regel) begrenzt erneutes Weiterleiten bereits weitergeleiteter Nachrichten. Zusätzlich begrenzt das Sendezeitbudget die Funkbelegung.\nDie eingestellte Wartezeit liegt vor dem Sendeversuch. Ein ausgelassenes Signal ist eine bewusste Entscheidung, kein Sendefehler.'], + duty: ['Sendezeit ist begrenzt', 'Funkbänder können gesetzliche Sendezeitgrenzen haben. Das Gerät berechnet die Sendedauer aus der Nachrichtenlänge und zählt abgeschlossene Sendungen in einem gleitenden Zeitfenster. Reicht das eingestellte Budget nicht, werden Nachrichten ausgelassen.\nSekunden (s) sind angerechnete Sendedauer, Prozent ist der verbrauchte Anteil des Budgets. Das ist keine Messung der tatsächlichen Funkbelegung. „Begrenzung aus“ ist nur eine Geräteeinstellung, keine Erlaubnis zu unbegrenztem Senden. Die passende Einstellung hängt von den geltenden Regeln ab.'], + identity: ['Absender ist nicht dein eigener Name', 'Die Kennung stammt aus dem unverschlüsselten Absenderkopf der Funknachricht, nicht aus einem entschlüsselten Zählerstand. Hersteller, Versionsbyte und Gerätetyp helfen bei der Zuordnung; ein genaues Modell wird nicht geraten.\nVerschiedene Absender können dieselbe achtstellige Kennung haben. Vergleiche bei einer Warnung die vollständigen Rohwerte unter „Einzelheiten“. Ein eigener Name ist nur deine Notiz, kein Nachweis der Herkunft.'], + labels: ['Eigene Namen sind optional', 'Du kannst Kennungen mit Namen wie „Wasserzähler Küche“ versehen. Das ändert weder das Gerät noch seine Messdaten. Namen gelten nur für geprüfte empfangene Kennungen, nicht für unlesbare Nachrichten oder vom Gerät erzeugte Testsignale.\nTeilen sich mehrere Absender eine Kennung, bekommen sie denselben Namen. Prüfe dann Hersteller, Version und Typ. Alle Namen bleiben nur im Speicher dieses Browser-Tabs und verschwinden beim Neuladen oder Schließen.'], + csv: ['Zählernamen aus einer CSV-Datei', 'Starte mit „Vorlage herunterladen“. Die erste Zeile muss exakt oms_id,label heißen; die Spalten werden durch Kommas getrennt. Jede Kennung braucht 8 Zeichen (0–9 oder A–F), auch die Nullen am Anfang: 00123456 bleibt 00123456.\nÖffne die Spalte oms_id in Tabellenprogrammen als Text, damit die Nullen erhalten bleiben. Kommas und Zeilenumbrüche im Namen brauchen CSV-Anführungszeichen. Erlaubt sind bis zu 256 KiB, 4.096 Zuordnungen und 200 Zeichen je Name.\nEine gültige Datei ersetzt alle bisherigen Namen in diesem Tab; bei einem Fehler bleibt alles unverändert. Es wird nichts hochgeladen oder dauerhaft im Browser gespeichert.'], + history: ['Wie viel Verlauf bleibt erhalten?', 'Das Gerät hält höchstens 256 abgeschlossene Funknachrichten seit seinem Start im Arbeitsspeicher. Die ältesten fallen heraus; die Diagnose-Summen zählen trotzdem weiter. Ein Geräteneustart löscht diesen Geräteverlauf.\nBei einer Verbindungsunterbrechung bleiben bereits geladene Daten hier sichtbar, sind aber möglicherweise veraltet. Beim Wiederverbinden wird der aktuelle Verlauf geladen. Ohne dauerhafte Speicherung ist das kein vollständiges Langzeitprotokoll. Laufende Sendeversuche erscheinen erst mit ihrem Ergebnis.'], + pause: ['Nur die Anzeige anhalten', 'Die Pause friert nur diese Tabelle samt Zeitabständen ein. Der Empfang, das Weiterleiten, die Diagnose und die Abfrage einmal pro Sekunde laufen weiter.\nBeim Fortsetzen erscheint der aktuelle Verlauf, nicht jede zwischenzeitliche Nachricht: Es bleiben höchstens 256 Einträge. Downloads verwenden auch während der Pause den neuesten geladenen Verlauf, nicht die eingefrorene Ansicht.'], + export: ['Was wird heruntergeladen?', '„Verlauf als CSV“ enthält den neuesten geladenen Verlauf mit Rohwerten, nicht nur die gefilterte oder pausierte Ansicht. Die CSV-Spaltennamen und technischen Codes bleiben unverändert; die Zeitstempel sind Mikrosekunden seit Gerätestart.\n„Kennungen und Namen als CSV“ enthält nur zuordenbare empfangene Kennungen aus diesem Verlauf. Importiere oms_id als Text, um führende Nullen zu bewahren. Mögliche Tabellenformeln erhalten zum Schutz ein vorangestelltes Apostroph.'], + diagnostics: ['Wie aktuell ist der Funkstatus?', 'Die Seite fragt das Gerät höchstens einmal pro Sekunde ab. Die Funkkonfiguration wird ungefähr alle 10 Sekunden geprüft; erst nach mehr als 15 Sekunden gilt diese Prüfung als veraltet. Der Aufgabenstatus des Geräts und die Browser-Verbindung gelten nach mehr als 5 Sekunden als veraltet.\nEin kurzer Sendevorgang kann zwischen zwei Abfragen liegen. Der angezeigte Funkzustand ist eine Momentaufnahme, kein lückenloser Nachweis aller Funkaktivität. „Funk-Reparaturversuche“ zählt Versuche, den Empfang nach einer Störung wiederherzustellen, nicht Geräteneustarts. Ob der Empfang wieder läuft, zeigt der aktuelle Funkzustand.'], + activity: ['Was zählt als letzte Aktivität?', '„Lesbar empfangen“ zeigt den Abstand zur letzten erfolgreich geprüften empfangenen Nachricht. „Senden beendet“ umfasst auch Test- und Kennungssignale, die das Gerät selbst erzeugt.\nDas Funkmodul hat das Sendeende bestätigt; ob ein Empfänger am Ziel die Nachricht erhalten hat, ist unbekannt. Die Abstände beziehen sich auf die Laufzeit seit Gerätestart.'], + counters: ['Summen sind keine Zahl der Zähler', 'Ein Zähler kann viele Funknachrichten senden. Diese Summen zählen Vorgänge seit Gerätestart, nicht verschiedene Zähler. Sie laufen weiter, wenn alte Einträge aus dem Verlauf fallen.\n„Lesbar empfangen“ umfasst auch später ausgelassene Nachrichten. „Weitergesendet“ zählt abgeschlossene Weiterleitungen, nicht eigene Testsignale. „Sendefehler“ und „ausgelassen“ sind getrennt. Nach einem Geräteneustart beginnen die Summen neu.'], + source: ['Empfangen oder vom Gerät erzeugt?', '„Empfangen“ ist eine eingegangene Funknachricht. „Geräte-Test“ und „Geräte-Kennungssignal“ werden vom Heltec-Gerät selbst erzeugt; sie belegen nicht den Empfang eines Zählers und erhalten keinen eigenen Zählernamen.\nDie Rohcodes source und reception bleiben unter „Einzelheiten“ erhalten. CRC beschreibt die Fehlerprüfung beim Empfang, nicht eine Empfangsbestätigung vom Ziel.'], + timing: ['Was bedeuten die Zeitangaben?', 'µs sind Mikrosekunden, ms sind Millisekunden: 1.000 µs = 1 ms. Rohzeitstempel zählen ab Gerätestart, nicht ab Mitternacht.\nDer Sendebeginn ist der Start des Softwarevorgangs einschließlich Treibervorbereitung, nicht der gemessene Beginn des Funksignals. Das Sendeergebnis wird beim Beobachten des Erfolgs oder Fehlers erfasst. Die Dauer dazwischen ist daher nicht die reine Sendezeit.\nEin Ergebnis-Zeitstempel bestätigt bei einer Fehlerzeile kein erfolgreiches Senden. Auch „Weitergesendet“ bestätigt nur das Sendeende am Funkmodul, nicht den Empfang am Ziel.'], + settings: ['Gerätewert, Entwurf und Speicherung', '„Vom Gerät angenommen“ zeigt den zuletzt geladenen Gerätewert, nicht deinen Entwurf. Ändern oder Umschalten im Eingabefeld sendet nichts. Erst der klar benannte Übernehmen-Knopf sendet genau dieses eine Feld. Andere Entwürfe bleiben erhalten, auch beim Nachladen. Beim Neuladen oder Schließen des Tabs gehen Entwürfe verloren.\nNur Wartezeit und Sendezeitbudget werden dauerhaft auf dem Heltec gespeichert. Alle anderen Einstellungen liegen im RAM und kehren nach einem Geräteneustart zu den Startwerten zurück. CSV-Namen bleiben getrennt davon nur in diesem Browser.\n„Angenommen“ bedeutet nicht sofort „im Funkablauf übernommen“: Die Funkaufgabe kopiert einen zusammengehörigen Stand an einer sicheren Grenze. Auch eine übernommene Revision ist kein Nachweis erfolgreicher Hardwarekonfiguration oder Funkübertragung. Bei Konflikten zuerst die aktuellen Gerätewerte mit den Entwürfen vergleichen, den Abgleich bestätigen und dann selbst erneut übernehmen. Es gibt keine automatische Wiederholung von Änderungen.'], + settings_repeat_enabled: ['Weiterleiten ein- oder ausschalten', 'Eingeschaltet: Geeignete empfangene Nachrichten dürfen nach den übrigen Regeln weitergesendet werden. Ausgeschaltet: Das Gerät empfängt weiter, leitet diese Nachrichten aber nicht weiter. Eigene Kennungssignale werden separat eingestellt.\nDer Entwurf allein schaltet nichts um. Erst „Weiterleiten übernehmen“ sendet die Änderung. Diese Einstellung gilt nur bis zum Geräteneustart (RAM).'], + settings_repeat_delay_ms: ['Wartezeit vor dem Weiterleiten', '20 bis 1.000 ms; 1.000 ms sind eine Sekunde. Das ist die Pause vor einem Sendeversuch, nicht die Dauer des Funksignals und nicht das erlaubte Sendezeitbudget. Eine längere Wartezeit ersetzt keine Sendezeitbegrenzung.\nDiese Einstellung wird dauerhaft im Heltec gespeichert und bleibt nach einem Geräteneustart erhalten.'], + settings_duty_budget_ppm: ['Sendezeitbudget in ppm', 'ppm bedeutet Anteile pro Million. 1.000 ppm = 0,1 % = 3,6 Sekunden Sendezeit je gleitender Stunde. Das Fenster wandert mit der Zeit, es beginnt nicht zur vollen Uhrzeit neu. 100.000 ppm entsprechen 10 % beziehungsweise 360 Sekunden.\nErlaubt sind ganze Zahlen von 0 bis 100.000. 0 schaltet nur die Budgetprüfung aus; es ist weder ein Sendestopp noch eine Erlaubnis zu unbegrenztem Senden. Das Gerät rechnet Sendezeiten an, es misst nicht die gesamte tatsächliche Funkbelegung. Vor dem Abschalten oder einem Wert über 1.000 erscheint eine Warnung. Prüfe die für dein Funkband und deinen Einsatz geltenden Vorschriften.\nNur dieses Budget und die Wartezeit werden dauerhaft gespeichert.'], + settings_tx_power: ['Sendeleistung: Funkchip und Verstärker', '−9 bis +2 dBm ist die eingestellte Ausgangsleistung des SX1262-Funkchips, nicht die endgültige abgestrahlte Leistung. Der nachgeschaltete FEM-Verstärker erhöht die Leistung; Antenne und Leitungen beeinflussen sie ebenfalls. +2 dBm hier bedeutet daher nicht +2 dBm an der Antenne.\nMehr Leistung kann Störungen und Stromverbrauch erhöhen. Zulässige Strahlungsleistung und Sendezeit sind getrennte Grenzen. Diese Einstellung bleibt nur im RAM.'], + settings_whitelist: ['Freigabeliste für Zählerkennungen', 'Leer bedeutet: Alle Absenderkennungen sind zugelassen, sofern die übrigen Weiterleitungsregeln passen. Sonst werden nur die aufgeführten Kennungen weitergeleitet. Höchstens acht unterschiedliche Kennungen, eine pro Zeile oder durch Kommas getrennt.\nJede Kennung muss vollständig acht Hex-Zeichen haben (0–9 und A–F), einschließlich führender Nullen: 00123456 ist richtig, 123456 nicht. Keine Namen, kein 0x-Präfix und keine verkürzten Kennungen. Groß- und Kleinbuchstaben bedeuten dasselbe; doppelte Kennungen sind ungültig.\nDas sind Kennungen aus dem Funkkopf, nicht deine lokalen CSV-Namen. Mehrere echte Zähler können dieselbe Kennung verwenden; die Liste ist kein Echtheitsnachweis. Sie gilt nur bis zum Geräteneustart (RAM).'], + settings_beacon_period_ms: ['Eigene Kennungssignale: Intervall', '0 schaltet regelmäßige Kennungssignale aus. Sonst sind 250 bis 600.000 ms erlaubt: von einer Viertelsekunde bis zehn Minuten. Das Heltec-Gerät erzeugt dabei selbst Funknachrichten, es hat dafür keinen Zähler empfangen.\nKennungssignale verursachen zusätzlichen Funkverkehr und belegen Sendezeit. Ein kürzeres Intervall bedeutet häufigere Sendeversuche; das tatsächliche Senden hängt auch von den übrigen Grenzen ab. Diese Einstellung bleibt nur im RAM.'], + settings_test_lfield: ['L-Feld selbst erzeugter Testnachrichten', 'Das L-Feld ist ein Längenwert im Kopf einer Funknachricht. Hier sind ganze Zahlen von 19 bis 200 erlaubt. Diese Einstellung betrifft die vom Gerät erzeugten Testnachrichten, nicht die Länge empfangener Zählernachrichten und nicht die Zählerauswahl.\n„Test-L-Feld übernehmen“ ändert nur den Wert und startet keinen einmaligen Testversand. Größere eigene Nachrichten können mehr Sendezeit benötigen. Bei eigenen T1-Testsendungen begrenzt die Firmware den wirksamen Wert auf 140. Diese Einstellung bleibt nur im RAM.'], + settings_verbose: ['Ausführliches serielles Protokoll', 'Schaltet zusätzliche Diagnoseausgaben auf der seriellen Verbindung des Heltec-Geräts ein oder aus. Das ist für Fehlersuche am angeschlossenen Rechner gedacht, nicht ein ausführlicherer Verlauf in dieser Webseite. Es werden dadurch keine Daten in eine Cloud hochgeladen.\nZusätzliche Ausgaben können das Zeitverhalten beeinflussen. Diese Einstellung bleibt nur im RAM.'], + settings_fem_rx_csd: ['Experiment: FEM-CSD beim Empfang', 'Der FEM ist der externe Funkverstärker. CSD ist eine seiner Steuerleitungen; diese Einstellung verändert deren Zustand beim Empfang. Das ist kein allgemeiner Schalter für besseren Empfang.\nEin ungeeigneter Zustand kann den Empfang verschlechtern oder verhindern. Nur mit Kenntnis der Hardware experimentieren und bei Problemen den vorherigen Gerätewert wiederherstellen. Diese Einstellung bleibt nur im RAM.'], + settings_preamble_bits: ['Experiment: Präambelerkennung', 'Eine Präambel ist das Bitmuster vor einer Funknachricht, das dem Empfänger beim Erkennen hilft. 0 schaltet diesen Detektor aus; 8, 16, 24 oder 32 Bit bestimmen die Erkennungslänge. Das ändert nicht die vom Zähler gesendete Präambel.\nMehr Bit sind nicht automatisch besser: Eine unpassende Erkennung kann Nachrichten übersehen und den Empfang verschlechtern. Bei Problemen den vorherigen Gerätewert wiederherstellen. Diese Einstellung bleibt nur im RAM.'], + settings_wifi: ['Nur das WLAN des Heltec ausschalten', 'Dieser Knopf sendet nach einer Bestätigung den Ausschaltauftrag an das Heltec-Gerät. Er verändert nicht die WLAN-Einstellungen deines Telefons oder Rechners. Danach wird die Verbindung zu dieser Seite getrennt; die letzten Daten bleiben sichtbar, sind aber nicht mehr aktuell. Ungesendete Entwürfe werden nicht übertragen.\nDie Funkweiterleitung läuft gemäß ihren Einstellungen weiter. Zum erneuten Einschalten ist eine Bedienung direkt am Gerät nötig; über das ausgeschaltete WLAN geht es nicht. Schlägt die Antwortübertragung fehl, kann das WLAN trotzdem schon ausgeschaltet sein. Dann bleibt das Ergebnis ausdrücklich unbekannt, und der Auftrag wird nicht automatisch wiederholt.'], +}; +let activeHelp = null; +let helpSequence = 0; + +function resultInfo(row) { + const result = outcomes[row.outcome] || ['neutral', 'Ergebnis unbekannt', 'Dieses Ergebnis ist noch nicht bekannt. Der unveränderte technische Code steht unter „Einzelheiten“.']; + if (row.source !== 'rx' && (row.outcome === 'ok' || row.outcome === 'ok_polled')) return [result[0], 'Gesendet', result[2]]; + return result; +} +function sourceName(source) { + return ({ rx: 'Empfangen', test: 'Geräte-Test', beacon: 'Geräte-Kennungssignal' })[source] || 'Quelle unbekannt'; +} +function radioValue(value) { return value === 'unknown' ? 'unbekannt' : value; } +function helpButton(topic, id) { + const button = node('button', '?', 'help-button'); + button.type = 'button'; + button.id = id; + button.dataset.help = topic; + button.setAttribute('aria-label', `Hilfe: ${helpTopics[topic][0]}`); + button.setAttribute('aria-controls', 'help-popover'); + button.setAttribute('aria-expanded', String(activeHelp === id)); + return button; +} +function closeHelp(restoreFocus = false) { + if (!activeHelp) return; + const trigger = $(activeHelp); + activeHelp = null; + trigger?.setAttribute('aria-expanded', 'false'); + $('help-popover').hidden = true; + if (restoreFocus) (trigger || $('filter')).focus({ preventScroll: true }); +} +document.addEventListener('click', event => { + const trigger = event.target.closest('button[data-help]'); + if (!trigger) return; + if (!trigger.id) trigger.id = `help-trigger-${++helpSequence}`; + if (activeHelp === trigger.id) { closeHelp(); return; } + closeHelp(); + activeHelp = trigger.id; + trigger.setAttribute('aria-expanded', 'true'); + const [title, text] = helpTopics[trigger.dataset.help]; + setText('help-title', title); + setText('help-text', text); + $('help-popover').hidden = false; + $('help-popover').scrollTop = 0; + $('help-close').focus({ preventScroll: true }); +}); +document.addEventListener('pointerdown', event => { + if (activeHelp && !event.target.closest('#help-popover, button[data-help]')) closeHelp(); +}); +document.addEventListener('keydown', event => { + if (event.key === 'Escape' && activeHelp) { + event.preventDefault(); + closeHelp(true); + } +}); +$('help-close').addEventListener('click', () => closeHelp(true)); +function node(tag, text, className) { + const element = document.createElement(tag); + if (text !== undefined) element.textContent = String(text); + if (className) element.className = className; + return element; +} +function setText(id, value) { + const element = $(id); + const text = String(value); + if (element.textContent !== text) element.textContent = text; +} +function count(value) { return Number(value || 0).toLocaleString('de-DE'); } +function decimal(value, digits) { + return Number(value).toLocaleString('de-DE', { minimumFractionDigits: digits, maximumFractionDigits: digits }); +} +function uptime(us) { + const seconds = Math.max(0, Math.floor(us / 1e6)); + const days = Math.floor(seconds / 86400); + const hours = Math.floor(seconds / 3600) % 24; + const minutes = Math.floor(seconds / 60) % 60; + return `${days ? `${count(days)} T ` : ''}${hours} Std ${minutes} Min ${seconds % 60} s`; +} +function age(timestamp, now = deviceNow()) { + if (!timestamp) return 'Noch nicht'; + const seconds = Math.max(0, (now - timestamp) / 1e6); + if (seconds < 1) return 'vor <1 s'; + if (seconds < 60) return `vor ${Math.floor(seconds)} s`; + if (seconds < 3600) return `vor ${Math.floor(seconds / 60)} Min ${Math.floor(seconds % 60)} s`; + if (seconds < 86400) return `vor ${Math.floor(seconds / 3600)} Std ${Math.floor(seconds / 60) % 60} Min`; + return `vor ${count(Math.floor(seconds / 86400))} T ${Math.floor(seconds / 3600) % 24} Std`; +} +function deviceNow() { + return state.nowUs + (state.receivedAt ? (performance.now() - state.receivedAt) * 1000 : 0); +} +function senderLabel(identity) { + return identity.labelEligible ? state.labels.get(identity.id) || '' : ''; +} +function visibleRows() { return state.paused ? state.frozenRows : state.rows; } +function collisions(rows) { + const identities = new Map(); + for (const row of rows) { + const sender = senderIdentity(row); + if (!sender.labelEligible) continue; + if (!identities.has(sender.id)) identities.set(sender.id, new Set()); + identities.get(sender.id).add(sender.key); + } + return new Set([...identities].filter(([, keys]) => keys.size > 1).map(([id]) => id)); +} + +function renderHealth() { + const elapsed = state.lastSuccess === null ? null : (performance.now() - state.lastSuccess) / 1000; + const stale = elapsed !== null && elapsed > 5; + const connection = $('connection'); + connection.textContent = settingsState.wifiDisabled ? 'Heltec-WLAN wird ausgeschaltet' : !state.connected ? (state.lastSuccess === null && !state.error ? 'Verbindung wird aufgebaut' : 'Nicht verbunden') : stale ? 'Daten veraltet' : 'Verbunden'; + connection.className = `badge ${!state.connected || stale || settingsState.wifiDisabled ? 'warning' : 'good'}`; + setText('connection-age', elapsed === null ? 'Warte auf das Gerät' : `Letzte Abfrage vor ${count(Math.floor(elapsed))} s`); + const notice = $('connection-notice'); + notice.className = `notice ${!state.connected || stale || settingsState.wifiDisabled ? 'warning' : ''}`; + notice.hidden = state.connected && !stale && !state.notice && !settingsState.wifiDisabled; + if (settingsState.wifiDisabled) { + notice.textContent = 'Ausschalten des Heltec-WLANs bestätigt. Die Verbindung wird getrennt; automatische Abfragen sind gestoppt. Letzte Daten bleiben sichtbar, sind aber nicht mehr aktuell. Zum Wiedereinschalten direkt am Gerät bedienen.'; + } else if (!state.connected) { + notice.textContent = `${state.error || 'Verbindung wird aufgebaut.'} Neuer Versuch automatisch. Bereits geladene Daten bleiben sichtbar, können aber veraltet sein.`; + } else if (stale) { + notice.textContent = 'Seit mehr als 5 Sekunden keine aktuelle Antwort. Der angezeigte Funkzustand kann veraltet sein.'; + } else { + notice.textContent = state.notice; + } + if (!state.status) return; + const s = state.status; + const now = deviceNow(); + const heartbeatAge = s.heartbeat_us ? Math.max(0, now - s.heartbeat_us) / 1e6 : Infinity; + const sampleAge = s.sampled_at_us ? Math.max(0, now - s.sampled_at_us) / 1e6 : Infinity; + const mode = ({ 2: 'Bereit (RC)', 3: 'Bereit (XOSC)', 4: 'Frequenz wird eingestellt', 5: 'Empfang läuft', 6: 'Sendet gerade' })[s.chip_mode] || 'Zustand unbekannt'; + setText('uptime', `Laufzeit ${uptime(now)}`); + // The radio configuration probe runs every 10 seconds; task snapshots + // arrive at least once per second outside bounded radio operations. + const radioStale = heartbeatAge > 15 || sampleAge > 5; + const current = state.connected && !stale && !radioStale && !settingsState.wifiDisabled; + setText('operation-state', !current ? 'Gerätestatus nicht aktuell' : !s.config_intact ? 'Funkkonfiguration prüfen' : `${mode} · Weiterleiten ${s.repeat_enabled ? 'an' : 'aus'}`); + setText('operation-detail', !current ? 'Die letzten Daten bleiben sichtbar. Funkaktivität derzeit nicht sicher beurteilbar.' : `${count(s.rx_valid)} lesbar empfangen · ${count(s.repeats_completed)} weitergesendet`); + setText('radio-state', !s.config_intact ? 'Konfiguration abweichend' : radioStale ? 'Funkstatus veraltet' : mode); + $('radio-state').className = `metric ${!s.config_intact ? 'danger-text' : radioStale ? 'warning-text' : ''}`; + setText('radio-detail', `Zustand ${hex(s.chip_mode)} · Konfiguration ${s.config_intact ? 'intakt' : 'abweichend'} · erfasst ${age(s.sampled_at_us, now)}`); + setText('heartbeat', `Funkprüfung ${age(s.heartbeat_us, now)} · alle 10 s`); + setText('repeat-state', s.repeat_enabled ? 'Eingeschaltet' : 'Ausgeschaltet'); + setText('repeat-detail', `Eingestellte Wartezeit ${count(s.repeat_delay_ms)} ms`); + setText('recovery-detail', `${count(s.recoveries)} Funk-Reparaturversuche seit Gerätestart`); + const percent = s.duty_budget_us > 0 ? 100 * s.duty_used_us / s.duty_budget_us : 0; + setText('duty-state', s.duty_budget_us > 0 ? `${decimal(percent, 1)} % verbraucht` : 'Begrenzung aus'); + $('duty-state').className = `metric ${percent >= 90 ? 'warning-text' : ''}`; + $('duty-meter').value = Math.min(100, Math.max(0, percent)); + $('duty-meter').hidden = s.duty_budget_us === 0; + setText('duty-detail', `${decimal(s.duty_used_us / 1e6, 3)} s verbraucht${s.duty_budget_us > 0 ? ` / ${decimal(s.duty_budget_us / 1e6, 3)} s im gleitenden Zeitfenster` : ' · kein Budget eingestellt'}`); + setText('last-rx', age(s.last_rx_us, now)); + setText('last-tx', age(s.last_tx_us, now)); + for (const [id, key] of [['count-rx', 'rx_valid'], ['count-rejected', 'rx_rejected'], ['count-repeats', 'repeats_completed'], ['count-skipped', 'skipped'], ['count-failed', 'tx_failed'], ['count-recoveries', 'recoveries']]) setText(id, count(s[key])); + if (!state.paused) { + for (const cell of document.querySelectorAll('[data-event-time]')) cell.textContent = age(Number(cell.dataset.eventTime), now); + } +} + +function addDetail(list, title, value, topic, eventId) { + const group = node('div'); + const term = node('dt', title, topic ? 'heading-with-help' : ''); + if (topic) term.append(helpButton(topic, `event-help-${eventId}-${list.childElementCount}`)); + group.append(term, node('dd', value)); + list.append(group); +} +function eventRows(row, ambiguous) { + const identity = senderIdentity(row); + const label = senderLabel(identity); + const result = resultInfo(row); + const summary = node('tr'); + const time = node('td'); + const ageNode = node('span', age(row.timestamp_us, state.paused ? state.frozenAt : deviceNow())); + ageNode.dataset.eventTime = row.timestamp_us; + time.append(ageNode, node('span', `#${row.id}`, 'sub mono')); + const sender = node('td'); + if (label) sender.append(node('span', label, 'sender-label')); + sender.append(node('span', identity.trusted ? identity.id || 'Kennung fehlt' : row.source === 'rx' ? 'Absender nicht lesbar' : sourceName(row.source), 'sender-id mono')); + if (identity.trusted) { + sender.append(node('span', `${identity.manufacturer.code || identity.manufacturer.raw} · ${identity.manufacturer.name}`, 'sub')); + sender.append(node('span', `${identity.medium.name}${identity.medium.scoped ? ' · TCH-spezifisch' : ''}`, 'sub')); + } else sender.append(node('span', 'Keine verlässliche Zählerzuordnung', 'sub')); + if (identity.trusted && identity.warnings.length) sender.append(node('span', 'Zuordnung prüfen · Einzelheiten', 'sub row-flag')); + if (ambiguous) sender.append(node('span', 'Kennung mehrfach vergeben', 'sub row-flag')); + const radio = node('td', `${radioValue(row.mode)} / ${radioValue(row.format)}`, 'radio-col'); + radio.append(node('span', sourceName(row.source), 'sub')); + radio.append(node('span', `${row.source === 'rx' ? `${count(row.rssi_dbm)} dBm · ` : ''}${count(row.length)} Byte`, 'sub')); + sender.append(node('span', `${sourceName(row.source)} · ${radioValue(row.mode)} / ${radioValue(row.format)}${row.source === 'rx' ? ` · ${count(row.rssi_dbm)} dBm` : ''}`, 'sub mobile-radio')); + const outcome = node('td'); + outcome.append(node('span', result[1], `badge ${result[0]}`)); + const toggle = node('button', expanded.has(row.id) ? 'Weniger' : 'Einzelheiten', 'detail-toggle'); + toggle.type = 'button'; + toggle.dataset.detailId = row.id; + toggle.setAttribute('aria-label', `Einzelheiten zur Funknachricht ${row.id}`); + toggle.setAttribute('aria-expanded', String(expanded.has(row.id))); + toggle.setAttribute('aria-controls', `details-${row.id}`); + outcome.append(toggle); + summary.append(time, sender, radio, outcome); + const detail = node('tr', undefined, 'detail-row'); + detail.hidden = !expanded.has(row.id); + detail.id = `details-${row.id}`; + const cell = node('td'); + cell.colSpan = compactTable.matches ? 3 : 4; + const list = node('dl', undefined, 'detail-grid'); + addDetail(list, 'Gerätestart-Kennung / Nachricht', `${state.paused ? state.frozenBoot : state.boot} / #${row.id}`, 'history', row.id); + addDetail(list, 'Ereigniszeit seit Gerätestart', `${row.timestamp_us} µs`, 'timing', row.id); + addDetail(list, 'Quelle / Empfang (Rohcodes)', `${row.source} / ${row.reception}`, 'source', row.id); + addDetail(list, 'Fehlerprüfung (CRC)', row.source === 'rx' ? row.crc_ok ? 'Bestanden' : 'Nicht bestanden' : 'Keine Empfangsprüfung', 'readable', row.id); + addDetail(list, 'Absenderkennung (unveränderter Text)', identity.rawId || 'Nicht verfügbar', 'identity', row.id); + addDetail(list, 'Eigener Zählername', label || 'Keiner', 'labels', row.id); + addDetail(list, 'Herstellerfeld (Rohwert)', identity.manufacturer.raw); + addDetail(list, 'Herstellerzuordnung', identity.trusted ? `${identity.manufacturer.code || 'Ungültige FLAG-Kennung'} · ${identity.manufacturer.name}` : 'Keine Zuordnung ohne erfolgreich geprüften Empfang'); + addDetail(list, 'Versionsbyte (keine Modellnummer)', hex(row.version)); + addDetail(list, 'Gerätetyp / Messmedium', identity.trusted ? `${identity.medium.raw} · ${identity.medium.name}${identity.medium.scoped ? ' (TCH-spezifische Ausnahme)' : ''}` : `${hex(row.device_type)} · keine Zuordnung`); + addDetail(list, 'Absender vollständig: Kennung / Hersteller / Version / Typ', `${identity.rawId || '—'} / ${hex(row.manufacturer, 4)} / ${hex(row.version)} / ${hex(row.device_type)}`); + addDetail(list, 'Übertragungsart / Format / Länge', `${row.mode} / ${row.format} / ${count(row.length)} Byte`, 'formats', row.id); + addDetail(list, 'Empfangene Signalstärke (RSSI)', row.source === 'rx' ? `${count(row.rssi_dbm)} dBm` : 'Nicht verfügbar: vom Gerät selbst gesendet', 'signal', row.id); + addDetail(list, 'Nachrichten-Prüfwert (Hash, keine Absenderkennung)', row.hash); + addDetail(list, 'Sendevorgang gestartet seit Gerätestart', row.tx_start_us ? `${row.tx_start_us} µs (einschließlich Treibervorbereitung)` : 'Kein Sendestart aufgezeichnet', 'timing', row.id); + addDetail(list, 'Sendeergebnis beobachtet seit Gerätestart', row.tx_done_us ? `${row.tx_done_us} µs` : 'Kein Ergebnis-Zeitstempel'); + addDetail(list, 'Empfang / Ereignis bis Start des Sendevorgangs', row.tx_start_us ? `${decimal((row.tx_start_us - row.timestamp_us) / 1000, 3)} ms` : 'Nicht zutreffend'); + addDetail(list, 'Dauer des Sendevorgangs bis zum Ergebnis', row.tx_start_us && row.tx_done_us ? `${decimal((row.tx_done_us - row.tx_start_us) / 1000, 3)} ms` : 'Nicht verfügbar'); + addDetail(list, 'Abschließendes Ergebnis (Rohcode)', row.outcome, result[0] === 'warning' ? 'policy' : 'outcomes', row.id); + cell.append(list, node('p', result[2], 'small detail-explanation')); + for (const warning of identity.warnings) cell.append(node('p', warning, 'notice warning')); + if (ambiguous) cell.append(node('p', 'Diese Kennung kommt im Verlauf mit verschiedenen Hersteller-, Versions- oder Typwerten vor. Ihr eigener Name gilt für alle diese Absender. Vergleiche die vollständige Absenderkennung, bevor du ein Signal einem Zähler zuordnest.', 'notice warning')); + detail.append(cell); + toggle.addEventListener('click', () => { + if (expanded.has(row.id)) expanded.delete(row.id); else expanded.add(row.id); + detail.hidden = !expanded.has(row.id); + toggle.setAttribute('aria-expanded', String(!detail.hidden)); + toggle.textContent = detail.hidden ? 'Einzelheiten' : 'Weniger'; + }); + return [summary, detail]; +} + +function renderEvents() { + const rows = visibleRows(); + const ambiguity = collisions(rows); + const query = $('filter').value.trim().toLocaleLowerCase('de-DE'); + const failures = $('failures').checked; + const filtered = rows.filter(row => { + if (failures && resultInfo(row)[0] !== 'danger') return false; + if (!query) return true; + const identity = senderIdentity(row); + // Corrupt raw header bytes are not searchable as a trusted sender. + return identity.trusted && `${identity.id} ${senderLabel(identity)} ${identity.manufacturer.code} ${identity.manufacturer.name} ${identity.manufacturer.raw}`.toLocaleLowerCase('de-DE').includes(query); + }); + const focused = document.activeElement?.dataset.detailId; + const focusedHelp = document.activeElement?.dataset.help ? document.activeElement.id : null; + const fragment = document.createDocumentFragment(); + for (const row of filtered) fragment.append(...eventRows(row, ambiguity.has(senderIdentity(row).id))); + $('event-rows').replaceChildren(fragment); + if (focused) document.querySelector(`[data-detail-id="${Number(focused)}"]`)?.focus({ preventScroll: true }); + if (focusedHelp) $(focusedHelp)?.focus({ preventScroll: true }); + setText('row-count', `${count(filtered.length)} angezeigt / ${count(rows.length)} im Verlauf${state.paused ? ' · pausiert' : ''}`); + setText('display-boot', (state.paused ? state.frozenBoot : state.boot) ? `Gerätestart ${state.paused ? state.frozenBoot : state.boot}` : ''); + $('empty-state').hidden = filtered.length > 0; + setText('empty-state', rows.length ? 'Keine Funknachricht passt zu diesem Filter.' : state.boot ? 'Noch keine abgeschlossene Funknachricht im Verlauf. Zähler können selten senden oder außerhalb der Reichweite liegen.' : 'Warte auf den ersten Verlauf …'); + const warning = $('ambiguity-notice'); + warning.hidden = ambiguity.size === 0; + warning.textContent = `Mehrfach vergebene Kennungen: ${[...ambiguity].slice(0, 8).join(', ')}${ambiguity.size > 8 ? ` und ${count(ambiguity.size - 8)} weitere` : ''}. Hersteller, Version oder Typ unterscheiden sich. Eigene Namen sind deshalb nicht eindeutig. Bitte die Einzelheiten prüfen.`; +} + +function renderRetention() { + const range = state.rows.length ? ` Nummern ${state.oldest}–${state.cursor}.` : ''; + setText('retention', `${count(state.rows.length)} / ${count(CAPACITY)} Einträge im Geräteverlauf.${range} ${count(state.evicted)} ältere Einträge seit Gerätestart entfernt.`); + $('download-events').disabled = state.rows.length === 0; + $('export-labels').disabled = !state.rows.some(row => senderIdentity(row).labelEligible); + $('pause-notice').hidden = !state.paused; + if (state.paused) setText('pause-notice', `Nur die Anzeige ist pausiert. ${count(state.newWhilePaused)} neue Funknachrichten im Hintergrund geladen. Gerätestatus und Abfragen laufen weiter. Fortsetzen zeigt den aktuellen Verlauf (höchstens 256 Einträge). Eingefrorener Gerätestart: ${state.frozenBoot || 'noch nicht verbunden'}.`); +} + +function checkSnapshot(data) { + if (!data || typeof data.boot_id !== 'string' || !data.boot_id || !Number.isSafeInteger(data.cursor) || data.cursor < 0 || !Number.isSafeInteger(data.oldest_id) || data.oldest_id < 0 || !Number.isSafeInteger(data.evicted) || data.evicted < 0 || typeof data.reset !== 'boolean' || !Number.isFinite(data.now_us) || data.now_us < 0 || data.capacity !== CAPACITY || !data.status || !Array.isArray(data.rows) || data.rows.length > CAPACITY) throw new Error('Das Gerät hat ungültige Verlaufsdaten geliefert.'); + const numericStatus = ['sampled_at_us', 'heartbeat_us', 'last_rx_us', 'last_tx_us', 'rx_valid', 'rx_rejected', 'repeats_completed', 'tx_failed', 'skipped', 'duty_used_us', 'duty_budget_us', 'recoveries', 'repeat_delay_ms', 'chip_mode']; + if (numericStatus.some(key => !Number.isFinite(data.status[key]) || data.status[key] < 0) || typeof data.status.config_intact !== 'boolean' || typeof data.status.repeat_enabled !== 'boolean') throw new Error('Das Gerät hat einen ungültigen Funkstatus geliefert.'); + for (const row of data.rows) { + if (!Number.isSafeInteger(row.id) || row.id < data.oldest_id || row.id > data.cursor || !['timestamp_us', 'tx_start_us', 'tx_done_us', 'length', 'rssi_dbm'].every(key => Number.isFinite(row[key])) || !['hash', 'source', 'mode', 'format', 'reception', 'outcome'].every(key => typeof row[key] === 'string') || typeof row.crc_ok !== 'boolean') throw new Error('Das Gerät hat ungültige Daten zu einer Funknachricht geliefert.'); + } +} + +async function poll() { + if (state.inFlight || settingsState.wifiDisabled) return; + clearTimeout(state.timer); + const started = performance.now(); + const remaining = 1000 - (started - state.lastPollStart); + if (remaining > 0) { + state.timer = setTimeout(poll, remaining); + return; + } + state.lastPollStart = started; + state.inFlight = true; + const requestedCursor = state.cursor; + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 4000); + try { + const response = await fetch(`/api/events?after=${requestedCursor}`, { cache: 'no-store', credentials: 'omit', signal: controller.signal }); + if (!response.ok) throw new Error(`Das Gerät meldet HTTP ${response.status}.`); + const data = await response.json(); + checkSnapshot(data); + if (settingsState.wifiDisabled) return; + const reconnected = !state.connected && state.lastSuccess !== null; + state.connected = true; + state.error = ''; + state.lastSuccess = performance.now(); + state.receivedAt = state.lastSuccess; + state.nowUs = data.now_us; + state.status = data.status; + if (state.boot !== null && data.boot_id !== state.boot) { + state.boot = data.boot_id; + state.cursor = 0; + state.oldest = 0; + state.evicted = data.evicted; + state.rows = []; + if (!state.paused) expanded.clear(); + state.notice = 'Das Gerät wurde neu gestartet. Der alte Geräteverlauf wurde verworfen; der neue Verlauf wird vollständig geladen. Deine Namen in diesem Tab bleiben erhalten.'; + if (settingsState.snapshot && settingsState.snapshot.boot_id !== data.boot_id) { + settingsState.ready = false; + settingsState.message = 'Geräteneustart erkannt. Letzte Einstellungen sind veraltet; Entwürfe bleiben erhalten.'; + settingsState.tone = 'warning'; + requireSettingsReview('Geräteneustart erkannt. Neue Gerätewerte laden und mit diesem Entwurf vergleichen.'); + renderSettings(); + if ($('settings-panel').open) loadSettings(true); + } + if (!state.paused) renderEvents(); + // Always explicitly fetch after=0 for the new boot, even if this response had reset=true. + } else { + const previousCursor = state.cursor; + state.boot = data.boot_id; + if (data.reset || requestedCursor === 0) { + state.rows = []; + if (!state.paused) expanded.clear(); + } + if (requestedCursor > 0 && data.oldest_id > requestedCursor + 1) { + state.notice = `Lücke im Verlauf: ${count(data.oldest_id - requestedCursor - 1)} Einträge wurden entfernt, bevor dieser Browser sie laden konnte. Der aktuelle Geräteverlauf wurde neu abgeglichen.`; + } else if (data.reset && requestedCursor > 0) { + state.notice = 'Das Gerät hat den Verlaufsstand zurückgesetzt. Die alten Einträge wurden durch den aktuellen Geräteverlauf ersetzt.'; + } else if (reconnected) { + state.notice = 'Wieder verbunden. Neue Funknachrichten werden wieder geladen. Unter der Tabelle steht, wie viele ältere Einträge entfernt wurden.'; + } + const merged = new Map(state.rows.map(row => [row.id, row])); + for (const row of data.rows) merged.set(row.id, row); + state.rows = [...merged.values()].filter(row => row.id >= data.oldest_id && row.id <= data.cursor).sort((a, b) => b.id - a.id).slice(0, CAPACITY); + state.cursor = data.cursor; + state.oldest = data.oldest_id; + state.evicted = data.evicted; + if (state.paused) state.newWhilePaused += data.rows.filter(row => row.id > previousCursor).length; + else { + const retainedIds = new Set(state.rows.map(row => row.id)); + for (const id of expanded) if (!retainedIds.has(id)) expanded.delete(id); + if (data.rows.length || data.reset || requestedCursor === 0 || previousCursor !== data.cursor) renderEvents(); + } + } + renderRetention(); + } catch (error) { + state.connected = false; + state.error = error.name === 'AbortError' ? 'Das Gerät hat nicht rechtzeitig geantwortet.' + : error instanceof SyntaxError ? 'Die Antwort des Geräts konnte nicht gelesen werden.' + : error instanceof TypeError ? 'Das Gerät ist nicht erreichbar. Prüfe, ob dein Telefon mit seinem WLAN verbunden ist.' + : `Der Geräteverlauf konnte nicht geladen werden. ${error.message}`; + } finally { + clearTimeout(timeout); + state.inFlight = false; + renderHealth(); + // Start at most once per second; a slow request is never overlapped. + if (!settingsState.wifiDisabled) state.timer = setTimeout(poll, Math.max(0, 1000 - (performance.now() - started))); + } +} + +// Accepted device values and local drafts have separate lifetimes. +const settingDefinitions = [ + { key: 'repeat_enabled', title: 'Weiterleiten', kind: 'boolean', hint: 'Empfangene Nachrichten weiterleiten: an oder aus.' }, + { key: 'repeat_delay_ms', title: 'Wartezeit', min: 20, max: 1000, unit: 'ms', persisted: true, hint: '20–1.000 ms vor dem Senden; nicht die Sendezeit.' }, + { key: 'duty_budget_ppm', title: 'Sendezeitbudget', min: 0, max: 100000, unit: 'ppm', persisted: true, hint: '0 = Begrenzung aus. 1.000 ppm = 0,1 % = 3,6 s je gleitender Stunde.' }, + { key: 'tx_power', title: 'Sendeleistung am Funkchip', min: -9, max: 2, unit: 'dBm', hint: '−9 bis +2 dBm am SX1262. Der FEM verstärkt die tatsächliche Sendeleistung.' }, + { key: 'whitelist', title: 'Freigabeliste', kind: 'whitelist', hint: 'Bis zu 8 vollständige achtstellige Hex-Kennungen, eine pro Zeile oder mit Komma. Leer = alle erlaubt.' }, + { key: 'beacon_period_ms', title: 'Kennungssignal-Intervall', min: 250, max: 600000, zero: true, unit: 'ms', expert: true, hint: '0 = aus; sonst 250–600.000 ms. Erzeugt zusätzlichen Funkverkehr.' }, + { key: 'test_lfield', title: 'Test-L-Feld', min: 19, max: 200, expert: true, hint: '19–200; Länge selbst erzeugter Testnachrichten, nicht empfangener Zählernachrichten.' }, + { key: 'verbose', title: 'Ausführliches serielles Protokoll', kind: 'boolean', expert: true, hint: 'Zusätzliche Diagnose auf der seriellen Verbindung, nicht im Web-Verlauf.' }, + { key: 'fem_rx_csd', title: 'FEM-CSD beim Empfang', kind: 'boolean', expert: true, hint: 'Experiment: Kann den Empfang verschlechtern oder verhindern.' }, + { key: 'preamble_bits', title: 'Präambelerkennung', choices: [0, 8, 16, 24, 32], unit: 'Bit', expert: true, hint: '0 = Detektor aus. Experiment: Mehr Bit sind nicht automatisch besser.' }, +]; +const settingsState = { + snapshot: null, ready: false, loading: false, writing: null, wifiDisabled: false, + timer: null, lastGet: -Infinity, pendingReads: 0, message: '', tone: '', +}; +const settingFields = new Map(); + +function validSettingValue(definition, value) { + if (definition.kind === 'boolean') return typeof value === 'boolean'; + if (definition.kind === 'whitelist') return Array.isArray(value) && value.length <= 8 + && value.every(id => typeof id === 'string' && /^[0-9a-f]{8}$/i.test(id)) + && new Set(value.map(id => id.toUpperCase())).size === value.length; + if (!Number.isSafeInteger(value)) return false; + if (definition.choices) return definition.choices.includes(value); + return (definition.zero && value === 0) || (value >= definition.min && value <= definition.max); +} + +function checkSettingsSnapshot(data) { + const uint = value => Number.isInteger(value) && value >= 0 && value <= 0xffffffff; + if (!data || typeof data.boot_id !== 'string' || !data.boot_id + || !uint(data.revision) || data.revision === 0 || !uint(data.applied_revision) + || data.applied_revision > data.revision || typeof data.csrf_token !== 'string' || !data.csrf_token + || !data.settings || settingDefinitions.some(definition => !validSettingValue(definition, data.settings[definition.key]))) { + throw new Error('Unbekannte oder ungültige Einstellungsantwort; kein Erfolg bestätigt.'); + } + data.settings.whitelist = data.settings.whitelist.map(id => id.toUpperCase()); +} + +function settingText(definition, value) { + if (definition.kind === 'boolean') return value ? 'Eingeschaltet' : 'Ausgeschaltet'; + if (definition.kind === 'whitelist') return value.length ? value.join(', ') : 'Leer – alle Kennungen erlaubt'; + if (definition.key === 'duty_budget_ppm') return value === 0 ? '0 ppm – Begrenzung aus' + : `${count(value)} ppm = ${decimal(value / 10000, 4).replace(/0+$/, '').replace(/,$/, '')} % = ${decimal(value * 0.0036, 4).replace(/0+$/, '').replace(/,$/, '')} s je gleitender Stunde`; + if (value === 0 && (definition.zero || definition.choices)) return `0 ${definition.unit} – aus`; + return `${count(value)}${definition.unit ? ` ${definition.unit}` : ''}`; +} + +function setSettingInput(field, value) { + field.input.value = field.definition.kind === 'whitelist' ? value.join('\n') : String(value); +} + +function readSettingDraft(field) { + const definition = field.definition; + const text = field.input.value.trim(); + let value; + if (definition.kind === 'boolean') { + if (text !== 'true' && text !== 'false') throw new Error('Bitte „Eingeschaltet“ oder „Ausgeschaltet“ auswählen.'); + value = text === 'true'; + } else if (definition.kind === 'whitelist') { + value = text ? text.split(/\r?\n|,/).map(id => id.trim().toUpperCase()) : []; + if (!validSettingValue(definition, value)) throw new Error('Höchstens 8 unterschiedliche Kennungen mit genau 8 Hex-Zeichen (0–9, A–F), inklusive führender Nullen. Eine pro Zeile oder mit Komma; keine leeren Zwischeneinträge. Ganz leer erlaubt alle.'); + } else { + if (!/^-?\d+$/.test(text)) throw new Error('Bitte eine ganze Zahl ohne Dezimalstellen, Tausendertrennzeichen oder Exponent eingeben.'); + value = Number(text); + } + if (!validSettingValue(definition, value)) throw new Error(definition.choices + ? 'Erlaubt sind nur 0, 8, 16, 24 oder 32 Bit.' + : `Erlaubt: ${definition.zero ? '0 (aus) oder ' : ''}${count(definition.min)} bis ${count(definition.max)}${definition.unit ? ` ${definition.unit}` : ''}, als ganze Zahl.`); + return value; +} + +function settingMessage(field, message, tone = '') { + field.message.textContent = message; + field.message.className = `small setting-message ${tone ? `${tone}-text` : ''}`; +} + +function requireSettingsReview(message) { + for (const field of settingFields.values()) { + if (!field.dirty) continue; + if (!field.review) settingMessage(field, message, 'warning'); + field.review = true; + field.reviewCheck.checked = false; + } +} + +function acceptSettingsSnapshot(data, submitted = null) { + const previous = settingsState.snapshot; + const changed = previous && (previous.boot_id !== data.boot_id || previous.revision !== data.revision); + if (changed && !submitted) requireSettingsReview(previous.boot_id !== data.boot_id + ? 'Geräteneustart erkannt. Dieser Entwurf blieb erhalten; neuen Gerätewert vergleichen und Abgleich bestätigen.' + : 'Der Gerätestand hat sich geändert. Entwurf mit dem aktuellen Gerätewert vergleichen und Abgleich bestätigen.'); + settingsState.snapshot = data; + settingsState.ready = true; + for (const field of settingFields.values()) { + if (submitted?.key === field.definition.key && submitted.version === field.version) { + field.dirty = false; + field.review = false; + field.reviewCheck.checked = false; + settingMessage(field, `Vom Gerät angenommen.${field.definition.persisted ? ' Dauerhaft gespeichert.' : ' Nur im RAM.'} Der Übernahmestand der Funkaufgabe steht oben.`, 'good'); + } + if (!field.dirty) setSettingInput(field, data.settings[field.definition.key]); + } +} + +function renderSettings() { + const s = settingsState; + const snapshot = s.snapshot; + const busy = s.loading || Boolean(s.writing); + const pending = snapshot && snapshot.applied_revision < snapshot.revision; + $('settings-reload').disabled = busy; + $('settings-wifi-disable').disabled = !s.ready || busy || s.wifiDisabled; + const status = $('settings-status'); + let message = s.message || 'Noch keine Einstellungen geladen. Zum Laden diesen Bereich öffnen.'; + if (pending && !s.wifiDisabled) message += s.ready + ? ` Übernahme durch die Funkaufgabe ausstehend.${s.pendingReads >= 30 ? ' Automatische Abfragen nach 30 Versuchen beendet; bitte später „Gerätewerte neu laden“.' : ' Bei geöffnetem Bereich wird höchstens einmal pro Sekunde nachgefragt.'}` + : ' Der zuletzt geladene Stand wartete auf die Funkaufgabe; der aktuelle Übernahmestand ist unbekannt.'; + status.textContent = message; + status.className = `notice ${s.tone || (pending ? 'warning' : '')}`; + setText('settings-revision', snapshot + ? `Gerätestart ${snapshot.boot_id} · angenommene Revision ${snapshot.revision} · von der Funkaufgabe kopiert: ${snapshot.applied_revision}. Kein Nachweis erfolgreicher Hardwarekonfiguration oder Funkübertragung.` + : 'Angenommene Gerätewerte und Übernahmestand sind noch unbekannt.'); + for (const field of settingFields.values()) { + const definition = field.definition; + field.accepted.textContent = snapshot + ? `${s.ready ? 'Vom Gerät angenommen (letzte Antwort)' : 'Zuletzt vom Gerät angenommen – möglicherweise veraltet'}: ${settingText(definition, snapshot.settings[definition.key])}` + : 'Vom Gerät angenommen: noch unbekannt'; + field.input.disabled = !snapshot || s.wifiDisabled; + field.submit.disabled = !s.ready || busy || !field.dirty || s.wifiDisabled || (field.review && !field.reviewCheck.checked); + field.discard.disabled = !snapshot || Boolean(s.writing) || !field.dirty || s.wifiDisabled; + field.reviewLabel.hidden = !field.review || !field.dirty; + field.reviewCheck.disabled = !s.ready || busy || s.wifiDisabled; + field.draft.textContent = field.dirty ? 'Lokaler Entwurf – noch nicht gesendet.' : 'Kein ungesendeter Entwurf.'; + if (field.dirty && definition.key === 'duty_budget_ppm') { + try { field.draft.textContent += ` ${settingText(definition, readSettingDraft(field))}`; } catch { /* The submit action reports validation errors. */ } + } + } +} + +function createSettingField(definition) { + const id = `setting-${definition.key}`; + const form = node('form', undefined, 'setting-field'); + form.noValidate = true; + const heading = node('div', undefined, 'heading-with-help'); + const title = node('h3', definition.title); + title.id = `${id}-title`; + form.setAttribute('aria-labelledby', title.id); + heading.append(title, helpButton(`settings_${definition.key}`, `${id}-help`)); + const storage = node('p', definition.persisted ? 'Speicherung beim Übernehmen: dauerhaft im Heltec' : 'Speicherung beim Übernehmen: nur RAM · bis zum Geräteneustart', 'small setting-storage'); + const hint = node('p', definition.hint, 'small'); + hint.id = `${id}-hint`; + const accepted = node('p', undefined, 'setting-accepted'); + accepted.id = `${id}-accepted`; + const label = node('label', `Lokaler Entwurf: ${definition.title}${definition.unit ? ` (${definition.unit})` : ''}`); + label.htmlFor = id; + const input = node(definition.kind === 'whitelist' ? 'textarea' : definition.kind === 'boolean' || definition.choices ? 'select' : 'input', undefined, 'setting-input'); + input.id = id; + if (input.tagName === 'SELECT') { + const placeholder = node('option', 'Noch nicht geladen'); + placeholder.value = ''; + placeholder.disabled = true; + input.append(placeholder); + const options = definition.kind === 'boolean' ? [false, true] : definition.choices; + for (const value of options) { + const option = node('option', settingText(definition, value)); + option.value = String(value); + input.append(option); + } + input.value = ''; + } else { + input.autocomplete = 'off'; + input.spellcheck = false; + if (input.tagName === 'INPUT') { + input.type = 'text'; + input.inputMode = definition.min < 0 ? 'text' : 'numeric'; + } else { + input.rows = 3; + input.autocapitalize = 'characters'; + } + } + const draft = node('p', undefined, 'small setting-draft'); + const message = node('p', undefined, 'small setting-message'); + message.id = `${id}-message`; + message.setAttribute('role', 'status'); + input.setAttribute('aria-describedby', `${hint.id} ${accepted.id} ${message.id}`); + const reviewLabel = node('label', undefined, 'checkbox setting-review'); + const reviewCheck = node('input'); + reviewCheck.type = 'checkbox'; + reviewLabel.append(reviewCheck, node('span', 'Aktuellen Gerätewert mit meinem Entwurf verglichen')); + const actions = node('div', undefined, 'button-row'); + const submit = node('button', `${definition.title} übernehmen`); + submit.type = 'submit'; + const discard = node('button', 'Letzten Gerätewert einsetzen'); + discard.type = 'button'; + actions.append(submit, discard); + form.append(heading, storage, hint, accepted, label, input, draft, reviewLabel, actions, message); + const field = { definition, input, accepted, draft, message, reviewLabel, reviewCheck, submit, discard, dirty: false, review: false, version: 0 }; + settingFields.set(definition.key, field); + input.addEventListener('input', () => { + field.dirty = true; + field.version++; + field.reviewCheck.checked = false; + input.removeAttribute('aria-invalid'); + settingMessage(field, ''); + renderSettings(); + }); + reviewCheck.addEventListener('change', renderSettings); + discard.addEventListener('click', () => { + field.dirty = false; + field.review = false; + field.version++; + input.removeAttribute('aria-invalid'); + setSettingInput(field, settingsState.snapshot.settings[definition.key]); + settingMessage(field, 'Lokalen Entwurf durch den zuletzt geladenen Gerätewert ersetzt. Nichts gesendet.'); + renderSettings(); + }); + // Enter in a number field is not consent to send a device change. + form.addEventListener('keydown', event => { + if (event.key === 'Enter' && event.target === input && input.tagName === 'INPUT') event.preventDefault(); + }); + form.addEventListener('submit', event => { event.preventDefault(); submitSetting(field); }); + $(definition.expert ? 'settings-advanced' : 'settings-common').append(form); +} + +async function settingsRequest(path, body) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 4000); + try { + const options = { cache: 'no-store', credentials: 'omit', signal: controller.signal }; + if (body) { + options.method = 'POST'; + options.headers = { 'Content-Type': 'application/json', 'X-CSRF-Token': settingsState.snapshot.csrf_token }; + options.body = JSON.stringify(body); + } + const response = await fetch(path, options); + let data; + try { data = await response.json(); } catch { throw new Error(`Antwort bei HTTP ${response.status} nicht lesbar; Ergebnis unbekannt.`); } + if (response.status !== 200) { + const error = new Error(typeof data?.error === 'string' && data.error ? data.error : `Unbekannte Antwort (HTTP ${response.status}).`); + error.status = response.status; + throw error; + } + return data; + } finally { + clearTimeout(timeout); + } +} + +function settingsError(error) { + if (error.name === 'AbortError') return 'Das Gerät hat nicht rechtzeitig geantwortet.'; + if (error instanceof TypeError) return 'Das Gerät ist nicht erreichbar. Verbindung zum Heltec-WLAN prüfen.'; + if (error.status === 404 || error.status === 405) return 'Diese Geräte-Firmware bietet die Einstellungs-API nicht an.'; + return error.message; +} + +async function loadSettings(resetBudget = false) { + const s = settingsState; + if (s.loading || s.writing) return; + clearTimeout(s.timer); + const wait = 1000 - (performance.now() - s.lastGet); + if (wait > 0) { s.timer = setTimeout(() => loadSettings(resetBudget), wait); return; } + if (resetBudget) s.pendingReads = 0; + s.lastGet = performance.now(); + s.loading = true; + s.message = 'Gerätewerte werden geladen. Lokale Entwürfe bleiben erhalten.'; + s.tone = ''; + renderSettings(); + try { + const data = await settingsRequest('/api/settings'); + checkSettingsSnapshot(data); + acceptSettingsSnapshot(data); + s.pendingReads++; + s.message = 'Gerätewerte geladen. Änderungen werden nur nach deinem ausdrücklichen Übernehmen gesendet.'; + if (s.wifiDisabled) { + s.wifiDisabled = false; + setText('settings-wifi-result', 'Das Heltec-Gerät antwortet wieder. Dies bestätigt die Erreichbarkeit; der WLAN-Zustand kann sich noch ändern.'); + if (!state.inFlight) poll(); + } + } catch (error) { + s.ready = false; + s.message = `${settingsError(error)} Keine aktuellen Einstellungen bestätigt. Letzte Werte und Entwürfe bleiben erhalten. Zum erneuten Versuch „Gerätewerte neu laden“.`; + s.tone = 'danger'; + } finally { + s.loading = false; + renderSettings(); + schedulePendingSettings(); + } +} + +function schedulePendingSettings() { + const s = settingsState; + clearTimeout(s.timer); + if (s.ready && !s.wifiDisabled && s.snapshot.applied_revision < s.snapshot.revision + && s.pendingReads < 30 && $('settings-panel').open && !document.hidden) { + s.timer = setTimeout(() => loadSettings(), Math.max(1000, 1000 - (performance.now() - s.lastGet))); + } +} + +async function submitSetting(field) { + const s = settingsState; + if (!s.ready || s.loading || s.writing || s.wifiDisabled || !field.dirty || (field.review && !field.reviewCheck.checked)) return; + let value; + try { value = readSettingDraft(field); } catch (error) { + field.input.setAttribute('aria-invalid', 'true'); + settingMessage(field, error.message, 'danger'); + field.input.focus(); + return; + } + const key = field.definition.key; + if (key === 'duty_budget_ppm' && (value === 0 || value > 1000) + && !window.confirm(`${value === 0 ? 'Sendezeitbegrenzung wirklich ausschalten? 0 ist kein Sendestopp.' : `Sendezeitbudget wirklich auf ${settingText(field.definition, value)} setzen?`}\n1.000 ppm = 0,1 % = 3,6 s je gleitender Stunde. Höhere Werte oder eine ausgeschaltete Prüfung können geltende Funkvorschriften verletzen. Du bist für die zulässigen Grenzen verantwortlich.\nNur „OK“ sendet diese Änderung.`)) return; + const submitted = { key, value, version: field.version, boot_id: s.snapshot.boot_id, revision: s.snapshot.revision }; + s.writing = key; + clearTimeout(s.timer); + settingMessage(field, 'Wird gesendet. Noch keine Annahme bestätigt.'); + renderSettings(); + let reconcile = false; + try { + const data = await settingsRequest('/api/settings', { boot_id: submitted.boot_id, revision: submitted.revision, key, value }); + checkSettingsSnapshot(data); + if (data.boot_id !== submitted.boot_id || data.revision < submitted.revision + || JSON.stringify(data.settings[key]) !== JSON.stringify(value)) throw new Error('Antwort bestätigt den gesendeten Wert nicht eindeutig; Ergebnis unbekannt.'); + acceptSettingsSnapshot(data, submitted); + if (field.version !== submitted.version) settingMessage(field, 'Gesendeter Wert vom Gerät angenommen. Dein inzwischen geänderter Entwurf bleibt ungesendet.', 'warning'); + s.pendingReads = 0; + s.message = `${field.definition.title}: vom Gerät angenommen.`; + s.tone = ''; + } catch (error) { + const conflict = error.status === 409; + if (error.status === 400) field.input.setAttribute('aria-invalid', 'true'); + settingMessage(field, conflict + ? `Konflikt: ${settingsError(error)} Aktuelle Gerätewerte werden geladen. Entwürfe vergleichen, Abgleich bestätigen und selbst erneut übernehmen.` + : `${settingsError(error)} ${error.status === 400 ? 'Eingabe wurde abgelehnt.' : error.status === 503 ? 'Speicherung/Übernahme nicht bestätigt.' : 'Ob die Änderung angenommen wurde, ist unbekannt.'} Keine automatische Wiederholung.`, 'danger'); + s.message = 'Änderung nicht bestätigt. Meldung am betroffenen Feld beachten.'; + s.tone = 'danger'; + if (error.status !== 400) { + s.ready = false; + requireSettingsReview('Änderung nicht bestätigt. Nach dem Nachladen Gerätewert mit dem erhaltenen Entwurf vergleichen und Abgleich bestätigen; keine automatische Wiederholung.'); + // Keep the actionable server error on the field that was submitted. + settingMessage(field, `${conflict ? 'Konflikt (409): ' : 'Änderung nicht bestätigt: '}${settingsError(error)} Keine automatische Wiederholung. Nach dem Nachladen Gerätewert und Entwurf vergleichen, Abgleich bestätigen und selbst erneut übernehmen.`, 'danger'); + reconcile = true; + } + } finally { + s.writing = null; + renderSettings(); + if (reconcile) loadSettings(true); + else schedulePendingSettings(); + } +} + +async function disableSettingsWifi() { + const s = settingsState; + if (!s.ready || s.loading || s.writing || s.wifiDisabled) return; + const drafts = [...settingFields.values()].some(field => field.dirty); + if (!window.confirm(`WLAN des Heltec-Geräts wirklich ausschalten?\nDiese Verbindung wird getrennt. Die Funkweiterleitung läuft gemäß ihren Einstellungen weiter. Wiedereinschalten ist nicht über diese Seite möglich, sondern nur direkt am Gerät.${drafts ? '\nDu hast ungesendete Entwürfe. Sie werden NICHT übernommen.' : ''}\nDas WLAN deines Telefons oder Rechners wird nicht umgestellt.`)) return; + s.writing = 'wifi'; + clearTimeout(s.timer); + setText('settings-wifi-result', 'Ausschaltauftrag wird gesendet. Noch keine Bestätigung.'); + renderSettings(); + let reconcile = false; + try { + const data = await settingsRequest('/api/wifi/disable', { boot_id: s.snapshot.boot_id }); + if (data?.ok !== true) throw new Error('Unbekannte Antwort; Ausschalten nicht bestätigt.'); + s.wifiDisabled = true; + s.ready = false; + state.connected = false; + clearTimeout(state.timer); + s.message = 'Heltec-WLAN: Ausschaltauftrag bestätigt. Die Verbindung wird getrennt; automatische Abfragen wurden beendet. Letzte Werte können veraltet sein.'; + s.tone = 'warning'; + setText('settings-wifi-result', 'Ausschalten bestätigt. Zum Wiedereinschalten das Gerät direkt bedienen. Danach wieder mit seinem WLAN verbinden und „Gerätewerte neu laden“.'); + renderHealth(); + } catch (error) { + s.ready = false; + s.message = 'WLAN-Ausschalten nicht bestätigt. Keine automatische Wiederholung.'; + s.tone = 'danger'; + setText('settings-wifi-result', `${settingsError(error)} Ob das WLAN bereits ausgeschaltet ist, ist unbekannt. Falls getrennt: zum Wiedereinschalten das Gerät direkt bedienen. Sonst Gerätewerte neu laden und vor einem neuen Auftrag prüfen.`); + requireSettingsReview('Verbindung oder Gerätestand unklar. Nach dem Nachladen Entwürfe mit den aktuellen Gerätewerten vergleichen.'); + reconcile = error.status === 409; + } finally { + s.writing = null; + renderSettings(); + if (reconcile) loadSettings(true); + } +} + +for (const definition of settingDefinitions) createSettingField(definition); +$('settings-reload').addEventListener('click', () => loadSettings(true)); +$('settings-wifi-disable').addEventListener('click', disableSettingsWifi); +$('settings-panel').addEventListener('toggle', () => { + if ($('settings-panel').open && !settingsState.wifiDisabled) loadSettings(true); + else clearTimeout(settingsState.timer); +}); +document.addEventListener('visibilitychange', () => { + if (document.hidden) clearTimeout(settingsState.timer); + else schedulePendingSettings(); +}); +renderSettings(); + +// RFC4180-style parser. Record start lines are preserved for actionable errors. +export function parseCSV(text) { + if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1); + const records = []; + let fields = [], field = '', quoted = false, afterQuote = false, line = 1, startLine = 1; + function fail(message) { throw new Error(`Zeile ${count(startLine)}: ${message}`); } + function pushField() { + fields.push(field); + field = ''; + afterQuote = false; + if (fields.length > 2) fail('Es werden genau zwei Spalten erwartet (oms_id,label).'); + } + function pushRecord() { + pushField(); + if (!(fields.length === 1 && fields[0] === '')) records.push({ line: startLine, fields }); + fields = []; + if (records.length > CSV_ROWS + 1) fail(`Mehr als ${count(CSV_ROWS)} Zuordnungen.`); + } + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (quoted) { + if (char === '"') { + if (text[i + 1] === '"') { field += '"'; i++; } + else { quoted = false; afterQuote = true; } + } else if (char === '\r' || char === '\n') { + if (char === '\r' && text[i + 1] === '\n') i++; + field += '\n'; + line++; + } else field += char; + } else if (char === ',') { + pushField(); + } else if (char === '\r' || char === '\n') { + if (char === '\r' && text[i + 1] === '\n') i++; + pushRecord(); + line++; + startLine = line; + } else if (char === '"' && field === '' && !afterQuote) { + quoted = true; + } else { + if (afterQuote) fail('Unerwarteter Text nach dem schließenden Anführungszeichen.'); + if (char === '"') fail('Anführungszeichen mitten in einem Feld: Bitte das ganze Feld in Anführungszeichen setzen und enthaltene Anführungszeichen verdoppeln.'); + field += char; + } + if (field.length > 2048) fail('Das Feld ist länger als 2.048 Zeichen.'); + } + if (quoted) fail('Das schließende Anführungszeichen fehlt.'); + if (field !== '' || fields.length || afterQuote) pushRecord(); + return records; +} + +export function parseLabels(text) { + if (new TextEncoder().encode(text).length > CSV_BYTES) throw new Error('Die Datei ist größer als 256 KiB.'); + const records = parseCSV(text); + if (!records.length || records[0].fields.length !== 2 || records[0].fields[0] !== 'oms_id' || records[0].fields[1] !== 'label') throw new Error(`Zeile ${count(records[0]?.line || 1)}: Die Kopfzeile muss exakt oms_id,label lauten.`); + const labels = new Map(); + const seen = new Map(); + const errors = []; + const warnings = []; + for (const { line, fields } of records.slice(1)) { + if (fields.length !== 2) { errors.push(`Zeile ${count(line)}: Es werden genau zwei Spalten erwartet.`); continue; } + const [raw, label] = fields; + const id = raw.toUpperCase(); + if (!/^[0-9A-F]{8}$/.test(id)) { errors.push(`Zeile ${count(line)}: Die Kennung muss genau 8 Zeichen (0–9 oder A–F) enthalten, einschließlich aller führenden Nullen.`); continue; } + if (seen.has(id)) errors.push(`Zeile ${count(line)}: Kennung ${id} ist doppelt vorhanden (zuerst in Zeile ${count(seen.get(id))}).`); + else seen.set(id, line); + if (label.length > CSV_LABEL_LENGTH) errors.push(`Zeile ${count(line)}: Der eigene Name ist länger als ${count(CSV_LABEL_LENGTH)} Zeichen.`); + if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(label)) errors.push(`Zeile ${count(line)}: Der eigene Name enthält nicht unterstützte Steuerzeichen.`); + if (!/^[0-9]{8}$/.test(id)) warnings.push(`Zeile ${count(line)}: ${id} enthält A–F statt nur Ziffern (kein BCD). Die Kennung bleibt unverändert als Hexadezimalwert erhalten.`); + labels.set(id, label); + } + if (errors.length) throw new Error(`${errors.slice(0, 20).join('\n')}${errors.length > 20 ? `\n… ${count(errors.length - 20)} weitere Fehler.` : ''}`); + return { labels, warnings }; +} + +export function csvCell(value) { + let text = value === null || value === undefined ? '' : String(value); + // Do not emit spreadsheet formulas, even after leading whitespace/control bytes. + // Eight-digit hexadecimal IDs cannot trigger this and are never numerically parsed. + if (typeof value === 'string' && (/^[\t\r\n]/.test(text) || /^[\s\u0000-\u001F]*[=+\-@]/.test(text))) text = `'${text}`; + return `"${text.replaceAll('"', '""')}"`; +} +function csvText(rows) { return `\uFEFF${rows.map(row => row.map(csvCell).join(',')).join('\r\n')}\r\n`; } +function download(name, rows) { + const url = URL.createObjectURL(new Blob([csvText(rows)], { type: 'text/csv;charset=utf-8' })); + const link = node('a'); + link.href = url; + link.download = name; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} +function exportEvents() { + const fields = ['boot_id', 'id', 'timestamp_us', 'tx_start_us', 'tx_done_us', 'meter_id', 'label', 'manufacturer_raw', 'manufacturer_flag', 'manufacturer_name', 'version_raw', 'device_type_raw', 'medium', 'identity_warning', 'ambiguous_id', 'hash', 'length', 'rssi_dbm', 'crc_ok', 'source', 'mode', 'format', 'reception', 'outcome']; + const ambiguity = collisions(state.rows); + const rows = state.rows.map(row => { + const identity = senderIdentity(row); + return [state.boot, row.id, row.timestamp_us, row.tx_start_us, row.tx_done_us, identity.rawId, senderLabel(identity), row.manufacturer, identity.trusted ? identity.manufacturer.code : '', identity.trusted ? identity.manufacturer.name : '', row.version, row.device_type, identity.trusted ? identity.medium.name : '', identity.warnings.join('; '), identity.labelEligible && ambiguity.has(identity.id), row.hash, row.length, row.rssi_dbm, row.crc_ok, row.source, row.mode, row.format, row.reception, row.outcome]; + }); + download('heltec-funkverlauf.csv', [fields, ...rows]); +} +function exportLabels() { + const ids = [...new Set(state.rows.map(senderIdentity).filter(identity => identity.labelEligible).map(identity => identity.id))].sort(); + download('heltec-zaehlernamen.csv', [['oms_id', 'label'], ...ids.map(id => [id, state.labels.get(id) || ''])]); +} +function renderLabels() { + setText('label-count', `${count(state.labels.size)} ${state.labels.size === 1 ? 'Name' : 'Namen'}`); + $('clear-labels').disabled = state.labels.size === 0; + renderEvents(); +} + +$('filter').addEventListener('input', renderEvents); +$('failures').addEventListener('change', renderEvents); +$('pause').addEventListener('click', () => { + state.paused = !state.paused; + if (state.paused) { + state.frozenRows = state.rows.slice(); + state.frozenBoot = state.boot; + state.frozenAt = deviceNow(); + state.newWhilePaused = 0; + } else { + state.frozenRows = []; + if (state.frozenBoot !== state.boot) expanded.clear(); + } + $('pause').setAttribute('aria-pressed', String(state.paused)); + setText('pause', state.paused ? 'Anzeige fortsetzen' : 'Nur Anzeige pausieren'); + renderEvents(); + renderRetention(); +}); +$('download-events').addEventListener('click', exportEvents); +$('export-labels').addEventListener('click', exportLabels); +$('sample-labels').addEventListener('click', () => download('heltec-namensvorlage.csv', [['oms_id', 'label'], ['00123456', 'Wasserzähler Küche'], ['00000001', 'Hauswirtschaftsraum, Wärme']])); +$('clear-labels').addEventListener('click', () => { + state.importGeneration++; + state.labels = new Map(); + $('label-file').value = ''; + $('label-result').className = 'small'; + setText('label-result', 'Eigene Namen aus diesem Tab entfernt. Am Gerät wurde nichts geändert.'); + renderLabels(); +}); +$('label-file').addEventListener('change', async event => { + const generation = ++state.importGeneration; + const file = event.target.files[0]; + if (!file) return; + let importStep = 'size'; + try { + if (file.size > CSV_BYTES) throw new Error('Die Datei ist größer als 256 KiB.'); + importStep = 'read'; + const bytes = await file.arrayBuffer(); + if (generation !== state.importGeneration) return; + importStep = 'decode'; + const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); + importStep = 'parse'; + const parsed = parseLabels(text); + state.labels = parsed.labels; + $('label-result').className = `small ${parsed.warnings.length ? 'warning-text' : 'good-text'}`; + setText('label-result', `${count(state.labels.size)} ${state.labels.size === 1 ? 'Name' : 'Namen'} aus „${file.name}“ übernommen. Vorherige Zuordnungen ersetzt; nichts hochgeladen.${parsed.warnings.length ? `\n${parsed.warnings.slice(0, 8).join('\n')}${parsed.warnings.length > 8 ? `\n… ${count(parsed.warnings.length - 8)} weitere Kennungen mit A–F (kein BCD).` : ''}` : ''}`); + renderLabels(); + } catch (error) { + if (generation !== state.importGeneration) return; + $('label-result').className = 'small danger-text'; + const message = importStep === 'read' ? 'Die ausgewählte Datei konnte nicht gelesen werden.' + : importStep === 'decode' ? 'Die Datei ist kein gültiger UTF-8-Text. Bitte als CSV mit UTF-8-Kodierung speichern.' + : error.message; + setText('label-result', `Datei nicht übernommen. Alle bisherigen Namen bleiben unverändert.\n${message}`); + } finally { + if (generation === state.importGeneration) event.target.value = ''; + } +}); +compactTable.addEventListener('change', () => { + for (const cell of document.querySelectorAll('.detail-row > td')) { + cell.colSpan = compactTable.matches ? 3 : 4; + } +}); +window.addEventListener('online', () => { if (!state.inFlight) poll(); }); +document.addEventListener('visibilitychange', () => { if (!document.hidden && !state.inFlight) poll(); }); +setText('registry-note', `Herstellernamen: ${count(registryInfo.count)} eindeutige FLAG-Kennungen aus dem offiziellen Verzeichnis der DLMS User Association, Stand ${registryInfo.date}. Die Namen bestimmen weder Zählermodell noch Treiber.`); +setInterval(renderHealth, 1000); +poll(); diff --git a/firmware/main/web/identity.js b/firmware/main/web/identity.js new file mode 100644 index 0000000..970fafb --- /dev/null +++ b/firmware/main/web/identity.js @@ -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}`, + }; +} diff --git a/firmware/main/web/index.html b/firmware/main/web/index.html new file mode 100644 index 0000000..a694358 --- /dev/null +++ b/firmware/main/web/index.html @@ -0,0 +1,115 @@ + + + + + + + + Heltec · Zählerfunk + + + + + + +
+
+

HELTEC / wM-Bus

Zählerfunk

+
Verbindung wird aufgebautWarte auf das Gerät
+
+
+
+ +

Verbindung zum Gerät wird aufgebaut.

+
+

Jetzt am Gerät

+

Warte auf den Gerätestatus.

+

Noch keine Daten verfügbar.

+
+ +
+

Letzte Funknachrichten

Neueste zuerst · je ein Signal mit abschließendem Ergebnis

+
+
+ + +
0 Funknachrichten
+
Empfangene Funknachrichten und Sendeergebnisse, neueste zuerst. Unter Einzelheiten stehen die vollständige Absenderkennung, Rohwerte und Zeitangaben.
ZeitAbsenderFunkErgebnis
+

Warte auf den ersten Verlauf …

+ +
+ +
+ Diagnose: Summen und Funkstatus +
+

Gerät im Detail

Laufzeit —
+
+

Funkzustand

—

Warte auf Messdaten

Funkprüfung —

+

Weiterleiten

—

Wartezeit —

Funk-Reparaturversuche —

+

Sendezeit

—

Warte auf Messdaten

+

Letzte Aktivität

Lesbar empfangen
—
Senden beendet
—
+
+

Summen seit Gerätestart

+
+
—
Lesbar empfangen
—
Nicht lesbar
—
Weitergesendet
—
Ausgelassen
—
Sendefehler
—
Funk-Reparaturversuche
+
+
+
+ +
+ Einstellungen am Heltec-Gerät ändern +
+
+

Geräteeinstellungen

+ +
+

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).

+

Ungesendete Entwürfe bleiben beim Nachladen erhalten, aber nicht beim Neuladen oder Schließen dieses Browser-Tabs.

+

Noch keine Einstellungen geladen. Zum Laden diesen Bereich öffnen.

+

+
+
+ Experteneinstellungen: Funkexperimente und eigene Signale +
+

FEM-CSD und Präambelerkennung sind Empfangsexperimente und können den Empfang verschlechtern. Kennungssignale erzeugen zusätzlichen Funkverkehr. Im Zweifel die vorhandenen Werte beibehalten.

+
+
+
+
+

WLAN des Heltec-Geräts

+

Ausschalten trennt diese Verbindung. Die Funkweiterleitung läuft gemäß ihren Einstellungen weiter. Das WLAN kann danach nicht über diese Seite wieder eingeschaltet werden.

+ +

+
+
+
+ +
+ Optional: eigene Namen für Zähler +
+

Eigene Zählernamen

0 Namen
+

Nur für diesen Browser-Tab. Die Datei bleibt auf deinem Gerät.

+
+

Keine Namen geladen. Neuladen oder Schließen der Seite entfernt alle eigenen Namen.

+
+
+ +
+ Datenschutz, Zuordnung und Quellen +
+

Wie wird ein Absender erkannt?

+

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.

+

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.

+

Herstellernamen: mitgelieferter Stand des offiziellen FLAG-ID-Verzeichnisses der DLMS User Association.

+

Quellen (nur das Öffnen dieser Links benötigt Internet): Offizielles DLMS-Verzeichnis · Gerätetyp-Codes bei wmbusmeters.

+

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.

+
+
+
Heltec-FunkweiterleitungLokal am Gerät · ohne Cloud
+
+ + + diff --git a/firmware/main/web/manufacturers.js b/firmware/main/web/manufacturers.js new file mode 100644 index 0000000..c5efcc1 --- /dev/null +++ b/firmware/main/web/manufacturers.js @@ -0,0 +1,1633 @@ +/* + * Offline FLAG ID registry: DLMS User Association (official public directory). + * https://www.dlms.com/flag-id-directory/ + * Data: https://www.dlms.com/srv/FlagIdLoader.php?internal=false&langId=0 + * Retrieved 2026-09-09: 1626 source rows, 1621 unique three-letter IDs. + * Registry facts only; no DLMS website implementation is included. + * Multiple published names for a FLAG are retained, separated by " / ". + * This snapshot is not a guarantee of current registration or device model. + */ +export const registryInfo = Object.freeze({ source: 'https://www.dlms.com/flag-id-directory/', date: '2026-09-09', count: 1621 }); +export const manufacturers = Object.freeze({ + "AAA": "Aventies GmbH", + "AAB": "Milas", + "ABB": "ABB AB", + "ABC": "Paya Energy", + "ABN": "ABN Braun AG", + "ABR": "ABB s.r.o.", + "ACA": "Acean", + "ACB": "AcBel Polytech Inc.", + "ACC": "Accurate (Pvt) Ltd", + "ACE": "Actaris, France. (Electricity)", + "ACG": "Actaris, France. (Gas)", + "ACH": "Acantho S.p.A.", + "ACL": "Aclara Meters UK Ltd", + "ACN": "ACN Advanced Communications Networks SA", + "ACS": "Tianjin Chuangshi Technology Developing CO. Ltd.", + "ACT": "Activis Metering GmbH", + "ACW": "Actaris, France. (Water and Heat)", + "ADA": "Andrea Informatique Sarl", + "ADD": "“ADD-Production” S.R.L.", + "ADE": "Yantai Aerospace Delu Energy-saving Technology Co., Ltd.", + "ADF": "ADFweb.com S.r.l.", + "ADN": "Aidon Oy", + "ADR": "Adrem Engineering SRL", + "ADU": "Adunos GmbH", + "ADV": "Advant sp. z o.o.", + "ADX": "ADD-Production S.R.L.", + "AEA": "Abam Electronic Alborz", + "AEC": "Advance Electronics Company", + "AEE": "Atlas Electronics", + "AEG": "AEG", + "AEI": "Ajay Electrical Industries", + "AEL": "Kohler", + "AEM": "S.C. AEM S.A.", + "AEN": "ADVANCED ENERGY MANAGEMENT SOLUTIONS LTD", + "AER": "Aerzener Maschinenfabrik GmbH", + "AES": "ALFANAR ELECTRICAL SYSTEM", + "AFS": "AFSONA INVEST LLC", + "AFX": "Alflex Products", + "AGE": "AccessGate AB", + "AGI": "PT. Armitec Electrical Systems", + "AGT": "Agnitio Technologies Pvt Ltd", + "AHV": "aventies GmbH", + "AHX": "Sepanta Electronic Tabarestan", + "AIC": "Avastu India Creations Pvt Ltd.", + "AIM": "Ningbo Aimei Meter Manufacture Co., Ltd.", + "AKK": "MAximum", + "AKU": "Akanksha Power and Infrastructure Limited", + "ALC": "Zenner Gas S.r.l.", + "ALE": "AEROSPACE LIANGLI ELECTRIC CO.,LTD", + "ALF": "Alfatech – Elektromed Elektronik", + "ALG": "Algodue Elettronica srl", + "ALH": "ALFANAR ELECTRICAL SYSTEM", + "ALK": "Actislink Sp. z o.o.", + "ALL": "Allied Engineering Works Limited", + "ALP": "Alphion India Private Limited", + "ALR": "Algorab S.R.L.", + "ALT": "Amplitec GmbH", + "ALV": "Alvicom Ltd.", + "AMB": "Würth Elektronik eiSos GmbH & Co. KG", + "AMC": "Arch Meter Corporation", + "AMD": "KEPID AMSTECH", + "AME": "Avon Meters Pvt. Ltd.", + "AMG": "ANTE METER GROUP CO., LTD", + "AMH": "AmiHo Ltd", + "AMI": "AMI Tech(I) Pvt. Ltd", + "AML": "Eon Electric Ltd.", + "AMP": "Ampy Automation Digilog Ltd", + "AMR": "Actislink", + "AMS": "Zhejiang Joy Electronic Technology Co.,Ltd", + "AMT": "INTEGRA METERING AG", + "AMX": "APATOR METRIX SA", + "ANA": "Anacle Systems PTE LTD", + "AND": "Andis, s.r.o.", + "ANE": "AN electronic", + "ANZ": "Anhui Nari Zenith Electricity&Electronic CO.,LTD", + "AOM": "Aquametro Oil & Marine AG", + "AON": "ASTRON d.o.o.", + "APA": "Apator SA", + "APL": "APLI s.r.o.", + "APO": "Apolis GmbH", + "APR": "Apronecs Ltd", + "APS": "Apsis Kontrol Sistemleri", + "APT": "Apator SA", + "APX": "Amplex A/S", + "AQA": "ACTAQUA GmbH", + "AQL": "Aqualoc", + "AQM": "INTEGRA METERING AG", + "AQN": "Aquantia S.r.l.", + "AQT": "Aquatherm sp.j. PPH.", + "AQU": "Aquamess Gmbh", + "ARA": "Aranha Ltd.", + "ARC": "Arcelik AS", + "ARD": "Arad Group Ltd", + "ARE": "Archai Electronics Inc.", + "ARF": "ADEUNIS RF", + "ARG": "ARGO group of companies", + "ARH": "PT. Armitec Electrical Systems", + "ARK": "Arkon Flow Systems, s.r.o", + "ARM": "Arivus metering GmbH", + "ARQ": "ARQIVA", + "ARS": "ADD – Bulgaria Ltd", + "ART": "Electrotécnica Arteche Smart Grid", + "ARW": "Arrow Electronics India Pvt. Ltd", + "ARX": "Aras Mercu Sdn. Bhd.", + "ASA": "Asac srl", + "ASC": "A2A Smart City", + "ASD": "AS DAQ SYSTEMS PVT LTD", + "ASG": "Meter technology Company", + "ASH": "Basic Electronics Company Limited", + "ASJ": "ACCUMET SOLUTIONS", + "ASM": "Adya Wifi Metering Pvt. Ltd.", + "ASR": "Erelsan Elektrik ve Elektronik", + "AST": "ASTINCO Inc.", + "ASY": "Arvato Systems Digital GmbH", + "ATA": "Alcansar Ölçüm ve Otomasyon Sistemleri", + "ATC": "Arabian Transformer Company", + "ATE": "ADVANCE TECHNOLOGY AND ELECTRICS COMPANY LIMTED", + "ATF": "AKTIF OTOMASYON LTD.STI.", + "ATI": "Analogics Tech India Ltd.", + "ATL": "Atlas Elektronik", + "ATM": "Atmel Spain SAU", + "ATS": "Atlas Sayaç Sanayi A.Ş.", + "AUR": "Aurum Europe B.V.", + "AUT": "Aiut Sp. z o.o.", + "AUX": "Ningbo Sanxing Smart Electric Co., Ltd.", + "AVA": "Avangard JSC", + "AVE": "ASHTAVINAYAKA ENERGY INFRA PVT. LTD.", + "AXI": "Axioma Metering, UAB", + "AXS": "AXSEM AG", + "AYS": "Euromet Ltd Stl", + "AZE": "AZEL Electronics", + "BAM": "Bachmann GmbH & Co KG", + "BAR": "Bär Industrie Elektronik GmbH", + "BAS": "BASIC INTELLIGENCE TECHNOLOGY CO.,LTD.", + "BBE": "Bentec Bhartia Engineers Pvt. Ltd.", + "BBS": "BBS Electronics", + "BCE": "ShenZhen B.C Electronic CO. Ltd.", + "BCR": "Jiangsu Bingchen Electronics Co Ltd.", + "BEA": "Baer Energy Automation GmbH", + "BEE": "Bentec India Limited", + "BEF": "BEFEGA GmbH", + "BEG": "begcomm Communication AB", + "BEL": "Belassitsa AD", + "BEN": "BEENIC GmbH", + "BER": "Bernina Electronic AG", + "BFW": "BFW Buero fuer Waermemesstechnik OHG", + "BHG": "Brunata A/S", + "BIM": "BEAM INFOTECH PVT. LTD.", + "BJY": "Beijing JOYO smart water meter co.,ltd.", + "BKB": "Boendekomfort AB", + "BKO": "Beko Elektronik AS", + "BKT": "Bekto Precisa", + "BLM": "BELIMO Automation AG", + "BLU": "Bluering", + "BMA": "Byte Machine s. r. o.", + "BME": "Beifeng GmbH", + "BMI": "Badger Meter Inc., 6116 E 15th St.", + "BMP": "BMETERS Polska Sp.z.o.o.", + "BMT": "BMETERS srl", + "BNR": "Beijing Banner Electric Co., Ltd.", + "BOV": "Zhejiang Bove Intelligent Technology Co., Ltd", + "BPM": "Aadharshila Mobility Solutions Pvt Ltd", + "BRA": "Brandes GmbH", + "BRC": "BRICK4U GmbH", + "BRN": "Bruntab Energy LTD.", + "BRT": "BEREKET TEKNOLOJİK ÖLÇÜM SİSTEMLERİ BİL.ELK.İNŞ.İTH.İHR.SAN VE TİC LTD.ŞTİ", + "BRU": "Klaus Bruchmann GmbH", + "BSC": "Sanaye Sanjesh Energy Behineh Sazan Toos", + "BSD": "BSED UG", + "BSE": "Basari Elektronik A.S.", + "BSI": "Bundesamt für Sicherheit in der Informationstechnik (BSI)", + "BSM": "Bluestar Electrical Meter Research Institute", + "BSP": "Byucksan Power Co. Ltd.", + "BSS": "Baylan Su Sayaçları", + "BST": "BESTAS Elektronik Optik", + "BSX": "BS-Messtechnik UG", + "BSY": "Aktif Enerji İnsaat Sanayi ve Ticaret Limited Sirketi", + "BTA": "Buta Elektromekanik A.Ş.", + "BTL": "BIT-LAB", + "BTM": "Bharatech Smart Industrial Pvt Ltd", + "BTR": "RIA-BTR Produktions-GmbH", + "BTS": "Basari Teknolojik Sistemler AS", + "BUR": "Bopp und Reuther Messtechnik GmbH", + "BUY": "BUYI TECHNOLOGOY CO., LIMITED.", + "BXC": "Beijing Fuxing Xiao-Cheng Electronic Technology Stock Co., Ltd Xisanhuan Beilu", + "BYD": "BYD Company Limited", + "BYL": "Baylan", + "BYW": "Baylan Water Meters", + "BZR": "Gebr. Bauer GbR", + "CAB": "Cabtronix AG", + "CAD": "CADIS", + "CAH": "MAEC – GROUPE CAHORS", + "CAL": "Caleffi S.p.A.", + "CAN": "PT CANNET ELEKTRIK INDONESIA", + "CAR": "CARI Electronic", + "CAT": "Cubes And Tubes OY", + "CAV": "CaveTronic", + "CBF": "ELECTRICAL CIRCUIT BREAKER FACTORY FOR INDUSTRY-ECB", + "CBI": "Circuit Breaker Industries", + "CBS": "CB Svendsen A/S", + "CCP": "13348164 Canada Corp", + "CCS": "Chetas Control Systems Pvt Ltd", + "CDA": "Centre for Development of Advanced Computing", + "CDL": "Customised Data Ltd.", + "CDT": "CENTRE FOR DEVELOPMENT OF TELEMATICS", + "CEB": "Cebyc AS", + "CED": "CEDARNET", + "CEG": "Consolinno Energy GmbH", + "CEH": "Tosee Garan Sanjesh Energy Hoshmand", + "CEL": "Creative Electronics (Pvt) Ltd", + "CEM": "YAVUZ METAL SANAYI VE TICARET A.S.", + "CET": "Cetinkaya Aydinlatma", + "CFL": "CF Smart Technologies (Pvt) Ltd.", + "CGC": "Contor Group S.A.", + "CGO": "Cavagna Group S.p.A", + "CHA": "Charles Technology & Research LTD.", + "CHC": "CHUN-IL INSTRUMENT CO.,LTD", + "CHE": "Shandong Chenhui Electronic Technology Co., Ltd.", + "CHM": "Chung-Hsin Electric and Machinery Manufacturing Corp.", + "CHS": "Smart Services International Sagl", + "CIC": "CHALLENGE INDUSTRIAL CO., LTD", + "CIR": "Circutor", + "CJS": "CJS Technology Ltd", + "CKT": "CKT Elektrik Elektronik Sanayi ve Ticaret A.Ş", + "CLA": "3g celllabs private limited", + "CLB": "CMC S.r.l.", + "CLE": "Shen Zhen Clou Electronics Co Ltd.", + "CLO": "Clorius Raab Karcher Energi Service A/S", + "CLS": "Celsa Messgeräte GmbH", + "CLT": "Zhuhai S.E.Z. Calintech Electric Co., Ltd.", + "CLX": "CLK IPEKYOLU LOJISTIK VE TICARET A.Ş.", + "CLY": "Clayster AB", + "CMC": "CMC EKOCON d.o.o.", + "CMP": "CM Partner Inc", + "CMS": "CMS Computers Limited", + "CMT": "CMOSTEK MICROELECTRONICS CO., LTD.", + "CMV": "Comverge, Inc.", + "CNM": "COSTEL", + "CNU": "CNU Global", + "COH": "COHEAT Ltd, Future Business Centre", + "COM": "COMMON S.A.", + "CON": "Conlog", + "CPG": "CentraPlus GmbH", + "CPL": "CPL CONCORDIA Soc.Coop.", + "CPO": "C3PO S.A.", + "CPS": "CAPITAL POWER SYSTEMS LIMITED", + "CQC": "Yueqing Qicheng Electric Co., Ltd", + "CRD": "CRDM DEVELOPPEMENTS", + "CRT": "CRDM Technology", + "CRW": "Xuzhou Runwu Science and Technology Development Co. Ltd.", + "CRX": "Corinex Communications Corp.", + "CRY": "Crystal Power", + "CSC": "CHUBUSEIKI Co., LTD.", + "CSL": "Comsel System Ltd", + "CSP": "CSP – Innovazione nelle ICT", + "CSW": "Critical Software", + "CTE": "COSTER T.E. S.p.A.", + "CTL": "Cyan Technology Ltd", + "CTP": "Cabcon Technologies Private Limited", + "CTQ": "Control-Q b.v", + "CTR": "Contar – Electronica Industrial", + "CTT": "DLMS User Association Conformance", + "CTX": "Contronix GmbH", + "CUB": "Cubic Sensor and Instrument Co.,Ltd", + "CUC": "Cuculus GmbH", + "CUR": "CURRENT Group, LLC", + "CWA": "CompWell AB", + "CWI": "Cewe Instrument AB", + "CWV": "CMEC Electric Import & Export Co. Ltd", + "CYE": "Quanzhou Chiyoung Electronics Technology Co. Ltd.", + "CYI": "QUANZHOU CHIYOUNG INSTRUMENT CO., LTD", + "CYN": "Cynox, Weinart Engineering", + "CZA": "Contadores de Agua de Zaragoza S.A.", + "CZM": "Cazzaniga S.p.A.", + "DAE": "DAE Srl", + "DAF": "Daf Enerji Sanayi ve Ticaret A.S.", + "DAN": "Danubia", + "DBD": "DBD Water Systems", + "DBE": "Decibels Electronics P Ltd, Decibels Electronics Pvt Ltd.", + "DCD": "Delhi Control Devices Pvt. Ltd.", + "DCO": "diaeco wave company", + "DCZ": "decarbon1ze GmbH", + "DDE": "D&D Elettronica srl", + "DDI": "DD Infraventures Pvt. Ltd.", + "DDL": "DONGDO LMS", + "DDM": "Delta Dore", + "DEA": "Dea HT srl", + "DEC": "DECODE d.o.o. Data Communications", + "DEI": "DevSys Embedded Technology", + "DEL": "DELTAMESS DWWF GmbH", + "DEN": "Ducati Energia", + "DES": "Desi (Alarms) Ltd", + "DEV": "Develco Products", + "DFE": "Dongfang Electronics Co., Ltd.", + "DFS": "Danfoss A/S", + "DGC": "Digicom S.p.A.", + "DGI": "Digi International Inc.", + "DGM": "Diehl Metering", + "DGY": "Discovergy GmbH", + "DHA": "Shanghai dahua measuring&auto control instruments manufactory", + "DHQ": "YIDU Smart Technology ( Beijing ) Co.,Ltd.", + "DIE": "Dielen GmbH", + "DIG": "Digutal Request GmbH", + "DIL": "DECCAN INFRATECH LIMETED", + "DJA": "De Jaeger Automation bvba", + "DKY": "Electric Power Research Institute of Guangdong Power Grid Corporation", + "DLX": "Delixi Group Instruments & Meters Co.,ltd", + "DMC": "DMC International", + "DME": "DIEHL Metering", + "DMG": "DIINNO GmbH", + "DMI": "Dualmicro Measurement Technologies B.V.", + "DMO": "BEENIC GmbH", + "DMP": "DM Power Co., Ltd", + "DMS": "Digilog Micro Solutions Private Limited", + "DNB": "Dana Sanjesh Ab o Bargh (Danaab)", + "DNC": "Dongnam Co., Ltd", + "DNO": "DENO d.o.o.", + "DNT": "Dr Neuhaus Telekommunikation GmbH", + "DNV": "DNV GL", + "DOJ": "Suzhou Dojustek Intelligent Technology Co.,Ltd.", + "DOM": "Domat Control System", + "DOS": "Metsec Cables Ltd.", + "DPM": "DELTA PRIMA METERING SDN. BHD.", + "DPP": "DECCAN POWER PRODUCTS PVT. LTD.", + "DRC": "DURECOM Co., Ltd.", + "DRP": "DBD WATER SYSTEMS", + "DRT": "DRESSER Italia S.r.l.", + "DSE": "Digitech Systems and Engineering Private Limited", + "DSM": "Desimal Elektronik Mühendislik San. ve Tic. A. Ş.", + "DST": "Shenzhen Donsun Technology Co. Ltd.", + "DTE": "DanTaet A/S", + "DUA": "DLMS User Association", + "DUS": "Dresser Utility Solutions GmbH", + "DVE": "DEV ENERGY", + "DVG": "Device GmbH", + "DVL": "devolo AG", + "DWT": "Hangzhou elecwatt Technology Co.,Ltd.", + "DWY": "Dwyer Instruments, LLC", + "DWZ": "Lorenz GmbH & Co. KG", + "DZG": "DZG Metering GmbH", + "EAA": "Electronic Afzar Azma", + "EAD": "EAD Energieabrechnungssysteme GmbH", + "EAH": "Endress+Hauser", + "EAS": "EAS Elektronik San. Tic. A.S.", + "EBE": "Ebeco AB", + "EBK": "Biesenthal GmbH", + "EBV": "EBV Elektronik GmbH & Co KG", + "EBZ": "eBZ GmbH", + "ECA": "ECO ADAPT", + "ECB": "ELECTRICAL CIRCUITT BREAKER FACTORY FOR INDUSTRY", + "ECC": "Energycare Company", + "ECH": "Networked Energy Services Corporation", + "ECI": "ECIL", + "ECL": "Electronics Corporation of India Ltd", + "ECM": "Ecomess Sp. z o. o.", + "ECO": "Engie BtoC (Smart program)", + "ECS": "Herholdt Controls srl", + "ECT": "Platform for Smart Manufacturing LLC (ECTRON)", + "EDI": "Enel Distribuzione S.p.A, Via Ombrone, 2, Rome", + "EDM": "EDMI Pty. Ltd.", + "EDP": "EDMP Group Limited", + "EEC": "ESCO Sp. z o.o.", + "EEE": "3E s.r.l.", + "EEI": "ELSOURCE PVT LTD", + "EEM": "Electrify Energy Pvt. Ltd.", + "EEO": "Eppeltone Engineers Pvt Ltd", + "EEP": "ELECTRONET EQUIPMENT PVT LTD", + "EES": "Eletra Industria e Comercio de Medidores Elétricos", + "EFA": "EFACEC Engenharia e Sistemas SA", + "EFE": "Engelmann Sensor GmbH", + "EFI": "Efimatic Iberica", + "EFN": "EFEN GmbH", + "EFR": "Europäische Funk-Rundsteuerung", + "EFS": "EFSYS", + "EFX": "Enerflux private limited", + "EGA": "eGain International AB", + "EGC": "Ekbatan Gas Control", + "EGD": "EcoGuard AB", + "EGM": "Elgama-Elektronika Ltd", + "EGO": "EWE Go GmbH", + "EGP": "Egypt Meters Company EMC", + "EGT": "Enegate Co.,Ltd.", + "EGW": "Enermess Energie Mess- und Servicedienste GmbH", + "EGY": "Egyptian Smart Meter Company", + "EHL": "Secure Meters Limited", + "EHS": "Endress+Hauser SICK GmbH+Co. KG", + "EIC": "Elite Experts Industry Company", + "EIE": "Ei Electronics", + "EIG": "Eigensonne GmbH", + "EIP": "Elmeasure India Pvt. Ltd", + "EIS": "ENERGY INTEGRATED TECH SOLUTIONS (PTY) LTD", + "EIT": "EnergyICT NV", + "EKA": "Eka Systems", + "EKF": "EKF", + "EKO": "EKOLIS", + "EKS": "DİCLE KÖK ENERJİ YATIRIM A.Ş", + "EKT": "PA KVANT J.S.", + "ELC": "CJSC \" EMIS \"", + "ELD": "Elektromed Elektronik Ltd", + "ELE": "Elster Electricity LLC", + "ELG": "Elgas s.r.o.", + "ELK": "ELEKTROMED ÖLÇÜM CİHAZLARI TEKNOLOJİ SAN. VE TİC. A.Ş.", + "ELL": "Energy Plus", + "ELM": "Elektromed Elektronik Ltd", + "ELO": "ELO Sistemas Eletronicos S.A.", + "ELP": "ElectroPlus", + "ELQ": "ELEQ b.v.", + "ELR": "Elster Metering Limited", + "ELS": "Elster GmbH", + "ELT": "ELTAKO GmbH", + "ELU": "Elupi Elektronik Elektrik LTD", + "ELV": "Elvaco AB", + "ELY": "Elektroniksystem i Umeå AB", + "EMB": "Embit s.r.l.", + "EMC": "Embedded Communication Systems GmbH", + "EME": "SC. Electromagnetica SA", + "EMF": "IT-Beratung Energiemanagement Flammang", + "EMH": "EMH metering GmbH & Co. KG (formerly EMH Elektrizitatszahler GmbH & CO KG)", + "EMI": "Entorno Inteligente de Medición S.L.", + "EML": "Emlite ltd", + "EMM": "Email Metering", + "EMO": "Enermet", + "EMP": "ELEKTROMETAL SPÓŁKA AKCYJNA", + "EMR": "CJSC “Energomera”", + "EMS": "EMS-PATVAG AG", + "EMT": "Elster Messtechnik GmbH", + "EMU": "EMU Elektronik AG", + "ENC": "ENSYCO ETHIOPIA ELECTRICITY METER MANUFACTURING PLC", + "END": "ENDYS GmbH", + "ENE": "ENERDIS", + "ENG": "ENER-G Switch2 Ltd", + "ENH": "ENMAS GmbH", + "ENI": "entec innovations GmbH", + "ENL": "ENEL d.o.o.", + "ENM": "ENLITE SMART SOLUTIONS PRIVATE LIMITED", + "ENN": "Enernet", + "ENO": "ennovatis GmbH", + "ENP": "“Kiev Polytechnical Scientific Research”", + "ENR": "Energisme", + "ENS": "ENSO NETZ GmbH", + "ENT": "ENTES Elektronik", + "ENX": "Enetronx GmbH", + "EPI": "EPI-USE AFRICA", + "EPL": "Escorts Pakistan Limited", + "EPM": "EcoSolutions Projects Management(Pty)Ltd", + "EPT": "Energy Prospect Technologies S.L.", + "ERE": "Enermatics Energy (PTY) LTD", + "ERI": "Easun Reyrolle Limited", + "ERL": "Erelsan Elektrik ve Elektronik", + "ERN": "Ericsson Telecomunicazioni S.p.A", + "ERS": "Eurosys OOD", + "ERW": "Everrenew Energy Pvt. Ltd.", + "ESA": "ESAC srl", + "ESC": "EDMI (Shenzhen) CO., Ltd", + "ESD": "Edelstrom Electronic Devices and Designing LLC", + "ESE": "ESE Nordic AB", + "ESG": "ESG CO.,LTD.", + "ESH": "EMSYCON GmbH", + "ESI": "Monosan Monofaze Elektrik Motorlari", + "ESL": "Esyasoft Landis and Gyr Limited", + "ESM": "Monosan Monofaze Elektrik Motorlari", + "ESN": "Zhejiang Eastron Electronic Co., Ltd.", + "ESO": "Monosan Monofaze Elektrik Motorlari", + "ESP": "EFICAA ENSMART SOLUTIONS PRIVATE LIMITED", + "ESR": "Ensor AG", + "ESS": "Energy Saving Systems LTD.", + "ESV": "ESKA VALVE", + "ESX": "Esave AS", + "ESY": "EasyMeter GmbH", + "ETD": "Energy Team S.p.A", + "ETK": "ELTEK BROJILA d.o.o.", + "ETO": "Sphere of economical technologies LTd", + "ETP": "Energotechnica Llc", + "EUE": "E+E Electronic", + "EUR": "Eurometers Ltd", + "EUS": "Ebeling und Sohn GmbH & Co. KG", + "EVD": "DREWAG NETZ GmbH", + "EVK": "EV KUR ELEKTRIK", + "EVL": "Geothermique Ltd", + "EVT": "EVThru", + "EWA": "EWATTCH", + "EWE": "EWE AG", + "EWG": "EWG DOO", + "EWS": "ENLESS WIRELESS", + "EWT": "Diehl Metering", + "EXS": "exceeding solutions GmbH", + "EXT": "LOTRIČ Metrology, Ltd.", + "EYA": "EYKON Utility Solutions (Pty) Ltd.", + "EYB": "EYKON Limited", + "EYE": "Eco-eye Ltd", + "EYF": "EYKON Oy", + "EYK": "EYKON Solutions GmbH", + "EYS": "EYKON Solutions GmbH", + "EYT": "Enerlyt Potsdam GmbH", + "EYZ": "EYKON AG", + "EZL": "Enerzolve Smart Energy Technologies Pvt. Ltd", + "FAC": "Fireangel Safety Technology Ltd", + "FAE": "Fae Technology Company", + "FAN": "Fantini Cosmi S.p.A.", + "FAR": "FARAB", + "FAS": "FAST S.P.A.", + "FAT": "Fardad azma toos", + "FED": "Federal Elektrik", + "FEI": "FUJI ELECTRIC INDIA Pvt LTD", + "FEM": "Fortune Electric", + "FFD": "Fast Forward AG", + "FID": "Fi Muhendislik Ltd.", + "FIM": "Frodexim Ltd", + "FIN": "Finder GmbH", + "FIO": "Pietro Fiorentini", + "FLA": "FLASH ELECTRONICS (INDIA) PVT LTD", + "FLD": "Fludia", + "FLE": "XI‘AN FLAG ELECTRONIC CO. LTD", + "FLG": "FLOMAG s.r.o.", + "FLO": "Flonidan A/S", + "FLS": "FLASH o.s", + "FLU": "SHANDONG FEILONG INSTRUMENT CO.", + "FLW": "Fluidwell bv", + "FLX": "FLEXIM Flexible Industriemesstechnik GmbH", + "FMG": "Flow Meter Group", + "FML": "Siemens Measurements Ltd. (Formerly FML Ltd.)", + "FMM": "F.IMM s.r.l.", + "FND": "findy IoT Solutions", + "FNF": "FlowSystem", + "FNX": "Flownetix Ltd", + "FOX": "FOXYTECH Sp. z o.o.", + "FPL": "fifthplay NV", + "FPR": "F-Pribor LLC", + "FRC": "Shenzhen Friendcom Technology Co.,Ltd.", + "FRE": "Frer Srl", + "FRT": "Foritec GmbH", + "FRU": "OJSC NRPA FRUNZE", + "FSE": "Flecto Sense", + "FSP": "Finmek Space S.p.A.", + "FST": "FieldServer Technologies", + "FSY": "FlowService", + "FTL": "Tritschler GmbH", + "FUN": "Micro Matic Norge AS", + "FUS": "Fuccesso", + "FUT": "first:utility", + "FWS": "FW Systeme GmbH", + "FYL": "Shanghai Fengyilong Electronic Co., Ltd.", + "FZK": "FUNZIN.Co. Ltd", + "GAT": "GEPDEC SMART TECHNOLOGY PRIVATE LIMITED", + "GAV": "Carlo Gavazzi Controls S.p.A.", + "GBJ": "Grundfoss A/S", + "GBX": "GRIDBLOX", + "GCE": "Genergica", + "GCG": "Goldcard Smart Group Co.,Ltd.", + "GCT": "GridCrest Technologies Private Limited", + "GCX": "grandcentrix GmbH", + "GDC": "GADICO TECNOLOGIA LTDA", + "GDS": "InnoSense AG", + "GEC": "GEC Meters Ltd.", + "GEE": "GE Energy", + "GEL": "Industrial Technology Research Institute", + "GEN": "Goerlitz AG, Germany", + "GEO": "Green Energy Options Limited", + "GEP": "GEPDEC INFRATECH LIMITED", + "GET": "Genus Electrotech Ltd.", + "GEX": "Global Evolution Lighting", + "GFM": "GE Fuji Meter Co.,Ltd.", + "GIL": "Genus Innovations Limited", + "GIN": "Gineers Ltd.", + "GIO": "G. GIOANOLA S.r.l.", + "GKA": "G.K.Assembly Co.,Ltd.", + "GKM": "George Kent (Malaysia) Bhd", + "GLM": "GETRALINE", + "GLO": "NetLand Sp. z o.o.", + "GLX": "Vietnam Electrical Equipment Joint Stock Corporation", + "GMC": "GMC-I Messtechnik GmbH", + "GME": "Global Metering Electronics", + "GMM": "Gamma International Egypt", + "GMS": "Gity Madara Sepahan", + "GMT": "GMT GmbH", + "GNP": "GEPDEC ENERGY PVT LTD", + "GNY": "JiangSu GuoNeng Instrument Technology CO.,LTD", + "GOE": "Genus Power Infrastructures Ltd.", + "GOM": "Zhejiang Gomelong Meter Co., Ltd.", + "GOT": "NetLand Spółka z ograniczoną odpowiedzialnością", + "GPM": "Polaris Smart Metering Pvt. Ltd.", + "GPT": "GINTAI POWER TECHNOLOGY CO., LTD", + "GRA": "Grässlin GmbH", + "GRD": "Greenradio", + "GRE": "GE2, Green Energy Electronics", + "GRI": "Grinpal Energy Management", + "GRN": "GREEN ENS Co., Ltd.", + "GRP": "GlobalRnD sp. z o.o.", + "GRS": "Garderos GmbH", + "GRU": "G.GURU Co., Ltd.", + "GRV": "Gridventure Arge ve Teknoloji Pazarlama A.Ş.", + "GRX": "Gurux Ltd", + "GSD": "Genesis Smart Devices Private Limited", + "GSE": "Gridspertise S.r.l.", + "GSP": "Ingenieurbuero Gasperowicz", + "GSS": "R&D Gran-System-S LLC", + "GST": "Shenzhen Golden Square Technology Co.,Ltd.", + "GTE": "GREATech GmbH", + "GTM": "G2 misuratori S.r.l.", + "GTR": "Globaltronics for Electronics S.A.E.", + "GTS": "GIGATRONIK Stuttgart GmbH", + "GUH": "ShenZhen GuangNing Industrial CO. Ltd.", + "GVL": "gAvilar", + "GWF": "Gas- u. Wassermesserfabrik", + "GWI": "George Wilson Industries, Aldermans Green Industrial Estate", + "HAG": "Hager Electro GmbH", + "HAK": "Hako, a.s.", + "HBY": "HENAN HUABIAO INSTRUMENT TECHNOLOGY Co., Ltd.", + "HCE": "Hsiang Cheng Electric Corp", + "HCM": "Hidroconta S.A.U.", + "HDA": "Hidria d.o.o.", + "HDK": "Hydroko NV", + "HDX": "Beijing TianRuiXiangDe Measuring Technology Co.,Ltd.", + "HDY": "Dalian hundao instrument Co. Ltd.", + "HEG": "Hamburger Elektronik Gesellschaft", + "HEI": "Hydro-Eco-Invest SP. Z O.O.", + "HEK": "Hexing Technology Company Limited", + "HEL": "Heliowatt", + "HEM": "Hokkaido Electric Meter Industry Co.", + "HEN": "Shenzhen Heiman Technology Co., Ltd.", + "HER": "Hermes Systems", + "HEW": "Honeywell Integrated Technology (China) Co., Ltd.", + "HEX": "Shenzhen Hexcell Electronics Technology CO.,LTD", + "HFI": "Nanjing Huiran Measurement&Control Technology Co. Ltd.", + "HFL": "HFIL Technologies Private Limited", + "HFR": "SAERI HEAT METERING TECHNOLOGY CO.,LTD.", + "HGM": "HG meter a/s", + "HGP": "Hangzhou GreenPalm Technology Co., Ltd.", + "HHE": "HAUSHELD AG", + "HHM": "Chongqing Huahong Metering Co.,Ltd.", + "HIE": "Shenzhen Holley South Electronics Technology Co., Ltd.", + "HIN": "huebner Informationselektronik", + "HIT": "ABB Sp. z o.o.", + "HJM": "Huaihua Jiannan Machinery Factory Co.,Ltd", + "HKK": "Hokuriku Instrumentation Co. Inc.", + "HKT": "Heklatech AB", + "HLD": "Hildebrand Technology Limited", + "HLE": "Shenzhen Hopeland Technologies Co,.Ltd", + "HLT": "Hangzhou Laison Technology Co.Ltd", + "HLY": "Holley Metering Ltd", + "HMD": "Shenzhen Heiman Technology Co., Ltd.", + "HMI": "HMI Energy Co., Ltd.", + "HML": "Holley Technology Ltd., 181 WuChang Avenue", + "HMS": "Hermes Systems", + "HMT": "Hangzhou Meteronic Technology Co., Ltd.", + "HMU": "Hugo Müller GmbH & Co KG", + "HNA": "Houshmand Namayeh Afraz", + "HND": "Shenzhen Hemei Group Co., Ltd.", + "HNN": "Houshmand Namayeh Afraz", + "HOE": "HOENTZSCH GMBH", + "HOL": "Holosys d.o.o.", + "HON": "Honeywell Technologies Sarl", + "HOP": "Shenzhen Hopeland Technologies Co,.Ltd", + "HOY": "Holley Meters", + "HPL": "HPL-Socomec Pvt. Ltd.", + "HPM": "HANGZHOU HPM COMPANY LIMITED", + "HQL": "H.Q LAMPS MANUFACTURING CO PRIVATE LIMITED", + "HRM": "Hefei Runa Metering Co., Ltd.", + "HRS": "HomeRider SA", + "HRZ": "HERZ Messtechnik GmbH", + "HSD": "Ningbo Histar Meter Technology Co.,Ltd.", + "HST": "HST Equipamentos Electronicos Ltda", + "HSX": "HST GmbH", + "HTC": "Horstmann Timers and Controls Ltd.", + "HTE": "Hexing Technologies Europe SRL", + "HTI": "Shandong Hetong Information Technology CO.,Ltd.", + "HTL": "Ernst Heitland GmbH & Co. KG, Erlenstr. 8-10", + "HTS": "HTS-Elektronik GmbH", + "HTY": "HELIOTY srl", + "HUK": "Helbeck & Kusemann GmbH & Co. KG", + "HUM": "Humanlitech Ghana Limited", + "HVG": "Hekatron Vertriebs GmbH", + "HVT": "Helvatron AG", + "HWC": "Qingdao Hiwits Meter Co.,Ltd.", + "HWM": "Beijing Hongwei Chaoda Instrument Manufacturing Co.,Ltd.", + "HWT": "Huawei Technologies Co. Ltd.", + "HXD": "Beijing HongHaoXingDa Meters CO.,LTD.", + "HXE": "Hexing Electrical Co. Ltd.", + "HXT": "HEXIN (HONGKONG) TECHNOLOGY CO., LIMITED", + "HXW": "Hangzhou Xili Watthour Meter Manufacture Co. Ltd.", + "HYC": "Zhejiang Hengye Electronics Co.,Ltd", + "HYD": "Diehl Metering", + "HYE": "Zhejiang Hyayi Electronic Industry Co Ltd.", + "HYG": "Diehl Metering", + "HYM": "Zhejiang Hengye Electronics Co.,Ltd", + "HYS": "Hydrelis", + "HYT": "Zhejiang Hengye Electronics Co.,Ltd", + "HZC": "TANGSHAN HUIZHONG INSTRUMENTATION CO., LTD.", + "HZI": "TANGSHAN HUIZHONG INSTRUMENTATION CO., LTD.", + "HZZ": "Huizhou Zhongcheng Electronic Technology Co.,Ltd.", + "IAC": "INHEMETER AFRICA COMPANY LIMITED", + "IBE": "IBOT ENERGY SYSTEMS INDIA PRIVATE LIMITED", + "IBG": "ITI LIMITED, BANGALORE PLANT", + "IBT": "İkom Bilişim Teknolojileri AŞ", + "ICB": "Inscobee", + "ICE": "Icoal incorporated", + "ICK": "I&C Technology", + "ICM": "Intracom", + "ICP": "PT Indonesia Comnets Plus", + "ICS": "ICSA (India) Limited", + "ICT": "International Control Metering-Technologies GmbH", + "ICU": "i-cube", + "IDE": "IMIT S.p.A", + "IDS": "IDS GmbH", + "IEC": "leonnardo Corporation", + "IEE": "I.E. Electromatic, S.L", + "IEI": "Informage Energy Pvt. Ltd.", + "IEN": "Institute of Power Engineering", + "IES": "Integrated Electronic Systems Lab Co., Ltd.", + "IFC": "infocon doo", + "IFX": "Infineon Technologies", + "IGE": "INDKOSQUARE GLOBAL ENGINEERING PRIVATE LIMITED", + "IGM": "ITALGAS RETI", + "IGR": "iGridS GmbH, Hebelweg 2", + "IGS": "I.G.S.DATAFLOW S.r.l.", + "IHM": "Shenzhen Inhemeter Co., Ltd.", + "IID": "PT Industri Telekomunikasi Indonesia (Persero) / PT INDUSTRI TELEKOMUNIKASI INDONESIA (Persero)", + "IIF": "Westenergie Metering GmbH", + "IJE": "ILJIN Electric", + "IJK": "IJENKO SA", + "IKE": "IK Elektronik GmbH, Friedrichsgruener Str. 11-13, 08262", + "IKM": "Ikom LTD", + "IKO": "İKOM Bilişim Teknolojileri A.Ş.", + "IKS": "IKASIAN", + "IMC": "Iranmadar", + "IME": "Fellows s.c.ul.", + "IMR": "iMeter LLC", + "IMS": "IMST GmbH", + "IMT": "INTEGRA METERING AG", + "IMZ": "iMezr Innovations Pvt Ltd", + "INC": "Incotex", + "IND": "INDRA SISTEMAS", + "INE": "INNOTAS Elektronik GmbH", + "INF": "Infometric", + "INI": "Altero AB", + "INM": "Inepro Metering BV", + "INN": "INNEXIV, Inc.", + "INO": "Indotech Switchgear & Controls(Delhi) Pvt. Ltd", + "INP": "INNOTAS Produktions GmbH", + "INS": "INSYS MICROELECTRONICS GmbH", + "INT": "Infranet Technologies GmbH", + "INV": "Sensus Metering Systems", + "INX": "Innolex Engineering BV", + "IOM": "IOmeter GmbH", + "ION": "Ionics EMS Inc", + "IOT": "Trilliant Networks Inc", + "IPD": "IPD Industrial Products Australia", + "IQO": "Kwhiq", + "IQS": "IQ Systems (Pty) Ltd", + "IRE": "IREN Energia S.p.A.", + "ISA": "Isabellenhütte Heusler GmbH & Co. KG", + "ISE": "INESH SMART ENERGY (P) LTD.", + "ISF": "Investcom Szymon Fiedorowicz", + "ISI": "Akcionarsko Drustvo “Insa” Industrija Satova", + "ISK": "Iskraemeco", + "ISO": "Isoil Industria spa", + "ISS": "Iskra d.d.", + "IST": "Ista", + "ISW": "iSAtech water GmbH", + "ITA": "iTrona GmbH", + "ITB": "Itron Solucoes para Energia e Agua Ltda.", + "ITC": "INTECH TUNISIE", + "ITE": "ITRON (Electricity)", + "ITF": "ITF Fröschl GmbH", + "ITG": "ITRON (Gas)", + "ITH": "INTELTEH d.o.o.", + "ITI": "ITRON Asia", + "ITK": "Itron GmbH", + "ITL": "Indriya Technologies Pvt Ltd", + "ITM": "Intelligent Metering Systems (Pvt.) Limited", + "ITP": "M/s ITI LIMITED.", + "ITR": "Itron Inc", + "ITS": "ITRON Australasia Pty Ltd", + "ITU": "ITRON United States, Itron Inc", + "ITW": "ITRON (Water)", + "ITX": "IDEAL TECHNICAL SOLUTIONS", + "ITZ": "ITRON South Africa", + "IUS": "IUSA SA DE CV", + "IVY": "IVY-metering", + "IWD": "Inkwell Data", + "IWK": "IWK Regler und Kompensatoren GmbH", + "IYI": "KAYI ENERGY Hacettepe Üniversitesi", + "IZE": "iZenze AB", + "JAC": "Jay Autocomponents Limited", + "JAN": "Janitza electronics GmbH", + "JBF": "Beijing jingyibeifang instrument limited company", + "JCE": "Janz – Contadores de Energia SA", + "JED": "JED Co Ltd", + "JGD": "tianjin guangdaweiye measuring instrument technology Co.,Ltd", + "JGF": "Janz – Contagem e Gestao de Fluidos SA", + "JGH": "ITSQUARE CO.,LTD", + "JHA": "Zhejiang JiaHe Instrument CO.,Ltd", + "JHM": "Changzhou Jianhu Intelligentize Meter Co.,Ltd.", + "JJN": "BeiJing Fine&Clean Enery Technology Co.,Ltd", + "JKW": "QingdaoJakewill Energy Technology Co.,Ltd.", + "JMA": "Huizhou JMAO Intelligent Technology Co., Ltd.", + "JMT": "JM-TRONIC Sp. z o.o.", + "JMV": "JMV LPS NOIDA", + "JNC": "NINGBO JIANAN ELECTRONICS CO.,LTD.", + "JND": "J&D Electronics CO.,Ltd", + "JNJ": "JNJ POWERCOM SYSTEMS LTD", + "JOY": "Zhejiang Joy Electronic Technology Co., Ltd.", + "JPM": "JPM INDUSTRIES LIMITED", + "JSM": "Jining Goldwater Science&Technology Co.,Ltd.", + "JSO": "Schlösser Armaturen GmbH & Co. KG", + "JST": "JSTech Co.,Ltd.", + "JUM": "JUMO GmbH & Co. KG", + "JWH": "TIANJIN WANHUA CO.,LTD.", + "JWR": "Shandong jingwei telecommunications equipment co., LTD.", + "JWS": "Wesson energy-saving technology (tianjin) co., LTD.", + "JXH": "Jiangyin Changyi Group Co.,Ltd", + "JYS": "Beijing Jingyuan instrument limited company", + "KAA": "Kamstrup A/S", + "KAC": "АО \"КАСКАД", + "KAL": "Kallenbach Elektronik GmbH", + "KAM": "Kamstrup Energi A/S", + "KAR": "Keskar Vana Metal Mak. Ltd. Sti.", + "KAS": "Kamstrup A/S", + "KAT": "KATHREIN-Werke KG", + "KAW": "Kamstrup A/S", + "KBH": "K. Biesinger GmbH", + "KBK": "KBK ELECTRONICS (PVT) LTD.", + "KBL": "Kimbal Private Limited", + "KBN": "Alpamis IT Ltd.", + "KDN": "KADEN-VODOMĚRY, s.r.o.", + "KDS": "Kedros a.s.", + "KEA": "Kea Metering Ptd Ltd", + "KEE": "Keewe.co ltd.", + "KEL": "KELEMINIC d.o.o.", + "KER": "KERMS UG (haftungsbeschränkt)", + "KES": "Kavosh Electronic Sepahan", + "KEY": "KEYTECH ELEKTRONİK ANONİM ŞİRKETİ", + "KFM": "Shenzhen Kaifa Technology (Chengdu) Co., Ltd. / Shenzhen Kaifa Technology Co., Ltd.", + "KGE": "Guangzhou Keli General Electric Co., Ltd.", + "KHL": "Kohler", + "KIG": "Kiwigrid GmbH Kleiststraße 10a-c", + "KIT": "KONCAR-Instrument transformers Inc.", + "KJN": "Radniroo Industrial Co", + "KKE": "KK-Electronic A/S", + "KKG": "Katronic AG & Co. KG", + "KLE": "SHIJIAZHUANG KELIN ELECTRIC CO., LTD.", + "KLK": "Kerlink", + "KMB": "Kamstrup A/S", + "KMT": "Krohne Messtechnik GmbH", + "KNI": "zhangzhou keneng electrical equipment co., ltd", + "KNR": "ISCIENTIFIC TECHSOLUTIONS LABS PRIVATE LIMITED", + "KNX": "KONNEX-based users (Siemens Regensburg)", + "KPD": "Korea Electric Power Industrial Development Co., Ltd.", + "KPL": "KPLC Kenya Power", + "KRO": "Kromschroder", + "KRT": "Karat", + "KSM": "Korea Testing Certification", + "KST": "Kundo SystemTechnik GmbH", + "KSY": "KUNDO SystemTechnik GmbH", + "KTC": "Kerman Tablo Co", + "KTE": "KEYTECH ELEKTRONIK ANONIM SIRKETI", + "KTL": "Korea Testing Laboratory", + "KUK": "\"KYRGYZ UNAA KURUUSH\" LLC", + "KUL": "Kultura IoT Çözümleri ve Yönetimleri AŞ", + "KVS": "Klepsan Klape Vana ölçü aletleri San Tic Ltd Şti", + "KWH": "Zhejiang Songxia Electric Meter Co., Ltd", + "KYN": "Kayon Sp. z o.o.", + "KZK": "KŘIŽÍK s.r.o.", + "LAC": "Heinz Lackmann GmbH & Co KG", + "LAI": "Hangzhou LAISON Technology Co.,LTD", + "LAN": "Langmatz GmbH", + "LAS": "Lansen Systems AB", + "LCG": "Landis+Gyr Meter & System (Zhuhai) Co., Ltd,", + "LCR": "ShanDong LiChuang Science and Technology Co.,Ltd.", + "LDE": "Shenzhen Londian Electrics Co., Ltd.", + "LDT": "Hangzhou Laydin Technology Co.,Ltd", + "LEC": "Lectrotek Systems Pvt Ltd.", + "LEI": "PCP International Ltd", + "LEM": "LEM HEME Ltd.", + "LES": "Lakshmi Electrical Control Systems Limited", + "LET": "LAN ENGINEERING & TECHNOLOGIES", + "LFS": "Payolcer Metering Devices", + "LFX": "LoggerFlex Smart Devices Ltd.", + "LGA": "Landis+Gyr AG", + "LGB": "EYKON Limited", + "LGC": "Landis+Gyr Equipamentos de Medição Ltda, Brasil", + "LGD": "EYKON Solutions GmbH", + "LGE": "Landis+Gyr PTE Ltd.", + "LGF": "EYKON Oy", + "LGG": "Ningxia LGG Instrument Co., LTD", + "LGI": "Landis+Gyr Ltd.", + "LGS": "EYKON Utility Solutions (Pty) Ltd.", + "LGU": "LG Uplus Corp.", + "LGZ": "EYKON AG", + "LHA": "Atlantic Meters", + "LIN": "Ever Meter Co., Ltd", + "LIQ": "Lianqiao Technology Co.Ltd", + "LIT": "Punos Electronic AB", + "LJP": "Lars Jansen Productions", + "LLM": "LianYunGang LianLi·First Meter CO. LTD.", + "LMC": "Lumacol s.r.o.", + "LMG": "Luftmeister GmbH", + "LML": "LUMEL", + "LMP": "LIN MAN POWER TECHNOLOGY,INC.", + "LMS": "LMS Services GmbH", + "LNC": "Lancier Monitoring GmbH", + "LNK": "Loenk F9", + "LNT": "Schneider Electric India Private Limited", + "LOB": "Lobaro GmbH", + "LOG": "LOGAREX Smart Metering, s.r.o.", + "LOV": "Lovato Electric S.p.A.", + "LQT": "Lianqiao Technology Co.Ltd", + "LRS": "AMCJ Sp. z o. o.", + "LSC": "Lund Science AB", + "LSE": "Landis & Staefa electronic", + "LSK": "LS Industrial Systems Co Ltd.", + "LSP": "EYKON Solutions GmbH", + "LSZ": "Siemens Building Technologies", + "LTO": "Labtrino AB", + "LUG": "EYKON Solutions GmbH", + "LUN": "LUNA Elektrik Elektronik A.S.", + "LUP": "LUPUS Electronics GmbH / LUPUS-Electronics GmbH", + "LWT": "Lotus Wireless Technologies India Private Limited", + "LYE": "Jiangsu Linyang Electronics Co. Ltd.", + "LYN": "Les Pépites & Co", + "LZG": "Lackmann Zähler Gesellschaft mbH & Co. KG", + "MAC": "RUDNAP Group Meter & Control", + "MAD": "Maddalena S.p.A.", + "MAE": "Mates Elektronik Metin Ates", + "MAG": "MAGNATECH Smart Grid Solutions Pvt. Ltd.", + "MAH": "MAHAM ELECTRONIC SAMA SANAT", + "MAN": "Manthey GmbH", + "MAS": "Master Meter Teknoloji", + "MAT": "Mitsubishi Electric Automation", + "MAX": "MAXMET Inc", + "MBH": "MBH POWER GHANA LIMITED", + "MBS": "MBS AG", + "MCI": "METERING AND COMMUNICATIONS SOLUTIONS PRIVATE LIMITED", + "MCP": "MPSE", + "MCR": "MICRORISC", + "MCS": "MetCom Solutions GmbH", + "MCV": "SOCIÉTÉ MAROCAINE DES COMPTEURS -SMCV", + "MCX": "MCX-PRO Kft.", + "MDA": "PT.MELCOINDA", + "MDE": "Diehl Metering", + "MDL": "Maddalena S.p.A.", + "MDT": "Minnotra Energy India Pvt Ltd", + "MDX": "mdex AG", + "MEC": "Mitsubishi Electric Corporation", + "MED": "MAHARASHTRA STATE ELECTRICITY DISTRIBUTION COMPANY LIMITED", + "MEE": "Metron Europe", + "MEH": "Mueller-electronic GmbH", + "MEI": "Sensus Metering Systems", + "MEL": "Mikroelektronika a.d", + "MEM": "MEMS AG", + "MEP": "Electro Tajhiz Daghigh Mana Co.", + "MES": "Electrometer Spain S.L.U.", + "MET": "METRA Energie-Messtechnik GmbH", + "MEX": "Metrix Italia s.r.l.", + "MHT": "Mechatronic Meters srl", + "MIC": "Microtronics Engineering GmbH", + "MID": "MiDo Srl", + "MII": "Apator Miitors ApS", + "MIJ": "MAXWELL INDIA", + "MIK": "Mikroklima s.r.o.", + "MIL": "Milur Smart System Limited liability company", + "MIM": "Malaysian Intelligence Meters Sdn. Bhd.", + "MIO": "Metiundo GmbH", + "MIR": "MIR Research and Production Association", + "MIS": "Iskra MIS d.d", + "MIT": "Sagemcom Energy & Telecom", + "MIV": "MIVO Technology AB", + "MKA": "mirakonta", + "MKE": "MKEK Genel Mudurlugu Gazi Fisek (ELSA)", + "MKL": "MAKEL Elektrik Malzemeleri", + "MKS": "MAK-SAY Elektrik Elektronik", + "MLQ": "MeterLinq", + "MLR": "PKK Milandr", + "MMC": "Modern Meters Co.", + "MMF": "MEMF Electrical Industries Co.", + "MMI": "MyMeterInfo", + "MMM": "MATRICA Ltd", + "MMP": "MATRIXMETERS PVT. LTD.", + "MMS": "Brunswick Bowling and Billiards UK Ltd", + "MMT": "METMOTEC", + "MNS": "MANAS Elektronik", + "MNT": "Mennet Enerji AŞ", + "MNW": "MENOWATT GE SRL", + "MOJ": "Mojec International", + "MOS": "MOMAS SYSTEMS NIGERIA LIMITED", + "MOT": "The Motwane Manufacturing Company Private Limited", + "MPA": "Mega Power Automation International Limited", + "MPL": "Metrona Polska Pomiary i Rozliczenia sp. z o.o.", + "MPR": "Michael Rac GmbH", + "MPS": "Multiprocessor Systems Ltd", + "MRB": "Jakub Chrzaniuk", + "MRN": "LLC \"RPC \"MEtRON", + "MRT": "MIRTEK LTD.", + "MSB": "MISA SDN BHD", + "MSC": "TECHSTUDIO Arge ve Tasarım Sanayi LTD. ŞTİ.", + "MSE": "Mahashakti Energy Limited", + "MSI": "MIC ELECTRONICS LIMITED", + "MSM": "MS-M Co., Ltd.", + "MSO": "Metiso", + "MST": "Microsoft Taiwan Corporation", + "MSY": "MAK-SAY Elektrik Elektronik Malzemeleri", + "MTC": "Metering Technology Corporation", + "MTD": "Removed - November 2006", + "MTE": "The Egyptian German Co. for Water Meter Manufacturing (Metrotec Egypt)", + "MTG": "Nanjing Meter Technology Co., Ltd.", + "MTH": "njmeter", + "MTI": "Microtech Industries Pakistan", + "MTL": "Advance Metering technology Limited", + "MTM": "Metrum Sweden AB", + "MTN": "Merytronic 2012,S.L", + "MTP": "Modern Transformers Pvt. Ltd.", + "MTR": "METER", + "MTS": "MeteRSit S.r.L.", + "MTT": "PT Metalindo Teratai Putra", + "MTX": "Matrix Energy Pvt. Ltd.", + "MUK": "Meters UK Ltd, Whitegate, White Lund Trading Estate", + "MWI": "Magic Wand Intelligent Systems", + "MWU": "METRONA Union GmbH", + "MXE": "Hangzhou MingX technology Co.,LTD", + "MXM": "Maxim India Integrated Circuit Design Pvt Ltd.", + "MYS": "MODEMSYS S.L.", + "NAE": "Nanjing NengRui Automation Equipment Co., LTD.", + "NAG": "Networked Energy Services AG", + "NAR": "NARI Group Corporation-NARI Technology Development Co., Ltd", + "NAS": "NAS Instruments OÜ", + "NAT": "Natural Heat Ahorro Energetico SL", + "NCK": "NC Korea", + "NDF": "NÚCLEO DURO FELGUERA", + "NDM": "Northern Design", + "NEE": "Northern Electric Equipment Joint Stock Company", + "NEI": "NEWLECTRIC INNOVATION PRIVATE LIMITED", + "NEO": "NeoVac", + "NER": "Nero Electronics Ltd", + "NES": "NORA ELK. MALZ. SAN. ve TİC. A.Ş.", + "NET": "Netatmo", + "NEX": "Nexelec", + "NGP": "Ngenic Poland Sp. z o.o.", + "NIK": "NIK-ELEKTRONIKA", + "NIS": "Nisko Industries", + "NJC": "NAMJUN Co Ltd", + "NKS": "N-ERGIE Kundenservice GmbH", + "NLI": "Next Level Integration GmbH", + "NME": "SI-ART LLC", + "NMG": "NMG S.A.", + "NMS": "Nisko Advanced Metering Solutions", + "NMT": "Nova-met s.r.o.", + "NNT": "2N Telekomunikace a.s.", + "NOI": "NOITAC sp. z o.o. sp.k.", + "NOQ": "NorthQ", + "NOV": "NovaTech LLC", + "NPL": "CSIR-National Physical Laboratory", + "NPS": "NEOPIS CO., LTD 4F", + "NPT": "CJSC PROGTECH", + "NRM": "Norm Elektronik", + "NRN": "Neuron AG", + "NRT": "Zavod Nartis Ltd.", + "NSE": "North Smart Equipment Co., Ltd", + "NSN": "NARI-TECH Sanneng Instrument (Nanjing) Co., Ltd", + "NSP": "M/S N S Power", + "NTC": "Nuri Telecom Co Ltd", + "NTM": "Netinium", + "NTT": "NTT DATA Italia S.p.A.", + "NUD": "Nudron IoT Solutions LLP", + "NVD": "METER Ltd", + "NVN": "NOVEN ENERGY AND ICT LTD.", + "NWG": "NINGBO WASSER GERAETE CO.,LTD.", + "NWM": "Ningbo Water Meter Co.Ltd.", + "NXG": "nexgen consultancy pvt ltd", + "NXP": "NXP Semiconductors", + "NYG": "Ningbo Yonggang Instrument Co. Ltd.", + "NYN": "Nanjing Yuneng Instrument Co Ltd.", + "NZR": "Nordwestdeutsche Zählerrevision Ing. Aug. Knemeyer GmbH & Co. KG", + "OAS": "Omni Agate Systems", + "OBC": "shandong oubiao information Technology. LTD", + "OBE": "Obeo as", + "OBR": "RMZ OBRIY LTD", + "ODI": "OAS Digital Infrastructures Pvt. Ltd.", + "ODK": "Okinawa Denki Kogyo Co.,Ltd.", + "OEE": "ONUR Elektrik ve Elektronik", + "OJA": "ELECTRICAL CIRCUIT BREAKER FACTORY FOR INDUSTRY-ECB", + "OKN": "be.storaged", + "OLI": "Olivetti S.p.A.", + "OMG": "Open Metering System Group – OMS-Group e. V.", + "OMS": "OMNISYSTEM Co., Ltd.", + "ONE": "Omnicore Stratejik Teknolojiler Ltd. Sti.", + "ONR": "ONUR Elektroteknik", + "ONS": "ONUR Elektroteknik", + "OPT": "Optec GmbH", + "ORB": "ORBIS Tecnologia Electrica, SA", + "ORM": "Ormazabal", + "ORN": "Orion System LLP", + "OSA": "Osaki Electric Co., Ltd.(Europe)", + "OSB": "Ocea Smart Building", + "OSC": "Oriental Sales Corporation", + "OSK": "Osaki Electric Co Ltd. (Japan)", + "OSV": "Onstar Venture Pvt Ltd", + "OTM": "OTMetric", + "OTS": "Shenzhen Oasis Technology Service Co., Ltd", + "OYK": "GULLWING(TIANJIN)INDUSTRY DEVELOPMENGT CO.,LTD.", + "OZK": "Oz-kar Enerji", + "PAD": "PadMess GmbH", + "PAF": "FAP PAFAL S.A.", + "PAI": "PAIBOONKIJTHANA CO.,LTD", + "PAK": "Paktim Energy Sp.zo.o.", + "PAN": "Panasonic Corporation", + "PBR": "PFIFFNER do Brasil", + "PCE": "Precise Electronics co.,LTD.", + "PCI": "POLYCAB INDIA LIMITED", + "PCR": "Powercom", + "PDE": "Pfiffner Deutschland GmbH", + "PDX": "Paradox Engineering SA", + "PEA": "PEA J.V. Company", + "PEE": "Prantech Energy Solutions", + "PEL": "Pak Elektron Ltd. (PEL)", + "PEM": "peerMetering GmbH", + "PEP": "POWRTEC ENERGY PVT. LTD.", + "PER": "Perry Electric", + "PES": "PES Electrical Pvt Ltd", + "PFI": "PFIFFNER Instrument Transformers Ltd", + "PGE": "PayGo Energy, Inc", + "PGP": "P.G.P. - Smart Sensing s.a.", + "PHL": "HangZhou PAX Electronic Technology Co., Ltd.", + "PHX": "Phoenix Systems sp z o.o.", + "PII": "PiiGAB Processinformation i Goteborg AB", + "PIK": "pikkerton GmbH", + "PIL": "Pilot Systems (London) Ltd", + "PIM": "Power Innovation GmbH", + "PIN": "PFIFFNER Instr. Transformers private", + "PIP": "Hermann Pipersberg jr.", + "PIV": "Pivot Access Ltd.", + "PLL": "POLL, s.r.o.", + "PLN": "Prolan Process Control Company", + "PLO": "Weihai Ploumeter Co. Ltd.", + "PLU": "Plutus Smart Energy Solutions Pvt. Ltd.", + "PME": "Pal Mohan Electronics Pvt Ltd", + "PMG": "Sensus Metering Systems", + "PML": "PROGRESSIVE METERS PVT LTD.", + "PMP": "REDUR GmbH & Co. KG", + "PMS": "PMS-Elektronik GmbH", + "PMX": "Dell`Anna Ing. Luca", + "PNC": "PNC Technology Co., Ltd", + "PNG": "PAKTIM METERING NIGERIA LTD", + "POD": "PowerOneData", + "POL": "Pronal Sp. z o.o. sp.k.", + "POW": "PowerApp", + "POZ": "ZEUP Pozyton sp. z o.o.", + "PPC": "Power Plus Communications AG", + "PPL": "Prompribor plant Limited", + "PPS": "Palace Power Systems", + "PQP": "PQ Plus GmbH", + "PRA": "Paya Ravesh Aria", + "PRE": "Predicate Software", + "PRG": "Paud Raad Industrial Group", + "PRI": "Polymeters Response International Ltd.", + "PRM": "Promatic d.o.o.", + "PRO": "Proton - Elektromed Ltd", + "PRY": "ShanDong LiChuang Science and Technology Co.,Ltd.", + "PSC": "PS Tec Co.,Ltd.", + "PSE": "pSenso sp. z o.o.", + "PSN": "PySENSE Sp. z o.o.", + "PSS": "Part Sanat Sanjesh", + "PST": "PS Tec Co., Ltd.", + "PSY": "PIKK-Systems GmbH", + "PTA": "PT. Alinco", + "PTI": "Prolific Technology Inc.", + "PTR": "Pfiffner Transformatör A.S.", + "PUK": "Paktim Consulting UK Ltd", + "PUL": "NPP Teplovodokhran Ltd", + "PVT": "Pavo Tasarım Üretim Elektronik Tic. A.Ş.", + "PWB": "Paul Wegener GmbH", + "PWR": "Powrtec", + "PXC": "Phoenix Contact GmbH & Co. KG", + "PYU": "PYUNGIL Co. Ltd", + "PYX": "Pyrexx GmbH", + "QDR": "Quadrar Tecnologia", + "QDS": "Qundis GmbH", + "QFP": "QFP Engineering", + "QLE": "Quickline Energy AG", + "QSD": "Quicksand", + "QTS": "QT systems ab", + "RAC": "Michael Rac GmbH", + "RAD": "Radiocrafts AS", + "RAM": "Rossweiner Armaturen und Messgeräte GmbH & Co. OHG", + "RAS": "Rubikon Apskaitos Sistemos", + "RAY": "Rayleigh Instruments Limited", + "RBM": "R.B.M. S.p.A", + "RCE": "RC ENERGY METERING PVT,LTD.", + "RDK": "Wuhan Radarking Electronics Corp.", + "RDM": "RDMx Consulting", + "REC": "Zhejiang Reallin Electron Co. Ltd.", + "REF": "REFERANS ELEKTRIK SAYACLARI A.S.", + "REI": "RENESAS ELECTRONICS INDIA PRIVATE LIMITED", + "REL": "Relay GmbH", + "REM": "Remote Energy Monitoring", + "REP": "Radiant Energy Solutions Pvt Ltd", + "RES": "Renesas Electronics Singapore Pte Ltd", + "RFC": "Shenzhen Friendcom Technology Co., Ltd.", + "RHN": "Rhino", + "RIC": "Richa Equipments Pvt. Ltd.", + "RIL": "Rikken Instrumentation Limited", + "RIM": "CJSC \\\"Radio and Microelectronics\\\"", + "RIN": "Rayleigh Instruments Ltd", + "RIT": "Ritz Instrument Transformers GmbH", + "RIX": "Raonix Co., Ltd.", + "RIZ": "RIZ Transmitters", + "RKD": "Ramakrishna Electro Components Pvt Ltd", + "RKE": "Viterra Energy Services (formerly Raab Karcher ES)", + "RMA": "Mess- und Regeltechnik GmbH & Co. KG", + "RMG": "RMG Messtechnik GmbH", + "RMI": "Racemosa Energy India Pvt Ltd", + "RML": "ROLEX METERS RPIVATE LIMITED", + "RMR": "Advanced Technology RAMAR", + "RMT": "Richter Messtechnik GmbH & Co.KG", + "RNW": "Renergy Micro-Technologies", + "ROK": "“ROKIP” Limited Liability Company", + "RSA": "Rahrovan Sepehr Andisheh Pte. Co.", + "RSM": "Zhejiang Risesun Science and Technology Co.,Ltd.", + "RSW": "RSW Technik GmbH", + "SAA": "Sanjesh Afzar Asia Ltd. Co.", + "SAC": "SACOFGAS srl", + "SAE": "SAE IT-systems GmbH & Co. KG", + "SAG": "Sagemcom Energy & Telecom", + "SAL": "Salzer Electronics Limited", + "SAM": "Siemens AG Österreich, AMIS (Automated Metering and Information System)", + "SAN": "SANN Stockholm AB", + "SAP": "Diehl Metering", + "SAT": "SATEC Ltd", + "SBC": "Saia-Burgess Controls", + "SBP": "Schuberg Philis", + "SCA": "SENECA srl", + "SCE": "Seo Chang Electric Communication Co Ltd", + "SCH": "Schinzel GmbH", + "SCL": "Steama Company Limited", + "SCM": "CalinMeter Co. ltd.", + "SCR": "Sanchuan Wisdom Technology Co., Ltd.", + "SCT": "S.I.C.E. Telecomunicazioni Srl", + "SCW": "ScatterWeb GmbH", + "SDC": "SdC – Sistemas de Contagem", + "SDM": "Shandong Delu Measurement Co., Ltd.", + "SDN": "Sagemcom Dr. Neuhaus GmbH", + "SDS": "Sitec s.r.l Elettronica industriale", + "SEC": "Schneider Electric Canada", + "SED": "SenseMi DMCC", + "SEE": "El Sewedy Electrometer Egypt", + "SEG": "SenseMi DMCC", + "SEH": "SAMRAKSHANA ELECTRICALS LTD", + "SEI": "Sicom Electronics International S.A.", + "SEK": "StroyEnergoKom Ltd.", + "SEL": "Selec Controls Pvt Ltd", + "SEM": "Smart Meter Company Limited", + "SEN": "Sensus Metering Systems", + "SEO": "SENSOCO Greatech GmbH", + "SES": "SenseMi DMCC", + "SET": "Sagemcom Energy & Telecom", + "SEW": "SenseMi DMCC", + "SFE": "WUHAN SANFRAN ELECTRONICS CO., LTD.", + "SFI": "Siemens AG - DI PA MI", + "SFR": "WUHAN SANFRAN ELECTRONICS CO., LTD.", + "SFT": "Sotflink s.r.o", + "SGA": "smartGAS Mikrosensorik GmbH", + "SGI": "Smartgrid Innovations Pvt Ltd", + "SGM": "Swiss Gas Metering AG", + "SGN": "SYGNITY S.A.", + "SGT": "SAGATEC LTDA", + "SGX": "Gao Xiang Water Meter Co. Ltd.", + "SHD": "Beijing SanHuaDeBao Energy Technoligy Co.,Ltd.", + "SHE": "Shenzhen SingHang Elec-tech Co., Ltd.", + "SHM": "Shanghai Metering, China", + "SHT": "Shitek Technology srl", + "SIC": "SICK Engineering GmbH", + "SIE": "Siemens AG", + "SIG": "Sigrenea", + "SIJ": "SUN STAR INDUSTRIES", + "SIL": "Silicon Laboratories", + "SIM": "Sana Intelligent Meter", + "SIN": "SINAPSI SRL", + "SIS": "Sevme Informatique Service", + "SIT": "SITEL doo", + "SIV": "Sieverding Heizungs- und Sanitaertechnik GmbH", + "SIX": "Six Innovation AB", + "SJA": "Sheng Jay Automation Technologies Co., Ltd.", + "SKI": "S.K.I. GmbH", + "SKK": "Shikoku Instrumentation Co.,Ltd.", + "SKN": "BENTEX CONTROL AND SWITCH GEAR CO.", + "SKQ": "SKI( sherkate kontorsazi Iran)", + "SKT": "SkyToll a.s.", + "SKY": "SKYLARK SMARTMETERS PVT LTD", + "SLB": "Schlumberger Industries Ltd.", + "SLG": "Silergy Technologies", + "SLP": "Sylop spółka z ograniczoną odpowiedzialnością sp.k.", + "SLV": "Solvimus GmbH", + "SLW": "SOLID WAY SAS", + "SLX": "Ymatron AG", + "SMA": "Smart-me AG", + "SMC": "Sierra Monitor Corporation", + "SME": "Siame", + "SMF": "Star Measure", + "SMG": "Samgas s.r.l.", + "SMI": "PT. SMART METER INDONESIA", + "SML": "Siemens Measurements Ltd.", + "SMM": "Smart Metering S.r.l.", + "SMN": "Saiman Corporation LLC", + "SMP": "LLC FIRM SEMPAL CO LTD", + "SMQ": "SMARTMETERQ srl", + "SMR": "Saudi Meters Company Ltd", + "SMS": "Smart Metering Solutions (Changsha) Co. Ltd.", + "SMT": "Smarteh d.o.o.", + "SMV": "Société Marocaine des Compteurs", + "SMX": "Smart Meters Technologies Sdn Bhd", + "SNB": "Stromnetz Berlin GmbH", + "SNM": "ShenZhen Northmeter Co.Ltd", + "SNR": "NTN-SNR", + "SNS": "Signals and Systems India Private Limited", + "SNT": "SensorNet s.r.l.", + "SOC": "SOCOMEC", + "SOF": "Softflow.de GmbH", + "SOG": "Sogecam Industrial, S.A.", + "SOL": "Soledia Srl", + "SOM": "Somesca", + "SON": "Sontex SA", + "SOS": "SOFTSERVICE", + "SOT": "Sotronix", + "SPC": "JSC RPC Spektr", + "SPE": "SUKHILA POWER ELECTRONICS PVT LTD", + "SPL": "Diehl Metering", + "SPM": "Stelmec Powercom Private Limited", + "SPX": "Sensus Metering Systems", + "SPZ": "SPowerZ Solutions Pvt Ltd", + "SRE": "Guangzhou Sunrise Electronics Development Co., Ltd.,", + "SRF": "Saraf Industries", + "SRI": "M K SRINIVASAN SYSTEMS PVT LTD", + "SRN": "Shandong SARON Intelligent Technology Co., Ltd.", + "SRV": "Servic LLC", + "SSE": "S&T Smart Energy GmbH", + "SSG": "Super Star Electronics Limited", + "SSI": "Security Solutions Institute LTD", + "SSL": "Synapsys Solutions Ltd.", + "SSM": "SCC METERS LTD.", + "SSN": "Silver Spring Networks", + "SSS": "SUEZ SMART SOLUTIONS", + "SST": "Qingdao Haina Electric Automation Systems Co., Ltd.", + "STA": "Shenzhen Star Instrument Co Ltd", + "STC": "Sunrise Technology Co., Ltd", + "STD": "Stedin B.V", + "STE": "Satera Elektrik Elektronik San. ve Tic. A.S.", + "STF": "STACKFORCE GmbH", + "STH": "Santech Sp. z o.o.", + "STL": "Saudi Technical Group", + "STM": "STELMEC LTD", + "STN": "Hunan Stron Smart Co., Ltd.", + "STO": "ABB STOTZ-KONTAKT GmbH", + "STP": "Spectrum Tool Engineers Pvt, Ltd.", + "STR": "Strike Technologies", + "STS": "Swistec Systems AG", + "STV": "STV Automation, Branch of STV Electronic", + "STW": "Siterwell Electronics CO. Limited", + "STZ": "Steinbeis Innovation Center Embedded Design and Networking", + "SUL": "SINHAL UDYOG PRIVATE LIMITED", + "SUM": "Sumeru Verrdhe Technologies Pvt Ltd", + "SUN": "TIAN JIN SUN ENERGY TECHNOLOGY CO. LTD.", + "SUP": "SUPERMAX COMPONENTS PVT LTD", + "SUX": "Supermax Components Pvt Ltd", + "SVM": "AB Svensk Värmemätning SVM", + "SVT": "SPUTNIK", + "SWI": "Swistec GmbH", + "SWM": "Smart Water Metering Inc.", + "SWS": "Stadtwerke Senftenberg GmbH", + "SWT": "Beijing Swirling Technology Co. Ltd", + "SYC": "Sycous Limited, Leeds Innovation Centre", + "SYD": "Sydler Electronics Pvt Ltd", + "SYN": "SMSISTEM Ltd.", + "SYR": "SAYRON GLOBAL ENERJİ A.Ş", + "SYS": "Softwareentwicklung & Systemdesign", + "SYX": "SyxthSense Ltd", + "SZS": "Szerver Szektor Kft.", + "SZZ": "Test Company (new) Ltd.", + "TAG": "Telma AG", + "TAL": "TALAMONA S.r.l.", + "TAN": "Tianxin instrument group co. LTD", + "TAS": "Pouyeshgaran Tabriz Azma", + "TAT": "Tatung Co.", + "TAU": "TARGUS TECHNOLOGIES PVT. LTD.", + "TAY": "Taytech Otomasyon ve Bilisim Teknolojileri LTD. Sti", + "TAZ": "PoyeshGaran Sahandzaran Tabrizazma", + "TBN": "TBEA Nanjing Intelligent Electric Co., Ltd.", + "TBS": "TEBAŞ END. ISI SİS İNŞ TUR SAN VE TİC LTD ŞTİ", + "TCE": "Qingdao iTechene Technologies Co., Ltd.", + "TCH": "Techem", + "TCM": "TCOM doo", + "TCO": "Teco a.s.", + "TCP": "Telecard-Prilad LLC", + "TCT": "Tecnotel Srl", + "TCX": "Qingdao Topscomm Communication Co.,Ltd", + "TCZ": "Tianjin Chuangzhan Tongcheng Technology Development Co.,Ltd.", + "TDC": "Telecom Design", + "TEA": "TEAM-R", + "TEC": "TECSON Digital", + "TEH": "IOTech LTD", + "TEI": "Tohoku Electric Meter Industry Co.,Inc.", + "TEK": "Tekmar Regelsysteme GmbH", + "TEL": "TURBO ENERGY LIMITED", + "TEN": "TekhnoEnergo LLC", + "TEO": "ubitricity Gesellschaft für verteilte Energiesysteme mbH", + "TEP": "TEPEECAL", + "TER": "Tavrida Electric Russia", + "TEU": "TOSHELECTROAPPARAT LLC FE", + "TFC": "Toos Fuse Co.", + "TFG": "TERMICS s.r.l. Divisione FIMIGAS", + "TGX": "Tiesse Spa", + "THA": "M A S ELECTRIC (THAI) CO.,LTD", + "THE": "Theben AG", + "THS": "JOZI 2009 Ltd.", + "THW": "TW-TEAMWARE", + "TIC": "TOKYO KEISO CO.,LTD.", + "TID": "TIDE Co.,Ltd", + "TIG": "ZHONGHUAN-TIG CO.,LTD", + "TII": "Pal Mohan Electronics Pvt Ltd / TRIKALA INDUSTRIES INDIA PVT LTD", + "TIL": "Thermal Integration Limited", + "TIP": "TIP GmbH", + "TIS": "Texas Instruments (Hong Kong) Ltd.", + "TIX": "Tixi.Com GmbH", + "TKK": "TOYOKEIKI CO., LTD.", + "TKN": "TECHKNAVE", + "TKS": "Teksan Teknolojik Ölçüm Sistemleri A.Ş.", + "TLC": "TELECON GALICIA,S.A.", + "TLM": "Theodor Lange Messgeräte GmbH", + "TLR": "Telereading srl", + "TLS": "TLS Energimätning AB", + "TLT": "Telecommunication Technologies LLC", + "TLY": "LLC «SPE» Telemetry»", + "TME": "TECHNO METERS & ELECTRONICS", + "TMK": "Timi Kosova Sh.p.k.", + "TMS": "TEMASS IMALAT A.S", + "TMZ": "TMZ - Thüringer Mess- und Zählerwesen Service GmbH", + "TNT": "Deltamess DWWF GmbH", + "TOE": "Top For Electrical Industries", + "TOP": "KMB systems, s.r.o.", + "TPB": "2 Plus Bulgaria AD", + "TPC": "Taipit - measuring equipment", + "TPG": "Texnopark", + "TPI": "Transfopower Industries (Pvt.) Ltd.", + "TPJ": "TAKAHATA PRECISION JAPAN CO., LTD.", + "TPL": "Teplocom Holding", + "TPZ": "PLC Technology", + "TRC": "Traco Doo", + "TRF": "Transforat", + "TRG": "Trench Germany GmbH", + "TRI": "Tritech Technology AB", + "TRJ": "SHENZHEN TECHRISE ELECTRONICS CO.,LTD", + "TRL": "Trilliant Inc.", + "TRN": "TERRANOVA SRL", + "TRO": "TROX GmbH", + "TRU": "Truteq Wireless", + "TRV": "Transvaro Elektron Aletleri A.S.", + "TRW": "Triowatt GmbH", + "TRX": "Beijing TianRuiXiang Equipment Co.,Ltd.", + "TRZ": "TR Group (Pty) Ltd", + "TSD": "Theobroma Systems Design und Consulting GmbH", + "TSE": "Nichi Manufacturing Pvt. Ltd.", + "TSG": "Testo Sensor GmbH", + "TSM": "Tatung Smart Meter CO., LTD.", + "TSW": "T7 WENMAX SDN. BHD.", + "TTG": "Tatung Co.", + "TTM": "Toshiba Toko Meter Systems Co., Ltd.", + "TTN": "Tatung Co.", + "TTR": "Tetraedre Sarl", + "TTT": "Telephone and Telegraph Technique Plc", + "TUR": "TURKSAY ELEKTRONIK ELEKTRIK ENDUSTRISI", + "TWO": "2Flow AB", + "TXL": "CETC46 TianJin New Top Electronics Technology Co.,Ltd.", + "TYK": "TOYOKEIKI CO., LTD.", + "UAG": "Uher", + "UBI": "Ubitronix system solutions gmbh", + "UBY": "ubitricity - Gesellschaft für verteilte Energiesysteme mbH", + "UEI": "United Electrical Industries Limited", + "UEL": "united electrical industries ltd", + "UGI": "United Gas Industries", + "UGT": "DP UKRGAZTECH Ltd. (Ukrainian gas technologies)", + "UHM": "Micronics Ltd.", + "ULP": "LITR ENERGY GROUP LLC", + "UNI": "Univations Limited", + "UNM": "UniMetric d.o.o.", + "UPS": "UMA POLY SOLUTIONS PRIVATE LIMITED", + "URM": "Urmet Telecomunicazioni SPA", + "USC": "Usanca Soluciones S.L.", + "UTF": "UtiliFlex", + "UTI": "Utilia Spa", + "UTL": "United Telecoms Limited", + "UTS": "UNIQUE TECHNOSOLUTIONS PRIVATE LIMITED", + "UTT": "UtiliTools GmbH", + "UZM": "YANGI ASR INOVATSIYA", + "VAI": "Shete Advanced Technologies Pvt Ltd", + "VAL": "Valkoder OOD", + "VAR": "VARAAHI ELECTROMECH PRIVATE LIMITED", + "VDP": "Plant Vodopribor management company", + "VEC": "Energo Control LLC", + "VEL": "VELANKANI ELECTRONICS PRIVATE LIMITED", + "VEN": "INVENDIS TECHNOLOGIES INDIA PVT LTD", + "VER": "VERAUT GmbH", + "VES": "Viterra Energy Services", + "VEX": "Vertex Electronics (Pvt) Ltd.", + "VFS": "Semas d.o.o.", + "VGO": "Vango Technologies, Inc.", + "VIE": "Vientech", + "VIK": "VI-KO ELEKTRIK", + "VIM": "VİEN ENERJİ SİSTEMLERİ SANAYİ VE TİCARET LİMİTED ŞİRKETİ", + "VIN": "Vektor innovations private limited", + "VIP": "VIPA CZ s.r.o.", + "VIT": "Vitir AS", + "VLT": "ABB s.r.o., EPMV Division", + "VMP": "VAMP Oy.", + "VNE": "Vision Networks", + "VPI": "Van Putten Instruments B.V.", + "VPL": "Verticross India Private Limited", + "VSE": "Valenciana Smart Energy of Mediterranean Sea S.A", + "VSN": "Viewshine Ltd.", + "VTC": "Vitelec", + "VTG": "vemm tec Messtechnik GmbH", + "VTK": "Linkwell Telesystems Pvt. Ltd.", + "VTN": "VITEX NOVA", + "VTZ": "VitzroSys Co., Ltd.", + "VVV": "VIVAVIS AG", + "WAD": "Waher Data AB", + "WAH": "WAHESOFT UG", + "WAI": "Chongqing WECAN Precision Instruments Co.,Ltd.", + "WAL": "Wallaby Metering Systems Pvt. Ltd.", + "WDN": "Webdyn SA", + "WEB": "Webolution GmbH & Co. KG", + "WEG": "WEG Equipamentos Elétricos S.A. – Automação", + "WEH": "E. Wehrle GmbH", + "WEL": "WELLTECH automation", + "WEP": "Weptech elektronik GmbH", + "WFT": "Waft Embedded Circuit Solutions", + "WGN": "Wasser-Geräte GmbH", + "WGP": "GreenPoint sp. z o.o.", + "WHU": "Wasion Hungary Kft.", + "WIG": "Wigersma & Sikkema", + "WIK": "WIKON Kommunikationstechnik GmbH", + "WIN": "Windmill Innovations BV", + "WKL": "Shenyang jia DE lian yi energy technology co., LTD", + "WKX": "JINING WUKEXING METER CO. LTD.", + "WLX": "Wallox elektronik AB", + "WMI": "Weidmueller", + "WMO": "Westermo Teleindustri AB", + "WNC": "wireless-netcontrol GmbH", + "WNW": "Wistron NeWeb Corporation, Marketing Center", + "WOW": "Sciknow Techno Solutions Ltd", + "WPZ": "Weepiez SaS", + "WRE": "Waaree Smart Meters Private Limited", + "WSD": "Yantai Wisdom Electric Co., Ltd.", + "WSE": "Wasion Group Co.Ltd", + "WSG": "ZHEJIANG WELLSUN INTELLIGENT TECHNOLOGY CO., LTD", + "WSM": "winAMR Systems Private Limited", + "WSR": "OOO WESER", + "WTI": "Weihai Sunts Electric Meter Co., Ltd.", + "WTL": "Wipro Technologies", + "WTM": "Watertech S.r.l.", + "WTT": "Watertech S.r.l.", + "WUR": "Wurm GmbH & Co. KG Elektronische Systeme", + "WZG": "Neumann & Co. Wasserzähler Glaubitz GmbH", + "WZT": "Wizit Co. Ltd.", + "XAO": "Info Solution SpA", + "XEE": "XEE Technology GmbH", + "XEM": "XEMTEC AG", + "XIO": "XIOTA India Pvt. Ltd", + "XJM": "XJ Metering Co. Ltd.", + "XLG": "X-LOGIC d.o.o", + "XMA": "XMASTER s.c. ul.", + "XMX": "Xemex NV", + "XPP": "XYROSYS PVT LTD", + "XTM": "Suntront Tech Co. Ltd.", + "XTR": "HENAN SUNTRONT TECH CO. LTD.", + "XTY": "LianYuanGang Tengyue Electronics & Technology Co. Ltd.", + "XYL": "Sensus GmbH Ludwigshafen", + "XYM": "Ningbo Xingyuan Meter Technology Co.,Ltd", + "YAW": "Yawgi Smart Technology Sarl", + "YDD": "Jilin Yongda Group Co. Ltd.", + "YDS": "YIDU Smart Technology ( Beijing ) Co. Ltd.", + "YEM": "KYENM TECH PVT LTD", + "YFC": "Yufeng Changhui Automation Instrument Co. Ltd.", + "YGM": "YGM, Shandong Yiguang heat metering technology CO. LTD.", + "YHE": "Youho Electric Co. Ltd.", + "YHF": "Hebei Haifeng Electronic Technology Co.", + "YJZ": "Zhuhai Yujian Science & Technology Co., Ltd", + "YNE": "YOONO ENERGY TECHNOLOGY (JIANGSU) CO., LTD.", + "YNP": "Ningbo Yong Neng Power Technology Co. Ltd.", + "YPP": "YPP Corp", + "YPW": "PT POWINT ELECTRIC INDONESIA", + "YSS": "Yellowstone Soft", + "YTE": "Yuksek Teknoloji", + "YTL": "ZheJiang yongtailong electronic co.,ltd.", + "YYW": "Shandong youyuan instrument co. LTD", + "YZR": "Cangzhou City Hebei Electronic Technology Co. Ltd.", + "ZAG": "Zellweger Uster AG", + "ZAP": "Zaptronix", + "ZAR": "SNC ZARALAB", + "ZCH": "Zhejiang Chaorong Electric Technology Co., Ltd", + "ZCU": "Suzhou Dojustek Intelligent Technology Co.,Ltd.", + "ZEL": "Dr. techn. Josef Zelisko GmbH", + "ZEN": "ZenMeter Solutions Pvt. Ltd.", + "ZEX": "ZEXON ENERGY PRIVATE LIMITED", + "ZFY": "Hang Zhou Fu Yang Instrument General Factory", + "ZGX": "ZIGNUX TECHNOLOGY S.L.", + "ZIP": "St. Petersburg Meters\\` Factory Co., Ltd.", + "ZIV": "ZIV Aplicaciones y Tecnologia, S.A.", + "ZJY": "Zhejiang Jiayou Thermal Technology Equipment Co. LTD.", + "ZLW": "Ningbo ZLINK Technology CO. Ltd", + "ZOT": "Zhejiang Ocaenergy Technology Co., Ltd", + "ZPA": "ZPA Smart Energy a.s.", + "ZQB": "Zhejiang Qibin Technology Co.,Ltd", + "ZRI": "ZENNER International GmbH & Co. KG", + "ZRM": "ZENNER International GmbH & Co. KG", + "ZTE": "ZTE Corporation ZTE Plaza", + "ZTX": "ZHEJIANG TANCY INSTRUMENT TECHNOLOGY CO. éTD-", + "ZTY": "ZHEJIANG CHINT INSTRUMENT & METER CO. LTD.", + "ZVC": "SigmaHeat GmbH", + "ZXT": "Zhejiang Xinghao Technology Co., Ltd", + "ZXY": "Linyi City Xiaoyuan Water Meter Co., Ltd.", + "ZYB": "WEIHAI ZHENYU INTELL & TECH Co. Ltd.", + "ZYS": "Wuxi Zhongyi Smart Technology CO,. LTD", + "ZZZ": "Michael Rac GmbH" +}); diff --git a/firmware/main/wifi_debug.c b/firmware/main/wifi_debug.c new file mode 100644 index 0000000..60f5e57 --- /dev/null +++ b/firmware/main/wifi_debug.c @@ -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 +#include +#include +#include +#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); + } +} diff --git a/firmware/main/wifi_debug.h b/firmware/main/wifi_debug.h new file mode 100644 index 0000000..10c2da8 --- /dev/null +++ b/firmware/main/wifi_debug.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +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); diff --git a/firmware/main/wifi_qr.c b/firmware/main/wifi_qr.c new file mode 100644 index 0000000..e659dcc --- /dev/null +++ b/firmware/main/wifi_qr.c @@ -0,0 +1,60 @@ +#include "wifi_qr.h" +#include "vendor/qrcodegen.h" +#include +#include + +// 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; +} diff --git a/firmware/main/wifi_qr.h b/firmware/main/wifi_qr.h new file mode 100644 index 0000000..e0a86c7 --- /dev/null +++ b/firmware/main/wifi_qr.h @@ -0,0 +1,11 @@ +#pragma once +#include +#include + +#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]); diff --git a/firmware/main/wmbus.c b/firmware/main/wmbus.c index 1b3e8c3..5e7d2b1 100644 --- a/firmware/main/wmbus.c +++ b/firmware/main/wmbus.c @@ -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; +} diff --git a/firmware/main/wmbus.h b/firmware/main/wmbus.h index 9132672..fc90078 100644 --- a/firmware/main/wmbus.h +++ b/firmware/main/wmbus.h @@ -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 @@ -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); diff --git a/firmware/sdkconfig.defaults b/firmware/sdkconfig.defaults index de5f150..428c16f 100644 --- a/firmware/sdkconfig.defaults +++ b/firmware/sdkconfig.defaults @@ -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 diff --git a/firmware/test/run_tests.sh b/firmware/test/run_tests.sh index ffdb91d..fb36ae4 100755 --- a/firmware/test/run_tests.sh +++ b/firmware/test/run_tests.sh @@ -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 diff --git a/firmware/test/test_duty_ledger.c b/firmware/test/test_duty_ledger.c new file mode 100644 index 0000000..a2834b0 --- /dev/null +++ b/firmware/test/test_duty_ledger.c @@ -0,0 +1,58 @@ +#include +#include +#include + +#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; +} diff --git a/firmware/test/test_font_render.c b/firmware/test/test_font_render.c new file mode 100644 index 0000000..effbaf1 --- /dev/null +++ b/firmware/test/test_font_render.c @@ -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 +#include +#include + +#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; +} diff --git a/firmware/test/test_t1_long.c b/firmware/test/test_t1_long.c new file mode 100644 index 0000000..709edfc --- /dev/null +++ b/firmware/test/test_t1_long.c @@ -0,0 +1,130 @@ +// T-mode 3-of-6 codec + long-frame CRC path tests (host, sanitizers). +#include +#include +#include +#include + +#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; +} diff --git a/firmware/test/test_wmbus.c b/firmware/test/test_wmbus.c index fd303ad..b417b2b 100644 --- a/firmware/test/test_wmbus.c +++ b/firmware/test/test_wmbus.c @@ -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) { diff --git a/firmware/test/tool_t1_decode.c b/firmware/test/tool_t1_decode.c new file mode 100644 index 0000000..455b0db --- /dev/null +++ b/firmware/test/tool_t1_decode.c @@ -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 +#include +#include + +#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; +}