mmu2.cpp 28 KB

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