forked from OpenNeptune3D/display_connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay.py
1448 lines (1325 loc) · 58.8 KB
/
display.py
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 requests
import re
import os
import os.path
import time
import io
import asyncio
import traceback
import aiohttp
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
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_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:
if display == "openneptune":
if model == MODEL_CUSTOM:
return CustomDisplayCommunicator
elif model in MODELS_N4:
return OpenNeptune4DisplayCommunicator
elif model in MODELS_N3:
return OpenNeptune3DisplayCommunicator
else:
if model == MODEL_CUSTOM:
return CustomDisplayCommunicator
elif model in MODELS_N4:
return ElegooNeptune4DisplayCommunicator
elif model in MODELS_N3:
return ElegooNeptune3DisplayCommunicator
SOCKET_LIMIT = 20 * 1024 * 1024
class DisplayController:
last_config_change = 0
filament_sensor_name = "filament_sensor"
def __init__(self, config):
self.config = config
self._handle_config()
self.connected = False
display_type = self.config.safe_get("general", "display_type")
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()
# Initialize lock for current_filename
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.klipper_restart_event = asyncio.Event()
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._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 "general" in self.config:
if "printer_model" in self.config["general"]:
return self.config["general"]["printer_model"]
try:
with open("/boot/.OpenNept4une.txt", "r") as file:
for line in file:
if line.startswith(tuple(SUPPORTED_PRINTERS)):
model_part = line.split("-")[0].strip()
return model_part
except FileNotFoundError:
logger.error("File not found")
except Exception as e:
logger.error(f"Error reading file: {e}")
return None
async def special_page_handling(self, current_page):
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:
self._loop.create_task(self.set_data_prepare_screen(self.current_filename))
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:
await self.display.draw_kamp_page(self.bed_leveling_counts)
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):
if not self.history or self.history[-1] != page:
# Handle page navigation within tabbed pages
if page in TABBED_PAGES and self.history and self.history[-1] in TABBED_PAGES:
self.history[-1] = page
else:
if clear_history:
self.history.clear()
self.history.append(page)
# Start navigation task asynchronously
mapped_page = self.display.mapper.map_page(page)
await self.display.navigate_to(mapped_page)
logger.debug(f"Navigating to {page}")
# Handle any special page logic
await self.special_page_handling(page)
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._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._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
]
change = int(self.printing_selected_speed_increment) * (
1 if direction == "+" else -1
)
self.send_speed_update(
self.printing_selected_speed_type,
(current_speed + (change / 100.0)) * 100,
)
elif action == "speed_reset":
self.send_speed_update(self.printing_selected_speed_type, 1.0)
elif action.startswith("files_page_"):
parts = action.split("_")
direction = parts[2]
self.files_page = int(
max(
0,
min(
(len(self.dir_contents) / 5),
self.files_page + (1 if direction == "next" else -1),
),
)
)
self._loop.create_task(
self.display.show_files_page(self.current_dir, self.dir_contents, self.files_page)
)
elif action.startswith("open_file_"):
parts = action.split("_")
index = int(parts[2])
selected = self.dir_contents[(self.files_page * 5) + index]
if selected["type"] == "dir":
self.current_dir = selected["path"]
self.files_page = 0
self._loop.create_task(self._load_files())
else:
self.current_filename = selected["path"]
self._loop.create_task(self._navigate_to_page(PAGE_CONFIRM_PRINT))
elif action == "print_opened_file":
self._go_back()
self._loop.create_task(self._navigate_to_page(PAGE_OVERLAY_LOADING))
self._loop.create_task(
self._send_moonraker_request(
"printer.print.start", {"filename": self.current_filename}
)
)
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_"):
parts = action.split("_")
direction = parts[1]
target_temp = 200
# Send GCODE commands in sequence:
gcode_sequence = f"""
M83
SET_HEATER_TEMPERATURE HEATER=extruder TARGET={target_temp}
TEMPERATURE_WAIT SENSOR=extruder MINIMUM={target_temp - 4} MAXIMUM={target_temp + 40}
G1 E{direction}{self.extrude_amount} F{self.extrude_speed}
"""
# Send the full GCODE sequence
self._loop.create_task(self.send_gcodes_async(gcode_sequence.strip().split('\n')))
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._go_back()
elif action == "save_zprobe":
self.send_gcode("ACCEPT")
self.send_gcode("SAVE_CONFIG")
self._go_back()
elif action == "save_config":
self.send_gcode("SAVE_CONFIG")
self._go_back()
elif action.startswith("set_speed_"):
parts = action.split("_")
speed = int(parts[2])
self.send_speed_update("print", speed)
elif action.startswith("set_flow_"):
parts = action.split("_")
speed = int(parts[2])
self.send_speed_update("flow", speed)
elif action == "reboot_host":
logger.info("Rebooting Host")
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._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._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:
self._go_back()
await self._navigate_to_page(PAGE_PRINTING_PAUSE)
async def _handle_pause_confirm(self):
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._go_back()
def send_speed_update(self, speed_type, new_speed):
if new_speed != 1.0:
if speed_type == "print":
self.send_gcode(f"M220 S{new_speed:.0f}")
elif speed_type == "flow":
self.send_gcode(f"M221 S{new_speed:.0f}")
elif speed_type == "fan":
new_speed = int(new_speed)
value = min(max(((new_speed) / 100) * 255, 0), 255)
self.send_gcode(f"M106 S{value}")
else:
if speed_type == "print":
self.send_gcode("M220 S100")
elif speed_type == "flow":
self.send_gcode("M221 S100")
elif speed_type == "fan":
self.send_gcode("M106 S0")
#edited for more stable print interface
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"]
self.dir_contents = []
dirs = []
for item in dir_info["dirs"]:
if not item["dirname"].startswith("."):
dirs.append(
{
"type": "dir",
"path": self._build_path(self.current_dir, item["dirname"]),
"size": item["size"],
"modified": item["modified"],
"name": item["dirname"],
}
)
files = []
for item in dir_info["files"]:
if item["filename"].endswith(".gcode"):
files.append(
{
"type": "file",
"path": self._build_path(self.current_dir, item["filename"]),
"size": item["size"],
"modified": item["modified"],
"name": build_format_filename()(item["filename"]),
}
)
sort_folders_first = True
if "files" in self.config:
sort_folders_first = self.config["files"].getboolean(
"sort_folders_first", fallback=True
)
if sort_folders_first:
self.dir_contents = self.sort_dir_contents(dirs) + self.sort_dir_contents(
files
)
else:
self.dir_contents = self.sort_dir_contents(dirs + files)
await self.display.show_files_page(
self.current_dir, self.dir_contents, self.files_page
)
def _page_id(self, page):
return self.display.mapper.map_page(page)
def _go_back(self):
if len(self.history) > 1:
if self._get_current_page() == PAGE_FILES and self.current_dir != "":
self.current_dir = "/".join(self.current_dir.split("/")[:-1])
self.files_page = 0
self._loop.create_task(self._load_files())
return
self.history.pop()
while len(self.history) > 1 and self.history[-1] in TRANSITION_PAGES:
self.history.pop()
back_page = self.history[-1]
self._loop.create_task(
self.display.navigate_to(self.display.mapper.map_page(back_page))
)
logger.debug(f"Navigating back to {back_page}")
self._loop.create_task(self.special_page_handling(back_page))
else:
logger.debug("Already at the main page.")
def start_listening(self):
self._loop.create_task(self.listen())
async def listen(self):
await self.display.connect()
await self.display.check_valid_version()
await self.connect_moonraker()
ret = await self._send_moonraker_request(
"printer.objects.subscribe",
{
"objects": {
"gcode_move": ["extrude_factor", "speed_factor", "homing_origin"],
"motion_report": ["live_position", "live_velocity"],
"fan": ["speed"],
"heater_bed": ["temperature", "target"],
"extruder": ["temperature", "target"],
"heater_generic heater_bed_outer": ["temperature", "target"],
"display_status": ["progress"],
"print_stats": [
"state",
"print_duration",
"filename",
"total_duration",
"info",
],
"output_pin Part_Light": ["value"],
"output_pin Frame_Light": ["value"],
"configfile": ["config"],
f"filament_switch_sensor {self.filament_sensor_name}": ["enabled"],
}
},
)
data = ret["result"]["status"]
logger.info("Display Type: " + str(self.display.get_display_type_name()))
logger.info("Printer Model: " + str(self.display.get_device_name()))
await self.display.initialize_display()
await self.handle_status_update(data)
async def _send_moonraker_request(self, method, params=None):
if params is None:
params = {}
message = self._make_rpc_msg(method, **params)
fut = self._loop.create_future()
self.pending_reqs[message["id"]] = fut
data = json.dumps(message).encode() + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
raise
except Exception:
await self.close()
return await fut
def _find_ips(self, network):
ips = []
for key in network:
if "ip_addresses" in network[key]:
for ip in network[key]["ip_addresses"]:
if ip["family"] == "ipv4":
ips.append(ip["address"])
return ips
async def connect_moonraker(self) -> None:
sockfile = os.path.expanduser("~/printer_data/comms/moonraker.sock")
sockpath = pathlib.Path(sockfile).expanduser().resolve()
logger.info(f"Connecting to Moonraker at {sockpath}")
while True:
try:
reader, writer = await asyncio.open_unix_connection(
sockpath, limit=SOCKET_LIMIT
)
self.writer = writer
self._loop.create_task(self._process_stream(reader))
self.connected = True
logger.info("Connected to Moonraker")
try:
software_version_response = await self._send_moonraker_request(
"printer.info"
)
software_version = software_version_response["result"][
"software_version"
]
software_version = "-".join(
software_version.split("-")[:2]
) # clean up version string
# Process the software_version...
logger.info(f"Software Version: {software_version}")
await self.display.update_klipper_version_ui(software_version)
break
except KeyError:
logger.error(
"KeyError encountered in software_version_response. Attempting to reconnect."
)
await asyncio.sleep(5) # Wait before reconnecting
continue # Retry the connection loop
except asyncio.CancelledError:
raise
except Exception as e:
logger.error(f"Error connecting to Moonraker: {e}")
await asyncio.sleep(5) # Wait before reconnecting
continue
ret = await self._send_moonraker_request(
"server.connection.identify",
{
"client_name": "OpenNept4une Display Connector",
"version": "0.0.1",
"type": "other",
"url": "https://github.com/halfbearman/opennept4une",
},
)
logger.debug(
f"Client Identified With Moonraker: {ret['result']['connection_id']}"
)
system = (await self._send_moonraker_request("machine.system_info"))["result"][
"system_info"
]
self.display.ips = ", ".join(self._find_ips(system["network"]))
def _make_rpc_msg(self, method: str, **kwargs):
msg = {"jsonrpc": "2.0", "method": method}
uid = id(msg)
msg["id"] = uid
self.pending_req = msg
if kwargs:
msg["params"] = kwargs
return msg
def handle_response(self, page, component):
if page in response_actions:
if component in response_actions[page]:
self.execute_action(response_actions[page][component])
return
if component == 0:
self._go_back()
return
logger.info(f"Unhandled Response: {page} {component}")
def handle_input(self, page, component, value):
if page in input_actions:
if component in input_actions[page]:
self.execute_action(
input_actions[page][component].replace("$", str(value))
)
return
logger.info(f"Unhandled Input: {page} {component} {value}")
def handle_custom_touch(self, x, y):
if self._get_current_page() in custom_touch_actions:
actions = custom_touch_actions[self._get_current_page()]
for key in actions:
min_x, min_y, max_x, max_y = key
if min_x < x and x < max_x and min_y < y and y < max_y:
self.execute_action(actions[key])
return
async def display_event_handler(self, type, data):
if type == EventType.TOUCH:
self.handle_response(data.page_id, data.component_id)
elif type == EventType.TOUCH_COORDINATE:
if data.touch_event == 0:
self.handle_custom_touch(data.x, data.y)
elif type == EventType.SLIDER_INPUT: