mmu2.cpp 32 KB

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