mmu2.cpp 36 KB

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