change the temperature public data access to pass in the pad_temp for the result...
[clinton/Smoothieware.git] / src / modules / utils / player / Player.cpp
index 6a1d38a..677a818 100644 (file)
@@ -8,6 +8,7 @@
 #include "Player.h"
 
 #include "libs/Kernel.h"
+#include "Robot.h"
 #include "libs/nuts_bolts.h"
 #include "libs/utils.h"
 #include "SerialConsole.h"
 #include "modules/robot/Conveyor.h"
 #include "DirHandle.h"
 #include "PublicDataRequest.h"
+#include "PublicData.h"
 #include "PlayerPublicAccess.h"
+#include "TemperatureControlPublicAccess.h"
+#include "TemperatureControlPool.h"
+#include "ExtruderPublicAccess.h"
 
-#define on_boot_gcode_checksum          CHECKSUM("on_boot_gcode")
-#define on_boot_gcode_enable_checksum   CHECKSUM("on_boot_gcode_enable")
+#include <cstddef>
+#include <cmath>
+#include <algorithm>
+
+#include "mbed.h"
+
+#define on_boot_gcode_checksum            CHECKSUM("on_boot_gcode")
+#define on_boot_gcode_enable_checksum     CHECKSUM("on_boot_gcode_enable")
+#define after_suspend_gcode_checksum      CHECKSUM("after_suspend_gcode")
+#define before_resume_gcode_checksum      CHECKSUM("before_resume_gcode")
+#define leave_heaters_on_suspend_checksum CHECKSUM("leave_heaters_on_suspend")
 
 extern SDFAT mounter;
 
-void Player::on_module_loaded()
+Player::Player()
 {
     this->playing_file = false;
-    this->current_file_handler = NULL;
+    this->current_file_handler = nullptr;
     this->booted = false;
+    this->elapsed_secs = 0;
+    this->reply_stream = nullptr;
+    this->halted= false;
+    this->suspended= false;
+    this->suspend_loops= 0;
+}
+
+void Player::on_module_loaded()
+{
     this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
     this->register_for_event(ON_MAIN_LOOP);
     this->register_for_event(ON_SECOND_TICK);
     this->register_for_event(ON_GET_PUBLIC_DATA);
     this->register_for_event(ON_SET_PUBLIC_DATA);
     this->register_for_event(ON_GCODE_RECEIVED);
+    this->register_for_event(ON_HALT);
 
     this->on_boot_gcode = THEKERNEL->config->value(on_boot_gcode_checksum)->by_default("/sd/on_boot.gcode")->as_string();
     this->on_boot_gcode_enable = THEKERNEL->config->value(on_boot_gcode_enable_checksum)->by_default(true)->as_bool();
-    this->elapsed_secs = 0;
-    this->reply_stream = NULL;
+
+    this->after_suspend_gcode = THEKERNEL->config->value(after_suspend_gcode_checksum)->by_default("")->as_string();
+    this->before_resume_gcode = THEKERNEL->config->value(before_resume_gcode_checksum)->by_default("")->as_string();
+    std::replace( this->after_suspend_gcode.begin(), this->after_suspend_gcode.end(), '_', ' '); // replace _ with space
+    std::replace( this->before_resume_gcode.begin(), this->before_resume_gcode.end(), '_', ' '); // replace _ with space
+    this->leave_heaters_on = THEKERNEL->config->value(leave_heaters_on_suspend_checksum)->by_default(false)->as_bool();
+}
+
+void Player::on_halt(void *arg)
+{
+    halted= (arg == nullptr);
 }
 
 void Player::on_second_tick(void *)
 {
-    if (!THEKERNEL->pauser->paused()) this->elapsed_secs++;
+    if(this->playing_file) this->elapsed_secs++;
 }
 
 // extract any options found on line, terminates args at the space before the first option (-v)
