mmu2.cpp 35 KB

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