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