mmu2.cpp 33 KB

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