diff --git a/CHANGELOG.md b/CHANGELOG.md index 7568042..3da9458 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to SparkMiner will be documented in this file. +## [Unreleased] + +### Added +- **Local stats API and settings page** (issue #12, opt-in, default OFF): AxeOS-compatible `/api/system/info` and `/api/system/statistics`, native `/api/sparkminer`, `/api/log`, mDNS announcement and an authenticated `/settings` page (WiFi, pools, display, access). See `WEB_API.md`. +- **LILYGO T-Display S3 compact layout** for the 170x320 panel (landscape and portrait) and a second-button backlight toggle. + +### Fixed +- **ESP32-S3 hashrate**: `miner_sha256_header` runs from IRAM. The ~20 KB straight-line hot path thrashed the 16 KB instruction cache and limited the S3 to ~1.3 KH/s; it now reaches ~49 KH/s. +- Pool URL accepts `host:port` and `stratum+tcp://` prefixes. + ## [v2.9.6-pre] - 2026-09-19 ### Fixed diff --git a/README.md b/README.md index 86a119b..2610695 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,16 @@ Configuration is automatically saved to flash memory after first successful setu --- +## Local Stats API (optional) + +SparkMiner can expose AxeOS / ESP-Miner compatible endpoints (`/api/system/info`, +`/api/system/statistics`) plus a settings page at `http:///settings`, so HashWatcher, +Home Assistant and other BitAxe tools can monitor the miner. It is off by default and costs +no hashrate while disabled. Enable it in the config portal ("Local Stats API"). +See [WEB_API.md](WEB_API.md). + +--- + ## Persistent Mining Stats SparkMiner automatically saves mining statistics to ensure your lifetime totals are preserved across reboots and power cycles. diff --git a/WEB_API.md b/WEB_API.md new file mode 100644 index 0000000..ed6cfbb --- /dev/null +++ b/WEB_API.md @@ -0,0 +1,74 @@ +# Local Stats API and Settings Page + +SparkMiner can serve a small HTTP API with AxeOS / ESP-Miner compatible endpoints +(issue #12). HashWatcher, Home Assistant and other BitAxe tools can poll the miner +over the LAN. It is **opt-in**: while disabled no task is created and no socket is +opened, so there is no hashrate cost. + +Uses the synchronous `WebServer` and `ESPmDNS` that ship with the Arduino core +(already pulled in by WiFiManager). No new library dependencies. + +## Enable it + +- **Config portal:** set "Local Stats API" to *Enabled* and save, or +- **Build default:** add `-DSPARKMINER_API_DEFAULT=1` to the build flags (only used while + the setting has never been written to NVS). + +The miner announces itself via mDNS as `http://sparkminer-xxxx.local/` (`xxxx` = last two MAC bytes). + +## Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/` | Minimal status page | +| GET | `/api/system/info` | AxeOS-compatible system info (JSON, `hashRate` in GH/s) | +| GET | `/api/system/statistics` | AxeOS-compatible history, 120 samples x 30 s (`?columns=a,b,c`) | +| GET | `/api/sparkminer` | Compact native stats (`hashrate` in H/s), handy for Home Assistant | +| GET | `/api/log` | Recent pool/stratum events as plain text (no wallet, no passwords) | +| GET | `/settings` | Settings page (HTTP Basic auth) | +| POST | `/settings` | Save settings and restart | +| POST | `/settings/reset` | Factory reset | +| POST | `/api/system/restart` | Restart the miner | + +The wallet address is masked in API responses unless "Wallet in API" is set to *Full address*. +Fields that a single ESP32 board cannot provide (power, voltage, fan, ...) are reported as `0`; +`temp` is the internal chip temperature. + +## Settings page + +`http:///settings`, user `admin`, default password = the setup hotspot password. +The password can be changed on the page (minimum 8 characters). + +It edits WiFi, wallet, primary/backup pool, display options, live stats and API access. +Saving restarts the miner. If a new WiFi network cannot be joined, the miner returns to the +previous credentials on the next boot. The pool field accepts `host`, `host:port` and +`stratum+tcp://host:port`. POST requests with a foreign `Origin` header are rejected. + +## Home Assistant + +The **Bitaxe** custom integration reads `/api/system/info` and works with SparkMiner, but it +truncates `hashRate` (GH/s) to an integer, so a few hundred KH/s show up as `0`. +Use `/api/sparkminer` for a correct value, for example: + +```yaml +rest: + - resource: http:///api/sparkminer + scan_interval: 30 + sensor: + - name: "SparkMiner Hashrate" + unique_id: sparkminer_hashrate_khs + unit_of_measurement: "kH/s" + state_class: measurement + value_template: "{{ (value_json.hashrate / 1000) | round(2) }}" + json_attributes: + - hashrate_1h + - shares_accepted + - shares_rejected + - pool_connected +``` + +## Event log + +`GET /api/log` returns the last 64 pool/stratum events (connect, handshake, difficulty, +share submits and the pool's answers). It is kept in RAM only and helps to diagnose a pool +that rejects the miner when no serial console is attached. diff --git a/src/api/web_api.cpp b/src/api/web_api.cpp new file mode 100644 index 0000000..d0979a4 --- /dev/null +++ b/src/api/web_api.cpp @@ -0,0 +1,742 @@ +/* + * SparkMiner - Local HTTP Stats API (Issue #12) + * AxeOS / ESP-Miner compatible endpoints for HashWatcher & Home Assistant + * + * GPL v3 License + */ + +#include +#include +#include +#include +#include +#include +#include +#include "web_api.h" +#include "../config/nvs_config.h" +#include "../mining/miner.h" +#include "../stratum/stratum.h" +#include "../stats/live_stats.h" + +#ifndef AUTO_VERSION + #define AUTO_VERSION "dev" +#endif + +// Internal ESP32 temperature sensor (rough, uncalibrated on classic ESP32) +#if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32S2) || \ + defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32C3) + #define WEB_API_HAS_TEMP 1 +#else + #define WEB_API_HAS_TEMP 0 +#endif + +// ============================================================ +// State +// ============================================================ + +static WebServer *s_server = nullptr; +static TaskHandle_t s_task = nullptr; +static bool s_running = false; +static bool s_mdnsStarted = false; +static char s_hostname[32] = ""; +static IPAddress s_lastIp; + +// Hashrate tracking: hash-counter snapshot every 10 s for 1 h (360 x 12 bytes) +#define HR_SLOT_MS 10000 +#define HR_SLOTS 361 +typedef struct { + uint64_t hashes; + uint32_t ms; +} hr_slot_t; +static hr_slot_t s_hrRing[HR_SLOTS]; +static uint16_t s_hrHead = 0; // Next write index +static uint16_t s_hrCount = 0; // Valid entries +static uint32_t s_lastHrSample = 0; +static double s_hashRateEma = 0.0; // H/s, 10 s samples, alpha 0.3 +static bool s_emaInit = false; + +// Statistics history (AxeOS /api/system/statistics) +typedef struct { + float hashrate; // GH/s (AxeOS unit) + float hashrate1m; // GH/s + float hashrate10m; // GH/s + float hashrate1h; // GH/s + float asicTemp; // Internal ESP32 temp, degC + int8_t wifiRssi; + uint32_t freeHeap; + float responseTime; // ms + uint32_t timestamp; // ms since boot +} stat_sample_t; +static stat_sample_t s_stats[WEB_API_STATS_SAMPLES]; +static uint16_t s_statHead = 0; +static uint16_t s_statCount = 0; +static uint32_t s_lastStatSample = 0; +static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED; + +// Event log (GET /api/log) +static char s_log[WEB_API_LOG_LINES][WEB_API_LOG_LINE_LEN]; +static uint32_t s_logMs[WEB_API_LOG_LINES]; +static uint16_t s_logHead = 0; +static uint16_t s_logCount = 0; +static uint32_t s_logTotal = 0; +static portMUX_TYPE s_logMux = portMUX_INITIALIZER_UNLOCKED; + +// ============================================================ +// Helpers +// ============================================================ + +static void buildHostname() { + if (s_hostname[0]) return; + uint8_t mac[6] = {0}; + esp_read_mac(mac, ESP_MAC_WIFI_STA); + snprintf(s_hostname, sizeof(s_hostname), "sparkminer-%02x%02x", mac[4], mac[5]); +} + +static uint64_t readHashes() { + // 64-bit volatile read is not atomic on Xtensa/RISC-V; read until stable + mining_stats_t *m = miner_get_stats(); + uint64_t a, b; + do { + a = m->hashes; + b = m->hashes; + } while (a != b && (b - a) > 1000000ULL); + return b; +} + +// Average H/s over the last windowMs, using the hash-counter ring buffer +static double hashRateOver(uint32_t windowMs) { + double rate = 0.0; + portENTER_CRITICAL(&s_mux); + if (s_hrCount >= 2) { + uint16_t newest = (s_hrHead + HR_SLOTS - 1) % HR_SLOTS; + uint16_t steps = windowMs / HR_SLOT_MS; + if (steps > s_hrCount - 1) steps = s_hrCount - 1; + if (steps < 1) steps = 1; + uint16_t oldest = (newest + HR_SLOTS - steps) % HR_SLOTS; + uint32_t dt = s_hrRing[newest].ms - s_hrRing[oldest].ms; + uint64_t dh = s_hrRing[newest].hashes - s_hrRing[oldest].hashes; + if (dt > 0) rate = (double)dh * 1000.0 / (double)dt; + } + portEXIT_CRITICAL(&s_mux); + return rate; +} + +static float readTemp() { +#if WEB_API_HAS_TEMP + float t = temperatureRead(); + // Classic ESP32 without a working sensor reports ~53.3 (raw 128) + if (isnan(t) || t < -40.0f || t > 150.0f) return 0.0f; + return t; +#else + return 0.0f; +#endif +} + +static void sampleTick() { + uint32_t now = millis(); + + // Hash-counter snapshot every 10 s + if (s_lastHrSample == 0 || now - s_lastHrSample >= HR_SLOT_MS) { + uint64_t h = readHashes(); + + // EMA of the 10 s instantaneous rate + if (s_hrCount > 0) { + uint16_t prev = (s_hrHead + HR_SLOTS - 1) % HR_SLOTS; + uint32_t dt = now - s_hrRing[prev].ms; + if (dt > 0) { + double inst = (double)(h - s_hrRing[prev].hashes) * 1000.0 / (double)dt; + if (!s_emaInit) { s_hashRateEma = inst; s_emaInit = true; } + else s_hashRateEma = 0.3 * inst + 0.7 * s_hashRateEma; + } + } + + portENTER_CRITICAL(&s_mux); + s_hrRing[s_hrHead].hashes = h; + s_hrRing[s_hrHead].ms = now; + s_hrHead = (s_hrHead + 1) % HR_SLOTS; + if (s_hrCount < HR_SLOTS) s_hrCount++; + portEXIT_CRITICAL(&s_mux); + s_lastHrSample = now; + } + + // Statistics history sample + if (s_lastStatSample == 0 || now - s_lastStatSample >= WEB_API_STATS_INTERVAL_MS) { + stat_sample_t s; + s.hashrate = (float)(s_hashRateEma / 1e9); + s.hashrate1m = (float)(hashRateOver(60000) / 1e9); + s.hashrate10m = (float)(hashRateOver(600000) / 1e9); + s.hashrate1h = (float)(hashRateOver(3600000) / 1e9); + s.asicTemp = readTemp(); + s.wifiRssi = (WiFi.status() == WL_CONNECTED) ? (int8_t)WiFi.RSSI() : 0; + s.freeHeap = ESP.getFreeHeap(); + s.responseTime = (float)miner_get_stats()->avgLatency; + s.timestamp = now; + + portENTER_CRITICAL(&s_mux); + s_stats[s_statHead] = s; + s_statHead = (s_statHead + 1) % WEB_API_STATS_SAMPLES; + if (s_statCount < WEB_API_STATS_SAMPLES) s_statCount++; + portEXIT_CRITICAL(&s_mux); + s_lastStatSample = now; + } +} + +// Mask wallet unless exposure is explicitly enabled: bc1qxy...wlh +static void maskWallet(const char *in, char *out, size_t outLen) { + size_t n = strlen(in); + if (n == 0) { out[0] = '\0'; return; } + if (nvs_api_expose_wallet()) { + strncpy(out, in, outLen - 1); + out[outLen - 1] = '\0'; + return; + } + // Keep a ".worker" suffix visible, mask the address part + const char *dot = strchr(in, '.'); + size_t addrLen = dot ? (size_t)(dot - in) : n; + if (addrLen <= 10) { + snprintf(out, outLen, "***%s", dot ? dot : ""); + } else { + snprintf(out, outLen, "%.6s...%.4s%s", in, in + addrLen - 4, dot ? dot : ""); + } +} + +static void jsonEscapeAppend(String &s, const char *v) { + s += '"'; + for (const char *p = v ? v : ""; *p; p++) { + char c = *p; + if (c == '"' || c == '\\') { s += '\\'; s += c; } + else if ((uint8_t)c < 0x20) { char b[8]; snprintf(b, sizeof(b), "\\u%04x", c); s += b; } + else s += c; + } + s += '"'; +} + +// Tiny JSON writer helpers (avoid a large JsonDocument on a small stack) +static void kStr(String &s, const char *k, const char *v) { + s += '"'; s += k; s += "\":"; jsonEscapeAppend(s, v); s += ','; +} +static void kNum(String &s, const char *k, double v, int decimals = 0) { + char b[40]; + if (isnan(v) || isinf(v)) v = 0; + if (decimals == 0) snprintf(b, sizeof(b), "\"%s\":%.0f,", k, v); + else snprintf(b, sizeof(b), "\"%s\":%.*f,", k, decimals, v); + s += b; +} +static void kU64(String &s, const char *k, uint64_t v) { + char b[48]; + snprintf(b, sizeof(b), "\"%s\":%llu,", k, (unsigned long long)v); + s += b; +} +static void kBool(String &s, const char *k, bool v) { + s += '"'; s += k; s += "\":"; s += v ? "true" : "false"; s += ','; +} +static void closeObj(String &s) { + if (s.length() && s[s.length() - 1] == ',') s.setCharAt(s.length() - 1, '}'); + else s += '}'; +} + +static void sendCors() { + s_server->sendHeader("Access-Control-Allow-Origin", "*"); + s_server->sendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + s_server->sendHeader("Access-Control-Allow-Headers", "Content-Type"); + s_server->sendHeader("Cache-Control", "no-store"); +} + +// Collect everything both JSON endpoints need in one place +typedef struct { + double hashRateHs, hr1m, hr10m, hr1h; + double bestDiffEver, bestSessionDiff, poolDiff; + uint32_t accepted, rejected, lifetimeAccepted, lifetimeRejected; + uint32_t blocks, lifetimeBlocks, templates, matches32; + uint64_t sessionHashes, lifetimeHashes; + uint32_t uptime, totalUptime, avgLatency; + uint32_t submitted; + bool poolConnected, usingBackup; +} snap_t; + +static void takeSnapshot(snap_t *o) { + mining_stats_t *m = miner_get_stats(); + mining_persistence_t *p = nvs_stats_get(); + + o->hashRateHs = s_hashRateEma; + o->hr1m = hashRateOver(60000); + o->hr10m = hashRateOver(600000); + o->hr1h = hashRateOver(3600000); + + o->bestSessionDiff = m->bestDifficulty; + o->bestDiffEver = (m->bestDifficulty > p->bestDifficultyEver) ? m->bestDifficulty : p->bestDifficultyEver; + o->poolDiff = miner_get_difficulty(); + + o->submitted = m->shares; + o->accepted = m->accepted; + o->rejected = m->rejected; + o->lifetimeAccepted = p->lifetimeAccepted + m->accepted; + o->lifetimeRejected = p->lifetimeRejected + m->rejected; + o->blocks = m->blocks; + o->lifetimeBlocks = p->lifetimeBlocks + m->blocks; + o->templates = m->templates; + o->matches32 = m->matches32; + o->sessionHashes = readHashes(); + o->lifetimeHashes = p->lifetimeHashes + o->sessionHashes; + o->uptime = millis() / 1000; + o->totalUptime = p->totalUptimeSeconds + o->uptime; + o->avgLatency = m->avgLatency; + o->poolConnected = stratum_is_connected(); + o->usingBackup = stratum_is_backup(); +} + +// ============================================================ +// Handlers +// ============================================================ + +// GET /api/system/info - AxeOS / ESP-Miner compatible +static void handleSystemInfo() { + snap_t sn; + takeSnapshot(&sn); + miner_config_t *cfg = nvs_config_get(); + live_stats_t ls; + live_stats_get_copy(&ls); + + char user[160], fbUser[160], full[200]; + if (cfg->workerName[0]) snprintf(full, sizeof(full), "%s.%s", cfg->wallet, cfg->workerName); + else snprintf(full, sizeof(full), "%s", cfg->wallet); + maskWallet(full, user, sizeof(user)); + const char *bw = cfg->backupWallet[0] ? cfg->backupWallet : cfg->wallet; + if (cfg->workerName[0]) snprintf(full, sizeof(full), "%s.%s", bw, cfg->workerName); + else snprintf(full, sizeof(full), "%s", bw); + maskWallet(full, fbUser, sizeof(fbUser)); + + char mac[18]; + uint8_t m[6]; + esp_read_mac(m, ESP_MAC_WIFI_STA); + snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", m[0], m[1], m[2], m[3], m[4], m[5]); + char fullHost[48]; + snprintf(fullHost, sizeof(fullHost), "%s.local", s_hostname); + + bool wifiOk = (WiFi.status() == WL_CONNECTED); + String s; + s.reserve(2300); + s = "{"; + + // --- Power / thermal (no power monitor on ESP32 boards -> 0) --- + kNum(s, "power", 0); + kNum(s, "voltage", 0); + kNum(s, "current", 0); + kNum(s, "temp", readTemp(), 1); + kNum(s, "vrTemp", 0); + kNum(s, "maxPower", 0); + kNum(s, "nominalVoltage", 0); + kNum(s, "coreVoltage", 0); + kNum(s, "coreVoltageActual", 0); + kNum(s, "frequency", getCpuFrequencyMhz()); + kNum(s, "actualFrequency", getCpuFrequencyMhz()); + kNum(s, "expectedHashrate", 0); + kNum(s, "fanspeed", 0); + kNum(s, "fanrpm", 0); + kNum(s, "overheat_mode", 0); + + // --- Mining (AxeOS units: hashRate in GH/s) --- + kNum(s, "hashRate", sn.hashRateHs / 1e9, 9); + kNum(s, "hashRate_1m", sn.hr1m / 1e9, 9); + kNum(s, "hashRate_10m", sn.hr10m / 1e9, 9); + kNum(s, "hashRate_1h", sn.hr1h / 1e9, 9); + double errPct = (sn.accepted + sn.rejected) ? (100.0 * sn.rejected / (sn.accepted + sn.rejected)) : 0.0; + kNum(s, "errorPercentage", errPct, 2); + kNum(s, "sharesAccepted", sn.accepted); + kNum(s, "sharesRejected", sn.rejected); + kNum(s, "bestDiff", sn.bestDiffEver, 4); + kNum(s, "bestSessionDiff", sn.bestSessionDiff, 4); + kNum(s, "poolDifficulty", sn.poolDiff, 6); + kNum(s, "responseTime", sn.avgLatency); + kNum(s, "workReceived", sn.templates); + kNum(s, "blockFound", sn.blocks > 0 ? 1 : 0); + kNum(s, "blockHeight", ls.blockValid ? ls.blockHeight : 0); + kNum(s, "networkDifficulty", ls.networkValid ? ls.difficultyRaw : 0); + kNum(s, "isUsingFallbackStratum", sn.usingBackup ? 1 : 0); + + // --- System --- + kNum(s, "freeHeap", ESP.getFreeHeap()); + kNum(s, "minFreeHeap", ESP.getMinFreeHeap()); + kNum(s, "maxAllocHeap", ESP.getMaxAllocHeap()); + kNum(s, "isPSRAMAvailable", psramFound() ? 1 : 0); + kNum(s, "uptimeSeconds", sn.uptime); + kNum(s, "totalUptimeSeconds", sn.totalUptime); + kU64(s, "totalHashes", sn.lifetimeHashes); + kNum(s, "smallCoreCount", ESP.getChipCores()); + kStr(s, "ASICModel", ESP.getChipModel()); + kStr(s, "deviceModel", "SparkMiner"); + kStr(s, "boardVersion", BOARD_NAME); + kStr(s, "version", AUTO_VERSION); + kStr(s, "axeOSVersion", AUTO_VERSION); + kStr(s, "idfVersion", esp_get_idf_version()); + kStr(s, "runningPartition", "app0"); + kStr(s, "hostname", s_hostname); + kStr(s, "fullHostname", fullHost); + kStr(s, "mdnsHostname", s_hostname); + kStr(s, "macAddr", mac); + kStr(s, "ssid", wifiOk ? WiFi.SSID().c_str() : ""); + kStr(s, "ipv4", wifiOk ? WiFi.localIP().toString().c_str() : ""); + kStr(s, "wifiStatus", wifiOk ? "Connected!" : "Disconnected"); + kNum(s, "wifiRSSI", wifiOk ? WiFi.RSSI() : 0); + kNum(s, "apEnabled", 0); + + // --- Pool --- + kStr(s, "stratumURL", cfg->poolUrl); + kNum(s, "stratumPort", cfg->poolPort); + kStr(s, "stratumUser", user); + kNum(s, "stratumSuggestedDifficulty", cfg->targetDifficulty, 6); + kStr(s, "fallbackStratumURL", cfg->backupPoolUrl); + kNum(s, "fallbackStratumPort", cfg->backupPoolPort); + kStr(s, "fallbackStratumUser", fbUser); + kStr(s, "poolConnectionInfo", sn.poolConnected ? "Connected" : "Disconnected"); + + // --- Display --- + kStr(s, "display", BOARD_NAME); + kNum(s, "rotation", cfg->rotation); + kNum(s, "invertscreen", cfg->invertColors ? 1 : 0); + kNum(s, "displayTimeout", cfg->screenTimeout); + + // --- SparkMiner extensions (native units, not part of AxeOS) --- + kNum(s, "hashRateHs", sn.hashRateHs, 1); + kNum(s, "hashRateKHs", sn.hashRateHs / 1e3, 2); + kNum(s, "hashRate_1mKHs", sn.hr1m / 1e3, 2); + kNum(s, "hashRate_10mKHs", sn.hr10m / 1e3, 2); + kNum(s, "hashRate_1hKHs", sn.hr1h / 1e3, 2); + kNum(s, "totalSharesAccepted", sn.lifetimeAccepted); + kNum(s, "totalSharesRejected", sn.lifetimeRejected); + kNum(s, "totalBlocksFound", sn.lifetimeBlocks); + kNum(s, "matches32bit", sn.matches32); + kBool(s, "poolConnected", sn.poolConnected); + closeObj(s); + + sendCors(); + s_server->send(200, "application/json", s); +} + +// GET /api/sparkminer - compact native stats, friendly for HA REST sensors +static void handleNative() { + snap_t sn; + takeSnapshot(&sn); + live_stats_t ls; + live_stats_get_copy(&ls); + + String s; + s.reserve(900); + s = "{"; + kNum(s, "hashrate", sn.hashRateHs, 1); + kNum(s, "hashrate_1m", sn.hr1m, 1); + kNum(s, "hashrate_10m", sn.hr10m, 1); + kNum(s, "hashrate_1h", sn.hr1h, 1); + kNum(s, "shares_submitted", sn.submitted); + kNum(s, "shares_accepted", sn.accepted); + kNum(s, "shares_rejected", sn.rejected); + kNum(s, "total_shares_accepted", sn.lifetimeAccepted); + kNum(s, "total_shares_rejected", sn.lifetimeRejected); + kNum(s, "best_diff", sn.bestDiffEver, 6); + kNum(s, "best_session_diff", sn.bestSessionDiff, 6); + kNum(s, "pool_diff", sn.poolDiff, 6); + kNum(s, "blocks_found", sn.lifetimeBlocks); + kNum(s, "matches_32bit", sn.matches32); + kNum(s, "templates", sn.templates); + kU64(s, "session_hashes", sn.sessionHashes); + kU64(s, "total_hashes", sn.lifetimeHashes); + kNum(s, "uptime", sn.uptime); + kNum(s, "total_uptime", sn.totalUptime); + kNum(s, "pool_latency_ms", sn.avgLatency); + kBool(s, "pool_connected", sn.poolConnected); + kBool(s, "pool_backup", sn.usingBackup); + kStr(s, "pool", stratum_get_pool()); + kNum(s, "temp", readTemp(), 1); + kNum(s, "rssi", WiFi.status() == WL_CONNECTED ? WiFi.RSSI() : 0); + kNum(s, "free_heap", ESP.getFreeHeap()); + kNum(s, "cpu_mhz", getCpuFrequencyMhz()); + kNum(s, "block_height", ls.blockValid ? ls.blockHeight : 0); + kStr(s, "version", AUTO_VERSION); + kStr(s, "board", BOARD_NAME); + closeObj(s); + + sendCors(); + s_server->send(200, "application/json", s); +} + +// GET /api/system/statistics[?columns=a,b,c] - AxeOS compatible, streamed +enum { C_HR = 0, C_HR1M, C_HR10M, C_HR1H, C_TEMP, C_RSSI, C_HEAP, C_RESP, C_NUM }; +static const char *kColNames[C_NUM] = { + "hashrate", "hashrate_1m", "hashrate_10m", "hashrate_1h", + "asicTemp", "wifiRssi", "freeHeap", "responseTime" +}; + +static void handleStatistics() { + bool sel[C_NUM]; + bool any = false; + for (int i = 0; i < C_NUM; i++) sel[i] = false; + + if (s_server->hasArg("columns")) { + String cols = s_server->arg("columns"); + int start = 0; + while (start <= (int)cols.length()) { + int comma = cols.indexOf(',', start); + if (comma < 0) comma = cols.length(); + String c = cols.substring(start, comma); + c.trim(); + for (int i = 0; i < C_NUM; i++) { + if (c == kColNames[i]) { sel[i] = true; any = true; } + } + start = comma + 1; + } + } + if (!any) for (int i = 0; i < C_NUM; i++) sel[i] = true; + + // Copy ring buffer under lock (~3 KB on heap) + uint16_t count; + stat_sample_t *copy = (stat_sample_t *)malloc(sizeof(stat_sample_t) * WEB_API_STATS_SAMPLES); + if (!copy) { + s_server->send(503, "application/json", "{\"error\":\"out of memory\"}"); + return; + } + portENTER_CRITICAL(&s_mux); + count = s_statCount; + uint16_t first = (s_statHead + WEB_API_STATS_SAMPLES - count) % WEB_API_STATS_SAMPLES; + for (uint16_t i = 0; i < count; i++) { + copy[i] = s_stats[(first + i) % WEB_API_STATS_SAMPLES]; + } + portEXIT_CRITICAL(&s_mux); + + sendCors(); + s_server->setContentLength(CONTENT_LENGTH_UNKNOWN); + s_server->send(200, "application/json", ""); + + char buf[160]; + snprintf(buf, sizeof(buf), "{\"currentTimestamp\":%lu,\"labels\":[", (unsigned long)millis()); + String out = buf; + for (int i = 0; i < C_NUM; i++) { + if (!sel[i]) continue; + out += '"'; out += kColNames[i]; out += "\","; + } + out += "\"timestamp\"],\"statistics\":["; + s_server->sendContent(out); + + for (uint16_t i = 0; i < count; i++) { + const stat_sample_t &r = copy[i]; + int n = snprintf(buf, sizeof(buf), "%s[", i ? "," : ""); + if (sel[C_HR]) n += snprintf(buf + n, sizeof(buf) - n, "%.9f,", r.hashrate); + if (sel[C_HR1M]) n += snprintf(buf + n, sizeof(buf) - n, "%.9f,", r.hashrate1m); + if (sel[C_HR10M]) n += snprintf(buf + n, sizeof(buf) - n, "%.9f,", r.hashrate10m); + if (sel[C_HR1H]) n += snprintf(buf + n, sizeof(buf) - n, "%.9f,", r.hashrate1h); + if (sel[C_TEMP]) n += snprintf(buf + n, sizeof(buf) - n, "%.1f,", r.asicTemp); + if (sel[C_RSSI]) n += snprintf(buf + n, sizeof(buf) - n, "%d,", r.wifiRssi); + if (sel[C_HEAP]) n += snprintf(buf + n, sizeof(buf) - n, "%lu,", (unsigned long)r.freeHeap); + if (sel[C_RESP]) n += snprintf(buf + n, sizeof(buf) - n, "%.0f,", r.responseTime); + snprintf(buf + n, sizeof(buf) - n, "%lu]", (unsigned long)r.timestamp); + s_server->sendContent(buf); + } + s_server->sendContent("]}"); + s_server->sendContent(""); // Terminate chunked response + free(copy); +} + +// GET /api/log - recent pool/stratum events, oldest first, streamed +static void handleLog() { + sendCors(); + s_server->setContentLength(CONTENT_LENGTH_UNKNOWN); + s_server->send(200, "text/plain; charset=utf-8", ""); + + char line[WEB_API_LOG_LINE_LEN]; + char out[WEB_API_LOG_LINE_LEN + 24]; + + portENTER_CRITICAL(&s_logMux); + uint16_t count = s_logCount; + uint16_t first = (s_logHead + WEB_API_LOG_LINES - count) % WEB_API_LOG_LINES; + uint32_t total = s_logTotal; + portEXIT_CRITICAL(&s_logMux); + + snprintf(out, sizeof(out), "# uptime %lu s, %lu events logged, showing last %u\n", + (unsigned long)(millis() / 1000), (unsigned long)total, (unsigned)count); + s_server->sendContent(out); + + for (uint16_t i = 0; i < count; i++) { + uint16_t idx = (first + i) % WEB_API_LOG_LINES; + portENTER_CRITICAL(&s_logMux); + memcpy(line, s_log[idx], sizeof(line)); + uint32_t ms = s_logMs[idx]; + portEXIT_CRITICAL(&s_logMux); + line[sizeof(line) - 1] = '\0'; + snprintf(out, sizeof(out), "[%7lu.%lus] %s\n", + (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100), line); + s_server->sendContent(out); + } + s_server->sendContent(""); // Terminate chunked response +} + +#include "web_settings.h" + +static void handleRestart() { + sendCors(); + s_server->send(200, "application/json", "{\"message\":\"System will restart shortly.\"}"); + delay(500); + ESP.restart(); +} + +static void handleOptions() { + sendCors(); + s_server->send(204); +} + +static void handleRoot() { + snap_t sn; + takeSnapshot(&sn); + const miner_config_t *cfg = nvs_config_get(); + const char *poolName = sn.poolConnected ? stratum_get_pool() : cfg->poolUrl; + char buf[1700]; + snprintf(buf, sizeof(buf), + "" + "" + "SparkMiner" + "" + "

