mmu2.cpp 30 KB

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