mmu2.cpp 31 KB

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