SparkMiner

" + "" + "" + "" + "" + "" + "" + "" + "
Hashrate%.2f kH/s
Hashrate 1h%.2f kH/s
Shares%lu accepted / %lu rejected
Best diff%.4f (session %.4f)
Pool%s (%s)
Wallet%s
Uptime%lu s
Version%s
" + "

Settings

" + "

/api/system/info
" + "/api/system/statistics
" + "/api/sparkminer
" + "/api/log

", + sn.hashRateHs / 1e3, sn.hr1h / 1e3, + (unsigned long)sn.accepted, (unsigned long)sn.rejected, + sn.bestDiffEver, sn.bestSessionDiff, + poolName, sn.poolConnected ? "connected" : "disconnected", + cfg->wallet[0] ? "configured" : "NOT SET - mining is off", + (unsigned long)sn.uptime, AUTO_VERSION); + s_server->send(200, "text/html", buf); +} + +static void handleNotFound() { + if (s_server->method() == HTTP_OPTIONS) { handleOptions(); return; } + sendCors(); + s_server->send(404, "application/json", "{\"error\":\"unknown route\"}"); +} + +// ============================================================ +// mDNS +// ============================================================ + +static void startMdns() { + if (s_mdnsStarted) { + MDNS.end(); + s_mdnsStarted = false; + } + if (!MDNS.begin(s_hostname)) { + Serial.println("[API] mDNS start failed"); + return; + } + MDNS.addService("http", "tcp", WEB_API_PORT); + MDNS.addServiceTxt("http", "tcp", "device", "sparkminer"); + MDNS.addServiceTxt("http", "tcp", "api", "axeos"); + s_mdnsStarted = true; + Serial.printf("[API] mDNS: http://%s.local/\n", s_hostname); +} + +// ============================================================ +// Task +// ============================================================ + +static void web_api_task(void *param) { + Serial.printf("[API] Task started on core %d\n", xPortGetCoreID()); + + s_server = new WebServer(WEB_API_PORT); + static const char *kHeaders[] = {"Origin"}; + s_server->collectHeaders(kHeaders, 1); + s_server->on("/settings", HTTP_GET, handleSettingsGet); + s_server->on("/settings", HTTP_POST, handleSettingsPost); + s_server->on("/settings/reset", HTTP_POST, handleSettingsReset); + s_server->on("/", HTTP_GET, handleRoot); + s_server->on("/api/system/info", HTTP_GET, handleSystemInfo); + s_server->on("/api/system/statistics", HTTP_GET, handleStatistics); + s_server->on("/api/system/statistics/dashboard", HTTP_GET, handleStatistics); + s_server->on("/api/sparkminer", HTTP_GET, handleNative); + s_server->on("/api/log", HTTP_GET, handleLog); + s_server->on("/api/system/restart", HTTP_POST, handleRestart); + s_server->onNotFound(handleNotFound); + s_server->begin(); + Serial.printf("[API] HTTP server listening on port %d\n", WEB_API_PORT); + + bool wasConnected = false; + for (;;) { + sampleTick(); + settingsTick(); + + bool connected = (WiFi.status() == WL_CONNECTED); + if (connected) { + IPAddress ip = WiFi.localIP(); + // (Re)announce mDNS after (re)connect or IP change + if (!wasConnected || ip != s_lastIp) { + s_lastIp = ip; + startMdns(); + Serial.printf("[API] Stats API: http://%s/api/system/info\n", ip.toString().c_str()); + } + s_server->handleClient(); + } + wasConnected = connected; + + // 20 ms poll: responsive enough for HTTP, negligible CPU on core 0 + vTaskDelay(pdMS_TO_TICKS(20)); + } +} + +// ============================================================ +// Public API +// ============================================================ + +void web_api_start() { + buildHostname(); + if (s_running) return; + if (!nvs_api_enabled()) { + Serial.println("[API] Local stats API disabled (enable in config portal)"); + return; + } + + BaseType_t ok = xTaskCreatePinnedToCore( + web_api_task, "WebAPI", WEB_API_STACK, NULL, + WEB_API_PRIORITY, &s_task, WEB_API_CORE); + if (ok == pdPASS) { + s_running = true; + Serial.println("[API] Local stats API enabled"); + } else { + Serial.println("[API] ERROR: Failed to create WebAPI task"); + } +} + +bool web_api_is_running() { + return s_running; +} + +void web_api_log(const char *fmt, ...) { + if (!s_running) return; + + char line[WEB_API_LOG_LINE_LEN]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + + uint32_t now = millis(); + portENTER_CRITICAL(&s_logMux); + memcpy(s_log[s_logHead], line, sizeof(line)); + s_logMs[s_logHead] = now; + s_logHead = (s_logHead + 1) % WEB_API_LOG_LINES; + if (s_logCount < WEB_API_LOG_LINES) s_logCount++; + s_logTotal++; + portEXIT_CRITICAL(&s_logMux); +} + +const char* web_api_get_hostname() { + buildHostname(); + return s_hostname; +} diff --git a/src/api/web_api.h b/src/api/web_api.h new file mode 100644 index 0000000..aadf3fc --- /dev/null +++ b/src/api/web_api.h @@ -0,0 +1,84 @@ +/* + * SparkMiner - Local HTTP Stats API (Issue #12) + * + * Optional, opt-in local web server exposing AxeOS / ESP-Miner compatible + * endpoints so HashWatcher, Home Assistant and other BitAxe tools can poll + * the miner over the LAN. + * + * GET / Minimal status page + * GET /api/system/info AxeOS-compatible system info (JSON) + * GET /api/system/statistics AxeOS-compatible history (JSON, ?columns=) + * GET /api/sparkminer SparkMiner-native stats (H/s units, JSON) + * GET /api/log Recent pool/stratum events (plain text) + * GET /settings Settings page (Basic auth, user "admin") + * POST /settings Save settings and restart + * POST /settings/reset Factory reset + * POST /api/system/restart Restart the miner + * + * Uses the synchronous WebServer + ESPmDNS that ship with the Arduino core + * (already pulled in by WiFiManager) - no new library dependencies. + * Disabled by default: when apiEnabled is false no task is created and no + * socket is opened, so there is zero hashrate cost. + * + * GPL v3 License + */ + +#ifndef WEB_API_H +#define WEB_API_H + +#include + +#ifndef WEB_API_PORT + #define WEB_API_PORT 80 +#endif +#ifndef WEB_API_CORE + #define WEB_API_CORE 0 +#endif +#ifndef WEB_API_PRIORITY + #define WEB_API_PRIORITY 1 // Same as monitor task, far below Miner1 (19) +#endif +#ifndef WEB_API_STACK + #define WEB_API_STACK 8192 +#endif + +// Statistics history: one sample every WEB_API_STATS_INTERVAL_MS, +// ring buffer of WEB_API_STATS_SAMPLES entries (default 120 x 30 s = 1 h) +#ifndef WEB_API_STATS_INTERVAL_MS + #define WEB_API_STATS_INTERVAL_MS 30000 +#endif +#ifndef WEB_API_STATS_SAMPLES + #define WEB_API_STATS_SAMPLES 120 +#endif + +// Event log ring buffer (GET /api/log) +#ifndef WEB_API_LOG_LINES + #define WEB_API_LOG_LINES 64 +#endif +#define WEB_API_LOG_LINE_LEN 120 + +/** + * Start the web API task if apiEnabled is set in NVS. + * Safe to call when disabled (no-op). + * Must be called after WiFi is connected (after wifi_manager_start()). + */ +void web_api_start(); + +/** + * True if the web API task is running. + */ +bool web_api_is_running(); + +/** + * mDNS hostname (without .local), e.g. "sparkminer-a1b2". + */ +const char* web_api_get_hostname(); + +/** + * Append one line to the in-RAM event log served at GET /api/log. + * Records pool/stratum events so a miner can be diagnosed from a browser + * when no serial console is attached. No-op while the API is disabled. + * Never pass wallet addresses or passwords. + */ +void web_api_log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +#endif // WEB_API_H diff --git a/src/api/web_settings.h b/src/api/web_settings.h new file mode 100644 index 0000000..76b37d9 --- /dev/null +++ b/src/api/web_settings.h @@ -0,0 +1,374 @@ +/* + * SparkMiner - Web settings page + * + * GET /settings Edit WiFi, pool, wallet, display and stats settings + * POST /settings Validate, save to NVS, restart + * POST /settings/reset Factory reset (wipes configuration, opens setup portal) + * + * Protected with HTTP Basic auth (user "admin"). The password defaults to the + * setup hotspot password and can be changed on the page. Only reachable while + * the local API is enabled. + * + * Included by web_api.cpp (uses its WebServer instance s_server). + * + * GPL v3 License + */ + +#ifndef WEB_SETTINGS_H +#define WEB_SETTINGS_H + +#define WEB_SETTINGS_USER "admin" +#define WEB_PASSWORD_MIN_LEN 8 + +static uint32_t s_restartAtMs = 0; // 0 = no restart pending +static bool s_wipeOnRestart = false; + +// ============================================================ +// Helpers +// ============================================================ + +static bool settingsAuth() { + char pass[40]; + nvs_web_password_get(pass, sizeof(pass)); + if (s_server->authenticate(WEB_SETTINGS_USER, pass)) return true; + s_server->requestAuthentication(BASIC_AUTH, "SparkMiner", "Login required (user: admin)"); + return false; +} + +// Reject cross-site form posts: a browser always sends Origin on those. +static bool settingsSameOrigin() { + if (!s_server->hasHeader("Origin")) return true; + String origin = s_server->header("Origin"); + int p = origin.indexOf("://"); + if (p < 0) return false; + return origin.substring(p + 3) == s_server->hostHeader(); +} + +static void htmlEsc(String &s, const char *v) { + for (const char *p = v ? v : ""; *p; p++) { + switch (*p) { + case '&': s += "&"; break; + case '<': s += "<"; break; + case '>': s += ">"; break; + case '"': s += """; break; + case '\'': s += "'"; break; + default: s += *p; break; + } + } +} + +static void fInput(String &s, const char *label, const char *name, const char *value, + int maxLen, const char *type = "text", const char *hint = "") { + s += ""; +} + +static void fSelectOpen(String &s, const char *label, const char *name) { + s += ""; +} + +static const char SETTINGS_HEAD[] = + "" + "" + "SparkMiner Settings"; + +static void settingsMessage(int code, const char *title, const char *text, bool refreshHome) { + String s; + s.reserve(900); + s = SETTINGS_HEAD; + if (refreshHome) s += ""; + s += "

