-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprobe_eddy_ng.py
3513 lines (3018 loc) · 130 KB
/
probe_eddy_ng.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
# EDDY-ng
#
# Copyright (C) 2025 Vladimir Vukicevic <vladimir@pobox.com>
# Copyright (C) 2020-2024 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os, logging, math, bisect, re
import numpy as np
import traceback
import pickle, base64
from itertools import combinations
from dataclasses import dataclass, field
from typing import (
Dict,
List,
Optional,
Tuple,
final,
ClassVar,
)
try:
from klippy import mcu, pins
from klippy.printer import Printer
from klippy.configfile import ConfigWrapper
from klippy.configfile import error as configerror
from klippy.gcode import GCodeCommand
from klippy.toolhead import ToolHead
except:
import mcu
import pins
from klippy import Printer
from configfile import ConfigWrapper
from configfile import error as configerror
from gcode import GCodeCommand
from toolhead import ToolHead
from .homing import HomingMove
from . import ldc1612_ng, probe, manual_probe
try:
import plotly # noqa
HAS_PLOTLY = True
except:
HAS_PLOTLY = False
try:
import scipy # noqa
HAS_SCIPY = True
except:
HAS_SCIPY = False
# In this file, a couple of conventions are used (for sanity).
# Variables are named according to:
# - "height" is always a physical height as detected by the probe in mm
# - "z" is always a z axis position (which may or may not match height)
# - "freq" is always a frequency value (float)
# - "freqval" is always an encoded frequency value, as communicated to/from the sensor (int)
# There are three distinct operations/phases. Homing Z via the virtual
# endstop is the only operation that can happen while Z is not homed:
#
# 1. Homing Z using a virtual probe endstop. This is largely handled by
# ProbeEddyEndstopWrapper. It sets up the sensor to trigger when a certain
# frequency is crossed, and then lets a HomingMove continue that moves the
# toolhead down. When that frequency is hit, it triggers, and Klipper stops
# the toolhead from moving down. The time point when it triggers is set as
# the z=trigger_height (which is home_trigger_height in the configurable
# params). Z should be accurate enough at this point. This operation can be run
# when the bed/toolhead are cold or hot.
#
# Once Z is homed, two additional operations become available:
#
# 2. Probing at either a single point or multiple points. This is used for
# Quad Gantry Leveling, Bed Mesh, and other similar operations. This is
# largely handled by the ProbeEddyScannigProbe class -- one is returned
# from the ProbeEddy `probe` object when `start_probe_session` is called.
# For Eddy probes, there is no reason to move the toolhead up and down at
# each probe point: the measured distance between the sensor and the build
# plate can be read directly. This class starts gathering sample data when
# the session starts and records the times when there's a sample that we
# care about, along with the toolhead position, whenever a caller calls
# `run_probe`. If this is a `rapid_scan` scan, then a callback is attached
# to the current motion so that we can save the movement's time and position
# without actually waiting for it. If it's in normal mode, then the toolhead
# will pause at each position. In both cases, the results are obtained by
# calling `pull_probed_results`, which returns an array of results at each
# point that `run_probe` was called for, in order.
#
# PROBE_STATIC HOME_Z=1 can be used to set the toolhead's Z position
# based on the current height reading from the probe while the toolhead is
# static, leading to a more accurate result than a regular homing operation
# (which involves movement).
#
# 3. A "tap" to fine-tune the Z offset. This should be run with the bed at print
# temperature and soaked for a bit. The nozzle should also be warm but not so
# hot that filament risks oozing out. The nozzle also must be clean. 150C
# is a good temperature to both clean and tap at.
#
# This operation will identify the exact position of the Z axis
# when the nozzle touches the bed, which means that a precise Z offset
# can be set.
#
# The eddy current response and readings depend on temperature of both the target
# (bed) and the sensor (coil). EddyNG does not do any temperature compensation. Instead
# it relies on the "tap" operation to get an accurate reference point for z=0 regardless
# of temperatures. Empirically, small offsets from a reference point can still be read
# accurately from the sensor, even if the absolute value is incorrect at temperature.
# For example, taking sensor readings at Z=2 when perfectly homed via tap may read as
# 1.9 due to temperatures, which is not correct. However, raising the toolhead to Z=2.1
# will raise the sensor reading to 2.0; likewise, lowering the toolhead to Z=1.9 will
# lower the sensor reading to 1.8.
#
# Care in macros should be taken to not invalidate the Z offset set after a tap
# by relying on absolute sensor readings.
#
@dataclass
class ProbeEddyParams:
# The speed at which to perform normal homing operations
probe_speed: float = 5.0
# The speed at which to lift the toolhead during probing operations
lift_speed: float = 10.0
# The speed at which to move in the xy plane (typically only for calibration)
move_speed: float = 50.0
# The height at which the virtual endstop should trigger. A value
# between 1.0 and 3.0 is recommended, with 2.0 or 2.5 being good
# choices.
home_trigger_height: float = 2.0
# The amount higher the probe needs to detect the toolhead is at in order to
# allow homing to begin. For example, if the trigger height is 2.0, and the
# start offset is 1.5, then homing will abort if the sensor detects the
# toolhead is below 3.5mm off the print bed.
home_trigger_safe_start_offset: float = 1.0
# The amount of time that must elapse from the start of probing until the
# safe start position is crossed. This is to make sure there are some values
# that are above the safe position before it's crossed, to ensure that homing
# doesn't begin with the toolhead too low.
home_trigger_safe_time_offset: float = 0.100
# The maximum z value to calibrate from. 15.0 is fine as a default, calibrating
# at higher values is not needed. Calibration will start with the first
# valid height.
calibration_z_max: float = 15.0
# The "drive current" for the LDC1612 sensor. This value is typically
# sensor specific and depends on the coil design and the operating distance.
# A good starting value for BTT Eddy is 15. A good value can be obtained
# by placing the toolhead ~10mm above the bed and running LDC_NG_CALIBRATE_
# DRIVE_CURRENT.
reg_drive_current: int = 0
# The drive current to use for tap operations. If not set, the `reg_drive_current`
# value will be used. Tapping involves reading values much closer to the print
# bed than basic homing, and may require a different, typically higher,
# drive current. For example, BTT Eddy performs best with this value at 16.
# Note that the sensor needs to be calibrated for both drive currents separately.
# Pass the DRIVE_CURRENT argument to EDDY_NG_CALIBRATE.
tap_drive_current: int = 0
# The Z position at which to start a tap-home operation. This height may
# need to be fine-tuned to ensure that the sensor can provide readings across the
# entire tap range (i.e. from this value down to tap_target_z), which in turn
# will depend on the tap_drive_current. When the tap_drive_current is
# increased, the sensor may not be able to read values at higher heights.
# For example, BTT Eddy typically cannot work with heights above 3.5mm with
# a drive current of 16.
#
# Note that all of these values are in terms of offsets from the nozzle
# to the toolhead. The actual sensor coil is mounted higher -- but must be placed
# between 2.5 and 3mm above the nozzle, ideally around 2.75mm. If there are
# amplitude errors, try raising or lowering the sensor coil slightly.
tap_start_z: float = 3.0
# The target Z position for a tap operation. This is the lowest position that
# the toolhead may travel to in case of a failed tap. Do not set this very low,
# as it will cause your toolhead to try to push through your build plate in
# the case of a failed tap. A value like -0.250 is no worse than moving the
# nozzle down one or two notches too far when doing manual Z adjustment.
tap_target_z: float = -0.250
# the tap mode to use. 'wma' is a derivative of weighted moving average,
# 'butter' is a butterworth filter
tap_mode: str = "butter"
# The threshold at which to detect a tap. This value is raw sensor value
# specific. A good value can be obtained by running [....] and examining
# the graph. See [calibration docs coming soon].
#
# The meaning of this depends on tap_mode, and the value will be different
# if a different tap_mode is used. You can experiment to arrive at this
# value. Typically, a lower value will make tap detection more sensitive,
# but might lead to false positives (too early detections). A higher value
# may cause the detection to wait too long or miss a tap entirely.
# You can pass a THRESHOLD parameter to the TAP command to experiment to
# find a good value.
#
# You may also need to use different thresholds for different build plates.
# Note that the default value of this threshold depends on the tap_mode.
tap_threshold: float = 250.0
# The speed at which a tap operation should be performed at. This shouldn't
# be much slower than 3.0, but you can experiment with lower or higher values.
# Don't go too high though, because Klipper needs some small amount of time
# to react to a tap trigger, and the toolhead will still be moving at this
# speed even past the tap point. So, consider any speed you'd feel comfortable
# triggering a toolhead move to tap_target_z at.
tap_speed: float = 3.0
# A static additional amount to add to the computed tap Z offset. Use this if
# the computed tap is a bit too high or too low for your taste. Positive
# values will raise the toolhead, negative values will lower it.
tap_adjust_z: float = 0.0
# The number of times to do a tap, averaging the results.
tap_samples: int = 3
# The maximum number of tap samples.
tap_max_samples: int = 5
# The maximum standard deviation for any 3 samples to be considered valid.
tap_samples_stddev: float = 0.020
# When probing multiple points (not rapid scan), how long to sample for at each probe point,
# after a scan_sample_time_delay delay. The total dwell time at each probe point is
# scan_sample_time + scan_sample_time_delay.
scan_sample_time: float = 0.100
# When probing multiple points (not rapid scan), how long to delay at each probe point
# before the scan_sample_time kicks in.
scan_sample_time_delay: float = 0.050
# number of points to save for calibration
calibration_points: int = 150
# configuration for butterworth filter
tap_butter_lowcut: float = 5.0
tap_butter_highcut: float = 25.0
tap_butter_order: int = 2
# Probe position relative to toolhead
x_offset: float = 0.0
y_offset: float = 0.0
# remove some safety checks, largely for testing/development
allow_unsafe: bool = False
# whether to write the tap plot for the last tap
write_tap_plot: bool = True
# whether to write the tap plot for every tap
write_every_tap_plot: bool = False
tap_trigger_safe_start_height: float = 1.5
_config_reg_drive_current: int = 0
_config_tap_drive_current: int = 0
_warning_msgs: List[str] = field(default_factory=list)
@staticmethod
def str_to_floatlist(s):
if s is None:
return None
try:
return [float(v) for v in re.split(r"\s*,\s*|\s+", s)]
except:
raise configerror(f"Can't parse '{s}' as list of floats")
def is_default_butter_config(self):
return (
self.tap_butter_lowcut == 5.0
and self.tap_butter_highcut == 25.0
and self.tap_butter_order == 2
)
def load_from_config(self, config: ConfigWrapper):
mode_choices = ["wma", "butter"]
self.probe_speed = config.getfloat(
"probe_speed", self.probe_speed, above=0.0
)
self.lift_speed = config.getfloat(
"lift_speed", self.lift_speed, above=0.0
)
self.move_speed = config.getfloat(
"move_speed", self.move_speed, above=0.0
)
self.home_trigger_height = config.getfloat(
"home_trigger_height", self.home_trigger_height, minval=1.0
)
self.home_trigger_safe_start_offset = config.getfloat(
"home_trigger_safe_start_offset",
self.home_trigger_safe_start_offset,
minval=0.5,
)
self.calibration_z_max = config.getfloat(
"calibration_z_max", self.calibration_z_max, above=0.0
)
# "saved_" is the values that save_config will write
saved_reg_drive_current = config.getint("saved_reg_drive_current", 0)
saved_tap_drive_current = config.getint("saved_tap_drive_current", 0)
reg_drive_current = self._config_reg_drive_current = config.getint(
"reg_drive_current", 0, minval=0, maxval=31
)
tap_drive_current = self._config_tap_drive_current = config.getint(
"tap_drive_current", 0, minval=0, maxval=31
)
logging.info(f"saved {saved_reg_drive_current} reg {reg_drive_current}")
if (
saved_reg_drive_current != 0
and reg_drive_current != 0
and reg_drive_current != saved_reg_drive_current
):
printer = config.get_printer()
msg = f"probe_eddy_ng has reg_drive_current specified in config and in saved variables. Config value ({reg_drive_current}) is taking precedence. Remove one of these to remove this warning."
logging.warning(msg)
self._warning_msgs.append(msg)
if (
saved_tap_drive_current != 0
and tap_drive_current != 0
and tap_drive_current != saved_tap_drive_current
):
printer = config.get_printer()
msg = f"probe_eddy_ng has tap_drive_current specified in config and in saved variables. Config value ({tap_drive_current}) is taking precedence. Remove one of these to remove this warning."
logging.warning(msg)
self._warning_msgs.append(msg)
# the config value overrides a saved value, if any
if reg_drive_current == 0:
reg_drive_current = saved_reg_drive_current
if tap_drive_current == 0:
tap_drive_current = saved_tap_drive_current
logging.info(f"saved reg {reg_drive_current} set")
self.reg_drive_current = reg_drive_current
self.tap_drive_current = tap_drive_current
self.tap_start_z = config.getfloat(
"tap_start_z", self.tap_start_z, above=0.0
)
self.tap_target_z = config.getfloat("tap_target_z", self.tap_target_z)
self.tap_speed = config.getfloat("tap_speed", self.tap_speed, above=0.0)
self.tap_adjust_z = config.getfloat("tap_adjust_z", self.tap_adjust_z)
self.calibration_points = config.getint(
"calibration_points", self.calibration_points
)
self.tap_mode = config.getchoice(
"tap_mode", mode_choices, self.tap_mode
)
default_tap_threshold = 1000.0 # for wma
if self.tap_mode == "butter":
default_tap_threshold = 250.0
self.tap_threshold = config.getfloat(
"tap_threshold", default_tap_threshold
)
# for 'butter'
self.tap_butter_lowcut = config.getfloat(
"tap_butter_lowcut", self.tap_butter_lowcut, above=0.0
)
self.tap_butter_highcut = config.getfloat(
"tap_butter_highcut",
self.tap_butter_highcut,
above=self.tap_butter_lowcut,
)
self.tap_butter_order = config.getint(
"tap_butter_order", self.tap_butter_order, minval=1
)
self.tap_samples = config.getint(
"tap_samples", self.tap_samples, minval=1
)
self.tap_max_samples = config.getint(
"tap_max_samples", self.tap_max_samples, minval=self.tap_samples
)
self.tap_samples_stddev = config.getfloat(
"tap_samples_stddev", self.tap_samples_stddev, above=0.0
)
self.tap_trigger_safe_start_height = config.getfloat(
"tap_trigger_safe_start_height",
-1.0,
above=0.0,
)
if self.tap_trigger_safe_start_height == -1.0: # sentinel
self.tap_trigger_safe_start_height = self.home_trigger_height / 2.0
self.allow_unsafe = config.getboolean("allow_unsafe", False)
self.write_tap_plot = config.getboolean("write_tap_plot", True)
self.write_every_tap_plot = config.getboolean(
"write_every_tap_plot", True
)
self.x_offset = config.getfloat("x_offset", self.x_offset)
self.y_offset = config.getfloat("y_offset", self.y_offset)
self.validate(config)
def validate(self, config: ConfigWrapper = None):
printer = config.get_printer()
req_cal_z_max = (
self.home_trigger_safe_start_offset + self.home_trigger_height + 1.0
)
if self.calibration_z_max < req_cal_z_max:
raise printer.config_error(
f"calibration_z_max must be at least home_trigger_safe_start_offset+home_trigger_height+1.0 ({self.home_trigger_safe_start_offset:.3f}+{self.home_trigger_height:.3f}+1.0={req_cal_z_max:.3f})"
)
if (
self.x_offset == 0.0
and self.y_offset == 0.0
and not self.allow_unsafe
):
raise printer.config_error(
"ProbeEddy: x_offset and y_offset are both 0.0; is the sensor really mounted at the nozzle?"
)
if self.home_trigger_height <= self.tap_trigger_safe_start_height:
raise printer.config_error(
"ProbeEddy: home_trigger_height must be greater than tap_trigger_safe_start_height"
)
need_scipy = False
if self.tap_mode == "butter" and not self.is_default_butter_config():
need_scipy = True
if need_scipy and not HAS_SCIPY:
raise printer.config_error(
"ProbeEddy: butter mode with custom filter parameters requires scipy, which is not available; please install scipy, use the defaults, or use wma mode"
)
@dataclass
class ProbeEddyProbeResult:
samples: List[float]
mean: float = 0.0
median: float = 0.0
min_value: float = 0.0
max_value: float = 0.0
tstart: float = 0.0
tend: float = 0.0
errors: int = 0
USE_MEAN_FOR_VALUE: ClassVar[bool] = False
@property
def valid(self):
return len(self.samples) > 0
@property
def value(self):
return self.mean if self.USE_MEAN_FOR_VALUE else self.median
@property
def stddev(self):
stddev_sum = np.sum([(s - self.value) ** 2.0 for s in self.samples])
return (stddev_sum / len(self.samples)) ** 0.5
def __format__(self, spec):
if spec == "v":
return f"{self.value:.3f}"
if self.USE_MEAN_FOR_VALUE:
value = f"{self.mean:.3f}"
extra = f"med={self.median:.3f}"
else:
value = f"{self.median:.3f}"
extra = f"avg={self.mean:.3f}"
return f"{value} ({extra}, {self.min_value:.3f} to {self.max_value:.3f}, [{self.stddev:.3f}])"
@final
class ProbeEddy:
def __init__(self, config: ConfigWrapper):
logging.info("Hello from ProbeEddyNG")
self._printer: Printer = config.get_printer()
self._gcode = self._printer.lookup_object("gcode")
self._full_name = config.get_name()
self._name = self._full_name.split()[-1]
sensors = {
"ldc1612": ldc1612_ng.LDC1612_ng,
"btt_eddy": ldc1612_ng.LDC1612_ng,
"cartographer": ldc1612_ng.LDC1612_ng,
"mellow_fly": ldc1612_ng.LDC1612_ng,
}
sensor_type = config.getchoice("sensor_type", {s: s for s in sensors})
self._sensor_type = sensor_type
self._sensor = sensors[sensor_type](config)
self._mcu = self._sensor.get_mcu()
self._toolhead: ToolHead = None # filled in _handle_connect
self.params = ProbeEddyParams()
self.params.load_from_config(config)
if self.params.reg_drive_current == 0:
logging.info(f" is zero, overriding {self._sensor._drive_current}")
# set as default
self.params.reg_drive_current = self._sensor._drive_current
# at what minimum physical height to start homing. It must be above the safe start position,
# because we need to move from the start through the safe start position
self._home_start_height = (
self.params.home_trigger_height
+ self.params.home_trigger_safe_start_offset
+ 1.0
)
# physical offsets between probe and nozzle
self.offset = {
"x": self.params.x_offset,
"y": self.params.y_offset,
}
# drive current to frequency map
self._dc_to_fmap: Dict[int, ProbeEddyFrequencyMap] = {}
version = config.getint("calibration_version", default=-1)
calibration_bad = False
if version == -1:
if config.get("calibrated_drive_currents", None) is not None:
calibration_bad = True
elif version != ProbeEddyFrequencyMap.calibration_version:
calibration_bad = True
if calibration_bad:
raise configerror(
"EDDYng calibration: calibration data invalid, please delete the calibrated_drive_currents, calibrated_version, and calibration data in your saved data in printer.cfg."
)
calibrated_drive_currents = config.getintlist(
"calibrated_drive_currents", []
)
for dc in calibrated_drive_currents:
self._dc_to_fmap[dc] = ProbeEddyFrequencyMap(self)
self._dc_to_fmap[dc].load_from_config(config, dc)
# Our virtual endstop wrapper -- used for homing.
self._endstop_wrapper = ProbeEddyEndstopWrapper(self)
# There can only be one active sampler at a time
self._sampler: ProbeEddySampler = None
self.save_samples_path = None
# This is a hack to keep the last set of data around so that we can
# do plots and things. It's updated after finish()
self._last_sampler_samples = None
self._last_sampler_raw_samples = None
self._last_sampler_memos = None
# This class emulates "PrinterProbe". We use some existing helpers to implement
# functionality like start_session
self._printer.add_object("probe", self)
# TODO: get rid of this
if hasattr(probe, "ProbeCommandHelper"):
self._cmd_helper = probe.ProbeCommandHelper(
config, self, self._endstop_wrapper.query_endstop
)
else:
self._cmd_helper = None
# when doing a scan, what's the offset between probe readings at the bed
# scan height and the accurate bed height, based on the last tap.
self._tap_offset = 0.0
self._last_probe_result = 0.0
# runtime configurable
self._tap_adjust_z = self.params.tap_adjust_z
# define our own commands
self._dummy_gcode_cmd = self._gcode.create_gcode_command("", "", {})
self.define_commands(self._gcode)
self._printer.register_event_handler(
"gcode:command_error", self._handle_command_error
)
self._printer.register_event_handler(
"klippy:connect", self._handle_connect
)
def _log_error(self, msg):
logging.error(f"{self._name}: {msg}")
self._gcode.respond_raw(f"!! {msg}\n")
def _log_warning(self, msg):
logging.warning(f"{self._name}: {msg}")
self._gcode.respond_raw(f"!! {msg}\n")
def _log_info(self, msg):
logging.info(f"{self._name}: {msg}")
self._gcode.respond_info(msg)
def _log_trace(self, msg):
logging.debug(f"{self._name}: {msg}")
def define_commands(self, gcode):
gcode.register_command(
"PROBE_EDDY_NG_STATUS", self.cmd_STATUS, self.cmd_STATUS_help
)
gcode.register_command(
"PROBE_EDDY_NG_CALIBRATE",
self.cmd_CALIBRATE,
self.cmd_CALIBRATE_help,
)
gcode.register_command(
"PROBE_EDDY_NG_SETUP",
self.cmd_SETUP,
self.cmd_SETUP_help,
)
gcode.register_command(
"PROBE_EDDY_NG_CLEAR_CALIBRATION",
self.cmd_CLEAR_CALIBRATION,
self.cmd_CLEAR_CALIBRATION_help,
)
gcode.register_command(
"PROBE_EDDY_NG_PROBE", self.cmd_PROBE, self.cmd_PROBE_help
)
gcode.register_command(
"PROBE_EDDY_NG_PROBE_STATIC",
self.cmd_PROBE_STATIC,
self.cmd_PROBE_STATIC_help,
)
gcode.register_command(
"PROBE_EDDY_NG_PROBE_ACCURACY",
self.cmd_PROBE_ACCURACY,
self.cmd_PROBE_ACCURACY_help,
)
gcode.register_command(
"PROBE_EDDY_NG_TAP", self.cmd_TAP, self.cmd_TAP_help
)
gcode.register_command(
"PROBE_EDDY_NG_SET_TAP_OFFSET",
self.cmd_SET_TAP_OFFSET,
"Set or clear the tap offset for the bed mesh scan and other probe operations",
)
gcode.register_command(
"PROBE_EDDY_NG_SET_TAP_ADJUST_Z",
self.cmd_SET_TAP_ADJUST_Z,
"Set the tap adjustment value",
)
gcode.register_command(
"PROBE_EDDY_NG_TEST_DRIVE_CURRENT",
self.cmd_TEST_DRIVE_CURRENT,
"Test a drive current.",
)
# some handy aliases while I'm debugging things to save my fingers
gcode.register_command(
"PES",
self.cmd_STATUS,
self.cmd_STATUS_help + " (alias for PROBE_EDDY_NG_STATUS)",
)
gcode.register_command(
"PEP",
self.cmd_PROBE,
self.cmd_PROBE_help + " (alias for PROBE_EDDY_NG_PROBE)",
)
gcode.register_command(
"PEPS",
self.cmd_PROBE_STATIC,
self.cmd_PROBE_STATIC_help
+ " (alias for PROBE_EDDY_NG_PROBE_STATIC)",
)
gcode.register_command(
"PETAP",
self.cmd_TAP,
self.cmd_TAP_help + " (alias for PROBE_EDDY_NG_TAP)",
)
def _handle_command_error(self, gcmd=None):
try:
if self._sampler is not None:
self._sampler.finish()
except:
logging.exception(
"EDDYng handle_command_error: sampler.finish() failed"
)
def _handle_connect(self):
self._toolhead = self._printer.lookup_object("toolhead")
for msg in self.params._warning_msgs:
self._log_warning(msg)
def current_drive_current(self) -> int:
return self._sensor.get_drive_current()
def map_for_drive_current(self, dc: int = None) -> ProbeEddyFrequencyMap:
if dc is None:
dc = self.current_drive_current()
if dc not in self._dc_to_fmap:
raise self._printer.command_error(
f"Drive current {dc} not calibrated"
)
return self._dc_to_fmap[dc]
# helpers to forward to the map
def height_to_freq(self, height: float, drive_current: int = None) -> float:
if drive_current is None:
drive_current = self.current_drive_current()
return self.map_for_drive_current(drive_current).height_to_freq(height)
def freq_to_height(self, freq: float, drive_current: int = None) -> float:
if drive_current is None:
drive_current = self.current_drive_current()
return self.map_for_drive_current(drive_current).freq_to_height(freq)
def calibrated(self, drive_current: int = None) -> bool:
if drive_current is None:
drive_current = self.current_drive_current()
return (
drive_current in self._dc_to_fmap
and self._dc_to_fmap[drive_current].calibrated()
)
def _z_homed(self):
curtime_r = self._printer.get_reactor().monotonic()
kin_status = (
self._printer.lookup_object("toolhead")
.get_kinematics()
.get_status(curtime_r)
)
return "z" in kin_status["homed_axes"]
def _xy_homed(self):
curtime_r = self._printer.get_reactor().monotonic()
kin_status = (
self._printer.lookup_object("toolhead")
.get_kinematics()
.get_status(curtime_r)
)
return (
"x" in kin_status["homed_axes"] and "y" in kin_status["homed_axes"]
)
def _z_hop(self, by=5.0):
if by < 0.0:
raise self._printer.command_error("Z hop must be positive")
toolhead: ToolHead = self._printer.lookup_object("toolhead")
curpos = toolhead.get_position()
curpos[2] = curpos[2] + by
toolhead.manual_move(curpos, self.params.probe_speed)
def _set_toolhead_position(self, pos, homing_axes):
# klipper changed homing_axes to be a "xyz" string instead
# of a tuple randomly on jan10 without support for the old
# syntax
func = self._toolhead.set_position
kind = type(func.__defaults__[0])
if kind is str:
# new
homing_axes_str = "".join(["xyz"[axis] for axis in homing_axes])
return self._toolhead.set_position(pos, homing_axes=homing_axes_str)
else:
# old
return self._toolhead.set_position(pos, homing_axes=homing_axes)
def _z_not_homed(self):
kin = self._toolhead.get_kinematics()
# klipper got rid of this
if hasattr(kin, "note_z_not_homed"):
kin.note_z_not_homed()
else:
try:
kin.clear_homing_state("z")
except TypeError:
raise self._printer.command_error(
"clear_homing_state failed: please update Klipper, your klipper is from the brief 5 day window where this was broken"
)
def save_config(self):
for _, fmap in self._dc_to_fmap.items():
fmap.save_calibration()
configfile = self._printer.lookup_object("configfile")
configfile.set(
self._full_name,
"calibrated_drive_currents",
str.join(", ", [str(dc) for dc in self._dc_to_fmap.keys()]),
)
configfile.set(
self._full_name,
"calibration_version",
str(ProbeEddyFrequencyMap.calibration_version),
)
if (
self.params._config_reg_drive_current == 0
or self.params.reg_drive_current
!= self.params._config_reg_drive_current
):
if self.params._config_reg_drive_current != 0:
self._log_warning(
f"Warning: reg_drive_current set in config ({self.params._config_reg_drive_current}) is different the value that is being saved. Please remove the config value, as it will override this one."
)
if self.params.reg_drive_current != 0:
configfile.set(
self._full_name,
"saved_reg_drive_current",
str(self.params.reg_drive_current),
)
if (
self.params._config_tap_drive_current == 0
or self.params.tap_drive_current
!= self.params._config_tap_drive_current
):
if self.params._config_tap_drive_current != 0:
self._log_warning(
f"Warning: tap_drive_current set in config ({self.params._config_tap_drive_current}) is different the value that is being saved. Please remove the config value, as it will override this one."
)
if self.params.tap_drive_current != 0:
configfile.set(
self._full_name,
"saved_tap_drive_current",
str(self.params.tap_drive_current),
)
self._log_info(
"Calibration saved. Issue a SAVE_CONFIG to write the values to your config file and restart Klipper."
)
def start_sampler(self, *args, **kwargs) -> ProbeEddySampler:
if self._sampler:
raise self._printer.command_error(
"EDDYng: Already sampling! (This shouldn't happen; FIRMWARE_RESTART to fix)"
)
self._sampler = ProbeEddySampler(self, *args, **kwargs)
self._sampler.start()
return self._sampler
def sampler_is_active(self):
return self._sampler is not None and self._sampler.active()
# Called by samplers when they're finished
def _sampler_finished(self, sampler: ProbeEddySampler, **kwargs):
if self._sampler is not sampler:
raise self._printer.command_error(
"EDDYng finishing sampler that's not active"
)
self._sampler = None
if self.save_samples_path is not None:
with open(self.save_samples_path, "w") as data_file:
samples = sampler.get_samples()
raw_samples = sampler.get_raw_samples()
data_file.write(
"time,frequency,z,kin_z,kin_v,raw_f,trigger_time,tap_end_time\n"
)
for i in range(len(samples)):
trigger_time = kwargs.get("trigger_time", "")
tap_end_time = kwargs.get("tap_end_time", "")
s_t, s_freq, s_z = samples[i]
_, raw_f, _ = raw_samples[i]
past_pos, past_v = get_toolhead_kin_pos(self._printer, s_t)
past_k_z = past_pos[2] if past_pos is not None else None
if past_k_z is None or past_v is None:
past_k_z = ""
past_v = ""
data_file.write(
f"{s_t},{s_freq},{s_z},{past_k_z},{past_v},{raw_f},{tap_end_time},{trigger_time}\n"
)
logging.info(
f"Wrote {len(samples)} samples to {self.save_samples_path}"
)
self.save_samples_path = None
self._last_sampler_samples = sampler.get_samples()
self._last_sampler_raw_samples = sampler.get_raw_samples()
self._last_sampler_memos = sampler.memos
cmd_STATUS_help = "Query the last raw coil value and status"
def cmd_STATUS(self, gcmd: GCodeCommand):
result = self._sensor.read_one_value()
status = result.status
freqval = result.freqval
freq = result.freq
height = self.freq_to_height(freq) if self.calibrated() else -math.inf
err = ""
if freqval > 0x0FFFFFFF:
height = -math.inf
freq = 0.0
err = f"ERROR: {bin(freqval >> 28)} "
if not self.calibrated():
err += "(Not calibrated) "
gcmd.respond_info(
f"Last coil value: {freq:.2f} ({height:.3f}mm) raw: {hex(freqval)} {err}status: {hex(status)} {self._sensor.status_to_str(status)}"
)
cmd_PROBE_ACCURACY_help = "Probe accuracy"
def cmd_PROBE_ACCURACY(self, gcmd: GCodeCommand):
if not self._z_homed():
raise self._printer.command_error(
"Must home Z before PROBE_ACCURACY"
)
# How long to read at each sample time
duration: float = gcmd.get_float("DURATION", 0.100, above=0.0)
# whether to check +/- 1mm positions for accuracy
start_z: float = gcmd.get_float("Z", 5.0)
offsets = gcmd.get("OFFSETS", None)
probe_speed = gcmd.get_float(
"SPEED", self.params.probe_speed, above=0.0
)
lift_speed = gcmd.get_float(
"LIFT_SPEED", self.params.lift_speed, above=0.0
)
probe_zs = [start_z]
if offsets is not None:
probe_zs.extend([float(v) + start_z for v in offsets.split(",")])
else:
probe_zs.extend(np.arange(0.5, start_z, 0.5).tolist())
probe_zs.sort()
probe_zs.reverse()
# drive current to use
old_drive_current = self.current_drive_current()
drive_current: int = gcmd.get_int(
"DRIVE_CURRENT", old_drive_current, minval=0, maxval=31
)
if not self.calibrated(drive_current):
raise self._printer.command_error(
f"Drive current {drive_current} not calibrated"
)
try:
self._sensor.set_drive_current(drive_current)
th = self._printer.lookup_object("toolhead")
th.manual_move(
[None, None, probe_zs[0] + 1.0],
lift_speed,
)
th.wait_moves()
results = []
ranges = []
from_zs = []
stddev_sums = []
stddev_count = 0
for pz in probe_zs:
th.manual_move([None, None, pz], probe_speed)
th.dwell(0.050)
th.wait_moves()
result = self.probe_static_height(duration=duration)
rangev = result.max_value - result.min_value
from_z = result.value - pz
stddev_sum = np.sum(
[(s - result.value) ** 2.0 for s in result.samples]
)
self._log_info(f"Probe at z={pz:.3f} is {result}")
stddev_sums.append(stddev_sum)
stddev_count += len(result.samples)
results.append(result)
ranges.append(rangev)
from_zs.append(from_z)
if len(results) > 1:
avg_range = np.mean(ranges)
avg_from_z = np.mean(from_zs)
stddev = (np.sum(stddev_sums) / stddev_count) ** 0.5
gcmd.respond_info(
f"Probe spread: {avg_range:.3f}, "
f"z deviation: {avg_from_z:.3f}, "
f"stddev: {stddev:.3f}"
)
finally:
self._sensor.set_drive_current(old_drive_current)
th.manual_move(
[None, None, start_z],
lift_speed,
)
cmd_CLEAR_CALIBRATION_help = "Clear calibration for all drive currents"
def cmd_CLEAR_CALIBRATION(self, gcmd: GCodeCommand):
drive_current: int = gcmd.get_int("DRIVE_CURRENT", -1)
if drive_current == -1:
self._dc_to_fmap = {}
gcmd.respond_info("Cleared calibration for all drive currents")
else:
if drive_current not in self._dc_to_fmap:
raise self._printer.command_error(
f"Drive current {drive_current} not calibrated"
)
del self._dc_to_fmap[drive_current]
gcmd.respond_info(
f"Cleared calibration for drive current {drive_current}"
)
self.save_config()
def cmd_SET_TAP_OFFSET(self, gcmd: GCodeCommand):
value = gcmd.get_float("VALUE", None)
adjust = gcmd.get_float("ADJUST", None)