mmu2_protocol_logic.cpp 28 KB

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