"; + s += title; + s += "

"; + htmlEsc(s, text); + s += "

Status · Settings

"; + s_server->send(code, "text/html", s); +} + +// Copy a trimmed form field into a fixed buffer; false if it does not fit. +// A field that was not submitted leaves the buffer untouched. +static bool argTo(const char *name, char *dest, size_t destSize) { + if (!s_server->hasArg(name)) return true; + String v = s_server->arg(name); + v.trim(); + if (v.length() >= destSize) return false; + strncpy(dest, v.c_str(), destSize - 1); + dest[destSize - 1] = '\0'; + return true; +} + +static bool argPort(const char *name, uint16_t *out) { + if (!s_server->hasArg(name)) return true; + String v = s_server->arg(name); + v.trim(); + long p = v.toInt(); + if (p < 1 || p > 65535) return false; + *out = (uint16_t)p; + return true; +} + +// ============================================================ +// GET /settings +// ============================================================ + +static void handleSettingsGet() { + if (!settingsAuth()) return; + const miner_config_t *c = nvs_config_get(); + char num[12]; + + s_server->sendHeader("Cache-Control", "no-store"); + s_server->setContentLength(CONTENT_LENGTH_UNKNOWN); + s_server->send(200, "text/html", ""); + + String s; + s.reserve(2600); + + s = SETTINGS_HEAD; + s += "

