mmu2_protocol_logic.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #pragma once
  2. #include <stdint.h>
  3. #include <avr/pgmspace.h>
  4. // #include <array> //@@TODO Don't we have STL for AVR somewhere?
  5. template<typename T, uint8_t N>
  6. class array {
  7. T data[N];
  8. public:
  9. array() = default;
  10. inline constexpr T* begin()const { return data; }
  11. inline constexpr T* end()const { return data + N; }
  12. constexpr uint8_t size()const { return N; }
  13. inline T &operator[](uint8_t i){
  14. return data[i];
  15. }
  16. };
  17. #include "mmu2/error_codes.h"
  18. #include "mmu2/progress_codes.h"
  19. #include "mmu2/buttons.h"
  20. #include "mmu2_protocol.h"
  21. #include "mmu2_serial.h"
  22. /// New MMU2 protocol logic
  23. namespace MMU2 {
  24. using namespace modules::protocol;
  25. class ProtocolLogic;
  26. /// ProtocolLogic stepping statuses
  27. enum StepStatus : uint_fast8_t {
  28. Processing = 0,
  29. MessageReady, ///< a message has been successfully decoded from the received bytes
  30. Finished,
  31. CommunicationTimeout, ///< the MMU failed to respond to a request within a specified time frame
  32. ProtocolError, ///< bytes read from the MMU didn't form a valid response
  33. CommandRejected, ///< the MMU rejected the command due to some other command in progress, may be the user is operating the MMU locally (button commands)
  34. CommandError, ///< the command in progress stopped due to unrecoverable error, user interaction required
  35. VersionMismatch, ///< the MMU reports its firmware version incompatible with our implementation
  36. CommunicationRecovered,
  37. ButtonPushed, ///< The MMU reported the user pushed one of its three buttons.
  38. };
  39. static constexpr uint32_t linkLayerTimeout = 2000; ///< default link layer communication timeout
  40. static constexpr uint32_t dataLayerTimeout = linkLayerTimeout * 3; ///< data layer communication timeout
  41. static constexpr uint32_t heartBeatPeriod = linkLayerTimeout / 2; ///< period of heart beat messages (Q0)
  42. static_assert(heartBeatPeriod < linkLayerTimeout && linkLayerTimeout < dataLayerTimeout, "Incorrect ordering of timeouts");
  43. ///< Filter of short consecutive drop outs which are recovered instantly
  44. class DropOutFilter {
  45. StepStatus cause;
  46. uint8_t occurrences;
  47. public:
  48. static constexpr uint8_t maxOccurrences = 10; // ideally set this to >8 seconds -> 12x heartBeatPeriod
  49. static_assert(maxOccurrences > 1, "we should really silently ignore at least 1 comm drop out if recovered immediately afterwards");
  50. DropOutFilter() = default;
  51. /// @returns true if the error should be reported to higher levels (max. number of consecutive occurrences reached)
  52. bool Record(StepStatus ss);
  53. /// @returns the initial cause which started this drop out event
  54. inline StepStatus InitialCause() const { return cause; }
  55. /// Rearms the object for further processing - basically call this once the MMU responds with something meaningful (e.g. S0 A2)
  56. inline void Reset() { occurrences = maxOccurrences; }
  57. };
  58. /// Logic layer of the MMU vs. printer communication protocol
  59. class ProtocolLogic {
  60. public:
  61. ProtocolLogic(MMU2Serial *uart);
  62. /// Start/Enable communication with the MMU
  63. void Start();
  64. /// Stop/Disable communication with the MMU
  65. void Stop();
  66. // Issue commands to the MMU
  67. void ToolChange(uint8_t slot);
  68. void Statistics();
  69. void UnloadFilament();
  70. void LoadFilament(uint8_t slot);
  71. void EjectFilament(uint8_t slot);
  72. void CutFilament(uint8_t slot);
  73. void ResetMMU();
  74. void Button(uint8_t index);
  75. void Home(uint8_t mode);
  76. void ReadRegister(uint8_t address);
  77. void WriteRegister(uint8_t address, uint16_t data);
  78. /// Step the state machine
  79. StepStatus Step();
  80. /// @returns the current/latest error code as reported by the MMU
  81. ErrorCode Error() const { return errorCode; }
  82. /// @returns the current/latest process code as reported by the MMU
  83. ProgressCode Progress() const { return progressCode; }
  84. /// @returns the current/latest button code as reported by the MMU
  85. Buttons Button() const { return buttonCode; }
  86. uint8_t CommandInProgress() const;
  87. inline bool Running() const {
  88. return state == State::Running;
  89. }
  90. inline bool FindaPressed() const {
  91. return regs8[0];
  92. }
  93. inline uint16_t FailStatistics() const {
  94. return regs16[0];
  95. }
  96. inline uint8_t MmuFwVersionMajor() const {
  97. return mmuFwVersion[0];
  98. }
  99. inline uint8_t MmuFwVersionMinor() const {
  100. return mmuFwVersion[1];
  101. }
  102. inline uint8_t MmuFwVersionRevision() const {
  103. return mmuFwVersion[2];
  104. }
  105. #ifndef UNITTEST
  106. private:
  107. #endif
  108. StepStatus ExpectingMessage();
  109. void SendMsg(RequestMsg rq);
  110. void SendWriteMsg(RequestMsg rq);
  111. void SwitchToIdle();
  112. StepStatus SuppressShortDropOuts(const char *msg_P, StepStatus ss);
  113. StepStatus HandleCommunicationTimeout();
  114. StepStatus HandleProtocolError();
  115. bool Elapsed(uint32_t timeout) const;
  116. void RecordUARTActivity();
  117. void RecordReceivedByte(uint8_t c);
  118. void FormatLastReceivedBytes(char *dst);
  119. void FormatLastResponseMsgAndClearLRB(char *dst);
  120. void LogRequestMsg(const uint8_t *txbuff, uint8_t size);
  121. void LogError(const char *reason_P);
  122. void LogResponse();
  123. StepStatus SwitchFromIdleToCommand();
  124. void SwitchFromStartToIdle();
  125. enum class State : uint_fast8_t {
  126. Stopped, ///< stopped for whatever reason
  127. InitSequence, ///< initial sequence running
  128. Running ///< normal operation - Idle + Command processing
  129. };
  130. // individual sub-state machines - may be they can be combined into a union since only one is active at once
  131. // or we can blend them into ProtocolLogic at the cost of a less nice code (but hopefully shorter)
  132. // Stopped stopped;
  133. // StartSeq startSeq;
  134. // DelayedRestart delayedRestart;
  135. // Idle idle;
  136. // Command command;
  137. // ProtocolLogicPartBase *currentState; ///< command currently being processed
  138. enum class Scope : uint_fast8_t {
  139. Stopped,
  140. StartSeq,
  141. DelayedRestart,
  142. Idle,
  143. Command
  144. };
  145. Scope currentScope;
  146. // basic scope members
  147. /// @returns true if the state machine is waiting for a response from the MMU
  148. bool ExpectsResponse() const { return ((uint8_t)scopeState & (uint8_t)ScopeState::NotExpectsResponse) == 0; }
  149. /// Common internal states of the derived sub-automata
  150. /// General rule of thumb: *Sent states are waiting for a response from the MMU
  151. enum class ScopeState : uint_fast8_t {
  152. S0Sent, // beware - due to optimization reasons these SxSent must be kept one after another
  153. S1Sent,
  154. S2Sent,
  155. S3Sent,
  156. QuerySent,
  157. CommandSent,
  158. FilamentSensorStateSent,
  159. Reading8bitRegisters,
  160. Reading16bitRegisters,
  161. ButtonSent,
  162. ReadRegisterSent, // standalone requests for reading registers - from higher layers
  163. WriteRegisterSent,
  164. // States which do not expect a message - MSb set
  165. NotExpectsResponse = 0x80,
  166. Wait = NotExpectsResponse + 1,
  167. Ready = NotExpectsResponse + 2,
  168. RecoveringProtocolError = NotExpectsResponse + 3,
  169. };
  170. ScopeState scopeState; ///< internal state of the sub-automaton
  171. /// @returns the status of processing of the FINDA query response
  172. /// @param finishedRV returned value in case the message was successfully received and processed
  173. /// @param nextState is a state where the state machine should transfer to after the message was successfully received and processed
  174. // StepStatus ProcessFINDAReqSent(StepStatus finishedRV, State nextState);
  175. /// @returns the status of processing of the statistics query response
  176. /// @param finishedRV returned value in case the message was successfully received and processed
  177. /// @param nextState is a state where the state machine should transfer to after the message was successfully received and processed
  178. // StepStatus ProcessStatisticsReqSent(StepStatus finishedRV, State nextState);
  179. /// Called repeatedly while waiting for a query (Q0) period.
  180. /// All event checks to report immediately from the printer to the MMU shall be done in this method.
  181. /// So far, the only such a case is the filament sensor, but there can be more like this in the future.
  182. void CheckAndReportAsyncEvents();
  183. void SendQuery();
  184. void StartReading8bitRegisters();
  185. void ProcessRead8bitRegister();
  186. void StartReading16bitRegisters();
  187. ScopeState ProcessRead16bitRegister(ProtocolLogic::ScopeState stateAtEnd);
  188. void SendAndUpdateFilamentSensor();
  189. void SendButton(uint8_t btn);
  190. void SendVersion(uint8_t stage);
  191. void SendReadRegister(uint8_t index, ScopeState nextState);
  192. void SendWriteRegister(uint8_t index, uint16_t value, ScopeState nextState);
  193. StepStatus ProcessVersionResponse(uint8_t stage);
  194. /// Top level split - calls the appropriate step based on current scope
  195. StepStatus ScopeStep();
  196. static constexpr uint8_t maxRetries = 6;
  197. uint8_t retries;
  198. void StartSeqRestart();
  199. void DelayedRestartRestart();
  200. void IdleRestart();
  201. void CommandRestart();
  202. StepStatus StartSeqStep();
  203. StepStatus DelayedRestartWait();
  204. StepStatus IdleStep();
  205. StepStatus IdleWait();
  206. StepStatus CommandStep();
  207. StepStatus CommandWait();
  208. StepStatus StoppedStep() { return Processing; }
  209. StepStatus ProcessCommandQueryResponse();
  210. inline void SetRequestMsg(RequestMsg msg) {
  211. rq = msg;
  212. }
  213. inline const RequestMsg &ReqMsg() const { return rq; }
  214. RequestMsg rq = RequestMsg(RequestMsgCodes::unknown, 0);
  215. /// Records the next planned state, "unknown" msg code if no command is planned.
  216. /// This is not intended to be a queue of commands to process, protocol_logic must not queue commands.
  217. /// It exists solely to prevent breaking the Request-Response protocol handshake -
  218. /// - during tests it turned out, that the commands from Marlin are coming in such an asynchronnous way, that
  219. /// we could accidentally send T2 immediately after Q0 without waiting for reception of response to Q0.
  220. ///
  221. /// Beware, if Marlin manages to call PlanGenericCommand multiple times before a response comes,
  222. /// these variables will get overwritten by the last call.
  223. /// However, that should not happen under normal circumstances as Marlin should wait for the Command to finish,
  224. /// which includes all responses (and error recovery if any).
  225. RequestMsg plannedRq;
  226. /// Plan a command to be processed once the immediate response to a sent request arrives
  227. void PlanGenericRequest(RequestMsg rq);
  228. /// Activate the planned state once the immediate response to a sent request arrived
  229. bool ActivatePlannedRequest();
  230. uint32_t lastUARTActivityMs; ///< timestamp - last ms when something occurred on the UART
  231. DropOutFilter dataTO; ///< Filter of short consecutive drop outs which are recovered instantly
  232. ResponseMsg rsp; ///< decoded response message from the MMU protocol
  233. State state; ///< internal state of ProtocolLogic
  234. Protocol protocol; ///< protocol codec
  235. array<uint8_t, 16> lastReceivedBytes; ///< remembers the last few bytes of incoming communication for diagnostic purposes
  236. uint8_t lrb;
  237. MMU2Serial *uart; ///< UART interface
  238. ErrorCode errorCode; ///< last received error code from the MMU
  239. ProgressCode progressCode; ///< last received progress code from the MMU
  240. Buttons buttonCode; ///< Last received button from the MMU.
  241. uint8_t lastFSensor; ///< last state of filament sensor
  242. // 8bit registers
  243. static constexpr uint8_t regs8Count = 3;
  244. static_assert(regs8Count > 0); // code is not ready for empty lists of registers
  245. static const uint8_t regs8Addrs[regs8Count] PROGMEM;
  246. uint8_t regs8[regs8Count];
  247. // 16bit registers
  248. static constexpr uint8_t regs16Count = 2;
  249. static_assert(regs16Count > 0); // code is not ready for empty lists of registers
  250. static const uint8_t regs16Addrs[regs16Count] PROGMEM;
  251. uint16_t regs16[regs16Count];
  252. uint8_t regIndex;
  253. uint8_t mmuFwVersion[3];
  254. uint16_t mmuFwVersionBuild;
  255. friend class ProtocolLogicPartBase;
  256. friend class Stopped;
  257. friend class Command;
  258. friend class Idle;
  259. friend class StartSeq;
  260. friend class DelayedRestart;
  261. friend class MMU2;
  262. };
  263. } // namespace MMU2