mmu2.cpp 29 KB

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