mmu2.cpp 36 KB

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