temperaturecontrol: allow setting background tool without activating
[clinton/Smoothieware.git] / src / modules / tools / zprobe / ZProbe.cpp
1 /*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 #include "ZProbe.h"
9
10 #include "Kernel.h"
11 #include "BaseSolution.h"
12 #include "Config.h"
13 #include "Robot.h"
14 #include "StepperMotor.h"
15 #include "StreamOutputPool.h"
16 #include "Gcode.h"
17 #include "Conveyor.h"
18 #include "checksumm.h"
19 #include "ConfigValue.h"
20 #include "SlowTicker.h"
21 #include "Planner.h"
22 #include "SerialMessage.h"
23 #include "PublicDataRequest.h"
24 #include "EndstopsPublicAccess.h"
25 #include "PublicData.h"
26 #include "LevelingStrategy.h"
27 #include "StepTicker.h"
28 #include "utils.h"
29
30 // strategies we know about
31 #include "DeltaCalibrationStrategy.h"
32 #include "ThreePointStrategy.h"
33 #include "DeltaGridStrategy.h"
34 #include "CartGridStrategy.h"
35
36 #define enable_checksum CHECKSUM("enable")
37 #define probe_pin_checksum CHECKSUM("probe_pin")
38 #define debounce_ms_checksum CHECKSUM("debounce_ms")
39 #define slow_feedrate_checksum CHECKSUM("slow_feedrate")
40 #define fast_feedrate_checksum CHECKSUM("fast_feedrate")
41 #define return_feedrate_checksum CHECKSUM("return_feedrate")
42 #define probe_height_checksum CHECKSUM("probe_height")
43 #define gamma_max_checksum CHECKSUM("gamma_max")
44 #define max_z_checksum CHECKSUM("max_z")
45 #define reverse_z_direction_checksum CHECKSUM("reverse_z")
46 #define dwell_before_probing_checksum CHECKSUM("dwell_before_probing")
47
48 // from endstop section
49 #define delta_homing_checksum CHECKSUM("delta_homing")
50 #define rdelta_homing_checksum CHECKSUM("rdelta_homing")
51
52 #define X_AXIS 0
53 #define Y_AXIS 1
54 #define Z_AXIS 2
55
56 #define STEPPER THEROBOT->actuators
57 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
58 #define Z_STEPS_PER_MM STEPS_PER_MM(Z_AXIS)
59
60 void ZProbe::on_module_loaded()
61 {
62 // if the module is disabled -> do nothing
63 if(!THEKERNEL->config->value( zprobe_checksum, enable_checksum )->by_default(false)->as_bool()) {
64 // as this module is not needed free up the resource
65 delete this;
66 return;
67 }
68
69 // load settings
70 this->config_load();
71 // register event-handlers
72 register_for_event(ON_GCODE_RECEIVED);
73
74 // we read the probe in this timer
75 probing= false;
76 THEKERNEL->slow_ticker->attach(1000, this, &ZProbe::read_probe);
77 }
78
79 void ZProbe::config_load()
80 {
81 this->pin.from_string( THEKERNEL->config->value(zprobe_checksum, probe_pin_checksum)->by_default("nc" )->as_string())->as_input();
82 this->debounce_ms = THEKERNEL->config->value(zprobe_checksum, debounce_ms_checksum)->by_default(0 )->as_number();
83
84 // get strategies to load
85 vector<uint16_t> modules;
86 THEKERNEL->config->get_module_list( &modules, leveling_strategy_checksum);
87 for( auto cs : modules ){
88 if( THEKERNEL->config->value(leveling_strategy_checksum, cs, enable_checksum )->as_bool() ){
89 bool found= false;
90 LevelingStrategy *ls= nullptr;
91
92 // check with each known strategy and load it if it matches
93 switch(cs) {
94 case delta_calibration_strategy_checksum:
95 ls= new DeltaCalibrationStrategy(this);
96 found= true;
97 break;
98
99 case three_point_leveling_strategy_checksum:
100 // NOTE this strategy is mutually exclusive with the delta calibration strategy
101 ls= new ThreePointStrategy(this);
102 found= true;
103 break;
104
105 case delta_grid_leveling_strategy_checksum:
106 ls= new DeltaGridStrategy(this);
107 found= true;
108 break;
109
110 case cart_grid_leveling_strategy_checksum:
111 ls= new CartGridStrategy(this);
112 found= true;
113 break;
114 }
115 if(found) {
116 if(ls->handleConfig()) {
117 this->strategies.push_back(ls);
118 }else{
119 delete ls;
120 }
121 }
122 }
123 }
124
125 // need to know if we need to use delta kinematics for homing
126 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
127 this->is_rdelta = THEKERNEL->config->value(rdelta_homing_checksum)->by_default(false)->as_bool();
128
129 // default for backwards compatibility add DeltaCalibrationStrategy if a delta
130 // may be deprecated
131 if(this->strategies.empty()) {
132 if(this->is_delta) {
133 this->strategies.push_back(new DeltaCalibrationStrategy(this));
134 this->strategies.back()->handleConfig();
135 }
136 }
137
138 this->probe_height = THEKERNEL->config->value(zprobe_checksum, probe_height_checksum)->by_default(5.0F)->as_number();
139 this->slow_feedrate = THEKERNEL->config->value(zprobe_checksum, slow_feedrate_checksum)->by_default(5)->as_number(); // feedrate in mm/sec
140 this->fast_feedrate = THEKERNEL->config->value(zprobe_checksum, fast_feedrate_checksum)->by_default(100)->as_number(); // feedrate in mm/sec
141 this->return_feedrate = THEKERNEL->config->value(zprobe_checksum, return_feedrate_checksum)->by_default(0)->as_number(); // feedrate in mm/sec
142 this->reverse_z = THEKERNEL->config->value(zprobe_checksum, reverse_z_direction_checksum)->by_default(false)->as_bool(); // Z probe moves in reverse direction
143 this->max_z = THEKERNEL->config->value(zprobe_checksum, max_z_checksum)->by_default(NAN)->as_number(); // maximum zprobe distance
144 if(isnan(this->max_z)){
145 this->max_z = THEKERNEL->config->value(gamma_max_checksum)->by_default(200)->as_number(); // maximum zprobe distance
146 }
147 this->dwell_before_probing = THEKERNEL->config->value(zprobe_checksum, dwell_before_probing_checksum)->by_default(0)->as_number(); // dwell time in seconds before probing
148
149 }
150
151 uint32_t ZProbe::read_probe(uint32_t dummy)
152 {
153 if(!probing || probe_detected) return 0;
154
155 // we check all axis as it maybe a G38.2 X10 for instance, not just a probe in Z
156 if(STEPPER[X_AXIS]->is_moving() || STEPPER[Y_AXIS]->is_moving() || STEPPER[Z_AXIS]->is_moving()) {
157 // if it is moving then we check the probe, and debounce it
158 if(this->pin.get() != invert_probe) {
159 if(debounce < debounce_ms) {
160 debounce++;
161 } else {
162 // we signal the motors to stop, which will preempt any moves on that axis
163 // we do all motors as it may be a delta
164 for(auto &a : THEROBOT->actuators) a->stop_moving();
165 probe_detected= true;
166 debounce= 0;
167 }
168
169 } else {
170 // The endstop was not hit yet
171 debounce= 0;
172 }
173 }
174
175 return 0;
176 }
177
178 // single probe in Z with custom feedrate
179 // returns boolean value indicating if probe was triggered
180 bool ZProbe::run_probe(float& mm, float feedrate, float max_dist, bool reverse)
181 {
182 if(dwell_before_probing > .0001F) safe_delay_ms(dwell_before_probing*1000);
183
184 if(this->pin.get()) {
185 // probe already triggered so abort
186 return false;
187 }
188
189 float maxz= max_dist < 0 ? this->max_z*2 : max_dist;
190
191 probing= true;
192 probe_detected= false;
193 debounce= 0;
194
195 // save current actuator position so we can report how far we moved
196 float z_start_pos= THEROBOT->actuators[Z_AXIS]->get_current_position();
197
198 // move Z down
199 bool dir= (!reverse_z != reverse); // xor
200 float delta[3]= {0,0,0};
201 delta[Z_AXIS]= dir ? -maxz : maxz;
202 THEROBOT->delta_move(delta, feedrate, 3);
203
204 // wait until finished
205 THECONVEYOR->wait_for_idle();
206
207 // now see how far we moved, get delta in z we moved
208 // NOTE this works for deltas as well as all three actuators move the same amount in Z
209 mm= z_start_pos - THEROBOT->actuators[2]->get_current_position();
210
211 // set the last probe position to the actuator units moved during this home
212 THEROBOT->set_last_probe_position(std::make_tuple(0, 0, mm, probe_detected?1:0));
213
214 probing= false;
215
216 if(probe_detected) {
217 // if the probe stopped the move we need to correct the last_milestone as it did not reach where it thought
218 THEROBOT->reset_position_from_current_actuator_position();
219 }
220
221 return probe_detected;
222 }
223
224 // do probe then return to start position
225 bool ZProbe::run_probe_return(float& mm, float feedrate, float max_dist, bool reverse)
226 {
227 float save_z_pos= THEROBOT->get_axis_position(Z_AXIS);
228
229 bool ok= run_probe(mm, feedrate, max_dist, reverse);
230
231 // move probe back to where it was
232 float fr;
233 if(this->return_feedrate != 0) { // use return_feedrate if set
234 fr = this->return_feedrate;
235 } else {
236 fr = this->slow_feedrate*2; // nominally twice slow feedrate
237 if(fr > this->fast_feedrate) fr = this->fast_feedrate; // unless that is greater than fast feedrate
238 }
239
240 // absolute move back to saved starting position
241 coordinated_move(NAN, NAN, save_z_pos, fr, false);
242
243 return ok;
244 }
245
246 bool ZProbe::doProbeAt(float &mm, float x, float y)
247 {
248 // move to xy
249 coordinated_move(x, y, NAN, getFastFeedrate());
250 return run_probe_return(mm, slow_feedrate);
251 }
252
253 void ZProbe::on_gcode_received(void *argument)
254 {
255 Gcode *gcode = static_cast<Gcode *>(argument);
256
257 if( gcode->has_g && gcode->g >= 29 && gcode->g <= 32) {
258
259 invert_probe = false;
260 // make sure the probe is defined and not already triggered before moving motors
261 if(!this->pin.connected()) {
262 gcode->stream->printf("ZProbe pin not configured.\n");
263 return;
264 }
265
266 if(this->pin.get()) {
267 gcode->stream->printf("ZProbe triggered before move, aborting command.\n");
268 return;
269 }
270
271 if( gcode->g == 30 ) { // simple Z probe
272 // first wait for all moves to finish
273 THEKERNEL->conveyor->wait_for_idle();
274
275 bool set_z= (gcode->has_letter('Z') && !is_rdelta);
276 bool probe_result;
277 bool reverse= (gcode->has_letter('R') && gcode->get_value('R') != 0); // specify to probe in reverse direction
278 float rate= gcode->has_letter('F') ? gcode->get_value('F') / 60 : this->slow_feedrate;
279 float mm;
280
281 // if not setting Z then return probe to where it started, otherwise leave it where it is
282 probe_result = (set_z ? run_probe(mm, rate, -1, reverse) : run_probe_return(mm, rate, -1, reverse));
283
284 if(probe_result) {
285 // the result is in actuator coordinates moved
286 gcode->stream->printf("Z:%1.4f\n", THEKERNEL->robot->from_millimeters(mm));
287
288 if(set_z) {
289 // set current Z to the specified value, shortcut for G92 Znnn
290 char buf[32];
291 int n = snprintf(buf, sizeof(buf), "G92 Z%f", gcode->get_value('Z'));
292 string g(buf, n);
293 Gcode gc(g, &(StreamOutput::NullStream));
294 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
295 }
296
297 } else {
298 gcode->stream->printf("ZProbe not triggered\n");
299 }
300
301 } else {
302 if(!gcode->has_letter('P')) {
303 // find the first strategy to handle the gcode
304 for(auto s : strategies){
305 if(s->handleGcode(gcode)) {
306 return;
307 }
308 }
309 gcode->stream->printf("No strategy found to handle G%d\n", gcode->g);
310
311 }else{
312 // P paramater selects which strategy to send the code to
313 // they are loaded in the order they are defined in config, 0 being the first, 1 being the second and so on.
314 uint16_t i= gcode->get_value('P');
315 if(i < strategies.size()) {
316 if(!strategies[i]->handleGcode(gcode)){
317 gcode->stream->printf("strategy #%d did not handle G%d\n", i, gcode->g);
318 }
319 return;
320
321 }else{
322 gcode->stream->printf("strategy #%d is not loaded\n", i);
323 }
324 }
325 }
326
327 } else if(gcode->has_g && gcode->g == 38 ) { // G38.2 Straight Probe with error, G38.3 straight probe without error
328 // linuxcnc/grbl style probe http://www.linuxcnc.org/docs/2.5/html/gcode/gcode.html#sec:G38-probe
329 if(gcode->subcode < 2 || gcode->subcode > 5) {
330 gcode->stream->printf("error:Only G38.2 to G38.5 are supported\n");
331 return;
332 }
333
334 // make sure the probe is defined and not already triggered before moving motors
335 if(!this->pin.connected()) {
336 gcode->stream->printf("error:ZProbe not connected.\n");
337 return;
338 }
339
340 if(this->pin.get() ^ (gcode->subcode >= 4)) {
341 gcode->stream->printf("error:ZProbe triggered before move, aborting command.\n");
342 return;
343 }
344
345 // first wait for all moves to finish
346 THEKERNEL->conveyor->wait_for_idle();
347
348 float x= NAN, y=NAN, z=NAN;
349 if(gcode->has_letter('X')) {
350 x= gcode->get_value('X');
351 }
352
353 if(gcode->has_letter('Y')) {
354 y= gcode->get_value('Y');
355 }
356
357 if(gcode->has_letter('Z')) {
358 z= gcode->get_value('Z');
359 }
360
361 if(isnan(x) && isnan(y) && isnan(z)) {
362 gcode->stream->printf("error:at least one of X Y or Z must be specified\n");
363 return;
364 }
365
366 if(gcode->subcode == 4 || gcode->subcode == 5) {
367 invert_probe = true;
368 } else {
369 invert_probe = false;
370 }
371
372 probe_XYZ(gcode, x, y, z);
373
374 invert_probe = false;
375
376 return;
377
378 } else if(gcode->has_m) {
379 // M code processing here
380 int c;
381 switch (gcode->m) {
382 case 119:
383 c = this->pin.get();
384 gcode->stream->printf(" Probe: %d", c);
385 gcode->add_nl = true;
386 break;
387
388 case 670:
389 if (gcode->has_letter('S')) this->slow_feedrate = gcode->get_value('S');
390 if (gcode->has_letter('K')) this->fast_feedrate = gcode->get_value('K');
391 if (gcode->has_letter('R')) this->return_feedrate = gcode->get_value('R');
392 if (gcode->has_letter('Z')) this->max_z = gcode->get_value('Z');
393 if (gcode->has_letter('H')) this->probe_height = gcode->get_value('H');
394 if (gcode->has_letter('I')) { // NOTE this is temporary and toggles the invertion status of the pin
395 invert_override= (gcode->get_value('I') != 0);
396 pin.set_inverting(pin.is_inverting() != invert_override); // XOR so inverted pin is not inverted and vice versa
397 }
398 if (gcode->has_letter('D')) this->dwell_before_probing = gcode->get_value('D');
399 break;
400
401 case 500: // save settings
402 case 503: // print settings
403 gcode->stream->printf(";Probe feedrates Slow/fast(K)/Return (mm/sec) max_z (mm) height (mm) dwell (s):\nM670 S%1.2f K%1.2f R%1.2f Z%1.2f H%1.2f D%1.2f\n",
404 this->slow_feedrate, this->fast_feedrate, this->return_feedrate, this->max_z, this->probe_height, this->dwell_before_probing);
405
406 // fall through is intended so leveling strategies can handle m-codes too
407
408 default:
409 for(auto s : strategies){
410 if(s->handleGcode(gcode)) {
411 return;
412 }
413 }
414 }
415 }
416 }
417
418 // special way to probe in the X or Y or Z direction using planned moves, should work with any kinematics
419 void ZProbe::probe_XYZ(Gcode *gcode, float x, float y, float z)
420 {
421 // enable the probe checking in the timer
422 probing= true;
423 probe_detected= false;
424 THEROBOT->disable_segmentation= true; // we must disable segmentation as this won't work with it enabled (beware on deltas probing in X or Y)
425
426 // get probe feedrate in mm/min and convert to mm/sec if specified
427 float rate = (gcode->has_letter('F')) ? gcode->get_value('F')/60 : this->slow_feedrate;
428
429 // do a regular move which will stop as soon as the probe is triggered, or the distance is reached
430 coordinated_move(x, y, z, rate, true);
431
432 // coordinated_move returns when the move is finished
433
434 // disable probe checking
435 probing= false;
436 THEROBOT->disable_segmentation= false;
437
438 // if the probe stopped the move we need to correct the last_milestone as it did not reach where it thought
439 // this also sets last_milestone to the machine coordinates it stopped at
440 THEROBOT->reset_position_from_current_actuator_position();
441 float pos[3];
442 THEROBOT->get_axis_position(pos, 3);
443
444 uint8_t probeok= this->probe_detected ? 1 : 0;
445
446 // print results using the GRBL format
447 gcode->stream->printf("[PRB:%1.3f,%1.3f,%1.3f:%d]\n", THEKERNEL->robot->from_millimeters(pos[X_AXIS]), THEKERNEL->robot->from_millimeters(pos[Y_AXIS]), THEKERNEL->robot->from_millimeters(pos[Z_AXIS]), probeok);
448 THEROBOT->set_last_probe_position(std::make_tuple(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], probeok));
449
450 if(probeok == 0 && (gcode->subcode == 2 || gcode->subcode == 4)) {
451 // issue error if probe was not triggered and subcode is 2 or 4
452 gcode->stream->printf("ALARM: Probe fail\n");
453 THEKERNEL->call_event(ON_HALT, nullptr);
454 }
455 }
456
457 // issue a coordinated move directly to robot, and return when done
458 // Only move the coordinates that are passed in as not nan
459 // NOTE must use G53 to force move in machine coordinates and ignore any WCS offsets
460 void ZProbe::coordinated_move(float x, float y, float z, float feedrate, bool relative)
461 {
462 #define CMDLEN 128
463 char *cmd= new char[CMDLEN]; // use heap here to reduce stack usage
464
465 if(relative) strcpy(cmd, "G91 G0 ");
466 else strcpy(cmd, "G53 G0 "); // G53 forces movement in machine coordinate system
467
468 if(!isnan(x)) {
469 size_t n= strlen(cmd);
470 snprintf(&cmd[n], CMDLEN-n, " X%1.3f", x);
471 }
472 if(!isnan(y)) {
473 size_t n= strlen(cmd);
474 snprintf(&cmd[n], CMDLEN-n, " Y%1.3f", y);
475 }
476 if(!isnan(z)) {
477 size_t n= strlen(cmd);
478 snprintf(&cmd[n], CMDLEN-n, " Z%1.3f", z);
479 }
480
481 {
482 size_t n= strlen(cmd);
483 // use specified feedrate (mm/sec)
484 snprintf(&cmd[n], CMDLEN-n, " F%1.1f", feedrate * 60); // feed rate is converted to mm/min
485 }
486
487 if(relative) strcat(cmd, " G90");
488
489 //THEKERNEL->streams->printf("DEBUG: move: %s: %u\n", cmd, strlen(cmd));
490
491 // send as a command line as may have multiple G codes in it
492 THEROBOT->push_state();
493 struct SerialMessage message;
494 message.message = cmd;
495 delete [] cmd;
496
497 message.stream = &(StreamOutput::NullStream);
498 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
499 THEKERNEL->conveyor->wait_for_idle();
500 THEROBOT->pop_state();
501
502 }
503
504 // issue home command
505 void ZProbe::home()
506 {
507 Gcode gc(THEKERNEL->is_grbl_mode() ? "G28.2" : "G28", &(StreamOutput::NullStream));
508 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
509 }