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