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

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