Debian Codegraph @

src/LibBGCode/binarize/meatpack.cpp

raw symbols SCIP
1 #include "meatpack.hpp"
2
3 #include <unordered_map>
4 #include <algorithm>
5 #include <cassert>
6
7 namespace MeatPack {
8
9 static constexpr const uint8_t Command_None{ 0 };
10 //#Command_TogglePacking = 253 -- Currently unused, byte 253 can be reused later.
11 static constexpr const uint8_t Command_EnablePacking{ 251 };
12 static constexpr const uint8_t Command_DisablePacking{ 250 };
13 static constexpr const uint8_t Command_ResetAll{ 249 };
14 static constexpr const uint8_t Command_QueryConfig{ 248 };
15 static constexpr const uint8_t Command_EnableNoSpaces{ 247 };
16 static constexpr const uint8_t Command_DisableNoSpaces{ 246 };
17 static constexpr const uint8_t Command_SignalByte{ 0xFF };
18
19 static constexpr const uint8_t BothUnpackable{ 0b11111111 };
20 static constexpr const char SpaceReplacedCharacter{ 'E' };
21
22 static constexpr const unsigned char SecondNotPacked{ 0b11110000 };
23 static constexpr const unsigned char FirstNotPacked{ 0b00001111 };
24 static constexpr const unsigned char NextPackedFirst{ 0b00000001 };
25 static constexpr const unsigned char NextPackedSecond{ 0b00000010 };
26
27 static const std::unordered_map<char, uint8_t> ReverseLookupTbl = {
28 { '0', 0b00000000 },
29 { '1', 0b00000001 },
30 { '2', 0b00000010 },
31 { '3', 0b00000011 },
32 { '4', 0b00000100 },
33 { '5', 0b00000101 },
34 { '6', 0b00000110 },
35 { '7', 0b00000111 },
36 { '8', 0b00001000 },
37 { '9', 0b00001001 },
38 { '.', 0b00001010 },
39 { ' ', 0b00001011 },
40 { '\n', 0b00001100 },
41 { 'G', 0b00001101 },
42 { 'X', 0b00001110 },
43 { '\0', 0b00001111 } // never used, 0b1111 is used to indicate the next 8-bits is a full character
44 };
45
46 static std::string_view trim(const std::string_view& str)
47 {
48 if (str.empty())
49 return std::string_view();
50 size_t start = 0;
51 while (start < str.size() - 1 && (str[start] == ' ' || str[start] == '\t')) { ++start; }
52 size_t end = str.size() - 1;
53 while (end > 0 && (str[end] == ' ' || str[end] == '\t')) { --end; }
54 if ((start == end && (str[end] == ' ' || str[end] == '\t')) || (start > end))
55 return std::string_view();
56 else
57 return std::string_view(&str[start], end - start + 1);
58 }
59
60 static std::string_view ltrim(const std::string_view& str)
61 {
62 const size_t start = str.find_first_not_of(" \t");
63 return start == std::string_view::npos ? std::string_view() : str.substr(start);
64 }
65
66 MPBinarizer::LookupTables MPBinarizer::s_lookup_tables = { { 0 }, { 0 }, false, 0 };
67
68 MPBinarizer::MPBinarizer(uint8_t flags) : m_flags(flags) {}
69
70 void MPBinarizer::initialize(std::vector<uint8_t>& dst)
71 {
72 initialize_lookup_tables();
73 append_command(Command_EnablePacking, dst);
74 if ((m_flags & Flag_OmitWhitespaces) != 0)
75 append_command(Command_EnableNoSpaces, dst);
76 m_binarizing = true;
77 }
78
79 void MPBinarizer::finalize(std::vector<uint8_t>& dst)
80 {
81 if ((m_flags & Flag_RemoveComments) != 0) {
82 assert(m_binarizing);
83 append_command(Command_ResetAll, dst);
84 m_binarizing = false;
85 }
86 }
87
88 void MPBinarizer::binarize_line(const std::string& line, std::vector<uint8_t>& dst)
89 {
90 auto unified_method = [this](const std::string& line) {
91 const std::string::size_type g_idx = line.find('G');
92 if (g_idx != std::string::npos) {
93 if (g_idx + 1 < line.size() && line[g_idx + 1] >= '0' && line[g_idx + 1] <= '9') {
94 if ((m_flags & Flag_OmitWhitespaces) != 0) {
95 std::string result = line;
96 std::replace(result.begin(), result.end(), 'e', 'E');
97 std::replace(result.begin(), result.end(), 'x', 'X');
98 std::replace(result.begin(), result.end(), 'g', 'G');
99 result.erase(std::remove(result.begin(), result.end(), ' '), result.end());
100 if (result.find('*') != std::string::npos) {
101 size_t checksum = 0;
102 result.erase(std::remove(result.begin(), result.end(), '*'), result.end());
103 for (size_t i = 0; i < result.size(); ++i) {
104 checksum ^= static_cast<uint8_t>(result[i]);
105 }
106 result += "*" + std::to_string(checksum);
107 }
108 result += '\n';
109 return result;
110 }
111 else {
112 std::string result = line;
113 std::replace(result.begin(), result.end(), 'x', 'X');
114 std::replace(result.begin(), result.end(), 'g', 'G');
115 result.erase(std::remove(result.begin(), result.end(), ' '), result.end());
116 if (result.find('*') != std::string::npos) {
117 size_t checksum = 0;
118 result.erase(std::remove(result.begin(), result.end(), '*'), result.end());
119 for (size_t i = 0; i < result.size(); ++i) {
120 checksum ^= static_cast<uint8_t>(result[i]);
121 }
122 result += "*" + std::to_string(checksum);
123 }
124 result += '\n';
125 return result;
126 }
127 }
128 }
129 return line;
130 };
131 auto is_packable = [](char c) {
132 return (s_lookup_tables.packable[static_cast<uint8_t>(c)] != 0);
133 };
134 auto pack_chars = [](char low, char high) {
135 return (((s_lookup_tables.value[static_cast<uint8_t>(high)] & 0xF) << 4) |
136 (s_lookup_tables.value[static_cast<uint8_t>(low)] & 0xF));
137 };
138
139 if (!line.empty()) {
140 const std::string_view trimmed_line = ltrim(line);
141
142 if ((m_flags & Flag_RemoveComments) == 0) {
143 if (!trimmed_line.empty() && trimmed_line[0] == ';') {
144 if (m_binarizing) {
145 append_command(Command_DisablePacking, dst);
146 m_binarizing = false;
147 }
148
149 dst.insert(dst.end(), line.begin(), line.end());
150 return;
151 }
152 }
153
154 if (trimmed_line.empty() ||
155 trimmed_line[0] == ';' ||
156 trimmed_line[0] == '\n' ||
157 trimmed_line[0] == '\r' ||
158 line.size() < 2)
159 return;
160
161 std::string modifiedLine = std::string(trim(std::string_view(line.substr(0, line.find(';')))));
162 if (modifiedLine.empty())
163 return;
164 modifiedLine = unified_method(modifiedLine);
165 if (modifiedLine.back() != '\n')
166 modifiedLine.push_back('\n');
167 const size_t line_len = modifiedLine.size();
168 std::vector<uint8_t> temp_buffer;
169 temp_buffer.reserve(line_len);
170
171 for (size_t line_idx = 0; line_idx < line_len; line_idx += 2) {
172 const bool skip_last = line_idx == (line_len - 1);
173 const char char_1 = modifiedLine[line_idx];
174 const char char_2 = (skip_last ? '\n' : modifiedLine[line_idx + 1]);
175 const bool c1_p = is_packable(char_1);
176 const bool c2_p = is_packable(char_2);
177
178 if (c1_p) {
179 if (c2_p)
180 temp_buffer.emplace_back(static_cast<uint8_t>(pack_chars(char_1, char_2)));
181 else {
182 temp_buffer.emplace_back(static_cast<uint8_t>(pack_chars(char_1, '\0')));
183 temp_buffer.emplace_back(static_cast<uint8_t>(char_2));
184 }
185 }
186 else {
187 if (c2_p) {
188 temp_buffer.emplace_back(static_cast<uint8_t>(pack_chars('\0', char_2)));
189 temp_buffer.emplace_back(static_cast<uint8_t>(char_1));
190 }
191 else {
192 temp_buffer.emplace_back(static_cast<uint8_t>(BothUnpackable));
193 temp_buffer.emplace_back(static_cast<uint8_t>(char_1));
194 temp_buffer.emplace_back(static_cast<uint8_t>(char_2));
195 }
196 }
197 }
198
199 if (!m_binarizing && !temp_buffer.empty()) {
200 append_command(Command_EnablePacking, dst);
201 m_binarizing = true;
202 }
203
204 dst.insert(dst.end(), temp_buffer.begin(), temp_buffer.end());
205 }
206 }
207
208 void MPBinarizer::append_command(unsigned char cmd, std::vector<uint8_t>& dst) {
209 dst.emplace_back(Command_SignalByte);
210 dst.emplace_back(Command_SignalByte);
211 dst.emplace_back(cmd);
212 }
213
214 void MPBinarizer::initialize_lookup_tables() {
215 if (s_lookup_tables.initialized && m_flags == s_lookup_tables.flags)
216 return;
217
218 for (const auto& [c, value] : ReverseLookupTbl) {
219 const int index = static_cast<int>(c);
220 s_lookup_tables.packable[index] = 1;
221 s_lookup_tables.value[index] = value;
222 }
223
224 if ((m_flags & Flag_OmitWhitespaces) != 0) {
225 s_lookup_tables.value[static_cast<uint8_t>(SpaceReplacedCharacter)] = ReverseLookupTbl.at(' ');
226 s_lookup_tables.packable[static_cast<uint8_t>(SpaceReplacedCharacter)] = 1;
227 s_lookup_tables.packable[static_cast<uint8_t>(' ')] = 0;
228 }
229 else {
230 s_lookup_tables.packable[static_cast<uint8_t>(SpaceReplacedCharacter)] = 0;
231 s_lookup_tables.packable[static_cast<uint8_t>(' ')] = 1;
232 }
233
234 s_lookup_tables.initialized = true;
235 s_lookup_tables.flags = m_flags;
236 }
237
238 // See for reference: https://github.com/scottmudge/Prusa-Firmware-MeatPack/blob/MK3_sm_MeatPack/Firmware/meatpack.cpp
239 void unbinarize(const std::vector<uint8_t>& src, std::string& dst)
240 {
241 bool unbinarizing = false;
242 bool nospace_enabled = false;
243 bool cmd_active = false; // Is a command pending
244 uint8_t char_buf = 0; // Buffers a character if dealing with out-of-sequence pairs
245 size_t cmd_count = 0; // Counts how many command bytes are received (need 2)
246 size_t full_char_queue = 0; // Counts how many full-width characters are to be received
247 std::array<uint8_t, 2> char_out_buf; // Output buffer for caching up to 2 characters
248 size_t char_out_count = 0; // Stores number of characters to be read out
249
250 auto handle_command = [&](uint8_t c) {
251 switch (c)
252 {
253 case Command_EnablePacking: { unbinarizing = true; break; }
254 case Command_DisablePacking: { unbinarizing = false; break; }
255 case Command_EnableNoSpaces: { nospace_enabled = true; break; }
256 case Command_DisableNoSpaces: { nospace_enabled = false; break; }
257 case Command_ResetAll: { unbinarizing = false; break; }
258 default:
259 case Command_QueryConfig: { break; }
260 }
261 };
262
263 auto handle_output_char = [&](uint8_t c) {
264 char_out_buf[char_out_count++] = c;
265 };
266
267 auto get_char = [&](uint8_t c) {
268 switch (c)
269 {
270 case 0b0000: { return '0'; }
271 case 0b0001: { return '1'; }
272 case 0b0010: { return '2'; }
273 case 0b0011: { return '3'; }
274 case 0b0100: { return '4'; }
275 case 0b0101: { return '5'; }
276 case 0b0110: { return '6'; }
277 case 0b0111: { return '7'; }
278 case 0b1000: { return '8'; }
279 case 0b1001: { return '9'; }
280 case 0b1010: { return '.'; }
281 case 0b1011: { return nospace_enabled ? 'E' : ' '; }
282 case 0b1100: { return '\n'; }
283 case 0b1101: { return 'G'; }
284 case 0b1110: { return 'X'; }
285 }
286 return '\0';
287 };
288
289 auto unpack_chars = [&](uint8_t pk, std::array<uint8_t, 2>& chars_out) {
290 uint8_t out = 0;
291
292 // If lower 4 bytes is 0b1111, the higher 4 are unused, and next char is full.
293 if ((pk & FirstNotPacked) == FirstNotPacked)
294 out |= NextPackedFirst;
295 else
296 chars_out[0] = get_char(pk & 0xF); // Assign lower char
297
298 // Check if upper 4 bytes is 0b1111... if so, we don't need the second char.
299 if ((pk & SecondNotPacked) == SecondNotPacked)
300 out |= NextPackedSecond;
301 else
302 chars_out[1] = get_char((pk >> 4) & 0xF); // Assign upper char
303
304 return out;
305 };
306
307 auto handle_rx_char = [&](uint8_t c) {
308 if (unbinarizing) {
309 if (full_char_queue > 0) {
310 handle_output_char(c);
311 if (char_buf > 0) {
312 handle_output_char(char_buf);
313 char_buf = 0;
314 }
315 --full_char_queue;
316 }
317 else {
318 std::array<uint8_t, 2> buf = { 0, 0 };
319 const uint8_t res = unpack_chars(c, buf);
320
321 if ((res & NextPackedFirst) != 0) {
322 ++full_char_queue;
323 if ((res & NextPackedSecond) != 0)
324 ++full_char_queue;
325 else
326 char_buf = buf[1];
327 }
328 else {
329 handle_output_char(buf[0]);
330 if (buf[0] != '\n') {
331 if ((res & NextPackedSecond) != 0)
332 ++full_char_queue;
333 else
334 handle_output_char(buf[1]);
335 }
336 }
337 }
338 }
339 else // Packing not enabled, just copy character to output
340 handle_output_char(c);
341 };
342
343 auto get_result_char = [&](std::array<char, 2>& chars_out) {
344 if (char_out_count > 0) {
345 const size_t res = char_out_count;
346 for (uint8_t i = 0; i < char_out_count; ++i) {
347 chars_out[i] = (char)char_out_buf[i];
348 }
349 char_out_count = 0;
350 return res;
351 }
352 return (size_t)0;
353 };
354
355 std::vector<uint8_t> unbin_buffer(2 * src.size(), 0);
356 auto it_unbin_end = unbin_buffer.begin();
357
358 bool add_space = false;
359
360 auto begin = src.begin();
361 auto end = src.end();
362
363 auto it_bin = begin;
364 while (it_bin != end) {
365 uint8_t c_bin = *it_bin;
366 if (c_bin == Command_SignalByte) {
367 if (cmd_count > 0) {
368 cmd_active = true;
369 cmd_count = 0;
370 }
371 else
372 ++cmd_count;
373 }
374 else {
375 if (cmd_active) {
376 handle_command(c_bin);
377 cmd_active = false;
378 }
379 else {
380 if (cmd_count > 0) {
381 handle_rx_char(Command_SignalByte);
382 cmd_count = 0;
383 }
384
385 handle_rx_char(c_bin);
386 }
387 }
388
389 auto is_gline_parameter = [](const char c) {
390 static const std::vector<char> parameters = {
391 // G0, G1
392 'X', 'Y', 'Z', 'E', 'F',
393 // G2, G3
394 'I', 'J', 'R',
395 // G4
396 'S',
397 // G29
398 'G', 'P', 'W', 'H', 'C', 'A'
399 };
400 return std::find(parameters.begin(), parameters.end(), c) != parameters.end();
401 };
402
403 std::array<char, 2> c_unbin{ 0, 0 };
404 const size_t char_count = get_result_char(c_unbin);
405 for (size_t i = 0; i < char_count; ++i) {
406 // GCodeReader::parse_line_internal() is unable to parse a G line where the data are not separated by spaces
407 // so we add them where needed
408 const size_t curr_unbin_buffer_length = std::distance(unbin_buffer.begin(), it_unbin_end);
409 bool new_line = false;
410 if (c_unbin[i] == 'G' && (curr_unbin_buffer_length == 0 || *std::prev(it_unbin_end, 1) == '\n')) {
411 add_space = true;
412 new_line = true;
413 }
414 else if (c_unbin[i] == '\n')
415 add_space = false;
416
417 if (!new_line && add_space && (curr_unbin_buffer_length == 0 || *std::prev(it_unbin_end, 1) != ' ') &&
418 is_gline_parameter(c_unbin[i])) {
419 *it_unbin_end = ' ';
420 ++it_unbin_end;
421 if (it_unbin_end == unbin_buffer.end()) {
422 // the buffer is not big enough, resize it
423 unbin_buffer.resize(2 * unbin_buffer.size(), 0);
424 it_unbin_end = unbin_buffer.begin() + curr_unbin_buffer_length + 1;
425 }
426 }
427
428 if (c_unbin[i] != '\n' || std::distance(unbin_buffer.begin(), it_unbin_end) == 0 || *std::prev(it_unbin_end, 1) != '\n') {
429 *it_unbin_end = c_unbin[i];
430 ++it_unbin_end;
431 if (it_unbin_end == unbin_buffer.end()) {
432 // the buffer is not big enough, resize it
433 unbin_buffer.resize(2 * unbin_buffer.size(), 0);
434 it_unbin_end = unbin_buffer.begin() + curr_unbin_buffer_length + 1;
435 }
436 }
437 }
438
439 ++it_bin;
440 }
441
442 dst.insert(dst.end(), unbin_buffer.begin(), it_unbin_end);
443 }
444
445 } // namespace MeatPack