mmu2.cpp 33 KB

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