mmu2_protocol_logic.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 constexpr uint8_t supportedMmuFWVersionMajor = 2;
  8. static constexpr uint8_t supportedMmuFWVersionMinor = 0;
  9. static constexpr uint8_t supportedMmuFWVersionBuild = 19;
  10. StepStatus ProtocolLogicPartBase::ProcessFINDAReqSent(StepStatus finishedRV, State nextState){
  11. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  12. return expmsg;
  13. logic->findaPressed = logic->rsp.paramValue;
  14. state = nextState;
  15. return finishedRV;
  16. }
  17. void ProtocolLogicPartBase::CheckAndReportAsyncEvents(){
  18. // even when waiting for a query period, we need to report a change in filament sensor's state
  19. // - it is vital for a precise synchronization of moves of the printer and the MMU
  20. uint8_t fs = (uint8_t)WhereIsFilament();
  21. if( fs != logic->lastFSensor ){
  22. SendAndUpdateFilamentSensor();
  23. }
  24. }
  25. void ProtocolLogicPartBase::SendQuery(){
  26. logic->SendMsg(RequestMsg(RequestMsgCodes::Query, 0));
  27. state = State::QuerySent;
  28. }
  29. void ProtocolLogicPartBase::SendFINDAQuery(){
  30. logic->SendMsg(RequestMsg(RequestMsgCodes::Finda, 0 ) );
  31. state = State::FINDAReqSent;
  32. }
  33. void ProtocolLogicPartBase::SendAndUpdateFilamentSensor(){
  34. logic->SendMsg(RequestMsg(RequestMsgCodes::FilamentSensor, logic->lastFSensor = (uint8_t)WhereIsFilament() ) );
  35. state = State::FilamentSensorStateSent;
  36. }
  37. void ProtocolLogicPartBase::SendButton(uint8_t btn){
  38. logic->SendMsg(RequestMsg(RequestMsgCodes::Button, btn));
  39. state = State::ButtonSent;
  40. }
  41. void ProtocolLogicPartBase::SendVersion(uint8_t stage) {
  42. logic->SendMsg(RequestMsg(RequestMsgCodes::Version, stage));
  43. state = (State)((uint_fast8_t)State::S0Sent + stage);
  44. }
  45. // searches for "ok\n" in the incoming serial data (that's the usual response of the old MMU FW)
  46. struct OldMMUFWDetector {
  47. uint8_t ok;
  48. inline constexpr OldMMUFWDetector():ok(0) { }
  49. enum class State : uint8_t { MatchingPart, SomethingElse, Matched };
  50. /// @returns true when "ok\n" gets detected
  51. State Detect(uint8_t c){
  52. // consume old MMU FW's data if any -> avoid confusion of protocol decoder
  53. if(ok == 0 && c == 'o'){
  54. ++ok;
  55. return State::MatchingPart;
  56. } else if(ok == 1 && c == 'k'){
  57. ++ok;
  58. return State::MatchingPart;
  59. } else if(ok == 2 && c == '\n'){
  60. return State::Matched;
  61. }
  62. return State::SomethingElse;
  63. }
  64. };
  65. StepStatus ProtocolLogic::ExpectingMessage(uint32_t timeout) {
  66. int bytesConsumed = 0;
  67. int c = -1;
  68. OldMMUFWDetector oldMMUh4x0r; // old MMU FW hacker ;)
  69. // try to consume as many rx bytes as possible (until a message has been completed)
  70. while((c = uart->read()) >= 0){
  71. ++bytesConsumed;
  72. RecordReceivedByte(c);
  73. switch (protocol.DecodeResponse(c)) {
  74. case DecodeStatus::MessageCompleted:
  75. rsp = protocol.GetResponseMsg();
  76. LogResponse();
  77. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  78. return MessageReady;
  79. case DecodeStatus::NeedMoreData:
  80. break;
  81. case DecodeStatus::Error:{
  82. // consume old MMU FW's data if any -> avoid confusion of protocol decoder
  83. auto old = oldMMUh4x0r.Detect(c);
  84. if( old == OldMMUFWDetector::State::Matched ){
  85. // hack bad FW version - BEWARE - we silently assume that the first query is an "S0"
  86. // The old MMU FW responds with "ok\n" and we fake the response to a bad FW version at this spot
  87. rsp = ResponseMsg(RequestMsg(RequestMsgCodes::Version, 0), ResponseMsgParamCodes::Accepted, 0);
  88. return MessageReady;
  89. } else if( old == OldMMUFWDetector::State::MatchingPart ){
  90. break;
  91. }
  92. }
  93. // otherwise [[fallthrough]]
  94. default:
  95. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  96. return ProtocolError;
  97. }
  98. }
  99. if( bytesConsumed != 0 ){
  100. RecordUARTActivity(); // something has happened on the UART, update the timeout record
  101. return Processing; // consumed some bytes, but message still not ready
  102. } else if (Elapsed(timeout)) {
  103. return CommunicationTimeout;
  104. }
  105. return Processing;
  106. }
  107. void ProtocolLogic::SendMsg(RequestMsg rq) {
  108. uint8_t txbuff[Protocol::MaxRequestSize()];
  109. uint8_t len = Protocol::EncodeRequest(rq, txbuff);
  110. uart->write(txbuff, len);
  111. LogRequestMsg(txbuff, len);
  112. RecordUARTActivity();
  113. }
  114. void StartSeq::Restart() {
  115. SendVersion(0);
  116. }
  117. StepStatus StartSeq::Step() {
  118. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  119. return expmsg;
  120. // solve initial handshake
  121. switch (state) {
  122. case State::S0Sent: // received response to S0 - major
  123. if( logic->rsp.request.code != RequestMsgCodes::Version || logic->rsp.request.value != 0 ){
  124. // got a response to something else - protocol corruption probably, repeat the query
  125. SendVersion(0);
  126. } else {
  127. logic->mmuFwVersionMajor = logic->rsp.paramValue;
  128. if (logic->mmuFwVersionMajor != supportedMmuFWVersionMajor) {
  129. return VersionMismatch;
  130. }
  131. logic->dataTO.Reset(); // got meaningful response from the MMU, stop data layer timeout tracking
  132. SendVersion(1);
  133. }
  134. break;
  135. case State::S1Sent: // received response to S1 - minor
  136. if( logic->rsp.request.code != RequestMsgCodes::Version || logic->rsp.request.value != 1 ){
  137. // got a response to something else - protocol corruption probably, repeat the query OR restart the comm by issuing S0?
  138. SendVersion(1);
  139. } else {
  140. logic->mmuFwVersionMinor = logic->rsp.paramValue;
  141. if (logic->mmuFwVersionMinor != supportedMmuFWVersionMinor) {
  142. return VersionMismatch;
  143. }
  144. SendVersion(2);
  145. }
  146. break;
  147. case State::S2Sent: // received response to S2 - revision
  148. if( logic->rsp.request.code != RequestMsgCodes::Version || logic->rsp.request.value != 2 ){
  149. // got a response to something else - protocol corruption probably, repeat the query OR restart the comm by issuing S0?
  150. SendVersion(2);
  151. } else {
  152. logic->mmuFwVersionBuild = logic->rsp.paramValue;
  153. if (logic->mmuFwVersionBuild < supportedMmuFWVersionBuild) {
  154. return VersionMismatch;
  155. }
  156. // Start General Interrogation after line up.
  157. // For now we just send the state of the filament sensor, but we may request
  158. // data point states from the MMU as well. TBD in the future, especially with another protocol
  159. SendAndUpdateFilamentSensor();
  160. }
  161. break;
  162. case State::FilamentSensorStateSent:
  163. state = State::Ready;
  164. logic->SwitchFromStartToIdle();
  165. return Processing; // Returning Finished is not a good idea in case of a fast error recovery
  166. // - it tells the printer, that the command which experienced a protocol error and recovered successfully actually terminated.
  167. // 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.
  168. break;
  169. case State::RecoveringProtocolError:
  170. // timer elapsed, clear the input buffer
  171. while (logic->uart->read() >= 0)
  172. ;
  173. SendVersion(0);
  174. break;
  175. default:
  176. return VersionMismatch;
  177. }
  178. return Processing;
  179. }
  180. void DelayedRestart::Restart() {
  181. state = State::RecoveringProtocolError;
  182. }
  183. StepStatus DelayedRestart::Step() {
  184. switch (state) {
  185. case State::RecoveringProtocolError:
  186. if (logic->Elapsed(heartBeatPeriod)) { // this basically means, that we are waiting until there is some traffic on
  187. while (logic->uart->read() != -1)
  188. ; // clear the input buffer
  189. // switch to StartSeq
  190. logic->Start();
  191. }
  192. return Processing;
  193. break;
  194. default:
  195. break;
  196. }
  197. return Finished;
  198. }
  199. void Command::Restart() {
  200. state = State::CommandSent;
  201. logic->SendMsg(logic->command.rq);
  202. }
  203. StepStatus Command::Step() {
  204. switch (state) {
  205. case State::CommandSent: {
  206. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  207. return expmsg;
  208. switch (logic->rsp.paramCode) { // the response should be either accepted or rejected
  209. case ResponseMsgParamCodes::Accepted:
  210. logic->progressCode = ProgressCode::OK;
  211. logic->errorCode = ErrorCode::RUNNING;
  212. state = State::Wait;
  213. break;
  214. case ResponseMsgParamCodes::Rejected:
  215. // rejected - should normally not happen, but report the error up
  216. logic->progressCode = ProgressCode::OK;
  217. logic->errorCode = ErrorCode::PROTOCOL_ERROR;
  218. return CommandRejected;
  219. default:
  220. return ProtocolError;
  221. }
  222. } break;
  223. case State::Wait:
  224. if (logic->Elapsed(heartBeatPeriod)) {
  225. SendQuery();
  226. } else {
  227. // even when waiting for a query period, we need to report a change in filament sensor's state
  228. // - it is vital for a precise synchronization of moves of the printer and the MMU
  229. CheckAndReportAsyncEvents();
  230. }
  231. break;
  232. case State::QuerySent:
  233. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  234. return expmsg;
  235. [[fallthrough]];
  236. case State::ContinueFromIdle:
  237. switch (logic->rsp.paramCode) {
  238. case ResponseMsgParamCodes::Processing:
  239. logic->progressCode = static_cast<ProgressCode>(logic->rsp.paramValue);
  240. logic->errorCode = ErrorCode::OK;
  241. SendAndUpdateFilamentSensor(); // keep on reporting the state of fsensor regularly
  242. break;
  243. case ResponseMsgParamCodes::Error:
  244. // in case of an error the progress code remains as it has been before
  245. logic->errorCode = static_cast<ErrorCode>(logic->rsp.paramValue);
  246. // keep on reporting the state of fsensor regularly even in command error state
  247. // - the MMU checks FINDA and fsensor even while recovering from errors
  248. SendAndUpdateFilamentSensor();
  249. return CommandError;
  250. case ResponseMsgParamCodes::Button:
  251. // The user pushed a button on the MMU. Save it, do what we need to do
  252. // to prepare, then pass it back to the MMU so it can work its magic.
  253. logic->buttonCode = static_cast<Buttons>(logic->rsp.paramValue);
  254. SendAndUpdateFilamentSensor();
  255. return ButtonPushed;
  256. case ResponseMsgParamCodes::Finished:
  257. logic->progressCode = ProgressCode::OK;
  258. state = State::Ready;
  259. return Finished;
  260. default:
  261. return ProtocolError;
  262. }
  263. break;
  264. case State::FilamentSensorStateSent:
  265. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  266. return expmsg;
  267. SendFINDAQuery();
  268. break;
  269. case State::FINDAReqSent:
  270. return ProcessFINDAReqSent(Processing, State::Wait);
  271. case State::ButtonSent:{
  272. // button is never confirmed ... may be it should be
  273. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  274. return expmsg;
  275. if (logic->rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  276. // Button was accepted, decrement the retry.
  277. mmu2.DecrementRetryAttempts();
  278. }
  279. SendAndUpdateFilamentSensor();
  280. } break;
  281. default:
  282. return ProtocolError;
  283. }
  284. return Processing;
  285. }
  286. void Idle::Restart() {
  287. state = State::Ready;
  288. }
  289. StepStatus Idle::Step() {
  290. switch (state) {
  291. case State::Ready: // check timeout
  292. if (logic->Elapsed(heartBeatPeriod)) {
  293. SendQuery();
  294. return Processing;
  295. }
  296. break;
  297. case State::QuerySent: // check UART
  298. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  299. return expmsg;
  300. // 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.
  301. // That causes no issues here, we just need to switch to Command processing and continue there from now on.
  302. // 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.
  303. switch( logic->rsp.request.code ){
  304. case RequestMsgCodes::Cut:
  305. case RequestMsgCodes::Eject:
  306. case RequestMsgCodes::Load:
  307. case RequestMsgCodes::Mode:
  308. case RequestMsgCodes::Tool:
  309. case RequestMsgCodes::Unload:
  310. if( logic->rsp.paramCode != ResponseMsgParamCodes::Finished ){
  311. logic->SwitchFromIdleToCommand();
  312. return Processing;
  313. }
  314. break;
  315. case RequestMsgCodes::Reset:
  316. // this one is kind of special
  317. // we do not transfer to any "running" command (i.e. we stay in Idle),
  318. // but in case there is an error reported we must make sure it gets propagated
  319. switch( logic->rsp.paramCode ){
  320. case ResponseMsgParamCodes::Processing:
  321. // @@TODO we may actually use this branch to report progress of manual operation on the MMU
  322. // The MMU sends e.g. X0 P27 after its restart when the user presses an MMU button to move the Selector
  323. // For now let's behave just like "finished"
  324. case ResponseMsgParamCodes::Finished:
  325. logic->errorCode = ErrorCode::OK;
  326. break;
  327. default:
  328. logic->errorCode = static_cast<ErrorCode>(logic->rsp.paramValue);
  329. SendFINDAQuery(); // continue Idle state without restarting the communication
  330. return CommandError;
  331. }
  332. break;
  333. default:
  334. break;
  335. }
  336. SendFINDAQuery();
  337. return Processing;
  338. break;
  339. case State::FINDAReqSent:
  340. return ProcessFINDAReqSent(Finished, State::Ready);
  341. default:
  342. return ProtocolError;
  343. }
  344. // The "return Finished" in this state machine requires a bit of explanation:
  345. // The Idle state either did nothing (still waiting for the heartbeat timeout)
  346. // or just successfully received the answer to Q0, whatever that was.
  347. // In both cases, it is ready to hand over work to a command or something else,
  348. // therefore we are returning Finished (also to exit mmu_loop() and unblock Marlin's loop!).
  349. // If there is no work, we'll end up in the Idle state again
  350. // and we'll send the heartbeat message after the specified timeout.
  351. return Finished;
  352. }
  353. ProtocolLogic::ProtocolLogic(MMU2Serial *uart)
  354. : stopped(this)
  355. , startSeq(this)
  356. , delayedRestart(this)
  357. , idle(this)
  358. , command(this)
  359. , currentState(&stopped)
  360. , plannedRq(RequestMsgCodes::unknown, 0)
  361. , lastUARTActivityMs(0)
  362. , dataTO()
  363. , rsp(RequestMsg(RequestMsgCodes::unknown, 0), ResponseMsgParamCodes::unknown, 0)
  364. , state(State::Stopped)
  365. , lrb(0)
  366. , uart(uart)
  367. , errorCode(ErrorCode::OK)
  368. , progressCode(ProgressCode::OK)
  369. , buttonCode(NoButton)
  370. , lastFSensor((uint8_t)WhereIsFilament())
  371. , findaPressed(false)
  372. , mmuFwVersionMajor(0)
  373. , mmuFwVersionMinor(0)
  374. , mmuFwVersionBuild(0)
  375. {}
  376. void ProtocolLogic::Start() {
  377. state = State::InitSequence;
  378. currentState = &startSeq;
  379. protocol.ResetResponseDecoder(); // important - finished delayed restart relies on this
  380. startSeq.Restart();
  381. }
  382. void ProtocolLogic::Stop() {
  383. state = State::Stopped;
  384. currentState = &stopped;
  385. }
  386. void ProtocolLogic::ToolChange(uint8_t slot) {
  387. PlanGenericRequest(RequestMsg(RequestMsgCodes::Tool, slot));
  388. }
  389. void ProtocolLogic::UnloadFilament() {
  390. PlanGenericRequest(RequestMsg(RequestMsgCodes::Unload, 0));
  391. }
  392. void ProtocolLogic::LoadFilament(uint8_t slot) {
  393. PlanGenericRequest(RequestMsg(RequestMsgCodes::Load, slot));
  394. }
  395. void ProtocolLogic::EjectFilament(uint8_t slot) {
  396. PlanGenericRequest(RequestMsg(RequestMsgCodes::Eject, slot));
  397. }
  398. void ProtocolLogic::CutFilament(uint8_t slot){
  399. PlanGenericRequest(RequestMsg(RequestMsgCodes::Cut, slot));
  400. }
  401. void ProtocolLogic::ResetMMU() {
  402. PlanGenericRequest(RequestMsg(RequestMsgCodes::Reset, 0));
  403. }
  404. void ProtocolLogic::Button(uint8_t index){
  405. PlanGenericRequest(RequestMsg(RequestMsgCodes::Button, index));
  406. }
  407. void ProtocolLogic::Home(uint8_t mode){
  408. PlanGenericRequest(RequestMsg(RequestMsgCodes::Home, mode));
  409. }
  410. void ProtocolLogic::PlanGenericRequest(RequestMsg rq) {
  411. plannedRq = rq;
  412. if( ! currentState->ExpectsResponse() ){
  413. ActivatePlannedRequest();
  414. } // otherwise wait for an empty window to activate the request
  415. }
  416. bool ProtocolLogic::ActivatePlannedRequest(){
  417. if( plannedRq.code == RequestMsgCodes::Button ){
  418. // only issue the button to the MMU and do not restart the state machines
  419. // @@TODO - this is not completely correct, but it does the job.
  420. // In Idle mode the command part is not active, but we still need button handling in Idle mode (resolve MMU init errors)
  421. // -> command.SendButton is not correct, but it sends the message and everything works (for now)
  422. command.SendButton(plannedRq.value);
  423. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  424. return true;
  425. } else if( plannedRq.code != RequestMsgCodes::unknown ){
  426. currentState = &command;
  427. command.SetRequestMsg(plannedRq);
  428. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  429. command.Restart();
  430. return true;
  431. }
  432. return false;
  433. }
  434. void ProtocolLogic::SwitchFromIdleToCommand(){
  435. currentState = &command;
  436. command.SetRequestMsg(rsp.request);
  437. // we are recovering from a communication drop out, the command is already running
  438. // and we have just received a response to a Q0 message about a command progress
  439. command.ContinueFromIdle();
  440. }
  441. void ProtocolLogic::SwitchToIdle() {
  442. state = State::Running;
  443. currentState = &idle;
  444. idle.Restart();
  445. }
  446. void ProtocolLogic::SwitchFromStartToIdle(){
  447. state = State::Running;
  448. currentState = &idle;
  449. idle.Restart();
  450. idle.SendQuery(); // force sending Q0 immediately
  451. idle.state = Idle::State::QuerySent;
  452. }
  453. bool ProtocolLogic::Elapsed(uint32_t timeout) const {
  454. return _millis() >= (lastUARTActivityMs + timeout);
  455. }
  456. void ProtocolLogic::RecordUARTActivity() {
  457. lastUARTActivityMs = _millis();
  458. }
  459. void ProtocolLogic::RecordReceivedByte(uint8_t c){
  460. lastReceivedBytes[lrb] = c;
  461. lrb = (lrb+1) % lastReceivedBytes.size();
  462. }
  463. constexpr char NibbleToChar(uint8_t c){
  464. switch (c) {
  465. case 0:
  466. case 1:
  467. case 2:
  468. case 3:
  469. case 4:
  470. case 5:
  471. case 6:
  472. case 7:
  473. case 8:
  474. case 9:
  475. return c + '0';
  476. case 10:
  477. case 11:
  478. case 12:
  479. case 13:
  480. case 14:
  481. case 15:
  482. return (c - 10) + 'a';
  483. default:
  484. return 0;
  485. }
  486. }
  487. void ProtocolLogic::FormatLastReceivedBytes(char *dst){
  488. for(uint8_t i = 0; i < lastReceivedBytes.size(); ++i){
  489. uint8_t b = lastReceivedBytes[ (lrb-i-1) % lastReceivedBytes.size() ];
  490. dst[i*3] = NibbleToChar(b >> 4);
  491. dst[i*3+1] = NibbleToChar(b & 0xf);
  492. dst[i*3+2] = ' ';
  493. }
  494. dst[ (lastReceivedBytes.size() - 1) * 3 + 2] = 0; // terminate properly
  495. }
  496. void ProtocolLogic::FormatLastResponseMsgAndClearLRB(char *dst){
  497. *dst++ = '<';
  498. for(uint8_t i = 0; i < lrb; ++i){
  499. uint8_t b = lastReceivedBytes[ i ];
  500. if( b < 32 )b = '.';
  501. if( b > 127 )b = '.';
  502. *dst++ = b;
  503. }
  504. *dst = 0; // terminate properly
  505. lrb = 0; // reset the input buffer index in case of a clean message
  506. }
  507. void ProtocolLogic::LogRequestMsg(const uint8_t *txbuff, uint8_t size){
  508. constexpr uint_fast8_t rqs = modules::protocol::Protocol::MaxRequestSize() + 2;
  509. char tmp[rqs] = ">";
  510. static char lastMsg[rqs] = "";
  511. for(uint8_t i = 0; i < size; ++i){
  512. uint8_t b = txbuff[i];
  513. if( b < 32 )b = '.';
  514. if( b > 127 )b = '.';
  515. tmp[i+1] = b;
  516. }
  517. tmp[size+1] = '\n';
  518. tmp[size+2] = 0;
  519. if( !strncmp(tmp, ">S0.\n", rqs) && !strncmp(lastMsg, tmp, rqs) ){
  520. // @@TODO we skip the repeated request msgs for now
  521. // to avoid spoiling the whole log just with ">S0" messages
  522. // especially when the MMU is not connected.
  523. // We'll lose the ability to see if the printer is actually
  524. // trying to find the MMU, but since it has been reliable in the past
  525. // we can live without it for now.
  526. } else {
  527. MMU2_ECHO_MSG(tmp);
  528. }
  529. memcpy(lastMsg, tmp, rqs);
  530. }
  531. void ProtocolLogic::LogError(const char *reason){
  532. char lrb[lastReceivedBytes.size() * 3];
  533. FormatLastReceivedBytes(lrb);
  534. MMU2_ERROR_MSG(reason);
  535. SERIAL_ECHO(", last bytes: ");
  536. SERIAL_ECHOLN(lrb);
  537. }
  538. void ProtocolLogic::LogResponse(){
  539. char lrb[lastReceivedBytes.size()];
  540. FormatLastResponseMsgAndClearLRB(lrb);
  541. MMU2_ECHO_MSG(lrb);
  542. SERIAL_ECHOLN();
  543. }
  544. StepStatus ProtocolLogic::SuppressShortDropOuts(const char *msg, StepStatus ss) {
  545. if( dataTO.Record(ss) ){
  546. LogError(msg);
  547. return dataTO.InitialCause();
  548. } else {
  549. return Processing; // suppress short drop outs of communication
  550. }
  551. }
  552. StepStatus ProtocolLogic::HandleCommunicationTimeout() {
  553. uart->flush(); // clear the output buffer
  554. protocol.ResetResponseDecoder();
  555. Start();
  556. return SuppressShortDropOuts("Communication timeout", CommunicationTimeout);
  557. }
  558. StepStatus ProtocolLogic::HandleProtocolError() {
  559. uart->flush(); // clear the output buffer
  560. state = State::InitSequence;
  561. currentState = &delayedRestart;
  562. delayedRestart.Restart();
  563. return SuppressShortDropOuts("Protocol Error", ProtocolError);
  564. }
  565. StepStatus ProtocolLogic::Step() {
  566. if( ! currentState->ExpectsResponse() ){ // if not waiting for a response, activate a planned request immediately
  567. ActivatePlannedRequest();
  568. }
  569. auto currentStatus = currentState->Step();
  570. switch (currentStatus) {
  571. case Processing:
  572. // we are ok, the state machine continues correctly
  573. break;
  574. case Finished: {
  575. // We are ok, switching to Idle if there is no potential next request planned.
  576. // But the trouble is we must report a finished command if the previous command has just been finished
  577. // i.e. only try to find some planned command if we just finished the Idle cycle
  578. bool previousCommandFinished = currentState == &command; // @@TODO this is a nasty hack :(
  579. if( ! ActivatePlannedRequest() ){ // if nothing is planned, switch to Idle
  580. SwitchToIdle();
  581. } else {
  582. // if the previous cycle was Idle and now we have planned a new command -> avoid returning Finished
  583. if( ! previousCommandFinished && currentState == &command){
  584. currentStatus = Processing;
  585. }
  586. }
  587. } break;
  588. case CommandRejected:
  589. // we have to repeat it - that's the only thing we can do
  590. // no change in state
  591. // @@TODO wait until Q0 returns command in progress finished, then we can send this one
  592. LogError("Command rejected");
  593. command.Restart();
  594. break;
  595. case CommandError:
  596. LogError("Command Error");
  597. // we shall probably transfer into the Idle state and await further instructions from the upper layer
  598. // Idle state may solve the problem of keeping up the heart beat running
  599. break;
  600. case VersionMismatch:
  601. LogError("Version mismatch");
  602. Stop(); // cannot continue
  603. break;
  604. case ProtocolError:
  605. currentStatus = HandleProtocolError();
  606. break;
  607. case CommunicationTimeout:
  608. currentStatus = HandleCommunicationTimeout();
  609. break;
  610. default:
  611. break;
  612. }
  613. return currentStatus;
  614. }
  615. uint8_t ProtocolLogic::CommandInProgress() const {
  616. if( currentState != &command )
  617. return 0;
  618. return (uint8_t)command.ReqMsg().code;
  619. }
  620. bool DropOutFilter::Record(StepStatus ss){
  621. if( occurrences == maxOccurrences ){
  622. cause = ss;
  623. }
  624. --occurrences;
  625. return occurrences == 0;
  626. }
  627. } // namespace MMU2