mmu2.cpp 33 KB

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