mmu2.cpp 33 KB

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