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