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/>.
10 #include "libs/Kernel.h"
12 #include "libs/nuts_bolts.h"
13 #include "libs/utils.h"
14 #include "SerialConsole.h"
15 #include "libs/SerialMessage.h"
16 #include "libs/StreamOutputPool.h"
17 #include "libs/StreamOutput.h"
19 #include "checksumm.h"
22 #include "ConfigValue.h"
25 #include "modules/robot/Conveyor.h"
26 #include "DirHandle.h"
27 #include "PublicDataRequest.h"
28 #include "PublicData.h"
29 #include "PlayerPublicAccess.h"
30 #include "TemperatureControlPublicAccess.h"
31 #include "TemperatureControlPool.h"
32 #include "ExtruderPublicAccess.h"
40 #define on_boot_gcode_checksum CHECKSUM("on_boot_gcode")
41 #define on_boot_gcode_enable_checksum CHECKSUM("on_boot_gcode_enable")
42 #define after_suspend_gcode_checksum CHECKSUM("after_suspend_gcode")
43 #define before_resume_gcode_checksum CHECKSUM("before_resume_gcode")
44 #define leave_heaters_on_suspend_checksum CHECKSUM("leave_heaters_on_suspend")
50 this->playing_file
= false;
51 this->current_file_handler
= nullptr;
53 this->elapsed_secs
= 0;
54 this->reply_stream
= nullptr;
55 this->suspended
= false;
56 this->suspend_loops
= 0;
59 void Player::on_module_loaded()
61 this->register_for_event(ON_CONSOLE_LINE_RECEIVED
);
62 this->register_for_event(ON_MAIN_LOOP
);
63 this->register_for_event(ON_SECOND_TICK
);
64 this->register_for_event(ON_GET_PUBLIC_DATA
);
65 this->register_for_event(ON_SET_PUBLIC_DATA
);
66 this->register_for_event(ON_GCODE_RECEIVED
);
68 this->on_boot_gcode
= THEKERNEL
->config
->value(on_boot_gcode_checksum
)->by_default("/sd/on_boot.gcode")->as_string();
69 this->on_boot_gcode_enable
= THEKERNEL
->config
->value(on_boot_gcode_enable_checksum
)->by_default(true)->as_bool();
71 this->after_suspend_gcode
= THEKERNEL
->config
->value(after_suspend_gcode_checksum
)->by_default("")->as_string();
72 this->before_resume_gcode
= THEKERNEL
->config
->value(before_resume_gcode_checksum
)->by_default("")->as_string();
73 std::replace( this->after_suspend_gcode
.begin(), this->after_suspend_gcode
.end(), '_', ' '); // replace _ with space
74 std::replace( this->before_resume_gcode
.begin(), this->before_resume_gcode
.end(), '_', ' '); // replace _ with space
75 this->leave_heaters_on
= THEKERNEL
->config
->value(leave_heaters_on_suspend_checksum
)->by_default(false)->as_bool();
78 void Player::on_second_tick(void *)
80 if(this->playing_file
) this->elapsed_secs
++;
83 // extract any options found on line, terminates args at the space before the first option (-v)
84 // eg this is a file.gcode -v
85 // will return -v and set args to this is a file.gcode
86 string
Player::extract_options(string
& args
)
89 size_t pos
= args
.find(" -");
90 if(pos
!= string::npos
) {
91 opts
= args
.substr(pos
);
92 args
= args
.substr(0, pos
);
98 void Player::on_gcode_received(void *argument
)
100 Gcode
*gcode
= static_cast<Gcode
*>(argument
);
101 string args
= get_arguments(gcode
->get_command());
103 if (gcode
->m
== 21) { // Dummy code; makes Octoprint happy -- supposed to initialize SD card
105 gcode
->stream
->printf("SD card ok\r\n");
107 } else if (gcode
->m
== 23) { // select file
108 this->filename
= "/sd/" + args
; // filename is whatever is in args
109 this->current_stream
= &(StreamOutput::NullStream
);
111 if(this->current_file_handler
!= NULL
) {
112 this->playing_file
= false;
113 fclose(this->current_file_handler
);
115 this->current_file_handler
= fopen( this->filename
.c_str(), "r");
117 if(this->current_file_handler
== NULL
) {
118 gcode
->stream
->printf("file.open failed: %s\r\n", this->filename
.c_str());
123 int result
= fseek(this->current_file_handler
, 0, SEEK_END
);
127 this->file_size
= ftell(this->current_file_handler
);
128 fseek(this->current_file_handler
, 0, SEEK_SET
);
130 gcode
->stream
->printf("File opened:%s Size:%ld\r\n", this->filename
.c_str(), this->file_size
);
131 gcode
->stream
->printf("File selected\r\n");
135 this->played_cnt
= 0;
136 this->elapsed_secs
= 0;
138 } else if (gcode
->m
== 24) { // start print
139 if (this->current_file_handler
!= NULL
) {
140 this->playing_file
= true;
141 // this would be a problem if the stream goes away before the file has finished,
142 // so we attach it to the kernel stream, however network connections from pronterface
143 // do not connect to the kernel streams so won't see this FIXME
144 this->reply_stream
= THEKERNEL
->streams
;
147 } else if (gcode
->m
== 25) { // pause print
148 this->playing_file
= false;
150 } else if (gcode
->m
== 26) { // Reset print. Slightly different than M26 in Marlin and the rest
151 if(this->current_file_handler
!= NULL
) {
152 string currentfn
= this->filename
.c_str();
153 unsigned long old_size
= this->file_size
;
156 abort_command("", gcode
->stream
);
158 if(!currentfn
.empty()) {
159 // reload the last file opened
160 this->current_file_handler
= fopen(currentfn
.c_str() , "r");
162 if(this->current_file_handler
== NULL
) {
163 gcode
->stream
->printf("file.open failed: %s\r\n", currentfn
.c_str());
165 this->filename
= currentfn
;
166 this->file_size
= old_size
;
167 this->current_stream
= &(StreamOutput::NullStream
);
171 gcode
->stream
->printf("No file loaded\r\n");
174 } else if (gcode
->m
== 27) { // report print progress, in format used by Marlin
175 progress_command("-b", gcode
->stream
);
177 } else if (gcode
->m
== 32) { // select file and start print
179 this->filename
= "/sd/" + args
; // filename is whatever is in args including spaces
180 this->current_stream
= &(StreamOutput::NullStream
);
182 if(this->current_file_handler
!= NULL
) {
183 this->playing_file
= false;
184 fclose(this->current_file_handler
);
187 this->current_file_handler
= fopen( this->filename
.c_str(), "r");
188 if(this->current_file_handler
== NULL
) {
189 gcode
->stream
->printf("file.open failed: %s\r\n", this->filename
.c_str());
191 this->playing_file
= true;
194 int result
= fseek(this->current_file_handler
, 0, SEEK_END
);
198 file_size
= ftell(this->current_file_handler
);
199 fseek(this->current_file_handler
, 0, SEEK_SET
);
203 this->played_cnt
= 0;
204 this->elapsed_secs
= 0;
206 } else if (gcode
->m
== 600) { // suspend print, Not entirely Marlin compliant
207 this->suspend_command("", gcode
->stream
);
209 } else if (gcode
->m
== 601) { // resume print
210 this->resume_command("", gcode
->stream
);
215 // When a new line is received, check if it is a command, and if it is, act upon it
216 void Player::on_console_line_received( void *argument
)
218 if(THEKERNEL
->is_halted()) return; // if in halted state ignore any commands
220 SerialMessage new_message
= *static_cast<SerialMessage
*>(argument
);
222 // ignore comments and blank lines and if this is a G code then also ignore it
223 char first_char
= new_message
.message
[0];
224 if(strchr(";( \n\rGMTN", first_char
) != NULL
) return;
226 string possible_command
= new_message
.message
;
227 string cmd
= shift_parameter(possible_command
);
229 //new_message.stream->printf("Received %s\r\n", possible_command.c_str());
231 // Act depending on command
233 this->play_command( possible_command
, new_message
.stream
);
234 }else if (cmd
== "progress"){
235 this->progress_command( possible_command
, new_message
.stream
);
236 }else if (cmd
== "abort") {
237 this->abort_command( possible_command
, new_message
.stream
);
238 }else if (cmd
== "suspend") {
239 this->suspend_command( possible_command
, new_message
.stream
);
240 }else if (cmd
== "resume") {
241 this->resume_command( possible_command
, new_message
.stream
);
245 // Play a gcode file by considering each line as if it was received on the serial console
246 void Player::play_command( string parameters
, StreamOutput
*stream
)
248 // extract any options from the line and terminate the line there
249 string options
= extract_options(parameters
);
250 // Get filename which is the entire parameter line upto any options found or entire line
251 this->filename
= absolute_from_relative(parameters
);
253 if(this->playing_file
|| this->suspended
) {
254 stream
->printf("Currently printing, abort print first\r\n");
258 if(this->current_file_handler
!= NULL
) { // must have been a paused print
259 fclose(this->current_file_handler
);
262 this->current_file_handler
= fopen( this->filename
.c_str(), "r");
263 if(this->current_file_handler
== NULL
) {
264 stream
->printf("File not found: %s\r\n", this->filename
.c_str());
268 stream
->printf("Playing %s\r\n", this->filename
.c_str());
270 this->playing_file
= true;
272 // Output to the current stream if we were passed the -v ( verbose ) option
273 if( options
.find_first_of("Vv") == string::npos
) {
274 this->current_stream
= &(StreamOutput::NullStream
);
276 // we send to the kernels stream as it cannot go away
277 this->current_stream
= THEKERNEL
->streams
;
281 int result
= fseek(this->current_file_handler
, 0, SEEK_END
);
283 stream
->printf("WARNING - Could not get file size\r\n");
286 file_size
= ftell(this->current_file_handler
);
287 fseek(this->current_file_handler
, 0, SEEK_SET
);
288 stream
->printf(" File size %ld\r\n", file_size
);
290 this->played_cnt
= 0;
291 this->elapsed_secs
= 0;
294 void Player::progress_command( string parameters
, StreamOutput
*stream
)
298 string options
= shift_parameter( parameters
);
299 bool sdprinting
= options
.find_first_of("Bb") != string::npos
;
301 if(!playing_file
&& current_file_handler
!= NULL
) {
303 stream
->printf("SD printing byte %lu/%lu\r\n", played_cnt
, file_size
);
305 stream
->printf("SD print is paused at %lu/%lu\r\n", played_cnt
, file_size
);
308 } else if(!playing_file
) {
309 stream
->printf("Not currently playing\r\n");
314 unsigned long est
= 0;
315 if(this->elapsed_secs
> 10) {
316 unsigned long bytespersec
= played_cnt
/ this->elapsed_secs
;
318 est
= (file_size
- played_cnt
) / bytespersec
;
321 unsigned int pcnt
= (file_size
- (file_size
- played_cnt
)) * 100 / file_size
;
322 // If -b or -B is passed, report in the format used by Marlin and the others.
324 stream
->printf("file: %s, %u %% complete, elapsed time: %lu s", this->filename
.c_str(), pcnt
, this->elapsed_secs
);
326 stream
->printf(", est time: %lu s", est
);
328 stream
->printf("\r\n");
330 stream
->printf("SD printing byte %lu/%lu\r\n", played_cnt
, file_size
);
334 stream
->printf("File size is unknown\r\n");
338 void Player::abort_command( string parameters
, StreamOutput
*stream
)
340 if(!playing_file
&& current_file_handler
== NULL
) {
341 stream
->printf("Not currently playing\r\n");
345 playing_file
= false;
349 this->current_stream
= NULL
;
350 fclose(current_file_handler
);
351 current_file_handler
= NULL
;
352 if(parameters
.empty()) {
353 // clear out the block queue, will wait until queue is empty
354 // MUST be called in on_main_loop to make sure there are no blocked main loops waiting to put something on the queue
355 THEKERNEL
->conveyor
->flush_queue();
357 // now the position will think it is at the last received pos, so we need to do FK to get the actuator position and reset the current position
358 THEKERNEL
->robot
->reset_position_from_current_actuator_position();
360 stream
->printf("Aborted playing or paused file\r\n");
363 void Player::on_main_loop(void *argument
)
365 if(suspended
&& suspend_loops
> 0) {
366 // if we are suspended we need to allow main loop to cycle a few times then finish off the suspend processing
367 if(--suspend_loops
== 0) {
373 if( !this->booted
) {
375 if( this->on_boot_gcode_enable
) {
376 this->play_command(this->on_boot_gcode
, THEKERNEL
->serial
);
378 //THEKERNEL->serial->printf("On boot gcode disabled! skipping...\n");
382 if( this->playing_file
) {
383 if(THEKERNEL
->is_halted()) {
384 abort_command("1", &(StreamOutput::NullStream
));
388 char buf
[130]; // lines upto 128 characters are allowed, anything longer is discarded
389 bool discard
= false;
391 while(fgets(buf
, sizeof(buf
), this->current_file_handler
) != NULL
) {
392 int len
= strlen(buf
);
393 if(len
== 0) continue; // empty line? should not be possible
394 if(buf
[len
- 1] == '\n' || feof(this->current_file_handler
)) {
395 if(discard
) { // we are discarding a long line
399 if(len
== 1) continue; // empty line
401 this->current_stream
->printf("%s", buf
);
402 struct SerialMessage message
;
403 message
.message
= buf
;
404 message
.stream
= this->current_stream
;
406 // waits for the queue to have enough room
407 THEKERNEL
->call_event(ON_CONSOLE_LINE_RECEIVED
, &message
);
409 return; // we feed one line per main loop
413 this->current_stream
->printf("Warning: Discarded long line\n");
418 this->playing_file
= false;
422 fclose(this->current_file_handler
);
423 current_file_handler
= NULL
;
424 this->current_stream
= NULL
;
426 if(this->reply_stream
!= NULL
) {
427 // if we were printing from an M command from pronterface we need to send this back
428 this->reply_stream
->printf("Done printing file\r\n");
429 this->reply_stream
= NULL
;
434 void Player::on_get_public_data(void *argument
)
436 PublicDataRequest
*pdr
= static_cast<PublicDataRequest
*>(argument
);
438 if(!pdr
->starts_with(player_checksum
)) return;
440 if(pdr
->second_element_is(is_playing_checksum
) || pdr
->second_element_is(is_suspended_checksum
)) {
441 static bool bool_data
;
442 bool_data
= pdr
->second_element_is(is_playing_checksum
) ? this->playing_file
: this->suspended
;
443 pdr
->set_data_ptr(&bool_data
);
446 } else if(pdr
->second_element_is(get_progress_checksum
)) {
447 static struct pad_progress p
;
448 if(file_size
> 0 && playing_file
) {
449 p
.elapsed_secs
= this->elapsed_secs
;
450 p
.percent_complete
= (this->file_size
- (this->file_size
- this->played_cnt
)) * 100 / this->file_size
;
451 p
.filename
= this->filename
;
452 pdr
->set_data_ptr(&p
);
458 void Player::on_set_public_data(void *argument
)
460 PublicDataRequest
*pdr
= static_cast<PublicDataRequest
*>(argument
);
462 if(!pdr
->starts_with(player_checksum
)) return;
464 if(pdr
->second_element_is(abort_play_checksum
)) {
465 abort_command("", &(StreamOutput::NullStream
));
471 Suspend a print in progress
472 1. send pause to upstream host, or pause if printing from sd
473 1a. loop on_main_loop several times to clear any buffered commmands
474 2. wait for empty queue
475 3. save the current position, extruder position, temperatures - any state that would need to be restored
476 4. retract by specifed amount either on command line or in config
478 6. optionally run after_suspend gcode (either in config or on command line)
480 User may jog or remove and insert filament at this point, extruding or retracting as needed
483 void Player::suspend_command(string parameters
, StreamOutput
*stream
)
486 stream
->printf("Already suspended\n");
490 stream
->printf("Suspending print, waiting for queue to empty...\n");
493 if( this->playing_file
) {
495 this->playing_file
= false;
496 this->was_playing_file
= true;
498 // send pause to upstream host, we send it on all ports as we don't know which it is on
499 THEKERNEL
->streams
->printf("// action:pause\r\n");
500 this->was_playing_file
= false;
503 // we need to allow main loop to cycle a few times to clear any buffered commands in the serial streams etc
505 suspend_stream
= stream
;
508 // this completes the suspend
509 void Player::suspend_part2()
511 // wait for queue to empty
512 THEKERNEL
->conveyor
->wait_for_empty_queue();
514 suspend_stream
->printf("// Saving current state...\n");
516 // save current XYZ position
517 THEKERNEL
->robot
->get_axis_position(this->saved_position
);
519 // save current extruder state
520 PublicData::set_value( extruder_checksum
, save_state_checksum
, nullptr );
523 this->saved_inch_mode
= THEKERNEL
->robot
->inch_mode
;
524 this->saved_absolute_mode
= THEKERNEL
->robot
->absolute_mode
;
525 this->saved_feed_rate
= THEKERNEL
->robot
->get_feed_rate() * 60; // save in mm/min
527 // TODO retract by optional amount...
529 this->saved_temperatures
.clear();
530 if(!this->leave_heaters_on
) {
531 // save current temperatures, get a vector of all the controllers data
532 std::vector
<struct pad_temperature
> controllers
;
533 bool ok
= PublicData::get_value(temperature_control_checksum
, poll_controls_checksum
, &controllers
);
535 // query each heater and save the target temperature if on
536 for (auto &c
: controllers
) {
537 // TODO see if in exclude list
538 if(c
.target_temperature
> 0) {
539 this->saved_temperatures
[c
.id
]= c
.target_temperature
;
544 // turn off heaters that were on
545 for(auto& h
: this->saved_temperatures
) {
547 PublicData::set_value( temperature_control_checksum
, h
.first
, &t
);
551 // execute optional gcode if defined
552 if(!after_suspend_gcode
.empty()) {
553 struct SerialMessage message
;
554 message
.message
= after_suspend_gcode
;
555 message
.stream
= &(StreamOutput::NullStream
);
556 THEKERNEL
->call_event(ON_CONSOLE_LINE_RECEIVED
, &message
);
559 suspend_stream
->printf("// Print Suspended, enter resume to continue printing\n");
563 resume the suspended print
564 1. restore the temperatures and wait for them to get up to temp
565 2. optionally run before_resume gcode if specified
566 3. restore the position it was at and E and any other saved state
567 4. resume sd print or send resume upstream
569 void Player::resume_command(string parameters
, StreamOutput
*stream
)
572 stream
->printf("Not suspended\n");
576 stream
->printf("resuming print...\n");
578 // set heaters to saved temps
579 for(auto& h
: this->saved_temperatures
) {
581 PublicData::set_value( temperature_control_checksum
, h
.first
, &t
);
584 // wait for them to reach temp
585 if(!this->saved_temperatures
.empty()) {
586 stream
->printf("Waiting for heaters...\n");
588 uint32_t tus
= us_ticker_read(); // mbed call
593 if((us_ticker_read() - tus
) >= 1000000) { // print every 1 second
595 tus
= us_ticker_read(); // mbed call
598 for(auto& h
: this->saved_temperatures
) {
599 struct pad_temperature temp
;
600 if(PublicData::get_value( temperature_control_checksum
, current_temperature_checksum
, h
.first
, &temp
)) {
602 stream
->printf("%s:%3.1f /%3.1f @%d ", temp
.designator
.c_str(), temp
.current_temperature
, ((temp
.target_temperature
== -1) ? 0.0 : temp
.target_temperature
), temp
.pwm
);
603 wait
= wait
|| (temp
.current_temperature
< h
.second
);
606 if(timeup
) stream
->printf("\n");
609 THEKERNEL
->call_event(ON_IDLE
, this);
613 // execute optional gcode if defined
614 if(!before_resume_gcode
.empty()) {
615 stream
->printf("Executing before resume gcode...\n");
616 struct SerialMessage message
;
617 message
.message
= before_resume_gcode
;
618 message
.stream
= &(StreamOutput::NullStream
);
619 THEKERNEL
->call_event(ON_CONSOLE_LINE_RECEIVED
, &message
);
623 stream
->printf("Restoring saved XYZ positions and state...\n");
624 THEKERNEL
->robot
->inch_mode
= saved_inch_mode
;
625 THEKERNEL
->robot
->absolute_mode
= saved_absolute_mode
;
628 int n
= snprintf(buf
, sizeof(buf
), "G1 X%f Y%f Z%f F%f", saved_position
[0], saved_position
[1], saved_position
[2], saved_feed_rate
);
630 Gcode
gcode(g
, &(StreamOutput::NullStream
));
631 THEKERNEL
->call_event(ON_GCODE_RECEIVED
, &gcode
);
634 // restore extruder state
635 PublicData::set_value( extruder_checksum
, restore_state_checksum
, nullptr );
637 stream
->printf("Resuming print\n");
639 if(this->was_playing_file
) {
640 this->playing_file
= true;
642 // Send resume to host
643 THEKERNEL
->streams
->printf("// action:resume\r\n");
647 this->saved_temperatures
.clear();