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