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