mmu2.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. #include "mmu2.h"
  2. #include "mmu2_error_converter.h"
  3. #include "mmu2_fsensor.h"
  4. #include "mmu2_log.h"
  5. #include "mmu2_power.h"
  6. #include "mmu2_progress_converter.h"
  7. #include "mmu2_reporting.h"
  8. #include "Marlin.h"
  9. #include "language.h"
  10. #include "messages.h"
  11. #include "sound.h"
  12. #include "stepper.h"
  13. #include "strlen_cx.h"
  14. #include "temperature.h"
  15. #include "ultralcd.h"
  16. #include "cardreader.h" // for IS_SD_PRINTING
  17. #include "SpoolJoin.h"
  18. // As of FW 3.12 we only support building the FW with only one extruder, all the multi-extruder infrastructure will be removed.
  19. // Saves at least 800B of code size
  20. static_assert(EXTRUDERS==1);
  21. // Settings for filament load / unload from the LCD menu.
  22. // This is for Prusa MK3-style extruders. Customize for your hardware.
  23. #define MMU2_FILAMENTCHANGE_EJECT_FEED 80.0
  24. #define NOZZLE_PARK_XY_FEEDRATE 50
  25. #define NOZZLE_PARK_Z_FEEDRATE 15
  26. // Nominal distance from the extruder gear to the nozzle tip is 87mm
  27. // However, some slipping may occur and we need separate distances for
  28. // LoadToNozzle and ToolChange.
  29. // - +5mm seemed good for LoadToNozzle,
  30. // - but too much (made blobs) for a ToolChange
  31. static constexpr float MMU2_LOAD_TO_NOZZLE_LENGTH = 87.0F + 5.0F;
  32. // As discussed with our PrusaSlicer profile specialist
  33. // - ToolChange shall not try to push filament into the very tip of the nozzle
  34. // to have some space for additional G-code to tune the extruded filament length
  35. // in the profile
  36. static constexpr float MMU2_TOOL_CHANGE_LOAD_LENGTH = 30.0F;
  37. static constexpr float MMU2_LOAD_TO_NOZZLE_FEED_RATE = 20.0F; // mm/s
  38. static constexpr float MMU2_UNLOAD_TO_FINDA_FEED_RATE = 120.0F; // mm/s
  39. // The first the MMU does is initialise its axis. Meanwhile the E-motor will unload 20mm of filament in approx. 1 second.
  40. static constexpr float MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH = 20.0f; // mm
  41. static constexpr float MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE = 20.0f; // mm/s
  42. static constexpr uint8_t MMU2_NO_TOOL = 99;
  43. static constexpr uint32_t MMU_BAUD = 115200;
  44. struct E_Step {
  45. float extrude; ///< extrude distance in mm
  46. float feedRate; ///< feed rate in mm/s
  47. };
  48. static constexpr E_Step ramming_sequence[] PROGMEM = {
  49. { 1.0F, 1000.0F / 60.F},
  50. { 1.0F, 1500.0F / 60.F},
  51. { 2.0F, 2000.0F / 60.F},
  52. { 1.5F, 3000.0F / 60.F},
  53. { 2.5F, 4000.0F / 60.F},
  54. {-15.0F, 5000.0F / 60.F},
  55. {-14.0F, 1200.0F / 60.F},
  56. {-6.0F, 600.0F / 60.F},
  57. { 10.0F, 700.0F / 60.F},
  58. {-10.0F, 400.0F / 60.F},
  59. {-50.0F, 2000.0F / 60.F},
  60. };
  61. static constexpr E_Step load_to_nozzle_sequence[] PROGMEM = {
  62. { 10.0F, 810.0F / 60.F}, // feed rate = 13.5mm/s - Load fast until filament reach end of nozzle
  63. { 25.0F, 198.0F / 60.F}, // feed rate = 3.3mm/s - Load slower once filament is out of the nozzle
  64. };
  65. namespace MMU2 {
  66. void execute_extruder_sequence(const E_Step *sequence, int steps);
  67. template<typename F>
  68. void waitForHotendTargetTemp(uint16_t delay, F f){
  69. while (((degTargetHotend(active_extruder) - degHotend(active_extruder)) > 5)) {
  70. f();
  71. delay_keep_alive(delay);
  72. }
  73. }
  74. void WaitForHotendTargetTempBeep(){
  75. waitForHotendTargetTemp(3000, []{ Sound_MakeSound(e_SOUND_TYPE_StandardPrompt); } );
  76. }
  77. MMU2 mmu2;
  78. MMU2::MMU2()
  79. : is_mmu_error_monitor_active(false)
  80. , logic(&mmu2Serial)
  81. , extruder(MMU2_NO_TOOL)
  82. , tool_change_extruder(MMU2_NO_TOOL)
  83. , resume_position()
  84. , resume_hotend_temp(0)
  85. , logicStepLastStatus(StepStatus::Finished)
  86. , state(xState::Stopped)
  87. , mmu_print_saved(SavedState::None)
  88. , loadFilamentStarted(false)
  89. , unloadFilamentStarted(false)
  90. , loadingToNozzle(false)
  91. , inAutoRetry(false)
  92. , retryAttempts(MAX_RETRIES)
  93. {
  94. }
  95. void MMU2::Start() {
  96. #ifdef MMU_HWRESET
  97. WRITE(MMU_RST_PIN, 1);
  98. SET_OUTPUT(MMU_RST_PIN); // setup reset pin
  99. #endif //MMU_HWRESET
  100. mmu2Serial.begin(MMU_BAUD);
  101. PowerOn(); // I repurposed this to serve as our EEPROM disable toggle.
  102. Reset(ResetForm::ResetPin);
  103. mmu2Serial.flush(); // make sure the UART buffer is clear before starting communication
  104. extruder = MMU2_NO_TOOL;
  105. state = xState::Connecting;
  106. // start the communication
  107. logic.Start();
  108. ResetRetryAttempts();
  109. }
  110. void MMU2::Stop() {
  111. StopKeepPowered();
  112. PowerOff(); // This also disables the MMU in the EEPROM.
  113. }
  114. void MMU2::StopKeepPowered(){
  115. state = xState::Stopped;
  116. logic.Stop();
  117. mmu2Serial.close();
  118. }
  119. void MMU2::Reset(ResetForm level){
  120. switch (level) {
  121. case Software: ResetX0(); break;
  122. case ResetPin: TriggerResetPin(); break;
  123. case CutThePower: PowerCycle(); break;
  124. default: break;
  125. }
  126. }
  127. void MMU2::ResetX0() {
  128. logic.ResetMMU(); // Send soft reset
  129. }
  130. void MMU2::TriggerResetPin(){
  131. reset();
  132. }
  133. void MMU2::PowerCycle(){
  134. // cut the power to the MMU and after a while restore it
  135. // Sadly, MK3/S/+ cannot do this
  136. // NOTE: the below will toggle the EEPROM var. Should we
  137. // assert this function is never called in the MK3 FW? Do we even care?
  138. PowerOff();
  139. delay_keep_alive(1000);
  140. PowerOn();
  141. }
  142. void MMU2::PowerOff(){
  143. power_off();
  144. }
  145. void MMU2::PowerOn(){
  146. power_on();
  147. }
  148. bool MMU2::ReadRegister(uint8_t address){
  149. if( ! WaitForMMUReady())
  150. return false;
  151. logic.ReadRegister(address); // we may signal the accepted/rejected status of the response as return value of this function
  152. manage_response(false, false);
  153. return true;
  154. }
  155. bool MMU2::WriteRegister(uint8_t address, uint16_t data){
  156. if( ! WaitForMMUReady())
  157. return false;
  158. logic.WriteRegister(address, data); // we may signal the accepted/rejected status of the response as return value of this function
  159. manage_response(false, false);
  160. return true;
  161. }
  162. void MMU2::mmu_loop() {
  163. // We only leave this method if the current command was successfully completed - that's the Marlin's way of blocking operation
  164. // Atomic compare_exchange would have been the most appropriate solution here, but this gets called only in Marlin's task,
  165. // so thread safety should be kept
  166. static bool avoidRecursion = false;
  167. if (avoidRecursion)
  168. return;
  169. avoidRecursion = true;
  170. logicStepLastStatus = LogicStep(); // it looks like the mmu_loop doesn't need to be a blocking call
  171. if (is_mmu_error_monitor_active){
  172. // Call this every iteration to keep the knob rotation responsive
  173. // This includes when mmu_loop is called within manage_response
  174. ReportErrorHook((uint16_t)lastErrorCode, mmu2.MMUCurrentErrorCode() == ErrorCode::OK ? ErrorSourcePrinter : ErrorSourceMMU);
  175. }
  176. // Check for FINDA filament runout
  177. if (!FindaDetectsFilament() && CHECK_FSENSOR) {
  178. SERIAL_ECHOLNPGM("FINDA filament runout!");
  179. stop_and_save_print_to_ram(0, 0);
  180. restore_print_from_ram_and_continue(0);
  181. if (SpoolJoin::spooljoin.isSpoolJoinEnabled() && get_current_tool() != (uint8_t)FILAMENT_UNKNOWN) // Can't auto if F=?
  182. {
  183. enquecommand_front_P(PSTR("M600 AUTO")); //save print and run M600 command
  184. }
  185. else
  186. {
  187. enquecommand_front_P(PSTR("M600")); //save print and run M600 command
  188. }
  189. }
  190. avoidRecursion = false;
  191. }
  192. struct ReportingRAII {
  193. CommandInProgress cip;
  194. inline ReportingRAII(CommandInProgress cip):cip(cip){
  195. BeginReport(cip, (uint16_t)ProgressCode::EngagingIdler);
  196. }
  197. inline ~ReportingRAII(){
  198. EndReport(cip, (uint16_t)ProgressCode::OK);
  199. }
  200. };
  201. bool MMU2::WaitForMMUReady(){
  202. switch(State()){
  203. case xState::Stopped:
  204. return false;
  205. case xState::Connecting:
  206. // shall we wait until the MMU reconnects?
  207. // fire-up a fsm_dlg and show "MMU not responding"?
  208. default:
  209. return true;
  210. }
  211. }
  212. bool MMU2::RetryIfPossible(uint16_t ec){
  213. if( retryAttempts ){
  214. SERIAL_ECHOPGM("retryAttempts=");SERIAL_ECHOLN((uint16_t)retryAttempts);
  215. SetButtonResponse(ButtonOperations::Retry);
  216. // check, that Retry is actually allowed on that operation
  217. if( ButtonAvailable(ec) != NoButton ){
  218. inAutoRetry = true;
  219. SERIAL_ECHOLNPGM("RetryButtonPressed");
  220. // We don't decrement until the button is acknowledged by the MMU.
  221. //--retryAttempts; // "used" one retry attempt
  222. return true;
  223. }
  224. }
  225. inAutoRetry = false;
  226. return false;
  227. }
  228. void MMU2::ResetRetryAttempts(){
  229. SERIAL_ECHOLNPGM("ResetRetryAttempts");
  230. retryAttempts = MAX_RETRIES;
  231. }
  232. void MMU2::DecrementRetryAttempts(){
  233. if (inAutoRetry && retryAttempts)
  234. {
  235. SERIAL_ECHOLNPGM("DecrementRetryAttempts");
  236. retryAttempts--;
  237. }
  238. }
  239. bool MMU2::tool_change(uint8_t index) {
  240. if( ! WaitForMMUReady())
  241. return false;
  242. if (index != extruder) {
  243. if (!IS_SD_PRINTING && !usb_timer.running())
  244. {
  245. // If Tcodes are used manually through the serial
  246. // we need to unload manually as well
  247. unload();
  248. }
  249. ReportingRAII rep(CommandInProgress::ToolChange);
  250. FSensorBlockRunout blockRunout;
  251. st_synchronize();
  252. tool_change_extruder = index;
  253. logic.ToolChange(index); // let the MMU pull the filament out and push a new one in
  254. manage_response(true, true);
  255. // reset current position to whatever the planner thinks it is
  256. plan_set_e_position(current_position[E_AXIS]);
  257. extruder = index; //filament change is finished
  258. SpoolJoin::spooljoin.setSlot(index);
  259. // @@TODO really report onto the serial? May be for the Octoprint? Not important now
  260. // SERIAL_ECHO_START();
  261. // SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(extruder));
  262. }
  263. return true;
  264. }
  265. /// Handle special T?/Tx/Tc commands
  266. ///
  267. ///- T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  268. ///- Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load.
  269. ///- Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated.
  270. bool MMU2::tool_change(char code, uint8_t slot) {
  271. if( ! WaitForMMUReady())
  272. return false;
  273. FSensorBlockRunout blockRunout;
  274. switch (code) {
  275. case '?': {
  276. waitForHotendTargetTemp(100, []{});
  277. load_filament_to_nozzle(slot);
  278. } break;
  279. case 'x': {
  280. set_extrude_min_temp(0); // Allow cold extrusion since Tx only loads to the gears not nozzle
  281. st_synchronize();
  282. tool_change_extruder = slot;
  283. logic.ToolChange(slot);
  284. manage_response(false, false);
  285. extruder = slot;
  286. SpoolJoin::spooljoin.setSlot(slot);
  287. set_extrude_min_temp(EXTRUDE_MINTEMP);
  288. } break;
  289. case 'c': {
  290. waitForHotendTargetTemp(100, []{});
  291. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  292. } break;
  293. }
  294. return true;
  295. }
  296. void MMU2::get_statistics() {
  297. logic.Statistics();
  298. }
  299. uint8_t MMU2::get_current_tool() const {
  300. return extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : extruder;
  301. }
  302. uint8_t MMU2::get_tool_change_tool() const {
  303. return tool_change_extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : tool_change_extruder;
  304. }
  305. bool MMU2::set_filament_type(uint8_t index, uint8_t type) {
  306. if( ! WaitForMMUReady())
  307. return false;
  308. // @@TODO - this is not supported in the new MMU yet
  309. // cmd_arg = filamentType;
  310. // command(MMU_CMD_F0 + index);
  311. manage_response(false, false); // true, true); -- Comment: how is it possible for a filament type set to fail?
  312. return true;
  313. }
  314. bool MMU2::unload() {
  315. if( ! WaitForMMUReady())
  316. return false;
  317. WaitForHotendTargetTempBeep();
  318. {
  319. FSensorBlockRunout blockRunout;
  320. ReportingRAII rep(CommandInProgress::UnloadFilament);
  321. filament_ramming();
  322. logic.UnloadFilament();
  323. manage_response(false, true);
  324. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  325. // no active tool
  326. extruder = MMU2_NO_TOOL;
  327. tool_change_extruder = MMU2_NO_TOOL;
  328. }
  329. return true;
  330. }
  331. bool MMU2::cut_filament(uint8_t index){
  332. if( ! WaitForMMUReady())
  333. return false;
  334. ReportingRAII rep(CommandInProgress::CutFilament);
  335. logic.CutFilament(index);
  336. manage_response(false, true);
  337. return true;
  338. }
  339. void FullScreenMsg(const char *pgmS, uint8_t slot){
  340. lcd_update_enable(false);
  341. lcd_clear();
  342. lcd_puts_at_P(0, 1, pgmS);
  343. lcd_print(' ');
  344. lcd_print(slot + 1);
  345. }
  346. bool MMU2::load_to_bondtech(uint8_t index){
  347. FullScreenMsg(_T(MSG_TESTING_FILAMENT), index);
  348. tool_change(index);
  349. st_synchronize();
  350. unload();
  351. lcd_update_enable(true);
  352. return true;
  353. }
  354. bool MMU2::load_filament(uint8_t index) {
  355. if( ! WaitForMMUReady())
  356. return false;
  357. FullScreenMsg(_T(MSG_LOADING_FILAMENT), index);
  358. ReportingRAII rep(CommandInProgress::LoadFilament);
  359. logic.LoadFilament(index);
  360. manage_response(false, false);
  361. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  362. lcd_update_enable(true);
  363. return true;
  364. }
  365. struct LoadingToNozzleRAII {
  366. MMU2 &mmu2;
  367. explicit inline LoadingToNozzleRAII(MMU2 &mmu2):mmu2(mmu2){
  368. mmu2.loadingToNozzle = true;
  369. }
  370. inline ~LoadingToNozzleRAII(){
  371. mmu2.loadingToNozzle = false;
  372. }
  373. };
  374. bool MMU2::load_filament_to_nozzle(uint8_t index) {
  375. if( ! WaitForMMUReady())
  376. return false;
  377. LoadingToNozzleRAII ln(*this);
  378. WaitForHotendTargetTempBeep();
  379. FullScreenMsg(_T(MSG_LOADING_FILAMENT), index);
  380. {
  381. // used for MMU-menu operation "Load to Nozzle"
  382. ReportingRAII rep(CommandInProgress::ToolChange);
  383. FSensorBlockRunout blockRunout;
  384. if( extruder != MMU2_NO_TOOL ){ // we already have some filament loaded - free it + shape its tip properly
  385. filament_ramming();
  386. }
  387. tool_change_extruder = index;
  388. logic.ToolChange(index);
  389. manage_response(true, true);
  390. // The MMU's idler is disengaged at this point
  391. // That means the MK3/S now has fully control
  392. // reset current position to whatever the planner thinks it is
  393. st_synchronize();
  394. plan_set_e_position(current_position[E_AXIS]);
  395. // Finish loading to the nozzle with finely tuned steps.
  396. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  397. extruder = index;
  398. SpoolJoin::spooljoin.setSlot(index);
  399. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  400. }
  401. lcd_update_enable(true);
  402. return true;
  403. }
  404. bool MMU2::eject_filament(uint8_t index, bool recover) {
  405. if( ! WaitForMMUReady())
  406. return false;
  407. ReportingRAII rep(CommandInProgress::EjectFilament);
  408. current_position[E_AXIS] -= MMU2_FILAMENTCHANGE_EJECT_FEED;
  409. plan_buffer_line_curposXYZE(2500.F / 60.F);
  410. st_synchronize();
  411. logic.EjectFilament(index);
  412. manage_response(false, false);
  413. if (recover) {
  414. // LCD_MESSAGEPGM(MSG_MMU2_EJECT_RECOVER);
  415. Sound_MakeSound(e_SOUND_TYPE_StandardPrompt);
  416. //@@TODO wait_for_user = true;
  417. //#if ENABLED(HOST_PROMPT_SUPPORT)
  418. // host_prompt_do(PROMPT_USER_CONTINUE, PSTR("MMU2 Eject Recover"), PSTR("Continue"));
  419. //#endif
  420. //#if ENABLED(EXTENSIBLE_UI)
  421. // ExtUI::onUserConfirmRequired_P(PSTR("MMU2 Eject Recover"));
  422. //#endif
  423. //@@TODO while (wait_for_user) idle(true);
  424. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  425. // logic.Command(); //@@TODO command(MMU_CMD_R0);
  426. manage_response(false, false);
  427. }
  428. // no active tool
  429. extruder = MMU2_NO_TOOL;
  430. tool_change_extruder = MMU2_NO_TOOL;
  431. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  432. // disable_E0();
  433. return true;
  434. }
  435. void MMU2::Button(uint8_t index){
  436. LogEchoEvent_P(PSTR("Button"));
  437. logic.Button(index);
  438. }
  439. void MMU2::Home(uint8_t mode){
  440. logic.Home(mode);
  441. }
  442. void MMU2::SaveAndPark(bool move_axes, bool turn_off_nozzle) {
  443. if (mmu_print_saved == SavedState::None) { // First occurrence. Save current position, park print head, disable nozzle heater.
  444. LogEchoEvent_P(PSTR("Saving and parking"));
  445. st_synchronize();
  446. resume_hotend_temp = degTargetHotend(active_extruder);
  447. if (move_axes){
  448. mmu_print_saved |= SavedState::ParkExtruder;
  449. // save current pos
  450. for(uint8_t i = 0; i < 3; ++i){
  451. resume_position.xyz[i] = current_position[i];
  452. }
  453. // lift Z
  454. raise_z(MMU_ERR_Z_PAUSE_LIFT);
  455. // move XY aside
  456. current_position[X_AXIS] = MMU_ERR_X_PAUSE_POS;
  457. current_position[Y_AXIS] = MMU_ERR_Y_PAUSE_POS;
  458. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  459. st_synchronize();
  460. }
  461. if (turn_off_nozzle){
  462. mmu_print_saved |= SavedState::CooldownPending;
  463. LogEchoEvent_P(PSTR("Heater cooldown pending"));
  464. // This just sets the flag that we should timeout and shut off the nozzle in 30 minutes...
  465. //setAllTargetHotends(0);
  466. }
  467. }
  468. // keep the motors powered forever (until some other strategy is chosen)
  469. // @@TODO do we need that in 8bit?
  470. // gcode.reset_stepper_timeout();
  471. }
  472. void MMU2::ResumeHotendTemp() {
  473. if ((mmu_print_saved & SavedState::CooldownPending))
  474. {
  475. // Clear the "pending" flag if we haven't cooled yet.
  476. mmu_print_saved &= ~(SavedState::CooldownPending);
  477. LogEchoEvent_P(PSTR("Cooldown flag cleared"));
  478. }
  479. if ((mmu_print_saved & SavedState::Cooldown) && resume_hotend_temp) {
  480. LogEchoEvent_P(PSTR("Resuming Temp"));
  481. MMU2_ECHO_MSGRPGM(PSTR("Restoring hotend temperature "));
  482. SERIAL_ECHOLN(resume_hotend_temp);
  483. mmu_print_saved &= ~(SavedState::Cooldown);
  484. setTargetHotend(resume_hotend_temp, active_extruder);
  485. lcd_display_message_fullscreen_P(_i("MMU Retry: Restoring temperature...")); // better report the event and let the GUI do its work somewhere else
  486. ReportErrorHookSensorLineRender();
  487. waitForHotendTargetTemp(1000, []{
  488. ReportErrorHookDynamicRender();
  489. manage_inactivity(true);
  490. });
  491. lcd_update_enable(true); // temporary hack to stop this locking the printer...
  492. LogEchoEvent_P(PSTR("Hotend temperature reached"));
  493. lcd_clear();
  494. }
  495. }
  496. void MMU2::ResumeUnpark(){
  497. if (mmu_print_saved & SavedState::ParkExtruder) {
  498. LogEchoEvent_P(PSTR("Resuming XYZ"));
  499. current_position[X_AXIS] = resume_position.xyz[X_AXIS];
  500. current_position[Y_AXIS] = resume_position.xyz[Y_AXIS];
  501. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  502. st_synchronize();
  503. current_position[Z_AXIS] = resume_position.xyz[Z_AXIS];
  504. plan_buffer_line_curposXYZE(NOZZLE_PARK_Z_FEEDRATE);
  505. st_synchronize();
  506. mmu_print_saved &= ~(SavedState::ParkExtruder);
  507. }
  508. }
  509. void MMU2::CheckUserInput(){
  510. auto btn = ButtonPressed((uint16_t)lastErrorCode);
  511. // Was a button pressed on the MMU itself instead of the LCD?
  512. if (btn == Buttons::NoButton && lastButton != Buttons::NoButton){
  513. btn = lastButton;
  514. lastButton = Buttons::NoButton; // Clear it.
  515. }
  516. switch (btn) {
  517. case Left:
  518. case Middle:
  519. case Right:
  520. SERIAL_ECHOPGM("CheckUserInput-btnLMR ");
  521. SERIAL_ECHOLN(btn);
  522. ResumeHotendTemp(); // Recover the hotend temp before we attempt to do anything else...
  523. Button(btn);
  524. break;
  525. case RestartMMU:
  526. Reset(ResetPin); // we cannot do power cycle on the MK3
  527. // ... but mmu2_power.cpp knows this and triggers a soft-reset instead.
  528. break;
  529. case DisableMMU:
  530. Stop(); // Poweroff handles updating the EEPROM shutoff.
  531. break;
  532. case StopPrint:
  533. // @@TODO not sure if we shall handle this high level operation at this spot
  534. break;
  535. default:
  536. break;
  537. }
  538. }
  539. /// Originally, this was used to wait for response and deal with timeout if necessary.
  540. /// The new protocol implementation enables much nicer and intense reporting, so this method will boil down
  541. /// just to verify the result of an issued command (which was basically the original idea)
  542. ///
  543. /// It is closely related to mmu_loop() (which corresponds to our ProtocolLogic::Step()), which does NOT perform any blocking wait for a command to finish.
  544. /// But - in case of an error, the command is not yet finished, but we must react accordingly - move the printhead elsewhere, stop heating, eat a cat or so.
  545. /// That's what's being done here...
  546. void MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) {
  547. mmu_print_saved = SavedState::None;
  548. KEEPALIVE_STATE(PAUSED_FOR_USER);
  549. LongTimer nozzleTimeout;
  550. for (;;) {
  551. // in our new implementation, we know the exact state of the MMU at any moment, we do not have to wait for a timeout
  552. // So in this case we shall decide if the operation is:
  553. // - still running -> wait normally in idle()
  554. // - failed -> then do the safety moves on the printer like before
  555. // - finished ok -> proceed with reading other commands
  556. manage_heater();
  557. manage_inactivity(true); // calls LogicStep() and remembers its return status
  558. lcd_update(0);
  559. if (mmu_print_saved & SavedState::CooldownPending){
  560. if (!nozzleTimeout.running()){
  561. nozzleTimeout.start();
  562. LogEchoEvent_P(PSTR("Cooling Timeout started"));
  563. } else if (nozzleTimeout.expired(DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul)){ // mins->msec. TODO: do we use the global or have our own independent timeout
  564. mmu_print_saved &= ~(SavedState::CooldownPending);
  565. mmu_print_saved |= SavedState::Cooldown;
  566. setAllTargetHotends(0);
  567. LogEchoEvent_P(PSTR("Heater cooldown"));
  568. }
  569. } else if (nozzleTimeout.running()) {
  570. nozzleTimeout.stop();
  571. LogEchoEvent_P(PSTR("Cooling timer stopped"));
  572. }
  573. switch (logicStepLastStatus) {
  574. case Finished:
  575. // command/operation completed, let Marlin continue its work
  576. // the E may have some more moves to finish - wait for them
  577. ResumeUnpark(); // We can now travel back to the tower or wherever we were when we saved.
  578. ResetRetryAttempts(); // Reset the retry counter.
  579. st_synchronize();
  580. return;
  581. case VersionMismatch: // this basically means the MMU will be disabled until reconnected
  582. CheckUserInput();
  583. return;
  584. case CommandError:
  585. // Don't proceed to the park/save if we are doing an autoretry.
  586. if (inAutoRetry){
  587. continue;
  588. }
  589. [[fallthrough]];
  590. case CommunicationTimeout:
  591. case ProtocolError:
  592. SaveAndPark(move_axes, turn_off_nozzle); // and wait for the user to resolve the problem
  593. CheckUserInput();
  594. break;
  595. case CommunicationRecovered: // @@TODO communication recovered and may be an error recovered as well
  596. // may be the logic layer can detect the change of state a respond with one "Recovered" to be handled here
  597. ResumeHotendTemp();
  598. ResumeUnpark();
  599. break;
  600. case Processing: // wait for the MMU to respond
  601. default:
  602. break;
  603. }
  604. }
  605. }
  606. StepStatus MMU2::LogicStep() {
  607. CheckUserInput(); // Process any buttons before proceeding with another MMU Query
  608. StepStatus ss = logic.Step();
  609. switch (ss) {
  610. case Finished:
  611. case Processing:
  612. OnMMUProgressMsg(logic.Progress());
  613. break;
  614. case CommandError:
  615. ReportError(logic.Error(), ErrorSourceMMU);
  616. break;
  617. case CommunicationTimeout:
  618. state = xState::Connecting;
  619. ReportError(ErrorCode::MMU_NOT_RESPONDING, ErrorSourcePrinter);
  620. break;
  621. case ProtocolError:
  622. state = xState::Connecting;
  623. ReportError(ErrorCode::PROTOCOL_ERROR, ErrorSourcePrinter);
  624. break;
  625. case VersionMismatch:
  626. StopKeepPowered();
  627. ReportError(ErrorCode::VERSION_MISMATCH, ErrorSourcePrinter);
  628. break;
  629. case ButtonPushed:
  630. lastButton = logic.Button();
  631. LogEchoEvent_P(PSTR("MMU Button pushed"));
  632. CheckUserInput(); // Process the button immediately
  633. break;
  634. default:
  635. break;
  636. }
  637. if( logic.Running() ){
  638. state = xState::Active;
  639. }
  640. return ss;
  641. }
  642. void MMU2::filament_ramming() {
  643. execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step));
  644. }
  645. void MMU2::execute_extruder_sequence(const E_Step *sequence, uint8_t steps) {
  646. st_synchronize();
  647. const E_Step *step = sequence;
  648. for (uint8_t i = 0; i < steps; i++) {
  649. current_position[E_AXIS] += pgm_read_float(&(step->extrude));
  650. plan_buffer_line_curposXYZE(pgm_read_float(&(step->feedRate)));
  651. st_synchronize();
  652. step++;
  653. }
  654. }
  655. void MMU2::ReportError(ErrorCode ec, uint8_t res) {
  656. // Due to a potential lossy error reporting layers linked to this hook
  657. // we'd better report everything to make sure especially the error states
  658. // do not get lost.
  659. // - The good news here is the fact, that the MMU reports the errors repeatedly until resolved.
  660. // - The bad news is, that MMU not responding may repeatedly occur on printers not having the MMU at all.
  661. //
  662. // Not sure how to properly handle this situation, options:
  663. // - skip reporting "MMU not responding" (at least for now)
  664. // - report only changes of states (we can miss an error message)
  665. // - may be some combination of MMUAvailable + UseMMU flags and decide based on their state
  666. // Right now the filtering of MMU_NOT_RESPONDING is done in ReportErrorHook() as it is not a problem if mmu2.cpp
  667. // Depending on the Progress code, we may want to do some action when an error occurs
  668. switch (logic.Progress()){
  669. case ProgressCode::UnloadingToFinda:
  670. unloadFilamentStarted = false;
  671. break;
  672. case ProgressCode::FeedingToFSensor:
  673. // FSENSOR error during load. Make sure E-motor stops moving.
  674. loadFilamentStarted = false;
  675. break;
  676. default:
  677. break;
  678. }
  679. ReportErrorHook((uint16_t)ec, res);
  680. if( ec != lastErrorCode ){ // deduplicate: only report changes in error codes into the log
  681. lastErrorCode = ec;
  682. LogErrorEvent_P( _T(PrusaErrorTitle(PrusaErrorCodeIndex((uint16_t)ec))) );
  683. }
  684. static_assert(mmu2Magic[0] == 'M'
  685. && mmu2Magic[1] == 'M'
  686. && mmu2Magic[2] == 'U'
  687. && mmu2Magic[3] == '2'
  688. && mmu2Magic[4] == ':'
  689. && strlen_constexpr(mmu2Magic) == 5,
  690. "MMU2 logging prefix mismatch, must be updated at various spots"
  691. );
  692. }
  693. void MMU2::ReportProgress(ProgressCode pc) {
  694. ReportProgressHook((CommandInProgress)logic.CommandInProgress(), (uint16_t)pc);
  695. LogEchoEvent_P( _T(ProgressCodeToText((uint16_t)pc)) );
  696. }
  697. void MMU2::OnMMUProgressMsg(ProgressCode pc){
  698. if (pc != lastProgressCode) {
  699. OnMMUProgressMsgChanged(pc);
  700. } else {
  701. OnMMUProgressMsgSame(pc);
  702. }
  703. }
  704. void MMU2::OnMMUProgressMsgChanged(ProgressCode pc){
  705. ReportProgress(pc);
  706. lastProgressCode = pc;
  707. switch (pc) {
  708. case ProgressCode::UnloadingToFinda:
  709. if ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::UnloadFilament
  710. || ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::ToolChange))
  711. {
  712. // If MK3S sent U0 command, ramming sequence takes care of releasing the filament.
  713. // If Toolchange is done while printing, PrusaSlicer takes care of releasing the filament
  714. // If printing is not in progress, ToolChange will issue a U0 command.
  715. break;
  716. } else {
  717. // We're likely recovering from an MMU error
  718. st_synchronize();
  719. unloadFilamentStarted = true;
  720. current_position[E_AXIS] -= MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH;
  721. plan_buffer_line_curposXYZE(MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE);
  722. }
  723. break;
  724. case ProgressCode::FeedingToFSensor:
  725. // prepare for the movement of the E-motor
  726. st_synchronize();
  727. loadFilamentStarted = true;
  728. break;
  729. default:
  730. // do nothing yet
  731. break;
  732. }
  733. }
  734. void MMU2::OnMMUProgressMsgSame(ProgressCode pc){
  735. switch (pc) {
  736. case ProgressCode::UnloadingToFinda:
  737. if (unloadFilamentStarted && !blocks_queued()) { // Only plan a move if there is no move ongoing
  738. if (fsensor.getFilamentPresent()) {
  739. current_position[E_AXIS] -= MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH;
  740. plan_buffer_line_curposXYZE(MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE);
  741. } else {
  742. unloadFilamentStarted = false;
  743. }
  744. }
  745. break;
  746. case ProgressCode::FeedingToFSensor:
  747. if (loadFilamentStarted) {
  748. switch (WhereIsFilament()) {
  749. case FilamentState::AT_FSENSOR:
  750. // fsensor triggered, finish FeedingToBondtech state
  751. loadFilamentStarted = false;
  752. // After the MMU knows the FSENSOR is triggered it will:
  753. // 1. Push the filament by additional 30mm (see fsensorToNozzle)
  754. // 2. Disengage the idler and push another 5mm.
  755. current_position[E_AXIS] += 30.0f + 2.0f;
  756. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  757. break;
  758. case FilamentState::NOT_PRESENT:
  759. // fsensor not triggered, continue moving extruder
  760. if (!blocks_queued()) { // Only plan a move if there is no move ongoing
  761. current_position[E_AXIS] += 2.0f;
  762. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  763. }
  764. break;
  765. default:
  766. // Abort here?
  767. break;
  768. }
  769. }
  770. break;
  771. default:
  772. // do nothing yet
  773. break;
  774. }
  775. }
  776. } // namespace MMU2