mmu2_protocol_logic.cpp 28 KB

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