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