Better better split impl

This commit is contained in:
Sims
2024-12-11 08:10:05 +01:00
parent fcd133eb32
commit 1578b4129d

View File

@@ -61,23 +61,22 @@ bool OctoPrinter::post_request(const char* endpoint, const char* body, int timeo
bool OctoPrinter::send_gcode(const char* gcode, bool wait) bool OctoPrinter::send_gcode(const char* gcode, bool wait)
{ {
char* gcode_copy = (char*)malloc(sizeof(char) * (strlen(gcode) + 1));
size_t out_buff_size = sizeof(char) * (strlen(gcode) * 2 + 51);
char* out_buff = (char*)malloc(out_buff_size);
strcpy(gcode_copy, gcode);
JsonDocument doc; JsonDocument doc;
JsonArray array = doc["commands"].to<JsonArray>(); JsonArray array = doc["commands"].to<JsonArray>();
const char* last_line_start = gcode; const char* last_line_start = gcode_copy;
char out_buff[512];
for (const char* iter = gcode;; iter++) for (char* iter = gcode_copy;; iter++)
{ {
if (*iter == '\n' || *iter == '\0') if (*iter == '\n' || *iter == '\0')
{ {
const char *prev_char = iter - 1;
if (iter != last_line_start) if (iter != last_line_start)
{ {
char* buff = (char*)malloc(sizeof(char) * ((prev_char - last_line_start) + 1)); *iter = '\0';
buff[prev_char - last_line_start] = '\0'; array.add(last_line_start);
memcpy(buff, last_line_start, prev_char - last_line_start);
array.add(buff);
} }
last_line_start = iter + 1; last_line_start = iter + 1;
@@ -89,17 +88,15 @@ bool OctoPrinter::send_gcode(const char* gcode, bool wait)
} }
} }
if (serializeJson(doc, out_buff, 512) != 512) if (serializeJson(doc, out_buff, out_buff_size) == out_buff_size)
{ {
return false; return false;
} }
for (char* alloc : array) free(gcode_copy);
{ bool result = post_request("/api/printer/command/custom", out_buff);
free(alloc); free(out_buff);
} return result;
return post_request("/api/printer/command/custom", out_buff);
} }
bool OctoPrinter::move_printer(const char* axis, float amount, bool relative) bool OctoPrinter::move_printer(const char* axis, float amount, bool relative)