mmu2_protocol_logic.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. #include "mmu2_protocol_logic.h"
  2. #include "mmu2_log.h"
  3. #include "mmu2_fsensor.h"
  4. #include "system_timer.h"
  5. #include <string.h>
  6. namespace MMU2 {
  7. static const uint8_t supportedMmuFWVersion[3] PROGMEM = { 2, 1, 6 };
  8. const uint8_t ProtocolLogic::regs8Addrs[ProtocolLogic::regs8Count] PROGMEM = {
  9. 8, // FINDA state
  10. 0x1b, // Selector slot
  11. 0x1c, // Idler slot
  12. };
  13. const uint8_t ProtocolLogic::regs16Addrs[ProtocolLogic::regs16Count] PROGMEM = {
  14. 4, // MMU errors - aka statistics
  15. 0x1a, // Pulley position [mm]
  16. };
  17. const uint8_t ProtocolLogic::initRegs8Addrs[ProtocolLogic::initRegs8Count] PROGMEM = {
  18. 0x0b, // extra load distance
  19. };
  20. void ProtocolLogic::CheckAndReportAsyncEvents() {
  21. // even when waiting for a query period, we need to report a change in filament sensor's state
  22. // - it is vital for a precise synchronization of moves of the printer and the MMU
  23. uint8_t fs = (uint8_t)WhereIsFilament();
  24. if (fs != lastFSensor) {
  25. SendAndUpdateFilamentSensor();
  26. }
  27. }
  28. void ProtocolLogic::SendQuery() {
  29. SendMsg(RequestMsg(RequestMsgCodes::Query, 0));
  30. scopeState = ScopeState::QuerySent;
  31. }
  32. void ProtocolLogic::StartReading8bitRegisters() {
  33. regIndex = 0;
  34. SendReadRegister(pgm_read_byte(regs8Addrs + regIndex), ScopeState::Reading8bitRegisters);
  35. }
  36. void ProtocolLogic::ProcessRead8bitRegister(){
  37. regs8[regIndex] = rsp.paramValue;
  38. ++regIndex;
  39. if(regIndex >= regs8Count){
  40. // proceed with reading 16bit registers
  41. StartReading16bitRegisters();
  42. } else {
  43. SendReadRegister(pgm_read_byte(regs8Addrs + regIndex), ScopeState::Reading8bitRegisters);
  44. }
  45. }
  46. void ProtocolLogic::StartReading16bitRegisters() {
  47. regIndex = 0;
  48. SendReadRegister(pgm_read_byte(regs16Addrs + regIndex), ScopeState::Reading16bitRegisters);
  49. }
  50. ProtocolLogic::ScopeState __attribute__((noinline)) ProtocolLogic::ProcessRead16bitRegister(ProtocolLogic::ScopeState stateAtEnd){
  51. regs16[regIndex] = rsp.paramValue;
  52. ++regIndex;
  53. if(regIndex >= regs16Count){
  54. return stateAtEnd;
  55. } else {
  56. SendReadRegister(pgm_read_byte(regs16Addrs + regIndex), ScopeState::Reading16bitRegisters);
  57. }
  58. return ScopeState::Reading16bitRegisters;
  59. }
  60. void ProtocolLogic::StartWritingInitRegisters() {
  61. regIndex = 0;
  62. SendWriteRegister(pgm_read_byte(initRegs8Addrs + regIndex), initRegs8[regIndex], ScopeState::WritingInitRegisters);
  63. }
  64. bool __attribute__((noinline)) ProtocolLogic::ProcessWritingInitRegister(){
  65. ++regIndex;
  66. if(regIndex >= initRegs8Count){
  67. return true;
  68. } else {
  69. SendWriteRegister(pgm_read_byte(initRegs8Addrs + regIndex), initRegs8[regIndex], ScopeState::WritingInitRegisters);
  70. }
  71. return false;
  72. }
  73. void ProtocolLogic::SendAndUpdateFilamentSensor() {
  74. SendMsg(RequestMsg(RequestMsgCodes::FilamentSensor, lastFSensor = (uint8_t)WhereIsFilament()));
  75. scopeState = ScopeState::FilamentSensorStateSent;
  76. }
  77. void ProtocolLogic::SendButton(uint8_t btn) {
  78. SendMsg(RequestMsg(RequestMsgCodes::Button, btn));
  79. scopeState = ScopeState::ButtonSent;
  80. }
  81. void ProtocolLogic::SendVersion(uint8_t stage) {
  82. SendMsg(RequestMsg(RequestMsgCodes::Version, stage));
  83. scopeState = (ScopeState)((uint_fast8_t)ScopeState::S0Sent + stage);
  84. }
  85. void ProtocolLogic::SendReadRegister(uint8_t index, ScopeState nextState) {
  86. SendMsg(RequestMsg(RequestMsgCodes::Read, index));
  87. scopeState = nextState;
  88. }
  89. void ProtocolLogic::SendWriteRegister(uint8_t index, uint16_t value, ScopeState nextState){
  90. SendWriteMsg(RequestMsg(RequestMsgCodes::Write, index, value));
  91. scopeState = nextState;
  92. }
  93. // searches for "ok\n" in the incoming serial data (that's the usual response of the old MMU FW)
  94. struct OldMMUFWDetector {
  95. uint8_t ok;
  96. inline constexpr OldMMUFWDetector():ok(0) { }
  97. enum class State : uint8_t { MatchingPart, SomethingElse, Matched };
  98. /// @returns true when "ok\n" gets detected
  99. State Detect(uint8_t c){
  100. // consume old MMU FW's data if any -> avoid confusion of protocol decoder
  101. if(ok == 0 && c == 'o'){
  102. ++ok;
  103. return State::MatchingPart;
  104. } else if(ok == 1 && c == 'k'){
  105. ++ok;
  106. return State::Matched;
  107. }
  108. return State::SomethingElse;
  109. }
  110. };
  111. StepStatus ProtocolLogic::ExpectingMessage() {
  112. int bytesConsumed = 0;
  113. int c = -1;
  114. OldMMUFWDetector oldMMUh4x0r; // old MMU FW hacker ;)
  115. // try to consume as many rx bytes as possible (until a message has been completed)
  116. while ((c = uart->read()) >= 0) {
  117. ++bytesConsumed;
  118. RecordReceivedByte(c);
  119. switch (protocol.DecodeResponse(c)) {
  120. case DecodeStatus::MessageCompleted:
  121. rsp = protocol.GetResponseMsg();
  122. LogResponse();
  123. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  124. return MessageReady;
  125. case DecodeStatus::NeedMoreData:
  126. break;
  127. case DecodeStatus::Error:{
  128. // consume old MMU FW's data if any -> avoid confusion of protocol decoder
  129. auto old = oldMMUh4x0r.Detect(c);
  130. if( old == OldMMUFWDetector::State::Matched ){
  131. // Old MMU FW 1.0.6 detected. Firmwares are incompatible.
  132. return VersionMismatch;
  133. } else if( old == OldMMUFWDetector::State::MatchingPart ){
  134. break;
  135. }
  136. }
  137. [[fallthrough]]; // otherwise
  138. default:
  139. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  140. return ProtocolError;
  141. }
  142. }
  143. if (bytesConsumed != 0) {
  144. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  145. return Processing; // consumed some bytes, but message still not ready
  146. } else if (Elapsed(linkLayerTimeout) && currentScope != Scope::Stopped) {
  147. return CommunicationTimeout;
  148. }
  149. return Processing;
  150. }
  151. void ProtocolLogic::SendMsg(RequestMsg rq) {
  152. uint8_t txbuff[Protocol::MaxRequestSize()];
  153. uint8_t len = Protocol::EncodeRequest(rq, txbuff);
  154. uart->write(txbuff, len);
  155. LogRequestMsg(txbuff, len);
  156. RecordUARTActivity();
  157. }
  158. void ProtocolLogic::SendWriteMsg(RequestMsg rq){
  159. uint8_t txbuff[Protocol::MaxRequestSize()];
  160. uint8_t len = Protocol::EncodeWriteRequest(rq.value, rq.value2, txbuff);
  161. uart->write(txbuff, len);
  162. LogRequestMsg(txbuff, len);
  163. RecordUARTActivity();
  164. }
  165. void ProtocolLogic::StartSeqRestart() {
  166. retries = maxRetries;
  167. SendVersion(0);
  168. }
  169. void ProtocolLogic::DelayedRestartRestart() {
  170. scopeState = ScopeState::RecoveringProtocolError;
  171. }
  172. void ProtocolLogic::CommandRestart() {
  173. scopeState = ScopeState::CommandSent;
  174. SendMsg(rq);
  175. }
  176. void ProtocolLogic::IdleRestart() {
  177. scopeState = ScopeState::Ready;
  178. }
  179. StepStatus ProtocolLogic::ProcessVersionResponse(uint8_t stage) {
  180. if (rsp.request.code != RequestMsgCodes::Version || rsp.request.value != stage) {
  181. // got a response to something else - protocol corruption probably, repeat the query OR restart the comm by issuing S0?
  182. SendVersion(stage);
  183. } else {
  184. mmuFwVersion[stage] = rsp.paramValue;
  185. if (mmuFwVersion[stage] != pgm_read_byte(supportedMmuFWVersion + stage)) {
  186. if (--retries == 0) {
  187. return VersionMismatch;
  188. } else {
  189. SendVersion(stage);
  190. }
  191. } else {
  192. dataTO.Reset(); // got a meaningful response from the MMU, stop data layer timeout tracking
  193. SendVersion(stage + 1);
  194. }
  195. }
  196. return Processing;
  197. }
  198. StepStatus ProtocolLogic::ScopeStep() {
  199. if ( ! ExpectsResponse() ) {
  200. // we are waiting for something
  201. switch (currentScope) {
  202. case Scope::DelayedRestart:
  203. return DelayedRestartWait();
  204. case Scope::Idle:
  205. return IdleWait();
  206. case Scope::Command:
  207. return CommandWait();
  208. case Scope::Stopped:
  209. return StoppedStep();
  210. default:
  211. break;
  212. }
  213. } else {
  214. // we are expecting a message
  215. if (auto expmsg = ExpectingMessage(); expmsg != MessageReady) // this whole statement takes 12B
  216. return expmsg;
  217. // process message
  218. switch (currentScope) {
  219. case Scope::StartSeq:
  220. return StartSeqStep(); // ~270B
  221. case Scope::Idle:
  222. return IdleStep(); // ~300B
  223. case Scope::Command:
  224. return CommandStep(); // ~430B
  225. case Scope::Stopped:
  226. return StoppedStep();
  227. default:
  228. break;
  229. }
  230. }
  231. return Finished;
  232. }
  233. StepStatus ProtocolLogic::StartSeqStep() {
  234. // solve initial handshake
  235. switch (scopeState) {
  236. case ScopeState::S0Sent: // received response to S0 - major
  237. case ScopeState::S1Sent: // received response to S1 - minor
  238. case ScopeState::S2Sent: // received response to S2 - minor
  239. return ProcessVersionResponse((uint8_t)scopeState - (uint8_t)ScopeState::S0Sent);
  240. case ScopeState::S3Sent: // received response to S3 - revision
  241. if (rsp.request.code != RequestMsgCodes::Version || rsp.request.value != 3) {
  242. // got a response to something else - protocol corruption probably, repeat the query OR restart the comm by issuing S0?
  243. SendVersion(3);
  244. } else {
  245. mmuFwVersionBuild = rsp.paramValue; // just register the build number
  246. // Start General Interrogation after line up - initial parametrization is started
  247. StartWritingInitRegisters();
  248. }
  249. return Processing;
  250. case ScopeState::WritingInitRegisters:
  251. if( ProcessWritingInitRegister() ){
  252. SendAndUpdateFilamentSensor();
  253. }
  254. return Processing;
  255. case ScopeState::FilamentSensorStateSent:
  256. SwitchFromStartToIdle();
  257. return Processing; // Returning Finished is not a good idea in case of a fast error recovery
  258. // - it tells the printer, that the command which experienced a protocol error and recovered successfully actually terminated.
  259. // In such a case we must return "Processing" in order to keep the MMU state machine running and prevent the printer from executing next G-codes.
  260. default:
  261. return VersionMismatch;
  262. }
  263. }
  264. StepStatus ProtocolLogic::DelayedRestartWait() {
  265. if (Elapsed(heartBeatPeriod)) { // this basically means, that we are waiting until there is some traffic on
  266. while (uart->read() != -1)
  267. ; // clear the input buffer
  268. // switch to StartSeq
  269. Start();
  270. }
  271. return Processing;
  272. }
  273. StepStatus ProtocolLogic::CommandWait() {
  274. if (Elapsed(heartBeatPeriod)) {
  275. SendQuery();
  276. } else {
  277. // even when waiting for a query period, we need to report a change in filament sensor's state
  278. // - it is vital for a precise synchronization of moves of the printer and the MMU
  279. CheckAndReportAsyncEvents();
  280. }
  281. return Processing;
  282. }
  283. StepStatus ProtocolLogic::ProcessCommandQueryResponse() {
  284. switch (rsp.paramCode) {
  285. case ResponseMsgParamCodes::Processing:
  286. progressCode = static_cast<ProgressCode>(rsp.paramValue);
  287. errorCode = ErrorCode::OK;
  288. SendAndUpdateFilamentSensor(); // keep on reporting the state of fsensor regularly
  289. return Processing;
  290. case ResponseMsgParamCodes::Error:
  291. // in case of an error the progress code remains as it has been before
  292. errorCode = static_cast<ErrorCode>(rsp.paramValue);
  293. // keep on reporting the state of fsensor regularly even in command error state
  294. // - the MMU checks FINDA and fsensor even while recovering from errors
  295. SendAndUpdateFilamentSensor();
  296. return CommandError;
  297. case ResponseMsgParamCodes::Button:
  298. // The user pushed a button on the MMU. Save it, do what we need to do
  299. // to prepare, then pass it back to the MMU so it can work its magic.
  300. buttonCode = static_cast<Buttons>(rsp.paramValue);
  301. SendAndUpdateFilamentSensor();
  302. return ButtonPushed;
  303. case ResponseMsgParamCodes::Finished:
  304. // We must check whether the "finished" is actually related to the command issued into the MMU
  305. // It can also be an X0 F which means MMU just successfully restarted.
  306. if( ReqMsg().code == rsp.request.code && ReqMsg().value == rsp.request.value ){
  307. progressCode = ProgressCode::OK;
  308. scopeState = ScopeState::Ready;
  309. rq = RequestMsg(RequestMsgCodes::unknown, 0); // clear the successfully finished request
  310. return Finished;
  311. } else {
  312. // got response to some other command - the originally issued command was interrupted!
  313. return Interrupted;
  314. }
  315. default:
  316. return ProtocolError;
  317. }
  318. }
  319. StepStatus ProtocolLogic::CommandStep() {
  320. switch (scopeState) {
  321. case ScopeState::CommandSent: {
  322. switch (rsp.paramCode) { // the response should be either accepted or rejected
  323. case ResponseMsgParamCodes::Accepted:
  324. progressCode = ProgressCode::OK;
  325. errorCode = ErrorCode::RUNNING;
  326. scopeState = ScopeState::Wait;
  327. break;
  328. case ResponseMsgParamCodes::Rejected:
  329. // rejected - should normally not happen, but report the error up
  330. progressCode = ProgressCode::OK;
  331. errorCode = ErrorCode::PROTOCOL_ERROR;
  332. return CommandRejected;
  333. default:
  334. return ProtocolError;
  335. }
  336. } break;
  337. case ScopeState::QuerySent:
  338. return ProcessCommandQueryResponse();
  339. case ScopeState::FilamentSensorStateSent:
  340. StartReading8bitRegisters();
  341. return Processing;
  342. case ScopeState::Reading8bitRegisters:
  343. ProcessRead8bitRegister();
  344. return Processing;
  345. case ScopeState::Reading16bitRegisters:
  346. scopeState = ProcessRead16bitRegister(ScopeState::Wait);
  347. return Processing;
  348. case ScopeState::ButtonSent:
  349. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  350. // Button was accepted, decrement the retry.
  351. mmu2.DecrementRetryAttempts();
  352. }
  353. SendAndUpdateFilamentSensor();
  354. break;
  355. default:
  356. return ProtocolError;
  357. }
  358. return Processing;
  359. }
  360. StepStatus ProtocolLogic::IdleWait() {
  361. if (scopeState == ScopeState::Ready) { // check timeout
  362. if (Elapsed(heartBeatPeriod)) {
  363. SendQuery();
  364. return Processing;
  365. }
  366. }
  367. return Finished;
  368. }
  369. StepStatus ProtocolLogic::IdleStep() {
  370. switch (scopeState) {
  371. case ScopeState::QuerySent: // check UART
  372. // If we are accidentally in Idle and we receive something like "T0 P1" - that means the communication dropped out while a command was in progress.
  373. // That causes no issues here, we just need to switch to Command processing and continue there from now on.
  374. // The usual response in this case should be some command and "F" - finished - that confirms we are in an Idle state even on the MMU side.
  375. switch (rsp.request.code) {
  376. case RequestMsgCodes::Cut:
  377. case RequestMsgCodes::Eject:
  378. case RequestMsgCodes::Load:
  379. case RequestMsgCodes::Mode:
  380. case RequestMsgCodes::Tool:
  381. case RequestMsgCodes::Unload:
  382. if (rsp.paramCode != ResponseMsgParamCodes::Finished) {
  383. return SwitchFromIdleToCommand();
  384. }
  385. break;
  386. case RequestMsgCodes::Reset:
  387. // this one is kind of special
  388. // we do not transfer to any "running" command (i.e. we stay in Idle),
  389. // but in case there is an error reported we must make sure it gets propagated
  390. switch (rsp.paramCode) {
  391. case ResponseMsgParamCodes::Button:
  392. // The user pushed a button on the MMU. Save it, do what we need to do
  393. // to prepare, then pass it back to the MMU so it can work its magic.
  394. buttonCode = static_cast<Buttons>(rsp.paramValue);
  395. StartReading8bitRegisters();
  396. return ButtonPushed;
  397. case ResponseMsgParamCodes::Finished:
  398. if( ReqMsg().code != RequestMsgCodes::unknown ){
  399. // got reset while doing some other command - the originally issued command was interrupted!
  400. // this must be solved by the upper layer, protocol logic doesn't have all the context (like unload before trying again)
  401. IdleRestart();
  402. return Interrupted;
  403. }
  404. [[fallthrough]];
  405. case ResponseMsgParamCodes::Processing:
  406. // @@TODO we may actually use this branch to report progress of manual operation on the MMU
  407. // The MMU sends e.g. X0 P27 after its restart when the user presses an MMU button to move the Selector
  408. errorCode = ErrorCode::OK;
  409. break;
  410. default:
  411. errorCode = static_cast<ErrorCode>(rsp.paramValue);
  412. StartReading8bitRegisters(); // continue Idle state without restarting the communication
  413. return CommandError;
  414. }
  415. break;
  416. default:
  417. return ProtocolError;
  418. }
  419. StartReading8bitRegisters();
  420. return Processing;
  421. case ScopeState::Reading8bitRegisters:
  422. ProcessRead8bitRegister();
  423. return Processing;
  424. case ScopeState::Reading16bitRegisters:
  425. scopeState = ProcessRead16bitRegister(ScopeState::Ready);
  426. return scopeState == ScopeState::Ready ? Finished : Processing;
  427. case ScopeState::ButtonSent:
  428. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  429. // Button was accepted, decrement the retry.
  430. mmu2.DecrementRetryAttempts();
  431. }
  432. StartReading8bitRegisters();
  433. return Processing;
  434. case ScopeState::ReadRegisterSent:
  435. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  436. // @@TODO just dump the value onto the serial
  437. }
  438. return Finished;
  439. case ScopeState::WriteRegisterSent:
  440. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  441. // @@TODO do something? Retry if not accepted?
  442. }
  443. return Finished;
  444. default:
  445. return ProtocolError;
  446. }
  447. // The "return Finished" in this state machine requires a bit of explanation:
  448. // The Idle state either did nothing (still waiting for the heartbeat timeout)
  449. // or just successfully received the answer to Q0, whatever that was.
  450. // In both cases, it is ready to hand over work to a command or something else,
  451. // therefore we are returning Finished (also to exit mmu_loop() and unblock Marlin's loop!).
  452. // If there is no work, we'll end up in the Idle state again
  453. // and we'll send the heartbeat message after the specified timeout.
  454. return Finished;
  455. }
  456. ProtocolLogic::ProtocolLogic(MMU2Serial *uart, uint8_t extraLoadDistance)
  457. : explicitPrinterError(ErrorCode::OK)
  458. , currentScope(Scope::Stopped)
  459. , scopeState(ScopeState::Ready)
  460. , plannedRq(RequestMsgCodes::unknown, 0)
  461. , lastUARTActivityMs(0)
  462. , dataTO()
  463. , rsp(RequestMsg(RequestMsgCodes::unknown, 0), ResponseMsgParamCodes::unknown, 0)
  464. , state(State::Stopped)
  465. , lrb(0)
  466. , uart(uart)
  467. , errorCode(ErrorCode::OK)
  468. , progressCode(ProgressCode::OK)
  469. , buttonCode(NoButton)
  470. , lastFSensor((uint8_t)WhereIsFilament())
  471. , regs8 { 0, 0, 0 }
  472. , regs16 { 0, 0 }
  473. , initRegs8 { extraLoadDistance }
  474. , regIndex(0)
  475. , mmuFwVersion { 0, 0, 0 }
  476. {}
  477. void ProtocolLogic::Start() {
  478. state = State::InitSequence;
  479. currentScope = Scope::StartSeq;
  480. protocol.ResetResponseDecoder(); // important - finished delayed restart relies on this
  481. StartSeqRestart();
  482. }
  483. void ProtocolLogic::Stop() {
  484. state = State::Stopped;
  485. currentScope = Scope::Stopped;
  486. }
  487. void ProtocolLogic::ToolChange(uint8_t slot) {
  488. PlanGenericRequest(RequestMsg(RequestMsgCodes::Tool, slot));
  489. }
  490. void ProtocolLogic::Statistics() {
  491. PlanGenericRequest(RequestMsg(RequestMsgCodes::Version, 3));
  492. }
  493. void ProtocolLogic::UnloadFilament() {
  494. PlanGenericRequest(RequestMsg(RequestMsgCodes::Unload, 0));
  495. }
  496. void ProtocolLogic::LoadFilament(uint8_t slot) {
  497. PlanGenericRequest(RequestMsg(RequestMsgCodes::Load, slot));
  498. }
  499. void ProtocolLogic::EjectFilament(uint8_t slot) {
  500. PlanGenericRequest(RequestMsg(RequestMsgCodes::Eject, slot));
  501. }
  502. void ProtocolLogic::CutFilament(uint8_t slot) {
  503. PlanGenericRequest(RequestMsg(RequestMsgCodes::Cut, slot));
  504. }
  505. void ProtocolLogic::ResetMMU() {
  506. PlanGenericRequest(RequestMsg(RequestMsgCodes::Reset, 0));
  507. }
  508. void ProtocolLogic::Button(uint8_t index) {
  509. PlanGenericRequest(RequestMsg(RequestMsgCodes::Button, index));
  510. }
  511. void ProtocolLogic::Home(uint8_t mode) {
  512. PlanGenericRequest(RequestMsg(RequestMsgCodes::Home, mode));
  513. }
  514. void ProtocolLogic::ReadRegister(uint8_t address){
  515. PlanGenericRequest(RequestMsg(RequestMsgCodes::Read, address));
  516. }
  517. void ProtocolLogic::WriteRegister(uint8_t address, uint16_t data){
  518. PlanGenericRequest(RequestMsg(RequestMsgCodes::Write, address, data));
  519. }
  520. void ProtocolLogic::PlanGenericRequest(RequestMsg rq) {
  521. plannedRq = rq;
  522. if (!ExpectsResponse()) {
  523. ActivatePlannedRequest();
  524. } // otherwise wait for an empty window to activate the request
  525. }
  526. bool ProtocolLogic::ActivatePlannedRequest() {
  527. switch(plannedRq.code){
  528. case RequestMsgCodes::Button:
  529. // only issue the button to the MMU and do not restart the state machines
  530. SendButton(plannedRq.value);
  531. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  532. return true;
  533. case RequestMsgCodes::Read:
  534. SendReadRegister(plannedRq.value, ScopeState::ReadRegisterSent );
  535. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  536. return true;
  537. case RequestMsgCodes::Write:
  538. SendWriteRegister(plannedRq.value, plannedRq.value2, ScopeState::WriteRegisterSent );
  539. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  540. return true;
  541. case RequestMsgCodes::unknown:
  542. return false;
  543. default:// commands
  544. currentScope = Scope::Command;
  545. SetRequestMsg(plannedRq);
  546. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  547. CommandRestart();
  548. return true;
  549. }
  550. }
  551. StepStatus ProtocolLogic::SwitchFromIdleToCommand() {
  552. currentScope = Scope::Command;
  553. SetRequestMsg(rsp.request);
  554. // we are recovering from a communication drop out, the command is already running
  555. // and we have just received a response to a Q0 message about a command progress
  556. return ProcessCommandQueryResponse();
  557. }
  558. void ProtocolLogic::SwitchToIdle() {
  559. state = State::Running;
  560. currentScope = Scope::Idle;
  561. IdleRestart();
  562. }
  563. void ProtocolLogic::SwitchFromStartToIdle() {
  564. state = State::Running;
  565. currentScope = Scope::Idle;
  566. IdleRestart();
  567. SendQuery(); // force sending Q0 immediately
  568. }
  569. bool ProtocolLogic::Elapsed(uint32_t timeout) const {
  570. return _millis() >= (lastUARTActivityMs + timeout);
  571. }
  572. void ProtocolLogic::RecordUARTActivity() {
  573. lastUARTActivityMs = _millis();
  574. }
  575. void ProtocolLogic::RecordReceivedByte(uint8_t c) {
  576. lastReceivedBytes[lrb] = c;
  577. lrb = (lrb + 1) % lastReceivedBytes.size();
  578. }
  579. constexpr char NibbleToChar(uint8_t c) {
  580. switch (c) {
  581. case 0:
  582. case 1:
  583. case 2:
  584. case 3:
  585. case 4:
  586. case 5:
  587. case 6:
  588. case 7:
  589. case 8:
  590. case 9:
  591. return c + '0';
  592. case 10:
  593. case 11:
  594. case 12:
  595. case 13:
  596. case 14:
  597. case 15:
  598. return (c - 10) + 'a';
  599. default:
  600. return 0;
  601. }
  602. }
  603. void ProtocolLogic::FormatLastReceivedBytes(char *dst) {
  604. for (uint8_t i = 0; i < lastReceivedBytes.size(); ++i) {
  605. uint8_t b = lastReceivedBytes[(lrb - i - 1) % lastReceivedBytes.size()];
  606. dst[i * 3] = NibbleToChar(b >> 4);
  607. dst[i * 3 + 1] = NibbleToChar(b & 0xf);
  608. dst[i * 3 + 2] = ' ';
  609. }
  610. dst[(lastReceivedBytes.size() - 1) * 3 + 2] = 0; // terminate properly
  611. }
  612. void ProtocolLogic::FormatLastResponseMsgAndClearLRB(char *dst) {
  613. *dst++ = '<';
  614. for (uint8_t i = 0; i < lrb; ++i) {
  615. uint8_t b = lastReceivedBytes[i];
  616. if (b < 32)
  617. b = '.';
  618. if (b > 127)
  619. b = '.';
  620. *dst++ = b;
  621. }
  622. *dst = 0; // terminate properly
  623. lrb = 0; // reset the input buffer index in case of a clean message
  624. }
  625. void ProtocolLogic::LogRequestMsg(const uint8_t *txbuff, uint8_t size) {
  626. constexpr uint_fast8_t rqs = modules::protocol::Protocol::MaxRequestSize() + 1;
  627. char tmp[rqs] = ">";
  628. static char lastMsg[rqs] = "";
  629. for (uint8_t i = 0; i < size; ++i) {
  630. uint8_t b = txbuff[i];
  631. if (b < 32)
  632. b = '.';
  633. if (b > 127)
  634. b = '.';
  635. tmp[i + 1] = b;
  636. }
  637. tmp[size + 1] = 0;
  638. if (!strncmp_P(tmp, PSTR(">S0*c6."), rqs) && !strncmp(lastMsg, tmp, rqs)) {
  639. // @@TODO we skip the repeated request msgs for now
  640. // to avoid spoiling the whole log just with ">S0" messages
  641. // especially when the MMU is not connected.
  642. // We'll lose the ability to see if the printer is actually
  643. // trying to find the MMU, but since it has been reliable in the past
  644. // we can live without it for now.
  645. } else {
  646. MMU2_ECHO_MSGLN(tmp);
  647. }
  648. strncpy(lastMsg, tmp, rqs);
  649. }
  650. void ProtocolLogic::LogError(const char *reason_P) {
  651. char lrb[lastReceivedBytes.size() * 3];
  652. FormatLastReceivedBytes(lrb);
  653. MMU2_ERROR_MSGRPGM(reason_P);
  654. SERIAL_ECHOPGM(", last bytes: ");
  655. SERIAL_ECHOLN(lrb);
  656. }
  657. void ProtocolLogic::LogResponse() {
  658. char lrb[lastReceivedBytes.size()];
  659. FormatLastResponseMsgAndClearLRB(lrb);
  660. MMU2_ECHO_MSGLN(lrb);
  661. }
  662. StepStatus ProtocolLogic::SuppressShortDropOuts(const char *msg_P, StepStatus ss) {
  663. if (dataTO.Record(ss)) {
  664. LogError(msg_P);
  665. return dataTO.InitialCause();
  666. } else {
  667. return Processing; // suppress short drop outs of communication
  668. }
  669. }
  670. StepStatus ProtocolLogic::HandleCommunicationTimeout() {
  671. uart->flush(); // clear the output buffer
  672. protocol.ResetResponseDecoder();
  673. Start();
  674. return SuppressShortDropOuts(PSTR("Communication timeout"), CommunicationTimeout);
  675. }
  676. StepStatus ProtocolLogic::HandleProtocolError() {
  677. uart->flush(); // clear the output buffer
  678. state = State::InitSequence;
  679. currentScope = Scope::DelayedRestart;
  680. DelayedRestartRestart();
  681. return SuppressShortDropOuts(PSTR("Protocol Error"), ProtocolError);
  682. }
  683. StepStatus ProtocolLogic::Step() {
  684. if (!ExpectsResponse()) { // if not waiting for a response, activate a planned request immediately
  685. ActivatePlannedRequest();
  686. }
  687. auto currentStatus = ScopeStep();
  688. switch (currentStatus) {
  689. case Processing:
  690. // we are ok, the state machine continues correctly
  691. break;
  692. case Finished: {
  693. // We are ok, switching to Idle if there is no potential next request planned.
  694. // But the trouble is we must report a finished command if the previous command has just been finished
  695. // i.e. only try to find some planned command if we just finished the Idle cycle
  696. bool previousCommandFinished = currentScope == Scope::Command; // @@TODO this is a nasty hack :(
  697. if (!ActivatePlannedRequest()) { // if nothing is planned, switch to Idle
  698. SwitchToIdle();
  699. } else {
  700. // if the previous cycle was Idle and now we have planned a new command -> avoid returning Finished
  701. if (!previousCommandFinished && currentScope == Scope::Command) {
  702. currentStatus = Processing;
  703. }
  704. }
  705. } break;
  706. case CommandRejected:
  707. // we have to repeat it - that's the only thing we can do
  708. // no change in state
  709. // @@TODO wait until Q0 returns command in progress finished, then we can send this one
  710. LogError(PSTR("Command rejected"));
  711. CommandRestart();
  712. break;
  713. case CommandError:
  714. LogError(PSTR("Command Error"));
  715. // we shall probably transfer into the Idle state and await further instructions from the upper layer
  716. // Idle state may solve the problem of keeping up the heart beat running
  717. break;
  718. case VersionMismatch:
  719. LogError(PSTR("Version mismatch"));
  720. break;
  721. case ProtocolError:
  722. currentStatus = HandleProtocolError();
  723. break;
  724. case CommunicationTimeout:
  725. currentStatus = HandleCommunicationTimeout();
  726. break;
  727. default:
  728. break;
  729. }
  730. // special handling of explicit printer errors
  731. return IsPrinterError() ? StepStatus::PrinterError : currentStatus;
  732. }
  733. uint8_t ProtocolLogic::CommandInProgress() const {
  734. if (currentScope != Scope::Command)
  735. return 0;
  736. return (uint8_t)ReqMsg().code;
  737. }
  738. bool DropOutFilter::Record(StepStatus ss) {
  739. if (occurrences == maxOccurrences) {
  740. cause = ss;
  741. }
  742. --occurrences;
  743. return occurrences == 0;
  744. }
  745. } // namespace MMU2