added mv command to simpleshell
[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 "FileStream.h"
21 #include "checksumm.h"
22 #include "PublicData.h"
23 #include "Gcode.h"
24
25 #include "modules/tools/temperaturecontrol/TemperatureControlPublicAccess.h"
26 #include "modules/robot/RobotPublicAccess.h"
27 #include "NetworkPublicAccess.h"
28 #include "platform_memory.h"
29 #include "SwitchPublicAccess.h"
30 #include "SDFAT.h"
31
32 #include "system_LPC17xx.h"
33 #include "LPC17xx.h"
34
35 extern unsigned int g_maximumHeapAddress;
36
37 #include <malloc.h>
38 #include <mri.h>
39 #include <stdio.h>
40 #include <stdint.h>
41
42 extern "C" uint32_t __end__;
43 extern "C" uint32_t __malloc_free_list;
44 extern "C" uint32_t _sbrk(int size);
45
46 // command lookup table
47 const SimpleShell::ptentry_t SimpleShell::commands_table[] = {
48 {"ls", SimpleShell::ls_command},
49 {"cd", SimpleShell::cd_command},
50 {"pwd", SimpleShell::pwd_command},
51 {"cat", SimpleShell::cat_command},
52 {"rm", SimpleShell::rm_command},
53 {"mv", SimpleShell::mv_command},
54 {"upload", SimpleShell::upload_command},
55 {"reset", SimpleShell::reset_command},
56 {"dfu", SimpleShell::dfu_command},
57 {"break", SimpleShell::break_command},
58 {"help", SimpleShell::help_command},
59 {"?", SimpleShell::help_command},
60 {"version", SimpleShell::version_command},
61 {"mem", SimpleShell::mem_command},
62 {"get", SimpleShell::get_command},
63 {"set_temp", SimpleShell::set_temp_command},
64 {"switch", SimpleShell::switch_command},
65 {"net", SimpleShell::net_command},
66 {"load", SimpleShell::load_command},
67 {"save", SimpleShell::save_command},
68 {"remount", SimpleShell::remount_command},
69
70 // unknown command
71 {NULL, NULL}
72 };
73
74 int SimpleShell::reset_delay_secs = 0;
75
76 // Adam Greens heap walk from http://mbed.org/forum/mbed/topic/2701/?page=4#comment-22556
77 static uint32_t heapWalk(StreamOutput *stream, bool verbose)
78 {
79 uint32_t chunkNumber = 1;
80 // The __end__ linker symbol points to the beginning of the heap.
81 uint32_t chunkCurr = (uint32_t)&__end__;
82 // __malloc_free_list is the head pointer to newlib-nano's link list of free chunks.
83 uint32_t freeCurr = __malloc_free_list;
84 // Calling _sbrk() with 0 reserves no more memory but it returns the current top of heap.
85 uint32_t heapEnd = _sbrk(0);
86 // accumulate totals
87 uint32_t freeSize = 0;
88 uint32_t usedSize = 0;
89
90 stream->printf("Used Heap Size: %lu\n", heapEnd - chunkCurr);
91
92 // Walk through the chunks until we hit the end of the heap.
93 while (chunkCurr < heapEnd) {
94 // Assume the chunk is in use. Will update later.
95 int isChunkFree = 0;
96 // The first 32-bit word in a chunk is the size of the allocation. newlib-nano over allocates by 8 bytes.
97 // 4 bytes for this 32-bit chunk size and another 4 bytes to allow for 8 byte-alignment of returned pointer.
98 uint32_t chunkSize = *(uint32_t *)chunkCurr;
99 // The start of the next chunk is right after the end of this one.
100 uint32_t chunkNext = chunkCurr + chunkSize;
101
102 // The free list is sorted by address.
103 // Check to see if we have found the next free chunk in the heap.
104 if (chunkCurr == freeCurr) {
105 // Chunk is free so flag it as such.
106 isChunkFree = 1;
107 // The second 32-bit word in a free chunk is a pointer to the next free chunk (again sorted by address).
108 freeCurr = *(uint32_t *)(freeCurr + 4);
109 }
110
111 // Skip past the 32-bit size field in the chunk header.
112 chunkCurr += 4;
113 // 8-byte align the data pointer.
114 chunkCurr = (chunkCurr + 7) & ~7;
115 // newlib-nano over allocates by 8 bytes, 4 bytes for the 32-bit chunk size and another 4 bytes to allow for 8
116 // byte-alignment of the returned pointer.
117 chunkSize -= 8;
118 if (verbose)
119 stream->printf(" Chunk: %lu Address: 0x%08lX Size: %lu %s\n", chunkNumber, chunkCurr, chunkSize, isChunkFree ? "CHUNK FREE" : "");
120
121 if (isChunkFree) freeSize += chunkSize;
122 else usedSize += chunkSize;
123
124 chunkCurr = chunkNext;
125 chunkNumber++;
126 }
127 stream->printf("Allocated: %lu, Free: %lu\r\n", usedSize, freeSize);
128 return freeSize;
129 }
130
131
132 void SimpleShell::on_module_loaded()
133 {
134 this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
135 this->register_for_event(ON_GCODE_RECEIVED);
136 this->register_for_event(ON_SECOND_TICK);
137
138 reset_delay_secs = 0;
139 }
140
141 void SimpleShell::on_second_tick(void *)
142 {
143 // we are timing out for the reset
144 if (reset_delay_secs > 0) {
145 if (--reset_delay_secs == 0) {
146 system_reset(false);
147 }
148 }
149 }
150
151 void SimpleShell::on_gcode_received(void *argument)
152 {
153 Gcode *gcode = static_cast<Gcode *>(argument);
154 string args = get_arguments(gcode->get_command());
155
156 if (gcode->has_m) {
157 if (gcode->m == 20) { // list sd card
158 gcode->mark_as_taken();
159 gcode->stream->printf("Begin file list\r\n");
160 ls_command("/sd", gcode->stream);
161 gcode->stream->printf("End file list\r\n");
162
163 } else if (gcode->m == 30) { // remove file
164 gcode->mark_as_taken();
165 rm_command("/sd/" + args, gcode->stream);
166
167 } else if(gcode->m == 501) { // load config override
168 gcode->mark_as_taken();
169 if(args.empty()) {
170 load_command("/sd/config-override", gcode->stream);
171 } else {
172 load_command("/sd/config-override." + args, gcode->stream);
173 }
174
175 } else if(gcode->m == 504) { // save to specific config override file
176 gcode->mark_as_taken();
177 if(args.empty()) {
178 save_command("/sd/config-override", gcode->stream);
179 } else {
180 save_command("/sd/config-override." + args, gcode->stream);
181 }
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
203 // ignore comments and blank lines and if this is a G code then also ignore it
204 char first_char = new_message.message[0];
205 if(strchr(";( \n\rGMTN", first_char) != NULL) return;
206
207 string possible_command = new_message.message;
208
209 //new_message.stream->printf("Received %s\r\n", possible_command.c_str());
210 string cmd = shift_parameter(possible_command);
211
212 // find command and execute it
213 parse_command(cmd.c_str(), possible_command, new_message.stream);
214 }
215
216 // Act upon an ls command
217 // Convert the first parameter into an absolute path, then list the files in that path
218 void SimpleShell::ls_command( string parameters, StreamOutput *stream )
219 {
220 string path, opts;
221 while(!parameters.empty()) {
222 string s = shift_parameter( parameters );
223 if(s.front() == '-') {
224 opts.append(s);
225 } else {
226 path = s;
227 if(!parameters.empty()) {
228 path.append(" ");
229 path.append(parameters);
230 }
231 break;
232 }
233 }
234
235 path = absolute_from_relative(path);
236
237 DIR *d;
238 struct dirent *p;
239 d = opendir(path.c_str());
240 if (d != NULL) {
241 while ((p = readdir(d)) != NULL) {
242 stream->printf("%s", lc(string(p->d_name)).c_str());
243 if(p->d_isdir) {
244 stream->printf("/");
245 } else if(opts.find("-s", 0, 2) != string::npos) {
246 stream->printf(" %d", p->d_fsize);
247 }
248 stream->printf("\r\n");
249 }
250 closedir(d);
251 } else {
252 stream->printf("Could not open directory %s\r\n", path.c_str());
253 }
254 }
255
256 extern SDFAT mounter;
257
258 void SimpleShell::remount_command( string parameters, StreamOutput *stream )
259 {
260 mounter.remount();
261 stream->printf("remounted\r\n");
262 }
263
264 // Delete a file
265 void SimpleShell::rm_command( string parameters, StreamOutput *stream )
266 {
267 const char *fn = absolute_from_relative(shift_parameter( parameters )).c_str();
268 int s = remove(fn);
269 if (s != 0) stream->printf("Could not delete %s \r\n", fn);
270 }
271
272 // Rename a file
273 void SimpleShell::mv_command( string parameters, StreamOutput *stream )
274 {
275 string from = absolute_from_relative(shift_parameter( parameters ));
276 string to = shift_parameter(parameters);
277 int s = rename(from.c_str(), to.c_str());
278 if (s != 0) stream->printf("Could not rename %s to %s\r\n", from.c_str(), to.c_str());
279 else stream->printf("renamed %s to %s\r\n", from.c_str(), to.c_str());
280 }
281
282 // Change current absolute path to provided path
283 void SimpleShell::cd_command( string parameters, StreamOutput *stream )
284 {
285 string folder = absolute_from_relative( parameters );
286
287 DIR *d;
288 d = opendir(folder.c_str());
289 if (d == NULL) {
290 stream->printf("Could not open directory %s \r\n", folder.c_str() );
291 } else {
292 THEKERNEL->current_path = folder;
293 closedir(d);
294 }
295 }
296
297 // Responds with the present working directory
298 void SimpleShell::pwd_command( string parameters, StreamOutput *stream )
299 {
300 stream->printf("%s\r\n", THEKERNEL->current_path.c_str());
301 }
302
303 // Output the contents of a file, first parameter is the filename, second is the limit ( in number of lines to output )
304 void SimpleShell::cat_command( string parameters, StreamOutput *stream )
305 {
306 // Get parameters ( filename and line limit )
307 string filename = absolute_from_relative(shift_parameter( parameters ));
308 string limit_paramater = shift_parameter( parameters );
309 int limit = -1;
310 if ( limit_paramater != "" ) {
311 char *e = NULL;
312 limit = strtol(limit_paramater.c_str(), &e, 10);
313 if (e <= limit_paramater.c_str())
314 limit = -1;
315 }
316
317 // Open file
318 FILE *lp = fopen(filename.c_str(), "r");
319 if (lp == NULL) {
320 stream->printf("File not found: %s\r\n", filename.c_str());
321 return;
322 }
323 string buffer;
324 int c;
325 int newlines = 0;
326 int linecnt = 0;
327 // Print each line of the file
328 while ((c = fgetc (lp)) != EOF) {
329 buffer.append((char *)&c, 1);
330 if ( char(c) == '\n' || ++linecnt > 80) {
331 newlines++;
332 stream->puts(buffer.c_str());
333 buffer.clear();
334 if(linecnt > 80) linecnt = 0;
335 }
336 if ( newlines == limit ) {
337 break;
338 }
339 };
340 fclose(lp);
341 }
342
343 void SimpleShell::upload_command( string parameters, StreamOutput *stream )
344 {
345 // this needs to be a hack. it needs to read direct from serial and not allow on_main_loop run until done
346 // NOTE this will block all operation until the upload is complete, so do not do while printing
347 if(!THEKERNEL->conveyor->is_queue_empty()) {
348 stream->printf("upload not allowed while printing or busy\n");
349 return;
350 }
351
352 // open file to upload to
353 string upload_filename = absolute_from_relative( parameters );
354 FILE *fd = fopen(upload_filename.c_str(), "w");
355 if(fd != NULL) {
356 stream->printf("uploading to file: %s, send control-D or control-Z to finish\r\n", upload_filename.c_str());
357 } else {
358 stream->printf("failed to open file: %s.\r\n", upload_filename.c_str());
359 return;
360 }
361
362 int cnt = 0;
363 bool uploading = true;
364 while(uploading) {
365 if(!stream->ready()) {
366 // we need to kick things or they die
367 THEKERNEL->call_event(ON_IDLE);
368 continue;
369 }
370
371 char c = stream->_getc();
372 if( c == 4 || c == 26) { // ctrl-D or ctrl-Z
373 uploading = false;
374 // close file
375 fclose(fd);
376 stream->printf("uploaded %d bytes\n", cnt);
377 return;
378
379 } else {
380 // write character to file
381 cnt++;
382 if(fputc(c, fd) != c) {
383 // error writing to file
384 stream->printf("error writing to file. ignoring all characters until EOF\r\n");
385 fclose(fd);
386 fd = NULL;
387 uploading= false;
388
389 } else {
390 if ((cnt%400) == 0) {
391 // HACK ALERT to get around fwrite corruption close and re open for append
392 fclose(fd);
393 fd = fopen(upload_filename.c_str(), "a");
394 }
395 }
396 }
397 }
398 // we got an error so ignore everything until EOF
399 char c;
400 do {
401 if(stream->ready()) {
402 c= stream->_getc();
403 }else{
404 THEKERNEL->call_event(ON_IDLE);
405 c= 0;
406 }
407 } while(c != 4 && c != 26);
408 }
409
410 // loads the specified config-override file
411 void SimpleShell::load_command( string parameters, StreamOutput *stream )
412 {
413 // Get parameters ( filename )
414 string filename = absolute_from_relative(parameters);
415 if(filename == "/") {
416 filename = THEKERNEL->config_override_filename();
417 }
418
419 FILE *fp = fopen(filename.c_str(), "r");
420 if(fp != NULL) {
421 char buf[132];
422 stream->printf("Loading config override file: %s...\n", filename.c_str());
423 while(fgets(buf, sizeof buf, fp) != NULL) {
424 stream->printf(" %s", buf);
425 if(buf[0] == ';') continue; // skip the comments
426 struct SerialMessage message = {&(StreamOutput::NullStream), buf};
427 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message);
428 }
429 stream->printf("config override file executed\n");
430 fclose(fp);
431
432 } else {
433 stream->printf("File not found: %s\n", filename.c_str());
434 }
435 }
436
437 // saves the specified config-override file
438 void SimpleShell::save_command( string parameters, StreamOutput *stream )
439 {
440 // Get parameters ( filename )
441 string filename = absolute_from_relative(parameters);
442 if(filename == "/") {
443 filename = THEKERNEL->config_override_filename();
444 }
445
446 // replace stream with one that writes to config-override file
447 FileStream *gs = new FileStream(filename.c_str());
448 if(!gs->is_open()) {
449 stream->printf("Unable to open File %s for write\n", filename.c_str());
450 return;
451 }
452
453 // issue a M500 which will store values in the file stream
454 Gcode *gcode = new Gcode("M500", gs);
455 THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
456 delete gs;
457 delete gcode;
458
459 stream->printf("Settings Stored to %s\r\n", filename.c_str());
460 }
461
462 // show free memory
463 void SimpleShell::mem_command( string parameters, StreamOutput *stream)
464 {
465 bool verbose = shift_parameter( parameters ).find_first_of("Vv") != string::npos ;
466 unsigned long heap = (unsigned long)_sbrk(0);
467 unsigned long m = g_maximumHeapAddress - heap;
468 stream->printf("Unused Heap: %lu bytes\r\n", m);
469
470 uint32_t f = heapWalk(stream, verbose);
471 stream->printf("Total Free RAM: %lu bytes\r\n", m + f);
472
473 stream->printf("Free AHB0: %lu, AHB1: %lu\r\n", AHB0.free(), AHB1.free());
474 if (verbose) {
475 AHB0.debug(stream);
476 AHB1.debug(stream);
477 }
478 }
479
480 static uint32_t getDeviceType()
481 {
482 #define IAP_LOCATION 0x1FFF1FF1
483 uint32_t command[1];
484 uint32_t result[5];
485 typedef void (*IAP)(uint32_t *, uint32_t *);
486 IAP iap = (IAP) IAP_LOCATION;
487
488 __disable_irq();
489
490 command[0] = 54;
491 iap(command, result);
492
493 __enable_irq();
494
495 return result[1];
496 }
497
498 // get network config
499 void SimpleShell::net_command( string parameters, StreamOutput *stream)
500 {
501 void *returned_data;
502 bool ok = PublicData::get_value( network_checksum, get_ipconfig_checksum, &returned_data );
503 if(ok) {
504 char *str = (char *)returned_data;
505 stream->printf("%s\r\n", str);
506 free(str);
507
508 } else {
509 stream->printf("No network detected\n");
510 }
511 }
512
513 // print out build version
514 void SimpleShell::version_command( string parameters, StreamOutput *stream)
515 {
516 Version vers;
517 uint32_t dev = getDeviceType();
518 const char *mcu = (dev & 0x00100000) ? "LPC1769" : "LPC1768";
519 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);
520 }
521
522 // Reset the system
523 void SimpleShell::reset_command( string parameters, StreamOutput *stream)
524 {
525 stream->printf("Smoothie out. Peace. Rebooting in 5 seconds...\r\n");
526 reset_delay_secs = 5; // reboot in 5 seconds
527 }
528
529 // go into dfu boot mode
530 void SimpleShell::dfu_command( string parameters, StreamOutput *stream)
531 {
532 stream->printf("Entering boot mode...\r\n");
533 system_reset(true);
534 }
535
536 // Break out into the MRI debugging system
537 void SimpleShell::break_command( string parameters, StreamOutput *stream)
538 {
539 stream->printf("Entering MRI debug mode...\r\n");
540 __debugbreak();
541 }
542
543 // used to test out the get public data events
544 void SimpleShell::get_command( string parameters, StreamOutput *stream)
545 {
546 string what = shift_parameter( parameters );
547 void *returned_data;
548
549 if (what == "temp") {
550 string type = shift_parameter( parameters );
551 bool ok = PublicData::get_value( temperature_control_checksum, get_checksum(type), current_temperature_checksum, &returned_data );
552
553 if (ok) {
554 struct pad_temperature temp = *static_cast<struct pad_temperature *>(returned_data);
555 stream->printf("%s temp: %f/%f @%d\r\n", type.c_str(), temp.current_temperature, temp.target_temperature, temp.pwm);
556 } else {
557 stream->printf("%s is not a known temperature device\r\n", type.c_str());
558 }
559
560 } else if (what == "pos") {
561 bool ok = PublicData::get_value( robot_checksum, current_position_checksum, &returned_data );
562
563 if (ok) {
564 float *pos = static_cast<float *>(returned_data);
565 stream->printf("Position X: %f, Y: %f, Z: %f\r\n", pos[0], pos[1], pos[2]);
566
567 } else {
568 stream->printf("get pos command failed\r\n");
569 }
570 }
571 }
572
573 // used to test out the get public data events
574 void SimpleShell::set_temp_command( string parameters, StreamOutput *stream)
575 {
576 string type = shift_parameter( parameters );
577 string temp = shift_parameter( parameters );
578 float t = temp.empty() ? 0.0 : strtof(temp.c_str(), NULL);
579 bool ok = PublicData::set_value( temperature_control_checksum, get_checksum(type), &t );
580
581 if (ok) {
582 stream->printf("%s temp set to: %3.1f\r\n", type.c_str(), t);
583 } else {
584 stream->printf("%s is not a known temperature device\r\n", type.c_str());
585 }
586 }
587
588 // used to test out the get public data events for switch
589 void SimpleShell::switch_command( string parameters, StreamOutput *stream)
590 {
591 string type = shift_parameter( parameters );
592 string value = shift_parameter( parameters );
593 bool ok = false;
594 if(value == "on" || value == "off") {
595 bool b = value == "on";
596 ok = PublicData::set_value( switch_checksum, get_checksum(type), state_checksum, &b );
597 } else {
598 float v = strtof(value.c_str(), NULL);
599 ok = PublicData::set_value( switch_checksum, get_checksum(type), value_checksum, &v );
600 }
601 if (ok) {
602 stream->printf("switch %s set to: %s\r\n", type.c_str(), value.c_str());
603 } else {
604 stream->printf("%s is not a known switch device\r\n", type.c_str());
605 }
606 }
607
608 void SimpleShell::help_command( string parameters, StreamOutput *stream )
609 {
610 stream->printf("Commands:\r\n");
611 stream->printf("version\r\n");
612 stream->printf("mem [-v]\r\n");
613 stream->printf("ls [-s] [folder]\r\n");
614 stream->printf("cd folder\r\n");
615 stream->printf("pwd\r\n");
616 stream->printf("cat file [limit]\r\n");
617 stream->printf("rm file\r\n");
618 stream->printf("mv file newfile\r\n");
619 stream->printf("remount\r\n");
620 stream->printf("play file [-v]\r\n");
621 stream->printf("progress - shows progress of current play\r\n");
622 stream->printf("abort - abort currently playing file\r\n");
623 stream->printf("reset - reset smoothie\r\n");
624 stream->printf("dfu - enter dfu boot loader\r\n");
625 stream->printf("break - break into debugger\r\n");
626 stream->printf("config-get [<configuration_source>] <configuration_setting>\r\n");
627 stream->printf("config-set [<configuration_source>] <configuration_setting> <value>\r\n");
628 stream->printf("get temp [bed|hotend]\r\n");
629 stream->printf("set_temp bed|hotend 185\r\n");
630 stream->printf("get pos\r\n");
631 stream->printf("net\r\n");
632 stream->printf("load [file] - loads a configuration override file from soecified name or config-override\r\n");
633 stream->printf("save [file] - saves a configuration override file as specified filename or as config-override\r\n");
634 }
635