mmu2.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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 = 80.0f; // mm
  46. static constexpr float MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE = 80.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. manage_heater();
  277. manage_inactivity(true);
  278. }
  279. if (fsensorState)
  280. {
  281. IncrementLoadFails();
  282. return false;
  283. } else {
  284. // else, happy printing! :)
  285. return true;
  286. }
  287. }
  288. void MMU2::ToolChangeCommon(uint8_t slot){
  289. for(;;) { // while not successfully fed into extruder's PTFE tube
  290. for(;;) {
  291. tool_change_extruder = slot;
  292. logic.ToolChange(slot); // let the MMU pull the filament out and push a new one in
  293. if( manage_response(true, true) )
  294. break;
  295. // otherwise: failed to perform the command - unload first and then let it run again
  296. IncrementMMUFails();
  297. // just in case we stood in an error screen for too long and the hotend got cold
  298. ResumeHotendTemp();
  299. // if the extruder has been parked, it will get unparked once the ToolChange command finishes OK
  300. // - so no ResumeUnpark() at this spot
  301. unload();
  302. // if we run out of retries, we must do something ... may be raise an error screen and allow the user to do something
  303. // but honestly - if the MMU restarts during every toolchange,
  304. // something else is seriously broken and stopping a print is probably our best option.
  305. }
  306. // reset current position to whatever the planner thinks it is
  307. plan_set_e_position(current_position[E_AXIS]);
  308. if (VerifyFilamentEnteredPTFE()) break;
  309. else { // Prepare a retry attempt
  310. unload(); // TODO cut filament
  311. }
  312. }
  313. extruder = slot; //filament change is finished
  314. SpoolJoin::spooljoin.setSlot(slot);
  315. // @@TODO really report onto the serial? May be for the Octoprint? Not important now
  316. // SERIAL_ECHO_START();
  317. // SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(extruder));
  318. ++toolchange_counter;
  319. }
  320. bool MMU2::tool_change(uint8_t slot) {
  321. if( ! WaitForMMUReady())
  322. return false;
  323. if (slot != extruder) {
  324. if (!IS_SD_PRINTING && !usb_timer.running()) {
  325. // If Tcodes are used manually through the serial
  326. // we need to unload manually as well
  327. unload();
  328. }
  329. ReportingRAII rep(CommandInProgress::ToolChange);
  330. FSensorBlockRunout blockRunout;
  331. st_synchronize();
  332. ToolChangeCommon(slot);
  333. }
  334. return true;
  335. }
  336. /// Handle special T?/Tx/Tc commands
  337. ///
  338. ///- T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically
  339. ///- 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.
  340. ///- Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated.
  341. bool MMU2::tool_change(char code, uint8_t slot) {
  342. if( ! WaitForMMUReady())
  343. return false;
  344. FSensorBlockRunout blockRunout;
  345. switch (code) {
  346. case '?': {
  347. waitForHotendTargetTemp(100, []{});
  348. load_filament_to_nozzle(slot);
  349. } break;
  350. case 'x': {
  351. set_extrude_min_temp(0); // Allow cold extrusion since Tx only loads to the gears not nozzle
  352. st_synchronize();
  353. ToolChangeCommon(slot); // the only difference was manage_response(false, false), but probably good enough
  354. set_extrude_min_temp(EXTRUDE_MINTEMP);
  355. } break;
  356. case 'c': {
  357. waitForHotendTargetTemp(100, []{});
  358. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  359. } break;
  360. }
  361. return true;
  362. }
  363. void MMU2::get_statistics() {
  364. logic.Statistics();
  365. }
  366. uint8_t MMU2::get_current_tool() const {
  367. return extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : extruder;
  368. }
  369. uint8_t MMU2::get_tool_change_tool() const {
  370. return tool_change_extruder == MMU2_NO_TOOL ? (uint8_t)FILAMENT_UNKNOWN : tool_change_extruder;
  371. }
  372. bool MMU2::set_filament_type(uint8_t slot, uint8_t type) {
  373. if( ! WaitForMMUReady())
  374. return false;
  375. // @@TODO - this is not supported in the new MMU yet
  376. slot = slot; // @@TODO
  377. type = type; // @@TODO
  378. // cmd_arg = filamentType;
  379. // command(MMU_CMD_F0 + index);
  380. if( ! manage_response(false, false) ){
  381. // @@TODO failed to perform the command - retry
  382. ;
  383. } // true, true); -- Comment: how is it possible for a filament type set to fail?
  384. return true;
  385. }
  386. bool MMU2::unload() {
  387. if( ! WaitForMMUReady())
  388. return false;
  389. WaitForHotendTargetTempBeep();
  390. {
  391. FSensorBlockRunout blockRunout;
  392. ReportingRAII rep(CommandInProgress::UnloadFilament);
  393. filament_ramming();
  394. // we assume the printer managed to relieve filament tip from the gears,
  395. // so repeating that part in case of an MMU restart is not necessary
  396. for(;;) {
  397. logic.UnloadFilament();
  398. if( manage_response(false, true) )
  399. break;
  400. IncrementMMUFails();
  401. }
  402. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  403. // no active tool
  404. extruder = MMU2_NO_TOOL;
  405. tool_change_extruder = MMU2_NO_TOOL;
  406. }
  407. return true;
  408. }
  409. bool MMU2::cut_filament(uint8_t slot){
  410. if( ! WaitForMMUReady())
  411. return false;
  412. ReportingRAII rep(CommandInProgress::CutFilament);
  413. for(;;){
  414. logic.CutFilament(slot);
  415. if( manage_response(false, true) )
  416. break;
  417. IncrementMMUFails();
  418. }
  419. return true;
  420. }
  421. void FullScreenMsg(const char *pgmS, uint8_t slot){
  422. lcd_update_enable(false);
  423. lcd_clear();
  424. lcd_puts_at_P(0, 1, pgmS);
  425. lcd_print(' ');
  426. lcd_print(slot + 1);
  427. }
  428. bool MMU2::loading_test(uint8_t slot){
  429. FullScreenMsg(_T(MSG_TESTING_FILAMENT), slot);
  430. tool_change(slot);
  431. st_synchronize();
  432. unload();
  433. lcd_update_enable(true);
  434. return true;
  435. }
  436. bool MMU2::load_filament(uint8_t slot) {
  437. if( ! WaitForMMUReady())
  438. return false;
  439. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  440. ReportingRAII rep(CommandInProgress::LoadFilament);
  441. for(;;) {
  442. logic.LoadFilament(slot);
  443. if( manage_response(false, false) )
  444. break;
  445. IncrementMMUFails();
  446. }
  447. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  448. lcd_update_enable(true);
  449. return true;
  450. }
  451. struct LoadingToNozzleRAII {
  452. MMU2 &mmu2;
  453. explicit inline LoadingToNozzleRAII(MMU2 &mmu2):mmu2(mmu2){
  454. mmu2.loadingToNozzle = true;
  455. }
  456. inline ~LoadingToNozzleRAII(){
  457. mmu2.loadingToNozzle = false;
  458. }
  459. };
  460. bool MMU2::load_filament_to_nozzle(uint8_t slot) {
  461. if( ! WaitForMMUReady())
  462. return false;
  463. LoadingToNozzleRAII ln(*this);
  464. WaitForHotendTargetTempBeep();
  465. FullScreenMsg(_T(MSG_LOADING_FILAMENT), slot);
  466. {
  467. // used for MMU-menu operation "Load to Nozzle"
  468. ReportingRAII rep(CommandInProgress::ToolChange);
  469. FSensorBlockRunout blockRunout;
  470. if( extruder != MMU2_NO_TOOL ){ // we already have some filament loaded - free it + shape its tip properly
  471. filament_ramming();
  472. }
  473. ToolChangeCommon(slot);
  474. // Finish loading to the nozzle with finely tuned steps.
  475. execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, sizeof(load_to_nozzle_sequence) / sizeof (load_to_nozzle_sequence[0]));
  476. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  477. }
  478. lcd_update_enable(true);
  479. return true;
  480. }
  481. bool MMU2::eject_filament(uint8_t slot, bool recover) {
  482. if( ! WaitForMMUReady())
  483. return false;
  484. ReportingRAII rep(CommandInProgress::EjectFilament);
  485. current_position[E_AXIS] -= MMU2_FILAMENTCHANGE_EJECT_FEED;
  486. plan_buffer_line_curposXYZE(2500.F / 60.F);
  487. st_synchronize();
  488. logic.EjectFilament(slot);
  489. if( ! manage_response(false, false) ){
  490. // @@TODO failed to perform the command - retry
  491. ;
  492. }
  493. if (recover) {
  494. // LCD_MESSAGEPGM(MSG_MMU2_EJECT_RECOVER);
  495. Sound_MakeSound(e_SOUND_TYPE_StandardPrompt);
  496. //@@TODO wait_for_user = true;
  497. //#if ENABLED(HOST_PROMPT_SUPPORT)
  498. // host_prompt_do(PROMPT_USER_CONTINUE, PSTR("MMU2 Eject Recover"), PSTR("Continue"));
  499. //#endif
  500. //#if ENABLED(EXTENSIBLE_UI)
  501. // ExtUI::onUserConfirmRequired_P(PSTR("MMU2 Eject Recover"));
  502. //#endif
  503. //@@TODO while (wait_for_user) idle(true);
  504. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  505. // logic.Command(); //@@TODO command(MMU_CMD_R0);
  506. if( ! manage_response(false, false) ){
  507. // @@TODO failed to perform the command - retry
  508. ;
  509. }
  510. }
  511. // no active tool
  512. extruder = MMU2_NO_TOOL;
  513. tool_change_extruder = MMU2_NO_TOOL;
  514. Sound_MakeSound(e_SOUND_TYPE_StandardConfirm);
  515. // disable_E0();
  516. return true;
  517. }
  518. void MMU2::Button(uint8_t index){
  519. LogEchoEvent_P(PSTR("Button"));
  520. logic.Button(index);
  521. }
  522. void MMU2::Home(uint8_t mode){
  523. logic.Home(mode);
  524. }
  525. void MMU2::SaveAndPark(bool move_axes, bool turn_off_nozzle) {
  526. if (mmu_print_saved == SavedState::None) { // First occurrence. Save current position, park print head, disable nozzle heater.
  527. LogEchoEvent_P(PSTR("Saving and parking"));
  528. st_synchronize();
  529. resume_hotend_temp = degTargetHotend(active_extruder);
  530. if (move_axes){
  531. mmu_print_saved |= SavedState::ParkExtruder;
  532. // save current pos
  533. for(uint8_t i = 0; i < 3; ++i){
  534. resume_position.xyz[i] = current_position[i];
  535. }
  536. // lift Z
  537. raise_z(MMU_ERR_Z_PAUSE_LIFT);
  538. // move XY aside
  539. if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS])
  540. {
  541. current_position[X_AXIS] = MMU_ERR_X_PAUSE_POS;
  542. current_position[Y_AXIS] = MMU_ERR_Y_PAUSE_POS;
  543. plan_buffer_line_curposXYZE(NOZZLE_PARK_XY_FEEDRATE);
  544. st_synchronize();
  545. }
  546. }
  547. if (turn_off_nozzle){
  548. mmu_print_saved |= SavedState::CooldownPending;
  549. LogEchoEvent_P(PSTR("Heater cooldown pending"));
  550. // This just sets the flag that we should timeout and shut off the nozzle in 30 minutes...
  551. //setAllTargetHotends(0);
  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. ResumeUnpark(); // We can now travel back to the tower or wherever we were when we saved.
  677. ResetRetryAttempts(); // Reset the retry counter.
  678. st_synchronize();
  679. return true;
  680. case Interrupted:
  681. // now what :D ... big bad ... ramming, unload, retry the whole command originally issued
  682. return false;
  683. case VersionMismatch: // this basically means the MMU will be disabled until reconnected
  684. CheckUserInput();
  685. return true;
  686. case CommandError:
  687. // Don't proceed to the park/save if we are doing an autoretry.
  688. if (inAutoRetry){
  689. continue;
  690. }
  691. [[fallthrough]];
  692. case CommunicationTimeout:
  693. case ProtocolError:
  694. SaveAndPark(move_axes, turn_off_nozzle); // and wait for the user to resolve the problem
  695. CheckUserInput();
  696. break;
  697. case CommunicationRecovered: // @@TODO communication recovered and may be an error recovered as well
  698. // may be the logic layer can detect the change of state a respond with one "Recovered" to be handled here
  699. ResumeHotendTemp();
  700. ResumeUnpark();
  701. break;
  702. case Processing: // wait for the MMU to respond
  703. default:
  704. break;
  705. }
  706. }
  707. }
  708. StepStatus MMU2::LogicStep(bool reportErrors) {
  709. CheckUserInput(); // Process any buttons before proceeding with another MMU Query
  710. StepStatus ss = logic.Step();
  711. switch (ss) {
  712. case Finished:
  713. // At this point it is safe to trigger a runout and not interrupt the MMU protocol
  714. CheckFINDARunout();
  715. break;
  716. case Processing:
  717. OnMMUProgressMsg(logic.Progress());
  718. break;
  719. case ButtonPushed:
  720. lastButton = logic.Button();
  721. LogEchoEvent_P(PSTR("MMU Button pushed"));
  722. CheckUserInput(); // Process the button immediately
  723. break;
  724. case Interrupted:
  725. // can be silently handed over to a higher layer, no processing necessary at this spot
  726. break;
  727. default:
  728. if(reportErrors) {
  729. switch (ss)
  730. {
  731. case CommandError:
  732. ReportError(logic.Error(), ErrorSourceMMU);
  733. break;
  734. case CommunicationTimeout:
  735. state = xState::Connecting;
  736. ReportError(ErrorCode::MMU_NOT_RESPONDING, ErrorSourcePrinter);
  737. break;
  738. case ProtocolError:
  739. state = xState::Connecting;
  740. ReportError(ErrorCode::PROTOCOL_ERROR, ErrorSourcePrinter);
  741. break;
  742. case VersionMismatch:
  743. StopKeepPowered();
  744. ReportError(ErrorCode::VERSION_MISMATCH, ErrorSourcePrinter);
  745. break;
  746. default:
  747. break;
  748. }
  749. }
  750. }
  751. if( logic.Running() ){
  752. state = xState::Active;
  753. }
  754. return ss;
  755. }
  756. void MMU2::filament_ramming() {
  757. execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step));
  758. }
  759. void MMU2::execute_extruder_sequence(const E_Step *sequence, uint8_t steps) {
  760. st_synchronize();
  761. const E_Step *step = sequence;
  762. for (uint8_t i = 0; i < steps; i++) {
  763. current_position[E_AXIS] += pgm_read_float(&(step->extrude));
  764. plan_buffer_line_curposXYZE(pgm_read_float(&(step->feedRate)));
  765. st_synchronize();
  766. step++;
  767. }
  768. }
  769. void MMU2::ReportError(ErrorCode ec, ErrorSource res) {
  770. // Due to a potential lossy error reporting layers linked to this hook
  771. // we'd better report everything to make sure especially the error states
  772. // do not get lost.
  773. // - The good news here is the fact, that the MMU reports the errors repeatedly until resolved.
  774. // - The bad news is, that MMU not responding may repeatedly occur on printers not having the MMU at all.
  775. //
  776. // Not sure how to properly handle this situation, options:
  777. // - skip reporting "MMU not responding" (at least for now)
  778. // - report only changes of states (we can miss an error message)
  779. // - may be some combination of MMUAvailable + UseMMU flags and decide based on their state
  780. // Right now the filtering of MMU_NOT_RESPONDING is done in ReportErrorHook() as it is not a problem if mmu2.cpp
  781. // Depending on the Progress code, we may want to do some action when an error occurs
  782. switch (logic.Progress()){
  783. case ProgressCode::UnloadingToFinda:
  784. unloadFilamentStarted = false;
  785. break;
  786. case ProgressCode::FeedingToFSensor:
  787. // FSENSOR error during load. Make sure E-motor stops moving.
  788. loadFilamentStarted = false;
  789. break;
  790. default:
  791. break;
  792. }
  793. if( ec != lastErrorCode ){ // deduplicate: only report changes in error codes into the log
  794. lastErrorCode = ec;
  795. lastErrorSource = res;
  796. LogErrorEvent_P( _O(PrusaErrorTitle(PrusaErrorCodeIndex((uint16_t)ec))) );
  797. if( ec != ErrorCode::OK ){
  798. IncrementMMUFails();
  799. // check if it is a "power" failure - we consider TMC-related errors as power failures
  800. static constexpr uint16_t tmcMask =
  801. ( (uint16_t)ErrorCode::TMC_IOIN_MISMATCH
  802. | (uint16_t)ErrorCode::TMC_RESET
  803. | (uint16_t)ErrorCode::TMC_UNDERVOLTAGE_ON_CHARGE_PUMP
  804. | (uint16_t)ErrorCode::TMC_SHORT_TO_GROUND
  805. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_WARN
  806. | (uint16_t)ErrorCode::TMC_OVER_TEMPERATURE_ERROR
  807. | (uint16_t)ErrorCode::MMU_SOLDERING_NEEDS_ATTENTION ) & 0x7fffU; // skip the top bit
  808. static_assert(tmcMask == 0x7e00); // just make sure we fail compilation if any of the TMC error codes change
  809. if ((uint16_t)ec & tmcMask) { // @@TODO can be optimized to uint8_t operation
  810. // TMC-related errors are from 0x8200 higher
  811. IncrementTMCFailures();
  812. }
  813. }
  814. }
  815. if( !mmu2.RetryIfPossible((uint16_t)ec) ) {
  816. // If retry attempts are all used up
  817. // or if 'Retry' operation is not available
  818. // raise the MMU error sceen and wait for user input
  819. ReportErrorHook((uint16_t)ec);
  820. }
  821. static_assert(mmu2Magic[0] == 'M'
  822. && mmu2Magic[1] == 'M'
  823. && mmu2Magic[2] == 'U'
  824. && mmu2Magic[3] == '2'
  825. && mmu2Magic[4] == ':'
  826. && strlen_constexpr(mmu2Magic) == 5,
  827. "MMU2 logging prefix mismatch, must be updated at various spots"
  828. );
  829. }
  830. void MMU2::ReportProgress(ProgressCode pc) {
  831. ReportProgressHook((CommandInProgress)logic.CommandInProgress(), (uint16_t)pc);
  832. LogEchoEvent_P( _O(ProgressCodeToText((uint16_t)pc)) );
  833. }
  834. void MMU2::OnMMUProgressMsg(ProgressCode pc){
  835. if (pc != lastProgressCode) {
  836. OnMMUProgressMsgChanged(pc);
  837. } else {
  838. OnMMUProgressMsgSame(pc);
  839. }
  840. }
  841. void MMU2::OnMMUProgressMsgChanged(ProgressCode pc){
  842. ReportProgress(pc);
  843. lastProgressCode = pc;
  844. switch (pc) {
  845. case ProgressCode::UnloadingToFinda:
  846. if ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::UnloadFilament
  847. || ((CommandInProgress)logic.CommandInProgress() == CommandInProgress::ToolChange))
  848. {
  849. // If MK3S sent U0 command, ramming sequence takes care of releasing the filament.
  850. // If Toolchange is done while printing, PrusaSlicer takes care of releasing the filament
  851. // If printing is not in progress, ToolChange will issue a U0 command.
  852. break;
  853. } else {
  854. // We're likely recovering from an MMU error
  855. st_synchronize();
  856. unloadFilamentStarted = true;
  857. HelpUnloadToFinda();
  858. }
  859. break;
  860. case ProgressCode::FeedingToFSensor:
  861. // prepare for the movement of the E-motor
  862. st_synchronize();
  863. loadFilamentStarted = true;
  864. break;
  865. default:
  866. // do nothing yet
  867. break;
  868. }
  869. }
  870. void __attribute__((noinline)) MMU2::HelpUnloadToFinda(){
  871. current_position[E_AXIS] -= MMU2_RETRY_UNLOAD_TO_FINDA_LENGTH;
  872. plan_buffer_line_curposXYZE(MMU2_RETRY_UNLOAD_TO_FINDA_FEED_RATE);
  873. }
  874. void MMU2::OnMMUProgressMsgSame(ProgressCode pc){
  875. switch (pc) {
  876. case ProgressCode::UnloadingToFinda:
  877. if (unloadFilamentStarted && !blocks_queued()) { // Only plan a move if there is no move ongoing
  878. if (fsensor.getFilamentPresent()) {
  879. HelpUnloadToFinda();
  880. } else {
  881. unloadFilamentStarted = false;
  882. }
  883. }
  884. break;
  885. case ProgressCode::FeedingToFSensor:
  886. if (loadFilamentStarted) {
  887. switch (WhereIsFilament()) {
  888. case FilamentState::AT_FSENSOR:
  889. // fsensor triggered, finish FeedingToExtruder state
  890. loadFilamentStarted = false;
  891. // After the MMU knows the FSENSOR is triggered it will:
  892. // 1. Push the filament by additional 30mm (see fsensorToNozzle)
  893. // 2. Disengage the idler and push another 2mm.
  894. current_position[E_AXIS] += logic.ExtraLoadDistance() + 2;
  895. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  896. break;
  897. case FilamentState::NOT_PRESENT:
  898. // fsensor not triggered, continue moving extruder
  899. if (!blocks_queued()) { // Only plan a move if there is no move ongoing
  900. current_position[E_AXIS] += 2.0f;
  901. plan_buffer_line_curposXYZE(MMU2_LOAD_TO_NOZZLE_FEED_RATE);
  902. }
  903. break;
  904. default:
  905. // Abort here?
  906. break;
  907. }
  908. }
  909. break;
  910. default:
  911. // do nothing yet
  912. break;
  913. }
  914. }
  915. } // namespace MMU2