forked from jkef80/Filament-Management
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
2279 lines (1935 loc) · 85.9 KB
/
main.py
File metadata and controls
2279 lines (1935 loc) · 85.9 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
from __future__ import annotations
import asyncio
import json
import math
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Optional, List
from urllib.request import Request as UrlRequest, urlopen
from urllib.parse import urlparse
import websockets
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from models.schemas import (
ApiResponse,
AppState,
FeedRequest,
JobReallocateSpoolRequest,
MultiAppState,
RetractRequest,
SelectSlotRequest,
SetAutoRequest,
SlotState,
SlotStats,
SetSpoolmanModeRequest,
SetSpoolmanUrlRequest,
SpoolmanLinkRequest,
SpoolmanUnlinkRequest,
UiSetColorRequest,
UiSpoolSetStartRequest,
UiSlotUpdateRequest,
UpdateSlotRequest,
)
# ---- Pydantic v1/v2 compatibility helpers ----
def _model_dump(obj) -> dict:
"""Return a plain dict for both Pydantic v1 and v2 models."""
if hasattr(obj, "model_dump"):
return obj.model_dump()
return obj.dict()
def _model_validate(cls, data):
"""Validate/parse a dict into a Pydantic model (v1/v2 compatible)."""
if hasattr(cls, "model_validate"):
return cls.model_validate(data)
return cls.parse_obj(data)
def _req_dump(obj, *, exclude_unset: bool = False) -> dict:
"""Dump request models (v1/v2 compatible) with optional exclude_unset."""
if hasattr(obj, "model_dump"):
return obj.model_dump(exclude_unset=exclude_unset)
return obj.dict(exclude_unset=exclude_unset)
APP_DIR = Path(__file__).resolve().parent
DATA_DIR = APP_DIR / "data"
STATIC_DIR = APP_DIR / "static"
STATE_PATH = DATA_DIR / "state.json"
PROFILES_PATH = DATA_DIR / "profiles.json"
CONFIG_PATH = DATA_DIR / "config.json"
DEFAULT_SLOTS = [
"1A", "1B", "1C", "1D",
"2A", "2B", "2C", "2D",
"3A", "3B", "3C", "3D",
"4A", "4B", "4C", "4D",
]
PRINTER_SPOOL_SLOT = "SP"
def _now() -> float:
return time.time()
def _parse_iso_ts(val: str) -> Optional[float]:
try:
# Accept "Z" and timezone offsets
if val.endswith("Z"):
dt = datetime.fromisoformat(val.replace("Z", "+00:00"))
else:
dt = datetime.fromisoformat(val)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.timestamp()
except Exception:
return None
def _ensure_data_files() -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
STATIC_DIR.mkdir(parents=True, exist_ok=True)
if not PROFILES_PATH.exists():
PROFILES_PATH.write_text(
json.dumps(
{
"PLA": {"density_g_cm3": 1.24, "notes": "Default profile"},
"ABS": {"density_g_cm3": 1.04, "notes": "Default profile"},
"PETG": {"density_g_cm3": 1.27, "notes": "Default profile"},
"TPU": {"density_g_cm3": 1.20, "notes": "Default profile"},
"ASA": {"density_g_cm3": 1.07, "notes": "Default profile"},
"PA": {"density_g_cm3": 1.15, "notes": "Default profile"},
"PC": {"density_g_cm3": 1.20, "notes": "Default profile"},
"OTHER": {"density_g_cm3": 1.20, "notes": "Fallback"},
},
indent=2,
ensure_ascii=False,
)
)
if not CONFIG_PATH.exists():
CONFIG_PATH.write_text(
json.dumps(
{
# Hostname or IPs of printers (used for WebSocket connection at ws://host:9999)
# Example: ["192.168.178.148", "192.168.178.149"]
"printer_urls": [],
# Filament diameter used for mm->g conversion
"filament_diameter_mm": 1.75,
# Optional: Spoolman URL for spool inventory integration
# Example: "http://192.168.178.148:7912"
"spoolman_url": "",
# Spoolman sync mode: "direct" (CFSync PUTs usage) or
# "moonraker" (CFSync calls SET_ACTIVE_SPOOL macro, plugin tracks usage)
"spoolman_mode": "direct",
},
indent=2,
ensure_ascii=False,
)
)
if not STATE_PATH.exists():
state = {
"printers": {},
"updated_at": _now(),
}
STATE_PATH.write_text(json.dumps(state, indent=2, ensure_ascii=False))
def load_profiles() -> dict:
_ensure_data_files()
try:
return json.loads(PROFILES_PATH.read_text())
except Exception:
return {}
def _normalize_printer_host(raw: str) -> str:
raw = (raw or "").strip()
if not raw:
return ""
if "://" in raw:
host = urlparse(raw).hostname or ""
return host.strip() if host else ""
# strip path/port if user pasted host:port or host/path
host = raw.split("/")[0].strip()
if ":" in host:
host = host.split(":", 1)[0].strip()
return host
def _normalize_printer_id(raw_id: str, address: str) -> str:
rid = (raw_id or "").strip()
if rid:
return rid
return (address or "").strip()
def _dedupe_printers(items: List[str]) -> List[str]:
seen = set()
out: List[str] = []
for it in items:
if not it or it in seen:
continue
seen.add(it)
out.append(it)
return out
def load_config() -> dict:
_ensure_data_files()
try:
cfg = json.loads(CONFIG_PATH.read_text())
except Exception:
cfg = {}
printer_urls: List[str] = []
printers: List[dict] = []
# Backward compat: migrate legacy printer_url into printer_urls
legacy_printer = _normalize_printer_host(cfg.get("printer_url") or "")
if legacy_printer:
printer_urls.append(legacy_printer)
# Backward compat: extract hostname from legacy moonraker_url if no printer provided
if not printer_urls:
mu = (cfg.get("moonraker_url") or "").strip()
if mu:
host = urlparse(mu).hostname or ""
if host:
print(f"[CONFIG] Migrating moonraker_url → printer_urls (host={host!r})")
printer_urls.append(host)
# Preferred multi-printer config
raw_list = cfg.get("printer_urls")
if isinstance(raw_list, list):
for raw in raw_list:
host = _normalize_printer_host(str(raw))
if host:
printer_urls.append(host)
# Backward/alternate compat: "printers": [{"address": "..."}]
raw_printers = cfg.get("printers")
if isinstance(raw_printers, list):
for item in raw_printers:
host = ""
if isinstance(item, dict):
host = (
item.get("address")
or item.get("host")
or item.get("ip")
or item.get("url")
or item.get("printer_url")
or ""
)
elif isinstance(item, str):
host = item
host = _normalize_printer_host(str(host))
if host:
printer_urls.append(host)
# Backward/alternate compat: "printers": [{"id": "...", "address": "..."}]
raw_printers = cfg.get("printers")
if isinstance(raw_printers, list):
for item in raw_printers:
host = ""
pid = ""
if isinstance(item, dict):
host = (
item.get("address")
or item.get("host")
or item.get("ip")
or item.get("url")
or item.get("printer_url")
or ""
)
pid = (
item.get("id")
or item.get("name")
or item.get("label")
or ""
)
elif isinstance(item, str):
host = item
host = _normalize_printer_host(str(host))
if not host:
continue
pid = _normalize_printer_id(str(pid), host)
printers.append({"id": pid, "address": host})
printer_urls.append(host)
# Also promote plain printer_urls into printers (id defaults to address)
existing_addrs = {str(p.get("address") or "").strip() for p in printers}
for host in printer_urls:
if host in existing_addrs:
continue
pid = _normalize_printer_id("", host)
printers.append({"id": pid, "address": host})
# Dedupe by id (keep first)
seen_ids = set()
printers_out: List[dict] = []
for p in printers:
pid = str(p.get("id") or "").strip()
addr = str(p.get("address") or "").strip()
if not pid or not addr or pid in seen_ids:
continue
seen_ids.add(pid)
printers_out.append({"id": pid, "address": addr})
cfg["printers"] = printers_out
cfg["printer_urls"] = _dedupe_printers(printer_urls)
cfg.setdefault("filament_diameter_mm", 1.75)
cfg.setdefault("spoolman_url", "")
cfg.setdefault("spoolman_mode", "direct")
return cfg
def _migrate_app_state_dict(data: dict) -> dict:
"""Make a single-printer AppState tolerant to older/hand-edited formats."""
if not isinstance(data, dict):
return data
# updated_at: allow ISO string
if isinstance(data.get("updated_at"), str):
ts = _parse_iso_ts(data["updated_at"])
if ts is not None:
data["updated_at"] = ts
# Some users wrote last_update instead of updated_at
if "updated_at" not in data and "last_update" in data:
if data["last_update"] is None:
data["updated_at"] = 0.0
elif isinstance(data["last_update"], str):
data["updated_at"] = _parse_iso_ts(data["last_update"]) or 0.0
else:
try:
data["updated_at"] = float(data["last_update"])
except Exception:
data["updated_at"] = 0.0
# Slots: allow keys like "2A": {material,color,...} without slot field
slots = data.get("slots", {}) or {}
if isinstance(slots, dict):
for slot_id, sd in list(slots.items()):
if not isinstance(sd, dict):
continue
sd.setdefault("slot", slot_id)
# allow 'color' key
if "color" in sd and "color_hex" not in sd:
sd["color_hex"] = sd.pop("color")
# legacy key 'vendor' -> 'manufacturer'
if "vendor" in sd and "manufacturer" not in sd:
sd["manufacturer"] = sd.pop("vendor")
# tolerate placeholders for material
mat = sd.get("material")
if isinstance(mat, str) and mat.strip() in ("", "-", "—", "–"):
sd["material"] = "OTHER"
# Spoolman integration (optional)
sd.setdefault("spoolman_id", None)
slots[slot_id] = sd
# ensure all CFS banks exist (1A-4D)
for sid in (
"1A", "1B", "1C", "1D",
"2A", "2B", "2C", "2D",
"3A", "3B", "3C", "3D",
"4A", "4B", "4C", "4D",
):
if sid not in slots:
slots[sid] = {
"slot": sid,
"material": "OTHER",
"color_hex": "#00aaff",
"name": "",
"manufacturer": "",
}
# Ensure the printer's direct spool input exists too.
if PRINTER_SPOOL_SLOT not in slots:
slots[PRINTER_SPOOL_SLOT] = {
"slot": PRINTER_SPOOL_SLOT,
"material": "OTHER",
"color_hex": "#00aaff",
"name": "",
"manufacturer": "",
"spoolman_id": None,
}
data["slots"] = slots
data.setdefault("printer_connected", False)
data.setdefault("printer_last_error", "")
data.setdefault("cfs_connected", False)
data.setdefault("cfs_last_update", 0.0)
data.setdefault("cfs_active_slot", None)
data.setdefault("cfs_slots", {})
data.setdefault("ws_slot_length_m", {})
data.setdefault("cfs_stats", {})
data.setdefault("job_history", [])
# Clear the stale "2A" schema default — active_slot is now driven by WS only
if data.get("active_slot") == "2A":
data["active_slot"] = None
return data
# Keep _migrate_state_dict as an alias for backward compat (used in older code paths)
_migrate_state_dict = _migrate_app_state_dict
def _default_printer_id() -> str:
cfg = load_config()
printers = cfg.get("printers") or []
if printers:
return str((printers[0] or {}).get("id") or "")
return "printer-1"
def _migrate_multi_state_dict(data: dict) -> dict:
"""Normalize the multi-printer state envelope."""
if not isinstance(data, dict):
return {"printers": {}, "updated_at": _now()}
# Already multi-printer
if isinstance(data.get("printers"), dict):
printers_out: Dict[str, dict] = {}
for pid, raw in (data.get("printers") or {}).items():
if not isinstance(raw, dict):
continue
printers_out[str(pid)] = _migrate_app_state_dict(raw)
updated_at = data.get("updated_at", _now())
if isinstance(updated_at, str):
updated_at = _parse_iso_ts(updated_at) or _now()
return {
"printers": printers_out,
"updated_at": updated_at,
}
# Legacy single-printer state
if isinstance(data.get("slots"), dict):
pid = _default_printer_id()
updated_at = data.get("updated_at", _now())
if isinstance(updated_at, str):
updated_at = _parse_iso_ts(updated_at) or _now()
return {
"printers": {pid: _migrate_app_state_dict(data)},
"updated_at": updated_at,
}
return {"printers": {}, "updated_at": _now()}
_state_load_failed: bool = False # True when last load fell back to default
def load_state_all() -> MultiAppState:
global _state_load_failed
_ensure_data_files()
try:
data = json.loads(STATE_PATH.read_text())
data = _migrate_multi_state_dict(data)
result = _model_validate(MultiAppState, data)
# Ensure configured printers exist in state
cfg_printers = load_config().get("printers") or []
for p in cfg_printers:
pid = str((p or {}).get("id") or "")
if not pid:
continue
# If state is keyed by address but config now uses a custom id, migrate it.
addr = str((p or {}).get("address") or "")
if pid not in result.printers and addr in result.printers and addr != pid:
result.printers[pid] = result.printers.pop(addr)
if pid not in result.printers:
result.printers[pid] = default_state()
_state_load_failed = False
return result
except Exception as e:
print(f"[STATE] load failed: {e}")
_state_load_failed = True
return default_multi_state()
def save_state_all(state: MultiAppState) -> None:
if _state_load_failed:
print("[STATE] save skipped: last load returned fallback default")
return
state.updated_at = _now()
STATE_PATH.write_text(json.dumps(_model_dump(state), indent=2, ensure_ascii=False))
def _all_printer_ids() -> List[str]:
cfg_printers = load_config().get("printers") or []
cfg_ids = [str((p or {}).get("id") or "") for p in cfg_printers if (p or {}).get("id")]
st = load_state_all()
state_ids = [str(x) for x in st.printers.keys()]
merged: List[str] = []
for pid in cfg_ids + state_ids:
if pid and pid not in merged:
merged.append(pid)
return merged
def _resolve_printer_id(printer_id: Optional[str], *, allow_unknown: bool = False) -> str:
raw = (printer_id or "").strip()
cfg_ids = {str((p or {}).get("id") or "").strip() for p in (load_config().get("printers") or [])}
if raw and raw in cfg_ids:
pid = raw
else:
pid = _normalize_printer_host(raw)
if not pid:
pid = _default_printer_id()
else:
# If caller passed an address, map it to configured id if present
for p in (load_config().get("printers") or []):
addr = str((p or {}).get("address") or "").strip()
cid = str((p or {}).get("id") or "").strip()
if addr and cid and pid == addr:
pid = cid
break
if not allow_unknown:
known = set(_all_printer_ids())
if pid not in known:
raise HTTPException(status_code=404, detail="Unknown printer")
return pid
def _printer_address(printer_id: str) -> str:
pid = (printer_id or "").strip()
if not pid:
return ""
for p in (load_config().get("printers") or []):
cid = str((p or {}).get("id") or "").strip()
addr = str((p or {}).get("address") or "").strip()
if cid and addr and cid == pid:
return addr
# Fallback: treat printer_id as host/IP
return _normalize_printer_host(pid)
def load_state(printer_id: Optional[str] = None) -> AppState:
pid = _resolve_printer_id(printer_id, allow_unknown=True)
st = load_state_all()
state = st.printers.get(pid)
if state is None:
return default_state()
return state
def save_state(printer_id: str, state: AppState) -> None:
pid = _resolve_printer_id(printer_id, allow_unknown=True)
st = load_state_all()
st.printers[pid] = state
save_state_all(st)
# --- Printer adapter (Dummy) ---
# Keep it minimal: this project is about material management.
# You can later replace these functions with real Moonraker/CFS actions.
def adapter_feed(mm: float) -> None:
print(f"[ADAPTER] feed {mm}mm")
def adapter_retract(mm: float) -> None:
print(f"[ADAPTER] retract {mm}mm")
# --- Conversion helpers ---
def mm_to_g(material: str, mm: float) -> float:
cfg = load_config()
d_mm = float(cfg.get("filament_diameter_mm", 1.75) or 1.75)
profiles = load_profiles()
density = float((profiles.get(material) or {}).get("density_g_cm3", 1.20))
# grams = density(g/cm^3) * volume(cm^3)
# volume = area * length
# area(mm^2) = pi*(d/2)^2 ; to cm^2 => /100
# length(mm) to cm => /10
area_cm2 = math.pi * (d_mm / 2.0) ** 2 / 100.0
length_cm = mm / 10.0
g = density * area_cm2 * length_cm
return float(max(0.0, g))
# --- Minimal Moonraker polling (optional) ---
def _http_get_json(url: str, timeout: float = 2.5) -> dict:
# NOTE: FastAPI also exports a Request type; avoid name clash by using
# UrlRequest for outbound HTTP requests.
req = UrlRequest(url, headers={"User-Agent": "filament-manager/1.0"})
with urlopen(req, timeout=timeout) as r:
raw = r.read().decode("utf-8", errors="replace")
return json.loads(raw)
def _http_put_json(url: str, body: dict, timeout: float = 3.0) -> dict:
"""PUT JSON body and return parsed response (stdlib only)."""
data = json.dumps(body).encode("utf-8")
req = UrlRequest(url, data=data, headers={
"User-Agent": "filament-manager/1.0",
"Content-Type": "application/json",
}, method="PUT")
with urlopen(req, timeout=timeout) as r:
raw = r.read().decode("utf-8", errors="replace")
return json.loads(raw) if raw.strip() else {}
# --- Spoolman integration (optional) ---
def _spoolman_base_url() -> str:
"""Return the configured Spoolman base URL, or empty string if not set."""
cfg = load_config()
return (cfg.get("spoolman_url") or "").rstrip("/")
def _spoolman_mode() -> str:
"""Return the Spoolman sync mode: 'direct' or 'moonraker'."""
return load_config().get("spoolman_mode", "direct")
def _spoolman_get_spools(base: str) -> list[dict]:
"""GET /api/v1/spool — return non-archived spools."""
url = base + "/api/v1/spool"
spools = _http_get_json(url, timeout=5.0)
if not isinstance(spools, list):
return []
return [s for s in spools if not s.get("archived", False)]
def _spoolman_get_spool(base: str, spool_id: int) -> dict:
"""GET /api/v1/spool/{id} — return single spool."""
url = f"{base}/api/v1/spool/{spool_id}"
return _http_get_json(url, timeout=5.0)
def _spoolman_report_usage(spool_id: int, grams: float) -> None:
"""PUT /api/v1/spool/{id}/use — fire-and-forget."""
if not spool_id or grams <= 0:
return
base = _spoolman_base_url()
if not base:
return
try:
url = f"{base}/api/v1/spool/{spool_id}/use"
_http_put_json(url, {"use_weight": round(grams, 2)})
print(f"[SPOOLMAN] reported usage: spool {spool_id} -= {grams:.2f}g")
except Exception as e:
print(f"[SPOOLMAN] usage report failed for spool {spool_id}: {e}")
def _spoolman_report_measure(spool_id: int, weight_g: float) -> None:
"""PUT /api/v1/spool/{id} — set remaining_weight directly. Fire-and-forget."""
if not spool_id:
return
base = _spoolman_base_url()
if not base:
return
try:
url = f"{base}/api/v1/spool/{spool_id}"
data = json.dumps({"remaining_weight": round(weight_g, 2)}).encode("utf-8")
req = UrlRequest(url, data=data, headers={
"User-Agent": "filament-manager/1.0",
"Content-Type": "application/json",
}, method="PATCH")
with urlopen(req, timeout=3.0) as r:
r.read()
print(f"[SPOOLMAN] reported measure: spool {spool_id} = {weight_g:.2f}g")
except Exception as e:
print(f"[SPOOLMAN] measure report failed for spool {spool_id}: {e}")
def _spoolman_remaining_weight(spool: dict) -> float:
try:
return max(0.0, float(spool.get("remaining_weight") or 0.0))
except Exception:
return 0.0
def _spoolman_set_remaining_weight(base: str, spool_id: int, weight_g: float) -> None:
"""PATCH /api/v1/spool/{id} with an exact remaining_weight. Raises on failure."""
if not spool_id:
raise ValueError("Invalid spool ID")
url = f"{base}/api/v1/spool/{spool_id}"
data = json.dumps({"remaining_weight": round(max(0.0, weight_g), 2)}).encode("utf-8")
req = UrlRequest(url, data=data, headers={
"User-Agent": "filament-manager/1.0",
"Content-Type": "application/json",
}, method="PATCH")
with urlopen(req, timeout=5.0) as r:
r.read()
def _spoolman_id_or_none(value) -> Optional[int]:
try:
sid = int(value)
return sid if sid > 0 else None
except Exception:
return None
def _normalize_color_hex(value: str) -> str:
raw = str(value or "").strip().lower()
if not raw:
return ""
if raw.startswith("0x"):
raw = raw[2:]
if raw.startswith("#"):
raw = raw[1:]
raw = "".join(ch for ch in raw if ch in "0123456789abcdef")
if not raw:
return ""
# Handle common printer formats:
# - 0RRGGBB -> strip leading 0
# - AARRGGBB -> strip alpha
# - anything longer -> keep least significant RGB bytes
if len(raw) == 7 and raw[0] == "0":
raw = raw[1:]
elif len(raw) == 8:
raw = raw[2:]
elif len(raw) > 8:
raw = raw[-6:]
if len(raw) != 6:
return ""
return "#" + raw
def _spoolman_set_extra(spool_id: int, key: str, value: str) -> None:
"""PATCH Spoolman spool to write a single extra field. Fire-and-forget."""
base = _spoolman_base_url()
if not base or not spool_id:
return
try:
url = f"{base}/api/v1/spool/{spool_id}"
# Spoolman requires extra field values to be JSON-encoded strings (double-encoded)
data = json.dumps({"extra": {key: json.dumps(value)}}).encode("utf-8")
req = UrlRequest(url, data=data, headers={
"User-Agent": "filament-manager/1.0",
"Content-Type": "application/json",
}, method="PATCH")
with urlopen(req, timeout=3.0) as r:
r.read()
print(f"[SPOOLMAN] set extra {key}={value!r} on spool {spool_id}")
except Exception as e:
print(f"[SPOOLMAN] set extra failed for spool {spool_id}: {e}")
def _spoolman_job_color_lookup(spool_id: int) -> str:
"""Return current filament color for a spool (cached for UI history rendering)."""
sid = _spoolman_id_or_none(spool_id)
if not sid:
return ""
now = _now()
cached = _spoolman_job_color_cache.get(sid)
if cached and (now - cached[0]) <= _SPOOLMAN_JOB_COLOR_CACHE_TTL:
return cached[1]
base = _spoolman_base_url()
if not base:
return ""
try:
spool = _spoolman_get_spool(base, sid)
filament = spool.get("filament") or {}
color = _normalize_color_hex(str(filament.get("color_hex") or ""))
_spoolman_job_color_cache[sid] = (now, color)
return color
except Exception:
return ""
def _ui_hydrate_job_history_colors(history_in: list) -> list:
"""Hydrate history spool colors from current linked Spoolman spool metadata."""
if not isinstance(history_in, list):
return []
out: list = []
for job in history_in:
if not isinstance(job, dict):
continue
job_out = dict(job)
spools_in = job.get("spools") or []
spools_out: list = []
if isinstance(spools_in, list):
for sp in spools_in:
if not isinstance(sp, dict):
continue
sp_out = dict(sp)
sid = _spoolman_id_or_none(sp_out.get("spoolman_id"))
color = _spoolman_job_color_lookup(sid or 0) if sid else ""
if color:
sp_out["color_hex"] = color
else:
sp_out["color_hex"] = _normalize_color_hex(str(sp_out.get("color_hex") or sp_out.get("color") or ""))
spools_out.append(sp_out)
job_out["spools"] = spools_out
out.append(job_out)
return out
def _spoolman_autolink_by_rfid(slot: str, rfid: str, st, printer_id: str) -> None:
"""Search active Spoolman spools for one with extra.cfs_rfid == rfid and auto-link."""
base = _spoolman_base_url()
if not base or not rfid:
return
try:
spools = _http_get_json(f"{base}/api/v1/spool?allow_archived=false", timeout=5.0)
if not isinstance(spools, list):
return
for sp in spools:
extra = sp.get("extra") or {}
raw = extra.get("cfs_rfid", "")
# Spoolman stores extra values as JSON-encoded strings — decode before comparing
try:
stored_rfid = json.loads(raw) if raw else ""
except Exception:
stored_rfid = raw
if stored_rfid != rfid:
continue
spool_id = sp.get("id")
if not spool_id:
continue
slot_state = st.slots.get(slot)
if slot_state is None:
return
slot_state.spoolman_id = spool_id
st.slots[slot] = slot_state
# Record RFID as seen so we don't re-trigger next cycle
_ws_last_rfid.setdefault(printer_id, {})[slot] = rfid
save_state(printer_id, st)
print(f"[SPOOLMAN] ({printer_id}) Auto-linked slot {slot} → spool {spool_id} via RFID {rfid!r}")
return
except Exception as e:
print(f"[SPOOLMAN] auto-link lookup failed for slot {slot}: {e}")
# --- SSH serial number auto-link ---
# Uses sshpass + system ssh binary for compatibility with Creality K2 Plus firmware.
# Tries multiple passwords and multiple file paths to support stock and K2-Improvements firmwares.
_SSH_PASSWORDS = ["creality_2023", "creality_2024", "creality"]
# Per-printer cached working password (reset never — stays valid across reconnects)
_ssh_working_password: Dict[str, Optional[str]] = {}
# Stock firmware path; K2-Improvements moves UDISK to /mnt/UDISK
_SSH_FILE_PATHS = [
"/mnt/UDISK/creality/userdata/box/material_box_info.json",
"/usr/data/creality/userdata/box/material_box_info.json",
]
async def _fetch_printer_material_json(printer_id: str) -> Optional[dict]:
"""Fetch material_box_info.json from the printer via sshpass + system ssh."""
host = (_printer_address(printer_id) or "").strip().split(":")[0]
if not host:
return None
def _ssh_cat() -> Optional[dict]:
import subprocess
working = _ssh_working_password.get(printer_id)
candidates = (
[working] + [p for p in _SSH_PASSWORDS if p != working]
if working else _SSH_PASSWORDS
)
try:
for password in candidates:
# Try all known file paths with this password in one shell command
cmd = " || ".join(f"cat {p}" for p in _SSH_FILE_PATHS)
result = subprocess.run(
[
"sshpass", "-p", password,
"ssh",
"-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "ConnectTimeout=5",
f"root@{host}",
cmd,
],
capture_output=True, text=True, timeout=10,
)
if result.returncode == 0 and result.stdout.strip():
if _ssh_working_password.get(printer_id) != password:
print(f"[SSH] ({printer_id}) authenticated with password {password!r}")
_ssh_working_password[printer_id] = password
return json.loads(result.stdout)
# Exit code 5 = sshpass auth failure — try next password
if result.returncode != 5:
print(f"[SSH] fetch failed ({host}): {result.stderr.strip() or 'no output'}")
return None
print(f"[SSH] all passwords failed for {host}")
return None
except FileNotFoundError:
print("[SSH] sshpass not found; run: apt install sshpass")
return None
except Exception as e:
print(f"[SSH] fetch failed ({host}): {e}")
return None
return await asyncio.get_event_loop().run_in_executor(None, _ssh_cat)
def _apply_serialnum_links(info: dict, printer_id: str) -> None:
"""Parse material_box_info.json; link slots whose serialNum is a valid Spoolman spool ID."""
base = _spoolman_base_url()
st = load_state(printer_id)
changed = False
boxes = (info.get("Material", {}).get("info") or [])
print(f"[SSH] ({printer_id}) material_box_info.json contains {len(boxes)} box(es): "
f"{[b.get('boxID') for b in boxes if isinstance(b, dict)]}")
for box in boxes:
box_id_str = box.get("boxID", "") # "T1" .. "T4"
if not box_id_str.startswith("T"):
continue
box_num = box_id_str[1:]
for mat in (box.get("list") or []):
mat_id = mat.get("materialId", "") # "A" .. "D"
slot = f"{box_num}{mat_id}"
if slot not in _VALID_CFS_SLOT_IDS:
continue
serial = (mat.get("serialNum") or "").strip()
if not serial or serial == "000000":
continue
try:
spool_id = int(serial)
except ValueError:
continue
if spool_id <= 0:
continue
slot_obj = st.slots.get(slot)
if slot_obj and getattr(slot_obj, "spoolman_id", None) == spool_id:
continue # already linked
if base:
try:
spool = _http_get_json(f"{base}/api/v1/spool/{spool_id}", timeout=5.0)
if not isinstance(spool, dict) or not spool.get("id"):
print(f"[SSH] Slot {slot}: serialNum {serial!r} → spool {spool_id} not in Spoolman")
continue
except Exception as e:
print(f"[SSH] Slot {slot}: Spoolman lookup failed for spool {spool_id}: {e}")
continue
if slot_obj is None:
slot_obj = SlotState(slot=slot)
slot_obj.spoolman_id = spool_id
st.slots[slot] = slot_obj
changed = True
print(f"[SSH] Slot {slot}: linked → Spoolman spool {spool_id} via serialNum {serial!r}")
if changed:
save_state(printer_id, st)
async def _ssh_fetch_and_apply(printer_id: str) -> None:
"""Fetch material_box_info.json via SSH and apply serialNum-based auto-links."""
_ssh_last_fetch[printer_id] = time.time()
info = await _fetch_printer_material_json(printer_id)
if info:
_apply_serialnum_links(info, printer_id)
def _color_distance(hex1: str, hex2: str) -> float:
"""Simple Euclidean RGB distance between two hex colors."""
try:
h1 = hex1.lstrip("#")
h2 = hex2.lstrip("#")
r1, g1, b1 = int(h1[0:2], 16), int(h1[2:4], 16), int(h1[4:6], 16)
r2, g2, b2 = int(h2[0:2], 16), int(h2[2:4], 16), int(h2[4:6], 16)
return math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
except Exception:
return 999.0
_WS_SAVE_INTERVAL = 10.0
_ws_last_save: Dict[str, float] = {}
_ws_last_rfid: Dict[str, Dict[str, str]] = {} # printer_id → slot → RFID
_ws_last_state: Dict[str, Dict[str, int]] = {} # printer_id → slot → CFS state (0/1/2)
_ws_last_fingerprint: Dict[str, Dict[str, str]] = {} # printer_id → slot → material fingerprint
_SSH_FETCH_COOLDOWN = 30.0 # seconds between SSH fetches of material_box_info.json
_ssh_last_fetch: Dict[str, float] = {}
_moon_last_state: Dict[str, str] = {} # printer_id → last known print_stats.state
_moon_last_filament_mm: Dict[str, float] = {} # printer_id → filament_used at last poll tick
_moon_job_track_slot_g: Dict[str, Dict[str, float]] = {} # printer_id → slot → grams
_moon_job_track_slot_mm: Dict[str, Dict[str, float]] = {} # printer_id → slot → mm
_moon_job_started_at: Dict[str, float] = {} # printer_id → Unix timestamp
_moon_job_name: Dict[str, str] = {} # printer_id → filename/job name
_VALID_CFS_SLOT_IDS = frozenset(
f"{b}{l}" for b in "1234" for l in "ABCD"
)
# Log unknown WS message top-level keys once per session to aid discovery
_ws_seen_keys: Dict[str, set] = {}
# Spoolman-derived percent cache for manual (non-RFID) slots
_spoolman_manual_pct: Dict[str, Dict[str, Optional[int]]] = {} # printer_id → slot → percent or None
_spoolman_pct_refresh_at: Dict[str, Dict[str, float]] = {} # printer_id → slot → next refresh timestamp
_SPOOLMAN_PCT_TTL = 60.0
_spoolman_job_color_cache: Dict[int, tuple[float, str]] = {} # spool_id → (ts, "#rrggbb"|"")
_SPOOLMAN_JOB_COLOR_CACHE_TTL = 30.0
# Known WS key names for printer identity (tried in order)
_WS_NAME_KEYS = ("hostname", "machineName", "printerName", "deviceName", "model", "MachineModel", "deviceModel")
_WS_FW_KEYS = ("softVersion", "firmwareVersion", "version", "FirmwareVersion", "SoftwareVersion", "firmware")
def _printer_ws_url(printer_id: str) -> str:
host = _printer_address(printer_id)
if not host:
return ""
return f"ws://{host.split(':')[0]}:9999"
def _moonraker_base_url(printer_id: str) -> str:
"""Return the Moonraker HTTP base URL (port 7125), or empty string if not configured."""
cfg = load_config()