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