SparkMiner Settings

← Status · "; + htmlEsc(s, s_hostname); + s += " · " AUTO_VERSION "

"; + + s += "

WiFi

"; + fInput(s, "Network name (SSID)", "ssid", c->ssid, 32); + fInput(s, "WiFi password", "wifi_pass", "", 63, "password", "leave empty to keep current"); + s += "

If the new network cannot be joined, the miner returns to the current one.

"; + s_server->sendContent(s); + + s = "

Mining

"; + fInput(s, "BTC wallet address", "wallet", c->wallet, MAX_WALLET_LEN); + fInput(s, "Worker name", "worker", c->workerName, 31); + s += "

Primary pool

"; + fInput(s, "Pool URL", "pool_url", c->poolUrl, MAX_POOL_URL_LEN); + snprintf(num, sizeof(num), "%u", (unsigned)c->poolPort); + fInput(s, "Pool port", "pool_port", num, 5, "number"); + fInput(s, "Pool password", "pool_pass", c->poolPassword, MAX_PASSWORD_LEN); + s += "

Backup pool

"; + fInput(s, "Backup pool URL", "bk_url", c->backupPoolUrl, MAX_POOL_URL_LEN); + snprintf(num, sizeof(num), "%u", (unsigned)c->backupPoolPort); + fInput(s, "Backup pool port", "bk_port", num, 5, "number"); + fInput(s, "Backup wallet (optional)", "bk_wallet", c->backupWallet, MAX_WALLET_LEN); + fInput(s, "Backup pool password", "bk_pass", c->backupPoolPassword, MAX_PASSWORD_LEN); + s_server->sendContent(s); + + s = "

