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