-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_server.py
More file actions
1527 lines (1406 loc) · 66.3 KB
/
ui_server.py
File metadata and controls
1527 lines (1406 loc) · 66.3 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from concurrent.futures import ThreadPoolExecutor, as_completed
import ipaddress
import json
import os
import re
import subprocess
import sys
import time
from functools import lru_cache
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib import error, request
from urllib.parse import parse_qs, urlparse
from esp32_tools import apply_nerdminer_config_api_patch, esp32_status, read_serial_log, write_nerdminer_firmware_defaults
from miner_adapters import get_adapter
def app_base_dir() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
def resource_base_dir() -> Path:
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
return Path(sys._MEIPASS)
return app_base_dir()
BASE_DIR = app_base_dir()
status_file_value = os.getenv("MINER_STATUS_FILE") or os.getenv("BITAXE_STATUS_FILE") or "status.json"
STATUS_FILE = Path(status_file_value)
if not STATUS_FILE.is_absolute():
STATUS_FILE = BASE_DIR / STATUS_FILE
swarm_file_value = os.getenv("MINER_SWARM_FILE") or "swarm.json"
SWARM_FILE = Path(swarm_file_value)
if not SWARM_FILE.is_absolute():
SWARM_FILE = BASE_DIR / SWARM_FILE
nerdminer_config_value = os.getenv("NERDMINER_CONFIG_FILE") or "nerdminer-config.json"
NERDMINER_CONFIG_FILE = Path(nerdminer_config_value)
if not NERDMINER_CONFIG_FILE.is_absolute():
NERDMINER_CONFIG_FILE = BASE_DIR / NERDMINER_CONFIG_FILE
ENV_FILE = BASE_DIR / ".env"
ASSETS_DIR = resource_base_dir() / "assets"
HOST = os.getenv("MINER_UI_HOST") or os.getenv("BITAXE_UI_HOST", "0.0.0.0")
PORT = int(os.getenv("MINER_UI_PORT") or os.getenv("BITAXE_UI_PORT", "8787"))
EDITABLE_KEYS = {
"MINER_NAME",
"MINER_URL",
"MINER_API_PROFILE",
"MINER_INFO_PATH",
"MINER_ASIC_PATH",
"MINER_SETTINGS_PATH",
"MINER_RESTART_PATH",
"MINER_FREQUENCY_FIELD",
"MINER_VOLTAGE_FIELD",
"MINER_FAN_SPEED_FIELD",
"MINER_AUTO_FAN_FIELD",
"MINER_STATUS_FILE",
"MINER_LEARNING_FILE",
"MINER_SWARM_FILE",
"MINER_UI_HOST",
"MINER_UI_PORT",
"NERDMINER_SERIAL_PORT",
"NERDMINER_CONFIG_FILE",
"NERDMINER_URL",
"BITAXE_URL",
"BITAXE_RESTART_PATH",
"BITAXE_MODE",
"BITAXE_DRY_RUN",
"BITAXE_AUTO_FAN",
"BITAXE_LOOP_SECONDS",
"BITAXE_MIN_FREQUENCY",
"BITAXE_MAX_FREQUENCY",
"BITAXE_ABSOLUTE_MAX_FREQUENCY",
"BITAXE_FREQ_STEP",
"BITAXE_MIN_VOLTAGE",
"BITAXE_MAX_VOLTAGE",
"BITAXE_ABSOLUTE_MAX_VOLTAGE",
"BITAXE_VOLTAGE_STEP",
"BITAXE_TARGET_TEMP_C",
"BITAXE_HOT_TEMP_C",
"BITAXE_EMERGENCY_TEMP_C",
"BITAXE_ABSOLUTE_MAX_EMERGENCY_TEMP_C",
"BITAXE_COOL_TEMP_C",
"BITAXE_MAX_VR_TEMP_C",
"BITAXE_ABSOLUTE_MAX_VR_TEMP_C",
"BITAXE_MIN_INPUT_VOLTAGE_MV",
"BITAXE_MAX_POWER_W",
"BITAXE_ABSOLUTE_MAX_POWER_W",
"BITAXE_CLIMB_POWER_RATIO",
"BITAXE_MAX_ERROR_PERCENTAGE",
"BITAXE_MAX_DOMAIN_SPREAD_PERCENTAGE",
"BITAXE_CRITICAL_DOMAIN_SPREAD_PERCENTAGE",
"BITAXE_DOMAIN_SPREAD_POLLS",
"BITAXE_LEARNING_ENABLED",
"BITAXE_LEARNING_MIN_SAMPLES",
"BITAXE_LEARNING_BAD_LIMIT",
"BITAXE_LEARNING_RESTORE_MARGIN",
"BITAXE_LEARNING_EFFICIENCY_WEIGHT",
"BITAXE_ADAPTIVE_COOLDOWN_ENABLED",
"BITAXE_ADAPTIVE_MIN_COOLDOWN_SECONDS",
"BITAXE_ADAPTIVE_MAX_COOLDOWN_SECONDS",
"BITAXE_ADAPTIVE_STABLE_SAMPLES",
"BITAXE_MIN_FAN_PERCENT",
"BITAXE_MAX_FAN_PERCENT",
"BITAXE_STEP_COOLDOWN_SECONDS",
"BITAXE_USE_ASIC_OPTIONS",
}
CONFIG_RANGES = {
"MINER_UI_PORT": (1, 65535),
"BITAXE_LOOP_SECONDS": (5, 3600),
"BITAXE_MIN_FREQUENCY": (300, 800),
"BITAXE_MAX_FREQUENCY": (300, 800),
"BITAXE_ABSOLUTE_MAX_FREQUENCY": (300, 800),
"BITAXE_FREQ_STEP": (1, 100),
"BITAXE_MIN_VOLTAGE": (800, 1400),
"BITAXE_MAX_VOLTAGE": (800, 1400),
"BITAXE_ABSOLUTE_MAX_VOLTAGE": (800, 1400),
"BITAXE_VOLTAGE_STEP": (1, 100),
"BITAXE_TARGET_TEMP_C": (40, 85),
"BITAXE_HOT_TEMP_C": (45, 90),
"BITAXE_EMERGENCY_TEMP_C": (50, 95),
"BITAXE_ABSOLUTE_MAX_EMERGENCY_TEMP_C": (50, 95),
"BITAXE_COOL_TEMP_C": (30, 85),
"BITAXE_MAX_VR_TEMP_C": (40, 100),
"BITAXE_ABSOLUTE_MAX_VR_TEMP_C": (40, 100),
"BITAXE_MIN_INPUT_VOLTAGE_MV": (4000, 6000),
"BITAXE_MAX_POWER_W": (5, 30),
"BITAXE_ABSOLUTE_MAX_POWER_W": (5, 30),
"BITAXE_CLIMB_POWER_RATIO": (0.5, 0.99),
"BITAXE_MAX_ERROR_PERCENTAGE": (0, 100),
"BITAXE_MAX_DOMAIN_SPREAD_PERCENTAGE": (0, 100),
"BITAXE_CRITICAL_DOMAIN_SPREAD_PERCENTAGE": (0, 100),
"BITAXE_DOMAIN_SPREAD_POLLS": (1, 20),
"BITAXE_LEARNING_MIN_SAMPLES": (1, 1000),
"BITAXE_LEARNING_BAD_LIMIT": (1, 1000),
"BITAXE_LEARNING_RESTORE_MARGIN": (0, 1),
"BITAXE_LEARNING_EFFICIENCY_WEIGHT": (0, 1),
"BITAXE_ADAPTIVE_MIN_COOLDOWN_SECONDS": (1, 3600),
"BITAXE_ADAPTIVE_MAX_COOLDOWN_SECONDS": (1, 7200),
"BITAXE_ADAPTIVE_STABLE_SAMPLES": (1, 1000),
"BITAXE_MIN_FAN_PERCENT": (0, 100),
"BITAXE_MAX_FAN_PERCENT": (0, 100),
"BITAXE_STEP_COOLDOWN_SECONDS": (1, 7200),
}
BOOLEAN_KEYS = {
"BITAXE_DRY_RUN",
"BITAXE_AUTO_FAN",
"BITAXE_USE_ASIC_OPTIONS",
"BITAXE_LEARNING_ENABLED",
"BITAXE_ADAPTIVE_COOLDOWN_ENABLED",
}
MODE_VALUES = {"rules", "openai"}
PROFILE_VALUES = {"axeos", "generic-json", "futurebit", "braiins", "esp32", "nerdminer"}
LIVE_PROBE_TTL_SECONDS = 12
LIVE_PROBE_TIMEOUT_SECONDS = 0.8
LIVE_PROBE_CACHE: dict[str, tuple[float, dict]] = {}
_LIVE_PROBE_CACHE_MAX = 256
NERDMINER_PROBE_PATHS = ("/api/status", "/status", "/api", "/")
GENERIC_PROBE_PATHS = ("/api/system/info", "/api/status", "/status", "/api", "/")
LOG_SERVICES = {
"controller": "bitaxe-agent",
"ui": "bitaxe-agent-ui",
}
DEFAULT_NERDMINER_CONFIG = {
"DeviceUrl": "",
"SSID": "",
"WifiPW": "",
"PoolUrl": "public-pool.io",
"PoolPort": 21496,
"PoolPassword": "x",
"BtcWallet": "",
"Timezone": 2,
"SaveStats": False,
}
SENSITIVE_LOG_PATTERNS = (
re.compile(r"(OPENAI_API_KEY|AI_API_KEY|API_KEY|TOKEN|PASSWORD|PASS|SECRET)(=|\s+)([^\s]+)", re.IGNORECASE),
re.compile(r"sk-[A-Za-z0-9_-]{12,}"),
)
def sanitize_env_value(key: str, value: str) -> str:
cleaned = value.strip()
if any(char in cleaned for char in ("\x00", "\n", "\r")):
raise ValueError(f"{key} cannot contain line breaks")
if any(char in cleaned for char in (";", "&", "|", "`", "$", "<", ">")):
raise ValueError(f"{key} contains an unsupported shell-control character")
return cleaned
def validate_config_value(key: str, value: str) -> None:
if key in BOOLEAN_KEYS and value.strip().lower() not in {"1", "0", "true", "false", "yes", "no", "on", "off"}:
raise ValueError(f"{key} must be a boolean")
if key == "BITAXE_MODE" and value.strip().lower() not in MODE_VALUES:
raise ValueError(f"{key} must be one of: {', '.join(sorted(MODE_VALUES))}")
if key == "MINER_API_PROFILE" and value.strip().lower() not in PROFILE_VALUES:
raise ValueError(f"{key} must be one of: {', '.join(sorted(PROFILE_VALUES))}")
if key in CONFIG_RANGES:
try:
number = float(value)
except ValueError as exc:
raise ValueError(f"{key} must be a number") from exc
lower, upper = CONFIG_RANGES[key]
if number < lower or number > upper:
raise ValueError(f"{key} must be between {lower} and {upper}")
def parse_env_file() -> dict[str, str]:
values: dict[str, str] = {}
if not ENV_FILE.exists():
return values
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
if not line or line.lstrip().startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip()
return values
def write_env_file(updates: dict[str, str]) -> dict[str, str]:
existing = parse_env_file()
validated: dict[str, str] = {}
for key, value in updates.items():
cleaned = sanitize_env_value(key, value)
validate_config_value(key, cleaned)
validated[key] = cleaned
existing.update(validated)
lines = [f"{key}={value}" for key, value in existing.items()]
ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")
return validated
def read_nerdminer_config(redacted: bool = True) -> dict:
values = dict(DEFAULT_NERDMINER_CONFIG)
if NERDMINER_CONFIG_FILE.exists():
data = json.loads(NERDMINER_CONFIG_FILE.read_text(encoding="utf-8"))
if isinstance(data, dict):
for key in DEFAULT_NERDMINER_CONFIG:
if key in data:
values[key] = data[key]
has_wifi_password = bool(str(values.get("WifiPW") or ""))
has_pool_password = bool(str(values.get("PoolPassword") or ""))
if redacted:
values["WifiPW"] = ""
values["PoolPassword"] = ""
return {
"values": values,
"config_file": str(NERDMINER_CONFIG_FILE),
"exists": NERDMINER_CONFIG_FILE.exists(),
"has_wifi_password": has_wifi_password,
"has_pool_password": has_pool_password,
"apply_hint": "Saved locally. Stock NerdMiner_v2 still needs SD or WiFiManager; for no-SD boards, build these values into the patched firmware and flash once.",
}
def validate_nerdminer_config(payload: dict) -> dict:
existing = read_nerdminer_config(redacted=False)["values"]
values = dict(existing)
string_keys = ("DeviceUrl", "SSID", "WifiPW", "PoolUrl", "PoolPassword", "BtcWallet")
for key in string_keys:
if key not in payload:
continue
value = str(payload.get(key) or "").strip()
if any(char in value for char in ("\x00", "\n", "\r")):
raise ValueError(f"{key} cannot contain line breaks")
if key in {"WifiPW", "PoolPassword"} and value == "":
continue
values[key] = value
if "PoolPort" in payload:
try:
pool_port = int(str(payload.get("PoolPort") or "").strip())
except ValueError as exc:
raise ValueError("PoolPort must be a number") from exc
if pool_port < 1 or pool_port > 65535:
raise ValueError("PoolPort must be between 1 and 65535")
values["PoolPort"] = pool_port
if "Timezone" in payload:
try:
timezone = int(str(payload.get("Timezone") or "").strip())
except ValueError as exc:
raise ValueError("Timezone must be a number") from exc
if timezone < -12 or timezone > 14:
raise ValueError("Timezone must be between -12 and 14")
values["Timezone"] = timezone
if "SaveStats" in payload:
raw = payload.get("SaveStats")
values["SaveStats"] = raw is True or str(raw).strip().lower() in {"1", "true", "yes", "on"}
return values
def write_nerdminer_config(payload: dict) -> dict:
values = validate_nerdminer_config(payload)
NERDMINER_CONFIG_FILE.write_text(json.dumps(values, indent=2) + "\n", encoding="utf-8")
return read_nerdminer_config(redacted=True)
def default_nerdminer_url(values: dict | None = None) -> str:
values = values or read_nerdminer_config(redacted=False)["values"]
if values.get("DeviceUrl"):
return str(values["DeviceUrl"])
env_url = os.getenv("NERDMINER_URL", "").strip()
if env_url:
return env_url
config = parse_env_file()
if (config.get("MINER_API_PROFILE") or "").strip().lower() in {"nerdminer", "esp32"}:
return config.get("MINER_URL") or ""
for miner in read_swarm_config():
if str(miner.get("api_profile") or "").strip().lower() in {"nerdminer", "esp32"}:
return str(miner.get("url") or "")
return ""
def nerdminer_device_payload(values: dict) -> dict:
return {
"SSID": values.get("SSID") or "",
"WifiPW": values.get("WifiPW") or "",
"PoolUrl": values.get("PoolUrl") or "public-pool.io",
"PoolPort": int(values.get("PoolPort") or 21496),
"PoolPassword": values.get("PoolPassword") or "x",
"BtcWallet": values.get("BtcWallet") or "",
"Timezone": int(values.get("Timezone") or 2),
"SaveStats": bool(values.get("SaveStats")),
"Restart": True,
}
def apply_nerdminer_config_to_device(payload: dict) -> dict:
values = validate_nerdminer_config(payload)
url = normalize_base_url(str(payload.get("DeviceUrl") or default_nerdminer_url(values)))
if not url:
raise ValueError("NerdMiner device URL is required")
body = json.dumps(nerdminer_device_payload(values)).encode("utf-8")
req = request.Request(f"{url}/api/config", data=body, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("Connection", "close")
try:
with request.urlopen(req, timeout=8) as response:
text = response.read().decode("utf-8", errors="ignore")
except error.HTTPError as exc:
text = exc.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"NerdMiner API returned HTTP {exc.code}: {text or exc.reason}") from exc
except (TimeoutError, error.URLError) as exc:
raise RuntimeError(f"NerdMiner API request failed: {exc}") from exc
device_response = json.loads(text) if text else {"ok": True}
return {
"ok": bool(device_response.get("ok", True)),
"url": url,
"device_response": device_response,
"message": "Config sent to NerdMiner. The ESP32 should restart if the firmware API accepted it.",
}
def build_nerdminer_firmware_defaults(payload: dict) -> dict:
values = validate_nerdminer_config(payload)
write_nerdminer_config(payload)
patch = apply_nerdminer_config_api_patch()
defaults = write_nerdminer_firmware_defaults(values)
defaults["patch"] = patch
defaults["message"] = "Firmware API patch and private defaults are ready. Rebuild and flash NerdMiner_v2 once; after that, use Apply to Patched ESP32 for live changes."
return defaults
def redact_log_line(line: str) -> str:
redacted = line
for pattern in SENSITIVE_LOG_PATTERNS:
redacted = pattern.sub(lambda match: f"{match.group(1)}{match.group(2)}[redacted]" if match.lastindex and match.lastindex >= 2 else "[redacted]", redacted)
return redacted
def service_logs(service: str, lines: int, port: str = "") -> dict:
service_key = (service or "controller").strip().lower()
if service_key == "nerdminer":
payload = read_serial_log(port=port, seconds=3.5)
payload["lines"] = [redact_log_line(line) for line in payload.get("lines", [])[-max(20, min(int(lines or 120), 500)):]]
return payload
unit = LOG_SERVICES.get(service_key)
if not unit:
supported = sorted([*LOG_SERVICES.keys(), "nerdminer"])
raise ValueError(f"service must be one of: {', '.join(supported)}")
bounded_lines = max(20, min(int(lines or 120), 500))
try:
result = subprocess.run(
["journalctl", "-u", unit, "-n", str(bounded_lines), "--no-pager", "--output", "short-iso"],
capture_output=True,
text=True,
check=False,
timeout=8,
)
except FileNotFoundError:
return {
"ok": False,
"service": service_key,
"unit": unit,
"lines": [],
"message": "journalctl is not available on this system.",
}
except subprocess.TimeoutExpired:
return {
"ok": False,
"service": service_key,
"unit": unit,
"lines": [],
"message": "Log request timed out.",
}
output = result.stdout if result.returncode == 0 else result.stderr or result.stdout
return {
"ok": result.returncode == 0,
"service": service_key,
"unit": unit,
"lines": [redact_log_line(line) for line in output.splitlines()[-bounded_lines:]],
"message": "Logs loaded." if result.returncode == 0 else "Unable to read service logs.",
}
def read_status() -> dict:
if not STATUS_FILE.exists():
return {"status": "waiting_for_controller"}
return json.loads(STATUS_FILE.read_text(encoding="utf-8"))
def read_json_file(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def display_miner_url(url: str) -> str:
parsed = urlparse(url)
if parsed.hostname:
return parsed.hostname
return url.replace("http://", "").replace("https://", "").split("/", 1)[0]
def read_swarm_config() -> list[dict]:
if not SWARM_FILE.exists():
config = parse_env_file()
return [{
"id": "primary",
"name": config.get("MINER_NAME") or "Primary Miner",
"url": config.get("MINER_URL") or config.get("BITAXE_URL") or "",
"api_profile": config.get("MINER_API_PROFILE") or "axeos",
"status_file": str(STATUS_FILE),
}]
payload = read_json_file(SWARM_FILE)
miners = payload.get("miners", [])
if not isinstance(miners, list):
raise ValueError("swarm.json must contain a miners list")
return miners
def write_swarm_config(miners: list[dict]) -> None:
SWARM_FILE.write_text(json.dumps({"miners": miners}, indent=2) + "\n", encoding="utf-8")
def add_swarm_miner(payload: dict) -> dict:
url = str(payload.get("url") or "").strip().rstrip("/")
if not url:
raise ValueError("url is required")
if not url.startswith(("http://", "https://")):
url = f"http://{url}"
name = str(payload.get("name") or display_miner_url(url) or "Miner").strip()
miner_id = "".join(char.lower() if char.isalnum() else "-" for char in name).strip("-") or "miner"
miners = read_swarm_config()
existing_ids = {str(miner.get("id")) for miner in miners}
base_id = miner_id
counter = 2
while miner_id in existing_ids:
miner_id = f"{base_id}-{counter}"
counter += 1
status_name = f"status-{miner_id}.json"
api_profile = str(payload.get("api_profile") or "axeos").strip().lower()
if api_profile not in PROFILE_VALUES:
raise ValueError(f"api_profile must be one of: {', '.join(sorted(PROFILE_VALUES))}")
miner = {
"id": miner_id,
"name": name,
"url": url,
"api_profile": api_profile,
"status_file": str(payload.get("status_file") or status_name),
}
miners.append(miner)
write_swarm_config(miners)
return miner
def remove_swarm_miner(payload: dict) -> dict:
miner_id = str(payload.get("id") or "").strip()
if not miner_id:
raise ValueError("id is required")
if miner_id == "primary":
raise ValueError("primary miner cannot be removed from the fleet")
miners = read_swarm_config()
kept = [miner for miner in miners if str(miner.get("id")) != miner_id]
if len(kept) == len(miners):
raise ValueError(f"miner {miner_id} was not found")
write_swarm_config(kept)
return {"ok": True, "removed": miner_id}
def resolve_status_file(path_value: str) -> Path:
path = Path(path_value)
if not path.is_absolute():
path = BASE_DIR / path
return path
def normalize_base_url(url: str) -> str:
cleaned = str(url or "").strip().rstrip("/")
if cleaned and not cleaned.startswith(("http://", "https://")):
cleaned = f"http://{cleaned}"
return cleaned
def probe_paths_for_profile(profile: str) -> tuple[str, ...]:
if profile in {"nerdminer", "esp32"}:
return NERDMINER_PROBE_PATHS
return GENERIC_PROBE_PATHS
def _evict_live_probe_cache() -> None:
"""Remove expired entries; if still over limit, evict oldest by timestamp."""
if len(LIVE_PROBE_CACHE) <= _LIVE_PROBE_CACHE_MAX:
return
now = time.time()
expired = [k for k, (ts, _) in LIVE_PROBE_CACHE.items() if now - ts > LIVE_PROBE_TTL_SECONDS]
for k in expired:
del LIVE_PROBE_CACHE[k]
if len(LIVE_PROBE_CACHE) > _LIVE_PROBE_CACHE_MAX:
oldest = sorted(LIVE_PROBE_CACHE, key=lambda k: LIVE_PROBE_CACHE[k][0])
for k in oldest[: len(LIVE_PROBE_CACHE) - _LIVE_PROBE_CACHE_MAX]:
del LIVE_PROBE_CACHE[k]
def probe_live_miner(miner: dict) -> dict | None:
profile = str(miner.get("api_profile") or "generic-json").strip().lower()
base_url = normalize_base_url(str(miner.get("url") or ""))
if not base_url:
return None
cache_key = f"{profile}:{base_url}"
cached = LIVE_PROBE_CACHE.get(cache_key)
if cached and time.time() - cached[0] < LIVE_PROBE_TTL_SECONDS:
return dict(cached[1])
adapter = get_adapter(profile)
fallback: dict | None = None
for path in probe_paths_for_profile(profile):
url = f"{base_url}{path}"
req = request.Request(url, method="GET")
req.add_header("Connection", "close")
try:
with request.urlopen(req, timeout=LIVE_PROBE_TIMEOUT_SECONDS) as response:
body = response.read(65536)
content_type = response.headers.get("Content-Type", "")
except Exception as exc:
fallback = {
"online": False,
"stale": True,
"last_error": f"live probe failed: {exc}",
}
continue
text = body.decode("utf-8", errors="ignore").strip()
if text:
try:
data = json.loads(text)
except json.JSONDecodeError:
data = None
if isinstance(data, dict):
normalized = adapter.normalize(data, {})
result = {
"online": True,
"stale": False,
"status_age_seconds": 0.0,
"temperature_c": normalized.get("temperature_c") or None,
"hashrate_gh": normalized.get("hashrate_gh") or None,
"power_w": normalized.get("power_w") or None,
"frequency_mhz": normalized.get("frequency_mhz") or None,
"domain_spread_percentage": normalized.get("domain_spread_percentage") or None,
"last_error": None,
"probe_source": path,
}
_evict_live_probe_cache()
LIVE_PROBE_CACHE[cache_key] = (time.time(), result)
return dict(result)
readable_type = content_type.split(";", 1)[0] or "HTTP"
fallback = {
"online": True,
"stale": False,
"status_age_seconds": 0.0,
"last_error": f"Device is reachable, but stock NerdMiner does not expose live stats over HTTP ({readable_type}).",
"probe_source": path,
}
break
if fallback:
_evict_live_probe_cache()
LIVE_PROBE_CACHE[cache_key] = (time.time(), fallback)
return dict(fallback)
return None
def summarize_miner(miner: dict) -> dict:
status_path = resolve_status_file(str(miner.get("status_file") or "status.json"))
profile = str(miner.get("api_profile") or "axeos").strip().lower()
summary = {
"id": str(miner.get("id") or miner.get("name") or status_path.stem),
"name": str(miner.get("name") or "Miner"),
"url": display_miner_url(str(miner.get("url") or "")),
"api_profile": profile,
"status_file": str(status_path),
"online": False,
"stale": True,
"status_age_seconds": None,
"temperature_c": None,
"hashrate_gh": None,
"power_w": None,
"frequency_mhz": None,
"domain_spread_percentage": None,
"last_error": None,
}
if not status_path.exists():
live = probe_live_miner(miner)
if live:
summary.update(live)
return summary
summary["last_error"] = "status file missing"
return summary
age_seconds = max(0.0, time.time() - status_path.stat().st_mtime)
summary["status_age_seconds"] = round(age_seconds, 3)
summary["stale"] = age_seconds > 120
try:
status = read_json_file(status_path)
except Exception as exc:
summary["last_error"] = f"status read failed: {exc}"
return summary
state = status.get("state") or {}
config = status.get("config") or {}
summary.update({
"online": bool(state) and not summary["stale"],
"temperature_c": state.get("temperature_c"),
"hashrate_gh": state.get("hashrate_gh"),
"power_w": state.get("power_w"),
"frequency_mhz": state.get("frequency_mhz"),
"domain_spread_percentage": state.get("domain_spread_percentage"),
"mode": config.get("mode"),
"dry_run": config.get("dry_run"),
"last_error": status.get("last_error"),
})
if summary["stale"] and profile in {"nerdminer", "esp32", "generic-json"}:
live = probe_live_miner(miner)
if live:
summary.update(live)
return summary
def swarm_status() -> dict:
miners = [summarize_miner(miner) for miner in read_swarm_config()]
online = [miner for miner in miners if miner.get("online")]
total_hashrate = sum(float(miner.get("hashrate_gh") or 0) for miner in miners)
total_power = sum(float(miner.get("power_w") or 0) for miner in miners)
hottest = max((float(miner.get("temperature_c") or 0) for miner in miners), default=0.0)
return {
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"swarm_file": str(SWARM_FILE),
"miners": miners,
"summary": {
"total_miners": len(miners),
"online_miners": len(online),
"total_hashrate_gh": total_hashrate,
"total_power_w": total_power,
"hottest_temperature_c": hottest,
"efficiency_gh_per_w": total_hashrate / total_power if total_power > 0 else None,
},
}
def discover_miners() -> dict:
config = parse_env_file()
base_url = config.get("MINER_URL") or config.get("BITAXE_URL")
if not base_url:
return {"devices": [], "message": "MINER_URL or BITAXE_URL is not configured."}
parsed = urlparse(base_url if "://" in base_url else f"http://{base_url}")
if not parsed.hostname:
return {"devices": [], "message": "Unable to detect subnet from configured miner URL."}
info_path = config.get("MINER_INFO_PATH") or "/api/system/info"
if not info_path.startswith("/"):
info_path = f"/{info_path}"
try:
network = ipaddress.ip_network(f"{parsed.hostname}/24", strict=False)
except ValueError as exc:
return {"devices": [], "message": f"Subnet scan unavailable: {exc}"}
known_hosts = {
display_miner_url(str(miner.get("url") or ""))
for miner in read_swarm_config()
}
def probe(host: str) -> dict | None:
url = f"http://{host}{info_path}"
req = request.Request(url, method="GET")
req.add_header("Connection", "close")
try:
with request.urlopen(req, timeout=0.35) as response:
text = response.read(65536).decode("utf-8", errors="ignore")
data = json.loads(text) if text else {}
except Exception:
return None
bitaxe_signals = ("axeOSVersion", "ASICModel", "deviceModel", "frequency", "voltage")
if not any(key in data for key in bitaxe_signals):
return None
return {
"name": str(data.get("hostname") or data.get("deviceModel") or f"Bitaxe {host}"),
"url": f"http://{host}",
"api_profile": "axeos",
"version": data.get("axeOSVersion") or data.get("version"),
"registered": host in known_hosts,
}
devices: list[dict] = []
hosts = [str(host) for host in network.hosts()]
with ThreadPoolExecutor(max_workers=48) as pool:
future_map = {pool.submit(probe, host): host for host in hosts}
for future in as_completed(future_map):
result = future.result()
if result:
devices.append(result)
devices.sort(key=lambda item: item["url"])
return {
"devices": devices,
"message": f"Found {len(devices)} Bitaxe-like device(s) on {network}.",
}
def update_status() -> dict:
def run_git(args: list[str], timeout: int = 12) -> subprocess.CompletedProcess:
return subprocess.run(["git", *args], cwd=BASE_DIR, capture_output=True, text=True, check=False, timeout=timeout)
current = run_git(["rev-parse", "--short", "HEAD"])
branch = run_git(["branch", "--show-current"])
upstream = run_git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
result = {
"current": current.stdout.strip() if current.returncode == 0 else "unknown",
"branch": branch.stdout.strip() if branch.returncode == 0 else "unknown",
"upstream": upstream.stdout.strip() if upstream.returncode == 0 else "",
"update_available": False,
"behind": 0,
"ahead": 0,
"message": "No upstream configured.",
}
if upstream.returncode != 0:
return result
fetch = run_git(["fetch", "--quiet"], timeout=30)
if fetch.returncode != 0:
result["message"] = fetch.stderr.strip() or "git fetch failed"
return result
counts = run_git(["rev-list", "--left-right", "--count", "HEAD...@{u}"])
if counts.returncode != 0:
result["message"] = counts.stderr.strip() or "unable to compare with upstream"
return result
ahead, behind = [int(part) for part in counts.stdout.strip().split()]
result.update({
"ahead": ahead,
"behind": behind,
"update_available": behind > 0,
"message": "Update available." if behind > 0 else "Already up to date.",
})
return result
def health_status() -> dict:
payload = {
"ok": True,
"ui": "running",
"status_file": str(STATUS_FILE),
"status_exists": STATUS_FILE.exists(),
}
if STATUS_FILE.exists():
age_seconds = max(0.0, time.time() - STATUS_FILE.stat().st_mtime)
payload["status_age_seconds"] = round(age_seconds, 3)
payload["controller_fresh"] = age_seconds <= 120
else:
payload["ok"] = False
payload["controller_fresh"] = False
return payload
def read_asset(path: str) -> tuple[bytes, str]:
relative = path.removeprefix("/assets/")
candidate = (ASSETS_DIR / relative).resolve()
# Use relative_to() instead of startswith() so symlinks that escape the
# assets directory are rejected correctly on all platforms.
try:
candidate.relative_to(ASSETS_DIR.resolve())
except ValueError:
raise FileNotFoundError(path)
if not candidate.is_file():
raise FileNotFoundError(path)
suffix = candidate.suffix.lower()
content_type = "text/plain; charset=utf-8"
if suffix == ".css":
content_type = "text/css; charset=utf-8"
elif suffix == ".js":
content_type = "application/javascript; charset=utf-8"
elif suffix == ".json":
content_type = "application/json; charset=utf-8"
return candidate.read_bytes(), content_type
@lru_cache(maxsize=64)
def read_asset_cached(path: str) -> tuple[bytes, str]:
return read_asset(path)
def post_json(url: str, max_retries: int = 2) -> dict:
req = request.Request(url, data=b"", method="POST")
req.add_header("Connection", "close")
for attempt in range(max_retries + 1):
try:
with request.urlopen(req, timeout=5) as response:
text = response.read().decode("utf-8")
return json.loads(text) if text else {"ok": True}
except error.HTTPError as exc:
text = exc.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"HTTP {exc.code}: {text or exc.reason}") from exc
except (TimeoutError, error.URLError) as exc:
if attempt >= max_retries:
raise RuntimeError(f"miner request failed after {max_retries + 1} attempts: {exc}") from exc
time.sleep(0.5 * (attempt + 1))
return {"ok": True}
def restart_controller_service() -> dict:
result = subprocess.run(
["systemctl", "restart", "bitaxe-agent"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "failed to restart controller")
return {"ok": True}
def restart_bitaxe() -> dict:
config = parse_env_file()
bitaxe_url = config.get("MINER_URL") or config.get("BITAXE_URL")
if not bitaxe_url:
raise RuntimeError("MINER_URL or BITAXE_URL is not configured")
restart_path = config.get("MINER_RESTART_PATH") or config.get("BITAXE_RESTART_PATH") or "/api/system/restart"
if not restart_path.startswith("/"):
restart_path = f"/{restart_path}"
return post_json(f"{bitaxe_url.rstrip('/')}{restart_path}")
def html() -> str:
return """<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<meta name=\"theme-color\" content=\"#0d1218\">
<meta name=\"description\" content=\"Bitaxe Agent dashboard for guarded miner tuning and telemetry\">
<title>Bitaxe Agent</title>
<link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' rx='20' fill='%230d1218'/%3E%3Ctext x='50' y='58' text-anchor='middle' font-size='34' font-family='Arial' font-weight='700' fill='%2300ff9c'%3EBA%3C/text%3E%3C/svg%3E\">
<link rel=\"stylesheet\" href=\"/assets/dashboard.css\">
<link rel=\"stylesheet\" href=\"/assets/dashboard-polish.css\">
<link rel=\"stylesheet\" href=\"/assets/dashboard-redesign.css?v=20260510-firmware-defaults\">
<link rel=\"stylesheet\" href=\"/assets/dashboard-ui-improvements.css?v=20260510\">
</head>
<body>
<div class=\"app-shell\">
<aside class=\"sidebar\">
<div class=\"brand-mark\">BA</div>
<nav class=\"nav\">
<a class=\"nav-link active\" href=\"#summarySec\" data-nav=\"summarySec\"><span class=\"nav-label\">Overview</span></a>
<a class=\"nav-link\" href=\"#statsSec\" data-nav=\"statsSec\"><span class=\"nav-label\">Metrics</span></a>
<a class=\"nav-link\" href=\"#trendsSec\" data-nav=\"trendsSec\"><span class=\"nav-label\">Trends</span></a>
<a class=\"nav-link\" href=\"#swarmSec\" data-nav=\"swarmSec\"><span class=\"nav-label\">Fleet</span></a>
<a class=\"nav-link\" href=\"#esp32Sec\" data-nav=\"esp32Sec\"><span class=\"nav-label\">ESP32</span></a>
<a class=\"nav-link\" href=\"#domainsSec\" data-nav=\"domainsSec\"><span class=\"nav-label\">ASICs</span></a>
<a class=\"nav-link\" href=\"#configSec\" data-nav=\"configSec\"><span class=\"nav-label\">Settings</span></a>
</nav>
<div class=\"sidebar-meta\">Bitaxe Agent</div>
</aside>
<main class=\"workspace\">
<header class=\"topbar\">
<div class=\"search-wrap\">
<input id=\"sectionSearch\" type=\"search\" placeholder=\"Search sections, metrics, or controls\">
</div>
<div class=\"profile\">
<div class=\"avatar\">OP</div>
<div class=\"profile-copy\">
<strong>Operations Console</strong>
<span id=\"updatedAt\">Waiting for telemetry</span>
</div>
</div>
</header>
<section id=\"summarySec\" class=\"section-card panel\">
<div class=\"panel-body\">
<div class=\"hero-grid\">
<div>
<div class=\"eyebrow\">Live Miner Control</div>
<h1 class=\"heading-xl\">Bitaxe Agent Dashboard</h1>
<p class=\"summary-copy\" id=\"heroText\">Synchronizing controller state, thermals, tuning limits, and live miner telemetry.</p>
<div class=\"summary-strip\">
<span id=\"health\" class=\"status-pill ok\"><span class=\"pulse\"></span><span>Online</span></span>
<span class=\"chip\" id=\"modeChip\">Mode: -</span>
<span class=\"chip\" id=\"dryRunChip\">Dry Run: -</span>
<span class=\"chip\" id=\"fanChip\">Fan: -</span>
<span class=\"chip\" id=\"stabilityChip\">Stability: -</span>
<span class=\"chip\" id=\"domainGuardChip\">Domain Guard: -</span>
<span class=\"chip\" id=\"updatedChip\">Updated: -</span>
</div>
</div>
<div class=\"panel\">
<div class=\"panel-body\">
<div class=\"section-head\">
<div>
<div class=\"eyebrow\">Recommended Action</div>
<h2 class=\"heading-md\" id=\"decisionReason\">Loading decision</h2>
</div>
</div>
<div class=\"decision-text\" id=\"decisionPatch\">Waiting for the controller to choose the safest next step.</div>
<div class=\"decision-hint\" id=\"decisionHint\">The controller will describe why it is holding, climbing, or rolling back.</div>
<div class=\"decision-actions\" style=\"margin-top:16px;\">
<button type=\"button\" class=\"btn-secondary\" id=\"applySafeBtn\">Apply Safe Rails</button>
<button type=\"button\" class=\"btn-secondary\" id=\"restartControllerBtn\">Restart Controller</button>
<button type=\"button\" class=\"btn-danger\" id=\"restartMinerBtn\">Restart Miner</button>
</div>
<div class=\"panel-copy\" id=\"actionMessage\">No operator action pending.</div>
</div>
</div>
</div>
</div>
</section>
<section id=\"statsSec\" class=\"section-card\">
<div class=\"stat-grid\" id=\"overview\"></div>
</section>
<section id=\"swarmSec\" class=\"section-card\">
<div class=\"panel swarm-panel\">
<div class=\"panel-body\">
<div class=\"section-head\">
<div>
<div class=\"eyebrow\">Swarm Control</div>
<h2 class=\"heading-md\">Fleet Overview</h2>
</div>
<button type=\"button\" class=\"btn-secondary\" id=\"checkUpdatesBtn\">Check Updates</button>
</div>
<div class=\"swarm-summary\">
<div><span class=\"mini-label\">Online</span><strong id=\"swarmOnline\">-</strong></div>
<div><span class=\"mini-label\">Hashrate</span><strong id=\"swarmHashrate\">-</strong></div>
<div><span class=\"mini-label\">Power</span><strong id=\"swarmPower\">-</strong></div>
<div><span class=\"mini-label\">Efficiency</span><strong id=\"swarmEfficiency\">-</strong></div>
</div>
<form id=\"swarmAddForm\" class=\"swarm-add-form\">
<input name=\"name\" placeholder=\"Nickname\">
<input name=\"url\" placeholder=\"Miner IP or URL\">
<select name=\"api_profile\">
<option value=\"axeos\">AxeOS / Bitaxe</option>
<option value=\"nerdminer\">NerdMiner / ESP32</option>
<option value=\"esp32\">Generic ESP32 Miner</option>
<option value=\"generic-json\">Generic JSON</option>
<option value=\"futurebit\">FutureBit</option>
<option value=\"braiins\">Braiins</option>
</select>
<button type=\"submit\" class=\"btn-secondary\">Add Device</button>
<button type=\"button\" class=\"btn-secondary\" id=\"rescanNetworkBtn\">Rescan Network</button>
</form>
<div id=\"discoveryNotice\" class=\"decision-hint hidden\">No new devices found yet.</div>
<div id=\"swarmGrid\" class=\"swarm-grid\"></div>
<div class=\"update-strip\" id=\"updateStrip\">
<span class=\"mini-label\">Updates</span>
<strong id=\"updateStatus\">Not checked yet</strong>
<span id=\"updateDetails\" class=\"muted\">Use Check Updates to compare this checkout with GitHub.</span>
</div>
</div>
</div>
</section>
<section id=\"trendsSec\" class=\"section-card\">
<div class=\"status-grid\">
<div class=\"panel\">
<div class=\"panel-body\">
<div class=\"section-head\">
<div>
<div class=\"eyebrow\">Trend Analysis</div>
<h2 class=\"heading-md\">Thermal And Power History</h2>
</div>
<div class=\"toolbar-group\">