mmu2.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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_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_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. for(;;) {
  234. tool_change_extruder = slot;
  235. logic.ToolChange(slot); // let the MMU pull the filament out and push a new one in
  236. if( manage_response(true, true) )
  237. break;
  238. // otherwise: failed to perform the command - unload first and then let it run again
  239. IncrementMMUFails();
  240. // just in case we stood in an error screen for too long and the hotend got cold
  241. ResumeHotendTemp();
  242. // if the extruder has been parked, it will get unparked once the ToolChange command finishes OK
  243. // - so no ResumeUnpark() at this spot
  244. unload();
  245. // if we run out of retries, we must do something ... may be raise an error screen and allow the user to do something
  246. // but honestly - if the MMU restarts during every toolchange,
  247. // something else is seriously broken and stopping a print is probably our best option.
  248. }
  249. // reset current position to whatever the planner thinks it is
  250. plan_set_e_position(current_position[E_AXIS]);
  251. if (VerifyFilamentEnteredPTFE()) break;
  252. else { // Prepare a retry attempt
  253. unload(); // TODO cut filament
  254. }
  255. }
  256. extruder = slot; //filament change is finished
  257. SpoolJoin::spooljoin.setSlot(slot);
  258. // @@TODO really report onto the serial? May be for the Octoprint? Not important now
  259. // SERIAL_ECHO_START();
  260. // SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(extruder));
  261. ++toolchange_counter;
  262. }
  263. bool MMU2::tool_change(uint8_t slot) {
  264. if( ! WaitForMMUReady())
  265. return false;
  266. if (slot != extruder) {
  267. if (FindaDetectsFilament()) {
  268. // If Tcodes are used manually through the serial
  269. // we need to unload manually as well -- but only if FINDA detects filament
  270. unload();
  271. }
  272. ReportingRAII rep(CommandInProgress::ToolChange);
  273. FSensorBlockRunout blockRunout;
  274. st_synchronize();
  275. ToolChangeCommon(slot);
  276. }
  277. return true;
  278. }
  279. /// Handle special T?/Tx/Tc commands
  280. ///
  281. ///- T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  282. ///- 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.
  283. ///- Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated.
  284. bool MMU2::tool_change(char code, uint8_t slot) {
  285. if( ! WaitForMMUReady())
  286. return false;
  287. FSensorBlockRunout blockRunout;
  288. switch (code) {
  289. case '?': {
  290. waitForHotendTargetTemp(100, []{});
  291. load_filament_to_nozzle(slot);
  292. } break;
  293. case 'x': {
  294. set_extrude_min_temp(0); // Allow cold extrusion since Tx only loads to the gears not nozzle
  295. st_synchronize();
  296. ToolChangeCommon(slot); // the only difference was manage_response(false, false), but probably good enough
  297. set_extrude_min_temp(EXTRUDE_MINTEMP);
  298. } break;
  299. case 'c': {
  300. waitForHotendTargetTemp(100, []{});
  301. execute_load_to_nozzle_sequence();
  302. } break;
  303. }
  304. return true;
  305. }
  306. void MMU2::get_statistics() {
  307. logic.Statistics();
  308. }
  309. uint8_t MMU2::get_current_tool() const {
  310. return extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : extruder;
  311. }
  312. uint8_t MMU2::get_tool_change_tool() const {
  313. return tool_change_extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : tool_change_extruder;
  314. }
  315. bool MMU2::set_filament_type(uint8_t slot, uint8_t type) {
  316. if( ! WaitForMMUReady())
  317. return false;
  318. // @@TODO - this is not supported in the new MMU yet
  319. slot = slot; // @@TODO
  320. type = type; // @@TODO
  321. // cmd_arg = filamentType;
  322. // command(MMU_CMD_F0 + index);
  323. if( ! manage_response(false, false) ){
  324. // @@TODO failed to perform the command - retry
  325. ;
  326. } // true, true); -- Comment: how is it possible for a filament type set to fail?
  327. return true;
  328. }
  329. bool MMU2::unload() {
  330. if( ! WaitForMMUReady())
  331. return false;
  332. WaitForHotendTargetTempBeep();
  333. {
  334. FSensorBlockRunout blockRunout;
  335. ReportingRAII rep(CommandInProgress::UnloadFilament);
  336. filament_ramming();
  337. // we assume the printer managed to relieve filament tip from the gears,
  338. // so repeating that part in case of an MMU restart is not necessary
  339. for(;;) {
  340. logic.UnloadFilament();
  341. if( manage_response(false, true) )
  342. break;
  343. IncrementMMUFails();
  344. }
  345. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  346. // no active tool
  347. extruder = MMU2_NO_TOOL;
  348. tool_change_extruder = MMU2_NO_TOOL;
  349. }
  350. return true;
  351. }
  352. bool MMU2::cut_filament(uint8_t slot){
  353. if( ! WaitForMMUReady())
  354. return false;
  355. ReportingRAII rep(CommandInProgress::CutFilament);
  356. for(;;){
  357. logic.CutFilament(slot);
  358. if( manage_response(false, true) )
  359. break;
  360. IncrementMMUFails();
  361. }
  362. return true;
  363. }
  364. void FullScreenMsg(const char *pgmS, uint8_t slot){
  365. lcd_update_enable(false);
  366. lcd_clear();
  367. lcd_puts_at_P(0, 1, pgmS);
  368. lcd_print(' ');
  369. lcd_print(slot + 1);
  370. }
  371. bool MMU2::loading_test(uint8_t slot){
  372. FullScreenMsg(_T(MSG_TESTING_FILAMENT), slot);
  373. tool_change(slot);
  374. st_synchronize();
  375. unload();
  376. lcd_update_enable(true);
  377. return true;
  378. }
  379. bool MMU2::load_filament(uint8_t slot) {
  380. if( ! WaitForMMUReady())
  381. return false;
  382. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  383. ReportingRAII rep(CommandInProgress::LoadFilament);
  384. for(;;) {
  385. logic.LoadFilament(slot);
  386. if( manage_response(false, false) )
  387. break;
  388. IncrementMMUFails();
  389. }
  390. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  391. lcd_update_enable(true);
  392. return true;
  393. }
  394. struct LoadingToNozzleRAII {
  395. MMU2 &mmu2;
  396. explicit inline LoadingToNozzleRAII(MMU2 &mmu2):mmu2(mmu2){
  397. mmu2.loadingToNozzle = true;
  398. }
  399. inline ~LoadingToNozzleRAII(){
  400. mmu2.loadingToNozzle = false;
  401. }
  402. };
  403. bool MMU2::load_filament_to_nozzle(uint8_t slot) {
  404. if( ! WaitForMMUReady())
  405. return false;
  406. LoadingToNozzleRAII ln(*this);
  407. WaitForHotendTargetTempBeep();
  408. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  409. {
  410. // used for MMU-menu operation "Load to Nozzle"
  411. ReportingRAII rep(CommandInProgress::ToolChange);
  412. FSensorBlockRunout blockRunout;
  413. if( extruder != MMU2_NO_TOOL ){ // we already have some filament loaded - free it + shape its tip properly
  414. filament_ramming();
  415. }
  416. ToolChangeCommon(slot);
  417. // Finish loading to the nozzle with finely tuned steps.
  418. execute_load_to_nozzle_sequence();
  419. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  420. }
  421. lcd_update_enable(true);
  422. return true;
  423. }
  424. bool MMU2::eject_filament(uint8_t slot, bool recover) {
  425. if( ! WaitForMMUReady())
  426. return false;
  427. ReportingRAII rep(CommandInProgress::EjectFilament);
  428. current_position[E_AXIS] -= MMU2_FILAMENTCHANGE_EJECT_FEED;
  429. plan_buffer_line_curposXYZE(2500.F / 60.F);
  430. st_synchronize();
  431. logic.EjectFilament(slot);
  432. if( ! manage_response(false, false) ){
  433. // @@TODO failed to perform the command - retry
  434. ;
  435. }
  436. if (recover) {
  437. // LCD_MESSAGEPGM(MSG_MMU2_EJECT_RECOVER);
  438. Sound_MakeSound(e_SOUND_TYPE_StandardPrompt);
  439. //@@TODO wait_for_user = true;
  440. //#if ENABLED(HOST_PROMPT_SUPPORT)
  441. // host_prompt_do(PROMPT_USER_CONTINUE, PSTR("MMU2 Eject Recover"), PSTR("Continue"));
  442. //#endif
  443. //#if ENABLED(EXTENSIBLE_UI)
  444. // ExtUI::onUserConfirmRequired_P(PSTR("MMU2 Eject Recover"));
  445. //#endif
  446. //@@TODO while (wait_for_user) idle(true);
  447. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  448. // logic.Command(); //@@TODO command(MMU_CMD_R0);
  449. if( ! manage_response(false, false) ){
  450. // @@TODO failed to perform the command - retry
  451. ;
  452. }
  453. }
  454. // no active tool
  455. extruder = MMU2_NO_TOOL;
  456. tool_change_extruder = MMU2_NO_TOOL;
  457. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  458. // disable_E0();
  459. return true;
  460. }
  461. void MMU2::Button(uint8_t index){
  462. LogEchoEvent_P(PSTR("Button"));
  463. logic.Button(index);
  464. }
  465. void MMU2::Home(uint8_t mode){
  466. logic.Home(mode);
  467. }
  468. void MMU2::SaveHotendTemp(bool turn_off_nozzle) {
  469. if (mmu_print_saved & SavedState::Cooldown) return;
  470. if (turn_off_nozzle && !(mmu_print_saved & SavedState::CooldownPending)){
  471. resume_hotend_temp = degTargetHotend(active_extruder);
  472. mmu_print_saved |= SavedState::CooldownPending;
  473. LogEchoEvent_P(PSTR("Heater cooldown pending"));
  474. }
  475. }
  476. void MMU2::SaveAndPark(bool move_axes) {
  477. if (mmu_print_saved == SavedState::None) { // First occurrence. Save current position, park print head, disable nozzle heater.
  478. LogEchoEvent_P(PSTR("Saving and parking"));
  479. st_synchronize();
  480. if (move_axes){
  481. mmu_print_saved |= SavedState::ParkExtruder;
  482. // save current pos
  483. for(uint8_t i = 0; i < 3; ++i){
  484. resume_position.xyz[i] = current_position[i];
  485. }
  486. // lift Z
  487. raise_z(MMU_ERR_Z_PAUSE_LIFT);
  488. // move XY aside
  489. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS])
  490. {
  491. current_position[X_AXIS] = MMU_ERR_X_PAUSE_POS;
  492. current_position[Y_AXIS] = MMU_ERR_Y_PAUSE_POS;
  493. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  494. st_synchronize();
  495. }
  496. }
  497. }
  498. // keep the motors powered forever (until some other strategy is chosen)
  499. // @@TODO do we need that in 8bit?
  500. // gcode.reset_stepper_timeout();
  501. }
  502. void MMU2::ResumeHotendTemp() {
  503. if ((mmu_print_saved & SavedState::CooldownPending))
  504. {
  505. // Clear the "pending" flag if we haven't cooled yet.
  506. mmu_print_saved &= ~(SavedState::CooldownPending);
  507. LogEchoEvent_P(PSTR("Cooldown flag cleared"));
  508. }
  509. if ((mmu_print_saved & SavedState::Cooldown) && resume_hotend_temp) {
  510. LogEchoEvent_P(PSTR("Resuming Temp"));
  511. MMU2_ECHO_MSGRPGM(PSTR("Restoring hotend temperature "));
  512. SERIAL_ECHOLN(resume_hotend_temp);
  513. mmu_print_saved &= ~(SavedState::Cooldown);
  514. setTargetHotend(resume_hotend_temp, active_extruder);
  515. lcd_display_message_fullscreen_P(_i("MMU Retry: Restoring temperature...")); ////MSG_MMU_RESTORE_TEMP c=20 r=4
  516. //@todo better report the event and let the GUI do its work somewhere else
  517. ReportErrorHookSensorLineRender();
  518. waitForHotendTargetTemp(100, []{
  519. manage_inactivity(true);
  520. mmu2.mmu_loop_inner(false);
  521. ReportErrorHookDynamicRender();
  522. });
  523. lcd_update_enable(true); // temporary hack to stop this locking the printer...
  524. LogEchoEvent_P(PSTR("Hotend temperature reached"));
  525. lcd_clear();
  526. }
  527. }
  528. void MMU2::ResumeUnpark(){
  529. if (mmu_print_saved & SavedState::ParkExtruder) {
  530. LogEchoEvent_P(PSTR("Resuming XYZ"));
  531. current_position[X_AXIS] = resume_position.xyz[X_AXIS];
  532. current_position[Y_AXIS] = resume_position.xyz[Y_AXIS];
  533. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  534. st_synchronize();
  535. current_position[Z_AXIS] = resume_position.xyz[Z_AXIS];
  536. plan_buffer_line_curposXYZE(NOZZLE_PARK_Z_FEEDRATE);
  537. st_synchronize();
  538. mmu_print_saved &= ~(SavedState::ParkExtruder);
  539. }
  540. }
  541. void MMU2::CheckUserInput(){
  542. auto btn = ButtonPressed((uint16_t)lastErrorCode);
  543. // Was a button pressed on the MMU itself instead of the LCD?
  544. if (btn == Buttons::NoButton && lastButton != Buttons::NoButton){
  545. btn = lastButton;
  546. lastButton = Buttons::NoButton; // Clear it.
  547. }
  548. switch (btn) {
  549. case Left:
  550. case Middle:
  551. case Right:
  552. SERIAL_ECHOPGM("CheckUserInput-btnLMR ");
  553. SERIAL_ECHOLN(btn);
  554. ResumeHotendTemp(); // Recover the hotend temp before we attempt to do anything else...
  555. Button(btn);
  556. // A quick hack: for specific error codes move the E-motor every time.
  557. // Not sure if we can rely on the fsensor.
  558. // Just plan the move, let the MMU take over when it is ready
  559. switch(lastErrorCode){
  560. case ErrorCode::FSENSOR_DIDNT_SWITCH_OFF:
  561. case ErrorCode::FSENSOR_TOO_EARLY:
  562. HelpUnloadToFinda();
  563. break;
  564. default:
  565. break;
  566. }
  567. break;
  568. case RestartMMU:
  569. Reset(ResetPin); // we cannot do power cycle on the MK3
  570. // ... but mmu2_power.cpp knows this and triggers a soft-reset instead.
  571. break;
  572. case DisableMMU:
  573. Stop(); // Poweroff handles updating the EEPROM shutoff.
  574. break;
  575. case StopPrint:
  576. // @@TODO not sure if we shall handle this high level operation at this spot
  577. break;
  578. default:
  579. break;
  580. }
  581. }
  582. /// Originally, this was used to wait for response and deal with timeout if necessary.
  583. /// The new protocol implementation enables much nicer and intense reporting, so this method will boil down
  584. /// just to verify the result of an issued command (which was basically the original idea)
  585. ///
  586. /// 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.
  587. /// 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.
  588. /// That's what's being done here...
  589. bool MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) {
  590. mmu_print_saved = SavedState::None;
  591. KEEPALIVE_STATE(IN_PROCESS);
  592. LongTimer nozzleTimeout;
  593. for (;;) {
  594. // in our new implementation, we know the exact state of the MMU at any moment, we do not have to wait for a timeout
  595. // So in this case we shall decide if the operation is:
  596. // - still running -> wait normally in idle()
  597. // - failed -> then do the safety moves on the printer like before
  598. // - finished ok -> proceed with reading other commands
  599. manage_heater();
  600. manage_inactivity(true); // calls LogicStep() and remembers its return status
  601. lcd_update(0);
  602. if (mmu_print_saved & SavedState::CooldownPending){
  603. if (!nozzleTimeout.running()){
  604. nozzleTimeout.start();
  605. LogEchoEvent_P(PSTR("Cooling Timeout started"));
  606. } else if (nozzleTimeout.expired(DEFAULT_SAFETYTIMER_TIME_MINS*60*1000ul)){ // mins->msec.
  607. mmu_print_saved &= ~(SavedState::CooldownPending);
  608. mmu_print_saved |= SavedState::Cooldown;
  609. setAllTargetHotends(0);
  610. LogEchoEvent_P(PSTR("Heater cooldown"));
  611. }
  612. } else if (nozzleTimeout.running()) {
  613. nozzleTimeout.stop();
  614. LogEchoEvent_P(PSTR("Cooling timer stopped"));
  615. }
  616. switch (logicStepLastStatus) {
  617. case Finished:
  618. // command/operation completed, let Marlin continue its work
  619. // the E may have some more moves to finish - wait for them
  620. ResumeHotendTemp();
  621. ResumeUnpark(); // We can now travel back to the tower or wherever we were when we saved.
  622. ResetRetryAttempts(); // Reset the retry counter.
  623. st_synchronize();
  624. return true;
  625. case Interrupted:
  626. // now what :D ... big bad ... ramming, unload, retry the whole command originally issued
  627. return false;
  628. case VersionMismatch: // this basically means the MMU will be disabled until reconnected
  629. CheckUserInput();
  630. return true;
  631. case CommandError:
  632. case CommunicationTimeout:
  633. case ProtocolError:
  634. case ButtonPushed:
  635. if (!inAutoRetry){
  636. // Don't proceed to the park/save if we are doing an autoretry.
  637. SaveAndPark(move_axes);
  638. SaveHotendTemp(turn_off_nozzle);
  639. CheckUserInput();
  640. }
  641. break;
  642. case CommunicationRecovered: // @@TODO communication recovered and may be an error recovered as well
  643. // may be the logic layer can detect the change of state a respond with one "Recovered" to be handled here
  644. ResumeHotendTemp();
  645. ResumeUnpark();
  646. break;
  647. case Processing: // wait for the MMU to respond
  648. default:
  649. break;
  650. }
  651. }
  652. }
  653. StepStatus MMU2::LogicStep(bool reportErrors) {
  654. CheckUserInput(); // Process any buttons before proceeding with another MMU Query
  655. StepStatus ss = logic.Step();
  656. switch (ss) {
  657. case Finished:
  658. // At this point it is safe to trigger a runout and not interrupt the MMU protocol
  659. CheckFINDARunout();
  660. break;
  661. case Processing:
  662. OnMMUProgressMsg(logic.Progress());
  663. break;
  664. case ButtonPushed:
  665. lastButton = logic.Button();
  666. LogEchoEvent_P(PSTR("MMU Button pushed"));
  667. CheckUserInput(); // Process the button immediately
  668. break;
  669. case Interrupted:
  670. // can be silently handed over to a higher layer, no processing necessary at this spot
  671. break;
  672. default:
  673. if(reportErrors) {
  674. switch (ss)
  675. {
  676. case CommandError:
  677. ReportError(logic.Error(), ErrorSourceMMU);
  678. break;
  679. case CommunicationTimeout:
  680. state = xState::Connecting;
  681. ReportError(ErrorCode::MMU_NOT_RESPONDING, ErrorSourcePrinter);
  682. break;
  683. case ProtocolError:
  684. state = xState::Connecting;
  685. ReportError(ErrorCode::PROTOCOL_ERROR, ErrorSourcePrinter);
  686. break;
  687. case VersionMismatch:
  688. StopKeepPowered();
  689. ReportError(ErrorCode::VERSION_MISMATCH, ErrorSourcePrinter);
  690. break;
  691. default:
  692. break;
  693. }
  694. }
  695. }
  696. if( logic.Running() ){
  697. state = xState::Active;
  698. }
  699. return ss;
  700. }
  701. void MMU2::filament_ramming() {
  702. execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step));
  703. }
  704. void MMU2::execute_extruder_sequence(const E_Step *sequence, uint8_t steps) {
  705. st_synchronize();
  706. const E_Step *step = sequence;
  707. for (uint8_t i = 0; i < steps; i++) {
  708. current_position[E_AXIS] += pgm_read_float(&(step->extrude));
  709. plan_buffer_line_curposXYZE(pgm_read_float(&(step->feedRate)));
  710. st_synchronize();
  711. step++;
  712. }
  713. }
  714. void MMU2::execute_load_to_nozzle_sequence() {
  715. st_synchronize();
  716. // Compensate for configurable Extra Loading Distance
  717. current_position[E_AXIS] -= (logic.ExtraLoadDistance() - MMU2_FILAMENT_SENSOR_POSITION);
  718. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  719. }
  720. void MMU2::ReportError(ErrorCode ec, ErrorSource res) {
  721. // Due to a potential lossy error reporting layers linked to this hook
  722. // we'd better report everything to make sure especially the error states
  723. // do not get lost.
  724. // - The good news here is the fact, that the MMU reports the errors repeatedly until resolved.
  725. // - The bad news is, that MMU not responding may repeatedly occur on printers not having the MMU at all.
  726. //
  727. // Not sure how to properly handle this situation, options:
  728. // - skip reporting "MMU not responding" (at least for now)
  729. // - report only changes of states (we can miss an error message)
  730. // - may be some combination of MMUAvailable + UseMMU flags and decide based on their state
  731. // Right now the filtering of MMU_NOT_RESPONDING is done in ReportErrorHook() as it is not a problem if mmu2.cpp
  732. // Depending on the Progress code, we may want to do some action when an error occurs
  733. switch (logic.Progress()){
  734. case ProgressCode::UnloadingToFinda:
  735. unloadFilamentStarted = false;
  736. break;
  737. case ProgressCode::FeedingToFSensor:
  738. // FSENSOR error during load. Make sure E-motor stops moving.
  739. loadFilamentStarted = false;
  740. break;
  741. default:
  742. break;
  743. }
  744. if( ec != lastErrorCode ){ // deduplicate: only report changes in error codes into the log
  745. lastErrorCode = ec;
  746. lastErrorSource = res;
  747. LogErrorEvent_P( _O(PrusaErrorTitle(PrusaErrorCodeIndex((uint16_t)ec))) );
  748. if( ec != ErrorCode::OK ){
  749. IncrementMMUFails();
  750. // check if it is a "power" failure - we consider TMC-related errors as power failures
  751. static constexpr uint16_t tmcMask =
  752. ( (uint16_t)ErrorCode::TMC_IOIN_MISMATCH
  753. | (uint16_t)ErrorCode::TMC_RESET
  754. | (uint16_t)ErrorCode::TMC_UNDERVOLTAGE_ON_CHARGE_PUMP
  755. | (uint16_t)ErrorCode::TMC_SHORT_TO_GROUND
  756. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_WARN
  757. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_ERROR
  758. | (uint16_t)ErrorCode::MMU_SOLDERING_NEEDS_ATTENTION ) & 0x7fffU; // skip the top bit
  759. static_assert(tmcMask == 0x7e00); // just make sure we fail compilation if any of the TMC error codes change
  760. if ((uint16_t)ec & tmcMask) { // @@TODO can be optimized to uint8_t operation
  761. // TMC-related errors are from 0x8200 higher
  762. IncrementTMCFailures();
  763. }
  764. }
  765. }
  766. if( !mmu2.RetryIfPossible((uint16_t)ec) ) {
  767. // If retry attempts are all used up
  768. // or if 'Retry' operation is not available
  769. // raise the MMU error sceen and wait for user input
  770. ReportErrorHook((uint16_t)ec);
  771. }
  772. static_assert(mmu2Magic[0] == 'M'
  773. && mmu2Magic[1] == 'M'
  774. && mmu2Magic[2] == 'U'
  775. && mmu2Magic[3] == '2'
  776. && mmu2Magic[4] == ':'
  777. && strlen_constexpr(mmu2Magic) == 5,
  778. "MMU2 logging prefix mismatch, must be updated at various spots"
  779. );
  780. }
  781. void MMU2::ReportProgress(ProgressCode pc) {
  782. ReportProgressHook((CommandInProgress)logic.CommandInProgress(), (uint16_t)pc);
  783. LogEchoEvent_P( _O(ProgressCodeToText((uint16_t)pc)) );
  784. }
  785. void MMU2::OnMMUProgressMsg(ProgressCode pc){
  786. if (pc != lastProgressCode) {
  787. OnMMUProgressMsgChanged(pc);
  788. } else {
  789. OnMMUProgressMsgSame(pc);
  790. }
  791. }
  792. void MMU2::OnMMUProgressMsgChanged(ProgressCode pc){
  793. ReportProgress(pc);
  794. lastProgressCode = pc;
  795. switch (pc) {
  796. case ProgressCode::UnloadingToFinda:
  797. if ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::UnloadFilament
  798. || ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::ToolChange))
  799. {
  800. // If MK3S sent U0 command, ramming sequence takes care of releasing the filament.
  801. // If Toolchange is done while printing, PrusaSlicer takes care of releasing the filament
  802. // If printing is not in progress, ToolChange will issue a U0 command.
  803. break;
  804. } else {
  805. // We're likely recovering from an MMU error
  806. st_synchronize();
  807. unloadFilamentStarted = true;
  808. HelpUnloadToFinda();
  809. }
  810. break;
  811. case ProgressCode::FeedingToFSensor:
  812. // prepare for the movement of the E-motor
  813. st_synchronize();
  814. loadFilamentStarted = true;
  815. break;
  816. default:
  817. // do nothing yet
  818. break;
  819. }
  820. }
  821. void __attribute__((noinline)) MMU2::HelpUnloadToFinda(){
  822. current_position[E_AXIS] -= MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH;
  823. plan_buffer_line_curposXYZE(MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE);
  824. }
  825. void MMU2::OnMMUProgressMsgSame(ProgressCode pc){
  826. switch (pc) {
  827. case ProgressCode::UnloadingToFinda:
  828. if (unloadFilamentStarted && !blocks_queued()) { // Only plan a move if there is no move ongoing
  829. if (fsensor.getFilamentPresent()) {
  830. HelpUnloadToFinda();
  831. } else {
  832. unloadFilamentStarted = false;
  833. }
  834. }
  835. break;
  836. case ProgressCode::FeedingToFSensor:
  837. if (loadFilamentStarted) {
  838. switch (WhereIsFilament()) {
  839. case FilamentState::AT_FSENSOR:
  840. // fsensor triggered, finish FeedingToExtruder state
  841. loadFilamentStarted = false;
  842. // After the MMU knows the FSENSOR is triggered it will:
  843. // 1. Push the filament by additional 30mm (see fsensorToNozzle)
  844. // 2. Disengage the idler and push another 2mm.
  845. current_position[E_AXIS] += logic.ExtraLoadDistance() + 2;
  846. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  847. break;
  848. case FilamentState::NOT_PRESENT:
  849. // fsensor not triggered, continue moving extruder
  850. if (!blocks_queued()) { // Only plan a move if there is no move ongoing
  851. current_position[E_AXIS] += 2.0f;
  852. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  853. }
  854. break;
  855. default:
  856. // Abort here?
  857. break;
  858. }
  859. }
  860. break;
  861. default:
  862. // do nothing yet
  863. break;
  864. }
  865. }
  866. } // namespace MMU2