forked from koen01/CFSync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1521 lines (1243 loc) · 54.4 KB
/
main.py
File metadata and controls
1521 lines (1243 loc) · 54.4 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
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,
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",
]
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 IP of the printer (used for WebSocket connection at ws://host:9999)
# Example: "192.168.178.148"
"printer_url": "",
# 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():
slots: Dict[str, dict] = {}
for s in DEFAULT_SLOTS:
slots[s] = _model_dump(SlotState(slot=s))
state = {
"active_slot": "2A",
"auto_mode": False,
"slots": slots,
"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 load_config() -> dict:
_ensure_data_files()
try:
cfg = json.loads(CONFIG_PATH.read_text())
except Exception:
cfg = {}
# Backward compat: extract hostname from legacy moonraker_url if printer_url not set
if not cfg.get("printer_url"):
mu = (cfg.get("moonraker_url") or "").strip()
if mu:
host = urlparse(mu).hostname or ""
if host:
print(f"[CONFIG] Migrating moonraker_url → printer_url (host={host!r})")
cfg["printer_url"] = host
cfg.setdefault("printer_url", "")
cfg.setdefault("filament_diameter_mm", 1.75)
cfg.setdefault("spoolman_url", "")
cfg.setdefault("spoolman_mode", "direct")
return cfg
def _migrate_state_dict(data: dict) -> dict:
"""Make state.json 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": "",
}
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", {})
# 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
_state_load_failed: bool = False # True when last load fell back to default
def load_state() -> AppState:
global _state_load_failed
_ensure_data_files()
try:
data = json.loads(STATE_PATH.read_text())
data = _migrate_state_dict(data)
result = _model_validate(AppState, data)
_state_load_failed = False
return result
except Exception as e:
# Corrupt/partial state files should never prevent the app from starting.
print(f"[STATE] load failed: {e}")
_state_load_failed = True
return default_state()
def save_state(state: AppState) -> None:
# Never overwrite real state with a fallback default — that destroys user data.
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 save_state(state: AppState) -> None:
state.updated_at = _now()
STATE_PATH.write_text(json.dumps(_model_dump(state), indent=2, ensure_ascii=False))
# --- 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}")
async def _fetch_printer_material_json() -> Optional[dict]:
"""SFTP-fetch material_box_info.json from the printer (runs in thread executor)."""
cfg = load_config()
host = (cfg.get("printer_url") or "").strip().split(":")[0]
if not host:
return None
def _sftp_get() -> Optional[dict]:
try:
import paramiko # lazy import — optional dependency
except ImportError:
print("[SSH] paramiko not installed; run: pip install paramiko")
return None
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username="root", password="creality_2023", timeout=5,
allow_agent=False, look_for_keys=False)
_, stdout, _ = ssh.exec_command(
"cat /usr/data/creality/userdata/box/material_box_info.json"
)
data = json.loads(stdout.read())
ssh.close()
return data
except Exception as e:
print(f"[SSH] fetch failed ({host}): {e}")
return None
return await asyncio.get_event_loop().run_in_executor(None, _sftp_get)
def _apply_serialnum_links(info: dict) -> None:
"""Parse material_box_info.json; link slots whose serialNum is a valid Spoolman spool ID."""
base = _spoolman_base_url()
st = load_state()
changed = False
for box in (info.get("Material", {}).get("info") or []):
box_id_str = box.get("boxID", "") # "T1" .. "T4"
if not box_id_str.startswith("T"):
continue
box_num = box_id_str[1:] # "1" .. "4"
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_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 correctly
# Verify spool exists in Spoolman before linking
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(st)
# Notify printer if active slot's spool changed
if _spoolman_mode() == "moonraker" and st.cfs_active_slot:
active_slot_obj = st.slots.get(st.cfs_active_slot)
new_spool_id = getattr(active_slot_obj, "spoolman_id", None) if active_slot_obj else None
_moonraker_set_active_spool(new_spool_id)
async def _ssh_fetch_and_apply() -> None:
"""Fetch material_box_info.json via SSH and apply serialNum-based auto-links."""
global _ssh_last_fetch
_ssh_last_fetch = time.time()
info = await _fetch_printer_material_json()
if info:
_apply_serialnum_links(info)
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: float = 0.0
_ws_last_state: Dict[str, int] = {} # slot → last seen CFS state (0/1/2)
_SENTINEL = object() # sentinel meaning "not yet seen this session"
_ws_active_slot: object = _SENTINEL # tracks last active slot in-process
_SSH_FETCH_COOLDOWN = 30.0 # seconds between SSH fetches of material_box_info.json
_ssh_last_fetch: float = 0.0
_moon_last_state: str = "" # last known print_stats.state from Moonraker
_moon_last_filament_mm: float = 0.0 # filament_used at last poll tick
_moon_job_track_slot_g: Dict[str, float] = {} # accumulated grams per slot for current job
_moon_job_track_slot_mm: Dict[str, float] = {} # accumulated mm per slot for current job
_VALID_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: set = set()
# Spoolman-derived percent cache for linked slots (both manual and RFID)
_spoolman_manual_pct: Dict[str, Optional[int]] = {} # slot → percent or None
_spoolman_pct_refresh_at: Dict[str, float] = {} # slot → next refresh timestamp
_SPOOLMAN_PCT_TTL = 60.0
_spoolman_remaining_g: Dict[str, float] = {} # slot → remaining_weight from Spoolman
_spoolman_nominal_g: Dict[str, float] = {} # slot → initial spool weight
# 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() -> str:
cfg = load_config()
host = (cfg.get("printer_url") or "").strip()
if not host:
mu = (cfg.get("moonraker_url") or "").strip()
if mu:
host = urlparse(mu).hostname or ""
if not host:
return ""
return f"ws://{host.split(':')[0]}:9999"
def _moonraker_base_url() -> str:
"""Return the Moonraker HTTP base URL (port 7125), or empty string if not configured."""
cfg = load_config()
mu = (cfg.get("moonraker_url") or "").strip()
if mu:
parsed = urlparse(mu)
host = parsed.hostname or ""
port = parsed.port or 7125
return f"http://{host}:{port}"
host = (cfg.get("printer_url") or "").strip().split(":")[0]
return f"http://{host}:7125" if host else ""
def _moonraker_send_gcode(script: str) -> bool:
"""POST a gcode script to Moonraker. Returns True on success."""
base = _moonraker_base_url()
if not base:
print(f"[MOON] send_gcode skipped — no Moonraker URL configured (script: {script!r})")
return False
url = f"{base}/printer/gcode/script"
try:
body = json.dumps({"script": script}).encode()
req = UrlRequest(url, data=body, headers={"Content-Type": "application/json"}, method="POST")
with urlopen(req, timeout=5.0) as resp:
if resp.status != 200:
print(f"[MOON] send_gcode HTTP {resp.status} for {script!r}")
return False
return True
except Exception as exc:
print(f"[MOON] send_gcode exception for {script!r}: {exc}")
return False
def _moonraker_set_active_spool(spool_id: Optional[int]) -> None:
"""Call SET_ACTIVE_SPOOL or CLEAR_ACTIVE_SPOOL on the printer via Moonraker."""
if spool_id:
cmd = f"SET_ACTIVE_SPOOL ID={spool_id}"
ok = _moonraker_send_gcode(cmd)
print(f"[MOON] {cmd} — {'OK' if ok else 'FAILED'}")
else:
ok = _moonraker_send_gcode("CLEAR_ACTIVE_SPOOL")
print(f"[MOON] CLEAR_ACTIVE_SPOOL — {'OK' if ok else 'FAILED'}")
def _normalize_ws_color(raw: str) -> str:
"""Strip leading zero after '#' from Creality color format '#0RRGGBB' → '#RRGGBB'."""
s = (raw or "").lstrip("#")
if len(s) == 7 and s[0] == "0":
return "#" + s[1:].lower()
if len(s) == 6:
return "#" + s.lower()
return raw
def _parse_ws_printer_info(payload: dict) -> None:
"""Extract printer name / firmware from any WS status message and persist to state.
Also logs any previously-unseen top-level keys once per session so we can
discover the exact field names the printer uses.
"""
global _ws_seen_keys
new_keys = set(payload.keys()) - _ws_seen_keys
if new_keys:
_ws_seen_keys |= new_keys
print(f"[WS] New message keys: {sorted(new_keys)}")
name = ""
for k in _WS_NAME_KEYS:
v = str(payload.get(k) or "").strip()
if v:
name = v
break
fw = ""
for k in _WS_FW_KEYS:
v = str(payload.get(k) or "").strip()
if v:
fw = v
break
# Parse "modelVersion" field: "printer hw ver:;printer sw ver:;DWIN sw ver:1.1.3.13;"
if not fw:
mv = str(payload.get("modelVersion") or "").strip()
if mv:
for part in mv.split(";"):
part = part.strip()
if "sw ver:" in part.lower() and ":" in part:
ver = part.split(":", 1)[1].strip()
if ver:
fw = ver
break
if not name and not fw:
return
st = load_state()
changed = False
if name and name != st.printer_name:
st.printer_name = name
changed = True
print(f"[WS] Printer name: {name!r}")
if fw and fw != st.printer_firmware:
st.printer_firmware = fw
changed = True
print(f"[WS] Firmware: {fw!r}")
if changed:
save_state(st)
def _parse_ws_cfs_data(payload: dict) -> None:
"""Parse a boxsInfo WS payload and update local state + Spoolman."""
global _ws_last_save, _ws_last_state, _ssh_last_fetch, _ws_active_slot
try:
boxes = (payload.get("boxsInfo") or {}).get("materialBoxs") or []
except Exception:
return
st = load_state()
active_slot: Optional[str] = None
boxes_meta: dict = {}
for box in boxes:
if not isinstance(box, dict):
continue
if box.get("type") != 0:
continue # skip spool holders (type 1)
box_id = box.get("id")
if not isinstance(box_id, int) or box_id < 1 or box_id > 4:
continue
boxes_meta[str(box_id)] = {
"connected": True,
"temperature_c": float(box["temp"]) if isinstance(box.get("temp"), (int, float)) else None,
"humidity_pct": float(box["humidity"]) if isinstance(box.get("humidity"), (int, float)) else None,
}
for mat in (box.get("materials") or []):
if not isinstance(mat, dict):
continue
mat_id = mat.get("id")
if not isinstance(mat_id, int) or mat_id < 0 or mat_id > 3:
continue
slot = f"{box_id}{'ABCD'[mat_id]}"
if slot not in _VALID_SLOT_IDS:
continue
state_val = int(mat.get("state") or 0)
selected = int(mat.get("selected") or 0)
# state 2 = RFID: use Spoolman-based calc (consistent with manual)
# state 1 = manual: WS always reports 100 (no sensor) → use Spoolman cache
# state 0 = empty: no percent
if state_val == 2:
pct = _spoolman_manual_pct.get(slot) # None until async refresh fills it
elif state_val == 1:
pct = _spoolman_manual_pct.get(slot) # None until async refresh fills it
else:
pct = None
raw_color = mat.get("color", "")
col = _normalize_ws_color(raw_color)
st.cfs_slots[slot] = {
"color": col if (state_val > 0 and col and col.startswith("#")) else "",
"percent": pct,
"state": state_val,
"rfid": mat.get("rfid", ""),
"selected": selected,
"present": state_val > 0,
}
if selected == 1:
active_slot = slot
# Update local slot metadata from CFS data (only if spool is physically present)
if state_val > 0 and slot in st.slots:
slot_obj = st.slots[slot]
if col and len(col) == 7 and col.startswith("#"):
slot_obj.color_hex = col
mat_type = (mat.get("type") or "").strip().upper()
if mat_type:
slot_obj.material = mat_type # type: ignore[assignment]
name = (mat.get("name") or "").strip()
if name:
slot_obj.name = name
vendor = (mat.get("vendor") or "").strip()
if vendor:
slot_obj.manufacturer = vendor
st.slots[slot] = slot_obj
# Detect RFID→non-RFID swap: unlink Spoolman when state drops from 2
prev_state = _ws_last_state.get(slot, -1)
_ws_last_state[slot] = state_val
if prev_state == 2 and state_val != 2:
slot_obj_swap = st.slots.get(slot)
if slot_obj_swap and getattr(slot_obj_swap, "spoolman_id", None):
if _spoolman_mode() == "moonraker" and active_slot == slot:
_moonraker_set_active_spool(None)
slot_obj_swap.spoolman_id = None
st.slots[slot] = slot_obj_swap
st.ws_slot_length_m.pop(slot, None)
_spoolman_manual_pct.pop(slot, None)
_spoolman_pct_refresh_at.pop(slot, None)
print(f"[CFS] Slot {slot}: state {prev_state}→{state_val}, unlinked Spoolman spool (spool swap)")
# SSH fetch for serialNum-based auto-link whenever a slot freshly becomes RFID
if state_val == 2 and prev_state != 2:
now = time.time()
if now - _ssh_last_fetch > _SSH_FETCH_COOLDOWN:
asyncio.create_task(_ssh_fetch_and_apply())
# Track cumulative length for per-job Moonraker attribution
cur_m = float(mat.get("usedMaterialLength") or 0)
st.ws_slot_length_m[slot] = cur_m
# Store box connection metadata so the frontend can show correct boxes
if boxes_meta:
st.cfs_slots["_boxes"] = boxes_meta
# Always update active slot — clears stale value when printer is idle
st.cfs_active_slot = active_slot
if active_slot and active_slot in st.slots:
st.active_slot = active_slot
# Moonraker mode: notify printer when the active spool changes.
# Use the in-process _ws_active_slot variable (not disk state) so that:
# (a) a restart with an already-active spool still fires the gcode, and
# (b) rapid WS messages within the save interval don't fire repeatedly.
if _spoolman_mode() == "moonraker" and active_slot != _ws_active_slot:
new_spool_id = (st.slots[active_slot].spoolman_id
if active_slot and active_slot in st.slots else None)
_moonraker_set_active_spool(new_spool_id)
_ws_active_slot = active_slot
st.cfs_connected = True
st.cfs_last_update = _now()
st.printer_connected = True
st.printer_last_error = ""
now = _now()
if now - _ws_last_save >= _WS_SAVE_INTERVAL:
save_state(st)
_ws_last_save = now
async def _refresh_manual_slot_pcts() -> None:
"""Calculate Spoolman-based percent for all linked slots (manual and RFID) and cache it.
Called after each boxsInfo parse. Uses a per-slot TTL so Spoolman is queried
at most once per _SPOOLMAN_PCT_TTL seconds per slot.
"""
base = _spoolman_base_url()
if not base:
return
st = load_state()
now = _now()
loop = asyncio.get_running_loop()
for slot, cfs_meta in list(st.cfs_slots.items()):
if not isinstance(cfs_meta, dict) or cfs_meta.get("state") not in (1, 2):
continue
slot_obj = st.slots.get(slot)
spool_id = getattr(slot_obj, "spoolman_id", None) if slot_obj else None
if not spool_id:
_spoolman_manual_pct.pop(slot, None)
continue
if _spoolman_pct_refresh_at.get(slot, 0) > now:
continue # still fresh
try:
sp = await loop.run_in_executor(None, _spoolman_get_spool, base, spool_id)
filament = sp.get("filament") or {}
nominal_g = float(filament.get("weight") or 0)
remaining_g = float(sp.get("remaining_weight") or 0)
used_g = float(sp.get("used_weight") or 0)
if nominal_g > 0:
pct: Optional[int] = max(0, min(100, int(round(remaining_g / nominal_g * 100))))
elif remaining_g + used_g > 0:
pct = max(0, min(100, int(round(remaining_g / (remaining_g + used_g) * 100))))
else:
pct = None
_spoolman_manual_pct[slot] = pct
_spoolman_remaining_g[slot] = remaining_g
_spoolman_nominal_g[slot] = nominal_g if nominal_g > 0 else (remaining_g + used_g)
_spoolman_pct_refresh_at[slot] = now + _SPOOLMAN_PCT_TTL
state_label = "RFID" if cfs_meta.get("state") == 2 else "manual"
print(f"[SPOOLMAN] Slot {slot} {state_label} percent: {pct}%")
except Exception:
_spoolman_pct_refresh_at[slot] = now + 10.0 # back off on error
async def _ws_connect_and_run(ws_url: str) -> None:
"""Open one WebSocket connection to the printer and run the polling loop."""
async with websockets.connect(ws_url, ping_interval=None, ping_timeout=None) as ws:
# Consume the very first burst (max 5 messages, 0.15 s each).
# Parse for printer identity (hostname/modelVersion) but skip CFS data,
# which may be stale at this point.
for _ in range(5):
try:
msg = await asyncio.wait_for(ws.recv(), timeout=0.15)
try:
_parse_ws_printer_info(json.loads(msg))
except Exception:
pass
except asyncio.TimeoutError:
break
# Heartbeat handshake. The printer may push status frames before "ok",
# so scan up to 10 messages instead of assuming the very next one is the ack.
await ws.send(json.dumps({"ModeCode": "heart_beat"}))
for _ in range(10):
try:
reply = await asyncio.wait_for(ws.recv(), timeout=2.0)
if str(reply).strip() == "ok":
break
except asyncio.TimeoutError:
break
st = load_state()
st.printer_connected = True
st.printer_last_error = ""
save_state(st)
print(f"[WS] Connected to {ws_url}")
# Request initial CFS data immediately after handshake
await ws.send(json.dumps({"method": "get", "params": {"boxsInfo": 1}}))
_last_request: float = asyncio.get_event_loop().time()
# Continuous message loop — process everything the printer sends.
# Never assume the next recv() is the response to our request; the printer
# pushes status frames continuously between our request and its reply.
while True:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=6.0)
except asyncio.TimeoutError:
# Printer went silent — re-request and wait again
await ws.send(json.dumps({"method": "get", "params": {"boxsInfo": 1}}))
_last_request = asyncio.get_event_loop().time()
continue
# Printer heartbeat ping — ack it immediately
if isinstance(msg, str) and "heart_beat" in msg:
await ws.send("ok")
continue
# Plain "ok" is the printer acking our heartbeat — nothing to do
if isinstance(msg, str) and msg.strip() == "ok":
continue
try:
data = json.loads(msg)
_parse_ws_printer_info(data)
if "boxsInfo" in data:
_parse_ws_cfs_data(data)
asyncio.create_task(_refresh_manual_slot_pcts())
except Exception:
pass
# Re-request every 5 s so we keep receiving fresh pushes
now = asyncio.get_event_loop().time()
if now - _last_request >= 5.0:
await ws.send(json.dumps({"method": "get", "params": {"boxsInfo": 1}}))
_last_request = now
async def printer_ws_loop() -> None:
"""Outer reconnect loop for the printer WebSocket connection."""
ws_url = _printer_ws_url()
if not ws_url:
print("[WS] No printer_url configured — WebSocket loop not started.")
return
print(f"[WS] Starting WebSocket loop for {ws_url}")
backoff = 2.0
while True:
last_err = ""
try:
await _ws_connect_and_run(ws_url)
backoff = 2.0 # reset on clean exit
except Exception as e:
last_err = str(e)
print(f"[WS] Connection lost: {e}")
try:
st = load_state()
st.printer_connected = False
st.cfs_connected = False
st.printer_last_error = last_err
save_state(st)
except Exception:
pass
print(f"[WS] Reconnecting in {backoff:.0f}s…")
await asyncio.sleep(backoff)
backoff = min(backoff * 2, 60.0)
def _moon_flush_to_spoolman(reason: str) -> None:
"""Sync accumulated per-slot grams to Spoolman and reset job trackers."""
global _moon_job_track_slot_g, _moon_job_track_slot_mm, _moon_last_filament_mm
st = load_state()
for slot, g in _moon_job_track_slot_g.items():
if g <= 0:
continue
slot_obj = st.slots.get(slot)
spool_id = getattr(slot_obj, "spoolman_id", None) if slot_obj else None
if spool_id:
if _spoolman_mode() == "direct":
_spoolman_report_usage(spool_id, g)
print(f"[MOON] {reason}: slot {slot} → {g:.2f}g synced to Spoolman spool {spool_id}")
else:
print(f"[MOON] {reason}: slot {slot} → {g:.2f}g (moonraker mode, Moonraker plugin tracks usage)")
else:
print(f"[MOON] {reason}: slot {slot} → {g:.2f}g (no Spoolman link, not synced)")
if not _moon_job_track_slot_g:
print(f"[MOON] {reason}: no filament deltas recorded")
# Persist lifetime stats for each slot that consumed filament this job
now = _now()
for slot, g in _moon_job_track_slot_g.items():
if g <= 0:
continue
stats = st.cfs_stats.get(slot) or SlotStats()
stats.total_kg = round(stats.total_kg + g / 1000.0, 6)
stats.total_meters = round(stats.total_meters + _moon_job_track_slot_mm.get(slot, 0.0) / 1000.0, 4)
stats.last_used_at = now
st.cfs_stats[slot] = stats
if any(g > 0 for g in _moon_job_track_slot_g.values()):
save_state(st)