@@ -75,12 +108,10 @@ void Player::on_gcode_received(void *argument)
     string args = get_arguments(gcode->get_command());
     if (gcode->has_m) {
         if (gcode->m == 21) { // Dummy code; makes Octoprint happy -- supposed to initialize SD card
-            gcode->mark_as_taken();
             mounter.remount();
             gcode->stream->printf("SD card ok\r\n");
 
         } else if (gcode->m == 23) { // select file
-            gcode->mark_as_taken();
             this->filename = "/sd/" + args; // filename is whatever is in args
             this->current_stream = &(StreamOutput::NullStream);
 
@@ -112,7 +143,6 @@ void Player::on_gcode_received(void *argument)
             this->elapsed_secs = 0;
 
         } else if (gcode->m == 24) { // start print
-            gcode->mark_as_taken();
             if (this->current_file_handler != NULL) {
                 this->playing_file = true;
                 // this would be a problem if the stream goes away before the file has finished,
@@ -122,11 +152,9 @@ void Player::on_gcode_received(void *argument)
             }
 
         } else if (gcode->m == 25) { // pause print
-            gcode->mark_as_taken();
             this->playing_file = false;
 
         } else if (gcode->m == 26) { // Reset print. Slightly different than M26 in Marlin and the rest
-            gcode->mark_as_taken();
             if(this->current_file_handler != NULL) {
                 string currentfn = this->filename.c_str();
                 unsigned long old_size = this->file_size;
@@ -146,17 +174,14 @@ void Player::on_gcode_received(void *argument)
                         this->current_stream = &(StreamOutput::NullStream);
                     }
                 }
-
             } else {
                 gcode->stream->printf("No file loaded\r\n");
             }
 
         } else if (gcode->m == 27) { // report print progress, in format used by Marlin
-            gcode->mark_as_taken();
             progress_command("-b", gcode->stream);
 
         } else if (gcode->m == 32) { // select file and start print
-            gcode->mark_as_taken();
             // Get filename
             this->filename = "/sd/" + args; // filename is whatever is in args including spaces
             this->current_stream = &(StreamOutput::NullStream);
@@ -171,7 +196,25 @@ void Player::on_gcode_received(void *argument)
                 gcode->stream->printf("file.open failed: %s\r\n", this->filename.c_str());
             } else {
                 this->playing_file = true;
+
+                // get size of file
+                int result = fseek(this->current_file_handler, 0, SEEK_END);
+                if (0 != result) {
+                        file_size = 0;
+                } else {
+                        file_size = ftell(this->current_file_handler);
+                        fseek(this->current_file_handler, 0, SEEK_SET);
+                }
             }
+
+            this->played_cnt = 0;
+            this->elapsed_secs = 0;
+
+        } else if (gcode->m == 600) { // suspend print, Not entirely Marlin compliant
+            this->suspend_command("", &(StreamOutput::NullStream));
+
+        } else if (gcode->m == 601) { // resume print
+            this->resume_command("", &(StreamOutput::NullStream));
         }
     }
 }
@@ -179,6 +222,8 @@ void Player::on_gcode_received(void *argument)
 // When a new line is received, check if it is a command, and if it is, act upon it
 void Player::on_console_line_received( void *argument )
 {
+    if(halted) return; // if in halted state ignore any commands
+
     SerialMessage new_message = *static_cast<SerialMessage *>(argument);
 
     // ignore comments and blank lines and if this is a G code then also ignore it
@@ -195,8 +240,13 @@ void Player::on_console_line_received( void *argument )
         this->play_command( possible_command, new_message.stream );
     }else if (cmd == "progress"){
         this->progress_command( possible_command, new_message.stream );
-    }else if (cmd == "abort")
+    }else if (cmd == "abort") {
         this->abort_command( possible_command, new_message.stream );
+    }else if (cmd == "suspend") {
+        this->suspend_command( possible_command, new_message.stream );
+    }else if (cmd == "resume") {
+        this->resume_command( possible_command, new_message.stream );
+    }
 }
 
 // Play a gcode file by considering each line as if it was received on the serial console
@@ -207,7 +257,7 @@ void Player::play_command( string parameters, StreamOutput *stream )
     // Get filename which is the entire parameter line upto any options found or entire line
     this->filename = absolute_from_relative(parameters);
 