Display

"; + fSelectOpen(s, "Brightness", "bright"); + static const int kBright[] = {10, 25, 50, 75, 100}; + for (int i = 0; i < 5; i++) { + snprintf(num, sizeof(num), "%d%%", kBright[i]); + fOption(s, kBright[i], num, c->brightness == kBright[i]); + } + fSelectClose(s); + fSelectOpen(s, "Screen timeout", "scrn_to"); + static const int kTimeout[] = {0, 30, 60, 120, 300}; + static const char *kTimeoutLabel[] = {"Never", "30 seconds", "1 minute", "2 minutes", "5 minutes"}; + for (int i = 0; i < 5; i++) fOption(s, kTimeout[i], kTimeoutLabel[i], c->screenTimeout == kTimeout[i]); + fSelectClose(s); + fSelectOpen(s, "Screen rotation", "rotation"); + static const char *kRotLabel[] = {"0 - Portrait", "1 - Landscape", "2 - Portrait (flipped)", "3 - Landscape (flipped)"}; + for (int i = 0; i < 4; i++) fOption(s, i, kRotLabel[i], c->rotation == i); + fSelectClose(s); + fSelectOpen(s, "Color theme", "invert"); + fOption(s, 0, "Dark", !c->invertColors); + fOption(s, 1, "Light", c->invertColors); + fSelectClose(s); + s_server->sendContent(s); + + s = ""; + fSelectOpen(s, "Timezone", "tz"); + for (int i = -12; i <= 14; i++) { + snprintf(num, sizeof(num), "UTC%+d", i); + fOption(s, i, num, c->timezoneOffset == i); + } + fSelectClose(s); + s_server->sendContent(s); + + s = "

