Fix doc path
[opentx.git] / radio / src / cli.cpp
blob7897138e6232d2d17829d240fd826c4f6db98920
1 /*
2 * Copyright (C) OpenTX
4 * Based on code named
5 * th9x - http://code.google.com/p/th9x
6 * er9x - http://code.google.com/p/er9x
7 * gruvin9x - http://code.google.com/p/gruvin9x
9 * License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
21 #include "opentx.h"
22 #include "diskio.h"
23 #include <ctype.h>
24 #include <malloc.h>
25 #include <new>
27 #define CLI_COMMAND_MAX_ARGS 8
28 #define CLI_COMMAND_MAX_LEN 256
30 OS_TID cliTaskId;
31 TaskStack<CLI_STACK_SIZE> _ALIGNED(8) cliStack; // stack must be aligned to 8 bytes otherwise printf for %f does not work!
32 Fifo<uint8_t, 256> cliRxFifo;
33 uint8_t cliTracesEnabled = true;
34 char cliLastLine[CLI_COMMAND_MAX_LEN+1];
36 typedef int (* CliFunction) (const char ** args);
37 int cliExecLine(char * line);
38 int cliExecCommand(const char ** argv);
39 int cliHelp(const char ** argv);
41 struct CliCommand
43 const char * name;
44 CliFunction func;
45 const char * args;
48 struct MemArea
50 const char * name;
51 void * start;
52 int size;
55 void cliPrompt()
57 serialPutc('>');
60 int toLongLongInt(const char ** argv, int index, long long int * val)
62 if (*argv[index] == '\0') {
63 return 0;
65 else {
66 int base = 10;
67 const char * s = argv[index];
68 if (strlen(s) > 2 && s[0] == '0' && s[1] == 'x') {
69 base = 16;
70 s = &argv[index][2];
72 char * endptr = NULL;
73 *val = strtoll(s, &endptr, base);
74 if (*endptr == '\0')
75 return 1;
76 else {
77 serialPrint("%s: Invalid argument \"%s\"", argv[0], argv[index]);
78 return -1;
83 int toInt(const char ** argv, int index, int * val)
85 long long int lval = 0;
86 int result = toLongLongInt(argv, index, &lval);
87 *val = (int)lval;
88 return result;
91 int cliBeep(const char ** argv)
93 int freq = BEEP_DEFAULT_FREQ;
94 int duration = 100;
95 if (toInt(argv, 1, &freq) >= 0 && toInt(argv, 2, &duration) >= 0) {
96 audioQueue.playTone(freq, duration, 20, PLAY_NOW);
98 return 0;
101 int cliPlay(const char ** argv)
103 audioQueue.playFile(argv[1], PLAY_NOW);
104 return 0;
107 int cliLs(const char ** argv)
109 FILINFO fno;
110 DIR dir;
112 FRESULT res = f_opendir(&dir, argv[1]); /* Open the directory */
113 if (res == FR_OK) {
114 for (;;) {
115 res = f_readdir(&dir, &fno); /* Read a directory item */
116 if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */
117 serialPrint(fno.fname);
119 f_closedir(&dir);
121 else {
122 serialPrint("%s: Invalid directory \"%s\"", argv[0], argv[1]);
124 return 0;
127 int cliRead(const char ** argv)
129 FIL file;
130 uint32_t bytesRead = 0;
131 int bufferSize;
132 if (toInt(argv, 2, &bufferSize) == 0 || bufferSize < 0 ) {
133 serialPrint("%s: Invalid buffer size \"%s\"", argv[0], argv[2]);
134 return 0;
137 uint8_t * buffer = (uint8_t*) malloc(bufferSize);
138 if (!buffer) {
139 serialPrint("Not enough memory");
140 return 0;
143 FRESULT result = f_open(&file, argv[1], FA_OPEN_EXISTING | FA_READ);
144 if (result != FR_OK) {
145 free(buffer);
146 serialPrint("%s: File not found \"%s\"", argv[0], argv[1]);
147 return 0;
150 tmr10ms_t start = get_tmr10ms();
152 while (true) {
153 UINT read;
154 result = f_read(&file, buffer, sizeof(buffer), &read);
155 if (result == FR_OK) {
156 if (read == 0) {
157 // end of file
158 f_close(&file);
159 break;
161 bytesRead += read;
164 uint32_t elapsedTime = (get_tmr10ms() - start) * 10;
165 if (elapsedTime == 0) elapsedTime = 1;
166 uint32_t speed = bytesRead / elapsedTime;
167 serialPrint("Read %d bytes in %d ms, speed %d kB/s", bytesRead, elapsedTime, speed);
168 free(buffer);
169 return 0;
172 int cliReadSD(const char ** argv)
174 int startSector;
175 int numberOfSectors;
176 int bufferSectors;
177 if (toInt(argv, 1, &startSector) == 0 || startSector < 0 ) {
178 serialPrint("%s: Invalid start sector \"%s\"", argv[0], argv[1]);
179 return 0;
181 if (toInt(argv, 2, &numberOfSectors) == 0 || numberOfSectors < 0 ) {
182 serialPrint("%s: Invalid number of sectors \"%s\"", argv[0], argv[2]);
183 return 0;
186 if (toInt(argv, 3, &bufferSectors) == 0 || bufferSectors < 0 ) {
187 serialPrint("%s: Invalid number of buffer sectors \"%s\"", argv[0], argv[3]);
188 return 0;
191 uint8_t * buffer = (uint8_t*) malloc(512*bufferSectors);
192 if (!buffer) {
193 serialPrint("Not enough memory");
194 return 0;
197 uint32_t bytesRead = numberOfSectors * 512;
198 tmr10ms_t start = get_tmr10ms();
200 while (numberOfSectors > 0) {
201 DRESULT res = __disk_read(0, buffer, startSector, bufferSectors);
202 if (res != RES_OK) {
203 serialPrint("disk_read error: %d, sector: %d(%d)", res, startSector, numberOfSectors);
205 #if 0
206 for(uint32_t n=0; n<bufferSectors; ++n) {
207 dump(buffer + n*512, 32);
209 #endif
210 #if 0
211 // calc checksumm
212 uint32_t summ = 0;
213 for(int n=0; n<(bufferSectors*512); ++n) {
214 summ += buffer[n];
216 serialPrint("sector %d(%d) checksumm: %u", startSector, numberOfSectors, summ);
217 #endif
218 if (numberOfSectors >= bufferSectors) {
219 numberOfSectors -= bufferSectors;
220 startSector += bufferSectors;
222 else {
223 numberOfSectors = 0;
227 uint32_t elapsedTime = (get_tmr10ms() - start) * 10;
228 if (elapsedTime == 0) elapsedTime = 1;
229 uint32_t speed = bytesRead / elapsedTime;
230 serialPrint("Read %d bytes in %d ms, speed %d kB/s", bytesRead, elapsedTime, speed);
231 free(buffer);
232 return 0;
235 int cliTestSD(const char ** argv)
237 // Do the read test on the SD card and report back the result
239 // get sector count
240 uint32_t sectorCount;
241 if (disk_ioctl(0, GET_SECTOR_COUNT, &sectorCount) != RES_OK) {
242 serialPrint("Error: can't read sector count");
243 return 0;
245 serialPrint("SD card has %u sectors", sectorCount);
247 // read last 16 sectors one sector at the time
248 serialPrint("Starting single sector read test, reading 16 sectors one by one");
249 uint8_t * buffer = (uint8_t*) malloc(512);
250 if (!buffer) {
251 serialPrint("Not enough memory");
252 return 0;
254 for (uint32_t s = sectorCount - 16; s<sectorCount; ++s) {
255 DRESULT res = __disk_read(0, buffer, s, 1);
256 if (res != RES_OK) {
257 serialPrint("sector %d read FAILED, err: %d", s, res);
259 else {
260 serialPrint("sector %d read OK", s);
263 free(buffer);
264 serialCrlf();
266 // read last 16 sectors, two sectors at the time with a multi-block read
267 buffer = (uint8_t *) malloc(512*2);
268 if (!buffer) {
269 serialPrint("Not enough memory");
270 return 0;
273 serialPrint("Starting multiple sector read test, reading two sectors at the time");
274 for (uint32_t s = sectorCount - 16; s<sectorCount; s+=2) {
275 DRESULT res = __disk_read(0, buffer, s, 2);
276 if (res != RES_OK) {
277 serialPrint("sector %d-%d read FAILED, err: %d", s, s+1, res);
279 else {
280 serialPrint("sector %d-%d read OK", s, s+1);
283 free(buffer);
284 serialCrlf();
286 // read last 16 sectors, all sectors with single multi-block read
287 buffer = (uint8_t*) malloc(512*16);
288 if (!buffer) {
289 serialPrint("Not enough memory");
290 return 0;
293 serialPrint("Starting multiple sector read test, reading 16 sectors at the time");
294 DRESULT res = __disk_read(0, buffer, sectorCount-16, 16);
295 if (res != RES_OK) {
296 serialPrint("sector %d-%d read FAILED, err: %d", sectorCount-16, sectorCount-1, res);
298 else {
299 serialPrint("sector %d-%d read OK", sectorCount-16, sectorCount-1);
301 free(buffer);
302 serialCrlf();
304 return 0;
307 int cliTestNew()
309 char * tmp = 0;
310 serialPrint("Allocating 1kB with new()");
311 CoTickDelay(100);
312 tmp = new char[1024];
313 if (tmp) {
314 serialPrint("\tsuccess");
315 delete[] tmp;
316 tmp = 0;
318 else {
319 serialPrint("\tFAILURE");
322 serialPrint("Allocating 10MB with (std::nothrow) new()");
323 CoTickDelay(100);
324 tmp = new (std::nothrow) char[1024*1024*10];
325 if (tmp) {
326 serialPrint("\tFAILURE, tmp = %p", tmp);
327 delete[] tmp;
328 tmp = 0;
330 else {
331 serialPrint("\tsuccess, allocaton failed, tmp = 0");
334 serialPrint("Allocating 10MB with new()");
335 CoTickDelay(100);
336 tmp = new char[1024*1024*10];
337 if (tmp) {
338 serialPrint("\tFAILURE, tmp = %p", tmp);
339 delete[] tmp;
340 tmp = 0;
342 else {
343 serialPrint("\tsuccess, allocaton failed, tmp = 0");
345 serialPrint("Test finished");
346 return 0;
349 #if defined(COLORLCD)
351 extern bool perMainEnabled;
352 typedef void (*graphichTestFunc)(void);
354 void testDrawSolidFilledRectangle()
356 lcdDrawFilledRect(0, 0, LCD_W, LCD_H, SOLID, TEXT_BGCOLOR);
359 void testDrawFilledRectangle()
361 lcdDrawFilledRect(0, 0, LCD_W, LCD_H, DOTTED, TEXT_BGCOLOR);
364 void testDrawSolidFilledRoundedRectangle()
366 lcdDrawFilledRect(0, 0, LCD_W/2, LCD_H/2, SOLID, ROUND|TEXT_BGCOLOR);
369 void testDrawBlackOverlay()
371 lcdDrawBlackOverlay();
374 void testDrawSolidHorizontalLine1()
376 lcdDrawSolidHorizontalLine(0, 0, 1, 0);
379 void testDrawSolidHorizontalLine2()
381 lcdDrawSolidHorizontalLine(0, 0, LCD_W, 0);
384 void testDrawSolidVerticalLine1()
386 lcdDrawSolidVerticalLine(0, 0, 1, 0);
389 void testDrawSolidVerticalLine2()
391 lcdDrawSolidVerticalLine(0, 0, LCD_H, 0);
394 void testDrawDiagonalLine()
396 lcdDrawLine(0,0, LCD_W, LCD_H, SOLID, TEXT_COLOR);
399 void testEmpty()
403 void testDrawRect()
405 lcdDrawRect(0, 0, LCD_W, LCD_H, 2, SOLID, TEXT_COLOR);
408 void testDrawText()
410 lcdDrawText(0, LCD_H/2, "The quick brown fox jumps over the lazy dog", TEXT_COLOR);
413 void testDrawTextVertical()
415 lcdDrawText(30, LCD_H, "The quick brown fox ", TEXT_COLOR|VERTICAL|NO_FONTCACHE);
418 void testClear()
420 lcdClear();
423 #define GRAPHICS_TEST_RUN_STEP 100
424 #define RUN_GRAPHICS_TEST(name, runtime) runGraphicsTest(name, #name, runtime)
426 float runGraphicsTest(graphichTestFunc func, const char * name, uint32_t runtime)
428 uint32_t start = (uint32_t)CoGetOSTime();
429 uint32_t noRuns = 0;
430 while (((uint32_t)CoGetOSTime() - start) < runtime/2 ) {
431 for (int n=0; n<GRAPHICS_TEST_RUN_STEP; n++) {
432 func();
434 lcdRefresh();
435 noRuns += GRAPHICS_TEST_RUN_STEP;
437 uint32_t actualRuntime = (uint32_t)CoGetOSTime() - start;
438 float result = (noRuns * 500.0f) / (float)actualRuntime; // runs/second
439 serialPrint("Test %s speed: %0.2f, (%d runs in %d ms)", name, result, noRuns, actualRuntime*2);
440 CoTickDelay(100);
441 return result;
444 int cliTestGraphics()
446 serialPrint("Starting graphics performance test...");
447 CoTickDelay(100);
449 watchdogSuspend(6000/*60s*/);
450 if (pulsesStarted()) {
451 pausePulses();
453 pauseMixerCalculations();
454 perMainEnabled = false;
456 float result = 0;
457 RUN_GRAPHICS_TEST(testEmpty, 1000);
458 // result += RUN_GRAPHICS_TEST(testDrawSolidHorizontalLine1, 1000);
459 result += RUN_GRAPHICS_TEST(testDrawSolidHorizontalLine2, 1000);
460 // result += RUN_GRAPHICS_TEST(testDrawSolidVerticalLine1, 1000);
461 result += RUN_GRAPHICS_TEST(testDrawSolidVerticalLine2, 1000);
462 result += RUN_GRAPHICS_TEST(testDrawDiagonalLine, 1000);
463 result += RUN_GRAPHICS_TEST(testDrawSolidFilledRectangle, 1000);
464 result += RUN_GRAPHICS_TEST(testDrawSolidFilledRoundedRectangle, 1000);
465 result += RUN_GRAPHICS_TEST(testDrawRect, 1000);
466 result += RUN_GRAPHICS_TEST(testDrawFilledRectangle, 1000);
467 result += RUN_GRAPHICS_TEST(testDrawBlackOverlay, 1000);
468 result += RUN_GRAPHICS_TEST(testDrawText, 1000);
469 result += RUN_GRAPHICS_TEST(testDrawTextVertical, 1000);
470 result += RUN_GRAPHICS_TEST(testClear, 1000);
472 serialPrint("Total speed: %0.2f", result);
474 perMainEnabled = true;
475 if (pulsesStarted()) {
476 resumePulses();
478 resumeMixerCalculations();
479 watchdogSuspend(0);
481 return 0;
484 void memoryRead(const uint8_t * src, uint32_t size)
486 // uint8_t data;
487 while(size--) {
488 /*data =*/ *(const uint8_t volatile *)src;
489 ++src;
494 void memoryRead(const uint32_t * src, uint32_t size)
496 while(size--) {
497 *(const uint32_t volatile *)src;
498 ++src;
502 uint32_t * testbuff[100];
504 void memoryCopy(uint8_t * dest, const uint8_t * src, uint32_t size)
506 while(size--) {
507 *dest = *src;
508 ++src;
509 ++dest;
513 void memoryCopy(uint32_t * dest, const uint32_t * src, uint32_t size)
515 while(size--) {
516 *dest = *src;
517 ++src;
518 ++dest;
522 #define MEMORY_SPEED_BLOCK_SIZE (4*1024)
524 void testMemoryReadFrom_RAM_8bit()
526 memoryRead((const uint8_t *)cliLastLine, MEMORY_SPEED_BLOCK_SIZE);
529 void testMemoryReadFrom_RAM_32bit()
531 memoryRead((const uint32_t *)0x20000000, MEMORY_SPEED_BLOCK_SIZE/4);
534 void testMemoryReadFrom_SDRAM_8bit()
536 memoryRead((const uint8_t *)0xD0000000, MEMORY_SPEED_BLOCK_SIZE);
539 void testMemoryReadFrom_SDRAM_32bit()
541 memoryRead((const uint32_t *)0xD0000000, MEMORY_SPEED_BLOCK_SIZE/4);
544 extern uint8_t * LCD_FIRST_FRAME_BUFFER;
545 extern uint8_t * LCD_SECOND_FRAME_BUFFER;
548 void testMemoryCopyFrom_RAM_to_SDRAM_32bit()
550 memoryCopy((uint32_t *)LCD_FIRST_FRAME_BUFFER, (const uint32_t * )cliLastLine, MEMORY_SPEED_BLOCK_SIZE/4);
553 void testMemoryCopyFrom_RAM_to_SDRAM_8bit()
555 memoryCopy((uint8_t *)LCD_FIRST_FRAME_BUFFER, (const uint8_t * )cliLastLine, MEMORY_SPEED_BLOCK_SIZE);
558 void testMemoryCopyFrom_SDRAM_to_SDRAM_32bit()
560 memoryCopy((uint32_t *)LCD_FIRST_FRAME_BUFFER, (const uint32_t * )LCD_SECOND_FRAME_BUFFER, MEMORY_SPEED_BLOCK_SIZE/4);
563 void testMemoryCopyFrom_SDRAM_to_SDRAM_8bit()
565 memoryCopy((uint8_t *)LCD_FIRST_FRAME_BUFFER, (const uint8_t * )LCD_SECOND_FRAME_BUFFER, MEMORY_SPEED_BLOCK_SIZE);
568 #define MEMORY_TEST_RUN_STEP 100
569 #define RUN_MEMORY_TEST(name, runtime) runMemoryTest(name, #name, runtime)
571 float runMemoryTest(graphichTestFunc func, const char * name, uint32_t runtime)
573 uint32_t start = (uint32_t)CoGetOSTime();
574 uint32_t noRuns = 0;
575 while (((uint32_t)CoGetOSTime() - start) < runtime/2 ) {
576 for (int n=0; n<MEMORY_TEST_RUN_STEP; n++) {
577 func();
579 noRuns += MEMORY_TEST_RUN_STEP;
581 uint32_t actualRuntime = (uint32_t)CoGetOSTime() - start;
582 float result = (noRuns * 500.0f) / (float)actualRuntime; // runs/second
583 serialPrint("Test %s speed: %0.2f, (%d runs in %d ms)", name, result, noRuns, actualRuntime*2);
584 CoTickDelay(100);
585 return result;
589 int cliTestMemorySpeed()
591 serialPrint("Starting memory speed test...");
592 CoTickDelay(100);
594 watchdogSuspend(6000/*60s*/);
595 if (pulsesStarted()) {
596 pausePulses();
598 pauseMixerCalculations();
599 perMainEnabled = false;
601 float result = 0;
602 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_RAM_8bit, 200);
603 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_RAM_32bit, 200);
604 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_SDRAM_8bit, 200);
605 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_SDRAM_32bit, 200);
606 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_RAM_to_SDRAM_8bit, 200);
607 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_RAM_to_SDRAM_32bit, 200);
608 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_SDRAM_to_SDRAM_8bit, 200);
609 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_SDRAM_to_SDRAM_32bit, 200);
611 LTDC_Cmd(DISABLE);
612 serialPrint("Disabling LCD...");
613 CoTickDelay(100);
615 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_RAM_8bit, 200);
616 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_RAM_32bit, 200);
617 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_SDRAM_8bit, 200);
618 result += RUN_GRAPHICS_TEST(testMemoryReadFrom_SDRAM_32bit, 200);
619 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_RAM_to_SDRAM_8bit, 200);
620 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_RAM_to_SDRAM_32bit, 200);
621 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_SDRAM_to_SDRAM_8bit, 200);
622 result += RUN_GRAPHICS_TEST(testMemoryCopyFrom_SDRAM_to_SDRAM_32bit, 200);
624 serialPrint("Total speed: %0.2f", result);
626 LTDC_Cmd(ENABLE);
628 perMainEnabled = true;
629 if (pulsesStarted()) {
630 resumePulses();
632 resumeMixerCalculations();
633 watchdogSuspend(0);
635 return 0;
638 #include "storage/modelslist.h"
639 using std::list;
641 int cliTestModelsList()
643 ModelsList modList;
644 modList.load();
646 int count=0;
648 serialPrint("Starting fetching RF data 100x...");
649 uint32_t start = (uint32_t)CoGetOSTime();
651 const list<ModelsCategory*>& cats = modList.getCategories();
652 while(1) {
653 for (list<ModelsCategory*>::const_iterator cat_it = cats.begin();
654 cat_it != cats.end(); ++cat_it) {
656 for (ModelsCategory::iterator mod_it = (*cat_it)->begin();
657 mod_it != (*cat_it)->end(); mod_it++) {
659 if (!(*mod_it)->fetchRfData()) {
660 serialPrint("Error while fetching RF data...");
661 return 0;
664 if (++count >= 100)
665 goto done;
670 done:
671 uint32_t actualRuntime = (uint32_t)CoGetOSTime() - start;
672 serialPrint("Done fetching %ix RF data: %d ms", count, actualRuntime*2);
674 return 0;
677 #endif // #if defined(COLORLCD)
679 int cliTest(const char ** argv)
681 if (!strcmp(argv[1], "new")) {
682 return cliTestNew();
684 else if (!strcmp(argv[1], "std::exception")) {
685 serialPrint("Not implemented");
687 #if defined(COLORLCD)
688 else if (!strcmp(argv[1], "graphics")) {
689 return cliTestGraphics();
691 else if (!strcmp(argv[1], "memspd")) {
692 return cliTestMemorySpeed();
694 else if (!strcmp(argv[1], "modelslist")) {
695 return cliTestModelsList();
697 #endif
698 else {
699 serialPrint("%s: Invalid argument \"%s\"", argv[0], argv[1]);
701 return 0;
704 #if defined(DEBUG)
705 int cliTrace(const char ** argv)
707 if (!strcmp(argv[1], "on")) {
708 cliTracesEnabled = true;
710 else if (!strcmp(argv[1], "off")) {
711 cliTracesEnabled = false;
713 else {
714 serialPrint("%s: Invalid argument \"%s\"", argv[0], argv[1]);
716 return 0;
718 #endif
720 int cliStackInfo(const char ** argv)
722 serialPrint("[MAIN] %d available / %d", stackAvailable(), stackSize() * 4); // stackSize() returns size in 32bit chunks
723 serialPrint("[MENUS] %d available / %d", menusStack.available(), menusStack.size());
724 serialPrint("[MIXER] %d available / %d", mixerStack.available(), mixerStack.size());
725 serialPrint("[AUDIO] %d available / %d", audioStack.available(), audioStack.size());
726 serialPrint("[CLI] %d available / %d", cliStack.available(), cliStack.size());
727 return 0;
730 extern int _end;
731 extern int _heap_end;
732 extern unsigned char *heap;
734 int cliMemoryInfo(const char ** argv)
736 // struct mallinfo {
737 // int arena; /* total space allocated from system */
738 // int ordblks; /* number of non-inuse chunks */
739 // int smblks; /* unused -- always zero */
740 // int hblks; /* number of mmapped regions */
741 // int hblkhd; /* total space in mmapped regions */
742 // int usmblks; /* unused -- always zero */
743 // int fsmblks; /* unused -- always zero */
744 // int uordblks; /* total allocated space */
745 // int fordblks; /* total non-inuse space */
746 // int keepcost; /* top-most, releasable (via malloc_trim) space */
747 // };
748 struct mallinfo info = mallinfo();
749 serialPrint("mallinfo:");
750 serialPrint("\tarena %d bytes", info.arena);
751 serialPrint("\tordblks %d bytes", info.ordblks);
752 serialPrint("\tuordblks %d bytes", info.uordblks);
753 serialPrint("\tfordblks %d bytes", info.fordblks);
754 serialPrint("\tkeepcost %d bytes", info.keepcost);
756 serialPrint("\nHeap:");
757 serialPrint("\tstart %p", (unsigned char *)&_end);
758 serialPrint("\tend %p", (unsigned char *)&_heap_end);
759 serialPrint("\tcurr %p", heap);
760 serialPrint("\tused %d bytes", (int)(heap - (unsigned char *)&_end));
761 serialPrint("\tfree %d bytes", (int)((unsigned char *)&_heap_end - heap));
763 #if defined(LUA)
764 serialPrint("\nLua:");
765 uint32_t s = luaGetMemUsed(lsScripts);
766 serialPrint("\tScripts %u", s);
767 #if defined(COLORLCD)
768 uint32_t w = luaGetMemUsed(lsWidgets);
769 uint32_t e = luaExtraMemoryUsage;
770 serialPrint("\tWidgets %u", w);
771 serialPrint("\tExtra %u", e);
772 serialPrint("------------");
773 serialPrint("\tTotal %u", s + w + e);
774 #endif
775 #endif
776 return 0;
779 int cliReboot(const char ** argv)
781 #if !defined(SIMU)
782 if (!strcmp(argv[1], "wdt")) {
783 // do a user requested watchdog test by pausing mixer thread
784 pausePulses();
786 else {
787 NVIC_SystemReset();
789 #endif
790 return 0;
793 const MemArea memAreas[] = {
794 { "RCC", RCC, sizeof(RCC_TypeDef) },
795 { "GPIOA", GPIOA, sizeof(GPIO_TypeDef) },
796 { "GPIOB", GPIOB, sizeof(GPIO_TypeDef) },
797 { "GPIOC", GPIOC, sizeof(GPIO_TypeDef) },
798 { "GPIOD", GPIOD, sizeof(GPIO_TypeDef) },
799 { "GPIOE", GPIOE, sizeof(GPIO_TypeDef) },
800 { "GPIOF", GPIOF, sizeof(GPIO_TypeDef) },
801 { "GPIOG", GPIOG, sizeof(GPIO_TypeDef) },
802 { "USART1", USART1, sizeof(USART_TypeDef) },
803 { "USART2", USART2, sizeof(USART_TypeDef) },
804 { "USART3", USART3, sizeof(USART_TypeDef) },
805 { NULL, NULL, 0 },
808 int cliSet(const char ** argv)
810 if (!strcmp(argv[1], "rtc")) {
811 struct gtm t;
812 int year, month, day, hour, minute, second;
813 if (toInt(argv, 2, &year) > 0 && toInt(argv, 3, &month) > 0 && toInt(argv, 4, &day) > 0 && toInt(argv, 5, &hour) > 0 && toInt(argv, 6, &minute) > 0 && toInt(argv, 7, &second) > 0) {
814 t.tm_year = year-TM_YEAR_BASE;
815 t.tm_mon = month-1;
816 t.tm_mday = day;
817 t.tm_hour = hour;
818 t.tm_min = minute;
819 t.tm_sec = second;
820 g_rtcTime = gmktime(&t); // update local timestamp and get wday calculated
821 rtcSetTime(&t);
823 else {
824 serialPrint("%s: Invalid arguments \"%s\" \"%s\"", argv[0], argv[1], argv[2]);
827 #if !defined(SOFTWARE_VOLUME)
828 else if (!strcmp(argv[1], "volume")) {
829 int level = 0;
830 if (toInt(argv, 2, &level) > 0) {
831 setVolume(level);
833 else {
834 serialPrint("%s: Invalid argument \"%s\" \"%s\"", argv[0], argv[1], argv[2]);
836 return 0;
838 #endif
839 return 0;
843 #if defined(DEBUG_INTERRUPTS)
844 void printInterrupts()
846 __disable_irq();
847 struct InterruptCounters ic = interruptCounters;
848 memset(&interruptCounters, 0, sizeof(interruptCounters));
849 interruptCounters.resetTime = get_tmr10ms();
850 __enable_irq();
851 serialPrint("Interrupts count in the last %u ms:", (get_tmr10ms() - ic.resetTime) * 10);
852 for(int n = 0; n < INT_LAST; n++) {
853 serialPrint("%s: %u", interruptNames[n], ic.cnt[n]);
856 #endif //#if defined(DEBUG_INTERRUPTS)
858 #if defined(DEBUG_TASKS)
860 void printTaskSwitchLog()
862 serialPrint("Tasks legend [<task_id>, <task name>]:");
863 for(int n = 0; n <= CFG_MAX_USER_TASKS+1; n++) {
864 if (0 == n) {
865 serialPrint("%d: Idle", n);
867 if (cliTaskId == n) {
868 serialPrint("%d: CLI", n);
870 else if (menusTaskId == n) {
871 serialPrint("%d: menus", n);
873 else if (mixerTaskId == n) {
874 serialPrint("%d: mixer", n);
876 else if (audioTaskId == n) {
877 serialPrint("%d: audio", n);
880 serialCrlf();
882 serialPrint("Tasks switch log at %u [<time>, <task_id>]:", get_tmr10ms());
883 uint32_t lastSwitchTime = 0;
884 uint32_t * tsl = new uint32_t[DEBUG_TASKS_LOG_SIZE];
885 if (!tsl) {
886 serialPrint("Not enough memory");
887 return;
889 memcpy(tsl, taskSwitchLog, sizeof(taskSwitchLog));
890 uint32_t * p = tsl + taskSwitchLogPos;
891 uint32_t * end = tsl + DEBUG_TASKS_LOG_SIZE;
892 for(int n = 0; n < DEBUG_TASKS_LOG_SIZE; n++) {
893 uint32_t taskId = *p >> 24;
894 uint32_t switchTime = *p & 0xFFFFFF;
895 if (lastSwitchTime != switchTime) {
896 serialPrintf("\r\n%06x: ", switchTime);
897 lastSwitchTime = switchTime;
899 serialPrintf("%u ", taskId);
900 if ( ++p >= end ) {
901 p = tsl;
904 delete[] tsl;
905 serialCrlf();
907 #endif // #if defined(DEBUG_TASKS)
909 #if defined(DEBUG_TIMERS)
911 void printDebugTime(uint32_t time)
913 if (time >= 30000) {
914 serialPrintf("%dms", time/1000);
916 else {
917 serialPrintf("%d.%03dms", time/1000, time%1000);
921 void printDebugTimer(const char * name, DebugTimer & timer)
923 serialPrintf("%s: ", name);
924 printDebugTime( timer.getMin());
925 serialPrintf(" - ");
926 printDebugTime(timer.getMax());
927 serialCrlf();
928 timer.reset();
930 void printDebugTimers()
932 for(int n = 0; n < DEBUG_TIMERS_COUNT; n++) {
933 printDebugTimer(debugTimerNames[n], debugTimers[n]);
936 #endif
938 #include "OsMutex.h"
939 extern OS_MutexID audioMutex;
941 void printAudioVars()
943 for(int n = 0; n < AUDIO_BUFFER_COUNT; n++) {
944 serialPrint("Audio Buffer %d: size: %u, ", n, (uint32_t)audioBuffers[n].size);
945 dump((uint8_t *)audioBuffers[n].data, 32);
947 serialPrint("fragments:");
948 for(int n = 0; n < AUDIO_QUEUE_LENGTH; n++) {
949 serialPrint("%d: type %u: id: %u, repeat: %u, ", n, (uint32_t)audioQueue.fragmentsFifo.fragments[n].type,
950 (uint32_t)audioQueue.fragmentsFifo.fragments[n].id,
951 (uint32_t)audioQueue.fragmentsFifo.fragments[n].repeat);
952 if ( audioQueue.fragmentsFifo.fragments[n].type == FRAGMENT_FILE) {
953 serialPrint(" file: %s", audioQueue.fragmentsFifo.fragments[n].file);
957 serialPrint("FragmentFifo: ridx: %d, widx: %d", audioQueue.fragmentsFifo.ridx, audioQueue.fragmentsFifo.widx);
958 serialPrint("audioQueue: readIdx: %d, writeIdx: %d, full: %d", audioQueue.buffersFifo.readIdx, audioQueue.buffersFifo.writeIdx, audioQueue.buffersFifo.bufferFull);
960 serialPrint("normalContext: %u", (uint32_t)audioQueue.normalContext.fragment.type);
962 serialPrint("audioMutex[%u] = %u", (uint32_t)audioMutex, (uint32_t)MutexTbl[audioMutex].mutexFlag);
966 int cliDisplay(const char ** argv)
968 long long int address = 0;
970 for (const MemArea * area = memAreas; area->name != NULL; area++) {
971 if (!strcmp(area->name, argv[1])) {
972 dump((uint8_t *)area->start, area->size);
973 return 0;
977 if (!strcmp(argv[1], "keys")) {
978 for (int i=0; i<TRM_BASE; i++) {
979 char name[8];
980 uint8_t len = STR_VKEYS[0];
981 strncpy(name, STR_VKEYS+1+len*i, len);
982 name[len] = '\0';
983 serialPrint("[%s] = %s", name, keyState(i) ? "on" : "off");
985 #if defined(ROTARY_ENCODER_NAVIGATION)
986 serialPrint("[Enc.] = %d", rotencValue[0] / ROTARY_ENCODER_GRANULARITY);
987 #endif
988 for (int i=TRM_BASE; i<=TRM_LAST; i++) {
989 serialPrint("[Trim%d] = %s", i-TRM_BASE, keyState(i) ? "on" : "off");
991 for (int i=MIXSRC_FIRST_SWITCH; i<=MIXSRC_LAST_SWITCH; i++) {
992 mixsrc_t sw = i - MIXSRC_FIRST_SWITCH;
993 if (SWITCH_EXISTS(sw)) {
994 char swName[LEN_SWITCH_NAME + 1];
995 strAppend(swName, STR_VSWITCHES+1+sw*STR_VSWITCHES[0], STR_VSWITCHES[0]);
996 static const char * const SWITCH_POSITIONS[] = { "down", "mid", "up" };
997 serialPrint("[%s] = %s", swName, SWITCH_POSITIONS[1 + getValue(i) / 1024]);
1001 else if (!strcmp(argv[1], "adc")) {
1002 for (int i=0; i<NUM_ANALOGS; i++) {
1003 serialPrint("adc[%d] = %04X", i, (int)adcValues[i]);
1006 else if (!strcmp(argv[1], "outputs")) {
1007 for (int i=0; i<MAX_OUTPUT_CHANNELS; i++) {
1008 serialPrint("outputs[%d] = %04d", i, (int)channelOutputs[i]);
1011 else if (!strcmp(argv[1], "rtc")) {
1012 struct gtm utm;
1013 gettime(&utm);
1014 serialPrint("rtc = %4d-%02d-%02d %02d:%02d:%02d.%02d0", utm.tm_year+TM_YEAR_BASE, utm.tm_mon+1, utm.tm_mday, utm.tm_hour, utm.tm_min, utm.tm_sec, g_ms100);
1016 #if !defined(SOFTWARE_VOLUME)
1017 else if (!strcmp(argv[1], "volume")) {
1018 serialPrint("volume = %d", getVolume());
1020 #endif
1021 #if defined(STM32)
1022 else if (!strcmp(argv[1], "uid")) {
1023 char str[LEN_CPU_UID+1];
1024 getCPUUniqueID(str);
1025 serialPrint("uid = %s", str);
1027 #endif
1028 else if (!strcmp(argv[1], "tim")) {
1029 int timerNumber;
1030 if (toInt(argv, 2, &timerNumber) > 0) {
1031 TIM_TypeDef * tim = TIM1;
1032 switch (timerNumber) {
1033 case 1:
1034 tim = TIM1;
1035 break;
1036 case 2:
1037 tim = TIM2;
1038 break;
1039 case 13:
1040 tim = TIM13;
1041 break;
1042 default:
1043 return 0;
1045 serialPrint("TIM%d", timerNumber);
1046 serialPrint(" CR1 0x%x", tim->CR1);
1047 serialPrint(" CR2 0x%x", tim->CR2);
1048 serialPrint(" DIER 0x%x", tim->DIER);
1049 serialPrint(" SR 0x%x", tim->SR);
1050 serialPrint(" EGR 0x%x", tim->EGR);
1051 serialPrint(" CCMR1 0x%x", tim->CCMR1);
1052 serialPrint(" CCMR2 0x%x", tim->CCMR2);
1054 serialPrint(" CNT 0x%x", tim->CNT);
1055 serialPrint(" ARR 0x%x", tim->ARR);
1056 serialPrint(" PSC 0x%x", tim->PSC);
1058 serialPrint(" CCER 0x%x", tim->CCER);
1059 serialPrint(" CCR1 0x%x", tim->CCR1);
1060 serialPrint(" CCR2 0x%x", tim->CCR2);
1061 serialPrint(" CCR3 0x%x", tim->CCR3);
1062 serialPrint(" CCR4 0x%x", tim->CCR4);
1065 else if (!strcmp(argv[1], "dma")) {
1066 serialPrint("DMA1_Stream7");
1067 serialPrint(" CR 0x%x", DMA1_Stream7->CR);
1069 #if defined(DEBUG_INTERRUPTS)
1070 else if (!strcmp(argv[1], "int")) {
1071 printInterrupts();
1073 #endif
1074 #if defined(DEBUG_TASKS)
1075 else if (!strcmp(argv[1], "tsl")) {
1076 printTaskSwitchLog();
1078 #endif
1079 #if defined(DEBUG_TIMERS)
1080 else if (!strcmp(argv[1], "dt")) {
1081 printDebugTimers();
1083 #endif
1084 else if (!strcmp(argv[1], "audio")) {
1085 printAudioVars();
1087 #if defined(DISK_CACHE)
1088 else if (!strcmp(argv[1], "dc")) {
1089 DiskCacheStats stats = diskCache.getStats();
1090 uint32_t hitRate = diskCache.getHitRate();
1091 serialPrint("Disk Cache stats: w:%u r: %u, h: %u(%0.1f%%), m: %u", stats.noWrites, (stats.noHits + stats.noMisses), stats.noHits, hitRate*0.1f, stats.noMisses);
1093 #endif
1094 else if (toLongLongInt(argv, 1, &address) > 0) {
1095 int size = 256;
1096 if (toInt(argv, 2, &size) >= 0) {
1097 dump((uint8_t *)address, size);
1100 return 0;
1103 int cliDebugVars(const char ** argv)
1105 #if defined(PCBHORUS)
1106 extern uint32_t ioMutexReq, ioMutexRel;
1107 extern uint32_t sdReadRetries;
1108 serialPrint("ioMutexReq=%d", ioMutexReq);
1109 serialPrint("ioMutexRel=%d", ioMutexRel);
1110 serialPrint("sdReadRetries=%d", sdReadRetries);
1111 #elif defined(PCBTARANIS)
1112 serialPrint("telemetryErrors=%d", telemetryErrors);
1113 #endif
1115 return 0;
1118 int cliRepeat(const char ** argv)
1120 int interval = 0;
1121 int counter = 0;
1122 if (toInt(argv, 1, &interval) > 0 && argv[2]) {
1123 interval *= 50;
1124 counter = interval;
1125 uint8_t c;
1126 while (!cliRxFifo.pop(c) || !(c == '\r' || c == '\n' || c == ' ')) {
1127 CoTickDelay(10); // 20ms
1128 if (++counter >= interval) {
1129 cliExecCommand(&argv[2]);
1130 counter = 0;
1134 else {
1135 serialPrint("%s: Invalid arguments", argv[0]);
1137 return 0;
1140 #if defined(JITTER_MEASURE)
1141 int cliShowJitter(const char ** argv)
1143 serialPrint( "# anaIn rawJ avgJ");
1144 for (int i=0; i<NUM_ANALOGS; i++) {
1145 serialPrint("A%02d %04X %04X %3d %3d", i, getAnalogValue(i), anaIn(i), rawJitter[i].get(), avgJitter[i].get());
1146 if (IS_POT_MULTIPOS(i)) {
1147 StepsCalibData * calib = (StepsCalibData *) &g_eeGeneral.calib[i];
1148 for (int j=0; j<calib->count; j++) {
1149 serialPrint(" s%d %04X", j, calib->steps[j]);
1153 return 0;
1155 #endif
1157 #if defined(INTERNAL_GPS)
1158 int cliGps(const char ** argv)
1160 int baudrate = 0;
1162 if (argv[1][0] == '$') {
1163 // send command to GPS
1164 gpsSendFrame(argv[1]);
1166 #if defined(DEBUG)
1167 else if (!strcmp(argv[1], "trace")) {
1168 gpsTraceEnabled = !gpsTraceEnabled;
1170 #endif
1171 else if (toInt(argv, 1, &baudrate) > 0 && baudrate > 0) {
1172 gpsInit(baudrate);
1173 serialPrint("GPS baudrate set to %d", baudrate);
1175 else {
1176 serialPrint("%s: Invalid arguments", argv[0]);
1178 return 0;
1180 #endif
1182 #if defined(BLUETOOTH)
1183 int cliBlueTooth(const char ** argv)
1185 int baudrate = 0;
1186 if (!strncmp(argv[1], "AT", 2) || !strncmp(argv[1], "TTM", 3)) {
1187 char command[32];
1188 strAppend(strAppend(command, argv[1]), "\r\n");
1189 bluetoothWriteString(command);
1190 char * line = bluetoothReadline();
1191 serialPrint("<BT %s", line);
1193 else if (toInt(argv, 1, &baudrate) > 0) {
1194 if (baudrate > 0) {
1195 bluetoothInit(baudrate);
1196 char * line = bluetoothReadline();
1197 serialPrint("<BT %s", line);
1199 else {
1200 bluetoothDone();
1201 serialPrint("BT turned off");
1204 else {
1205 serialPrint("%s: Invalid arguments", argv[0]);
1207 return 0;
1209 #endif
1211 const CliCommand cliCommands[] = {
1212 { "beep", cliBeep, "[<frequency>] [<duration>]" },
1213 { "ls", cliLs, "<directory>" },
1214 { "read", cliRead, "<filename>" },
1215 { "readsd", cliReadSD, "<start sector> <sectors count> <read buffer size (sectors)>" },
1216 { "testsd", cliTestSD, "" },
1217 { "play", cliPlay, "<filename>" },
1218 { "print", cliDisplay, "<address> [<size>] | <what>" },
1219 { "p", cliDisplay, "<address> [<size>] | <what>" },
1220 { "reboot", cliReboot, "[wdt]" },
1221 { "set", cliSet, "<what> <value>" },
1222 { "stackinfo", cliStackInfo, "" },
1223 { "meminfo", cliMemoryInfo, "" },
1224 { "test", cliTest, "new | std::exception | graphics | memspd" },
1225 #if defined(DEBUG)
1226 { "trace", cliTrace, "on | off" },
1227 #endif
1228 { "help", cliHelp, "[<command>]" },
1229 { "debugvars", cliDebugVars, "" },
1230 { "repeat", cliRepeat, "<interval> <command>" },
1231 #if defined(JITTER_MEASURE)
1232 { "jitter", cliShowJitter, "" },
1233 #endif
1234 #if defined(INTERNAL_GPS)
1235 { "gps", cliGps, "<baudrate>|$<command>|trace" },
1236 #endif
1237 #if defined(BLUETOOTH)
1238 { "bt", cliBlueTooth, "<baudrate>|<command>" },
1239 #endif
1240 { NULL, NULL, NULL } /* sentinel */
1243 int cliHelp(const char ** argv)
1245 for (const CliCommand * command = cliCommands; command->name != NULL; command++) {
1246 if (argv[1][0] == '\0' || !strcmp(command->name, argv[0])) {
1247 serialPrint("%s %s", command->name, command->args);
1248 if (argv[1][0] != '\0') {
1249 return 0;
1253 if (argv[1][0] != '\0') {
1254 serialPrint("Invalid command \"%s\"", argv[0]);
1256 return -1;
1259 int cliExecCommand(const char ** argv)
1261 if (argv[0][0] == '\0')
1262 return 0;
1264 for (const CliCommand * command = cliCommands; command->name != NULL; command++) {
1265 if (!strcmp(command->name, argv[0])) {
1266 return command->func(argv);
1269 serialPrint("Invalid command \"%s\"", argv[0]);
1270 return -1;
1273 int cliExecLine(char * line)
1275 int len = strlen(line);
1276 const char * argv[CLI_COMMAND_MAX_ARGS];
1277 memset(argv, 0, sizeof(argv));
1278 int argc = 1;
1279 argv[0] = line;
1280 for (int i=0; i<len; i++) {
1281 if (line[i] == ' ') {
1282 line[i] = '\0';
1283 if (argc < CLI_COMMAND_MAX_ARGS) {
1284 argv[argc++] = &line[i+1];
1288 return cliExecCommand(argv);
1291 void cliTask(void * pdata)
1293 char line[CLI_COMMAND_MAX_LEN+1];
1294 int pos = 0;
1296 cliPrompt();
1298 for (;;) {
1299 uint8_t c;
1301 while (!cliRxFifo.pop(c)) {
1302 CoTickDelay(10); // 20ms
1305 if (c == 12) {
1306 // clear screen
1307 serialPrint("\033[2J\033[1;1H");
1308 cliPrompt();
1310 else if (c == 127) {
1311 // backspace
1312 if (pos) {
1313 line[--pos] = '\0';
1314 serialPutc(c);
1317 else if (c == '\r' || c == '\n') {
1318 // enter
1319 serialCrlf();
1320 line[pos] = '\0';
1321 if (pos == 0 && cliLastLine[0]) {
1322 // execute (repeat) last command
1323 strcpy(line, cliLastLine);
1325 else {
1326 // save new command
1327 strcpy(cliLastLine, line);
1329 cliExecLine(line);
1330 pos = 0;
1331 cliPrompt();
1333 else if (isascii(c) && pos < CLI_COMMAND_MAX_LEN) {
1334 line[pos++] = c;
1335 serialPutc(c);
1340 void cliStart()
1342 cliTaskId = CoCreateTaskEx(cliTask, NULL, 10, &cliStack.stack[CLI_STACK_SIZE-1], CLI_STACK_SIZE, 1, false);