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. {}
  98. void MMU2::Start() {
  99. #ifdef MMU_HWRESET
  100. WRITE(MMU_RST_PIN, 1);
  101. SET_OUTPUT(MMU_RST_PIN); // setup reset pin
  102. #endif //MMU_HWRESET
  103. mmu2Serial.begin(MMU_BAUD);
  104. PowerOn(); // I repurposed this to serve as our EEPROM disable toggle.
  105. Reset(ResetForm::ResetPin);
  106. mmu2Serial.flush(); // make sure the UART buffer is clear before starting communication
  107. extruder = MMU2_NO_TOOL;
  108. state = xState::Connecting;
  109. // start the communication
  110. logic.Start();
  111. ResetRetryAttempts();
  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. inAutoRetry = true;
  194. SERIAL_ECHOLNPGM("RetryButtonPressed");
  195. // We don't decrement until the button is acknowledged by the MMU.
  196. //--retryAttempts; // "used" one retry attempt
  197. return true;
  198. }
  199. }
  200. inAutoRetry = false;
  201. return false;
  202. }
  203. void MMU2::ResetRetryAttempts(){
  204. SERIAL_ECHOLNPGM("ResetRetryAttempts");
  205. retryAttempts = MAX_RETRIES;
  206. }
  207. void MMU2::DecrementRetryAttempts(){
  208. if (inAutoRetry && retryAttempts)
  209. {
  210. SERIAL_ECHOLNPGM("DecrementRetryAttempts");
  211. retryAttempts--;
  212. }
  213. }
  214. bool MMU2::tool_change(uint8_t index) {
  215. if( ! WaitForMMUReady())
  216. return false;
  217. if (index != extruder) {
  218. ReportingRAII rep(CommandInProgress::ToolChange);
  219. FSensorBlockRunout blockRunout;
  220. st_synchronize();
  221. tool_change_extruder = index;
  222. logic.ToolChange(index); // let the MMU pull the filament out and push a new one in
  223. manage_response(true, true);
  224. // reset current position to whatever the planner thinks it is
  225. // SERIAL_ECHOPGM("TC1:p=");
  226. // SERIAL_ECHO(position[E_AXIS]);
  227. // SERIAL_ECHOPGM("TC1:cp=");
  228. // SERIAL_ECHOLN(current_position[E_AXIS]);
  229. plan_set_e_position(current_position[E_AXIS]);
  230. // SERIAL_ECHOPGM("TC2:p=");
  231. // SERIAL_ECHO(position[E_AXIS]);
  232. // SERIAL_ECHOPGM("TC2:cp=");
  233. // SERIAL_ECHOLN(current_position[E_AXIS]);
  234. extruder = index; //filament change is finished
  235. previous_extruder = extruder;
  236. SetActiveExtruder(0);
  237. // @@TODO really report onto the serial? May be for the Octoprint? Not important now
  238. // SERIAL_ECHO_START();
  239. // SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(extruder));
  240. }
  241. return true;
  242. }
  243. /// Handle special T?/Tx/Tc commands
  244. ///
  245. ///- T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  246. ///- 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.
  247. ///- Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated.
  248. bool MMU2::tool_change(char code, uint8_t slot) {
  249. if( ! WaitForMMUReady())
  250. return false;
  251. FSensorBlockRunout blockRunout;
  252. switch (code) {
  253. case '?': {
  254. waitForHotendTargetTemp(100, []{});
  255. load_filament_to_nozzle(slot);
  256. } break;
  257. case 'x': {
  258. set_extrude_min_temp(0); // Allow cold extrusion since Tx only loads to the gears not nozzle
  259. st_synchronize();
  260. tool_change_extruder = slot;
  261. logic.ToolChange(slot);
  262. manage_response(false, false);
  263. extruder = slot;
  264. previous_extruder = extruder;
  265. SetActiveExtruder(0);
  266. set_extrude_min_temp(EXTRUDE_MINTEMP);
  267. } break;
  268. case 'c': {
  269. waitForHotendTargetTemp(100, []{});
  270. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  271. } break;
  272. }
  273. return true;
  274. }
  275. uint8_t MMU2::get_current_tool() const {
  276. return extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : extruder;
  277. }
  278. uint8_t MMU2::get_tool_change_tool() const {
  279. return tool_change_extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : tool_change_extruder;
  280. }
  281. bool MMU2::set_filament_type(uint8_t index, uint8_t type) {
  282. if( ! WaitForMMUReady())
  283. return false;
  284. // @@TODO - this is not supported in the new MMU yet
  285. // cmd_arg = filamentType;
  286. // command(MMU_CMD_F0 + index);
  287. manage_response(false, false); // true, true); -- Comment: how is it possible for a filament type set to fail?
  288. return true;
  289. }
  290. bool MMU2::unload() {
  291. if( ! WaitForMMUReady())
  292. return false;
  293. WaitForHotendTargetTempBeep();
  294. {
  295. FSensorBlockRunout blockRunout;
  296. ReportingRAII rep(CommandInProgress::UnloadFilament);
  297. filament_ramming();
  298. logic.UnloadFilament();
  299. manage_response(false, true);
  300. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  301. // no active tool
  302. extruder = MMU2_NO_TOOL;
  303. tool_change_extruder = MMU2_NO_TOOL;
  304. }
  305. return true;
  306. }
  307. bool MMU2::cut_filament(uint8_t index){
  308. if( ! WaitForMMUReady())
  309. return false;
  310. ReportingRAII rep(CommandInProgress::CutFilament);
  311. logic.CutFilament(index);
  312. manage_response(false, true);
  313. return true;
  314. }
  315. void FullScreenMsg(const char *pgmS, uint8_t slot){
  316. lcd_update_enable(false);
  317. lcd_clear();
  318. lcd_puts_at_P(0, 1, pgmS);
  319. lcd_print(' ');
  320. lcd_print(slot + 1);
  321. }
  322. bool MMU2::load_to_bondtech(uint8_t index){
  323. FullScreenMsg(_T(MSG_TESTING_FILAMENT), index);
  324. tool_change(index);
  325. st_synchronize();
  326. unload();
  327. lcd_update_enable(true);
  328. return true;
  329. }
  330. bool MMU2::load_filament(uint8_t index) {
  331. if( ! WaitForMMUReady())
  332. return false;
  333. FullScreenMsg(_T(MSG_LOADING_FILAMENT), index);
  334. ReportingRAII rep(CommandInProgress::LoadFilament);
  335. logic.LoadFilament(index);
  336. manage_response(false, false);
  337. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  338. lcd_update_enable(true);
  339. return true;
  340. }
  341. struct LoadingToNozzleRAII {
  342. MMU2 &mmu2;
  343. explicit inline LoadingToNozzleRAII(MMU2 &mmu2):mmu2(mmu2){
  344. mmu2.loadingToNozzle = true;
  345. }
  346. inline ~LoadingToNozzleRAII(){
  347. mmu2.loadingToNozzle = false;
  348. }
  349. };
  350. bool MMU2::load_filament_to_nozzle(uint8_t index) {
  351. if( ! WaitForMMUReady())
  352. return false;
  353. LoadingToNozzleRAII ln(*this);
  354. WaitForHotendTargetTempBeep();
  355. FullScreenMsg(_T(MSG_LOADING_FILAMENT), index);
  356. {
  357. // used for MMU-menu operation "Load to Nozzle"
  358. ReportingRAII rep(CommandInProgress::ToolChange);
  359. FSensorBlockRunout blockRunout;
  360. if( extruder != MMU2_NO_TOOL ){ // we already have some filament loaded - free it + shape its tip properly
  361. filament_ramming();
  362. }
  363. tool_change_extruder = index;
  364. logic.ToolChange(index);
  365. manage_response(true, true);
  366. // The MMU's idler is disengaged at this point
  367. // That means the MK3/S now has fully control
  368. // reset current position to whatever the planner thinks it is
  369. st_synchronize();
  370. // SERIAL_ECHOPGM("LFTN1:p=");
  371. // SERIAL_ECHO(position[E_AXIS]);
  372. // SERIAL_ECHOPGM("LFTN1:cp=");
  373. // SERIAL_ECHOLN(current_position[E_AXIS]);
  374. plan_set_e_position(current_position[E_AXIS]);
  375. // SERIAL_ECHOPGM("LFTN2:p=");
  376. // SERIAL_ECHO(position[E_AXIS]);
  377. // SERIAL_ECHOPGM("LFTN2:cp=");
  378. // SERIAL_ECHOLN(current_position[E_AXIS]);
  379. // Finish loading to the nozzle with finely tuned steps.
  380. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  381. extruder = index;
  382. previous_extruder = extruder;
  383. SetActiveExtruder(0);
  384. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  385. }
  386. lcd_update_enable(true);
  387. return true;
  388. }
  389. bool MMU2::eject_filament(uint8_t index, bool recover) {
  390. if( ! WaitForMMUReady())
  391. return false;
  392. ReportingRAII rep(CommandInProgress::EjectFilament);
  393. current_position[E_AXIS] -= MMU2_FILAMENTCHANGE_EJECT_FEED;
  394. plan_buffer_line_curposXYZE(2500.F / 60.F);
  395. st_synchronize();
  396. logic.EjectFilament(index);
  397. manage_response(false, false);
  398. if (recover) {
  399. // LCD_MESSAGEPGM(MSG_MMU2_EJECT_RECOVER);
  400. Sound_MakeSound(e_SOUND_TYPE_StandardPrompt);
  401. //@@TODO wait_for_user = true;
  402. //#if ENABLED(HOST_PROMPT_SUPPORT)
  403. // host_prompt_do(PROMPT_USER_CONTINUE, PSTR("MMU2 Eject Recover"), PSTR("Continue"));
  404. //#endif
  405. //#if ENABLED(EXTENSIBLE_UI)
  406. // ExtUI::onUserConfirmRequired_P(PSTR("MMU2 Eject Recover"));
  407. //#endif
  408. //@@TODO while (wait_for_user) idle(true);
  409. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  410. // logic.Command(); //@@TODO command(MMU_CMD_R0);
  411. manage_response(false, false);
  412. }
  413. // no active tool
  414. extruder = MMU2_NO_TOOL;
  415. tool_change_extruder = MMU2_NO_TOOL;
  416. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  417. // disable_E0();
  418. return true;
  419. }
  420. void MMU2::Button(uint8_t index){
  421. SERIAL_ECHOLNPGM("Button");
  422. logic.Button(index);
  423. }
  424. void MMU2::Home(uint8_t mode){
  425. logic.Home(mode);
  426. }
  427. void MMU2::SaveAndPark(bool move_axes, bool turn_off_nozzle) {
  428. if (mmu_print_saved == SavedState::None) { // First occurrence. Save current position, park print head, disable nozzle heater.
  429. LogEchoEvent("Saving and parking");
  430. st_synchronize();
  431. resume_hotend_temp = degTargetHotend(active_extruder);
  432. if (move_axes){
  433. mmu_print_saved |= SavedState::ParkExtruder;
  434. // save current pos
  435. for(uint8_t i = 0; i < 3; ++i){
  436. resume_position.xyz[i] = current_position[i];
  437. }
  438. // lift Z
  439. current_position[Z_AXIS] += Z_PAUSE_LIFT;
  440. if (current_position[Z_AXIS] > Z_MAX_POS)
  441. current_position[Z_AXIS] = Z_MAX_POS;
  442. plan_buffer_line_curposXYZE(NOZZLE_PARK_Z_FEEDRATE);
  443. st_synchronize();
  444. // move XY aside
  445. current_position[X_AXIS] = X_PAUSE_POS;
  446. current_position[Y_AXIS] = Y_PAUSE_POS;
  447. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  448. st_synchronize();
  449. }
  450. if (turn_off_nozzle){
  451. mmu_print_saved |= SavedState::CooldownPending;
  452. LogEchoEvent("Heater cooldown pending");
  453. // This just sets the flag that we should timeout and shut off the nozzle in 30 minutes...
  454. //setAllTargetHotends(0);
  455. }
  456. }
  457. // keep the motors powered forever (until some other strategy is chosen)
  458. // @@TODO do we need that in 8bit?
  459. // gcode.reset_stepper_timeout();
  460. }
  461. void MMU2::ResumeHotendTemp() {
  462. if ((mmu_print_saved & SavedState::CooldownPending))
  463. {
  464. // Clear the "pending" flag if we haven't cooled yet.
  465. mmu_print_saved &= ~(SavedState::CooldownPending);
  466. LogEchoEvent("Cooldown flag cleared");
  467. }
  468. if ((mmu_print_saved & SavedState::Cooldown) && resume_hotend_temp) {
  469. LogEchoEvent("Resuming Temp");
  470. MMU2_ECHO_MSG("Restoring hotend temperature ");
  471. SERIAL_ECHOLN(resume_hotend_temp);
  472. mmu_print_saved &= ~(SavedState::Cooldown);
  473. setTargetHotend(resume_hotend_temp, active_extruder);
  474. lcd_display_message_fullscreen_P(_i("MMU Retry: Restoring temperature...")); // better report the event and let the GUI do its work somewhere else
  475. ReportErrorHookSensorLineRender();
  476. waitForHotendTargetTemp(1000, []{
  477. ReportErrorHookDynamicRender();
  478. manage_inactivity(true);
  479. });
  480. lcd_update_enable(true); // temporary hack to stop this locking the printer...
  481. LogEchoEvent("Hotend temperature reached");
  482. lcd_clear();
  483. }
  484. }
  485. void MMU2::ResumeUnpark()
  486. {
  487. if (mmu_print_saved & SavedState::ParkExtruder) {
  488. LogEchoEvent("Resuming XYZ");
  489. current_position[X_AXIS] = resume_position.xyz[X_AXIS];
  490. current_position[Y_AXIS] = resume_position.xyz[Y_AXIS];
  491. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  492. st_synchronize();
  493. current_position[Z_AXIS] = resume_position.xyz[Z_AXIS];
  494. plan_buffer_line_curposXYZE(NOZZLE_PARK_Z_FEEDRATE);
  495. st_synchronize();
  496. mmu_print_saved &= ~(SavedState::ParkExtruder);
  497. }
  498. }
  499. void MMU2::CheckUserInput(){
  500. auto btn = ButtonPressed((uint16_t)lastErrorCode);
  501. // Was a button pressed on the MMU itself instead of the LCD?
  502. if (btn == Buttons::NoButton && lastButton != Buttons::NoButton)
  503. {
  504. btn = lastButton;
  505. lastButton = Buttons::NoButton; // Clear it.
  506. }
  507. switch (btn) {
  508. case Left:
  509. case Middle:
  510. case Right:
  511. SERIAL_ECHOPGM("CheckUserInput-btnLMR ");
  512. SERIAL_ECHOLN(btn);
  513. ResumeHotendTemp(); // Recover the hotend temp before we attempt to do anything else...
  514. Button(btn);
  515. break;
  516. case RestartMMU:
  517. Reset(ResetPin); // we cannot do power cycle on the MK3
  518. // ... but mmu2_power.cpp knows this and triggers a soft-reset instead.
  519. break;
  520. case DisableMMU:
  521. Stop(); // Poweroff handles updating the EEPROM shutoff.
  522. break;
  523. case StopPrint:
  524. // @@TODO not sure if we shall handle this high level operation at this spot
  525. break;
  526. default:
  527. break;
  528. }
  529. }
  530. /// Originally, this was used to wait for response and deal with timeout if necessary.
  531. /// The new protocol implementation enables much nicer and intense reporting, so this method will boil down
  532. /// just to verify the result of an issued command (which was basically the original idea)
  533. ///
  534. /// 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.
  535. /// 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.
  536. /// That's what's being done here...
  537. void MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) {
  538. mmu_print_saved = SavedState::None;
  539. KEEPALIVE_STATE(PAUSED_FOR_USER);
  540. LongTimer nozzleTimeout;
  541. for (;;) {
  542. // in our new implementation, we know the exact state of the MMU at any moment, we do not have to wait for a timeout
  543. // So in this case we shall decide if the operation is:
  544. // - still running -> wait normally in idle()
  545. // - failed -> then do the safety moves on the printer like before
  546. // - finished ok -> proceed with reading other commands
  547. manage_heater();
  548. manage_inactivity(true); // calls LogicStep() and remembers its return status
  549. lcd_update(0);
  550. if (mmu_print_saved & SavedState::CooldownPending)
  551. {
  552. if (!nozzleTimeout.running())
  553. {
  554. nozzleTimeout.start();
  555. LogEchoEvent("Cooling Timeout started");
  556. }
  557. else if (nozzleTimeout.expired(DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul)) // mins->msec. TODO: do we use the global or have our own independent timeout
  558. {
  559. mmu_print_saved &= ~(SavedState::CooldownPending);
  560. mmu_print_saved |= SavedState::Cooldown;
  561. setAllTargetHotends(0);
  562. LogEchoEvent("Heater cooldown");
  563. }
  564. }
  565. else if (nozzleTimeout.running())
  566. {
  567. nozzleTimeout.stop();
  568. LogEchoEvent("Cooling timer stopped");
  569. }
  570. switch (logicStepLastStatus) {
  571. case Finished:
  572. // command/operation completed, let Marlin continue its work
  573. // the E may have some more moves to finish - wait for them
  574. ResumeUnpark(); // We can now travel back to the tower or wherever we were when we saved.
  575. ResetRetryAttempts(); // Reset the retry counter.
  576. st_synchronize();
  577. return;
  578. case VersionMismatch: // this basically means the MMU will be disabled until reconnected
  579. CheckUserInput();
  580. return;
  581. case CommandError:
  582. // Don't proceed to the park/save if we are doing an autoretry.
  583. if (inAutoRetry)
  584. {
  585. continue;
  586. }
  587. /* FALLTHRU */
  588. case CommunicationTimeout:
  589. case ProtocolError:
  590. SaveAndPark(move_axes, turn_off_nozzle); // and wait for the user to resolve the problem
  591. CheckUserInput();
  592. break;
  593. case CommunicationRecovered: // @@TODO communication recovered and may be an error recovered as well
  594. // may be the logic layer can detect the change of state a respond with one "Recovered" to be handled here
  595. ResumeHotendTemp();
  596. ResumeUnpark();
  597. break;
  598. case Processing: // wait for the MMU to respond
  599. default:
  600. break;
  601. }
  602. }
  603. }
  604. StepStatus MMU2::LogicStep() {
  605. CheckUserInput(); // Process any buttons before proceeding with another MMU Query
  606. StepStatus ss = logic.Step();
  607. switch (ss) {
  608. case Finished:
  609. case Processing:
  610. OnMMUProgressMsg(logic.Progress());
  611. break;
  612. case CommandError:
  613. ReportError(logic.Error(), ErrorSourceMMU);
  614. break;
  615. case CommunicationTimeout:
  616. state = xState::Connecting;
  617. ReportError(ErrorCode::MMU_NOT_RESPONDING, ErrorSourcePrinter);
  618. break;
  619. case ProtocolError:
  620. state = xState::Connecting;
  621. ReportError(ErrorCode::PROTOCOL_ERROR, ErrorSourcePrinter);
  622. break;
  623. case VersionMismatch:
  624. StopKeepPowered();
  625. ReportError(ErrorCode::VERSION_MISMATCH, ErrorSourcePrinter);
  626. break;
  627. case ButtonPushed:
  628. lastButton = logic.Button();
  629. LogEchoEvent("MMU Button pushed");
  630. CheckUserInput(); // Process the button immediately
  631. break;
  632. default:
  633. break;
  634. }
  635. if( logic.Running() ){
  636. state = xState::Active;
  637. }
  638. return ss;
  639. }
  640. void MMU2::filament_ramming() {
  641. execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step));
  642. }
  643. void MMU2::execute_extruder_sequence(const E_Step *sequence, uint8_t steps) {
  644. st_synchronize();
  645. const E_Step *step = sequence;
  646. for (uint8_t i = 0; i < steps; i++) {
  647. current_position[E_AXIS] += pgm_read_float(&(step->extrude));
  648. plan_buffer_line_curposXYZE(pgm_read_float(&(step->feedRate)));
  649. st_synchronize();
  650. // SERIAL_ECHOPGM("EES:");
  651. // SERIAL_ECHOLN(position[E_AXIS]);
  652. step++;
  653. }
  654. }
  655. void MMU2::SetActiveExtruder(uint8_t ex){
  656. active_extruder = ex;
  657. }
  658. void MMU2::ReportError(ErrorCode ec, uint8_t res) {
  659. // Due to a potential lossy error reporting layers linked to this hook
  660. // we'd better report everything to make sure especially the error states
  661. // do not get lost.
  662. // - The good news here is the fact, that the MMU reports the errors repeatedly until resolved.
  663. // - The bad news is, that MMU not responding may repeatedly occur on printers not having the MMU at all.
  664. //
  665. // Not sure how to properly handle this situation, options:
  666. // - skip reporting "MMU not responding" (at least for now)
  667. // - report only changes of states (we can miss an error message)
  668. // - may be some combination of MMUAvailable + UseMMU flags and decide based on their state
  669. // Right now the filtering of MMU_NOT_RESPONDING is done in ReportErrorHook() as it is not a problem if mmu2.cpp
  670. // Depending on the Progress code, we may want to do some action when an error occurs
  671. switch (logic.Progress())
  672. {
  673. case ProgressCode::UnloadingToFinda:
  674. unloadFilamentStarted = false;
  675. break;
  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