Live stats (price, block height)

"; + fSelectOpen(s, "Live stats", "stats_en"); + fOption(s, 1, "Enabled", c->statsEnabled); + fOption(s, 0, "Disabled", !c->statsEnabled); + fSelectClose(s); + fSelectOpen(s, "Direct HTTPS", "https_stats"); + fOption(s, 0, "Disabled", !c->enableHttpsStats); + fOption(s, 1, "Enabled (needed without proxy)", c->enableHttpsStats); + fSelectClose(s); + fInput(s, "Custom stats API URL (optional)", "stats_api", c->statsApiUrl, 127); + fInput(s, "HTTP proxy (optional)", "stats_proxy", c->statsProxyUrl, 127); + + s += "

Access

"; + fSelectOpen(s, "Wallet in API responses", "api_wallet"); + fOption(s, 0, "Masked", !nvs_api_expose_wallet()); + fOption(s, 1, "Full address", nvs_api_expose_wallet()); + fSelectClose(s); + fInput(s, "New settings password", "web_pass", "", 32, "password", "leave empty to keep current"); + s += "
"; + s += "
"; + s += "
" + "
"; + s += "

Saving restarts the miner. This page is back after about 20 seconds.

"; + s_server->sendContent(s); + s_server->sendContent(""); // Terminate chunked response +} + +// ============================================================ +// POST /settings +// ============================================================ + +static void handleSettingsPost() { + if (!settingsAuth()) return; + if (!settingsSameOrigin()) { + settingsMessage(403, "Rejected", "Cross-site request blocked.", false); + return; + } + + const miner_config_t *cur = nvs_config_get(); + miner_config_t c = *cur; + const char *err = NULL; + + char ssid[33]; + char wifiPass[64] = ""; + char webPass[33] = ""; + strncpy(ssid, cur->ssid, sizeof(ssid) - 1); + ssid[sizeof(ssid) - 1] = '\0'; + + if (!argTo("ssid", ssid, sizeof(ssid)) || !ssid[0]) err = "WiFi network name is missing or too long."; + else if (!argTo("wifi_pass", wifiPass, sizeof(wifiPass))) err = "WiFi password is too long."; + else if (wifiPass[0] && strlen(wifiPass) < 8) err = "WiFi password needs at least 8 characters."; + else if (!argTo("wallet", c.wallet, sizeof(c.wallet)) || !c.wallet[0]) err = "Wallet address is missing or too long."; + else if (!argTo("worker", c.workerName, sizeof(c.workerName))) err = "Worker name is too long."; + else if (!argTo("pool_url", c.poolUrl, sizeof(c.poolUrl)) || !c.poolUrl[0]) err = "Pool URL is missing or too long."; + else if (!argPort("pool_port", &c.poolPort)) err = "Pool port must be 1-65535."; + else if (!argTo("pool_pass", c.poolPassword, sizeof(c.poolPassword))) err = "Pool password is too long."; + else if (!argTo("bk_url", c.backupPoolUrl, sizeof(c.backupPoolUrl))) err = "Backup pool URL is too long."; + else if (c.backupPoolUrl[0] && !argPort("bk_port", &c.backupPoolPort)) err = "Backup pool port must be 1-65535."; + else if (!argTo("bk_wallet", c.backupWallet, sizeof(c.backupWallet))) err = "Backup wallet is too long."; + else if (!argTo("bk_pass", c.backupPoolPassword, sizeof(c.backupPoolPassword))) err = "Backup pool password is too long."; + else if (!argTo("stats_api", c.statsApiUrl, sizeof(c.statsApiUrl))) err = "Stats API URL is too long."; + else if (!argTo("stats_proxy", c.statsProxyUrl, sizeof(c.statsProxyUrl))) err = "Proxy URL is too long."; + else if (!argTo("web_pass", webPass, sizeof(webPass))) err = "Settings password is too long (max 32)."; + else if (webPass[0] && strlen(webPass) < WEB_PASSWORD_MIN_LEN) err = "Settings password needs at least 8 characters."; + else if (strchr(c.poolUrl, ' ') || strchr(c.wallet, ' ')) err = "Pool URL and wallet must not contain spaces."; + else if (strpbrk(c.poolUrl, ":/") || strpbrk(c.backupPoolUrl, ":/")) err = "Pool URL: host name only (no stratum+tcp:// and no :port, the port has its own field)."; + + if (err) { + settingsMessage(400, "Not saved", err, false); + return; + } + + long v; + if (s_server->hasArg("bright")) { + v = s_server->arg("bright").toInt(); + c.brightness = (uint8_t)(v < 10 ? 10 : (v > 100 ? 100 : v)); + } + if (s_server->hasArg("scrn_to")) { + v = s_server->arg("scrn_to").toInt(); + c.screenTimeout = (uint16_t)(v < 0 ? 0 : (v > 3600 ? 3600 : v)); + } + if (s_server->hasArg("rotation")) { + v = s_server->arg("rotation").toInt(); + c.rotation = (uint8_t)(v < 0 || v > 3 ? 0 : v); + } + if (s_server->hasArg("tz")) { + v = s_server->arg("tz").toInt(); + c.timezoneOffset = (int8_t)(v < -12 ? -12 : (v > 14 ? 14 : v)); + } + if (s_server->hasArg("invert")) c.invertColors = (s_server->arg("invert").toInt() == 1); + if (s_server->hasArg("stats_en")) c.statsEnabled = (s_server->arg("stats_en").toInt() == 1); + if (s_server->hasArg("https_stats")) c.enableHttpsStats = (s_server->arg("https_stats").toInt() == 1); + bool exposeWallet = nvs_api_expose_wallet(); + if (s_server->hasArg("api_wallet")) exposeWallet = (s_server->arg("api_wallet").toInt() == 1); + + // WiFi: keep the current password unless a new one was entered. If anything + // changes, remember the working credentials so boot can fall back to them. + bool wifiChanged = (strcmp(ssid, cur->ssid) != 0) || + (wifiPass[0] && strcmp(wifiPass, cur->wifiPassword) != 0); + if (wifiChanged) { + nvs_wifi_prev_save(cur->ssid, cur->wifiPassword); + strncpy(c.ssid, ssid, sizeof(c.ssid) - 1); + c.ssid[sizeof(c.ssid) - 1] = '\0'; + if (wifiPass[0]) { + strncpy(c.wifiPassword, wifiPass, sizeof(c.wifiPassword) - 1); + c.wifiPassword[sizeof(c.wifiPassword) - 1] = '\0'; + } + } + + if (!nvs_config_save(&c)) { + settingsMessage(500, "Not saved", "Writing the configuration to flash failed.", false); + return; + } + nvs_api_save(nvs_api_enabled(), exposeWallet); + if (webPass[0]) nvs_web_password_set(webPass); + + web_api_log("SETTINGS saved via web (wifi %s), restarting", wifiChanged ? "changed" : "unchanged"); + settingsMessage(200, "Saved", wifiChanged + ? "Settings saved. The miner restarts and joins the new WiFi; its address may change (see display)." + : "Settings saved. The miner restarts now; this page returns to the status view in 20 seconds.", + !wifiChanged); + s_restartAtMs = millis() + 1500; +} + +// ============================================================ +// POST /settings/reset +// ============================================================ + +static void handleSettingsReset() { + if (!settingsAuth()) return; + if (!settingsSameOrigin()) { + settingsMessage(403, "Rejected", "Cross-site request blocked.", false); + return; + } + settingsMessage(200, "Factory reset", + "All settings are erased. Connect to the SparkMiner_XXXX hotspot (password minebitcoin) to set the miner up again.", + false); + s_wipeOnRestart = true; + s_restartAtMs = millis() + 1500; +} + +// Called from the API task loop: perform a pending restart once the response is out +static void settingsTick() { + if (!s_restartAtMs || (int32_t)(millis() - s_restartAtMs) < 0) return; + if (s_wipeOnRestart) { + nvs_factory_reset(); + WiFi.disconnect(true, true); + delay(300); + } + ESP.restart(); +} + +#endif // WEB_SETTINGS_H diff --git a/src/config/nvs_config.cpp b/src/config/nvs_config.cpp index b7eea07..7fac4f2 100644 --- a/src/config/nvs_config.cpp +++ b/src/config/nvs_config.cpp @@ -277,6 +277,13 @@ static bool loadConfigFromFile(miner_config_t *config) { config->enableHttpsStats = doc["enable_https_stats"]; } + // Local stats API (optional, stored as separate NVS keys) + if (doc.containsKey("api_enabled") || doc.containsKey("api_expose_wallet")) { + bool apiEn = doc["api_enabled"] | (bool)SPARKMINER_API_DEFAULT; + bool apiWallet = doc["api_expose_wallet"] | false; + nvs_api_save(apiEn, apiWallet); + } + // Config file stays on SD card - NOT deleted // It will only be read again if NVS is reset/cleared @@ -572,8 +579,16 @@ void nvs_config_reset(miner_config_t *config) { config->brightness = 100; config->screenTimeout = 0; // Never timeout config->rotation = 0; // Portrait USB Top (default) + #if defined(LILYGO_T_DISPLAY_S3) + config->rotation = 1; // 170x320 panel reads best in landscape + #endif config->displayEnabled = true; config->invertColors = true; // Dark theme (default) - CYD panel is inverted, so invertDisplay(true) = dark + #if defined(LILYGO_T_DISPLAY_S3) + // ST7789 IPS panel: inversion ON is its normal state, so "false" is the + // dark theme here - matching the portal's "Dark (Default)" option. + config->invertColors = false; + #endif config->timezoneOffset = 0; // UTC+0 default // Miner defaults @@ -766,3 +781,127 @@ void nvs_stats_update(uint64_t currentHashes, uint32_t currentShares, // Save to NVS nvs_stats_save(stats); } + +// ============================================================ +// Local Stats API settings (Issue #12) +// ============================================================ + +#define NVS_KEY_API_ENABLED "api_en" +#define NVS_KEY_API_WALLET "api_wallet" + +static bool s_apiLoaded = false; +static bool s_apiEnabled = SPARKMINER_API_DEFAULT; +static bool s_apiExposeWallet = false; + +static void loadApiSettings() { + if (s_apiLoaded) return; + s_apiEnabled = SPARKMINER_API_DEFAULT; + s_apiExposeWallet = false; + if (s_prefs.begin(NVS_NAMESPACE, true)) { + if (s_prefs.isKey(NVS_KEY_API_ENABLED)) { + s_apiEnabled = s_prefs.getBool(NVS_KEY_API_ENABLED, SPARKMINER_API_DEFAULT); + } + if (s_prefs.isKey(NVS_KEY_API_WALLET)) { + s_apiExposeWallet = s_prefs.getBool(NVS_KEY_API_WALLET, false); + } + s_prefs.end(); + } + s_apiLoaded = true; +} + +bool nvs_api_enabled() { + loadApiSettings(); + return s_apiEnabled; +} + +bool nvs_api_expose_wallet() { + loadApiSettings(); + return s_apiExposeWallet; +} + +bool nvs_api_save(bool enabled, bool exposeWallet) { + if (!s_prefs.begin(NVS_NAMESPACE, false)) { + Serial.println("[NVS] ERROR: Failed to open namespace for API settings"); + return false; + } + bool ok = s_prefs.putBool(NVS_KEY_API_ENABLED, enabled) > 0; + ok = (s_prefs.putBool(NVS_KEY_API_WALLET, exposeWallet) > 0) && ok; + s_prefs.end(); + s_apiEnabled = enabled; + s_apiExposeWallet = exposeWallet; + s_apiLoaded = true; + Serial.printf("[NVS] API settings saved: enabled=%d, exposeWallet=%d\n", enabled, exposeWallet); + return ok; +} + +// ============================================================ +// Web settings page +// ============================================================ + +#define NVS_KEY_WEB_PASS "web_pass" +#define NVS_KEY_PREV_SSID "prev_ssid" +#define NVS_KEY_PREV_PASS "prev_pass" + +void nvs_web_password_get(char *out, size_t outLen) { + if (!out || outLen == 0) return; + safeStrCpy(out, AP_PASSWORD, outLen); + if (s_prefs.begin(NVS_NAMESPACE, true)) { + if (s_prefs.isKey(NVS_KEY_WEB_PASS)) { + String p = s_prefs.getString(NVS_KEY_WEB_PASS, AP_PASSWORD); + if (p.length() > 0) safeStrCpy(out, p.c_str(), outLen); + } + s_prefs.end(); + } +} + +bool nvs_web_password_set(const char *password) { + if (!password || !password[0]) return false; + if (!s_prefs.begin(NVS_NAMESPACE, false)) return false; + bool ok = s_prefs.putString(NVS_KEY_WEB_PASS, password) > 0; + s_prefs.end(); + return ok; +} + +bool nvs_wifi_prev_save(const char *ssid, const char *password) { + if (!ssid || !ssid[0]) return false; + if (!s_prefs.begin(NVS_NAMESPACE, false)) return false; + bool ok = s_prefs.putString(NVS_KEY_PREV_SSID, ssid) > 0; + s_prefs.putString(NVS_KEY_PREV_PASS, password ? password : ""); + s_prefs.end(); + return ok; +} + +bool nvs_wifi_prev_load(char *ssid, size_t ssidLen, char *password, size_t passLen) { + if (!ssid || !password || ssidLen == 0 || passLen == 0) return false; + ssid[0] = '\0'; + password[0] = '\0'; + if (!s_prefs.begin(NVS_NAMESPACE, true)) return false; + bool found = s_prefs.isKey(NVS_KEY_PREV_SSID); + if (found) { + safeStrCpy(ssid, s_prefs.getString(NVS_KEY_PREV_SSID, "").c_str(), ssidLen); + if (s_prefs.isKey(NVS_KEY_PREV_PASS)) { + safeStrCpy(password, s_prefs.getString(NVS_KEY_PREV_PASS, "").c_str(), passLen); + } + } + s_prefs.end(); + return found && ssid[0] != '\0'; +} + +void nvs_wifi_prev_clear() { + if (!s_prefs.begin(NVS_NAMESPACE, true)) return; + bool found = s_prefs.isKey(NVS_KEY_PREV_SSID); + s_prefs.end(); + if (!found) return; // Nothing stored: avoid a flash write on every boot + if (s_prefs.begin(NVS_NAMESPACE, false)) { + s_prefs.remove(NVS_KEY_PREV_SSID); + s_prefs.remove(NVS_KEY_PREV_PASS); + s_prefs.end(); + } +} + +void nvs_factory_reset() { + if (s_prefs.begin(NVS_NAMESPACE, false)) { + s_prefs.clear(); + s_prefs.end(); + } +} diff --git a/src/config/nvs_config.h b/src/config/nvs_config.h index 9ae23f0..a4470ae 100644 --- a/src/config/nvs_config.h +++ b/src/config/nvs_config.h @@ -153,4 +153,45 @@ void nvs_stats_update(uint64_t currentHashes, uint32_t currentShares, uint32_t currentBlocks, uint32_t sessionSeconds, double bestDiff); +// ============================================================ +// Local Stats API settings (Issue #12) +// Stored as separate NVS keys (not in miner_config_t) so enabling the +// feature does not change the config blob layout and existing +// configurations survive the firmware update. +// ============================================================ + +// Build-time default when the key has never been written (upstream: OFF) +#ifndef SPARKMINER_API_DEFAULT + #define SPARKMINER_API_DEFAULT 0 +#endif + +/** Local HTTP stats API enabled? */ +bool nvs_api_enabled(); + +/** Expose the full wallet address in API responses? (default: masked) */ +bool nvs_api_expose_wallet(); + +/** Persist local stats API settings */ +bool nvs_api_save(bool enabled, bool exposeWallet); + +// ============================================================ +// Web settings page (separate NVS keys, same reasoning as above) +// ============================================================ + +/** Password for the /settings page (default: setup hotspot password) */ +void nvs_web_password_get(char *out, size_t outLen); +bool nvs_web_password_set(const char *password); + +/** + * WiFi credentials that worked before a change made on the settings page. + * Boot falls back to them if the new network cannot be joined, then clears + * them once a connection with the new credentials has succeeded. + */ +bool nvs_wifi_prev_save(const char *ssid, const char *password); +bool nvs_wifi_prev_load(char *ssid, size_t ssidLen, char *password, size_t passLen); +void nvs_wifi_prev_clear(); + +/** Erase every SparkMiner setting (config, stats, API keys) */ +void nvs_factory_reset(); + #endif // NVS_CONFIG_H diff --git a/src/config/wifi_manager.cpp b/src/config/wifi_manager.cpp index b4d179f..5ab4d26 100644 --- a/src/config/wifi_manager.cpp +++ b/src/config/wifi_manager.cpp @@ -10,6 +10,7 @@ #include "nvs_config.h" #include "../stratum/stratum.h" #include "../display/display.h" +#include "../api/web_api.h" // WiFiManager instance static WiFiManager s_wm; @@ -52,6 +53,13 @@ static WiFiManagerParameter* s_paramHttpsStats = NULL; static char s_statsEnabledHtml[512]; static char s_httpsStatsHtml[512]; +// Local stats API parameters (Issue #12) +static WiFiManagerParameter* s_paramApiHeader = NULL; +static WiFiManagerParameter* s_paramApiEnabled = NULL; +static WiFiManagerParameter* s_paramApiWallet = NULL; +static char s_apiEnabledHtml[512]; +static char s_apiWalletHtml[512]; + // Buffers for text inputs only static char s_bufPoolPort[8]; static char s_bufBackupPort[8]; @@ -136,6 +144,13 @@ static void saveParamsCallback() { config->enableHttpsStats = (atoi(s_paramHttpsStats->getValue()) == 1); } + // Local stats API (separate NVS keys - takes effect after restart) + if (s_paramApiEnabled && s_paramApiWallet) { + bool apiEn = (atoi(s_paramApiEnabled->getValue()) == 1); + bool apiWallet = (atoi(s_paramApiWallet->getValue()) == 1); + nvs_api_save(apiEn, apiWallet); + } + // Save to NVS if (nvs_config_save(config)) { Serial.println("[WIFI] Configuration saved successfully"); @@ -347,8 +362,33 @@ void wifi_manager_init() { // Use config value as default for hidden input s_paramHttpsStats = new WiFiManagerParameter("https_stats", "Direct HTTPS", config->enableHttpsStats ? "1" : "0", 2, s_httpsStatsHtml); + // Local Stats API Settings (Issue #12) + const char* apiHeader = "

Local Stats API

AxeOS-compatible HTTP API for HashWatcher / Home Assistant (http://<ip>/api/system/info). Off = no web server, zero hashrate cost.
"; + s_paramApiHeader = new WiFiManagerParameter(apiHeader); + + bool apiEn = nvs_api_enabled(); + strcpy(s_apiEnabledHtml, "
"); + s_paramApiEnabled = new WiFiManagerParameter("api_en", "Local Stats API", apiEn ? "1" : "0", 2, s_apiEnabledHtml); + + bool apiWallet = nvs_api_expose_wallet(); + strcpy(s_apiWalletHtml, "
"); + s_paramApiWallet = new WiFiManagerParameter("api_wallet", "Wallet in API", apiWallet ? "1" : "0", 2, s_apiWalletHtml); + // Configure WiFiManager s_wm.setDebugOutput(false); + s_wm.setHostname(web_api_get_hostname()); s_wm.setMinimumSignalQuality(20); s_wm.setConnectTimeout(30); s_wm.setConfigPortalTimeout(180); @@ -370,13 +410,13 @@ void wifi_manager_init() { "button:hover{background:#ff8c00;}" "div{padding:5px 0;}" // Hide redundant text inputs for dropdown fields (dropdowns handle these) - "input[name='bright'],input[name='scrn_to'],input[name='diff'],input[name='rotation'],input[name='invert'],input[name='https_stats'],input[name='tz'],input[name='stats_en']{display:none;}" + "input[name='bright'],input[name='scrn_to'],input[name='diff'],input[name='rotation'],input[name='invert'],input[name='https_stats'],input[name='tz'],input[name='stats_en'],input[name='api_en'],input[name='api_wallet']{display:none;}" "" "