Parsing of relative path corrected
[clinton/Smoothieware.git] / src / modules / utils / simpleshell / SimpleShell.cpp
CommitLineData
58baeec1
MM
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/>.
cd011f58
AW
6*/
7
8
0325af12
AW
9#include "libs/Kernel.h"
10#include "SimpleShell.h"
11#include "libs/nuts_bolts.h"
12#include "libs/utils.h"
423df6df 13#include "libs/SerialMessage.h"
838b33b4 14#include "libs/StreamOutput.h"
3fceb8eb 15#include "modules/robot/Conveyor.h"
172d42d9 16#include "DirHandle.h"
0f0b1656 17#include "mri.h"
582559c6 18#include "version.h"
8293d443 19#include "PublicDataRequest.h"
618c9b0f 20#include "FileStream.h"
0325af12 21
47339e4a 22#include "modules/tools/temperaturecontrol/TemperatureControlPublicAccess.h"
5647f709 23#include "modules/robot/RobotPublicAccess.h"
d4ee6ee2 24#include "NetworkPublicAccess.h"
a200fc31 25#include "platform_memory.h"
47339e4a 26
6187a020
JM
27extern unsigned int g_maximumHeapAddress;
28
ecc610a4
JM
29#include <malloc.h>
30#include <mri.h>
31#include <stdio.h>
32#include <stdint.h>
33
34extern "C" uint32_t __end__;
35extern "C" uint32_t __malloc_free_list;
36extern "C" uint32_t _sbrk(int size);
37
9e403697
JM
38#define get_temp_command_checksum CHECKSUM("temp")
39#define get_pos_command_checksum CHECKSUM("pos")
40
41// command lookup table
42SimpleShell::ptentry_t SimpleShell::commands_table[] = {
43 {CHECKSUM("ls"), &SimpleShell::ls_command},
44 {CHECKSUM("cd"), &SimpleShell::cd_command},
45 {CHECKSUM("pwd"), &SimpleShell::pwd_command},
46 {CHECKSUM("cat"), &SimpleShell::cat_command},
47 {CHECKSUM("rm"), &SimpleShell::rm_command},
48 {CHECKSUM("reset"), &SimpleShell::reset_command},
49 {CHECKSUM("dfu"), &SimpleShell::dfu_command},
50 {CHECKSUM("break"), &SimpleShell::break_command},
51 {CHECKSUM("help"), &SimpleShell::help_command},
d4ee6ee2 52 {CHECKSUM("?"), &SimpleShell::help_command},
9e403697
JM
53 {CHECKSUM("version"), &SimpleShell::version_command},
54 {CHECKSUM("mem"), &SimpleShell::mem_command},
55 {CHECKSUM("get"), &SimpleShell::get_command},
56 {CHECKSUM("set_temp"), &SimpleShell::set_temp_command},
d4ee6ee2 57 {CHECKSUM("net"), &SimpleShell::net_command},
618c9b0f
JM
58 {CHECKSUM("load"), &SimpleShell::load_command},
59 {CHECKSUM("save"), &SimpleShell::save_command},
9e403697
JM
60
61 // unknown command
62 {0, NULL}
63};
ecc610a4
JM
64
65// Adam Greens heap walk from http://mbed.org/forum/mbed/topic/2701/?page=4#comment-22556
0c683b26 66static uint32_t heapWalk(StreamOutput *stream, bool verbose)
ecc610a4
JM
67{
68 uint32_t chunkNumber = 1;
69 // The __end__ linker symbol points to the beginning of the heap.
70 uint32_t chunkCurr = (uint32_t)&__end__;
71 // __malloc_free_list is the head pointer to newlib-nano's link list of free chunks.
72 uint32_t freeCurr = __malloc_free_list;
73 // Calling _sbrk() with 0 reserves no more memory but it returns the current top of heap.
74 uint32_t heapEnd = _sbrk(0);
75 // accumulate totals
9e403697
JM
76 uint32_t freeSize = 0;
77 uint32_t usedSize = 0;
ecc610a4
JM
78
79 stream->printf("Used Heap Size: %lu\n", heapEnd - chunkCurr);
80
81 // Walk through the chunks until we hit the end of the heap.
9e403697 82 while (chunkCurr < heapEnd) {
ecc610a4
JM
83 // Assume the chunk is in use. Will update later.
84 int isChunkFree = 0;
85 // The first 32-bit word in a chunk is the size of the allocation. newlib-nano over allocates by 8 bytes.
86 // 4 bytes for this 32-bit chunk size and another 4 bytes to allow for 8 byte-alignment of returned pointer.
9e403697 87 uint32_t chunkSize = *(uint32_t *)chunkCurr;
ecc610a4
JM
88 // The start of the next chunk is right after the end of this one.
89 uint32_t chunkNext = chunkCurr + chunkSize;
90
91 // The free list is sorted by address.
92 // Check to see if we have found the next free chunk in the heap.
9e403697 93 if (chunkCurr == freeCurr) {
ecc610a4
JM
94 // Chunk is free so flag it as such.
95 isChunkFree = 1;
96 // The second 32-bit word in a free chunk is a pointer to the next free chunk (again sorted by address).
9e403697 97 freeCurr = *(uint32_t *)(freeCurr + 4);
ecc610a4
JM
98 }
99
100 // Skip past the 32-bit size field in the chunk header.
101 chunkCurr += 4;
102 // 8-byte align the data pointer.
103 chunkCurr = (chunkCurr + 7) & ~7;
104 // newlib-nano over allocates by 8 bytes, 4 bytes for the 32-bit chunk size and another 4 bytes to allow for 8
105 // byte-alignment of the returned pointer.
106 chunkSize -= 8;
9e403697 107 if (verbose)
ecc610a4
JM
108 stream->printf(" Chunk: %lu Address: 0x%08lX Size: %lu %s\n", chunkNumber, chunkCurr, chunkSize, isChunkFree ? "CHUNK FREE" : "");
109
9e403697 110 if (isChunkFree) freeSize += chunkSize;
ecc610a4
JM
111 else usedSize += chunkSize;
112
113 chunkCurr = chunkNext;
114 chunkNumber++;
115 }
116 stream->printf("Allocated: %lu, Free: %lu\r\n", usedSize, freeSize);
0c683b26 117 return freeSize;
ecc610a4
JM
118}
119
120
9e403697
JM
121void SimpleShell::on_module_loaded()
122{
0325af12
AW
123 this->current_path = "/";
124 this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
d4ee6ee2
JM
125 this->register_for_event(ON_GCODE_RECEIVED);
126 this->register_for_event(ON_SECOND_TICK);
c4e56997 127
d4ee6ee2 128 this->reset_delay_secs = 0;
ead17727
JM
129}
130
9e403697
JM
131void SimpleShell::on_second_tick(void *)
132{
ead17727 133 // we are timing out for the reset
5895ead3 134 if (this->reset_delay_secs > 0) {
9e403697 135 if (--this->reset_delay_secs == 0) {
ead17727
JM
136 system_reset(false);
137 }
138 }
0325af12
AW
139}
140
9e403697
JM
141void SimpleShell::on_gcode_received(void *argument)
142{
143 Gcode *gcode = static_cast<Gcode *>(argument);
3a238fdc 144 string args= get_arguments(gcode->command);
c4e56997
JM
145
146 if (gcode->has_m) {
147 if (gcode->m == 20) { // list sd card
148 gcode->mark_as_taken();
149 gcode->stream->printf("Begin file list\r\n");
150 ls_command("/sd", gcode->stream);
151 gcode->stream->printf("End file list\r\n");
d4ee6ee2
JM
152
153 } else if (gcode->m == 30) { // remove file
3a238fdc
CG
154 gcode->mark_as_taken();
155 rm_command("/sd/" + args, gcode->stream);
618c9b0f
JM
156
157 }else if(gcode->m == 501) { // load config override
158 gcode->mark_as_taken();
159 if(args.empty()) {
160 load_command("/sd/config-override", gcode->stream);
161 }else{
162 load_command("/sd/config-override." + args, gcode->stream);
163 }
164
165 }else if(gcode->m == 504) { // save to specific config override file
166 gcode->mark_as_taken();
167 if(args.empty()) {
168 save_command("/sd/config-override", gcode->stream);
169 }else{
170 save_command("/sd/config-override." + args, gcode->stream);
171 }
3a238fdc 172 }
c4e56997
JM
173 }
174}
175
9e403697
JM
176bool SimpleShell::parse_command(unsigned short cs, string args, StreamOutput *stream)
177{
178 for (ptentry_t *p = commands_table; p->pfunc != NULL; ++p) {
179 if (cs == p->command_cs) {
180 PFUNC fnc= p->pfunc;
181 (this->*fnc)(args, stream);
182 return true;
183 }
184 }
185
186 return false;
187}
188
0325af12 189// When a new line is received, check if it is a command, and if it is, act upon it
9e403697
JM
190void SimpleShell::on_console_line_received( void *argument )
191{
192 SerialMessage new_message = *static_cast<SerialMessage *>(argument);
7f613782
JM
193
194 // ignore comments
9e403697 195 if (new_message.message[0] == ';') return;
7f613782 196
b6c86164 197 string possible_command = new_message.message;
0325af12 198
3add9a23
AW
199 //new_message.stream->printf("Received %s\r\n", possible_command.c_str());
200
9e403697 201 unsigned short check_sum = get_checksum( possible_command.substr(0, possible_command.find_first_of(" \r\n")) ); // todo: put this method somewhere more convenient
6187a020 202
9e403697
JM
203 // find command and execute it
204 parse_command(check_sum, get_arguments(possible_command), new_message.stream);
0325af12
AW
205}
206
0325af12 207// Convert a path indication ( absolute or relative ) into a path ( absolute )
9e403697
JM
208string SimpleShell::absolute_from_relative( string path )
209{
6bcd4886 210 string cwd = this->current_path;
211
212 if ( path.empty() ) {
213 return this->current_path;
214 }
215
216 if ( path[0] == '/' ) {
9e403697
JM
217 return path;
218 }
6bcd4886 219
220 string match = "../" ;
221 while ( path.substr(0,3) == match ) {
222 path = path.substr(3);
223 unsigned found = cwd.find_last_of("/");
224 cwd = cwd.substr(0,found);
9e403697 225 }
6bcd4886 226
227 match = ".." ;
228 if ( path.substr(0,2) == match ) {
229 path = path.substr(2);
230 unsigned found = cwd.find_last_of("/");
231 cwd = cwd.substr(0,found);
232 }
233
234 if ( cwd[cwd.length() - 1] == '/' ) {
235 return cwd + path;
236 }
237
238 return cwd + '/' + path;
0325af12
AW
239}
240
241// Act upon an ls command
242// Convert the first parameter into an absolute path, then list the files in that path
9e403697
JM
243void SimpleShell::ls_command( string parameters, StreamOutput *stream )
244{
0325af12 245 string folder = this->absolute_from_relative( parameters );
9e403697
JM
246 DIR *d;
247 struct dirent *p;
0325af12 248 d = opendir(folder.c_str());
9e403697
JM
249 if (d != NULL) {
250 while ((p = readdir(d)) != NULL) {
251 stream->printf("%s\r\n", lc(string(p->d_name)).c_str());
252 }
ed7c5844 253 closedir(d);
0325af12 254 } else {
b6c86164 255 stream->printf("Could not open directory %s \r\n", folder.c_str());
0325af12
AW
256 }
257}
258
9e403697
JM
259// Delete a file
260void SimpleShell::rm_command( string parameters, StreamOutput *stream )
261{
262 const char *fn= this->absolute_from_relative(shift_parameter( parameters )).c_str();
263 int s = remove(fn);
264 if (s != 0) stream->printf("Could not delete %s \r\n", fn);
265}
266
0325af12 267// Change current absolute path to provided path
9e403697
JM
268void SimpleShell::cd_command( string parameters, StreamOutput *stream )
269{
0325af12 270 string folder = this->absolute_from_relative( parameters );
6bcd4886 271
0325af12 272 DIR *d;
0325af12 273 d = opendir(folder.c_str());
9e403697 274 if (d == NULL) {
58baeec1 275 stream->printf("Could not open directory %s \r\n", folder.c_str() );
9e403697 276 } else {
ed7c5844
JM
277 this->current_path = folder;
278 closedir(d);
0325af12
AW
279 }
280}
281
b7250484 282// Responds with the present working directory
9e403697
JM
283void SimpleShell::pwd_command( string parameters, StreamOutput *stream )
284{
b7250484
L
285 stream->printf("%s\r\n", this->current_path.c_str());
286}
287
0325af12 288// Output the contents of a file, first parameter is the filename, second is the limit ( in number of lines to output )
9e403697
JM
289void SimpleShell::cat_command( string parameters, StreamOutput *stream )
290{
58baeec1 291 // Get parameters ( filename and line limit )
0325af12
AW
292 string filename = this->absolute_from_relative(shift_parameter( parameters ));
293 string limit_paramater = shift_parameter( parameters );
294 int limit = -1;
9e403697
JM
295 if ( limit_paramater != "" ) {
296 char *e = NULL;
f7e6f459
MM
297 limit = strtol(limit_paramater.c_str(), &e, 10);
298 if (e <= limit_paramater.c_str())
299 limit = -1;
300 }
58baeec1
MM
301
302 // Open file
0325af12 303 FILE *lp = fopen(filename.c_str(), "r");
9e403697 304 if (lp == NULL) {
58baeec1
MM
305 stream->printf("File not found: %s\r\n", filename.c_str());
306 return;
9ed670c5 307 }
0325af12
AW
308 string buffer;
309 int c;
58baeec1 310 int newlines = 0;
dfb15d68 311 int linecnt= 0;
0325af12 312 // Print each line of the file
9e403697 313 while ((c = fgetc (lp)) != EOF) {
58baeec1 314 buffer.append((char *)&c, 1);
dfb15d68 315 if ( char(c) == '\n' || ++linecnt > 80) {
58baeec1 316 newlines++;
d728799b 317 stream->puts(buffer.c_str());
58baeec1 318 buffer.clear();
dfb15d68 319 if(linecnt > 80) linecnt= 0;
68b7afb4 320 }
9e403697
JM
321 if ( newlines == limit ) {
322 break;
323 }
58baeec1 324 };
0325af12
AW
325 fclose(lp);
326
327}
328
618c9b0f
JM
329// loads the specified config-override file
330void SimpleShell::load_command( string parameters, StreamOutput *stream )
331{
332 // Get parameters ( filename )
333 string filename = this->absolute_from_relative(parameters);
334 if(filename == "/") {
335 filename = THEKERNEL->config_override_filename();
336 }
337
338 FILE *fp= fopen(filename.c_str(), "r");
339 if(fp != NULL) {
340 char buf[132];
341 stream->printf("Loading config override file: %s...\n", filename.c_str());
342 while(fgets(buf, sizeof buf, fp) != NULL) {
343 stream->printf(" %s", buf);
344 if(buf[0] == ';') continue; // skip the comments
345 struct SerialMessage message= {&(StreamOutput::NullStream), buf};
346 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message);
347 }
348 stream->printf("config override file executed\n");
349 fclose(fp);
350
351 }else{
352 stream->printf("File not found: %s\n", filename.c_str());
353 }
354}
355
356// saves the specified config-override file
357void SimpleShell::save_command( string parameters, StreamOutput *stream )
358{
359 // Get parameters ( filename )
360 string filename = this->absolute_from_relative(parameters);
361 if(filename == "/") {
362 filename = THEKERNEL->config_override_filename();
363 }
364
365 // replace stream with one that writes to config-override file
366 FileStream *gs = new FileStream(filename.c_str());
367 if(!gs->is_open()) {
368 stream->printf("Unable to open File %s for write\n", filename.c_str());
369 return;
370 }
371
372 // issue a M500 which will store values in the file stream
373 Gcode *gcode = new Gcode("M500", gs);
374 THEKERNEL->call_event(ON_GCODE_RECEIVED, gcode );
375 delete gs;
376 delete gcode;
377
378 stream->printf("Settings Stored to %s\r\n", filename.c_str());
379}
380
6187a020 381// show free memory
9e403697
JM
382void SimpleShell::mem_command( string parameters, StreamOutput *stream)
383{
384 bool verbose = shift_parameter( parameters ).find_first_of("Vv") != string::npos ;
385 unsigned long heap = (unsigned long)_sbrk(0);
386 unsigned long m = g_maximumHeapAddress - heap;
ecc610a4
JM
387 stream->printf("Unused Heap: %lu bytes\r\n", m);
388
0c683b26
JM
389 uint32_t f= heapWalk(stream, verbose);
390 stream->printf("Total Free RAM: %lu bytes\r\n", m + f);
a200fc31 391
0c683b26 392 stream->printf("Free AHB0: %lu, AHB1: %lu\r\n", AHB0.free(), AHB1.free());
1803076a
MM
393 if (verbose)
394 {
395 AHB0.debug(stream);
396 AHB1.debug(stream);
397 }
6187a020
JM
398}
399
9e403697
JM
400static uint32_t getDeviceType()
401{
402#define IAP_LOCATION 0x1FFF1FF1
01f35bcc
JM
403 uint32_t command[1];
404 uint32_t result[5];
9e403697 405 typedef void (*IAP)(uint32_t *, uint32_t *);
01f35bcc
JM
406 IAP iap = (IAP) IAP_LOCATION;
407
408 __disable_irq();
409
410 command[0] = 54;
411 iap(command, result);
412
413 __enable_irq();
414
415 return result[1];
416}
417
d4ee6ee2
JM
418// get network config
419void SimpleShell::net_command( string parameters, StreamOutput *stream)
420{
421 void *returned_data;
422 bool ok= THEKERNEL->public_data->get_value( network_checksum, get_ipconfig_checksum, &returned_data );
423 if(ok) {
424 char *str= (char *)returned_data;
425 stream->printf("%s\r\n", str);
426 free(str);
427
428 }else{
429 stream->printf("No network detected\n");
430 }
431}
432
582559c6 433// print out build version
9e403697
JM
434void SimpleShell::version_command( string parameters, StreamOutput *stream)
435{
582559c6 436 Version vers;
9e403697
JM
437 uint32_t dev = getDeviceType();
438 const char *mcu = (dev & 0x00100000) ? "LPC1769" : "LPC1768";
01f35bcc 439 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);
582559c6
JM
440}
441
77983aa1 442// Reset the system
9e403697
JM
443void SimpleShell::reset_command( string parameters, StreamOutput *stream)
444{
ead17727 445 stream->printf("Smoothie out. Peace. Rebooting in 5 seconds...\r\n");
9e403697 446 this->reset_delay_secs = 5; // reboot in 5 seconds
2742fca9
JM
447}
448
449// go into dfu boot mode
9e403697
JM
450void SimpleShell::dfu_command( string parameters, StreamOutput *stream)
451{
ed7c5844
JM
452 stream->printf("Entering boot mode...\r\n");
453 system_reset(true);
77983aa1
L
454}
455
0f0b1656 456// Break out into the MRI debugging system
9e403697
JM
457void SimpleShell::break_command( string parameters, StreamOutput *stream)
458{
0f0b1656
L
459 stream->printf("Entering MRI debug mode...\r\n");
460 __debugbreak();
461}
462
8293d443 463// used to test out the get public data events
9e403697
JM
464void SimpleShell::get_command( string parameters, StreamOutput *stream)
465{
466 int what = get_checksum(shift_parameter( parameters ));
b55cfff1 467 void *returned_data;
c4e56997 468
9e403697
JM
469 if (what == get_temp_command_checksum) {
470 string type = shift_parameter( parameters );
314ab8f7 471 bool ok = THEKERNEL->public_data->get_value( temperature_control_checksum, get_checksum(type), current_temperature_checksum, &returned_data );
b55cfff1 472
9e403697
JM
473 if (ok) {
474 struct pad_temperature temp = *static_cast<struct pad_temperature *>(returned_data);
b55cfff1 475 stream->printf("%s temp: %f/%f @%d\r\n", type.c_str(), temp.current_temperature, temp.target_temperature, temp.pwm);
9e403697 476 } else {
b55cfff1
JM
477 stream->printf("%s is not a known temperature device\r\n", type.c_str());
478 }
c4e56997 479
9e403697 480 } else if (what == get_pos_command_checksum) {
314ab8f7 481 bool ok = THEKERNEL->public_data->get_value( robot_checksum, current_position_checksum, &returned_data );
b55cfff1 482
9e403697 483 if (ok) {
1ad23cd3 484 float *pos = static_cast<float *>(returned_data);
b55cfff1 485 stream->printf("Position X: %f, Y: %f, Z: %f\r\n", pos[0], pos[1], pos[2]);
c4e56997 486
9e403697 487 } else {
b55cfff1
JM
488 stream->printf("get pos command failed\r\n");
489 }
490 }
8293d443
JM
491}
492
77047e76 493// used to test out the get public data events
9e403697
JM
494void SimpleShell::set_temp_command( string parameters, StreamOutput *stream)
495{
496 string type = shift_parameter( parameters );
497 string temp = shift_parameter( parameters );
04211969 498 float t = temp.empty() ? 0.0 : strtof(temp.c_str(), NULL);
314ab8f7 499 bool ok = THEKERNEL->public_data->set_value( temperature_control_checksum, get_checksum(type), &t );
991d98cc 500
9e403697 501 if (ok) {
991d98cc 502 stream->printf("%s temp set to: %3.1f\r\n", type.c_str(), t);
9e403697 503 } else {
991d98cc
JM
504 stream->printf("%s is not a known temperature device\r\n", type.c_str());
505 }
77047e76
JM
506}
507
9e403697
JM
508void SimpleShell::help_command( string parameters, StreamOutput *stream )
509{
ed7c5844 510 stream->printf("Commands:\r\n");
582559c6 511 stream->printf("version\r\n");
ecc610a4 512 stream->printf("mem [-v]\r\n");
ed7c5844
JM
513 stream->printf("ls [folder]\r\n");
514 stream->printf("cd folder\r\n");
c4e56997 515 stream->printf("pwd\r\n");
ed7c5844 516 stream->printf("cat file [limit]\r\n");
9e403697 517 stream->printf("rm file\r\n");
4eb0e279 518 stream->printf("play file [-v]\r\n");
ed7c5844
JM
519 stream->printf("progress - shows progress of current play\r\n");
520 stream->printf("abort - abort currently playing file\r\n");
c4e56997
JM
521 stream->printf("reset - reset smoothie\r\n");
522 stream->printf("dfu - enter dfu boot loader\r\n");
523 stream->printf("break - break into debugger\r\n");
ed7c5844
JM
524 stream->printf("config-get [<configuration_source>] <configuration_setting>\r\n");
525 stream->printf("config-set [<configuration_source>] <configuration_setting> <value>\r\n");
526 stream->printf("config-load [<file_name>]\r\n");
5647f709 527 stream->printf("get temp [bed|hotend]\r\n");
991d98cc 528 stream->printf("set_temp bed|hotend 185\r\n");
b55cfff1 529 stream->printf("get pos\r\n");
d4ee6ee2 530 stream->printf("net\r\n");
618c9b0f
JM
531 stream->printf("load [file] - loads a configuration override file from soecified name or config-override\r\n");
532 stream->printf("save [file] - saves a configuration override file as specified filename or as config-override\r\n");
235a7435
JM
533}
534