mmu2_protocol_logic.h 13 KB

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