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