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