Merge branch 'fix/use-wrap-delete' into rdelta/improve-homing-and-calibration
[clinton/Smoothieware.git] / src / modules / utils / simpleshell / SimpleShell.cpp
1 /*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8
9 #include "SimpleShell.h"
10 #include "libs/Kernel.h"
11 #include "libs/nuts_bolts.h"
12 #include "libs/utils.h"
13 #include "libs/SerialMessage.h"
14 #include "libs/StreamOutput.h"
15 #include "modules/robot/Conveyor.h"
16 #include "DirHandle.h"
17 #include "mri.h"
18 #include "version.h"
19 #include "PublicDataRequest.h"
20 #include "AppendFileStream.h"
21 #include "FileStream.h"
22 #include "checksumm.h"
23 #include "PublicData.h"
24 #include "Gcode.h"
25 #include "Robot.h"
26 #include "ToolManagerPublicAccess.h"
27 #include "GcodeDispatch.h"
28 #include "BaseSolution.h"
29 #include "StepperMotor.h"
30 #include "Configurator.h"
31
32 #include "TemperatureControlPublicAccess.h"
33 #include "EndstopsPublicAccess.h"
34 #include "NetworkPublicAccess.h"
35 #include "platform_memory.h"
36 #include "SwitchPublicAccess.h"
37 #include "SDFAT.h"
38 #include "Thermistor.h"
39 #include "md5.h"
40 #include "utils.h"
41
42 #include "system_LPC17xx.h"
43 #include "LPC17xx.h"
44
45 #include "mbed.h" // for wait_ms()
46
47 extern unsigned int g_maximumHeapAddress;
48
49 #include <malloc.h>
50 #include <mri.h>
51 #include <stdio.h>
52 #include <stdint.h>
53
54 extern "C" uint32_t __end__;
55 extern "C" uint32_t __malloc_free_list;
56 extern "C" uint32_t _sbrk(int size);
57
58 // command lookup table
59 const SimpleShell::ptentry_t SimpleShell::commands_table[] = {
60 {"ls", SimpleShell::ls_command},
61 {"cd", SimpleShell::cd_command},
62 {"pwd", SimpleShell::pwd_command},
63 {"cat", SimpleShell::cat_command},
64 {"rm", SimpleShell::rm_command},
65 {"mv", SimpleShell::mv_command},
66 {"upload", SimpleShell::upload_command},
67 {"reset", SimpleShell::reset_command},
68 {"dfu", SimpleShell::dfu_command},
69 {"break", SimpleShell::break_command},
70 {"help", SimpleShell::help_command},
71 {"?", SimpleShell::help_command},
72 {"version", SimpleShell::version_command},
73 {"mem", SimpleShell::mem_command},
74 {"get", SimpleShell::get_command},
75 {"set_temp", SimpleShell::set_temp_command},
76 {"switch", SimpleShell::switch_command},
77 {"net", SimpleShell::net_command},
78 {"load", SimpleShell::load_command},
79 {"save", SimpleShell::save_command},
80 {"remount", SimpleShell::remount_command},
81 {"calc_thermistor", SimpleShell::calc_thermistor_command},
82 {"thermistors", SimpleShell::print_thermistors_command},
83 {"md5sum", SimpleShell::md5sum_command},
84
85 // unknown command
86 {NULL, NULL}
87 };
88
89 int SimpleShell::reset_delay_secs = 0;
90
91 // Adam Greens heap walk from http://mbed.org/forum/mbed/topic/2701/?page=4#comment-22556
92 static uint32_t heapWalk(StreamOutput *stream, bool verbose)
93 {
94 uint32_t chunkNumber = 1;
95 // The __end__ linker symbol points to the beginning of the heap.
96 uint32_t chunkCurr = (uint32_t)&__end__;
97 // __malloc_free_list is the head pointer to newlib-nano's link list of free chunks.
98 uint32_t freeCurr = __malloc_free_list;
99 // Calling _sbrk() with 0 reserves no more memory but it returns the current top of heap.
100 uint32_t heapEnd = _sbrk(0);
101 // accumulate totals
102 uint32_t freeSize = 0;
103 uint32_t usedSize = 0;
104
105 stream->printf("Used Heap Size: %lu\n", heapEnd - chunkCurr);
106
107 // Walk through the chunks until we hit the end of the heap.
108 while (chunkCurr < heapEnd) {
109 // Assume the chunk is in use. Will update later.
110 int isChunkFree = 0;
111 // The first 32-bit word in a chunk is the size of the allocation. newlib-nano over allocates by 8 bytes.
112 // 4 bytes for this 32-bit chunk size and another 4 bytes to allow for 8 byte-alignment of returned pointer.
113 uint32_t chunkSize = *(uint32_t *)chunkCurr;
114 // The start of the next chunk is right after the end of this one.
115 uint32_t chunkNext = chunkCurr + chunkSize;
116
117 // The free list is sorted by address.
118 // Check to see if we have found the next free chunk in the heap.
119 if (chunkCurr == freeCurr) {
120 // Chunk is free so flag it as such.
121 isChunkFree = 1;
122 // The second 32-bit word in a free chunk is a pointer to the next free chunk (again sorted by address).
123 freeCurr = *(uint32_t *)(freeCurr + 4);
124 }
125
126 // Skip past the 32-bit size field in the chunk header.
127 chunkCurr += 4;
128 // 8-byte align the data pointer.
129 chunkCurr = (chunkCurr + 7) & ~7;
130 // newlib-nano over allocates by 8 bytes, 4 bytes for the 32-bit chunk size and another 4 bytes to allow for 8
131 // byte-alignment of the returned pointer.
132 chunkSize -= 8;
133 if (verbose)
134 stream->printf(" Chunk: %lu Address: 0x%08lX Size: %lu %s\n", chunkNumber, chunkCurr, chunkSize, isChunkFree ? "CHUNK FREE" : "");
135
136 if (isChunkFree) freeSize += chunkSize;
137 else usedSize += chunkSize;
138
139 chunkCurr = chunkNext;
140 chunkNumber++;
141 }
142 stream->printf("Allocated: %lu, Free: %lu\r\n", usedSize, freeSize);
143 return freeSize;
144 }
145
146
147 void SimpleShell::on_module_loaded()
148 {
149 this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
150 this->register_for_event(ON_GCODE_RECEIVED);
151 this->register_for_event(ON_SECOND_TICK);
152
153 reset_delay_secs = 0;
154 }
155
156 void SimpleShell::on_second_tick(void *)
157 {
158 // we are timing out for the reset
159 if (reset_delay_secs > 0) {
160 if (--reset_delay_secs == 0) {
161 system_reset(false);
162 }
163 }
164 }
165
166 void SimpleShell::on_gcode_received(void *argument)
167 {
168 Gcode *gcode = static_cast<Gcode *>(argument);
169 string args = get_arguments(gcode->get_command());
170
171 if (gcode->has_m) {
172 if (gcode->m == 20) { // list sd card
173 gcode->stream->printf("Begin file list\r\n");
174 ls_command("/sd", gcode->stream);
175 gcode->stream->printf("End file list\r\n");
176
177 } else if (gcode->m == 30) { // remove file
178 rm_command("/sd/" + args, gcode->stream);
179
180 } else if(gcode->m == 501) { // load config override
181 if(args.empty()) {
182 load_command("/sd/config-override", gcode->stream);
183 } else {
184 load_command("/sd/config-override." + args, gcode->stream);
185 }
186
187 } else if(gcode->m == 504) { // save to specific config override file
188 if(args.empty()) {
189 save_command("/sd/config-override", gcode->stream);
190 } else {
191 save_command("/sd/config-override." + args, gcode->stream);
192 }
193 }
194 }
195 }
196
197 bool SimpleShell::parse_command(const char *cmd, string args, StreamOutput *stream)
198 {
199 for (const ptentry_t *p = commands_table; p->command != NULL; ++p) {
200 if (strncasecmp(cmd, p->command, strlen(p->command)) == 0) {
201 p->func(args, stream);
202 return true;
203 }
204 }
205
206 return false;
207 }
208
209 // When a new line is received, check if it is a command, and if it is, act upon it
210 void SimpleShell::on_console_line_received( void *argument )
211 {
212 SerialMessage new_message = *static_cast<SerialMessage *>(argument);
213 string possible_command = new_message.message;
214
215 // ignore anything that is not lowercase or a $ as it is not a command
216 if(possible_command.size() == 0 || (!islower(possible_command[0]) && possible_command[0] != '$')) {
217 return;
218 }
219
220 // it is a grbl compatible command
221 if(possible_command[0] == '$' && possible_command.size() >= 2) {
222 switch(possible_command[1]) {
223 case 'G':
224 // issue get state
225 get_command("state", new_message.stream);
226 break;
227
228 case 'X':
229 THEKERNEL->call_event(ON_HALT, (void *)1); // clears on_halt
230 new_message.stream->printf("[Caution: Unlocked]\n");
231 break;
232
233 case '#':
234 grblDP_command("", new_message.stream);
235 break;
236
237 case 'H':
238 if(THEKERNEL->is_grbl_mode()) {
239 THEKERNEL->call_event(ON_HALT, (void *)1); // clears on_halt
240 // issue G28.2 which is force homing cycle
241 Gcode gcode("G28.2", new_message.stream);
242 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gcode);
243 }else{
244 new_message.stream->printf("error:only supported in GRBL mode\n");
245 }
246 break;
247
248 default:
249 new_message.stream->printf("error:Invalid statement\n");
250 break;
251 }
252
253 }else{
254
255 //new_message.stream->printf("Received %s\r\n", possible_command.c_str());
256 string cmd = shift_parameter(possible_command);
257
258 // Configurator commands
259 if (cmd == "config-get"){
260 THEKERNEL->configurator->config_get_command( possible_command, new_message.stream );
261
262 } else if (cmd == "config-set"){
263 THEKERNEL->configurator->config_set_command( possible_command, new_message.stream );
264
265 } else if (cmd == "config-load"){
266 THEKERNEL->configurator->config_load_command( possible_command, new_message.stream );
267
268 } else if (cmd == "play" || cmd == "progress" || cmd == "abort" || cmd == "suspend" || cmd == "resume") {
269
270 } else if (cmd == "ok") {
271 // probably an echo so reply ok
272 new_message.stream->printf("ok\n");
273
274 }else if(!parse_command(cmd.c_str(), possible_command, new_message.stream)) {
275 new_message.stream->printf("error:Unsupported command - %s\n", cmd.c_str());
276 }
277 }
278 }
279
280 // Act upon an ls command
281 // Convert the first parameter into an absolute path, then list the files in that path
282 void SimpleShell::ls_command( string parameters, StreamOutput *stream )
283 {
284 string path, opts;
285 while(!parameters.empty()) {
286 string s = shift_parameter( parameters );
287 if(s.front() == '-') {
288 opts.append(s);
289 } else {
290 path = s;
291 if(!parameters.empty()) {
292 path.append(" ");
293 path.append(parameters);
294 }
295 break;
296 }
297 }
298
299 path = absolute_from_relative(path);
300
301 DIR *d;
302 struct dirent *p;
303 d = opendir(path.c_str());
304 if (d != NULL) {
305 while ((p = readdir(d)) != NULL) {
306 stream->printf("%s", lc(string(p->d_name)).c_str());
307 if(p->d_isdir) {
308 stream->printf("/");
309 } else if(opts.find("-s", 0, 2) != string::npos) {
310 stream->printf(" %d", p->d_fsize);
311 }
312 stream->printf("\r\n");
313 }
314 closedir(d);
315 } else {
316 stream->printf("Could not open directory %s\r\n", path.c_str());
317 }
318 }
319
320 extern SDFAT mounter;
321
322 void SimpleShell::remount_command( string parameters, StreamOutput *stream )
323 {
324 mounter.remount();
325 stream->printf("remounted\r\n");
326 }
327
328 // Delete a file
329 void SimpleShell::rm_command( string parameters, StreamOutput *stream )
330 {
331 const char *fn = absolute_from_relative(shift_parameter( parameters )).c_str();
332 int s = remove(fn);
333 if (s != 0) stream->printf("Could not delete %s \r\n", fn);
334 }
335
336 // Rename a file
337 void SimpleShell::mv_command( string parameters, StreamOutput *stream )
338 {
339 string from = absolute_from_relative(shift_parameter( parameters ));
340 string to = absolute_from_relative(shift_parameter(parameters));
341 int s = rename(from.c_str(), to.c_str());
342 if (s != 0) stream->printf("Could not rename %s to %s\r\n", from.c_str(), to.c_str());
343 else stream->printf("renamed %s to %s\r\n", from.c_str(), to.c_str());
344 }
345
346 // Change current absolute path to provided path
347 void SimpleShell::cd_command( string parameters, StreamOutput *stream )
348 {
349 string folder = absolute_from_relative( parameters );
350
351 DIR *d;
352 d = opendir(folder.c_str());
353 if (d == NULL) {
354 stream->printf("Could not open directory %s \r\n", folder.c_str() );
355 } else {
356 THEKERNEL->current_path = folder;
357 closedir(d);
358 }
359 }
360
361 // Responds with the present working directory
362 void SimpleShell::pwd_command( string parameters, StreamOutput *stream )
363 {
364 stream->printf("%s\r\n", THEKERNEL->current_path.c_str());
365 }
366
367 // Output the contents of a file, first parameter is the filename, second is the limit ( in number of lines to output )
368 void SimpleShell::cat_command( string parameters, StreamOutput *stream )
369 {
370 // Get parameters ( filename and line limit )
371 string filename = absolute_from_relative(shift_parameter( parameters ));
372 string limit_parameter = shift_parameter( parameters );
373 int limit = -1;
374 int delay= 0;
375 bool send_eof= false;
376 if ( limit_parameter == "-d" ) {
377 string d= shift_parameter( parameters );
378 char *e = NULL;
379 delay = strtol(d.c_str(), &e, 10);
380 if (e <= d.c_str()) {
381 delay = 0;
382
383 } else {
384 send_eof= true; // we need to terminate file send with an eof
385 }
386
387 }else if ( limit_parameter != "" ) {
388 char *e = NULL;
389 limit = strtol(limit_parameter.c_str(), &e, 10);
390 if (e <= limit_parameter.c_str())
391 limit = -1;
392 }
393
394 // we have been asked to delay before cat, probably to allow time to issue upload command
395 if(delay > 0) {
396 safe_delay(delay*1000);
397 }
398
399 // Open file
400 FILE *lp = fopen(filename.c_str(), "r");
401 if (lp == NULL) {
402 stream->printf("File not found: %s\r\n", filename.c_str());
403 return;
404 }
405 string buffer;
406 int c;
407 int newlines = 0;
408 int linecnt = 0;
409 // Print each line of the file
410 while ((c = fgetc (lp)) != EOF) {
411 buffer.append((char *)&c, 1);
412 if ( c == '\n' || ++linecnt > 80) {
413 if(c == '\n') newlines++;
414 stream->puts(buffer.c_str());
415 buffer.clear();
416 if(linecnt > 80) linecnt = 0;
417 // we need to kick things or they die
418 THEKERNEL->call_event(ON_IDLE);
419 }
420 if ( newlines == limit ) {
421 break;
422 }
423 };
424 fclose(lp);
425
426 if(send_eof) {
427 stream->puts("\032"); // ^Z terminates the upload
428 }
429 }
430
431 void SimpleShell::upload_command( string parameters, StreamOutput *stream )
432 {
433 // this needs to be a hack. it needs to read direct from serial and not allow on_main_loop run until done
434 // NOTE this will block all operation until the upload is complete, so do not do while printing
435 if(!THEKERNEL->conveyor->is_queue_empty()) {
436 stream->printf("upload not allowed while printing or busy\n");
437 return;
438 }
439
440 // open file to upload to
441 string upload_filename = absolute_from_relative( parameters );
442 FILE *fd = fopen(upload_filename.c_str(), "w");
443 if(fd != NULL) {
444 stream->printf("uploading to file: %s, send control-D or control-Z to finish\r\n", upload_filename.c_str());
445 } else {
446 stream->printf("failed to open file: %s.\r\n", upload_filename.c_str());
447 return;
448 }
449
450 int cnt = 0;
451 bool uploading = true;
452 while(uploading) {
453 if(!stream->ready()) {
454 // we need to kick things or they die
455 THEKERNEL->call_event(ON_IDLE);
456 continue;
457 }
458
459 char c = stream->_getc();
460 if( c == 4 || c == 26) { // ctrl-D or ctrl-Z
461 uploading = false;
462 // close file
463 fclose(fd);
464 stream->printf("uploaded %d bytes\n", cnt);
465 return;
466
467 } else {
468 // write character to file
469 cnt++;
470 if(fputc(c, fd) != c) {
471 // error writing to file
472 stream->printf("error writing to file. ignoring all characters until EOF\r\n");
473 fclose(fd);
474 fd = NULL;
475 uploading= false;
476
477 } else {
478 if ((cnt%400) == 0) {
479 // HACK ALERT to get around fwrite corruption close and re open for append
480 fclose(fd);
481 fd = fopen(upload_filename.c_str(), "a");
482 // we need to kick things or they die
483 THEKERNEL->call_event(ON_IDLE);
484 }
485 }
486 }
487 }
488 // we got an error so ignore everything until EOF
489 char c;
490 do {
491 if(stream->ready()) {
492 c= stream->_getc();
493 }else{
494 THEKERNEL->call_event(ON_IDLE);
495 c= 0;
496 }
497 } while(c != 4 && c != 26);
498 }
499
500 // loads the specified config-override file
501 void SimpleShell::load_command( string parameters, StreamOutput *stream )
502 {
503 // Get parameters ( filename )
504 string filename = absolute_from_relative(parameters);
505 if(filename == "/") {
506 filename = THEKERNEL->config_override_filename();
507 }
508
509 FILE *fp = fopen(filename.c_str(), "r");
510 if(fp != NULL) {
511 char buf[132];
512 stream->printf("Loading config override file: %s...\n", filename.c_str());
513 while(fgets(buf, sizeof buf, fp) != NULL) {
514 stream->printf(" %s", buf);
515 if(buf[0] == ';') continue; // skip the comments
516 struct SerialMessage message = {&(StreamOutput::NullStream), buf};
517 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message);
518 }
519 stream->printf("config override file executed\n");
520 fclose(fp);
521
522 } else {
523 stream->printf("File not found: %s\n", filename.c_str());
524 }
525 }
526
527 // saves the specified config-override file
528 void SimpleShell::save_command( string parameters, StreamOutput *stream )
529 {
530 // Get parameters ( filename )
531 string filename = absolute_from_relative(parameters);
532 if(filename == "/") {
533 filename = THEKERNEL->config_override_filename();
534 }
535
536 THEKERNEL->conveyor->wait_for_empty_queue(); //just to be safe as it can take a while to run
537
538 //remove(filename.c_str()); // seems to cause a hang every now and then
539 {
540 FileStream fs(filename.c_str());
541 fs.printf("; DO NOT EDIT THIS FILE\n");
542 // this also will truncate the existing file instead of deleting it
543 }
544
545 // stream that appends to file
546 AppendFileStream *gs = new AppendFileStream(filename.c_str());
547 // if(!gs->is_open()) {
548 // stream->printf("Unable to open File %s for write\n", filename.c_str());
549 // return;
550 // }
551
552 __disable_irq();
553 // issue a M500 which will store values in the file stream
554 Gcode *gcode = new Gcode("M500", gs);
555 THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
556 delete gs;
557 delete gcode;
558 __enable_irq();
559
560 stream->printf("Settings Stored to %s\r\n", filename.c_str());
561 }
562
563 // show free memory
564 void SimpleShell::mem_command( string parameters, StreamOutput *stream)
565 {
566 bool verbose = shift_parameter( parameters ).find_first_of("Vv") != string::npos ;
567 unsigned long heap = (unsigned long)_sbrk(0);
568 unsigned long m = g_maximumHeapAddress - heap;
569 stream->printf("Unused Heap: %lu bytes\r\n", m);
570
571 uint32_t f = heapWalk(stream, verbose);
572 stream->printf("Total Free RAM: %lu bytes\r\n", m + f);
573
574 stream->printf("Free AHB0: %lu, AHB1: %lu\r\n", AHB0.free(), AHB1.free());
575 if (verbose) {
576 AHB0.debug(stream);
577 AHB1.debug(stream);
578 }
579 }
580
581 static uint32_t getDeviceType()
582 {
583 #define IAP_LOCATION 0x1FFF1FF1
584 uint32_t command[1];
585 uint32_t result[5];
586 typedef void (*IAP)(uint32_t *, uint32_t *);
587 IAP iap = (IAP) IAP_LOCATION;
588
589 __disable_irq();
590
591 command[0] = 54;
592 iap(command, result);
593
594 __enable_irq();
595
596 return result[1];
597 }
598
599 // get network config
600 void SimpleShell::net_command( string parameters, StreamOutput *stream)
601 {
602 void *returned_data;
603 bool ok = PublicData::get_value( network_checksum, get_ipconfig_checksum, &returned_data );
604 if(ok) {
605 char *str = (char *)returned_data;
606 stream->printf("%s\r\n", str);
607 free(str);
608
609 } else {
610 stream->printf("No network detected\n");
611 }
612 }
613
614 // print out build version
615 void SimpleShell::version_command( string parameters, StreamOutput *stream)
616 {
617 Version vers;
618 uint32_t dev = getDeviceType();
619 const char *mcu = (dev & 0x00100000) ? "LPC1769" : "LPC1768";
620 stream->printf("Build version: %s, Build date: %s, MCU: %s, System Clock: %ldMHz\r\n", vers.get_build(), vers.get_build_date(), mcu, SystemCoreClock / 1000000);
621 }
622
623 // Reset the system
624 void SimpleShell::reset_command( string parameters, StreamOutput *stream)
625 {
626 stream->printf("Smoothie out. Peace. Rebooting in 5 seconds...\r\n");
627 reset_delay_secs = 5; // reboot in 5 seconds
628 }
629
630 // go into dfu boot mode
631 void SimpleShell::dfu_command( string parameters, StreamOutput *stream)
632 {
633 stream->printf("Entering boot mode...\r\n");
634 system_reset(true);
635 }
636
637 // Break out into the MRI debugging system
638 void SimpleShell::break_command( string parameters, StreamOutput *stream)
639 {
640 stream->printf("Entering MRI debug mode...\r\n");
641 __debugbreak();
642 }
643
644 static int get_active_tool()
645 {
646 void *returned_data;
647 bool ok = PublicData::get_value(tool_manager_checksum, get_active_tool_checksum, &returned_data);
648 if (ok) {
649 int active_tool= *static_cast<int *>(returned_data);
650 return active_tool;
651 } else {
652 return 0;
653 }
654 }
655
656 void SimpleShell::grblDP_command( string parameters, StreamOutput *stream)
657 {
658 /*
659 [G54:95.000,40.000,-23.600]
660 [G55:0.000,0.000,0.000]
661 [G56:0.000,0.000,0.000]
662 [G57:0.000,0.000,0.000]
663 [G58:0.000,0.000,0.000]
664 [G59:0.000,0.000,0.000]
665 [G28:0.000,0.000,0.000]
666 [G30:0.000,0.000,0.000]
667 [G92:0.000,0.000,0.000]
668 [TLO:0.000]
669 [PRB:0.000,0.000,0.000:0]
670 */
671 std::vector<Robot::wcs_t> v= THEKERNEL->robot->get_wcs_state();
672 int n= std::get<1>(v[0]);
673 for (int i = 1; i <= n; ++i) {
674 stream->printf("[%s:%1.4f,%1.4f,%1.4f]\n", wcs2gcode(i-1).c_str(), std::get<0>(v[i]), std::get<1>(v[i]), std::get<2>(v[i]));
675 }
676
677 float *rd;
678 PublicData::get_value( endstops_checksum, saved_position_checksum, &rd );
679 stream->printf("[G28:%1.4f,%1.4f,%1.4f]\n", rd[0], rd[1], rd[2]);
680 stream->printf("[G30:%1.4f,%1.4f,%1.4f]\n", 0.0F, 0.0F, 0.0F); // not implemented
681
682 stream->printf("[G92:%1.4f,%1.4f,%1.4f]\n", std::get<0>(v[n+1]), std::get<1>(v[n+1]), std::get<2>(v[n+1]));
683 stream->printf("[TL0:%1.4f]\n", std::get<2>(v[n+2]));
684
685 // this is the last probe position, updated when a probe completes, also stores the number of steps moved after a homing cycle
686 float px, py, pz;
687 uint8_t ps;
688 std::tie(px, py, pz, ps) = THEKERNEL->robot->get_last_probe_position();
689 stream->printf("[PRB:%1.4f,%1.4f,%1.4f:%d]\n", px, py, pz, ps);
690 }
691
692 void SimpleShell::get_command( string parameters, StreamOutput *stream)
693 {
694 string what = shift_parameter( parameters );
695
696 if (what == "temp") {
697 struct pad_temperature temp;
698 string type = shift_parameter( parameters );
699 if(type.empty()) {
700 // scan all temperature controls
701 std::vector<struct pad_temperature> controllers;
702 bool ok = PublicData::get_value(temperature_control_checksum, poll_controls_checksum, &controllers);
703 if (ok) {
704 for (auto &c : controllers) {
705 stream->printf("%s (%d) temp: %f/%f @%d\r\n", c.designator.c_str(), c.id, c.current_temperature, c.target_temperature, c.pwm);
706 }
707
708 } else {
709 stream->printf("no heaters found\r\n");
710 }
711
712 }else{
713 bool ok = PublicData::get_value( temperature_control_checksum, current_temperature_checksum, get_checksum(type), &temp );
714
715 if (ok) {
716 stream->printf("%s temp: %f/%f @%d\r\n", type.c_str(), temp.current_temperature, temp.target_temperature, temp.pwm);
717 } else {
718 stream->printf("%s is not a known temperature device\r\n", type.c_str());
719 }
720 }
721
722 } else if (what == "fk" || what == "ik") {
723 string p= shift_parameter( parameters );
724 bool move= false;
725 if(p == "-m") {
726 move= true;
727 p= shift_parameter( parameters );
728 }
729
730 std::vector<float> v= parse_number_list(p.c_str());
731 if(p.empty() || v.size() < 1) {
732 stream->printf("error:usage: get [fk|ik] [-m] x[,y,z]\n");
733 return;
734 }
735
736 float x= v[0];
737 float y= (v.size() > 1) ? v[1] : x;
738 float z= (v.size() > 2) ? v[2] : y;
739
740 if(what == "fk") {
741 // do forward kinematics on the given actuator position and display the cartesian coordinates
742 ActuatorCoordinates apos{x, y, z};
743 float pos[3];
744 THEKERNEL->robot->arm_solution->actuator_to_cartesian(apos, pos);
745 stream->printf("cartesian= X %f, Y %f, Z %f, Steps= A %lu, B %lu, C %lu\n",
746 pos[0], pos[1], pos[2],
747 lroundf(x*THEKERNEL->robot->actuators[0]->get_steps_per_mm()),
748 lroundf(y*THEKERNEL->robot->actuators[1]->get_steps_per_mm()),
749 lroundf(z*THEKERNEL->robot->actuators[2]->get_steps_per_mm()));
750 x= pos[0];
751 y= pos[1];
752 z= pos[2];
753
754 }else{
755 // do inverse kinematics on the given cartesian position and display the actuator coordinates
756 float pos[3]{x, y, z};
757 ActuatorCoordinates apos;
758 THEKERNEL->robot->arm_solution->cartesian_to_actuator(pos, apos);
759 stream->printf("actuator= A %f, B %f, C %f\n", apos[0], apos[1], apos[2]);
760 }
761
762 if(move) {
763 // move to the calculated, or given, XYZ
764 char cmd[64];
765 snprintf(cmd, sizeof(cmd), "G53 G0 X%f Y%f Z%f", x, y, z);
766 struct SerialMessage message;
767 message.message = cmd;
768 message.stream = &(StreamOutput::NullStream);
769 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
770 THEKERNEL->conveyor->wait_for_empty_queue();
771 }
772
773 } else if (what == "pos") {
774 // convenience to call all the various M114 variants
775 char buf[64];
776 THEKERNEL->robot->print_position(0, buf, sizeof buf); stream->printf("last %s\n", buf);
777 THEKERNEL->robot->print_position(1, buf, sizeof buf); stream->printf("realtime %s\n", buf);
778 THEKERNEL->robot->print_position(2, buf, sizeof buf); stream->printf("%s\n", buf);
779 THEKERNEL->robot->print_position(3, buf, sizeof buf); stream->printf("%s\n", buf);
780 THEKERNEL->robot->print_position(4, buf, sizeof buf); stream->printf("%s\n", buf);
781 THEKERNEL->robot->print_position(5, buf, sizeof buf); stream->printf("%s\n", buf);
782
783 } else if (what == "wcs") {
784 // print the wcs state
785 std::vector<Robot::wcs_t> v= THEKERNEL->robot->get_wcs_state();
786 char current_wcs= std::get<0>(v[0]);
787 stream->printf("current WCS: %s\n", wcs2gcode(current_wcs).c_str());
788 int n= std::get<1>(v[0]);
789 for (int i = 1; i <= n; ++i) {
790 stream->printf("%s: %f, %f, %f\n", wcs2gcode(i-1).c_str(), std::get<0>(v[i]), std::get<1>(v[i]), std::get<2>(v[i]));
791 }
792
793 stream->printf("G92: %f, %f, %f\n", std::get<0>(v[n+1]), std::get<1>(v[n+1]), std::get<2>(v[n+1]));
794 stream->printf("ToolOffset: %f, %f, %f\n", std::get<0>(v[n+2]), std::get<1>(v[n+2]), std::get<2>(v[n+2]));
795
796 } else if (what == "state") {
797 // also $G
798 // [G0 G54 G17 G21 G90 G94 M0 M5 M9 T0 F0.]
799 stream->printf("[G%d %s G%d G%d G%d G94 M0 M5 M9 T%d F%1.4f]\n",
800 THEKERNEL->gcode_dispatch->get_modal_command(),
801 wcs2gcode(THEKERNEL->robot->get_current_wcs()).c_str(),
802 THEKERNEL->robot->plane_axis_0 == X_AXIS && THEKERNEL->robot->plane_axis_1 == Y_AXIS && THEKERNEL->robot->plane_axis_2 == Z_AXIS ? 17 :
803 THEKERNEL->robot->plane_axis_0 == X_AXIS && THEKERNEL->robot->plane_axis_1 == Z_AXIS && THEKERNEL->robot->plane_axis_2 == Y_AXIS ? 18 :
804 THEKERNEL->robot->plane_axis_0 == Y_AXIS && THEKERNEL->robot->plane_axis_1 == Z_AXIS && THEKERNEL->robot->plane_axis_2 == X_AXIS ? 19 : 17,
805 THEKERNEL->robot->inch_mode ? 20 : 21,
806 THEKERNEL->robot->absolute_mode ? 90 : 91,
807 get_active_tool(),
808 THEKERNEL->robot->get_feed_rate());
809
810 } else {
811 stream->printf("error:unknown option %s\n", what.c_str());
812 }
813 }
814
815 // used to test out the get public data events
816 void SimpleShell::set_temp_command( string parameters, StreamOutput *stream)
817 {
818 string type = shift_parameter( parameters );
819 string temp = shift_parameter( parameters );
820 float t = temp.empty() ? 0.0 : strtof(temp.c_str(), NULL);
821 bool ok = PublicData::set_value( temperature_control_checksum, get_checksum(type), &t );
822
823 if (ok) {
824 stream->printf("%s temp set to: %3.1f\r\n", type.c_str(), t);
825 } else {
826 stream->printf("%s is not a known temperature device\r\n", type.c_str());
827 }
828 }
829
830 void SimpleShell::print_thermistors_command( string parameters, StreamOutput *stream)
831 {
832 Thermistor::print_predefined_thermistors(stream);
833 }
834
835 void SimpleShell::calc_thermistor_command( string parameters, StreamOutput *stream)
836 {
837 string s = shift_parameter( parameters );
838 int saveto= -1;
839 // see if we have -sn as first argument
840 if(s.find("-s", 0, 2) != string::npos) {
841 // save the results to thermistor n
842 saveto= strtol(s.substr(2).c_str(), nullptr, 10);
843 }else{
844 parameters= s;
845 }
846
847 std::vector<float> trl= parse_number_list(parameters.c_str());
848 if(trl.size() == 6) {
849 // calculate the coefficients
850 float c1, c2, c3;
851 std::tie(c1, c2, c3) = Thermistor::calculate_steinhart_hart_coefficients(trl[0], trl[1], trl[2], trl[3], trl[4], trl[5]);
852 stream->printf("Steinhart Hart coefficients: I%1.18f J%1.18f K%1.18f\n", c1, c2, c3);
853 if(saveto == -1) {
854 stream->printf(" Paste the above in the M305 S0 command, then save with M500\n");
855 }else{
856 char buf[80];
857 int n = snprintf(buf, sizeof(buf), "M305 S%d I%1.18f J%1.18f K%1.18f", saveto, c1, c2, c3);
858 string g(buf, n);
859 Gcode gcode(g, &(StreamOutput::NullStream));
860 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gcode );
861 stream->printf(" Setting Thermistor %d to those settings, save with M500\n", saveto);
862 }
863
864 }else{
865 // give help
866 stream->printf("Usage: calc_thermistor T1,R1,T2,R2,T3,R3\n");
867 }
868 }
869
870 // used to test out the get public data events for switch
871 void SimpleShell::switch_command( string parameters, StreamOutput *stream)
872 {
873 string type = shift_parameter( parameters );
874 string value = shift_parameter( parameters );
875 bool ok = false;
876 if(value == "on" || value == "off") {
877 bool b = value == "on";
878 ok = PublicData::set_value( switch_checksum, get_checksum(type), state_checksum, &b );
879 } else {
880 float v = strtof(value.c_str(), NULL);
881 ok = PublicData::set_value( switch_checksum, get_checksum(type), value_checksum, &v );
882 }
883 if (ok) {
884 stream->printf("switch %s set to: %s\r\n", type.c_str(), value.c_str());
885 } else {
886 stream->printf("%s is not a known switch device\r\n", type.c_str());
887 }
888 }
889
890 void SimpleShell::md5sum_command( string parameters, StreamOutput *stream )
891 {
892 string filename = absolute_from_relative(parameters);
893
894 // Open file
895 FILE *lp = fopen(filename.c_str(), "r");
896 if (lp == NULL) {
897 stream->printf("File not found: %s\r\n", filename.c_str());
898 return;
899 }
900 MD5 md5;
901 uint8_t buf[64];
902 do {
903 size_t n= fread(buf, 1, sizeof buf, lp);
904 if(n > 0) md5.update(buf, n);
905 THEKERNEL->call_event(ON_IDLE);
906 } while(!feof(lp));
907
908 stream->printf("%s %s\n", md5.finalize().hexdigest().c_str(), filename.c_str());
909 fclose(lp);
910 }
911
912
913
914 void SimpleShell::help_command( string parameters, StreamOutput *stream )
915 {
916 stream->printf("Commands:\r\n");
917 stream->printf("version\r\n");
918 stream->printf("mem [-v]\r\n");
919 stream->printf("ls [-s] [folder]\r\n");
920 stream->printf("cd folder\r\n");
921 stream->printf("pwd\r\n");
922 stream->printf("cat file [limit] [-d 10]\r\n");
923 stream->printf("rm file\r\n");
924 stream->printf("mv file newfile\r\n");
925 stream->printf("remount\r\n");
926 stream->printf("play file [-v]\r\n");
927 stream->printf("progress - shows progress of current play\r\n");
928 stream->printf("abort - abort currently playing file\r\n");
929 stream->printf("reset - reset smoothie\r\n");
930 stream->printf("dfu - enter dfu boot loader\r\n");
931 stream->printf("break - break into debugger\r\n");
932 stream->printf("config-get [<configuration_source>] <configuration_setting>\r\n");
933 stream->printf("config-set [<configuration_source>] <configuration_setting> <value>\r\n");
934 stream->printf("get [pos|wcs|state|fk|ik]\r\n");
935 stream->printf("get temp [bed|hotend]\r\n");
936 stream->printf("set_temp bed|hotend 185\r\n");
937 stream->printf("net\r\n");
938 stream->printf("load [file] - loads a configuration override file from soecified name or config-override\r\n");
939 stream->printf("save [file] - saves a configuration override file as specified filename or as config-override\r\n");
940 stream->printf("upload filename - saves a stream of text to the named file\r\n");
941 stream->printf("calc_thermistor [-s0] T1,R1,T2,R2,T3,R3 - calculate the Steinhart Hart coefficients for a thermistor\r\n");
942 stream->printf("thermistors - print out the predefined thermistors\r\n");
943 stream->printf("md5sum file - prints md5 sum of the given file\r\n");
944 }
945