mmu2.cpp 31 KB

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