forked from beacon3d/beacon_klipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeacon.py
3953 lines (3395 loc) · 144 KB
/
beacon.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
# Beacon eddy current scanner support
#
# Copyright (C) 2020-2023 Matt Baker <baker.matt.j@gmail.com>
# Copyright (C) 2020-2023 Lasse Dalegaard <dalegaard@gmail.com>
# Copyright (C) 2023 Beacon <beacon3d.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import re
import threading
import multiprocessing
import subprocess
import os
import importlib
import traceback
import logging
import chelper
import pins
import math
import time
import queue
import struct
import numpy as np
import copy
import collections
import itertools
from numpy.polynomial import Polynomial
from . import manual_probe
from . import probe
from . import bed_mesh
from . import thermistor
from . import adxl345
from .homing import HomingMove
from mcu import MCU, MCU_trsync
from clocksync import SecondarySync
from extras.danger_options import get_danger_options
import msgproto
STREAM_BUFFER_LIMIT_DEFAULT = 100
STREAM_TIMEOUT = 1.0
API_DUMP_FIELDS = ["dist", "temp", "pos", "freq", "vel", "time"]
class BeaconProbe:
def __init__(self, config):
self.printer = config.get_printer()
self.reactor = self.printer.get_reactor()
self.mcu_temp_wrapper = BeaconMCUTempWrapper(self)
self.name = config.get_name()
self.home_dir = os.path.dirname(os.path.realpath(__file__))
self.speed = config.getfloat("speed", 5.0, above=0.0)
self.lift_speed = config.getfloat("lift_speed", self.speed, above=0.0)
self.backlash_comp = config.getfloat("backlash_comp", 0.5)
self.x_offset = config.getfloat("x_offset", 0.0)
self.y_offset = config.getfloat("y_offset", 0.0)
self.trigger_distance = config.getfloat("trigger_distance", 2.0)
self.trigger_dive_threshold = config.getfloat("trigger_dive_threshold", 1.0)
self.trigger_hysteresis = config.getfloat("trigger_hysteresis", 0.006)
self.z_settling_time = config.getint("z_settling_time", 5, minval=0)
self.default_probe_method = config.getchoice(
"default_probe_method", PROBING_METHOD_CHOICES, "proximity"
)
self.default_mesh_method = config.getchoice(
"default_mesh_method", MESHING_METHOD_CHOICES, self.default_probe_method
)
# If using paper for calibration, this would be .1mm
self.cal_nozzle_z = config.getfloat("cal_nozzle_z", 0.1)
self.cal_floor = config.getfloat("cal_floor", 0.2)
self.cal_ceil = config.getfloat("cal_ceil", 5.0)
self.cal_speed = config.getfloat("cal_speed", 1.0)
self.cal_move_speed = config.getfloat("cal_move_speed", 10.0)
self.autocal_max_speed = config.getfloat("autocal_max_speed", 10)
self.autocal_speed = config.getfloat("autocal_speed", 3)
self.autocal_accel = config.getfloat("autocal_accel", 100)
self.autocal_retract_dist = config.getfloat("autocal_retract_dist", 2)
self.autocal_retract_speed = config.getfloat("autocal_retract_speed", 10)
self.autocal_sample_count = config.getfloat("autocal_sample_count", 3)
self.autocal_tolerance = config.getfloat("autocal_tolerance", 0.008)
self.autocal_max_retries = config.getfloat("autocal_max_retries", 3)
self.contact_latency_min = config.getint("contact_latency_min", 0)
self.contact_sensitivity = config.getint("contact_sensitivity", 0)
# Load models
self.model = None
self.models = {}
self.model_temp_builder = BeaconTempModelBuilder.load(config)
self.model_temp = None
self.fmin = None
self.default_model_name = config.get("default_model_name", "default")
self.model_manager = ModelManager(self)
# Temperature sensor integration
self.temp = None
self.last_temp = 0
self.last_mcu_temp = None
self.measured_min = 99999999.0
self.measured_max = 0.0
self.mcu_temp = None
self.thermistor = None
self.last_sample = None
self.last_received_sample = None
self.last_z_result = 0
self.last_probe_position = (0, 0)
self.last_probe_result = None
self.last_offset_result = None
self.last_poke_result = None
self.last_contact_msg = None
self.hardware_failure = None
self.last_state = False
self.mesh_helper = BeaconMeshHelper.create(self, config)
self.homing_helper = BeaconHomingHelper.create(self, config)
self.accel_helper = None
self.accel_config = BeaconAccelConfig(config)
self._stream_en = 0
self._stream_timeout_timer = self.reactor.register_timer(self._stream_timeout)
self._stream_callbacks = {}
self._stream_latency_requests = {}
self._stream_buffer = []
self._stream_buffer_count = 0
self._stream_buffer_limit = STREAM_BUFFER_LIMIT_DEFAULT
self._stream_buffer_limit_new = self._stream_buffer_limit
self._stream_samples_queue = queue.Queue()
self._stream_flush_event = threading.Event()
self._log_stream = None
self._data_filter = AlphaBetaFilter(
config.getfloat("filter_alpha", 0.5),
config.getfloat("filter_beta", 0.000001),
)
self.trapq = None
self.mod_axis_twist_comp = None
self.get_z_compensation_value = lambda pos: 0.0
mainsync = self.printer.lookup_object("mcu")._clocksync
self._mcu = MCU(config, SecondarySync(self.reactor, mainsync))
orig_stats = self._mcu.stats
def beacon_mcu_stats(eventtime):
show, value = orig_stats(eventtime)
value += " " + self._extend_stats()
return show, value
self._mcu.stats = beacon_mcu_stats
self.printer.add_object("mcu " + self.name, self._mcu)
self.cmd_queue = self._mcu.alloc_command_queue()
self._endstop_shared = BeaconEndstopShared(self)
self.mcu_probe = BeaconEndstopWrapper(self)
self.mcu_contact_probe = BeaconContactEndstopWrapper(self, config)
self._current_probe = self.default_probe_method
self.beacon_stream_cmd = None
self.beacon_set_threshold = None
self.beacon_home_cmd = None
self.beacon_stop_home_cmd = None
self.beacon_nvm_read_cmd = None
self.beacon_contact_home_cmd = None
self.beacon_contact_query_cmd = None
self.beacon_contact_stop_home_cmd = None
self.beacon_contact_set_latency_min_cmd = None
self.beacon_contact_set_sensitivity_cmd = None
# Register z_virtual_endstop
self.printer.lookup_object("pins").register_chip("probe", self)
# Register event handlers
self.printer.register_event_handler("klippy:connect", self._handle_connect)
self.printer.register_event_handler(
"klippy:shutdown", self.force_stop_streaming
)
self._mcu.register_config_callback(self._build_config)
self._mcu.register_response(self._handle_beacon_data, "beacon_data")
self._mcu.register_response(self._handle_beacon_status, "beacon_status")
self._mcu.register_response(self._handle_beacon_contact, "beacon_contact")
# Register webhooks
self._api_dump = APIDumpHelper(
self.printer,
lambda: self.streaming_session(self._api_dump_callback, latency=50),
lambda stream: stream.stop(),
None,
)
self.webhooks = self.printer.lookup_object("webhooks")
self.webhooks.register_endpoint("beacon/status", self._handle_req_status)
self.webhooks.register_endpoint("beacon/dump", self._handle_req_dump)
# Register gcode commands
self.gcode = self.printer.lookup_object("gcode")
self.gcode.register_command(
"BEACON_STREAM", self.cmd_BEACON_STREAM, desc=self.cmd_BEACON_STREAM_help
)
self.gcode.register_command(
"BEACON_QUERY", self.cmd_BEACON_QUERY, desc=self.cmd_BEACON_QUERY_help
)
self.gcode.register_command(
"BEACON_CALIBRATE",
self.cmd_BEACON_CALIBRATE,
desc=self.cmd_BEACON_CALIBRATE_help,
)
self.gcode.register_command(
"BEACON_ESTIMATE_BACKLASH",
self.cmd_BEACON_ESTIMATE_BACKLASH,
desc=self.cmd_BEACON_ESTIMATE_BACKLASH_help,
)
self.gcode.register_command("PROBE", self.cmd_PROBE, desc=self.cmd_PROBE_help)
self.gcode.register_command(
"QUERY_PROBE", self.cmd_QUERY_PROBE, desc=self.cmd_QUERY_PROBE_help
)
self.gcode.register_command(
"PROBE_ACCURACY", self.cmd_PROBE_ACCURACY, desc=self.cmd_PROBE_ACCURACY_help
)
self.gcode.register_command(
"Z_OFFSET_APPLY_PROBE",
self.cmd_Z_OFFSET_APPLY_PROBE,
desc=self.cmd_Z_OFFSET_APPLY_PROBE_help,
)
self.gcode.register_command(
"BEACON_POKE", self.cmd_BEACON_POKE, desc=self.cmd_BEACON_POKE_help
)
self.gcode.register_command(
"BEACON_AUTO_CALIBRATE",
self.cmd_BEACON_AUTO_CALIBRATE,
desc=self.cmd_BEACON_AUTO_CALIBRATE_help,
)
self.gcode.register_command(
"BEACON_OFFSET_COMPARE",
self.cmd_BEACON_OFFSET_COMPARE,
desc=self.cmd_BEACON_OFFSET_COMPARE_help,
)
self._hook_probing_gcode(config, "z_tilt", "Z_TILT_ADJUST")
self._hook_probing_gcode(config, "quad_gantry_level", "QUAD_GANTRY_LEVEL")
self._hook_probing_gcode(config, "screws_tilt_adjust", "SCREWS_TILT_ADJUST")
self._hook_probing_gcode(config, "delta_calibrate", "DELTA_CALIBRATE")
# Event handlers
def _handle_connect(self):
self.phoming = self.printer.lookup_object("homing")
self.mod_axis_twist_comp = self.printer.lookup_object(
"axis_twist_compensation", None
)
if self.mod_axis_twist_comp:
if hasattr(self.mod_axis_twist_comp, "get_z_compensation_value"):
self.get_z_compensation_value = (
lambda pos: self.mod_axis_twist_comp.get_z_compensation_value(pos)
)
else:
def _update_compensation(pos):
cpos = list(pos)
self.mod_axis_twist_comp._update_z_compensation_value(cpos)
return cpos[2] - pos[2]
self.get_z_compensation_value = _update_compensation
if self.model is None:
self.model = self.models.get(self.default_model_name, None)
def _check_mcu_version(self):
updater = os.path.join(self.home_dir, "update_firmware.py")
if not os.path.exists(updater):
logging.info(
"Could not find Beacon firmware update script, won't check for update."
)
return ""
serialport = self._mcu._serialport
parent_conn, child_conn = multiprocessing.Pipe()
def do():
try:
output = subprocess.check_output(
[updater, "check", serialport], universal_newlines=True
)
child_conn.send((False, output.strip()))
except Exception:
child_conn.send((True, traceback.format_exc()))
child_conn.close()
child = multiprocessing.Process(target=do)
child.daemon = True
child.start()
eventtime = self.reactor.monotonic()
while child.is_alive():
eventtime = self.reactor.pause(eventtime + 0.1)
(is_err, result) = parent_conn.recv()
child.join()
parent_conn.close()
if is_err:
logging.info("Executing Beacon update script failed: %s", result)
elif result != "":
self.gcode.respond_raw("!! " + result + "\n")
pconfig = self.printer.lookup_object("configfile")
try:
pconfig.runtime_warning(result)
except AttributeError:
logging.info(result)
return result
return ""
def _build_config(self):
version_info = self._check_mcu_version()
try:
self.beacon_stream_cmd = self._mcu.lookup_command(
"beacon_stream en=%u", cq=self.cmd_queue
)
self.beacon_set_threshold = self._mcu.lookup_command(
"beacon_set_threshold trigger=%u untrigger=%u", cq=self.cmd_queue
)
self.beacon_home_cmd = self._mcu.lookup_command(
"beacon_home trsync_oid=%c trigger_reason=%c trigger_invert=%c",
cq=self.cmd_queue,
)
self.beacon_stop_home_cmd = self._mcu.lookup_command(
"beacon_stop_home", cq=self.cmd_queue
)
self.beacon_nvm_read_cmd = self._mcu.lookup_query_command(
"beacon_nvm_read len=%c offset=%hu",
"beacon_nvm_data bytes=%*s offset=%hu",
cq=self.cmd_queue,
)
self.beacon_contact_home_cmd = self._mcu.lookup_command(
"beacon_contact_home trsync_oid=%c trigger_reason=%c trigger_type=%c",
cq=self.cmd_queue,
)
self.beacon_contact_query_cmd = self._mcu.lookup_query_command(
"beacon_contact_query",
"beacon_contact_state triggered=%c detect_clock=%u",
cq=self.cmd_queue,
)
self.beacon_contact_stop_home_cmd = self._mcu.lookup_command(
"beacon_contact_stop_home",
cq=self.cmd_queue,
)
try:
self.beacon_contact_set_latency_min_cmd = self._mcu.lookup_command(
"beacon_contact_set_latency_min latency_min=%c",
cq=self.cmd_queue,
)
except msgproto.error:
pass
try:
self.beacon_contact_set_sensitivity_cmd = self._mcu.lookup_command(
"beacon_contact_set_sensitivity sensitivity=%c",
cq=self.cmd_queue,
)
except msgproto.error:
pass
constants = self._mcu.get_constants()
self._mcu_freq = self._mcu._mcu_freq
self.inv_adc_max = 1.0 / constants.get("ADC_MAX")
self.temp_smooth_count = constants.get("BEACON_ADC_SMOOTH_COUNT")
self.thermistor = thermistor.Thermistor(10000.0, 0.0)
self.thermistor.setup_coefficients_beta(25.0, 47000.0, 4101.0)
self.toolhead = self.printer.lookup_object("toolhead")
self.trapq = self.toolhead.get_trapq()
rails = self.toolhead.get_kinematics().get_rails()
if len(rails) > 2:
rails[2].homing_retract_dist = 0
if hasattr(rails[2], "min_home_dist"):
rails[2].min_home_dist = 0
self.mcu_temp = BeaconMCUTempHelper.build_with_nvm(self)
self.model_temp = self.model_temp_builder.build_with_nvm(self)
if self.model_temp:
self.fmin = self.model_temp.fmin
if self.model is None:
self.model = self.models.get(self.default_model_name, None)
if self.model:
self._apply_threshold()
if self.beacon_stream_cmd is not None:
self.beacon_stream_cmd.send([1 if self._stream_en else 0])
if self._stream_en:
curtime = self.reactor.monotonic()
self.reactor.update_timer(
self._stream_timeout_timer, curtime + STREAM_TIMEOUT
)
else:
self.reactor.update_timer(
self._stream_timeout_timer, self.reactor.NEVER
)
if constants.get("BEACON_HAS_ACCEL", 0) == 1:
logging.info("Enabling Beacon accelerometer")
if self.accel_helper is None:
self.accel_helper = BeaconAccelHelper(
self, self.accel_config, constants
)
else:
self.accel_helper.reinit(constants)
except msgproto.error as e:
if version_info != "":
raise msgproto.error(version_info + "\n\n" + str(e))
raise
def _extend_stats(self):
parts = [
"coil_temp=%.1f" % (self.last_temp,),
"refs=%d" % (self._stream_en,),
]
if self.last_mcu_temp is not None:
(mcu_temp, supply_voltage) = self.last_mcu_temp
parts.append("mcu_temp=%.2f" % (mcu_temp,))
parts.append("supply_voltage=%.3f" % (supply_voltage,))
return " ".join(parts)
def _api_dump_callback(self, sample):
tmp = [sample.get(key, None) for key in API_DUMP_FIELDS]
self._api_dump.buffer.append(tmp)
# Virtual endstop
def setup_pin(self, pin_type, pin_params):
if pin_type != "endstop" or pin_params["pin"] != "z_virtual_endstop":
raise pins.error("Probe virtual endstop only useful as endstop pin")
if pin_params["invert"] or pin_params["pullup"]:
raise pins.error("Can not pullup/invert probe virtual endstop")
return self.mcu_probe
# Probe interface
def multi_probe_begin(self):
self.printer.send_event("beacon:probing_move_begin")
self._start_streaming()
def multi_probe_end(self):
self._stop_streaming()
self.printer.send_event("beacon:probing_move_end")
def get_offsets(self):
if self._current_probe == "contact":
return 0, 0, 0
else:
return self.x_offset, self.y_offset, self.trigger_distance
def get_lift_speed(self, gcmd=None):
if gcmd is not None:
return gcmd.get_float("LIFT_SPEED", self.lift_speed, above=0.0)
return self.lift_speed
def run_probe(self, gcmd):
method = gcmd.get("PROBE_METHOD", self.default_probe_method).lower()
self._current_probe = method
if method == "proximity":
return self._run_probe_proximity(gcmd)
elif method == "contact":
self.printer.send_event("beacon:probing_move_begin")
self._start_streaming()
try:
return self._run_probe_contact(gcmd)
finally:
self._stop_streaming()
self.printer.send_event("beacon:probing_move_end")
else:
raise gcmd.error("Invalid PROBE_METHOD, valid choices: proximity, contact")
def _move_to_probing_height(self, speed):
target = self.trigger_distance
top = target + self.backlash_comp
cur_z = self.toolhead.get_position()[2]
if cur_z < top:
self.toolhead.manual_move([None, None, top], speed)
self.toolhead.manual_move([None, None, target], speed)
self.toolhead.wait_moves()
def _run_probe_proximity(self, gcmd):
if self.model is None:
raise self.printer.command_error("No Beacon model loaded")
speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.0)
allow_faulty = gcmd.get_int("ALLOW_FAULTY_COORDINATE", 0) != 0
toolhead = self.printer.lookup_object("toolhead")
curtime = self.reactor.monotonic()
if "z" not in toolhead.get_status(curtime)["homed_axes"]:
raise self.printer.command_error("Must home before probe")
self.printer.send_event("beacon:probing_move_begin")
self._start_streaming()
try:
return self._probe(speed, allow_faulty=allow_faulty)
finally:
self._stop_streaming()
self.printer.send_event("beacon:probing_move_end")
def _probing_move_to_probing_height(self, speed):
curtime = self.reactor.monotonic()
status = self.toolhead.get_kinematics().get_status(curtime)
pos = self.toolhead.get_position()
pos[2] = status["axis_minimum"][2]
try:
self.phoming.probing_move(self.mcu_probe, pos, speed)
self._sample_printtime_sync(self.z_settling_time)
except self.printer.command_error as e:
if self.printer.is_shutdown():
reason = "Probing failed due to printer shutdown"
else:
reason = str(e)
if "Timeout during probing move" in reason:
reason += probe.HINT_TIMEOUT
raise self.printer.command_error(reason)
def _probe(self, speed, num_samples=10, allow_faulty=False):
target = self.trigger_distance
tdt = self.trigger_dive_threshold
(dist, samples) = self._sample(5, num_samples)
x, y = samples[0]["pos"][0:2]
if self._is_faulty_coordinate(x, y, True):
msg = "Probing within a faulty area"
if not allow_faulty:
raise self.printer.command_error(msg)
else:
self.gcode.respond_raw("!! " + msg + "\n")
if dist > target + tdt:
# If we are above the dive threshold right now, we'll need to
# do probing move and then re-measure
self._probing_move_to_probing_height(speed)
(dist, samples) = self._sample(self.z_settling_time, num_samples)
elif math.isinf(dist) and dist < 0:
# We were below the valid range of the model
msg = "Attempted to probe with Beacon below calibrated model range"
raise self.printer.command_error(msg)
elif self.toolhead.get_position()[2] < target - tdt:
# We are below the probing target height, we'll move to the
# correct height and take a new sample.
self._move_to_probing_height(speed)
(dist, samples) = self._sample(self.z_settling_time, num_samples)
pos = samples[0]["pos"]
self.gcode.respond_info(
"probe at %.3f,%.3f,%.3f is z=%.6f" % (pos[0], pos[1], pos[2], dist)
)
return [pos[0], pos[1], pos[2] + target - dist]
def _run_probe_contact(self, gcmd):
self.toolhead.wait_moves()
speed = gcmd.get_float(
"PROBE_SPEED", self.autocal_speed, above=0.0, maxval=self.autocal_max_speed
)
lift_speed = self.get_lift_speed(gcmd)
sample_count = gcmd.get_int("SAMPLES", self.autocal_sample_count, minval=1)
retract_dist = gcmd.get_float(
"SAMPLE_RETRACT_DIST", self.autocal_retract_dist, minval=1
)
tolerance = gcmd.get_float(
"SAMPLES_TOLERANCE", self.autocal_tolerance, above=0.0
)
max_retries = gcmd.get_int(
"SAMPLES_TOLERANCE_RETRIES", self.autocal_max_retries, minval=0
)
samples_result = gcmd.get("SAMPLES_RESULT", "mean")
drop_n = gcmd.get_int("SAMPLES_DROP", 0, minval=0)
retries = 0
samples = []
posxy = self.toolhead.get_position()[:2]
self.mcu_contact_probe.activate_gcode.run_gcode_from_command()
try:
while len(samples) < sample_count:
pos = self._probe_contact(speed)
self.toolhead.manual_move(posxy + [pos[2] + retract_dist], lift_speed)
if drop_n > 0:
drop_n -= 1
continue
samples.append(pos[2])
spread = max(samples) - min(samples)
if spread > tolerance:
if retries >= max_retries:
raise gcmd.error("Probe samples exceed sample_tolerance")
gcmd.respond_info("Probe samples exceed tolerance. Retrying...")
samples = []
retries += 1
if samples_result == "median":
return posxy + [median(samples)]
else:
return posxy + [float(np.mean(samples))]
finally:
self.mcu_contact_probe.deactivate_gcode.run_gcode_from_command()
def _probe_contact(self, speed, num_samples=10, allow_faulty=False):
self.toolhead.get_last_move_time()
self._sample_async()
start_pos = self.toolhead.get_position()
hmove = HomingMove(self.printer, [(self.mcu_contact_probe, "contact")])
pos = start_pos[:]
pos[2] = -2
try:
epos = hmove.homing_move(pos, speed, probe_pos=True)[:3]
except self.printer.command_error as e:
if self.printer.is_shutdown():
reason = "Probing failed due to printer shutdown"
else:
reason = str(e)
if "Timeout during probing move" in reason:
reason += probe.HINT_TIMEOUT
raise self.printer.command_error(reason)
epos[2] += self.get_z_compensation_value(pos)
self.gcode.respond_info(
"probe at %.3f,%.3f is z=%.6f" % (epos[0], epos[1], epos[2])
)
return epos[:3]
# Accelerometer interface
def start_internal_client(self):
if not self.accel_helper:
msg = "This Beacon has no accelerometer"
raise self.printer.command_error(msg)
return self.accel_helper.start_internal_client()
# Calibration routines
def _start_calibration(self, gcmd):
allow_faulty = gcmd.get_int("ALLOW_FAULTY_COORDINATE", 0) != 0
nozzle_z = gcmd.get_float("NOZZLE_Z", self.cal_nozzle_z)
if gcmd.get("SKIP_MANUAL_PROBE", None) is not None:
kin = self.toolhead.get_kinematics()
kin_spos = {
s.get_name(): s.get_commanded_position() for s in kin.get_steppers()
}
kin_pos = kin.calc_position(kin_spos)
if self._is_faulty_coordinate(kin_pos[0], kin_pos[1]):
msg = "Calibrating within a faulty area"
if not allow_faulty:
raise gcmd.error(msg)
else:
gcmd.respond_raw("!! " + msg + "\n")
self._calibrate(gcmd, kin_pos, nozzle_z, False)
else:
curtime = self.printer.get_reactor().monotonic()
kin_status = self.toolhead.get_status(curtime)
if "xy" not in kin_status["homed_axes"]:
raise self.printer.command_error(
"Must home X and Y " "before calibration"
)
kin_pos = self.toolhead.get_position()
if self._is_faulty_coordinate(kin_pos[0], kin_pos[1]):
msg = "Calibrating within a faulty area"
if not allow_faulty:
raise gcmd.error(msg)
else:
gcmd.respond_raw("!! " + msg + "\n")
forced_z = False
if "z" not in kin_status["homed_axes"]:
self.toolhead.get_last_move_time()
pos = self.toolhead.get_position()
pos[2] = (
kin_status["axis_maximum"][2]
- 2.0
- gcmd.get_float("CEIL", self.cal_ceil)
)
self.toolhead.set_position(pos, homing_axes=[2])
forced_z = True
def cb(kin_pos):
return self._calibrate(gcmd, kin_pos, nozzle_z, forced_z)
manual_probe.ManualProbeHelper(self.printer, gcmd, cb)
def _calibrate(self, gcmd, kin_pos, cal_nozzle_z, forced_z, is_auto=False):
if kin_pos is None:
if forced_z:
kin = self.toolhead.get_kinematics()
if hasattr(kin, "note_z_not_homed"):
kin.note_z_not_homed()
return
gcmd.respond_info("Beacon calibration starting")
cal_floor = gcmd.get_float("FLOOR", self.cal_floor)
cal_ceil = gcmd.get_float("CEIL", self.cal_ceil)
cal_speed = gcmd.get_float("DESCEND_SPEED", self.cal_speed)
move_speed = gcmd.get_float("MOVE_SPEED", self.cal_move_speed)
model_name = gcmd.get("MODEL_NAME", "default")
toolhead = self.toolhead
toolhead.wait_moves()
# Move coordinate system to nozzle location
self.toolhead.get_last_move_time()
curpos = toolhead.get_position()
curpos[2] = cal_nozzle_z
toolhead.set_position(curpos)
# Move over to probe coordinate and pull out backlash
curpos[2] = cal_ceil + self.backlash_comp
toolhead.manual_move(curpos, move_speed) # Up
curpos[0] -= self.x_offset
curpos[1] -= self.y_offset
toolhead.manual_move(curpos, move_speed) # Over
curpos[2] = cal_ceil
toolhead.manual_move(curpos, move_speed) # Down
toolhead.wait_moves()
samples = []
def cb(sample):
samples.append(sample)
# Descend while sampling
toolhead.flush_step_generation()
try:
self.printer.send_event("beacon:probing_move_begin")
self._start_streaming()
self._sample_printtime_sync(50)
with self.streaming_session(cb):
self._sample_printtime_sync(50)
toolhead.dwell(0.250)
curpos[2] = cal_floor
toolhead.manual_move(curpos, cal_speed)
toolhead.flush_step_generation()
self._sample_printtime_sync(50)
finally:
self._stop_streaming()
self.printer.send_event("beacon:probing_move_end")
# Fit the sampled data
z_offset = [s["pos"][2] for s in samples]
freq = [s["freq"] for s in samples]
temp = [s["temp"] for s in samples]
inv_freq = [1 / f for f in freq]
poly = Polynomial.fit(inv_freq, z_offset, 9)
temp_median = median(temp)
self.model = BeaconModel(
model_name, self, poly, temp_median, min(z_offset), max(z_offset)
)
self.models[self.model.name] = self.model
self.model.save(self, not is_auto)
self._apply_threshold()
# Dump calibration curve
fn = "/tmp/beacon-calibrate-" + time.strftime("%Y%m%d_%H%M%S") + ".csv"
with open(fn, "w") as f:
f.write("freq,z,temp\n")
for i in range(len(freq)):
f.write("%.5f,%.5f,%.3f\n" % (freq[i], z_offset[i], temp[i]))
gcmd.respond_info(
"Beacon calibrated at %.3f,%.3f from "
"%.3f to %.3f, speed %.2f mm/s, temp %.2fC"
% (curpos[0], curpos[1], cal_floor, cal_ceil, cal_speed, temp_median)
)
self.printer.lookup_object("toolhead").wait_moves()
# Internal
def _update_thresholds(self, moving_up=False):
self.trigger_freq = self.dist_to_freq(self.trigger_distance, self.last_temp)
self.untrigger_freq = self.trigger_freq * (1 - self.trigger_hysteresis)
def _apply_threshold(self, moving_up=False):
self._update_thresholds()
trigger_c = int(self.freq_to_count(self.trigger_freq))
untrigger_c = int(self.freq_to_count(self.untrigger_freq))
if self.beacon_set_threshold is not None:
self.beacon_set_threshold.send([trigger_c, untrigger_c])
def _register_model(self, name, model):
if name in self.models:
raise self.printer.config_error(
"Multiple Beacon models with same" "name '%s'" % (name,)
)
self.models[name] = model
def _is_faulty_coordinate(self, x, y, add_offsets=False):
if not self.mesh_helper:
return False
return self.mesh_helper._is_faulty_coordinate(x, y, add_offsets)
def _handle_beacon_status(self, params):
if self.mcu_temp is not None:
self.last_mcu_temp = self.mcu_temp.compensate(
self, params["mcu_temp"], params["supply_voltage"]
)
if self.thermistor is not None:
self.temp = self.thermistor.calc_temp(
params["coil_temp"] / self.temp_smooth_count * self.inv_adc_max
)
self.last_temp = self.temp
def _handle_beacon_contact(self, params):
self.last_contact_msg = params
def _hook_probing_gcode(self, config, module, cmd):
if not config.has_section(module):
return
section = config.getsection(module)
mod = self.printer.load_object(section, module)
if mod is None:
return
orig = self.gcode.register_command(cmd, None)
def cb(gcmd):
self._current_probe = gcmd.get(
"PROBE_METHOD", self.default_probe_method
).lower()
return orig(gcmd)
self.gcode.register_command(cmd, cb)
# Streaming mode
def _check_hardware(self, sample):
if not self.hardware_failure:
msg = None
if sample["data"] == 0xFFFFFFF:
msg = "coil is shorted or not connected"
elif self.fmin is not None and sample["freq"] > 1.35 * self.fmin:
msg = "coil expected max frequency exceeded"
if msg:
msg = "Beacon hardware issue: " + msg
self.hardware_failure = msg
logging.error(msg)
if self._stream_en:
self.printer.invoke_shutdown(msg)
else:
self.gcode.respond_raw("!! " + msg + "\n")
elif self._stream_en:
self.printer.invoke_shutdown(self.hardware_failure)
def _clock32_to_time(self, clock):
clock64 = self._mcu.clock32_to_clock64(clock)
return self._mcu.clock_to_print_time(clock64)
def _start_streaming(self):
if self._stream_en == 0 and self.beacon_stream_cmd is not None:
self.beacon_stream_cmd.send([1])
curtime = self.reactor.monotonic()
self.reactor.update_timer(
self._stream_timeout_timer, curtime + STREAM_TIMEOUT
)
self._stream_en += 1
self._data_filter.reset()
self._stream_flush()
def _stop_streaming(self):
if self.printer.is_shutdown():
self.force_stop_streaming()
return
self._stream_en -= 1
if self._stream_en == 0:
self.reactor.update_timer(self._stream_timeout_timer, self.reactor.NEVER)
if self.beacon_stream_cmd is not None:
self.beacon_stream_cmd.send([0])
self._stream_flush()
def force_stop_streaming(self):
try:
self.reactor.update_timer(self._stream_timeout_timer, self.reactor.NEVER)
finally:
if self.beacon_stream_cmd is not None:
self.beacon_stream_cmd.send([0])
self._stream_flush()
def _stream_timeout(self, eventtime):
if self._stream_flush():
return eventtime + STREAM_TIMEOUT
if not self._stream_en:
return self.reactor.NEVER
if not self.printer.is_shutdown():
msg = "Beacon sensor not receiving data"
logging.error(msg)
self.printer.invoke_shutdown(msg)
return self.reactor.NEVER
def request_stream_latency(self, latency):
next_key = 0
if self._stream_latency_requests:
next_key = max(self._stream_latency_requests.keys()) + 1
new_limit = STREAM_BUFFER_LIMIT_DEFAULT
self._stream_latency_requests[next_key] = latency
min_requested = min(self._stream_latency_requests.values())
if min_requested < new_limit:
new_limit = min_requested
if new_limit < 1:
new_limit = 1
self._stream_buffer_limit_new = new_limit
return next_key
def drop_stream_latency_request(self, key):
self._stream_latency_requests.pop(key, None)
new_limit = STREAM_BUFFER_LIMIT_DEFAULT
if self._stream_latency_requests:
min_requested = min(self._stream_latency_requests.values())
if min_requested < new_limit:
new_limit = min_requested
if new_limit < 1:
new_limit = 1
self._stream_buffer_limit_new = new_limit
def streaming_session(self, callback, completion_callback=None, latency=None):
return StreamingHelper(self, callback, completion_callback, latency)
def _stream_flush_message(self, msg):
last = None
for sample in msg:
(clock, data) = sample
temp = self.last_temp
if self.model_temp is not None and not (-40 < temp < 180):
msg = (
"Beacon temperature sensor faulty(read %.2f C),"
" disabling temperature compensation" % (temp,)
)
logging.error(msg)
self.gcode.respond_raw("!! " + msg + "\n")
self.model_temp = None
if temp:
self.measured_min = min(self.measured_min, temp)
self.measured_max = max(self.measured_max, temp)
clock = self._mcu.clock32_to_clock64(clock)
time = self._mcu.clock_to_print_time(clock)
self._data_filter.update(time, data)
data_smooth = self._data_filter.value()
freq = self.count_to_freq(data_smooth)
dist = self.freq_to_dist(freq, temp)
pos, vel = self._get_trapq_position(time)
if pos is not None:
if dist is not None:
dist -= self.get_z_compensation_value(pos)
last = sample = {
"temp": temp,
"clock": clock,
"time": time,
"data": data,
"data_smooth": data_smooth,
"freq": freq,
"dist": dist,
}
if pos is not None:
sample["pos"] = pos
sample["vel"] = vel
self._check_hardware(sample)
if len(self._stream_callbacks) > 0:
for cb in list(self._stream_callbacks.values()):
cb(sample)
if last is not None:
last = last.copy()
dist = last["dist"]
if dist is None or np.isinf(dist) or np.isnan(dist):
del last["dist"]
self.last_received_sample = last
def _stream_flush(self):
self._stream_flush_event.clear()
updated_timer = False
while True:
try:
samples = self._stream_samples_queue.get_nowait()
updated_timer = False
for sample in samples:
if not updated_timer:
curtime = self.reactor.monotonic()
self.reactor.update_timer(
self._stream_timeout_timer, curtime + STREAM_TIMEOUT
)
updated_timer = True
self._stream_flush_message(sample)
except queue.Empty:
return updated_timer
def _stream_flush_schedule(self):
force = self._stream_en == 0 # When streaming is disabled, let all through
if self._stream_buffer_limit_new != self._stream_buffer_limit:
force = True
self._stream_buffer_limit = self._stream_buffer_limit_new
if not force and self._stream_buffer_count < self._stream_buffer_limit:
return
self._stream_samples_queue.put_nowait(self._stream_buffer)
self._stream_buffer = []
self._stream_buffer_count = 0
if self._stream_flush_event.is_set():
return
self._stream_flush_event.set()
self.reactor.register_async_callback(lambda e: self._stream_flush())
def _handle_beacon_data(self, params):