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