-    if(this->playing_file) {
+    if(this->playing_file || this->suspended) {
         stream->printf("Currently printing, abort print first\r\n");
         return;
     }
@@ -278,7 +328,7 @@ void Player::progress_command( string parameters, StreamOutput *stream )
         unsigned int pcnt = (file_size - (file_size - played_cnt)) * 100 / file_size;
         // If -b or -B is passed, report in the format used by Marlin and the others.
         if (!sdprinting) {
-            stream->printf("%u %% complete, elapsed time: %lu s", pcnt, this->elapsed_secs);
+            stream->printf("file: %s, %u %% complete, elapsed time: %lu s", this->filename.c_str(), pcnt, this->elapsed_secs);
             if(est > 0) {
                 stream->printf(", est time: %lu s",  est);
             }
@@ -298,6 +348,7 @@ void Player::abort_command( string parameters, StreamOutput *stream )
         stream->printf("Not currently playing\r\n");
         return;
     }
+    suspended= false;
     playing_file = false;
     played_cnt = 0;
     file_size = 0;
@@ -305,11 +356,27 @@ void Player::abort_command( string parameters, StreamOutput *stream )
     this->current_stream = NULL;
     fclose(current_file_handler);
     current_file_handler = NULL;
+    if(parameters.empty()) {
+        // clear out the block queue, will wait until queue is empty
+        // MUST be called in on_main_loop to make sure there are no blocked main loops waiting to put something on the queue
+        THEKERNEL->conveyor->flush_queue();
+
+        // 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
+        THEKERNEL->robot->reset_position_from_current_actuator_position();
+    }
     stream->printf("Aborted playing or paused file\r\n");
 }
 
 void Player::on_main_loop(void *argument)
 {
+    if(suspended && suspend_loops > 0) {
+        // if we are suspended we need to allow main loop to cycle a few times then finish off the suspend processing
+        if(--suspend_loops == 0) {
+            suspend_part2();
+            return;
+        }
+    }
+
     if( !this->booted ) {
         this->booted = true;
         if( this->on_boot_gcode_enable ) {
@@ -320,6 +387,11 @@ void Player::on_main_loop(void *argument)
     }
 
     if( this->playing_file ) {
+        if(halted) {
+            abort_command("1", &(StreamOutput::NullStream));
+            return;
+        }
+
         char buf[130]; // lines upto 128 characters are allowed, anything longer is discarded
         bool discard = false;
 
@@ -372,9 +444,9 @@ void Player::on_get_public_data(void *argument)
 
     if(!pdr->starts_with(player_checksum)) return;
 
-    if(pdr->second_element_is(is_playing_checksum)) {
+    if(pdr->second_element_is(is_playing_checksum) || pdr->second_element_is(is_suspended_checksum)) {
         static bool bool_data;
-        bool_data = this->playing_file;
+        bool_data = pdr->second_element_is(is_playing_checksum) ? this->playing_file : this->suspended;
         pdr->set_data_ptr(&bool_data);
         pdr->set_taken();
 
@@ -401,3 +473,184 @@ void Player::on_set_public_data(void *argument)
         pdr->set_taken();
     }
 }
+
+/**
+Suspend a print in progress
+1. send pause to upstream host, or pause if printing from sd
+1a. loop on_main_loop several times to clear any buffered commmands
+2. wait for empty queue
+3. save the current position, extruder position, temperatures - any state that would need to be restored
+4. retract by specifed amount either on command line or in config
+5. turn off heaters.
+6. optionally run after_suspend gcode (either in config or on command line)
+
+User may jog or remove and insert filament at this point, extruding or retracting as needed
+
+*/
+void Player::suspend_command(string parameters, StreamOutput *stream )
+{
+    if(suspended) {
+        stream->printf("Already suspended\n");
+        return;
+    }
+
+    stream->printf("ok Suspending print, waiting for queue to empty...\n");
+
+    suspended= true;
+    if( this->playing_file ) {
+        // pause an sd print
+        this->playing_file = false;
+        this->was_playing_file= true;
+    }else{
+        // send pause to upstream host, we send it on all ports as we don't know which it is on
+        THEKERNEL->streams->printf("// action:pause\r\n");
+        this->was_playing_file= false;
+    }
+
+    // we need to allow main loop to cycle a few times to clear any buffered commands in the serial streams etc
+    suspend_loops= 10;
+    suspend_stream= stream;
+}
+
+// this completes the suspend
+void Player::suspend_part2()
+{
+    // wait for queue to empty
+    THEKERNEL->conveyor->wait_for_empty_queue();
+
+    suspend_stream->printf("Saving current state...\n");
+
+    // save current XYZ position
+    THEKERNEL->robot->get_axis_position(this->saved_position);
+
+    // save current extruder state
+    PublicData::set_value( extruder_checksum, save_state_checksum, nullptr );
+
+    // save state
+    this->saved_inch_mode= THEKERNEL->robot->inch_mode;
+    this->saved_absolute_mode= THEKERNEL->robot->absolute_mode;
+    this->saved_feed_rate= THEKERNEL->robot->get_feed_rate() * 60; // save in mm/min
+
+    // TODO retract by optional amount...
+
+    this->saved_temperatures.clear();
+    if(!this->leave_heaters_on) {
+        // save current temperatures, get a vector of all the controllers data
+        std::vector<struct pad_temperature*> *controllers;
+        bool ok = PublicData::get_value(temperature_control_checksum, poll_controls_checksum, (void**)&controllers);
+        if (ok) {
+            // query each heater and save the target temperature if on
+            for (auto &c : *controllers) {
+                // TODO see if in exclude list
+                if(c->target_temperature > 0) {
+                    this->saved_temperatures[c->id]= c->target_temperature;
+                }
+            }
+        }
+
+        // turn off heaters that were on
+        for(auto& h : this->saved_temperatures) {
+            float t= 0;
+            PublicData::set_value( temperature_control_checksum, h.first, &t );
+        }
+    }
+
+    // execute optional gcode if defined
+    if(!after_suspend_gcode.empty()) {
+        struct SerialMessage message;
+        message.message = after_suspend_gcode;
+        message.stream = &(StreamOutput::NullStream);
+        THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
+    }
+
+    suspend_stream->printf("Print Suspended, enter resume to continue printing\n");
+}
+
+/**
+resume the suspended print
+1. restore the temperatures and wait for them to get up to temp
+2. optionally run before_resume gcode if specified
+3. restore the position it was at and E and any other saved state
+4. resume sd print or send resume upstream
+*/
+void Player::resume_command(string parameters, StreamOutput *stream )
+{
+    if(!suspended) {
+        stream->printf("Not suspended\n");
+        return;
+    }
+
+    stream->printf("ok resuming print...\n");
+
+    // set heaters to saved temps
+    for(auto& h : this->saved_temperatures) {
+        float t= h.second;
+        PublicData::set_value( temperature_control_checksum, h.first, &t );
+    }
+
+    // wait for them to reach temp
+    if(!this->saved_temperatures.empty()) {
+        stream->printf("Waiting for heaters...\n");
+        bool wait= true;
+        uint32_t tus= us_ticker_read(); // mbed call
+        while(wait) {
+            wait= false;
+
+            bool timeup= false;
+            if((us_ticker_read() - tus) >= 1000000) { // print every 1 second
+                timeup= true;
+                tus= us_ticker_read(); // mbed call
+            }
+
+            for(auto& h : this->saved_temperatures) {
+                struct pad_temperature temp;
+                if(PublicData::get_value( temperature_control_checksum, h.first, current_temperature_checksum, &temp )) {
+                    if(timeup)
+                        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);
+                    wait= wait || (temp.current_temperature < h.second);
+                }
+            }
+            if(timeup) stream->printf("\n");
+
+            if(wait)
+                THEKERNEL->call_event(ON_IDLE, this);
+        }
+    }
+
+    // execute optional gcode if defined
+    if(!before_resume_gcode.empty()) {
+        stream->printf("Executing before resume gcode...\n");
+        struct SerialMessage message;
+        message.message = before_resume_gcode;
+        message.stream = &(StreamOutput::NullStream);
+        THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
+    }
+
+    // Restore position
+    stream->printf("Restoring saved XYZ positions and state...\n");
+    THEKERNEL->robot->inch_mode= saved_inch_mode;
+    THEKERNEL->robot->absolute_mode= saved_absolute_mode;
+    char buf[128];
+    {
+        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);
+        string g(buf, n);
+        Gcode gcode(g, &(StreamOutput::NullStream));
+        THEKERNEL->call_event(ON_GCODE_RECEIVED, &gcode );
+    }
+
+    // restore extruder state
+    PublicData::set_value( extruder_checksum, restore_state_checksum, nullptr );
+
+    stream->printf("Resuming print\n");
+
+    if(this->was_playing_file) {
+        this->playing_file = true;
+    }else{
+        // Send resume to host
+        THEKERNEL->streams->printf("// action:resume\r\n");
+    }
+
+    // clean up
+    this->saved_temperatures.clear();
+    suspended= false;
+}