mmu2.cpp 34 KB

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