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