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