mmu2.cpp 29 KB

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