mmu2_protocol_logic.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. /// Step the state machine
  76. StepStatus Step();
  77. /// @returns the current/latest error code as reported by the MMU
  78. ErrorCode Error() const { return errorCode; }
  79. /// @returns the current/latest process code as reported by the MMU
  80. ProgressCode Progress() const { return progressCode; }
  81. /// @returns the current/latest button code as reported by the MMU
  82. Buttons Button() const { return buttonCode; }
  83. uint8_t CommandInProgress() const;
  84. inline bool Running() const {
  85. return state == State::Running;
  86. }
  87. inline bool FindaPressed() const {
  88. return findaPressed;
  89. }
  90. inline uint16_t FailStatistics() const {
  91. return failStatistics;
  92. }
  93. inline uint8_t MmuFwVersionMajor() const {
  94. return mmuFwVersion[0];
  95. }
  96. inline uint8_t MmuFwVersionMinor() const {
  97. return mmuFwVersion[1];
  98. }
  99. inline uint8_t MmuFwVersionRevision() const {
  100. return mmuFwVersion[2];
  101. }
  102. #ifndef UNITTEST
  103. private:
  104. #endif
  105. StepStatus ExpectingMessage();
  106. void SendMsg(RequestMsg rq);
  107. void SwitchToIdle();
  108. StepStatus SuppressShortDropOuts(const char *msg_P, StepStatus ss);
  109. StepStatus HandleCommunicationTimeout();
  110. StepStatus HandleProtocolError();
  111. bool Elapsed(uint32_t timeout) const;
  112. void RecordUARTActivity();
  113. void RecordReceivedByte(uint8_t c);
  114. void FormatLastReceivedBytes(char *dst);
  115. void FormatLastResponseMsgAndClearLRB(char *dst);
  116. void LogRequestMsg(const uint8_t *txbuff, uint8_t size);
  117. void LogError(const char *reason_P);
  118. void LogResponse();
  119. StepStatus SwitchFromIdleToCommand();
  120. void SwitchFromStartToIdle();
  121. enum class State : uint_fast8_t {
  122. Stopped, ///< stopped for whatever reason
  123. InitSequence, ///< initial sequence running
  124. Running ///< normal operation - Idle + Command processing
  125. };
  126. // individual sub-state machines - may be they can be combined into a union since only one is active at once
  127. // or we can blend them into ProtocolLogic at the cost of a less nice code (but hopefully shorter)
  128. // Stopped stopped;
  129. // StartSeq startSeq;
  130. // DelayedRestart delayedRestart;
  131. // Idle idle;
  132. // Command command;
  133. // ProtocolLogicPartBase *currentState; ///< command currently being processed
  134. enum class Scope : uint_fast8_t {
  135. Stopped,
  136. StartSeq,
  137. DelayedRestart,
  138. Idle,
  139. Command
  140. };
  141. Scope currentScope;
  142. // basic scope members
  143. /// @returns true if the state machine is waiting for a response from the MMU
  144. bool ExpectsResponse() const { return ((uint8_t)scopeState & (uint8_t)ScopeState::NotExpectsResponse) == 0; }
  145. /// Common internal states of the derived sub-automata
  146. /// General rule of thumb: *Sent states are waiting for a response from the MMU
  147. enum class ScopeState : uint_fast8_t {
  148. S0Sent, // beware - due to optimization reasons these SxSent must be kept one after another
  149. S1Sent,
  150. S2Sent,
  151. S3Sent,
  152. QuerySent,
  153. CommandSent,
  154. FilamentSensorStateSent,
  155. FINDAReqSent,
  156. StatisticsSent,
  157. ButtonSent,
  158. // States which do not expect a message - MSb set
  159. NotExpectsResponse = 0x80,
  160. Wait = NotExpectsResponse + 1,
  161. Ready = NotExpectsResponse + 2,
  162. RecoveringProtocolError = NotExpectsResponse + 3,
  163. };
  164. ScopeState scopeState; ///< internal state of the sub-automaton
  165. /// @returns the status of processing of the FINDA query response
  166. /// @param finishedRV returned value in case the message was successfully received and processed
  167. /// @param nextState is a state where the state machine should transfer to after the message was successfully received and processed
  168. // StepStatus ProcessFINDAReqSent(StepStatus finishedRV, State nextState);
  169. /// @returns the status of processing of the statistics query response
  170. /// @param finishedRV returned value in case the message was successfully received and processed
  171. /// @param nextState is a state where the state machine should transfer to after the message was successfully received and processed
  172. // StepStatus ProcessStatisticsReqSent(StepStatus finishedRV, State nextState);
  173. /// Called repeatedly while waiting for a query (Q0) period.
  174. /// All event checks to report immediately from the printer to the MMU shall be done in this method.
  175. /// So far, the only such a case is the filament sensor, but there can be more like this in the future.
  176. void CheckAndReportAsyncEvents();
  177. void SendQuery();
  178. void SendFINDAQuery();
  179. void SendAndUpdateFilamentSensor();
  180. void SendButton(uint8_t btn);
  181. void SendVersion(uint8_t stage);
  182. void SendReadRegister(uint8_t index, ScopeState nextState);
  183. StepStatus ProcessVersionResponse(uint8_t stage);
  184. /// Top level split - calls the appropriate step based on current scope
  185. StepStatus ScopeStep();
  186. static constexpr uint8_t maxRetries = 6;
  187. uint8_t retries;
  188. void StartSeqRestart();
  189. void DelayedRestartRestart();
  190. void IdleRestart();
  191. void CommandRestart();
  192. StepStatus StartSeqStep();
  193. StepStatus DelayedRestartWait();
  194. StepStatus IdleStep();
  195. StepStatus IdleWait();
  196. StepStatus CommandStep();
  197. StepStatus CommandWait();
  198. StepStatus StoppedStep() { return Processing; }
  199. StepStatus ProcessCommandQueryResponse();
  200. inline void SetRequestMsg(RequestMsg msg) {
  201. rq = msg;
  202. }
  203. inline const RequestMsg &ReqMsg() const { return rq; }
  204. RequestMsg rq = RequestMsg(RequestMsgCodes::unknown, 0);
  205. /// Records the next planned state, "unknown" msg code if no command is planned.
  206. /// This is not intended to be a queue of commands to process, protocol_logic must not queue commands.
  207. /// It exists solely to prevent breaking the Request-Response protocol handshake -
  208. /// - during tests it turned out, that the commands from Marlin are coming in such an asynchronnous way, that
  209. /// we could accidentally send T2 immediately after Q0 without waiting for reception of response to Q0.
  210. ///
  211. /// Beware, if Marlin manages to call PlanGenericCommand multiple times before a response comes,
  212. /// these variables will get overwritten by the last call.
  213. /// However, that should not happen under normal circumstances as Marlin should wait for the Command to finish,
  214. /// which includes all responses (and error recovery if any).
  215. RequestMsg plannedRq;
  216. /// Plan a command to be processed once the immediate response to a sent request arrives
  217. void PlanGenericRequest(RequestMsg rq);
  218. /// Activate the planned state once the immediate response to a sent request arrived
  219. bool ActivatePlannedRequest();
  220. uint32_t lastUARTActivityMs; ///< timestamp - last ms when something occurred on the UART
  221. DropOutFilter dataTO; ///< Filter of short consecutive drop outs which are recovered instantly
  222. ResponseMsg rsp; ///< decoded response message from the MMU protocol
  223. State state; ///< internal state of ProtocolLogic
  224. Protocol protocol; ///< protocol codec
  225. array<uint8_t, 16> lastReceivedBytes; ///< remembers the last few bytes of incoming communication for diagnostic purposes
  226. uint8_t lrb;
  227. MMU2Serial *uart; ///< UART interface
  228. ErrorCode errorCode; ///< last received error code from the MMU
  229. ProgressCode progressCode; ///< last received progress code from the MMU
  230. Buttons buttonCode; ///< Last received button from the MMU.
  231. uint8_t lastFSensor; ///< last state of filament sensor
  232. bool findaPressed;
  233. uint16_t failStatistics;
  234. uint8_t mmuFwVersion[3];
  235. uint16_t mmuFwVersionBuild;
  236. friend class ProtocolLogicPartBase;
  237. friend class Stopped;
  238. friend class Command;
  239. friend class Idle;
  240. friend class StartSeq;
  241. friend class DelayedRestart;
  242. friend class MMU2;
  243. };
  244. } // namespace MMU2