mmu2_protocol_logic.cpp 18 KB

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