mmu2.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. #include "mmu2.h"
  2. #include "mmu2_config.h"
  3. #include "mmu2_error_converter.h"
  4. #include "mmu2_fsensor.h"
  5. #include "mmu2_log.h"
  6. #include "mmu2_power.h"
  7. #include "mmu2_progress_converter.h"
  8. #include "mmu2_reporting.h"
  9. #include "cardreader.h" // for IS_SD_PRINTING
  10. #include "Marlin.h"
  11. #include "language.h"
  12. #include "messages.h"
  13. #include "sound.h"
  14. #include "stepper.h"
  15. #include "strlen_cx.h"
  16. #include "temperature.h"
  17. #include "ultralcd.h"
  18. #include "SpoolJoin.h"
  19. // As of FW 3.12 we only support building the FW with only one extruder, all the multi-extruder infrastructure will be removed.
  20. // Saves at least 800B of code size
  21. static_assert(EXTRUDERS==1);
  22. namespace MMU2 {
  23. template<typename F>
  24. void waitForHotendTargetTemp(uint16_t delay, F f){
  25. while (((degTargetHotend(active_extruder) - degHotend(active_extruder)) > 5)) {
  26. f();
  27. delay_keep_alive(delay);
  28. }
  29. }
  30. void WaitForHotendTargetTempBeep(){
  31. waitForHotendTargetTemp(3000, []{ Sound_MakeSound(e_SOUND_TYPE_StandardPrompt); } );
  32. }
  33. MMU2 mmu2;
  34. MMU2::MMU2()
  35. : is_mmu_error_monitor_active(false)
  36. , logic(&mmu2Serial, MMU2_TOOL_CHANGE_LOAD_LENGTH)
  37. , extruder(MMU2_NO_TOOL)
  38. , tool_change_extruder(MMU2_NO_TOOL)
  39. , resume_position()
  40. , resume_hotend_temp(0)
  41. , logicStepLastStatus(StepStatus::Finished)
  42. , state(xState::Stopped)
  43. , mmu_print_saved(SavedState::None)
  44. , loadFilamentStarted(false)
  45. , unloadFilamentStarted(false)
  46. , loadingToNozzle(false)
  47. , inAutoRetry(false)
  48. , retryAttempts(MAX_RETRIES)
  49. , toolchange_counter(0)
  50. , tmcFailures(0)
  51. {
  52. }
  53. void MMU2::Start() {
  54. #ifdef MMU_HWRESET
  55. WRITE(MMU_RST_PIN, 1);
  56. SET_OUTPUT(MMU_RST_PIN); // setup reset pin
  57. #endif //MMU_HWRESET
  58. mmu2Serial.begin(MMU_BAUD);
  59. PowerOn(); // I repurposed this to serve as our EEPROM disable toggle.
  60. Reset(ResetForm::ResetPin);
  61. mmu2Serial.flush(); // make sure the UART buffer is clear before starting communication
  62. extruder = MMU2_NO_TOOL;
  63. state = xState::Connecting;
  64. // start the communication
  65. logic.Start();
  66. ResetRetryAttempts();
  67. }
  68. void MMU2::Stop() {
  69. StopKeepPowered();
  70. PowerOff(); // This also disables the MMU in the EEPROM.
  71. }
  72. void MMU2::StopKeepPowered(){
  73. state = xState::Stopped;
  74. logic.Stop();
  75. mmu2Serial.close();
  76. }
  77. void MMU2::Reset(ResetForm level){
  78. switch (level) {
  79. case Software: ResetX0(); break;
  80. case ResetPin: TriggerResetPin(); break;
  81. case CutThePower: PowerCycle(); break;
  82. default: break;
  83. }
  84. }
  85. void MMU2::ResetX0() {
  86. logic.ResetMMU(); // Send soft reset
  87. }
  88. void MMU2::TriggerResetPin(){
  89. reset();
  90. }
  91. void MMU2::PowerCycle(){
  92. // cut the power to the MMU and after a while restore it
  93. // Sadly, MK3/S/+ cannot do this
  94. // NOTE: the below will toggle the EEPROM var. Should we
  95. // assert this function is never called in the MK3 FW? Do we even care?
  96. PowerOff();
  97. delay_keep_alive(1000);
  98. PowerOn();
  99. }
  100. void MMU2::PowerOff(){
  101. power_off();
  102. }
  103. void MMU2::PowerOn(){
  104. power_on();
  105. }
  106. bool MMU2::ReadRegister(uint8_t address){
  107. if( ! WaitForMMUReady())
  108. return false;
  109. do {
  110. logic.ReadRegister(address); // we may signal the accepted/rejected status of the response as return value of this function
  111. } while( ! manage_response(false, false) );
  112. return true;
  113. }
  114. bool MMU2::WriteRegister(uint8_t address, uint16_t data){
  115. if( ! WaitForMMUReady())
  116. return false;
  117. // special case - intercept requests of extra loading distance and perform the change even on the printer's side
  118. if( address == 0x0b ){
  119. logic.PlanExtraLoadDistance(data);
  120. }
  121. do {
  122. logic.WriteRegister(address, data); // we may signal the accepted/rejected status of the response as return value of this function
  123. } while( ! manage_response(false, false) );
  124. return true;
  125. }
  126. void MMU2::mmu_loop() {
  127. // We only leave this method if the current command was successfully completed - that's the Marlin's way of blocking operation
  128. // Atomic compare_exchange would have been the most appropriate solution here, but this gets called only in Marlin's task,
  129. // so thread safety should be kept
  130. static bool avoidRecursion = false;
  131. if (avoidRecursion)
  132. return;
  133. avoidRecursion = true;
  134. mmu_loop_inner(true);
  135. avoidRecursion = false;
  136. }
  137. void __attribute__((noinline)) MMU2::mmu_loop_inner(bool reportErrors) {
  138. logicStepLastStatus = LogicStep(reportErrors); // it looks like the mmu_loop doesn't need to be a blocking call
  139. if (is_mmu_error_monitor_active) {
  140. // Call this every iteration to keep the knob rotation responsive
  141. // This includes when mmu_loop is called within manage_response
  142. ReportErrorHook((uint16_t)lastErrorCode);
  143. }
  144. }
  145. void MMU2::CheckFINDARunout() {
  146. // Check for FINDA filament runout
  147. if (!FindaDetectsFilament() && check_fsensor()) {
  148. SERIAL_ECHOLNPGM("FINDA filament runout!");
  149. stop_and_save_print_to_ram(0, 0);
  150. restore_print_from_ram_and_continue(0);
  151. if (SpoolJoin::spooljoin.isSpoolJoinEnabled() && get_current_tool() != (uint8_t)FILAMENT_UNKNOWN){ // Can't auto if F=?
  152. enquecommand_front_P(PSTR("M600 AUTO")); // save print and run M600 command
  153. } else {
  154. enquecommand_front_P(PSTR("M600")); // save print and run M600 command
  155. }
  156. }
  157. }
  158. struct ReportingRAII {
  159. CommandInProgress cip;
  160. inline ReportingRAII(CommandInProgress cip):cip(cip){
  161. BeginReport(cip, (uint16_t)ProgressCode::EngagingIdler);
  162. }
  163. inline ~ReportingRAII(){
  164. EndReport(cip, (uint16_t)ProgressCode::OK);
  165. }
  166. };
  167. bool MMU2::WaitForMMUReady(){
  168. switch(State()){
  169. case xState::Stopped:
  170. return false;
  171. case xState::Connecting:
  172. // shall we wait until the MMU reconnects?
  173. // fire-up a fsm_dlg and show "MMU not responding"?
  174. default:
  175. return true;
  176. }
  177. }
  178. bool MMU2::RetryIfPossible(uint16_t ec){
  179. if( retryAttempts ){
  180. SERIAL_ECHOPGM("retryAttempts=");SERIAL_ECHOLN((uint16_t)retryAttempts);
  181. SetButtonResponse(ButtonOperations::Retry);
  182. // check, that Retry is actually allowed on that operation
  183. if( ButtonAvailable(ec) != NoButton ){
  184. inAutoRetry = true;
  185. SERIAL_ECHOLNPGM("RetryButtonPressed");
  186. // We don't decrement until the button is acknowledged by the MMU.
  187. //--retryAttempts; // "used" one retry attempt
  188. return true;
  189. }
  190. }
  191. inAutoRetry = false;
  192. return false;
  193. }
  194. void MMU2::ResetRetryAttempts(){
  195. SERIAL_ECHOLNPGM("ResetRetryAttempts");
  196. retryAttempts = MAX_RETRIES;
  197. }
  198. void MMU2::DecrementRetryAttempts() {
  199. if (inAutoRetry && retryAttempts) {
  200. SERIAL_ECHOLNPGM("DecrementRetryAttempts");
  201. retryAttempts--;
  202. }
  203. }
  204. bool MMU2::VerifyFilamentEnteredPTFE()
  205. {
  206. st_synchronize();
  207. if (!fsensor.getFilamentPresent()) return false;
  208. uint8_t fsensorState = 0;
  209. // MMU has finished its load, push the filament further by some defined constant length
  210. // If the filament sensor reads 0 at any moment, then report FAILURE
  211. current_position[E_AXIS] += MMU2_EXTRUDER_PTFE_LENGTH + MMU2_EXTRUDER_HEATBREAK_LENGTH - (logic.ExtraLoadDistance() - MMU2_FILAMENT_SENSOR_POSITION);
  212. plan_buffer_line_curposXYZE(MMU2_VERIFY_LOAD_TO_NOZZLE_FEED_RATE);
  213. current_position[E_AXIS] -= (MMU2_EXTRUDER_PTFE_LENGTH + MMU2_EXTRUDER_HEATBREAK_LENGTH - (logic.ExtraLoadDistance() - MMU2_FILAMENT_SENSOR_POSITION));
  214. plan_buffer_line_curposXYZE(MMU2_VERIFY_LOAD_TO_NOZZLE_FEED_RATE);
  215. while(blocks_queued())
  216. {
  217. // Wait for move to finish and monitor the fsensor the entire time
  218. // A single 0 reading will set the bit.
  219. fsensorState |= !fsensor.getFilamentPresent();
  220. manage_heater();
  221. manage_inactivity(true);
  222. }
  223. if (fsensorState)
  224. {
  225. IncrementLoadFails();
  226. return false;
  227. } else {
  228. // else, happy printing! :)
  229. return true;
  230. }
  231. }
  232. bool MMU2::ToolChangeCommonOnce(uint8_t slot){
  233. static_assert(MAX_RETRIES > 1); // need >1 retries to do the cut in the last attempt
  234. for(uint8_t retries = MAX_RETRIES; retries; --retries){
  235. for(;;) {
  236. tool_change_extruder = slot;
  237. logic.ToolChange(slot); // let the MMU pull the filament out and push a new one in
  238. if( manage_response(true, true) )
  239. break;
  240. // otherwise: failed to perform the command - unload first and then let it run again
  241. IncrementMMUFails();
  242. // just in case we stood in an error screen for too long and the hotend got cold
  243. ResumeHotendTemp();
  244. // if the extruder has been parked, it will get unparked once the ToolChange command finishes OK
  245. // - so no ResumeUnpark() at this spot
  246. unload();
  247. // if we run out of retries, we must do something ... may be raise an error screen and allow the user to do something
  248. // but honestly - if the MMU restarts during every toolchange,
  249. // something else is seriously broken and stopping a print is probably our best option.
  250. }
  251. // reset current position to whatever the planner thinks it is
  252. plan_set_e_position(current_position[E_AXIS]);
  253. if (VerifyFilamentEnteredPTFE()){
  254. return true; // success
  255. } else { // Prepare a retry attempt
  256. unload();
  257. if( retries == 1 && eeprom_read_byte((uint8_t*)EEPROM_MMU_CUTTER_ENABLED) == EEPROM_MMU_CUTTER_ENABLED_enabled){
  258. cut_filament(slot); // try cutting filament tip at the last attempt
  259. }
  260. }
  261. }
  262. return false; // couldn't accomplish the task
  263. }
  264. void MMU2::ToolChangeCommon(uint8_t slot){
  265. while( ! ToolChangeCommonOnce(slot) ){ // while not successfully fed into extruder's PTFE tube
  266. // failed autoretry, report an error by forcing a "printer" error into the MMU infrastructure - it is a hack to leverage existing code
  267. // @@TODO theoretically logic layer may not need to be spoiled with the printer error - may be just the manage_response needs it...
  268. logic.SetPrinterError(ErrorCode::LOAD_TO_EXTRUDER_FAILED);
  269. // We only have to wait for the user to fix the issue and press "Retry".
  270. // Please see CheckUserInput() for details how we "leave" manage_response.
  271. // If manage_response returns false at this spot (MMU operation interrupted aka MMU reset)
  272. // we can safely continue because the MMU is not doing an operation now.
  273. static_cast<void>(manage_response(true, true)); // yes, I'd like to silence [[nodiscard]] warning at this spot by casting to void
  274. }
  275. extruder = slot; //filament change is finished
  276. SpoolJoin::spooljoin.setSlot(slot);
  277. // @@TODO really report onto the serial? May be for the Octoprint? Not important now
  278. // SERIAL_ECHO_START();
  279. // SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(extruder));
  280. ++toolchange_counter;
  281. }
  282. bool MMU2::tool_change(uint8_t slot) {
  283. if( ! WaitForMMUReady())
  284. return false;
  285. if (slot != extruder) {
  286. if (/*FindaDetectsFilament()*/
  287. /*!IS_SD_PRINTING && !usb_timer.running()*/
  288. ! printer_active()
  289. ) {
  290. // If Tcodes are used manually through the serial
  291. // we need to unload manually as well -- but only if FINDA detects filament
  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_load_to_nozzle_sequence();
  324. } break;
  325. }
  326. return true;
  327. }
  328. void MMU2::get_statistics() {
  329. logic.Statistics();
  330. }
  331. uint8_t __attribute__((noinline)) 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. void FullScreenMsg(const char *pgmS, uint8_t slot){
  375. lcd_update_enable(false);
  376. lcd_clear();
  377. lcd_puts_at_P(0, 1, pgmS);
  378. lcd_print(' ');
  379. lcd_print(slot + 1);
  380. }
  381. bool MMU2::cut_filament(uint8_t slot){
  382. if( ! WaitForMMUReady())
  383. return false;
  384. FullScreenMsg(_T(MSG_CUT_FILAMENT), slot);
  385. {
  386. if( FindaDetectsFilament() ){
  387. unload();
  388. }
  389. ReportingRAII rep(CommandInProgress::CutFilament);
  390. for(;;){
  391. logic.CutFilament(slot);
  392. if( manage_response(false, true) )
  393. break;
  394. IncrementMMUFails();
  395. }
  396. }
  397. extruder = MMU2_NO_TOOL;
  398. tool_change_extruder = MMU2_NO_TOOL;
  399. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  400. return true;
  401. }
  402. bool MMU2::loading_test(uint8_t slot){
  403. FullScreenMsg(_T(MSG_TESTING_FILAMENT), slot);
  404. tool_change(slot);
  405. st_synchronize();
  406. unload();
  407. lcd_update_enable(true);
  408. return true;
  409. }
  410. bool MMU2::load_filament(uint8_t slot) {
  411. if( ! WaitForMMUReady())
  412. return false;
  413. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  414. ReportingRAII rep(CommandInProgress::LoadFilament);
  415. for(;;) {
  416. logic.LoadFilament(slot);
  417. if( manage_response(false, false) )
  418. break;
  419. IncrementMMUFails();
  420. }
  421. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  422. lcd_update_enable(true);
  423. return true;
  424. }
  425. struct LoadingToNozzleRAII {
  426. MMU2 &mmu2;
  427. explicit inline LoadingToNozzleRAII(MMU2 &mmu2):mmu2(mmu2){
  428. mmu2.loadingToNozzle = true;
  429. }
  430. inline ~LoadingToNozzleRAII(){
  431. mmu2.loadingToNozzle = false;
  432. }
  433. };
  434. bool MMU2::load_filament_to_nozzle(uint8_t slot) {
  435. if( ! WaitForMMUReady())
  436. return false;
  437. LoadingToNozzleRAII ln(*this);
  438. WaitForHotendTargetTempBeep();
  439. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  440. {
  441. // used for MMU-menu operation "Load to Nozzle"
  442. ReportingRAII rep(CommandInProgress::ToolChange);
  443. FSensorBlockRunout blockRunout;
  444. if( extruder != MMU2_NO_TOOL ){ // we already have some filament loaded - free it + shape its tip properly
  445. filament_ramming();
  446. }
  447. ToolChangeCommon(slot);
  448. // Finish loading to the nozzle with finely tuned steps.
  449. execute_load_to_nozzle_sequence();
  450. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  451. }
  452. lcd_update_enable(true);
  453. return true;
  454. }
  455. bool MMU2::eject_filament(uint8_t slot, bool recover) {
  456. if( ! WaitForMMUReady())
  457. return false;
  458. FullScreenMsg(_T(MSG_EJECT_FILAMENT), slot);
  459. {
  460. if( FindaDetectsFilament() ){
  461. unload();
  462. }
  463. ReportingRAII rep(CommandInProgress::EjectFilament);
  464. for(;;) {
  465. logic.EjectFilament(slot);
  466. if( manage_response(false, true) )
  467. break;
  468. IncrementMMUFails();
  469. }
  470. }
  471. extruder = MMU2_NO_TOOL;
  472. tool_change_extruder = MMU2_NO_TOOL;
  473. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  474. // disable_E0();
  475. return true;
  476. }
  477. void MMU2::Button(uint8_t index){
  478. LogEchoEvent_P(PSTR("Button"));
  479. logic.Button(index);
  480. }
  481. void MMU2::Home(uint8_t mode){
  482. logic.Home(mode);
  483. }
  484. void MMU2::SaveHotendTemp(bool turn_off_nozzle) {
  485. if (mmu_print_saved & SavedState::Cooldown) return;
  486. if (turn_off_nozzle && !(mmu_print_saved & SavedState::CooldownPending)){
  487. resume_hotend_temp = degTargetHotend(active_extruder);
  488. mmu_print_saved |= SavedState::CooldownPending;
  489. LogEchoEvent_P(PSTR("Heater cooldown pending"));
  490. }
  491. }
  492. void MMU2::SaveAndPark(bool move_axes) {
  493. if (mmu_print_saved == SavedState::None) { // First occurrence. Save current position, park print head, disable nozzle heater.
  494. LogEchoEvent_P(PSTR("Saving and parking"));
  495. st_synchronize();
  496. if (move_axes){
  497. mmu_print_saved |= SavedState::ParkExtruder;
  498. // save current pos
  499. for(uint8_t i = 0; i < 3; ++i){
  500. resume_position.xyz[i] = current_position[i];
  501. }
  502. // lift Z
  503. raise_z(MMU_ERR_Z_PAUSE_LIFT);
  504. // move XY aside
  505. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS])
  506. {
  507. current_position[X_AXIS] = MMU_ERR_X_PAUSE_POS;
  508. current_position[Y_AXIS] = MMU_ERR_Y_PAUSE_POS;
  509. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  510. st_synchronize();
  511. }
  512. }
  513. }
  514. // keep the motors powered forever (until some other strategy is chosen)
  515. // @@TODO do we need that in 8bit?
  516. // gcode.reset_stepper_timeout();
  517. }
  518. void MMU2::ResumeHotendTemp() {
  519. if ((mmu_print_saved & SavedState::CooldownPending))
  520. {
  521. // Clear the "pending" flag if we haven't cooled yet.
  522. mmu_print_saved &= ~(SavedState::CooldownPending);
  523. LogEchoEvent_P(PSTR("Cooldown flag cleared"));
  524. }
  525. if ((mmu_print_saved & SavedState::Cooldown) && resume_hotend_temp) {
  526. LogEchoEvent_P(PSTR("Resuming Temp"));
  527. MMU2_ECHO_MSGRPGM(PSTR("Restoring hotend temperature "));
  528. SERIAL_ECHOLN(resume_hotend_temp);
  529. mmu_print_saved &= ~(SavedState::Cooldown);
  530. setTargetHotend(resume_hotend_temp, active_extruder);
  531. lcd_display_message_fullscreen_P(_i("MMU Retry: Restoring temperature...")); ////MSG_MMU_RESTORE_TEMP c=20 r=4
  532. //@todo better report the event and let the GUI do its work somewhere else
  533. ReportErrorHookSensorLineRender();
  534. waitForHotendTargetTemp(100, []{
  535. manage_inactivity(true);
  536. mmu2.mmu_loop_inner(false);
  537. ReportErrorHookDynamicRender();
  538. });
  539. lcd_update_enable(true); // temporary hack to stop this locking the printer...
  540. LogEchoEvent_P(PSTR("Hotend temperature reached"));
  541. lcd_clear();
  542. }
  543. }
  544. void MMU2::ResumeUnpark(){
  545. if (mmu_print_saved & SavedState::ParkExtruder) {
  546. LogEchoEvent_P(PSTR("Resuming XYZ"));
  547. current_position[X_AXIS] = resume_position.xyz[X_AXIS];
  548. current_position[Y_AXIS] = resume_position.xyz[Y_AXIS];
  549. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  550. st_synchronize();
  551. current_position[Z_AXIS] = resume_position.xyz[Z_AXIS];
  552. plan_buffer_line_curposXYZE(NOZZLE_PARK_Z_FEEDRATE);
  553. st_synchronize();
  554. mmu_print_saved &= ~(SavedState::ParkExtruder);
  555. }
  556. }
  557. void MMU2::CheckUserInput(){
  558. auto btn = ButtonPressed((uint16_t)lastErrorCode);
  559. // Was a button pressed on the MMU itself instead of the LCD?
  560. if (btn == Buttons::NoButton && lastButton != Buttons::NoButton){
  561. btn = lastButton;
  562. lastButton = Buttons::NoButton; // Clear it.
  563. }
  564. switch (btn) {
  565. case Left:
  566. case Middle:
  567. case Right:
  568. SERIAL_ECHOPGM("CheckUserInput-btnLMR ");
  569. SERIAL_ECHOLN(btn);
  570. // clear the explicit printer error as soon as possible so that the MMU error screens + reporting doesn't get too confused
  571. if( lastErrorCode == ErrorCode::LOAD_TO_EXTRUDER_FAILED ){
  572. // A horrible hack - clear the explicit printer error allowing manage_response to recover on MMU's Finished state
  573. // Moreover - if the MMU is currently doing something (like the LoadFilament - see comment above)
  574. // we'll actually wait for it automagically in manage_response and after it finishes correctly,
  575. // we'll issue another command (like toolchange)
  576. logic.ClearPrinterError();
  577. lastErrorSource = ErrorSourceMMU; // this seems to help clearing the error screen
  578. }
  579. ResumeHotendTemp(); // Recover the hotend temp before we attempt to do anything else...
  580. // In case of LOAD_TO_EXTRUDER_FAILED sending a button into the MMU has an interesting side effect
  581. // - it triggers the standalone LoadFilament function on the current active slot.
  582. // Considering the fact, that we are recovering from a failed load to extruder, this side effect is actually quite beneficial
  583. // - it checks if the filament is correctly loaded in the MMU (we assume the user was playing with the filament to recover from the failed load)
  584. // Moreover, the "button" makes all the nice things like temp recovery
  585. Button(btn);
  586. // A quick hack: for specific error codes move the E-motor every time.
  587. // Not sure if we can rely on the fsensor.
  588. // Just plan the move, let the MMU take over when it is ready
  589. switch(lastErrorCode){
  590. case ErrorCode::FSENSOR_DIDNT_SWITCH_OFF:
  591. case ErrorCode::FSENSOR_TOO_EARLY:
  592. HelpUnloadToFinda();
  593. break;
  594. default:
  595. break;
  596. }
  597. break;
  598. case RestartMMU:
  599. Reset(ResetPin); // we cannot do power cycle on the MK3
  600. // ... but mmu2_power.cpp knows this and triggers a soft-reset instead.
  601. break;
  602. case DisableMMU:
  603. Stop(); // Poweroff handles updating the EEPROM shutoff.
  604. break;
  605. case StopPrint:
  606. // @@TODO not sure if we shall handle this high level operation at this spot
  607. break;
  608. default:
  609. break;
  610. }
  611. }
  612. /// Originally, this was used to wait for response and deal with timeout if necessary.
  613. /// The new protocol implementation enables much nicer and intense reporting, so this method will boil down
  614. /// just to verify the result of an issued command (which was basically the original idea)
  615. ///
  616. /// 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.
  617. /// 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.
  618. /// That's what's being done here...
  619. bool MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) {
  620. mmu_print_saved = SavedState::None;
  621. KEEPALIVE_STATE(IN_PROCESS);
  622. LongTimer nozzleTimeout;
  623. for (;;) {
  624. // in our new implementation, we know the exact state of the MMU at any moment, we do not have to wait for a timeout
  625. // So in this case we shall decide if the operation is:
  626. // - still running -> wait normally in idle()
  627. // - failed -> then do the safety moves on the printer like before
  628. // - finished ok -> proceed with reading other commands
  629. manage_heater();
  630. manage_inactivity(true); // calls LogicStep() and remembers its return status
  631. lcd_update(0);
  632. if (mmu_print_saved & SavedState::CooldownPending){
  633. if (!nozzleTimeout.running()){
  634. nozzleTimeout.start();
  635. LogEchoEvent_P(PSTR("Cooling Timeout started"));
  636. } else if (nozzleTimeout.expired(DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul)){ // mins->msec.
  637. mmu_print_saved &= ~(SavedState::CooldownPending);
  638. mmu_print_saved |= SavedState::Cooldown;
  639. setAllTargetHotends(0);
  640. LogEchoEvent_P(PSTR("Heater cooldown"));
  641. }
  642. } else if (nozzleTimeout.running()) {
  643. nozzleTimeout.stop();
  644. LogEchoEvent_P(PSTR("Cooling timer stopped"));
  645. }
  646. switch (logicStepLastStatus) {
  647. case Finished:
  648. // command/operation completed, let Marlin continue its work
  649. // the E may have some more moves to finish - wait for them
  650. ResumeHotendTemp();
  651. ResumeUnpark(); // We can now travel back to the tower or wherever we were when we saved.
  652. ResetRetryAttempts(); // Reset the retry counter.
  653. st_synchronize();
  654. return true;
  655. case Interrupted:
  656. // now what :D ... big bad ... ramming, unload, retry the whole command originally issued
  657. return false;
  658. case VersionMismatch: // this basically means the MMU will be disabled until reconnected
  659. CheckUserInput();
  660. return true;
  661. case PrinterError:
  662. SaveAndPark(move_axes);
  663. SaveHotendTemp(turn_off_nozzle);
  664. CheckUserInput();
  665. // if button pressed "Done", return true, otherwise stay within manage_response
  666. // Please see CheckUserInput() for details how we "leave" manage_response
  667. break;
  668. case CommandError:
  669. case CommunicationTimeout:
  670. case ProtocolError:
  671. case ButtonPushed:
  672. if (!inAutoRetry){
  673. // Don't proceed to the park/save if we are doing an autoretry.
  674. SaveAndPark(move_axes);
  675. SaveHotendTemp(turn_off_nozzle);
  676. CheckUserInput();
  677. }
  678. break;
  679. case CommunicationRecovered: // @@TODO communication recovered and may be an error recovered as well
  680. // may be the logic layer can detect the change of state a respond with one "Recovered" to be handled here
  681. ResumeHotendTemp();
  682. ResumeUnpark();
  683. break;
  684. case Processing: // wait for the MMU to respond
  685. default:
  686. break;
  687. }
  688. }
  689. }
  690. StepStatus MMU2::LogicStep(bool reportErrors) {
  691. CheckUserInput(); // Process any buttons before proceeding with another MMU Query
  692. StepStatus ss = logic.Step();
  693. switch (ss) {
  694. case Finished:
  695. // At this point it is safe to trigger a runout and not interrupt the MMU protocol
  696. CheckFINDARunout();
  697. break;
  698. case Processing:
  699. OnMMUProgressMsg(logic.Progress());
  700. break;
  701. case ButtonPushed:
  702. lastButton = logic.Button();
  703. LogEchoEvent_P(PSTR("MMU Button pushed"));
  704. CheckUserInput(); // Process the button immediately
  705. break;
  706. case Interrupted:
  707. // can be silently handed over to a higher layer, no processing necessary at this spot
  708. break;
  709. default:
  710. if(reportErrors) {
  711. switch (ss)
  712. {
  713. case CommandError:
  714. ReportError(logic.Error(), ErrorSourceMMU);
  715. break;
  716. case CommunicationTimeout:
  717. state = xState::Connecting;
  718. ReportError(ErrorCode::MMU_NOT_RESPONDING, ErrorSourcePrinter);
  719. break;
  720. case ProtocolError:
  721. state = xState::Connecting;
  722. ReportError(ErrorCode::PROTOCOL_ERROR, ErrorSourcePrinter);
  723. break;
  724. case VersionMismatch:
  725. StopKeepPowered();
  726. ReportError(ErrorCode::VERSION_MISMATCH, ErrorSourcePrinter);
  727. break;
  728. case PrinterError:
  729. ReportError(logic.PrinterError(), ErrorSourcePrinter);
  730. break;
  731. default:
  732. break;
  733. }
  734. }
  735. }
  736. if( logic.Running() ){
  737. state = xState::Active;
  738. }
  739. return ss;
  740. }
  741. void MMU2::filament_ramming() {
  742. execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step));
  743. }
  744. void MMU2::execute_extruder_sequence(const E_Step *sequence, uint8_t steps) {
  745. st_synchronize();
  746. const E_Step *step = sequence;
  747. for (uint8_t i = 0; i < steps; i++) {
  748. current_position[E_AXIS] += pgm_read_float(&(step->extrude));
  749. plan_buffer_line_curposXYZE(pgm_read_float(&(step->feedRate)));
  750. st_synchronize();
  751. step++;
  752. }
  753. }
  754. void MMU2::execute_load_to_nozzle_sequence() {
  755. st_synchronize();
  756. // Compensate for configurable Extra Loading Distance
  757. current_position[E_AXIS] -= (logic.ExtraLoadDistance() - MMU2_FILAMENT_SENSOR_POSITION);
  758. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  759. }
  760. void MMU2::ReportError(ErrorCode ec, ErrorSource res) {
  761. // Due to a potential lossy error reporting layers linked to this hook
  762. // we'd better report everything to make sure especially the error states
  763. // do not get lost.
  764. // - The good news here is the fact, that the MMU reports the errors repeatedly until resolved.
  765. // - The bad news is, that MMU not responding may repeatedly occur on printers not having the MMU at all.
  766. //
  767. // Not sure how to properly handle this situation, options:
  768. // - skip reporting "MMU not responding" (at least for now)
  769. // - report only changes of states (we can miss an error message)
  770. // - may be some combination of MMUAvailable + UseMMU flags and decide based on their state
  771. // Right now the filtering of MMU_NOT_RESPONDING is done in ReportErrorHook() as it is not a problem if mmu2.cpp
  772. // Depending on the Progress code, we may want to do some action when an error occurs
  773. switch (logic.Progress()){
  774. case ProgressCode::UnloadingToFinda:
  775. unloadFilamentStarted = false;
  776. break;
  777. case ProgressCode::FeedingToFSensor:
  778. // FSENSOR error during load. Make sure E-motor stops moving.
  779. loadFilamentStarted = false;
  780. break;
  781. default:
  782. break;
  783. }
  784. if( ec != lastErrorCode ){ // deduplicate: only report changes in error codes into the log
  785. lastErrorCode = ec;
  786. lastErrorSource = res;
  787. LogErrorEvent_P( _O(PrusaErrorTitle(PrusaErrorCodeIndex((uint16_t)ec))) );
  788. if( ec != ErrorCode::OK ){
  789. IncrementMMUFails();
  790. // check if it is a "power" failure - we consider TMC-related errors as power failures
  791. static constexpr uint16_t tmcMask =
  792. ( (uint16_t)ErrorCode::TMC_IOIN_MISMATCH
  793. | (uint16_t)ErrorCode::TMC_RESET
  794. | (uint16_t)ErrorCode::TMC_UNDERVOLTAGE_ON_CHARGE_PUMP
  795. | (uint16_t)ErrorCode::TMC_SHORT_TO_GROUND
  796. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_WARN
  797. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_ERROR
  798. | (uint16_t)ErrorCode::MMU_SOLDERING_NEEDS_ATTENTION ) & 0x7fffU; // skip the top bit
  799. static_assert(tmcMask == 0x7e00); // just make sure we fail compilation if any of the TMC error codes change
  800. if ((uint16_t)ec & tmcMask) { // @@TODO can be optimized to uint8_t operation
  801. // TMC-related errors are from 0x8200 higher
  802. IncrementTMCFailures();
  803. }
  804. }
  805. }
  806. if( !mmu2.RetryIfPossible((uint16_t)ec) ) {
  807. // If retry attempts are all used up
  808. // or if 'Retry' operation is not available
  809. // raise the MMU error sceen and wait for user input
  810. ReportErrorHook((uint16_t)ec);
  811. }
  812. static_assert(mmu2Magic[0] == 'M'
  813. && mmu2Magic[1] == 'M'
  814. && mmu2Magic[2] == 'U'
  815. && mmu2Magic[3] == '2'
  816. && mmu2Magic[4] == ':'
  817. && strlen_constexpr(mmu2Magic) == 5,
  818. "MMU2 logging prefix mismatch, must be updated at various spots"
  819. );
  820. }
  821. void MMU2::ReportProgress(ProgressCode pc) {
  822. ReportProgressHook((CommandInProgress)logic.CommandInProgress(), (uint16_t)pc);
  823. LogEchoEvent_P( _O(ProgressCodeToText((uint16_t)pc)) );
  824. }
  825. void MMU2::OnMMUProgressMsg(ProgressCode pc){
  826. if (pc != lastProgressCode) {
  827. OnMMUProgressMsgChanged(pc);
  828. } else {
  829. OnMMUProgressMsgSame(pc);
  830. }
  831. }
  832. void MMU2::OnMMUProgressMsgChanged(ProgressCode pc){
  833. ReportProgress(pc);
  834. lastProgressCode = pc;
  835. switch (pc) {
  836. case ProgressCode::UnloadingToFinda:
  837. if ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::UnloadFilament
  838. || ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::ToolChange))
  839. {
  840. // If MK3S sent U0 command, ramming sequence takes care of releasing the filament.
  841. // If Toolchange is done while printing, PrusaSlicer takes care of releasing the filament
  842. // If printing is not in progress, ToolChange will issue a U0 command.
  843. break;
  844. } else {
  845. // We're likely recovering from an MMU error
  846. st_synchronize();
  847. unloadFilamentStarted = true;
  848. HelpUnloadToFinda();
  849. }
  850. break;
  851. case ProgressCode::FeedingToFSensor:
  852. // prepare for the movement of the E-motor
  853. st_synchronize();
  854. loadFilamentStarted = true;
  855. break;
  856. default:
  857. // do nothing yet
  858. break;
  859. }
  860. }
  861. void __attribute__((noinline)) MMU2::HelpUnloadToFinda(){
  862. current_position[E_AXIS] -= MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH;
  863. plan_buffer_line_curposXYZE(MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE);
  864. }
  865. void MMU2::OnMMUProgressMsgSame(ProgressCode pc){
  866. switch (pc) {
  867. case ProgressCode::UnloadingToFinda:
  868. if (unloadFilamentStarted && !blocks_queued()) { // Only plan a move if there is no move ongoing
  869. if (fsensor.getFilamentPresent()) {
  870. HelpUnloadToFinda();
  871. } else {
  872. unloadFilamentStarted = false;
  873. }
  874. }
  875. break;
  876. case ProgressCode::FeedingToFSensor:
  877. if (loadFilamentStarted) {
  878. switch (WhereIsFilament()) {
  879. case FilamentState::AT_FSENSOR:
  880. // fsensor triggered, finish FeedingToExtruder state
  881. loadFilamentStarted = false;
  882. // After the MMU knows the FSENSOR is triggered it will:
  883. // 1. Push the filament by additional 30mm (see fsensorToNozzle)
  884. // 2. Disengage the idler and push another 2mm.
  885. current_position[E_AXIS] += logic.ExtraLoadDistance() + 2;
  886. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  887. break;
  888. case FilamentState::NOT_PRESENT:
  889. // fsensor not triggered, continue moving extruder
  890. if (!blocks_queued()) { // Only plan a move if there is no move ongoing
  891. current_position[E_AXIS] += 2.0f;
  892. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  893. }
  894. break;
  895. default:
  896. // Abort here?
  897. break;
  898. }
  899. }
  900. break;
  901. default:
  902. // do nothing yet
  903. break;
  904. }
  905. }
  906. } // namespace MMU2