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