mmu2.cpp 32 KB

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