-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·2483 lines (2058 loc) · 74.7 KB
/
run.py
File metadata and controls
executable file
·2483 lines (2058 loc) · 74.7 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
"""ReefBeat Devices Simulator fixture exporter.
This script snapshots ReefBeat device endpoints from:
- The local device HTTP API (by IP), and
- Optionally the ReefBeat cloud API (account-level endpoints).
Outputs are written as a fixture tree under ``devices/`` where each endpoint is
stored as a ``data`` file. Payloads are sanitized to remove secrets/PII while
preserving stable relationships (e.g. aquarium/device linkage).
Key entrypoints:
- ``python run.py scan``: Discover devices (cloud-fast listing or LAN CIDR scan).
- ``python run.py --ip <ip>``: Snapshot a local device (type auto-detected).
- ``python run.py --cloud``: Export cloud fixtures only.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import hashlib
import ipaddress
import json
import logging
import os
import random
import re
import subprocess
import sys
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final, Mapping, Union, cast
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from xml.dom import minidom
from xml.parsers.expat import ExpatError
try:
import colorlog # type: ignore[import]
has_colorlog = True
except Exception:
colorlog = None
has_colorlog = False
handler = logging.StreamHandler()
if has_colorlog:
formatter = colorlog.ColoredFormatter( # type: ignore[call-arg]
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s:%(reset)s %(message)s",
log_colors={
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
},
)
handler.setFormatter(formatter) # type: ignore[arg-type]
else:
handler.setFormatter(logging.Formatter("%(levelname)-8s: %(message)s"))
root = logging.getLogger()
root.setLevel(logging.INFO)
root.handlers[:] = []
root.addHandler(handler)
logger = logging.getLogger(__name__)
# =============================================================================
# Constants
# =============================================================================
CLOUD_SERVER_ADDR: Final[str] = "cloud.reef-beat.com"
# This Basic auth value is what the component uses for the OAuth token exchange.
# (It is not your username/password.)
CLOUD_BASIC_AUTH: Final[str] = "Basic Z0ZqSHRKcGE6Qzlmb2d3cmpEV09SVDJHWQ=="
HTTP_TIMEOUT_SECS_DEFAULT: Final[int] = 10
ENV_USERNAME: Final[str] = "REEFBEAT_USERNAME"
ENV_PASSWORD: Final[str] = "REEFBEAT_PASSWORD"
# Local device endpoints
BASE_URLS: Final[list[str]] = [
"/",
"/time",
"/description.xml",
"/cloud",
"/connectivity",
"/connectivity/events",
"/device-info",
"/device-settings",
"/dashboard",
"/mode",
"/firmware",
"/logging",
"/wifi",
"/wifi/scan",
]
ATO_URLS: Final[list[str]] = [
"/",
"/cloud",
"/dashboard",
"/device-info",
"/firmware",
"/logging",
"/mode",
"/time",
"/wifi",
"/description.xml",
"/configuration",
"/water-level",
"/temperature",
"/temperature-log",
]
DOSE2_URLS: Final[list[str]] = [
"/head/1/settings",
"/head/2/settings",
"/daily-log",
"/dosing-queue",
"/supplement",
"/head/1/supplement-volume",
"/head/2/supplement-volume",
"/export-log",
]
DOSE4_URLS: Final[list[str]] = [
*DOSE2_URLS,
"/head/3/settings",
"/head/4/settings",
"/head/3/supplement-volume",
"/head/4/supplement-volume",
]
MAT_URLS: Final[list[str]] = [
"/configuration",
]
LED_URLS: Final[list[str]] = [
"/manual",
"/acclimation",
"/moonphase",
"/current",
"/timer",
"/auto/1",
"/auto/2",
"/auto/3",
"/auto/4",
"/auto/5",
"/auto/6",
"/auto/7",
"/preset_name",
"/preset_name/1",
"/preset_name/2",
"/preset_name/3",
"/preset_name/4",
"/preset_name/5",
"/preset_name/6",
"/preset_name/7",
"/clouds/1",
"/clouds/2",
"/clouds/3",
"/clouds/4",
"/clouds/5",
"/clouds/6",
"/clouds/7",
]
RUN_URLS: Final[list[str]] = [
"/pump/settings",
]
WAVE_URLS: Final[list[str]] = [
"/controlling-mode",
"/feeding/schedule",
]
TYPE_MAP: Final[dict[str, list[str]]] = {
"ATO": ATO_URLS,
"DOSE": DOSE4_URLS, # alias
"DOSE2": DOSE2_URLS,
"DOSE4": DOSE4_URLS,
"MAT": MAT_URLS,
"LED": LED_URLS,
"RUN": RUN_URLS,
"WAVE": WAVE_URLS,
}
# Cloud endpoints (account-level). Keep this simple; add more later as needed.
CLOUD_URLS: Final[list[str]] = [
"/user",
"/aquarium",
"/device",
]
JsonScalar = Union[str, int, float, bool, None]
JsonValue = Union[JsonScalar, "JsonObject", "JsonArray"]
JsonObject = dict[str, JsonValue]
JsonArray = list[JsonValue]
SANITIZED_USER: Final[JsonObject] = {
"backup_email": "user@example.com",
"country": "United States",
"country_code": "US",
"created_at": "2025-01-01T00:00:00Z",
"email": "user@example.com",
"first_name": "User",
"id": 123456,
"language": "en",
"last_name": "User",
"mobile_number": "+10000000000",
"onboarding_complete": True,
"uid": "00000000-0000-0000-0000-000000000000",
"zip_code": "00000",
}
# Keep relationships stable across cloud fixtures
SANITIZED_AQUARIUM_ID: Final[int] = 111111
SANITIZED_AQUARIUM_UID: Final[str] = "00000000-0000-0000-0000-000000000001"
# Device/network identifiers in /device payloads
SANITIZED_IP_ADDRESS: Final[str] = "10.0.0.10"
SANITIZED_MAC: Final[str] = "00:11:22:33:44:55"
SANITIZED_BSSID: Final[str] = "66:55:44:33:22:11"
SANITIZED_HWID: Final[str] = "000000000000"
SANITIZED_SERIAL_CODE: Final[str] = "cf00000000000000"
SANITIZED_SSID: Final[str] = "REDACTED_SSID"
SANITIZED_GATEWAY: Final[str] = "10.0.0.1"
SANITIZED_SECRET: Final[str] = "REDACTED_SECRET"
# Aquarium naming can contain personal context; keep it generic
SANITIZED_AQUARIUM_NAME: Final[str] = "Aquarium"
SANITIZED_SYSTEM_MODEL: Final[str] = "Aquarium System"
# Hidden, local-only mapping used to keep sanitized IDs stable/unique across runs.
# Add this filename to your .gitignore.
SANITIZE_MAP_FILENAME: Final[str] = ".reefbeat_sanitize_map.json"
# Debugging aid:
# - When True, sanitize-map keys are SHA256 digests of raw values.
# - When False (default), sanitize-map keys are the raw values themselves (easier to debug, contains PII).
SANITIZE_MAP_USE_HASH_KEYS: Final[bool] = os.getenv(
"REEFBEAT_SANITIZE_MAP_USE_HASH_KEYS", "0"
) in {
"1",
"true",
"True",
"yes",
"YES",
}
_UUID_RE: Final[re.Pattern[str]] = re.compile(r"uuid:[0-9a-zA-Z\-]+")
# LED model strings look like RSLED90 / RSLED160 / RSLED115.
_RSLED_MODEL_RE: Final[re.Pattern[str]] = re.compile(
r"\bRSLED(?P<size>\d+)\b", re.IGNORECASE
)
# Override maps for LED generation inference.
#
# Some firmwares report ambiguous hw_revision strings (e.g. "v2.2_23F") that don't
# explicitly include "G1"/"G2". By default we assume G1 unless we see "G2" in the
# device identity fields. If you find exceptions, pin them here.
#
# Examples:
# - Override by HWID (preferred / stable):
# LED_GEN_OVERRIDE_BY_HWID = {"521f271d32c8": "G2"}
#
# - Override by name (fallback when hwid is missing or bogus like "null").
# Note: this must match the *exact* payload["name"] string returned by /device-info
# for your device/firmware (some firmwares append a suffix).
# LED_GEN_OVERRIDE_BY_NAME = {"RSLED90": "G1"}
LED_GEN_OVERRIDE_BY_HWID: Final[dict[str, str]] = {}
LED_GEN_OVERRIDE_BY_NAME: Final[dict[str, str]] = {}
_EMAIL_RE: Final[re.Pattern[str]] = re.compile(
r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
)
_PHONE_RE: Final[re.Pattern[str]] = re.compile(r"\+\d{7,15}")
_RAW_UUID_RE: Final[re.Pattern[str]] = re.compile(
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
)
# =============================================================================
# Sanitization mapping (local-only; should be gitignored)
# =============================================================================
@dataclass
class SanitizeMap:
"""Persistent mapping for stable, unique sanitized identifiers.
This file is intended to be gitignored. To avoid storing personal values
directly, map keys can be SHA256 digests of the original values.
(In the current debugging mode, keys are stored as raw values.)
"""
user_uid: dict[str, str]
aquarium_id: dict[str, int]
aquarium_uid: dict[str, str]
device_hwid: dict[str, str]
device_name: dict[str, str]
mac: dict[str, str]
bssid: dict[str, str]
ip_address: dict[str, str]
ssid: dict[str, str]
serial_code: dict[str, str]
next_aquarium_id: int
next_ip_host: int
next_ssid_suffix: int
next_device_suffix: int
next_device_suffix_by_prefix: dict[str, int]
def _hash_key(kind: str, raw: str) -> str:
"""Return the sanitize-map key for a raw identifier.
Args:
kind: Identifier kind (namespaces the key to reduce collisions).
raw: Raw identifier value.
Returns:
A stable key string. In debug mode this is the raw value; otherwise it is a
SHA256 digest.
"""
if not SANITIZE_MAP_USE_HASH_KEYS:
return raw
h = hashlib.sha256()
h.update(kind.encode("utf-8"))
h.update(b"\x00")
h.update(raw.encode("utf-8", errors="replace"))
return h.hexdigest()
def _sanitize_map_default() -> SanitizeMap:
"""Create an empty sanitize map with initial counters.
Returns:
A fresh `SanitizeMap` instance suitable for first-run initialization.
"""
return SanitizeMap(
user_uid={},
aquarium_id={},
aquarium_uid={},
device_hwid={},
device_name={},
mac={},
bssid={},
ip_address={},
ssid={},
serial_code={},
next_aquarium_id=111111,
next_ip_host=10,
next_ssid_suffix=1,
next_device_suffix=1,
next_device_suffix_by_prefix={},
)
def load_sanitize_map(path: Path) -> SanitizeMap:
"""Load the persistent sanitize map from disk.
Args:
path: Path to the JSON mapping file.
Returns:
A populated `SanitizeMap`. If the file is missing or invalid, returns a
default empty map.
"""
if not path.exists():
return _sanitize_map_default()
try:
obj_any: Any = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return _sanitize_map_default()
if not isinstance(obj_any, dict):
return _sanitize_map_default()
obj = cast(dict[str, Any], obj_any)
def _d_str(val: Any) -> dict[str, str]:
if isinstance(val, dict):
out: dict[str, str] = {}
for k, v in cast(dict[str, Any], val).items():
if isinstance(v, str):
out[k] = v
return out
return {}
def _d_int(val: Any) -> dict[str, int]:
if isinstance(val, dict):
out2: dict[str, int] = {}
for k, v in cast(dict[str, Any], val).items():
if isinstance(v, int):
out2[k] = v
return out2
return {}
def _d_int_str_keys(val: Any) -> dict[str, int]:
if isinstance(val, dict):
out3: dict[str, int] = {}
for k, v in cast(dict[str, Any], val).items():
if isinstance(v, int):
out3[k] = v
return out3
return {}
return SanitizeMap(
user_uid=_d_str(obj.get("user_uid")),
aquarium_id=_d_int(obj.get("aquarium_id")),
aquarium_uid=_d_str(obj.get("aquarium_uid")),
device_hwid=_d_str(obj.get("device_hwid")),
device_name=_d_str(obj.get("device_name")),
mac=_d_str(obj.get("mac")),
bssid=_d_str(obj.get("bssid")),
ip_address=_d_str(obj.get("ip_address")),
ssid=_d_str(obj.get("ssid")),
serial_code=_d_str(obj.get("serial_code")),
next_aquarium_id=int(obj.get("next_aquarium_id") or 111111),
next_ip_host=int(obj.get("next_ip_host") or 10),
next_ssid_suffix=int(obj.get("next_ssid_suffix") or 1),
next_device_suffix=int(obj.get("next_device_suffix") or 1),
next_device_suffix_by_prefix=_d_int_str_keys(
obj.get("next_device_suffix_by_prefix")
),
)
def save_sanitize_map(path: Path, smap: SanitizeMap) -> None:
"""Persist the sanitize map to disk atomically.
Args:
path: Output path for the map JSON file.
smap: Map object to serialize.
Returns:
None
"""
payload: dict[str, Any] = {
"user_uid": smap.user_uid,
"aquarium_id": smap.aquarium_id,
"aquarium_uid": smap.aquarium_uid,
"device_hwid": smap.device_hwid,
"device_name": smap.device_name,
"mac": smap.mac,
"bssid": smap.bssid,
"ip_address": smap.ip_address,
"ssid": smap.ssid,
"serial_code": smap.serial_code,
"next_aquarium_id": smap.next_aquarium_id,
"next_ip_host": smap.next_ip_host,
"next_ssid_suffix": smap.next_ssid_suffix,
"next_device_suffix": smap.next_device_suffix,
"next_device_suffix_by_prefix": smap.next_device_suffix_by_prefix,
}
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
tmp.replace(path)
def _alloc_fake_uuid(counter: int) -> str:
"""Return a stable, readable UUID-like value.
Args:
counter: 1-based counter.
Returns:
A valid UUID string derived from the counter.
"""
return f"00000000-0000-0000-0000-{counter:012d}"[-36:]
def map_user_uid(raw_uid: str, smap: SanitizeMap) -> str:
"""Map a raw user UID to a stable sanitized value.
Args:
raw_uid: Raw user UUID.
smap: Persistent mapping.
Returns:
Sanitized user UUID.
"""
key = _hash_key("user_uid", raw_uid)
if key in smap.user_uid:
return smap.user_uid[key]
smap.user_uid[key] = "00000000-0000-0000-0000-000000000000"
return smap.user_uid[key]
def map_aquarium_id(raw_id: int, smap: SanitizeMap) -> int:
"""Map a raw aquarium numeric ID to a stable sanitized integer.
Args:
raw_id: Raw aquarium numeric ID.
smap: Persistent mapping.
Returns:
Sanitized aquarium numeric ID.
"""
key = _hash_key("aquarium_id", str(raw_id))
if key in smap.aquarium_id:
return smap.aquarium_id[key]
smap.aquarium_id[key] = smap.next_aquarium_id
smap.next_aquarium_id += 1
return smap.aquarium_id[key]
def map_aquarium_uid(raw_uid: str, smap: SanitizeMap) -> str:
"""Map a raw aquarium UUID to a stable fake UUID.
Args:
raw_uid: Raw aquarium UUID.
smap: Persistent mapping.
Returns:
Sanitized aquarium UUID.
"""
key = _hash_key("aquarium_uid", raw_uid)
if key in smap.aquarium_uid:
return smap.aquarium_uid[key]
fake = _alloc_fake_uuid(len(smap.aquarium_uid) + 1)
smap.aquarium_uid[key] = fake
return fake
def _rand_hex(n_bytes: int) -> str:
"""Return a random lowercase hex string.
Args:
n_bytes: Number of random bytes to generate.
Returns:
Hex string of length ``2 * n_bytes``.
"""
return "".join(f"{random.randint(0, 255):02x}" for _ in range(n_bytes))
def map_device_hwid(raw_hwid: str, smap: SanitizeMap) -> str:
"""Map a device HWID to a stable sanitized HWID.
Args:
raw_hwid: Raw HWID string.
smap: Persistent mapping.
Returns:
Sanitized HWID (12 hex chars) or the constant sanitized placeholder if the
input does not look like a HWID.
"""
# Only map real-looking HWIDs to prevent mapping growth.
norm = raw_hwid.strip().lower()
if not re.fullmatch(r"[0-9a-f]{12}", norm):
return SANITIZED_HWID
# Idempotence: if we already produced this value, don't re-map it.
if norm in (v.lower() for v in smap.device_hwid.values()):
return norm
key = _hash_key("device_hwid", norm)
if key in smap.device_hwid:
return smap.device_hwid[key]
smap.device_hwid[key] = _rand_hex(6)
return smap.device_hwid[key]
def map_device_name(raw_name: str, smap: SanitizeMap) -> str:
"""Map a raw device name to a stable sanitized device name.
Preserves the prefix when the input matches the standard format.
Args:
raw_name: Raw device name (e.g. ``RSATO+2487379135``).
smap: Persistent mapping.
Returns:
Sanitized device name (e.g. ``RSATO+0000000001``).
"""
# Idempotence: if the caller passes an already-sanitized name, do not re-map.
if raw_name in smap.device_name.values():
return raw_name
key = _hash_key("device_name", raw_name)
if key in smap.device_name:
return smap.device_name[key]
# Preserve the device type prefix; replace only the numeric suffix.
m = re.fullmatch(r"([A-Za-z0-9]+[+\-])(\d+)", raw_name)
if m:
prefix = m.group(1)
width = len(m.group(2))
n = smap.next_device_suffix_by_prefix.get(prefix, 1)
smap.next_device_suffix_by_prefix[prefix] = n + 1
smap.device_name[key] = f"{prefix}{n:0{width}d}"
return smap.device_name[key]
# Fallback for unexpected formats.
n2 = smap.next_device_suffix
smap.next_device_suffix += 1
smap.device_name[key] = f"DEVICE_{n2}"
return smap.device_name[key]
def _rand_mac(prefix: str | None = None) -> str:
"""Generate a random MAC address, optionally with a fixed prefix.
Args:
prefix: Optional MAC prefix like ``"02:00:00"``.
Returns:
Uppercase MAC address string.
"""
parts: list[str] = []
if prefix:
parts.extend(prefix.split(":"))
while len(parts) < 6:
parts.append(f"{random.randint(0, 255):02x}")
return ":".join(parts[:6]).upper()
def map_mac(raw_mac: str, smap: SanitizeMap) -> str:
"""Map a raw MAC to a stable sanitized MAC.
Args:
raw_mac: Raw MAC address.
smap: Persistent mapping.
Returns:
Sanitized MAC address.
"""
# Idempotence: if we already produced this value, don't re-map it.
norm = raw_mac.strip().upper()
if norm in (v.upper() for v in smap.mac.values()):
return norm
key = _hash_key("mac", raw_mac.lower())
if key in smap.mac:
return smap.mac[key]
smap.mac[key] = _rand_mac("02:00:00")
return smap.mac[key]
def map_bssid(raw_bssid: str, smap: SanitizeMap) -> str:
"""Map a raw BSSID to a stable sanitized BSSID.
Args:
raw_bssid: Raw BSSID.
smap: Persistent mapping.
Returns:
Sanitized BSSID.
"""
# Idempotence: if we already produced this value, don't re-map it.
norm = raw_bssid.strip().upper()
if norm in (v.upper() for v in smap.bssid.values()):
return norm
key = _hash_key("bssid", raw_bssid.lower())
if key in smap.bssid:
return smap.bssid[key]
smap.bssid[key] = _rand_mac("02:00:01")
return smap.bssid[key]
def map_ip_address(raw_ip: str, smap: SanitizeMap) -> str:
"""Map a raw IP address to a stable sanitized IP (10.0.0.x).
Args:
raw_ip: Raw IPv4 address string.
smap: Persistent mapping.
Returns:
Sanitized IPv4 address string.
"""
# If the caller accidentally passes an already-sanitized IP (e.g. from a prior run),
# keep mapping idempotent and avoid polluting the sanitize map with synthetic values.
norm = raw_ip.strip()
if re.fullmatch(r"10\.0\.0\.(?:[0-9]{1,3})", norm):
return norm
# Idempotence: if we already produced this value, don't re-map it.
if norm in smap.ip_address.values():
return norm
key = _hash_key("ip_address", norm)
if key in smap.ip_address:
return smap.ip_address[key]
host = smap.next_ip_host
smap.next_ip_host += 1
smap.ip_address[key] = f"10.0.0.{host}"
return smap.ip_address[key]
def map_ssid(raw_ssid: str, smap: SanitizeMap) -> str:
"""Return the constant sanitized SSID.
WiFi scan payloads may include many nearby SSIDs; we intentionally do not preserve
uniqueness to avoid growing the mapping file.
Args:
raw_ssid: Raw SSID (ignored).
smap: Persistent mapping (unused).
Returns:
Constant sanitized SSID.
"""
_ = raw_ssid
__ = smap
return SANITIZED_SSID
def stable_device_uuid(raw_hwid: str) -> str:
"""Return a deterministic UUID derived from a device identifier.
Args:
raw_hwid: Device identifier used as the seed.
Returns:
Deterministic UUID string.
"""
h = hashlib.sha256()
h.update(b"device_uuid\x00")
h.update(raw_hwid.lower().encode("utf-8", errors="replace"))
b = bytearray(h.digest()[:16])
# Set RFC4122 variant and a stable UUID version nibble.
b[6] = (b[6] & 0x0F) | 0x40
b[8] = (b[8] & 0x3F) | 0x80
return str(uuid.UUID(bytes=bytes(b)))
def map_serial_code(raw_code: str, smap: SanitizeMap) -> str:
"""Map a raw serial code to a stable sanitized serial-like value.
Args:
raw_code: Raw serial code.
smap: Persistent mapping.
Returns:
Sanitized serial code.
"""
key = _hash_key("serial_code", raw_code)
if key in smap.serial_code:
return smap.serial_code[key]
# Preserve the 'cf' prefix pattern if present.
prefix = "cf" if raw_code.lower().startswith("cf") else "sc"
smap.serial_code[key] = f"{prefix}{_rand_hex(7)}"
return smap.serial_code[key]
# =============================================================================
# Types / Data
# =============================================================================
@dataclass(frozen=True)
class DeviceIdentity:
hwid: str
name: str
# =============================================================================
# Helpers: env
# =============================================================================
def load_dotenv_simple(dotenv_path: Path) -> dict[str, str]:
"""Load a simple `.env` file.
Args:
dotenv_path: Path to the `.env` file.
Returns:
Mapping of keys to values. Missing files return an empty dict.
"""
if not dotenv_path.exists():
return {}
env: dict[str, str] = {}
for raw_line in dotenv_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, val = line.split("=", 1)
key = key.strip()
val = val.strip().strip('"').strip("'")
if key:
env[key] = val
return env
# =============================================================================
# Helpers: scan (LAN + optional cloud)
# =============================================================================
def _as_str(val: Any) -> str:
"""Convert an arbitrary value into a printable string.
Args:
val: Any value.
Returns:
Empty string for ``None``, otherwise a string representation.
"""
if val is None:
return ""
return val if isinstance(val, str) else str(val)
def print_devices_table(rows: list[dict[str, Any]]) -> None:
"""Print a human-readable device table.
Supports both cloud-style rows (``aquarium_name``, ``ip_address``, etc.) and LAN
scan rows (``aquarium``, ``ip``, etc.).
Args:
rows: List of row dictionaries.
Returns:
None
"""
table: list[tuple[str, str, str, str, str, str, str]] = []
for r in rows:
source = _as_str(r.get("_source"))
if not source:
if "ip_address" in r or "aquarium_name" in r:
source = "CLOUD"
elif "ip" in r:
source = "LAN"
aquarium = _as_str(r.get("aquarium") or r.get("aquarium_name"))
device = _as_str(r.get("device") or r.get("name"))
dtype = _as_str(r.get("type"))
ip = _as_str(r.get("ip") or r.get("ip_address"))
model = _as_str(r.get("model"))
fw = _as_str(r.get("fw") or r.get("firmware_version"))
table.append((source, aquarium, device, dtype, ip, model, fw))
table.sort(key=lambda t: (t[1].lower(), t[3].lower(), t[2].lower(), t[4]))
headers = ("From", "Aquarium", "Device", "Type", "IP", "Model", "FW")
widths = [len(h) for h in headers]
for row in table:
for i, val in enumerate(row):
widths[i] = max(widths[i], len(val))
def fmt_row(row: tuple[str, ...]) -> str:
return " ".join(val.ljust(widths[i]) for i, val in enumerate(row))
print(fmt_row(headers))
print(" ".join("-" * w for w in widths))
for row in table:
print(fmt_row(row))
def cloud_list_devices(
username: str, password: str, *, timeout_s: int
) -> list[dict[str, Any]]:
"""List devices from the ReefBeat cloud.
Args:
username: Cloud username.
password: Cloud password.
timeout_s: HTTP timeout seconds.
Returns:
List of cloud device dicts, each enriched with an aquarium name when possible.
"""
token = cloud_auth_token(username, password, timeout=timeout_s)
if not token:
return []
aquariums_any = cloud_get_json("/aquarium", token, timeout=timeout_s)
devices_any = cloud_get_json("/device", token, timeout=timeout_s)
aq_name_by_id: dict[str, str] = {}
if isinstance(aquariums_any, list):
for aq_any in cast(list[Any], aquariums_any):
if not isinstance(aq_any, dict):
continue
aq = cast(dict[str, Any], aq_any)
aq_id = aq.get("id")
aq_name = aq.get("name")
if aq_id is not None and isinstance(aq_name, str):
aq_name_by_id[str(aq_id)] = aq_name
out: list[dict[str, Any]] = []
if isinstance(devices_any, list):
for dev_any in cast(list[Any], devices_any):
if not isinstance(dev_any, dict):
continue
dev = cast(dict[str, Any], dev_any)
aq_id = dev.get("aquarium_id")
row = dict(dev)
row["_source"] = "CLOUD"
if aq_id is not None:
row["aquarium_name"] = aq_name_by_id.get(str(aq_id), "")
out.append(row)
return out
def _safe_json_loads(raw: bytes) -> Any:
"""Parse JSON bytes safely.
Args:
raw: Raw bytes from an HTTP response.
Returns:
Parsed JSON value, or ``None`` if parsing fails.
"""
try:
return json.loads(raw.decode("utf-8", errors="replace"))
except Exception:
return None
def _normalize_fw(val: Any) -> str:
"""Normalize a firmware version field to a string.
Args:
val: Raw firmware version value.
Returns:
Firmware version string.
"""
if isinstance(val, str):
return val
if val is None:
return ""
return str(val)
def scan_network_for_devices(
cidr: str,
*,
timeout_s: float = HTTP_TIMEOUT_SECS_DEFAULT,
workers: int = 128,
max_hosts: int = 4096,
allow_large: bool = False,
) -> list[dict[str, str]]:
"""Scan a CIDR and return detected ReefBeat devices.
This probes ``/device-info`` on each host in the CIDR.
Args:
cidr: CIDR string to scan.
timeout_s: Per-host HTTP timeout.
workers: Thread pool size.
max_hosts: Refuse scanning networks larger than this many hosts unless overridden.
allow_large: If True, allow scanning very large networks.
Returns:
List of device rows, one per detected host.
Raises:
ValueError: If the CIDR is larger than ``max_hosts`` and ``allow_large`` is False.
"""
net = ipaddress.ip_network(cidr, strict=False)
# Guard against accidentally scanning huge networks (docker /16, etc.).
host_count = (
int(max(0, net.num_addresses - 2))
if getattr(net, "version", 4) == 4
else int(net.num_addresses)
)
if host_count > max_hosts and not allow_large:
raise ValueError(
f"Refusing to scan {net} ({host_count} hosts). "
f"Pass --scan-max-hosts {host_count} or --scan-allow-large to override."
)
ips_iter = (str(ip) for ip in net.hosts())
def probe_one(ip: str) -> dict[str, str] | None:
try:
raw = fetch_url_http(ip, "/device-info", timeout=timeout_s)
if not raw:
return None
payload_any = _safe_json_loads(raw)
if not isinstance(payload_any, dict):
return None
payload = cast(dict[str, Any], payload_any)
name = payload.get("name")
hwid = payload.get("hwid")
# Different firmware revisions use different key names.
model = (
payload.get("model")
if payload.get("model") is not None