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::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. default:
  265. return VersionMismatch;
  266. }
  267. }
  268. StepStatus ProtocolLogic::DelayedRestartWait() {
  269. if (Elapsed(heartBeatPeriod)) { // this basically means, that we are waiting until there is some traffic on
  270. while (uart->read() != -1)
  271. ; // clear the input buffer
  272. // switch to StartSeq
  273. Start();
  274. }
  275. return Processing;
  276. }
  277. StepStatus ProtocolLogic::CommandWait() {
  278. if (Elapsed(heartBeatPeriod)) {
  279. SendQuery();
  280. } else {
  281. // even when waiting for a query period, we need to report a change in filament sensor's state
  282. // - it is vital for a precise synchronization of moves of the printer and the MMU
  283. CheckAndReportAsyncEvents();
  284. }
  285. return Processing;
  286. }
  287. StepStatus ProtocolLogic::ProcessCommandQueryResponse() {
  288. switch (rsp.paramCode) {
  289. case ResponseMsgParamCodes::Processing:
  290. progressCode = static_cast<ProgressCode>(rsp.paramValue);
  291. errorCode = ErrorCode::OK;
  292. SendAndUpdateFilamentSensor(); // keep on reporting the state of fsensor regularly
  293. return Processing;
  294. case ResponseMsgParamCodes::Error:
  295. // in case of an error the progress code remains as it has been before
  296. errorCode = static_cast<ErrorCode>(rsp.paramValue);
  297. // keep on reporting the state of fsensor regularly even in command error state
  298. // - the MMU checks FINDA and fsensor even while recovering from errors
  299. SendAndUpdateFilamentSensor();
  300. return CommandError;
  301. case ResponseMsgParamCodes::Button:
  302. // The user pushed a button on the MMU. Save it, do what we need to do
  303. // to prepare, then pass it back to the MMU so it can work its magic.
  304. buttonCode = static_cast<Buttons>(rsp.paramValue);
  305. SendAndUpdateFilamentSensor();
  306. return ButtonPushed;
  307. case ResponseMsgParamCodes::Finished:
  308. // We must check whether the "finished" is actually related to the command issued into the MMU
  309. // It can also be an X0 F which means MMU just successfully restarted.
  310. if( ReqMsg().code == rsp.request.code && ReqMsg().value == rsp.request.value ){
  311. progressCode = ProgressCode::OK;
  312. scopeState = ScopeState::Ready;
  313. return Finished;
  314. } else {
  315. // got response to some other command - the originally issued command was interrupted!
  316. return Interrupted;
  317. }
  318. default:
  319. return ProtocolError;
  320. }
  321. }
  322. StepStatus ProtocolLogic::CommandStep() {
  323. switch (scopeState) {
  324. case ScopeState::CommandSent: {
  325. switch (rsp.paramCode) { // the response should be either accepted or rejected
  326. case ResponseMsgParamCodes::Accepted:
  327. progressCode = ProgressCode::OK;
  328. errorCode = ErrorCode::RUNNING;
  329. scopeState = ScopeState::Wait;
  330. break;
  331. case ResponseMsgParamCodes::Rejected:
  332. // rejected - should normally not happen, but report the error up
  333. progressCode = ProgressCode::OK;
  334. errorCode = ErrorCode::PROTOCOL_ERROR;
  335. return CommandRejected;
  336. default:
  337. return ProtocolError;
  338. }
  339. } break;
  340. case ScopeState::QuerySent:
  341. return ProcessCommandQueryResponse();
  342. case ScopeState::FilamentSensorStateSent:
  343. StartReading8bitRegisters();
  344. return Processing;
  345. case ScopeState::Reading8bitRegisters:
  346. ProcessRead8bitRegister();
  347. return Processing;
  348. case ScopeState::Reading16bitRegisters:
  349. scopeState = ProcessRead16bitRegister(ScopeState::Wait);
  350. return Processing;
  351. case ScopeState::ButtonSent:
  352. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  353. // Button was accepted, decrement the retry.
  354. mmu2.DecrementRetryAttempts();
  355. }
  356. SendAndUpdateFilamentSensor();
  357. break;
  358. default:
  359. return ProtocolError;
  360. }
  361. return Processing;
  362. }
  363. StepStatus ProtocolLogic::IdleWait() {
  364. if (scopeState == ScopeState::Ready) { // check timeout
  365. if (Elapsed(heartBeatPeriod)) {
  366. SendQuery();
  367. return Processing;
  368. }
  369. }
  370. return Finished;
  371. }
  372. StepStatus ProtocolLogic::IdleStep() {
  373. switch (scopeState) {
  374. case ScopeState::QuerySent: // check UART
  375. // 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.
  376. // That causes no issues here, we just need to switch to Command processing and continue there from now on.
  377. // 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.
  378. switch (rsp.request.code) {
  379. case RequestMsgCodes::Cut:
  380. case RequestMsgCodes::Eject:
  381. case RequestMsgCodes::Load:
  382. case RequestMsgCodes::Mode:
  383. case RequestMsgCodes::Tool:
  384. case RequestMsgCodes::Unload:
  385. if (rsp.paramCode != ResponseMsgParamCodes::Finished) {
  386. return SwitchFromIdleToCommand();
  387. }
  388. break;
  389. case RequestMsgCodes::Reset:
  390. // this one is kind of special
  391. // we do not transfer to any "running" command (i.e. we stay in Idle),
  392. // but in case there is an error reported we must make sure it gets propagated
  393. switch (rsp.paramCode) {
  394. case ResponseMsgParamCodes::Button:
  395. // The user pushed a button on the MMU. Save it, do what we need to do
  396. // to prepare, then pass it back to the MMU so it can work its magic.
  397. buttonCode = static_cast<Buttons>(rsp.paramValue);
  398. StartReading8bitRegisters();
  399. return ButtonPushed;
  400. case ResponseMsgParamCodes::Processing:
  401. // @@TODO we may actually use this branch to report progress of manual operation on the MMU
  402. // The MMU sends e.g. X0 P27 after its restart when the user presses an MMU button to move the Selector
  403. // For now let's behave just like "finished"
  404. case ResponseMsgParamCodes::Finished:
  405. errorCode = ErrorCode::OK;
  406. break;
  407. default:
  408. errorCode = static_cast<ErrorCode>(rsp.paramValue);
  409. StartReading8bitRegisters(); // continue Idle state without restarting the communication
  410. return CommandError;
  411. }
  412. break;
  413. default:
  414. return ProtocolError;
  415. }
  416. StartReading8bitRegisters();
  417. return Processing;
  418. case ScopeState::Reading8bitRegisters:
  419. ProcessRead8bitRegister();
  420. return Processing;
  421. case ScopeState::Reading16bitRegisters:
  422. scopeState = ProcessRead16bitRegister(ScopeState::Ready);
  423. return scopeState == ScopeState::Ready ? Finished : Processing;
  424. case ScopeState::ButtonSent:
  425. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  426. // Button was accepted, decrement the retry.
  427. mmu2.DecrementRetryAttempts();
  428. }
  429. StartReading8bitRegisters();
  430. return Processing;
  431. case ScopeState::ReadRegisterSent:
  432. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  433. // @@TODO just dump the value onto the serial
  434. }
  435. return Finished;
  436. case ScopeState::WriteRegisterSent:
  437. if (rsp.paramCode == ResponseMsgParamCodes::Accepted) {
  438. // @@TODO do something? Retry if not accepted?
  439. }
  440. return Finished;
  441. default:
  442. return ProtocolError;
  443. }
  444. // The "return Finished" in this state machine requires a bit of explanation:
  445. // The Idle state either did nothing (still waiting for the heartbeat timeout)
  446. // or just successfully received the answer to Q0, whatever that was.
  447. // In both cases, it is ready to hand over work to a command or something else,
  448. // therefore we are returning Finished (also to exit mmu_loop() and unblock Marlin's loop!).
  449. // If there is no work, we'll end up in the Idle state again
  450. // and we'll send the heartbeat message after the specified timeout.
  451. return Finished;
  452. }
  453. ProtocolLogic::ProtocolLogic(MMU2Serial *uart, uint8_t extraLoadDistance)
  454. : currentScope(Scope::Stopped)
  455. , scopeState(ScopeState::Ready)
  456. , plannedRq(RequestMsgCodes::unknown, 0)
  457. , lastUARTActivityMs(0)
  458. , dataTO()
  459. , rsp(RequestMsg(RequestMsgCodes::unknown, 0), ResponseMsgParamCodes::unknown, 0)
  460. , state(State::Stopped)
  461. , lrb(0)
  462. , uart(uart)
  463. , errorCode(ErrorCode::OK)
  464. , progressCode(ProgressCode::OK)
  465. , buttonCode(NoButton)
  466. , lastFSensor((uint8_t)WhereIsFilament())
  467. , regs8 { 0, 0, 0 }
  468. , regs16 { 0, 0 }
  469. , initRegs8 { extraLoadDistance }
  470. , regIndex(0)
  471. , mmuFwVersion { 0, 0, 0 }
  472. {}
  473. void ProtocolLogic::Start() {
  474. state = State::InitSequence;
  475. currentScope = Scope::StartSeq;
  476. protocol.ResetResponseDecoder(); // important - finished delayed restart relies on this
  477. StartSeqRestart();
  478. }
  479. void ProtocolLogic::Stop() {
  480. state = State::Stopped;
  481. currentScope = Scope::Stopped;
  482. }
  483. void ProtocolLogic::ToolChange(uint8_t slot) {
  484. PlanGenericRequest(RequestMsg(RequestMsgCodes::Tool, slot));
  485. }
  486. void ProtocolLogic::Statistics() {
  487. PlanGenericRequest(RequestMsg(RequestMsgCodes::Version, 3));
  488. }
  489. void ProtocolLogic::UnloadFilament() {
  490. PlanGenericRequest(RequestMsg(RequestMsgCodes::Unload, 0));
  491. }
  492. void ProtocolLogic::LoadFilament(uint8_t slot) {
  493. PlanGenericRequest(RequestMsg(RequestMsgCodes::Load, slot));
  494. }
  495. void ProtocolLogic::EjectFilament(uint8_t slot) {
  496. PlanGenericRequest(RequestMsg(RequestMsgCodes::Eject, slot));
  497. }
  498. void ProtocolLogic::CutFilament(uint8_t slot) {
  499. PlanGenericRequest(RequestMsg(RequestMsgCodes::Cut, slot));
  500. }
  501. void ProtocolLogic::ResetMMU() {
  502. PlanGenericRequest(RequestMsg(RequestMsgCodes::Reset, 0));
  503. }
  504. void ProtocolLogic::Button(uint8_t index) {
  505. PlanGenericRequest(RequestMsg(RequestMsgCodes::Button, index));
  506. }
  507. void ProtocolLogic::Home(uint8_t mode) {
  508. PlanGenericRequest(RequestMsg(RequestMsgCodes::Home, mode));
  509. }
  510. void ProtocolLogic::ReadRegister(uint8_t address){
  511. PlanGenericRequest(RequestMsg(RequestMsgCodes::Read, address));
  512. }
  513. void ProtocolLogic::WriteRegister(uint8_t address, uint16_t data){
  514. PlanGenericRequest(RequestMsg(RequestMsgCodes::Write, address, data));
  515. }
  516. void ProtocolLogic::PlanGenericRequest(RequestMsg rq) {
  517. plannedRq = rq;
  518. if (!ExpectsResponse()) {
  519. ActivatePlannedRequest();
  520. } // otherwise wait for an empty window to activate the request
  521. }
  522. bool ProtocolLogic::ActivatePlannedRequest() {
  523. switch(plannedRq.code){
  524. case RequestMsgCodes::Button:
  525. // only issue the button to the MMU and do not restart the state machines
  526. SendButton(plannedRq.value);
  527. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  528. return true;
  529. case RequestMsgCodes::Read:
  530. SendReadRegister(plannedRq.value, ScopeState::ReadRegisterSent );
  531. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  532. return true;
  533. case RequestMsgCodes::Write:
  534. SendWriteRegister(plannedRq.value, plannedRq.value2, ScopeState::WriteRegisterSent );
  535. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  536. return true;
  537. case RequestMsgCodes::unknown:
  538. return false;
  539. default:// commands
  540. currentScope = Scope::Command;
  541. SetRequestMsg(plannedRq);
  542. plannedRq = RequestMsg(RequestMsgCodes::unknown, 0);
  543. CommandRestart();
  544. return true;
  545. }
  546. }
  547. StepStatus ProtocolLogic::SwitchFromIdleToCommand() {
  548. currentScope = Scope::Command;
  549. SetRequestMsg(rsp.request);
  550. // we are recovering from a communication drop out, the command is already running
  551. // and we have just received a response to a Q0 message about a command progress
  552. return ProcessCommandQueryResponse();
  553. }
  554. void ProtocolLogic::SwitchToIdle() {
  555. state = State::Running;
  556. currentScope = Scope::Idle;
  557. IdleRestart();
  558. }
  559. void ProtocolLogic::SwitchFromStartToIdle() {
  560. state = State::Running;
  561. currentScope = Scope::Idle;
  562. IdleRestart();
  563. SendQuery(); // force sending Q0 immediately
  564. }
  565. bool ProtocolLogic::Elapsed(uint32_t timeout) const {
  566. return _millis() >= (lastUARTActivityMs + timeout);
  567. }
  568. void ProtocolLogic::RecordUARTActivity() {
  569. lastUARTActivityMs = _millis();
  570. }
  571. void ProtocolLogic::RecordReceivedByte(uint8_t c) {
  572. lastReceivedBytes[lrb] = c;
  573. lrb = (lrb + 1) % lastReceivedBytes.size();
  574. }
  575. constexpr char NibbleToChar(uint8_t c) {
  576. switch (c) {
  577. case 0:
  578. case 1:
  579. case 2:
  580. case 3:
  581. case 4:
  582. case 5:
  583. case 6:
  584. case 7:
  585. case 8:
  586. case 9:
  587. return c + '0';
  588. case 10:
  589. case 11:
  590. case 12:
  591. case 13:
  592. case 14:
  593. case 15:
  594. return (c - 10) + 'a';
  595. default:
  596. return 0;
  597. }
  598. }
  599. void ProtocolLogic::FormatLastReceivedBytes(char *dst) {
  600. for (uint8_t i = 0; i < lastReceivedBytes.size(); ++i) {
  601. uint8_t b = lastReceivedBytes[(lrb - i - 1) % lastReceivedBytes.size()];
  602. dst[i * 3] = NibbleToChar(b >> 4);
  603. dst[i * 3 + 1] = NibbleToChar(b & 0xf);
  604. dst[i * 3 + 2] = ' ';
  605. }
  606. dst[(lastReceivedBytes.size() - 1) * 3 + 2] = 0; // terminate properly
  607. }
  608. void ProtocolLogic::FormatLastResponseMsgAndClearLRB(char *dst) {
  609. *dst++ = '<';
  610. for (uint8_t i = 0; i < lrb; ++i) {
  611. uint8_t b = lastReceivedBytes[i];
  612. if (b < 32)
  613. b = '.';
  614. if (b > 127)
  615. b = '.';
  616. *dst++ = b;
  617. }
  618. *dst = 0; // terminate properly
  619. lrb = 0; // reset the input buffer index in case of a clean message
  620. }
  621. void ProtocolLogic::LogRequestMsg(const uint8_t *txbuff, uint8_t size) {
  622. constexpr uint_fast8_t rqs = modules::protocol::Protocol::MaxRequestSize() + 2;
  623. char tmp[rqs] = ">";
  624. static char lastMsg[rqs] = "";
  625. for (uint8_t i = 0; i < size; ++i) {
  626. uint8_t b = txbuff[i];
  627. if (b < 32)
  628. b = '.';
  629. if (b > 127)
  630. b = '.';
  631. tmp[i + 1] = b;
  632. }
  633. tmp[size + 1] = '\n';
  634. tmp[size + 2] = 0;
  635. if (!strncmp_P(tmp, PSTR(">S0*99.\n"), rqs) && !strncmp(lastMsg, tmp, rqs)) {
  636. // @@TODO we skip the repeated request msgs for now
  637. // to avoid spoiling the whole log just with ">S0" messages
  638. // especially when the MMU is not connected.
  639. // We'll lose the ability to see if the printer is actually
  640. // trying to find the MMU, but since it has been reliable in the past
  641. // we can live without it for now.
  642. } else {
  643. MMU2_ECHO_MSG(tmp);
  644. }
  645. memcpy(lastMsg, tmp, rqs);
  646. }
  647. void ProtocolLogic::LogError(const char *reason_P) {
  648. char lrb[lastReceivedBytes.size() * 3];
  649. FormatLastReceivedBytes(lrb);
  650. MMU2_ERROR_MSGRPGM(reason_P);
  651. SERIAL_ECHOPGM(", last bytes: ");
  652. SERIAL_ECHOLN(lrb);
  653. }
  654. void ProtocolLogic::LogResponse() {
  655. char lrb[lastReceivedBytes.size()];
  656. FormatLastResponseMsgAndClearLRB(lrb);
  657. MMU2_ECHO_MSG(lrb);
  658. SERIAL_ECHOLN();
  659. }
  660. StepStatus ProtocolLogic::SuppressShortDropOuts(const char *msg_P, StepStatus ss) {
  661. if (dataTO.Record(ss)) {
  662. LogError(msg_P);
  663. return dataTO.InitialCause();
  664. } else {
  665. return Processing; // suppress short drop outs of communication
  666. }
  667. }
  668. StepStatus ProtocolLogic::HandleCommunicationTimeout() {
  669. uart->flush(); // clear the output buffer
  670. protocol.ResetResponseDecoder();
  671. Start();
  672. return SuppressShortDropOuts(PSTR("Communication timeout"), CommunicationTimeout);
  673. }
  674. StepStatus ProtocolLogic::HandleProtocolError() {
  675. uart->flush(); // clear the output buffer
  676. state = State::InitSequence;
  677. currentScope = Scope::DelayedRestart;
  678. DelayedRestartRestart();
  679. return SuppressShortDropOuts(PSTR("Protocol Error"), ProtocolError);
  680. }
  681. StepStatus ProtocolLogic::Step() {
  682. if (!ExpectsResponse()) { // if not waiting for a response, activate a planned request immediately
  683. ActivatePlannedRequest();
  684. }
  685. auto currentStatus = ScopeStep();
  686. switch (currentStatus) {
  687. case Processing:
  688. // we are ok, the state machine continues correctly
  689. break;
  690. case Finished: {
  691. // We are ok, switching to Idle if there is no potential next request planned.
  692. // But the trouble is we must report a finished command if the previous command has just been finished
  693. // i.e. only try to find some planned command if we just finished the Idle cycle
  694. bool previousCommandFinished = currentScope == Scope::Command; // @@TODO this is a nasty hack :(
  695. if (!ActivatePlannedRequest()) { // if nothing is planned, switch to Idle
  696. SwitchToIdle();
  697. } else {
  698. // if the previous cycle was Idle and now we have planned a new command -> avoid returning Finished
  699. if (!previousCommandFinished && currentScope == Scope::Command) {
  700. currentStatus = Processing;
  701. }
  702. }
  703. } break;
  704. case CommandRejected:
  705. // we have to repeat it - that's the only thing we can do
  706. // no change in state
  707. // @@TODO wait until Q0 returns command in progress finished, then we can send this one
  708. LogError(PSTR("Command rejected"));
  709. CommandRestart();
  710. break;
  711. case CommandError:
  712. LogError(PSTR("Command Error"));
  713. // we shall probably transfer into the Idle state and await further instructions from the upper layer
  714. // Idle state may solve the problem of keeping up the heart beat running
  715. break;
  716. case VersionMismatch:
  717. LogError(PSTR("Version mismatch"));
  718. Stop(); // cannot continue
  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