My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

binary_stream.h 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #pragma once
  23. #include "../inc/MarlinConfig.h"
  24. #define BINARY_STREAM_COMPRESSION
  25. #if ENABLED(BINARY_STREAM_COMPRESSION)
  26. #include "../libs/heatshrink/heatshrink_decoder.h"
  27. // STM32 (and others?) require a word-aligned buffer for SD card transfers via DMA
  28. static __attribute__((aligned(sizeof(size_t)))) uint8_t decode_buffer[512] = {};
  29. static heatshrink_decoder hsd;
  30. #endif
  31. inline bool bs_serial_data_available(const serial_index_t index) {
  32. return SERIAL_IMPL.available(index);
  33. }
  34. inline int bs_read_serial(const serial_index_t index) {
  35. return SERIAL_IMPL.read(index);
  36. }
  37. class SDFileTransferProtocol {
  38. private:
  39. struct Packet {
  40. struct [[gnu::packed]] Open {
  41. static bool validate(char *buffer, size_t length) {
  42. return (length > sizeof(Open) && buffer[length - 1] == '\0');
  43. }
  44. static Open& decode(char *buffer) {
  45. data = &buffer[2];
  46. return *reinterpret_cast<Open*>(buffer);
  47. }
  48. bool compression_enabled() { return compression & 0x1; }
  49. bool dummy_transfer() { return dummy & 0x1; }
  50. static char* filename() { return data; }
  51. private:
  52. uint8_t dummy, compression;
  53. static char* data; // variable length strings complicate things
  54. };
  55. };
  56. static bool file_open(char *filename) {
  57. if (!dummy_transfer) {
  58. card.mount();
  59. card.openFileWrite(filename);
  60. if (!card.isFileOpen()) return false;
  61. }
  62. transfer_active = true;
  63. data_waiting = 0;
  64. TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_reset(&hsd));
  65. return true;
  66. }
  67. static bool file_write(char *buffer, const size_t length) {
  68. #if ENABLED(BINARY_STREAM_COMPRESSION)
  69. if (compression) {
  70. size_t total_processed = 0, processed_count = 0;
  71. HSD_poll_res presult;
  72. while (total_processed < length) {
  73. heatshrink_decoder_sink(&hsd, reinterpret_cast<uint8_t*>(&buffer[total_processed]), length - total_processed, &processed_count);
  74. total_processed += processed_count;
  75. do {
  76. presult = heatshrink_decoder_poll(&hsd, &decode_buffer[data_waiting], sizeof(decode_buffer) - data_waiting, &processed_count);
  77. data_waiting += processed_count;
  78. if (data_waiting == sizeof(decode_buffer)) {
  79. if (!dummy_transfer)
  80. if (card.write(decode_buffer, data_waiting) < 0) {
  81. return false;
  82. }
  83. data_waiting = 0;
  84. }
  85. } while (presult == HSDR_POLL_MORE);
  86. }
  87. return true;
  88. }
  89. #endif
  90. return (dummy_transfer || card.write(buffer, length) >= 0);
  91. }
  92. static bool file_close() {
  93. if (!dummy_transfer) {
  94. #if ENABLED(BINARY_STREAM_COMPRESSION)
  95. // flush any buffered data
  96. if (data_waiting) {
  97. if (card.write(decode_buffer, data_waiting) < 0) return false;
  98. data_waiting = 0;
  99. }
  100. #endif
  101. card.closefile();
  102. card.release();
  103. }
  104. TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_finish(&hsd));
  105. transfer_active = false;
  106. return true;
  107. }
  108. static void transfer_abort() {
  109. if (!dummy_transfer) {
  110. card.closefile();
  111. card.removeFile(card.filename);
  112. card.release();
  113. TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_finish(&hsd));
  114. }
  115. transfer_active = false;
  116. return;
  117. }
  118. enum class FileTransfer : uint8_t { QUERY, OPEN, CLOSE, WRITE, ABORT };
  119. static size_t data_waiting, transfer_timeout, idle_timeout;
  120. static bool transfer_active, dummy_transfer, compression;
  121. public:
  122. static void idle() {
  123. // If a transfer is interrupted and a file is left open, abort it after TIMEOUT ms
  124. const millis_t ms = millis();
  125. if (transfer_active && ELAPSED(ms, idle_timeout)) {
  126. idle_timeout = ms + IDLE_PERIOD;
  127. if (ELAPSED(ms, transfer_timeout)) transfer_abort();
  128. }
  129. }
  130. static void process(uint8_t packet_type, char *buffer, const uint16_t length) {
  131. transfer_timeout = millis() + TIMEOUT;
  132. switch (static_cast<FileTransfer>(packet_type)) {
  133. case FileTransfer::QUERY:
  134. SERIAL_ECHOPGM("PFT:version:", VERSION_MAJOR, ".", VERSION_MINOR, ".", VERSION_PATCH);
  135. #if ENABLED(BINARY_STREAM_COMPRESSION)
  136. SERIAL_ECHOLNPGM(":compression:heatshrink,", HEATSHRINK_STATIC_WINDOW_BITS, ",", HEATSHRINK_STATIC_LOOKAHEAD_BITS);
  137. #else
  138. SERIAL_ECHOLNPGM(":compression:none");
  139. #endif
  140. break;
  141. case FileTransfer::OPEN:
  142. if (transfer_active)
  143. SERIAL_ECHOLNPGM("PFT:busy");
  144. else {
  145. if (Packet::Open::validate(buffer, length)) {
  146. auto packet = Packet::Open::decode(buffer);
  147. compression = packet.compression_enabled();
  148. dummy_transfer = packet.dummy_transfer();
  149. if (file_open(packet.filename())) {
  150. SERIAL_ECHOLNPGM("PFT:success");
  151. break;
  152. }
  153. }
  154. SERIAL_ECHOLNPGM("PFT:fail");
  155. }
  156. break;
  157. case FileTransfer::CLOSE:
  158. if (transfer_active) {
  159. if (file_close())
  160. SERIAL_ECHOLNPGM("PFT:success");
  161. else
  162. SERIAL_ECHOLNPGM("PFT:ioerror");
  163. }
  164. else SERIAL_ECHOLNPGM("PFT:invalid");
  165. break;
  166. case FileTransfer::WRITE:
  167. if (!transfer_active)
  168. SERIAL_ECHOLNPGM("PFT:invalid");
  169. else if (!file_write(buffer, length))
  170. SERIAL_ECHOLNPGM("PFT:ioerror");
  171. break;
  172. case FileTransfer::ABORT:
  173. transfer_abort();
  174. SERIAL_ECHOLNPGM("PFT:success");
  175. break;
  176. default:
  177. SERIAL_ECHOLNPGM("PTF:invalid");
  178. break;
  179. }
  180. }
  181. static const uint16_t VERSION_MAJOR = 0, VERSION_MINOR = 1, VERSION_PATCH = 0, TIMEOUT = 10000, IDLE_PERIOD = 1000;
  182. };
  183. class BinaryStream {
  184. public:
  185. enum class Protocol : uint8_t { CONTROL, FILE_TRANSFER };
  186. enum class ProtocolControl : uint8_t { SYNC = 1, CLOSE };
  187. enum class StreamState : uint8_t { PACKET_RESET, PACKET_WAIT, PACKET_HEADER, PACKET_DATA, PACKET_FOOTER,
  188. PACKET_PROCESS, PACKET_RESEND, PACKET_TIMEOUT, PACKET_ERROR };
  189. struct Packet { // 10 byte protocol overhead, ascii with checksum and line number has a minimum of 7 increasing with line
  190. union Header {
  191. static constexpr uint16_t HEADER_TOKEN = 0xB5AD;
  192. struct [[gnu::packed]] {
  193. uint16_t token; // packet start token
  194. uint8_t sync; // stream sync, resend id and packet loss detection
  195. uint8_t meta; // 4 bit protocol,
  196. // 4 bit packet type
  197. uint16_t size; // data length
  198. uint16_t checksum; // header checksum
  199. };
  200. uint8_t protocol() { return (meta >> 4) & 0xF; }
  201. uint8_t type() { return meta & 0xF; }
  202. void reset() { token = 0; sync = 0; meta = 0; size = 0; checksum = 0; }
  203. uint8_t data[2];
  204. };
  205. union Footer {
  206. struct [[gnu::packed]] {
  207. uint16_t checksum; // full packet checksum
  208. };
  209. void reset() { checksum = 0; }
  210. uint8_t data[1];
  211. };
  212. Header header;
  213. Footer footer;
  214. uint32_t bytes_received;
  215. uint16_t checksum, header_checksum;
  216. millis_t timeout;
  217. char* buffer;
  218. void reset() {
  219. header.reset();
  220. footer.reset();
  221. bytes_received = 0;
  222. checksum = 0;
  223. header_checksum = 0;
  224. timeout = millis() + PACKET_MAX_WAIT;
  225. buffer = nullptr;
  226. }
  227. } packet{};
  228. void reset() {
  229. sync = 0;
  230. packet_retries = 0;
  231. buffer_next_index = 0;
  232. }
  233. // fletchers 16 checksum
  234. uint32_t checksum(uint32_t cs, uint8_t value) {
  235. uint16_t cs_low = (((cs & 0xFF) + value) % 255);
  236. return ((((cs >> 8) + cs_low) % 255) << 8) | cs_low;
  237. }
  238. // read the next byte from the data stream keeping track of
  239. // whether the stream times out from data starvation
  240. // takes the data variable by reference in order to return status
  241. bool stream_read(uint8_t& data) {
  242. if (stream_state != StreamState::PACKET_WAIT && ELAPSED(millis(), packet.timeout)) {
  243. stream_state = StreamState::PACKET_TIMEOUT;
  244. return false;
  245. }
  246. if (!bs_serial_data_available(card.transfer_port_index)) return false;
  247. data = bs_read_serial(card.transfer_port_index);
  248. packet.timeout = millis() + PACKET_MAX_WAIT;
  249. return true;
  250. }
  251. template<const size_t buffer_size>
  252. void receive(char (&buffer)[buffer_size]) {
  253. uint8_t data = 0;
  254. millis_t transfer_window = millis() + RX_TIMESLICE;
  255. #if ENABLED(SDSUPPORT)
  256. PORT_REDIRECT(SERIAL_PORTMASK(card.transfer_port_index));
  257. #endif
  258. #pragma GCC diagnostic push
  259. #pragma GCC diagnostic ignored "-Warray-bounds"
  260. while (PENDING(millis(), transfer_window)) {
  261. switch (stream_state) {
  262. /**
  263. * Data stream packet handling
  264. */
  265. case StreamState::PACKET_RESET:
  266. packet.reset();
  267. stream_state = StreamState::PACKET_WAIT;
  268. case StreamState::PACKET_WAIT:
  269. if (!stream_read(data)) { idle(); return; } // no active packet so don't wait
  270. packet.header.data[1] = data;
  271. if (packet.header.token == packet.header.HEADER_TOKEN) {
  272. packet.bytes_received = 2;
  273. stream_state = StreamState::PACKET_HEADER;
  274. }
  275. else {
  276. // stream corruption drop data
  277. packet.header.data[0] = data;
  278. }
  279. break;
  280. case StreamState::PACKET_HEADER:
  281. if (!stream_read(data)) break;
  282. packet.header.data[packet.bytes_received++] = data;
  283. packet.checksum = checksum(packet.checksum, data);
  284. // header checksum calculation can't contain the checksum
  285. if (packet.bytes_received == sizeof(Packet::header) - 2)
  286. packet.header_checksum = packet.checksum;
  287. if (packet.bytes_received == sizeof(Packet::header)) {
  288. if (packet.header.checksum == packet.header_checksum) {
  289. // The SYNC control packet is a special case in that it doesn't require the stream sync to be correct
  290. if (static_cast<Protocol>(packet.header.protocol()) == Protocol::CONTROL && static_cast<ProtocolControl>(packet.header.type()) == ProtocolControl::SYNC) {
  291. SERIAL_ECHOLNPGM("ss", sync, ",", buffer_size, ",", VERSION_MAJOR, ".", VERSION_MINOR, ".", VERSION_PATCH);
  292. stream_state = StreamState::PACKET_RESET;
  293. break;
  294. }
  295. if (packet.header.sync == sync) {
  296. buffer_next_index = 0;
  297. packet.bytes_received = 0;
  298. if (packet.header.size) {
  299. stream_state = StreamState::PACKET_DATA;
  300. packet.buffer = static_cast<char *>(&buffer[0]); // multipacket buffering not implemented, always allocate whole buffer to packet
  301. }
  302. else
  303. stream_state = StreamState::PACKET_PROCESS;
  304. }
  305. else if (packet.header.sync == sync - 1) { // ok response must have been lost
  306. SERIAL_ECHOLNPGM("ok", packet.header.sync); // transmit valid packet received and drop the payload
  307. stream_state = StreamState::PACKET_RESET;
  308. }
  309. else if (packet_retries) {
  310. stream_state = StreamState::PACKET_RESET; // could be packets already buffered on flow controlled connections, drop them without ack
  311. }
  312. else {
  313. SERIAL_ECHO_MSG("Datastream packet out of order");
  314. stream_state = StreamState::PACKET_RESEND;
  315. }
  316. }
  317. else {
  318. SERIAL_ECHO_MSG("Packet header(", packet.header.sync, "?) corrupt");
  319. stream_state = StreamState::PACKET_RESEND;
  320. }
  321. }
  322. break;
  323. case StreamState::PACKET_DATA:
  324. if (!stream_read(data)) break;
  325. if (buffer_next_index < buffer_size)
  326. packet.buffer[buffer_next_index] = data;
  327. else {
  328. SERIAL_ECHO_MSG("Datastream packet data buffer overrun");
  329. stream_state = StreamState::PACKET_ERROR;
  330. break;
  331. }
  332. packet.checksum = checksum(packet.checksum, data);
  333. packet.bytes_received++;
  334. buffer_next_index++;
  335. if (packet.bytes_received == packet.header.size) {
  336. stream_state = StreamState::PACKET_FOOTER;
  337. packet.bytes_received = 0;
  338. }
  339. break;
  340. case StreamState::PACKET_FOOTER:
  341. if (!stream_read(data)) break;
  342. packet.footer.data[packet.bytes_received++] = data;
  343. if (packet.bytes_received == sizeof(Packet::footer)) {
  344. if (packet.footer.checksum == packet.checksum) {
  345. stream_state = StreamState::PACKET_PROCESS;
  346. }
  347. else {
  348. SERIAL_ECHO_MSG("Packet(", packet.header.sync, ") payload corrupt");
  349. stream_state = StreamState::PACKET_RESEND;
  350. }
  351. }
  352. break;
  353. case StreamState::PACKET_PROCESS:
  354. sync++;
  355. packet_retries = 0;
  356. bytes_received += packet.header.size;
  357. SERIAL_ECHOLNPGM("ok", packet.header.sync); // transmit valid packet received
  358. dispatch();
  359. stream_state = StreamState::PACKET_RESET;
  360. break;
  361. case StreamState::PACKET_RESEND:
  362. if (packet_retries < MAX_RETRIES || MAX_RETRIES == 0) {
  363. packet_retries++;
  364. stream_state = StreamState::PACKET_RESET;
  365. SERIAL_ECHO_MSG("Resend request ", packet_retries);
  366. SERIAL_ECHOLNPGM("rs", sync);
  367. }
  368. else
  369. stream_state = StreamState::PACKET_ERROR;
  370. break;
  371. case StreamState::PACKET_TIMEOUT:
  372. SERIAL_ECHO_MSG("Datastream timeout");
  373. stream_state = StreamState::PACKET_RESEND;
  374. break;
  375. case StreamState::PACKET_ERROR:
  376. SERIAL_ECHOLNPGM("fe", packet.header.sync);
  377. reset(); // reset everything, resync required
  378. stream_state = StreamState::PACKET_RESET;
  379. break;
  380. }
  381. }
  382. #pragma GCC diagnostic pop
  383. }
  384. void dispatch() {
  385. switch (static_cast<Protocol>(packet.header.protocol())) {
  386. case Protocol::CONTROL:
  387. switch (static_cast<ProtocolControl>(packet.header.type())) {
  388. case ProtocolControl::CLOSE: // revert back to ASCII mode
  389. card.flag.binary_mode = false;
  390. break;
  391. default:
  392. SERIAL_ECHO_MSG("Unknown BinaryProtocolControl Packet");
  393. }
  394. break;
  395. case Protocol::FILE_TRANSFER:
  396. SDFileTransferProtocol::process(packet.header.type(), packet.buffer, packet.header.size); // send user data to be processed
  397. break;
  398. default:
  399. SERIAL_ECHO_MSG("Unsupported Binary Protocol");
  400. }
  401. }
  402. void idle() {
  403. // Some Protocols may need periodic updates without new data
  404. SDFileTransferProtocol::idle();
  405. }
  406. static const uint16_t PACKET_MAX_WAIT = 500, RX_TIMESLICE = 20, MAX_RETRIES = 0, VERSION_MAJOR = 0, VERSION_MINOR = 1, VERSION_PATCH = 0;
  407. uint8_t packet_retries, sync;
  408. uint16_t buffer_next_index;
  409. uint32_t bytes_received;
  410. StreamState stream_state = StreamState::PACKET_RESET;
  411. };
  412. extern BinaryStream binaryStream[NUM_SERIAL];