mmu2.cpp 31 KB

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