refactor zprobe probe return to be a method and returns to saved last_milestone so...
[clinton/Smoothieware.git] / src / modules / communication / GcodeDispatch.cpp
CommitLineData
de91760a 1/*
4cff3ded
AW
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.
de91760a 5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
4cff3ded
AW
6*/
7
b14f84e0
JM
8#include "GcodeDispatch.h"
9
4cff3ded 10#include "libs/Kernel.h"
00e607c7 11#include "Robot.h"
4cff3ded 12#include "utils/Gcode.h"
436a2cd1 13#include "libs/nuts_bolts.h"
3fceb8eb 14#include "modules/robot/Conveyor.h"
423df6df 15#include "libs/SerialMessage.h"
838b33b4 16#include "libs/StreamOutput.h"
17704c93 17#include "libs/StreamOutputPool.h"
c4d4e3f8 18#include "libs/FileStream.h"
825f27de 19#include "libs/AppendFileStream.h"
61134a65 20#include "Config.h"
7af0714f 21#include "checksumm.h"
8d54c34c 22#include "ConfigValue.h"
c89338bd
JM
23#include "PublicDataRequest.h"
24#include "PublicData.h"
5c051155
JM
25#include "SimpleShell.h"
26#include "utils.h"
5534e39e 27#include "LPC17xx.h"
4cff3ded 28
c89338bd
JM
29#define panel_display_message_checksum CHECKSUM("display_message")
30#define panel_checksum CHECKSUM("panel")
b375ba1d 31
4fb7087f 32// goes in Flash, list of Mxxx codes that are allowed when in Halted state
f88068ec 33static const int allowed_mcodes[]= {2,5,9,30,105,114,119,80,81,911,503,106,107}; // get temp, get pos, get endstops etc
4fb7087f
JM
34static bool is_allowed_mcode(int m) {
35 for (size_t i = 0; i < sizeof(allowed_mcodes)/sizeof(int); ++i) {
36 if(allowed_mcodes[i] == m) return true;
37 }
38 return false;
39}
40
b375ba1d
JM
41GcodeDispatch::GcodeDispatch()
42{
b375ba1d
JM
43 uploading = false;
44 currentline = -1;
ae7c4219 45 modal_group_1= 0;
b375ba1d 46}
4cff3ded
AW
47
48// Called when the module has just been loaded
adf89655
JM
49void GcodeDispatch::on_module_loaded()
50{
4cff3ded
AW
51 this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
52}
53
54// When a command is received, if it is a Gcode, dispatch it as an object via an event
adf89655
JM
55void GcodeDispatch::on_console_line_received(void *line)
56{
57 SerialMessage new_message = *static_cast<SerialMessage *>(line);
de91760a 58 string possible_command = new_message.message;
b6c86164 59
62567509
MC
60 int ln = 0;
61 int cs = 0;
c4c70e85 62
2a58aabf 63 // just reply ok to empty lines
543c4b6d
JM
64 if(possible_command.empty()) {
65 new_message.stream->printf("ok\r\n");
66 return;
67 }
68
2a58aabf
JM
69try_again:
70
c4c70e85 71 char first_char = possible_command[0];
c2885de8 72 unsigned int n;
6c0193b3
JM
73
74 if(first_char == '$') {
75 // ignore as simpleshell will handle it
76 return;
77
78 }else if(islower(first_char)) {
79 // ignore all lowercase as they are simpleshell commands
80 return;
81 }
82
7d105bc4 83 if ( first_char == 'G' || first_char == 'M' || first_char == 'T' || first_char == 'S' || first_char == 'N' ) {
9a29161f 84
62567509 85 //Get linenumber
adf89655 86 if ( first_char == 'N' ) {
aae5a789 87 Gcode full_line = Gcode(possible_command, new_message.stream, false);
534e17b9
MC
88 ln = (int) full_line.get_value('N');
89 int chksum = (int) full_line.get_value('*');
62567509 90
f337d8fd 91 //Catch message if it is M110: Set Current Line Number
b9b1bb25
JM
92 if ( full_line.has_m ) {
93 if ( full_line.m == 110 ) {
f337d8fd
MC
94 currentline = ln;
95 new_message.stream->printf("ok\r\n");
96 return;
97 }
98 }
99
534e17b9 100 //Strip checksum value from possible_command
62567509 101 size_t chkpos = possible_command.find_first_of("*");
de91760a 102 possible_command = possible_command.substr(0, chkpos);
534e17b9 103 //Calculate checksum
adf89655
JM
104 if ( chkpos != string::npos ) {
105 for (auto c = possible_command.cbegin(); *c != '*' && c != possible_command.cend(); c++)
7a2ca498 106 cs = cs ^ *c;
62567509 107 cs &= 0xff; // Defensive programming...
534e17b9 108 cs -= chksum;
62567509 109 }
534e17b9 110 //Strip line number value from possible_command
9883efb8 111 size_t lnsize = possible_command.find_first_not_of("N0123456789.,- ");
de91760a 112 possible_command = possible_command.substr(lnsize);
f337d8fd 113
adf89655 114 } else {
534e17b9
MC
115 //Assume checks succeeded
116 cs = 0x00;
117 ln = currentline + 1;
9a29161f
MC
118 }
119
436a2cd1 120 //Remove comments
30c006fd 121 size_t comment = possible_command.find_first_of(";(");
adf89655
JM
122 if( comment != string::npos ) {
123 possible_command = possible_command.substr(0, comment);
124 }
436a2cd1 125
62567509
MC
126 //If checksum passes then process message, else request resend
127 int nextline = currentline + 1;
adf89655 128 if( cs == 0x00 && ln == nextline ) {
f337d8fd 129 if( first_char == 'N' ) {
534e17b9 130 currentline = nextline;
f337d8fd
MC
131 }
132
d6190d18 133 while(possible_command.size() > 0) {
49d2ca86
JM
134 // assumes G or M are always the first on the line
135 size_t nextcmd = possible_command.find_first_of("GM", 2);
d6190d18 136 string single_command;
85bb8e89 137 if(nextcmd == string::npos) {
d6190d18
MC
138 single_command = possible_command;
139 possible_command = "";
adf89655
JM
140 } else {
141 single_command = possible_command.substr(0, nextcmd);
2c4285ec 142 possible_command = possible_command.substr(nextcmd);
d6190d18 143 }
702023f3 144
b375ba1d 145
bb270b88
JM
146 if(!uploading || upload_stream != new_message.stream) {
147 // Prepare gcode for dispatch
adf89655 148 Gcode *gcode = new Gcode(single_command, new_message.stream);
c4c70e85 149
73706276 150 if(THEKERNEL->is_halted()) {
4fb7087f 151 // we ignore all commands until M999, unless it is in the exceptions list (like M105 get temp)
b375ba1d 152 if(gcode->has_m && gcode->m == 999) {
b9ad75de
JM
153 if(THEKERNEL->is_halted()) {
154 THEKERNEL->call_event(ON_HALT, (void *)1); // clears on_halt
155 new_message.stream->printf("WARNING: After HALT you should HOME as position is currently unknown\n");
156 }
157 new_message.stream->printf("ok\n");
158 delete gcode;
159 continue;
4fb7087f
JM
160
161 }else if(!is_allowed_mcode(gcode->m)) {
76217df5 162 // ignore everything, return error string to host
6c0193b3 163 if(THEKERNEL->is_grbl_mode()) {
07186543 164 new_message.stream->printf("error:Alarm lock\n");
6c0193b3
JM
165
166 }else{
167 new_message.stream->printf("!!\r\n");
168 }
76217df5
JM
169 delete gcode;
170 continue;
b375ba1d 171 }
b375ba1d
JM
172 }
173
c2885de8 174 if(gcode->has_g) {
00e607c7
JM
175 if(gcode->g == 53) { // G53 makes next movement command use machine coordinates
176 // this is ugly to implement as there may or may not be a G0/G1 on the same line
a3be54e3 177 // valid version seem to include G53 G0 X1 Y2 Z3 G53 X1 Y2
00e607c7 178 if(possible_command.empty()) {
5d2319a9 179 // use last gcode G1 or G0 if none on the line, and pass through as if it was a G0/G1
ae7c4219
JM
180 // TODO it is really an error if the last is not G0 thru G3
181 if(modal_group_1 > 3) {
5d2319a9
JM
182 delete gcode;
183 new_message.stream->printf("ok - Invalid G53\r\n");
184 return;
185 }
186 // use last G0 or G1
ae7c4219 187 gcode->g= modal_group_1;
00e607c7
JM
188
189 }else{
190 delete gcode;
191 // extract next G0/G1 from the rest of the line, ignore if it is not one of these
192 gcode = new Gcode(possible_command, new_message.stream);
5d2319a9 193 possible_command= "";
00e607c7
JM
194 if(!gcode->has_g || gcode->g > 1) {
195 // not G0 or G1 so ignore it as it is invalid
196 delete gcode;
197 new_message.stream->printf("ok - Invalid G53\r\n");
198 return;
199 }
200 }
201 // makes it handle the parameters as a machine position
c8bac202 202 THEROBOT->next_command_is_MCS= true;
5d2319a9 203
00e607c7 204 }
5d2319a9 205
ae7c4219
JM
206 // remember last modal group 1 code
207 if(gcode->g < 4) {
208 modal_group_1= gcode->g;
209 }
c2885de8 210 }
b375ba1d 211
adf89655
JM
212 if(gcode->has_m) {
213 switch (gcode->m) {
214 case 28: // start upload command
215 delete gcode;
216
217 this->upload_filename = "/sd/" + single_command.substr(4); // rest of line is filename
218 // open file
219 upload_fd = fopen(this->upload_filename.c_str(), "w");
220 if(upload_fd != NULL) {
221 this->uploading = true;
6d91d256 222 new_message.stream->printf("Writing to file: %s\r\nok\r\n", this->upload_filename.c_str());
adf89655 223 } else {
6d91d256 224 new_message.stream->printf("open failed, File: %s.\r\nok\r\n", this->upload_filename.c_str());
adf89655 225 }
bb270b88
JM
226
227 // only save stuff from this stream
228 upload_stream= new_message.stream;
229
adf89655
JM
230 //printf("Start Uploading file: %s, %p\n", upload_filename.c_str(), upload_fd);
231 continue;
232
01a8d21a
JM
233 case 30: // end of program
234 if(!THEKERNEL->is_grbl_mode()) break; // Special case M30 as it is also delete sd card file so only do this if in grbl mode
235 // fall through to M2
236 case 2:
8ad60a4c
JM
237 {
238 modal_group_1= 1; // set to G1
239 // issue M5 and M9 in case spindle and coolant are being used
240 Gcode gc1("M5", &StreamOutput::NullStream);
241 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc1);
242 Gcode gc2("M9", &StreamOutput::NullStream);
243 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc2);
244 }
245 break;
246
17704c93 247 case 112: // emergency stop, do the best we can with this
e714bd32 248 // this is also handled out-of-band (it is now with ^X in the serial driver)
b375ba1d 249 // disables heaters and motors, ignores further incoming Gcode and clears block queue
728477c4 250 THEKERNEL->call_event(ON_HALT, nullptr);
e714bd32 251 THEKERNEL->streams->printf("ok Emergency Stop Requested - reset or M999 required to exit HALT state\r\n");
b375ba1d 252 delete gcode;
17704c93
JM
253 return;
254
c89338bd
JM
255 case 117: // M117 is a special non compliant Gcode as it allows arbitrary text on the line following the command
256 { // concatenate the command again and send to panel if enabled
257 string str= single_command.substr(4) + possible_command;
258 PublicData::set_value( panel_checksum, panel_display_message_checksum, &str );
259 delete gcode;
260 new_message.stream->printf("ok\r\n");
261 return;
262 }
263
e714bd32 264 case 1000: // M1000 is a special command that will pass thru the raw lowercased command to the simpleshell (for hosts that do not allow such things)
5c051155
JM
265 {
266 // reconstruct entire command line again
267 string str= single_command.substr(5) + possible_command;
268 while(is_whitespace(str.front())){ str= str.substr(1); } // strip leading whitespace
269
270 delete gcode;
271
272 if(str.empty()) {
273 SimpleShell::parse_command("help", "", new_message.stream);
274
275 }else{
276 string args= lc(str);
277 string cmd = shift_parameter(args);
278 // find command and execute it
279 if(!SimpleShell::parse_command(cmd.c_str(), args, new_message.stream)) {
280 new_message.stream->printf("Command not found: %s\n", cmd.c_str());
281 }
282 }
283
284 new_message.stream->printf("ok\r\n");
285 return;
286 }
287
adf89655 288 case 500: // M500 save volatile settings to config-override
04782655 289 THEKERNEL->conveyor->wait_for_idle(); //just to be safe as it can take a while to run
c4d4e3f8 290 //remove(THEKERNEL->config_override_filename()); // seems to cause a hang every now and then
5534e39e 291 __disable_irq();
c4d4e3f8
JM
292 {
293 FileStream fs(THEKERNEL->config_override_filename());
294 fs.printf("; DO NOT EDIT THIS FILE\n");
295 // this also will truncate the existing file instead of deleting it
296 }
f2f0dfed 297 // replace stream with one that writes to config-override file
825f27de 298 gcode->stream = new AppendFileStream(THEKERNEL->config_override_filename());
adf89655 299 // dispatch the M500 here so we can free up the stream when done
314ab8f7 300 THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
adf89655
JM
301 delete gcode->stream;
302 delete gcode;
5534e39e 303 __enable_irq();
347854ff 304 new_message.stream->printf("Settings Stored to %s\r\nok\r\n", THEKERNEL->config_override_filename());
adf89655
JM
305 continue;
306
c0b50fa8
JM
307 case 501: // load config override
308 case 504: // save to specific config override file
309 {
310 string arg= get_arguments(single_command + possible_command); // rest of line is filename
311 if(arg.empty()) arg= "/sd/config-override";
312 else arg= "/sd/config-override." + arg;
b95ebd3a 313 //new_message.stream->printf("args: <%s>\n", arg.c_str());
c0b50fa8
JM
314 SimpleShell::parse_command((gcode->m == 501) ? "load_command" : "save_command", arg, new_message.stream);
315 }
316 delete gcode;
317 new_message.stream->printf("ok\r\n");
318 return;
319
618c9b0f 320 case 502: // M502 deletes config-override so everything defaults to what is in config
347854ff 321 remove(THEKERNEL->config_override_filename());
adf89655 322 delete gcode;
5534e39e 323 new_message.stream->printf("config override file deleted %s, reboot needed\r\nok\r\n", THEKERNEL->config_override_filename());
adf89655
JM
324 continue;
325
326 case 503: { // M503 display live settings and indicates if there is an override file
347854ff 327 FILE *fd = fopen(THEKERNEL->config_override_filename(), "r");
adf89655
JM
328 if(fd != NULL) {
329 fclose(fd);
347854ff 330 new_message.stream->printf("; config override present: %s\n", THEKERNEL->config_override_filename());
adf89655
JM
331
332 } else {
333 new_message.stream->printf("; No config override\n");
334 }
08d9afc6 335 gcode->add_nl= true;
618c9b0f 336 break; // fall through to process by modules
adf89655 337 }
c0b50fa8 338
44e8c359 339 }
33e4cc02
JM
340 }
341
342 //printf("dispatch %p: '%s' G%d M%d...", gcode, gcode->command.c_str(), gcode->g, gcode->m);
44e8c359 343 //Dispatch message!
314ab8f7 344 THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
44e8c359 345
166836be
JM
346 if (gcode->is_error) {
347 // report error
348 if(THEKERNEL->is_grbl_mode()) {
349 new_message.stream->printf("error: ");
350 }else{
8e777b5f 351 new_message.stream->printf("Error: ");
166836be
JM
352 }
353
354 if(!gcode->txt_after_ok.empty()) {
355 new_message.stream->printf("%s\r\n", gcode->txt_after_ok.c_str());
356 gcode->txt_after_ok.clear();
357
358 }else{
359 new_message.stream->printf("unknown\r\n");
360 }
361
50cb3c04
JM
362 // we cannot continue safely after an error so we enter HALT state
363 new_message.stream->printf("Entering Alarm/Halt state\n");
364 THEKERNEL->call_event(ON_HALT, nullptr);
365
166836be
JM
366 }else{
367
368 if(gcode->add_nl)
369 new_message.stream->printf("\r\n");
370
371 if(!gcode->txt_after_ok.empty()) {
372 new_message.stream->printf("ok %s\r\n", gcode->txt_after_ok.c_str());
373 gcode->txt_after_ok.clear();
05cdadd6 374
05cdadd6 375 } else {
166836be
JM
376 if(THEKERNEL->is_ok_per_line() || THEKERNEL->is_grbl_mode()) {
377 // only send ok once per line if this is a multi g code line send ok on the last one
378 if(possible_command.empty())
379 new_message.stream->printf("ok\r\n");
380 } else {
381 // maybe should do the above for all hosts?
382 new_message.stream->printf("ok\r\n");
383 }
05cdadd6
JM
384 }
385 }
44e8c359
JM
386
387 delete gcode;
388
adf89655 389 } else {
bb270b88 390 // we are uploading and it is the upload stream so so save it
44e8c359
JM
391 if(single_command.substr(0, 3) == "M29") {
392 // done uploading, close file
393 fclose(upload_fd);
adf89655
JM
394 upload_fd = NULL;
395 uploading = false;
44e8c359 396 upload_filename.clear();
bb270b88 397 upload_stream= nullptr;
6d91d256 398 new_message.stream->printf("Done saving file.\r\nok\r\n");
44e8c359
JM
399 continue;
400 }
adf89655 401
44e8c359
JM
402 if(upload_fd == NULL) {
403 // error detected writing to file so discard everything until it stops
404 new_message.stream->printf("ok\r\n");
405 continue;
406 }
adf89655 407
44e8c359 408 single_command.append("\n");
adf89655 409 static int cnt = 0;
44e8c359
JM
410 if(fwrite(single_command.c_str(), 1, single_command.size(), upload_fd) != single_command.size()) {
411 // error writing to file
412 new_message.stream->printf("Error:error writing to file.\r\n");
413 fclose(upload_fd);
adf89655 414 upload_fd = NULL;
44e8c359 415 continue;
adf89655
JM
416
417 } else {
418 cnt += single_command.size();
419 if (cnt > 400) {
44e8c359
JM
420 // HACK ALERT to get around fwrite corruption close and re open for append
421 fclose(upload_fd);
adf89655
JM
422 upload_fd = fopen(upload_filename.c_str(), "a");
423 cnt = 0;
44e8c359
JM
424 }
425 new_message.stream->printf("ok\r\n");
426 //printf("uploading file write ok\n");
427 }
428 }
d6190d18 429 }
adf89655
JM
430
431 } else {
62567509 432 //Request resend
f337d8fd 433 new_message.stream->printf("rs N%d\r\n", nextline);
62567509 434 }
2bb8b390 435
c2885de8 436 } else if( (n=possible_command.find_first_of("XYZF")) == 0 || (first_char == ' ' && n != string::npos) ) {
ae7c4219 437 // handle pycam syntax, use last modal group 1 command and resubmit if an X Y Z or F is found on its own line
c2885de8 438 char buf[6];
ae7c4219 439 snprintf(buf, sizeof(buf), "G%d ", modal_group_1);
c2885de8
JM
440 possible_command.insert(0, buf);
441 goto try_again;
442
adf89655
JM
443 // Ignore comments and blank lines
444 } else if ( first_char == ';' || first_char == '(' || first_char == ' ' || first_char == '\n' || first_char == '\r' ) {
b6c86164 445 new_message.stream->printf("ok\r\n");
4cff3ded
AW
446 }
447}
448