mmu2_protocol_logic.h 11 KB

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