Merge remote-tracking branch 'upstream/edge' into optimize/gcode
[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 // command lookup table
45 const 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},
63
64 // unknown command
65 {NULL, NULL}
66 };
67
68 int SimpleShell::reset_delay_secs= 0;
69
70 // Adam Greens heap walk from http://mbed.org/forum/mbed/topic/2701/?page=4#comment-22556
71 static uint32_t heapWalk(StreamOutput *stream, bool verbose)
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
81 uint32_t freeSize = 0;
82 uint32_t usedSize = 0;
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.
87 while (chunkCurr < heapEnd) {
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.
92 uint32_t chunkSize = *(uint32_t *)chunkCurr;
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.
98 if (chunkCurr == freeCurr) {
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).
102 freeCurr = *(uint32_t *)(freeCurr + 4);
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;
112 if (verbose)
113 stream->printf(" Chunk: %lu Address: 0x%08lX Size: %lu %s\n", chunkNumber, chunkCurr, chunkSize, isChunkFree ? "CHUNK FREE" : "");
114
115 if (isChunkFree) freeSize += chunkSize;
116 else usedSize += chunkSize;
117
118 chunkCurr = chunkNext;
119 chunkNumber++;
120 }
121 stream->printf("Allocated: %lu, Free: %lu\r\n", usedSize, freeSize);
122 return freeSize;
123 }
124
125
126 void SimpleShell::on_module_loaded()
127 {
128 this->register_for_event(ON_CONSOLE_LINE_RECEIVED);
129 this->register_for_event(ON_GCODE_RECEIVED);
130 this->register_for_event(ON_SECOND_TICK);
131
132 reset_delay_secs = 0;
133 }
134
135 void SimpleShell::on_second_tick(void *)
136 {
137 // we are timing out for the reset
138 if (reset_delay_secs > 0) {
139 if (--reset_delay_secs == 0) {
140 system_reset(false);
141 }
142 }
143 }
144
145 void SimpleShell::on_gcode_received(void *argument)
146 {
147 Gcode *gcode = static_cast<Gcode *>(argument);
148 string args= get_arguments(gcode->get_command());
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");
156
157 } else if (gcode->m == 30) { // remove file
158 gcode->mark_as_taken();
159 rm_command("/sd/" + args, gcode->stream);
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 }
176 }
177 }
178 }
179
180 bool SimpleShell::parse_command(const char *cmd, string args, StreamOutput *stream)
181 {
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);
185 return true;
186 }
187 }
188
189 return false;
190 }
191
192 // When a new line is received, check if it is a command, and if it is, act upon it
193 void SimpleShell::on_console_line_received( void *argument )
194 {
195 SerialMessage new_message = *static_cast<SerialMessage *>(argument);
196
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;
200
201 string possible_command = new_message.message;
202
203 //new_message.stream->printf("Received %s\r\n", possible_command.c_str());
204 string cmd = shift_parameter(possible_command);
205
206 // find command and execute it
207 parse_command(cmd.c_str(), possible_command, new_message.stream);
208 }
209
210 // Act upon an ls command
211 // Convert the first parameter into an absolute path, then list the files in that path
212 void SimpleShell::ls_command( string parameters, StreamOutput *stream )
213 {
214 string folder = absolute_from_relative( parameters );
215 DIR *d;
216 struct dirent *p;
217 d = opendir(folder.c_str());
218 if (d != NULL) {
219 while ((p = readdir(d)) != NULL) {
220 stream->printf("%s\r\n", lc(string(p->d_name)).c_str());
221 }
222 closedir(d);
223 } else {
224 stream->printf("Could not open directory %s \r\n", folder.c_str());
225 }
226 }
227
228 // Delete a file
229 void SimpleShell::rm_command( string parameters, StreamOutput *stream )
230 {
231 const char *fn= absolute_from_relative(shift_parameter( parameters )).c_str();
232 int s = remove(fn);
233 if (s != 0) stream->printf("Could not delete %s \r\n", fn);
234 }
235
236 // Change current absolute path to provided path
237 void SimpleShell::cd_command( string parameters, StreamOutput *stream )
238 {
239 string folder = absolute_from_relative( parameters );
240
241 DIR *d;
242 d = opendir(folder.c_str());
243 if (d == NULL) {
244 stream->printf("Could not open directory %s \r\n", folder.c_str() );
245 } else {
246 THEKERNEL->current_path = folder;
247 closedir(d);
248 }
249 }
250
251 // Responds with the present working directory
252 void SimpleShell::pwd_command( string parameters, StreamOutput *stream )
253 {
254 stream->printf("%s\r\n", THEKERNEL->current_path.c_str());
255 }
256
257 // Output the contents of a file, first parameter is the filename, second is the limit ( in number of lines to output )
258 void SimpleShell::cat_command( string parameters, StreamOutput *stream )
259 {
260 // Get parameters ( filename and line limit )
261 string filename = absolute_from_relative(shift_parameter( parameters ));
262 string limit_paramater = shift_parameter( parameters );
263 int limit = -1;
264 if ( limit_paramater != "" ) {
265 char *e = NULL;
266 limit = strtol(limit_paramater.c_str(), &e, 10);
267 if (e <= limit_paramater.c_str())
268 limit = -1;
269 }
270
271 // Open file
272 FILE *lp = fopen(filename.c_str(), "r");
273 if (lp == NULL) {
274 stream->printf("File not found: %s\r\n", filename.c_str());
275 return;
276 }
277 string buffer;
278 int c;
279 int newlines = 0;
280 int linecnt= 0;
281 // Print each line of the file
282 while ((c = fgetc (lp)) != EOF) {
283 buffer.append((char *)&c, 1);
284 if ( char(c) == '\n' || ++linecnt > 80) {
285 newlines++;
286 stream->puts(buffer.c_str());
287 buffer.clear();
288 if(linecnt > 80) linecnt= 0;
289 }
290 if ( newlines == limit ) {
291 break;
292 }
293 };
294 fclose(lp);
295
296 }
297
298 // loads the specified config-override file
299 void SimpleShell::load_command( string parameters, StreamOutput *stream )
300 {
301 // Get parameters ( filename )
302 string filename = absolute_from_relative(parameters);
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
326 void SimpleShell::save_command( string parameters, StreamOutput *stream )
327 {
328 // Get parameters ( filename )
329 string filename = absolute_from_relative(parameters);
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
350 // show free memory
351 void 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;
356 stream->printf("Unused Heap: %lu bytes\r\n", m);
357
358 uint32_t f= heapWalk(stream, verbose);
359 stream->printf("Total Free RAM: %lu bytes\r\n", m + f);
360
361 stream->printf("Free AHB0: %lu, AHB1: %lu\r\n", AHB0.free(), AHB1.free());
362 if (verbose)
363 {
364 AHB0.debug(stream);
365 AHB1.debug(stream);
366 }
367 }
368
369 static uint32_t getDeviceType()
370 {
371 #define IAP_LOCATION 0x1FFF1FF1
372 uint32_t command[1];
373 uint32_t result[5];
374 typedef void (*IAP)(uint32_t *, uint32_t *);
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
387 // get network config
388 void SimpleShell::net_command( string parameters, StreamOutput *stream)
389 {
390 void *returned_data;
391 bool ok= PublicData::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
402 // print out build version
403 void SimpleShell::version_command( string parameters, StreamOutput *stream)
404 {
405 Version vers;
406 uint32_t dev = getDeviceType();
407 const char *mcu = (dev & 0x00100000) ? "LPC1769" : "LPC1768";
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);
409 }
410
411 // Reset the system
412 void SimpleShell::reset_command( string parameters, StreamOutput *stream)
413 {
414 stream->printf("Smoothie out. Peace. Rebooting in 5 seconds...\r\n");
415 reset_delay_secs = 5; // reboot in 5 seconds
416 }
417
418 // go into dfu boot mode
419 void SimpleShell::dfu_command( string parameters, StreamOutput *stream)
420 {
421 stream->printf("Entering boot mode...\r\n");
422 system_reset(true);
423 }
424
425 // Break out into the MRI debugging system
426 void SimpleShell::break_command( string parameters, StreamOutput *stream)
427 {
428 stream->printf("Entering MRI debug mode...\r\n");
429 __debugbreak();
430 }
431
432 // used to test out the get public data events
433 void SimpleShell::get_command( string parameters, StreamOutput *stream)
434 {
435 string what = shift_parameter( parameters );
436 void *returned_data;
437
438 if (what == "temp") {
439 string type = shift_parameter( parameters );
440 bool ok = PublicData::get_value( temperature_control_checksum, get_checksum(type), current_temperature_checksum, &returned_data );
441
442 if (ok) {
443 struct pad_temperature temp = *static_cast<struct pad_temperature *>(returned_data);
444 stream->printf("%s temp: %f/%f @%d\r\n", type.c_str(), temp.current_temperature, temp.target_temperature, temp.pwm);
445 } else {
446 stream->printf("%s is not a known temperature device\r\n", type.c_str());
447 }
448
449 } else if (what == "pos") {
450 bool ok = PublicData::get_value( robot_checksum, current_position_checksum, &returned_data );
451
452 if (ok) {
453 float *pos = static_cast<float *>(returned_data);
454 stream->printf("Position X: %f, Y: %f, Z: %f\r\n", pos[0], pos[1], pos[2]);
455
456 } else {
457 stream->printf("get pos command failed\r\n");
458 }
459 }
460 }
461
462 // used to test out the get public data events
463 void SimpleShell::set_temp_command( string parameters, StreamOutput *stream)
464 {
465 string type = shift_parameter( parameters );
466 string temp = shift_parameter( parameters );
467 float t = temp.empty() ? 0.0 : strtof(temp.c_str(), NULL);
468 bool ok = PublicData::set_value( temperature_control_checksum, get_checksum(type), &t );
469
470 if (ok) {
471 stream->printf("%s temp set to: %3.1f\r\n", type.c_str(), t);
472 } else {
473 stream->printf("%s is not a known temperature device\r\n", type.c_str());
474 }
475 }
476
477 void SimpleShell::help_command( string parameters, StreamOutput *stream )
478 {
479 stream->printf("Commands:\r\n");
480 stream->printf("version\r\n");
481 stream->printf("mem [-v]\r\n");
482 stream->printf("ls [folder]\r\n");
483 stream->printf("cd folder\r\n");
484 stream->printf("pwd\r\n");
485 stream->printf("cat file [limit]\r\n");
486 stream->printf("rm file\r\n");
487 stream->printf("play file [-v]\r\n");
488 stream->printf("progress - shows progress of current play\r\n");
489 stream->printf("abort - abort currently playing file\r\n");
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");
493 stream->printf("config-get [<configuration_source>] <configuration_setting>\r\n");
494 stream->printf("config-set [<configuration_source>] <configuration_setting> <value>\r\n");
495 stream->printf("get temp [bed|hotend]\r\n");
496 stream->printf("set_temp bed|hotend 185\r\n");
497 stream->printf("get pos\r\n");
498 stream->printf("net\r\n");
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");
501 }
502