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