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