forked from beacon3d/beacon_klipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
beacon.py
2468 lines (2097 loc) · 85.9 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 <[email protected]>
# Copyright (C) 2020-2023 Lasse Dalegaard <[email protected]>
# Copyright (C) 2023 Beacon <beacon3d.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import threading
import logging
import chelper
import pins
import math
import time
import queue
import json
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 adc_temperature
from . import adxl345
from mcu import MCU, MCU_trsync
from clocksync import SecondarySync
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.name = config.get_name()
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)
# 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)
# 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.last_temp = 0
self.measured_min = 99999999.0
self.measured_max = 0.0
self.last_sample = None
self.hardware_failure = None
self.mesh_helper = BeaconMeshHelper.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_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
mainsync = self.printer.lookup_object("mcu")._clocksync
self._mcu = MCU(config, SecondarySync(self.reactor, mainsync))
self.printer.add_object("mcu " + self.name, self._mcu)
self.cmd_queue = self._mcu.alloc_command_queue()
self.mcu_probe = BeaconEndstopWrapper(self)
# 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:mcu_identify", self._handle_mcu_identify
)
self._mcu.register_config_callback(self._build_config)
self._mcu.register_response(self._handle_beacon_data, "beacon_data")
# 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(
"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,
)
# Event handlers
def _handle_connect(self):
self.phoming = self.printer.lookup_object("homing")
# Ensure streaming mode is stopped
self.beacon_stream_cmd.send([0])
if self.accel_helper:
self.accel_helper._handle_connect()
self.model_temp = self.model_temp_builder.build_with_nvm(self)
if self.model_temp:
self.fmin = self.model_temp.fmin
self.model = self.models.get(self.default_model_name, None)
if self.model:
self._apply_threshold()
def _handle_mcu_identify(self):
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()
def _build_config(self):
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 = 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,
)
constants = self._mcu.get_constants()
if constants.get("BEACON_HAS_ACCEL", 0) == 1:
logging.info("Enabling Beacon accelerometer")
self.accel_helper = BeaconAccelHelper(self, self.accel_config)
def stats(self, eventtime):
return False, "%s: coil_temp=%.1f" % (self.name, self.last_temp)
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._start_streaming()
def multi_probe_end(self):
self._stop_streaming()
def get_offsets(self):
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):
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
lift_speed = self.get_lift_speed(gcmd)
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._start_streaming()
try:
return self._probe(speed, allow_faulty=allow_faulty)
finally:
self._stop_streaming()
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 _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:
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]
# 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
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, 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] - 1.0
self.toolhead.set_position(pos, homing_axes=[2])
forced_z = True
cb = lambda kin_pos: self._calibrate(gcmd, kin_pos, forced_z)
manual_probe.ManualProbeHelper(self.printer, gcmd, cb)
def _calibrate(self, gcmd, kin_pos, forced_z):
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_nozzle_z = gcmd.get_float("NOZZLE_Z", self.cal_nozzle_z)
cal_floor = gcmd.get_float("FLOOR", self.cal_floor)
cal_ceil = gcmd.get_float("CEIL", self.cal_ceil)
cal_min_z = kin_pos[2] - cal_nozzle_z + cal_floor
cal_max_z = kin_pos[2] - cal_nozzle_z + cal_ceil
cal_speed = gcmd.get_float("SPEED", self.cal_speed)
move_speed = gcmd.get_float("MOVE_SPEED", self.cal_move_speed)
toolhead = self.toolhead
curtime = self.reactor.monotonic()
toolhead.wait_moves()
pos = toolhead.get_position()
# Move over to probe coordinate and pull out backlash
curpos = self.toolhead.get_position()
curpos[2] = cal_max_z + 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_max_z
toolhead.manual_move(curpos, move_speed) # Down
toolhead.wait_moves()
samples = []
def cb(sample):
samples.append(sample)
try:
self._start_streaming()
self._sample_printtime_sync(50)
with self.streaming_session(cb) as ss:
self._sample_printtime_sync(50)
toolhead.dwell(0.250)
curpos[2] = cal_min_z
toolhead.manual_move(curpos, cal_speed)
toolhead.dwell(0.250)
self._sample_printtime_sync(50)
finally:
self._stop_streaming()
# Fit the sampled data
z_offset = [s["pos"][2] - cal_min_z + cal_floor 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(
"default", self, poly, temp_median, min(z_offset), max(z_offset)
)
self.models[self.model.name] = self.model
self.model.save(self)
self._apply_threshold()
self.toolhead.get_last_move_time()
pos = self.toolhead.get_position()
pos[2] = cal_floor
self.toolhead.set_position(pos)
# Dump calibration curve
fn = "/tmp/beacon-calibrate-" + time.strftime("%Y%m%d_%H%M%S") + ".csv"
f = open(fn, "w")
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]))
f.close()
gcmd.respond_info(
"Beacon calibrated at %.3f,%.3f from "
"%.3f to %.3f, speed %.2f mm/s, temp %.2fC"
% (pos[0], pos[1], cal_min_z, cal_max_z, cal_speed, temp_median)
)
# 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))
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)
# 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 _enrich_sample_time(self, sample):
clock = sample["clock"] = self._mcu.clock32_to_clock64(sample["clock"])
sample["time"] = self._mcu.clock_to_print_time(clock)
def _enrich_sample_temp(self, sample):
temp_adc = sample["temp"] / self.temp_smooth_count * self.inv_adc_max
sample["temp"] = self.thermistor.calc_temp(temp_adc)
def _enrich_sample_freq(self, sample):
sample["data_smooth"] = self._data_filter.value()
sample["freq"] = self.count_to_freq(sample["data_smooth"])
self._check_hardware(sample)
def _enrich_sample(self, sample):
sample["dist"] = self.freq_to_dist(sample["freq"], sample["temp"])
pos, vel = self._get_trapq_position(sample["time"])
if pos is None:
return
sample["pos"] = pos
sample["vel"] = vel
def _start_streaming(self):
if self._stream_en == 0:
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):
self._stream_en -= 1
if self._stream_en == 0:
self.reactor.update_timer(self._stream_timeout_timer, self.reactor.NEVER)
self.beacon_stream_cmd.send([0])
self._stream_flush()
def _stream_timeout(self, eventtime):
if not self._stream_en:
return self.reactor.NEVER
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(self):
self._stream_flush_event.clear()
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._enrich_sample_temp(sample)
temp = sample["temp"]
if self.model_temp is not None and not (-40 < temp < 180):
msg = (
"Beacon temperature sensor faulty(read %.2f C),"
" disabling temperaure compensation" % (temp,)
)
logging.error(msg)
self.gcode.respond_raw("!! " + msg + "\n")
self.model_temp = None
self.last_temp = temp
if temp:
self.measured_min = min(self.measured_min, temp)
self.measured_max = max(self.measured_max, temp)
self._enrich_sample_time(sample)
self._data_filter.update(sample["time"], sample["data"])
self._enrich_sample_freq(sample)
if len(self._stream_callbacks) > 0:
self._enrich_sample(sample)
for cb in list(self._stream_callbacks.values()):
cb(sample)
except queue.Empty:
return
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 len(self._stream_buffer) < self._stream_buffer_limit:
return
self._stream_samples_queue.put_nowait(self._stream_buffer)
self._stream_buffer = []
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):
if self.trapq is None:
return
self._stream_buffer.append(params.copy())
self._stream_flush_schedule()
def _get_trapq_position(self, print_time):
ffi_main, ffi_lib = chelper.get_ffi()
data = ffi_main.new("struct pull_move[1]")
count = ffi_lib.trapq_extract_old(self.trapq, data, 1, 0.0, print_time)
if not count:
return None, None
move = data[0]
move_time = max(0.0, min(move.move_t, print_time - move.print_time))
dist = (move.start_v + 0.5 * move.accel * move_time) * move_time
pos = (
move.start_x + move.x_r * dist,
move.start_y + move.y_r * dist,
move.start_z + move.z_r * dist,
)
velocity = move.start_v + move.accel * move_time
return pos, velocity
def _sample_printtime_sync(self, skip=0, count=1):
toolhead = self.printer.lookup_object("toolhead")
move_time = toolhead.get_last_move_time()
settle_clock = self._mcu.print_time_to_clock(move_time)
samples = []
total = skip + count
def cb(sample):
if sample["clock"] >= settle_clock:
samples.append(sample)
if len(samples) >= total:
raise StopStreaming
with self.streaming_session(cb, latency=skip + count) as ss:
ss.wait()
samples = samples[skip:]
if count == 1:
return samples[0]
else:
return samples
def _sample(self, skip, count):
samples = self._sample_printtime_sync(skip, count)
return (median([s["dist"] for s in samples]), samples)
def _sample_async(self, count=1):
samples = []
def cb(sample):
samples.append(sample)
if len(samples) >= count:
raise StopStreaming
with self.streaming_session(cb, latency=count) as ss:
ss.wait()
if count == 1:
return samples[0]
else:
return samples
def count_to_freq(self, count):
return count * self._mcu_freq / (2**28)
def freq_to_count(self, freq):
return freq * (2**28) / self._mcu_freq
def dist_to_freq(self, dist, temp):
if self.model is None:
return None
return self.model.dist_to_freq(dist, temp)
def freq_to_dist(self, freq, temp):
if self.model is None:
return None
return self.model.freq_to_dist(freq, temp)
def get_status(self, eventtime):
model = None
if self.model is not None:
model = self.model.name
return {
"last_sample": self.last_sample,
"model": model,
}
# Webhook handlers
def _handle_req_status(self, web_request):
temp = None
sample = self._sample_async()
out = {
"freq": sample["freq"],
"dist": sample["dist"],
}
temp = sample["temp"]
if temp is not None:
out["temp"] = temp
web_request.send(out)
def _handle_req_dump(self, web_request):
self._api_dump.add_web_client(web_request)
web_request.send({"header": API_DUMP_FIELDS})
# GCode command handlers
cmd_PROBE_help = "Probe Z-height at current XY position"
def cmd_PROBE(self, gcmd):
pos = self.run_probe(gcmd)
gcmd.respond_info("Result is z=%.6f" % (pos[2],))
cmd_BEACON_CALIBRATE_help = "Calibrate beacon response curve"
def cmd_BEACON_CALIBRATE(self, gcmd):
self._start_calibration(gcmd)
cmd_BEACON_ESTIMATE_BACKLASH_help = "Estimate Z axis backlash"
def cmd_BEACON_ESTIMATE_BACKLASH(self, gcmd):
# Get to correct Z height
overrun = gcmd.get_float("OVERRUN", 1.0)
speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.0)
cur_z = self.toolhead.get_position()[2]
self.toolhead.manual_move([None, None, cur_z + overrun], speed)
self.run_probe(gcmd)
lift_speed = self.get_lift_speed(gcmd)
target = gcmd.get_float("Z", self.trigger_distance)
num_samples = gcmd.get_int("SAMPLES", 20)
wait = self.z_settling_time
samples_up = []
samples_down = []
next_dir = -1
try:
self._start_streaming()
(cur_dist, _samples) = self._sample(wait, 10)
pos = self.toolhead.get_position()
missing = target - cur_dist
target = pos[2] + missing
gcmd.respond_info("Target kinematic Z is %.3f" % (target,))
if target - overrun < 0:
raise gcmd.error("Target minus overrun must exceed 0mm")
while len(samples_up) + len(samples_down) < num_samples:
liftpos = [None, None, target + overrun * next_dir]
self.toolhead.manual_move(liftpos, lift_speed)
liftpos = [None, None, target]
self.toolhead.manual_move(liftpos, lift_speed)
self.toolhead.wait_moves()
(dist, _samples) = self._sample(wait, 10)
{-1: samples_up, 1: samples_down}[next_dir].append(dist)
next_dir = next_dir * -1
finally:
self._stop_streaming()
res_up = median(samples_up)
res_down = median(samples_down)
gcmd.respond_info(
"Median distance moving up %.5f, down %.5f, "
"delta %.5f over %d samples"
% (res_up, res_down, res_down - res_up, num_samples)
)
cmd_BEACON_QUERY_help = "Take a sample from the sensor"
def cmd_BEACON_QUERY(self, gcmd):
sample = self._sample_async()
last_value = sample["freq"]
dist = sample["dist"]
temp = sample["temp"]
self.last_sample = {
"time": sample["time"],
"value": last_value,
"temp": temp,
"dist": dist,
}
if dist is None:
gcmd.respond_info(
"Last reading: %.2fHz, %.2fC, no model"
% (
last_value,
temp,
)
)
else:
gcmd.respond_info(
"Last reading: %.2fHz, %.2fC, %.5fmm" % (last_value, temp, dist)
)
cmd_BEACON_STREAM_help = "Enable Beacon Streaming"
def cmd_BEACON_STREAM(self, gcmd):
if self._log_stream is not None:
self._log_stream.stop()
self._log_stream = None
gcmd.respond_info("Beacon Streaming disabled")
else:
f = None
completion_cb = None
fn = gcmd.get("FILENAME")
f = open(fn, "w")
def close_file():
f.close()
completion_cb = close_file
f.write("time,data,data_smooth,freq,dist,temp,pos_x,pos_y,pos_z,vel\n")
def cb(sample):
pos = sample.get("pos", None)
obj = "%.4f,%d,%.2f,%.5f,%.5f,%.2f,%s,%s,%s,%s\n" % (
sample["time"],
sample["data"],
sample["data_smooth"],
sample["freq"],
sample["dist"],
sample["temp"],
"%.3f" % (pos[0],) if pos is not None else "",
"%.3f" % (pos[1],) if pos is not None else "",
"%.3f" % (pos[2],) if pos is not None else "",
"%.3f" % (sample["vel"],) if "vel" in sample else "",
)
f.write(obj)
self._log_stream = self.streaming_session(cb, completion_cb)
gcmd.respond_info("Beacon Streaming enabled")
cmd_PROBE_ACCURACY_help = "Probe Z-height accuracy at current XY position"
def cmd_PROBE_ACCURACY(self, gcmd):
speed = gcmd.get_float("PROBE_SPEED", self.speed, above=0.0)
lift_speed = self.get_lift_speed(gcmd)
sample_count = gcmd.get_int("SAMPLES", 10, minval=1)
sample_retract_dist = gcmd.get_float("SAMPLE_RETRACT_DIST", 0)
allow_faulty = gcmd.get_int("ALLOW_FAULTY_COORDINATE", 0) != 0
pos = self.toolhead.get_position()
gcmd.respond_info(
"PROBE_ACCURACY at X:%.3f Y:%.3f Z:%.3f"
" (samples=%d retract=%.3f"
" speed=%.1f lift_speed=%.1f)\n"
% (
pos[0],
pos[1],
pos[2],
sample_count,
sample_retract_dist,
speed,
lift_speed,
)
)
start_height = self.trigger_distance + sample_retract_dist
liftpos = [None, None, start_height]
self.toolhead.manual_move(liftpos, lift_speed)
self.multi_probe_begin()
positions = []
while len(positions) < sample_count:
pos = self._probe(speed, allow_faulty=allow_faulty)
positions.append(pos)
self.toolhead.manual_move(liftpos, lift_speed)
self.multi_probe_end()
zs = [p[2] for p in positions]
max_value = max(zs)
min_value = min(zs)
range_value = max_value - min_value
avg_value = sum(zs) / len(positions)
median_ = median(zs)
deviation_sum = 0
for i in range(len(zs)):
deviation_sum += pow(zs[2] - avg_value, 2.0)
sigma = (deviation_sum / len(zs)) ** 0.5
gcmd.respond_info(
"probe accuracy results: maximum %.6f, minimum %.6f, range %.6f, "
"average %.6f, median %.6f, standard deviation %.6f"
% (max_value, min_value, range_value, avg_value, median_, sigma)
)
cmd_Z_OFFSET_APPLY_PROBE_help = "Adjust the probe's z_offset"
def cmd_Z_OFFSET_APPLY_PROBE(self, gcmd):
gcode_move = self.printer.lookup_object("gcode_move")
offset = gcode_move.get_status()["homing_origin"].z
if offset == 0:
self.gcode.respond_info("Nothing to do: Z Offset is 0")
return
if not self.model:
raise self.gcode.error(
"You must calibrate your model first, " "use BEACON_CALIBRATE."
)
# We use the model code to save the new offset, but we can't actually
# apply that offset yet because the gcode_offset is still in effect.
# If the user continues to do stuff after this, the newly set model
# offset would compound with the gcode offset. To ensure this doesn't
# happen, we revert to the old model offset afterwards.
# Really, the user should just be calling `SAVE_CONFIG` now.
old_offset = self.model.offset
self.model.offset += offset
self.model.save(self, False)
gcmd.respond_info(
"Beacon model offset has been updated\n"
"You must run the SAVE_CONFIG command now to update the\n"
"printer config file and restart the printer."
)
self.model.offset = old_offset
class BeaconModel:
@classmethod
def load(cls, name, config, beacon):
coef = config.getfloatlist("model_coef")
temp = config.getfloat("model_temp")
domain = config.getfloatlist("model_domain", count=2)
[min_z, max_z] = config.getfloatlist("model_range", count=2)
offset = config.getfloat("model_offset", 0.0)
poly = Polynomial(coef, domain)
return BeaconModel(name, beacon, poly, temp, min_z, max_z, offset)
def __init__(self, name, beacon, poly, temp, min_z, max_z, offset=0):
self.name = name
self.beacon = beacon
self.poly = poly
self.min_z = min_z
self.max_z = max_z
self.temp = temp
self.offset = offset
def save(self, beacon, show_message=True):
configfile = beacon.printer.lookup_object("configfile")
section = "beacon model " + self.name
configfile.set(section, "model_coef", ",\n ".join(map(str, self.poly.coef)))
configfile.set(section, "model_domain", ",".join(map(str, self.poly.domain)))
configfile.set(section, "model_range", "%f,%f" % (self.min_z, self.max_z))
configfile.set(section, "model_temp", "%f" % (self.temp))
configfile.set(section, "model_offset", "%.5f" % (self.offset,))
if show_message:
beacon.gcode.respond_info(
"Beacon calibration for model '%s' has "
"been updated\nfor the current session. The SAVE_CONFIG "
"command will\nupdate the printer config file and restart "
"the printer." % (self.name,)
)
def freq_to_dist_raw(self, freq):
[begin, end] = self.poly.domain
invfreq = 1 / freq
if invfreq > end:
return float("inf")
elif invfreq < begin:
return float("-inf")
else:
return float(self.poly(invfreq) - self.offset)