mmu2_protocol_logic.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. return Finished;
  165. break;
  166. case State::RecoveringProtocolError:
  167. // timer elapsed, clear the input buffer
  168. while (logic->uart->read() >= 0)
  169. ;
  170. SendVersion(0);
  171. break;
  172. default:
  173. return VersionMismatch;
  174. }
  175. return Processing;
  176. }
  177. void DelayedRestart::Restart() {
  178. state = State::RecoveringProtocolError;
  179. }
  180. StepStatus DelayedRestart::Step() {
  181. switch (state) {
  182. case State::RecoveringProtocolError:
  183. if (logic->Elapsed(heartBeatPeriod)) { // this basically means, that we are waiting until there is some traffic on
  184. while (logic->uart->read() != -1)
  185. ; // clear the input buffer
  186. // switch to StartSeq
  187. logic->Start();
  188. }
  189. return Processing;
  190. break;
  191. default:
  192. break;
  193. }
  194. return Finished;
  195. }
  196. void Command::Restart() {
  197. state = State::CommandSent;
  198. logic->SendMsg(logic->command.rq);
  199. }
  200. StepStatus Command::Step() {
  201. switch (state) {
  202. case State::CommandSent: {
  203. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  204. return expmsg;
  205. switch (logic->rsp.paramCode) { // the response should be either accepted or rejected
  206. case ResponseMsgParamCodes::Accepted:
  207. logic->progressCode = ProgressCode::OK;
  208. logic->errorCode = ErrorCode::RUNNING;
  209. state = State::Wait;
  210. break;
  211. case ResponseMsgParamCodes::Rejected:
  212. // rejected - should normally not happen, but report the error up
  213. logic->progressCode = ProgressCode::OK;
  214. logic->errorCode = ErrorCode::PROTOCOL_ERROR;
  215. return CommandRejected;
  216. default:
  217. return ProtocolError;
  218. }
  219. } break;
  220. case State::Wait:
  221. if (logic->Elapsed(heartBeatPeriod)) {
  222. SendQuery();
  223. } else {
  224. // even when waiting for a query period, we need to report a change in filament sensor's state
  225. // - it is vital for a precise synchronization of moves of the printer and the MMU
  226. CheckAndReportAsyncEvents();
  227. }
  228. break;
  229. case State::QuerySent:
  230. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  231. return expmsg;
  232. [[fallthrough]];
  233. case State::ContinueFromIdle:
  234. switch (logic->rsp.paramCode) {
  235. case ResponseMsgParamCodes::Processing:
  236. logic->progressCode = static_cast<ProgressCode>(logic->rsp.paramValue);
  237. logic->errorCode = ErrorCode::OK;
  238. SendAndUpdateFilamentSensor(); // keep on reporting the state of fsensor regularly
  239. break;
  240. case ResponseMsgParamCodes::Error:
  241. // in case of an error the progress code remains as it has been before
  242. logic->errorCode = static_cast<ErrorCode>(logic->rsp.paramValue);
  243. // keep on reporting the state of fsensor regularly even in command error state
  244. // - the MMU checks FINDA and fsensor even while recovering from errors
  245. SendAndUpdateFilamentSensor();
  246. return CommandError;
  247. case ResponseMsgParamCodes::Button:
  248. // The user pushed a button on the MMU. Save it, do what we need to do
  249. // to prepare, then pass it back to the MMU so it can work its magic.
  250. logic->buttonCode = static_cast<Buttons>(logic->rsp.paramValue);
  251. SendAndUpdateFilamentSensor();
  252. return ButtonPushed;
  253. case ResponseMsgParamCodes::Finished:
  254. logic->progressCode = ProgressCode::OK;
  255. state = State::Ready;
  256. return Finished;
  257. default:
  258. return ProtocolError;
  259. }
  260. break;
  261. case State::FilamentSensorStateSent:
  262. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  263. return expmsg;
  264. SendFINDAQuery();
  265. break;
  266. case State::FINDAReqSent:
  267. return ProcessFINDAReqSent(Processing, State::Wait);
  268. case State::ButtonSent:{
  269. // button is never confirmed ... may be it should be
  270. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  271. return expmsg;
  272. if (logic->rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  273. // Button was accepted, decrement the retry.
  274. mmu2.DecrementRetryAttempts();
  275. }
  276. SendAndUpdateFilamentSensor();
  277. } break;
  278. default:
  279. return ProtocolError;
  280. }
  281. return Processing;
  282. }
  283. void Idle::Restart() {
  284. state = State::Ready;
  285. }
  286. StepStatus Idle::Step() {
  287. switch (state) {
  288. case State::Ready: // check timeout
  289. if (logic->Elapsed(heartBeatPeriod)) {
  290. SendQuery();
  291. return Processing;
  292. }
  293. break;
  294. case State::QuerySent: // check UART
  295. if (auto expmsg = logic->ExpectingMessage(linkLayerTimeout); expmsg != MessageReady)
  296. return expmsg;
  297. // 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.
  298. // That causes no issues here, we just need to switch to Command processing and continue there from now on.
  299. // 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.
  300. switch( logic->rsp.request.code ){
  301. case RequestMsgCodes::Cut:
  302. case RequestMsgCodes::Eject:
  303. case RequestMsgCodes::Load:
  304. case RequestMsgCodes::Mode:
  305. case RequestMsgCodes::Tool:
  306. case RequestMsgCodes::Unload:
  307. if( logic->rsp.paramCode != ResponseMsgParamCodes::Finished ){
  308. logic->SwitchFromIdleToCommand();
  309. return Processing;
  310. }
  311. break;
  312. case RequestMsgCodes::Reset:
  313. // this one is kind of special
  314. // we do not transfer to any "running" command (i.e. we stay in Idle),
  315. // but in case there is an error reported we must make sure it gets propagated
  316. switch( logic->rsp.paramCode ){
  317. case ResponseMsgParamCodes::Processing:
  318. // @@TODO we may actually use this branch to report progress of manual operation on the MMU
  319. // The MMU sends e.g. X0 P27 after its restart when the user presses an MMU button to move the Selector
  320. // For now let's behave just like "finished"
  321. case ResponseMsgParamCodes::Finished:
  322. logic->errorCode = ErrorCode::OK;
  323. break;
  324. default:
  325. logic->errorCode = static_cast<ErrorCode>(logic->rsp.paramValue);
  326. SendFINDAQuery(); // continue Idle state without restarting the communication
  327. return CommandError;
  328. }
  329. break;
  330. default:
  331. break;
  332. }
  333. SendFINDAQuery();
  334. return Processing;
  335. break;
  336. case State::FINDAReqSent:
  337. return ProcessFINDAReqSent(Finished, State::Ready);
  338. default:
  339. return ProtocolError;
  340. }
  341. // The "return Finished" in this state machine requires a bit of explanation:
  342. // The Idle state either did nothing (still waiting for the heartbeat timeout)
  343. // or just successfully received the answer to Q0, whatever that was.
  344. // In both cases, it is ready to hand over work to a command or something else,
  345. // therefore we are returning Finished (also to exit mmu_loop() and unblock Marlin's loop!).
  346. // If there is no work, we'll end up in the Idle state again
  347. // and we'll send the heartbeat message after the specified timeout.
  348. return Finished;
  349. }
  350. ProtocolLogic::ProtocolLogic(MMU2Serial *uart)
  351. : stopped(this)
  352. , startSeq(this)
  353. , delayedRestart(this)
  354. , idle(this)
  355. , command(this)
  356. , currentState(&stopped)
  357. , plannedRq(RequestMsgCodes::unknown, 0)
  358. , lastUARTActivityMs(0)
  359. , dataTO()
  360. , rsp(RequestMsg(RequestMsgCodes::unknown, 0), ResponseMsgParamCodes::unknown, 0)
  361. , state(State::Stopped)
  362. , lrb(0)
  363. , uart(uart)
  364. , errorCode(ErrorCode::OK)
  365. , progressCode(ProgressCode::OK)
  366. , buttonCode(NoButton)
  367. , lastFSensor((uint8_t)WhereIsFilament())
  368. , findaPressed(false)
  369. , mmuFwVersionMajor(0)
  370. , mmuFwVersionMinor(0)
  371. , mmuFwVersionBuild(0)
  372. {}
  373. void ProtocolLogic::Start() {
  374. state = State::InitSequence;
  375. currentState = &startSeq;
  376. protocol.ResetResponseDecoder(); // important - finished delayed restart relies on this
  377. startSeq.Restart();
  378. }
  379. void ProtocolLogic::Stop() {
  380. state = State::Stopped;
  381. currentState = &stopped;
  382. }
  383. void ProtocolLogic::ToolChange(uint8_t slot) {
  384. PlanGenericRequest(RequestMsg(RequestMsgCodes::Tool, slot));
  385. }
  386. void ProtocolLogic::UnloadFilament() {
  387. PlanGenericRequest(RequestMsg(RequestMsgCodes::Unload, 0));
  388. }
  389. void ProtocolLogic::LoadFilament(uint8_t slot) {
  390. PlanGenericRequest(RequestMsg(RequestMsgCodes::Load, slot));
  391. }
  392. void ProtocolLogic::EjectFilament(uint8_t slot) {
  393. PlanGenericRequest(RequestMsg(RequestMsgCodes::Eject, slot));
  394. }
  395. void ProtocolLogic::CutFilament(uint8_t slot){
  396. PlanGenericRequest(RequestMsg(RequestMsgCodes::Cut, slot));
  397. }
  398. void ProtocolLogic::ResetMMU() {
  399. PlanGenericRequest(RequestMsg(RequestMsgCodes::Reset, 0));
  400. }
  401. void ProtocolLogic::Button(uint8_t index){
  402. PlanGenericRequest(RequestMsg(RequestMsgCodes::Button, index));
  403. }
  404. void ProtocolLogic::Home(uint8_t mode){
  405. PlanGenericRequest(RequestMsg(RequestMsgCodes::Home, mode));
  406. }
  407. void ProtocolLogic::PlanGenericRequest(RequestMsg rq) {
  408. plannedRq = rq;
  409. if( ! currentState->ExpectsResponse() ){
  410. ActivatePlannedRequest();
  411. } // otherwise wait for an empty window to activate the request
  412. }
  413. bool ProtocolLogic::ActivatePlannedRequest(){
  414. if( plannedRq.code == RequestMsgCodes::Button ){
  415. // only issue the button to the MMU and do not restart the state machines
  416. // @@TODO - this is not completely correct, but it does the job.
  417. // In Idle mode the command part is not active, but we still need button handling in Idle mode (resolve MMU init errors)
  418. // -> command.SendButton is not correct, but it sends the message and everything works (for now)
  419. command.SendButton(plannedRq.value);
  420. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  421. return true;
  422. } else if( plannedRq.code != RequestMsgCodes::unknown ){
  423. currentState = &command;
  424. command.SetRequestMsg(plannedRq);
  425. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  426. command.Restart();
  427. return true;
  428. }
  429. return false;
  430. }
  431. void ProtocolLogic::SwitchFromIdleToCommand(){
  432. currentState = &command;
  433. command.SetRequestMsg(rsp.request);
  434. // we are recovering from a communication drop out, the command is already running
  435. // and we have just received a response to a Q0 message about a command progress
  436. command.ContinueFromIdle();
  437. }
  438. void ProtocolLogic::SwitchToIdle() {
  439. state = State::Running;
  440. currentState = &idle;
  441. idle.Restart();
  442. }
  443. bool ProtocolLogic::Elapsed(uint32_t timeout) const {
  444. return _millis() >= (lastUARTActivityMs + timeout);
  445. }
  446. void ProtocolLogic::RecordUARTActivity() {
  447. lastUARTActivityMs = _millis();
  448. }
  449. void ProtocolLogic::RecordReceivedByte(uint8_t c){
  450. lastReceivedBytes[lrb] = c;
  451. lrb = (lrb+1) % lastReceivedBytes.size();
  452. }
  453. constexpr char NibbleToChar(uint8_t c){
  454. switch (c) {
  455. case 0:
  456. case 1:
  457. case 2:
  458. case 3:
  459. case 4:
  460. case 5:
  461. case 6:
  462. case 7:
  463. case 8:
  464. case 9:
  465. return c + '0';
  466. case 10:
  467. case 11:
  468. case 12:
  469. case 13:
  470. case 14:
  471. case 15:
  472. return (c - 10) + 'a';
  473. default:
  474. return 0;
  475. }
  476. }
  477. void ProtocolLogic::FormatLastReceivedBytes(char *dst){
  478. for(uint8_t i = 0; i < lastReceivedBytes.size(); ++i){
  479. uint8_t b = lastReceivedBytes[ (lrb-i-1) % lastReceivedBytes.size() ];
  480. dst[i*3] = NibbleToChar(b >> 4);
  481. dst[i*3+1] = NibbleToChar(b & 0xf);
  482. dst[i*3+2] = ' ';
  483. }
  484. dst[ (lastReceivedBytes.size() - 1) * 3 + 2] = 0; // terminate properly
  485. }
  486. void ProtocolLogic::FormatLastResponseMsgAndClearLRB(char *dst){
  487. *dst++ = '<';
  488. for(uint8_t i = 0; i < lrb; ++i){
  489. uint8_t b = lastReceivedBytes[ i ];
  490. if( b < 32 )b = '.';
  491. if( b > 127 )b = '.';
  492. *dst++ = b;
  493. }
  494. *dst = 0; // terminate properly
  495. lrb = 0; // reset the input buffer index in case of a clean message
  496. }
  497. void ProtocolLogic::LogRequestMsg(const uint8_t *txbuff, uint8_t size){
  498. constexpr uint_fast8_t rqs = modules::protocol::Protocol::MaxRequestSize() + 2;
  499. char tmp[rqs] = ">";
  500. static char lastMsg[rqs] = "";
  501. for(uint8_t i = 0; i < size; ++i){
  502. uint8_t b = txbuff[i];
  503. if( b < 32 )b = '.';
  504. if( b > 127 )b = '.';
  505. tmp[i+1] = b;
  506. }
  507. tmp[size+1] = '\n';
  508. tmp[size+2] = 0;
  509. if( !strncmp(tmp, ">S0.\n", rqs) && !strncmp(lastMsg, tmp, rqs) ){
  510. // @@TODO we skip the repeated request msgs for now
  511. // to avoid spoiling the whole log just with ">S0" messages
  512. // especially when the MMU is not connected.
  513. // We'll lose the ability to see if the printer is actually
  514. // trying to find the MMU, but since it has been reliable in the past
  515. // we can live without it for now.
  516. } else {
  517. MMU2_ECHO_MSG(tmp);
  518. }
  519. memcpy(lastMsg, tmp, rqs);
  520. }
  521. void ProtocolLogic::LogError(const char *reason){
  522. char lrb[lastReceivedBytes.size() * 3];
  523. FormatLastReceivedBytes(lrb);
  524. MMU2_ERROR_MSG(reason);
  525. SERIAL_ECHO(", last bytes: ");
  526. SERIAL_ECHOLN(lrb);
  527. }
  528. void ProtocolLogic::LogResponse(){
  529. char lrb[lastReceivedBytes.size()];
  530. FormatLastResponseMsgAndClearLRB(lrb);
  531. MMU2_ECHO_MSG(lrb);
  532. SERIAL_ECHOLN();
  533. }
  534. StepStatus ProtocolLogic::SuppressShortDropOuts(const char *msg, StepStatus ss) {
  535. if( dataTO.Record(ss) ){
  536. LogError(msg);
  537. return dataTO.InitialCause();
  538. } else {
  539. return Processing; // suppress short drop outs of communication
  540. }
  541. }
  542. StepStatus ProtocolLogic::HandleCommunicationTimeout() {
  543. uart->flush(); // clear the output buffer
  544. protocol.ResetResponseDecoder();
  545. Start();
  546. return SuppressShortDropOuts("Communication timeout", CommunicationTimeout);
  547. }
  548. StepStatus ProtocolLogic::HandleProtocolError() {
  549. uart->flush(); // clear the output buffer
  550. state = State::InitSequence;
  551. currentState = &delayedRestart;
  552. delayedRestart.Restart();
  553. return SuppressShortDropOuts("Protocol Error", ProtocolError);
  554. }
  555. StepStatus ProtocolLogic::Step() {
  556. if( ! currentState->ExpectsResponse() ){ // if not waiting for a response, activate a planned request immediately
  557. ActivatePlannedRequest();
  558. }
  559. auto currentStatus = currentState->Step();
  560. switch (currentStatus) {
  561. case Processing:
  562. // we are ok, the state machine continues correctly
  563. break;
  564. case Finished: {
  565. // We are ok, switching to Idle if there is no potential next request planned.
  566. // But the trouble is we must report a finished command if the previous command has just been finished
  567. // i.e. only try to find some planned command if we just finished the Idle cycle
  568. bool previousCommandFinished = currentState == &command; // @@TODO this is a nasty hack :(
  569. if( ! ActivatePlannedRequest() ){ // if nothing is planned, switch to Idle
  570. SwitchToIdle();
  571. } else {
  572. // if the previous cycle was Idle and now we have planned a new command -> avoid returning Finished
  573. if( ! previousCommandFinished && currentState == &command){
  574. currentStatus = Processing;
  575. }
  576. }
  577. } break;
  578. case CommandRejected:
  579. // we have to repeat it - that's the only thing we can do
  580. // no change in state
  581. // @@TODO wait until Q0 returns command in progress finished, then we can send this one
  582. LogError("Command rejected");
  583. command.Restart();
  584. break;
  585. case CommandError:
  586. LogError("Command Error");
  587. // we shall probably transfer into the Idle state and await further instructions from the upper layer
  588. // Idle state may solve the problem of keeping up the heart beat running
  589. break;
  590. case VersionMismatch:
  591. LogError("Version mismatch");
  592. Stop(); // cannot continue
  593. break;
  594. case ProtocolError:
  595. currentStatus = HandleProtocolError();
  596. break;
  597. case CommunicationTimeout:
  598. currentStatus = HandleCommunicationTimeout();
  599. break;
  600. default:
  601. break;
  602. }
  603. return currentStatus;
  604. }
  605. uint8_t ProtocolLogic::CommandInProgress() const {
  606. if( currentState != &command )
  607. return 0;
  608. return (uint8_t)command.ReqMsg().code;
  609. }
  610. bool DropOutFilter::Record(StepStatus ss){
  611. if( occurrences == maxOccurrences ){
  612. cause = ss;
  613. }
  614. --occurrences;
  615. return occurrences == 0;
  616. }
  617. } // namespace MMU2