mmu2.cpp 35 KB

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