mmu2.cpp 26 KB

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