mmu2_protocol_logic.h 13 KB

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