mmu2.cpp 29 KB

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