mmu2.cpp 31 KB

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