mmu2.cpp 30 KB

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