mmu2.cpp 35 KB

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