-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathdisplay.py
More file actions
2333 lines (2058 loc) · 97.4 KB
/
display.py
File metadata and controls
2333 lines (2058 loc) · 97.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
import json
import sys
import logging
import pathlib
import re
import os
import os.path
import time
import io
import asyncio
import traceback
import aiohttp
import signal
import systemd.daemon
from PIL import Image
from src.config import TEMP_DEFAULTS, ConfigHandler
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from math import ceil
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import quote
from src.tjc import EventType
from src.response_actions import response_actions, input_actions, custom_touch_actions
from src.lib_col_pic import parse_thumbnail
from src.communicator import DisplayCommunicator
from src.neptune4 import (
MODEL_N4_REGULAR,
MODEL_N4_PRO,
MODEL_N4_PLUS,
MODEL_N4_MAX,
MODELS_N4,
ElegooNeptune4DisplayCommunicator,
OpenNeptune4DisplayCommunicator
)
from src.elegoo_neptune3 import MODELS_N3, ElegooNeptune3DisplayCommunicator, OpenNeptune3DisplayCommunicator
from src.elegoo_custom import MODEL_CUSTOM, CustomDisplayCommunicator
from src.mapping import (
build_format_filename,
filename_regex_wrapper,
PAGE_MAIN,
PAGE_FILES,
PAGE_PREPARE_MOVE,
PAGE_PREPARE_TEMP,
PAGE_PREPARE_EXTRUDER,
PAGE_SETTINGS_TEMPERATURE_SET,
PAGE_LEVELING,
PAGE_LEVELING_SCREW_ADJUST,
PAGE_LEVELING_Z_OFFSET_ADJUST,
PAGE_CONFIRM_PRINT,
PAGE_PRINTING,
PAGE_PRINTING_KAMP,
PAGE_PRINTING_PAUSE,
PAGE_PRINTING_STOP,
PAGE_PRINTING_EMERGENCY_STOP,
PAGE_PRINTING_COMPLETE,
PAGE_PRINTING_FILAMENT,
PAGE_PRINTING_SPEED,
PAGE_PRINTING_ADJUST,
PAGE_OVERLAY_LOADING,
format_time,
)
from src.colors import BACKGROUND_SUCCESS, BACKGROUND_WARNING
# Global flag for graceful shutdown
_shutdown_requested = False
# Create module-level logger and placeholder for event loop
logger = logging.getLogger(__name__)
loop = None
def signal_handler(signum, frame):
global _shutdown_requested, loop
_shutdown_requested = True
logger.info("Received signal %s, initiating graceful shutdown...", signum)
try:
# Only attempt to stop the loop if it exists and is running.
if loop is not None and loop.is_running():
loop.call_soon_threadsafe(loop.stop)
except Exception:
# Log the error instead of swallowing it silently
logger.exception("Unexpected error in signal_handler")
# Register signal handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
log_file = os.path.expanduser("~/printer_data/logs/display_connector.log")
logger = logging.getLogger(__name__)
ch_log = logging.StreamHandler(sys.stdout)
ch_log.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
ch_log.setFormatter(formatter)
logger.addHandler(ch_log)
file_log = logging.FileHandler(log_file)
file_log.setLevel(logging.ERROR)
file_log.setFormatter(formatter)
logger.addHandler(file_log)
logger.setLevel(logging.DEBUG)
comms_directory = os.path.expanduser("~/printer_data/comms")
config_file = os.path.expanduser("~/printer_data/config/display_connector.cfg")
PRINTING_PAGES = [
PAGE_PRINTING,
PAGE_PRINTING_KAMP,
PAGE_PRINTING_FILAMENT,
PAGE_PRINTING_PAUSE,
PAGE_PRINTING_STOP,
PAGE_PRINTING_EMERGENCY_STOP,
PAGE_PRINTING_FILAMENT,
PAGE_PRINTING_SPEED,
PAGE_PRINTING_ADJUST,
]
TABBED_PAGES = [
PAGE_PREPARE_EXTRUDER,
PAGE_PREPARE_MOVE,
PAGE_PREPARE_TEMP,
PAGE_PRINTING_ADJUST,
PAGE_PRINTING_FILAMENT,
PAGE_PRINTING_SPEED,
]
TRANSITION_PAGES = [PAGE_OVERLAY_LOADING]
SUPPORTED_PRINTERS = [MODEL_N4_REGULAR, MODEL_N4_PRO, MODEL_N4_PLUS, MODEL_N4_MAX]
def get_communicator(display, model) -> DisplayCommunicator:
# Normalize display name to avoid None/whitespace/case issues
disp = (display or "").strip().lower()
# OpenNeptune variants
if disp == "openneptune":
if model == MODEL_CUSTOM:
return CustomDisplayCommunicator
elif model in MODELS_N4:
return OpenNeptune4DisplayCommunicator
elif model in MODELS_N3:
return OpenNeptune3DisplayCommunicator
# Default to Elegoo-compatible communicators for everything else (including empty/None)
if model == MODEL_CUSTOM:
return CustomDisplayCommunicator
elif model in MODELS_N4:
return ElegooNeptune4DisplayCommunicator
elif model in MODELS_N3:
return ElegooNeptune3DisplayCommunicator
# Final fallback to avoid returning None (log to make debugging easier)
logger.warning(f"get_communicator: unknown display '{display}' or unsupported model '{model}', falling back to ElegooNeptune4DisplayCommunicator")
return ElegooNeptune4DisplayCommunicator
SOCKET_LIMIT = 20 * 1024 * 1024
class ResourceManager:
def __init__(self):
self._thread_pool = None
self._shutdown = False
self._lock = asyncio.Lock()
def get_thread_pool(self):
"""Get thread pool, creating it if necessary"""
if self._thread_pool is None and not self._shutdown:
logger.info("Creating new thread pool")
self._thread_pool = ThreadPoolExecutor(max_workers=2)
return self._thread_pool
async def cleanup(self):
if self._shutdown or not self._thread_pool:
return
self._shutdown = True
tp = self._thread_pool
self._thread_pool = None
try:
tp.shutdown(wait=False, cancel_futures=True)
logger.info("Thread pool shutdown initiated (non-blocking)")
except Exception as e:
logger.warning(f"Exception during thread pool shutdown: {e}")
def allow_new_pool(self):
"""Allow creating a new thread pool after shutdown"""
logger.info("Allowing new thread pool creation")
self._shutdown = False
class DisplayController:
last_config_change = 0
filament_sensor_name = "filament_sensor"
def __init__(self, config, loop):
self._loop = loop
self.pending_reqs_lock = asyncio.Lock()
self.config = config
self._handle_config()
self.connected = False
self._cached_printer_model = None
self._display_initialized = False
display_type = self.config.safe_get("general", "display_type", "elegoo")
printer_model = self.get_printer_model()
self.display = get_communicator(display_type, printer_model)(
logger,
printer_model,
event_handler=self.display_event_handler,
port=self.config.safe_get("general", "serial_port"),
)
self._handle_display_config()
self._filename_lock = asyncio.Lock()
self.current_filename = None
self.part_light_state = False
self.frame_light_state = False
self.fan_state = False
self.filament_sensor_state = False
self.move_distance = "1"
self.xy_move_speed = 130
self.z_move_speed = 10
self.z_offset_distance = "0.01"
self.out_fd = sys.stdout.fileno()
os.set_blocking(self.out_fd, False)
self.pending_req = {}
self.pending_reqs = {}
self.history = []
self.current_state = "booting"
self.dir_contents = []
self.current_dir = ""
self.files_page = 0
self.printing_selected_heater = "extruder"
self.printing_target_temps = {
"extruder": 0,
"heater_bed": 0,
"heater_bed_outer": 0,
}
self.printing_selected_temp_increment = "10"
self.printing_selected_speed_type = "print"
self.printing_target_speeds = {"print": 1.0, "flow": 1.0, "fan": 1.0}
self.printing_selected_speed_increment = "10"
self.extrude_amount = 50
self.extrude_speed = 300
self.temperature_preset_material = "pla"
self.temperature_preset_step = 10
self.temperature_preset_extruder = 0
self.temperature_preset_bed = 0
self.leveling_mode = None
self.screw_probe_count = 0
self.screw_levels = {}
self.z_probe_step = "0.1"
self.z_probe_distance = "0.0"
self.full_bed_leveling_counts = [0, 0]
self.bed_leveling_counts = [0, 0]
self.bed_leveling_probed_count = 0
self.bed_leveling_last_position = None
self._rapid_scan_mode = False
self.klipper_restart_event = asyncio.Event()
self.resources = ResourceManager()
self._speed_lock = asyncio.Lock()
self.REQUEST_TIMEOUT = 1200 # seconds
self._cleanup_task = None
self._last_thumbnail_request = None
self._thumbnail_retry_lock = asyncio.Lock()
self._bed_leveling_complete = False
self._thumbnail_displayed = False
self._thumbnail_task = None
self._is_reconnecting = False
self._listen_task = None
self._is_listening = False
self._process_stream_task = None
self._history_lock = asyncio.Lock()
self._reconnect_lock = asyncio.Lock()
self._files_lock = asyncio.Lock()
def pathname2url(self, path):
return quote(path.replace("\\", "/"))
def handle_config_change(self):
if self.last_config_change + 5 > time.time():
return
self.last_config_change = time.time()
logger.info("Config file changed, Reloading")
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
self.config.reload_config()
self._handle_config()
self._loop.create_task(self._go_back())
def _handle_config(self):
logger.info("Loading config")
if "general" in self.config:
if "clean_filename_regex" in self.config["general"]:
filename_regex_wrapper["default"] = re.compile(
self.config["general"]["clean_filename_regex"]
)
if "filament_sensor_name" in self.config["general"]:
self.filament_sensor_name = self.config["general"][
"filament_sensor_name"
]
if "LOGGING" in self.config:
if "file_log_level" in self.config["LOGGING"]:
file_log.setLevel(self.config["LOGGING"]["file_log_level"])
logger.setLevel(logging.DEBUG)
if "prepare" in self.config:
prepare = self.config["prepare"]
if "move_distance" in prepare:
distance = prepare["move_distance"]
if distance in ["0.1", "1", "10"]:
self.move_distance = distance
self.xy_move_speed = prepare.getint("xy_move_speed", fallback=130)
self.z_move_speed = prepare.getint("z_move_speed", fallback=10)
self.extrude_amount = prepare.getint("extrude_amount", fallback=50)
self.extrude_speed = prepare.getint("extrude_speed", fallback=300)
def _handle_display_config(self):
self.display.mapper.set_filament_sensor_name(self.filament_sensor_name)
if "main_screen" in self.config:
if "display_name" in self.config["main_screen"]:
self.display.display_name_override = self.config["main_screen"][
"display_name"
]
if "display_name_line_color" in self.config["main_screen"]:
self.display.display_name_line_color = self.config["main_screen"][
"display_name_line_color"
]
if "print_screen" in self.config:
if "z_display" in self.config["print_screen"]:
self.display.mapper.set_z_display(
self.config["print_screen"]["z_display"]
)
if "clean_filename_regex" in self.config["print_screen"]:
filename_regex_wrapper["printing"] = re.compile(
self.config["print_screen"]["clean_filename_regex"]
)
def get_printer_model(self):
if self._cached_printer_model is not None:
return self._cached_printer_model
# Check config first
try:
if "general" in self.config:
if "printer_model" in self.config["general"]:
self._cached_printer_model = self.config["general"]["printer_model"]
return self._cached_printer_model
except Exception as e:
logger.warning(f"Error reading printer model from config: {e}")
# Read from file
try:
with open("/boot/.OpenNept4une.txt", "r") as file:
for line in file:
try:
if line.startswith(tuple(SUPPORTED_PRINTERS)):
model_part = line.split("-")[0].strip()
self._cached_printer_model = model_part
return self._cached_printer_model
except Exception as e:
logger.warning(f"Error parsing line '{line}': {e}")
continue
except FileNotFoundError:
logger.error("Printer model file not found at /boot/.OpenNept4une.txt")
except Exception as e:
logger.error(f"Error reading printer model file: {e}")
# Default
logger.info(f"Using default printer model: {MODEL_N4_REGULAR}")
self._cached_printer_model = MODEL_N4_REGULAR
return self._cached_printer_model
async def special_page_handling(self, current_page):
"""Handle special page setup. Called after navigation completes."""
if current_page == PAGE_FILES:
await self.display.show_files_page(
self.current_dir, self.dir_contents, self.files_page
)
elif current_page == PAGE_PREPARE_MOVE:
await self.display.update_prepare_move_ui(self.move_distance)
elif current_page == PAGE_PREPARE_EXTRUDER:
await self.display.update_prepare_extrude_ui(
self.extrude_amount, self.extrude_speed
)
elif current_page == PAGE_SETTINGS_TEMPERATURE_SET:
await self.display.update_preset_temp_ui(
self.temperature_preset_step,
self.temperature_preset_extruder,
self.temperature_preset_bed,
)
elif current_page == PAGE_CONFIRM_PRINT:
# Safely get filename under lock
async with self._filename_lock:
filename = self.current_filename
if filename:
self._loop.create_task(self.set_data_prepare_screen(filename))
else:
logger.warning("PAGE_CONFIRM_PRINT reached but no filename set")
elif current_page == PAGE_PRINTING_FILAMENT:
await self.display.update_printing_heater_settings_ui(
self.printing_selected_heater,
self.printing_target_temps[self.printing_selected_heater],
)
await self.display.update_printing_temperature_increment_ui(
self.printing_selected_temp_increment
)
elif current_page == PAGE_PRINTING_ADJUST:
await self.display.update_printing_zoffset_increment_ui(
self.z_offset_distance
)
elif current_page == PAGE_PRINTING_SPEED:
await self.display.update_printing_speed_settings_ui(
self.printing_selected_speed_type,
self.printing_target_speeds[self.printing_selected_speed_type],
)
await self.display.update_printing_speed_increment_ui(
self.printing_selected_speed_increment
)
elif current_page == PAGE_LEVELING:
self.leveling_mode = None
elif current_page == PAGE_LEVELING_SCREW_ADJUST:
await self.display.draw_initial_screw_leveling()
self._loop.create_task(self.handle_screw_leveling())
elif current_page == PAGE_LEVELING_Z_OFFSET_ADJUST:
await self.display.draw_initial_zprobe_leveling(self.z_probe_step, self.z_probe_distance)
self._loop.create_task(self.handle_zprobe_leveling())
elif current_page == PAGE_PRINTING_KAMP:
if not self._rapid_scan_mode:
await self.display.draw_kamp_page(self.bed_leveling_counts)
return
await self.display.special_page_handling(current_page)
async def send_gcodes_async(self, gcodes):
for gcode in gcodes:
logger.debug("Sending GCODE: " + gcode)
await self._send_moonraker_request(
"printer.gcode.script", {"script": gcode}
)
await asyncio.sleep(0.1)
def send_gcode(self, gcode):
logger.debug("Sending GCODE: " + gcode)
self._loop.create_task(
self._send_moonraker_request("printer.gcode.script", {"script": gcode})
)
def move_axis(self, axis, distance):
speed = self.xy_move_speed if axis in ["X", "Y"] else self.z_move_speed
self.send_gcode(f"G91\nG1 {axis}{distance} F{int(speed) * 60}\nG90")
async def _navigate_to_page(self, page, clear_history=False):
"""Navigate to a page without holding locks during I/O operations."""
# Cancel any pending thumbnail task when navigating (outside lock)
if self._thumbnail_task and not self._thumbnail_task.done():
self._thumbnail_task.cancel()
try:
await self._thumbnail_task
except asyncio.CancelledError:
pass
# PHASE 1: Check bed leveling block (under lock - DATA ONLY)
async with self._history_lock:
current_page = self.history[-1] if self.history else None
if current_page == PAGE_PRINTING_KAMP and not self._bed_leveling_complete and page != PAGE_PRINTING:
logger.info("Preventing navigation during bed leveling")
return
# PHASE 2: Handle KAMP special case
async with self._history_lock:
current_page = self.history[-1] if self.history else None
need_printing_first = (
page == PAGE_PRINTING_KAMP and
(not self.history or current_page not in PRINTING_PAGES)
)
if need_printing_first:
async with self._history_lock:
if clear_history:
self.history.clear()
self.history.append(PAGE_PRINTING)
# Do mapping under lock (fast dict lookup)
mapped_printing = self.display.mapper.map_page(PAGE_PRINTING)
# Navigate (outside lock - I/O)
await self.display.navigate_to(mapped_printing)
await asyncio.sleep(0.1)
logger.debug(f"Navigating to {PAGE_PRINTING}")
try:
await self.special_page_handling(PAGE_PRINTING)
except Exception as e:
logger.error(f"Error in special page handling for PRINTING: {e}")
await asyncio.sleep(0.1)
# PHASE 3: Normal navigation path
should_navigate = False
mapped_page = None
async with self._history_lock:
current_page = self.history[-1] if self.history else None
if not self.history or current_page != page:
# Decide what to do with history
if page in TABBED_PAGES and self.history and current_page in TABBED_PAGES:
self.history[-1] = page
else:
if clear_history and page != PAGE_PRINTING_KAMP:
self.history.clear()
self.history.append(page)
should_navigate = True
# Do mapping under lock (fast)
mapped_page = self.display.mapper.map_page(page)
# Action phase (outside lock - I/O)
if should_navigate:
await self.display.navigate_to(mapped_page)
logger.debug(f"Navigating to {page}")
try:
await self.special_page_handling(page)
except Exception as e:
logger.error(f"Error in special page handling for {page}: {e}")
def execute_action(self, action):
if action.startswith("move_"):
parts = action.split("_")
axis = parts[1].upper()
direction = parts[2]
self.move_axis(axis, direction + self.move_distance)
elif action.startswith("set_distance_"):
parts = action.split("_")
self.move_distance = parts[2]
self._loop.create_task(
self.display.update_prepare_move_ui(self.move_distance)
)
if action.startswith("zoffset_"):
parts = action.split("_")
direction = parts[1]
self.send_gcode(
f"SET_GCODE_OFFSET Z_ADJUST={direction}{self.z_offset_distance} MOVE=1"
)
elif action.startswith("zoffsetchange_"):
parts = action.split("_")
self.z_offset_distance = parts[1]
self._loop.create_task(
self.display.update_printing_zoffset_increment_ui(
self.z_offset_distance
)
)
elif action == "toggle_part_light":
self.part_light_state = not self.part_light_state
self._set_light("Part_Light", self.part_light_state)
elif action == "toggle_frame_light":
self.frame_light_state = not self.frame_light_state
self._set_light("Frame_Light", self.frame_light_state)
elif action == "toggle_filament_sensor":
self.filament_sensor_state = not self.filament_sensor_state
self._toggle_filament_sensor(self.filament_sensor_state)
elif action == "toggle_fan":
self.fan_state = not self.fan_state
self._toggle_fan(self.fan_state)
elif action.startswith("printer.send_gcode"):
gcode = action.split("'")[1]
self.send_gcode(gcode)
elif action == "go_back":
self._loop.create_task(self._go_back())
elif action.startswith("page"):
self._loop.create_task(self._navigate_to_page(action.split(" ")[1]))
elif action == "emergency_stop":
logger.info("Executing emergency stop!")
self._loop.create_task(
self._send_moonraker_request("printer.emergency_stop")
)
elif action == "pause_print_button":
self._loop.create_task(self._handle_pause_resume())
elif action == "pause_print_confirm":
self._loop.create_task(self._handle_pause_confirm())
elif action == "stop_print":
self._loop.create_task(self._go_back())
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
logger.info("Stopping print")
self._loop.create_task(self._send_moonraker_request("printer.print.cancel"))
elif action == "files_picker":
self._loop.create_task(self._navigate_to_page(PAGE_FILES))
self._loop.create_task(self._load_files())
elif action.startswith("temp_heater_"):
parts = action.split("_")
self.printing_selected_heater = "_".join(parts[2:])
self._loop.create_task(
self.display.update_printing_heater_settings_ui(
self.printing_selected_heater,
self.printing_target_temps[self.printing_selected_heater],
)
)
elif action.startswith("temp_increment_"):
parts = action.split("_")
self.printing_selected_temp_increment = parts[2]
self._loop.create_task(
self.display.update_printing_temperature_increment_ui(
self.printing_selected_temp_increment
)
)
elif action.startswith("temp_adjust_"):
parts = action.split("_")
direction = parts[2]
current_temp = self.printing_target_temps[self.printing_selected_heater]
self.send_gcode(
"SET_HEATER_TEMPERATURE HEATER="
+ self.printing_selected_heater
+ " TARGET="
+ str(
current_temp
+ (
int(self.printing_selected_temp_increment)
* (1 if direction == "+" else -1)
)
)
)
elif action == "temp_reset":
self.send_gcode(
"SET_HEATER_TEMPERATURE HEATER="
+ self.printing_selected_heater
+ " TARGET=0"
)
elif action.startswith("speed_type_"):
parts = action.split("_")
self.printing_selected_speed_type = parts[2]
self._loop.create_task(
self.display.update_printing_speed_settings_ui(
self.printing_selected_speed_type,
self.printing_target_speeds[self.printing_selected_speed_type],
)
)
elif action.startswith("speed_increment_"):
parts = action.split("_")
self.printing_selected_speed_increment = parts[2]
self._loop.create_task(
self.display.update_printing_speed_increment_ui(
self.printing_selected_speed_increment
)
)
elif action.startswith("speed_adjust_"):
parts = action.split("_")
direction = parts[2]
current_speed = self.printing_target_speeds[self.printing_selected_speed_type] # factor
change = int(self.printing_selected_speed_increment) * (
1 if direction == "+" else -1
)
new_speed = current_speed + (change / 100.0) # factor math only
self._loop.create_task(
self.send_speed_update(self.printing_selected_speed_type, new_speed)
)
elif action == "speed_reset":
# for fan you might prefer 0.0 instead of 1.0
reset_value = 1.0 if self.printing_selected_speed_type != "fan" else 0.0
self._loop.create_task(
self.send_speed_update(self.printing_selected_speed_type, reset_value)
)
elif action.startswith("files_page_"):
parts = action.split("_")
direction = parts[2]
async def _change_files_page():
async with self._files_lock:
self.files_page = int(
max(
0,
min(
(len(self.dir_contents) / 5),
self.files_page + (1 if direction == "next" else -1),
),
)
)
await self.display.show_files_page(
self.current_dir, self.dir_contents, self.files_page
)
self._loop.create_task(_change_files_page())
elif action.startswith("open_file_"):
parts = action.split("_")
index = int(parts[2])
async def _handle_file_selection():
async with self._files_lock:
selected = self.dir_contents[(self.files_page * 5) + index]
is_dir = selected["type"] == "dir"
file_path = selected["path"]
if is_dir:
self.current_dir = file_path
self.files_page = 0
if is_dir:
await self._load_files()
else:
async with self._filename_lock:
self.current_filename = file_path
await self._navigate_to_page(PAGE_CONFIRM_PRINT)
self._loop.create_task(_handle_file_selection())
elif action == "print_opened_file":
# Create async task that safely reads filename under lock
async def _navigate_and_print():
await self._navigate_to_page(PAGE_OVERLAY_LOADING, clear_history=True)
async with self._filename_lock:
filename_to_print = self.current_filename
await self._send_moonraker_request(
"printer.print.start", {"filename": filename_to_print}
)
self._loop.create_task(_navigate_and_print())
elif action == "confirm_complete":
logger.info("Clearing SD Card")
self.send_gcode("SDCARD_RESET_FILE")
elif action.startswith("set_temp"):
parts = action.split("_")
target = parts[-1]
heater = "_".join(parts[2:-1])
self.send_gcode(
"SET_HEATER_TEMPERATURE HEATER=" + heater + " TARGET=" + target
)
elif action.startswith("set_preset_temp"):
parts = action.split("_")
material = parts[3].lower()
if "temperatures." + material in self.config:
extruder = self.config["temperatures." + material]["extruder"]
heater_bed = self.config["temperatures." + material]["heater_bed"]
else:
extruder = TEMP_DEFAULTS[material][0]
heater_bed = TEMP_DEFAULTS[material][1]
gcodes = [
f"SET_HEATER_TEMPERATURE HEATER=extruder TARGET={extruder}",
f"SET_HEATER_TEMPERATURE HEATER=heater_bed TARGET={heater_bed}",
]
if self.display.model == MODEL_N4_PRO:
gcodes.append(
f"SET_HEATER_TEMPERATURE HEATER=heater_bed_outer TARGET={heater_bed}"
)
self._loop.create_task(self.send_gcodes_async(gcodes))
elif action.startswith("set_extrude_amount"):
self.extrude_amount = int(action.split("_")[3])
self._loop.create_task(
self.display.update_prepare_extrude_ui(self.extrude_amount, self.extrude_speed)
)
elif action.startswith("set_extrude_speed"):
self.extrude_speed = int(action.split("_")[3])
self._loop.create_task(
self.display.update_prepare_extrude_ui(self.extrude_amount, self.extrude_speed)
)
elif action.startswith("extrude_"):
async def _handle_extrude():
async with self._filename_lock: # Reuse existing lock or create _state_lock
is_not_printing = (self.current_state != "printing")
if is_not_printing:
parts = action.split("_")
direction = parts[1]
loadtype = "LOAD" if direction == "+" else "UNLOAD"
gcode_sequence = f"{loadtype}_FILAMENT"
await self.send_gcodes_async(gcode_sequence.strip().split('\n'))
self._loop.create_task(_handle_extrude())
elif action.startswith("start_temp_preset_"):
material = action.split("_")[3]
self.temperature_preset_material = material
if "temperatures." + material in self.config:
self.temperature_preset_extruder = int(
self.config["temperatures." + material]["extruder"]
)
self.temperature_preset_bed = int(
self.config["temperatures." + material]["heater_bed"]
)
else:
self.temperature_preset_extruder = TEMP_DEFAULTS[material][0]
self.temperature_preset_bed = TEMP_DEFAULTS[material][1]
self._loop.create_task(self._navigate_to_page(PAGE_SETTINGS_TEMPERATURE_SET))
elif action.startswith("preset_temp_step_"):
size = int(action.split("_")[3])
self.temperature_preset_step = size
elif action.startswith("preset_temp_"):
parts = action.split("_")
heater = parts[2]
change = (
self.temperature_preset_step
if parts[3] == "up"
else -self.temperature_preset_step
)
if heater == "extruder":
self.temperature_preset_extruder += change
else:
self.temperature_preset_bed += change
self._loop.create_task(
self.display.update_preset_temp_ui(
self.temperature_preset_step,
self.temperature_preset_extruder,
self.temperature_preset_bed,
)
)
elif action == "save_temp_preset":
logger.info("Saving temp preset")
self.save_temp_preset()
elif action == "retry_screw_leveling":
self._loop.create_task(self.display.draw_initial_screw_leveling())
self._loop.create_task(self.handle_screw_leveling())
elif action == "begin_full_bed_level":
self.leveling_mode = "full_bed"
self._loop.create_task(self._navigate_to_page(PAGE_PRINTING_KAMP))
self.send_gcode("AUTO_FULL_BED_LEVEL")
elif action.startswith("zprobe_step_"):
parts = action.split("_")
self.z_probe_step = parts[2]
self._loop.create_task(
self.display.update_zprobe_leveling_ui(
self.z_probe_step, self.z_probe_distance
)
)
elif action.startswith("zprobe_"):
parts = action.split("_")
direction = parts[1]
self.send_gcode(f"TESTZ Z={direction}{self.z_probe_step}")
elif action == "abort_zprobe":
self.send_gcode("ABORT")
self._loop.create_task(self._go_back())
elif action == "save_zprobe":
self.send_gcode("ACCEPT")
self.send_gcode("SAVE_CONFIG")
self._loop.create_task(self._go_back())
elif action == "save_config":
self.send_gcode("SAVE_CONFIG")
self._loop.create_task(self._go_back())
elif action.startswith("set_speed_"):
parts = action.split("_")
percent = int(parts[2])
self._loop.create_task(
self.send_speed_update("print", percent / 100.0)
)
elif action.startswith("set_flow_"):
parts = action.split("_")
percent = int(parts[2])
self._loop.create_task(
self.send_speed_update("flow", percent / 100.0)
)
elif action == "reboot_host":
logger.info("Rebooting Host")
self._loop.create_task(self._go_back())
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
self._loop.create_task(self._send_moonraker_request("machine.reboot"))
elif action == "shutdown_host":
logger.info("Shutting down Host")
self._loop.create_task(self.run_shutdown_sequence())
elif action == "reboot_klipper":
logger.info("Rebooting Klipper")
self._loop.create_task(
self._send_moonraker_request(
"machine.services.restart", {"service": "klipper"}
)
)
self._loop.create_task(self._go_back())
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
elif action == "firmware_restart":
logger.info("Firmware Restart")
self._loop.create_task(self._send_moonraker_request("printer.firmware_restart"))
self._loop.create_task(self._go_back())
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
async def _handle_pause_resume(self):
if self.current_state == "paused":
logger.info("Resuming print")
await self._send_moonraker_request("printer.print.resume")
else:
await self._go_back()
await self._navigate_to_page(PAGE_PRINTING_PAUSE)
async def _handle_pause_confirm(self):
await self._go_back()
logger.info("Pausing print")
await self._send_moonraker_request("printer.print.pause")
def _set_light(self, light_name, new_state):
gcode = f"{light_name}_{'ON' if new_state else 'OFF'}"
self.send_gcode(gcode)
def _toggle_filament_sensor(self, state):
gcode = f"SET_FILAMENT_SENSOR SENSOR={self.filament_sensor_name} ENABLE={'1' if state else '0'}"
self.send_gcode(gcode)
def save_temp_preset(self):
if "temperatures." + self.temperature_preset_material not in self.config:
self.config["temperatures." + self.temperature_preset_material] = {}
self.config.set(
"temperatures." + self.temperature_preset_material,
"extruder",
str(self.temperature_preset_extruder),
)
self.config.set(
"temperatures." + self.temperature_preset_material,
"heater_bed",
str(self.temperature_preset_bed),
)
self.config.write_changes()
self._loop.create_task(self._go_back())
async def send_speed_update(self, speed_type, new_speed):
"""Update speed/flow/fan without holding lock during I/O."""
gcode_script = None
new_target_value = None
if speed_type == "print":
factor = float(new_speed)
percent = factor * 100.0
gcode_script = f"M220 S{percent:.0f}"
new_target_value = factor
elif speed_type == "flow":
factor = float(new_speed)
percent = factor * 100.0
gcode_script = f"M221 S{percent:.0f}"
new_target_value = factor
elif speed_type == "fan":
factor = min(max(float(new_speed), 0.0), 1.0) # clamp 0–1
value = int(round(factor * 255))
gcode_script = f"M106 S{value}"
new_target_value = factor
try:
if gcode_script:
await self._send_moonraker_request(
"printer.gcode.script",
{"script": gcode_script},
)
async with self._speed_lock:
if new_target_value is not None:
self.printing_target_speeds[speed_type] = new_target_value
ui_speed_type = self.printing_selected_speed_type
ui_speed_value = self.printing_target_speeds[ui_speed_type]
await self.display.update_printing_speed_settings_ui(
ui_speed_type,
ui_speed_value,
)
except Exception as e:
logger.error(f"Error updating speed: {e}")
raise
def _toggle_fan(self, state):
gcode = f"M106 S{'255' if state else '0'}"
self.send_gcode(gcode)
def _build_path(self, *components):
path = ""
for component in components:
if component is None or component == "" or component == "/":
continue
path += f"/{component}"
return path[1:]
def sort_dir_contents(self, dir_contents):
key = "modified"
reverse = True
if "files" in self.config:
files_config = self.config["files"]
if "sort_by" in files_config:
key = files_config["sort_by"]
if "sort_order" in files_config:
reverse = files_config["sort_order"] == "desc"
return sorted(dir_contents, key=lambda k: k[key], reverse=reverse)
async def _load_files(self):
data = await self._send_moonraker_request(
"server.files.get_directory",
{"path": "/".join(["gcodes", self.current_dir])},
)
dir_info = data["result"]