mmu2_protocol_logic.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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_protocol.h"
  19. #include "mmu2_serial.h"
  20. /// New MMU2 protocol logic
  21. namespace MMU2 {
  22. using namespace modules::protocol;
  23. class ProtocolLogic;
  24. /// ProtocolLogic stepping statuses
  25. enum StepStatus : uint_fast8_t {
  26. Processing = 0,
  27. MessageReady, ///< a message has been successfully decoded from the received bytes
  28. Finished,
  29. CommunicationTimeout, ///< the MMU failed to respond to a request within a specified time frame
  30. ProtocolError, ///< bytes read from the MMU didn't form a valid response
  31. CommandRejected, ///< the MMU rejected the command due to some other command in progress, may be the user is operating the MMU locally (button commands)
  32. CommandError, ///< the command in progress stopped due to unrecoverable error, user interaction required
  33. VersionMismatch, ///< the MMU reports its firmware version incompatible with our implementation
  34. CommunicationRecovered,
  35. };
  36. static constexpr uint32_t linkLayerTimeout = 2000; ///< default link layer communication timeout
  37. static constexpr uint32_t dataLayerTimeout = linkLayerTimeout * 3; ///< data layer communication timeout
  38. static constexpr uint32_t heartBeatPeriod = linkLayerTimeout / 2; ///< period of heart beat messages (Q0)
  39. static_assert( heartBeatPeriod < linkLayerTimeout && linkLayerTimeout < dataLayerTimeout, "Incorrect ordering of timeouts");
  40. /// Base class for sub-automata of the ProtocolLogic class.
  41. /// Their operation should never block (wait inside).
  42. class ProtocolLogicPartBase {
  43. public:
  44. inline ProtocolLogicPartBase(ProtocolLogic *logic)
  45. : logic(logic)
  46. , state(State::Ready) {}
  47. /// Restarts the sub-automaton
  48. virtual void Restart() = 0;
  49. /// Makes one step in the sub-automaton
  50. /// @returns StepStatus
  51. virtual StepStatus Step() = 0;
  52. /// @returns true if the state machine is waiting for a response from the MMU
  53. bool ExpectsResponse()const { return state != State::Ready && state != State::Wait; }
  54. protected:
  55. ProtocolLogic *logic; ///< pointer to parent ProtocolLogic layer
  56. friend class ProtocolLogic;
  57. /// Common internal states of the derived sub-automata
  58. /// General rule of thumb: *Sent states are waiting for a response from the MMU
  59. enum class State : uint_fast8_t {
  60. Ready,
  61. Wait,
  62. S0Sent,
  63. S1Sent,
  64. S2Sent,
  65. QuerySent,
  66. CommandSent,
  67. FilamentSensorStateSent,
  68. FINDAReqSent,
  69. ButtonSent,
  70. ContinueFromIdle
  71. };
  72. State state; ///< internal state of the sub-automaton
  73. /// @returns the status of processing of the FINDA query response
  74. /// @param finishedRV returned value in case the message was successfully received and processed
  75. /// @param nextState is a state where the state machine should transfer to after the message was successfully received and processed
  76. StepStatus ProcessFINDAReqSent(StepStatus finishedRV, State nextState);
  77. /// Called repeatedly while waiting for a query (Q0) period.
  78. /// All event checks to report immediately from the printer to the MMU shall be done in this method.
  79. /// So far, the only such a case is the filament sensor, but there can be more like this in the future.
  80. void CheckAndReportAsyncEvents();
  81. void SendQuery();
  82. void SendFINDAQuery();
  83. void SendAndUpdateFilamentSensor();
  84. void SendButton(uint8_t btn);
  85. };
  86. /// Starting sequence of the communication with the MMU.
  87. /// The printer shall ask for MMU's version numbers.
  88. /// If everything goes well and the MMU's version is good enough,
  89. /// the ProtocolLogic layer may continue talking to the MMU
  90. class StartSeq : public ProtocolLogicPartBase {
  91. public:
  92. inline StartSeq(ProtocolLogic *logic)
  93. : ProtocolLogicPartBase(logic) {}
  94. void Restart() override;
  95. StepStatus Step() override;
  96. };
  97. /// A command and its lifecycle.
  98. /// CommandSent:
  99. /// - the command was placed into the UART TX buffer, awaiting response from the MMU
  100. /// - if the MMU confirms the command, we'll wait for it to finish
  101. /// - if the MMU refuses the command, we report an error (should normally not happen unless someone is hacking the communication without waiting for the previous command to finish)
  102. /// Wait:
  103. /// - waiting for the MMU to process the command - may take several seconds, for example Tool change operation
  104. /// - meawhile, every 300ms we send a Q0 query to obtain the current state of the command being processed
  105. /// - as soon as we receive a response to Q0 from the MMU, we process it in the next state
  106. /// QuerySent - check the reply from the MMU - can be any of the following:
  107. /// - Processing: the MMU is still working
  108. /// - Error: the command failed on the MMU, we'll have the exact error report in the response message
  109. /// - Finished: the MMU finished the command successfully, another command may be issued now
  110. class Command : public ProtocolLogicPartBase {
  111. public:
  112. inline Command(ProtocolLogic *logic)
  113. : ProtocolLogicPartBase(logic)
  114. , rq(RequestMsgCodes::unknown, 0) {}
  115. void Restart() override;
  116. StepStatus Step() override;
  117. inline void SetRequestMsg(RequestMsg msg) {
  118. rq = msg;
  119. }
  120. void ContinueFromIdle(){
  121. state = State::ContinueFromIdle;
  122. }
  123. inline const RequestMsg &ReqMsg()const { return rq; }
  124. private:
  125. RequestMsg rq;
  126. };
  127. /// Idle state - we have no command for the MMU, so we are only regularly querying its state with Q0 messages.
  128. /// The idle state can be interrupted any time to issue a command into the MMU
  129. class Idle : public ProtocolLogicPartBase {
  130. public:
  131. inline Idle(ProtocolLogic *logic)
  132. : ProtocolLogicPartBase(logic) {}
  133. void Restart() override;
  134. StepStatus Step() override;
  135. };
  136. /// The communication with the MMU is stopped/disabled (for whatever reason).
  137. /// Nothing is being put onto the UART.
  138. class Stopped : public ProtocolLogicPartBase {
  139. public:
  140. inline Stopped(ProtocolLogic *logic)
  141. : ProtocolLogicPartBase(logic) {}
  142. void Restart() override {}
  143. StepStatus Step() override { return Processing; }
  144. };
  145. ///< Filter of short consecutive drop outs which are recovered instantly
  146. class DropOutFilter {
  147. StepStatus cause;
  148. uint8_t occurrences;
  149. public:
  150. static constexpr uint8_t maxOccurrences = 3;
  151. static_assert (maxOccurrences > 1, "we should really silently ignore at least 1 comm drop out if recovered immediately afterwards");
  152. DropOutFilter() = default;
  153. /// @returns true if the error should be reported to higher levels (max. number of consecutive occurrences reached)
  154. bool Record(StepStatus ss);
  155. /// @returns the initial cause which started this drop out event
  156. inline StepStatus InitialCause()const { return cause; }
  157. /// Rearms the object for further processing - basically call this once the MMU responds with something meaningful (e.g. S0 A2)
  158. inline void Reset(){ occurrences = maxOccurrences; }
  159. };
  160. /// Logic layer of the MMU vs. printer communication protocol
  161. class ProtocolLogic {
  162. public:
  163. ProtocolLogic(MMU2Serial *uart);
  164. /// Start/Enable communication with the MMU
  165. void Start();
  166. /// Stop/Disable communication with the MMU
  167. void Stop();
  168. // Issue commands to the MMU
  169. void ToolChange(uint8_t slot);
  170. void UnloadFilament();
  171. void LoadFilament(uint8_t slot);
  172. void EjectFilament(uint8_t slot);
  173. void CutFilament(uint8_t slot);
  174. void ResetMMU();
  175. void Button(uint8_t index);
  176. void Home(uint8_t mode);
  177. /// Step the state machine
  178. StepStatus Step();
  179. /// @returns the current/latest error code as reported by the MMU
  180. ErrorCode Error() const { return errorCode; }
  181. /// @returns the current/latest process code as reported by the MMU
  182. ProgressCode Progress() const { return progressCode; }
  183. uint8_t CommandInProgress()const;
  184. inline bool Running()const {
  185. return state == State::Running;
  186. }
  187. inline bool FindaPressed() const {
  188. return findaPressed;
  189. }
  190. #ifndef UNITTEST
  191. private:
  192. #endif
  193. StepStatus ProcessUARTByte(uint8_t c);
  194. StepStatus ExpectingMessage(uint32_t timeout);
  195. void SendMsg(RequestMsg rq);
  196. void SwitchToIdle();
  197. void HandleCommunicationTimeout();
  198. StepStatus HandleCommError(const char *msg, StepStatus ss);
  199. bool Elapsed(uint32_t timeout) const;
  200. void RecordUARTActivity();
  201. void RecordReceivedByte(uint8_t c);
  202. void FormatLastReceivedBytes(char *dst);
  203. void FormatLastResponseMsgAndClearLRB(char *dst);
  204. void LogRequestMsg(const uint8_t *txbuff, uint8_t size);
  205. void LogError(const char *reason);
  206. void LogResponse();
  207. void SwitchFromIdleToCommand();
  208. enum class State : uint_fast8_t {
  209. Stopped, ///< stopped for whatever reason
  210. InitSequence, ///< initial sequence running
  211. Running ///< normal operation - Idle + Command processing
  212. };
  213. // individual sub-state machines - may be they can be combined into a union since only one is active at once
  214. Stopped stopped;
  215. StartSeq startSeq;
  216. Idle idle;
  217. Command command;
  218. ProtocolLogicPartBase *currentState; ///< command currently being processed
  219. /// Records the next planned state, "unknown" msg code if no command is planned.
  220. /// This is not intended to be a queue of commands to process, protocol_logic must not queue commands.
  221. /// It exists solely to prevent breaking the Request-Response protocol handshake -
  222. /// - during tests it turned out, that the commands from Marlin are coming in such an asynchronnous way, that
  223. /// we could accidentally send T2 immediately after Q0 without waiting for reception of response to Q0.
  224. ///
  225. /// Beware, if Marlin manages to call PlanGenericCommand multiple times before a response comes,
  226. /// these variables will get overwritten by the last call.
  227. /// However, that should not happen under normal circumstances as Marlin should wait for the Command to finish,
  228. /// which includes all responses (and error recovery if any).
  229. RequestMsg plannedRq;
  230. /// Plan a command to be processed once the immediate response to a sent request arrives
  231. void PlanGenericRequest(RequestMsg rq);
  232. /// Activate the planned state once the immediate response to a sent request arrived
  233. bool ActivatePlannedRequest();
  234. uint32_t lastUARTActivityMs; ///< timestamp - last ms when something occurred on the UART
  235. DropOutFilter dataTO; ///< Filter of short consecutive drop outs which are recovered instantly
  236. ResponseMsg rsp; ///< decoded response message from the MMU protocol
  237. State state; ///< internal state of ProtocolLogic
  238. Protocol protocol; ///< protocol codec
  239. array<uint8_t, 16> lastReceivedBytes; ///< remembers the last few bytes of incoming communication for diagnostic purposes
  240. uint8_t lrb;
  241. MMU2Serial *uart; ///< UART interface
  242. ErrorCode errorCode; ///< last received error code from the MMU
  243. ProgressCode progressCode; ///< last received progress code from the MMU
  244. uint8_t lastFSensor; ///< last state of filament sensor
  245. bool findaPressed;
  246. friend class ProtocolLogicPartBase;
  247. friend class Stopped;
  248. friend class Command;
  249. friend class Idle;
  250. friend class StartSeq;
  251. friend class MMU2;
  252. };
  253. } // namespace MMU2