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