unleashed-firmware/applications/cli/cli.c

418 lines
12 KiB
C
Raw Normal View History

#include "cli_i.h"
#include "cli_commands.h"
#include <furi_hal_version.h>
#include <loader/loader.h>
Cli* cli_alloc() {
[FL-2274] Inventing streams and moving FFF to them (#981) * Streams: string stream * String stream: updated insert/delete api * Streams: generic stream interface and string stream implementation * Streams: helpers for insert and delete_and_insert * FFF: now compatible with streams * MinUnit: introduced tests with arguments * FFF: stream access violation * Streams: copy data between streams * Streams: file stream * FFF: documentation * FFStream: documentation * FFF: alloc as file * MinUnit: support for nested tests * Streams: changed delete_and_insert, now it returns success flag. Added ability dump stream inner parameters and data to cout. * FFF: simplified file open function * Streams: unit tests * FFF: tests * Streams: declare cache_size constant as define, to allow variable modified arrays * FFF: lib moved to a separate folder * iButton: new FFF * RFID: new FFF * Animations: new FFF * IR: new FFF * NFC: new FFF * Flipper file format: delete lib * U2F: new FFF * Subghz: new FFF and streams * Streams: read line * Streams: split * FuriCore: implement memset with extra asserts * FuriCore: implement extra heap asserts without inventing memset * Scene manager: protected access to the scene id stack with a size check * NFC worker: dirty fix for issue where hal_nfc was busy on app start * Furi: update allocator to erase memory on allocation. Replace furi_alloc with malloc. * FuriCore: cleanup memmgr code. * Furi HAL: furi_hal_init is split into critical and non-critical parts. The critical part is currently clock and console. * Memmgr: added ability to track allocations and deallocations through console. * FFStream: some speedup * Streams, FF: minor fixes * Tests: restore * File stream: a slightly more thread-safe version of file_stream_delete_and_insert Co-authored-by: Aleksandr Kutuzov <alleteam@gmail.com>
2022-02-18 19:53:46 +00:00
Cli* cli = malloc(sizeof(Cli));
CliCommandTree_init(cli->commands);
string_init(cli->last_line);
string_init(cli->line);
cli->mutex = osMutexNew(NULL);
furi_check(cli->mutex);
return cli;
}
void cli_free(Cli* cli) {
furi_assert(cli);
string_clear(cli->last_line);
string_clear(cli->line);
CliCommandTree_clear(cli->commands);
free(cli);
}
void cli_putc(char c) {
2021-08-08 18:03:25 +00:00
furi_hal_vcp_tx((uint8_t*)&c, 1);
}
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
char cli_getc(Cli* cli) {
furi_assert(cli);
char c;
2021-08-08 18:03:25 +00:00
if(furi_hal_vcp_rx((uint8_t*)&c, 1) == 0) {
cli_reset(cli);
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
}
return c;
}
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
void cli_stdout_callback(void* _cookie, const char* data, size_t size) {
2021-08-08 18:03:25 +00:00
furi_hal_vcp_tx((const uint8_t*)data, size);
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
}
void cli_write(Cli* cli, const uint8_t* buffer, size_t size) {
2021-08-08 18:03:25 +00:00
return furi_hal_vcp_tx(buffer, size);
}
size_t cli_read(Cli* cli, uint8_t* buffer, size_t size) {
2021-08-08 18:03:25 +00:00
return furi_hal_vcp_rx(buffer, size);
}
bool cli_cmd_interrupt_received(Cli* cli) {
char c = '\0';
2021-08-08 18:03:25 +00:00
if(furi_hal_vcp_rx_with_timeout((uint8_t*)&c, 1, 0) == 1) {
return c == CliSymbolAsciiETX;
} else {
return false;
}
}
void cli_print_usage(const char* cmd, const char* usage, const char* arg) {
furi_assert(cmd);
furi_assert(arg);
furi_assert(usage);
printf("%s: illegal option -- %s\r\nusage: %s %s", cmd, arg, cmd, usage);
}
void cli_motd() {
printf("\r\n"
" _.-------.._ -,\r\n"
" .-\"```\"--..,,_/ /`-, -, \\ \r\n"
" .:\" /:/ /'\\ \\ ,_..., `. | |\r\n"
" / ,----/:/ /`\\ _\\~`_-\"` _;\r\n"
" ' / /`\"\"\"'\\ \\ \\.~`_-' ,-\"'/ \r\n"
" | | | 0 | | .-' ,/` /\r\n"
" | ,..\\ \\ ,.-\"` ,/` /\r\n"
" ; : `/`\"\"\\` ,/--==,/-----,\r\n"
" | `-...| -.___-Z:_______J...---;\r\n"
" : ` _-'\r\n"
" _L_ _ ___ ___ ___ ___ ____--\"`___ _ ___\r\n"
"| __|| | |_ _|| _ \\| _ \\| __|| _ \\ / __|| | |_ _|\r\n"
"| _| | |__ | | | _/| _/| _| | / | (__ | |__ | |\r\n"
"|_| |____||___||_| |_| |___||_|_\\ \\___||____||___|\r\n"
"\r\n"
"Welcome to Flipper Zero Command Line Interface!\r\n"
"Read Manual https://docs.flipperzero.one\r\n"
"\r\n");
2021-08-08 18:03:25 +00:00
const Version* firmware_version = furi_hal_version_get_firmware_version();
if(firmware_version) {
printf(
[FL-2263] Flasher service & RAM exec (#1006) * WIP on stripping fw * Compact FW build - use RAM_EXEC=1 COMPACT=1 DEBUG=0 * Fixed uninitialized storage struct; small fixes to compact fw * Flasher srv w/mocked flash ops * Fixed typos & accomodated FFF changes * Alternative fw startup branch * Working load & jmp to RAM fw * +manifest processing for stage loader; + crc verification for stage payload * Fixed questionable code & potential leaks * Lowered screen update rate; added radio stack update stubs; working dfu write * Console EP with manifest & stage validation * Added microtar lib; minor ui fixes for updater * Removed microtar * Removed mtar #2 * Added a better version of microtar * TAR archive api; LFS backup & restore core * Recursive backup/restore * LFS worker thread * Added system apps to loader - not visible in UI; full update process with restarts * Typo fix * Dropped BL & f6; tooling for updater WIP * Minor py fixes * Minor fixes to make it build after merge * Ported flash workaround from BL + fixed visuals * Minor cleanup * Chmod + loader app search fix * Python linter fix * Removed usb stuff & float read support for staged loader == -10% of binary size * Added backup/restore & update pb requests * Added stub impl to RPC for backup/restore/update commands * Reworked TAR to use borrowed Storage api; slightly reduced build size by removing `static string`; hidden update-related RPC behind defines * Moved backup&restore to storage * Fixed new message types * Backup/restore/update RPC impl * Moved furi_hal_crc to LL; minor fixes * CRC HAL rework to LL * Purging STM HAL * Brought back minimal DFU boot mode (no gui); additional crc state checks * Added splash screen, BROKEN usb function * Clock init rework WIP * Stripped graphics from DFU mode * Temp fix for unused static fun * WIP update picker - broken! * Fixed UI * Bumping version * Fixed RTC setup * Backup to update folder instead of ext root * Removed unused scenes & more usb remnants from staged loader * CI updates * Fixed update bundle name * Temporary restored USB handler * Attempt to prevent .text corruption * Comments on how I spent this Saturday * Added update file icon * Documentation updates * Moved common code to lib folder * Storage: more unit tests * Storage: blocking dir open, differentiate file and dir when freed. * Major refactoring; added input processing to updater to allow retrying on failures (not very useful prob). Added API for extraction of thread return value * Removed re-init check for manifest * Changed low-level path manipulation to toolbox/path.h; makefile cleanup; tiny fix in lint.py * Increased update worker stack size * Text fixes in backup CLI * Displaying number of update stages to run; removed timeout in handling errors * Bumping version * Added thread cleanup for spawner thread * Updated build targets to exclude firmware bundle from 'ALL' * Fixed makefile for update_package; skipping VCP init for update mode (ugly) * Switched github build from ALL to update_package * Added +x for dist_update.sh * Cli: add total heap size to "free" command * Moved (RAM) suffix to build version instead of git commit no. * DFU comment * Some fixes suggested by clang-tidy * Fixed recursive PREFIX macro * Makefile: gather all new rules in updater namespace. FuriHal: rename bootloader to boot, isr safe delays * Github: correct build target name in firmware build * FuriHal: move target switch to boot * Makefile: fix firmware flash * Furi, FuriHal: move kernel start to furi, early init * Drop bootloader related stuff * Drop cube. Drop bootloader linker script. * Renamed update_hl, moved constants to #defines * Moved update-related boot mode to separate bitfield * Reworked updater cli to single entry point; fixed crash on tar cleanup * Added Python replacement for dist shell scripts * Linter fixes for dist.py +x * Fixes for environment suffix * Dropped bash scripts * Added dirty build flag to version structure & interfaces * Version string escapes * Fixed flag logic in dist.py; added support for App instances being imported and not terminating the whole program * Fixed fw address in ReadMe.md * Rpc: fix crash on double screen start * Return back original boot behavior and fix jump to system bootloader * Cleanup code, add error sequence for RTC * Update firmware readme * FuriHal: drop boot, restructure RTC registers usage and add header register check * Furi goes first * Toolchain: add ccache support * Renamed update bundle dir Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com> Co-authored-by: あく <alleteam@gmail.com>
2022-04-13 20:50:25 +00:00
"Firmware version: %s %s (%s%s built on %s)\r\n",
version_get_gitbranch(firmware_version),
version_get_version(firmware_version),
version_get_githash(firmware_version),
[FL-2263] Flasher service & RAM exec (#1006) * WIP on stripping fw * Compact FW build - use RAM_EXEC=1 COMPACT=1 DEBUG=0 * Fixed uninitialized storage struct; small fixes to compact fw * Flasher srv w/mocked flash ops * Fixed typos & accomodated FFF changes * Alternative fw startup branch * Working load & jmp to RAM fw * +manifest processing for stage loader; + crc verification for stage payload * Fixed questionable code & potential leaks * Lowered screen update rate; added radio stack update stubs; working dfu write * Console EP with manifest & stage validation * Added microtar lib; minor ui fixes for updater * Removed microtar * Removed mtar #2 * Added a better version of microtar * TAR archive api; LFS backup & restore core * Recursive backup/restore * LFS worker thread * Added system apps to loader - not visible in UI; full update process with restarts * Typo fix * Dropped BL & f6; tooling for updater WIP * Minor py fixes * Minor fixes to make it build after merge * Ported flash workaround from BL + fixed visuals * Minor cleanup * Chmod + loader app search fix * Python linter fix * Removed usb stuff & float read support for staged loader == -10% of binary size * Added backup/restore & update pb requests * Added stub impl to RPC for backup/restore/update commands * Reworked TAR to use borrowed Storage api; slightly reduced build size by removing `static string`; hidden update-related RPC behind defines * Moved backup&restore to storage * Fixed new message types * Backup/restore/update RPC impl * Moved furi_hal_crc to LL; minor fixes * CRC HAL rework to LL * Purging STM HAL * Brought back minimal DFU boot mode (no gui); additional crc state checks * Added splash screen, BROKEN usb function * Clock init rework WIP * Stripped graphics from DFU mode * Temp fix for unused static fun * WIP update picker - broken! * Fixed UI * Bumping version * Fixed RTC setup * Backup to update folder instead of ext root * Removed unused scenes & more usb remnants from staged loader * CI updates * Fixed update bundle name * Temporary restored USB handler * Attempt to prevent .text corruption * Comments on how I spent this Saturday * Added update file icon * Documentation updates * Moved common code to lib folder * Storage: more unit tests * Storage: blocking dir open, differentiate file and dir when freed. * Major refactoring; added input processing to updater to allow retrying on failures (not very useful prob). Added API for extraction of thread return value * Removed re-init check for manifest * Changed low-level path manipulation to toolbox/path.h; makefile cleanup; tiny fix in lint.py * Increased update worker stack size * Text fixes in backup CLI * Displaying number of update stages to run; removed timeout in handling errors * Bumping version * Added thread cleanup for spawner thread * Updated build targets to exclude firmware bundle from 'ALL' * Fixed makefile for update_package; skipping VCP init for update mode (ugly) * Switched github build from ALL to update_package * Added +x for dist_update.sh * Cli: add total heap size to "free" command * Moved (RAM) suffix to build version instead of git commit no. * DFU comment * Some fixes suggested by clang-tidy * Fixed recursive PREFIX macro * Makefile: gather all new rules in updater namespace. FuriHal: rename bootloader to boot, isr safe delays * Github: correct build target name in firmware build * FuriHal: move target switch to boot * Makefile: fix firmware flash * Furi, FuriHal: move kernel start to furi, early init * Drop bootloader related stuff * Drop cube. Drop bootloader linker script. * Renamed update_hl, moved constants to #defines * Moved update-related boot mode to separate bitfield * Reworked updater cli to single entry point; fixed crash on tar cleanup * Added Python replacement for dist shell scripts * Linter fixes for dist.py +x * Fixes for environment suffix * Dropped bash scripts * Added dirty build flag to version structure & interfaces * Version string escapes * Fixed flag logic in dist.py; added support for App instances being imported and not terminating the whole program * Fixed fw address in ReadMe.md * Rpc: fix crash on double screen start * Return back original boot behavior and fix jump to system bootloader * Cleanup code, add error sequence for RTC * Update firmware readme * FuriHal: drop boot, restructure RTC registers usage and add header register check * Furi goes first * Toolchain: add ccache support * Renamed update bundle dir Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com> Co-authored-by: あく <alleteam@gmail.com>
2022-04-13 20:50:25 +00:00
version_get_dirty_flag(firmware_version) ? "-dirty" : "",
version_get_builddate(firmware_version));
}
}
void cli_nl(Cli* cli) {
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
printf("\r\n");
}
void cli_prompt(Cli* cli) {
printf("\r\n>: %s", string_get_cstr(cli->line));
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
fflush(stdout);
}
void cli_reset(Cli* cli) {
// cli->last_line is cleared and cli->line's buffer moved to cli->last_line
string_move(cli->last_line, cli->line);
// Reiniting cli->line
string_init(cli->line);
cli->cursor_position = 0;
}
static void cli_handle_backspace(Cli* cli) {
if(string_size(cli->line) > 0) {
// Other side
printf("\e[D\e[1P");
fflush(stdout);
// Our side
string_t temp;
string_init(temp);
string_reserve(temp, string_size(cli->line) - 1);
string_set_strn(temp, string_get_cstr(cli->line), cli->cursor_position - 1);
string_cat_str(temp, string_get_cstr(cli->line) + cli->cursor_position);
// cli->line is cleared and temp's buffer moved to cli->line
string_move(cli->line, temp);
// NO MEMORY LEAK, STOP REPORTING IT
cli->cursor_position--;
} else {
cli_putc(CliSymbolAsciiBell);
}
}
static void cli_normalize_line(Cli* cli) {
string_strim(cli->line);
cli->cursor_position = string_size(cli->line);
}
static void cli_execute_command(Cli* cli, CliCommand* command, string_t args) {
if(!(command->flags & CliCommandFlagInsomniaSafe)) {
2021-08-08 18:03:25 +00:00
furi_hal_power_insomnia_enter();
}
// Ensure that we running alone
if(!(command->flags & CliCommandFlagParallelSafe)) {
Loader* loader = furi_record_open("loader");
bool safety_lock = loader_lock(loader);
if(safety_lock) {
// Execute command
command->callback(cli, args, command->context);
loader_unlock(loader);
} else {
printf("Other application is running, close it first");
}
furi_record_close("loader");
} else {
// Execute command
command->callback(cli, args, command->context);
}
if(!(command->flags & CliCommandFlagInsomniaSafe)) {
2021-08-08 18:03:25 +00:00
furi_hal_power_insomnia_exit();
}
}
static void cli_handle_enter(Cli* cli) {
cli_normalize_line(cli);
if(string_size(cli->line) == 0) {
cli_prompt(cli);
return;
}
// Command and args container
string_t command;
string_init(command);
string_t args;
string_init(args);
// Split command and args
size_t ws = string_search_char(cli->line, ' ');
if(ws == STRING_FAILURE) {
string_set(command, cli->line);
} else {
string_set_n(command, cli->line, 0, ws);
string_set_n(args, cli->line, ws, string_size(cli->line));
string_strim(args);
}
// Search for command
furi_check(osMutexAcquire(cli->mutex, osWaitForever) == osOK);
CliCommand* cli_command = CliCommandTree_get(cli->commands, command);
if(cli_command) {
cli_nl(cli);
cli_execute_command(cli, cli_command, args);
} else {
cli_nl(cli);
printf(
"`%s` command not found, use `help` or `?` to list all available commands",
string_get_cstr(command));
cli_putc(CliSymbolAsciiBell);
}
furi_check(osMutexRelease(cli->mutex) == osOK);
cli_reset(cli);
cli_prompt(cli);
// Cleanup command and args
string_clear(command);
string_clear(args);
}
static void cli_handle_autocomplete(Cli* cli) {
cli_normalize_line(cli);
if(string_size(cli->line) == 0) {
return;
}
cli_nl(cli);
// Prepare common base for autocomplete
string_t common;
string_init(common);
// Iterate throw commands
for
M_EACH(cli_command, cli->commands, CliCommandTree_t) {
// Process only if starts with line buffer
if(string_start_with_string_p(*cli_command->key_ptr, cli->line)) {
// Show autocomplete option
printf("%s\r\n", string_get_cstr(*cli_command->key_ptr));
// Process common base for autocomplete
if(string_size(common) > 0) {
// Choose shortest string
const size_t key_size = string_size(*cli_command->key_ptr);
const size_t common_size = string_size(common);
const size_t min_size = key_size > common_size ? common_size : key_size;
size_t i = 0;
while(i < min_size) {
// Stop when do not match
if(string_get_char(*cli_command->key_ptr, i) !=
string_get_char(common, i)) {
break;
}
i++;
}
// Cut right part if any
string_left(common, i);
} else {
// Start with something
string_set(common, *cli_command->key_ptr);
}
}
}
// Replace line buffer if autocomplete better
if(string_size(common) > string_size(cli->line)) {
string_set(cli->line, common);
cli->cursor_position = string_size(cli->line);
}
// Cleanup
string_clear(common);
// Show prompt
cli_prompt(cli);
}
static void cli_handle_escape(Cli* cli, char c) {
if(c == 'A') {
// Use previous command if line buffer is empty
if(string_size(cli->line) == 0 && string_cmp(cli->line, cli->last_line) != 0) {
// Set line buffer and cursor position
string_set(cli->line, cli->last_line);
cli->cursor_position = string_size(cli->line);
// Show new line to user
printf("%s", string_get_cstr(cli->line));
}
} else if(c == 'B') {
} else if(c == 'C') {
if(cli->cursor_position < string_size(cli->line)) {
cli->cursor_position++;
printf("\e[C");
}
} else if(c == 'D') {
if(cli->cursor_position > 0) {
cli->cursor_position--;
printf("\e[D");
}
}
fflush(stdout);
}
void cli_process_input(Cli* cli) {
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
char c = cli_getc(cli);
size_t r;
if(c == CliSymbolAsciiTab) {
cli_handle_autocomplete(cli);
} else if(c == CliSymbolAsciiSOH) {
osDelay(33); // We are too fast, Minicom is not ready yet
cli_motd();
cli_prompt(cli);
2021-08-13 13:18:13 +00:00
} else if(c == CliSymbolAsciiETX) {
cli_reset(cli);
cli_prompt(cli);
} else if(c == CliSymbolAsciiEOT) {
cli_reset(cli);
} else if(c == CliSymbolAsciiEsc) {
2021-08-08 18:03:25 +00:00
r = furi_hal_vcp_rx((uint8_t*)&c, 1);
if(r && c == '[') {
2021-08-08 18:03:25 +00:00
furi_hal_vcp_rx((uint8_t*)&c, 1);
cli_handle_escape(cli, c);
} else {
cli_putc(CliSymbolAsciiBell);
}
} else if(c == CliSymbolAsciiBackspace || c == CliSymbolAsciiDel) {
cli_handle_backspace(cli);
} else if(c == CliSymbolAsciiCR) {
cli_handle_enter(cli);
} else if(c >= 0x20 && c < 0x7F) {
if(cli->cursor_position == string_size(cli->line)) {
string_push_back(cli->line, c);
cli_putc(c);
} else {
// ToDo: better way?
string_t temp;
string_init(temp);
string_reserve(temp, string_size(cli->line) + 1);
string_set_strn(temp, string_get_cstr(cli->line), cli->cursor_position);
string_push_back(temp, c);
string_cat_str(temp, string_get_cstr(cli->line) + cli->cursor_position);
// cli->line is cleared and temp's buffer moved to cli->line
string_move(cli->line, temp);
// NO MEMORY LEAK, STOP REPORTING IT
// Print character in replace mode
printf("\e[4h%c\e[4l", c);
fflush(stdout);
}
cli->cursor_position++;
} else {
cli_putc(CliSymbolAsciiBell);
}
}
void cli_add_command(
Cli* cli,
const char* name,
CliCommandFlag flags,
CliCallback callback,
void* context) {
string_t name_str;
string_init_set_str(name_str, name);
string_strim(name_str);
size_t name_replace;
do {
name_replace = string_replace_str(name_str, " ", "_");
} while(name_replace != STRING_FAILURE);
CliCommand c;
c.callback = callback;
c.context = context;
c.flags = flags;
furi_check(osMutexAcquire(cli->mutex, osWaitForever) == osOK);
CliCommandTree_set_at(cli->commands, name_str, c);
furi_check(osMutexRelease(cli->mutex) == osOK);
string_clear(name_str);
}
void cli_delete_command(Cli* cli, const char* name) {
string_t name_str;
string_init_set_str(name_str, name);
string_strim(name_str);
size_t name_replace;
do {
name_replace = string_replace_str(name_str, " ", "_");
} while(name_replace != STRING_FAILURE);
furi_check(osMutexAcquire(cli->mutex, osWaitForever) == osOK);
CliCommandTree_erase(cli->commands, name_str);
furi_check(osMutexRelease(cli->mutex) == osOK);
string_clear(name_str);
}
int32_t cli_srv(void* p) {
Cli* cli = cli_alloc();
furi_hal_vcp_init();
// Init basic cli commands
cli_commands_init(cli);
[FL-140] Core api dynamic records (#296) * SYSTEM: tickless mode with deep sleep. * Move FreeRTOS ticks to lptim2 * API: move all sumbodules init routines to one place. Timebase: working lptim2 at tick source. * API Timebase: lp-timer routines, timer access safe zones prediction and synchronization. FreeRTOS: adjust configuration for tickless mode. * NFC: support for tickless mode. * API Timebase: improve tick error handling in IRQ. Apploader: use insomnia mode to run applications. * BLE: prevent sleep while core2 starting * HAL: nap while in insomnia mode * init records work * try to implement record delete * tests and flapp * flapp subsystem * new core functions to get app stat, simplify core code * fix thread termination * add strdup to core * fix tests * Refactoring: remove all unusued parts, update API usage, aggreagate API sources and headers, new record storage * Refactoring: update furi record api usage, cleanup code * Fix broken merge for freertos apps * Core, Target: fix compilation warnings * Drop firmware target local * HAL Timebase, Power, Clock: semaphore guarded access to clock and power modes, better sleep mode. * SD-Filesystem: wait for all deps to arrive before adding widget. Core, BLE: disable debug dump to serial. * delete old app example-ipc * delete old app fatfs list * fix strobe app, add input header * delete old display driver * comment old app qr-code * fix sd-card test, add forced widget update * remove unused new core test * increase heap to 128k * comment and assert old core tests * fix syntax Co-authored-by: Aleksandr Kutuzov <alleteam@gmail.com>
2021-01-20 16:09:26 +00:00
furi_record_create("cli", cli);
[FL-781] FURI, CLI, stdlib: stdout hooks, integration between subsystems, uniform printf usage (#311) * FURI stdglue: stdout hooks, local and global, ISR safe printf. Uniform newlines for terminal/debug output. Power: prevent sleep while core 2 has not started. * Furi record, stdglue: check mutex allocation * remove unused test * Furi stdglue: buferized output, dynamically allocated state. Furi record: dynamically allocated state. Input dump: proper line ending. Hal VCP: dynamically allocated state. * Interrupt manager: explicitly init list. * Makefile: cleanup rules, fix broken dfu upload. F4: add compiler stack protection options. * BLE: call debug uart callback on transmission complete * FreeRTOS: add configUSE_NEWLIB_REENTRANT * API HAL Timebase: fix issue with idle thread stack corruption caused by systick interrupt. BT: cleanup debug info output. FreeRTOS: disable reentry for newlib. * F4: update stack protection CFLAGS to match used compiller * F4: disable compiller stack protection because of incompatibility with current compiller * Makefile: return openocd logs to gdb * BLE: fixed pin, moar power, ble trace info. * Prevent sleep when connection is active * Makefile: return serial port to upload rule, add workaround for mac os * Furi: prevent usage of stack for cmsis functions. * F4: add missing includes, add debugger breakpoints * Applications: per app stack size. * Furi: honor kernel state in stdglue * FreeRTOS: remove unused hooks * Cleanup and format sources Co-authored-by: DrZlo13 <who.just.the.doctor@gmail.com>
2021-01-29 00:09:33 +00:00
furi_stdglue_set_thread_stdout_callback(cli_stdout_callback);
while(1) {
cli_process_input(cli);
}
return 0;
}