From 8c93695d01d3af4acbd3cb0d5bc756c30c0564dc Mon Sep 17 00:00:00 2001 From: Skorpionm <85568270+Skorpionm@users.noreply.github.com> Date: Fri, 30 Jun 2023 18:03:36 +0400 Subject: [PATCH 01/40] [FL-3375] SubGhz: add CC1101 module external (#2747) * SubGhz: add CC1101 Ext driver * SubGhz: move TIM2 -> TIM17 use cc1101_ext * FuriHal: SPI move channel DMA 3,4 -> 6.7 * Documentation: fix font * SubGhz: add work with SubGhz devices by link to device * SubGhz: add support switching external/internal cc1101 "subghz chat" * SubGhz: add support switching external/internal cc1101 "subghz tx" and "subghz rx" * SubGhz: add "Radio Settings" scene * SubGhz: add icon * SubGhz: add supported CC1101 external module in SubGhz app * SubGhz: fix check frequency supported radio device * SubGhz: fix clang-formatted * Sughz: move dirver CC1101_Ext to lib , compile cmd ./fbt launch_app APPSRC=radio_device_cc1101_ext * SubGhz: fix CLI * SubGhz: fix PVS * SubGhz: delete comments * SubGhz: fix unit_test * Format sources * Update api symbols and drivers targets * Drivers: find proper place for target option * SubGhz: external device connected method naming * Format sources * SubGhz: fix module selection menu, when external is not connected * SubGhz: fix furi_assert(device); * SubGhz: fix split h and c * SubGhz: furi_hal_subghz remove preset load function by name * SubGhz: deleted comments * Format Sources * SubGhz: add some consts and fix unit tests * Sync API Symbols Co-authored-by: Aleksandr Kutuzov --- .../debug/unit_tests/subghz/subghz_test.c | 11 +- applications/drivers/application.fam | 6 + applications/drivers/subghz/application.fam | 8 + .../drivers/subghz/cc1101_ext/cc1101_ext.c | 765 ++++++++++++++++++ .../drivers/subghz/cc1101_ext/cc1101_ext.h | 206 +++++ .../cc1101_ext/cc1101_ext_interconnect.c | 110 +++ .../cc1101_ext/cc1101_ext_interconnect.h | 8 + .../main/subghz/helpers/subghz_chat.c | 7 +- .../main/subghz/helpers/subghz_chat.h | 6 +- .../subghz/helpers/subghz_threshold_rssi.c | 3 +- .../subghz/helpers/subghz_threshold_rssi.h | 3 +- .../main/subghz/helpers/subghz_txrx.c | 166 +++- .../main/subghz/helpers/subghz_txrx.h | 46 ++ .../main/subghz/helpers/subghz_txrx_i.h | 2 + .../main/subghz/helpers/subghz_types.h | 7 + .../main/subghz/scenes/subghz_scene_config.h | 1 + .../scenes/subghz_scene_radio_setting.c | 70 ++ .../subghz/scenes/subghz_scene_read_raw.c | 11 +- .../subghz/scenes/subghz_scene_receiver.c | 6 +- .../subghz/scenes/subghz_scene_save_name.c | 3 +- .../main/subghz/scenes/subghz_scene_start.c | 14 +- .../subghz/scenes/subghz_scene_transmitter.c | 2 + applications/main/subghz/subghz_cli.c | 215 +++-- applications/main/subghz/subghz_i.c | 5 +- applications/main/subghz/views/receiver.c | 44 +- applications/main/subghz/views/receiver.h | 4 + .../subghz/views/subghz_frequency_analyzer.c | 3 +- .../main/subghz/views/subghz_read_raw.c | 20 +- .../main/subghz/views/subghz_read_raw.h | 5 + .../main/subghz/views/subghz_test_carrier.c | 3 +- .../main/subghz/views/subghz_test_packet.c | 3 +- .../main/subghz/views/subghz_test_static.c | 3 +- applications/main/subghz/views/transmitter.c | 23 +- applications/main/subghz/views/transmitter.h | 5 + .../icons/SubGhz/External_antenna_20x12.png | Bin 0 -> 990 bytes .../icons/SubGhz/Internal_antenna_20x12.png | Bin 0 -> 994 bytes assets/icons/SubGhz/Scanning_123x52.png | Bin 1690 -> 0 bytes assets/icons/SubGhz/Scanning_short_96x52.png | Bin 0 -> 1388 bytes documentation/FuriHalBus.md | 16 +- firmware/targets/f18/api_symbols.csv | 3 +- firmware/targets/f7/api_symbols.csv | 73 +- firmware/targets/f7/furi_hal/furi_hal_spi.c | 28 +- .../targets/f7/furi_hal/furi_hal_subghz.c | 65 +- .../targets/f7/furi_hal/furi_hal_subghz.h | 51 +- .../f7/furi_hal/furi_hal_subghz_configs.h | 314 ------- .../f7/platform_specific/intrinsic_export.h | 2 + lib/subghz/SConscript | 1 + lib/subghz/devices/cc1101_configs.c | 431 ++++++++++ lib/subghz/devices/cc1101_configs.h | 18 + .../cc1101_int/cc1101_int_interconnect.c | 96 +++ .../cc1101_int/cc1101_int_interconnect.h | 8 + lib/subghz/devices/device_registry.h | 13 + lib/subghz/devices/devices.c | 236 ++++++ lib/subghz/devices/devices.h | 52 ++ lib/subghz/devices/preset.h | 13 + lib/subghz/devices/registry.c | 76 ++ lib/subghz/devices/registry.h | 40 + lib/subghz/devices/types.h | 91 +++ lib/subghz/protocols/raw.c | 25 +- lib/subghz/protocols/raw.h | 6 +- lib/subghz/subghz_file_encoder_worker.c | 13 +- lib/subghz/subghz_file_encoder_worker.h | 7 +- lib/subghz/subghz_setting.c | 32 +- lib/subghz/subghz_tx_rx_worker.c | 65 +- lib/subghz/subghz_tx_rx_worker.h | 7 +- lib/subghz/types.h | 6 + site_scons/commandline.scons | 1 + 67 files changed, 2932 insertions(+), 651 deletions(-) create mode 100644 applications/drivers/application.fam create mode 100644 applications/drivers/subghz/application.fam create mode 100644 applications/drivers/subghz/cc1101_ext/cc1101_ext.c create mode 100644 applications/drivers/subghz/cc1101_ext/cc1101_ext.h create mode 100644 applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.c create mode 100644 applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h create mode 100644 applications/main/subghz/scenes/subghz_scene_radio_setting.c create mode 100644 assets/icons/SubGhz/External_antenna_20x12.png create mode 100644 assets/icons/SubGhz/Internal_antenna_20x12.png delete mode 100644 assets/icons/SubGhz/Scanning_123x52.png create mode 100644 assets/icons/SubGhz/Scanning_short_96x52.png delete mode 100644 firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h create mode 100644 lib/subghz/devices/cc1101_configs.c create mode 100644 lib/subghz/devices/cc1101_configs.h create mode 100644 lib/subghz/devices/cc1101_int/cc1101_int_interconnect.c create mode 100644 lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h create mode 100644 lib/subghz/devices/device_registry.h create mode 100644 lib/subghz/devices/devices.c create mode 100644 lib/subghz/devices/devices.h create mode 100644 lib/subghz/devices/preset.h create mode 100644 lib/subghz/devices/registry.c create mode 100644 lib/subghz/devices/registry.h create mode 100644 lib/subghz/devices/types.h diff --git a/applications/debug/unit_tests/subghz/subghz_test.c b/applications/debug/unit_tests/subghz/subghz_test.c index f1ab92653..6bdaa641e 100644 --- a/applications/debug/unit_tests/subghz/subghz_test.c +++ b/applications/debug/unit_tests/subghz/subghz_test.c @@ -7,6 +7,8 @@ #include #include #include +#include +#include #define TAG "SubGhz TEST" #define KEYSTORE_DIR_NAME EXT_PATH("subghz/assets/keeloq_mfcodes") @@ -49,12 +51,15 @@ static void subghz_test_init(void) { subghz_environment_set_protocol_registry( environment_handler, (void*)&subghz_protocol_registry); + subghz_devices_init(); + receiver_handler = subghz_receiver_alloc_init(environment_handler); subghz_receiver_set_filter(receiver_handler, SubGhzProtocolFlag_Decodable); subghz_receiver_set_rx_callback(receiver_handler, subghz_test_rx_callback, NULL); } static void subghz_test_deinit(void) { + subghz_devices_deinit(); subghz_receiver_free(receiver_handler); subghz_environment_free(environment_handler); } @@ -68,7 +73,7 @@ static bool subghz_decoder_test(const char* path, const char* name_decoder) { if(decoder) { file_worker_encoder_handler = subghz_file_encoder_worker_alloc(); - if(subghz_file_encoder_worker_start(file_worker_encoder_handler, path)) { + if(subghz_file_encoder_worker_start(file_worker_encoder_handler, path, NULL)) { // the worker needs a file in order to open and read part of the file furi_delay_ms(100); @@ -108,7 +113,7 @@ static bool subghz_decode_random_test(const char* path) { uint32_t test_start = furi_get_tick(); file_worker_encoder_handler = subghz_file_encoder_worker_alloc(); - if(subghz_file_encoder_worker_start(file_worker_encoder_handler, path)) { + if(subghz_file_encoder_worker_start(file_worker_encoder_handler, path, NULL)) { // the worker needs a file in order to open and read part of the file furi_delay_ms(100); @@ -318,7 +323,7 @@ bool subghz_hal_async_tx_test_run(SubGhzHalAsyncTxTestType type) { SubGhzHalAsyncTxTest test = {0}; test.type = type; furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); furi_hal_subghz_set_frequency_and_path(433920000); if(!furi_hal_subghz_start_async_tx(subghz_hal_async_tx_test_yield, &test)) { diff --git a/applications/drivers/application.fam b/applications/drivers/application.fam new file mode 100644 index 000000000..dc70e630c --- /dev/null +++ b/applications/drivers/application.fam @@ -0,0 +1,6 @@ +# Placeholder +App( + appid="drivers", + name="Drivers device", + apptype=FlipperAppType.METAPACKAGE, +) diff --git a/applications/drivers/subghz/application.fam b/applications/drivers/subghz/application.fam new file mode 100644 index 000000000..aaf0e1bd9 --- /dev/null +++ b/applications/drivers/subghz/application.fam @@ -0,0 +1,8 @@ +App( + appid="radio_device_cc1101_ext", + apptype=FlipperAppType.PLUGIN, + targets=["f7"], + entry_point="subghz_device_cc1101_ext_ep", + requires=["subghz"], + fap_libs=["hwdrivers"], +) diff --git a/applications/drivers/subghz/cc1101_ext/cc1101_ext.c b/applications/drivers/subghz/cc1101_ext/cc1101_ext.c new file mode 100644 index 000000000..896b9bd2f --- /dev/null +++ b/applications/drivers/subghz/cc1101_ext/cc1101_ext.c @@ -0,0 +1,765 @@ +#include "cc1101_ext.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#define TAG "SubGhz_Device_CC1101_Ext" + +#define SUBGHZ_DEVICE_CC1101_EXT_TX_GPIO &gpio_ext_pb2 + +/* DMA Channels definition */ +#define SUBGHZ_DEVICE_CC1101_EXT_DMA DMA2 +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_CHANNEL LL_DMA_CHANNEL_3 +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_CHANNEL LL_DMA_CHANNEL_4 +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_CHANNEL LL_DMA_CHANNEL_5 +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_IRQ FuriHalInterruptIdDma2Ch3 +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF \ + SUBGHZ_DEVICE_CC1101_EXT_DMA, SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_CHANNEL +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF \ + SUBGHZ_DEVICE_CC1101_EXT_DMA, SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_CHANNEL +#define SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF \ + SUBGHZ_DEVICE_CC1101_EXT_DMA, SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_CHANNEL + +/** Low level buffer dimensions and guard times */ +#define SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_FULL (256) +#define SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_HALF \ + (SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_FULL / 2) +#define SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_GUARD_TIME 999 + +/** SubGhz state */ +typedef enum { + SubGhzDeviceCC1101ExtStateInit, /**< Init pending */ + SubGhzDeviceCC1101ExtStateIdle, /**< Idle, energy save mode */ + SubGhzDeviceCC1101ExtStateAsyncRx, /**< Async RX started */ + SubGhzDeviceCC1101ExtStateAsyncTx, /**< Async TX started, DMA and timer is on */ + SubGhzDeviceCC1101ExtStateAsyncTxEnd, /**< Async TX complete, cleanup needed */ +} SubGhzDeviceCC1101ExtState; + +/** SubGhz regulation, receive transmission on the current frequency for the + * region */ +typedef enum { + SubGhzDeviceCC1101ExtRegulationOnlyRx, /**only Rx*/ + SubGhzDeviceCC1101ExtRegulationTxRx, /**TxRx*/ +} SubGhzDeviceCC1101ExtRegulation; + +typedef struct { + uint32_t* buffer; + LevelDuration carry_ld; + SubGhzDeviceCC1101ExtCallback callback; + void* callback_context; + uint32_t gpio_tx_buff[2]; + uint32_t debug_gpio_buff[2]; +} SubGhzDeviceCC1101ExtAsyncTx; + +typedef struct { + uint32_t capture_delta_duration; + SubGhzDeviceCC1101ExtCaptureCallback capture_callback; + void* capture_callback_context; +} SubGhzDeviceCC1101ExtAsyncRx; + +typedef struct { + volatile SubGhzDeviceCC1101ExtState state; + volatile SubGhzDeviceCC1101ExtRegulation regulation; + const GpioPin* async_mirror_pin; + FuriHalSpiBusHandle* spi_bus_handle; + const GpioPin* g0_pin; + SubGhzDeviceCC1101ExtAsyncTx async_tx; + SubGhzDeviceCC1101ExtAsyncRx async_rx; +} SubGhzDeviceCC1101Ext; + +static SubGhzDeviceCC1101Ext* subghz_device_cc1101_ext = NULL; + +static bool subghz_device_cc1101_ext_check_init() { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateInit); + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateIdle; + + bool ret = false; + + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + FuriHalCortexTimer timer = furi_hal_cortex_timer_get(100 * 1000); + do { + // Reset + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_reset(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + + // Prepare GD0 for power on self test + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + + // GD0 low + cc1101_write_reg(subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHW); + while(furi_hal_gpio_read(subghz_device_cc1101_ext->g0_pin) != false) { + if(furi_hal_cortex_timer_is_expired(timer)) { + //timeout + break; + } + } + if(furi_hal_cortex_timer_is_expired(timer)) { + //timeout + break; + } + + // GD0 high + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, + CC1101_IOCFG0, + CC1101IocfgHW | CC1101_IOCFG_INV); + while(furi_hal_gpio_read(subghz_device_cc1101_ext->g0_pin) != true) { + if(furi_hal_cortex_timer_is_expired(timer)) { + //timeout + break; + } + } + if(furi_hal_cortex_timer_is_expired(timer)) { + //timeout + break; + } + + // Reset GD0 to floating state + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + + // RF switches + furi_hal_gpio_init(&gpio_rf_sw_0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); + cc1101_write_reg(subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW); + + // Go to sleep + cc1101_shutdown(subghz_device_cc1101_ext->spi_bus_handle); + ret = true; + } while(false); + + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + + if(ret) { + FURI_LOG_I(TAG, "Init OK"); + } else { + FURI_LOG_E(TAG, "Init failed"); + } + return ret; +} + +bool subghz_device_cc1101_ext_alloc() { + furi_assert(subghz_device_cc1101_ext == NULL); + subghz_device_cc1101_ext = malloc(sizeof(SubGhzDeviceCC1101Ext)); + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateInit; + subghz_device_cc1101_ext->regulation = SubGhzDeviceCC1101ExtRegulationTxRx; + subghz_device_cc1101_ext->async_mirror_pin = NULL; + subghz_device_cc1101_ext->spi_bus_handle = &furi_hal_spi_bus_handle_external; + subghz_device_cc1101_ext->g0_pin = SUBGHZ_DEVICE_CC1101_EXT_TX_GPIO; + + subghz_device_cc1101_ext->async_rx.capture_delta_duration = 0; + + furi_hal_spi_bus_handle_init(subghz_device_cc1101_ext->spi_bus_handle); + return subghz_device_cc1101_ext_check_init(); +} + +void subghz_device_cc1101_ext_free() { + furi_assert(subghz_device_cc1101_ext != NULL); + furi_hal_spi_bus_handle_deinit(subghz_device_cc1101_ext->spi_bus_handle); + free(subghz_device_cc1101_ext); + subghz_device_cc1101_ext = NULL; +} + +void subghz_device_cc1101_ext_set_async_mirror_pin(const GpioPin* pin) { + subghz_device_cc1101_ext->async_mirror_pin = pin; +} + +const GpioPin* subghz_device_cc1101_ext_get_data_gpio() { + return subghz_device_cc1101_ext->g0_pin; +} + +bool subghz_device_cc1101_ext_is_connect() { + bool ret = false; + + if(subghz_device_cc1101_ext == NULL) { // not initialized + ret = subghz_device_cc1101_ext_alloc(); + subghz_device_cc1101_ext_free(); + } else { // initialized + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + uint8_t partnumber = cc1101_get_partnumber(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + ret = (partnumber != 0) && (partnumber != 0xFF); + } + + return ret; +} + +void subghz_device_cc1101_ext_sleep() { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateIdle); + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + + cc1101_switch_to_idle(subghz_device_cc1101_ext->spi_bus_handle); + + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_gpio_init(subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + + cc1101_shutdown(subghz_device_cc1101_ext->spi_bus_handle); + + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_dump_state() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + printf( + "[subghz_device_cc1101_ext] cc1101 chip %d, version %d\r\n", + cc1101_get_partnumber(subghz_device_cc1101_ext->spi_bus_handle), + cc1101_get_version(subghz_device_cc1101_ext->spi_bus_handle)); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_load_custom_preset(const uint8_t* preset_data) { + //load config + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_reset(subghz_device_cc1101_ext->spi_bus_handle); + uint32_t i = 0; + uint8_t pa[8] = {0}; + while(preset_data[i]) { + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, preset_data[i], preset_data[i + 1]); + i += 2; + } + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + + //load pa table + memcpy(&pa[0], &preset_data[i + 2], 8); + subghz_device_cc1101_ext_load_patable(pa); + + //show debug + if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { + i = 0; + FURI_LOG_D(TAG, "Loading custom preset"); + while(preset_data[i]) { + FURI_LOG_D(TAG, "Reg[%lu]: %02X=%02X", i, preset_data[i], preset_data[i + 1]); + i += 2; + } + for(uint8_t y = i; y < i + 10; y++) { + FURI_LOG_D(TAG, "PA[%u]: %02X", y, preset_data[y]); + } + } +} + +void subghz_device_cc1101_ext_load_registers(const uint8_t* data) { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_reset(subghz_device_cc1101_ext->spi_bus_handle); + uint32_t i = 0; + while(data[i]) { + cc1101_write_reg(subghz_device_cc1101_ext->spi_bus_handle, data[i], data[i + 1]); + i += 2; + } + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_load_patable(const uint8_t data[8]) { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_set_pa_table(subghz_device_cc1101_ext->spi_bus_handle, data); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_write_packet(const uint8_t* data, uint8_t size) { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_flush_tx(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_write_reg(subghz_device_cc1101_ext->spi_bus_handle, CC1101_FIFO, size); + cc1101_write_fifo(subghz_device_cc1101_ext->spi_bus_handle, data, size); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_flush_rx() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_flush_rx(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_flush_tx() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_flush_tx(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +bool subghz_device_cc1101_ext_rx_pipe_not_empty() { + CC1101RxBytes status[1]; + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_read_reg( + subghz_device_cc1101_ext->spi_bus_handle, + (CC1101_STATUS_RXBYTES) | CC1101_BURST, + (uint8_t*)status); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + // TODO: you can add a buffer overflow flag if needed + if(status->NUM_RXBYTES > 0) { + return true; + } else { + return false; + } +} + +bool subghz_device_cc1101_ext_is_rx_data_crc_valid() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + uint8_t data[1]; + cc1101_read_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_STATUS_LQI | CC1101_BURST, data); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + if(((data[0] >> 7) & 0x01)) { + return true; + } else { + return false; + } +} + +void subghz_device_cc1101_ext_read_packet(uint8_t* data, uint8_t* size) { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_read_fifo(subghz_device_cc1101_ext->spi_bus_handle, data, size); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_shutdown() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + // Reset and shutdown + cc1101_shutdown(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_reset() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_gpio_init(subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_switch_to_idle(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_reset(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_idle() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_switch_to_idle(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +void subghz_device_cc1101_ext_rx() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_switch_to_rx(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); +} + +bool subghz_device_cc1101_ext_tx() { + if(subghz_device_cc1101_ext->regulation != SubGhzDeviceCC1101ExtRegulationTxRx) return false; + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + cc1101_switch_to_tx(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + return true; +} + +float subghz_device_cc1101_ext_get_rssi() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + int32_t rssi_dec = cc1101_get_rssi(subghz_device_cc1101_ext->spi_bus_handle); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + + float rssi = rssi_dec; + if(rssi_dec >= 128) { + rssi = ((rssi - 256.0f) / 2.0f) - 74.0f; + } else { + rssi = (rssi / 2.0f) - 74.0f; + } + + return rssi; +} + +uint8_t subghz_device_cc1101_ext_get_lqi() { + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + uint8_t data[1]; + cc1101_read_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_STATUS_LQI | CC1101_BURST, data); + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + return data[0] & 0x7F; +} + +bool subghz_device_cc1101_ext_is_frequency_valid(uint32_t value) { + if(!(value >= 299999755 && value <= 348000335) && + !(value >= 386999938 && value <= 464000000) && + !(value >= 778999847 && value <= 928000000)) { + return false; + } + + return true; +} + +uint32_t subghz_device_cc1101_ext_set_frequency(uint32_t value) { + if(furi_hal_region_is_frequency_allowed(value)) { + subghz_device_cc1101_ext->regulation = SubGhzDeviceCC1101ExtRegulationTxRx; + } else { + subghz_device_cc1101_ext->regulation = SubGhzDeviceCC1101ExtRegulationOnlyRx; + } + + furi_hal_spi_acquire(subghz_device_cc1101_ext->spi_bus_handle); + uint32_t real_frequency = + cc1101_set_frequency(subghz_device_cc1101_ext->spi_bus_handle, value); + cc1101_calibrate(subghz_device_cc1101_ext->spi_bus_handle); + + while(true) { + CC1101Status status = cc1101_get_status(subghz_device_cc1101_ext->spi_bus_handle); + if(status.STATE == CC1101StateIDLE) break; + } + + furi_hal_spi_release(subghz_device_cc1101_ext->spi_bus_handle); + return real_frequency; +} + +static bool subghz_device_cc1101_ext_start_debug() { + bool ret = false; + if(subghz_device_cc1101_ext->async_mirror_pin != NULL) { + furi_hal_gpio_init( + subghz_device_cc1101_ext->async_mirror_pin, + GpioModeOutputPushPull, + GpioPullNo, + GpioSpeedVeryHigh); + ret = true; + } + return ret; +} + +static bool subghz_device_cc1101_ext_stop_debug() { + bool ret = false; + if(subghz_device_cc1101_ext->async_mirror_pin != NULL) { + furi_hal_gpio_init( + subghz_device_cc1101_ext->async_mirror_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + ret = true; + } + return ret; +} + +static void subghz_device_cc1101_ext_capture_ISR() { + if(!furi_hal_gpio_read(subghz_device_cc1101_ext->g0_pin)) { + if(subghz_device_cc1101_ext->async_rx.capture_callback) { + if(subghz_device_cc1101_ext->async_mirror_pin != NULL) + furi_hal_gpio_write(subghz_device_cc1101_ext->async_mirror_pin, false); + + subghz_device_cc1101_ext->async_rx.capture_callback( + true, + LL_TIM_GetCounter(TIM17), + (void*)subghz_device_cc1101_ext->async_rx.capture_callback_context); + } + } else { + if(subghz_device_cc1101_ext->async_rx.capture_callback) { + if(subghz_device_cc1101_ext->async_mirror_pin != NULL) + furi_hal_gpio_write(subghz_device_cc1101_ext->async_mirror_pin, true); + + subghz_device_cc1101_ext->async_rx.capture_callback( + false, + LL_TIM_GetCounter(TIM17), + (void*)subghz_device_cc1101_ext->async_rx.capture_callback_context); + } + } + LL_TIM_SetCounter(TIM17, 6); +} + +void subghz_device_cc1101_ext_start_async_rx( + SubGhzDeviceCC1101ExtCaptureCallback callback, + void* context) { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateIdle); + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateAsyncRx; + + subghz_device_cc1101_ext->async_rx.capture_callback = callback; + subghz_device_cc1101_ext->async_rx.capture_callback_context = context; + + furi_hal_bus_enable(FuriHalBusTIM17); + + // Configure TIM + LL_TIM_SetPrescaler(TIM17, 64 - 1); + LL_TIM_SetCounterMode(TIM17, LL_TIM_COUNTERMODE_UP); + LL_TIM_SetAutoReload(TIM17, 0xFFFF); + LL_TIM_SetClockDivision(TIM17, LL_TIM_CLOCKDIVISION_DIV1); + + // Timer: advanced + LL_TIM_SetClockSource(TIM17, LL_TIM_CLOCKSOURCE_INTERNAL); + LL_TIM_DisableARRPreload(TIM17); + LL_TIM_DisableDMAReq_TRIG(TIM17); + LL_TIM_DisableIT_TRIG(TIM17); + + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeInterruptRiseFall, GpioPullUp, GpioSpeedVeryHigh); + furi_hal_gpio_remove_int_callback(subghz_device_cc1101_ext->g0_pin); + furi_hal_gpio_add_int_callback( + subghz_device_cc1101_ext->g0_pin, + subghz_device_cc1101_ext_capture_ISR, + subghz_device_cc1101_ext->async_rx.capture_callback); + + // Start timer + LL_TIM_SetCounter(TIM17, 0); + LL_TIM_EnableCounter(TIM17); + + // Start debug + subghz_device_cc1101_ext_start_debug(); + + // Switch to RX + subghz_device_cc1101_ext_rx(); + + //Clear the variable after the end of the session + subghz_device_cc1101_ext->async_rx.capture_delta_duration = 0; +} + +void subghz_device_cc1101_ext_stop_async_rx() { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncRx); + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateIdle; + + // Shutdown radio + subghz_device_cc1101_ext_idle(); + + FURI_CRITICAL_ENTER(); + furi_hal_bus_disable(FuriHalBusTIM17); + + // Stop debug + subghz_device_cc1101_ext_stop_debug(); + + FURI_CRITICAL_EXIT(); + furi_hal_gpio_remove_int_callback(subghz_device_cc1101_ext->g0_pin); + furi_hal_gpio_init(subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); +} + +static void subghz_device_cc1101_ext_async_tx_refill(uint32_t* buffer, size_t samples) { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncTx); + while(samples > 0) { + bool is_odd = samples % 2; + LevelDuration ld; + if(level_duration_is_reset(subghz_device_cc1101_ext->async_tx.carry_ld)) { + ld = subghz_device_cc1101_ext->async_tx.callback( + subghz_device_cc1101_ext->async_tx.callback_context); + } else { + ld = subghz_device_cc1101_ext->async_tx.carry_ld; + subghz_device_cc1101_ext->async_tx.carry_ld = level_duration_reset(); + } + + if(level_duration_is_wait(ld)) { + *buffer = SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_GUARD_TIME; + buffer++; + samples--; + } else if(level_duration_is_reset(ld)) { + *buffer = 0; + buffer++; + samples--; + LL_DMA_DisableIT_HT(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + LL_DMA_DisableIT_TC(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + LL_TIM_EnableIT_UPDATE(TIM17); + break; + } else { + bool level = level_duration_get_level(ld); + + // Inject guard time if level is incorrect + if(is_odd != level) { + *buffer = SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_GUARD_TIME; + buffer++; + samples--; + + // Special case: prevent buffer overflow if sample is last + if(samples == 0) { + subghz_device_cc1101_ext->async_tx.carry_ld = ld; + break; + } + } + + uint32_t duration = level_duration_get_duration(ld); + furi_assert(duration > 0); + *buffer = duration - 1; + buffer++; + samples--; + } + } +} + +static void subghz_device_cc1101_ext_async_tx_dma_isr() { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncTx); + +#if SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_CHANNEL == LL_DMA_CHANNEL_3 + if(LL_DMA_IsActiveFlag_HT3(SUBGHZ_DEVICE_CC1101_EXT_DMA)) { + LL_DMA_ClearFlag_HT3(SUBGHZ_DEVICE_CC1101_EXT_DMA); + subghz_device_cc1101_ext_async_tx_refill( + subghz_device_cc1101_ext->async_tx.buffer, + SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_HALF); + } + if(LL_DMA_IsActiveFlag_TC3(SUBGHZ_DEVICE_CC1101_EXT_DMA)) { + LL_DMA_ClearFlag_TC3(SUBGHZ_DEVICE_CC1101_EXT_DMA); + subghz_device_cc1101_ext_async_tx_refill( + subghz_device_cc1101_ext->async_tx.buffer + + SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_HALF, + SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_HALF); + } +#else +#error Update this code. Would you kindly? +#endif +} + +static void subghz_device_cc1101_ext_async_tx_timer_isr() { + if(LL_TIM_IsActiveFlag_UPDATE(TIM17)) { + if(LL_TIM_GetAutoReload(TIM17) == 0) { + LL_DMA_DisableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + furi_hal_gpio_write(subghz_device_cc1101_ext->g0_pin, false); + if(subghz_device_cc1101_ext->async_mirror_pin != NULL) + furi_hal_gpio_write(subghz_device_cc1101_ext->async_mirror_pin, false); + LL_TIM_DisableCounter(TIM17); + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateAsyncTxEnd; + } + LL_TIM_ClearFlag_UPDATE(TIM17); + } +} + +bool subghz_device_cc1101_ext_start_async_tx(SubGhzDeviceCC1101ExtCallback callback, void* context) { + furi_assert(subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateIdle); + furi_assert(callback); + + //If transmission is prohibited by regional settings + if(subghz_device_cc1101_ext->regulation != SubGhzDeviceCC1101ExtRegulationTxRx) return false; + + subghz_device_cc1101_ext->async_tx.callback = callback; + subghz_device_cc1101_ext->async_tx.callback_context = context; + + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateAsyncTx; + + subghz_device_cc1101_ext->async_tx.buffer = + malloc(SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_FULL * sizeof(uint32_t)); + + //Signal generation with mem-to-mem DMA + furi_hal_gpio_write(subghz_device_cc1101_ext->g0_pin, false); + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); + + // Configure DMA update timer + LL_DMA_SetMemoryAddress( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF, (uint32_t)subghz_device_cc1101_ext->async_tx.buffer); + LL_DMA_SetPeriphAddress(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF, (uint32_t) & (TIM17->ARR)); + LL_DMA_ConfigTransfer( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF, + LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | + LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_WORD | LL_DMA_MDATAALIGN_WORD | + LL_DMA_MODE_NORMAL); + LL_DMA_SetDataLength( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF, SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_FULL); + LL_DMA_SetPeriphRequest(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF, LL_DMAMUX_REQ_TIM17_UP); + + LL_DMA_EnableIT_TC(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + LL_DMA_EnableIT_HT(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + LL_DMA_EnableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + + furi_hal_interrupt_set_isr( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_IRQ, subghz_device_cc1101_ext_async_tx_dma_isr, NULL); + + furi_hal_bus_enable(FuriHalBusTIM17); + + // Configure TIM + LL_TIM_SetPrescaler(TIM17, 64 - 1); + LL_TIM_SetCounterMode(TIM17, LL_TIM_COUNTERMODE_UP); + LL_TIM_SetAutoReload(TIM17, 0xFFFF); + LL_TIM_SetClockDivision(TIM17, LL_TIM_CLOCKDIVISION_DIV1); + LL_TIM_SetClockSource(TIM17, LL_TIM_CLOCKSOURCE_INTERNAL); + LL_TIM_DisableARRPreload(TIM17); + + furi_hal_interrupt_set_isr( + FuriHalInterruptIdTim1TrgComTim17, subghz_device_cc1101_ext_async_tx_timer_isr, NULL); + + subghz_device_cc1101_ext_async_tx_refill( + subghz_device_cc1101_ext->async_tx.buffer, SUBGHZ_DEVICE_CC1101_EXT_ASYNC_TX_BUFFER_FULL); + + // Configure tx gpio dma + const GpioPin* gpio = subghz_device_cc1101_ext->g0_pin; + + subghz_device_cc1101_ext->async_tx.gpio_tx_buff[0] = (uint32_t)gpio->pin << GPIO_NUMBER; + subghz_device_cc1101_ext->async_tx.gpio_tx_buff[1] = gpio->pin; + + LL_DMA_SetMemoryAddress( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF, + (uint32_t)subghz_device_cc1101_ext->async_tx.gpio_tx_buff); + LL_DMA_SetPeriphAddress(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF, (uint32_t) & (gpio->port->BSRR)); + LL_DMA_ConfigTransfer( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF, + LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | + LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_WORD | LL_DMA_MDATAALIGN_WORD | + LL_DMA_PRIORITY_HIGH); + LL_DMA_SetDataLength(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF, 2); + LL_DMA_SetPeriphRequest(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF, LL_DMAMUX_REQ_TIM17_UP); + LL_DMA_EnableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF); + + // Start debug + if(subghz_device_cc1101_ext_start_debug()) { + gpio = subghz_device_cc1101_ext->async_mirror_pin; + subghz_device_cc1101_ext->async_tx.debug_gpio_buff[0] = (uint32_t)gpio->pin << GPIO_NUMBER; + subghz_device_cc1101_ext->async_tx.debug_gpio_buff[1] = gpio->pin; + + LL_DMA_SetMemoryAddress( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF, + (uint32_t)subghz_device_cc1101_ext->async_tx.debug_gpio_buff); + LL_DMA_SetPeriphAddress( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF, (uint32_t) & (gpio->port->BSRR)); + LL_DMA_ConfigTransfer( + SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF, + LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | + LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_WORD | LL_DMA_MDATAALIGN_WORD | + LL_DMA_PRIORITY_LOW); + LL_DMA_SetDataLength(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF, 2); + LL_DMA_SetPeriphRequest(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF, LL_DMAMUX_REQ_TIM17_UP); + LL_DMA_EnableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF); + } + + // Start counter + LL_TIM_EnableDMAReq_UPDATE(TIM17); + LL_TIM_GenerateEvent_UPDATE(TIM17); + + subghz_device_cc1101_ext_tx(); + + LL_TIM_SetCounter(TIM17, 0); + LL_TIM_EnableCounter(TIM17); + + return true; +} + +bool subghz_device_cc1101_ext_is_async_tx_complete() { + return subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncTxEnd; +} + +void subghz_device_cc1101_ext_stop_async_tx() { + furi_assert( + subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncTx || + subghz_device_cc1101_ext->state == SubGhzDeviceCC1101ExtStateAsyncTxEnd); + + // Shutdown radio + subghz_device_cc1101_ext_idle(); + + // Deinitialize Timer + FURI_CRITICAL_ENTER(); + furi_hal_bus_disable(FuriHalBusTIM17); + furi_hal_interrupt_set_isr(FuriHalInterruptIdTim1TrgComTim17, NULL, NULL); + + // Deinitialize DMA + LL_DMA_DeInit(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_DEF); + LL_DMA_DisableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH4_DEF); + furi_hal_interrupt_set_isr(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH3_IRQ, NULL, NULL); + + // Deinitialize GPIO + furi_hal_gpio_write(subghz_device_cc1101_ext->g0_pin, false); + furi_hal_gpio_init(subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + + // Stop debug + if(subghz_device_cc1101_ext_stop_debug()) { + LL_DMA_DisableChannel(SUBGHZ_DEVICE_CC1101_EXT_DMA_CH5_DEF); + } + + FURI_CRITICAL_EXIT(); + + free(subghz_device_cc1101_ext->async_tx.buffer); + + subghz_device_cc1101_ext->state = SubGhzDeviceCC1101ExtStateIdle; +} diff --git a/applications/drivers/subghz/cc1101_ext/cc1101_ext.h b/applications/drivers/subghz/cc1101_ext/cc1101_ext.h new file mode 100644 index 000000000..d972fcb66 --- /dev/null +++ b/applications/drivers/subghz/cc1101_ext/cc1101_ext.h @@ -0,0 +1,206 @@ +/** + * @file furi_hal_subghz.h + * SubGhz HAL API + */ + +#pragma once +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Mirror RX/TX async modulation signal to specified pin + * + * @warning Configures pin to output mode. Make sure it is not connected + * directly to power or ground. + * + * @param[in] pin pointer to the gpio pin structure or NULL to disable + */ +void subghz_device_cc1101_ext_set_async_mirror_pin(const GpioPin* pin); + +/** Get data GPIO + * + * @return pointer to the gpio pin structure + */ +const GpioPin* subghz_device_cc1101_ext_get_data_gpio(); + +/** Initialize device + * + * @return true if success + */ +bool subghz_device_cc1101_ext_alloc(); + +/** Deinitialize device + */ +void subghz_device_cc1101_ext_free(); + +/** Check and switch to power save mode Used by internal API-HAL + * initialization routine Can be used to reinitialize device to safe state and + * send it to sleep + */ +bool subghz_device_cc1101_ext_is_connect(); + +/** Send device to sleep mode + */ +void subghz_device_cc1101_ext_sleep(); + +/** Dump info to stdout + */ +void subghz_device_cc1101_ext_dump_state(); + +/** Load custom registers from preset + * + * @param preset_data registers to load + */ +void subghz_device_cc1101_ext_load_custom_preset(const uint8_t* preset_data); + +/** Load registers + * + * @param data Registers data + */ +void subghz_device_cc1101_ext_load_registers(const uint8_t* data); + +/** Load PATABLE + * + * @param data 8 uint8_t values + */ +void subghz_device_cc1101_ext_load_patable(const uint8_t data[8]); + +/** Write packet to FIFO + * + * @param data bytes array + * @param size size + */ +void subghz_device_cc1101_ext_write_packet(const uint8_t* data, uint8_t size); + +/** Check if receive pipe is not empty + * + * @return true if not empty + */ +bool subghz_device_cc1101_ext_rx_pipe_not_empty(); + +/** Check if received data crc is valid + * + * @return true if valid + */ +bool subghz_device_cc1101_ext_is_rx_data_crc_valid(); + +/** Read packet from FIFO + * + * @param data pointer + * @param size size + */ +void subghz_device_cc1101_ext_read_packet(uint8_t* data, uint8_t* size); + +/** Flush rx FIFO buffer + */ +void subghz_device_cc1101_ext_flush_rx(); + +/** Flush tx FIFO buffer + */ +void subghz_device_cc1101_ext_flush_tx(); + +/** Shutdown Issue SPWD command + * @warning registers content will be lost + */ +void subghz_device_cc1101_ext_shutdown(); + +/** Reset Issue reset command + * @warning registers content will be lost + */ +void subghz_device_cc1101_ext_reset(); + +/** Switch to Idle + */ +void subghz_device_cc1101_ext_idle(); + +/** Switch to Receive + */ +void subghz_device_cc1101_ext_rx(); + +/** Switch to Transmit + * + * @return true if the transfer is allowed by belonging to the region + */ +bool subghz_device_cc1101_ext_tx(); + +/** Get RSSI value in dBm + * + * @return RSSI value + */ +float subghz_device_cc1101_ext_get_rssi(); + +/** Get LQI + * + * @return LQI value + */ +uint8_t subghz_device_cc1101_ext_get_lqi(); + +/** Check if frequency is in valid range + * + * @param value frequency in Hz + * + * @return true if frequency is valid, otherwise false + */ +bool subghz_device_cc1101_ext_is_frequency_valid(uint32_t value); + +/** Set frequency + * + * @param value frequency in Hz + * + * @return real frequency in Hz + */ +uint32_t subghz_device_cc1101_ext_set_frequency(uint32_t value); + +/* High Level API */ + +/** Signal Timings Capture callback */ +typedef void (*SubGhzDeviceCC1101ExtCaptureCallback)(bool level, uint32_t duration, void* context); + +/** Enable signal timings capture Initializes GPIO and TIM2 for timings capture + * + * @param callback SubGhzDeviceCC1101ExtCaptureCallback + * @param context callback context + */ +void subghz_device_cc1101_ext_start_async_rx( + SubGhzDeviceCC1101ExtCaptureCallback callback, + void* context); + +/** Disable signal timings capture Resets GPIO and TIM2 + */ +void subghz_device_cc1101_ext_stop_async_rx(); + +/** Async TX callback type + * @param context callback context + * @return LevelDuration + */ +typedef LevelDuration (*SubGhzDeviceCC1101ExtCallback)(void* context); + +/** Start async TX Initializes GPIO, TIM2 and DMA1 for signal output + * + * @param callback SubGhzDeviceCC1101ExtCallback + * @param context callback context + * + * @return true if the transfer is allowed by belonging to the region + */ +bool subghz_device_cc1101_ext_start_async_tx(SubGhzDeviceCC1101ExtCallback callback, void* context); + +/** Wait for async transmission to complete + * + * @return true if TX complete + */ +bool subghz_device_cc1101_ext_is_async_tx_complete(); + +/** Stop async transmission and cleanup resources Resets GPIO, TIM2, and DMA1 + */ +void subghz_device_cc1101_ext_stop_async_tx(); + +#ifdef __cplusplus +} +#endif diff --git a/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.c b/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.c new file mode 100644 index 000000000..51f5a0d1d --- /dev/null +++ b/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.c @@ -0,0 +1,110 @@ +#include "cc1101_ext_interconnect.h" +#include "cc1101_ext.h" +#include + +#define TAG "SubGhzDeviceCC1101Ext" + +static bool subghz_device_cc1101_ext_interconnect_is_frequency_valid(uint32_t frequency) { + bool ret = subghz_device_cc1101_ext_is_frequency_valid(frequency); + if(!ret) { + furi_crash("SubGhz: Incorrect frequency."); + } + return ret; +} + +static uint32_t subghz_device_cc1101_ext_interconnect_set_frequency(uint32_t frequency) { + subghz_device_cc1101_ext_interconnect_is_frequency_valid(frequency); + return subghz_device_cc1101_ext_set_frequency(frequency); +} + +static bool subghz_device_cc1101_ext_interconnect_start_async_tx(void* callback, void* context) { + return subghz_device_cc1101_ext_start_async_tx( + (SubGhzDeviceCC1101ExtCallback)callback, context); +} + +static void subghz_device_cc1101_ext_interconnect_start_async_rx(void* callback, void* context) { + subghz_device_cc1101_ext_start_async_rx( + (SubGhzDeviceCC1101ExtCaptureCallback)callback, context); +} + +static void subghz_device_cc1101_ext_interconnect_load_preset( + FuriHalSubGhzPreset preset, + uint8_t* preset_data) { + switch(preset) { + case FuriHalSubGhzPresetOok650Async: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_ook_650khz_async_regs); + break; + case FuriHalSubGhzPresetOok270Async: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_ook_270khz_async_regs); + break; + case FuriHalSubGhzPreset2FSKDev238Async: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs); + break; + case FuriHalSubGhzPreset2FSKDev476Async: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs); + break; + case FuriHalSubGhzPresetMSK99_97KbAsync: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_msk_99_97kb_async_regs); + break; + case FuriHalSubGhzPresetGFSK9_99KbAsync: + subghz_device_cc1101_ext_load_custom_preset( + subghz_device_cc1101_preset_gfsk_9_99kb_async_regs); + break; + + default: + subghz_device_cc1101_ext_load_custom_preset(preset_data); + } +} + +const SubGhzDeviceInterconnect subghz_device_cc1101_ext_interconnect = { + .begin = subghz_device_cc1101_ext_alloc, + .end = subghz_device_cc1101_ext_free, + .is_connect = subghz_device_cc1101_ext_is_connect, + .reset = subghz_device_cc1101_ext_reset, + .sleep = subghz_device_cc1101_ext_sleep, + .idle = subghz_device_cc1101_ext_idle, + .load_preset = subghz_device_cc1101_ext_interconnect_load_preset, + .set_frequency = subghz_device_cc1101_ext_interconnect_set_frequency, + .is_frequency_valid = subghz_device_cc1101_ext_is_frequency_valid, + .set_async_mirror_pin = subghz_device_cc1101_ext_set_async_mirror_pin, + .get_data_gpio = subghz_device_cc1101_ext_get_data_gpio, + + .set_tx = subghz_device_cc1101_ext_tx, + .flush_tx = subghz_device_cc1101_ext_flush_tx, + .start_async_tx = subghz_device_cc1101_ext_interconnect_start_async_tx, + .is_async_complete_tx = subghz_device_cc1101_ext_is_async_tx_complete, + .stop_async_tx = subghz_device_cc1101_ext_stop_async_tx, + + .set_rx = subghz_device_cc1101_ext_rx, + .flush_rx = subghz_device_cc1101_ext_flush_rx, + .start_async_rx = subghz_device_cc1101_ext_interconnect_start_async_rx, + .stop_async_rx = subghz_device_cc1101_ext_stop_async_rx, + + .get_rssi = subghz_device_cc1101_ext_get_rssi, + .get_lqi = subghz_device_cc1101_ext_get_lqi, + + .rx_pipe_not_empty = subghz_device_cc1101_ext_rx_pipe_not_empty, + .is_rx_data_crc_valid = subghz_device_cc1101_ext_is_rx_data_crc_valid, + .read_packet = subghz_device_cc1101_ext_read_packet, + .write_packet = subghz_device_cc1101_ext_write_packet, +}; + +const SubGhzDevice subghz_device_cc1101_ext = { + .name = SUBGHZ_DEVICE_CC1101_EXT_NAME, + .interconnect = &subghz_device_cc1101_ext_interconnect, +}; + +static const FlipperAppPluginDescriptor subghz_device_cc1101_ext_descriptor = { + .appid = SUBGHZ_RADIO_DEVICE_PLUGIN_APP_ID, + .ep_api_version = SUBGHZ_RADIO_DEVICE_PLUGIN_API_VERSION, + .entry_point = &subghz_device_cc1101_ext, +}; + +const FlipperAppPluginDescriptor* subghz_device_cc1101_ext_ep() { + return &subghz_device_cc1101_ext_descriptor; +} \ No newline at end of file diff --git a/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h b/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h new file mode 100644 index 000000000..cf1ff3ee0 --- /dev/null +++ b/applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h @@ -0,0 +1,8 @@ +#pragma once +#include + +#define SUBGHZ_DEVICE_CC1101_EXT_NAME "cc1101_ext" + +typedef struct SubGhzDeviceCC1101Ext SubGhzDeviceCC1101Ext; + +const FlipperAppPluginDescriptor* subghz_device_cc1101_ext_ep(); diff --git a/applications/main/subghz/helpers/subghz_chat.c b/applications/main/subghz/helpers/subghz_chat.c index dbf34c970..bbe219fd2 100644 --- a/applications/main/subghz/helpers/subghz_chat.c +++ b/applications/main/subghz/helpers/subghz_chat.c @@ -76,12 +76,15 @@ void subghz_chat_worker_free(SubGhzChatWorker* instance) { free(instance); } -bool subghz_chat_worker_start(SubGhzChatWorker* instance, uint32_t frequency) { +bool subghz_chat_worker_start( + SubGhzChatWorker* instance, + const SubGhzDevice* device, + uint32_t frequency) { furi_assert(instance); furi_assert(!instance->worker_running); bool res = false; - if(subghz_tx_rx_worker_start(instance->subghz_txrx, frequency)) { + if(subghz_tx_rx_worker_start(instance->subghz_txrx, device, frequency)) { furi_message_queue_reset(instance->event_queue); subghz_tx_rx_worker_set_callback_have_read( instance->subghz_txrx, subghz_chat_worker_update_rx_event_chat, instance); diff --git a/applications/main/subghz/helpers/subghz_chat.h b/applications/main/subghz/helpers/subghz_chat.h index b418bbdbf..2c454b75d 100644 --- a/applications/main/subghz/helpers/subghz_chat.h +++ b/applications/main/subghz/helpers/subghz_chat.h @@ -1,5 +1,6 @@ #pragma once #include "../subghz_i.h" +#include #include typedef struct SubGhzChatWorker SubGhzChatWorker; @@ -20,7 +21,10 @@ typedef struct { SubGhzChatWorker* subghz_chat_worker_alloc(Cli* cli); void subghz_chat_worker_free(SubGhzChatWorker* instance); -bool subghz_chat_worker_start(SubGhzChatWorker* instance, uint32_t frequency); +bool subghz_chat_worker_start( + SubGhzChatWorker* instance, + const SubGhzDevice* device, + uint32_t frequency); void subghz_chat_worker_stop(SubGhzChatWorker* instance); bool subghz_chat_worker_is_running(SubGhzChatWorker* instance); SubGhzChatEvent subghz_chat_worker_get_event_chat(SubGhzChatWorker* instance); diff --git a/applications/main/subghz/helpers/subghz_threshold_rssi.c b/applications/main/subghz/helpers/subghz_threshold_rssi.c index 04a06bc17..07d7bccf9 100644 --- a/applications/main/subghz/helpers/subghz_threshold_rssi.c +++ b/applications/main/subghz/helpers/subghz_threshold_rssi.c @@ -32,9 +32,8 @@ float subghz_threshold_rssi_get(SubGhzThresholdRssi* instance) { return instance->threshold_rssi; } -SubGhzThresholdRssiData subghz_threshold_get_rssi_data(SubGhzThresholdRssi* instance) { +SubGhzThresholdRssiData subghz_threshold_get_rssi_data(SubGhzThresholdRssi* instance, float rssi) { furi_assert(instance); - float rssi = furi_hal_subghz_get_rssi(); SubGhzThresholdRssiData ret = {.rssi = rssi, .is_above = false}; if(float_is_equal(instance->threshold_rssi, SUBGHZ_RAW_THRESHOLD_MIN)) { diff --git a/applications/main/subghz/helpers/subghz_threshold_rssi.h b/applications/main/subghz/helpers/subghz_threshold_rssi.h index e28092acb..1d588e271 100644 --- a/applications/main/subghz/helpers/subghz_threshold_rssi.h +++ b/applications/main/subghz/helpers/subghz_threshold_rssi.h @@ -38,6 +38,7 @@ float subghz_threshold_rssi_get(SubGhzThresholdRssi* instance); /** Check threshold * * @param instance Pointer to a SubGhzThresholdRssi + * @param rssi Current RSSI * @return SubGhzThresholdRssiData */ -SubGhzThresholdRssiData subghz_threshold_get_rssi_data(SubGhzThresholdRssi* instance); +SubGhzThresholdRssiData subghz_threshold_get_rssi_data(SubGhzThresholdRssi* instance, float rssi); diff --git a/applications/main/subghz/helpers/subghz_txrx.c b/applications/main/subghz/helpers/subghz_txrx.c index 1517cb998..f117d3974 100644 --- a/applications/main/subghz/helpers/subghz_txrx.c +++ b/applications/main/subghz/helpers/subghz_txrx.c @@ -1,9 +1,26 @@ #include "subghz_txrx_i.h" #include +#include +#include #define TAG "SubGhz" +static void subghz_txrx_radio_device_power_on(SubGhzTxRx* instance) { + UNUSED(instance); + 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 subghz_txrx_radio_device_power_off(SubGhzTxRx* instance) { + UNUSED(instance); + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + SubGhzTxRx* subghz_txrx_alloc() { SubGhzTxRx* instance = malloc(sizeof(SubGhzTxRx)); instance->setting = subghz_setting_alloc(); @@ -23,16 +40,15 @@ SubGhzTxRx* subghz_txrx_alloc() { instance->fff_data = flipper_format_string_alloc(); instance->environment = subghz_environment_alloc(); - instance->is_database_loaded = subghz_environment_load_keystore( - instance->environment, EXT_PATH("subghz/assets/keeloq_mfcodes")); - subghz_environment_load_keystore( - instance->environment, EXT_PATH("subghz/assets/keeloq_mfcodes_user")); + instance->is_database_loaded = + subghz_environment_load_keystore(instance->environment, SUBGHZ_KEYSTORE_DIR_NAME); + subghz_environment_load_keystore(instance->environment, SUBGHZ_KEYSTORE_DIR_USER_NAME); subghz_environment_set_came_atomo_rainbow_table_file_name( - instance->environment, EXT_PATH("subghz/assets/came_atomo")); + instance->environment, SUBGHZ_CAME_ATOMO_DIR_NAME); subghz_environment_set_alutech_at_4n_rainbow_table_file_name( - instance->environment, EXT_PATH("subghz/assets/alutech_at_4n")); + instance->environment, SUBGHZ_ALUTECH_AT_4N_DIR_NAME); subghz_environment_set_nice_flor_s_rainbow_table_file_name( - instance->environment, EXT_PATH("subghz/assets/nice_flor_s")); + instance->environment, SUBGHZ_NICE_FLOR_S_DIR_NAME); subghz_environment_set_protocol_registry( instance->environment, (void*)&subghz_protocol_registry); instance->receiver = subghz_receiver_alloc_init(instance->environment); @@ -43,18 +59,32 @@ SubGhzTxRx* subghz_txrx_alloc() { instance->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode); subghz_worker_set_context(instance->worker, instance->receiver); + //set default device External + subghz_devices_init(); + instance->radio_device_type = SubGhzRadioDeviceTypeInternal; + instance->radio_device_type = + subghz_txrx_radio_device_set(instance, SubGhzRadioDeviceTypeExternalCC1101); + return instance; } void subghz_txrx_free(SubGhzTxRx* instance) { furi_assert(instance); + if(instance->radio_device_type != SubGhzRadioDeviceTypeInternal) { + subghz_txrx_radio_device_power_off(instance); + subghz_devices_end(instance->radio_device); + } + + subghz_devices_deinit(); + subghz_worker_free(instance->worker); subghz_receiver_free(instance->receiver); subghz_environment_free(instance->environment); flipper_format_free(instance->fff_data); furi_string_free(instance->preset->name); subghz_setting_free(instance->setting); + free(instance->preset); free(instance); } @@ -122,29 +152,26 @@ void subghz_txrx_get_frequency_and_modulation( static void subghz_txrx_begin(SubGhzTxRx* instance, uint8_t* preset_data) { furi_assert(instance); - furi_hal_subghz_reset(); - furi_hal_subghz_idle(); - furi_hal_subghz_load_custom_preset(preset_data); - furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); + subghz_devices_reset(instance->radio_device); + subghz_devices_idle(instance->radio_device); + subghz_devices_load_preset(instance->radio_device, FuriHalSubGhzPresetCustom, preset_data); instance->txrx_state = SubGhzTxRxStateIDLE; } static uint32_t subghz_txrx_rx(SubGhzTxRx* instance, uint32_t frequency) { furi_assert(instance); - if(!furi_hal_subghz_is_frequency_valid(frequency)) { - furi_crash("SubGhz: Incorrect RX frequency."); - } + furi_assert( instance->txrx_state != SubGhzTxRxStateRx && instance->txrx_state != SubGhzTxRxStateSleep); - furi_hal_subghz_idle(); - uint32_t value = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); - furi_hal_subghz_flush_rx(); - subghz_txrx_speaker_on(instance); - furi_hal_subghz_rx(); + subghz_devices_idle(instance->radio_device); - furi_hal_subghz_start_async_rx(subghz_worker_rx_callback, instance->worker); + uint32_t value = subghz_devices_set_frequency(instance->radio_device, frequency); + subghz_devices_flush_rx(instance->radio_device); + subghz_txrx_speaker_on(instance); + + subghz_devices_start_async_rx( + instance->radio_device, subghz_worker_rx_callback, instance->worker); subghz_worker_start(instance->worker); instance->txrx_state = SubGhzTxRxStateRx; return value; @@ -153,7 +180,7 @@ static uint32_t subghz_txrx_rx(SubGhzTxRx* instance, uint32_t frequency) { static void subghz_txrx_idle(SubGhzTxRx* instance) { furi_assert(instance); furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); - furi_hal_subghz_idle(); + subghz_devices_idle(instance->radio_device); subghz_txrx_speaker_off(instance); instance->txrx_state = SubGhzTxRxStateIDLE; } @@ -164,30 +191,26 @@ static void subghz_txrx_rx_end(SubGhzTxRx* instance) { if(subghz_worker_is_running(instance->worker)) { subghz_worker_stop(instance->worker); - furi_hal_subghz_stop_async_rx(); + subghz_devices_stop_async_rx(instance->radio_device); } - furi_hal_subghz_idle(); + subghz_devices_idle(instance->radio_device); subghz_txrx_speaker_off(instance); instance->txrx_state = SubGhzTxRxStateIDLE; } void subghz_txrx_sleep(SubGhzTxRx* instance) { furi_assert(instance); - furi_hal_subghz_sleep(); + subghz_devices_sleep(instance->radio_device); instance->txrx_state = SubGhzTxRxStateSleep; } static bool subghz_txrx_tx(SubGhzTxRx* instance, uint32_t frequency) { furi_assert(instance); - if(!furi_hal_subghz_is_frequency_valid(frequency)) { - furi_crash("SubGhz: Incorrect TX frequency."); - } furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); - furi_hal_subghz_idle(); - furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_write(&gpio_cc1101_g0, false); - furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); - bool ret = furi_hal_subghz_tx(); + subghz_devices_idle(instance->radio_device); + subghz_devices_set_frequency(instance->radio_device, frequency); + + bool ret = subghz_devices_set_tx(instance->radio_device); if(ret) { subghz_txrx_speaker_on(instance); instance->txrx_state = SubGhzTxRxStateTx; @@ -249,8 +272,8 @@ SubGhzTxRxStartTxState subghz_txrx_tx_start(SubGhzTxRx* instance, FlipperFormat* if(ret == SubGhzTxRxStartTxStateOk) { //Start TX - furi_hal_subghz_start_async_tx( - subghz_transmitter_yield, instance->transmitter); + subghz_devices_start_async_tx( + instance->radio_device, subghz_transmitter_yield, instance->transmitter); } } else { ret = SubGhzTxRxStartTxStateErrorParserOthers; @@ -293,7 +316,7 @@ static void subghz_txrx_tx_stop(SubGhzTxRx* instance) { furi_assert(instance); furi_assert(instance->txrx_state == SubGhzTxRxStateTx); //Stop TX - furi_hal_subghz_stop_async_tx(); + subghz_devices_stop_async_tx(instance->radio_device); subghz_transmitter_stop(instance->transmitter); subghz_transmitter_free(instance->transmitter); @@ -306,7 +329,6 @@ static void subghz_txrx_tx_stop(SubGhzTxRx* instance) { subghz_txrx_idle(instance); subghz_txrx_speaker_off(instance); //Todo: Show message - // notification_message(notifications, &sequence_reset_red); } FlipperFormat* subghz_txrx_get_fff_data(SubGhzTxRx* instance) { @@ -356,7 +378,7 @@ void subghz_txrx_hopper_update(SubGhzTxRx* instance) { float rssi = -127.0f; if(instance->hopper_state != SubGhzHopperStateRSSITimeOut) { // See RSSI Calculation timings in CC1101 17.3 RSSI - rssi = furi_hal_subghz_get_rssi(); + rssi = subghz_devices_get_rssi(instance->radio_device); // Stay if RSSI is high enough if(rssi > -90.0f) { @@ -414,7 +436,7 @@ void subghz_txrx_speaker_on(SubGhzTxRx* instance) { furi_assert(instance); if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_acquire(30)) { - furi_hal_subghz_set_async_mirror_pin(&gpio_speaker); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); } else { instance->speaker_state = SubGhzSpeakerStateDisable; } @@ -425,7 +447,7 @@ void subghz_txrx_speaker_off(SubGhzTxRx* instance) { furi_assert(instance); if(instance->speaker_state != SubGhzSpeakerStateDisable) { if(furi_hal_speaker_is_mine()) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); furi_hal_speaker_release(); if(instance->speaker_state == SubGhzSpeakerStateShutdown) instance->speaker_state = SubGhzSpeakerStateDisable; @@ -437,7 +459,7 @@ void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } } } @@ -446,7 +468,7 @@ void subghz_txrx_speaker_unmute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { - furi_hal_subghz_set_async_mirror_pin(&gpio_speaker); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); } } } @@ -519,3 +541,63 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( callback, context); } + +bool subghz_txrx_radio_device_is_external_connected(SubGhzTxRx* instance, const char* name) { + furi_assert(instance); + + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + subghz_txrx_radio_device_power_on(instance); + } + + is_connect = subghz_devices_is_connect(subghz_devices_get_by_name(name)); + + if(!is_otg_enabled) { + subghz_txrx_radio_device_power_off(instance); + } + return is_connect; +} + +SubGhzRadioDeviceType + subghz_txrx_radio_device_set(SubGhzTxRx* instance, SubGhzRadioDeviceType radio_device_type) { + furi_assert(instance); + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + subghz_txrx_radio_device_is_external_connected(instance, SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + subghz_txrx_radio_device_power_on(instance); + instance->radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(instance->radio_device); + instance->radio_device_type = SubGhzRadioDeviceTypeExternalCC1101; + } else { + subghz_txrx_radio_device_power_off(instance); + if(instance->radio_device_type != SubGhzRadioDeviceTypeInternal) { + subghz_devices_end(instance->radio_device); + } + instance->radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + instance->radio_device_type = SubGhzRadioDeviceTypeInternal; + } + + return instance->radio_device_type; +} + +SubGhzRadioDeviceType subghz_txrx_radio_device_get(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->radio_device_type; +} + +float subghz_txrx_radio_device_get_rssi(SubGhzTxRx* instance) { + furi_assert(instance); + return subghz_devices_get_rssi(instance->radio_device); +} + +const char* subghz_txrx_radio_device_get_name(SubGhzTxRx* instance) { + furi_assert(instance); + return subghz_devices_get_name(instance->radio_device); +} + +bool subghz_txrx_radio_device_is_frequecy_valid(SubGhzTxRx* instance, uint32_t frequency) { + furi_assert(instance); + return subghz_devices_is_frequency_valid(instance->radio_device, frequency); +} \ No newline at end of file diff --git a/applications/main/subghz/helpers/subghz_txrx.h b/applications/main/subghz/helpers/subghz_txrx.h index 0f2daf05d..e49789206 100644 --- a/applications/main/subghz/helpers/subghz_txrx.h +++ b/applications/main/subghz/helpers/subghz_txrx.h @@ -7,6 +7,7 @@ #include #include #include +#include typedef struct SubGhzTxRx SubGhzTxRx; @@ -288,3 +289,48 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( SubGhzTxRx* instance, SubGhzProtocolEncoderRAWCallbackEnd callback, void* context); + +/* Checking if an external radio device is connected +* +* @param instance Pointer to a SubGhzTxRx +* @param name Name of external radio device +* @return bool True if is connected to the external radio device +*/ +bool subghz_txrx_radio_device_is_external_connected(SubGhzTxRx* instance, const char* name); + +/* Set the selected radio device to use +* +* @param instance Pointer to a SubGhzTxRx +* @param radio_device_type Radio device type +* @return SubGhzRadioDeviceType Type of installed radio device +*/ +SubGhzRadioDeviceType + subghz_txrx_radio_device_set(SubGhzTxRx* instance, SubGhzRadioDeviceType radio_device_type); + +/* Get the selected radio device to use +* +* @param instance Pointer to a SubGhzTxRx +* @return SubGhzRadioDeviceType Type of installed radio device +*/ +SubGhzRadioDeviceType subghz_txrx_radio_device_get(SubGhzTxRx* instance); + +/* Get RSSI the selected radio device to use +* +* @param instance Pointer to a SubGhzTxRx +* @return float RSSI +*/ +float subghz_txrx_radio_device_get_rssi(SubGhzTxRx* instance); + +/* Get name the selected radio device to use +* +* @param instance Pointer to a SubGhzTxRx +* @return const char* Name of installed radio device +*/ +const char* subghz_txrx_radio_device_get_name(SubGhzTxRx* instance); + +/* Get get intelligence whether frequency the selected radio device to use +* +* @param instance Pointer to a SubGhzTxRx +* @return bool True if the frequency is valid +*/ +bool subghz_txrx_radio_device_is_frequecy_valid(SubGhzTxRx* instance, uint32_t frequency); \ No newline at end of file diff --git a/applications/main/subghz/helpers/subghz_txrx_i.h b/applications/main/subghz/helpers/subghz_txrx_i.h index bd0ad8b7b..b7d74fd49 100644 --- a/applications/main/subghz/helpers/subghz_txrx_i.h +++ b/applications/main/subghz/helpers/subghz_txrx_i.h @@ -21,6 +21,8 @@ struct SubGhzTxRx { SubGhzTxRxState txrx_state; SubGhzSpeakerState speaker_state; + const SubGhzDevice* radio_device; + SubGhzRadioDeviceType radio_device_type; SubGhzTxRxNeedSaveCallback need_save_callback; void* need_save_context; diff --git a/applications/main/subghz/helpers/subghz_types.h b/applications/main/subghz/helpers/subghz_types.h index 46bf940f4..8beb7b9ed 100644 --- a/applications/main/subghz/helpers/subghz_types.h +++ b/applications/main/subghz/helpers/subghz_types.h @@ -35,6 +35,13 @@ typedef enum { SubGhzSpeakerStateEnable, } SubGhzSpeakerState; +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeAuto, + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + /** SubGhzRxKeyState state */ typedef enum { SubGhzRxKeyStateIDLE, diff --git a/applications/main/subghz/scenes/subghz_scene_config.h b/applications/main/subghz/scenes/subghz_scene_config.h index 86a307317..97aa946e8 100644 --- a/applications/main/subghz/scenes/subghz_scene_config.h +++ b/applications/main/subghz/scenes/subghz_scene_config.h @@ -24,3 +24,4 @@ ADD_SCENE(subghz, delete_raw, DeleteRAW) ADD_SCENE(subghz, need_saving, NeedSaving) ADD_SCENE(subghz, rpc, Rpc) ADD_SCENE(subghz, region_info, RegionInfo) +ADD_SCENE(subghz, radio_settings, RadioSettings) diff --git a/applications/main/subghz/scenes/subghz_scene_radio_setting.c b/applications/main/subghz/scenes/subghz_scene_radio_setting.c new file mode 100644 index 000000000..0a47d5bfd --- /dev/null +++ b/applications/main/subghz/scenes/subghz_scene_radio_setting.c @@ -0,0 +1,70 @@ +#include "../subghz_i.h" +#include +#include + +enum SubGhzRadioSettingIndex { + SubGhzRadioSettingIndexDevice, +}; + +#define RADIO_DEVICE_COUNT 2 +const char* const radio_device_text[RADIO_DEVICE_COUNT] = { + "Internal", + "External", +}; + +const uint32_t radio_device_value[RADIO_DEVICE_COUNT] = { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +}; + +static void subghz_scene_radio_settings_set_device(VariableItem* item) { + SubGhz* subghz = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + + if(!subghz_txrx_radio_device_is_external_connected( + subghz->txrx, SUBGHZ_DEVICE_CC1101_EXT_NAME) && + radio_device_value[index] == SubGhzRadioDeviceTypeExternalCC1101) { + //ToDo correct if there is more than 1 module + index = 0; + } + variable_item_set_current_value_text(item, radio_device_text[index]); + subghz_txrx_radio_device_set(subghz->txrx, radio_device_value[index]); +} + +void subghz_scene_radio_settings_on_enter(void* context) { + SubGhz* subghz = context; + VariableItem* item; + uint8_t value_index; + + uint8_t value_count_device = RADIO_DEVICE_COUNT; + if(subghz_txrx_radio_device_get(subghz->txrx) == SubGhzRadioDeviceTypeInternal && + !subghz_txrx_radio_device_is_external_connected(subghz->txrx, SUBGHZ_DEVICE_CC1101_EXT_NAME)) + value_count_device = 1; + item = variable_item_list_add( + subghz->variable_item_list, + "Module", + value_count_device, + subghz_scene_radio_settings_set_device, + subghz); + value_index = value_index_uint32( + subghz_txrx_radio_device_get(subghz->txrx), radio_device_value, value_count_device); + variable_item_set_current_value_index(item, value_index); + variable_item_set_current_value_text(item, radio_device_text[value_index]); + + view_dispatcher_switch_to_view(subghz->view_dispatcher, SubGhzViewIdVariableItemList); +} + +bool subghz_scene_radio_settings_on_event(void* context, SceneManagerEvent event) { + SubGhz* subghz = context; + bool consumed = false; + UNUSED(subghz); + UNUSED(event); + + return consumed; +} + +void subghz_scene_radio_settings_on_exit(void* context) { + SubGhz* subghz = context; + variable_item_list_set_selected_item(subghz->variable_item_list, 0); + variable_item_list_reset(subghz->variable_item_list); +} diff --git a/applications/main/subghz/scenes/subghz_scene_read_raw.c b/applications/main/subghz/scenes/subghz_scene_read_raw.c index a29f86a07..58e4b0429 100644 --- a/applications/main/subghz/scenes/subghz_scene_read_raw.c +++ b/applications/main/subghz/scenes/subghz_scene_read_raw.c @@ -48,6 +48,9 @@ static void subghz_scene_read_raw_update_statusbar(void* context) { furi_string_free(frequency_str); furi_string_free(modulation_str); + + subghz_read_raw_set_radio_device_type( + subghz->subghz_read_raw, subghz_txrx_radio_device_get(subghz->txrx)); } void subghz_scene_read_raw_callback(SubGhzCustomEvent event, void* context) { @@ -238,7 +241,9 @@ bool subghz_scene_read_raw_on_event(void* context, SceneManagerEvent event) { furi_string_printf( temp_str, "%s/%s%s", SUBGHZ_RAW_FOLDER, RAW_FILE_NAME, SUBGHZ_APP_EXTENSION); subghz_protocol_raw_gen_fff_data( - subghz_txrx_get_fff_data(subghz->txrx), furi_string_get_cstr(temp_str)); + subghz_txrx_get_fff_data(subghz->txrx), + furi_string_get_cstr(temp_str), + subghz_txrx_radio_device_get_name(subghz->txrx)); furi_string_free(temp_str); if(spl_count > 0) { @@ -298,8 +303,8 @@ bool subghz_scene_read_raw_on_event(void* context, SceneManagerEvent event) { subghz_read_raw_update_sample_write( subghz->subghz_read_raw, subghz_protocol_raw_get_sample_write(decoder_raw)); - SubGhzThresholdRssiData ret_rssi = - subghz_threshold_get_rssi_data(subghz->threshold_rssi); + SubGhzThresholdRssiData ret_rssi = subghz_threshold_get_rssi_data( + subghz->threshold_rssi, subghz_txrx_radio_device_get_rssi(subghz->txrx)); subghz_read_raw_add_data_rssi( subghz->subghz_read_raw, ret_rssi.rssi, ret_rssi.is_above); subghz_protocol_raw_save_to_file_pause(decoder_raw, !ret_rssi.is_above); diff --git a/applications/main/subghz/scenes/subghz_scene_receiver.c b/applications/main/subghz/scenes/subghz_scene_receiver.c index 6771f8213..6ab443579 100644 --- a/applications/main/subghz/scenes/subghz_scene_receiver.c +++ b/applications/main/subghz/scenes/subghz_scene_receiver.c @@ -56,6 +56,9 @@ static void subghz_scene_receiver_update_statusbar(void* context) { subghz->state_notifications = SubGhzNotificationStateIDLE; } furi_string_free(history_stat_str); + + subghz_view_receiver_set_radio_device_type( + subghz->subghz_receiver, subghz_txrx_radio_device_get(subghz->txrx)); } void subghz_scene_receiver_callback(SubGhzCustomEvent event, void* context) { @@ -189,7 +192,8 @@ bool subghz_scene_receiver_on_event(void* context, SceneManagerEvent event) { subghz_scene_receiver_update_statusbar(subghz); } - SubGhzThresholdRssiData ret_rssi = subghz_threshold_get_rssi_data(subghz->threshold_rssi); + SubGhzThresholdRssiData ret_rssi = subghz_threshold_get_rssi_data( + subghz->threshold_rssi, subghz_txrx_radio_device_get_rssi(subghz->txrx)); subghz_receiver_rssi(subghz->subghz_receiver, ret_rssi.rssi); subghz_protocol_decoder_bin_raw_data_input_rssi( diff --git a/applications/main/subghz/scenes/subghz_scene_save_name.c b/applications/main/subghz/scenes/subghz_scene_save_name.c index 7d0a4f4f8..86eddfe8e 100644 --- a/applications/main/subghz/scenes/subghz_scene_save_name.c +++ b/applications/main/subghz/scenes/subghz_scene_save_name.c @@ -122,7 +122,8 @@ bool subghz_scene_save_name_on_event(void* context, SceneManagerEvent event) { SubGhzCustomEventManagerNoSet) { subghz_protocol_raw_gen_fff_data( subghz_txrx_get_fff_data(subghz->txrx), - furi_string_get_cstr(subghz->file_path)); + furi_string_get_cstr(subghz->file_path), + subghz_txrx_radio_device_get_name(subghz->txrx)); scene_manager_set_scene_state( subghz->scene_manager, SubGhzSceneReadRAW, SubGhzCustomEventManagerNoSet); } else { diff --git a/applications/main/subghz/scenes/subghz_scene_start.c b/applications/main/subghz/scenes/subghz_scene_start.c index 0ab5f123e..ce631b398 100644 --- a/applications/main/subghz/scenes/subghz_scene_start.c +++ b/applications/main/subghz/scenes/subghz_scene_start.c @@ -8,7 +8,8 @@ enum SubmenuIndex { SubmenuIndexAddManually, SubmenuIndexFrequencyAnalyzer, SubmenuIndexReadRAW, - SubmenuIndexShowRegionInfo + SubmenuIndexShowRegionInfo, + SubmenuIndexRadioSetting, }; void subghz_scene_start_submenu_callback(void* context, uint32_t index) { @@ -49,6 +50,12 @@ void subghz_scene_start_on_enter(void* context) { SubmenuIndexShowRegionInfo, subghz_scene_start_submenu_callback, subghz); + submenu_add_item( + subghz->submenu, + "Radio Settings", + SubmenuIndexRadioSetting, + subghz_scene_start_submenu_callback, + subghz); if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { submenu_add_item( subghz->submenu, "Test", SubmenuIndexTest, subghz_scene_start_submenu_callback, subghz); @@ -104,6 +111,11 @@ bool subghz_scene_start_on_event(void* context, SceneManagerEvent event) { subghz->scene_manager, SubGhzSceneStart, SubmenuIndexShowRegionInfo); scene_manager_next_scene(subghz->scene_manager, SubGhzSceneRegionInfo); return true; + } else if(event.event == SubmenuIndexRadioSetting) { + scene_manager_set_scene_state( + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexRadioSetting); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneRadioSettings); + return true; } } return false; diff --git a/applications/main/subghz/scenes/subghz_scene_transmitter.c b/applications/main/subghz/scenes/subghz_scene_transmitter.c index 274dd61ad..f83e44a0a 100644 --- a/applications/main/subghz/scenes/subghz_scene_transmitter.c +++ b/applications/main/subghz/scenes/subghz_scene_transmitter.c @@ -35,6 +35,8 @@ bool subghz_scene_transmitter_update_data_show(void* context) { furi_string_free(modulation_str); furi_string_free(key_str); } + subghz_view_transmitter_set_radio_device_type( + subghz->subghz_transmitter, subghz_txrx_radio_device_get(subghz->txrx)); return ret; } diff --git a/applications/main/subghz/subghz_cli.c b/applications/main/subghz/subghz_cli.c index 60845ac99..bc7be507e 100644 --- a/applications/main/subghz/subghz_cli.c +++ b/applications/main/subghz/subghz_cli.c @@ -10,6 +10,10 @@ #include #include #include +#include +#include +#include +#include #include "helpers/subghz_chat.h" @@ -24,6 +28,19 @@ #define SUBGHZ_REGION_FILENAME "/int/.region_data" +static void subghz_cli_radio_device_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 subghz_cli_radio_device_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + void subghz_cli_command_tx_carrier(Cli* cli, FuriString* args, void* context) { UNUSED(context); uint32_t frequency = 433920000; @@ -44,7 +61,7 @@ void subghz_cli_command_tx_carrier(Cli* cli, FuriString* args, void* context) { } furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); frequency = furi_hal_subghz_set_frequency_and_path(frequency); furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); @@ -88,7 +105,7 @@ void subghz_cli_command_rx_carrier(Cli* cli, FuriString* args, void* context) { } furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); frequency = furi_hal_subghz_set_frequency_and_path(frequency); printf("Receiving at frequency %lu Hz\r\n", frequency); printf("Press CTRL+C to stop\r\n"); @@ -109,44 +126,70 @@ void subghz_cli_command_rx_carrier(Cli* cli, FuriString* args, void* context) { furi_hal_subghz_sleep(); } +static const SubGhzDevice* subghz_cli_command_get_device(uint32_t device_ind) { + const SubGhzDevice* device = NULL; + switch(device_ind) { + case 1: + subghz_cli_radio_device_power_on(); + device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + break; + + default: + device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + break; + } + return device; +} + void subghz_cli_command_tx(Cli* cli, FuriString* args, void* context) { UNUSED(context); uint32_t frequency = 433920000; uint32_t key = 0x0074BADE; uint32_t repeat = 10; uint32_t te = 403; + uint32_t device_ind = 0; // 0 - CC1101_INT, 1 - CC1101_EXT if(furi_string_size(args)) { - int ret = - sscanf(furi_string_get_cstr(args), "%lx %lu %lu %lu", &key, &frequency, &te, &repeat); - if(ret != 4) { + int ret = sscanf( + furi_string_get_cstr(args), + "%lx %lu %lu %lu %lu", + &key, + &frequency, + &te, + &repeat, + &device_ind); + if(ret != 5) { printf( - "sscanf returned %d, key: %lx, frequency: %lu, te:%lu, repeat: %lu\r\n", + "sscanf returned %d, key: %lx, frequency: %lu, te: %lu, repeat: %lu, device: %lu\r\n ", ret, key, frequency, te, - repeat); + repeat, + device_ind); cli_print_usage( "subghz tx", - "<3 Byte Key: in hex> ", + "<3 Byte Key: in hex> ", furi_string_get_cstr(args)); return; } - if(!furi_hal_subghz_is_frequency_valid(frequency)) { - printf( - "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", - frequency); - return; - } } - + subghz_devices_init(); + const SubGhzDevice* device = subghz_cli_command_get_device(device_ind); + if(!subghz_devices_is_frequency_valid(device, frequency)) { + printf( + "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", frequency); + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); + return; + } printf( - "Transmitting at %lu, key %lx, te %lu, repeat %lu. Press CTRL+C to stop\r\n", + "Transmitting at %lu, key %lx, te %lu, repeat %lu device %lu. Press CTRL+C to stop\r\n", frequency, key, te, - repeat); + repeat, + device_ind); FuriString* flipper_format_string = furi_string_alloc_printf( "Protocol: Princeton\n" @@ -170,25 +213,29 @@ void subghz_cli_command_tx(Cli* cli, FuriString* args, void* context) { SubGhzTransmitter* transmitter = subghz_transmitter_alloc_init(environment, "Princeton"); subghz_transmitter_deserialize(transmitter, flipper_format); - furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); - frequency = furi_hal_subghz_set_frequency_and_path(frequency); + subghz_devices_begin(device); + subghz_devices_reset(device); + subghz_devices_load_preset(device, FuriHalSubGhzPresetOok650Async, NULL); + frequency = subghz_devices_set_frequency(device, frequency); furi_hal_power_suppress_charge_enter(); - - if(furi_hal_subghz_start_async_tx(subghz_transmitter_yield, transmitter)) { - while(!(furi_hal_subghz_is_async_tx_complete() || cli_cmd_interrupt_received(cli))) { + if(subghz_devices_start_async_tx(device, subghz_transmitter_yield, transmitter)) { + while(!(subghz_devices_is_async_complete_tx(device) || cli_cmd_interrupt_received(cli))) { printf("."); fflush(stdout); furi_delay_ms(333); } - furi_hal_subghz_stop_async_tx(); + subghz_devices_stop_async_tx(device); } else { printf("Transmission on this frequency is restricted in your region\r\n"); } - furi_hal_subghz_sleep(); + subghz_devices_sleep(device); + subghz_devices_end(device); + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); + furi_hal_power_suppress_charge_exit(); flipper_format_free(flipper_format); @@ -233,21 +280,29 @@ static void subghz_cli_command_rx_callback( void subghz_cli_command_rx(Cli* cli, FuriString* args, void* context) { UNUSED(context); uint32_t frequency = 433920000; + uint32_t device_ind = 0; // 0 - CC1101_INT, 1 - CC1101_EXT if(furi_string_size(args)) { - int ret = sscanf(furi_string_get_cstr(args), "%lu", &frequency); - if(ret != 1) { - printf("sscanf returned %d, frequency: %lu\r\n", ret, frequency); - cli_print_usage("subghz rx", "", furi_string_get_cstr(args)); - return; - } - if(!furi_hal_subghz_is_frequency_valid(frequency)) { + int ret = sscanf(furi_string_get_cstr(args), "%lu %lu", &frequency, &device_ind); + if(ret != 2) { printf( - "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", - frequency); + "sscanf returned %d, frequency: %lu device: %lu\r\n", ret, frequency, device_ind); + cli_print_usage( + "subghz rx", + " ", + furi_string_get_cstr(args)); return; } } + subghz_devices_init(); + const SubGhzDevice* device = subghz_cli_command_get_device(device_ind); + if(!subghz_devices_is_frequency_valid(device, frequency)) { + printf( + "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", frequency); + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); + return; + } // Allocate context and buffers SubGhzCliCommandRx* instance = malloc(sizeof(SubGhzCliCommandRx)); @@ -256,14 +311,14 @@ void subghz_cli_command_rx(Cli* cli, FuriString* args, void* context) { furi_check(instance->stream); SubGhzEnvironment* environment = subghz_environment_alloc(); - subghz_environment_load_keystore(environment, EXT_PATH("subghz/assets/keeloq_mfcodes")); - subghz_environment_load_keystore(environment, EXT_PATH("subghz/assets/keeloq_mfcodes_user")); + subghz_environment_load_keystore(environment, SUBGHZ_KEYSTORE_DIR_NAME); + subghz_environment_load_keystore(environment, SUBGHZ_KEYSTORE_DIR_USER_NAME); subghz_environment_set_came_atomo_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/came_atomo")); + environment, SUBGHZ_CAME_ATOMO_DIR_NAME); subghz_environment_set_alutech_at_4n_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/alutech_at_4n")); + environment, SUBGHZ_ALUTECH_AT_4N_DIR_NAME); subghz_environment_set_nice_flor_s_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/nice_flor_s")); + environment, SUBGHZ_NICE_FLOR_S_DIR_NAME); subghz_environment_set_protocol_registry(environment, (void*)&subghz_protocol_registry); SubGhzReceiver* receiver = subghz_receiver_alloc_init(environment); @@ -271,18 +326,21 @@ void subghz_cli_command_rx(Cli* cli, FuriString* args, void* context) { subghz_receiver_set_rx_callback(receiver, subghz_cli_command_rx_callback, instance); // Configure radio - furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); - frequency = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); + subghz_devices_begin(device); + subghz_devices_reset(device); + subghz_devices_load_preset(device, FuriHalSubGhzPresetOok650Async, NULL); + frequency = subghz_devices_set_frequency(device, frequency); furi_hal_power_suppress_charge_enter(); // Prepare and start RX - furi_hal_subghz_start_async_rx(subghz_cli_command_rx_capture_callback, instance); + subghz_devices_start_async_rx(device, subghz_cli_command_rx_capture_callback, instance); // Wait for packets to arrive - printf("Listening at %lu. Press CTRL+C to stop\r\n", frequency); + printf( + "Listening at frequency: %lu device: %lu. Press CTRL+C to stop\r\n", + frequency, + device_ind); LevelDuration level_duration; while(!cli_cmd_interrupt_received(cli)) { int ret = furi_stream_buffer_receive( @@ -300,8 +358,11 @@ void subghz_cli_command_rx(Cli* cli, FuriString* args, void* context) { } // Shutdown radio - furi_hal_subghz_stop_async_rx(); - furi_hal_subghz_sleep(); + subghz_devices_stop_async_rx(device); + subghz_devices_sleep(device); + subghz_devices_end(device); + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); furi_hal_power_suppress_charge_exit(); @@ -341,7 +402,7 @@ void subghz_cli_command_rx_raw(Cli* cli, FuriString* args, void* context) { // Configure radio furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok270Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_270khz_async_regs); frequency = furi_hal_subghz_set_frequency_and_path(frequency); furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); @@ -389,6 +450,7 @@ void subghz_cli_command_rx_raw(Cli* cli, FuriString* args, void* context) { furi_stream_buffer_free(instance->stream); free(instance); } + void subghz_cli_command_decode_raw(Cli* cli, FuriString* args, void* context) { UNUSED(context); FuriString* file_name; @@ -442,25 +504,23 @@ void subghz_cli_command_decode_raw(Cli* cli, FuriString* args, void* context) { SubGhzCliCommandRx* instance = malloc(sizeof(SubGhzCliCommandRx)); SubGhzEnvironment* environment = subghz_environment_alloc(); - if(subghz_environment_load_keystore( - environment, EXT_PATH("subghz/assets/keeloq_mfcodes"))) { + if(subghz_environment_load_keystore(environment, SUBGHZ_KEYSTORE_DIR_NAME)) { printf("SubGhz decode_raw: Load_keystore keeloq_mfcodes \033[0;32mOK\033[0m\r\n"); } else { printf("SubGhz decode_raw: Load_keystore keeloq_mfcodes \033[0;31mERROR\033[0m\r\n"); } - if(subghz_environment_load_keystore( - environment, EXT_PATH("subghz/assets/keeloq_mfcodes_user"))) { + if(subghz_environment_load_keystore(environment, SUBGHZ_KEYSTORE_DIR_USER_NAME)) { printf("SubGhz decode_raw: Load_keystore keeloq_mfcodes_user \033[0;32mOK\033[0m\r\n"); } else { printf( "SubGhz decode_raw: Load_keystore keeloq_mfcodes_user \033[0;31mERROR\033[0m\r\n"); } subghz_environment_set_came_atomo_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/came_atomo")); + environment, SUBGHZ_CAME_ATOMO_DIR_NAME); subghz_environment_set_alutech_at_4n_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/alutech_at_4n")); + environment, SUBGHZ_ALUTECH_AT_4N_DIR_NAME); subghz_environment_set_nice_flor_s_rainbow_table_file_name( - environment, EXT_PATH("subghz/assets/nice_flor_s")); + environment, SUBGHZ_NICE_FLOR_S_DIR_NAME); subghz_environment_set_protocol_registry(environment, (void*)&subghz_protocol_registry); SubGhzReceiver* receiver = subghz_receiver_alloc_init(environment); @@ -468,7 +528,8 @@ void subghz_cli_command_decode_raw(Cli* cli, FuriString* args, void* context) { subghz_receiver_set_rx_callback(receiver, subghz_cli_command_rx_callback, instance); SubGhzFileEncoderWorker* file_worker_encoder = subghz_file_encoder_worker_alloc(); - if(subghz_file_encoder_worker_start(file_worker_encoder, furi_string_get_cstr(file_name))) { + if(subghz_file_encoder_worker_start( + file_worker_encoder, furi_string_get_cstr(file_name), NULL)) { //the worker needs a file in order to open and read part of the file furi_delay_ms(100); } @@ -510,10 +571,11 @@ static void subghz_cli_command_print_usage() { printf("subghz \r\n"); printf("Cmd list:\r\n"); - printf("\tchat \t - Chat with other Flippers\r\n"); printf( - "\ttx <3 byte Key: in hex> \t - Transmitting key\r\n"); - printf("\trx \t - Receive\r\n"); + "\tchat \t - Chat with other Flippers\r\n"); + printf( + "\ttx <3 byte Key: in hex> \t - Transmitting key\r\n"); + printf("\trx \t - Receive\r\n"); printf("\trx_raw \t - Receive RAW\r\n"); printf("\tdecode_raw \t - Testing\r\n"); @@ -611,21 +673,29 @@ static void subghz_cli_command_encrypt_raw(Cli* cli, FuriString* args) { static void subghz_cli_command_chat(Cli* cli, FuriString* args) { uint32_t frequency = 433920000; + uint32_t device_ind = 0; // 0 - CC1101_INT, 1 - CC1101_EXT if(furi_string_size(args)) { - int ret = sscanf(furi_string_get_cstr(args), "%lu", &frequency); - if(ret != 1) { - printf("sscanf returned %d, frequency: %lu\r\n", ret, frequency); - cli_print_usage("subghz chat", "", furi_string_get_cstr(args)); - return; - } - if(!furi_hal_subghz_is_frequency_valid(frequency)) { - printf( - "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", - frequency); + int ret = sscanf(furi_string_get_cstr(args), "%lu %lu", &frequency, &device_ind); + if(ret != 2) { + printf("sscanf returned %d, Frequency: %lu\r\n", ret, frequency); + printf("sscanf returned %d, Device: %lu\r\n", ret, device_ind); + cli_print_usage( + "subghz chat", + " ", + furi_string_get_cstr(args)); return; } } + subghz_devices_init(); + const SubGhzDevice* device = subghz_cli_command_get_device(device_ind); + if(!subghz_devices_is_frequency_valid(device, frequency)) { + printf( + "Frequency must be in " SUBGHZ_FREQUENCY_RANGE_STR " range, not %lu\r\n", frequency); + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); + return; + } if(!furi_hal_region_is_frequency_allowed(frequency)) { printf( "In your region, only reception on this frequency (%lu) is allowed,\r\n" @@ -635,7 +705,8 @@ static void subghz_cli_command_chat(Cli* cli, FuriString* args) { } SubGhzChatWorker* subghz_chat = subghz_chat_worker_alloc(cli); - if(!subghz_chat_worker_start(subghz_chat, frequency)) { + + if(!subghz_chat_worker_start(subghz_chat, device, frequency)) { printf("Startup error SubGhzChatWorker\r\n"); if(subghz_chat_worker_is_running(subghz_chat)) { @@ -781,6 +852,10 @@ static void subghz_cli_command_chat(Cli* cli, FuriString* args) { furi_string_free(name); furi_string_free(output); furi_string_free(sysmsg); + + subghz_devices_deinit(); + subghz_cli_radio_device_power_off(); + furi_hal_power_suppress_charge_exit(); furi_record_close(RECORD_NOTIFICATION); diff --git a/applications/main/subghz/subghz_i.c b/applications/main/subghz/subghz_i.c index 8036ed5f7..55036846c 100644 --- a/applications/main/subghz/subghz_i.c +++ b/applications/main/subghz/subghz_i.c @@ -115,7 +115,7 @@ bool subghz_key_load(SubGhz* subghz, const char* file_path, bool show_dialog) { break; } - if(!furi_hal_subghz_is_frequency_valid(temp_data32)) { + if(!subghz_txrx_radio_device_is_frequecy_valid(subghz->txrx, temp_data32)) { FURI_LOG_E(TAG, "Frequency not supported"); break; } @@ -163,7 +163,8 @@ bool subghz_key_load(SubGhz* subghz, const char* file_path, bool show_dialog) { if(!strcmp(furi_string_get_cstr(temp_str), "RAW")) { //if RAW subghz->load_type_file = SubGhzLoadTypeFileRaw; - subghz_protocol_raw_gen_fff_data(fff_data, file_path); + subghz_protocol_raw_gen_fff_data( + fff_data, file_path, subghz_txrx_radio_device_get_name(subghz->txrx)); } else { subghz->load_type_file = SubGhzLoadTypeFileKey; stream_copy_full( diff --git a/applications/main/subghz/views/receiver.c b/applications/main/subghz/views/receiver.c index f84ddfed0..e1014b811 100644 --- a/applications/main/subghz/views/receiver.c +++ b/applications/main/subghz/views/receiver.c @@ -62,6 +62,7 @@ typedef struct { uint16_t history_item; SubGhzViewReceiverBarShow bar_show; uint8_t u_rssi; + SubGhzRadioDeviceType device_type; } SubGhzViewReceiverModel; void subghz_receiver_rssi(SubGhzViewReceiver* instance, float rssi) { @@ -173,6 +174,17 @@ void subghz_view_receiver_add_data_statusbar( true); } +void subghz_view_receiver_set_radio_device_type( + SubGhzViewReceiver* subghz_receiver, + SubGhzRadioDeviceType device_type) { + furi_assert(subghz_receiver); + with_view_model( + subghz_receiver->view, + SubGhzViewReceiverModel * model, + { model->device_type = device_type; }, + true); +} + static void subghz_view_receiver_draw_frame(Canvas* canvas, uint16_t idx, bool scrollbar) { canvas_set_color(canvas, ColorBlack); canvas_draw_box(canvas, 0, 0 + idx * FRAME_HEIGHT, scrollbar ? 122 : 127, FRAME_HEIGHT); @@ -190,9 +202,9 @@ static void subghz_view_receiver_draw_frame(Canvas* canvas, uint16_t idx, bool s static void subghz_view_rssi_draw(Canvas* canvas, SubGhzViewReceiverModel* model) { for(uint8_t i = 1; i < model->u_rssi; i++) { if(i % 5) { - canvas_draw_dot(canvas, 46 + i, 50); - canvas_draw_dot(canvas, 47 + i, 51); canvas_draw_dot(canvas, 46 + i, 52); + canvas_draw_dot(canvas, 47 + i, 53); + canvas_draw_dot(canvas, 46 + i, 54); } } } @@ -232,22 +244,28 @@ void subghz_view_receiver_draw(Canvas* canvas, SubGhzViewReceiverModel* model) { canvas_set_color(canvas, ColorBlack); if(model->history_item == 0) { - canvas_draw_icon(canvas, 0, 0, &I_Scanning_123x52); + canvas_draw_icon(canvas, 0, 0, &I_Scanning_short_96x52); canvas_set_font(canvas, FontPrimary); canvas_draw_str(canvas, 63, 44, "Scanning..."); canvas_set_font(canvas, FontSecondary); } + if(model->device_type == SubGhzRadioDeviceTypeInternal) { + canvas_draw_icon(canvas, 108, 0, &I_Internal_antenna_20x12); + } else { + canvas_draw_icon(canvas, 108, 0, &I_External_antenna_20x12); + } + subghz_view_rssi_draw(canvas, model); switch(model->bar_show) { case SubGhzViewReceiverBarShowLock: - canvas_draw_icon(canvas, 64, 55, &I_Lock_7x8); - canvas_draw_str(canvas, 74, 62, "Locked"); + canvas_draw_icon(canvas, 64, 56, &I_Lock_7x8); + canvas_draw_str(canvas, 74, 64, "Locked"); break; case SubGhzViewReceiverBarShowToUnlockPress: - canvas_draw_str(canvas, 44, 62, furi_string_get_cstr(model->frequency_str)); - canvas_draw_str(canvas, 79, 62, furi_string_get_cstr(model->preset_str)); - canvas_draw_str(canvas, 96, 62, furi_string_get_cstr(model->history_stat_str)); + canvas_draw_str(canvas, 44, 64, furi_string_get_cstr(model->frequency_str)); + canvas_draw_str(canvas, 79, 64, furi_string_get_cstr(model->preset_str)); + canvas_draw_str(canvas, 97, 64, furi_string_get_cstr(model->history_stat_str)); canvas_set_font(canvas, FontSecondary); elements_bold_rounded_frame(canvas, 14, 8, 99, 48); elements_multiline_text(canvas, 65, 26, "To unlock\npress:"); @@ -258,13 +276,13 @@ void subghz_view_receiver_draw(Canvas* canvas, SubGhzViewReceiverModel* model) { canvas_draw_dot(canvas, 17, 61); break; case SubGhzViewReceiverBarShowUnlock: - canvas_draw_icon(canvas, 64, 55, &I_Unlock_7x8); - canvas_draw_str(canvas, 74, 62, "Unlocked"); + canvas_draw_icon(canvas, 64, 56, &I_Unlock_7x8); + canvas_draw_str(canvas, 74, 64, "Unlocked"); break; default: - canvas_draw_str(canvas, 44, 62, furi_string_get_cstr(model->frequency_str)); - canvas_draw_str(canvas, 79, 62, furi_string_get_cstr(model->preset_str)); - canvas_draw_str(canvas, 96, 62, furi_string_get_cstr(model->history_stat_str)); + canvas_draw_str(canvas, 44, 64, furi_string_get_cstr(model->frequency_str)); + canvas_draw_str(canvas, 79, 64, furi_string_get_cstr(model->preset_str)); + canvas_draw_str(canvas, 97, 64, furi_string_get_cstr(model->history_stat_str)); break; } } diff --git a/applications/main/subghz/views/receiver.h b/applications/main/subghz/views/receiver.h index 5119105e9..c91c06938 100644 --- a/applications/main/subghz/views/receiver.h +++ b/applications/main/subghz/views/receiver.h @@ -29,6 +29,10 @@ void subghz_view_receiver_add_data_statusbar( const char* preset_str, const char* history_stat_str); +void subghz_view_receiver_set_radio_device_type( + SubGhzViewReceiver* subghz_receiver, + SubGhzRadioDeviceType device_type); + void subghz_view_receiver_add_item_to_menu( SubGhzViewReceiver* subghz_receiver, const char* name, diff --git a/applications/main/subghz/views/subghz_frequency_analyzer.c b/applications/main/subghz/views/subghz_frequency_analyzer.c index 325664f4a..d90401678 100644 --- a/applications/main/subghz/views/subghz_frequency_analyzer.c +++ b/applications/main/subghz/views/subghz_frequency_analyzer.c @@ -177,7 +177,8 @@ void subghz_frequency_analyzer_draw(Canvas* canvas, SubGhzFrequencyAnalyzerModel } subghz_frequency_analyzer_log_frequency_draw(canvas, model); } else { - canvas_draw_str(canvas, 20, 8, "Frequency Analyzer"); + canvas_draw_str(canvas, 0, 8, "Frequency Analyzer"); + canvas_draw_icon(canvas, 108, 0, &I_Internal_antenna_20x12); canvas_draw_str(canvas, 0, 64, "RSSI"); subghz_frequency_analyzer_draw_rssi(canvas, model->rssi, 20, 64); diff --git a/applications/main/subghz/views/subghz_read_raw.c b/applications/main/subghz/views/subghz_read_raw.c index 2ff598b60..88ac129ca 100644 --- a/applications/main/subghz/views/subghz_read_raw.c +++ b/applications/main/subghz/views/subghz_read_raw.c @@ -29,6 +29,7 @@ typedef struct { uint8_t ind_sin; SubGhzReadRAWStatus status; float raw_threshold_rssi; + SubGhzRadioDeviceType device_type; } SubGhzReadRAWModel; void subghz_read_raw_set_callback( @@ -56,6 +57,14 @@ void subghz_read_raw_add_data_statusbar( true); } +void subghz_read_raw_set_radio_device_type( + SubGhzReadRAW* instance, + SubGhzRadioDeviceType device_type) { + furi_assert(instance); + with_view_model( + instance->view, SubGhzReadRAWModel * model, { model->device_type = device_type; }, true); +} + void subghz_read_raw_add_data_rssi(SubGhzReadRAW* instance, float rssi, bool trace) { furi_assert(instance); uint8_t u_rssi = 0; @@ -279,11 +288,16 @@ void subghz_read_raw_draw(Canvas* canvas, SubGhzReadRAWModel* model) { uint8_t graphics_mode = 1; canvas_set_color(canvas, ColorBlack); canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 5, 7, furi_string_get_cstr(model->frequency_str)); - canvas_draw_str(canvas, 40, 7, furi_string_get_cstr(model->preset_str)); + canvas_draw_str(canvas, 0, 9, furi_string_get_cstr(model->frequency_str)); + canvas_draw_str(canvas, 35, 9, furi_string_get_cstr(model->preset_str)); canvas_draw_str_aligned( - canvas, 126, 0, AlignRight, AlignTop, furi_string_get_cstr(model->sample_write)); + canvas, 106, 2, AlignRight, AlignTop, furi_string_get_cstr(model->sample_write)); + if(model->device_type == SubGhzRadioDeviceTypeInternal) { + canvas_draw_icon(canvas, 108, 0, &I_Internal_antenna_20x12); + } else { + canvas_draw_icon(canvas, 108, 0, &I_External_antenna_20x12); + } canvas_draw_line(canvas, 0, 14, 115, 14); canvas_draw_line(canvas, 0, 48, 115, 48); canvas_draw_line(canvas, 115, 14, 115, 48); diff --git a/applications/main/subghz/views/subghz_read_raw.h b/applications/main/subghz/views/subghz_read_raw.h index 31aa9db6f..83403e975 100644 --- a/applications/main/subghz/views/subghz_read_raw.h +++ b/applications/main/subghz/views/subghz_read_raw.h @@ -1,6 +1,7 @@ #pragma once #include +#include "../helpers/subghz_types.h" #include "../helpers/subghz_custom_event.h" #define SUBGHZ_RAW_THRESHOLD_MIN -90.0f @@ -36,6 +37,10 @@ void subghz_read_raw_add_data_statusbar( const char* frequency_str, const char* preset_str); +void subghz_read_raw_set_radio_device_type( + SubGhzReadRAW* instance, + SubGhzRadioDeviceType device_type); + void subghz_read_raw_update_sample_write(SubGhzReadRAW* instance, size_t sample); void subghz_read_raw_stop_send(SubGhzReadRAW* instance); diff --git a/applications/main/subghz/views/subghz_test_carrier.c b/applications/main/subghz/views/subghz_test_carrier.c index e533a6aac..254a4127b 100644 --- a/applications/main/subghz/views/subghz_test_carrier.c +++ b/applications/main/subghz/views/subghz_test_carrier.c @@ -1,6 +1,7 @@ #include "subghz_test_carrier.h" #include "../subghz_i.h" #include "../helpers/subghz_testing.h" +#include #include #include @@ -138,7 +139,7 @@ void subghz_test_carrier_enter(void* context) { SubGhzTestCarrier* subghz_test_carrier = context; furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); diff --git a/applications/main/subghz/views/subghz_test_packet.c b/applications/main/subghz/views/subghz_test_packet.c index 43502180c..bc2c474b5 100644 --- a/applications/main/subghz/views/subghz_test_packet.c +++ b/applications/main/subghz/views/subghz_test_packet.c @@ -1,6 +1,7 @@ #include "subghz_test_packet.h" #include "../subghz_i.h" #include "../helpers/subghz_testing.h" +#include #include #include @@ -194,7 +195,7 @@ void subghz_test_packet_enter(void* context) { SubGhzTestPacket* instance = context; furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); with_view_model( instance->view, diff --git a/applications/main/subghz/views/subghz_test_static.c b/applications/main/subghz/views/subghz_test_static.c index 6abefda76..197af21fb 100644 --- a/applications/main/subghz/views/subghz_test_static.c +++ b/applications/main/subghz/views/subghz_test_static.c @@ -1,6 +1,7 @@ #include "subghz_test_static.h" #include "../subghz_i.h" #include "../helpers/subghz_testing.h" +#include #include #include @@ -141,7 +142,7 @@ void subghz_test_static_enter(void* context) { SubGhzTestStatic* instance = context; furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(&gpio_cc1101_g0, false); diff --git a/applications/main/subghz/views/transmitter.c b/applications/main/subghz/views/transmitter.c index 86dc17a38..2a876f8c2 100644 --- a/applications/main/subghz/views/transmitter.c +++ b/applications/main/subghz/views/transmitter.c @@ -15,6 +15,7 @@ typedef struct { FuriString* preset_str; FuriString* key_str; bool show_button; + SubGhzRadioDeviceType device_type; } SubGhzViewTransmitterModel; void subghz_view_transmitter_set_callback( @@ -46,6 +47,17 @@ void subghz_view_transmitter_add_data_to_show( true); } +void subghz_view_transmitter_set_radio_device_type( + SubGhzViewTransmitter* subghz_transmitter, + SubGhzRadioDeviceType device_type) { + furi_assert(subghz_transmitter); + with_view_model( + subghz_transmitter->view, + SubGhzViewTransmitterModel * model, + { model->device_type = device_type; }, + true); +} + static void subghz_view_transmitter_button_right(Canvas* canvas, const char* str) { const uint8_t button_height = 12; const uint8_t vertical_offset = 3; @@ -56,7 +68,7 @@ static void subghz_view_transmitter_button_right(Canvas* canvas, const char* str const uint8_t icon_width_with_offset = icon_get_width(icon) + icon_offset; const uint8_t button_width = string_width + horizontal_offset * 2 + icon_width_with_offset; - const uint8_t x = (canvas_width(canvas) - button_width) / 2 + 40; + const uint8_t x = (canvas_width(canvas) - button_width) / 2 + 44; const uint8_t y = canvas_height(canvas); canvas_draw_box(canvas, x, y - button_height, button_width, button_height); @@ -88,7 +100,14 @@ void subghz_view_transmitter_draw(Canvas* canvas, SubGhzViewTransmitterModel* mo canvas, 0, 0, AlignLeft, AlignTop, furi_string_get_cstr(model->key_str)); canvas_draw_str(canvas, 78, 7, furi_string_get_cstr(model->frequency_str)); canvas_draw_str(canvas, 113, 7, furi_string_get_cstr(model->preset_str)); - if(model->show_button) subghz_view_transmitter_button_right(canvas, "Send"); + if(model->show_button) { + if(model->device_type == SubGhzRadioDeviceTypeInternal) { + canvas_draw_icon(canvas, 108, 39, &I_Internal_antenna_20x12); + } else { + canvas_draw_icon(canvas, 108, 39, &I_External_antenna_20x12); + } + subghz_view_transmitter_button_right(canvas, "Send"); + } } bool subghz_view_transmitter_input(InputEvent* event, void* context) { diff --git a/applications/main/subghz/views/transmitter.h b/applications/main/subghz/views/transmitter.h index 06aae7c6b..19da3145c 100644 --- a/applications/main/subghz/views/transmitter.h +++ b/applications/main/subghz/views/transmitter.h @@ -1,6 +1,7 @@ #pragma once #include +#include "../helpers/subghz_types.h" #include "../helpers/subghz_custom_event.h" typedef struct SubGhzViewTransmitter SubGhzViewTransmitter; @@ -12,6 +13,10 @@ void subghz_view_transmitter_set_callback( SubGhzViewTransmitterCallback callback, void* context); +void subghz_view_transmitter_set_radio_device_type( + SubGhzViewTransmitter* subghz_transmitter, + SubGhzRadioDeviceType device_type); + SubGhzViewTransmitter* subghz_view_transmitter_alloc(); void subghz_view_transmitter_free(SubGhzViewTransmitter* subghz_transmitter); diff --git a/assets/icons/SubGhz/External_antenna_20x12.png b/assets/icons/SubGhz/External_antenna_20x12.png new file mode 100644 index 0000000000000000000000000000000000000000..940087071a1c4225eb48383e3a93d5c841b638b2 GIT binary patch literal 990 zcmaJ=zi-n(6t>hBswf?bK&VV7S4dPe_W6LTf33i9am!vER3maae$(r__=1^b4 zsgIQSAx8^Bc`FIA(@%PtnBJf;Yd{MNa9h#))?T#XHFxqc8qrRiM;?^@z zPBc#76NW+J9|f_N=;D}H<9ceAMKE?@eOlf;6R|p#qpZB99ok9j$KdOycpAF7_A;HCY}E2GSre(Womcs;Z_O2<5m( zE*=I9C%GVApE6h^b|Noi9t}Xsh}-mp=_1eex(q*@(FXCPRlI3(fiaYAnAOQmzW*eS8^e&ubrRE)$l=55tf!$u&5Q_UG-^vCn{I?3^2ip6yqCn?iKq|8Rcqe-T+F$A6RbNw7i%t7=E=zEZ2y|| z)WjDkRcG7F53~Iz0blxvZ}*$#HV%6gRB|C29u*3tc$5LZVXRk4r*o6H_^HN`vYuq=9C{u`i9)p3m49;&em^ zfspzyAO@HKu~vL^r4xb$0YYMBKrk{Og>$~j5U^~&cTey4d%t)0?p}HA(oAAD!ExM7 zX~n28dy0M2Qt%PmE|Wp5!0>S)vTH2%kneIB@u#&2Xy$@B}T>8|VqXnkj`YVT~> zio-8m1i46M1Q<~ZM0nc^)kx!eyejkKu*id63fx1^uoCzgMmUjaDD0$55$aCowTUNGqwFTus@>p!ogOtO%o%_7iB?; z+ZraC=KoVM9%YBLf)4eLB@U|{ABhzdl2%}|!)wgNrF^vzAd8ZqO33zbC(BJjN!TPl zfN3EE&Y70&dU0gF2Qf{x!{g6=6pJ%>k=%aWVu+>mBp+A^G06Q z^$b+9L##pU7DgT&Vx2>5{-4-*BCyXY8z^vZB4;@u81%YU-7#A7c|9c+78S+^$7|_h zoiSPl*tn1JSdobl)>*yJ)S*p|h?~Q6$-f1d>2NNH}5%Lt|z{KrzQc(y-YyStJQ+g^C9Q zSWv-YttjHfh@wyt@GLFhMTjB}M;LSv6%;{^;@J%X_DAW??0&~Q&+|U-`@P@n?x@Hx zJ8Nfa0)b%14d?LjF%^HQmS*_Zy;Prz4^CJ}G`0p!z*2-Nm=GjEMKHicgo!X87D}`~ zG{XJ_!fZF0AR3G2MKHxELKK=XL=B?E*#v@rphhVa%V7)_o@3{?OoMWF~y##kV3^-~Ura#~iQo~#pIF_K28B$0`bDW@qQkN5vj1er#wF+Tj+ z?|%xb1zIIc;=^h*StZ6#E@7!Dl#l0+R;G}k zDeC1D1RjscRj4tcLJV^`ED)C<%48Czw=bJb<4}SjatMt~4q?;jbe~|z8=_EsXfzI; zGR5Vf;$#F?U{hSlXD)k2uBjOiB_5drt7MyCNvH}%fQg)$vYEXwX4ISHN@n&FG$WUU zn<1G__FpGGwS~8jX*%7w_+q;CVFljrD!j4V;}c)t_r;dW2@+`9`eU1O>Hy1H=Z_x? z#)vXQ4`HsunYK6jxY4-M*|zlR`rg;$+V*St8!R`}`J(H(M(Fn4S4n;$pnW-UN$QA` z?fY?KM*pGHedF?8-QC`CtG>sHp2-iZetB?^`cj>4f5g#9o;N06J$3^rWaoX6Zp!iN6AS8ml(v%micb;q2O2KuEfM&;;GfOLnbEbQ;Xh2MB~uUb$O z=Tf34Z;Mngv^s8}xvK?|Q)X5xaeMf&yLz=D);7(;s_;xKaAkeDy_0K?%Yn2|k9C6T z^kdg4x7}!2l%F~e-2N&yKK{I*<bm{PN1M%~EqIS+ z#{g%nih7mt;>v=&E{mA(e4W(c;<>|5`bM6gWBHY@vRSt9LE+^Uhns6zS!2UzZw(cU zoUfWE)n;PLGTwze=xNtR#E5s54 z?u4@P3{ljfm#4cr?==i}&Q~nx+6o_SALMl>7g+8+b*EGr+g0b>QusCdoqSG@XTkT} zJKW>*p7M7!ScsC+I$SWe`PeH**g7LKd+2^e4BT{9(i5Fx*_t#~^L&3q*^<`Bg8SLL zJr^&8Wvz+nlWyNPFyz7qEt>zJmbmY7f19~I|Kz}R|I(kU_SSdG*|X+`TiP_=YR)O9 z%>w2`t#*GaxqGd${KiVYrAK$bi$_|DyT^Fr>F$>+;8w9Tw&Z$d+!FWSfdT)vdK%bz zZxc14Zjp1X%kW^EaVRy?Y1r_3XHB46)J>z~?!08J+0&8}hNJx?^62efuWTu{t@zFL zVZ4jin2pbcGJ}2f!HjR`wC}%p=#A$7DVOR4RjdwPz~ZWrAMHE3V&KiltB9(rl{Yu) zpLzA}yq2xqYW6IxKLj-^F^5Q^3s;lX5 N!3~Mzlm%~0{|8*@s)qmo diff --git a/assets/icons/SubGhz/Scanning_short_96x52.png b/assets/icons/SubGhz/Scanning_short_96x52.png new file mode 100644 index 0000000000000000000000000000000000000000..718d0e695a2560bbb7ccd538c062375d2a318ffb GIT binary patch literal 1388 zcmeAS@N?(olHy`uVBq!ia0vp^2|#SZ!3-pwBG0}CQj#UE5hcO-X(i=}MX3yqDfvmM z3ZA)%>8U}fi7AzZCsS=07??FPLn2Bde0{8v^KOF1ees}+T7#dW-K+~^CEYLU9GXQxDrqI_HztY@Xxa#7Ppj3o=u^L<) zQdy9yACy|0Us{w5jJz~ukW~d%&PAz-CHX}m`T04pkPOJkFUc>?$S+VZGSM?t(C|%6 z&ddXeXo9u)`dWGB6_+IDC8v72*eU@H(aX$Cv2rvwbTM{yvotVrF*h`Hb+t5ib#ZZZ zGBYr7HZyQ^c7^G6$xklLP0cHT=}kfCb;PL`lp=BqfHu3N7G;*DrnnX5=PH1GZIy}J zE#^4QgX&Ge?G_81di8;h(FesXQe4A?fC&i1gr{C02cG^@^MHxI2$;HE)=X;#<_xv~ zpAgso|NjG-p@%NlF)%P5_jGX#skrrK#_ef`6*ydP{{Me@b6A>-Lx{=S+e`Fw7pH3% zdAs~uznOdQKDGRP;?HGHaQkgH+0OUlYP}u%=DQ!xddxlW<9jtjncLh35yqCy>x5P@ z99nmph1Eg!gFqI;m$L2IZAmtkId|qVUWuQv{-flTsXLiZSp3i5+YxWBeR>{4#?3=K zQI)4O879AZQ!=f=OphVwlFMhA6*GHUS2Jun{nDgi4&yF~hwUt~FTby;Ok>#fvsCFC zgLT90@}S8k5r-}+1~*7Jtl;ZBy)z@GLQshF(2R*k^si5`SIfI4o-plV-QgL*9Sk=a zbl8*MN4oOyJ#{*I*J09={JmL|?tkbM6X($R#JRC=Vu_J%Y75Vf{xaL$l#n(7>J9Z>Rsez4>?m+v^4&(=dnl-7VtQ3hUR|<$h?CUGgiufh#fR z%(}0KHCtpPcD3>gZd$&^{MVzu8kg;Bj?5L<)Uo%9dbPy-BY$?*-Bo?}_2;U(sTYb~ z&aKl-jNh-QDG;}};pXvkx4&CUAG$r=-JXeuLGKE4-|ks^mx9VaPgg&ebxsLQ09S_o Aa{vGU literal 0 HcmV?d00001 diff --git a/documentation/FuriHalBus.md b/documentation/FuriHalBus.md index 5c754018b..230a98050 100644 --- a/documentation/FuriHalBus.md +++ b/documentation/FuriHalBus.md @@ -78,9 +78,9 @@ The system will take over any given peripheral only when the respective feature | ADC | | | | QUADSPI | | | | TIM1 | yes | subghz, lfrfid, nfc, infrared, etc... | -| TIM2 | yes | -- | +| TIM2 | yes | subghz, infrared, etc... | | TIM16 | yes | speaker | -| TIM17 | | | +| TIM17 | yes | cc1101_ext | | LPTIM1 | yes | tickless idle timer | | LPTIM2 | yes | pwm | | SAI1 | | | @@ -104,10 +104,10 @@ Below is the list of DMA channels and their usage by the system. | -- | 5 | | | | -- | 6 | | | | -- | 7 | | | -| DMA2 | 1 | yes | infrared, lfrfid, subghz | +| DMA2 | 1 | yes | infrared, lfrfid, subghz, | | -- | 2 | yes | -- | -| -- | 3 | yes | SPI | -| -- | 4 | yes | SPI | -| -- | 5 | | | -| -- | 6 | | | -| -- | 7 | | | +| -- | 3 | yes | cc1101_ext | +| -- | 4 | yes | cc1101_ext | +| -- | 5 | yes | cc1101_ext | +| -- | 6 | yes | SPI | +| -- | 7 | yes | SPI | diff --git a/firmware/targets/f18/api_symbols.csv b/firmware/targets/f18/api_symbols.csv index a689d5a21..1884fe433 100644 --- a/firmware/targets/f18/api_symbols.csv +++ b/firmware/targets/f18/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,31.3,, +Version,+,32.0,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -283,6 +283,7 @@ Function,-,LL_mDelay,void,uint32_t Function,-,SystemCoreClockUpdate,void, Function,-,SystemInit,void, Function,-,_Exit,void,int +Function,+,__aeabi_uldivmod,void*,"uint64_t, uint64_t" Function,-,__assert,void,"const char*, int, const char*" Function,+,__assert_func,void,"const char*, int, const char*, const char*" Function,+,__clear_cache,void,"void*, void*" diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index 0183540f6..f4dec15a7 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,31.3,, +Version,+,32.0,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -56,7 +56,6 @@ Header,+,firmware/targets/f7/furi_hal/furi_hal_rfid.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_config.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_types.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_subghz.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_target_hw.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, @@ -186,6 +185,7 @@ Header,+,lib/subghz/blocks/decoder.h,, Header,+,lib/subghz/blocks/encoder.h,, Header,+,lib/subghz/blocks/generic.h,, Header,+,lib/subghz/blocks/math.h,, +Header,+,lib/subghz/devices/cc1101_configs.h,, Header,+,lib/subghz/environment.h,, Header,+,lib/subghz/protocols/raw.h,, Header,+,lib/subghz/receiver.h,, @@ -317,6 +317,7 @@ Function,-,LL_mDelay,void,uint32_t Function,-,SystemCoreClockUpdate,void, Function,-,SystemInit,void, Function,-,_Exit,void,int +Function,+,__aeabi_uldivmod,void*,"uint64_t, uint64_t" Function,-,__assert,void,"const char*, int, const char*" Function,+,__assert_func,void,"const char*, int, const char*, const char*" Function,+,__clear_cache,void,"void*, void*" @@ -657,26 +658,6 @@ Function,+,canvas_width,uint8_t,const Canvas* Function,-,cbrt,double,double Function,-,cbrtf,float,float Function,-,cbrtl,long double,long double -Function,+,cc1101_calibrate,void,FuriHalSpiBusHandle* -Function,+,cc1101_flush_rx,void,FuriHalSpiBusHandle* -Function,+,cc1101_flush_tx,void,FuriHalSpiBusHandle* -Function,-,cc1101_get_partnumber,uint8_t,FuriHalSpiBusHandle* -Function,+,cc1101_get_rssi,uint8_t,FuriHalSpiBusHandle* -Function,+,cc1101_get_status,CC1101Status,FuriHalSpiBusHandle* -Function,-,cc1101_get_version,uint8_t,FuriHalSpiBusHandle* -Function,+,cc1101_read_fifo,uint8_t,"FuriHalSpiBusHandle*, uint8_t*, uint8_t*" -Function,+,cc1101_read_reg,CC1101Status,"FuriHalSpiBusHandle*, uint8_t, uint8_t*" -Function,+,cc1101_reset,void,FuriHalSpiBusHandle* -Function,+,cc1101_set_frequency,uint32_t,"FuriHalSpiBusHandle*, uint32_t" -Function,-,cc1101_set_intermediate_frequency,uint32_t,"FuriHalSpiBusHandle*, uint32_t" -Function,+,cc1101_set_pa_table,void,"FuriHalSpiBusHandle*, const uint8_t[8]" -Function,+,cc1101_shutdown,void,FuriHalSpiBusHandle* -Function,+,cc1101_strobe,CC1101Status,"FuriHalSpiBusHandle*, uint8_t" -Function,+,cc1101_switch_to_idle,void,FuriHalSpiBusHandle* -Function,+,cc1101_switch_to_rx,void,FuriHalSpiBusHandle* -Function,+,cc1101_switch_to_tx,void,FuriHalSpiBusHandle* -Function,+,cc1101_write_fifo,uint8_t,"FuriHalSpiBusHandle*, const uint8_t*, uint8_t" -Function,+,cc1101_write_reg,CC1101Status,"FuriHalSpiBusHandle*, uint8_t, uint8_t" Function,-,ceil,double,double Function,-,ceilf,float,float Function,-,ceill,long double,long double @@ -1383,6 +1364,7 @@ Function,+,furi_hal_spi_release,void,FuriHalSpiBusHandle* Function,-,furi_hal_subghz_dump_state,void, Function,+,furi_hal_subghz_flush_rx,void, Function,+,furi_hal_subghz_flush_tx,void, +Function,+,furi_hal_subghz_get_data_gpio,const GpioPin*, Function,+,furi_hal_subghz_get_lqi,uint8_t, Function,+,furi_hal_subghz_get_rssi,float, Function,+,furi_hal_subghz_idle,void, @@ -1390,10 +1372,9 @@ Function,-,furi_hal_subghz_init,void, Function,+,furi_hal_subghz_is_async_tx_complete,_Bool, Function,+,furi_hal_subghz_is_frequency_valid,_Bool,uint32_t Function,+,furi_hal_subghz_is_rx_data_crc_valid,_Bool, -Function,+,furi_hal_subghz_load_custom_preset,void,uint8_t* +Function,+,furi_hal_subghz_load_custom_preset,void,const uint8_t* Function,+,furi_hal_subghz_load_patable,void,const uint8_t[8] -Function,+,furi_hal_subghz_load_preset,void,FuriHalSubGhzPreset -Function,+,furi_hal_subghz_load_registers,void,uint8_t* +Function,+,furi_hal_subghz_load_registers,void,const uint8_t* Function,+,furi_hal_subghz_read_packet,void,"uint8_t*, uint8_t*" Function,+,furi_hal_subghz_reset,void, Function,+,furi_hal_subghz_rx,void, @@ -1401,7 +1382,7 @@ Function,+,furi_hal_subghz_rx_pipe_not_empty,_Bool, Function,+,furi_hal_subghz_set_async_mirror_pin,void,const GpioPin* Function,+,furi_hal_subghz_set_frequency,uint32_t,uint32_t Function,+,furi_hal_subghz_set_frequency_and_path,uint32_t,uint32_t -Function,+,furi_hal_subghz_set_path,void,FuriHalSubGhzPath +Function,-,furi_hal_subghz_set_path,void,FuriHalSubGhzPath Function,-,furi_hal_subghz_shutdown,void, Function,+,furi_hal_subghz_sleep,void, Function,+,furi_hal_subghz_start_async_rx,void,"FuriHalSubGhzCaptureCallback, void*" @@ -2686,6 +2667,36 @@ Function,+,subghz_block_generic_deserialize,SubGhzProtocolStatus,"SubGhzBlockGen Function,+,subghz_block_generic_deserialize_check_count_bit,SubGhzProtocolStatus,"SubGhzBlockGeneric*, FlipperFormat*, uint16_t" Function,+,subghz_block_generic_get_preset_name,void,"const char*, FuriString*" Function,+,subghz_block_generic_serialize,SubGhzProtocolStatus,"SubGhzBlockGeneric*, FlipperFormat*, SubGhzRadioPreset*" +Function,+,subghz_devices_begin,_Bool,const SubGhzDevice* +Function,+,subghz_devices_deinit,void, +Function,+,subghz_devices_end,void,const SubGhzDevice* +Function,+,subghz_devices_flush_rx,void,const SubGhzDevice* +Function,+,subghz_devices_flush_tx,void,const SubGhzDevice* +Function,+,subghz_devices_get_by_name,const SubGhzDevice*,const char* +Function,+,subghz_devices_get_data_gpio,const GpioPin*,const SubGhzDevice* +Function,+,subghz_devices_get_lqi,uint8_t,const SubGhzDevice* +Function,+,subghz_devices_get_name,const char*,const SubGhzDevice* +Function,+,subghz_devices_get_rssi,float,const SubGhzDevice* +Function,+,subghz_devices_idle,void,const SubGhzDevice* +Function,+,subghz_devices_init,void, +Function,+,subghz_devices_is_async_complete_tx,_Bool,const SubGhzDevice* +Function,+,subghz_devices_is_connect,_Bool,const SubGhzDevice* +Function,+,subghz_devices_is_frequency_valid,_Bool,"const SubGhzDevice*, uint32_t" +Function,+,subghz_devices_is_rx_data_crc_valid,_Bool,const SubGhzDevice* +Function,+,subghz_devices_load_preset,void,"const SubGhzDevice*, FuriHalSubGhzPreset, uint8_t*" +Function,+,subghz_devices_read_packet,void,"const SubGhzDevice*, uint8_t*, uint8_t*" +Function,+,subghz_devices_reset,void,const SubGhzDevice* +Function,+,subghz_devices_rx_pipe_not_empty,_Bool,const SubGhzDevice* +Function,+,subghz_devices_set_async_mirror_pin,void,"const SubGhzDevice*, const GpioPin*" +Function,+,subghz_devices_set_frequency,uint32_t,"const SubGhzDevice*, uint32_t" +Function,+,subghz_devices_set_rx,void,const SubGhzDevice* +Function,+,subghz_devices_set_tx,_Bool,const SubGhzDevice* +Function,+,subghz_devices_sleep,void,const SubGhzDevice* +Function,+,subghz_devices_start_async_rx,void,"const SubGhzDevice*, void*, void*" +Function,+,subghz_devices_start_async_tx,_Bool,"const SubGhzDevice*, void*, void*" +Function,+,subghz_devices_stop_async_rx,void,const SubGhzDevice* +Function,+,subghz_devices_stop_async_tx,void,const SubGhzDevice* +Function,+,subghz_devices_write_packet,void,"const SubGhzDevice*, const uint8_t*, uint8_t" Function,+,subghz_environment_alloc,SubGhzEnvironment*, Function,+,subghz_environment_free,void,SubGhzEnvironment* Function,+,subghz_environment_get_alutech_at_4n_rainbow_table_file_name,const char*,SubGhzEnvironment* @@ -2744,7 +2755,7 @@ Function,+,subghz_protocol_encoder_raw_free,void,void* Function,+,subghz_protocol_encoder_raw_stop,void,void* Function,+,subghz_protocol_encoder_raw_yield,LevelDuration,void* Function,+,subghz_protocol_raw_file_encoder_worker_set_callback_end,void,"SubGhzProtocolEncoderRAW*, SubGhzProtocolEncoderRAWCallbackEnd, void*" -Function,+,subghz_protocol_raw_gen_fff_data,void,"FlipperFormat*, const char*" +Function,+,subghz_protocol_raw_gen_fff_data,void,"FlipperFormat*, const char*, const char*" Function,+,subghz_protocol_raw_get_sample_write,size_t,SubGhzProtocolDecoderRAW* Function,+,subghz_protocol_raw_save_to_file_init,_Bool,"SubGhzProtocolDecoderRAW*, const char*, SubGhzRadioPreset*" Function,+,subghz_protocol_raw_save_to_file_pause,void,"SubGhzProtocolDecoderRAW*, _Bool" @@ -2788,7 +2799,7 @@ Function,+,subghz_tx_rx_worker_free,void,SubGhzTxRxWorker* Function,+,subghz_tx_rx_worker_is_running,_Bool,SubGhzTxRxWorker* Function,+,subghz_tx_rx_worker_read,size_t,"SubGhzTxRxWorker*, uint8_t*, size_t" Function,+,subghz_tx_rx_worker_set_callback_have_read,void,"SubGhzTxRxWorker*, SubGhzTxRxWorkerCallbackHaveRead, void*" -Function,+,subghz_tx_rx_worker_start,_Bool,"SubGhzTxRxWorker*, uint32_t" +Function,+,subghz_tx_rx_worker_start,_Bool,"SubGhzTxRxWorker*, const SubGhzDevice*, uint32_t" Function,+,subghz_tx_rx_worker_stop,void,SubGhzTxRxWorker* Function,+,subghz_tx_rx_worker_write,_Bool,"SubGhzTxRxWorker*, uint8_t*, size_t" Function,+,subghz_worker_alloc,SubGhzWorker*, @@ -3389,6 +3400,12 @@ Variable,+,sequence_set_vibro_on,const NotificationSequence, Variable,+,sequence_single_vibro,const NotificationSequence, Variable,+,sequence_solid_yellow,const NotificationSequence, Variable,+,sequence_success,const NotificationSequence, +Variable,+,subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs,const uint8_t[], +Variable,+,subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs,const uint8_t[], +Variable,+,subghz_device_cc1101_preset_gfsk_9_99kb_async_regs,const uint8_t[], +Variable,+,subghz_device_cc1101_preset_msk_99_97kb_async_regs,const uint8_t[], +Variable,+,subghz_device_cc1101_preset_ook_270khz_async_regs,const uint8_t[], +Variable,+,subghz_device_cc1101_preset_ook_650khz_async_regs,const uint8_t[], Variable,+,subghz_protocol_raw,const SubGhzProtocol, Variable,+,subghz_protocol_raw_decoder,const SubGhzProtocolDecoder, Variable,+,subghz_protocol_raw_encoder,const SubGhzProtocolEncoder, diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi.c b/firmware/targets/f7/furi_hal/furi_hal_spi.c index 42b854799..17769832b 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_spi.c +++ b/firmware/targets/f7/furi_hal/furi_hal_spi.c @@ -12,10 +12,10 @@ #define TAG "FuriHalSpi" #define SPI_DMA DMA2 -#define SPI_DMA_RX_CHANNEL LL_DMA_CHANNEL_3 -#define SPI_DMA_TX_CHANNEL LL_DMA_CHANNEL_4 -#define SPI_DMA_RX_IRQ FuriHalInterruptIdDma2Ch3 -#define SPI_DMA_TX_IRQ FuriHalInterruptIdDma2Ch4 +#define SPI_DMA_RX_CHANNEL LL_DMA_CHANNEL_6 +#define SPI_DMA_TX_CHANNEL LL_DMA_CHANNEL_7 +#define SPI_DMA_RX_IRQ FuriHalInterruptIdDma2Ch6 +#define SPI_DMA_TX_IRQ FuriHalInterruptIdDma2Ch7 #define SPI_DMA_RX_DEF SPI_DMA, SPI_DMA_RX_CHANNEL #define SPI_DMA_TX_DEF SPI_DMA, SPI_DMA_TX_CHANNEL @@ -170,18 +170,18 @@ bool furi_hal_spi_bus_trx( } static void spi_dma_isr() { -#if SPI_DMA_RX_CHANNEL == LL_DMA_CHANNEL_3 - if(LL_DMA_IsActiveFlag_TC3(SPI_DMA) && LL_DMA_IsEnabledIT_TC(SPI_DMA_RX_DEF)) { - LL_DMA_ClearFlag_TC3(SPI_DMA); +#if SPI_DMA_RX_CHANNEL == LL_DMA_CHANNEL_6 + if(LL_DMA_IsActiveFlag_TC6(SPI_DMA) && LL_DMA_IsEnabledIT_TC(SPI_DMA_RX_DEF)) { + LL_DMA_ClearFlag_TC6(SPI_DMA); furi_check(furi_semaphore_release(spi_dma_completed) == FuriStatusOk); } #else #error Update this code. Would you kindly? #endif -#if SPI_DMA_TX_CHANNEL == LL_DMA_CHANNEL_4 - if(LL_DMA_IsActiveFlag_TC4(SPI_DMA) && LL_DMA_IsEnabledIT_TC(SPI_DMA_TX_DEF)) { - LL_DMA_ClearFlag_TC4(SPI_DMA); +#if SPI_DMA_TX_CHANNEL == LL_DMA_CHANNEL_7 + if(LL_DMA_IsActiveFlag_TC7(SPI_DMA) && LL_DMA_IsEnabledIT_TC(SPI_DMA_TX_DEF)) { + LL_DMA_ClearFlag_TC7(SPI_DMA); furi_check(furi_semaphore_release(spi_dma_completed) == FuriStatusOk); } #else @@ -241,8 +241,8 @@ bool furi_hal_spi_bus_trx_dma( dma_config.Priority = LL_DMA_PRIORITY_MEDIUM; LL_DMA_Init(SPI_DMA_TX_DEF, &dma_config); -#if SPI_DMA_TX_CHANNEL == LL_DMA_CHANNEL_4 - LL_DMA_ClearFlag_TC4(SPI_DMA); +#if SPI_DMA_TX_CHANNEL == LL_DMA_CHANNEL_7 + LL_DMA_ClearFlag_TC7(SPI_DMA); #else #error Update this code. Would you kindly? #endif @@ -315,8 +315,8 @@ bool furi_hal_spi_bus_trx_dma( dma_config.Priority = LL_DMA_PRIORITY_MEDIUM; LL_DMA_Init(SPI_DMA_RX_DEF, &dma_config); -#if SPI_DMA_RX_CHANNEL == LL_DMA_CHANNEL_3 - LL_DMA_ClearFlag_TC3(SPI_DMA); +#if SPI_DMA_RX_CHANNEL == LL_DMA_CHANNEL_6 + LL_DMA_ClearFlag_TC6(SPI_DMA); #else #error Update this code. Would you kindly? #endif diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.c b/firmware/targets/f7/furi_hal/furi_hal_subghz.c index 6d671a9e1..ac5adefb8 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz.c +++ b/firmware/targets/f7/furi_hal/furi_hal_subghz.c @@ -1,6 +1,5 @@ #include -#include - +#include #include #include #include @@ -27,17 +26,36 @@ static uint32_t furi_hal_subghz_debug_gpio_buff[2]; #define SUBGHZ_DMA_CH1_DEF SUBGHZ_DMA, SUBGHZ_DMA_CH1_CHANNEL #define SUBGHZ_DMA_CH2_DEF SUBGHZ_DMA, SUBGHZ_DMA_CH2_CHANNEL +/** SubGhz state */ +typedef enum { + SubGhzStateInit, /**< Init pending */ + + SubGhzStateIdle, /**< Idle, energy save mode */ + + SubGhzStateAsyncRx, /**< Async RX started */ + + SubGhzStateAsyncTx, /**< Async TX started, DMA and timer is on */ + SubGhzStateAsyncTxLast, /**< Async TX continue, DMA completed and timer got last value to go */ + SubGhzStateAsyncTxEnd, /**< Async TX complete, cleanup needed */ + +} SubGhzState; + +/** SubGhz regulation, receive transmission on the current frequency for the + * region */ +typedef enum { + SubGhzRegulationOnlyRx, /**only Rx*/ + SubGhzRegulationTxRx, /**TxRx*/ +} SubGhzRegulation; + typedef struct { volatile SubGhzState state; volatile SubGhzRegulation regulation; - volatile FuriHalSubGhzPreset preset; const GpioPin* async_mirror_pin; } FuriHalSubGhz; volatile FuriHalSubGhz furi_hal_subghz = { .state = SubGhzStateInit, .regulation = SubGhzRegulationTxRx, - .preset = FuriHalSubGhzPresetIDLE, .async_mirror_pin = NULL, }; @@ -45,10 +63,13 @@ void furi_hal_subghz_set_async_mirror_pin(const GpioPin* pin) { furi_hal_subghz.async_mirror_pin = pin; } +const GpioPin* furi_hal_subghz_get_data_gpio() { + return &gpio_cc1101_g0; +} + void furi_hal_subghz_init() { furi_assert(furi_hal_subghz.state == SubGhzStateInit); furi_hal_subghz.state = SubGhzStateIdle; - furi_hal_subghz.preset = FuriHalSubGhzPresetIDLE; furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); @@ -102,8 +123,6 @@ void furi_hal_subghz_sleep() { cc1101_shutdown(&furi_hal_spi_bus_handle_subghz); furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); - - furi_hal_subghz.preset = FuriHalSubGhzPresetIDLE; } void furi_hal_subghz_dump_state() { @@ -115,34 +134,7 @@ void furi_hal_subghz_dump_state() { furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } -void furi_hal_subghz_load_preset(FuriHalSubGhzPreset preset) { - if(preset == FuriHalSubGhzPresetOok650Async) { - furi_hal_subghz_load_registers((uint8_t*)furi_hal_subghz_preset_ook_650khz_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_ook_async_patable); - } else if(preset == FuriHalSubGhzPresetOok270Async) { - furi_hal_subghz_load_registers((uint8_t*)furi_hal_subghz_preset_ook_270khz_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_ook_async_patable); - } else if(preset == FuriHalSubGhzPreset2FSKDev238Async) { - furi_hal_subghz_load_registers( - (uint8_t*)furi_hal_subghz_preset_2fsk_dev2_38khz_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_2fsk_async_patable); - } else if(preset == FuriHalSubGhzPreset2FSKDev476Async) { - furi_hal_subghz_load_registers( - (uint8_t*)furi_hal_subghz_preset_2fsk_dev47_6khz_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_2fsk_async_patable); - } else if(preset == FuriHalSubGhzPresetMSK99_97KbAsync) { - furi_hal_subghz_load_registers((uint8_t*)furi_hal_subghz_preset_msk_99_97kb_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_msk_async_patable); - } else if(preset == FuriHalSubGhzPresetGFSK9_99KbAsync) { - furi_hal_subghz_load_registers((uint8_t*)furi_hal_subghz_preset_gfsk_9_99kb_async_regs); - furi_hal_subghz_load_patable(furi_hal_subghz_preset_gfsk_async_patable); - } else { - furi_crash("SubGhz: Missing config."); - } - furi_hal_subghz.preset = preset; -} - -void furi_hal_subghz_load_custom_preset(uint8_t* preset_data) { +void furi_hal_subghz_load_custom_preset(const uint8_t* preset_data) { //load config furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); cc1101_reset(&furi_hal_spi_bus_handle_subghz); @@ -157,7 +149,6 @@ void furi_hal_subghz_load_custom_preset(uint8_t* preset_data) { //load pa table memcpy(&pa[0], &preset_data[i + 2], 8); furi_hal_subghz_load_patable(pa); - furi_hal_subghz.preset = FuriHalSubGhzPresetCustom; //show debug if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { @@ -173,7 +164,7 @@ void furi_hal_subghz_load_custom_preset(uint8_t* preset_data) { } } -void furi_hal_subghz_load_registers(uint8_t* data) { +void furi_hal_subghz_load_registers(const uint8_t* data) { furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); cc1101_reset(&furi_hal_spi_bus_handle_subghz); uint32_t i = 0; diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.h b/firmware/targets/f7/furi_hal/furi_hal_subghz.h index 102981dbe..855ce3161 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz.h +++ b/firmware/targets/f7/furi_hal/furi_hal_subghz.h @@ -5,6 +5,8 @@ #pragma once +#include + #include #include #include @@ -20,18 +22,6 @@ extern "C" { #define API_HAL_SUBGHZ_ASYNC_TX_BUFFER_HALF (API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL / 2) #define API_HAL_SUBGHZ_ASYNC_TX_GUARD_TIME 999 -/** Radio Presets */ -typedef enum { - FuriHalSubGhzPresetIDLE, /**< default configuration */ - FuriHalSubGhzPresetOok270Async, /**< OOK, bandwidth 270kHz, asynchronous */ - FuriHalSubGhzPresetOok650Async, /**< OOK, bandwidth 650kHz, asynchronous */ - FuriHalSubGhzPreset2FSKDev238Async, /**< FM, deviation 2.380371 kHz, asynchronous */ - FuriHalSubGhzPreset2FSKDev476Async, /**< FM, deviation 47.60742 kHz, asynchronous */ - FuriHalSubGhzPresetMSK99_97KbAsync, /**< MSK, deviation 47.60742 kHz, 99.97Kb/s, asynchronous */ - FuriHalSubGhzPresetGFSK9_99KbAsync, /**< GFSK, deviation 19.042969 kHz, 9.996Kb/s, asynchronous */ - FuriHalSubGhzPresetCustom, /**Custom Preset*/ -} FuriHalSubGhzPreset; - /** Switchable Radio Paths */ typedef enum { FuriHalSubGhzPathIsolate, /**< Isolate Radio from antenna */ @@ -40,27 +30,6 @@ typedef enum { FuriHalSubGhzPath868, /**< Center Frequency: 868MHz. Path 3: SW1RF3-SW2RF3, LCLC */ } FuriHalSubGhzPath; -/** SubGhz state */ -typedef enum { - SubGhzStateInit, /**< Init pending */ - - SubGhzStateIdle, /**< Idle, energy save mode */ - - SubGhzStateAsyncRx, /**< Async RX started */ - - SubGhzStateAsyncTx, /**< Async TX started, DMA and timer is on */ - SubGhzStateAsyncTxLast, /**< Async TX continue, DMA completed and timer got last value to go */ - SubGhzStateAsyncTxEnd, /**< Async TX complete, cleanup needed */ - -} SubGhzState; - -/** SubGhz regulation, receive transmission on the current frequency for the - * region */ -typedef enum { - SubGhzRegulationOnlyRx, /**only Rx*/ - SubGhzRegulationTxRx, /**TxRx*/ -} SubGhzRegulation; - /* Mirror RX/TX async modulation signal to specified pin * * @warning Configures pin to output mode. Make sure it is not connected @@ -70,6 +39,12 @@ typedef enum { */ void furi_hal_subghz_set_async_mirror_pin(const GpioPin* pin); +/** Get data GPIO + * + * @return pointer to the gpio pin structure + */ +const GpioPin* furi_hal_subghz_get_data_gpio(); + /** Initialize and switch to power save mode Used by internal API-HAL * initialization routine Can be used to reinitialize device to safe state and * send it to sleep @@ -84,23 +59,17 @@ void furi_hal_subghz_sleep(); */ void furi_hal_subghz_dump_state(); -/** Load registers from preset by preset name - * - * @param preset to load - */ -void furi_hal_subghz_load_preset(FuriHalSubGhzPreset preset); - /** Load custom registers from preset * * @param preset_data registers to load */ -void furi_hal_subghz_load_custom_preset(uint8_t* preset_data); +void furi_hal_subghz_load_custom_preset(const uint8_t* preset_data); /** Load registers * * @param data Registers data */ -void furi_hal_subghz_load_registers(uint8_t* data); +void furi_hal_subghz_load_registers(const uint8_t* data); /** Load PATABLE * diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h b/firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h deleted file mode 100644 index 5ea17b6dd..000000000 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h +++ /dev/null @@ -1,314 +0,0 @@ -#pragma once - -#include - -static const uint8_t furi_hal_subghz_preset_ook_270khz_async_regs[][2] = { - // https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration - - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x0D}, // GD0 as async serial data output/input - - /* FIFO and internals */ - {CC1101_FIFOTHR, 0x47}, // The only important bit is ADC_RETENTION, FIFO Tx=33 Rx=32 - - /* 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, 0x32}, // Data rate is 3.79372 kBaud - {CC1101_MDMCFG4, 0x67}, // Rx BW filter is 270.833333kHz - - /* 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, - 0x40}, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB 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, 0x03}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 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}, -}; - -static const uint8_t furi_hal_subghz_preset_ook_650khz_async_regs[][2] = { - // https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration - - /* 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, 0x32}, // Data rate is 3.79372 kBaud - {CC1101_MDMCFG4, 0x17}, // 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_AGCTRL0,0x40}, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB boundary - // {CC1101_AGCTRL1,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, 0x03}, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 dB - //MAGN_TARGET for RX filter BW =< 100 kHz is 0x3. For higher RX filter BW's MAGN_TARGET is 0x7. - {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}, -}; - -static const uint8_t furi_hal_subghz_preset_2fsk_dev2_38khz_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) - {CC1101_MDMCFG3, 0x83}, // Data rate is 4.79794 kBaud - {CC1101_MDMCFG4, 0x67}, //Rx BW filter is 270.833333 kHz - {CC1101_DEVIATN, 0x04}, //Deviation 2.380371 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}, -}; - -static const uint8_t furi_hal_subghz_preset_2fsk_dev47_6khz_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) - {CC1101_MDMCFG3, 0x83}, // Data rate is 4.79794 kBaud - {CC1101_MDMCFG4, 0x67}, //Rx BW filter is 270.833333 kHz - {CC1101_DEVIATN, 0x47}, //Deviation 47.60742 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}, -}; - -static const uint8_t furi_hal_subghz_preset_msk_99_97kb_async_regs[][2] = { - /* GPIO GD0 */ - {CC1101_IOCFG0, 0x06}, - - {CC1101_FIFOTHR, 0x07}, // The only important bit is ADC_RETENTION - {CC1101_SYNC1, 0x46}, - {CC1101_SYNC0, 0x4C}, - {CC1101_ADDR, 0x00}, - {CC1101_PKTLEN, 0x00}, - {CC1101_CHANNR, 0x00}, - - {CC1101_PKTCTRL0, 0x05}, - - {CC1101_FSCTRL0, 0x23}, - {CC1101_FSCTRL1, 0x06}, - - {CC1101_MDMCFG0, 0xF8}, - {CC1101_MDMCFG1, 0x22}, - {CC1101_MDMCFG2, 0x72}, - {CC1101_MDMCFG3, 0xF8}, - {CC1101_MDMCFG4, 0x5B}, - {CC1101_DEVIATN, 0x47}, - - {CC1101_MCSM0, 0x18}, - {CC1101_FOCCFG, 0x16}, - - {CC1101_AGCCTRL0, 0xB2}, - {CC1101_AGCCTRL1, 0x00}, - {CC1101_AGCCTRL2, 0xC7}, - - {CC1101_FREND0, 0x10}, - {CC1101_FREND1, 0x56}, - - {CC1101_BSCFG, 0x1C}, - {CC1101_FSTEST, 0x59}, - - /* End */ - {0, 0}, -}; - -static const uint8_t furi_hal_subghz_preset_gfsk_9_99kb_async_regs[][2] = { - - {CC1101_IOCFG0, 0x06}, //GDO0 Output Pin Configuration - {CC1101_FIFOTHR, 0x47}, //RX FIFO and TX FIFO Thresholds - - //1 : CRC calculation in TX and CRC check in RX enabled, - //1 : Variable packet length mode. Packet length configured by the first byte after sync word - {CC1101_PKTCTRL0, 0x05}, - - {CC1101_FSCTRL1, 0x06}, //Frequency Synthesizer Control - - {CC1101_SYNC1, 0x46}, - {CC1101_SYNC0, 0x4C}, - {CC1101_ADDR, 0x00}, - {CC1101_PKTLEN, 0x00}, - - {CC1101_MDMCFG4, 0xC8}, //Modem Configuration 9.99 - {CC1101_MDMCFG3, 0x93}, //Modem Configuration - {CC1101_MDMCFG2, 0x12}, // 2: 16/16 sync word bits detected - - {CC1101_DEVIATN, 0x34}, //Deviation = 19.042969 - {CC1101_MCSM0, 0x18}, //Main Radio Control State Machine Configuration - {CC1101_FOCCFG, 0x16}, //Frequency Offset Compensation Configuration - - {CC1101_AGCCTRL2, 0x43}, //AGC Control - {CC1101_AGCCTRL1, 0x40}, - {CC1101_AGCCTRL0, 0x91}, - - {CC1101_WORCTRL, 0xFB}, //Wake On Radio Control - /* End */ - {0, 0}, -}; - -static const uint8_t furi_hal_subghz_preset_ook_async_patable[8] = { - 0x00, - 0xC0, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}; - -static const uint8_t furi_hal_subghz_preset_ook_async_patable_au[8] = { - 0x00, - 0x37, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}; - -static const uint8_t furi_hal_subghz_preset_2fsk_async_patable[8] = { - 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}; - -static const uint8_t furi_hal_subghz_preset_msk_async_patable[8] = { - 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}; - -static const uint8_t furi_hal_subghz_preset_gfsk_async_patable[8] = { - 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}; diff --git a/firmware/targets/f7/platform_specific/intrinsic_export.h b/firmware/targets/f7/platform_specific/intrinsic_export.h index 8dbc4bd03..ca343a128 100644 --- a/firmware/targets/f7/platform_specific/intrinsic_export.h +++ b/firmware/targets/f7/platform_specific/intrinsic_export.h @@ -1,10 +1,12 @@ #include +#include #ifdef __cplusplus extern "C" { #endif void __clear_cache(void*, void*); +void* __aeabi_uldivmod(uint64_t, uint64_t); #ifdef __cplusplus } diff --git a/lib/subghz/SConscript b/lib/subghz/SConscript index 3a0325b71..2c42a5157 100644 --- a/lib/subghz/SConscript +++ b/lib/subghz/SConscript @@ -19,6 +19,7 @@ env.Append( File("blocks/math.h"), File("subghz_setting.h"), File("subghz_protocol_registry.h"), + File("devices/cc1101_configs.h"), ], ) diff --git a/lib/subghz/devices/cc1101_configs.c b/lib/subghz/devices/cc1101_configs.c new file mode 100644 index 000000000..35ddccd54 --- /dev/null +++ b/lib/subghz/devices/cc1101_configs.c @@ -0,0 +1,431 @@ +#include "cc1101_configs.h" +#include + +const uint8_t subghz_device_cc1101_preset_ook_270khz_async_regs[] = { + // https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration + + /* GPIO GD0 */ + CC1101_IOCFG0, + 0x0D, // GD0 as async serial data output/input + + /* FIFO and internals */ + CC1101_FIFOTHR, + 0x47, // The only important bit is ADC_RETENTION, FIFO Tx=33 Rx=32 + + /* 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, + 0x32, // Data rate is 3.79372 kBaud + CC1101_MDMCFG4, + 0x67, // Rx BW filter is 270.833333kHz + + /* 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, + 0x40, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB 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, + 0x03, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 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 load reg */ + 0, + 0, + + //ook_async_patable[8] + 0x00, + 0xC0, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; + +const uint8_t subghz_device_cc1101_preset_ook_650khz_async_regs[] = { + // https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz-group/sub-1-ghz/f/sub-1-ghz-forum/382066/cc1101---don-t-know-the-correct-registers-configuration + + /* 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, + 0x32, // Data rate is 3.79372 kBaud + CC1101_MDMCFG4, + 0x17, // 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_AGCTRL0,0x40, // 01 - Low hysteresis, small asymmetric dead zone, medium gain; 00 - 8 samples agc; 00 - Normal AGC, 00 - 4dB boundary + // CC1101_AGCTRL1,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, 0x03, // 00 - DVGA all; 000 - MAX LNA+LNA2; 011 - MAIN_TARGET 24 dB + //MAGN_TARGET for RX filter BW =< 100 kHz is 0x3. For higher RX filter BW's MAGN_TARGET is 0x7. + 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 load reg */ + 0, + 0, + + //ook_async_patable[8] + 0x00, + 0xC0, // 12dBm 0xC0, 10dBm 0xC5, 7dBm 0xCD, 5dBm 0x86, 0dBm 0x50, -6dBm 0x37, -10dBm 0x26, -15dBm 0x1D, -20dBm 0x17, -30dBm 0x03 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; + +const uint8_t subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs[] = { + + /* 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) + CC1101_MDMCFG3, + 0x83, // Data rate is 4.79794 kBaud + CC1101_MDMCFG4, + 0x67, //Rx BW filter is 270.833333 kHz + CC1101_DEVIATN, + 0x04, //Deviation 2.380371 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 load reg */ + 0, + 0, + + // 2fsk_async_patable[8] + 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; + +const uint8_t subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs[] = { + + /* 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) + CC1101_MDMCFG3, + 0x83, // Data rate is 4.79794 kBaud + CC1101_MDMCFG4, + 0x67, //Rx BW filter is 270.833333 kHz + CC1101_DEVIATN, + 0x47, //Deviation 47.60742 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 load reg */ + 0, + 0, + + // 2fsk_async_patable[8] + 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; + +const uint8_t subghz_device_cc1101_preset_msk_99_97kb_async_regs[] = { + /* GPIO GD0 */ + CC1101_IOCFG0, + 0x06, + + CC1101_FIFOTHR, + 0x07, // The only important bit is ADC_RETENTION + CC1101_SYNC1, + 0x46, + CC1101_SYNC0, + 0x4C, + CC1101_ADDR, + 0x00, + CC1101_PKTLEN, + 0x00, + CC1101_CHANNR, + 0x00, + + CC1101_PKTCTRL0, + 0x05, + + CC1101_FSCTRL0, + 0x23, + CC1101_FSCTRL1, + 0x06, + + CC1101_MDMCFG0, + 0xF8, + CC1101_MDMCFG1, + 0x22, + CC1101_MDMCFG2, + 0x72, + CC1101_MDMCFG3, + 0xF8, + CC1101_MDMCFG4, + 0x5B, + CC1101_DEVIATN, + 0x47, + + CC1101_MCSM0, + 0x18, + CC1101_FOCCFG, + 0x16, + + CC1101_AGCCTRL0, + 0xB2, + CC1101_AGCCTRL1, + 0x00, + CC1101_AGCCTRL2, + 0xC7, + + CC1101_FREND0, + 0x10, + CC1101_FREND1, + 0x56, + + CC1101_BSCFG, + 0x1C, + CC1101_FSTEST, + 0x59, + + /* End load reg */ + 0, + 0, + + // msk_async_patable[8] + 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; + +const uint8_t subghz_device_cc1101_preset_gfsk_9_99kb_async_regs[] = { + + CC1101_IOCFG0, + 0x06, //GDO0 Output Pin Configuration + CC1101_FIFOTHR, + 0x47, //RX FIFO and TX FIFO Thresholds + + //1 : CRC calculation in TX and CRC check in RX enabled, + //1 : Variable packet length mode. Packet length configured by the first byte after sync word + CC1101_PKTCTRL0, + 0x05, + + CC1101_FSCTRL1, + 0x06, //Frequency Synthesizer Control + + CC1101_SYNC1, + 0x46, + CC1101_SYNC0, + 0x4C, + CC1101_ADDR, + 0x00, + CC1101_PKTLEN, + 0x00, + + CC1101_MDMCFG4, + 0xC8, //Modem Configuration 9.99 + CC1101_MDMCFG3, + 0x93, //Modem Configuration + CC1101_MDMCFG2, + 0x12, // 2: 16/16 sync word bits detected + + CC1101_DEVIATN, + 0x34, //Deviation = 19.042969 + CC1101_MCSM0, + 0x18, //Main Radio Control State Machine Configuration + CC1101_FOCCFG, + 0x16, //Frequency Offset Compensation Configuration + + CC1101_AGCCTRL2, + 0x43, //AGC Control + CC1101_AGCCTRL1, + 0x40, + CC1101_AGCCTRL0, + 0x91, + + CC1101_WORCTRL, + 0xFB, //Wake On Radio Control + + /* End load reg */ + 0, + 0, + + // gfsk_async_patable[8] + 0xC0, // 10dBm 0xC0, 7dBm 0xC8, 5dBm 0x84, 0dBm 0x60, -10dBm 0x34, -15dBm 0x1D, -20dBm 0x0E, -30dBm 0x12 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, +}; diff --git a/lib/subghz/devices/cc1101_configs.h b/lib/subghz/devices/cc1101_configs.h new file mode 100644 index 000000000..eecab01d9 --- /dev/null +++ b/lib/subghz/devices/cc1101_configs.h @@ -0,0 +1,18 @@ +#pragma once +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const uint8_t subghz_device_cc1101_preset_ook_270khz_async_regs[]; +extern const uint8_t subghz_device_cc1101_preset_ook_650khz_async_regs[]; +extern const uint8_t subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs[]; +extern const uint8_t subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs[]; +extern const uint8_t subghz_device_cc1101_preset_msk_99_97kb_async_regs[]; +extern const uint8_t subghz_device_cc1101_preset_gfsk_9_99kb_async_regs[]; + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.c b/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.c new file mode 100644 index 000000000..41a0609df --- /dev/null +++ b/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.c @@ -0,0 +1,96 @@ +#include "cc1101_int_interconnect.h" +#include +#include "../cc1101_configs.h" + +#define TAG "SubGhzDeviceCC1101Int" + +static bool subghz_device_cc1101_int_interconnect_is_frequency_valid(uint32_t frequency) { + bool ret = furi_hal_subghz_is_frequency_valid(frequency); + if(!ret) { + furi_crash("SubGhz: Incorrect frequency."); + } + return ret; +} + +static uint32_t subghz_device_cc1101_int_interconnect_set_frequency(uint32_t frequency) { + subghz_device_cc1101_int_interconnect_is_frequency_valid(frequency); + return furi_hal_subghz_set_frequency_and_path(frequency); +} + +static bool subghz_device_cc1101_int_interconnect_start_async_tx(void* callback, void* context) { + return furi_hal_subghz_start_async_tx((FuriHalSubGhzAsyncTxCallback)callback, context); +} + +static void subghz_device_cc1101_int_interconnect_start_async_rx(void* callback, void* context) { + furi_hal_subghz_start_async_rx((FuriHalSubGhzCaptureCallback)callback, context); +} + +static void subghz_device_cc1101_int_interconnect_load_preset( + FuriHalSubGhzPreset preset, + uint8_t* preset_data) { + switch(preset) { + case FuriHalSubGhzPresetOok650Async: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); + break; + case FuriHalSubGhzPresetOok270Async: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_270khz_async_regs); + break; + case FuriHalSubGhzPreset2FSKDev238Async: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs); + break; + case FuriHalSubGhzPreset2FSKDev476Async: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs); + break; + case FuriHalSubGhzPresetMSK99_97KbAsync: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_msk_99_97kb_async_regs); + break; + case FuriHalSubGhzPresetGFSK9_99KbAsync: + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_gfsk_9_99kb_async_regs); + break; + + default: + furi_hal_subghz_load_custom_preset(preset_data); + } +} + +static bool subghz_device_cc1101_int_interconnect_is_connect(void) { + return true; +} + +const SubGhzDeviceInterconnect subghz_device_cc1101_int_interconnect = { + .begin = NULL, + .end = furi_hal_subghz_shutdown, + .is_connect = subghz_device_cc1101_int_interconnect_is_connect, + .reset = furi_hal_subghz_reset, + .sleep = furi_hal_subghz_sleep, + .idle = furi_hal_subghz_idle, + .load_preset = subghz_device_cc1101_int_interconnect_load_preset, + .set_frequency = subghz_device_cc1101_int_interconnect_set_frequency, + .is_frequency_valid = furi_hal_subghz_is_frequency_valid, + .set_async_mirror_pin = furi_hal_subghz_set_async_mirror_pin, + .get_data_gpio = furi_hal_subghz_get_data_gpio, + + .set_tx = furi_hal_subghz_tx, + .flush_tx = furi_hal_subghz_flush_tx, + .start_async_tx = subghz_device_cc1101_int_interconnect_start_async_tx, + .is_async_complete_tx = furi_hal_subghz_is_async_tx_complete, + .stop_async_tx = furi_hal_subghz_stop_async_tx, + + .set_rx = furi_hal_subghz_rx, + .flush_rx = furi_hal_subghz_flush_rx, + .start_async_rx = subghz_device_cc1101_int_interconnect_start_async_rx, + .stop_async_rx = furi_hal_subghz_stop_async_rx, + + .get_rssi = furi_hal_subghz_get_rssi, + .get_lqi = furi_hal_subghz_get_lqi, + + .rx_pipe_not_empty = furi_hal_subghz_rx_pipe_not_empty, + .is_rx_data_crc_valid = furi_hal_subghz_is_rx_data_crc_valid, + .read_packet = furi_hal_subghz_read_packet, + .write_packet = furi_hal_subghz_write_packet, +}; + +const SubGhzDevice subghz_device_cc1101_int = { + .name = SUBGHZ_DEVICE_CC1101_INT_NAME, + .interconnect = &subghz_device_cc1101_int_interconnect, +}; diff --git a/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h b/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h new file mode 100644 index 000000000..629d1264c --- /dev/null +++ b/lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h @@ -0,0 +1,8 @@ +#pragma once +#include "../types.h" + +#define SUBGHZ_DEVICE_CC1101_INT_NAME "cc1101_int" + +typedef struct SubGhzDeviceCC1101Int SubGhzDeviceCC1101Int; + +extern const SubGhzDevice subghz_device_cc1101_int; diff --git a/lib/subghz/devices/device_registry.h b/lib/subghz/devices/device_registry.h new file mode 100644 index 000000000..70a0db4b2 --- /dev/null +++ b/lib/subghz/devices/device_registry.h @@ -0,0 +1,13 @@ +#pragma once + +#include "registry.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const SubGhzDeviceRegistry subghz_device_registry; + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/devices/devices.c b/lib/subghz/devices/devices.c new file mode 100644 index 000000000..55db61e11 --- /dev/null +++ b/lib/subghz/devices/devices.c @@ -0,0 +1,236 @@ +#include "devices.h" + +#include "registry.h" + +void subghz_devices_init() { + furi_check(!subghz_device_registry_is_valid()); + subghz_device_registry_init(); +} + +void subghz_devices_deinit(void) { + furi_check(subghz_device_registry_is_valid()); + subghz_device_registry_deinit(); +} + +const SubGhzDevice* subghz_devices_get_by_name(const char* device_name) { + furi_check(subghz_device_registry_is_valid()); + const SubGhzDevice* device = subghz_device_registry_get_by_name(device_name); + return device; +} + +const char* subghz_devices_get_name(const SubGhzDevice* device) { + const char* ret = NULL; + if(device) { + ret = device->name; + } + return ret; +} + +bool subghz_devices_begin(const SubGhzDevice* device) { + bool ret = false; + furi_assert(device); + if(device->interconnect->begin) { + ret = device->interconnect->begin(); + } + return ret; +} + +void subghz_devices_end(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->end) { + device->interconnect->end(); + } +} + +bool subghz_devices_is_connect(const SubGhzDevice* device) { + bool ret = false; + furi_assert(device); + if(device->interconnect->is_connect) { + ret = device->interconnect->is_connect(); + } + return ret; +} + +void subghz_devices_reset(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->reset) { + device->interconnect->reset(); + } +} + +void subghz_devices_sleep(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->sleep) { + device->interconnect->sleep(); + } +} + +void subghz_devices_idle(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->idle) { + device->interconnect->idle(); + } +} + +void subghz_devices_load_preset( + const SubGhzDevice* device, + FuriHalSubGhzPreset preset, + uint8_t* preset_data) { + furi_assert(device); + if(device->interconnect->load_preset) { + device->interconnect->load_preset(preset, preset_data); + } +} + +uint32_t subghz_devices_set_frequency(const SubGhzDevice* device, uint32_t frequency) { + uint32_t ret = 0; + furi_assert(device); + if(device->interconnect->set_frequency) { + ret = device->interconnect->set_frequency(frequency); + } + return ret; +} + +bool subghz_devices_is_frequency_valid(const SubGhzDevice* device, uint32_t frequency) { + bool ret = false; + furi_assert(device); + if(device->interconnect->is_frequency_valid) { + ret = device->interconnect->is_frequency_valid(frequency); + } + return ret; +} + +void subghz_devices_set_async_mirror_pin(const SubGhzDevice* device, const GpioPin* gpio) { + furi_assert(device); + if(device->interconnect->set_async_mirror_pin) { + device->interconnect->set_async_mirror_pin(gpio); + } +} + +const GpioPin* subghz_devices_get_data_gpio(const SubGhzDevice* device) { + const GpioPin* ret = NULL; + furi_assert(device); + if(device->interconnect->get_data_gpio) { + ret = device->interconnect->get_data_gpio(); + } + return ret; +} + +bool subghz_devices_set_tx(const SubGhzDevice* device) { + bool ret = 0; + furi_assert(device); + if(device->interconnect->set_tx) { + ret = device->interconnect->set_tx(); + } + return ret; +} + +void subghz_devices_flush_tx(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->flush_tx) { + device->interconnect->flush_tx(); + } +} + +bool subghz_devices_start_async_tx(const SubGhzDevice* device, void* callback, void* context) { + bool ret = false; + furi_assert(device); + if(device->interconnect->start_async_tx) { + ret = device->interconnect->start_async_tx(callback, context); + } + return ret; +} + +bool subghz_devices_is_async_complete_tx(const SubGhzDevice* device) { + bool ret = false; + furi_assert(device); + if(device->interconnect->is_async_complete_tx) { + ret = device->interconnect->is_async_complete_tx(); + } + return ret; +} + +void subghz_devices_stop_async_tx(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->stop_async_tx) { + device->interconnect->stop_async_tx(); + } +} + +void subghz_devices_set_rx(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->set_rx) { + device->interconnect->set_rx(); + } +} + +void subghz_devices_flush_rx(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->flush_rx) { + device->interconnect->flush_rx(); + } +} + +void subghz_devices_start_async_rx(const SubGhzDevice* device, void* callback, void* context) { + furi_assert(device); + if(device->interconnect->start_async_rx) { + device->interconnect->start_async_rx(callback, context); + } +} + +void subghz_devices_stop_async_rx(const SubGhzDevice* device) { + furi_assert(device); + if(device->interconnect->stop_async_rx) { + device->interconnect->stop_async_rx(); + } +} + +float subghz_devices_get_rssi(const SubGhzDevice* device) { + float ret = 0; + furi_assert(device); + if(device->interconnect->get_rssi) { + ret = device->interconnect->get_rssi(); + } + return ret; +} + +uint8_t subghz_devices_get_lqi(const SubGhzDevice* device) { + uint8_t ret = 0; + furi_assert(device); + if(device->interconnect->get_lqi) { + ret = device->interconnect->get_lqi(); + } + return ret; +} + +bool subghz_devices_rx_pipe_not_empty(const SubGhzDevice* device) { + bool ret = false; + furi_assert(device); + if(device->interconnect->rx_pipe_not_empty) { + ret = device->interconnect->rx_pipe_not_empty(); + } + return ret; +} + +bool subghz_devices_is_rx_data_crc_valid(const SubGhzDevice* device) { + bool ret = false; + furi_assert(device); + if(device->interconnect->is_rx_data_crc_valid) { + ret = device->interconnect->is_rx_data_crc_valid(); + } + return ret; +} + +void subghz_devices_read_packet(const SubGhzDevice* device, uint8_t* data, uint8_t* size) { + furi_assert(device); + if(device->interconnect->read_packet) { + device->interconnect->read_packet(data, size); + } +} + +void subghz_devices_write_packet(const SubGhzDevice* device, const uint8_t* data, uint8_t size) { + furi_assert(device); + if(device->interconnect->write_packet) { + device->interconnect->write_packet(data, size); + } +} diff --git a/lib/subghz/devices/devices.h b/lib/subghz/devices/devices.h new file mode 100644 index 000000000..dad3c9aeb --- /dev/null +++ b/lib/subghz/devices/devices.h @@ -0,0 +1,52 @@ +#pragma once + +#include "types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SubGhzDevice SubGhzDevice; + +void subghz_devices_init(); +void subghz_devices_deinit(void); + +const SubGhzDevice* subghz_devices_get_by_name(const char* device_name); +const char* subghz_devices_get_name(const SubGhzDevice* device); +bool subghz_devices_begin(const SubGhzDevice* device); +void subghz_devices_end(const SubGhzDevice* device); +bool subghz_devices_is_connect(const SubGhzDevice* device); +void subghz_devices_reset(const SubGhzDevice* device); +void subghz_devices_sleep(const SubGhzDevice* device); +void subghz_devices_idle(const SubGhzDevice* device); +void subghz_devices_load_preset( + const SubGhzDevice* device, + FuriHalSubGhzPreset preset, + uint8_t* preset_data); +uint32_t subghz_devices_set_frequency(const SubGhzDevice* device, uint32_t frequency); +bool subghz_devices_is_frequency_valid(const SubGhzDevice* device, uint32_t frequency); +void subghz_devices_set_async_mirror_pin(const SubGhzDevice* device, const GpioPin* gpio); +const GpioPin* subghz_devices_get_data_gpio(const SubGhzDevice* device); + +bool subghz_devices_set_tx(const SubGhzDevice* device); +void subghz_devices_flush_tx(const SubGhzDevice* device); +bool subghz_devices_start_async_tx(const SubGhzDevice* device, void* callback, void* context); +bool subghz_devices_is_async_complete_tx(const SubGhzDevice* device); +void subghz_devices_stop_async_tx(const SubGhzDevice* device); + +void subghz_devices_set_rx(const SubGhzDevice* device); +void subghz_devices_flush_rx(const SubGhzDevice* device); +void subghz_devices_start_async_rx(const SubGhzDevice* device, void* callback, void* context); +void subghz_devices_stop_async_rx(const SubGhzDevice* device); + +float subghz_devices_get_rssi(const SubGhzDevice* device); +uint8_t subghz_devices_get_lqi(const SubGhzDevice* device); + +bool subghz_devices_rx_pipe_not_empty(const SubGhzDevice* device); +bool subghz_devices_is_rx_data_crc_valid(const SubGhzDevice* device); +void subghz_devices_read_packet(const SubGhzDevice* device, uint8_t* data, uint8_t* size); +void subghz_devices_write_packet(const SubGhzDevice* device, const uint8_t* data, uint8_t size); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/devices/preset.h b/lib/subghz/devices/preset.h new file mode 100644 index 000000000..8716f2e23 --- /dev/null +++ b/lib/subghz/devices/preset.h @@ -0,0 +1,13 @@ +#pragma once + +/** Radio Presets */ +typedef enum { + FuriHalSubGhzPresetIDLE, /**< default configuration */ + FuriHalSubGhzPresetOok270Async, /**< OOK, bandwidth 270kHz, asynchronous */ + FuriHalSubGhzPresetOok650Async, /**< OOK, bandwidth 650kHz, asynchronous */ + FuriHalSubGhzPreset2FSKDev238Async, /**< FM, deviation 2.380371 kHz, asynchronous */ + FuriHalSubGhzPreset2FSKDev476Async, /**< FM, deviation 47.60742 kHz, asynchronous */ + FuriHalSubGhzPresetMSK99_97KbAsync, /**< MSK, deviation 47.60742 kHz, 99.97Kb/s, asynchronous */ + FuriHalSubGhzPresetGFSK9_99KbAsync, /**< GFSK, deviation 19.042969 kHz, 9.996Kb/s, asynchronous */ + FuriHalSubGhzPresetCustom, /**Custom Preset*/ +} FuriHalSubGhzPreset; diff --git a/lib/subghz/devices/registry.c b/lib/subghz/devices/registry.c new file mode 100644 index 000000000..c0d5bb292 --- /dev/null +++ b/lib/subghz/devices/registry.c @@ -0,0 +1,76 @@ +#include "registry.h" + +#include "cc1101_int/cc1101_int_interconnect.h" +#include +#include + +#define TAG "SubGhzDeviceRegistry" + +struct SubGhzDeviceRegistry { + const SubGhzDevice** items; + size_t size; + PluginManager* manager; +}; + +static SubGhzDeviceRegistry* subghz_device_registry = NULL; + +void subghz_device_registry_init(void) { + SubGhzDeviceRegistry* subghz_device = + (SubGhzDeviceRegistry*)malloc(sizeof(SubGhzDeviceRegistry)); + subghz_device->manager = plugin_manager_alloc( + SUBGHZ_RADIO_DEVICE_PLUGIN_APP_ID, + SUBGHZ_RADIO_DEVICE_PLUGIN_API_VERSION, + firmware_api_interface); + + //ToDo: fix path to plugins + if(plugin_manager_load_all(subghz_device->manager, "/any/apps_data/subghz/plugins") != + //if(plugin_manager_load_all(subghz_device->manager, APP_DATA_PATH("plugins")) != + PluginManagerErrorNone) { + FURI_LOG_E(TAG, "Failed to load all libs"); + } + + subghz_device->size = plugin_manager_get_count(subghz_device->manager) + 1; + subghz_device->items = + (const SubGhzDevice**)malloc(sizeof(SubGhzDevice*) * subghz_device->size); + subghz_device->items[0] = &subghz_device_cc1101_int; + for(uint32_t i = 1; i < subghz_device->size; i++) { + const SubGhzDevice* plugin = plugin_manager_get_ep(subghz_device->manager, i - 1); + subghz_device->items[i] = plugin; + } + + FURI_LOG_I(TAG, "Loaded %zu radio device", subghz_device->size); + subghz_device_registry = subghz_device; +} + +void subghz_device_registry_deinit(void) { + plugin_manager_free(subghz_device_registry->manager); + free(subghz_device_registry->items); + free(subghz_device_registry); + subghz_device_registry = NULL; +} + +bool subghz_device_registry_is_valid(void) { + return subghz_device_registry != NULL; +} + +const SubGhzDevice* subghz_device_registry_get_by_name(const char* name) { + furi_assert(subghz_device_registry); + + if(name != NULL) { + for(size_t i = 0; i < subghz_device_registry->size; i++) { + if(strcmp(name, subghz_device_registry->items[i]->name) == 0) { + return subghz_device_registry->items[i]; + } + } + } + return NULL; +} + +const SubGhzDevice* subghz_device_registry_get_by_index(size_t index) { + furi_assert(subghz_device_registry); + if(index < subghz_device_registry->size) { + return subghz_device_registry->items[index]; + } else { + return NULL; + } +} diff --git a/lib/subghz/devices/registry.h b/lib/subghz/devices/registry.h new file mode 100644 index 000000000..520058920 --- /dev/null +++ b/lib/subghz/devices/registry.h @@ -0,0 +1,40 @@ +#pragma once + +#include "types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SubGhzDevice SubGhzDevice; + +void subghz_device_registry_init(void); + +void subghz_device_registry_deinit(void); + +bool subghz_device_registry_is_valid(void); + +/** + * Registration by name SubGhzDevice. + * @param name SubGhzDevice name + * @return SubGhzDevice* pointer to a SubGhzDevice instance + */ +const SubGhzDevice* subghz_device_registry_get_by_name(const char* name); + +/** + * Registration subghzdevice by index in array SubGhzDevice. + * @param index SubGhzDevice by index in array + * @return SubGhzDevice* pointer to a SubGhzDevice instance + */ +const SubGhzDevice* subghz_device_registry_get_by_index(size_t index); + +/** + * Getting the number of registered subghzdevices. + * @param subghz_device SubGhzDeviceRegistry + * @return Number of subghzdevices + */ +size_t subghz_device_registry_count(void); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/devices/types.h b/lib/subghz/devices/types.h new file mode 100644 index 000000000..8a4198426 --- /dev/null +++ b/lib/subghz/devices/types.h @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include "preset.h" + +#include + +#define SUBGHZ_RADIO_DEVICE_PLUGIN_APP_ID "subghz_radio_device" +#define SUBGHZ_RADIO_DEVICE_PLUGIN_API_VERSION 1 + +typedef struct SubGhzDeviceRegistry SubGhzDeviceRegistry; +typedef struct SubGhzDevice SubGhzDevice; + +typedef bool (*SubGhzBegin)(void); +typedef void (*SubGhzEnd)(void); +typedef bool (*SubGhzIsConnect)(void); +typedef void (*SubGhzReset)(void); +typedef void (*SubGhzSleep)(void); +typedef void (*SubGhzIdle)(void); +typedef void (*SubGhzLoadPreset)(FuriHalSubGhzPreset preset, uint8_t* preset_data); +typedef uint32_t (*SubGhzSetFrequency)(uint32_t frequency); +typedef bool (*SubGhzIsFrequencyValid)(uint32_t frequency); + +typedef void (*SubGhzSetAsyncMirrorPin)(const GpioPin* gpio); +typedef const GpioPin* (*SubGhzGetDataGpio)(void); + +typedef bool (*SubGhzSetTx)(void); +typedef void (*SubGhzFlushTx)(void); +typedef bool (*SubGhzStartAsyncTx)(void* callback, void* context); +typedef bool (*SubGhzIsAsyncCompleteTx)(void); +typedef void (*SubGhzStopAsyncTx)(void); + +typedef void (*SubGhzSetRx)(void); +typedef void (*SubGhzFlushRx)(void); +typedef void (*SubGhzStartAsyncRx)(void* callback, void* context); +typedef void (*SubGhzStopAsyncRx)(void); + +typedef float (*SubGhzGetRSSI)(void); +typedef uint8_t (*SubGhzGetLQI)(void); + +typedef bool (*SubGhzRxPipeNotEmpty)(void); +typedef bool (*SubGhzRxIsDataCrcValid)(void); +typedef void (*SubGhzReadPacket)(uint8_t* data, uint8_t* size); +typedef void (*SubGhzWritePacket)(const uint8_t* data, uint8_t size); + +typedef struct { + SubGhzBegin begin; + SubGhzEnd end; + + SubGhzIsConnect is_connect; + SubGhzReset reset; + SubGhzSleep sleep; + SubGhzIdle idle; + + SubGhzLoadPreset load_preset; + SubGhzSetFrequency set_frequency; + SubGhzIsFrequencyValid is_frequency_valid; + SubGhzSetAsyncMirrorPin set_async_mirror_pin; + SubGhzGetDataGpio get_data_gpio; + + SubGhzSetTx set_tx; + SubGhzFlushTx flush_tx; + SubGhzStartAsyncTx start_async_tx; + SubGhzIsAsyncCompleteTx is_async_complete_tx; + SubGhzStopAsyncTx stop_async_tx; + + SubGhzSetRx set_rx; + SubGhzFlushRx flush_rx; + SubGhzStartAsyncRx start_async_rx; + SubGhzStopAsyncRx stop_async_rx; + + SubGhzGetRSSI get_rssi; + SubGhzGetLQI get_lqi; + + SubGhzRxPipeNotEmpty rx_pipe_not_empty; + SubGhzRxIsDataCrcValid is_rx_data_crc_valid; + SubGhzReadPacket read_packet; + SubGhzWritePacket write_packet; + +} SubGhzDeviceInterconnect; + +struct SubGhzDevice { + const char* name; + const SubGhzDeviceInterconnect* interconnect; +}; diff --git a/lib/subghz/protocols/raw.c b/lib/subghz/protocols/raw.c index 66358698a..1288c9573 100644 --- a/lib/subghz/protocols/raw.c +++ b/lib/subghz/protocols/raw.c @@ -40,6 +40,7 @@ struct SubGhzProtocolEncoderRAW { bool is_running; FuriString* file_name; + FuriString* radio_device_name; SubGhzFileEncoderWorker* file_worker_encoder; }; @@ -282,6 +283,7 @@ void* subghz_protocol_encoder_raw_alloc(SubGhzEnvironment* environment) { instance->base.protocol = &subghz_protocol_raw; instance->file_name = furi_string_alloc(); + instance->radio_device_name = furi_string_alloc(); instance->is_running = false; return instance; } @@ -300,6 +302,7 @@ void subghz_protocol_encoder_raw_free(void* context) { SubGhzProtocolEncoderRAW* instance = context; subghz_protocol_encoder_raw_stop(instance); furi_string_free(instance->file_name); + furi_string_free(instance->radio_device_name); free(instance); } @@ -318,7 +321,9 @@ static bool subghz_protocol_encoder_raw_worker_init(SubGhzProtocolEncoderRAW* in instance->file_worker_encoder = subghz_file_encoder_worker_alloc(); if(subghz_file_encoder_worker_start( - instance->file_worker_encoder, furi_string_get_cstr(instance->file_name))) { + instance->file_worker_encoder, + furi_string_get_cstr(instance->file_name), + furi_string_get_cstr(instance->radio_device_name))) { //the worker needs a file in order to open and read part of the file furi_delay_ms(100); instance->is_running = true; @@ -328,7 +333,10 @@ static bool subghz_protocol_encoder_raw_worker_init(SubGhzProtocolEncoderRAW* in return instance->is_running; } -void subghz_protocol_raw_gen_fff_data(FlipperFormat* flipper_format, const char* file_path) { +void subghz_protocol_raw_gen_fff_data( + FlipperFormat* flipper_format, + const char* file_path, + const char* radio_device_name) { do { stream_clean(flipper_format_get_raw_stream(flipper_format)); if(!flipper_format_write_string_cstr(flipper_format, "Protocol", "RAW")) { @@ -340,6 +348,12 @@ void subghz_protocol_raw_gen_fff_data(FlipperFormat* flipper_format, const char* FURI_LOG_E(TAG, "Unable to add File_name"); break; } + + if(!flipper_format_write_string_cstr( + flipper_format, "Radio_device_name", radio_device_name)) { + FURI_LOG_E(TAG, "Unable to add Radio_device_name"); + break; + } } while(false); } @@ -364,6 +378,13 @@ SubGhzProtocolStatus } furi_string_set(instance->file_name, temp_str); + if(!flipper_format_read_string(flipper_format, "Radio_device_name", temp_str)) { + FURI_LOG_E(TAG, "Missing Radio_device_name"); + res = SubGhzProtocolStatusErrorParserOthers; + break; + } + furi_string_set(instance->radio_device_name, temp_str); + if(!subghz_protocol_encoder_raw_worker_init(instance)) { res = SubGhzProtocolStatusErrorEncoderGetUpload; break; diff --git a/lib/subghz/protocols/raw.h b/lib/subghz/protocols/raw.h index 4f67a4e2f..6d791bb36 100644 --- a/lib/subghz/protocols/raw.h +++ b/lib/subghz/protocols/raw.h @@ -126,8 +126,12 @@ void subghz_protocol_raw_file_encoder_worker_set_callback_end( * File generation for RAW work. * @param flipper_format Pointer to a FlipperFormat instance * @param file_path File path + * @param radio_dev_name Radio device name */ -void subghz_protocol_raw_gen_fff_data(FlipperFormat* flipper_format, const char* file_path); +void subghz_protocol_raw_gen_fff_data( + FlipperFormat* flipper_format, + const char* file_path, + const char* radio_dev_name); /** * Deserialize and generating an upload to send. diff --git a/lib/subghz/subghz_file_encoder_worker.c b/lib/subghz/subghz_file_encoder_worker.c index 5c4d36f78..519ff3fdc 100644 --- a/lib/subghz/subghz_file_encoder_worker.c +++ b/lib/subghz/subghz_file_encoder_worker.c @@ -3,6 +3,7 @@ #include #include #include +#include #define TAG "SubGhzFileEncoderWorker" @@ -21,6 +22,7 @@ struct SubGhzFileEncoderWorker { bool is_storage_slow; FuriString* str_data; FuriString* file_path; + const SubGhzDevice* device; SubGhzFileEncoderWorkerCallbackEnd callback_end; void* context_end; @@ -156,10 +158,13 @@ static int32_t subghz_file_encoder_worker_thread(void* context) { if(instance->is_storage_slow) { FURI_LOG_E(TAG, "Storage is slow"); } + FURI_LOG_I(TAG, "End read file"); - while(!furi_hal_subghz_is_async_tx_complete() && instance->worker_running) { + while(instance->device && !subghz_devices_is_async_complete_tx(instance->device) && + instance->worker_running) { furi_delay_ms(5); } + FURI_LOG_I(TAG, "End transmission"); while(instance->worker_running) { if(instance->worker_stoping) { @@ -206,12 +211,16 @@ void subghz_file_encoder_worker_free(SubGhzFileEncoderWorker* instance) { free(instance); } -bool subghz_file_encoder_worker_start(SubGhzFileEncoderWorker* instance, const char* file_path) { +bool subghz_file_encoder_worker_start( + SubGhzFileEncoderWorker* instance, + const char* file_path, + const char* radio_device_name) { furi_assert(instance); furi_assert(!instance->worker_running); furi_stream_buffer_reset(instance->stream); furi_string_set(instance->file_path, file_path); + instance->device = subghz_devices_get_by_name(radio_device_name); instance->worker_running = true; furi_thread_start(instance->thread); diff --git a/lib/subghz/subghz_file_encoder_worker.h b/lib/subghz/subghz_file_encoder_worker.h index a87be5cd6..e66c66d76 100644 --- a/lib/subghz/subghz_file_encoder_worker.h +++ b/lib/subghz/subghz_file_encoder_worker.h @@ -38,9 +38,14 @@ LevelDuration subghz_file_encoder_worker_get_level_duration(void* context); /** * Start SubGhzFileEncoderWorker. * @param instance Pointer to a SubGhzFileEncoderWorker instance + * @param file_path File path + * @param radio_device_name Radio device name * @return bool - true if ok */ -bool subghz_file_encoder_worker_start(SubGhzFileEncoderWorker* instance, const char* file_path); +bool subghz_file_encoder_worker_start( + SubGhzFileEncoderWorker* instance, + const char* file_path, + const char* radio_device_name); /** * Stop SubGhzFileEncoderWorker diff --git a/lib/subghz/subghz_setting.c b/lib/subghz/subghz_setting.c index 656580043..9804f8277 100644 --- a/lib/subghz/subghz_setting.c +++ b/lib/subghz/subghz_setting.c @@ -4,7 +4,7 @@ #include #include -#include +#include #define TAG "SubGhzSetting" @@ -218,8 +218,7 @@ void subghz_setting_free(SubGhzSetting* instance) { static void subghz_setting_load_default_preset( SubGhzSetting* instance, const char* preset_name, - const uint8_t* preset_data, - const uint8_t preset_pa_table[8]) { + const uint8_t* preset_data) { furi_assert(instance); furi_assert(preset_data); uint32_t preset_data_count = 0; @@ -235,10 +234,8 @@ static void subghz_setting_load_default_preset( preset_data_count += 2; item->custom_preset_data_size = sizeof(uint8_t) * preset_data_count + sizeof(uint8_t) * 8; item->custom_preset_data = malloc(item->custom_preset_data_size); - //load preset register - memcpy(&item->custom_preset_data[0], &preset_data[0], preset_data_count); - //load pa table - memcpy(&item->custom_preset_data[preset_data_count], &preset_pa_table[0], 8); + //load preset register + pa table + memcpy(&item->custom_preset_data[0], &preset_data[0], item->custom_preset_data_size); } static void subghz_setting_load_default_region( @@ -262,25 +259,13 @@ static void subghz_setting_load_default_region( } subghz_setting_load_default_preset( - instance, - "AM270", - (uint8_t*)furi_hal_subghz_preset_ook_270khz_async_regs, - furi_hal_subghz_preset_ook_async_patable); + instance, "AM270", subghz_device_cc1101_preset_ook_270khz_async_regs); subghz_setting_load_default_preset( - instance, - "AM650", - (uint8_t*)furi_hal_subghz_preset_ook_650khz_async_regs, - furi_hal_subghz_preset_ook_async_patable); + instance, "AM650", subghz_device_cc1101_preset_ook_650khz_async_regs); subghz_setting_load_default_preset( - instance, - "FM238", - (uint8_t*)furi_hal_subghz_preset_2fsk_dev2_38khz_async_regs, - furi_hal_subghz_preset_2fsk_async_patable); + instance, "FM238", subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs); subghz_setting_load_default_preset( - instance, - "FM476", - (uint8_t*)furi_hal_subghz_preset_2fsk_dev47_6khz_async_regs, - furi_hal_subghz_preset_2fsk_async_patable); + instance, "FM476", subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs); } void subghz_setting_load_default(SubGhzSetting* instance) { @@ -359,6 +344,7 @@ void subghz_setting_load(SubGhzSetting* instance, const char* file_path) { } while(flipper_format_read_uint32( fff_data_file, "Frequency", (uint32_t*)&temp_data32, 1)) { + //Todo: add a frequency support check depending on the selected radio device if(furi_hal_subghz_is_frequency_valid(temp_data32)) { FURI_LOG_I(TAG, "Frequency loaded %lu", temp_data32); FrequencyList_push_back(instance->frequencies, temp_data32); diff --git a/lib/subghz/subghz_tx_rx_worker.c b/lib/subghz/subghz_tx_rx_worker.c index 42124bebc..250e6666f 100644 --- a/lib/subghz/subghz_tx_rx_worker.c +++ b/lib/subghz/subghz_tx_rx_worker.c @@ -21,6 +21,8 @@ struct SubGhzTxRxWorker { SubGhzTxRxWorkerStatus status; uint32_t frequency; + const SubGhzDevice* device; + const GpioPin* device_data_gpio; SubGhzTxRxWorkerCallbackHaveRead callback_have_read; void* context_have_read; @@ -65,33 +67,33 @@ bool subghz_tx_rx_worker_rx(SubGhzTxRxWorker* instance, uint8_t* data, uint8_t* uint8_t timeout = 100; bool ret = false; if(instance->status != SubGhzTxRxWorkerStatusRx) { - furi_hal_subghz_rx(); + subghz_devices_set_rx(instance->device); instance->status = SubGhzTxRxWorkerStatusRx; furi_delay_tick(1); } //waiting for reception to complete - while(furi_hal_gpio_read(&gpio_cc1101_g0)) { + while(furi_hal_gpio_read(instance->device_data_gpio)) { furi_delay_tick(1); if(!--timeout) { FURI_LOG_W(TAG, "RX cc1101_g0 timeout"); - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + subghz_devices_flush_rx(instance->device); + subghz_devices_set_rx(instance->device); break; } } - if(furi_hal_subghz_rx_pipe_not_empty()) { + if(subghz_devices_rx_pipe_not_empty(instance->device)) { FURI_LOG_I( TAG, "RSSI: %03.1fdbm LQI: %d", - (double)furi_hal_subghz_get_rssi(), - furi_hal_subghz_get_lqi()); - if(furi_hal_subghz_is_rx_data_crc_valid()) { - furi_hal_subghz_read_packet(data, size); + (double)subghz_devices_get_rssi(instance->device), + subghz_devices_get_lqi(instance->device)); + if(subghz_devices_is_rx_data_crc_valid(instance->device)) { + subghz_devices_read_packet(instance->device, data, size); ret = true; } - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + subghz_devices_flush_rx(instance->device); + subghz_devices_set_rx(instance->device); } return ret; } @@ -99,26 +101,28 @@ bool subghz_tx_rx_worker_rx(SubGhzTxRxWorker* instance, uint8_t* data, uint8_t* void subghz_tx_rx_worker_tx(SubGhzTxRxWorker* instance, uint8_t* data, size_t size) { uint8_t timeout = 200; if(instance->status != SubGhzTxRxWorkerStatusIDLE) { - furi_hal_subghz_idle(); + subghz_devices_idle(instance->device); } - furi_hal_subghz_write_packet(data, size); - furi_hal_subghz_tx(); //start send + subghz_devices_write_packet(instance->device, data, size); + subghz_devices_set_tx(instance->device); //start send instance->status = SubGhzTxRxWorkerStatusTx; - while(!furi_hal_gpio_read(&gpio_cc1101_g0)) { // Wait for GDO0 to be set -> sync transmitted + while(!furi_hal_gpio_read( + instance->device_data_gpio)) { // Wait for GDO0 to be set -> sync transmitted furi_delay_tick(1); if(!--timeout) { FURI_LOG_W(TAG, "TX !cc1101_g0 timeout"); break; } } - while(furi_hal_gpio_read(&gpio_cc1101_g0)) { // Wait for GDO0 to be cleared -> end of packet + while(furi_hal_gpio_read( + instance->device_data_gpio)) { // Wait for GDO0 to be cleared -> end of packet furi_delay_tick(1); if(!--timeout) { FURI_LOG_W(TAG, "TX cc1101_g0 timeout"); break; } } - furi_hal_subghz_idle(); + subghz_devices_idle(instance->device); instance->status = SubGhzTxRxWorkerStatusIDLE; } /** Worker thread @@ -128,16 +132,19 @@ void subghz_tx_rx_worker_tx(SubGhzTxRxWorker* instance, uint8_t* data, size_t si */ static int32_t subghz_tx_rx_worker_thread(void* context) { SubGhzTxRxWorker* instance = context; + furi_assert(instance->device); FURI_LOG_I(TAG, "Worker start"); - furi_hal_subghz_reset(); - furi_hal_subghz_idle(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetGFSK9_99KbAsync); - //furi_hal_subghz_load_preset(FuriHalSubGhzPresetMSK99_97KbAsync); - furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); + subghz_devices_begin(instance->device); + instance->device_data_gpio = subghz_devices_get_data_gpio(instance->device); + subghz_devices_reset(instance->device); + subghz_devices_idle(instance->device); + subghz_devices_load_preset(instance->device, FuriHalSubGhzPresetGFSK9_99KbAsync, NULL); - furi_hal_subghz_set_frequency_and_path(instance->frequency); - furi_hal_subghz_flush_rx(); + furi_hal_gpio_init(instance->device_data_gpio, GpioModeInput, GpioPullNo, GpioSpeedLow); + + subghz_devices_set_frequency(instance->device, instance->frequency); + subghz_devices_flush_rx(instance->device); uint8_t data[SUBGHZ_TXRX_WORKER_MAX_TXRX_SIZE + 1] = {0}; size_t size_tx = 0; @@ -191,8 +198,8 @@ static int32_t subghz_tx_rx_worker_thread(void* context) { furi_delay_tick(1); } - furi_hal_subghz_set_path(FuriHalSubGhzPathIsolate); - furi_hal_subghz_sleep(); + subghz_devices_sleep(instance->device); + subghz_devices_end(instance->device); FURI_LOG_I(TAG, "Worker stop"); return 0; @@ -224,7 +231,10 @@ void subghz_tx_rx_worker_free(SubGhzTxRxWorker* instance) { free(instance); } -bool subghz_tx_rx_worker_start(SubGhzTxRxWorker* instance, uint32_t frequency) { +bool subghz_tx_rx_worker_start( + SubGhzTxRxWorker* instance, + const SubGhzDevice* device, + uint32_t frequency) { furi_assert(instance); furi_assert(!instance->worker_running); bool res = false; @@ -235,6 +245,7 @@ bool subghz_tx_rx_worker_start(SubGhzTxRxWorker* instance, uint32_t frequency) { if(furi_hal_region_is_frequency_allowed(frequency)) { instance->frequency = frequency; + instance->device = device; res = true; } diff --git a/lib/subghz/subghz_tx_rx_worker.h b/lib/subghz/subghz_tx_rx_worker.h index ddc02e749..56bdb0a1f 100644 --- a/lib/subghz/subghz_tx_rx_worker.h +++ b/lib/subghz/subghz_tx_rx_worker.h @@ -1,6 +1,7 @@ #pragma once #include +#include #ifdef __cplusplus extern "C" { @@ -67,9 +68,13 @@ void subghz_tx_rx_worker_free(SubGhzTxRxWorker* instance); /** * Start SubGhzTxRxWorker * @param instance Pointer to a SubGhzTxRxWorker instance + * @param device Pointer to a SubGhzDevice instance * @return bool - true if ok */ -bool subghz_tx_rx_worker_start(SubGhzTxRxWorker* instance, uint32_t frequency); +bool subghz_tx_rx_worker_start( + SubGhzTxRxWorker* instance, + const SubGhzDevice* device, + uint32_t frequency); /** * Stop SubGhzTxRxWorker diff --git a/lib/subghz/types.h b/lib/subghz/types.h index 719beff45..d87a0dc76 100644 --- a/lib/subghz/types.h +++ b/lib/subghz/types.h @@ -21,6 +21,12 @@ #define SUBGHZ_RAW_FILE_VERSION 1 #define SUBGHZ_RAW_FILE_TYPE "Flipper SubGhz RAW File" +#define SUBGHZ_KEYSTORE_DIR_NAME EXT_PATH("subghz/assets/keeloq_mfcodes") +#define SUBGHZ_KEYSTORE_DIR_USER_NAME EXT_PATH("subghz/assets/keeloq_mfcodes_user") +#define SUBGHZ_CAME_ATOMO_DIR_NAME EXT_PATH("subghz/assets/came_atomo") +#define SUBGHZ_NICE_FLOR_S_DIR_NAME EXT_PATH("subghz/assets/nice_flor_s") +#define SUBGHZ_ALUTECH_AT_4N_DIR_NAME EXT_PATH("subghz/assets/alutech_at_4n") + typedef struct SubGhzProtocolRegistry SubGhzProtocolRegistry; typedef struct SubGhzEnvironment SubGhzEnvironment; diff --git a/site_scons/commandline.scons b/site_scons/commandline.scons index b70b5cff5..776977cda 100644 --- a/site_scons/commandline.scons +++ b/site_scons/commandline.scons @@ -228,6 +228,7 @@ vars.AddVariables( ("applications/debug", False), ("applications/external", False), ("applications/examples", False), + ("applications/drivers", False), ("applications_user", False), ], ), From 88f8f68e292629d2c11c12334804c1f14742d032 Mon Sep 17 00:00:00 2001 From: Slavik Nychkalo Date: Fri, 30 Jun 2023 18:50:46 +0300 Subject: [PATCH 02/40] fix width of submenu items on Vertical orientation (#2306) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix width of submenu items on vertical view * Gui: slightly better canvas width handling in submenu * Gui: remove unused include Co-authored-by: あく --- applications/services/gui/modules/submenu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/applications/services/gui/modules/submenu.c b/applications/services/gui/modules/submenu.c index 9d81c30b6..3ba35edde 100644 --- a/applications/services/gui/modules/submenu.c +++ b/applications/services/gui/modules/submenu.c @@ -63,7 +63,7 @@ static void submenu_view_draw_callback(Canvas* canvas, void* _model) { SubmenuModel* model = _model; const uint8_t item_height = 16; - const uint8_t item_width = 123; + uint8_t item_width = canvas_width(canvas) - 5; canvas_clear(canvas); From e7bd547d05c9cb70c5da26caa39ad1efcfd04e74 Mon Sep 17 00:00:00 2001 From: Sergey Gavrilov Date: Fri, 30 Jun 2023 20:56:41 +0300 Subject: [PATCH 03/40] SubGHz: properly working with missing external driver (#2821) --- applications/main/subghz/helpers/subghz_txrx.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/applications/main/subghz/helpers/subghz_txrx.c b/applications/main/subghz/helpers/subghz_txrx.c index f117d3974..b911f4434 100644 --- a/applications/main/subghz/helpers/subghz_txrx.c +++ b/applications/main/subghz/helpers/subghz_txrx.c @@ -552,7 +552,10 @@ bool subghz_txrx_radio_device_is_external_connected(SubGhzTxRx* instance, const subghz_txrx_radio_device_power_on(instance); } - is_connect = subghz_devices_is_connect(subghz_devices_get_by_name(name)); + const SubGhzDevice* device = subghz_devices_get_by_name(name); + if(device) { + is_connect = subghz_devices_is_connect(device); + } if(!is_otg_enabled) { subghz_txrx_radio_device_power_off(instance); From bb169978097b13f30d93592d7d13903b747822bb Mon Sep 17 00:00:00 2001 From: Sergey Gavrilov Date: Tue, 4 Jul 2023 12:38:47 +0300 Subject: [PATCH 04/40] [FL-3398] Desktop settings: show icon and name for external applications (#2837) --- .../scenes/desktop_settings_scene_favorite.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c index 698cfae1b..c43f8e350 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c @@ -1,6 +1,7 @@ #include "../desktop_settings_app.h" #include "applications.h" #include "desktop_settings_scene.h" +#include #include #include @@ -13,16 +14,9 @@ static bool favorite_fap_selector_item_callback( uint8_t** icon_ptr, FuriString* item_name) { UNUSED(context); -#ifdef APP_FAP_LOADER Storage* storage = furi_record_open(RECORD_STORAGE); - bool success = fap_loader_load_name_and_icon(file_path, storage, icon_ptr, item_name); + bool success = flipper_application_load_name_and_icon(file_path, storage, icon_ptr, item_name); furi_record_close(RECORD_STORAGE); -#else - UNUSED(file_path); - UNUSED(icon_ptr); - UNUSED(item_name); - bool success = false; -#endif return success; } From d4300a10dd57e72165f8f987a2dec0ad43714987 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Tue, 4 Jul 2023 14:03:11 +0300 Subject: [PATCH 05/40] fix --- applications/external/swd_probe/swd_probe_app.h | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/applications/external/swd_probe/swd_probe_app.h b/applications/external/swd_probe/swd_probe_app.h index ff7154caf..5a45a4fd9 100644 --- a/applications/external/swd_probe/swd_probe_app.h +++ b/applications/external/swd_probe/swd_probe_app.h @@ -1,5 +1,5 @@ -#ifndef __ARHA_FLIPPERAPP_DEMO -#define __ARHA_FLIPPERAPP_DEMO +#ifndef __SWD_PROBE_APP_H +#define __SWD_PROBE_APP_H #include #include @@ -18,10 +18,6 @@ #include #include #include -#include -#include -#include -#include #include "usb_uart.h" From 08bafc478e98f6d179e059759cc13d9bf199a151 Mon Sep 17 00:00:00 2001 From: Eric Betts Date: Wed, 5 Jul 2023 02:26:50 -0700 Subject: [PATCH 06/40] Picopass fix ice (#2836) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix copypaste error * Add iCE key to dictionary * Write iCE key as elite, others with standard kdf Co-authored-by: あく --- applications/external/picopass/picopass_device.c | 3 +++ applications/external/picopass/picopass_device.h | 1 + applications/external/picopass/picopass_worker.c | 3 ++- .../external/picopass/scenes/picopass_scene_key_menu.c | 8 ++++++-- .../apps_data/picopass/assets/iclass_elite_dict.txt | 4 ++++ 5 files changed, 16 insertions(+), 3 deletions(-) diff --git a/applications/external/picopass/picopass_device.c b/applications/external/picopass/picopass_device.c index 53778cfb3..de43b0bb7 100644 --- a/applications/external/picopass/picopass_device.c +++ b/applications/external/picopass/picopass_device.c @@ -16,6 +16,7 @@ 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); @@ -77,6 +78,7 @@ static bool picopass_device_save_file( break; } } + // TODO: Add elite if(!flipper_format_write_comment_cstr(file, "Picopass blocks")) break; bool block_saved = true; @@ -256,6 +258,7 @@ void picopass_device_data_clear(PicopassDeviceData* dev_data) { } dev_data->pacs.legacy = false; dev_data->pacs.se_enabled = false; + dev_data->pacs.elite_kdf = false; dev_data->pacs.pin_length = 0; } diff --git a/applications/external/picopass/picopass_device.h b/applications/external/picopass/picopass_device.h index 7fc35ebda..b45df346c 100644 --- a/applications/external/picopass/picopass_device.h +++ b/applications/external/picopass/picopass_device.h @@ -62,6 +62,7 @@ typedef struct { bool sio; bool biometrics; uint8_t key[8]; + bool elite_kdf; uint8_t pin_length; PicopassEncryption encryption; uint8_t credential[8]; diff --git a/applications/external/picopass/picopass_worker.c b/applications/external/picopass/picopass_worker.c index e671552c5..6301704ca 100644 --- a/applications/external/picopass/picopass_worker.c +++ b/applications/external/picopass/picopass_worker.c @@ -550,6 +550,7 @@ void picopass_worker_elite_dict_attack(PicopassWorker* picopass_worker) { if(err == ERR_NONE) { FURI_LOG_I(TAG, "Found key"); memcpy(pacs->key, key, 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); @@ -720,7 +721,7 @@ void picopass_worker_write_key(PicopassWorker* picopass_worker) { uint8_t* oldKey = AA1[PICOPASS_KD_BLOCK_INDEX].data; uint8_t newKey[PICOPASS_BLOCK_LEN] = {0}; - loclass_iclass_calc_div_key(csn, pacs->key, newKey, false); + 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"); diff --git a/applications/external/picopass/scenes/picopass_scene_key_menu.c b/applications/external/picopass/scenes/picopass_scene_key_menu.c index 8aac6cb24..15a32ff44 100644 --- a/applications/external/picopass/scenes/picopass_scene_key_menu.c +++ b/applications/external/picopass/scenes/picopass_scene_key_menu.c @@ -60,24 +60,28 @@ bool picopass_scene_key_menu_on_event(void* context, SceneManagerEvent event) { scene_manager_set_scene_state( picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteStandard); memcpy(picopass->dev->dev_data.pacs.key, picopass_iclass_key, 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, 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, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCL); memcpy(picopass->dev->dev_data.pacs.key, picopass_xicl_key, 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, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCS); memcpy(picopass->dev->dev_data.pacs.key, picopass_xics_key, PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } diff --git a/assets/resources/apps_data/picopass/assets/iclass_elite_dict.txt b/assets/resources/apps_data/picopass/assets/iclass_elite_dict.txt index d11892372..908889aec 100644 --- a/assets/resources/apps_data/picopass/assets/iclass_elite_dict.txt +++ b/assets/resources/apps_data/picopass/assets/iclass_elite_dict.txt @@ -34,4 +34,8 @@ C1B74D7478053AE2 # default iCLASS RFIDeas 6B65797374726B72 +# CTF key 5C100DF7042EAE64 + +# iCopy-X DRM key (iCE product) +2020666666668888 From 9e67fe6794ca6da66600d97a2a7d77ce58a21dd1 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 14:41:28 +0300 Subject: [PATCH 07/40] BLE stuff + BadBT fixes by Willy-JL --- .../external/bad_bt/helpers/ducky_script.c | 51 +++++++++++-------- .../bad_bt/scenes/bad_bt_scene_config_mac.c | 7 ++- firmware/targets/f7/api_symbols.csv | 3 +- firmware/targets/f7/ble_glue/gap.h | 2 +- firmware/targets/f7/furi_hal/furi_hal_bt.c | 43 +++++++++------- .../targets/f7/furi_hal/furi_hal_version.c | 6 ++- .../targets/furi_hal_include/furi_hal_bt.h | 13 ++++- .../furi_hal_include/furi_hal_version.h | 3 +- 8 files changed, 84 insertions(+), 44 deletions(-) diff --git a/applications/external/bad_bt/helpers/ducky_script.c b/applications/external/bad_bt/helpers/ducky_script.c index a59d377f2..96807f44d 100644 --- a/applications/external/bad_bt/helpers/ducky_script.c +++ b/applications/external/bad_bt/helpers/ducky_script.c @@ -64,10 +64,11 @@ static inline void update_bt_timeout(Bt* bt) { } typedef enum { - WorkerEvtToggle = (1 << 0), - WorkerEvtEnd = (1 << 1), - WorkerEvtConnect = (1 << 2), - WorkerEvtDisconnect = (1 << 3), + WorkerEvtStartStop = (1 << 0), + WorkerEvtPauseResume = (1 << 1), + WorkerEvtEnd = (1 << 2), + WorkerEvtConnect = (1 << 3), + WorkerEvtDisconnect = (1 << 4), } WorkerEvtFlags; static const char ducky_cmd_id[] = {"ID"}; @@ -280,6 +281,7 @@ static bool ducky_set_bt_id(BadBtScript* bad_bt, const char* line) { return false; } } + furi_hal_bt_reverse_mac_addr(mac); furi_hal_bt_set_profile_adv_name(FuriHalBtProfileHidKeyboard, line + mac_len); bt_set_profile_mac_address(bad_bt->bt, mac); @@ -498,24 +500,26 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateNotConnected) { // State: Not connected uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtConnect | WorkerEvtToggle, FuriWaitForever); + WorkerEvtEnd | WorkerEvtConnect | WorkerEvtDisconnect | WorkerEvtStartStop, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; } else if(flags & WorkerEvtConnect) { worker_state = BadBtStateIdle; // Ready to run - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateWillRun; // Will run when connected } bad_bt->st.state = worker_state; } else if(worker_state == BadBtStateIdle) { // State: ready to start uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriWaitForever); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtConnect | WorkerEvtDisconnect, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { // Start executing script + } else if(flags & WorkerEvtStartStop) { // Start executing script delay_val = 0; bad_bt->buf_len = 0; bad_bt->st.line_cur = 0; @@ -534,7 +538,8 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateWillRun) { // State: start on connection uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtConnect | WorkerEvtToggle, FuriWaitForever); + WorkerEvtEnd | WorkerEvtConnect | WorkerEvtDisconnect | WorkerEvtStartStop, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; @@ -549,21 +554,21 @@ static int32_t bad_bt_worker(void* context) { storage_file_seek(script_file, 0, true); // extra time for PC to recognize Flipper as keyboard flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtDisconnect | WorkerEvtToggle, + WorkerEvtEnd | WorkerEvtDisconnect | WorkerEvtStartStop, FuriFlagWaitAny | FuriFlagNoClear, 1500); if(flags == (unsigned)FuriFlagErrorTimeout) { // If nothing happened - start script execution worker_state = BadBtStateRunning; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; - furi_thread_flags_clear(WorkerEvtToggle); + furi_thread_flags_clear(WorkerEvtStartStop); } update_bt_timeout(bad_bt->bt); bad_bt_script_set_keyboard_layout(bad_bt, bad_bt->keyboard_layout); - } else if(flags & WorkerEvtToggle) { // Cancel scheduled execution + } else if(flags & WorkerEvtStartStop) { // Cancel scheduled execution worker_state = BadBtStateNotConnected; } bad_bt->st.state = worker_state; @@ -571,13 +576,15 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateRunning) { // State: running uint16_t delay_cur = (delay_val > 1000) ? (1000) : (delay_val); uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriFlagWaitAny, delay_cur); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtConnect | WorkerEvtDisconnect, + FuriFlagWaitAny, + delay_cur); delay_val -= delay_cur; if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; // Stop executing script furi_hal_bt_hid_kb_release_all(); @@ -630,11 +637,14 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateWaitForBtn) { // State: Wait for button Press uint16_t delay_cur = (delay_val > 1000) ? (1000) : (delay_val); uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriFlagWaitAny, delay_cur); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtPauseResume | WorkerEvtConnect | + WorkerEvtDisconnect, + FuriFlagWaitAny, + delay_cur); if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { delay_val = 0; worker_state = BadBtStateRunning; } else if(flags & WorkerEvtDisconnect) { @@ -646,14 +656,15 @@ static int32_t bad_bt_worker(void* context) { } } else if(worker_state == BadBtStateStringDelay) { // State: print string with delays uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtPauseResume | WorkerEvtConnect | + WorkerEvtDisconnect, FuriFlagWaitAny, bad_bt->stringdelay); if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; // Stop executing script furi_hal_bt_hid_kb_release_all(); @@ -768,7 +779,7 @@ void bad_bt_script_set_keyboard_layout(BadBtScript* bad_bt, FuriString* layout_p void bad_bt_script_toggle(BadBtScript* bad_bt) { furi_assert(bad_bt); - furi_thread_flags_set(furi_thread_get_id(bad_bt->thread), WorkerEvtToggle); + furi_thread_flags_set(furi_thread_get_id(bad_bt->thread), WorkerEvtStartStop); } BadBtState* bad_bt_script_get_state(BadBtScript* bad_bt) { diff --git a/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c b/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c index 47f63e08c..dcc783f0f 100644 --- a/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c +++ b/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c @@ -11,6 +11,8 @@ void bad_bt_scene_config_mac_byte_input_callback(void* context) { void bad_bt_scene_config_mac_on_enter(void* context) { BadBtApp* bad_bt = context; + furi_hal_bt_reverse_mac_addr(bad_bt->config.bt_mac); + // Setup view ByteInput* byte_input = bad_bt->byte_input; byte_input_set_header_text(byte_input, "Set BT MAC address"); @@ -30,7 +32,6 @@ bool bad_bt_scene_config_mac_on_event(void* context, SceneManagerEvent event) { if(event.type == SceneManagerEventTypeCustom) { if(event.event == BadBtAppCustomEventByteInputDone) { - bt_set_profile_mac_address(bad_bt->bt, bad_bt->config.bt_mac); scene_manager_previous_scene(bad_bt->scene_manager); consumed = true; } @@ -41,6 +42,10 @@ bool bad_bt_scene_config_mac_on_event(void* context, SceneManagerEvent event) { void bad_bt_scene_config_mac_on_exit(void* context) { BadBtApp* bad_bt = context; + furi_hal_bt_reverse_mac_addr(bad_bt->config.bt_mac); + + bt_set_profile_mac_address(bad_bt->bt, bad_bt->config.bt_mac); + // Clear view byte_input_set_result_callback(bad_bt->byte_input, NULL, NULL, NULL, NULL, 0); byte_input_set_header_text(bad_bt->byte_input, ""); diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index f8d7ef279..a636a757a 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1072,6 +1072,7 @@ Function,+,furi_hal_bt_lock_core2,void, Function,+,furi_hal_bt_nvm_sram_sem_acquire,void, Function,+,furi_hal_bt_nvm_sram_sem_release,void, Function,+,furi_hal_bt_reinit,void, +Function,+,furi_hal_bt_reverse_mac_addr,void,uint8_t[( 6 )] Function,+,furi_hal_bt_serial_notify_buffer_is_empty,void, Function,+,furi_hal_bt_serial_set_event_callback,void,"uint16_t, FuriHalBtSerialCallback, void*" Function,+,furi_hal_bt_serial_set_rpc_status,void,FuriHalBtSerialRpcStatus @@ -1079,7 +1080,7 @@ Function,+,furi_hal_bt_serial_start,void, Function,+,furi_hal_bt_serial_stop,void, Function,+,furi_hal_bt_serial_tx,_Bool,"uint8_t*, uint16_t" Function,+,furi_hal_bt_set_key_storage_change_callback,void,"BleGlueKeyStorageChangedCallback, void*" -Function,+,furi_hal_bt_set_profile_adv_name,void,"FuriHalBtProfile, const char[( 18 + 1 )]" +Function,+,furi_hal_bt_set_profile_adv_name,void,"FuriHalBtProfile, const char[( ( 1 + 8 + ( 8 + 1 ) ) + 1 )]" Function,+,furi_hal_bt_set_profile_mac_addr,void,"FuriHalBtProfile, const uint8_t[( 6 )]" Function,+,furi_hal_bt_set_profile_pairing_method,void,"FuriHalBtProfile, GapPairing" Function,+,furi_hal_bt_start_advertising,void, diff --git a/firmware/targets/f7/ble_glue/gap.h b/firmware/targets/f7/ble_glue/gap.h index 7b317e06c..396d64e67 100644 --- a/firmware/targets/f7/ble_glue/gap.h +++ b/firmware/targets/f7/ble_glue/gap.h @@ -67,7 +67,7 @@ typedef struct { bool bonding_mode; GapPairing pairing_method; uint8_t mac_address[GAP_MAC_ADDR_SIZE]; - char adv_name[FURI_HAL_VERSION_DEVICE_NAME_LENGTH]; + char adv_name[FURI_HAL_BT_ADV_NAME_LENGTH]; GapConnectionParamsRequest conn_param; } GapConfig; diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/firmware/targets/f7/furi_hal/furi_hal_bt.c index 2fc028d7c..5a150d388 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_bt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_bt.c @@ -14,9 +14,6 @@ #define TAG "FuriHalBt" -#define FURI_HAL_BT_DEFAULT_MAC_ADDR \ - { 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 } - /* Time, in ms, to wait for mode transition before crashing */ #define C2_MODE_SWITCH_TIMEOUT 10000 @@ -238,28 +235,29 @@ bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, strlcpy( config->adv_name, furi_hal_version_get_ble_local_device_name_ptr(), - FURI_HAL_VERSION_DEVICE_NAME_LENGTH); + FURI_HAL_BT_ADV_NAME_LENGTH); config->adv_service_uuid |= furi_hal_version_get_hw_color(); } else if(profile == FuriHalBtProfileHidKeyboard) { // Change MAC address for HID profile - uint8_t default_mac[sizeof(config->mac_address)] = FURI_HAL_BT_DEFAULT_MAC_ADDR; const uint8_t* normal_mac = furi_hal_version_get_ble_mac(); - if(memcmp(config->mac_address, default_mac, sizeof(config->mac_address)) == 0) { + uint8_t empty_mac[sizeof(config->mac_address)] = FURI_HAL_BT_EMPTY_MAC_ADDR; + uint8_t default_mac[sizeof(config->mac_address)] = FURI_HAL_BT_DEFAULT_MAC_ADDR; + if(memcmp(config->mac_address, empty_mac, sizeof(config->mac_address)) == 0 || + memcmp(config->mac_address, normal_mac, sizeof(config->mac_address)) == 0 || + memcmp(config->mac_address, default_mac, sizeof(config->mac_address)) == 0) { memcpy(config->mac_address, normal_mac, sizeof(config->mac_address)); - } - if(memcmp(config->mac_address, normal_mac, sizeof(config->mac_address)) == 0) { config->mac_address[2]++; } // Change name Flipper -> Control - if(strnlen(config->adv_name, FURI_HAL_VERSION_DEVICE_NAME_LENGTH) < 2 || - strnlen(config->adv_name + 1, FURI_HAL_VERSION_DEVICE_NAME_LENGTH) < 1) { + if(strnlen(config->adv_name, FURI_HAL_BT_ADV_NAME_LENGTH) < 2 || + strnlen(config->adv_name + 1, FURI_HAL_BT_ADV_NAME_LENGTH - 1) < 1) { snprintf( config->adv_name, - FURI_HAL_VERSION_DEVICE_NAME_LENGTH, + FURI_HAL_BT_ADV_NAME_LENGTH, "%cControl %s", - *furi_hal_version_get_ble_local_device_name_ptr(), - furi_hal_version_get_ble_local_device_name_ptr() + 9); + AD_TYPE_COMPLETE_LOCAL_NAME, + furi_hal_version_get_name_ptr()); } } if(!gap_init(config, event_cb, context)) { @@ -485,6 +483,15 @@ uint32_t furi_hal_bt_get_conn_rssi(uint8_t* rssi) { return since; } +void furi_hal_bt_reverse_mac_addr(uint8_t mac_addr[GAP_MAC_ADDR_SIZE]) { + uint8_t tmp; + for(size_t i = 0; i < GAP_MAC_ADDR_SIZE / 2; i++) { + tmp = mac_addr[i]; + mac_addr[i] = mac_addr[GAP_MAC_ADDR_SIZE - 1 - i]; + mac_addr[GAP_MAC_ADDR_SIZE - 1 - i] = tmp; + } +} + void furi_hal_bt_set_profile_adv_name( FuriHalBtProfile profile, const char name[FURI_HAL_BT_ADV_NAME_LENGTH]) { @@ -492,13 +499,13 @@ void furi_hal_bt_set_profile_adv_name( furi_assert(name); if(strlen(name) == 0) { - memset( - &(profile_config[profile].config.adv_name[1]), - 0, - strlen(&(profile_config[profile].config.adv_name[1]))); + memset(&(profile_config[profile].config.adv_name[1]), 0, FURI_HAL_BT_ADV_NAME_LENGTH - 1); } else { profile_config[profile].config.adv_name[0] = AD_TYPE_COMPLETE_LOCAL_NAME; - memcpy(&(profile_config[profile].config.adv_name[1]), name, FURI_HAL_BT_ADV_NAME_LENGTH); + strlcpy( + &(profile_config[profile].config.adv_name[1]), + name, + FURI_HAL_BT_ADV_NAME_LENGTH - 1 /* BLE symbol */); } } diff --git a/firmware/targets/f7/furi_hal/furi_hal_version.c b/firmware/targets/f7/furi_hal/furi_hal_version.c index 0e5f428ba..b6460cc5f 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_version.c +++ b/firmware/targets/f7/furi_hal/furi_hal_version.c @@ -111,7 +111,11 @@ void furi_hal_version_set_name(const char* name) { } uint32_t company_id = LL_FLASH_GetSTCompanyID(); - uint32_t device_id = LL_FLASH_GetDeviceID(); + // uint32_t device_id = LL_FLASH_GetDeviceID(); + // Some flippers return 0x27 (flippers with chip revision 2003 6495) instead of 0x26 (flippers with chip revision 2001 6495) + // Mobile apps expects it to return 0x26 + // Hardcoded here temporarily until mobile apps is updated to handle 0x27 + uint32_t device_id = 0x26; furi_hal_version.ble_mac[0] = (uint8_t)(udn & 0x000000FF); furi_hal_version.ble_mac[1] = (uint8_t)((udn & 0x0000FF00) >> 8); furi_hal_version.ble_mac[2] = (uint8_t)((udn & 0x00FF0000) >> 16); diff --git a/firmware/targets/furi_hal_include/furi_hal_bt.h b/firmware/targets/furi_hal_include/furi_hal_bt.h index f128b1064..7354d8770 100644 --- a/firmware/targets/furi_hal_include/furi_hal_bt.h +++ b/firmware/targets/furi_hal_include/furi_hal_bt.h @@ -18,6 +18,12 @@ #define FURI_HAL_BT_STACK_VERSION_MINOR (12) #define FURI_HAL_BT_C2_START_TIMEOUT 1000 +#define FURI_HAL_BT_EMPTY_MAC_ADDR \ + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } + +#define FURI_HAL_BT_DEFAULT_MAC_ADDR \ + { 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 } + #ifdef __cplusplus extern "C" { #endif @@ -218,7 +224,12 @@ float furi_hal_bt_get_rssi(); */ uint32_t furi_hal_bt_get_transmitted_packets(); -// BadBT stuff +// BadBT Stuff +/** Reverse a MAC address byte order in-place + * @param[in] mac mac address to reverse +*/ +void furi_hal_bt_reverse_mac_addr(uint8_t mac_addr[GAP_MAC_ADDR_SIZE]); + /** Modify profile advertisement name and restart bluetooth * @param[in] profile profile type * @param[in] name new adv name diff --git a/firmware/targets/furi_hal_include/furi_hal_version.h b/firmware/targets/furi_hal_include/furi_hal_version.h index 4a3f4c170..351a7849b 100644 --- a/firmware/targets/furi_hal_include/furi_hal_version.h +++ b/firmware/targets/furi_hal_include/furi_hal_version.h @@ -16,9 +16,10 @@ extern "C" { #define FURI_HAL_VERSION_NAME_LENGTH 8 #define FURI_HAL_VERSION_ARRAY_NAME_LENGTH (FURI_HAL_VERSION_NAME_LENGTH + 1) -#define FURI_HAL_BT_ADV_NAME_LENGTH (18 + 1) // 18 characters + null terminator /** BLE symbol + "Flipper " + name */ #define FURI_HAL_VERSION_DEVICE_NAME_LENGTH (1 + 8 + FURI_HAL_VERSION_ARRAY_NAME_LENGTH) +// 18 characters + null terminator +#define FURI_HAL_BT_ADV_NAME_LENGTH (FURI_HAL_VERSION_DEVICE_NAME_LENGTH + 1) /** OTP Versions enum */ typedef enum { From bbbb371d357a78c2a97b9f19628d1a677d0e89c7 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 14:51:22 +0300 Subject: [PATCH 08/40] fix typos --- firmware/targets/f7/ble_glue/gap.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/firmware/targets/f7/ble_glue/gap.c b/firmware/targets/f7/ble_glue/gap.c index 55ddc5faf..ab7b9d16c 100644 --- a/firmware/targets/f7/ble_glue/gap.c +++ b/firmware/targets/f7/ble_glue/gap.c @@ -500,7 +500,7 @@ void gap_stop_advertising() { furi_mutex_release(gap->state_mutex); } -static void gap_advetise_timer_callback(void* context) { +static void gap_advertise_timer_callback(void* context) { UNUSED(context); GapCommand command = GapCommandAdvLowPower; furi_check(furi_message_queue_put(gap->command_queue, &command, 0) == FuriStatusOk); @@ -514,7 +514,7 @@ bool gap_init(GapConfig* config, GapEventCallback on_event_cb, void* context) { gap = malloc(sizeof(Gap)); gap->config = config; // Create advertising timer - gap->advertise_timer = furi_timer_alloc(gap_advetise_timer_callback, FuriTimerTypeOnce, NULL); + gap->advertise_timer = furi_timer_alloc(gap_advertise_timer_callback, FuriTimerTypeOnce, NULL); // Initialization of GATT & GAP layer gap->service.adv_name = config->adv_name; gap_init_svc(gap); From ae545cdb0911bcf14b8a4d4d0562ccf528f1a6a4 Mon Sep 17 00:00:00 2001 From: Nikita Vostokov Date: Wed, 5 Jul 2023 15:04:56 +0300 Subject: [PATCH 09/40] Fix name reset after bt apps exit --- firmware/targets/f7/furi_hal/furi_hal_bt.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/firmware/targets/f7/furi_hal/furi_hal_bt.c index 5a150d388..870d9c967 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_bt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_bt.c @@ -54,6 +54,7 @@ FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = { .bonding_mode = true, .pairing_method = GapPairingPinCodeShow, .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR, + .adv_name = "\0", .conn_param = { .conn_int_min = 0x18, // 30 ms @@ -74,6 +75,7 @@ FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = { .bonding_mode = true, .pairing_method = GapPairingPinCodeVerifyYesNo, .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR, + .adv_name = "\0", .conn_param = { .conn_int_min = 0x18, // 30 ms @@ -231,11 +233,12 @@ bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, // Set mac address memcpy( config->mac_address, furi_hal_version_get_ble_mac(), sizeof(config->mac_address)); - // Set advertise name - strlcpy( - config->adv_name, - furi_hal_version_get_ble_local_device_name_ptr(), - FURI_HAL_BT_ADV_NAME_LENGTH); + // Set stock advertise name only once on bootup + if(!strnlen(config->adv_name, FURI_HAL_BT_ADV_NAME_LENGTH)) + strlcpy( + config->adv_name, + furi_hal_version_get_ble_local_device_name_ptr(), + FURI_HAL_BT_ADV_NAME_LENGTH); config->adv_service_uuid |= furi_hal_version_get_hw_color(); } else if(profile == FuriHalBtProfileHidKeyboard) { From 0980424bb9447d7969ccfa1c3ff957352644c0ed Mon Sep 17 00:00:00 2001 From: Nikita Vostokov Date: Wed, 5 Jul 2023 15:04:56 +0300 Subject: [PATCH 10/40] Revert "Fix name reset after bt apps exit" This reverts commit ae545cdb0911bcf14b8a4d4d0562ccf528f1a6a4. --- firmware/targets/f7/furi_hal/furi_hal_bt.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/firmware/targets/f7/furi_hal/furi_hal_bt.c index 870d9c967..5a150d388 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_bt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_bt.c @@ -54,7 +54,6 @@ FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = { .bonding_mode = true, .pairing_method = GapPairingPinCodeShow, .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR, - .adv_name = "\0", .conn_param = { .conn_int_min = 0x18, // 30 ms @@ -75,7 +74,6 @@ FuriHalBtProfileConfig profile_config[FuriHalBtProfileNumber] = { .bonding_mode = true, .pairing_method = GapPairingPinCodeVerifyYesNo, .mac_address = FURI_HAL_BT_DEFAULT_MAC_ADDR, - .adv_name = "\0", .conn_param = { .conn_int_min = 0x18, // 30 ms @@ -233,12 +231,11 @@ bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, // Set mac address memcpy( config->mac_address, furi_hal_version_get_ble_mac(), sizeof(config->mac_address)); - // Set stock advertise name only once on bootup - if(!strnlen(config->adv_name, FURI_HAL_BT_ADV_NAME_LENGTH)) - strlcpy( - config->adv_name, - furi_hal_version_get_ble_local_device_name_ptr(), - FURI_HAL_BT_ADV_NAME_LENGTH); + // Set advertise name + strlcpy( + config->adv_name, + furi_hal_version_get_ble_local_device_name_ptr(), + FURI_HAL_BT_ADV_NAME_LENGTH); config->adv_service_uuid |= furi_hal_version_get_hw_color(); } else if(profile == FuriHalBtProfileHidKeyboard) { From 97fbd84e08d77a3ef2edf7a059c8d3635cd7facc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=81=82=E3=81=8F?= Date: Wed, 5 Jul 2023 22:56:52 +0900 Subject: [PATCH 11/40] FuriHal, Infrared, Protobuf: various fixes and improvements (#2845) * Infrared: fix crash caused by null-ptr dereference in interrupt call. FuriHal: callback checks in interrupt handlers. Protobuf: bump to latest. * DesktopSettings: allow application browser as favourite * Format sources * FuriHal: fix pvs warnings --- .../scenes/desktop_settings_scene_favorite.c | 27 ++++++++++++++++--- assets/protobuf | 2 +- .../targets/f7/furi_hal/furi_hal_infrared.c | 3 --- .../targets/f7/furi_hal/furi_hal_interrupt.c | 11 ++++---- 4 files changed, 30 insertions(+), 13 deletions(-) diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c index c43f8e350..c35a10568 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c @@ -5,8 +5,11 @@ #include #include +#define EXTERNAL_BROWSER_NAME ("Applications") +#define EXTERNAL_BROWSER_INDEX (FLIPPER_APPS_COUNT + 1) + #define EXTERNAL_APPLICATION_NAME ("[External Application]") -#define EXTERNAL_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 1) +#define EXTERNAL_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 2) static bool favorite_fap_selector_item_callback( FuriString* file_path, @@ -58,14 +61,28 @@ void desktop_settings_scene_favorite_on_enter(void* context) { } } + // Special case: Application browser + submenu_add_item( + submenu, + EXTERNAL_BROWSER_NAME, + EXTERNAL_BROWSER_INDEX, + desktop_settings_scene_favorite_submenu_callback, + app); + + // Special case: Specific application submenu_add_item( submenu, EXTERNAL_APPLICATION_NAME, EXTERNAL_APPLICATION_INDEX, desktop_settings_scene_favorite_submenu_callback, app); + if(curr_favorite_app->is_external) { - pre_select_item = EXTERNAL_APPLICATION_INDEX; + if(curr_favorite_app->name_or_path[0] == '\0') { + pre_select_item = EXTERNAL_BROWSER_INDEX; + } else { + pre_select_item = EXTERNAL_APPLICATION_INDEX; + } } submenu_set_header( @@ -86,7 +103,11 @@ bool desktop_settings_scene_favorite_on_event(void* context, SceneManagerEvent e &app->settings.favorite_secondary; if(event.type == SceneManagerEventTypeCustom) { - if(event.event == EXTERNAL_APPLICATION_INDEX) { + if(event.event == EXTERNAL_BROWSER_INDEX) { + curr_favorite_app->is_external = true; + curr_favorite_app->name_or_path[0] = '\0'; + consumed = true; + } else if(event.event == EXTERNAL_APPLICATION_INDEX) { const DialogsFileBrowserOptions browser_options = { .extension = ".fap", .icon = &I_unknown_10px, diff --git a/assets/protobuf b/assets/protobuf index f71c4b7f7..08a907d95 160000 --- a/assets/protobuf +++ b/assets/protobuf @@ -1 +1 @@ -Subproject commit f71c4b7f750f2539a1fed08925d8da3abdc80ff9 +Subproject commit 08a907d95733600becc41c0602ef5ee4c4baf782 diff --git a/firmware/targets/f7/furi_hal/furi_hal_infrared.c b/firmware/targets/f7/furi_hal/furi_hal_infrared.c index c60db5f20..d3e36c2b5 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_infrared.c +++ b/firmware/targets/f7/furi_hal/furi_hal_infrared.c @@ -373,9 +373,6 @@ static void furi_hal_infrared_configure_tim_pwm_tx(uint32_t freq, float duty_cyc LL_TIM_EnableAllOutputs(INFRARED_DMA_TIMER); LL_TIM_DisableIT_UPDATE(INFRARED_DMA_TIMER); LL_TIM_EnableDMAReq_UPDATE(INFRARED_DMA_TIMER); - - NVIC_SetPriority(TIM1_UP_TIM16_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0)); - NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn); } static void furi_hal_infrared_configure_tim_cmgr2_dma_tx(void) { diff --git a/firmware/targets/f7/furi_hal/furi_hal_interrupt.c b/firmware/targets/f7/furi_hal/furi_hal_interrupt.c index b5639d230..9f4d43316 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_interrupt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_interrupt.c @@ -62,7 +62,7 @@ const IRQn_Type furi_hal_interrupt_irqn[FuriHalInterruptIdMax] = { __attribute__((always_inline)) static inline void furi_hal_interrupt_call(FuriHalInterruptId index) { - furi_assert(furi_hal_interrupt_isr[index].isr); + furi_check(furi_hal_interrupt_isr[index].isr); furi_hal_interrupt_isr[index].isr(furi_hal_interrupt_isr[index].context); } @@ -127,16 +127,15 @@ void furi_hal_interrupt_set_isr_ex( uint16_t priority, FuriHalInterruptISR isr, void* context) { - furi_assert(index < FuriHalInterruptIdMax); - furi_assert(priority < 15); - furi_assert(furi_hal_interrupt_irqn[index]); + furi_check(index < FuriHalInterruptIdMax); + furi_check(priority < 15); if(isr) { // Pre ISR set - furi_assert(furi_hal_interrupt_isr[index].isr == NULL); + furi_check(furi_hal_interrupt_isr[index].isr == NULL); } else { // Pre ISR clear - furi_assert(furi_hal_interrupt_isr[index].isr != NULL); + furi_check(furi_hal_interrupt_isr[index].isr != NULL); furi_hal_interrupt_disable(index); furi_hal_interrupt_clear_pending(index); } From 255830ffab64aa2aa03b9f108426508f5f252e05 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 17:56:08 +0300 Subject: [PATCH 12/40] FAAC ui and counter with no seed fixes --- lib/subghz/protocols/faac_slh.c | 56 ++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/lib/subghz/protocols/faac_slh.c b/lib/subghz/protocols/faac_slh.c index c1c96b7a7..62e8c37d2 100644 --- a/lib/subghz/protocols/faac_slh.c +++ b/lib/subghz/protocols/faac_slh.c @@ -110,7 +110,9 @@ void subghz_protocol_encoder_faac_slh_free(void* context) { } static bool subghz_protocol_faac_slh_gen_data(SubGhzProtocolEncoderFaacSLH* instance) { - instance->generic.cnt += furi_hal_subghz_get_rolling_counter_mult(); + if(instance->generic.seed != 0x0) { + instance->generic.cnt += furi_hal_subghz_get_rolling_counter_mult(); + } uint32_t fix = instance->generic.serial << 4 | instance->generic.btn; uint32_t hop = 0; uint32_t decrypt = 0; @@ -499,21 +501,39 @@ void subghz_protocol_decoder_faac_slh_get_string(void* context, FuriString* outp uint32_t code_fix = instance->generic.data >> 32; uint32_t code_hop = instance->generic.data & 0xFFFFFFFF; - furi_string_cat_printf( - output, - "%s %dbit\r\n" - "Key:%lX%08lX\r\n" - "Fix:%08lX Cnt:%05lX\r\n" - "Hop:%08lX Btn:%X\r\n" - "Sn:%07lX Sd:%08lX", - instance->generic.protocol_name, - instance->generic.data_count_bit, - (uint32_t)(instance->generic.data >> 32), - (uint32_t)instance->generic.data, - code_fix, - instance->generic.cnt, - code_hop, - instance->generic.btn, - instance->generic.serial, - instance->generic.seed); + if(instance->generic.seed == 0x0) { + furi_string_cat_printf( + output, + "%s %dbit\r\n" + "Key:%lX%08lX\r\n" + "Fix:%08lX\r\n" + "Hop:%08lX Btn:%X\r\n" + "Sn:%07lX Sd:Unknown", + instance->generic.protocol_name, + instance->generic.data_count_bit, + (uint32_t)(instance->generic.data >> 32), + (uint32_t)instance->generic.data, + code_fix, + code_hop, + instance->generic.btn, + instance->generic.serial); + } else { + furi_string_cat_printf( + output, + "%s %dbit\r\n" + "Key:%lX%08lX\r\n" + "Fix:%08lX Cnt:%05lX\r\n" + "Hop:%08lX Btn:%X\r\n" + "Sn:%07lX Sd:%08lX", + instance->generic.protocol_name, + instance->generic.data_count_bit, + (uint32_t)(instance->generic.data >> 32), + (uint32_t)instance->generic.data, + code_fix, + instance->generic.cnt, + code_hop, + instance->generic.btn, + instance->generic.serial, + instance->generic.seed); + } } From 000bc845a811ae1242697dc62f175c9b6c79c30e Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 17:59:09 +0300 Subject: [PATCH 13/40] Multiple Fixes by hedger --- applications/external/bomberduck/bomberduck.c | 1 - .../flappy_bird/assets/bird/frame_rate | 1 - .../assets/{bird/frame_01.png => bird_01.png} | Bin .../assets/{bird/frame_02.png => bird_02.png} | Bin .../assets/{bird/frame_03.png => bird_03.png} | Bin .../external/flappy_bird/flappy_bird.c | 27 +++++--- .../external/heap_defence_game/heap_defence.c | 1 - .../external/minesweeper/minesweeper.c | 1 - .../external/swd_probe/swd_probe_app.c | 65 ++++++++++-------- 9 files changed, 53 insertions(+), 43 deletions(-) delete mode 100644 applications/external/flappy_bird/assets/bird/frame_rate rename applications/external/flappy_bird/assets/{bird/frame_01.png => bird_01.png} (100%) rename applications/external/flappy_bird/assets/{bird/frame_02.png => bird_02.png} (100%) rename applications/external/flappy_bird/assets/{bird/frame_03.png => bird_03.png} (100%) diff --git a/applications/external/bomberduck/bomberduck.c b/applications/external/bomberduck/bomberduck.c index 79471c99e..3e9d52f56 100644 --- a/applications/external/bomberduck/bomberduck.c +++ b/applications/external/bomberduck/bomberduck.c @@ -5,7 +5,6 @@ #include #include #include -#include #include "bomberduck_icons.h" #include diff --git a/applications/external/flappy_bird/assets/bird/frame_rate b/applications/external/flappy_bird/assets/bird/frame_rate deleted file mode 100644 index e440e5c84..000000000 --- a/applications/external/flappy_bird/assets/bird/frame_rate +++ /dev/null @@ -1 +0,0 @@ -3 \ No newline at end of file diff --git a/applications/external/flappy_bird/assets/bird/frame_01.png b/applications/external/flappy_bird/assets/bird_01.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_01.png rename to applications/external/flappy_bird/assets/bird_01.png diff --git a/applications/external/flappy_bird/assets/bird/frame_02.png b/applications/external/flappy_bird/assets/bird_02.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_02.png rename to applications/external/flappy_bird/assets/bird_02.png diff --git a/applications/external/flappy_bird/assets/bird/frame_03.png b/applications/external/flappy_bird/assets/bird_03.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_03.png rename to applications/external/flappy_bird/assets/bird_03.png diff --git a/applications/external/flappy_bird/flappy_bird.c b/applications/external/flappy_bird/flappy_bird.c index 2a50868f2..7ec152b99 100644 --- a/applications/external/flappy_bird/flappy_bird.c +++ b/applications/external/flappy_bird/flappy_bird.c @@ -3,7 +3,6 @@ #include #include #include -#include #include #include @@ -30,6 +29,19 @@ typedef enum { EventTypeKey, } EventType; +typedef enum { + BirdState0 = 0, + BirdState1, + BirdState2, + BirdStateMAX +} BirdState; + +const Icon* bird_states[BirdStateMAX] = { + &I_bird_01, + &I_bird_02, + &I_bird_03, +}; + typedef struct { int x; int y; @@ -38,7 +50,6 @@ typedef struct { typedef struct { float gravity; POINT point; - IconAnimation* sprite; } BIRD; typedef struct { @@ -93,7 +104,6 @@ static void flappy_game_state_init(GameState* const game_state) { bird.gravity = 0.0f; bird.point.x = 15; bird.point.y = 32; - bird.sprite = icon_animation_alloc(&A_bird); game_state->debug = DEBUG; game_state->bird = bird; @@ -106,7 +116,6 @@ static void flappy_game_state_init(GameState* const game_state) { } static void flappy_game_state_free(GameState* const game_state) { - icon_animation_free(game_state->bird.sprite); free(game_state); } @@ -224,14 +233,14 @@ static void flappy_game_render_callback(Canvas* const canvas, void* ctx) { } // Switch animation - game_state->bird.sprite->frame = 1; + BirdState bird_state = BirdState1; if(game_state->bird.gravity < -0.5) - game_state->bird.sprite->frame = 0; + bird_state = BirdState0; else if(game_state->bird.gravity > 0.5) - game_state->bird.sprite->frame = 2; + bird_state = BirdState2; - canvas_draw_icon_animation( - canvas, game_state->bird.point.x, game_state->bird.point.y, game_state->bird.sprite); + canvas_draw_icon( + canvas, game_state->bird.point.x, game_state->bird.point.y, bird_states[bird_state]); canvas_set_font(canvas, FontSecondary); char buffer[12]; diff --git a/applications/external/heap_defence_game/heap_defence.c b/applications/external/heap_defence_game/heap_defence.c index 3c8483c75..111c22dce 100644 --- a/applications/external/heap_defence_game/heap_defence.c +++ b/applications/external/heap_defence_game/heap_defence.c @@ -14,7 +14,6 @@ #include #include #include -#include #include #define Y_FIELD_SIZE 6 diff --git a/applications/external/minesweeper/minesweeper.c b/applications/external/minesweeper/minesweeper.c index c169b075e..4e92fba33 100644 --- a/applications/external/minesweeper/minesweeper.c +++ b/applications/external/minesweeper/minesweeper.c @@ -6,7 +6,6 @@ #include #include -#include #include diff --git a/applications/external/swd_probe/swd_probe_app.c b/applications/external/swd_probe/swd_probe_app.c index 27ef03f5d..63f219508 100644 --- a/applications/external/swd_probe/swd_probe_app.c +++ b/applications/external/swd_probe/swd_probe_app.c @@ -679,7 +679,7 @@ static bool swd_apscan_test(AppFSM* const ctx, uint32_t ap) { static void swd_script_log(ScriptContext* ctx, FuriLogLevel level, const char* format, ...) { bool commandline = false; ScriptContext* cur = ctx; - char buffer[256]; + FuriString* buffer = furi_string_alloc(); va_list argp; va_start(argp, format); @@ -704,17 +704,19 @@ static void swd_script_log(ScriptContext* ctx, FuriLogLevel level, const char* f break; } - strcpy(buffer, prefix); - size_t pos = strlen(buffer); - vsnprintf(&buffer[pos], sizeof(buffer) - pos - 2, format, argp); - strcat(buffer, "\n"); - if(!usb_uart_tx_data(ctx->app->uart, (uint8_t*)buffer, strlen(buffer))) { + furi_string_cat_str(buffer, prefix); + furi_string_cat_printf(buffer, format, argp); + furi_string_cat_str(buffer, "\n"); + + if(!usb_uart_tx_data( + ctx->app->uart, (uint8_t*)furi_string_get_cstr(buffer), furi_string_size(buffer))) { DBGS("Sending via USB failed"); } } else { - LOG(buffer); + LOG(furi_string_get_cstr(buffer)); } va_end(argp); + furi_string_free(buffer); } /* read characters until newline was read */ @@ -939,41 +941,44 @@ static bool swd_scriptfunc_goto(ScriptContext* ctx) { return true; } +#include + static bool swd_scriptfunc_call(ScriptContext* ctx) { DBGS("call"); swd_script_skip_whitespace(ctx); /* fetch previous file directory */ - char filename[MAX_FILE_LENGTH]; - strncpy(filename, ctx->filename, sizeof(filename)); - char* path = strrchr(filename, '/'); - path[1] = '\000'; + FuriString* filepath = furi_string_alloc(); + path_extract_dirname(ctx->filename, filepath); + // strncpy(filename, ctx->filename, sizeof(filename)); - /* append filename */ - if(!swd_script_get_string(ctx, &path[1], sizeof(filename) - strlen(path))) { - swd_script_log(ctx, FuriLogLevelError, "failed to parse filename"); - return false; - } + char filename[MAX_FILE_LENGTH] = {}; + bool success = false; + do { + /* append filename */ + if(!swd_script_get_string(ctx, filename, sizeof(filename))) { + swd_script_log(ctx, FuriLogLevelError, "failed to parse filename"); + break; + } - swd_script_seek_newline(ctx); + swd_script_seek_newline(ctx); + /* append extension */ + furi_string_cat_str(filepath, ".swd"); - /* append extension */ - if(strlen(filename) + 5 >= sizeof(filename)) { - swd_script_log(ctx, FuriLogLevelError, "name too long"); - return false; - } + bool ret = swd_execute_script(ctx->app, furi_string_get_cstr(filepath)); - strcat(filename, ".swd"); + if(!ret) { + swd_script_log( + ctx, FuriLogLevelError, "failed to exec '%s'", furi_string_get_cstr(filepath)); + break; + } - bool ret = swd_execute_script(ctx->app, filename); + success = true; + } while(false); + furi_string_free(filepath); - if(!ret) { - swd_script_log(ctx, FuriLogLevelError, "failed to exec '%s'", filename); - return false; - } - - return true; + return success; } static bool swd_scriptfunc_status(ScriptContext* ctx) { From 0cff0d603ef6d765edb4eddc70f55f67634f1cdc Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 19:21:42 +0300 Subject: [PATCH 14/40] categories --- .../barcode_generator/application.fam | 4 +-- .../external/hex_viewer/application.fam | 2 +- applications/external/hid_app/application.fam | 4 +-- .../external/multi_converter/application.fam | 2 +- .../external/multi_fuzzer/application.fam | 36 +++++++++---------- .../external/text_viewer/application.fam | 2 +- applications/external/totp/application.fam | 12 ++----- 7 files changed, 27 insertions(+), 35 deletions(-) diff --git a/applications/external/barcode_generator/application.fam b/applications/external/barcode_generator/application.fam index 61d6b7394..9bb44915c 100644 --- a/applications/external/barcode_generator/application.fam +++ b/applications/external/barcode_generator/application.fam @@ -10,8 +10,8 @@ App( stack_size=1 * 1024, order=50, fap_icon="barcode_10px.png", - fap_category="Misc", + fap_category="Tools", fap_author="@xMasterX & @msvsergey & @McAzzaMan", fap_version="1.0", fap_description="App displays Barcode on flipper screen and allows to edit it", -) \ No newline at end of file +) diff --git a/applications/external/hex_viewer/application.fam b/applications/external/hex_viewer/application.fam index 03967ffa5..5d6d3959d 100644 --- a/applications/external/hex_viewer/application.fam +++ b/applications/external/hex_viewer/application.fam @@ -10,7 +10,7 @@ App( stack_size=2 * 1024, order=20, fap_icon="icons/hex_10px.png", - fap_category="Misc", + fap_category="Tools", fap_icon_assets="icons", fap_author="@QtRoS", fap_version="1.0", diff --git a/applications/external/hid_app/application.fam b/applications/external/hid_app/application.fam index e96e956d8..c27ad9c81 100644 --- a/applications/external/hid_app/application.fam +++ b/applications/external/hid_app/application.fam @@ -4,7 +4,7 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="hid_usb_app", stack_size=1 * 1024, - fap_category="Misc", + fap_category="USB", fap_icon="hid_usb_10px.png", fap_icon_assets="assets", fap_icon_assets_symbol="hid", @@ -17,7 +17,7 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="hid_ble_app", stack_size=1 * 1024, - fap_category="Misc", + fap_category="Bluetooth", fap_icon="hid_ble_10px.png", fap_icon_assets="assets", fap_icon_assets_symbol="hid", diff --git a/applications/external/multi_converter/application.fam b/applications/external/multi_converter/application.fam index 84eaa805b..3a8a488b4 100644 --- a/applications/external/multi_converter/application.fam +++ b/applications/external/multi_converter/application.fam @@ -7,7 +7,7 @@ App( stack_size=1 * 1024, order=19, fap_icon="converter_10px.png", - fap_category="Misc", + fap_category="Tools", fap_author="@theisolinearchip", fap_version="1.0", fap_description="A multi-unit converter written with an easy and expandable system for adding new units and conversion methods", diff --git a/applications/external/multi_fuzzer/application.fam b/applications/external/multi_fuzzer/application.fam index a0ce1be0a..1fa33943f 100644 --- a/applications/external/multi_fuzzer/application.fam +++ b/applications/external/multi_fuzzer/application.fam @@ -4,21 +4,21 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="fuzzer_start_ibtn", requires=[ - "gui", + "gui", "storage", - "dialogs", - "input", + "dialogs", + "input", "notification", ], stack_size=2 * 1024, fap_icon="icons/ibutt_10px.png", - fap_category="Tools", + fap_category="iButton", fap_private_libs=[ - Lib( - name="worker", - cdefines=["IBUTTON_PROTOCOL"], - ), - ], + Lib( + name="worker", + cdefines=["IBUTTON_PROTOCOL"], + ), + ], fap_icon_assets="icons", fap_icon_assets_symbol="fuzzer", ) @@ -29,21 +29,21 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="fuzzer_start_rfid", requires=[ - "gui", + "gui", "storage", - "dialogs", - "input", + "dialogs", + "input", "notification", ], stack_size=2 * 1024, fap_icon="icons/rfid_10px.png", - fap_category="Tools", + fap_category="RFID 125", fap_private_libs=[ - Lib( - name="worker", - cdefines=["RFID_125_PROTOCOL"], - ), - ], + Lib( + name="worker", + cdefines=["RFID_125_PROTOCOL"], + ), + ], fap_icon_assets="icons", fap_icon_assets_symbol="fuzzer", ) diff --git a/applications/external/text_viewer/application.fam b/applications/external/text_viewer/application.fam index e36b7a870..6222dc643 100644 --- a/applications/external/text_viewer/application.fam +++ b/applications/external/text_viewer/application.fam @@ -10,7 +10,7 @@ App( stack_size=2 * 1024, order=20, fap_icon="icons/text_10px.png", - fap_category="Misc", + fap_category="Tools", fap_icon_assets="icons", fap_author="@kowalski7cc & @kyhwana", fap_version="1.0", diff --git a/applications/external/totp/application.fam b/applications/external/totp/application.fam index 4f71c2ce8..fcac78700 100644 --- a/applications/external/totp/application.fam +++ b/applications/external/totp/application.fam @@ -3,21 +3,13 @@ App( name="Authenticator", apptype=FlipperAppType.EXTERNAL, entry_point="totp_app", - requires=[ - "gui", - "cli", - "dialogs", - "storage", - "input", - "notification", - "bt" - ], + requires=["gui", "cli", "dialogs", "storage", "input", "notification", "bt"], stack_size=2 * 1024, order=20, 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="Misc", + fap_category="Tools", fap_icon_assets="images", fap_icon="totp_10px.png", fap_private_libs=[ From f6d0b1d399d15411f8d436f93ed0537b4233e6e3 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 19:33:27 +0300 Subject: [PATCH 15/40] Change LED and volume settings by 5% steps We discussed such change before with Svarich, but while I was busy with other stuff looks like this Idea has been already implemented by cokyrain So credits goes to cokyrain (github) --- .../notification_settings_app.c | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/applications/settings/notification_settings/notification_settings_app.c b/applications/settings/notification_settings/notification_settings_app.c index 565d4f1f6..195501210 100644 --- a/applications/settings/notification_settings/notification_settings_app.c +++ b/applications/settings/notification_settings/notification_settings_app.c @@ -48,31 +48,25 @@ const int32_t contrast_value[CONTRAST_COUNT] = { 5, }; -#define BACKLIGHT_COUNT 5 +#define BACKLIGHT_COUNT 21 const char* const backlight_text[BACKLIGHT_COUNT] = { - "0%", - "25%", - "50%", - "75%", - "100%", + "0%", "5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", + "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", }; const float backlight_value[BACKLIGHT_COUNT] = { - 0.0f, - 0.25f, - 0.5f, - 0.75f, - 1.0f, + 0.00f, 0.05f, 0.10f, 0.15f, 0.20f, 0.25f, 0.30f, 0.35f, 0.40f, 0.45f, 0.50f, + 0.55f, 0.60f, 0.65f, 0.70f, 0.75f, 0.80f, 0.85f, 0.90f, 0.95f, 1.00f, }; -#define VOLUME_COUNT 5 +#define VOLUME_COUNT 21 const char* const volume_text[VOLUME_COUNT] = { - "0%", - "25%", - "50%", - "75%", - "100%", + "0%", "5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", + "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", +}; +const float volume_value[VOLUME_COUNT] = { + 0.00f, 0.05f, 0.10f, 0.15f, 0.20f, 0.25f, 0.30f, 0.35f, 0.40f, 0.45f, 0.50f, + 0.55f, 0.60f, 0.65f, 0.70f, 0.75f, 0.80f, 0.85f, 0.90f, 0.95f, 1.00f, }; -const float volume_value[VOLUME_COUNT] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}; #define DELAY_COUNT 11 const char* const delay_text[DELAY_COUNT] = { From f3ae09cc16550025d42766f87d1db521e03e92d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=81=82=E3=81=8F?= Date: Thu, 6 Jul 2023 01:39:17 +0900 Subject: [PATCH 16/40] FuriHal: allow nulling null isr (#2846) * FuriHal: allow nulling null isr * FuriHal: include interrupt priority 15 as allowed * Furi: prevent compiler from optimizing arg in r0 of RESTORE_REGISTERS_AND_HALT_MCU --- firmware/targets/f7/furi_hal/furi_hal_interrupt.c | 3 +-- furi/core/check.c | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/firmware/targets/f7/furi_hal/furi_hal_interrupt.c b/firmware/targets/f7/furi_hal/furi_hal_interrupt.c index 9f4d43316..c508dac72 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_interrupt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_interrupt.c @@ -128,14 +128,13 @@ void furi_hal_interrupt_set_isr_ex( FuriHalInterruptISR isr, void* context) { furi_check(index < FuriHalInterruptIdMax); - furi_check(priority < 15); + furi_check(priority <= 15); if(isr) { // Pre ISR set furi_check(furi_hal_interrupt_isr[index].isr == NULL); } else { // Pre ISR clear - furi_check(furi_hal_interrupt_isr[index].isr != NULL); furi_hal_interrupt_disable(index); furi_hal_interrupt_clear_pending(index); } diff --git a/furi/core/check.c b/furi/core/check.c index c5c4ef1a4..f7dcfc595 100644 --- a/furi/core/check.c +++ b/furi/core/check.c @@ -36,7 +36,7 @@ PLACE_IN_SECTION("MB_MEM2") uint32_t __furi_check_registers[13] = {0}; * */ #define RESTORE_REGISTERS_AND_HALT_MCU(debug) \ - register const bool r0 asm("r0") = debug; \ + register bool r0 asm("r0") = debug; \ asm volatile("cbnz r0, with_debugger%= \n" \ "ldr r12, =__furi_check_registers\n" \ "ldm r12, {r0-r11} \n" \ From 94efd48cd0dd600f3cdb04978e0904338fbaa8aa Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 19:43:05 +0300 Subject: [PATCH 17/40] categories again --- applications/external/ir_scope/application.fam | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/applications/external/ir_scope/application.fam b/applications/external/ir_scope/application.fam index f6fb6fbdc..00e161d97 100644 --- a/applications/external/ir_scope/application.fam +++ b/applications/external/ir_scope/application.fam @@ -7,7 +7,7 @@ App( requires=["gui"], stack_size=2 * 1024, fap_icon="ir_scope.png", - fap_category="Tools", + fap_category="Infrared", fap_author="@kallanreed", fap_version="1.0", fap_description="App allows to see incoming IR signals.", From 906cca8f242c7864565464a50b0a2ab6cbfa0475 Mon Sep 17 00:00:00 2001 From: Skorpionm <85568270+Skorpionm@users.noreply.github.com> Date: Wed, 5 Jul 2023 20:48:02 +0400 Subject: [PATCH 18/40] Furi_Power: fix furi_hal_power_enable_otg (#2842) * Furi_Power: fix furi_hal_power_enable_otg * SubGhz: fix error output connected USB * Furi_Hal: fix target F18 * Fix api_symbols.csv version for F7 Co-authored-by: Aleksandr Kutuzov --- applications/main/subghz/helpers/subghz_txrx.c | 16 +++++++++++----- firmware/targets/f18/api_symbols.csv | 5 +++-- firmware/targets/f7/api_symbols.csv | 5 +++-- firmware/targets/f7/furi_hal/furi_hal_power.c | 14 +++++++++++++- .../targets/furi_hal_include/furi_hal_power.h | 6 +++++- lib/drivers/bq25896.c | 8 +++++++- lib/drivers/bq25896.h | 3 +++ lib/drivers/bq25896_reg.h | 18 ++++++++++-------- 8 files changed, 55 insertions(+), 20 deletions(-) diff --git a/applications/main/subghz/helpers/subghz_txrx.c b/applications/main/subghz/helpers/subghz_txrx.c index b911f4434..cbd47f5e5 100644 --- a/applications/main/subghz/helpers/subghz_txrx.c +++ b/applications/main/subghz/helpers/subghz_txrx.c @@ -8,11 +8,17 @@ static void subghz_txrx_radio_device_power_on(SubGhzTxRx* instance) { UNUSED(instance); - 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); + 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); + } } } diff --git a/firmware/targets/f18/api_symbols.csv b/firmware/targets/f18/api_symbols.csv index 1884fe433..46099799b 100644 --- a/firmware/targets/f18/api_symbols.csv +++ b/firmware/targets/f18/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,32.0,, +Version,+,33.0,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -1030,12 +1030,13 @@ Function,+,furi_hal_mpu_protect_no_access,void,"FuriHalMpuRegion, uint32_t, Furi Function,+,furi_hal_mpu_protect_read_only,void,"FuriHalMpuRegion, uint32_t, FuriHalMPURegionSize" Function,-,furi_hal_os_init,void, Function,+,furi_hal_os_tick,void, +Function,+,furi_hal_power_check_otg_fault,_Bool, Function,+,furi_hal_power_check_otg_status,void, Function,+,furi_hal_power_debug_get,void,"PropertyValueCallback, void*" Function,+,furi_hal_power_disable_external_3_3v,void, Function,+,furi_hal_power_disable_otg,void, Function,+,furi_hal_power_enable_external_3_3v,void, -Function,+,furi_hal_power_enable_otg,void, +Function,+,furi_hal_power_enable_otg,_Bool, Function,+,furi_hal_power_gauge_is_ok,_Bool, Function,+,furi_hal_power_get_bat_health_pct,uint8_t, Function,+,furi_hal_power_get_battery_charge_voltage_limit,float, diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index f4dec15a7..dbaeb8e4c 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,32.0,, +Version,+,33.0,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -1235,12 +1235,13 @@ Function,+,furi_hal_nfc_tx_rx,_Bool,"FuriHalNfcTxRxContext*, uint16_t" Function,+,furi_hal_nfc_tx_rx_full,_Bool,FuriHalNfcTxRxContext* Function,-,furi_hal_os_init,void, Function,+,furi_hal_os_tick,void, +Function,+,furi_hal_power_check_otg_fault,_Bool, Function,+,furi_hal_power_check_otg_status,void, Function,+,furi_hal_power_debug_get,void,"PropertyValueCallback, void*" Function,+,furi_hal_power_disable_external_3_3v,void, Function,+,furi_hal_power_disable_otg,void, Function,+,furi_hal_power_enable_external_3_3v,void, -Function,+,furi_hal_power_enable_otg,void, +Function,+,furi_hal_power_enable_otg,_Bool, Function,+,furi_hal_power_gauge_is_ok,_Bool, Function,+,furi_hal_power_get_bat_health_pct,uint8_t, Function,+,furi_hal_power_get_battery_charge_voltage_limit,float, diff --git a/firmware/targets/f7/furi_hal/furi_hal_power.c b/firmware/targets/f7/furi_hal/furi_hal_power.c index ec405f108..5edde86e9 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_power.c +++ b/firmware/targets/f7/furi_hal/furi_hal_power.c @@ -284,10 +284,15 @@ void furi_hal_power_reset() { NVIC_SystemReset(); } -void furi_hal_power_enable_otg() { +bool furi_hal_power_enable_otg() { furi_hal_i2c_acquire(&furi_hal_i2c_handle_power); + bq25896_set_boost_lim(&furi_hal_i2c_handle_power, BoostLim_2150); bq25896_enable_otg(&furi_hal_i2c_handle_power); + furi_delay_ms(30); + bool ret = bq25896_is_otg_enabled(&furi_hal_i2c_handle_power); + bq25896_set_boost_lim(&furi_hal_i2c_handle_power, BoostLim_1400); furi_hal_i2c_release(&furi_hal_i2c_handle_power); + return ret; } void furi_hal_power_disable_otg() { @@ -317,6 +322,13 @@ void furi_hal_power_set_battery_charge_voltage_limit(float voltage) { furi_hal_i2c_release(&furi_hal_i2c_handle_power); } +bool furi_hal_power_check_otg_fault() { + furi_hal_i2c_acquire(&furi_hal_i2c_handle_power); + bool ret = bq25896_check_otg_fault(&furi_hal_i2c_handle_power); + furi_hal_i2c_release(&furi_hal_i2c_handle_power); + return ret; +} + void furi_hal_power_check_otg_status() { furi_hal_i2c_acquire(&furi_hal_i2c_handle_power); if(bq25896_check_otg_fault(&furi_hal_i2c_handle_power)) diff --git a/firmware/targets/furi_hal_include/furi_hal_power.h b/firmware/targets/furi_hal_include/furi_hal_power.h index 00182fa28..6b4b6cd89 100644 --- a/firmware/targets/furi_hal_include/furi_hal_power.h +++ b/firmware/targets/furi_hal_include/furi_hal_power.h @@ -99,12 +99,16 @@ void furi_hal_power_reset(); /** OTG enable */ -void furi_hal_power_enable_otg(); +bool furi_hal_power_enable_otg(); /** OTG disable */ void furi_hal_power_disable_otg(); +/** Check OTG status fault + */ +bool furi_hal_power_check_otg_fault(); + /** Check OTG status and disable it if falt happened */ void furi_hal_power_check_otg_status(); diff --git a/lib/drivers/bq25896.c b/lib/drivers/bq25896.c index 4c1d687cb..f675233bd 100644 --- a/lib/drivers/bq25896.c +++ b/lib/drivers/bq25896.c @@ -61,7 +61,7 @@ void bq25896_init(FuriHalI2cBusHandle* handle) { // OTG power configuration bq25896_regs.r0A.BOOSTV = 0x8; // BOOST Voltage: 5.062V - bq25896_regs.r0A.BOOST_LIM = BOOST_LIM_1400; // BOOST Current limit: 1.4A + bq25896_regs.r0A.BOOST_LIM = BoostLim_1400; // BOOST Current limit: 1.4A furi_hal_i2c_write_reg_8( handle, BQ25896_ADDRESS, 0x0A, *(uint8_t*)&bq25896_regs.r0A, BQ25896_I2C_TIMEOUT); @@ -74,6 +74,12 @@ void bq25896_init(FuriHalI2cBusHandle* handle) { BQ25896_I2C_TIMEOUT); } +void bq25896_set_boost_lim(FuriHalI2cBusHandle* handle, BoostLim boost_lim) { + bq25896_regs.r0A.BOOST_LIM = boost_lim; + furi_hal_i2c_write_reg_8( + handle, BQ25896_ADDRESS, 0x0A, *(uint8_t*)&bq25896_regs.r0A, BQ25896_I2C_TIMEOUT); +} + void bq25896_poweroff(FuriHalI2cBusHandle* handle) { bq25896_regs.r09.BATFET_DIS = 1; furi_hal_i2c_write_reg_8( diff --git a/lib/drivers/bq25896.h b/lib/drivers/bq25896.h index f3d1d0e05..ce7293960 100644 --- a/lib/drivers/bq25896.h +++ b/lib/drivers/bq25896.h @@ -9,6 +9,9 @@ /** Initialize Driver */ void bq25896_init(FuriHalI2cBusHandle* handle); +/** Set boost lim*/ +void bq25896_set_boost_lim(FuriHalI2cBusHandle* handle, BoostLim boost_lim); + /** Send device into shipping mode */ void bq25896_poweroff(FuriHalI2cBusHandle* handle); diff --git a/lib/drivers/bq25896_reg.h b/lib/drivers/bq25896_reg.h index 3cb3d7140..a6ca3e1c7 100644 --- a/lib/drivers/bq25896_reg.h +++ b/lib/drivers/bq25896_reg.h @@ -159,14 +159,16 @@ typedef struct { #define BOOSTV_128 (1 << 1) #define BOOSTV_64 (1 << 0) -#define BOOST_LIM_500 (0b000) -#define BOOST_LIM_750 (0b001) -#define BOOST_LIM_1200 (0b010) -#define BOOST_LIM_1400 (0b011) -#define BOOST_LIM_1650 (0b100) -#define BOOST_LIM_1875 (0b101) -#define BOOST_LIM_2150 (0b110) -#define BOOST_LIM_RSVD (0b111) +typedef enum { + BoostLim_500 = 0b000, + BoostLim_750 = 0b001, + BoostLim_1200 = 0b010, + BoostLim_1400 = 0b011, + BoostLim_1650 = 0b100, + BoostLim_1875 = 0b101, + BoostLim_2150 = 0b110, + BoostLim_Rsvd = 0b111, +} BoostLim; typedef struct { uint8_t BOOST_LIM : 3; // Boost Mode Current Limit From e6b0494d4d225658cef09d3e6e86a9778ad876d5 Mon Sep 17 00:00:00 2001 From: gornekich Date: Wed, 5 Jul 2023 20:55:04 +0400 Subject: [PATCH 19/40] [FL-3407] NFC: Mf Ultralight emulation optimization (#2847) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: あく --- lib/nfc/nfc_worker.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/nfc/nfc_worker.c b/lib/nfc/nfc_worker.c index a39531c8c..d2834fa46 100644 --- a/lib/nfc/nfc_worker.c +++ b/lib/nfc/nfc_worker.c @@ -724,6 +724,8 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker) { emulator.auth_received_callback = nfc_worker_mf_ultralight_auth_received_callback; emulator.context = nfc_worker; + rfal_platform_spi_acquire(); + while(nfc_worker->state == NfcWorkerStateMfUltralightEmulate) { mf_ul_reset_emulation(&emulator, true); furi_hal_nfc_emulate_nfca( @@ -743,6 +745,8 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker) { emulator.data_changed = false; } } + + rfal_platform_spi_release(); } static bool nfc_worker_mf_get_b_key_from_sector_trailer( From 93acba9ae3ef4190f8ca3ec7057f7f5c2d6ebacd Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 20:07:43 +0300 Subject: [PATCH 20/40] i2c tools update --- .../external/flipper_i2ctools/LICENSE | 674 ++++++++++++++++++ .../external/flipper_i2ctools/application.fam | 4 +- .../external/flipper_i2ctools/i2ctools.c | 4 + .../external/flipper_i2ctools/i2ctools_i.h | 1 + .../flipper_i2ctools/images/Voltage_16x16.png | Bin 0 -> 294 bytes .../flipper_i2ctools/views/infos_view.c | 15 + .../flipper_i2ctools/views/infos_view.h | 8 + .../flipper_i2ctools/views/main_view.c | 20 + .../flipper_i2ctools/views/main_view.h | 13 +- .../flipper_i2ctools/views/scanner_view.h | 2 +- .../flipper_i2ctools/views/sender_view.h | 2 +- .../flipper_i2ctools/views/sniffer_view.h | 2 +- 12 files changed, 736 insertions(+), 9 deletions(-) create mode 100644 applications/external/flipper_i2ctools/LICENSE create mode 100644 applications/external/flipper_i2ctools/images/Voltage_16x16.png create mode 100644 applications/external/flipper_i2ctools/views/infos_view.c create mode 100644 applications/external/flipper_i2ctools/views/infos_view.h diff --git a/applications/external/flipper_i2ctools/LICENSE b/applications/external/flipper_i2ctools/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/applications/external/flipper_i2ctools/LICENSE @@ -0,0 +1,674 @@ + 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/flipper_i2ctools/application.fam b/applications/external/flipper_i2ctools/application.fam index f91bcceba..c576c71b0 100644 --- a/applications/external/flipper_i2ctools/application.fam +++ b/applications/external/flipper_i2ctools/application.fam @@ -1,5 +1,5 @@ App( - appid="i2c_tools", + appid="i2ctools", name="[GPIO] i2c Tools", apptype=FlipperAppType.EXTERNAL, entry_point="i2ctools_app", @@ -10,6 +10,6 @@ App( fap_category="GPIO", fap_icon_assets="images", fap_author="@NaejEL", - fap_version="1.0", + fap_version="1.1", fap_description="Set of i2c tools", ) \ No newline at end of file diff --git a/applications/external/flipper_i2ctools/i2ctools.c b/applications/external/flipper_i2ctools/i2ctools.c index 6d4cc739f..7be6e5961 100644 --- a/applications/external/flipper_i2ctools/i2ctools.c +++ b/applications/external/flipper_i2ctools/i2ctools.c @@ -22,6 +22,10 @@ void i2ctools_draw_callback(Canvas* canvas, void* ctx) { draw_sender_view(canvas, i2ctools->sender); break; + case INFOS_VIEW: + draw_infos_view(canvas); + break; + default: break; } diff --git a/applications/external/flipper_i2ctools/i2ctools_i.h b/applications/external/flipper_i2ctools/i2ctools_i.h index f31e42478..2e32d3fd4 100644 --- a/applications/external/flipper_i2ctools/i2ctools_i.h +++ b/applications/external/flipper_i2ctools/i2ctools_i.h @@ -10,6 +10,7 @@ #include "views/sniffer_view.h" #include "views/scanner_view.h" #include "views/sender_view.h" +#include "views/infos_view.h" // App datas typedef struct { diff --git a/applications/external/flipper_i2ctools/images/Voltage_16x16.png b/applications/external/flipper_i2ctools/images/Voltage_16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..94e79687295fe8af81fa8984083c9ed9c40627ae GIT binary patch literal 294 zcmeAS@N?(olHy`uVBq!ia0vp^0wBx?BpA#)4xIr~Ea{HEjtmSN`?>!lvI6-E$sR$z z3=CCj3=9n|3=F@3LJcn%7)lKo7+xhXFj&oCU=S~uvn$XBD8ZEE?e4Vure^!HUN?acl*3zP&DM`r(~v8;?}U{@}~zt4Gf;HelF{r5}E)Ni&owM literal 0 HcmV?d00001 diff --git a/applications/external/flipper_i2ctools/views/infos_view.c b/applications/external/flipper_i2ctools/views/infos_view.c new file mode 100644 index 000000000..108bdeb46 --- /dev/null +++ b/applications/external/flipper_i2ctools/views/infos_view.c @@ -0,0 +1,15 @@ +#include "infos_view.h" + +void draw_infos_view(Canvas* canvas) { + canvas_clear(canvas); + canvas_set_color(canvas, ColorBlack); + canvas_draw_rframe(canvas, 0, 0, 128, 64, 3); + canvas_set_font(canvas, FontSecondary); + + canvas_draw_str_aligned(canvas, 3, 3, AlignLeft, AlignTop, "Wiring: "); + canvas_draw_str_aligned(canvas, 43, 3, AlignLeft, AlignTop, "C0->SCL"); + canvas_draw_str_aligned(canvas, 43, 13, AlignLeft, AlignTop, "C1->SDA"); + canvas_draw_str_aligned(canvas, 43, 23, AlignLeft, AlignTop, "GND->GND"); + canvas_draw_icon(canvas, 15, 33, &I_Voltage_16x16); + canvas_draw_str_aligned(canvas, 30, 38, AlignLeft, AlignTop, "Only use 3v3 levels"); +} \ No newline at end of file diff --git a/applications/external/flipper_i2ctools/views/infos_view.h b/applications/external/flipper_i2ctools/views/infos_view.h new file mode 100644 index 000000000..11b388c02 --- /dev/null +++ b/applications/external/flipper_i2ctools/views/infos_view.h @@ -0,0 +1,8 @@ +#include +#include +#include +#include + +#define INFOS_TEXT "INFOS" + +void draw_infos_view(Canvas* canvas); \ No newline at end of file diff --git a/applications/external/flipper_i2ctools/views/main_view.c b/applications/external/flipper_i2ctools/views/main_view.c index abcb26224..909a3904b 100644 --- a/applications/external/flipper_i2ctools/views/main_view.c +++ b/applications/external/flipper_i2ctools/views/main_view.c @@ -14,6 +14,8 @@ void draw_main_view(Canvas* canvas, i2cMainView* main_view) { canvas, SNIFF_MENU_X, SNIFF_MENU_Y, AlignLeft, AlignTop, SNIFF_MENU_TEXT); canvas_draw_str_aligned( canvas, SEND_MENU_X, SEND_MENU_Y, AlignLeft, AlignTop, SEND_MENU_TEXT); + canvas_draw_str_aligned( + canvas, INFOS_MENU_X, INFOS_MENU_Y, AlignLeft, AlignTop, INFOS_MENU_TEXT); canvas_draw_rbox(canvas, 80, SCAN_MENU_Y - 2, 43, 13, 3); canvas_set_color(canvas, ColorWhite); canvas_draw_str_aligned( @@ -26,6 +28,8 @@ void draw_main_view(Canvas* canvas, i2cMainView* main_view) { canvas, SCAN_MENU_X, SCAN_MENU_Y, AlignLeft, AlignTop, SCAN_MENU_TEXT); canvas_draw_str_aligned( canvas, SEND_MENU_X, SEND_MENU_Y, AlignLeft, AlignTop, SEND_MENU_TEXT); + canvas_draw_str_aligned( + canvas, INFOS_MENU_X, INFOS_MENU_Y, AlignLeft, AlignTop, INFOS_MENU_TEXT); canvas_draw_rbox(canvas, 80, SNIFF_MENU_Y - 2, 43, 13, 3); canvas_set_color(canvas, ColorWhite); canvas_draw_str_aligned( @@ -38,12 +42,28 @@ void draw_main_view(Canvas* canvas, i2cMainView* main_view) { canvas, SCAN_MENU_X, SCAN_MENU_Y, AlignLeft, AlignTop, SCAN_MENU_TEXT); canvas_draw_str_aligned( canvas, SNIFF_MENU_X, SNIFF_MENU_Y, AlignLeft, AlignTop, SNIFF_MENU_TEXT); + canvas_draw_str_aligned( + canvas, INFOS_MENU_X, INFOS_MENU_Y, AlignLeft, AlignTop, INFOS_MENU_TEXT); canvas_draw_rbox(canvas, 80, SEND_MENU_Y - 2, 43, 13, 3); canvas_set_color(canvas, ColorWhite); canvas_draw_str_aligned( canvas, SEND_MENU_X, SEND_MENU_Y, AlignLeft, AlignTop, SEND_MENU_TEXT); break; + case INFOS_VIEW: + canvas_set_color(canvas, ColorBlack); + canvas_draw_str_aligned( + canvas, SCAN_MENU_X, SCAN_MENU_Y, AlignLeft, AlignTop, SCAN_MENU_TEXT); + canvas_draw_str_aligned( + canvas, SNIFF_MENU_X, SNIFF_MENU_Y, AlignLeft, AlignTop, SNIFF_MENU_TEXT); + canvas_draw_str_aligned( + canvas, SEND_MENU_X, SEND_MENU_Y, AlignLeft, AlignTop, SEND_MENU_TEXT); + canvas_draw_rbox(canvas, 80, INFOS_MENU_Y - 2, 43, 13, 3); + canvas_set_color(canvas, ColorWhite); + canvas_draw_str_aligned( + canvas, INFOS_MENU_X, INFOS_MENU_Y, AlignLeft, AlignTop, INFOS_MENU_TEXT); + break; + default: break; } diff --git a/applications/external/flipper_i2ctools/views/main_view.h b/applications/external/flipper_i2ctools/views/main_view.h index f0ce5e8ad..118a8f5f9 100644 --- a/applications/external/flipper_i2ctools/views/main_view.h +++ b/applications/external/flipper_i2ctools/views/main_view.h @@ -1,20 +1,24 @@ #include #include #include -#include +#include #define APP_NAME "I2C Tools" #define SCAN_MENU_TEXT "Scan" #define SCAN_MENU_X 90 -#define SCAN_MENU_Y 13 +#define SCAN_MENU_Y 7 #define SNIFF_MENU_TEXT "Sniff" #define SNIFF_MENU_X 90 -#define SNIFF_MENU_Y 27 +#define SNIFF_MENU_Y 21 #define SEND_MENU_TEXT "Send" #define SEND_MENU_X 90 -#define SEND_MENU_Y 41 +#define SEND_MENU_Y 35 + +#define INFOS_MENU_TEXT "Infos" +#define INFOS_MENU_X 90 +#define INFOS_MENU_Y 49 // Menu typedef enum { @@ -22,6 +26,7 @@ typedef enum { SCAN_VIEW, SNIFF_VIEW, SEND_VIEW, + INFOS_VIEW, /* Know menu Size*/ MENU_SIZE diff --git a/applications/external/flipper_i2ctools/views/scanner_view.h b/applications/external/flipper_i2ctools/views/scanner_view.h index 52f30a7bf..4c59f8836 100644 --- a/applications/external/flipper_i2ctools/views/scanner_view.h +++ b/applications/external/flipper_i2ctools/views/scanner_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2cscanner.h" #define SCAN_TEXT "SCAN" diff --git a/applications/external/flipper_i2ctools/views/sender_view.h b/applications/external/flipper_i2ctools/views/sender_view.h index c4fdd98a2..c5192d0b6 100644 --- a/applications/external/flipper_i2ctools/views/sender_view.h +++ b/applications/external/flipper_i2ctools/views/sender_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2csender.h" #define SEND_TEXT "SEND" diff --git a/applications/external/flipper_i2ctools/views/sniffer_view.h b/applications/external/flipper_i2ctools/views/sniffer_view.h index 8f2140bba..db4dbd1ff 100644 --- a/applications/external/flipper_i2ctools/views/sniffer_view.h +++ b/applications/external/flipper_i2ctools/views/sniffer_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2csniffer.h" #define SNIFF_TEXT "SNIFF" From a9d4897dfbaf5003c2cc550b7d0a519a0e28d0eb Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 20:26:47 +0300 Subject: [PATCH 21/40] Update wifi marauder --- .../external/wifi_marauder_companion/LICENSE | 674 ++++++++++++++++++ .../wifi_marauder_companion/ReadMe.md | 35 +- .../wifi_marauder_companion/application.fam | 17 + .../wifi_marauder_companion/docs/README.md | 9 + .../wifi_marauder_companion/docs/changelog.md | 5 + .../lib/esp-serial-flasher/LICENSE | 202 ++++++ .../lib/esp-serial-flasher/README.md | 154 ++++ .../esp-serial-flasher/include/esp_loader.h | 313 ++++++++ .../include/esp_loader_io.h | 112 +++ .../esp-serial-flasher/include/serial_io.h | 24 + .../lib/esp-serial-flasher/port/esp32_port.c | 181 +++++ .../lib/esp-serial-flasher/port/esp32_port.h | 59 ++ .../esp-serial-flasher/port/esp32_spi_port.c | 298 ++++++++ .../esp-serial-flasher/port/esp32_spi_port.h | 60 ++ .../esp-serial-flasher/port/raspberry_port.c | 302 ++++++++ .../esp-serial-flasher/port/raspberry_port.h | 36 + .../lib/esp-serial-flasher/port/stm32_port.c | 140 ++++ .../lib/esp-serial-flasher/port/stm32_port.h | 38 + .../lib/esp-serial-flasher/port/zephyr_port.c | 170 +++++ .../lib/esp-serial-flasher/port/zephyr_port.h | 39 + .../private_include/esp_targets.h | 33 + .../private_include/md5_hash.h | 28 + .../private_include/protocol.h | 230 ++++++ .../private_include/protocol_prv.h | 31 + .../esp-serial-flasher/private_include/slip.h | 28 + .../lib/esp-serial-flasher/src/esp_loader.c | 415 +++++++++++ .../lib/esp-serial-flasher/src/esp_targets.c | 263 +++++++ .../lib/esp-serial-flasher/src/md5_hash.c | 262 +++++++ .../esp-serial-flasher/src/protocol_common.c | 301 ++++++++ .../lib/esp-serial-flasher/src/protocol_spi.c | 312 ++++++++ .../esp-serial-flasher/src/protocol_uart.c | 114 +++ .../lib/esp-serial-flasher/src/slip.c | 125 ++++ .../esp-serial-flasher/zephyr/CMakeLists.txt | 30 + .../lib/esp-serial-flasher/zephyr/Kconfig | 16 + .../lib/esp-serial-flasher/zephyr/module.yml | 5 + .../scenes/wifi_marauder_scene_config.h | 1 + .../wifi_marauder_scene_console_output.c | 23 +- .../scenes/wifi_marauder_scene_flasher.c | 92 +++ .../scenes/wifi_marauder_scene_start.c | 16 + .../scenes/wifi_marauder_scene_text_input.c | 4 +- .../wifi_marauder_app.c | 2 + .../wifi_marauder_app.h | 2 +- .../wifi_marauder_app_i.h | 9 +- .../wifi_marauder_custom_event.h | 3 +- .../wifi_marauder_flasher.c | 200 ++++++ .../wifi_marauder_flasher.h | 10 + .../wifi_marauder_uart.c | 2 +- 47 files changed, 5416 insertions(+), 9 deletions(-) create mode 100644 applications/external/wifi_marauder_companion/LICENSE create mode 100644 applications/external/wifi_marauder_companion/docs/README.md create mode 100644 applications/external/wifi_marauder_companion/docs/changelog.md create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig create mode 100644 applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml create mode 100644 applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c create mode 100644 applications/external/wifi_marauder_companion/wifi_marauder_flasher.c create mode 100644 applications/external/wifi_marauder_companion/wifi_marauder_flasher.h diff --git a/applications/external/wifi_marauder_companion/LICENSE b/applications/external/wifi_marauder_companion/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/applications/external/wifi_marauder_companion/LICENSE @@ -0,0 +1,674 @@ + 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/wifi_marauder_companion/ReadMe.md b/applications/external/wifi_marauder_companion/ReadMe.md index fd690ece6..bc14e0f8c 100644 --- a/applications/external/wifi_marauder_companion/ReadMe.md +++ b/applications/external/wifi_marauder_companion/ReadMe.md @@ -1,8 +1,41 @@ # WiFi Marauder companion app for Flipper Zero +Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information) + ## https://github.com/0xchocolate/flipperzero-wifi-marauder -Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information) +## Get the app +1. Make sure you're logged in with a github account (otherwise the downloads in step 2 won't work) +2. Navigate to the [FAP Build](https://github.com/0xchocolate/flipperzero-wifi-marauder/actions/workflows/build.yml) + GitHub action workflow, and select the most recent run, scroll down to artifacts. +3. The FAP is built for the `dev` and `release` channels of both official and unleashed + firmware. Download the artifact corresponding to your firmware version. +4. (Optional step to avoid confusion) Go to "Apps/GPIO" on the Flipper SD Card, delete any existing Marauder app, on some firmwares there will be a `ESP32CAM_Marauder.fap` or similar. +5. Extract `esp32_wifi_marauder.fap` from the ZIP file downloaded in step 3 to your Flipper Zero SD card, preferably under Apps/GPIO along with the rest of the GPIO apps. (If you're using qFlipper to transfer files you need to extract the content of the ZIP file to your computer before you drag it to qFlipper, as qFlipper does not support direct dragging from a ZIP file (at least on Windows)). + +From a local clone of this repo, you can also build the app yourself using ufbt. + +## In-app ESP32 flasher (WIP) +Guide by [@francis2054](https://github.com/francis2054) + +The app now contains a work-in-progress of an ESP32 flasher (close to the bottom of the marauder menu). Use at your own risk. This hardcodes addresses for non-S3 ESP32 chips. + +To use this method: +1. Make sure you follow the instructions for how to get the Marauder app on your Flipper Zero, they can be found on the top of this page. Latest release needs to be downloaded and installed. +2. Go to [Justcallmekoko's firmware page](https://github.com/justcallmekoko/ESP32Marauder/wiki/update-firmware#using-spacehuhn-web-updater) and download all files necessary for the board you are flashing, most boards will want all 4 files but for the Wifi Devboard you want to download these 3 files: `0x1000` (Bootloader), `0x8000` (partitions), `0x10000` (Firmware). The `Boot App` is not needed for the Wifi Devboard with this method. The Firmware one will redirect you to the releases page where you'll need to pick the one relevant to the board you're flashing, if you are using the official Wi-Fi Devboard you want to pick the one ending in `_flipper_sd_serial.bin`. +3. Place all files downloaded in step 2 in a new folder on your desktop, the name does not matter. Rename the `_flipper_sd_serial.bin` file you downloaded in step 2 to `Firmware.bin`. +4. Now for transferring the files to the Flipper Zero, drag all the files from the folder on your desktop to the "Marauder" folder inside "apps_data" folder on the Flipper Zero SD card. Preferred method to transfer these files is plugging the SD card into your computer with an adapter, but qFlipper works as well. Insert the Flipper Zero SD Card back into the Flipper before proceeding to the next step. +5. Plug your Wi-Fi Devboard into the Flipper. +6. Press and keep holding the boot button while you press the reset button once, release the boot button after 2 seconds. +7. Open the Marauder app on your Flipper Zero, it should be named "esp32_wifi_marauder" and be located under Apps->GPIO from the main menu if you followed the instructions for how to install the app further up on this page. (You might get an API mismatch error if the Flipper firmware you are running doesn't match the files you've downloaded, you can try "Continue" anyway, otherwise the app needs to be rebuilt or you might need to update the firmware on your Flipper). +8. Press the up arrow on the Flipper three times to get to "Reflash ESP32 (WIP)" and open it. +9. For "Bootloader" scroll down in the list and select `esp32_marauder.ino.bootloader.bin`, for "Paritition table" select `esp32_marauder.ino.partitions.bin` and for "Firmware" select `Firmware.bin`. +10. Scroll down and click "[>] FLASH" and wait for it to complete. (If you get errors here, press back button once and repeat step 6 then try "[>] FLASH" again). +11. Once it says "Done flashing" on the screen, restart the Flipper and you are done :) + +## For future updates, just repeat from step 2 and only download the new "Firmware" bin + +This process will improve with future updates! :) ## Support diff --git a/applications/external/wifi_marauder_companion/application.fam b/applications/external/wifi_marauder_companion/application.fam index 59e53b725..6b3403f39 100644 --- a/applications/external/wifi_marauder_companion/application.fam +++ b/applications/external/wifi_marauder_companion/application.fam @@ -8,5 +8,22 @@ App( order=90, fap_icon="wifi_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/wifi_marauder_companion/docs/README.md b/applications/external/wifi_marauder_companion/docs/README.md new file mode 100644 index 000000000..40b7a5ad0 --- /dev/null +++ b/applications/external/wifi_marauder_companion/docs/README.md @@ -0,0 +1,9 @@ +## WiFi Marauder companion app for Flipper Zero + +Requires a connected dev board running Marauder FW. See install instructions from UberGuidoZ here: https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information + +## Support + +For app feedback, bugs, and feature requests, please create an issue here: https://github.com/0xchocolate/flipperzero-wifi-marauder/issues + +You can find me (0xchocolate) on discord as @cococode. diff --git a/applications/external/wifi_marauder_companion/docs/changelog.md b/applications/external/wifi_marauder_companion/docs/changelog.md new file mode 100644 index 000000000..ae0f328e7 --- /dev/null +++ b/applications/external/wifi_marauder_companion/docs/changelog.md @@ -0,0 +1,5 @@ +## v0.4.0 + +Added Signal Monitor (thanks @justcallmekoko!) to support new sigmon command in Marauder v0.10.5: https://github.com/justcallmekoko/ESP32Marauder/releases + +Added keyboard and +5V support from unleashed (thanks @xMasterX!) diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE @@ -0,0 +1,202 @@ + + 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/wifi_marauder_companion/lib/esp-serial-flasher/README.md b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md new file mode 100644 index 000000000..b1ae448d7 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md @@ -0,0 +1,154 @@ +# esp-serial-flasher + +`esp-serial-flasher` is a portable C library for flashing or loading apps to RAM of Espressif SoCs from other host microcontrollers. + +## Using the library +Espressif SoCs are normally programmed via serial interface (UART). The port layer for the given host microcontroller has to be implemented if not available. Details can be found in section below. + +Supported **host** microcontrollers: + +- STM32 +- Raspberry Pi SBC +- ESP32 +- Any MCU running Zephyr OS + +Supported **target** microcontrollers: + +- ESP32 +- ESP8266 +- ESP32-S2 +- ESP32-S3 +- ESP32-C3 +- ESP32-C2 +- ESP32-H2 + +Supported hardware interfaces: +- UART +- SPI (only for RAM download, experimental) + +For example usage check the `examples` directory. + +## Supporting a new host target + +In order to support a new target, following functions have to be implemented by user: + +- `loader_port_read()` +- `loader_port_write()` +- `loader_port_enter_bootloader()` +- `loader_port_delay_ms()` +- `loader_port_start_timer()` +- `loader_port_remaining_time()` + +For the SPI interface ports +- `loader_port_spi_set_cs()` +needs to be implemented as well. + +The following functions are part of the [io.h](include/io.h) header for convenience, however, the user does not have to strictly follow function signatures, as there are not called directly from library. + +- `loader_port_change_transmission_rate()` +- `loader_port_reset_target()` +- `loader_port_debug_print()` + +Prototypes of all functions mentioned above can be found in [io.h](include/io.h). + +## Configuration + +These are the configuration toggles available to the user: + +* `SERIAL_FLASHER_INTERFACE_UART/SERIAL_FLASHER_INTERFACE_SPI` + +This defines the hardware interface to use. SPI interface only supports RAM download mode and is in experimental stage and can undergo changes. + +Default: SERIAL_FLASHER_INTERFACE_UART + +* `MD5_ENABLED` + +If enabled, `esp-serial-flasher` is capable of verifying flash integrity after writing to flash. + +Default: Enabled +> Warning: As ROM bootloader of the ESP8266 does not support MD5_CHECK, this option has to be disabled! + +* `SERIAL_FLASHER_RESET_HOLD_TIME_MS` + +This is the time for which the reset pin is asserted when doing a hard reset in milliseconds. + +Default: 100 + +* `SERIAL_FLASHER_BOOT_HOLD_TIME_MS` + +This is the time for which the boot pin is asserted when doing a hard reset in milliseconds. + +Default: 50 + +Configuration can be passed to `cmake` via command line: + +``` +cmake -DMD5_ENABLED=1 .. && cmake --build . +``` + +### STM32 support + +The STM32 port makes use of STM32 HAL libraries, and these do not come with CMake support. In order to compile the project, `stm32-cmake` (a `CMake` support package) has to be pulled as submodule. + +``` +git clone --recursive https://github.com/espressif/esp-serial-flasher.git +``` + +If you have cloned this repository without the `--recursive` flag, you can initialize the submodule using the following command: + +``` +git submodule update --init +``` + +In addition to configuration parameters mentioned above, following definitions has to be set: + +- TOOLCHAIN_PREFIX: path to arm toolchain (i.e /home/user/gcc-arm-none-eabi-9-2019-q4-major) +- STM32Cube_DIR: path to STM32 Cube libraries (i.e /home/user/STM32Cube/Repository/STM32Cube_FW_F4_V1.25.0) +- STM32_CHIP: name of STM32 for which project should be compiled (i.e STM32F407VG) +- PORT: STM32 + +This can be achieved by passing definitions to the command line, such as: + +``` +cmake -DTOOLCHAIN_PREFIX="/path_to_toolchain" -DSTM32Cube_DIR="path_to_stm32Cube" -DSTM32_CHIP="STM32F407VG" -DPORT="STM32" .. && cmake --build . +``` + +Alternatively, those variables can be set in the top level `cmake` directory: + +``` +set(TOOLCHAIN_PREFIX path_to_toolchain) +set(STM32Cube_DIR path_to_stm32_HAL) +set(STM32_CHIP STM32F407VG) +set(PORT STM32) +``` + +### Zephyr support + +The Zephyr port is ready to be integrated into Zephyr apps as a Zephyr module. In the manifest file (west.yml), add: + +``` + - name: esp-flasher + url: https://github.com/espressif/esp-serial-flasher + revision: master + path: modules/lib/esp_flasher +``` + +And add + +``` +CONFIG_ESP_SERIAL_FLASHER=y +CONFIG_CONSOLE_GETCHAR=y +CONFIG_SERIAL_FLASHER_MD5_ENABLED=y +``` + +to the project configuration `prj.conf`. + +For the C/C++ source code, the example code provided in `examples/zephyr_example` can be used as a starting point. + +## Licence + +Code is distributed under Apache 2.0 license. + +## Known limitations + +Size of new binary image has to be known before flashing. diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h new file mode 100644 index 000000000..43f4fb9d9 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h @@ -0,0 +1,313 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h new file mode 100644 index 000000000..2ff99b4f9 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h @@ -0,0 +1,112 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h new file mode 100644 index 000000000..e34939300 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h @@ -0,0 +1,24 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c new file mode 100644 index 000000000..a6c8687c6 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c @@ -0,0 +1,181 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h new file mode 100644 index 000000000..c098762d2 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h @@ -0,0 +1,59 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c new file mode 100644 index 000000000..55e8f3e57 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c @@ -0,0 +1,298 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h new file mode 100644 index 000000000..72304c5df --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h @@ -0,0 +1,60 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c new file mode 100644 index 000000000..d733db702 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c @@ -0,0 +1,302 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h new file mode 100644 index 000000000..803ab72dd --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h @@ -0,0 +1,36 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c new file mode 100644 index 000000000..716c9c91b --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c @@ -0,0 +1,140 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h new file mode 100644 index 000000000..a3a89a733 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h @@ -0,0 +1,38 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c new file mode 100644 index 000000000..21270ba0a --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c @@ -0,0 +1,170 @@ +/* + * 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/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h new file mode 100644 index 000000000..0b104e375 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h @@ -0,0 +1,39 @@ +/* + * 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/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h new file mode 100644 index 000000000..cf8af91fa --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h @@ -0,0 +1,33 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h new file mode 100644 index 000000000..eb5738c8b --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h @@ -0,0 +1,28 @@ +/* + * 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/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h new file mode 100644 index 000000000..fb8b086fd --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h @@ -0,0 +1,230 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h new file mode 100644 index 000000000..3b9575606 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h @@ -0,0 +1,31 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h new file mode 100644 index 000000000..00f1f7d0d --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h @@ -0,0 +1,28 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c new file mode 100644 index 000000000..6ef32673c --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c @@ -0,0 +1,415 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c new file mode 100644 index 000000000..8764d2369 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c @@ -0,0 +1,263 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c new file mode 100644 index 000000000..4da76bcb5 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c @@ -0,0 +1,262 @@ +/* + * 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/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c new file mode 100644 index 000000000..8d1d9dd53 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c @@ -0,0 +1,301 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c new file mode 100644 index 000000000..bd04fe79f --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c @@ -0,0 +1,312 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c new file mode 100644 index 000000000..c5a51cec6 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c @@ -0,0 +1,114 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c new file mode 100644 index 000000000..ba926169c --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c @@ -0,0 +1,125 @@ +/* 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/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt new file mode 100644 index 000000000..97da4eaae --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt @@ -0,0 +1,30 @@ +cmake_minimum_required(VERSION 3.5) + +if (CONFIG_ESP_SERIAL_FLASHER) + zephyr_include_directories( + "${ZEPHYR_CURRENT_MODULE_DIR}/include" + "${ZEPHYR_CURRENT_MODULE_DIR}/port" + "${ZEPHYR_CURRENT_MODULE_DIR}/private_include" + ) + + zephyr_interface_library_named(esp_flasher) + + zephyr_library() + + zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_loader.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_targets.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_common.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_uart.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/slip.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/md5_hash.c + ${ZEPHYR_CURRENT_MODULE_DIR}/port/zephyr_port.c + ) + + target_compile_definitions(esp_flasher INTERFACE SERIAL_FLASHER_INTERFACE_UART) + + zephyr_library_link_libraries(esp_flasher) + + if(DEFINED MD5_ENABLED OR CONFIG_SERIAL_FLASHER_MD5_ENABLED) + target_compile_definitions(esp_flasher INTERFACE -DMD5_ENABLED=1) + endif() +endif() diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig new file mode 100644 index 000000000..ebb524c86 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig @@ -0,0 +1,16 @@ +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/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml new file mode 100644 index 000000000..01d484fcb --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml @@ -0,0 +1,5 @@ +name: esp-flasher + +build: + cmake: zephyr + kconfig: zephyr/Kconfig diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h index d223af79a..402fca479 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h @@ -13,3 +13,4 @@ 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) +ADD_SCENE(wifi_marauder, flasher, Flasher) diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c index 05d94fe80..236fe4eff 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c @@ -1,5 +1,7 @@ #include "../wifi_marauder_app_i.h" +#include "../wifi_marauder_flasher.h" + char* _wifi_marauder_get_prefix_from_cmd(const char* command) { int end = strcspn(command, " "); char* prefix = (char*)malloc(sizeof(char) * (end + 1)); @@ -101,13 +103,24 @@ void wifi_marauder_scene_console_output_on_enter(void* context) { 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 + // setup callback for general log rx thread + if(app->flash_mode) { + wifi_marauder_uart_set_handle_rx_data_cb( + app->uart, + wifi_marauder_flash_handle_rx_data_cb); // setup callback for general log rx thread + } else { + 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 + if(app->flash_mode) { + wifi_marauder_flash_start_thread(app); + } + // Get ready to send command if((app->is_command && app->selected_tx_string) || app->script) { const char* prefix = @@ -183,6 +196,10 @@ void wifi_marauder_scene_console_output_on_exit(void* context) { furi_delay_ms(50); } + if(app->flash_mode) { + wifi_marauder_flash_stop_thread(app); + } + // 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); diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c new file mode 100644 index 000000000..79682879d --- /dev/null +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c @@ -0,0 +1,92 @@ +#include "../wifi_marauder_app_i.h" + +enum SubmenuIndex { + SubmenuIndexBoot, + SubmenuIndexPart, + SubmenuIndexApp, + SubmenuIndexFlash, +}; + +static void wifi_marauder_scene_flasher_callback(void* context, uint32_t index) { + WifiMarauderApp* app = context; + + scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneFlasher, index); + + // browse for files + FuriString* predefined_filepath = furi_string_alloc_set_str(MARAUDER_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 SubmenuIndexBoot: + 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)); + } + break; + case SubmenuIndexPart: + 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)); + } + break; + case SubmenuIndexApp: + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_app, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_app)); + } + break; + case SubmenuIndexFlash: + // TODO error checking + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); + break; + } + + furi_string_free(selected_filepath); + furi_string_free(predefined_filepath); +} + +void wifi_marauder_scene_flasher_on_enter(void* context) { + WifiMarauderApp* app = context; + + Submenu* submenu = app->submenu; + + submenu_set_header(submenu, "Browse for files to flash"); + submenu_add_item( + submenu, "Bootloader", SubmenuIndexBoot, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "Partition Table", SubmenuIndexPart, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "Application", SubmenuIndexApp, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "[>] FLASH", SubmenuIndexFlash, wifi_marauder_scene_flasher_callback, app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneFlasher)); + view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); +} + +bool wifi_marauder_scene_flasher_on_event(void* context, SceneManagerEvent event) { + //WifiMarauderApp* app = context; + UNUSED(context); + UNUSED(event); + bool consumed = false; + + return consumed; +} + +void wifi_marauder_scene_flasher_on_exit(void* context) { + WifiMarauderApp* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c index b2bd39d3e..06dcd7fd7 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c @@ -121,6 +121,7 @@ const WifiMarauderItem items[NUM_MENU_ITEMS] = { {"Update", {"ota", "sd"}, 2, {"update -w", "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}, + {"Reflash ESP32 (WIP)", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Scripts", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Save to flipper sdcard", // keep as last entry or change logic in callback below {""}, @@ -149,6 +150,17 @@ static void wifi_marauder_scene_start_var_list_enter_callback(void* context, uin item->focus_console; app->show_stopscan_tip = item->show_stopscan_tip; + // TODO cleanup + if(index == NUM_MENU_ITEMS - 3) { + // flasher + app->is_command = false; + app->flash_mode = true; + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartFlasher); + return; + } + + app->flash_mode = false; + if(!app->is_command && selected_option_index == 0) { // View Log from start view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartLogViewer); @@ -260,6 +272,10 @@ bool wifi_marauder_scene_start_on_event(void* context, SceneManagerEvent event) scene_manager_set_scene_state( app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSniffPmkidOptions); + } else if(event.event == WifiMarauderEventStartFlasher) { + scene_manager_set_scene_state( + app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneFlasher); } consumed = true; } else if(event.type == SceneManagerEventTypeTick) { diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c index e6091a410..66a508f66 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c @@ -46,7 +46,9 @@ void wifi_marauder_scene_text_input_on_enter(void* context) { // Setup view WIFI_TextInput* text_input = app->text_input; // Add help message to header - if(app->special_case_input_step == 1) { + if(app->flash_mode) { + wifi_text_input_set_header_text(text_input, "Enter destination address"); + } else if(app->special_case_input_step == 1) { wifi_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"))) { wifi_text_input_set_header_text(text_input, "Enter # SSIDs to generate"); diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app.c b/applications/external/wifi_marauder_companion/wifi_marauder_app.c index 97b1d9715..91fcb2372 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app.c +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app.c @@ -86,6 +86,8 @@ WifiMarauderApp* wifi_marauder_app_alloc() { view_dispatcher_add_view( app->view_dispatcher, WifiMarauderAppViewSubmenu, submenu_get_view(app->submenu)); + app->flash_mode = false; + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneStart); return app; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app.h b/applications/external/wifi_marauder_companion/wifi_marauder_app.h index 3a342bbba..b6664fdab 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app.h @@ -4,7 +4,7 @@ extern "C" { #endif -#define WIFI_MARAUDER_APP_VERSION "v0.4.0" +#define WIFI_MARAUDER_APP_VERSION "v0.5.0" typedef struct WifiMarauderApp WifiMarauderApp; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h b/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h index d6a0d37c7..cd248648a 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h @@ -26,7 +26,7 @@ #include #include -#define NUM_MENU_ITEMS (18) +#define NUM_MENU_ITEMS (19) #define WIFI_MARAUDER_TEXT_BOX_STORE_SIZE (4096) #define WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE (512) @@ -113,6 +113,13 @@ struct WifiMarauderApp { int special_case_input_step; char special_case_input_src_addr[20]; char special_case_input_dst_addr[20]; + + // For flashing - TODO: put into its own struct? + char bin_file_path_boot[100]; + char bin_file_path_part[100]; + char bin_file_path_app[100]; + FuriThread* flash_worker; + bool flash_mode; }; // Supported commands: diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h b/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h index b6d9f8274..8f020b754 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h @@ -9,5 +9,6 @@ typedef enum { WifiMarauderEventStartSettingsInit, WifiMarauderEventStartLogViewer, WifiMarauderEventStartScriptSelect, - WifiMarauderEventStartSniffPmkidOptions + WifiMarauderEventStartSniffPmkidOptions, + WifiMarauderEventStartFlasher } WifiMarauderCustomEvent; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c new file mode 100644 index 000000000..8d30c1539 --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c @@ -0,0 +1,200 @@ +#include "wifi_marauder_flasher.h" + +FuriStreamBuffer* flash_rx_stream; // TODO make safe +WifiMarauderApp* 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(WifiMarauderApp* 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); + + // 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); + + /* + // TODO packet drops with higher BR? + 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); + storage_file_close(bin_file); + storage_file_free(bin_file); + loader_port_debug_print(err_msg); + return; + } + + furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); + // TODO remember to change BR back! + */ + + 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); + char err_msg[256]; + snprintf(err_msg, sizeof(err_msg), "Erasing flash failed with error %d\n", err); + loader_port_debug_print(err_msg); + return err; + } + + loader_port_debug_print("Start programming\n"); + while(size > 0) { + 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) { + char err_msg[256]; + snprintf(err_msg, sizeof(err_msg), "Packet could not be written! Error: %u\n", err); + storage_file_close(bin_file); + storage_file_free(bin_file); + loader_port_debug_print(err_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; +} + +static int32_t wifi_marauder_flash_bin(void* context) { + WifiMarauderApp* app = (void*)context; + esp_loader_error_t err; + + // alloc global objects + flash_rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); + timer = furi_timer_alloc(_timer_callback, FuriTimerTypePeriodic, app); + + 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\n", err); + loader_port_debug_print(err_msg); + } + + if(!err) { + loader_port_debug_print("Connected\n"); + loader_port_debug_print("Flashing bootloader (1/3)\n"); + err = _flash_file(app, app->bin_file_path_boot, 0x1000); + } + if(!err) { + loader_port_debug_print("Flashing partition table (2/3)\n"); + err = _flash_file(app, app->bin_file_path_part, 0x8000); + } + if(!err) { + loader_port_debug_print("Flashing app (3/3)\n"); + err = _flash_file(app, app->bin_file_path_app, 0x10000); + loader_port_debug_print("Done flashing. Please reset the board manually.\n"); + } + + // done + + // cleanup + furi_stream_buffer_free(flash_rx_stream); + flash_rx_stream = NULL; + furi_timer_free(timer); + return 0; +} + +void wifi_marauder_flash_start_thread(WifiMarauderApp* app) { + global_app = app; + + app->flash_worker = furi_thread_alloc(); + furi_thread_set_name(app->flash_worker, "WifiMarauderFlashWorker"); + furi_thread_set_stack_size(app->flash_worker, 2048); + furi_thread_set_context(app->flash_worker, app); + furi_thread_set_callback(app->flash_worker, wifi_marauder_flash_bin); + furi_thread_start(app->flash_worker); +} + +void wifi_marauder_flash_stop_thread(WifiMarauderApp* 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); + wifi_marauder_uart_tx((uint8_t*)data, size); + return ESP_LOADER_SUCCESS; +} + +void loader_port_enter_bootloader(void) { + // unimplemented +} + +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 wifi_marauder_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) + wifi_marauder_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 wifi_marauder_flash_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) wifi_marauder_console_output_handle_rx_data_cb(buf, len, global_app); + } +} \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h new file mode 100644 index 000000000..796e258e5 --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h @@ -0,0 +1,10 @@ +#pragma once + +#include "wifi_marauder_app_i.h" +#include "wifi_marauder_uart.h" +#define SERIAL_FLASHER_INTERFACE_UART /* TODO why is application.fam not passing this via cdefines */ +#include "esp_loader_io.h" + +void wifi_marauder_flash_start_thread(WifiMarauderApp* app); +void wifi_marauder_flash_stop_thread(WifiMarauderApp* app); +void wifi_marauder_flash_handle_rx_data_cb(uint8_t* buf, size_t len, void* context); \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_uart.c b/applications/external/wifi_marauder_companion/wifi_marauder_uart.c index 080280b5f..0c9147752 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_uart.c +++ b/applications/external/wifi_marauder_companion/wifi_marauder_uart.c @@ -112,4 +112,4 @@ void wifi_marauder_uart_free(WifiMarauderUart* uart) { furi_hal_console_enable(); free(uart); -} \ No newline at end of file +} From ab6c1d0d8ca66b2cd757edb067321ba33b10377b Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 20:26:52 +0300 Subject: [PATCH 22/40] format --- applications/external/flappy_bird/flappy_bird.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/applications/external/flappy_bird/flappy_bird.c b/applications/external/flappy_bird/flappy_bird.c index 7ec152b99..2052488bf 100644 --- a/applications/external/flappy_bird/flappy_bird.c +++ b/applications/external/flappy_bird/flappy_bird.c @@ -29,12 +29,7 @@ typedef enum { EventTypeKey, } EventType; -typedef enum { - BirdState0 = 0, - BirdState1, - BirdState2, - BirdStateMAX -} BirdState; +typedef enum { BirdState0 = 0, BirdState1, BirdState2, BirdStateMAX } BirdState; const Icon* bird_states[BirdStateMAX] = { &I_bird_01, From 550edc366661f49e0b7cf1a850b3408b0a97ca7a Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Wed, 5 Jul 2023 20:35:57 +0300 Subject: [PATCH 23/40] Fix Issue #532 --- lib/nfc/helpers/mf_classic_dict.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/nfc/helpers/mf_classic_dict.c b/lib/nfc/helpers/mf_classic_dict.c index 7bdfa9e78..937addb46 100644 --- a/lib/nfc/helpers/mf_classic_dict.c +++ b/lib/nfc/helpers/mf_classic_dict.c @@ -336,8 +336,8 @@ bool mf_classic_dict_delete_index(MfClassicDict* dict, uint32_t target) { if(furi_string_get_char(next_line, 0) == '#') continue; if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; if(index++ != target) continue; - stream_seek(dict->stream, -(NFC_MF_CLASSIC_KEY_LEN + 1), StreamOffsetFromCurrent); - if(!stream_delete(dict->stream, (NFC_MF_CLASSIC_KEY_LEN + 1))) break; + stream_seek(dict->stream, -NFC_MF_CLASSIC_KEY_LEN, StreamOffsetFromCurrent); + if(!stream_delete(dict->stream, NFC_MF_CLASSIC_KEY_LEN)) break; dict->total_keys--; key_removed = true; } From e6ae2c03ca45033a15f6dd93410673ee03618657 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 00:49:54 +0300 Subject: [PATCH 24/40] Keeloq: Centurion Nova support --- ReadMe.md | 1 + .../main/subghz/helpers/subghz_custom_event.h | 1 + .../subghz/scenes/subghz_scene_set_type.c | 15 +++ assets/resources/subghz/assets/keeloq_mfcodes | 111 +++++++++--------- lib/subghz/protocols/keeloq.c | 49 +++++++- 5 files changed, 117 insertions(+), 60 deletions(-) diff --git a/ReadMe.md b/ReadMe.md index 3ab8e4b4a..28c580a3c 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -93,6 +93,7 @@ Encoders or sending made by @xMasterX: - Keeloq: Stilmatic - Keeloq: CAME Space - Keeloq: Aprimatic (model TR and similar) +- Keeloq: Centurion Nova (thanks Carlos !) Encoders or sending made by @Eng1n33r(first implementation in Q2 2022) & @xMasterX (current version): - CAME Atomo -> Update! check out new [instructions](https://github.com/DarkFlippers/unleashed-firmware/blob/dev/documentation/SubGHzRemoteProg.md) diff --git a/applications/main/subghz/helpers/subghz_custom_event.h b/applications/main/subghz/helpers/subghz_custom_event.h index 83c16fbbc..e5321264e 100644 --- a/applications/main/subghz/helpers/subghz_custom_event.h +++ b/applications/main/subghz/helpers/subghz_custom_event.h @@ -15,6 +15,7 @@ typedef enum { SubmenuIndexBeninca868, SubmenuIndexAllmatic433, SubmenuIndexAllmatic868, + SubmenuIndexCenturion433, SubmenuIndexIronLogic, SubmenuIndexElmesElectronic, SubmenuIndexSommer_FM_434, diff --git a/applications/main/subghz/scenes/subghz_scene_set_type.c b/applications/main/subghz/scenes/subghz_scene_set_type.c index 0219f406b..64e927250 100644 --- a/applications/main/subghz/scenes/subghz_scene_set_type.c +++ b/applications/main/subghz/scenes/subghz_scene_set_type.c @@ -91,6 +91,12 @@ void subghz_scene_set_type_on_enter(void* context) { SubmenuIndexAllmatic868, subghz_scene_set_type_submenu_callback, subghz); + submenu_add_item( + subghz->submenu, + "KL: Centurion 433MHz", + SubmenuIndexCenturion433, + subghz_scene_set_type_submenu_callback, + subghz); submenu_add_item( subghz->submenu, "KL: Sommer 434MHz", @@ -444,6 +450,15 @@ bool subghz_scene_set_type_on_event(void* context, SceneManagerEvent event) { scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowError); } break; + case SubmenuIndexCenturion433: + generated_protocol = subghz_txrx_gen_keeloq_protocol( + subghz->txrx, "AM650", 433920000, (key & 0x0000FFFF), 0x2, 0x0003, "Centurion"); + if(!generated_protocol) { + furi_string_set( + subghz->error_str, "Function requires\nan SD card with\nfresh databases."); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowError); + } + break; case SubmenuIndexElmesElectronic: generated_protocol = subghz_txrx_gen_keeloq_protocol( subghz->txrx, diff --git a/assets/resources/subghz/assets/keeloq_mfcodes b/assets/resources/subghz/assets/keeloq_mfcodes index e65eb0868..27ab5aaaf 100644 --- a/assets/resources/subghz/assets/keeloq_mfcodes +++ b/assets/resources/subghz/assets/keeloq_mfcodes @@ -1,58 +1,59 @@ Filetype: Flipper SubGhz Keystore File Version: 0 Encryption: 1 -IV: AF 0B A3 13 56 FA F7 46 76 78 25 28 34 16 3D 62 -77995F096640A6CA8735DE839975FA3573145DDB995E45F58AECCD6A6F2D6FCB -A062DD58F9957EC098075344DFF69FB3B2A3C9893D4240C74BE32299F330290B -2AD2CCC4FB760D772001A903A995435260F442152BDCD5B075FBC61015BEC7E1 -34AE78CF87A10211C8E6F6E2EE18C4F0BBE3B677094B7118E03AD9E89AF70E28 -41943E7507D37A344F56EDF4BBDCDA75FAA10A6E97DF801ACF2A0E97E41782053CA74E31E3488EA1AFE29369E7A542C7 -9FA67B118BC1FE289F38A78DA4E1FFBAEB4498404B49CBD9690B9421FC05564D -3A872E97A668C644D3827273ADDA6B1BC689A3AD09F5980EC7461E40624653BE -5E1F4D865E5F4176DBF7832992B60947812E05701E647CF36427C2EE04F97FE2 -7FCF6E437D0DA231A2937C46622C4939F0045AEF5CF7FCF5D97E24B67995F0D3 -D09F230FEDB9CB690B5AC7C6BCE86B0779D9C233D2823562EABE340FF06C819D -84F0A81ABB7857438BF52BE8988C1A471EFEDFE16EC11851BFC39F34EB26236F318CFAAEC9A53AD5500D48CAE21E777A -F3FDDDD5DB6038D0E2FC02750530325976ADA2600DE19BF736AF6CB7E810D7627B4F396963F0288F486182228B9AAE22 -87E07B23B3B2740D93C82696C020057CC7F3864ABD6E6967656F44427C529DD1 -20C35809F7F5161C21E643A606DC48A5CC85BCEB546A03023DF778C4499426E3 -81CCF1CA68E2B6663DA9D12FEE241307A2E449440901793A955CB5D5915819DD -1B66D0664451153D0124364834E1543960A756351330523C3FFE83DA4EE7F0E6 -7025D550A40466B472BA71F3248C37E6DE1FD59ED5C11CBB26238795DD44F4B21BD447F3CA72AED6A25B977982100A1E -99F38C3F7C89D2805FB36F931AC5D1B248A56838AC29E13B1255CAE706B68216 -D138C616E4E1F6053177118C94F65C0BA6B155286CE63E0728E3F2D2BF6C6A98 -276E646DBF54B341F93AB4E1C36525AF983879F7251D84BB02DD54F4A5E0FA85A3278891F7ADA9ADE2F8AAD010F6F6D4 -3F3598143FE40E04FE25EADE1EC2B4CDAE339AF7730AE9DC45C97C0E44B299DBCC0E9DA6F4B0EE00F25D2FDD9E1C6BF5 -20FA8F62628FEA51A584CE298F22E60FF85BFE193AF1C5DE57605FF02E90739C -B14B4896088EF58E0CE659511C93782FB5F94BC69B64E5011EBD10DF18FFB3B1 -90BBE045FFEA06A77B55B0B6D0CFA8F12C4E1B35FB0111DD0C2CF1637AE8924A -04B87BC1D09E8EE3C8A91CE75169546D37868B2D87BF2D712623F84937ACE974 -B8C5B04070FFB27B4686057C57F762FA3CAF2BBD3E5BEBE462C1C2FC283AE118 -A40B154CEC2F5F989CA6F30703A0133217530D41F12739B25E2C1BEF54E6AC7C -4F5B9A68E8DEDB00410F5AD7FB7F7CA8F43B75F0457DA2AFAA8279A8C4AF34AB -9A7B185F6A157B1886DC6AA98B1F3D6899331D8BDDBAAC9620321E16BB4CC7E8 -4A710E11F1C7A7138065801BDB4E72B07608220BBCF7455111FDD41DC0290B94 -3A5B715089F926049077172755B0C48B4A4420031787D7DB113CF402C7D3D0AE -EE0B90EC27EC0F4A8DCD3C747E17594E0A27A92E05F2DE7B0457873C7154E075 -0B9B201C209072676A47225BE4E43B4631B080A85F9FCFAA5683A4F9A727187A -13A15C606AA2EA40F2DCDE7F44217F02D2D9796CAC9164100B211D7A22CF333B -DF5292BBF35AB1408956D439A81EF12F53573F985489727A10FB652B7BD8B10D -50E59C9DD3A08EA8752656B753B8D9D2BFD674EB4C5F0DCAE9870E81D7F00F6AAC133FA7C7307FA197D551EE877F8CD7 -E173C1798596A31F697D63E0CCDDFAB14B1B1E299DD642102A7858ECC795CF1B -92D3326A93AA6B37041F219C8035F37A057C1B69BECA7881098BED2A49C58751 -27D17F007115734FA0F55F2BDF016ECE8DFA703FA6D61729456E95B78FC8AC29 -4FF7306A426B7DE021D59968FAEF3453F555A9A952D81C4008D5000513799DEA -660CB0D4634EABC6CAA9E321CB08FC0C8C8F6BAE0FAF0C10C1FCCBA93B68D9B4 -86D84C91BFBF0DE22088C0F5A8598A2C2807033E60BC11333E8D1A6188F043D5 -F3E0E8566E12ADBA44974A3CA1D6D60456649031DCAD4365D0AE80FEDBC80AAA106A9BAB39448CD62EF916A59ECA9579 -F4D6EB6D241B17CA0A9E73E93DA3B58B6B257CC0484FC92E285984A09FD4CEA9 -094265CB574E0C9B8954B3130A2017492B1149C3FB9239A6B690A9C7B6635E5A -BE67B61B2F99BAA4AF94B71CB5F2386417D5F3B187899222D2671B1147BA9932 -74840B34C9F27A76FCB593629C8114BCABD1B1CE96E22CC378DC9E7BEEF263FB -2511F44F0A13D94B55D7FF3297194E47D6987890F9170BCBC14A7607C5A38E01 -FD0CF9314CB9B949CEFE1DA3FA05A18FBEEF751B4DC900DBAE068EE211C4492C -22ECD6934472760CF806E7C9E86885D0C0AAE501EDBF9DCB7ADC7AE53F3B73C38F2B6FB3FD0F867C5B5BFD00440CB43A -325CA78241AE4EE784CC867815403E342F77BB428EB1FE189AD569F10170CB98 -BF065D29EC8E2BB411F0131DF3A06BDF07B1436A14004D0E11E1261F0E232CB8 -CE015802FCE9AFD9807F855D813FD06D5446A8953057A79BC4A452BDAB8E9DD7 -C6B569EB172EC4609966E2C9426BE99A86529073A57824B1752392658C4E87F08ED8675A32F44E413CD6037CA4A0DE71 +IV: AD 0B A4 A1 51 C0 C0 41 36 78 26 82 17 24 9D 62 +0D18FF475E57A67CC5C0B430664E8EF6E07CB6AF72454995F17DE84E2E876D87 +C9BC55E1E3A9B312E341D7E2663C66C2479D5C51AE2EB83BAE47D8C6C79DB8A0 +776E01A7B4FCB929FA59CFE1F16D2D600F6FD9FD8BE1E9E41667144E61E023E4 +C354F854F14AAC08C6A51606582CD73EECEED54779927DC1E04A0D72C4E6A58E +09BA4DC551CDB0141F4A053133DBF9B7B99CBAA402C7B6B2AC8ADB516CA2FCB29FF9744DD95FB009BED6A09AE3303317 +675777F65042358100A9A2BE142C42E10CC5CF98CA6BFF82284FFD9BF7E7FB11 +4739972DCC08EFF0E8547694A67E116F3EC8638F286E333E7D89F2D61218F65D +FE8D5A0A9ED36545004CEE70D3C1FE477F34212364CF7C9EBA0FDD4F6B8F1D3E +453D5C6FE0EA7FD779B54696E66DE6BD6AEF3B1EE347142A3DB7505609077219 +A52339EE40D046E7DF6C130CEC7F9F686753A73A5F72EF344E01B00C3A3CF5F2 +94029CE386CC0403984F7C9D80B40FF12BE6E50412891FD45B347742340D1E6E679102DEC6F7D36C36863701A2BBDA7B +793633A3D97D704779E2E841A5F616ED0BB0BD50740C0B196D72C6C6453124183CA93ADCAC1A5042EBD579AC238B9DBC +B1C6EBB7320CAE97E28A244228B288BEEA44C9FD262E2C448219DAC6E194CB14 +A6C374B3FB7E8BB6F3052ED9DB67E5BCFA6CCC42F5A0D7F20BEDB7C0B58592A5 +DF4FCBDCA3414B7551797A856048625186B2EC7B836EB35B4B080CEE4A72C39F +4127F58BDEB18D79EA8317B1858F7575CF4B648E3C53338975B4A093FA9730C0 +294659EBD39D7CC01DC4E0E3B0B90A3555704E736D3BE4485BAAACBC58A84652CF3A7DA3C271E3198C72561332F2A141 +9E2CC77756BE7AB3D500C0B4A91271C0A4DED5BCB78484217EA922B7878AA8F5 +BF13D9949C783CF6B2F0E489A6912E56DDD9183D651D7F36FD0342981596A85C +8441C62006E1334FC31F53DAFF5281260C463AF3E92B1E797CB67882C49566846825606804C14C49FFD440F4E05CE692 +BE7E62E9CFA1C703CCB971F2B0C6C0F339C78A951CA8DB287B40C3BA76EA7179E8B62C29EAC8293FD218CF981BB84BEF +DA53C52101FAC8FD8F9545768CF1DB59F3B31C9249A2FC64B66DB259C721ABE1 +C9842AD0A8A8E94FCE94F46BDE89DAA8D11C41F9C83A7F6394D595028829AB92 +904A94542BCD85F72D470640A220FD28EBC337C0673C189C96BFB8CE373B4F84 +EEEE187B03FE77B955F22214707017DB8A60B2E3979D5C2F6BED61D0623D4D50 +CEF91BE6EBD8F331E2422B6B948053E8DA143F3DD907C922E0328D49B0ADA8A6 +A6F0F8A4F03B45062CEA86B291E80EE15906C0B226ABDB77E222EB95B026952D +62280870E48A2E8B8A18AD5DFF0089E927BEACE1F81A8BB1A8A2BE8EB0E92BFD +C9A3DE8165D47D1D41715F00192313755226C1B0A3D04BCD7A121B1CB4999FBD +3CAEEB62FCF601F34D3320E3EACE9EFC5D627BF69FEE965F8B84A258A765B6FE +8D83CC36514CE5CC46B181AE28089BE5BC99CE3096C569751B4E07A7D956AFA3 +0F81DDB18F60E238C7FF751E70431AA5328EFDBBDFF03D5F360A524AA968CEE9 +1F1E498A279E9BA15CB6BB836E90FEE522F2BE16572A4D057DF9C2B104487458 +68C60FF95056BE4D814CE9B8A4175625DB3E365712C2D3E42CEEBA2E0977CDB9 +D95FB21943FCAD5A21F157E629314986D92F568FD3067B65911135E6335FB7E8 +17908EF142C4B6740CBE7DCA43DA3C23C7912739299786473A994E5752E7E9459B23653EE0D7775FCECB7B7608CB0495 +6D17B6BA17DBFFAA4E90953CE6A73AB967076B8FBC14A9361D93A01C0850CC38 +8723740BCC0A5CCEE52B6EF73DD441672FB6728965CC588044C78D495AB0675F +CA548FA44A444C8F45490A11DBC8FB24E6DB38F910EC60520A3890C8B45664FE +591356440344AAFEC21FAA0C85B6A8F354D45074932E37E0972F851E08937469 +DE3A54CAAC8014625EE502F547A93754AFAD0A7EB6028599D03CCB0473BC8D5C +B2C2F6F971034E1591AD374793D6D17A595D6544DF5A9585780C6B2E3505BCFF +54447BE6C626D1CA37FD799B76B35ED266D12757B5DA1AB9277F671BBF7F07B461D0CE26593F1372354979E836972F85 +45FBD88AA7C26B967BC3638F6083A6B83AA82D5B974B37DF1C3F52839DDA020C +33B9890FBE46FDB7AEE404B71C893DC20059F96224CF48F284A66D3A8D91918E +CCEA5BC148BC84DB4825320A2B8D39A30BAB4641FFEE33BD4B8700339F15892D +4BC4E0D1263E9B02DA401C884923778D1A6FACACFFE7F660381ECD64CCA5CCD2 +0284EA911FB1B37F623F92B1662E10D79AEBD0009C107A9C554D417F7553B28E +FE48F26C44FA4C3EB3B2F3497FE99AC30A0A7BF9FF261740E177D7A2A5BD7880 +1EA96FEBB62543A8731D19BBDD1C7FE323CADBAB7242E5A8F4B1D706964B4C32 +4AB7EEF02FD59EA5D16837A50282A6254B93A34F31FE9335DA9FABEF76EA714591029C64967506B99860358E5CBF4EDA +A0F25C5387FE9B871E246F33FE64396A5DC0A9BC9AD9DF9E219F3482ADD6497E +0130F99FA395F4364491E6718B53E9D6983B68E29A70035B158CA7629C31C33E +3CDAEDA88534C2E31D1235C99DEC466221C89F63E1F8F59C9CE224573E39E2D4 +F5ED2863D8B51DA620484CDE23D590F4A208DA6D155E645FCD6BCF5FEB39EE551EAE9C0366F7FFD4CBF1DCA063D154E1 diff --git a/lib/subghz/protocols/keeloq.c b/lib/subghz/protocols/keeloq.c index 0d17fa4b5..db46936c2 100644 --- a/lib/subghz/protocols/keeloq.c +++ b/lib/subghz/protocols/keeloq.c @@ -231,6 +231,9 @@ static bool subghz_protocol_keeloq_gen_data( } else if(strcmp(instance->manufacture_name, "Beninca") == 0) { decrypt = btn << 28 | (0x000) << 16 | instance->generic.cnt; // Beninca / Allmatic -> no serial - simple XOR + } else if(strcmp(instance->manufacture_name, "Centurion") == 0) { + decrypt = btn << 28 | (0x1CE) << 16 | instance->generic.cnt; + // Centurion -> no serial in hop, uses fixed value 0x1CE - normal learning } uint8_t kl_type_en = instance->keystore->kl_type; for @@ -302,7 +305,7 @@ static bool subghz_protocol_keeloq_gen_data( uint64_t yek = (uint64_t)fix << 32 | hop; instance->generic.data = subghz_protocol_blocks_reverse_key(yek, instance->generic.data_count_bit); - } // What should happen if seed = 0 in bft programming mode + } // What should happen if seed = 0 in bft programming mode -> collapse of the universe I think :) return true; // Always return true } @@ -693,6 +696,33 @@ static inline bool subghz_protocol_keeloq_check_decrypt( if((decrypt >> 28 == btn) && (((((uint16_t)(decrypt >> 16)) & 0xFF) == end_serial) || ((((uint16_t)(decrypt >> 16)) & 0xFF) == 0))) { instance->cnt = decrypt & 0x0000FFFF; + /*FURI_LOG_I( + "KL", + "decrypt: 0x%08lX, btn: %d, end_serial: 0x%03lX, cnt: %ld", + decrypt, + btn, + end_serial, + instance->cnt);*/ + return true; + } + return false; +} +// Centurion specific check +static inline bool subghz_protocol_keeloq_check_decrypt_centurion( + SubGhzBlockGeneric* instance, + uint32_t decrypt, + uint8_t btn) { + furi_assert(instance); + + if((decrypt >> 28 == btn) && (((((uint16_t)(decrypt >> 16)) & 0x3FF) == 0x1CE))) { + instance->cnt = decrypt & 0x0000FFFF; + /*FURI_LOG_I( + "KL", + "decrypt: 0x%08lX, btn: %d, end_serial: 0x%03lX, cnt: %ld", + decrypt, + btn, + end_serial, + instance->cnt);*/ return true; } return false; @@ -753,10 +783,19 @@ static uint8_t subghz_protocol_keeloq_check_remote_controller_selector( man = subghz_protocol_keeloq_common_normal_learning(fix, manufacture_code->key); decrypt = subghz_protocol_keeloq_common_decrypt(hop, man); - if(subghz_protocol_keeloq_check_decrypt(instance, decrypt, btn, end_serial)) { - *manufacture_name = furi_string_get_cstr(manufacture_code->name); - keystore->mfname = *manufacture_name; - return 1; + if((strcmp(furi_string_get_cstr(manufacture_code->name), "Centurion") == 0)) { + if(subghz_protocol_keeloq_check_decrypt_centurion(instance, decrypt, btn)) { + *manufacture_name = furi_string_get_cstr(manufacture_code->name); + keystore->mfname = *manufacture_name; + return 1; + } + } else { + if(subghz_protocol_keeloq_check_decrypt( + instance, decrypt, btn, end_serial)) { + *manufacture_name = furi_string_get_cstr(manufacture_code->name); + keystore->mfname = *manufacture_name; + return 1; + } } break; case KEELOQ_LEARNING_SECURE: From e83764ef4e5d3b13fa706a5feaed6d07a802b1f4 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 01:09:32 +0300 Subject: [PATCH 25/40] RCA protocol unit test --- .../debug/unit_tests/infrared/infrared_test.c | 12 ++ assets/unit_tests/infrared/test_rca.irtest | 105 ++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 assets/unit_tests/infrared/test_rca.irtest diff --git a/applications/debug/unit_tests/infrared/infrared_test.c b/applications/debug/unit_tests/infrared/infrared_test.c index 2bcb95da8..b2acad470 100644 --- a/applications/debug/unit_tests/infrared/infrared_test.c +++ b/applications/debug/unit_tests/infrared/infrared_test.c @@ -425,6 +425,7 @@ MU_TEST(infrared_test_decoder_mixed) { infrared_test_run_decoder(InfraredProtocolSamsung32, 1); infrared_test_run_decoder(InfraredProtocolSIRC, 3); infrared_test_run_decoder(InfraredProtocolKaseikyo, 1); + infrared_test_run_decoder(InfraredProtocolRCA, 1); } MU_TEST(infrared_test_decoder_nec) { @@ -499,6 +500,15 @@ MU_TEST(infrared_test_decoder_kaseikyo) { infrared_test_run_decoder(InfraredProtocolKaseikyo, 6); } +MU_TEST(infrared_test_decoder_rca) { + infrared_test_run_decoder(InfraredProtocolRCA, 1); + infrared_test_run_decoder(InfraredProtocolRCA, 2); + infrared_test_run_decoder(InfraredProtocolRCA, 3); + infrared_test_run_decoder(InfraredProtocolRCA, 4); + infrared_test_run_decoder(InfraredProtocolRCA, 5); + infrared_test_run_decoder(InfraredProtocolRCA, 6); +} + MU_TEST(infrared_test_encoder_decoder_all) { infrared_test_run_encoder_decoder(InfraredProtocolNEC, 1); infrared_test_run_encoder_decoder(InfraredProtocolNECext, 1); @@ -509,6 +519,7 @@ MU_TEST(infrared_test_encoder_decoder_all) { infrared_test_run_encoder_decoder(InfraredProtocolRC5, 1); infrared_test_run_encoder_decoder(InfraredProtocolSIRC, 1); infrared_test_run_encoder_decoder(InfraredProtocolKaseikyo, 1); + infrared_test_run_encoder_decoder(InfraredProtocolRCA, 1); } MU_TEST_SUITE(infrared_test) { @@ -527,6 +538,7 @@ MU_TEST_SUITE(infrared_test) { MU_RUN_TEST(infrared_test_decoder_samsung32); MU_RUN_TEST(infrared_test_decoder_necext1); MU_RUN_TEST(infrared_test_decoder_kaseikyo); + MU_RUN_TEST(infrared_test_decoder_rca); MU_RUN_TEST(infrared_test_decoder_mixed); MU_RUN_TEST(infrared_test_encoder_decoder_all); } diff --git a/assets/unit_tests/infrared/test_rca.irtest b/assets/unit_tests/infrared/test_rca.irtest new file mode 100644 index 000000000..bfe34e8e4 --- /dev/null +++ b/assets/unit_tests/infrared/test_rca.irtest @@ -0,0 +1,105 @@ +Filetype: IR tests file +Version: 1 +# +name: decoder_input1 +type: raw +data: 1000000 3994 3969 552 1945 551 1945 552 1945 551 1945 552 946 551 947 550 1947 548 951 546 1953 542 979 518 1979 517 981 492 1006 491 1006 492 1006 492 1006 492 2005 492 2005 492 1006 492 2005 492 1006 492 2005 492 1006 492 2006 491 +# +name: decoder_expected1 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: 54 00 00 00 +repeat: false +# +name: decoder_input2 +type: raw +data: 1000000 4055 3941 605 1891 551 1947 550 1946 551 1946 551 947 551 947 550 1947 549 949 548 1951 545 1977 519 1978 519 1979 518 980 518 980 518 980 518 980 518 1979 518 1979 518 981 517 1979 518 980 518 980 518 980 518 980 518 +# +name: decoder_expected2 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: F4 00 00 00 +repeat: false +# +name: decoder_input3 +type: raw +data: 1000000 4027 3970 551 1946 550 1946 551 1946 551 1946 551 946 551 947 550 1947 549 949 547 1951 545 1978 518 1979 492 1006 492 1007 491 1006 492 1006 492 1006 492 2006 491 2006 491 1006 492 2006 491 1007 491 1007 491 1006 492 2006 491 +# +name: decoder_expected3 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: 74 00 00 00 +repeat: false +# +name: decoder_input4 +type: raw +data: 1000000 4021 3941 551 1946 550 1946 551 1946 551 1945 552 946 551 947 550 1947 549 950 547 1952 544 1977 519 979 519 1979 518 980 518 980 518 980 518 980 518 1979 518 1979 518 980 518 1979 518 980 518 980 518 1979 518 980 518 +# +name: decoder_expected4 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: B4 00 00 00 +repeat: false +# +name: decoder_input5 +type: raw +data: 1000000 4022 3941 551 1946 551 1946 577 1919 578 1919 578 920 552 946 551 1946 550 947 550 1949 547 1952 544 978 520 979 519 980 518 980 518 980 518 980 518 1979 518 1979 518 980 518 1979 518 980 518 980 518 1979 518 1980 517 +# +name: decoder_expected5 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: 34 00 00 00 +repeat: false +# +name: decoder_input6 +type: raw +data: 1000000 3995 3968 552 1944 552 1946 550 1946 550 1946 551 947 550 948 549 1947 549 1949 547 1952 544 1978 518 1979 492 2005 492 1006 492 1006 492 1006 492 1006 492 2005 492 2005 492 1006 492 1006 492 1006 492 1006 492 1006 492 1006 492 +# +name: decoder_expected6 +type: parsed_array +count: 1 +# +protocol: RCA +address: 0F 00 00 00 +command: FC 00 00 00 +repeat: false +# +name: encoder_decoder_input1 +type: parsed_array +count: 4 +# +protocol: RCA +address: 0F 00 00 00 +command: 74 00 00 00 +repeat: false +# +protocol: RCA +address: 0F 00 00 00 +command: B4 00 00 00 +repeat: false +# +protocol: RCA +address: 0F 00 00 00 +command: 34 00 00 00 +repeat: false +# +protocol: RCA +address: 0F 00 00 00 +command: FC 00 00 00 +repeat: false +# From 4876e03932675787dcc33cb5e238508a7dc7604d Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 01:14:41 +0300 Subject: [PATCH 26/40] OFW PR 2829: Decode only supported Oregon 3 sensor by wosk --- applications/external/weather_station/protocols/oregon3.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/applications/external/weather_station/protocols/oregon3.c b/applications/external/weather_station/protocols/oregon3.c index a211c5ad3..bd35c2fd5 100644 --- a/applications/external/weather_station/protocols/oregon3.c +++ b/applications/external/weather_station/protocols/oregon3.c @@ -116,9 +116,11 @@ static ManchesterEvent level_and_duration_to_event(bool level, uint32_t duration static uint8_t oregon3_sensor_id_var_bits(uint16_t sensor_id) { switch(sensor_id) { case ID_THGR221: - default: // nibbles: temp + hum + '0' return (4 + 2 + 1) * 4; + default: + FURI_LOG_D(TAG, "Unsupported sensor id 0x%x", sensor_id); + return 0; } } @@ -198,10 +200,8 @@ void ws_protocol_decoder_oregon3_feed(void* context, bool level, uint32_t durati oregon3_sensor_id_var_bits(OREGON3_SENSOR_ID(instance->generic.data)); if(!instance->var_bits) { - // sensor is not supported, stop decoding, but showing the decoded fixed part + // sensor is not supported, stop decoding instance->decoder.parser_step = Oregon3DecoderStepReset; - if(instance->base.callback) - instance->base.callback(&instance->base, instance->base.context); } else { instance->decoder.parser_step = Oregon3DecoderStepVarData; } From 0f5fc11f8f265006ca9a946efacf056ad7193e55 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 01:20:09 +0300 Subject: [PATCH 27/40] Dbg stuff --- applications/main/application.fam | 13 +++++++------ documentation/HowToBuild.md | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/applications/main/application.fam b/applications/main/application.fam index c8884f934..43aea2e5d 100644 --- a/applications/main/application.fam +++ b/applications/main/application.fam @@ -18,19 +18,20 @@ App( ], ) +# Enable apps that you need in DEBUG firmware here: App( appid="main_apps_default", name="Basic applications for main menu", apptype=FlipperAppType.METAPACKAGE, provides=[ - #"gpio", - #"ibutton", - #"infrared", + # "gpio", + # "ibutton", + # "infrared", "lfrfid", - "nfc", + # "nfc", "subghz", - #"bad_usb", - #"u2f", + # "bad_usb", + # "u2f", "archive", ], ) diff --git a/documentation/HowToBuild.md b/documentation/HowToBuild.md index 80b93b1c3..76830063f 100644 --- a/documentation/HowToBuild.md +++ b/documentation/HowToBuild.md @@ -31,6 +31,9 @@ Check out `documentation/fbt.md` for details on building and flashing firmware. ### Compile everything for development +Edit this file to enable/disable Main apps that you need in DEBUG mode, flash space doesn't allows us to fit them all in DEBUG currently +- `applications/main/application.fam` + ```sh ./fbt FIRMWARE_APP_SET=debug_pack updater_package ``` @@ -52,6 +55,9 @@ Check out `documentation/fbt.md` for details on building and flashing firmware. ### Compile everything for development +Edit this file to enable/disable Main apps that you need in DEBUG mode, flash space doesn't allows us to fit them all in DEBUG currently +- `applications/main/application.fam` + ```sh ./fbt.cmd FIRMWARE_APP_SET=debug_pack updater_package ``` From cebc56dc23229da68100ef6844eb4c9f1a9388af Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 02:07:07 +0300 Subject: [PATCH 28/40] move --- applications/external/barcode_generator/barcode_generator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/applications/external/barcode_generator/barcode_generator.h b/applications/external/barcode_generator/barcode_generator.h index 5d2c8307e..9f2e10c16 100644 --- a/applications/external/barcode_generator/barcode_generator.h +++ b/applications/external/barcode_generator/barcode_generator.h @@ -7,7 +7,7 @@ #include #include -#define BARCODE_SETTINGS_FILE_NAME "apps/Misc/barcodegen.save" +#define BARCODE_SETTINGS_FILE_NAME "apps/Tools/barcodegen.save" #define BARCODE_SETTINGS_VER (1) #define BARCODE_SETTINGS_PATH EXT_PATH(BARCODE_SETTINGS_FILE_NAME) From 45f3a7754850a595bfaeaa3a82f49b1cc69d8be7 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 02:26:56 +0300 Subject: [PATCH 29/40] barcodes --- ReadMe.md | 2 +- applications/external/barcode_gen/LICENSE | 22 + applications/external/barcode_gen/README.md | 88 +++ .../external/barcode_gen/application.fam | 16 + .../external/barcode_gen/barcode_app.c | 348 ++++++++++++ .../external/barcode_gen/barcode_app.h | 91 +++ .../external/barcode_gen/barcode_utils.c | 147 +++++ .../external/barcode_gen/barcode_utils.h | 55 ++ .../external/barcode_gen/barcode_validator.c | 532 ++++++++++++++++++ .../external/barcode_gen/barcode_validator.h | 15 + applications/external/barcode_gen/encodings.c | 52 ++ applications/external/barcode_gen/encodings.h | 6 + .../barcode_gen/images/barcode_10.png | Bin 0 -> 161 bytes .../screenshots/Codabar Data Example.png | Bin 0 -> 1672 bytes .../screenshots/Creating Barcode.png | Bin 0 -> 1681 bytes .../screenshots/Flipper Barcode.png | Bin 0 -> 1207 bytes .../screenshots/Flipper Box Barcode.png | Bin 0 -> 1372 bytes .../external/barcode_gen/views/barcode_view.c | 510 +++++++++++++++++ .../external/barcode_gen/views/barcode_view.h | 23 + .../external/barcode_gen/views/create_view.c | 494 ++++++++++++++++ .../external/barcode_gen/views/create_view.h | 46 ++ .../external/barcode_gen/views/message_view.c | 66 +++ .../external/barcode_gen/views/message_view.h | 22 + .../barcode_generator/application.fam | 17 - .../barcode_generator/barcode_10px.png | Bin 2363 -> 0 bytes .../barcode_generator/barcode_generator.c | 447 --------------- .../barcode_generator/barcode_generator.h | 115 ---- .../barcode_data/codabar_encodings.txt | 22 + .../barcode_data/code128_encodings.txt | 202 +++++++ .../barcode_data/code128c_encodings.txt | 106 ++++ .../barcode_data/code39_encodings.txt | 44 ++ 31 files changed, 2908 insertions(+), 580 deletions(-) create mode 100644 applications/external/barcode_gen/LICENSE create mode 100644 applications/external/barcode_gen/README.md create mode 100644 applications/external/barcode_gen/application.fam create mode 100644 applications/external/barcode_gen/barcode_app.c create mode 100644 applications/external/barcode_gen/barcode_app.h create mode 100644 applications/external/barcode_gen/barcode_utils.c create mode 100644 applications/external/barcode_gen/barcode_utils.h create mode 100644 applications/external/barcode_gen/barcode_validator.c create mode 100644 applications/external/barcode_gen/barcode_validator.h create mode 100644 applications/external/barcode_gen/encodings.c create mode 100644 applications/external/barcode_gen/encodings.h create mode 100644 applications/external/barcode_gen/images/barcode_10.png create mode 100644 applications/external/barcode_gen/screenshots/Codabar Data Example.png create mode 100644 applications/external/barcode_gen/screenshots/Creating Barcode.png create mode 100644 applications/external/barcode_gen/screenshots/Flipper Barcode.png create mode 100644 applications/external/barcode_gen/screenshots/Flipper Box Barcode.png create mode 100644 applications/external/barcode_gen/views/barcode_view.c create mode 100644 applications/external/barcode_gen/views/barcode_view.h create mode 100644 applications/external/barcode_gen/views/create_view.c create mode 100644 applications/external/barcode_gen/views/create_view.h create mode 100644 applications/external/barcode_gen/views/message_view.c create mode 100644 applications/external/barcode_gen/views/message_view.h delete mode 100644 applications/external/barcode_generator/application.fam delete mode 100644 applications/external/barcode_generator/barcode_10px.png delete mode 100644 applications/external/barcode_generator/barcode_generator.c delete mode 100644 applications/external/barcode_generator/barcode_generator.h create mode 100644 assets/resources/apps_data/barcode_data/codabar_encodings.txt create mode 100644 assets/resources/apps_data/barcode_data/code128_encodings.txt create mode 100644 assets/resources/apps_data/barcode_data/code128c_encodings.txt create mode 100644 assets/resources/apps_data/barcode_data/code39_encodings.txt diff --git a/ReadMe.md b/ReadMe.md index 28c580a3c..b589e164e 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -145,7 +145,7 @@ You can support us by using links or addresses below: - WiFi Scanner plugin [(by SequoiaSan)](https://github.com/SequoiaSan/FlipperZero-WiFi-Scanner_Module) - MultiConverter plugin [(by theisolinearchip)](https://github.com/theisolinearchip/flipperzero_stuff) - WAV Player [(OFW: DrZlo13)](https://github.com/flipperdevices/flipperzero-firmware/tree/zlo/wav-player) - Fixed and improved by [LTVA1](https://github.com/LTVA1/wav_player) -> Also outputs audio on `PA6` - `3(A6)` pin -- Barcode generator plugin [(original by McAzzaMan)](https://github.com/McAzzaMan/flipperzero-firmware/tree/UPC-A_Barcode_Generator/applications/barcode_generator) - [EAN-8 and refactoring](https://github.com/DarkFlippers/unleashed-firmware/pull/154) by @msvsergey +- Barcode Generator [(by Kingal1337)](https://github.com/Kingal1337/flipper-barcode-generator) - GPIO: Sentry Safe plugin [(by H4ckd4ddy)](https://github.com/H4ckd4ddy/flipperzero-sentry-safe-plugin) - ESP32: WiFi Marauder companion plugin [(by 0xchocolate)](https://github.com/0xchocolate/flipperzero-wifi-marauder) - Saving .pcap on flipper microSD [by tcpassos](https://github.com/tcpassos/flipperzero-firmware-with-wifi-marauder-companion) -> Only with custom marauder build (It is necessary to uncomment "#define WRITE_PACKETS_SERIAL" in configs.h (in marauder fw) and compile the firmware for the wifi board.) Or download precompiled build -> [Download esp32_marauder_ver_flipper_sd_serial.bin](https://github.com/justcallmekoko/ESP32Marauder/releases/latest) - NRF24: Sniffer & MouseJacker (with changes) [(by mothball187)](https://github.com/mothball187/flipperzero-nrf24/tree/main/mousejacker) diff --git a/applications/external/barcode_gen/LICENSE b/applications/external/barcode_gen/LICENSE new file mode 100644 index 000000000..4c02d8221 --- /dev/null +++ b/applications/external/barcode_gen/LICENSE @@ -0,0 +1,22 @@ + +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/README.md b/applications/external/barcode_gen/README.md new file mode 100644 index 000000000..ec944cb26 --- /dev/null +++ b/applications/external/barcode_gen/README.md @@ -0,0 +1,88 @@ +

+

Barcode Generator

+

+ +A barcode generator for the Flipper Zero that supports **UPC-A**, **EAN-8**, **EAN-13**, **Code-39**, **Codabar**, and **Code-128**[1] +

+ +Note: Barcode save locations have been moved from `/barcodes` to `/apps_data/barcodes` + +## Table of Contents +- [Table of Contents](#table-of-contents) +- [Installing](#installing) +- [Building](#building) +- [Usage](#usage) + - [Creating a barcode](#creating-a-barcode) + - [Editing a barcode](#editing-a-barcode) + - [Deleting a barcode](#deleting-a-barcode) + - [Viewing a barcode](#viewing-a-barcode) +- [Screenshots](#screenshots) +- [Credits](#credits) + + +## Installing +1) Download the `.zip` file from the release section +2) Extract/unzip the `.zip` file onto your computer +3) Open qFlipper and go to the file manager +4) Navigate to the `apps` folder +5) Drag & drop the `.fap` file into the `apps` folder +6) Navigate back to the root folder of the SD card and create the folder `apps_data`, if not already there +7) Navigate into `apps_data` and create another folder called `barcode_data` +8) Navigate into `barcode_data` +9) Drag & drop the encoding txts (`code39_encodings.txt`, `code128_encodings.txt` & `codabar_encodings.txt`) into the `barcode_data` folder + +## Building +1) Clone the [flipperzero-firmware](https://github.com/flipperdevices/flipperzero-firmware) repository or a firmware of your choice +2) Clone this repository and put it in the `applications_user` folder +3) Build this app by using the command `./fbt fap_Barcode_App` +4) Copy the `.fap` from `build\f7-firmware-D\.extapps\Barcode_App.fap` to `apps\Misc` using the qFlipper app +5) While still in the qFlipper app, navigate to the root folder of the SD card and create the folder `apps_data`, if not already there +6) Navigate into `apps_data` and create another folder called `barcode_data` +7) Navigate into `barcode_data` +8) Drag & drop the encoding txts (`code39_encodings.txt`, `code128_encodings.txt` & `codabar_encodings.txt`) from the `encoding_tables` folder in this repository into the `barcode_data` folder + +## Usage + +### Creating a barcode +1) To create a barcode click on `Create Barcode` +2) Next select your type using the left and right arrows +3) Enter your filename and then your barcode data +4) Click save + +**Note**: For Codabar barcodes, you must manually add the start and stop codes to the barcode data +Start/Stop codes can be A, B, C, or D +For example, if you wanted to represent `1234` as a barcode you will need to enter something like `A1234A`. (You can replace the letters A with either A, B, C, or D) + +![Codabar Data Example](screenshots/Codabar%20Data%20Example.png "Codabar Data Example") + +### Editing a barcode +1) To edit a barcode click on `Edit Barcode` +2) Next select the barcode file you want to edit +3) Edit the type, name, or data +4) Click save + +### Deleting a barcode +1) To delete a barcode click on `Edit Barcode` +2) Next select the barcode file you want to delete +3) Scroll all the way to the bottom +4) Click delete + +### Viewing a barcode +1) To view a barcode click on `Load Barcode` +2) Next select the barcode file you want to view + +## Screenshots +![Barcode Create Screen](screenshots/Creating%20Barcode.png "Barcode Create Screen") + +![Flipper Code-128 Barcode](screenshots/Flipper%20Barcode.png "Flipper Code-128 Barcode") + +![Flipper Box EAN-13 Barcode](screenshots/Flipper%20Box%20Barcode.png "Flipper Box EAN-13 Barcode") + +## Credits + +- [Kingal1337](https://github.com/Kingal1337) - Developer +- [Z0wl](https://github.com/Z0wl) - Added Code128-C Support +- [@teeebor](https://github.com/teeebor) - Menu Code Snippet + + +[1] - supports Set B (only the characters from 0-94). Also supports Set C diff --git a/applications/external/barcode_gen/application.fam b/applications/external/barcode_gen/application.fam new file mode 100644 index 000000000..371e52c04 --- /dev/null +++ b/applications/external/barcode_gen/application.fam @@ -0,0 +1,16 @@ +App( + appid="barcode_app", + name="Barcode App", + 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_icon_assets_symbol="barcode_app", + fap_author="@Kingal1337", + fap_weburl="https://github.com/Kingal1337/flipper-barcode-generator", + fap_version="1.0", + 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 new file mode 100644 index 000000000..99e5769d2 --- /dev/null +++ b/applications/external/barcode_gen/barcode_app.c @@ -0,0 +1,348 @@ +#include "barcode_app.h" + +#include "barcode_app_icons.h" + +/** + * 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 new file mode 100644 index 000000000..3150bff1f --- /dev/null +++ b/applications/external/barcode_gen/barcode_app.h @@ -0,0 +1,91 @@ +#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 encodings are located +#define BARCODE_DATA_FILE_DIR_PATH EXT_PATH("apps_data/barcode_data") + +//the folder where the codabar encoding table is located +#define CODABAR_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/codabar_encodings.txt" + +//the folder where the code 39 encoding table is located +#define CODE39_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/code39_encodings.txt" + +//the folder where the code 128 encoding table is located +#define CODE128_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/code128_encodings.txt" + +//the folder where the code 128 C encoding table is located +#define CODE128C_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_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_utils.c b/applications/external/barcode_gen/barcode_utils.c new file mode 100644 index 000000000..31274c1fe --- /dev/null +++ b/applications/external/barcode_gen/barcode_utils.c @@ -0,0 +1,147 @@ +#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 new file mode 100644 index 000000000..0a27785cf --- /dev/null +++ b/applications/external/barcode_gen/barcode_utils.h @@ -0,0 +1,55 @@ + +#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 new file mode 100644 index 000000000..cb493f3e9 --- /dev/null +++ b/applications/external/barcode_gen/barcode_validator.c @@ -0,0 +1,532 @@ +#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 new file mode 100644 index 000000000..2138124dd --- /dev/null +++ b/applications/external/barcode_gen/barcode_validator.h @@ -0,0 +1,15 @@ +#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 new file mode 100644 index 000000000..764fde796 --- /dev/null +++ b/applications/external/barcode_gen/encodings.c @@ -0,0 +1,52 @@ +#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 new file mode 100644 index 000000000..c5b8d61ff --- /dev/null +++ b/applications/external/barcode_gen/encodings.h @@ -0,0 +1,6 @@ +#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 new file mode 100644 index 0000000000000000000000000000000000000000..32d4971ad355874ef62be4cf9eb9586fdef48ad7 GIT binary patch literal 161 zcmeAS@N?(olHy`uVBq!ia0vp^AT}2ZGmxy8xzq=w7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O`1M1^9%x0_p$%|1Z5c|1OZlS>O>_%)r2R2!t6$HM|;tf-0Uajv*44lM@6) zL{btGSSB$ks7+8-IB?=bM{COorw}H~CLRWdH%zMMw$JzmRL|h)>gTe~DWM4f+!!l! literal 0 HcmV?d00001 diff --git a/applications/external/barcode_gen/screenshots/Codabar Data Example.png b/applications/external/barcode_gen/screenshots/Codabar Data Example.png new file mode 100644 index 0000000000000000000000000000000000000000..907dfd901317f06d5cc034e9a30866959506edb1 GIT binary patch literal 1672 zcmeAS@N?(olHy`uVBq!ia0y~yU;;8388|?c*QZDWAjMhW5n0T@z;^_M8K-LVNi#68 zS$VoRhE&XXdpA1owgrR3Mb8OOQ)(k!u1){S^4Yu~-EC!r*R{vHGyFV8zV!95JQ6o(bS6V7uj|0R#)|!eqY|!WcvJK z;PcauZ)}q~EO-8-jWOJ$6%TD2mVUL)u9@-J}Ub`mpevDPx>g*NM z=N+$lZ5va|Tl@a|hcoF_Y3B~^J-+Ao`>x$a%y8#fc9roUOT4sYczx)5+1I}f+I=&# z4N=YhGViXp+k4%8&q~*Bzjt2ppa1q<{(sL@S3KKe{n_&Ld?eLXmQ@V)Gk4lsI2=3^ zw@i}3VG09-3nzoa70q|7PpWDfo*N^X{Pj5l!;hOUYM0jil)0*>%=F+33xk3e1H&SG z)V*tW+?g7FBiTuO992oz9sowLeSO^LSf<6toew^)-1ub0=hXh5!gyk9%(48rxx zzA;R@c5BT1#QU)vdMklb2HR2TjU?yO6+^IS?$ePgqBwu-m}h`Pw-oyG#BUuWxQMjwp`H`C51H@tzqsZzs${3X8;Q2IJRX7hhM)-)hcKZE?6d z|C!X!i+kH`*B!S%eEvfhQtbJCv}Dk@{n*YjJ7=rd{_pp0&w6h8D!rleoxn_v?+Hxubln;c{&>;BLef|*QB|8 z5AKQWum0I_kfFea=wgQW0*MHfE4D9YXZZi^*T=87llR%*pKlkPQ5z`%M)B0Xno zJ;V7FgwIp?8!qqswYTBhjpPQ~8HfnK$^1a%+@59juUOt^pBD2MV(V9UHJH8P33ft*|iGXh-O*l}B63G!RV) z9eV&(9?|{*i)$Mo4uloD;#QrdKS;1$8Mf=t7I}=&biPDPzIDq@n?2NZR zsA^yO?QZj76MjjE4Vjx~+7d0_p2XD!b)V+(^UFMylS;wCDy7&f;A zEUR_H!bX^B#`7@fj)E@&pbool=wVMDy10ZFN;)k!HS?QiqUrp4&TJ#GJ2QfWyw2_u zn;5j?0J$#kVvHTe$UxV6EvFXWr{PWODK%!EB#PFaDR@iP&odL)g&Nzt(YxV$G)Z;b zMUHJ6#~LWpTGcOUQ#k`-%tFhrGF|M`XCvdcvN50fCeUM`<>l=VwCONW?ghCYqgzvJ zeuPKj^sh`)rFe;Yy`zCcJ@TMn0p*lTYq4uvuXrX(Qm9eQ4}Vqd*F|W>_jXoJRk%x6 z@BqXU0N);fgRw&Q5~4wsNAx?r#Na>a(U;fjS@qOJmtC%Ej?Aay)(g1wMgt!5HWv|H z=WL^DpjIA9z~xnS0{;mricDER@%wu8X6^l-fkN1~h&ys`YZ=F!n$_e)rrEf) z$^j-htx^#j*tkuEBdrDn)Y(WEnp9>2QgUEhReMrN-@8+$@ITR?-cSwctF^0Kb!iCm zHB6bdFx-M>6N|ZmVH!rUu@H*-n*zs!-{YaAi`jj;RUEaMD~YlUKm5EtH*=iF9+68) z2Bkt4q}U*b?46Ie9Xv5-xs!jXd(>N(O3qP|43(;DT~4`muF;{g&<{J~EfsE|Z8G}W zH7C|T9QC}jmU=gr-ZWMqGopw2f_r;Z&-0RXZYTSoqH3MT%DPm3Sv>pCUu1 zl4@I?uVBV}0Rm?u)^1kThW>X4o}#iiN`ogj@(2Nx@;s=NDieIGGv$w{a z_#U6Zh=k?V+Og0>uA(h_mF;-`e+7b!fHHLJ1eI`N1y=o(R9m`zegAW5 z2HWqO{TUjHIT#$KFfh1q;-PH&><;|>`}z3w>E{)q_NBkQ>7x8z(z1QxM&;*wzD7hp zmznwe#p?}bWtr>G7rwqB7;fJ_v(oL&*Lw3}U$k^IdiTD4yxi_P^-<@H zKUo=^=VDOsVqjRr!k}uGMS-v2W>+w^asLAucWW)t~#lw{dgg;Bx3M%^>bP0l+XkK2Z=AV literal 0 HcmV?d00001 diff --git a/applications/external/barcode_gen/screenshots/Flipper Box Barcode.png b/applications/external/barcode_gen/screenshots/Flipper Box Barcode.png new file mode 100644 index 0000000000000000000000000000000000000000..8dbd7d2a9c1b0564a1a2188e6de48fe9370ad426 GIT binary patch literal 1372 zcmeAS@N?(olHy`uVBq!ia0y~yU;;8388|?c*QZDWAjMhW5n0T@z;^_M8K-LVNi#68 z@_D*AhE&XXd)M3VwE=^}MfN1iHT|v|?5;K6<0%!=419F!rEPl4Dzo{=UTEdb-t)Jv z{vY##=e6J17!2AO7+g3R9H!u*t{i{EYw`N;>*w#^AAc>CYrF63E%)kq`=3jBRd379 z-s`?S_e)jy?Ka!>dtZHATWTxy@t&OQ;c(gGf{#D1`af6j{LRmQ7N6e9ozB1z$iyI^ zI!cWO!H`M?`TOtB-@N_dl<({3@82)~J@s|rtRCTSD|&^IQndW$us;^dx21lGx!qB@ zclEdI^F?m@|6f!WO;4S-@zV^;UF#x`Kk7^V9cszU&>_Uopuxz{QS~aF!Tq^>`q}OC zBA<2qon`ue_w%3Sk$~yq>ajDi76?7FzF9ZuDnE;s&yBsGoVxYB z>H2N@L_AKW^J5uTZKKS~}5{XBJZ&y8os_ov?b{P*>0yYPxoyXX8zo#$ z{h9gt{2Bvsn@6?Mg@5O)j2BYgfF$?abI_=KPCw;X0F^`vvZs1y6c9o=N(pl*O@i*eBpG%&FQh5>$Y!9k4^tp tzSVHE5mM-0wqs^U&_fcySC0H=oN}tJOPWI=6Ifg_c)I$ztaD0e0suzQQWgLJ literal 0 HcmV?d00001 diff --git a/applications/external/barcode_gen/views/barcode_view.c b/applications/external/barcode_gen/views/barcode_view.c new file mode 100644 index 000000000..55ab52046 --- /dev/null +++ b/applications/external/barcode_gen/views/barcode_view.c @@ -0,0 +1,510 @@ +#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 new file mode 100644 index 000000000..828428c08 --- /dev/null +++ b/applications/external/barcode_gen/views/barcode_view.h @@ -0,0 +1,23 @@ +#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 new file mode 100644 index 000000000..e4e489113 --- /dev/null +++ b/applications/external/barcode_gen/views/create_view.c @@ -0,0 +1,494 @@ +#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 new file mode 100644 index 000000000..6063786d9 --- /dev/null +++ b/applications/external/barcode_gen/views/create_view.h @@ -0,0 +1,46 @@ +#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 new file mode 100644 index 000000000..3a9aa90b3 --- /dev/null +++ b/applications/external/barcode_gen/views/message_view.c @@ -0,0 +1,66 @@ +#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 new file mode 100644 index 000000000..33acc3d0c --- /dev/null +++ b/applications/external/barcode_gen/views/message_view.h @@ -0,0 +1,22 @@ +#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/barcode_generator/application.fam b/applications/external/barcode_generator/application.fam deleted file mode 100644 index 9bb44915c..000000000 --- a/applications/external/barcode_generator/application.fam +++ /dev/null @@ -1,17 +0,0 @@ -App( - appid="barcode_generator", - name="Barcode Generator", - apptype=FlipperAppType.EXTERNAL, - entry_point="barcode_generator_app", - requires=[ - "gui", - "dialogs", - ], - stack_size=1 * 1024, - order=50, - fap_icon="barcode_10px.png", - fap_category="Tools", - fap_author="@xMasterX & @msvsergey & @McAzzaMan", - fap_version="1.0", - fap_description="App displays Barcode on flipper screen and allows to edit it", -) diff --git a/applications/external/barcode_generator/barcode_10px.png b/applications/external/barcode_generator/barcode_10px.png deleted file mode 100644 index 7c19c665687e0e6f81a805511af4d8ed409b54bc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2363 zcmcIleQeZZ81FWfF+QB4FvMlG7#NXWKkwSN?ikzM?JL~4Z6|D~fnNLeR(IEyYq#AN z%oaruB@i%+Xe3Ao#)CCTV+^Ork;KJQyBnW;32#3Z*#BN*U?_IKaeUzS z(mh7`Q{OyWxU&9K%`bDe6`dY_KCpfM-7jDH?cf#g@cDuxu}cScwCuRreyr!qeaC+| zcX^3+pm4DHz|o##-B{_$tsj?NnJ6B-6doDp&s-m1E8c1?Xn7AZ;Hz?we2wykvY;APuiu^WudPi-z(SN?R@;HLcx zzv`HXo_hy&To_+b^XT3=ukAU{ovhfot7*~2FItwIohaJER3wD*lN;WD_rq%gfBEmb zbQKzh>WkN|_AlwENgwtMJW=-eD?i6Rv6e2Jko%+Rh+v&4n0F%d!KN2}U0k(r02@2A z{?Dsz)n`#A=UNRNHipexmF-j2N>s1GtI`r8NJ2-()5(Nk zOKCrm;g!(Zy-g8#2I6%2iEKgJ!x21SrXVhO7*e5W8fO@vM+B;mlj+qsOS25cFcd42 zEF;lC;y66_AyB-Os!6TEx?D7Lg|^w9QedbD8qV^3FssvaOuN&(gSN@XwZJ((Pu#-JdnCYAT3h zGMkbHfmhKWPx68YNKWHpB=89W$)F&DLi0Qq6Z35AQ#$G$IWd*hRiz?EFAG&o0D#nF zD3F@KE2QWZASo!K07OLqng|H|X54_8FjHYuMcL&DTva5^OeJOHA3Z6@A!QkH*Ug9> zouWavQR(_}{m}-u=2i(E&zMe<71!&2LUD@>RU&s=pC)^=)0w61?SzPQhT>;owy8P2 zathYOQKtXZT-2S!+j7s$(tTc$<9v#jgtU(%V*<~UKm;rac%W!BOZx;LlRx_ZB0ZN@ zrBgQI5WPAn;=dneb}pW_4*%?{+19~3waK%aZaWO+zAv*5qi#3fP4ng(pa!+3YfU>> z(^@$`S=}|$_ZtmF=mQKSQNQ>|p64|ZXsSxGKn9G)sv>06s*H++ev>QTWdUDpD8SOZ z;HwiECKM1uAW+NlLC#mlhXQr%l${xltRQM;hMI%NYqvc2H!SJ|umAu6 diff --git a/applications/external/barcode_generator/barcode_generator.c b/applications/external/barcode_generator/barcode_generator.c deleted file mode 100644 index 2645bbcea..000000000 --- a/applications/external/barcode_generator/barcode_generator.c +++ /dev/null @@ -1,447 +0,0 @@ -#include "barcode_generator.h" - -static BarcodeType* barcodeTypes[NUMBER_OF_BARCODE_TYPES]; - -void init_types() { - BarcodeType* upcA = malloc(sizeof(BarcodeType)); - upcA->name = "UPC-A"; - upcA->numberOfDigits = 12; - upcA->startPos = 19; - upcA->bartype = BarTypeUPCA; - barcodeTypes[0] = upcA; - - BarcodeType* ean8 = malloc(sizeof(BarcodeType)); - ean8->name = "EAN-8"; - ean8->numberOfDigits = 8; - ean8->startPos = 33; - ean8->bartype = BarTypeEAN8; - barcodeTypes[1] = ean8; - - BarcodeType* ean13 = malloc(sizeof(BarcodeType)); - ean13->name = "EAN-13"; - ean13->numberOfDigits = 13; - ean13->startPos = 19; - ean13->bartype = BarTypeEAN13; - barcodeTypes[2] = ean13; -} - -void draw_digit( - Canvas* canvas, - int digit, - BarEncodingType rightHand, - int startingPosition, - bool drawlines) { - char digitStr[2]; - snprintf(digitStr, 2, "%u", digit); - canvas_set_color(canvas, ColorBlack); - canvas_draw_str( - canvas, startingPosition, BARCODE_Y_START + BARCODE_HEIGHT + BARCODE_TEXT_OFFSET, digitStr); - - if(drawlines) { - switch(rightHand) { - case BarEncodingTypeLeft: - case BarEncodingTypeRight: - canvas_set_color( - canvas, (rightHand == BarEncodingTypeRight) ? ColorBlack : ColorWhite); - //int count = 0; - for(int i = 0; i < 4; i++) { - canvas_draw_box( - canvas, startingPosition, BARCODE_Y_START, DIGITS[digit][i], BARCODE_HEIGHT); - canvas_invert_color(canvas); - startingPosition += DIGITS[digit][i]; - } - break; - case BarEncodingTypeG: - canvas_set_color(canvas, ColorWhite); - //int count = 0; - for(int i = 3; i >= 0; i--) { - canvas_draw_box( - canvas, startingPosition, BARCODE_Y_START, DIGITS[digit][i], BARCODE_HEIGHT); - canvas_invert_color(canvas); - startingPosition += DIGITS[digit][i]; - } - break; - default: - break; - } - } -} - -int get_digit_position(int index, BarcodeType* type) { - int pos = 0; - switch(type->bartype) { - case BarTypeEAN8: - case BarTypeUPCA: - pos = type->startPos + index * 7; - if(index >= type->numberOfDigits / 2) { - pos += 5; - } - break; - case BarTypeEAN13: - if(index == 0) - pos = type->startPos - 10; - else { - pos = type->startPos + (index - 1) * 7; - if((index - 1) >= type->numberOfDigits / 2) { - pos += 5; - } - } - break; - default: - break; - } - return pos; -} - -int get_menu_text_location(int index) { - return 20 + 10 * index; -} - -int get_barcode_max_index(PluginState* plugin_state) { - return plugin_state->barcode_state.doParityCalculation ? - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]->numberOfDigits - 1 : - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]->numberOfDigits; -} - -int calculate_check_digit(PluginState* plugin_state, BarcodeType* type) { - int checkDigit = 0; - int checkDigitOdd = 0; - int checkDigitEven = 0; - //add all odd positions. Confusing because 0index - for(int i = 0; i < type->numberOfDigits - 1; i += 2) { - checkDigitOdd += plugin_state->barcode_state.barcodeNumeral[i]; - } - - //add all even positions to above. Confusing because 0index - for(int i = 1; i < type->numberOfDigits - 1; i += 2) { - checkDigitEven += plugin_state->barcode_state.barcodeNumeral[i]; - } - - if(type->bartype == BarTypeEAN13) { - checkDigit = checkDigitEven * 3 + checkDigitOdd; - } else { - checkDigit = checkDigitOdd * 3 + checkDigitEven; - } - - checkDigit = checkDigit % 10; //mod 10 - - //if m = 0 then x12 = 0, otherwise x12 is 10 - m - return (10 - checkDigit) % 10; -} - -static void render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - PluginState* plugin_state = ctx; - furi_mutex_acquire(plugin_state->mutex, FuriWaitForever); - - if(plugin_state->mode == MenuMode) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_str_aligned(canvas, 64, 6, AlignCenter, AlignCenter, "MENU"); - canvas_draw_frame(canvas, 50, 0, 29, 11); //box around Menu - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(0), AlignCenter, AlignCenter, "View"); - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(1), AlignCenter, AlignCenter, "Edit"); - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(2), AlignCenter, AlignCenter, "Parity?"); - - canvas_draw_frame(canvas, 83, get_menu_text_location(2) - 3, 6, 6); - if(plugin_state->barcode_state.doParityCalculation == true) { - canvas_draw_box(canvas, 85, get_menu_text_location(2) - 1, 2, 2); - } - canvas_draw_str_aligned( - canvas, - 64, - get_menu_text_location(3), - AlignCenter, - AlignCenter, - (barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex])->name); - canvas_draw_disc( - canvas, - 40, - get_menu_text_location(plugin_state->menuIndex) - 1, - 2); //draw menu cursor - } else { - BarcodeType* type = barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]; - - //start saftey - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, type->startPos - 3, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, (type->startPos - 1), BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - - int startpos = 0; - int endpos = type->numberOfDigits; - if(type->bartype == BarTypeEAN13) { - startpos++; - draw_digit( - canvas, - plugin_state->barcode_state.barcodeNumeral[0], - BarEncodingTypeRight, - get_digit_position(0, barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]), - false); - } - if(plugin_state->barcode_state.doParityCalculation) { //calculate the check digit - plugin_state->barcode_state.barcodeNumeral[type->numberOfDigits - 1] = - calculate_check_digit(plugin_state, type); - } - for(int index = startpos; index < endpos; index++) { - BarEncodingType barEncodingType = BarEncodingTypeLeft; - if(type->bartype == BarTypeEAN13) { - if(index - 1 >= (type->numberOfDigits - 1) / 2) { - barEncodingType = BarEncodingTypeRight; - } else { - barEncodingType = - (FURI_BIT( - EAN13ENCODE[plugin_state->barcode_state.barcodeNumeral[0]], - index - 1)) ? - BarEncodingTypeG : - BarEncodingTypeLeft; - } - } else { - if(index >= type->numberOfDigits / 2) { - barEncodingType = BarEncodingTypeRight; - } - } - - int digitPosition = get_digit_position( - index, barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]); - draw_digit( - canvas, - plugin_state->barcode_state.barcodeNumeral[index], - barEncodingType, - digitPosition, - true); - } - - //central separator - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 62, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, 64, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - - if(plugin_state->mode == EditMode) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_box( - canvas, - get_digit_position( - plugin_state->editingIndex, - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]) - - 1, - 63, - 7, - 1); //draw editing cursor - } - - //end safety - int endSafetyPosition = get_digit_position(type->numberOfDigits - 1, type) + 7; - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, endSafetyPosition, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, (endSafetyPosition + 2), BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - } - - furi_mutex_release(plugin_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 barcode_generator_state_init(PluginState* plugin_state) { - plugin_state->editingIndex = 0; - plugin_state->mode = ViewMode; - plugin_state->menuIndex = MENU_INDEX_VIEW; - if(!LOAD_BARCODE_SETTINGS(&plugin_state->barcode_state)) { - for(int i = 0; i < BARCODE_MAX_LENS; ++i) { - plugin_state->barcode_state.barcodeNumeral[i] = i % 10; - } - plugin_state->barcode_state.doParityCalculation = true; - plugin_state->barcode_state.barcodeTypeIndex = 0; - } -} - -static bool handle_key_press_view(InputKey key, PluginState* plugin_state) { - switch(key) { - case InputKeyOk: - case InputKeyBack: - plugin_state->mode = MenuMode; - break; - - default: - break; - } - - return true; -} - -static bool handle_key_press_edit(InputKey key, PluginState* plugin_state) { - int barcodeMaxIndex = get_barcode_max_index(plugin_state); - - switch(key) { - case InputKeyUp: - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] = - (plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] + 1) % 10; - break; - - case InputKeyDown: - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] = - (plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] == 0) ? - 9 : - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] - 1; - break; - - case InputKeyRight: - plugin_state->editingIndex = (plugin_state->editingIndex + 1) % barcodeMaxIndex; - break; - - case InputKeyLeft: - plugin_state->editingIndex = (plugin_state->editingIndex == 0) ? - barcodeMaxIndex - 1 : - plugin_state->editingIndex - 1; - break; - - case InputKeyOk: - case InputKeyBack: - plugin_state->mode = MenuMode; - break; - - default: - break; - } - - return true; -} - -static bool handle_key_press_menu(InputKey key, PluginState* plugin_state) { - switch(key) { - case InputKeyUp: - plugin_state->menuIndex = (plugin_state->menuIndex == MENU_INDEX_VIEW) ? - MENU_INDEX_TYPE : - plugin_state->menuIndex - 1; - break; - - case InputKeyDown: - plugin_state->menuIndex = (plugin_state->menuIndex + 1) % 4; - break; - - case InputKeyRight: - if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == NUMBER_OF_BARCODE_TYPES - 1) ? - 0 : - plugin_state->barcode_state.barcodeTypeIndex + 1; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } - break; - case InputKeyLeft: - if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == 0) ? - NUMBER_OF_BARCODE_TYPES - 1 : - plugin_state->barcode_state.barcodeTypeIndex - 1; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } - break; - - case InputKeyOk: - if(plugin_state->menuIndex == MENU_INDEX_VIEW) { - plugin_state->mode = ViewMode; - } else if(plugin_state->menuIndex == MENU_INDEX_EDIT) { - plugin_state->mode = EditMode; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } else if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == NUMBER_OF_BARCODE_TYPES - 1) ? - 0 : - plugin_state->barcode_state.barcodeTypeIndex + 1; - } - break; - - case InputKeyBack: - return false; - - default: - break; - } - int barcodeMaxIndex = get_barcode_max_index(plugin_state); - if(plugin_state->editingIndex >= barcodeMaxIndex) - plugin_state->editingIndex = barcodeMaxIndex - 1; - - return true; -} - -int32_t barcode_generator_app(void* p) { - UNUSED(p); - - init_types(); - - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent)); - - PluginState* plugin_state = malloc(sizeof(PluginState)); - barcode_generator_state_init(plugin_state); - - plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!plugin_state->mutex) { - FURI_LOG_E("barcode_generator", "cannot create mutex\r\n"); - furi_message_queue_free(event_queue); - free(plugin_state); - return 255; - } - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, plugin_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); - - PluginEvent event; - for(bool processing = true; processing;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - furi_mutex_acquire(plugin_state->mutex, FuriWaitForever); - - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey && - ((event.input.type == InputTypePress) || (event.input.type == InputTypeRepeat))) { - switch(plugin_state->mode) { - case ViewMode: - processing = handle_key_press_view(event.input.key, plugin_state); - break; - case EditMode: - processing = handle_key_press_edit(event.input.key, plugin_state); - break; - case MenuMode: - processing = handle_key_press_menu(event.input.key, plugin_state); - break; - default: - break; - } - } - } - - view_port_update(view_port); - furi_mutex_release(plugin_state->mutex); - } - - 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(plugin_state->mutex); - // save settings - SAVE_BARCODE_SETTINGS(&plugin_state->barcode_state); - free(plugin_state); - - return 0; -} diff --git a/applications/external/barcode_generator/barcode_generator.h b/applications/external/barcode_generator/barcode_generator.h deleted file mode 100644 index 9f2e10c16..000000000 --- a/applications/external/barcode_generator/barcode_generator.h +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#define BARCODE_SETTINGS_FILE_NAME "apps/Tools/barcodegen.save" - -#define BARCODE_SETTINGS_VER (1) -#define BARCODE_SETTINGS_PATH EXT_PATH(BARCODE_SETTINGS_FILE_NAME) -#define BARCODE_SETTINGS_MAGIC (0xC2) - -#define SAVE_BARCODE_SETTINGS(x) \ - saved_struct_save( \ - BARCODE_SETTINGS_PATH, \ - (x), \ - sizeof(BarcodeState), \ - BARCODE_SETTINGS_MAGIC, \ - BARCODE_SETTINGS_VER) - -#define LOAD_BARCODE_SETTINGS(x) \ - saved_struct_load( \ - BARCODE_SETTINGS_PATH, \ - (x), \ - sizeof(BarcodeState), \ - BARCODE_SETTINGS_MAGIC, \ - BARCODE_SETTINGS_VER) - -#define BARCODE_HEIGHT 50 -#define BARCODE_Y_START 3 -#define BARCODE_TEXT_OFFSET 9 -#define BARCODE_MAX_LENS 13 -#define NUMBER_OF_BARCODE_TYPES 3 -#define MENU_INDEX_VIEW 0 -#define MENU_INDEX_EDIT 1 -#define MENU_INDEX_PARITY 2 -#define MENU_INDEX_TYPE 3 - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; - -typedef enum { - ViewMode, - EditMode, - MenuMode, -} Mode; - -typedef enum { - BarEncodingTypeLeft, - BarEncodingTypeRight, - BarEncodingTypeG, -} BarEncodingType; - -typedef enum { - BarTypeEAN8, - BarTypeUPCA, - BarTypeEAN13, -} BarType; - -typedef struct { - char* name; - int numberOfDigits; - int startPos; - BarType bartype; -} BarcodeType; - -typedef struct { - int barcodeNumeral[BARCODE_MAX_LENS]; //The current barcode number - bool doParityCalculation; //Should do parity check? - int barcodeTypeIndex; -} BarcodeState; - -typedef struct { - FuriMutex* mutex; - BarcodeState barcode_state; - int editingIndex; //The index of the editing symbol - int menuIndex; //The index of the menu cursor - Mode mode; //View, edit or menu -} PluginState; - -static const int DIGITS[10][4] = { - {3, 2, 1, 1}, - {2, 2, 2, 1}, - {2, 1, 2, 2}, - {1, 4, 1, 1}, - {1, 1, 3, 2}, - {1, 2, 3, 1}, - {1, 1, 1, 4}, - {1, 3, 1, 2}, - {1, 2, 1, 3}, - {3, 1, 1, 2}, -}; - -static const uint8_t EAN13ENCODE[10] = { - 0b000000, - 0b110100, - 0b101100, - 0b011100, - 0b110010, - 0b100110, - 0b001110, - 0b101010, - 0b011010, - 0b010110, -}; \ No newline at end of file diff --git a/assets/resources/apps_data/barcode_data/codabar_encodings.txt b/assets/resources/apps_data/barcode_data/codabar_encodings.txt new file mode 100644 index 000000000..5f0684cbd --- /dev/null +++ b/assets/resources/apps_data/barcode_data/codabar_encodings.txt @@ -0,0 +1,22 @@ +# 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/assets/resources/apps_data/barcode_data/code128_encodings.txt b/assets/resources/apps_data/barcode_data/code128_encodings.txt new file mode 100644 index 000000000..394a34520 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code128_encodings.txt @@ -0,0 +1,202 @@ + : 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/assets/resources/apps_data/barcode_data/code128c_encodings.txt b/assets/resources/apps_data/barcode_data/code128c_encodings.txt new file mode 100644 index 000000000..75cc71135 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code128c_encodings.txt @@ -0,0 +1,106 @@ +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/assets/resources/apps_data/barcode_data/code39_encodings.txt b/assets/resources/apps_data/barcode_data/code39_encodings.txt new file mode 100644 index 000000000..a41ad16e9 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code39_encodings.txt @@ -0,0 +1,44 @@ +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 From d9b95fd156894f0be12e9c047f79bc19dd728901 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 02:42:05 +0300 Subject: [PATCH 30/40] Misc folder issues --- .../system/storage_move_to_sd/storage_move_to_sd.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/applications/system/storage_move_to_sd/storage_move_to_sd.c b/applications/system/storage_move_to_sd/storage_move_to_sd.c index 4a0f3f4ad..5aaacd736 100644 --- a/applications/system/storage_move_to_sd/storage_move_to_sd.c +++ b/applications/system/storage_move_to_sd/storage_move_to_sd.c @@ -28,6 +28,14 @@ static void storage_move_to_sd_remove_region() { if(storage_common_exists(storage, INT_PATH(".region_data"))) { storage_common_remove(storage, INT_PATH(".region_data")); } + if(storage_common_exists(storage, EXT_PATH("apps/Misc/totp.conf"))) { + storage_common_rename( + storage, EXT_PATH("apps/Misc/totp.conf"), EXT_PATH("authenticator/totp.conf")); + } + if(storage_common_exists(storage, EXT_PATH("apps/Misc/barcodegen.save"))) { + storage_common_remove(storage, EXT_PATH("apps/Misc/barcodegen.save")); + storage_common_remove(storage, EXT_PATH("apps/Misc")); + } furi_record_close(RECORD_STORAGE); } From a6978bfd2d8fc30045e1d9dc20a14c3f230fad10 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 02:44:28 +0300 Subject: [PATCH 31/40] WIP OFW PR 2825: NFC: Improved MFC emulation on some readers Not finished yet, added in current condition for more tests by AloneLiberty --- lib/nfc/nfc_worker.c | 11 ++++++---- lib/nfc/protocols/mifare_classic.c | 33 +++++++++++++++--------------- lib/nfc/protocols/nfca.c | 12 +++++------ lib/nfc/protocols/nfca.h | 3 +++ 4 files changed, 32 insertions(+), 27 deletions(-) diff --git a/lib/nfc/nfc_worker.c b/lib/nfc/nfc_worker.c index 61212540d..959696e7c 100644 --- a/lib/nfc/nfc_worker.c +++ b/lib/nfc/nfc_worker.c @@ -1107,7 +1107,9 @@ void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker) { furi_hal_nfc_listen_start(nfc_data); while(nfc_worker->state == NfcWorkerStateMfClassicEmulate) { //-V1044 if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { - mf_classic_emulator(&emulator, &tx_rx, false); + if(!mf_classic_emulator(&emulator, &tx_rx, false)) { + furi_hal_nfc_listen_start(nfc_data); + } } } if(emulator.data_changed) { @@ -1382,8 +1384,6 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { bool reader_no_data_notified = true; while(nfc_worker->state == NfcWorkerStateAnalyzeReader) { - furi_hal_nfc_stop_cmd(); - furi_delay_ms(5); furi_hal_nfc_listen_start(nfc_data); if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { if(reader_no_data_notified) { @@ -1394,7 +1394,9 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { NfcProtocol protocol = reader_analyzer_guess_protocol(reader_analyzer, tx_rx.rx_data, tx_rx.rx_bits / 8); if(protocol == NfcDeviceProtocolMifareClassic) { - mf_classic_emulator(&emulator, &tx_rx, true); + if(!mf_classic_emulator(&emulator, &tx_rx, true)) { + furi_hal_nfc_listen_start(nfc_data); + } } } else { reader_no_data_received_cnt++; @@ -1406,6 +1408,7 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { FURI_LOG_D(TAG, "No data from reader"); continue; } + furi_delay_ms(1); } rfal_platform_spi_release(); diff --git a/lib/nfc/protocols/mifare_classic.c b/lib/nfc/protocols/mifare_classic.c index 9547c68d0..a6d521dc5 100644 --- a/lib/nfc/protocols/mifare_classic.c +++ b/lib/nfc/protocols/mifare_classic.c @@ -869,7 +869,7 @@ bool mf_classic_emulator( if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { FURI_LOG_D( TAG, - "Error in tx rx. Tx :%d bits, Rx: %d bits", + "Error in tx rx. Tx: %d bits, Rx: %d bits", tx_rx->tx_bits, tx_rx->rx_bits); break; @@ -883,12 +883,17 @@ bool mf_classic_emulator( break; } - if(cmd == 0x50 && plain_data[1] == 0x00) { + if(cmd == NFCA_CMD_HALT && plain_data[1] == 0x00) { FURI_LOG_T(TAG, "Halt received"); - furi_hal_nfc_listen_sleep(); - command_processed = true; + return false; + } + + if(cmd == NFCA_CMD_RATS && !is_encrypted) { + // Mifare Classic doesn't support ATS, NACK it and start listening again + FURI_LOG_T(TAG, "RATS received"); break; } + if(cmd == MF_CLASSIC_AUTH_KEY_A_CMD || cmd == MF_CLASSIC_AUTH_KEY_B_CMD) { uint8_t block = plain_data[1]; uint64_t key = 0; @@ -903,8 +908,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyA; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; - break; + return false; } } else { if(mf_classic_is_key_found( @@ -914,8 +918,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyB; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; - break; + return false; } } @@ -943,16 +946,14 @@ bool mf_classic_emulator( tx_rx->tx_bits = sizeof(nt) * 8; tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; } + if(!furi_hal_nfc_tx_rx(tx_rx, 500)) { FURI_LOG_E(TAG, "Error in NT exchange"); - command_processed = true; - break; + return false; } if(tx_rx->rx_bits != 64) { - FURI_LOG_W(TAG, "Incorrect nr + ar length: %d", tx_rx->rx_bits); - command_processed = true; - break; + return false; } uint32_t nr = nfc_util_bytes2num(tx_rx->rx_data, 4); @@ -963,8 +964,7 @@ bool mf_classic_emulator( if(cardRr != prng_successor(nonce, 64)) { FURI_LOG_T(TAG, "Wrong AUTH! %08lX != %08lX", cardRr, prng_successor(nonce, 64)); // Don't send NACK, as the tag doesn't send it - command_processed = true; - break; + return false; } uint32_t ans = prng_successor(nonce, 96); @@ -1156,6 +1156,7 @@ bool mf_classic_emulator( tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; furi_hal_nfc_tx_rx(tx_rx, 300); + return false; } return true; @@ -1164,7 +1165,7 @@ bool mf_classic_emulator( void mf_classic_halt(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto) { furi_assert(tx_rx); - uint8_t plain_data[4] = {0x50, 0x00, 0x00, 0x00}; + uint8_t plain_data[4] = {NFCA_CMD_HALT, 0x00, 0x00, 0x00}; nfca_append_crc16(plain_data, 2); if(crypto) { diff --git a/lib/nfc/protocols/nfca.c b/lib/nfc/protocols/nfca.c index c401f8cc5..ab4f3f23c 100644 --- a/lib/nfc/protocols/nfca.c +++ b/lib/nfc/protocols/nfca.c @@ -3,8 +3,6 @@ #include #include -#define NFCA_CMD_RATS (0xE0U) - #define NFCA_CRC_INIT (0x6363) #define NFCA_F_SIG (13560000.0) @@ -22,7 +20,7 @@ typedef struct { static uint8_t nfca_default_ats[] = {0x05, 0x78, 0x80, 0x80, 0x00}; -static uint8_t nfca_sleep_req[] = {0x50, 0x00}; +static uint8_t nfca_halt_req[] = {NFCA_CMD_HALT, 0x00}; uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) { uint16_t crc = NFCA_CRC_INIT; @@ -50,17 +48,17 @@ bool nfca_emulation_handler( uint16_t buff_rx_len, uint8_t* buff_tx, uint16_t* buff_tx_len) { - bool sleep = false; + bool halt = false; uint8_t rx_bytes = buff_rx_len / 8; - if(rx_bytes == sizeof(nfca_sleep_req) && !memcmp(buff_rx, nfca_sleep_req, rx_bytes)) { - sleep = true; + if(rx_bytes == sizeof(nfca_halt_req) && !memcmp(buff_rx, nfca_halt_req, rx_bytes)) { + halt = true; } else if(rx_bytes == sizeof(nfca_cmd_rats) && buff_rx[0] == NFCA_CMD_RATS) { memcpy(buff_tx, nfca_default_ats, sizeof(nfca_default_ats)); *buff_tx_len = sizeof(nfca_default_ats) * 8; } - return sleep; + return halt; } static void nfca_add_bit(DigitalSignal* signal, bool bit) { diff --git a/lib/nfc/protocols/nfca.h b/lib/nfc/protocols/nfca.h index 498ef2843..e4978a3e0 100644 --- a/lib/nfc/protocols/nfca.h +++ b/lib/nfc/protocols/nfca.h @@ -5,6 +5,9 @@ #include +#define NFCA_CMD_RATS (0xE0U) +#define NFCA_CMD_HALT (0x50U) + typedef struct { DigitalSignal* one; DigitalSignal* zero; From 1a283cde3eeab922eedfdda43b91e41286353397 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 03:03:10 +0300 Subject: [PATCH 32/40] Update changelog --- CHANGELOG.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37d8c680d..05aba5e16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ ## New changes +* SubGHz: Keeloq: Centurion Nova read and emulate support (+ add manually) +* SubGHz: FAAC SLH - UI Fixes, Fix sending signals with no seed +* SubGHz: Code cleanup, proper handling of protocols ignore options (by @gid9798 | PR #516) +* SubGHz: Various UI fixes (by @wosk | PR #527) +* NFC: Fixed issue #532 (Mifare classic user dict - delete removes more than selected key) +* Infrared: Updated universal remote assets (by @amec0e | PR #529) +* Plugins: Use correct categories for all plugins (extra pack too) +* Plugins: Various fixes for uFBT (by @hedger) +* Plugins: Moved Barcode Generator [(by Kingal1337)](https://github.com/Kingal1337/flipper-barcode-generator) from extra pack into base fw, old barcode generator was removed +* Plugins: Updated ESP32: WiFi Marauder companion plugin [(by 0xchocolate)](https://github.com/0xchocolate/flipperzero-wifi-marauder) +* Plugins: Updated i2c Tools [(by NaejEL)](https://github.com/NaejEL/flipperzero-i2ctools) +* Settings: Change LED and volume settings by 5% steps (by @cokyrain) +* BLE: BadBT fixes and furi_hal_bt cleanup (by @Willy-JL) +* WIP OFW PR 2825: NFC: Improved MFC emulation on some readers (by AloneLiberty) +* OFW PR 2829: Decode only supported Oregon 3 sensor (by @wosk) * OFW PR: Update OFW PR 2782 +* OFW: NFC: Mf Ultralight emulation optimization +* OFW: Furi_Power: fix furi_hal_power_enable_otg +* OFW: FuriHal: allow nulling null isr +* OFW: FuriHal, Infrared, Protobuf: various fixes and improvements +* OFW: Picopass fix ice +* OFW: Desktop settings: show icon and name for external applications +* OFW: Furi,FuriHal: various improvements +* OFW: Debug apps: speaker, uart_echo with baudrate * OFW: Add Mitsubishi MSZ-AP25VGK universal ac remote * OFW: Fix roll-over in file browser and archive * OFW: Fix fr-FR-mac keylayout From d8500510bed982f20a3ebfafdf48ceb62c5b87c0 Mon Sep 17 00:00:00 2001 From: Sergey Gavrilov Date: Thu, 6 Jul 2023 14:49:53 +0300 Subject: [PATCH 33/40] API: explicitly add math.h (#2852) * API: explicitly add math.h * sync target api versions --- firmware/targets/f18/api_symbols.csv | 218 +++++++++++++++++- firmware/targets/f7/api_symbols.csv | 3 +- .../f7/platform_specific/intrinsic_export.h | 1 + .../f7/platform_specific/math_wrapper.h | 2 + 4 files changed, 222 insertions(+), 2 deletions(-) create mode 100644 firmware/targets/f7/platform_specific/math_wrapper.h diff --git a/firmware/targets/f18/api_symbols.csv b/firmware/targets/f18/api_symbols.csv index 46099799b..62b237a51 100644 --- a/firmware/targets/f18/api_symbols.csv +++ b/firmware/targets/f18/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,33.0,, +Version,+,33.1,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -56,6 +56,7 @@ Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_types.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, +Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, Header,+,firmware/targets/furi_hal_include/furi_hal.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, @@ -289,12 +290,18 @@ Function,+,__assert_func,void,"const char*, int, const char*, const char*" Function,+,__clear_cache,void,"void*, void*" Function,-,__eprintf,void,"const char*, const char*, unsigned int, const char*" Function,+,__errno,int*, +Function,-,__fpclassifyd,int,double +Function,-,__fpclassifyf,int,float Function,+,__furi_crash,void, Function,+,__furi_critical_enter,__FuriCriticalInfo, Function,+,__furi_critical_exit,void,__FuriCriticalInfo Function,+,__furi_halt,void, Function,-,__getdelim,ssize_t,"char**, size_t*, int, FILE*" Function,-,__getline,ssize_t,"char**, size_t*, FILE*" +Function,-,__isinfd,int,double +Function,-,__isinff,int,float +Function,-,__isnand,int,double +Function,-,__isnanf,int,float Function,-,__itoa,char*,"int, char*, int" Function,-,__locale_mb_cur_max,int, Function,+,__retarget_lock_acquire,void,_LOCK_T @@ -307,6 +314,9 @@ Function,+,__retarget_lock_release,void,_LOCK_T Function,+,__retarget_lock_release_recursive,void,_LOCK_T Function,-,__retarget_lock_try_acquire,int,_LOCK_T Function,-,__retarget_lock_try_acquire_recursive,int,_LOCK_T +Function,-,__signbitd,int,double +Function,-,__signbitf,int,float +Function,-,__signgam,int*, Function,-,__srget_r,int,"_reent*, FILE*" Function,-,__swbuf_r,int,"_reent*, int, FILE*" Function,-,__utoa,char*,"unsigned, char*, int" @@ -459,6 +469,12 @@ Function,-,_wctomb_r,int,"_reent*, char*, wchar_t, _mbstate_t*" Function,-,a64l,long,const char* Function,+,abort,void, Function,-,abs,int,int +Function,-,acos,double,double +Function,-,acosf,float,float +Function,-,acosh,double,double +Function,-,acoshf,float,float +Function,-,acoshl,long double,long double +Function,-,acosl,long double,long double Function,-,aligned_alloc,void*,"size_t, size_t" Function,+,aligned_free,void,void* Function,+,aligned_malloc,void*,"size_t, size_t" @@ -474,11 +490,26 @@ Function,+,args_read_probably_quoted_string_and_trim,_Bool,"FuriString*, FuriStr Function,+,args_read_string_and_trim,_Bool,"FuriString*, FuriString*" Function,-,asctime,char*,const tm* Function,-,asctime_r,char*,"const tm*, char*" +Function,-,asin,double,double +Function,-,asinf,float,float +Function,-,asinh,double,double +Function,-,asinhf,float,float +Function,-,asinhl,long double,long double +Function,-,asinl,long double,long double Function,-,asiprintf,int,"char**, const char*, ..." Function,-,asniprintf,char*,"char*, size_t*, const char*, ..." Function,-,asnprintf,char*,"char*, size_t*, const char*, ..." Function,-,asprintf,int,"char**, const char*, ..." Function,-,at_quick_exit,int,void (*)() +Function,-,atan,double,double +Function,-,atan2,double,"double, double" +Function,-,atan2f,float,"float, float" +Function,-,atan2l,long double,"long double, long double" +Function,-,atanf,float,float +Function,-,atanh,double,double +Function,-,atanhf,float,float +Function,-,atanhl,long double,long double +Function,-,atanl,long double,long double Function,-,atexit,int,void (*)() Function,-,atof,double,const char* Function,-,atoff,float,const char* @@ -571,6 +602,12 @@ Function,+,canvas_set_font,void,"Canvas*, Font" Function,+,canvas_set_font_direction,void,"Canvas*, CanvasDirection" Function,+,canvas_string_width,uint16_t,"Canvas*, const char*" Function,+,canvas_width,uint8_t,const Canvas* +Function,-,cbrt,double,double +Function,-,cbrtf,float,float +Function,-,cbrtl,long double,long double +Function,-,ceil,double,double +Function,-,ceilf,float,float +Function,-,ceill,long double,long double Function,-,cfree,void,void* Function,-,clearerr,void,FILE* Function,-,clearerr_unlocked,void,FILE* @@ -591,6 +628,15 @@ Function,+,composite_api_resolver_add,void,"CompositeApiResolver*, const ElfApiI Function,+,composite_api_resolver_alloc,CompositeApiResolver*, Function,+,composite_api_resolver_free,void,CompositeApiResolver* Function,+,composite_api_resolver_get,const ElfApiInterface*,CompositeApiResolver* +Function,-,copysign,double,"double, double" +Function,-,copysignf,float,"float, float" +Function,-,copysignl,long double,"long double, long double" +Function,-,cos,double,double +Function,-,cosf,float,float +Function,-,cosh,double,double +Function,-,coshf,float,float +Function,-,coshl,long double,long double +Function,-,cosl,long double,long double Function,+,crc32_calc_buffer,uint32_t,"uint32_t, const void*, size_t" Function,+,crc32_calc_file,uint32_t,"File*, const FileCrcProgressCb, void*" Function,-,ctermid,char*,char* @@ -660,6 +706,8 @@ Function,+,dolphin_stats,DolphinStats,Dolphin* Function,+,dolphin_upgrade_level,void,Dolphin* Function,-,dprintf,int,"int, const char*, ..." Function,-,drand48,double, +Function,-,drem,double,"double, double" +Function,-,dremf,float,"float, float" Function,-,eTaskConfirmSleepModeStatus,eSleepModeStatus, Function,-,eTaskGetState,eTaskState,TaskHandle_t Function,+,elements_bold_rounded_frame,void,"Canvas*, uint8_t, uint8_t, uint8_t, uint8_t" @@ -687,10 +735,33 @@ Function,+,empty_screen_alloc,EmptyScreen*, Function,+,empty_screen_free,void,EmptyScreen* Function,+,empty_screen_get_view,View*,EmptyScreen* Function,-,erand48,double,unsigned short[3] +Function,-,erf,double,double +Function,-,erfc,double,double +Function,-,erfcf,float,float +Function,-,erfcl,long double,long double +Function,-,erff,float,float +Function,-,erfl,long double,long double Function,-,exit,void,int +Function,-,exp,double,double +Function,-,exp10,double,double +Function,-,exp10f,float,float +Function,-,exp2,double,double +Function,-,exp2f,float,float +Function,-,exp2l,long double,long double +Function,-,expf,float,float +Function,-,expl,long double,long double Function,-,explicit_bzero,void,"void*, size_t" +Function,-,expm1,double,double +Function,-,expm1f,float,float +Function,-,expm1l,long double,long double +Function,-,fabs,double,double +Function,-,fabsf,float,float +Function,-,fabsl,long double,long double Function,-,fclose,int,FILE* Function,-,fcloseall,int, +Function,-,fdim,double,"double, double" +Function,-,fdimf,float,"float, float" +Function,-,fdiml,long double,"long double, long double" Function,-,fdopen,FILE*,"int, const char*" Function,-,feof,int,FILE* Function,-,feof_unlocked,int,FILE* @@ -735,6 +806,9 @@ Function,+,file_stream_open,_Bool,"Stream*, const char*, FS_AccessMode, FS_OpenM Function,-,fileno,int,FILE* Function,-,fileno_unlocked,int,FILE* Function,+,filesystem_api_error_get_desc,const char*,FS_Error +Function,-,finite,int,double +Function,-,finitef,int,float +Function,-,finitel,int,long double Function,-,fiprintf,int,"FILE*, const char*, ..." Function,-,fiscanf,int,"FILE*, const char*, ..." Function,+,flipper_application_alloc,FlipperApplication*,"Storage*, const ElfApiInterface*" @@ -812,10 +886,25 @@ Function,+,flipper_format_write_string_cstr,_Bool,"FlipperFormat*, const char*, Function,+,flipper_format_write_uint32,_Bool,"FlipperFormat*, const char*, const uint32_t*, const uint16_t" Function,+,float_is_equal,_Bool,"float, float" Function,-,flockfile,void,FILE* +Function,-,floor,double,double +Function,-,floorf,float,float +Function,-,floorl,long double,long double Function,-,fls,int,int Function,-,flsl,int,long Function,-,flsll,int,long long +Function,-,fma,double,"double, double, double" +Function,-,fmaf,float,"float, float, float" +Function,-,fmal,long double,"long double, long double, long double" +Function,-,fmax,double,"double, double" +Function,-,fmaxf,float,"float, float" +Function,-,fmaxl,long double,"long double, long double" Function,-,fmemopen,FILE*,"void*, size_t, const char*" +Function,-,fmin,double,"double, double" +Function,-,fminf,float,"float, float" +Function,-,fminl,long double,"long double, long double" +Function,-,fmod,double,"double, double" +Function,-,fmodf,float,"float, float" +Function,-,fmodl,long double,"long double, long double" Function,-,fopen,FILE*,"const char*, const char*" Function,-,fopencookie,FILE*,"void*, const char*, cookie_io_functions_t" Function,-,fprintf,int,"FILE*, const char*, ..." @@ -828,6 +917,9 @@ Function,-,fread,size_t,"void*, size_t, size_t, FILE*" Function,-,fread_unlocked,size_t,"void*, size_t, size_t, FILE*" Function,+,free,void,void* Function,-,freopen,FILE*,"const char*, const char*, FILE*" +Function,-,frexp,double,"double, int*" +Function,-,frexpf,float,"float, int*" +Function,-,frexpl,long double,"long double, int*" Function,-,fscanf,int,"FILE*, const char*, ..." Function,-,fseek,int,"FILE*, long, int" Function,-,fseeko,int,"FILE*, off_t, int" @@ -1338,6 +1430,10 @@ Function,+,furi_timer_start,FuriStatus,"FuriTimer*, uint32_t" Function,+,furi_timer_stop,FuriStatus,FuriTimer* Function,-,fwrite,size_t,"const void*, size_t, size_t, FILE*" Function,-,fwrite_unlocked,size_t,"const void*, size_t, size_t, FILE*" +Function,-,gamma,double,double +Function,-,gamma_r,double,"double, int*" +Function,-,gammaf,float,float +Function,-,gammaf_r,float,"float, int*" Function,-,gap_get_state,GapState, Function,-,gap_init,_Bool,"GapConfig*, GapEventCallback, void*" Function,-,gap_start_advertising,void, @@ -1370,6 +1466,9 @@ Function,+,hex_char_to_hex_nibble,_Bool,"char, uint8_t*" Function,+,hex_char_to_uint8,_Bool,"char, char, uint8_t*" Function,+,hex_chars_to_uint64,_Bool,"const char*, uint64_t*" Function,+,hex_chars_to_uint8,_Bool,"const char*, uint8_t*" +Function,-,hypot,double,"double, double" +Function,-,hypotf,float,"float, float" +Function,-,hypotl,long double,"long double, long double" Function,+,icon_animation_alloc,IconAnimation*,const Icon* Function,+,icon_animation_free,void,IconAnimation* Function,+,icon_animation_get_height,uint8_t,const IconAnimation* @@ -1381,7 +1480,12 @@ Function,+,icon_animation_stop,void,IconAnimation* Function,+,icon_get_data,const uint8_t*,const Icon* Function,+,icon_get_height,uint8_t,const Icon* Function,+,icon_get_width,uint8_t,const Icon* +Function,-,ilogb,int,double +Function,-,ilogbf,int,float +Function,-,ilogbl,int,long double Function,-,index,char*,"const char*, int" +Function,-,infinity,double, +Function,-,infinityf,float, Function,-,initstate,char*,"unsigned, char*, size_t" Function,+,input_get_key_name,const char*,InputKey Function,+,input_get_type_name,const char*,InputType @@ -1401,8 +1505,12 @@ Function,-,isdigit,int,int Function,-,isdigit_l,int,"int, locale_t" Function,-,isgraph,int,int Function,-,isgraph_l,int,"int, locale_t" +Function,-,isinf,int,double +Function,-,isinff,int,float Function,-,islower,int,int Function,-,islower_l,int,"int, locale_t" +Function,-,isnan,int,double +Function,-,isnanf,int,float Function,-,isprint,int,int Function,-,isprint_l,int,"int, locale_t" Function,-,ispunct,int,int @@ -1414,13 +1522,33 @@ Function,-,isupper_l,int,"int, locale_t" Function,-,isxdigit,int,int Function,-,isxdigit_l,int,"int, locale_t" Function,-,itoa,char*,"int, char*, int" +Function,-,j0,double,double +Function,-,j0f,float,float +Function,-,j1,double,double +Function,-,j1f,float,float +Function,-,jn,double,"int, double" +Function,-,jnf,float,"int, float" Function,-,jrand48,long,unsigned short[3] Function,-,l64a,char*,long Function,-,labs,long,long Function,-,lcong48,void,unsigned short[7] +Function,-,ldexp,double,"double, int" +Function,-,ldexpf,float,"float, int" +Function,-,ldexpl,long double,"long double, int" Function,-,ldiv,ldiv_t,"long, long" +Function,-,lgamma,double,double +Function,-,lgamma_r,double,"double, int*" +Function,-,lgammaf,float,float +Function,-,lgammaf_r,float,"float, int*" +Function,-,lgammal,long double,long double Function,-,llabs,long long,long long Function,-,lldiv,lldiv_t,"long long, long long" +Function,-,llrint,long long int,double +Function,-,llrintf,long long int,float +Function,-,llrintl,long long int,long double +Function,-,llround,long long int,double +Function,-,llroundf,long long int,float +Function,-,llroundl,long long int,long double Function,+,loader_get_pubsub,FuriPubSub*,Loader* Function,+,loader_is_locked,_Bool,Loader* Function,+,loader_lock,_Bool,Loader* @@ -1443,7 +1571,28 @@ Function,+,locale_set_measurement_unit,void,LocaleMeasurementUnits Function,+,locale_set_time_format,void,LocaleTimeFormat Function,-,localtime,tm*,const time_t* Function,-,localtime_r,tm*,"const time_t*, tm*" +Function,-,log,double,double +Function,-,log10,double,double +Function,-,log10f,float,float +Function,-,log10l,long double,long double +Function,-,log1p,double,double +Function,-,log1pf,float,float +Function,-,log1pl,long double,long double +Function,-,log2,double,double +Function,-,log2f,float,float +Function,-,log2l,long double,long double +Function,-,logb,double,double +Function,-,logbf,float,float +Function,-,logbl,long double,long double +Function,-,logf,float,float +Function,-,logl,long double,long double Function,-,lrand48,long, +Function,-,lrint,long int,double +Function,-,lrintf,long int,float +Function,-,lrintl,long int,long double +Function,-,lround,long int,double +Function,-,lroundf,long int,float +Function,-,lroundl,long,long double Function,+,malloc,void*,size_t Function,+,manchester_advance,_Bool,"ManchesterState, ManchesterEvent, ManchesterState*, _Bool*" Function,+,manchester_encoder_advance,_Bool,"ManchesterEncoderState*, const _Bool, ManchesterEncoderResult*" @@ -1521,6 +1670,9 @@ Function,-,mkstemp,int,char* Function,-,mkstemps,int,"char*, int" Function,-,mktemp,char*,char* Function,-,mktime,time_t,tm* +Function,-,modf,double,"double, double*" +Function,-,modff,float,"float, float*" +Function,-,modfl,long double,"long double, long double*" Function,-,mrand48,long, Function,-,music_worker_alloc,MusicWorker*, Function,-,music_worker_clear,void,MusicWorker* @@ -1534,6 +1686,18 @@ Function,-,music_worker_set_callback,void,"MusicWorker*, MusicWorkerCallback, vo Function,-,music_worker_set_volume,void,"MusicWorker*, float" Function,-,music_worker_start,void,MusicWorker* Function,-,music_worker_stop,void,MusicWorker* +Function,-,nan,double,const char* +Function,-,nanf,float,const char* +Function,-,nanl,long double,const char* +Function,-,nearbyint,double,double +Function,-,nearbyintf,float,float +Function,-,nearbyintl,long double,long double +Function,-,nextafter,double,"double, double" +Function,-,nextafterf,float,"float, float" +Function,-,nextafterl,long double,"long double, long double" +Function,-,nexttoward,double,"double, long double" +Function,-,nexttowardf,float,"float, long double" +Function,-,nexttowardl,long double,"long double, long double" Function,+,notification_internal_message,void,"NotificationApp*, const NotificationSequence*" Function,+,notification_internal_message_block,void,"NotificationApp*, const NotificationSequence*" Function,+,notification_message,void,"NotificationApp*, const NotificationSequence*" @@ -1601,12 +1765,17 @@ Function,+,popup_set_icon,void,"Popup*, uint8_t, uint8_t, const Icon*" Function,+,popup_set_text,void,"Popup*, const char*, uint8_t, uint8_t, Align, Align" Function,+,popup_set_timeout,void,"Popup*, uint32_t" Function,-,posix_memalign,int,"void**, size_t, size_t" +Function,-,pow,double,"double, double" +Function,-,pow10,double,double +Function,-,pow10f,float,float Function,+,power_enable_low_battery_level_notification,void,"Power*, _Bool" Function,+,power_get_info,void,"Power*, PowerInfo*" Function,+,power_get_pubsub,FuriPubSub*,Power* Function,+,power_is_battery_healthy,_Bool,Power* Function,+,power_off,void,Power* Function,+,power_reboot,void,PowerBootMode +Function,+,powf,float,"float, float" +Function,-,powl,long double,"long double, long double" Function,+,pretty_format_bytes_hex_canonical,void,"FuriString*, size_t, const char*, const uint8_t*, size_t" Function,-,printf,int,"const char*, ..." Function,+,property_value_out,void,"PropertyValueContext*, const char*, unsigned int, ..." @@ -1664,11 +1833,23 @@ Function,+,realloc,void*,"void*, size_t" Function,-,reallocarray,void*,"void*, size_t, size_t" Function,-,reallocf,void*,"void*, size_t" Function,-,realpath,char*,"const char*, char*" +Function,-,remainder,double,"double, double" +Function,-,remainderf,float,"float, float" +Function,-,remainderl,long double,"long double, long double" Function,-,remove,int,const char* +Function,-,remquo,double,"double, double, int*" +Function,-,remquof,float,"float, float, int*" +Function,-,remquol,long double,"long double, long double, int*" Function,-,rename,int,"const char*, const char*" Function,-,renameat,int,"int, const char*, int, const char*" Function,-,rewind,void,FILE* Function,-,rindex,char*,"const char*, int" +Function,-,rint,double,double +Function,-,rintf,float,float +Function,-,rintl,long double,long double +Function,-,round,double,double +Function,+,roundf,float,float +Function,-,roundl,long double,long double Function,+,rpc_session_close,void,RpcSession* Function,+,rpc_session_feed,size_t,"RpcSession*, uint8_t*, size_t, TickType_t" Function,+,rpc_session_get_available_size,size_t,RpcSession* @@ -1693,6 +1874,12 @@ Function,-,rpmatch,int,const char* Function,+,saved_struct_get_payload_size,_Bool,"const char*, uint8_t, uint8_t, size_t*" Function,+,saved_struct_load,_Bool,"const char*, void*, size_t, uint8_t, uint8_t" Function,+,saved_struct_save,_Bool,"const char*, void*, size_t, uint8_t, uint8_t" +Function,-,scalbln,double,"double, long int" +Function,-,scalblnf,float,"float, long int" +Function,-,scalblnl,long double,"long double, long" +Function,-,scalbn,double,"double, int" +Function,+,scalbnf,float,"float, int" +Function,-,scalbnl,long double,"long double, int" Function,-,scanf,int,"const char*, ..." Function,+,scene_manager_alloc,SceneManager*,"const SceneManagerHandlers*, void*" Function,+,scene_manager_free,void,SceneManager* @@ -1732,11 +1919,22 @@ Function,+,sha256_finish,void,"sha256_context*, unsigned char[32]" Function,+,sha256_process,void,sha256_context* Function,+,sha256_start,void,sha256_context* Function,+,sha256_update,void,"sha256_context*, const unsigned char*, unsigned int" +Function,-,sin,double,double +Function,-,sincos,void,"double, double*, double*" +Function,-,sincosf,void,"float, float*, float*" +Function,-,sinf,float,float +Function,-,sinh,double,double +Function,-,sinhf,float,float +Function,-,sinhl,long double,long double +Function,-,sinl,long double,long double Function,-,siprintf,int,"char*, const char*, ..." Function,-,siscanf,int,"const char*, const char*, ..." Function,-,sniprintf,int,"char*, size_t, const char*, ..." Function,+,snprintf,int,"char*, size_t, const char*, ..." Function,-,sprintf,int,"char*, const char*, ..." +Function,-,sqrt,double,double +Function,-,sqrtf,float,float +Function,-,sqrtl,long double,long double Function,+,srand,void,unsigned Function,-,srand48,void,long Function,-,srandom,void,unsigned @@ -1891,6 +2089,12 @@ Function,+,submenu_reset,void,Submenu* Function,+,submenu_set_header,void,"Submenu*, const char*" Function,+,submenu_set_selected_item,void,"Submenu*, uint32_t" Function,-,system,int,const char* +Function,-,tan,double,double +Function,-,tanf,float,float +Function,-,tanh,double,double +Function,-,tanhf,float,float +Function,-,tanhl,long double,long double +Function,-,tanl,long double,long double Function,+,tar_archive_add_dir,_Bool,"TarArchive*, const char*, const char*" Function,+,tar_archive_add_file,_Bool,"TarArchive*, const char*, const char*, const int32_t" Function,+,tar_archive_alloc,TarArchive*,Storage* @@ -1923,6 +2127,9 @@ Function,+,text_input_reset,void,TextInput* Function,+,text_input_set_header_text,void,"TextInput*, const char*" Function,+,text_input_set_result_callback,void,"TextInput*, TextInputCallback, void*, char*, size_t, _Bool" Function,+,text_input_set_validator,void,"TextInput*, TextInputValidatorCallback, void*" +Function,-,tgamma,double,double +Function,-,tgammaf,float,float +Function,-,tgammal,long double,long double Function,-,time,time_t,time_t* Function,-,timingsafe_bcmp,int,"const void*, const void*, size_t" Function,-,timingsafe_memcmp,int,"const void*, const void*, size_t" @@ -1934,6 +2141,9 @@ Function,-,tolower,int,int Function,-,tolower_l,int,"int, locale_t" Function,-,toupper,int,int Function,-,toupper_l,int,"int, locale_t" +Function,-,trunc,double,double +Function,-,truncf,float,float +Function,-,truncl,long double,long double Function,-,tzset,void, Function,-,uECC_compress,void,"const uint8_t*, uint8_t*, uECC_Curve" Function,+,uECC_compute_public_key,int,"const uint8_t*, uint8_t*, uECC_Curve" @@ -2166,6 +2376,12 @@ Function,-,xTimerGetTimerDaemonTaskHandle,TaskHandle_t, Function,-,xTimerIsTimerActive,BaseType_t,TimerHandle_t Function,-,xTimerPendFunctionCall,BaseType_t,"PendedFunction_t, void*, uint32_t, TickType_t" Function,-,xTimerPendFunctionCallFromISR,BaseType_t,"PendedFunction_t, void*, uint32_t, BaseType_t*" +Function,-,y0,double,double +Function,-,y0f,float,float +Function,-,y1,double,double +Function,-,y1f,float,float +Function,-,yn,double,"int, double" +Function,-,ynf,float,"int, float" Variable,-,AHBPrescTable,const uint32_t[16], Variable,-,APBPrescTable,const uint32_t[8], Variable,-,ITM_RxBuffer,volatile int32_t, diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index dbaeb8e4c..a44e663ba 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,33.0,, +Version,+,33.1,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -60,6 +60,7 @@ Header,+,firmware/targets/f7/furi_hal/furi_hal_target_hw.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, +Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, Header,+,firmware/targets/furi_hal_include/furi_hal.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, diff --git a/firmware/targets/f7/platform_specific/intrinsic_export.h b/firmware/targets/f7/platform_specific/intrinsic_export.h index ca343a128..d3c7be5e0 100644 --- a/firmware/targets/f7/platform_specific/intrinsic_export.h +++ b/firmware/targets/f7/platform_specific/intrinsic_export.h @@ -1,3 +1,4 @@ +#pragma once #include #include diff --git a/firmware/targets/f7/platform_specific/math_wrapper.h b/firmware/targets/f7/platform_specific/math_wrapper.h new file mode 100644 index 000000000..83f5a8b75 --- /dev/null +++ b/firmware/targets/f7/platform_specific/math_wrapper.h @@ -0,0 +1,2 @@ +#pragma once +#include \ No newline at end of file From 55149f6d4ca43c4f44b0b98f81217a21b743aa88 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 16:58:53 +0300 Subject: [PATCH 34/40] Move --- applications/external/multi_fuzzer/application.fam | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/applications/external/multi_fuzzer/application.fam b/applications/external/multi_fuzzer/application.fam index 1fa33943f..b5205803d 100644 --- a/applications/external/multi_fuzzer/application.fam +++ b/applications/external/multi_fuzzer/application.fam @@ -37,7 +37,7 @@ App( ], stack_size=2 * 1024, fap_icon="icons/rfid_10px.png", - fap_category="RFID 125", + fap_category="RFID", fap_private_libs=[ Lib( name="worker", From f81f4edad36f3af488df97b6320102a580906215 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 17:42:18 +0300 Subject: [PATCH 35/40] Fix loader hangup on exit if api mismatch happened --- applications/services/loader/loader.c | 5 ++++- applications/services/loader/loader.h | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/applications/services/loader/loader.c b/applications/services/loader/loader.c index 833954bf7..94b699748 100644 --- a/applications/services/loader/loader.c +++ b/applications/services/loader/loader.c @@ -273,7 +273,7 @@ static LoaderStatus loader_start_external_app( DialogMessage* message = dialog_message_alloc(); dialog_message_set_header( message, "API Mismatch", 64, 0, AlignCenter, AlignTop); - dialog_message_set_buttons(message, "Cancel", NULL, "Continue"); + dialog_message_set_buttons(message, NULL, NULL, "Continue"); dialog_message_set_text( message, "This app might not\nwork correctly\nContinue anyways?", @@ -284,6 +284,9 @@ static LoaderStatus loader_start_external_app( if(dialog_message_show(dialogs, message) == DialogMessageButtonRight) { status = loader_make_status_error( LoaderStatusErrorApiMismatch, error_message, "API Mismatch"); + } else { + status = loader_make_status_error( + LoaderStatusErrorApiMismatchExit, error_message, "API Mismatch"); } dialog_message_free(message); furi_record_close(RECORD_DIALOGS); diff --git a/applications/services/loader/loader.h b/applications/services/loader/loader.h index 550d3d508..62c198b37 100644 --- a/applications/services/loader/loader.h +++ b/applications/services/loader/loader.h @@ -16,6 +16,7 @@ typedef enum { LoaderStatusErrorUnknownApp, LoaderStatusErrorInternal, LoaderStatusErrorApiMismatch, + LoaderStatusErrorApiMismatchExit, } LoaderStatus; typedef enum { From cef59887ed367d4d1d22274de42996e385eedaea Mon Sep 17 00:00:00 2001 From: Skorpionm <85568270+Skorpionm@users.noreply.github.com> Date: Thu, 6 Jul 2023 19:15:03 +0400 Subject: [PATCH 36/40] [FL-3401, FL-3402] SubGhz: add "SubGhz test" external application and the ability to work "SubGhz" as an external application (#2851) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FL-3401] SubGhz: add "SubGhz test" external application * SubGhz: delete test test functionality from SubGhz app * [FL-3402] SubGhz: move func protocol creation API Co-authored-by: あく --- .../debug/subghz_test/application.fam | 14 + .../subghz_test/helpers/subghz_test_event.h | 7 + .../helpers/subghz_test_frequency.c} | 2 +- .../helpers/subghz_test_frequency.h} | 2 +- .../subghz_test/helpers/subghz_test_types.h | 18 ++ .../images/DolphinCommon_56x48.png | Bin 0 -> 1416 bytes .../debug/subghz_test/protocol/math.c | 244 ++++++++++++++++++ .../debug/subghz_test/protocol/math.h | 222 ++++++++++++++++ .../protocol}/princeton_for_testing.c | 2 +- .../protocol}/princeton_for_testing.h | 4 +- .../subghz_test/scenes/subghz_test_scene.c | 30 +++ .../subghz_test/scenes/subghz_test_scene.h | 29 +++ .../scenes/subghz_test_scene_about.c | 66 +++++ .../scenes/subghz_test_scene_carrier.c | 29 +++ .../scenes/subghz_test_scene_config.h | 6 + .../scenes/subghz_test_scene_packet.c | 29 +++ .../scenes/subghz_test_scene_show_only_rx.c | 49 ++++ .../scenes/subghz_test_scene_start.c | 77 ++++++ .../scenes/subghz_test_scene_static.c | 29 +++ .../debug/subghz_test/subghz_test_10px.png | Bin 0 -> 181 bytes .../debug/subghz_test/subghz_test_app.c | 139 ++++++++++ .../debug/subghz_test/subghz_test_app_i.c | 5 + .../debug/subghz_test/subghz_test_app_i.h | 32 +++ .../subghz_test}/views/subghz_test_carrier.c | 4 +- .../subghz_test}/views/subghz_test_carrier.h | 0 .../subghz_test}/views/subghz_test_packet.c | 6 +- .../subghz_test}/views/subghz_test_packet.h | 0 .../subghz_test}/views/subghz_test_static.c | 6 +- .../subghz_test}/views/subghz_test_static.h | 0 .../main/subghz/helpers/subghz_types.h | 3 - .../main/subghz/scenes/subghz_scene_config.h | 4 - .../main/subghz/scenes/subghz_scene_start.c | 10 - .../main/subghz/scenes/subghz_scene_test.c | 61 ----- .../subghz/scenes/subghz_scene_test_carrier.c | 30 --- .../subghz/scenes/subghz_scene_test_packet.c | 30 --- .../subghz/scenes/subghz_scene_test_static.c | 30 --- applications/main/subghz/subghz.c | 33 --- applications/main/subghz/subghz_i.h | 7 - firmware/targets/f7/api_symbols.csv | 8 +- lib/subghz/subghz_protocol_registry.h | 25 ++ 40 files changed, 1070 insertions(+), 222 deletions(-) create mode 100644 applications/debug/subghz_test/application.fam create mode 100644 applications/debug/subghz_test/helpers/subghz_test_event.h rename applications/{main/subghz/helpers/subghz_testing.c => debug/subghz_test/helpers/subghz_test_frequency.c} (95%) rename applications/{main/subghz/helpers/subghz_testing.h => debug/subghz_test/helpers/subghz_test_frequency.h} (84%) create mode 100644 applications/debug/subghz_test/helpers/subghz_test_types.h create mode 100644 applications/debug/subghz_test/images/DolphinCommon_56x48.png create mode 100644 applications/debug/subghz_test/protocol/math.c create mode 100644 applications/debug/subghz_test/protocol/math.h rename {lib/subghz/protocols => applications/debug/subghz_test/protocol}/princeton_for_testing.c (99%) rename {lib/subghz/protocols => applications/debug/subghz_test/protocol}/princeton_for_testing.h (97%) create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene.h create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_about.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_carrier.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_config.h create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_packet.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_show_only_rx.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_start.c create mode 100644 applications/debug/subghz_test/scenes/subghz_test_scene_static.c create mode 100644 applications/debug/subghz_test/subghz_test_10px.png create mode 100644 applications/debug/subghz_test/subghz_test_app.c create mode 100644 applications/debug/subghz_test/subghz_test_app_i.c create mode 100644 applications/debug/subghz_test/subghz_test_app_i.h rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_carrier.c (98%) rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_carrier.h (100%) rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_packet.c (98%) rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_packet.h (100%) rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_static.c (98%) rename applications/{main/subghz => debug/subghz_test}/views/subghz_test_static.h (100%) delete mode 100644 applications/main/subghz/scenes/subghz_scene_test.c delete mode 100644 applications/main/subghz/scenes/subghz_scene_test_carrier.c delete mode 100644 applications/main/subghz/scenes/subghz_scene_test_packet.c delete mode 100644 applications/main/subghz/scenes/subghz_scene_test_static.c diff --git a/applications/debug/subghz_test/application.fam b/applications/debug/subghz_test/application.fam new file mode 100644 index 000000000..1b3e19d73 --- /dev/null +++ b/applications/debug/subghz_test/application.fam @@ -0,0 +1,14 @@ +App( + appid="subghz_test", + name="Sub-Ghz test", + apptype=FlipperAppType.DEBUG, + targets=["f7"], + entry_point="subghz_test_app", + requires=["gui"], + stack_size=4 * 1024, + order=50, + fap_icon="subghz_test_10px.png", + fap_category="Debug", + fap_icon_assets="images", + fap_version="0.1", +) diff --git a/applications/debug/subghz_test/helpers/subghz_test_event.h b/applications/debug/subghz_test/helpers/subghz_test_event.h new file mode 100644 index 000000000..a0a851976 --- /dev/null +++ b/applications/debug/subghz_test/helpers/subghz_test_event.h @@ -0,0 +1,7 @@ +#pragma once + +typedef enum { + //SubGhzTestCustomEvent + SubGhzTestCustomEventStartId = 100, + SubGhzTestCustomEventSceneShowOnlyRX, +} SubGhzTestCustomEvent; diff --git a/applications/main/subghz/helpers/subghz_testing.c b/applications/debug/subghz_test/helpers/subghz_test_frequency.c similarity index 95% rename from applications/main/subghz/helpers/subghz_testing.c rename to applications/debug/subghz_test/helpers/subghz_test_frequency.c index 8afa868e0..ed1ba704e 100644 --- a/applications/main/subghz/helpers/subghz_testing.c +++ b/applications/debug/subghz_test/helpers/subghz_test_frequency.c @@ -1,4 +1,4 @@ -#include "subghz_testing.h" +#include "subghz_test_frequency.h" const uint32_t subghz_frequencies_testing[] = { /* 300 - 348 */ diff --git a/applications/main/subghz/helpers/subghz_testing.h b/applications/debug/subghz_test/helpers/subghz_test_frequency.h similarity index 84% rename from applications/main/subghz/helpers/subghz_testing.h rename to applications/debug/subghz_test/helpers/subghz_test_frequency.h index 29ce578a0..7dd1423f9 100644 --- a/applications/main/subghz/helpers/subghz_testing.h +++ b/applications/debug/subghz_test/helpers/subghz_test_frequency.h @@ -1,5 +1,5 @@ #pragma once -#include "../subghz_i.h" +#include "../subghz_test_app_i.h" extern const uint32_t subghz_frequencies_testing[]; extern const uint32_t subghz_frequencies_count_testing; diff --git a/applications/debug/subghz_test/helpers/subghz_test_types.h b/applications/debug/subghz_test/helpers/subghz_test_types.h new file mode 100644 index 000000000..03be6459e --- /dev/null +++ b/applications/debug/subghz_test/helpers/subghz_test_types.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +#define SUBGHZ_TEST_VERSION_APP "0.1" +#define SUBGHZ_TEST_DEVELOPED "SkorP" +#define SUBGHZ_TEST_GITHUB "https://github.com/flipperdevices/flipperzero-firmware" + +typedef enum { + SubGhzTestViewVariableItemList, + SubGhzTestViewSubmenu, + SubGhzTestViewStatic, + SubGhzTestViewCarrier, + SubGhzTestViewPacket, + SubGhzTestViewWidget, + SubGhzTestViewPopup, +} SubGhzTestView; diff --git a/applications/debug/subghz_test/images/DolphinCommon_56x48.png b/applications/debug/subghz_test/images/DolphinCommon_56x48.png new file mode 100644 index 0000000000000000000000000000000000000000..089aaed83507431993a76ca25d32fdd9664c1c84 GIT binary patch literal 1416 zcmaJ>eNYr-7(dh;KXS5&nWVIBjS_NizYg|x=Pr^vz*7zxJO|P-dw2IeZq?gec9-rD zoPZchQ_6}yP{Slc4I!!28K==nodOJ_nsCY-(wOq2uZbLx!rlYU{KIi)_Wj!D_j`WN z^FGgREXdEDF)ewT&1Re7Tj(uBvlG44lnH3;I%IzsO|z`*Vr!`uv?9QOwgs{#Ld+Ki zC9n_zxxBOkx@@+IwMwAaD)#3Ik`}gun2kLe))Crfb7e+#AgzHGCc+X$b>qJuIf`S7 z?8b}I{ghw#z>uiaLknQh@LJUrqHcVYS3v97F^OZN zCe|7^J|?QzUx0Zu17e(=CM1fYFpjtLk|a4~$g}e?hGH0!VoBOT&<=s(1ct%J9~?O} z$)jW_dkX9yTX~%W*i_IM%0{ z7EmP^_pKn`<5>E(SixgJU};7`)7Hidp&+DLnizsebUk}_-GfgbN^il9b`v)f+ z{o5Zry)d<7`fHQ^uw_;+x>mcPw0&8iW69x{k92O{Q}`yFdH=5d$pbf49w1&NS)G+vhr6y}5TMsofQirRDUmKilk5=(KGouJ{H9hW=$X zgi;)vI!jl!_4H3jD(?Jz=8By|i47I&tKA1y9{nfp;_|FxKBDNWp{hN9hJ1nU?z%J6 z?>UxyzWvO}Pgc~rCZ#5%Eq+_hNS~bBdiGlT&f%%e`hHjSySR2=JuK2^+%;$R3#Wz~ z=e_mfqW23bPa0fhe)HdE5+GelU&!jS3ckUZOQ)CC5?mo zo=tzG_4|RuvPUO|mhCwA>y)1c%SWC%a4?a-x|J*?ch~+n=R7o@>p6J2dE=$stKZmK z-xoTRwET2^Wu)&1U7!Ebw!!D?x`xwQX3pMnrRwCT?`4GHt4&?|cIiI{_^XYp-np>6 xE^lPSXzOYCC4X`6tl@OB1M5_S7jml-Y~(TPp{aTIejNKZ`m*!Atyxdk{0EAy49frj literal 0 HcmV?d00001 diff --git a/applications/debug/subghz_test/protocol/math.c b/applications/debug/subghz_test/protocol/math.c new file mode 100644 index 000000000..24202ad1c --- /dev/null +++ b/applications/debug/subghz_test/protocol/math.c @@ -0,0 +1,244 @@ +#include "math.h" + +uint64_t subghz_protocol_blocks_reverse_key(uint64_t key, uint8_t bit_count) { + uint64_t reverse_key = 0; + for(uint8_t i = 0; i < bit_count; i++) { + reverse_key = reverse_key << 1 | bit_read(key, i); + } + return reverse_key; +} + +uint8_t subghz_protocol_blocks_get_parity(uint64_t key, uint8_t bit_count) { + uint8_t parity = 0; + for(uint8_t i = 0; i < bit_count; i++) { + parity += bit_read(key, i); + } + return parity & 0x01; +} + +uint8_t subghz_protocol_blocks_crc4( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init) { + uint8_t remainder = init << 4; // LSBs are unused + uint8_t poly = polynomial << 4; + uint8_t bit; + + while(size--) { + remainder ^= *message++; + for(bit = 0; bit < 8; bit++) { + if(remainder & 0x80) { + remainder = (remainder << 1) ^ poly; + } else { + remainder = (remainder << 1); + } + } + } + return remainder >> 4 & 0x0f; // discard the LSBs +} + +uint8_t subghz_protocol_blocks_crc7( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init) { + uint8_t remainder = init << 1; // LSB is unused + uint8_t poly = polynomial << 1; + + for(size_t byte = 0; byte < size; ++byte) { + remainder ^= message[byte]; + for(uint8_t bit = 0; bit < 8; ++bit) { + if(remainder & 0x80) { + remainder = (remainder << 1) ^ poly; + } else { + remainder = (remainder << 1); + } + } + } + return remainder >> 1 & 0x7f; // discard the LSB +} + +uint8_t subghz_protocol_blocks_crc8( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init) { + uint8_t remainder = init; + + for(size_t byte = 0; byte < size; ++byte) { + remainder ^= message[byte]; + for(uint8_t bit = 0; bit < 8; ++bit) { + if(remainder & 0x80) { + remainder = (remainder << 1) ^ polynomial; + } else { + remainder = (remainder << 1); + } + } + } + return remainder; +} + +uint8_t subghz_protocol_blocks_crc8le( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init) { + uint8_t remainder = subghz_protocol_blocks_reverse_key(init, 8); + polynomial = subghz_protocol_blocks_reverse_key(polynomial, 8); + + for(size_t byte = 0; byte < size; ++byte) { + remainder ^= message[byte]; + for(uint8_t bit = 0; bit < 8; ++bit) { + if(remainder & 1) { + remainder = (remainder >> 1) ^ polynomial; + } else { + remainder = (remainder >> 1); + } + } + } + return remainder; +} + +uint16_t subghz_protocol_blocks_crc16lsb( + uint8_t const message[], + size_t size, + uint16_t polynomial, + uint16_t init) { + uint16_t remainder = init; + + for(size_t byte = 0; byte < size; ++byte) { + remainder ^= message[byte]; + for(uint8_t bit = 0; bit < 8; ++bit) { + if(remainder & 1) { + remainder = (remainder >> 1) ^ polynomial; + } else { + remainder = (remainder >> 1); + } + } + } + return remainder; +} + +uint16_t subghz_protocol_blocks_crc16( + uint8_t const message[], + size_t size, + uint16_t polynomial, + uint16_t init) { + uint16_t remainder = init; + + for(size_t byte = 0; byte < size; ++byte) { + remainder ^= message[byte] << 8; + for(uint8_t bit = 0; bit < 8; ++bit) { + if(remainder & 0x8000) { + remainder = (remainder << 1) ^ polynomial; + } else { + remainder = (remainder << 1); + } + } + } + return remainder; +} + +uint8_t subghz_protocol_blocks_lfsr_digest8( + uint8_t const message[], + size_t size, + uint8_t gen, + uint8_t key) { + uint8_t sum = 0; + for(size_t byte = 0; byte < size; ++byte) { + uint8_t data = message[byte]; + for(int i = 7; i >= 0; --i) { + // XOR key into sum if data bit is set + if((data >> i) & 1) sum ^= key; + + // roll the key right (actually the LSB is dropped here) + // and apply the gen (needs to include the dropped LSB as MSB) + if(key & 1) + key = (key >> 1) ^ gen; + else + key = (key >> 1); + } + } + return sum; +} + +uint8_t subghz_protocol_blocks_lfsr_digest8_reflect( + uint8_t const message[], + size_t size, + uint8_t gen, + uint8_t key) { + uint8_t sum = 0; + // Process message from last byte to first byte (reflected) + for(int byte = size - 1; byte >= 0; --byte) { + uint8_t data = message[byte]; + // Process individual bits of each byte (reflected) + for(uint8_t i = 0; i < 8; ++i) { + // XOR key into sum if data bit is set + if((data >> i) & 1) { + sum ^= key; + } + + // roll the key left (actually the LSB is dropped here) + // and apply the gen (needs to include the dropped lsb as MSB) + if(key & 0x80) + key = (key << 1) ^ gen; + else + key = (key << 1); + } + } + return sum; +} + +uint16_t subghz_protocol_blocks_lfsr_digest16( + uint8_t const message[], + size_t size, + uint16_t gen, + uint16_t key) { + uint16_t sum = 0; + for(size_t byte = 0; byte < size; ++byte) { + uint8_t data = message[byte]; + for(int8_t i = 7; i >= 0; --i) { + // if data bit is set then xor with key + if((data >> i) & 1) sum ^= key; + + // roll the key right (actually the LSB is dropped here) + // and apply the gen (needs to include the dropped LSB as MSB) + if(key & 1) + key = (key >> 1) ^ gen; + else + key = (key >> 1); + } + } + return sum; +} + +uint8_t subghz_protocol_blocks_add_bytes(uint8_t const message[], size_t size) { + uint32_t result = 0; + for(size_t i = 0; i < size; ++i) { + result += message[i]; + } + return (uint8_t)result; +} + +uint8_t subghz_protocol_blocks_parity8(uint8_t byte) { + byte ^= byte >> 4; + byte &= 0xf; + return (0x6996 >> byte) & 1; +} + +uint8_t subghz_protocol_blocks_parity_bytes(uint8_t const message[], size_t size) { + uint8_t result = 0; + for(size_t i = 0; i < size; ++i) { + result ^= subghz_protocol_blocks_parity8(message[i]); + } + return result; +} + +uint8_t subghz_protocol_blocks_xor_bytes(uint8_t const message[], size_t size) { + uint8_t result = 0; + for(size_t i = 0; i < size; ++i) { + result ^= message[i]; + } + return result; +} \ No newline at end of file diff --git a/applications/debug/subghz_test/protocol/math.h b/applications/debug/subghz_test/protocol/math.h new file mode 100644 index 000000000..dcea3da5f --- /dev/null +++ b/applications/debug/subghz_test/protocol/math.h @@ -0,0 +1,222 @@ +#pragma once + +#include +#include +#include + +#define bit_read(value, bit) (((value) >> (bit)) & 0x01) +#define bit_set(value, bit) \ + ({ \ + __typeof__(value) _one = (1); \ + (value) |= (_one << (bit)); \ + }) +#define bit_clear(value, bit) \ + ({ \ + __typeof__(value) _one = (1); \ + (value) &= ~(_one << (bit)); \ + }) +#define bit_write(value, bit, bitvalue) (bitvalue ? bit_set(value, bit) : bit_clear(value, bit)) +#define DURATION_DIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y))) + +#ifdef __cplusplus +extern "C" { +#endif + +/** Flip the data bitwise + * + * @param key In data + * @param bit_count number of data bits + * + * @return Reverse data + */ +uint64_t subghz_protocol_blocks_reverse_key(uint64_t key, uint8_t bit_count); + +/** Get parity the data bitwise + * + * @param key In data + * @param bit_count number of data bits + * + * @return parity + */ +uint8_t subghz_protocol_blocks_get_parity(uint64_t key, uint8_t bit_count); + +/** CRC-4 + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial CRC polynomial + * @param init starting crc value + * + * @return CRC value + */ +uint8_t subghz_protocol_blocks_crc4( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init); + +/** CRC-7 + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial CRC polynomial + * @param init starting crc value + * + * @return CRC value + */ +uint8_t subghz_protocol_blocks_crc7( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init); + +/** Generic Cyclic Redundancy Check CRC-8. Example polynomial: 0x31 = x8 + x5 + + * x4 + 1 (x8 is implicit) Example polynomial: 0x80 = x8 + x7 (a normal + * bit-by-bit parity XOR) + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial byte is from x^7 to x^0 (x^8 is implicitly one) + * @param init starting crc value + * + * @return CRC value + */ +uint8_t subghz_protocol_blocks_crc8( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init); + +/** "Little-endian" Cyclic Redundancy Check CRC-8 LE Input and output are + * reflected, i.e. least significant bit is shifted in first + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial CRC polynomial + * @param init starting crc value + * + * @return CRC value + */ +uint8_t subghz_protocol_blocks_crc8le( + uint8_t const message[], + size_t size, + uint8_t polynomial, + uint8_t init); + +/** CRC-16 LSB. Input and output are reflected, i.e. least significant bit is + * shifted in first. Note that poly and init already need to be reflected + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial CRC polynomial + * @param init starting crc value + * + * @return CRC value + */ +uint16_t subghz_protocol_blocks_crc16lsb( + uint8_t const message[], + size_t size, + uint16_t polynomial, + uint16_t init); + +/** CRC-16 + * + * @param message array of bytes to check + * @param size number of bytes in message + * @param polynomial CRC polynomial + * @param init starting crc value + * + * @return CRC value + */ +uint16_t subghz_protocol_blocks_crc16( + uint8_t const message[], + size_t size, + uint16_t polynomial, + uint16_t init); + +/** Digest-8 by "LFSR-based Toeplitz hash" + * + * @param message bytes of message data + * @param size number of bytes to digest + * @param gen key stream generator, needs to includes the MSB if the + * LFSR is rolling + * @param key initial key + * + * @return digest value + */ +uint8_t subghz_protocol_blocks_lfsr_digest8( + uint8_t const message[], + size_t size, + uint8_t gen, + uint8_t key); + +/** Digest-8 by "LFSR-based Toeplitz hash", byte reflect, bit reflect + * + * @param message bytes of message data + * @param size number of bytes to digest + * @param gen key stream generator, needs to includes the MSB if the + * LFSR is rolling + * @param key initial key + * + * @return digest value + */ +uint8_t subghz_protocol_blocks_lfsr_digest8_reflect( + uint8_t const message[], + size_t size, + uint8_t gen, + uint8_t key); + +/** Digest-16 by "LFSR-based Toeplitz hash" + * + * @param message bytes of message data + * @param size number of bytes to digest + * @param gen key stream generator, needs to includes the MSB if the + * LFSR is rolling + * @param key initial key + * + * @return digest value + */ +uint16_t subghz_protocol_blocks_lfsr_digest16( + uint8_t const message[], + size_t size, + uint16_t gen, + uint16_t key); + +/** Compute Addition of a number of bytes + * + * @param message bytes of message data + * @param size number of bytes to sum + * + * @return summation value + */ +uint8_t subghz_protocol_blocks_add_bytes(uint8_t const message[], size_t size); + +/** Compute bit parity of a single byte (8 bits) + * + * @param byte single byte to check + * + * @return 1 odd parity, 0 even parity + */ +uint8_t subghz_protocol_blocks_parity8(uint8_t byte); + +/** Compute bit parity of a number of bytes + * + * @param message bytes of message data + * @param size number of bytes to sum + * + * @return 1 odd parity, 0 even parity + */ +uint8_t subghz_protocol_blocks_parity_bytes(uint8_t const message[], size_t size); + +/** Compute XOR (byte-wide parity) of a number of bytes + * + * @param message bytes of message data + * @param size number of bytes to sum + * + * @return summation value, per bit-position 1 odd parity, 0 even parity + */ +uint8_t subghz_protocol_blocks_xor_bytes(uint8_t const message[], size_t size); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/protocols/princeton_for_testing.c b/applications/debug/subghz_test/protocol/princeton_for_testing.c similarity index 99% rename from lib/subghz/protocols/princeton_for_testing.c rename to applications/debug/subghz_test/protocol/princeton_for_testing.c index 478d14cdf..334a8241b 100644 --- a/lib/subghz/protocols/princeton_for_testing.c +++ b/applications/debug/subghz_test/protocol/princeton_for_testing.c @@ -1,7 +1,7 @@ #include "princeton_for_testing.h" #include -#include "../blocks/math.h" +#include "math.h" /* * Help diff --git a/lib/subghz/protocols/princeton_for_testing.h b/applications/debug/subghz_test/protocol/princeton_for_testing.h similarity index 97% rename from lib/subghz/protocols/princeton_for_testing.h rename to applications/debug/subghz_test/protocol/princeton_for_testing.h index 07a37ec5f..7b4201d38 100644 --- a/lib/subghz/protocols/princeton_for_testing.h +++ b/applications/debug/subghz_test/protocol/princeton_for_testing.h @@ -1,6 +1,8 @@ #pragma once -#include "base.h" +//#include "base.h" +#include +#include /** SubGhzDecoderPrinceton anonymous type */ typedef struct SubGhzDecoderPrinceton SubGhzDecoderPrinceton; diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene.c b/applications/debug/subghz_test/scenes/subghz_test_scene.c new file mode 100644 index 000000000..ff439ef0f --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene.c @@ -0,0 +1,30 @@ +#include "../subghz_test_app_i.h" + +// Generate scene on_enter handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, +void (*const subghz_test_scene_on_enter_handlers[])(void*) = { +#include "subghz_test_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 subghz_test_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = { +#include "subghz_test_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 subghz_test_scene_on_exit_handlers[])(void* context) = { +#include "subghz_test_scene_config.h" +}; +#undef ADD_SCENE + +// Initialize scene handlers configuration structure +const SceneManagerHandlers subghz_test_scene_handlers = { + .on_enter_handlers = subghz_test_scene_on_enter_handlers, + .on_event_handlers = subghz_test_scene_on_event_handlers, + .on_exit_handlers = subghz_test_scene_on_exit_handlers, + .scene_num = SubGhzTestSceneNum, +}; diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene.h b/applications/debug/subghz_test/scenes/subghz_test_scene.h new file mode 100644 index 000000000..0e6e06481 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +// Generate scene id and total number +#define ADD_SCENE(prefix, name, id) SubGhzTestScene##id, +typedef enum { +#include "subghz_test_scene_config.h" + SubGhzTestSceneNum, +} SubGhzTestScene; +#undef ADD_SCENE + +extern const SceneManagerHandlers subghz_test_scene_handlers; + +// Generate scene on_enter handlers declaration +#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); +#include "subghz_test_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 "subghz_test_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 "subghz_test_scene_config.h" +#undef ADD_SCENE diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_about.c b/applications/debug/subghz_test/scenes/subghz_test_scene_about.c new file mode 100644 index 000000000..64263d738 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_about.c @@ -0,0 +1,66 @@ +#include "../subghz_test_app_i.h" + +void subghz_test_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) { + SubGhzTestApp* app = context; + if(type == InputTypeShort) { + view_dispatcher_send_custom_event(app->view_dispatcher, result); + } +} + +void subghz_test_scene_about_on_enter(void* context) { + SubGhzTestApp* 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", SUBGHZ_TEST_VERSION_APP); + furi_string_cat_printf(temp_str, "Developed by: %s\n", SUBGHZ_TEST_DEVELOPED); + furi_string_cat_printf(temp_str, "Github: %s\n\n", SUBGHZ_TEST_GITHUB); + + furi_string_cat_printf(temp_str, "\e#%s\n", "Description"); + furi_string_cat_printf( + temp_str, + "This application is designed\nto test the functionality of the\nbuilt-in CC1101 module.\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! Sub-Ghz Test \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, SubGhzTestViewWidget); +} + +bool subghz_test_scene_about_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + bool consumed = false; + UNUSED(app); + UNUSED(event); + + return consumed; +} + +void subghz_test_scene_about_on_exit(void* context) { + SubGhzTestApp* app = context; + + // Clear views + widget_reset(app->widget); +} diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_carrier.c b/applications/debug/subghz_test/scenes/subghz_test_scene_carrier.c new file mode 100644 index 000000000..41ff5c8c6 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_carrier.c @@ -0,0 +1,29 @@ +#include "../subghz_test_app_i.h" + +void subghz_test_scene_carrier_callback(SubGhzTestCarrierEvent event, void* context) { + furi_assert(context); + SubGhzTestApp* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void subghz_test_scene_carrier_on_enter(void* context) { + SubGhzTestApp* app = context; + subghz_test_carrier_set_callback( + app->subghz_test_carrier, subghz_test_scene_carrier_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, SubGhzTestViewCarrier); +} + +bool subghz_test_scene_carrier_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubGhzTestCarrierEventOnlyRx) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneShowOnlyRx); + return true; + } + } + return false; +} + +void subghz_test_scene_carrier_on_exit(void* context) { + UNUSED(context); +} diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_config.h b/applications/debug/subghz_test/scenes/subghz_test_scene_config.h new file mode 100644 index 000000000..80a42c376 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_config.h @@ -0,0 +1,6 @@ +ADD_SCENE(subghz_test, start, Start) +ADD_SCENE(subghz_test, about, About) +ADD_SCENE(subghz_test, carrier, Carrier) +ADD_SCENE(subghz_test, packet, Packet) +ADD_SCENE(subghz_test, static, Static) +ADD_SCENE(subghz_test, show_only_rx, ShowOnlyRx) diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_packet.c b/applications/debug/subghz_test/scenes/subghz_test_scene_packet.c new file mode 100644 index 000000000..b43a4d0cb --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_packet.c @@ -0,0 +1,29 @@ +#include "../subghz_test_app_i.h" + +void subghz_test_scene_packet_callback(SubGhzTestPacketEvent event, void* context) { + furi_assert(context); + SubGhzTestApp* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void subghz_test_scene_packet_on_enter(void* context) { + SubGhzTestApp* app = context; + subghz_test_packet_set_callback( + app->subghz_test_packet, subghz_test_scene_packet_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, SubGhzTestViewPacket); +} + +bool subghz_test_scene_packet_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubGhzTestPacketEventOnlyRx) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneShowOnlyRx); + return true; + } + } + return false; +} + +void subghz_test_scene_packet_on_exit(void* context) { + UNUSED(context); +} diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_show_only_rx.c b/applications/debug/subghz_test/scenes/subghz_test_scene_show_only_rx.c new file mode 100644 index 000000000..3d5a54355 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_show_only_rx.c @@ -0,0 +1,49 @@ +#include "../subghz_test_app_i.h" +#include + +void subghz_test_scene_show_only_rx_popup_callback(void* context) { + SubGhzTestApp* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, SubGhzTestCustomEventSceneShowOnlyRX); +} + +void subghz_test_scene_show_only_rx_on_enter(void* context) { + SubGhzTestApp* app = context; + + // Setup view + Popup* popup = app->popup; + + const char* header_text = "Transmission is blocked"; + const char* message_text = "Transmission on\nthis frequency is\nrestricted in\nyour region"; + if(!furi_hal_region_is_provisioned()) { + header_text = "Firmware update needed"; + message_text = "Please update\nfirmware before\nusing this feature\nflipp.dev/upd"; + } + + popup_set_header(popup, header_text, 63, 3, AlignCenter, AlignTop); + popup_set_text(popup, message_text, 0, 17, AlignLeft, AlignTop); + popup_set_icon(popup, 72, 17, &I_DolphinCommon_56x48); + + popup_set_timeout(popup, 1500); + popup_set_context(popup, app); + popup_set_callback(popup, subghz_test_scene_show_only_rx_popup_callback); + popup_enable_timeout(popup); + view_dispatcher_switch_to_view(app->view_dispatcher, SubGhzTestViewPopup); +} + +bool subghz_test_scene_show_only_rx_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubGhzTestCustomEventSceneShowOnlyRX) { + scene_manager_previous_scene(app->scene_manager); + return true; + } + } + return false; +} + +void subghz_test_scene_show_only_rx_on_exit(void* context) { + SubGhzTestApp* app = context; + Popup* popup = app->popup; + + popup_reset(popup); +} diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_start.c b/applications/debug/subghz_test/scenes/subghz_test_scene_start.c new file mode 100644 index 000000000..cf3b08163 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_start.c @@ -0,0 +1,77 @@ +#include "../subghz_test_app_i.h" + +typedef enum { + SubmenuIndexSubGhzTestCarrier, + SubmenuIndexSubGhzTestPacket, + SubmenuIndexSubGhzTestStatic, + SubmenuIndexSubGhzTestAbout, +} SubmenuIndex; + +void subghz_test_scene_start_submenu_callback(void* context, uint32_t index) { + SubGhzTestApp* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void subghz_test_scene_start_on_enter(void* context) { + SubGhzTestApp* app = context; + Submenu* submenu = app->submenu; + + submenu_add_item( + submenu, + "Carrier", + SubmenuIndexSubGhzTestCarrier, + subghz_test_scene_start_submenu_callback, + app); + submenu_add_item( + submenu, + "Packet", + SubmenuIndexSubGhzTestPacket, + subghz_test_scene_start_submenu_callback, + app); + submenu_add_item( + submenu, + "Static", + SubmenuIndexSubGhzTestStatic, + subghz_test_scene_start_submenu_callback, + app); + submenu_add_item( + submenu, + "About", + SubmenuIndexSubGhzTestAbout, + subghz_test_scene_start_submenu_callback, + app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, SubGhzTestSceneStart)); + + view_dispatcher_switch_to_view(app->view_dispatcher, SubGhzTestViewSubmenu); +} + +bool subghz_test_scene_start_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubmenuIndexSubGhzTestAbout) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneAbout); + consumed = true; + } else if(event.event == SubmenuIndexSubGhzTestCarrier) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneCarrier); + consumed = true; + } else if(event.event == SubmenuIndexSubGhzTestPacket) { + scene_manager_next_scene(app->scene_manager, SubGhzTestScenePacket); + consumed = true; + } else if(event.event == SubmenuIndexSubGhzTestStatic) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneStatic); + consumed = true; + } + scene_manager_set_scene_state(app->scene_manager, SubGhzTestSceneStart, event.event); + } + + return consumed; +} + +void subghz_test_scene_start_on_exit(void* context) { + SubGhzTestApp* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/debug/subghz_test/scenes/subghz_test_scene_static.c b/applications/debug/subghz_test/scenes/subghz_test_scene_static.c new file mode 100644 index 000000000..a008d2438 --- /dev/null +++ b/applications/debug/subghz_test/scenes/subghz_test_scene_static.c @@ -0,0 +1,29 @@ +#include "../subghz_test_app_i.h" + +void subghz_test_scene_static_callback(SubGhzTestStaticEvent event, void* context) { + furi_assert(context); + SubGhzTestApp* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void subghz_test_scene_static_on_enter(void* context) { + SubGhzTestApp* app = context; + subghz_test_static_set_callback( + app->subghz_test_static, subghz_test_scene_static_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, SubGhzTestViewStatic); +} + +bool subghz_test_scene_static_on_event(void* context, SceneManagerEvent event) { + SubGhzTestApp* app = context; + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubGhzTestStaticEventOnlyRx) { + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneShowOnlyRx); + return true; + } + } + return false; +} + +void subghz_test_scene_static_on_exit(void* context) { + UNUSED(context); +} diff --git a/applications/debug/subghz_test/subghz_test_10px.png b/applications/debug/subghz_test/subghz_test_10px.png new file mode 100644 index 0000000000000000000000000000000000000000..10dac0ecaac608aba6d445bc5fef45d8cc1efff4 GIT binary patch literal 181 zcmeAS@N?(olHy`uVBq!ia0vp^AT}2V8<6ZZI=>f4F%}28J29*~C-V}>VM%xNb!1@J z*w6hZkrl}2EbxddW? +#include + +static bool subghz_test_app_custom_event_callback(void* context, uint32_t event) { + furi_assert(context); + SubGhzTestApp* app = context; + return scene_manager_handle_custom_event(app->scene_manager, event); +} + +static bool subghz_test_app_back_event_callback(void* context) { + furi_assert(context); + SubGhzTestApp* app = context; + return scene_manager_handle_back_event(app->scene_manager); +} + +static void subghz_test_app_tick_event_callback(void* context) { + furi_assert(context); + SubGhzTestApp* app = context; + scene_manager_handle_tick_event(app->scene_manager); +} + +SubGhzTestApp* subghz_test_app_alloc() { + SubGhzTestApp* app = malloc(sizeof(SubGhzTestApp)); + + // GUI + app->gui = furi_record_open(RECORD_GUI); + + // View Dispatcher + app->view_dispatcher = view_dispatcher_alloc(); + app->scene_manager = scene_manager_alloc(&subghz_test_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, subghz_test_app_custom_event_callback); + view_dispatcher_set_navigation_event_callback( + app->view_dispatcher, subghz_test_app_back_event_callback); + view_dispatcher_set_tick_event_callback( + app->view_dispatcher, subghz_test_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, SubGhzTestViewSubmenu, submenu_get_view(app->submenu)); + + // Widget + app->widget = widget_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, SubGhzTestViewWidget, widget_get_view(app->widget)); + + // Popup + app->popup = popup_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, SubGhzTestViewPopup, popup_get_view(app->popup)); + + // Carrier Test Module + app->subghz_test_carrier = subghz_test_carrier_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + SubGhzTestViewCarrier, + subghz_test_carrier_get_view(app->subghz_test_carrier)); + + // Packet Test + app->subghz_test_packet = subghz_test_packet_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + SubGhzTestViewPacket, + subghz_test_packet_get_view(app->subghz_test_packet)); + + // Static send + app->subghz_test_static = subghz_test_static_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + SubGhzTestViewStatic, + subghz_test_static_get_view(app->subghz_test_static)); + + scene_manager_next_scene(app->scene_manager, SubGhzTestSceneStart); + + return app; +} + +void subghz_test_app_free(SubGhzTestApp* app) { + furi_assert(app); + + // Submenu + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewSubmenu); + submenu_free(app->submenu); + + // Widget + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewWidget); + widget_free(app->widget); + + // Popup + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewPopup); + popup_free(app->popup); + + // Carrier Test + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewCarrier); + subghz_test_carrier_free(app->subghz_test_carrier); + + // Packet Test + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewPacket); + subghz_test_packet_free(app->subghz_test_packet); + + // Static + view_dispatcher_remove_view(app->view_dispatcher, SubGhzTestViewStatic); + subghz_test_static_free(app->subghz_test_static); + + // 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 subghz_test_app(void* p) { + UNUSED(p); + SubGhzTestApp* subghz_test_app = subghz_test_app_alloc(); + + view_dispatcher_run(subghz_test_app->view_dispatcher); + + subghz_test_app_free(subghz_test_app); + + return 0; +} diff --git a/applications/debug/subghz_test/subghz_test_app_i.c b/applications/debug/subghz_test/subghz_test_app_i.c new file mode 100644 index 000000000..0ec6635a0 --- /dev/null +++ b/applications/debug/subghz_test/subghz_test_app_i.c @@ -0,0 +1,5 @@ +#include "subghz_test_app_i.h" + +#include + +#define TAG "SubGhzTest" diff --git a/applications/debug/subghz_test/subghz_test_app_i.h b/applications/debug/subghz_test/subghz_test_app_i.h new file mode 100644 index 000000000..c96f9c4ee --- /dev/null +++ b/applications/debug/subghz_test/subghz_test_app_i.h @@ -0,0 +1,32 @@ +#pragma once + +#include "helpers/subghz_test_types.h" +#include "helpers/subghz_test_event.h" + +#include "scenes/subghz_test_scene.h" +#include +#include +#include +#include +#include +#include +#include + +#include "views/subghz_test_static.h" +#include "views/subghz_test_carrier.h" +#include "views/subghz_test_packet.h" + +typedef struct SubGhzTestApp SubGhzTestApp; + +struct SubGhzTestApp { + Gui* gui; + ViewDispatcher* view_dispatcher; + SceneManager* scene_manager; + NotificationApp* notifications; + Submenu* submenu; + Widget* widget; + Popup* popup; + SubGhzTestStatic* subghz_test_static; + SubGhzTestCarrier* subghz_test_carrier; + SubGhzTestPacket* subghz_test_packet; +}; diff --git a/applications/main/subghz/views/subghz_test_carrier.c b/applications/debug/subghz_test/views/subghz_test_carrier.c similarity index 98% rename from applications/main/subghz/views/subghz_test_carrier.c rename to applications/debug/subghz_test/views/subghz_test_carrier.c index 254a4127b..53e309b7c 100644 --- a/applications/main/subghz/views/subghz_test_carrier.c +++ b/applications/debug/subghz_test/views/subghz_test_carrier.c @@ -1,6 +1,6 @@ #include "subghz_test_carrier.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include diff --git a/applications/main/subghz/views/subghz_test_carrier.h b/applications/debug/subghz_test/views/subghz_test_carrier.h similarity index 100% rename from applications/main/subghz/views/subghz_test_carrier.h rename to applications/debug/subghz_test/views/subghz_test_carrier.h diff --git a/applications/main/subghz/views/subghz_test_packet.c b/applications/debug/subghz_test/views/subghz_test_packet.c similarity index 98% rename from applications/main/subghz/views/subghz_test_packet.c rename to applications/debug/subghz_test/views/subghz_test_packet.c index bc2c474b5..bab83ab5b 100644 --- a/applications/main/subghz/views/subghz_test_packet.c +++ b/applications/debug/subghz_test/views/subghz_test_packet.c @@ -1,6 +1,6 @@ #include "subghz_test_packet.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include @@ -8,7 +8,7 @@ #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define SUBGHZ_TEST_PACKET_COUNT 500 diff --git a/applications/main/subghz/views/subghz_test_packet.h b/applications/debug/subghz_test/views/subghz_test_packet.h similarity index 100% rename from applications/main/subghz/views/subghz_test_packet.h rename to applications/debug/subghz_test/views/subghz_test_packet.h diff --git a/applications/main/subghz/views/subghz_test_static.c b/applications/debug/subghz_test/views/subghz_test_static.c similarity index 98% rename from applications/main/subghz/views/subghz_test_static.c rename to applications/debug/subghz_test/views/subghz_test_static.c index 197af21fb..6764fd5ca 100644 --- a/applications/main/subghz/views/subghz_test_static.c +++ b/applications/debug/subghz_test/views/subghz_test_static.c @@ -1,6 +1,6 @@ #include "subghz_test_static.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include @@ -8,7 +8,7 @@ #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define TAG "SubGhzTestStatic" diff --git a/applications/main/subghz/views/subghz_test_static.h b/applications/debug/subghz_test/views/subghz_test_static.h similarity index 100% rename from applications/main/subghz/views/subghz_test_static.h rename to applications/debug/subghz_test/views/subghz_test_static.h diff --git a/applications/main/subghz/helpers/subghz_types.h b/applications/main/subghz/helpers/subghz_types.h index 8beb7b9ed..e71c22dd5 100644 --- a/applications/main/subghz/helpers/subghz_types.h +++ b/applications/main/subghz/helpers/subghz_types.h @@ -80,9 +80,6 @@ typedef enum { SubGhzViewIdFrequencyAnalyzer, SubGhzViewIdReadRAW, - SubGhzViewIdStatic, - SubGhzViewIdTestCarrier, - SubGhzViewIdTestPacket, } SubGhzViewId; /** SubGhz load type file */ diff --git a/applications/main/subghz/scenes/subghz_scene_config.h b/applications/main/subghz/scenes/subghz_scene_config.h index 97aa946e8..47655958b 100644 --- a/applications/main/subghz/scenes/subghz_scene_config.h +++ b/applications/main/subghz/scenes/subghz_scene_config.h @@ -12,10 +12,6 @@ ADD_SCENE(subghz, show_only_rx, ShowOnlyRx) ADD_SCENE(subghz, saved_menu, SavedMenu) ADD_SCENE(subghz, delete, Delete) ADD_SCENE(subghz, delete_success, DeleteSuccess) -ADD_SCENE(subghz, test, Test) -ADD_SCENE(subghz, test_static, TestStatic) -ADD_SCENE(subghz, test_carrier, TestCarrier) -ADD_SCENE(subghz, test_packet, TestPacket) ADD_SCENE(subghz, set_type, SetType) ADD_SCENE(subghz, frequency_analyzer, FrequencyAnalyzer) ADD_SCENE(subghz, read_raw, ReadRAW) diff --git a/applications/main/subghz/scenes/subghz_scene_start.c b/applications/main/subghz/scenes/subghz_scene_start.c index ce631b398..951c756d8 100644 --- a/applications/main/subghz/scenes/subghz_scene_start.c +++ b/applications/main/subghz/scenes/subghz_scene_start.c @@ -4,7 +4,6 @@ enum SubmenuIndex { SubmenuIndexRead = 10, SubmenuIndexSaved, - SubmenuIndexTest, SubmenuIndexAddManually, SubmenuIndexFrequencyAnalyzer, SubmenuIndexReadRAW, @@ -56,10 +55,6 @@ void subghz_scene_start_on_enter(void* context) { SubmenuIndexRadioSetting, subghz_scene_start_submenu_callback, subghz); - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - submenu_add_item( - subghz->submenu, "Test", SubmenuIndexTest, subghz_scene_start_submenu_callback, subghz); - } submenu_set_selected_item( subghz->submenu, scene_manager_get_scene_state(subghz->scene_manager, SubGhzSceneStart)); @@ -101,11 +96,6 @@ bool subghz_scene_start_on_event(void* context, SceneManagerEvent event) { scene_manager_next_scene(subghz->scene_manager, SubGhzSceneFrequencyAnalyzer); dolphin_deed(DolphinDeedSubGhzFrequencyAnalyzer); return true; - } else if(event.event == SubmenuIndexTest) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexTest); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTest); - return true; } else if(event.event == SubmenuIndexShowRegionInfo) { scene_manager_set_scene_state( subghz->scene_manager, SubGhzSceneStart, SubmenuIndexShowRegionInfo); diff --git a/applications/main/subghz/scenes/subghz_scene_test.c b/applications/main/subghz/scenes/subghz_scene_test.c deleted file mode 100644 index 65f9bbdef..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test.c +++ /dev/null @@ -1,61 +0,0 @@ -#include "../subghz_i.h" - -enum SubmenuIndex { - SubmenuIndexCarrier, - SubmenuIndexPacket, - SubmenuIndexStatic, -}; - -void subghz_scene_test_submenu_callback(void* context, uint32_t index) { - SubGhz* subghz = context; - view_dispatcher_send_custom_event(subghz->view_dispatcher, index); -} - -void subghz_scene_test_on_enter(void* context) { - SubGhz* subghz = context; - - submenu_add_item( - subghz->submenu, - "Carrier", - SubmenuIndexCarrier, - subghz_scene_test_submenu_callback, - subghz); - submenu_add_item( - subghz->submenu, "Packet", SubmenuIndexPacket, subghz_scene_test_submenu_callback, subghz); - submenu_add_item( - subghz->submenu, "Static", SubmenuIndexStatic, subghz_scene_test_submenu_callback, subghz); - - submenu_set_selected_item( - subghz->submenu, scene_manager_get_scene_state(subghz->scene_manager, SubGhzSceneTest)); - - view_dispatcher_switch_to_view(subghz->view_dispatcher, SubGhzViewIdMenu); -} - -bool subghz_scene_test_on_event(void* context, SceneManagerEvent event) { - SubGhz* subghz = context; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexCarrier) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneTest, SubmenuIndexCarrier); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTestCarrier); - return true; - } else if(event.event == SubmenuIndexPacket) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneTest, SubmenuIndexPacket); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTestPacket); - return true; - } else if(event.event == SubmenuIndexStatic) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneTest, SubmenuIndexStatic); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTestStatic); - return true; - } - } - return false; -} - -void subghz_scene_test_on_exit(void* context) { - SubGhz* subghz = context; - submenu_reset(subghz->submenu); -} diff --git a/applications/main/subghz/scenes/subghz_scene_test_carrier.c b/applications/main/subghz/scenes/subghz_scene_test_carrier.c deleted file mode 100644 index 9677792ba..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_carrier.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "../subghz_i.h" -#include "../views/subghz_test_carrier.h" - -void subghz_scene_test_carrier_callback(SubGhzTestCarrierEvent event, void* context) { - furi_assert(context); - SubGhz* subghz = context; - view_dispatcher_send_custom_event(subghz->view_dispatcher, event); -} - -void subghz_scene_test_carrier_on_enter(void* context) { - SubGhz* subghz = context; - subghz_test_carrier_set_callback( - subghz->subghz_test_carrier, subghz_scene_test_carrier_callback, subghz); - view_dispatcher_switch_to_view(subghz->view_dispatcher, SubGhzViewIdTestCarrier); -} - -bool subghz_scene_test_carrier_on_event(void* context, SceneManagerEvent event) { - SubGhz* subghz = context; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubGhzTestCarrierEventOnlyRx) { - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowOnlyRx); - return true; - } - } - return false; -} - -void subghz_scene_test_carrier_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/main/subghz/scenes/subghz_scene_test_packet.c b/applications/main/subghz/scenes/subghz_scene_test_packet.c deleted file mode 100644 index 99f0ab179..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_packet.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "../subghz_i.h" -#include "../views/subghz_test_packet.h" - -void subghz_scene_test_packet_callback(SubGhzTestPacketEvent event, void* context) { - furi_assert(context); - SubGhz* subghz = context; - view_dispatcher_send_custom_event(subghz->view_dispatcher, event); -} - -void subghz_scene_test_packet_on_enter(void* context) { - SubGhz* subghz = context; - subghz_test_packet_set_callback( - subghz->subghz_test_packet, subghz_scene_test_packet_callback, subghz); - view_dispatcher_switch_to_view(subghz->view_dispatcher, SubGhzViewIdTestPacket); -} - -bool subghz_scene_test_packet_on_event(void* context, SceneManagerEvent event) { - SubGhz* subghz = context; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubGhzTestPacketEventOnlyRx) { - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowOnlyRx); - return true; - } - } - return false; -} - -void subghz_scene_test_packet_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/main/subghz/scenes/subghz_scene_test_static.c b/applications/main/subghz/scenes/subghz_scene_test_static.c deleted file mode 100644 index 10e6d02a1..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_static.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "../subghz_i.h" -#include "../views/subghz_test_static.h" - -void subghz_scene_test_static_callback(SubGhzTestStaticEvent event, void* context) { - furi_assert(context); - SubGhz* subghz = context; - view_dispatcher_send_custom_event(subghz->view_dispatcher, event); -} - -void subghz_scene_test_static_on_enter(void* context) { - SubGhz* subghz = context; - subghz_test_static_set_callback( - subghz->subghz_test_static, subghz_scene_test_static_callback, subghz); - view_dispatcher_switch_to_view(subghz->view_dispatcher, SubGhzViewIdStatic); -} - -bool subghz_scene_test_static_on_event(void* context, SceneManagerEvent event) { - SubGhz* subghz = context; - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubGhzTestStaticEventOnlyRx) { - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowOnlyRx); - return true; - } - } - return false; -} - -void subghz_scene_test_static_on_exit(void* context) { - UNUSED(context); -} diff --git a/applications/main/subghz/subghz.c b/applications/main/subghz/subghz.c index 09963584a..e8148798e 100644 --- a/applications/main/subghz/subghz.c +++ b/applications/main/subghz/subghz.c @@ -129,27 +129,6 @@ SubGhz* subghz_alloc() { SubGhzViewIdReadRAW, subghz_read_raw_get_view(subghz->subghz_read_raw)); - // Carrier Test Module - subghz->subghz_test_carrier = subghz_test_carrier_alloc(); - view_dispatcher_add_view( - subghz->view_dispatcher, - SubGhzViewIdTestCarrier, - subghz_test_carrier_get_view(subghz->subghz_test_carrier)); - - // Packet Test - subghz->subghz_test_packet = subghz_test_packet_alloc(); - view_dispatcher_add_view( - subghz->view_dispatcher, - SubGhzViewIdTestPacket, - subghz_test_packet_get_view(subghz->subghz_test_packet)); - - // Static send - subghz->subghz_test_static = subghz_test_static_alloc(); - view_dispatcher_add_view( - subghz->view_dispatcher, - SubGhzViewIdStatic, - subghz_test_static_get_view(subghz->subghz_test_static)); - //init threshold rssi subghz->threshold_rssi = subghz_threshold_rssi_alloc(); @@ -183,18 +162,6 @@ void subghz_free(SubGhz* subghz) { subghz_txrx_stop(subghz->txrx); subghz_txrx_sleep(subghz->txrx); - // Packet Test - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdTestPacket); - subghz_test_packet_free(subghz->subghz_test_packet); - - // Carrier Test - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdTestCarrier); - subghz_test_carrier_free(subghz->subghz_test_carrier); - - // Static - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdStatic); - subghz_test_static_free(subghz->subghz_test_static); - // Receiver view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdReceiver); subghz_view_receiver_free(subghz->subghz_receiver); diff --git a/applications/main/subghz/subghz_i.h b/applications/main/subghz/subghz_i.h index fc3404c07..9e58f3947 100644 --- a/applications/main/subghz/subghz_i.h +++ b/applications/main/subghz/subghz_i.h @@ -9,10 +9,6 @@ #include "views/subghz_frequency_analyzer.h" #include "views/subghz_read_raw.h" -#include "views/subghz_test_static.h" -#include "views/subghz_test_carrier.h" -#include "views/subghz_test_packet.h" - #include #include #include @@ -64,9 +60,6 @@ struct SubGhz { SubGhzFrequencyAnalyzer* subghz_frequency_analyzer; SubGhzReadRAW* subghz_read_raw; - SubGhzTestStatic* subghz_test_static; - SubGhzTestCarrier* subghz_test_carrier; - SubGhzTestPacket* subghz_test_packet; SubGhzProtocolFlag filter; FuriString* error_str; diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index a44e663ba..ffbc0104b 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1384,8 +1384,8 @@ Function,+,furi_hal_subghz_rx_pipe_not_empty,_Bool, Function,+,furi_hal_subghz_set_async_mirror_pin,void,const GpioPin* Function,+,furi_hal_subghz_set_frequency,uint32_t,uint32_t Function,+,furi_hal_subghz_set_frequency_and_path,uint32_t,uint32_t -Function,-,furi_hal_subghz_set_path,void,FuriHalSubGhzPath -Function,-,furi_hal_subghz_shutdown,void, +Function,+,furi_hal_subghz_set_path,void,FuriHalSubGhzPath +Function,+,furi_hal_subghz_shutdown,void, Function,+,furi_hal_subghz_sleep,void, Function,+,furi_hal_subghz_start_async_rx,void,"FuriHalSubGhzCaptureCallback, void*" Function,+,furi_hal_subghz_start_async_tx,_Bool,"FuriHalSubGhzAsyncTxCallback, void*" @@ -2745,6 +2745,7 @@ Function,+,subghz_protocol_decoder_base_get_hash_data,uint8_t,SubGhzProtocolDeco Function,+,subghz_protocol_decoder_base_get_string,_Bool,"SubGhzProtocolDecoderBase*, FuriString*" Function,+,subghz_protocol_decoder_base_serialize,SubGhzProtocolStatus,"SubGhzProtocolDecoderBase*, FlipperFormat*, SubGhzRadioPreset*" Function,-,subghz_protocol_decoder_base_set_decoder_callback,void,"SubGhzProtocolDecoderBase*, SubGhzProtocolDecoderBaseRxCallback, void*" +Function,+,subghz_protocol_decoder_bin_raw_data_input_rssi,void,"SubGhzProtocolDecoderBinRAW*, float" Function,+,subghz_protocol_decoder_raw_alloc,void*,SubGhzEnvironment* Function,+,subghz_protocol_decoder_raw_deserialize,SubGhzProtocolStatus,"void*, FlipperFormat*" Function,+,subghz_protocol_decoder_raw_feed,void,"void*, _Bool, uint32_t" @@ -2756,6 +2757,7 @@ Function,+,subghz_protocol_encoder_raw_deserialize,SubGhzProtocolStatus,"void*, Function,+,subghz_protocol_encoder_raw_free,void,void* Function,+,subghz_protocol_encoder_raw_stop,void,void* Function,+,subghz_protocol_encoder_raw_yield,LevelDuration,void* +Function,+,subghz_protocol_keeloq_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, const char*, SubGhzRadioPreset*" Function,+,subghz_protocol_raw_file_encoder_worker_set_callback_end,void,"SubGhzProtocolEncoderRAW*, SubGhzProtocolEncoderRAWCallbackEnd, void*" Function,+,subghz_protocol_raw_gen_fff_data,void,"FlipperFormat*, const char*, const char*" Function,+,subghz_protocol_raw_get_sample_write,size_t,SubGhzProtocolDecoderRAW* @@ -2765,6 +2767,8 @@ Function,+,subghz_protocol_raw_save_to_file_stop,void,SubGhzProtocolDecoderRAW* Function,+,subghz_protocol_registry_count,size_t,const SubGhzProtocolRegistry* Function,+,subghz_protocol_registry_get_by_index,const SubGhzProtocol*,"const SubGhzProtocolRegistry*, size_t" Function,+,subghz_protocol_registry_get_by_name,const SubGhzProtocol*,"const SubGhzProtocolRegistry*, const char*" +Function,+,subghz_protocol_secplus_v1_check_fixed,_Bool,uint32_t +Function,+,subghz_protocol_secplus_v2_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint32_t, SubGhzRadioPreset*" Function,+,subghz_receiver_alloc_init,SubGhzReceiver*,SubGhzEnvironment* Function,+,subghz_receiver_decode,void,"SubGhzReceiver*, _Bool, uint32_t" Function,+,subghz_receiver_free,void,SubGhzReceiver* diff --git a/lib/subghz/subghz_protocol_registry.h b/lib/subghz/subghz_protocol_registry.h index 6a27da992..8e80071b5 100644 --- a/lib/subghz/subghz_protocol_registry.h +++ b/lib/subghz/subghz_protocol_registry.h @@ -8,6 +8,31 @@ extern "C" { extern const SubGhzProtocolRegistry subghz_protocol_registry; +typedef struct SubGhzProtocolDecoderBinRAW SubGhzProtocolDecoderBinRAW; + +bool subghz_protocol_secplus_v2_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint32_t cnt, + SubGhzRadioPreset* preset); + +bool subghz_protocol_keeloq_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +void subghz_protocol_decoder_bin_raw_data_input_rssi( + SubGhzProtocolDecoderBinRAW* instance, + float rssi); + +bool subghz_protocol_secplus_v1_check_fixed(uint32_t fixed); + #ifdef __cplusplus } #endif From 79bcd5a1c6b780752a9511e9c70fd5d259c5f80f Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 18:44:45 +0300 Subject: [PATCH 37/40] Jetpack joyride and NFC Maker apps --- ReadMe.md | 2 + .../external/jetpack_joyride/application.fam | 15 + .../jetpack_joyride/assets/air_vent.png | Bin 0 -> 1838 bytes .../jetpack_joyride/assets/alert/frame_01.png | Bin 0 -> 1820 bytes .../jetpack_joyride/assets/alert/frame_02.png | Bin 0 -> 1807 bytes .../jetpack_joyride/assets/alert/frame_rate | 1 + .../jetpack_joyride/assets/barry/frame_01.png | Bin 0 -> 1932 bytes .../jetpack_joyride/assets/barry/frame_02.png | Bin 0 -> 1930 bytes .../jetpack_joyride/assets/barry/frame_03.png | Bin 0 -> 1929 bytes .../jetpack_joyride/assets/barry/frame_rate | 1 + .../jetpack_joyride/assets/barry_infill.png | Bin 0 -> 1614 bytes .../external/jetpack_joyride/assets/bg1.png | Bin 0 -> 835 bytes .../external/jetpack_joyride/assets/bg2.png | Bin 0 -> 968 bytes .../external/jetpack_joyride/assets/bg3.png | Bin 0 -> 886 bytes .../external/jetpack_joyride/assets/coin.png | Bin 0 -> 1842 bytes .../jetpack_joyride/assets/coin_infill.png | Bin 0 -> 1974 bytes .../jetpack_joyride/assets/dead_scientist.png | Bin 0 -> 1768 bytes .../assets/dead_scientist_infill.png | Bin 0 -> 1900 bytes .../external/jetpack_joyride/assets/door.png | Bin 0 -> 1961 bytes .../assets/missile/frame_01.png | Bin 0 -> 1898 bytes .../jetpack_joyride/assets/missile/frame_rate | 1 + .../jetpack_joyride/assets/missile_infill.png | Bin 0 -> 1591 bytes .../jetpack_joyride/assets/pillar.png | Bin 0 -> 1880 bytes .../jetpack_joyride/assets/scientist_left.png | Bin 0 -> 2056 bytes .../assets/scientist_left_infill.png | Bin 0 -> 2211 bytes .../assets/scientist_right.png | Bin 0 -> 1917 bytes .../assets/scientist_right_infill.png | Bin 0 -> 2210 bytes .../external/jetpack_joyride/icon.png | Bin 0 -> 1836 bytes .../includes/background_asset.c | 81 ++++ .../includes/background_assets.h | 34 ++ .../external/jetpack_joyride/includes/barry.c | 33 ++ .../external/jetpack_joyride/includes/barry.h | 23 ++ .../external/jetpack_joyride/includes/coin.c | 98 +++++ .../external/jetpack_joyride/includes/coin.h | 26 ++ .../jetpack_joyride/includes/game_sprites.h | 35 ++ .../jetpack_joyride/includes/game_state.c | 5 + .../jetpack_joyride/includes/game_state.h | 34 ++ .../jetpack_joyride/includes/missile.c | 86 ++++ .../jetpack_joyride/includes/missile.h | 24 ++ .../jetpack_joyride/includes/particle.c | 57 +++ .../jetpack_joyride/includes/particle.h | 21 + .../external/jetpack_joyride/includes/point.h | 14 + .../jetpack_joyride/includes/scientist.c | 77 ++++ .../jetpack_joyride/includes/scientist.h | 29 ++ .../jetpack_joyride/includes/states.h | 9 + .../external/jetpack_joyride/jetpack.c | 379 ++++++++++++++++++ .../external/nfc_maker/application.fam | 14 + applications/external/nfc_maker/nfc_maker.c | 81 ++++ applications/external/nfc_maker/nfc_maker.h | 59 +++ .../external/nfc_maker/nfc_maker_10px.png | Bin 0 -> 4142 bytes .../nfc_maker/scenes/nfc_maker_scene.c | 30 ++ .../nfc_maker/scenes/nfc_maker_scene.h | 29 ++ .../scenes/nfc_maker_scene_bluetooth.c | 57 +++ .../nfc_maker/scenes/nfc_maker_scene_config.h | 13 + .../nfc_maker/scenes/nfc_maker_scene_https.c | 53 +++ .../nfc_maker/scenes/nfc_maker_scene_mail.c | 53 +++ .../nfc_maker/scenes/nfc_maker_scene_menu.c | 61 +++ .../nfc_maker/scenes/nfc_maker_scene_name.c | 57 +++ .../nfc_maker/scenes/nfc_maker_scene_phone.c | 53 +++ .../nfc_maker/scenes/nfc_maker_scene_result.c | 359 +++++++++++++++++ .../nfc_maker/scenes/nfc_maker_scene_text.c | 53 +++ .../nfc_maker/scenes/nfc_maker_scene_url.c | 53 +++ .../nfc_maker/scenes/nfc_maker_scene_wifi.c | 55 +++ .../scenes/nfc_maker_scene_wifi_auth.c | 83 ++++ .../scenes/nfc_maker_scene_wifi_encr.c | 48 +++ .../scenes/nfc_maker_scene_wifi_pass.c | 53 +++ 66 files changed, 2349 insertions(+) create mode 100644 applications/external/jetpack_joyride/application.fam create mode 100644 applications/external/jetpack_joyride/assets/air_vent.png create mode 100644 applications/external/jetpack_joyride/assets/alert/frame_01.png create mode 100644 applications/external/jetpack_joyride/assets/alert/frame_02.png create mode 100644 applications/external/jetpack_joyride/assets/alert/frame_rate create mode 100644 applications/external/jetpack_joyride/assets/barry/frame_01.png create mode 100644 applications/external/jetpack_joyride/assets/barry/frame_02.png create mode 100644 applications/external/jetpack_joyride/assets/barry/frame_03.png create mode 100644 applications/external/jetpack_joyride/assets/barry/frame_rate create mode 100644 applications/external/jetpack_joyride/assets/barry_infill.png create mode 100644 applications/external/jetpack_joyride/assets/bg1.png create mode 100644 applications/external/jetpack_joyride/assets/bg2.png create mode 100644 applications/external/jetpack_joyride/assets/bg3.png create mode 100644 applications/external/jetpack_joyride/assets/coin.png create mode 100644 applications/external/jetpack_joyride/assets/coin_infill.png create mode 100644 applications/external/jetpack_joyride/assets/dead_scientist.png create mode 100644 applications/external/jetpack_joyride/assets/dead_scientist_infill.png create mode 100644 applications/external/jetpack_joyride/assets/door.png create mode 100644 applications/external/jetpack_joyride/assets/missile/frame_01.png create mode 100644 applications/external/jetpack_joyride/assets/missile/frame_rate create mode 100644 applications/external/jetpack_joyride/assets/missile_infill.png create mode 100644 applications/external/jetpack_joyride/assets/pillar.png create mode 100644 applications/external/jetpack_joyride/assets/scientist_left.png create mode 100644 applications/external/jetpack_joyride/assets/scientist_left_infill.png create mode 100644 applications/external/jetpack_joyride/assets/scientist_right.png create mode 100644 applications/external/jetpack_joyride/assets/scientist_right_infill.png create mode 100644 applications/external/jetpack_joyride/icon.png create mode 100644 applications/external/jetpack_joyride/includes/background_asset.c create mode 100644 applications/external/jetpack_joyride/includes/background_assets.h create mode 100644 applications/external/jetpack_joyride/includes/barry.c create mode 100644 applications/external/jetpack_joyride/includes/barry.h create mode 100644 applications/external/jetpack_joyride/includes/coin.c create mode 100644 applications/external/jetpack_joyride/includes/coin.h create mode 100644 applications/external/jetpack_joyride/includes/game_sprites.h create mode 100644 applications/external/jetpack_joyride/includes/game_state.c create mode 100644 applications/external/jetpack_joyride/includes/game_state.h create mode 100644 applications/external/jetpack_joyride/includes/missile.c create mode 100644 applications/external/jetpack_joyride/includes/missile.h create mode 100644 applications/external/jetpack_joyride/includes/particle.c create mode 100644 applications/external/jetpack_joyride/includes/particle.h create mode 100644 applications/external/jetpack_joyride/includes/point.h create mode 100644 applications/external/jetpack_joyride/includes/scientist.c create mode 100644 applications/external/jetpack_joyride/includes/scientist.h create mode 100644 applications/external/jetpack_joyride/includes/states.h create mode 100644 applications/external/jetpack_joyride/jetpack.c create mode 100644 applications/external/nfc_maker/application.fam create mode 100644 applications/external/nfc_maker/nfc_maker.c create mode 100644 applications/external/nfc_maker/nfc_maker.h create mode 100644 applications/external/nfc_maker/nfc_maker_10px.png create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene.h create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_config.h create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_https.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_name.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_result.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_text.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_url.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c create mode 100644 applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c diff --git a/ReadMe.md b/ReadMe.md index b589e164e..f57256713 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -170,6 +170,7 @@ You can support us by using links or addresses below: - IR Scope [(by kallanreed)](https://github.com/DarkFlippers/unleashed-firmware/pull/407) - **BadBT** plugin (BT version of BadKB) [(by Willy-JL, ClaraCrazy, XFW contributors)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/main/bad_kb) (See in Applications->Tools) - (aka BadUSB via Bluetooth) - **Mifare Nested** [(by AloneLiberty)](https://github.com/AloneLiberty/FlipperNested) - Works with PC and python app `FlipperNested` +- **NFC Maker** plugin (make tags with URLs, Wifi and other things) [(by Willy-JL)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/external/nfc_maker) Games: - DOOM (fixed) [(by p4nic4ttack)](https://github.com/p4nic4ttack/doom-flipper-zero/) @@ -185,6 +186,7 @@ Games: - BlackJack [(by teeebor)](https://github.com/teeebor/flipper_games) - 2048 game [(by eugene-kirzhanov)](https://github.com/eugene-kirzhanov/flipper-zero-2048-game) - Bomberduck [(by leo-need-more-coffee)](https://github.com/leo-need-more-coffee/flipperzero-bomberduck) +- JetPack Joyride [(by timstrasser)](https://github.com/timstrasser) # Instructions diff --git a/applications/external/jetpack_joyride/application.fam b/applications/external/jetpack_joyride/application.fam new file mode 100644 index 000000000..1b98e11ce --- /dev/null +++ b/applications/external/jetpack_joyride/application.fam @@ -0,0 +1,15 @@ +# 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, + order=100, + 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 new file mode 100644 index 0000000000000000000000000000000000000000..a7fcf0b203a79875b27f4a90870bf66b8ec4e597 GIT binary patch literal 1838 zcma)7eNYr-7+>=vJkTK&D$80|6O6gry@NZr?G^^^PVR(b2#y2?!R79~yN$cuZFi45 z&{CWMzs4aHwWh|=88TCYMy9E3nlw#?$Q&RiDQiNQoW`Q2X0kz}clYo(B%S`)yM3SE z@A-V6=h+=4#RUsgOH>GgEU?=wrSLxiKJjr6!QXR9<8cTwH<@u(NEMDE(!~Wdw4191 zns9)JID(jR!#wS(0}@&bybMcWV;_Htp^Tft*6JOEgEs>oV`~&ZS!1!&)mY~;y0P3G zl_^X@0|6k>XgJ_!MKVlbid_=E%VHcu6^c|xVHJ)N)XWJ0)ob(`0?SdMCc*6?OD(G> zmEnoPe3HbII35axG@%R)CwOtK(P+d89j?=Md> z23=x2_o2(k3_7f}!|~uO0)c6Xh?2D)7Gkof(*nAix9Du(0bUA3E-1KwwH~n2a-|l~ z8)+5*EddLBC`?D_GSq}YO=LQ?*(6~g_4;%|M-Wl6gL5;UhW{jIky-;Jld){r9&TEq z{|`S}a8hPRf`YC2z=)=F%$%PSU~n*p3?9puJ!%(d1O$N(nzF@5hYG&P(+bADg!S? zPLZRZQ3eP_l{O-2m+YUyc!6^VUBIoB0Gf-SBIl7pv;gwFu!ATp&*NcWqzx#XO~%Ut z0o9?frf~45*$nvrw0O@&#&iol867T<_1*AH_>2Th3L$0>K)r|z?iaYI@aU$3hv=>Y zEbJlyZn7=y*P9Sz))of#!;C&akhHd7+ZToTd5gE@K24>aJ(QxZvN?|@q`x{eXVvq0 zme=ySc30Ol4UJYm(-FA*LfZDBKi3V`lze+An7G)Q7^qu6cx0r$Q?+K~@k?)VuVnm0 zi1SVyZr^j|muj2$cg77@v0x*Xzb|YR;KpecAZR7%{x7$ zxmi5OceL#5*q^fhz`)+((e~b#`wnE+zTVuh0BIF043jZSAqOWsOgK(ABspe6;G?kK0-vJ$vg$ z^O2=#DGArdzae&}ZrIpzyhy+KPTcAoEAD*%pqXdSd>$;{b@R-qL89KF)m3}^!&kyj ze*e{>z~&xx^-%! literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/alert/frame_01.png b/applications/external/jetpack_joyride/assets/alert/frame_01.png new file mode 100644 index 0000000000000000000000000000000000000000..ac4cca1b1f85f1ac36afa559e601804c50074838 GIT binary patch literal 1820 zcma)7eM}o=7(Y-phI~v%Hc{iwBam&--nEP_Jz5I1eALmV<3q}#lcRmx9?-kn-IbQ= z;+Vpexf#s9m`W=8hcg5WI?b4ah$cqI2Gg*qTa1pGOcsNgK@*3;_pVUN>K6Za+rIDb z_x_%b_j#VaVzZW~Bt4RZAV`Y2!c+yn6W~ftjEA3D@jnIOejQz77wwix(!qL_l#^`) z%7B-HID+U50giGs0}*WmZko|!vu8#zly>T|x_k>^;f%mTR|I)b9kkXsg3S)C6EhSh z=>jAa@B)!S1Kt)!AOm_#)+OO@=@`dQnIbmpF}uZv8d)Bo`O17HffXj9I^O9bt4w8! zm*Gy2c|?&Taoq3sEB$#&mUrVStyYT@YFw>WK!!qSV?-*TV1!IbBCKHof`g|yk!BfG z(xe($pQy($h@(rMdAW!P_^MD5^4p%7&JetgTSdkSx>|L%z;FyabKrhFz!iC zkwzX+A~3n;quH=LoRmoY zAATg^q{I$81xxdu9xdN7vMnqRor5vt$<8iAW~0%@vo5*?VnS7U32H7iYE)W{Mxj=! zWUlmXq>T=M7Q2b|0!Dx}rpNN{!0Mwgm3kSJO;^Ltg8E@S>0wE;mvVzT+9`ULq?V5> z0ppg=7iDBXdYu-ZRNl1=4c{|tL5A$hm>$z=@F*+wF_6?Ss7@{;vVs;wmT!}f!d+Ai zc87Q2Z3`{84~oh~L{bjPz8>Rv*6DKqryL}d3!?(-68#hpiruh&^jNXWMMF>9P}rHY zn*ltkMqx%_+po~{djM3t;~ArB1z+?ImzsLXJslnsfKDbvO#yf>ds}<+8!SqTl$zhrZExa?(xSpkfAp&pSybc404nd`j6=%@@=qWbvKCg>9of!g1|= zM{Q49Mk7$MgDc%v`_v^xom=o9(Oeemp(Cb8h0Ff*<-+ z&$M^0|9MU6)X>Lxo?df zGNqI^+09Kf)u!F^YmN2f)i0knKbQL40^uVb^2hM8|78Ix{vHx*kX~4)s|_ z&Kx$J8@|5fTJ0@Qe>ZAATD(K3(r2rb!Ae)xr{6D(?wOj-?B(ZL@$YsePrtMAgg;~_ zUY&J(zNvTbT*iQUYJM*B;oIqFZBu`zem0V@;c~5FX!WrxlYhM1d5SX+b=6>$E73u#FpD{7M6IbM`l+2nbuHr;Y!^LaSsl=N1xj6#^4{)8m^*VK#V`e}7&46BmEU=$>0gKdwfQ{apHAAAQxUf^5WG LYBdd%H0=8q6;5LQ literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/alert/frame_02.png b/applications/external/jetpack_joyride/assets/alert/frame_02.png new file mode 100644 index 0000000000000000000000000000000000000000..c3955f090f5c9e496e536ae34cb206384191a0bb GIT binary patch literal 1807 zcma)7ZA=?w94{km40+MXUQiP+M_A^dy=yzV^ypEb<)x02ju$D5PLB3zd(eB?-Ic!R z;@AQz8#9=_$1RBa;0ytSnP%W1qRA4612t^w7NcVyCX2z$;0K4n=dQez)h&Lw_MYeW zdw&0y=l}oT+m5R8w3KI3R4P@Pt-@Lj|C8X8n!E=7=B)W80@qK|wNA-tuOwU?qoLef z6VQYh9^xvM$sFP-R|}AkCg7!65}h3$MG@LfqV@T9+|FBokFJOape9mP>x#6vjBeCi zm|_YMP=Emvg@hPCD-t0RRdfmXE^lKfqEMt35_Q@gh=mgXlCR0v;AmkAViMdQqS{)v zco?oo)F(+ifnmX5P!rT^IKhi)jYcDe>oA>84H;@N%t};9&5GHwL{!5HM3+GG63wxQ ztVuO-0f|IWh$Bm$G5oSPD=tP4^MHjY9@A=YESAjsIEfQ|+#`-G!*K^eh+c_dl^Gd{ zqf4~s5p)@eqr+U=?T?RwVO9kqN~NtZ5sOJ(<xXm0Un; zghc?91g!8OQ5~++t8s%G&#%>K3EV*JFy`Vq9A75eIXCSI|0j7Tp~oSah-Jg_a8nZX zfB4G@CuDZiDOj41^=Rdch4XU)bPmR#SDameY!-_{;5@V+Vq$f931Ta?7_>%%L9Nqh z6|Q`5go6$Nztc)HfE8hlk!b!ySVIh^)vbVv=^EHsP(P|CUo2r`C@-j|-I8xfYGu0; zuwHq8QAPpe+wlkF@~&fPc%M-V3gleDNYrS+Vyra8L2|<&CZ&vs3R;vnA*^ggyQl{2 zi>{(eKdrP6f+$5qP%ha%iSh#H4!D3@2@=XhQIYdVK}rC{URXaQTI})A(9!Q!lw^!r}rjDTJ6Q0MAAD;Br1Bw$G#tH>*{O1-_L*cZfbe^MEkn@OFe&FzEJ-4yhrFAH*aluzb7N_?ATFj zT6we6)=X1jTeX@B)1rv6U}en|#_ezp!9V+|bxmlyvB9hN}2{;>Imq(^us0n60$R+F#Om@LxZYToM2P literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/alert/frame_rate b/applications/external/jetpack_joyride/assets/alert/frame_rate new file mode 100644 index 000000000..e440e5c84 --- /dev/null +++ b/applications/external/jetpack_joyride/assets/alert/frame_rate @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..8abdcaf6150ec448cba1279fd790c03985e4778e GIT binary patch literal 1932 zcma)7eM}Q~7(O>=80r*1rgJg59Y&_6z4rP+dbA+4d=xoWp=u#+di1XCNqcv@yULX@ z+{|!nGcr(v5dIKMoI|6iac*u7KjN4l(@X_JTy(l6nl0)aDC(H*cUL|IxBYSL{odz! zzn**Vy^mbEnG<7Y#X=A?(V6AQ1OMZ}H7Vvf@OyYglOKX!a4>F<IxHR;fVem*%>?rNv$gg`_0M zT4fvr2+Q(UOu9ZHYn434T;>u~<+YhGLioFf?L>l}K5`it$Q_XbcA}dIg4;7>htl}~Cvjqc;|D4l<}(0~aFiI|Gx8|N z2s)5&^b9h|k47elf2W5+!`cv~^wmI!K2e9Y(4RnbM|c{|qeU((cGP{UJ@({6VOoR0|t zOw7wngPrMiv)*DhYcOpzhoU3y43U01hi3g!03?sb9|V>$lxiR1pfnf^D-*JWWq>4@ znpbu43}QAU5krS~6^sgjhlUeix+zj39i#**#dMfKqcdqRy&J=D%zzt>3v?K+)2Ufh zK1VUW$bYewiH5C!PY`$(BTAeQQBBb?&!^vxo}$Mfqt3T7;R>JhD&5%-Uf`&(m!{Oz z>ijFH$oZraQlL})-~ro^RG*IlIz(Xb>M(wm7GMmlvwbUp-b-*#iA?S|k%)bcjoO3SXTQ#>% zOzJ7S-E&1e)U&)L6I<1><8G?C_R{gjtyogxo-g0x&*#2+U~E%!b#r1Z_ zecD-7TV6`1Z!WvaJ)U#AX6LD0d)J+vGVlDacPkGe?Ng_0Y)YUg&;CbG4(`biwzhf> z>toLPFO=OGcgZ~Mi=3|Czc-F=`&nLldbwrI!^z`P99QQT-+n%D<-M+*`(D0W@d}&c=wpaE;=gffOX7#% z6ZRsXRUm?|-c;op1JyUo1jdz4N2+_~=CCXEr6cf!DHoosshh3a@Z;{!3Ma?FUj?BD z8|O5{wfK52oVj_uzKcJC7RJik9+cOfc`fPaBiB**mAaa18HVE~$KSVpncrUDEN#0r myL(Gp`ofF%$nM_V-B6P&|8eVyd6Sfns53p+u{&+$+J6AnqoRNS literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/barry/frame_02.png b/applications/external/jetpack_joyride/assets/barry/frame_02.png new file mode 100644 index 0000000000000000000000000000000000000000..5a4587ac8f56f2c9ee981d4811def57ed952329e GIT binary patch literal 1930 zcma)7du$VR96uDv81fhoAv4CyjZgvGYj0g=Z|&yR?ors)F$(Jlg16qU?QQMdd3R;k zNe~yth7w^sGC=--B@$kd0U`!P5Tlca5RsJ(2#7I4FagE}lSih%yY9(``p32R`+h#( z*XO?Xy;Vi-{LzWYi3oy>b`>~_;r}RjjZJtC{vKW27(kF0oUF$yd#OUw$A=9x!kl#xYc*$Q5?XOBJCGUIb{GA$kLoY=+nO5|il%j@+$8ZA4C$fUf@*Jwh zq|5k-Y{xK&qus%Q!uCbyr0({i5V(rqCW8_0PZxr`%u7LD=&fjgPcJ;kQD*(m$fF{I z=up0)Gbpq$6q%y_ogNMkXhV{7mp~!9MIF#WPXfsk6#!lgBt9bgK<*O2$tju=sxG91 z5Aot$I2yo?nflB{tO7z_CmRNw1Vx9~(_m?TFirF96)hf>;u#n;^(n~Za1@EWpAA7w zD$dVAUAYd6$!f9a2}3-Gsw3$N(*aNjxPTml$>Z_+fD)F`?EM_n215~bLgsNSl!Vao zYA)VB%#NiKct5YwAtCtCND59jL(8<2mSLrYkx11W)AWSNLl7j9P7-M|jRa{lYFRWs z&#?aJf3ekxMs1K!QDgxt$-EfVOz|N;>QrH&9^$?DxdbL-PtigHWPmhUr8gv-g~$(a)#+!V8~XUtwR>0!%np88|@ zSjzRJro#y{cO`y2uW3u{;E8+UmDV#KE;zF0{<rPuhbsi)WNIkk8H%CqCApZ~qB?g-X0Vf^|=9m9AJKKlFczC3Z;G4D}R z!r8ztOYe-hXqos$Vf&vynnyMNs#Kp|Xnp_TxDi>-YcnctKOelhynWAsmoC?QMBP*_ zG*)$#h;^6OyOfNY9oFE{4<6N&otyP|tL;tZ?Qd=+KX|Y`|7<$mg|Np1H%@IzuZ5qm zkwQVK1iyL{)N2^BW$P4ZT;y_Qd!}rRterFFxG^E;)3&Y>|EsURl6|9LV~Ke=Q#$Of z&h&Ob{9%5kA-h_<;j1!+qx{#+L$X=JEoesvS9^&X=LZPN1rrDZe42Z$kpB3 i)Uiwd`P3bMxW`_&Pj#6`)hz-_=Nw4ky_x+yV zefPWfoJDz);%CQ05H!h=Z!ZSF6TtOc+*t5^bXl_xg2vfdms@s|g@lI>>M5G9VDw5* z05}AhvlM~yR5CJL!T4Ctf^>a-9D!Ndf|RC_7%A8oKbv1IG9}eTE>Cr($3!Dpnek?Y z011MOOuh0)e7cRaN?`6g@BcP=m>2LNOf0aUJl`NnuW=6dfleswtv5?2P0QSwUub4pwtg z6?{mxAPB(WzT}L;4rb@1zVQJOsEVKlJ%$c-7yP`;OMYG$=xA8X06Zd4X1!0Tqaq{R z0ez!aP$*$EXOjGP_h4|?7?PZ`0ua$h>aY>|3rMc8z@Wv9#D_!=le2>1l#eN7IG^kX#iRKLfl`*%>_Y<70RtgbA&WQ`P=af9 zwGj6pWzS`K%=KVpuapWnRL(89hah0anwus&Lhx@~G2U5JBYWkcXkQ(whEN zRN}pI6(urOAGpC5#On33fQK*)9v#-lF(Qn^xE|A|4v(txGazICbOxgfHxQVCNW=Q3 zLr3jLQ{7YhiK73jAMjN6_Y;j8-p@$3`}#4X>K5py%Z!d7H0m&9ZGbtVHn5JsUPA{K z8#oNCMur3XPy~yw{FXpM(3sUM5bFq$LeMMqq54b7_Jz|=XQg=7KdQ?vbAOY%$D6w2 zOkh*}x`x!;`v1@mF+E;cvQrWg^ zW#_WWx}=FS0-=+(T`f0iPp?f{+}(64<799-F?(j_w0k#2>-CHU8)n>Z`^{Bs2B>i3R3L7uv zmr3BQH%-09Kuud`0pn7K-RhdPIpnlXK7qx}|M2l+JmZHiV?Irq5rgFGlcCIpwJBp4 z|8=bCg{4bEvCr0g-m+@usfSnS$sOY()^TfSx?tU$3lrO?-0gX(bZ6vFLHf_VYhLU= fEO*iJ`OTS~pE-LAw;pO#-=L11BKsHFZ>;_YytSIB literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/barry/frame_rate b/applications/external/jetpack_joyride/assets/barry/frame_rate new file mode 100644 index 000000000..e440e5c84 --- /dev/null +++ b/applications/external/jetpack_joyride/assets/barry/frame_rate @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000000000000000000000000000000000..9462801f02c43ffc7bc9fc70ab9b9ea902a908e4 GIT binary patch literal 1614 zcmcIlJ#W)M7mTfsOwFD?`=to}JGo6cz?MxqF`X>$&${zuekfo1U7P5(Hto zv|iYT-y87UoPd`wvpV@+5UzbAdPUmLu2a1R=K+`IdcvnYfQ@#51Iy zU%pBraSUlUW2&Z~$91ya4)9KUvuw8y?5ra#El%Yk9UQorSz_ciyikt}DfX+wf4;3q zVoYHNhEy@P#5@hKn2|HGDlJZlxxlIF+lAGRF{})!&X}(&O0(INn`xN_HATy2vxu+z72sbJP;$klZ(E+;*?hS&O*s>>D z;?<-MI89%IO8NX&K&zwySh&5mB9@Bzc`Z9XpF(mHgX^f5T&spRuvcSs2%h-w1G~hD z_XiAkfsI4nA&)%*lAt(lY*OiChO~f`0js^S5FDCrLU%hBvkDf2Op%JxDK(Qq3uRT) zRivlq9>H5x<0vtoI;7hA8=H5um;=6P>gyzAG-$9IzoRSE~ecXo+xjNX^56h(si-^4zdhvyQ=Iw>oXU zjG#JA&!jumDgQSgxRqDsgS0Y2I!fzvUA4#O6W@YA>XV@Vq|ZP;iPf+^qo?1=C#UeK z)IGkOGIGEPVPK4buE`#ZN0_rpZ_vV`H>$A*^ErS){ObPaA27tP`|Eol%>CQ^nGoK- zy9b+Msjyt0d}IH*cs_A_{!l%8a&r3d4os(eD;=bcIWPc58vBW{uwA0Hw&Lu Ho*w@ODWKxk literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/bg1.png b/applications/external/jetpack_joyride/assets/bg1.png new file mode 100644 index 0000000000000000000000000000000000000000..82d614e1cc45e9a74c6d44d4ae45b772807aae8d GIT binary patch literal 835 zcmeAS@N?(olHy`uVBq!ia0vp^4M6O`!2~2@x4h6`U|?*>baoCX4sv%=@N{)HGqf}_ z(>2mFWMI&kSUT~%wo9PMaeHGQWw$Aj8e;m1rY3H_Ia6k~Ofqqk%t@Q~bK$e&ulG(& zS)H?7W8=r{gYgH#BDGzYq@130!@%}=WtK{D-t&3q|K6+i`#z8RTt?Vg$*pxKo_1HI zm@GMS?3u`SVZB=)g8J>(N!|KzIL|r}qH=DQH)0x$M?uQAhUb;Rs zeAqd4QQF688^X^X5pVTxsofP5@Z;DeVKe*aIop0-PO_EaY~CCh;raj35&baZD!+(0 zzjVFbYyRCiUe&2SbN-wzHmPi|;UB7-Mv{pZT(m zywh3cInT9!w$@5i2=5KKX!U(TrmUa7R#cMoIkN>{YPx1s;*b3=De8Ak0{?)V>TD zL7AQ|jv*Cu-p)BViAj-%b-M2V|IMv0h^{JmuI#%rSa=m@{%nKHon~S}#Y*?=Ru=#TBivFikZ4_Zx%pk#fK!btGLf((FCW)LCj5w*^b@qH$g|R*3$>ZJA zpMTGrwIO`binj-UOzldv?mo@$XZ&-@1WBtft$*(x xShl0Tw<`T`xX?Esf3NW-AFq#6TnHEY&z`#_Q`kX&5-=thJYD@<);T3K0RWSjY2^R_ literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/bg2.png b/applications/external/jetpack_joyride/assets/bg2.png new file mode 100644 index 0000000000000000000000000000000000000000..ec8590d3ada26094c39a3019b72084423c75ec41 GIT binary patch literal 968 zcmeAS@N?(olHy`uVBq!ia0vp^4M6O`!2~2@x4h6`U|?*>baoCX4sv%=@N{)HGqf}_ z(>2mFWMI&kSUT~%wo9PMaeHGQWw$Aj8e;m1rY3H_Ia6k~Ofqqk%t@Q~bK$e&ulG(& zS)H?7W8=r{gYgH#BDGzYq@130!@%}=WtK{D-t&3q|K6+i`#z8RTt?Vg$*pxKo_1HI zm@GMS?3u`SVZB=)g8J>(N!|KzIL|r}qH=DQH)0x$M?uQAhUb;Rs zeAqd4QQF688^X^X5pVTxsofP5@Z;DeVKe*aIop0-PO_EaY~CCh;raj35&baZD!+(0 zzjVFbYyRCiUe&2SbN-wzHmPi|;UB7-Mv{pZT(m zywh3cInT9!w$@5i2=5KKX!U(TrmUa7R#cMoIkN>{YPx1s;*b3=De8Ak0{?)V>TD zLGL_W978JRyq$BguSJ2!HF5L*|EJ#^PT^STk-f0G^UmiK9)qp!+I?*?UY;z+`K=l* zFJv$fVQ6DI5Wp}a-h1(!;u4uWoy`{Uf0`%W<=ojf^D6TS`)v{~fy z!Q9RB_XYBvb1(l>u6$l)iS@G=TsLffPu;z_)b5}4R%1@Vi?6;noZUP>NNXvNUenAU z%6+jery~U-q9+S^IbGfmwOJO_DO zEzBW0?p0a&^Nk5k9_x2n5%>BjQ(JEzy~+5G3!s-tD=)+hD+FX>9_pJov#eO^bb ztK~C9SA`apSFC#ExB8|IE0a_*E$7%bnb?*JlzA|Ls0@Y+se_JJX-n z)~kM~J+XY-6|Um#g+Ht%?bsVQ>-hrw|6gGErvB~I_9x$;{F=OoRY3F}^MOB%JgZEz TaygEGawvnRtDnm{r-UW|@zu8~ literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/bg3.png b/applications/external/jetpack_joyride/assets/bg3.png new file mode 100644 index 0000000000000000000000000000000000000000..ebb1dd66ba4e92493aacc09d90e44096d5035693 GIT binary patch literal 886 zcmeAS@N?(olHy`uVBq!ia0vp^4M6O`!2~2@x4h6`U|?*>baoCX4sv%=@N{)HGqf}_ z(>2mFWMI&kSUT~%wo9PMaeHGQWw$Aj8e;m1rY3H_Ia6k~Ofqqk%t@Q~bK$e&ulG(& zS)H?7W8=r{gYgH#BDGzYq@130!@%}=WtK{D-t&3q|K6+i`#z8RTt?Vg$*pxKo_1HI zm@GMS?3u`SVZB=)g8J>(N!|KzIL|r}qH=DQH)0x$M?uQAhUb;Rs zeAqd4QQF688^X^X5pVTxsofP5@Z;DeVKe*aIop0-PO_EaY~CCh;raj35&baZD!+(0 zzjVFbYyRCiUe&2SbN-wzHmPi|;UB7-Mv{pZT(m zywh3cInT9!w$@5i2=5KKX!U(TrmUa7R#cMoIkN>{YPx1s;*b3=De8Ak0{?)V>TD zL32D^978JRyq$9}?~s82>+Dtk|DS%xc+%-eB>Vd5mIlQxKPpdNImmZaZtYh2hd-8b z|0ok-Sj-^7dO(BW+52;|`yPAv3BTDo>0x$|1|kfk%CpEu|~|2b{%-)Kk1G3C{h=b)tTch2l(m*?rUELq0F~>*cz6 z?r+ZMU#zT$jn6i%b5s4zx|gSBabj@WuD-~^3bp+!o_&`xJ6gKNcc*#1RgEr?KXqDa hP}l7MgmZqf2kd!Rba~T-7GUHtc)I$ztaD0e0sz#Bj4uEH literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/coin.png b/applications/external/jetpack_joyride/assets/coin.png new file mode 100644 index 0000000000000000000000000000000000000000..a2b5a409e43ce74ce6d84d83d8dda61c67b74d5b GIT binary patch literal 1842 zcma)6eM}Q)7(a20fx)N~U6hRT93aE?u7^~5_Q29sVbBIj8K7?K(Y|d@dLO$xXd#9v z_z~v(gDG*$uR*4Psl+U9#%#kab1c(se(Xct7KquhEsn70Viu=^y?5nP)a;M9*Z2AT zp3nDro|Y2l+QfuK2?&BD78clC@EfO|n3?eRwE4_x1c{x?x+|4RM=|9UI6dPNs)0Vj zi4aE+b6!Mbyfr{Ut3iO}Y3$Dr&R{6(qp^x?2jLK{AjlRpNT962>Gn3%cuhVmFE_y) zp`ZZ{C=43mLcB~xXiT$9!T+il$54%;)X-R^qXe}I5Dl(0( zu>Ob8Rb(0+*4p8CbQT;pB@tP%*TF)J7IjKMV|mN&dJ*6*APcpU7uf3nuPoJS0liUH z2`~zf3~B)#fheS@@cy=3G;$oWN+zWW*;qshS3<GVpTr7QKd8 zZFo>rYaxp9s{UzAlmuU`7x=Ugpt&e23w|ZcNWc<+-9uv*zn_JX)}wGP*#HkDltf8A zpanAF5#Nrw^+VCa;0;)>4(RUH@~&4DY*WRPGjmRIg7w9h`(<7YoBRHdzPog z-?qR1mu(w*yX;MkpKl2DU%Iz7Y1Ipx(|dlu5y?sJ?D=TmvZt@+RMpYp)2|%oGP*M_ zUc}5ty4ICOTsbFQZb$#Tq36k)sn?%m_NFbI-)p#SYdhp{R^0iHRyMThYekVuJ-qX@2e8;HO{BdAh1Jec!VOHEt*;&Lurxi#x9aVzbgH4b@b3zz7`H?FH*{Pp)8zrDDt=BChH`qS&reRAHQ zoc*{l_V}#t4*okRD{+^~@4QoV_1d->CSm=(m{t1%mxpt9!^c44ON!lg_#GJ;Nwa@} zo`{6uWv1eCmW_-cSI#9`RE}6sB_qh}v+9}AmN|Pd6fP*VS=>*wdqof9srAf>-;AL@ aZiz(}u8qk%++N2+22yBu+IsRmP5%LQYG}3q literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/coin_infill.png b/applications/external/jetpack_joyride/assets/coin_infill.png new file mode 100644 index 0000000000000000000000000000000000000000..ab37874ff8b25de5a5d955a376dff3534ee4ed41 GIT binary patch literal 1974 zcma)7e{2(V6u)g@8zozun90zX;}%4j?OktcS&w#OYd2cp_N$!~voN~$+xA?0SMILs zt>9$17?8zeFoJ|>1Q$t!kc|l>fK1~MGEoqf;K2C<`NJ8(1at_P`Mv9Yl@9TbyY}Aa z^WOKp&%O6jfRABK*v%9D7|M7|*lHb3&>=JMGu9{%?9mE`JKE?rc(CFk zl~JN#fFKZEs1yva0wtL+B`yX3%Vr!y6^hts!kly!YUX%=>NGkHffcDxBk%E2HJ0*m zXZU2o{Gu45a6A%;Xd?LOZW zj_GRP!lDVoAdZd)2NE+CofXE*heF^of@?JdKAj%&b0R1BxzJ=raXyo9f}_ZIA99Y2 zB+#LJGoK*2LNk$R`oHPHU|bo3Sk?rE7#B6Jgoy(LM{@|^H9+9Pyc?7?0anaal#q3y z%v^xu?XWd~3DZuQs~8CcoE9bsSOJP|!j?RMtx3QpC5y$RIS&k(ueeP?7MBRjJb-uD zc_cyRs|lT2YjBVRMQEu4eI7wl1o42A&1|mXIWH4{0fn07rKqjUtk)X!dNrwu?!sbV3hHZ2T10-+_DxXEW~r3up4+3Ih65|QGxS{5f=|ie6W8^Sc%umK-HR2IGK!( z1w2Zkq=wKG#Ct{j07i^|&ssf2lH=9kGv=c-^+WTCq5mr%IP??w#JuA3NmP40A0sX= znF+a!c!HoY!nCaf>xkLlwu5UEpWK`9VRG{V7B)Q(_v)qXSvL_RX%hn*JE5TwToy@Z|GX_gx%1`A2Wh z51n&V^-H7s&Q@mbf8+j7JvrMlTTfJ9-gWo%*7}1Ny)Qb~R&3Dsb+_EOc5-0HIhtM( zm^<2#1=@(B&*pip(TjBdxdq9$FD%R({3Wgb)*@$T-NL?4RL{=ow(dBCk8F2TuK1>` za`0@=&$q|8di6)g_B+3y`}zlIS6Y7EG?H=Wh0A~4I~9EOnPsO(gLD>Gd9Y&_4y>fi5M_UFhA61HgAceTiqkY>Rw0HIHD%TF3 zGs7V|5!5jWf1pd8Q!^3cG)#wK*_fh`=ztIwoW?}O{ zjYvWP7Z4~^bU7KG6t$SFOTu@_jAN)w5z4ig*_4awSq`8H$^@kf(*>g%&T1p`4H=Wp zaHYi@g5V}`yrQB)SrMmXIXfP!R;zIpffIxRG8DX*5hzi?@KKV4U&8=+3rD*Jnq^Q) zlPYCBf)>Ldj!udLk)Bp(_{sEPA#e%7W0fj=CS9Oy&!J1m9J<@V3M}tn-BSt7+F}Zx z;|R<5Y!{JoKZ|TK{Wsm^nw17Gq;Gi*+CI)6&zDi)Anq@ z*d@R(Bip68oF1vMg$xZdA*Q9w)0h@ZBJdfz6h9N1>H;YTXJV}|wm4aE8Zzqjxg2Yw zoe<;mGt*FGx;`;hotUT~l>QxH%Sh-;+q?!!fGk2q#3@t>3L>_EAjr6QG9e*GMUX0$ ztSqzPBv>hd`aiyOo>2|-Fqz0Knip8kE1Ud>d@b1MU-_3#T0Y$R(}PnvOS8fOpyKoM!zZJ| zrI~vgo(7+jfJP?F7*goxx543uw+KFUjljj!MFbdl`*84@*;qD6AjrIJG;GbBmLSL* zb)LGO7(-rIXG)x9*F<$%vH4v5aa;V6i_U#@+w0>q#!nycj;_A4tN*>Ii|Ynfu5wP4 z{2AU-*taTV#X#%w#Oxlgt!()LK6$M2&e#y&HnzSclPK#uGLo9u(EshhW+FN1#MyV; zS94xH9dPLA!9{CKrrciL-IK*5edWDJx7>NRygK@&rA|+W{^;S`Rh=J3uN!UrF1f>1 zMn;C~LLUrssW*~W*Df9Jy;)G#uIP)p5z=xdDCUdc-GwcUeWyD9;(i*qTvO6kd%ymB z17j;GZ4jdaskDH+2>ZT}iF+Y?25K9&_(1yp%IoZtWnJ~hE*(F)y?e=utG7m~+pyly zC3_D=Tdn3(5C1-MB7b762yc^h`81_~6=x;y7FYNqT+}5>T{r>pNfhmUT zE6eY^;27FEdaU)8!K$66Ve!X9zI#Pn_26Ekm|S&O?KuCz!>ZDrRgao9Z&}~|=GVvv z4-RH_C*e;J`hxxTrB9PSf**_p?yO=SK^BHe&pf2DDFPaEjE2;Li2a-QV#GvP{nlmqk mxl*{Mb7*k)@VQ%$F3%_PQXgr5c`SX$5Mz3d;mfoQ+x`KUOK@NS literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/dead_scientist_infill.png b/applications/external/jetpack_joyride/assets/dead_scientist_infill.png new file mode 100644 index 0000000000000000000000000000000000000000..6f036fde2f35d695c8eb2bb4ec27bb84f44de90c GIT binary patch literal 1900 zcmb7FeM}Q)7(ZN8EP=$a5p-rdk2t5Sy>g{UPs&GIutko~GO7}>v~Sy!wpZ@1^gzbc zm}Pz?GBM79%XB0rgAtI4*<_MsI0<8uv5zqPn46k7m&r15INj#nyH>v4vOn(QeSXjT zd!FZa&->i&{M>bsvZXQvK_X2?Lm_-d!D~_YJb2%a?@2|F`8wKc;Vo1SX=6MJtDPwa z3c=%pID(|42|lZ>0`O=#aME5aHhQK9LutDfD^XKQ%BKe|+E~MaqMBT@t){}Jv14he zvJ`=Y1RlU!QNiQ(a-^WeBwiA}i)I`{B^SOzi&?0ARL`&gRV&mAC6+2fQ&_u$EHq?= zHp7(`bMd^7#PL8Npa`fG4C}-bG#U-AByfU|Lk~Gu?d7e4+{?v@6hRIH;A|}I<7vi= zik#MR#?Nap4B}{r90>FzyO#@<4~4)*1W!;X@u}`U7sE50i}6ilG;PlWJZmFQJ0259 zL}s}|`R0xwSbcLjQ`En^dpy(1;P}icC`3rqX(c=gz?rLk051d_<7aIkvkG|mI7tan z7gEo-8MX+v2GC*&ljeL{0B(zc_5d#jMTc183~<8~P$OXzngvNI#tu1EGa!>*pU*N5 z+6^(TaGee{W$Kd>G)YNvLJ^EF%1D|#Rwu{-UMKI;VnO;zdkJk9&7qVeyI7vvFZM^V zmxh86QdkMHOk!GW4S`RIvSCgLeln7Ry=}MhR)dv?i4saeC0DBDM6#JslImnqsft$; zq*5tGk^C7u?Wq1QZ?T`z6zES;q><)$hOL%N!6q*PmBCeT>87Rb7W-TDx7x(&w3v@& z?0y@tOQEIi7g3IJ@Bu3eGMw=9YOxH5gN8a(qwwI+PA_0l0)_g*Q#p+@-~y0wqPhe# zL6E9MQmqbEhtHXh)N_x`Cy4&ve1f}X3n0? zH~SW-I|{ONrmtc_do}lYV}a`0-7ChE#a%@W!}m^I#kaJy9>NMw0?Iwey;Tr*gj+ja zdwcu}_u+V{?>w=(qIkjb#?KnRtZ!$?)N3tu%`%+Y6~48fSP)lV**|hIQn7OL{HBdJ zF8o#Dzhhdzqa{m7U*gy-n1xymlia=P(($2@?q56Fzi)_;m94Eg-j^43V$YvHv@h8k zwc|{|@ZtOCc9*pdIbO1C&fS*O*<5$~T6gck0gB3YM~{~;2D_B0pT;_jHA7U-!18%x zgDc|uuP^Mmv(nN~x}x)A+4B+2#)IeaTd$k*vcJyE>+fs-aqJ;eCjaR43Crc^SKnQD zvF@ksw<7PoIQ;vAvz}L;O+Tk?x{>|I-fe^9t80!mpBmMDvb3q`@cX?nO>O$0j~+WR za@xH7_P2f^b?5!$#4_D4?ha?#gJoBA?&7nz=5+<$F8X54z{_F%ZLa9=z@;bQ?`x6I zxPe2Eh-mQ&L*8tPg+_zPkYSEJwEw_*8Im5Z^W6Nqq$;LhY}57Czpbi2&`XW>J#8*c z8ojwSht8=S+n7_>dAYlG6YVLD+SK|^*U@Fj2M_N)aqsFg&y{ZjIu`BT1p~-tMLC|QUL6-ym-vT2cItu)@-`>9mf?kg!%=v7-DHF4i9+AaPT5(ap zLjfFuRI>w=#a4>5uoZU_UNv(6==TUr*wsj$+$1(pTHHk#%4s~eJj-k=FSRM{$n121 zDu4k49-Otn0gv0uU;#D4+r_{)w~Qh%Phm^dNWLi>){-<1%SCdL7)ckvD%$SAa&&Y1 zHiMZOaj`6gp{U>Q7x`r(l6ImJrBaECrKnUY1Pmb)^s<(K(92BaOoVOdaK=Ux6ibj^ zn6qiIl0H_AAOMG-N9Lg-#=T5m_Mi@Ez(S!Ckr*9Frd%XTGA{BZTO#m~jd+0Q&tZ@o z4jDpc3CBz595RFsYHc#TIt!0yP$CSgF9U_>E9#(tp6AV&gA|VD;0)=bZMeP+_p(#@ zS^#gDmc}hCt^-4jNX1f_P^=J&Q_YfDn0OYJnwlb(ip3GKiL?`r;7iDI86aZ=*+3q4 z3v2m5{7AtujvWpPNb{8u_3zP=ZjuJUfgEIfu>FuxtIeiK2jK=7lanzAHtMwsiBh2u zN<|W$%bgpRO$2avzK-zVUIu6kcuso(EEotX`a#}zE@&;_AZ(C3SSY4_Q1J0Ait7e*PBVVS3WJ)0#vf$U@4~rqz9_ATTF}1eP_C_?ho?e^B%tC61MUH^FT4is7jRLb zk(&xkB6l6`1uCM!O@_zy$RTLhG6Lvfhz=kqx!PBKcK#gAxYe`YQ70d7h!++a%==76Lamn(|p5nxi=i-OSYdZffyj+rft-&{DoPLa_bm8UQ-DS;!dEFDw zZzGq;{tz=Gns#j5aOKZpgY!Tkb?JU_QDIrycbC>oN)kn<9Kq7l(zFYolpnL6e6Olt z-_yfOzmg|(#O+TVRW+k=b6ow{`d>~rPQNek&upj6kBSbJ)Ql4R_Coe(O`*;4n`=92vU)b2sW?|V%UZW8xc0_P5xXMu=BXc3-yHsz8cnBoN~K+@%+cFP4kde^aleylp3Z3)bCj>rt@kFD=5N z4epy)0&o9%p}{i}^X|ZRU2i>;zNczT=f;*J%X?qDRrB!tPbK$Soh_j$Z5P3dG?FqD zFc1{`12=|kN{Qv3vu2}CV>YbqS#UOXnK*joiD%Dn)w>&Zjk~_>f%W~<4PA-3vYJti zGw)28sMGZx?Pz--+?jW62U9CKJi_?~6v}YqT|IcHUe;)>Snf)N4(^RAt<}^eY9^#T zi0j%?ebzkj>nnHaw%_h;>X<<8Nn*Ms=QA%Pbj3bZsxut_G+eEilDuW!;k=zoW41Tl zdwjJLQzU#==c|}vA0O)IGR8$E_EMAYKcC9UI5vFS+>28;T~r{9P3N*i;}V&}X;3G7?urG*H2ZM9KF{y> z{NJA6|9@|nl@=u>q$VH;l4L8kl*4x_d=j6CgTK={tb+*hWD4VOicWh8>EZ%vistHo zS_%Xqjv$5tDM-0|Kt$_+hhdG_(Bb14%FsrvI>)ZD2hG6C6xZ{hqQ2DOs`t6{G**zG zV30^?AOJ)Pl>&ZNASENF*d^hAc^k)2g(CWlnA2W{nmHbzIqDp>2Fp)C4Lt28%Pq^s z4#SlZ^NM1S#PM)AtPW?XIo^Y7^?E(7A#j3FL550*up%X?SRqX|5w&3ff{SN@BEzw$ zY?G?vLZT7FAdWtaED($tXN9rsVI6RZ3gTL|2A@a{dO493yxb#>#Na6hfy9jGFv*RK zOreX6`w?^*nL>xPw%Z?{MIbOK5ka)BfrS_=>ZE`k<}ElPL4cP7feZ02U|j=PF-@rj z^hTO_K#9NtA0tL+h%A*RM@48IL>8I#JgL=WY6y)cMz(V_-R&Y{gM}vaWd~8JHXUv?R<6&?xhb$%7amZ#im+_pN@k2}~FDgWBRTMIgf8kBFAv;`;+sAg!<8?!aO zUjkT<42;=P0Qr9WAz9#+ECX*e>Oz5>+lI~YNkMP%b*5DNMtc1h#VhLwxWGh z0bY%+qDw!cG!Tj^G9oFL?B9q5d5#Xb0Ig&R%|%gxbBke$2PO|xkP$Pv-3*L0g2LWp zJS^Z*0);h&jX%j|*bC%xPL|dLwcumX;c{C)49|d1Nx+~GCd>hNF1iQj3mjB0BJS1cJA}MDYj51S zB=p=_)mcQW?%R9Qq}$&AW$P{?FL(c^F9pw+E;uy3t-Uqr1-rehH-D(B=4PL-w|(7> zmwk;Hi7Ecj33L1Is|_dL%%~dP`E}ljz-lseUjCfh*Lc&FycJC;BfY;mnvbjc(yk@95>H0?ZiceH!|GJe-_=TU9^S+j)-G;hz%kOGyNrg5RW>WhD+P ze27aOiqTP||8$Z`<^+pt1O%D&mHbTGmN{zy+_c#&CP(~^g`2x( zBHF~bl;Zl_OBsugRWJQ<{kHI`h4DXs@oawjKHnnK($5<4oGNWa{+{_4=X^6R#$y2NQ3`ghPF^TS{9%;$eTx`@VVe-Z$^P=PSz#VbV&(`H*F89JUINcox2Gp%jH(H5yu zSI55&KVU>{9j|8$#qbKGP8aumvbMimw)VHJoQ-FuNAjTt4jjTw6gmwz&_W$Yel_?P zW*MW1!nbu?F;-B4`2=N>nWTcJM^N6ktJ-SuL1#0pbX@1$(`32XY$luOB=c)>DwoU2 ziYlvW0vL&)<#IDjxWS}w5&I~T!1AfbDRYtVX>PGyu44>1>NqDMJ@f7co%BHnSs-#M zsmQ%_ug*9N>dfm#)VHS#pWDc3^^$W0a*hu2U3@}ldKZxmJT>o(RHk52f&RU zFr`LdSG3rx!EA7v9)OA_Ck3Ct8){Eg)O140B-B({O>61ndtw#m%_{=Kr2(v*8zCflP$#Ai0Gwyt7} zra^h&8-}(>1J3+bWQsd!jqJp$c-f#)3yCHYeA5zI=-Bg_y=xIWx`wF51RAg^Z<;=t ztw9axc(z)lpjrz-chZ_me54|{4ru*8pUpZE_0xaTIZaVJ*~u5i6BYKQ@xhmN#)O{91bM_Zn0PQcHC iw_N$t!O02w+`cA#d5qq_dp72Xd0(1eF20@HeDW83_Th8@ literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/pillar.png b/applications/external/jetpack_joyride/assets/pillar.png new file mode 100644 index 0000000000000000000000000000000000000000..61979b393acb5f4397d25af4c2590f7f4b4bb1cc GIT binary patch literal 1880 zcma)74Qvxt950GE%J>Mv&?#~p$TpYWUAuLqXK$oy3oWd3jv^Zw8@KkgJ=Wfxch~h+ zl&^$OLk1fk8WBe_5&75*i%~I#5tNTPaPqO>bbjE7K!9mP#USdt>*zKch)rJG_kO?k z`+vOu|Gf>xMRP`L)3q9nX0*#`FM+>f;mA#S2!3~u{7uwo9+}8^N~KbFA?fA9813V# z049fdh-);KSu#(1tAT`6fdIo&Xy3<2P=xVO=t85LaPu}0WSlVp%#Rg$ys>Jp*@w=` z*IHx}3WR|~BXT&zilj`TsxArtE6X^Fs1&K1LQCDnh>a5fV#JIXf#z!wi{SH0wF&v91 znsgNxkth^}IC9UkFrN@-#s27F9&nlFaXm)hgUNi5lQ=QR-DgVzPTB}$W*~+kW)vie zE;0W5&=n+!4s-2xKRAkTct{|k}eZ z+5|vLzzzq68VEyyvyxgPyYk}#3EGqVW;K_tj-&d2y`??X14AekJ@hUMX-CHnvH z6A333cHAjgnh*47V2_OpaRPJ>#*m{rI{>+Cwqk+vGa-nHC36Z8m&2B)H|OQ)447W! zD(6NPGcpL3+LL}Xdo`AoGj@I(*dxM@kzmi*1&op zU;_%!ucHFW`Gg`$fiGYgc%pF=DpWdvQK&f&A7rL12~t`Hv8aVaIvG*ogj#he-beGn zOYvEJ8e-H2LJ+l#NZPB|r%+ztd=W43sZm0?I4W{}DM|~#8h{l5pz65vf%(s8;%qZzi6f%TA72O3T0mdKXR=M`8dteZ83$~@MXrYm=P_NQiV?jD}? zg4O<-wPjO9<*M$>70)zV&2+NzE}S68#LLdX7p*J&z|Bvx641QY#62e?u}Se2R9?5{V(sKH0_AC zZtQx|dA@1wwx;cA+jpF6D7w70{gsX#Gpk--Q@f$(5+#E!uZt`f*3yDd!f`oqs-PiM=fEE${hZ-P%dV zZeLlmXL4p*>W_CW5*ss?EL*$3(757m%Itgx?s^`n>bB2Xy^}n|b X8$D^dPo8AzRUSl_qsZP|uw?bWG&6$} literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/scientist_left.png b/applications/external/jetpack_joyride/assets/scientist_left.png new file mode 100644 index 0000000000000000000000000000000000000000..a9e880b6b2e1b8ee4a19c47c48b66bbcf88bb29c GIT binary patch literal 2056 zcmcIleNYr-7+)$HC4pu<9Y$tsXU(+eZtoWE;I>-{xI>QN2;q>AzSz5a?`{Wfcimm& zz(i}9Qe!G;s4%I)X>ueGqbZosH2i2rK}I?eYDO!WbTGnE#y&=+cXyEwQR|=n*xh@d z-}C;S=lQ+Q``q@N?6r{*%OVg2iL_@}bK!R(e4-XS0N=v(=1BwzA7Gq?QlTS@baMe6 z?crQN7Yy(aM-WSLkf+_HKtf%>$FLMO-hBu|84raO7#(^Cp9cI)MwI~as;&??xg{~rA#|b{%U^bg^J%JO17J6vKN>-wST2@>kQ>YwPAi4#H zml%#kWlq|~l}i+cK^&bT2SH|rofW6bheF^of*W*te6~C9=Oj+_bNqBhbM{Qb^EOJ1 z_a1R%WS%>e@9q(TG=Dc|hvWY4fxw(HM9H=h3Na<>oDyya5S^7gz;l7fl?!fQ+Xz@` zg`$M43z^21aY7z!4M1Ur8FLO31Z9O*CIDCwicVqXJFuczm?1#{r!`Ya9h?Vp#@_+i z)6#MT&dZcROw3)IirQ^yCWF~z(h@o~zAPhY570i41z4Zthk2>|Ge803k?m?uidinN ztX%Goe3pTN5K34DDxAS6ERn!xMJc)~1doh#z~1)I5^bd=m?)tq;uKUIyw=iNcG+_*fvI1WM@iI#tN&T@`)+ z8E;o-FgXbWsW*_u_^Imf|2H3aC+Ai%Hy^^FsBIt(iTBM%xdZpqM@9dWKC|*scioZC zywji3$AZf<>Gtti@OcNUI?NhkP*>Fkha;S_`1F{Ci|IiPSU8;pIEKFmAFM}^uvZy) zcjnz01X*2IUe_OIU8ngj*}LtAUvsSImzAxx53e+x$Xb>;5Cir%R$lX__rwuU(dl$UM)M>Y^x;&|9gnOfpUybbZ(kuUZ(|xGW(fIZL1G{w8!It-a zzi{A_btilKGJn&IAI7YYCP%zmySQXqb-HJH&q-u+$L`c`+TTg;+cDBY#J0LSvg$QO zRkjx!Mt2^qxwNx3;d1um+o0SyPG%0UN!%Ci|iP?Vd(n!CnE3E z%jTM&qfd*V?J{Edkgv`kbanHehmXCT9;#jXcxP8!-PX=L|Bh!*MuzaEo7VquaU`rK z_GZQ z=lMO)^Ly@j-?ge zSb15tEk;9v5KtI27UIJ)9kXK^FAe{z+c<`5CQ6GP^SW!%N} z31L*_WSWJDV#hFuqe*fQ(sf>pBq~KwW3g>@B z92FU64&{4zgcu_}%-HRIym=@zqzqYcu7W}&MIBPYU;x?EDgwM7$U;Q&0p}_ZRtnOU zV0|fnF(UC=OIRNcco2f7GE9=xL#jH`l>#qF4e(O}c8t_$wC!3h26(T7gDx^`k{z=? zfHkFI)K=Xi+8^;L6Fm$TABS}hg>Wz^%VveT{*69Dr- zIG_Y!UONAMppj$MeLW{_Ta|;4sNd6qFb4&sw6GfFy^q%Up6-#==D_HH*_&B=-&wQ5`X zP&9y*`buB&oHh;WJgD}JPp!_5iITuZe1O$LYty2lvfx*uj07qIu*Y_+!tdvx4y`C0 zG%gSZ5=xaasY?JZQr8Fw z!@EO*m&BNJBPtLiql1H!I&4A_WXAf)`rcwkUH-{(Q|I`)0@t{_W7*wxd6Pilj$Pck zTP>#kYn!(``{^D327c3x{O2s~hQD*ZD{6Va^DVw9Z_@3pzwYT_&)oQ-|KR1e-rq0D zN2k;jPdI#WWDmbIr~BR#xj$#$#px@8yT?vnGRE0hwfgAHqKo$o7Sqx@J)akCyLVw? z^U5U|i{HK3xpPJ9m8>g!Hhs0?*4yIi8@i6KnZKsZd~o~C?mbn8c8it!Yxk)|rTIwP zf&IlzC;F&`^^4|um%cH3qjAQOJLIyTIs<{gv{hZv?Rm|U%Z-H-3Oe4*cohuvy|%f% zsc!1!{*C4C8fk3Lf`xtFLRXjV@Xm3&;x9JOx&7t3S$qA7#K402qvD@jA6`^XX2Z2ht3Qa89-hJVg-XBg_@d3c)7ieO zXk{CgfuB5E`sA7750`xwA2`(8_sp6LSN9s3z|--oFMWHi1iTmcW!%fAZg|;e)z0%c z;X9E?6gp3#`(shK7^&3PG$azph10pPUr3f%-6SJOPM-Q?AX~PMhnq89jtWm^k1sPf zvOJR!muE)c)4^1s+s0HMK)8%)&u1S0_=U;W5oGG!>`ZP){s44BT+SNDzB$WZ`3G@U B(K-MC literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/scientist_right.png b/applications/external/jetpack_joyride/assets/scientist_right.png new file mode 100644 index 0000000000000000000000000000000000000000..dc40b560de9f5d5212491fe62a09f849a9ba8b56 GIT binary patch literal 1917 zcma)7dr%a09AAwX#B2g28T)5j8u8KH-Y#&=Ew>QdAsn)VaN?n8F1LGkD|frs?&9sC zW9EdBj}RZ3jyd8Vj-e&K(k#Pp%6!kL;E;`GW20r`BMe4kq~GrH6s-Q(yZwDXpYQ9l z-~H|fMTNQJq9;Z}5H!w_XDUi>j5H%uutp^i z1ULj)GnF9iu4HAng7tDdiQN0D8G$*5L}sT_CMsxSeOz9($d*(WI^ETkZVQ8CW<*;R z0t5)KG7T#MKQ9pqiD+>NaIczC1lA~WC5gDGBG@K~ESzdgHJXr&XxJ(;9-`Pjz1JC> zNW>@0K>|fXp^!0@Y!pNO$BA zzaW-?(O^jg8!#7f3hQ^-xd6*cKy(tZJcX4F!mtz#?AJ^WN(l^znfw&wu-S@4!Nd6h zCKcyq!;T!A8MBzp2HdFUS7js|0ouzJu)J6Hfx7hg1Hf#KQSEw7npthnU!~5+ES>{` z;96P@at&Z4l7^#$vXqSofk#GAV73`rrtP#03dK!$vcZ&Uz%eI|6Ui8XrA;&8gvq33 z(f9(xdBXq2R_7VE0zO3%d7LB*VpucjLtetZt)KLxpVOvWoo|&-yVdSUBq$0@m78U> z)Y|l`s3dsg5G}GQ}5wnf~a|=5WW1bE~f`PCQlGJ~iLpJ?H*}rde(IF;m+2Pcj!=2zwSz z+AO7aExFruO*-0D-js_kY}@r9%e?8ziH7ZXdfMJ2^Me-)UpW-9qp@M!n-o>lnsIMm z*@L#q*2blG->R%ldLiCl)naShd8_8+dr74oTfR$g2`nTgPRNMsye($kNS{#`|ETpB zXMMAwE%8Q7)8VLTpGJQ;t7%KyftEkTpW4r^oO879uXW$sdC#1RO-fQEogFbV!Mh=* z`(e!5_PR|=tJ$25ORft~UOTgH_vtb&>Tl6#R?%;Uc(=(zJk%Gi@XE6dN6Ti$u}Qe>w6`qaw1&-tz`>)5^j<*PNT zsN2fr9n}wKi?vtRJCyXAofhA*cOTbOT*&`>tMv_L-Z#Hb?CfmFJ)ed?fw<$|TceZ8mW*G@S8qnqOke}oSv zG<_C(oIEmrv}M7WHIXyOWpks?mM`vFbn4qn=NzSz<1Zh))19ADzHMdmw%>4b5_e0m ch89C7N^}2Mv+B#a>Q~c|Q)vG@d%^O50K+qvi~s-t literal 0 HcmV?d00001 diff --git a/applications/external/jetpack_joyride/assets/scientist_right_infill.png b/applications/external/jetpack_joyride/assets/scientist_right_infill.png new file mode 100644 index 0000000000000000000000000000000000000000..e4bc7def8808e256ca957c218ce88ae9ab722036 GIT binary patch literal 2210 zcmcIlYj6`)6yCz<(3T=jd4srawba&RA0cV8BrR`o zr=<6~s7@)QPsP^!$}puk3qc+gIgeNIy64h9A!KA& zp&l4xArayTVk?S?jIR+WXgvsUVLSH6{sS1wv39K1>?Yh|DF|}qaS7DKD?Gk zMTKd$7!3(RKw;2Wh!4wj%#LZiH2kk_;~1)$D2;Z^>#jsg1qq;LquEGcg=wfwV*PZr zW6ppxT-mXpqKGt(N25_=)MON-08U!1R-B-4iZVb8gWMEWn3y3fXQ>oAhXcqyi4zr0 z2%{<|Q!hjmJBC3V9UuoW?k;;+9w;9QfvX5k8VNkvTnq||AO{68kX>h24{7SnDx3oN5B z4n~2AQUql(5M~3F?;!}~RCw-Fg(Y@};XIS?K^s(XU88+BH8$P_jHr7WgoWg^ob{F%?PdWXEbucCUcn0e5)%ST2~rQja{~-o$UzDlp3JXXCLOWRMc;!*H@pMz#3cY1iE9Le z;oTv@OJd>JhTjn+rImw|I&4A_BxikOeRrOtYTWT6Q`@AfEZ2n0BWWE~nNvabyF0kG zHyTZSS2k~X^5fh74g99wanD#<41cA6m)rPW+v|K?=G2>8f7#W^p6dOfZ{LOH?qAQ# zho)ELP3}53vXftu-f?HK+?T%R+>D0c&haxAKklq8TYc!++;evf7Sod3ouB2tbLZ@o z`sIsL7QJ=7ZF@u0rPNEiHhtM};|=lE4edwQ%v;lJ-nZ>~$F4F%i^ah~iBT{&D&sNnn7&zsHLoh>_Z zmp5Z6`0>*PkDbc3vo>+7C@@^v&m>9qO!nfb#gSP`ePk7PP0WbU1%DEmV zeE0YFXFE@zdt*_!7^zfO)b#fwXHRAnt2SbJos1yqnd*~*Y}q;qZsxcg#hy`}zEK&G zW#Y0&>c{quI+TJwckSTC!&eVp%xOQka`vHX3+>%;chDBm z=?DWh4dD+qokSL55FK$67bL+*2wM!Y4`jmP$7cVSae{6TH#al4`rZ`^SXunzKHm5D zdp_UidEPctNkN<BTHI^d)W8+cIGP*QGfsIh8nSnf_m zj+cZA+(4vIuiM24q*sf{dP(>%ZQ~d!Q^XoAR%tY$I+h1$hB8B`!geaq9NuOp&H7!7 z!f>UqISvK^$H3%*}H#Ar%ejEo zNF5I-5$NHg#RwIVo~Fu3Q)iSDYEqp+rf2U^5h_)PY-DY;-S=N)BAZOlf@E?f8aYX+F}UWf>joVtMEsj3Hfib{Q(t=}bIpr(F;e%mw*qkwKTK)?{X; z5lXepmClVc(O%%H)YERj2(ZSqm^v8sGH6)?lx>&6)`A9t3Z;`Ji`}u% z+Tbd)lU;!7f~dgSMGwV;JO`{GEtY4u)6i2N3VV}w zFn~u1lu)Xa&##v9I04kS`XEq54W!0H=218{r+C+ZG5ug)6MG*8_rhL7`Ao_7o#_*KRbW%^O38G z^^Va~y|>R)%|!iLJfmoTtn=L){pN*2&Fe{hJ*Ai30zvecr>-&cLkp??nbg;A?muN| z{ekqRHn)hEzgD!zl=j<<$FrKZ-uYkbd|Qk|Mc;MsE6El=CP;dXJU7> z?SJC_xrV9Tu@e)t@xxAT~bYY)eKQ<~L8+)X&yQet@- z8<~6I;E|N^X^=Ti4HO>QW+C-e$7XBW4&SIve3oYdfj_4+8(vjR*EE?P`m=GjX&|E8 z_m%G_PuHc$`Kx1=-gidMJRW(v=a-{<=al!Z_^*G_cW%%xK6&D1@r9``Q@V$)sQiCL z&-P4mG1Efx`wxB-ys@(%H%>>nZoN3%b@$T22tLU%H!=8oHoTHzxI&A7Ah8M36M>xQ z+5$IKMf$w*EuGfC1A*M+ + +#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 new file mode 100644 index 000000000..d42fcfd71 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/background_assets.h @@ -0,0 +1,34 @@ +#ifndef BACKGROUND_ASSETS_H +#define BACKGROUND_ASSETS_H + +#include +#include + +#include + +#include "point.h" +#include "states.h" +#include "game_sprites.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 new file mode 100644 index 000000000..61d3a6fc4 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/barry.c @@ -0,0 +1,33 @@ +#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 new file mode 100644 index 000000000..494af434d --- /dev/null +++ b/applications/external/jetpack_joyride/includes/barry.h @@ -0,0 +1,23 @@ +#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 new file mode 100644 index 000000000..7a3811a8c --- /dev/null +++ b/applications/external/jetpack_joyride/includes/coin.c @@ -0,0 +1,98 @@ +#include +#include + +#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 new file mode 100644 index 000000000..41fd21ddc --- /dev/null +++ b/applications/external/jetpack_joyride/includes/coin.h @@ -0,0 +1,26 @@ +#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 new file mode 100644 index 000000000..d38494bf8 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_sprites.h @@ -0,0 +1,35 @@ +#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 new file mode 100644 index 000000000..a8a9db618 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_state.c @@ -0,0 +1,5 @@ +#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 new file mode 100644 index 000000000..1e97aaf18 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_state.h @@ -0,0 +1,34 @@ +#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 new file mode 100644 index 000000000..af47e8478 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/missile.c @@ -0,0 +1,86 @@ +#include +#include + +#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 new file mode 100644 index 000000000..a5af4e885 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/missile.h @@ -0,0 +1,24 @@ +#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 new file mode 100644 index 000000000..cf8e6e0a6 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/particle.c @@ -0,0 +1,57 @@ +#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 new file mode 100644 index 000000000..3442c9c4e --- /dev/null +++ b/applications/external/jetpack_joyride/includes/particle.h @@ -0,0 +1,21 @@ + + +#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 new file mode 100644 index 000000000..02c9a6ce4 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/point.h @@ -0,0 +1,14 @@ +#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 new file mode 100644 index 000000000..b1a8a14c0 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/scientist.c @@ -0,0 +1,77 @@ +#include "scientist.h" +#include "game_sprites.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 new file mode 100644 index 000000000..a49e8028c --- /dev/null +++ b/applications/external/jetpack_joyride/includes/scientist.h @@ -0,0 +1,29 @@ +#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 new file mode 100644 index 000000000..d58e3e1f6 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/states.h @@ -0,0 +1,9 @@ +#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 new file mode 100644 index 000000000..c12f094c9 --- /dev/null +++ b/applications/external/jetpack_joyride/jetpack.c @@ -0,0 +1,379 @@ +#include + +#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_DIRECTORY "/ext/apps/Games" +#define SAVING_FILENAME SAVING_DIRECTORY "/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); + 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); + + if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) { + if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) { + return; + } + } + + 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/nfc_maker/application.fam b/applications/external/nfc_maker/application.fam new file mode 100644 index 000000000..89bbb202e --- /dev/null +++ b/applications/external/nfc_maker/application.fam @@ -0,0 +1,14 @@ +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 new file mode 100644 index 000000000..578054ade --- /dev/null +++ b/applications/external/nfc_maker/nfc_maker.c @@ -0,0 +1,81 @@ +#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_next_scene(app->scene_manager, NfcMakerSceneMenu); + 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 new file mode 100644 index 000000000..388dc7196 --- /dev/null +++ b/applications/external/nfc_maker/nfc_maker.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "scenes/nfc_maker_scene.h" +#include +#include +#include +#include + +#define TEXT_INPUT_LEN 248 +#define WIFI_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[GAP_MAC_ADDR_SIZE]; + char text_buf[TEXT_INPUT_LEN]; + char pass_buf[WIFI_INPUT_LEN]; + char name_buf[TEXT_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 new file mode 100644 index 0000000000000000000000000000000000000000..a9e2443f1790f0b3a595767feb8622ff3cf7ab31 GIT binary patch literal 4142 zcmeH~d2ka|9LIxVTMCs!E&*YiGEkAt9@%WNYg4F6OCt@Gl4;8T%4YYa-D#2y$)-u` zw47xu$T0}YB`Bg*1cm`RGNYB5wt}_gK2$E{vgI0()=@?}_;z~_%s8Eq|C-6M``&jy z@Avz@-+Pl+nm%nxO!SCojYbn=OSNXeU*$SFsyF-||9T`1f2s=|*>VOKLVSM7CAtA3 z7x(}I!lFx~37_|*Ck{&dxC;rWUClX9DjCN+(S z-&lHktbO*>h|F`R&^6Z^M%Gu4+?E%2=*-Ol%h%5{CafRY{Em4{L~(G%t(w%!v2|HV z%%dBw!Tq^3$HeT))T*fOOGZVQ$9X24emLxR!`#^7+%*k!Egrc0L8EYC_RfkW8JWUZ zeqlxAwS_0p+`})EBktaw=cwOMJ@mnWvR9fS=O3H3`mdt%vPRP@PPACkZ5B&gJ}`?d zAFZi)vwHI2l0&=pE&rlqK}q(Gz4FwVvkp$^ofLa`$ei8#Y(s~=KYZ=P71D2;8>-x~ zQQs}DSX`d7y`)4Ob#Tk-+KT$Reh2Q1O{@K-D0Tl%U$gh|z6IcT#YtC5FhBdnO7dRe zi!lbZ|}mUg?=!zaGHZJ%;OnB zJ1H?bARSDF^xp zy@KVbdWFQRGx%y(bto4o(*q4daTXrlD68BWs|7KTo$8idH z;lH2|JS;VxS#%U0w4QTLonqCjpU_}^2=Ds%QfCD;n!baSPp?y#iXXwoNZDpjj;xOu zGz3MDUV0Bxj%PM&k|XM;xvOgWXz+ej*H1KO<&W|FaOK0e!F$~)OG{Ty9y#Kaqp_bg t_Wr$-tJBizZ`5U#ZOn{0H@d&CSIm|E10x2OB9No8B~P>Nd1Kz + +// 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 new file mode 100644 index 000000000..4e70a184d --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c @@ -0,0 +1,57 @@ +#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 < GAP_MAC_ADDR_SIZE; 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, + GAP_MAC_ADDR_SIZE); + + 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, NfcMakerSceneName); + 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 new file mode 100644 index 000000000..a89b4198c --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h @@ -0,0 +1,13 @@ +ADD_SCENE(nfc_maker, menu, Menu) +ADD_SCENE(nfc_maker, bluetooth, Bluetooth) +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, name, Name) +ADD_SCENE(nfc_maker, result, Result) diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c new file mode 100644 index 000000000..77b32afe1 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c @@ -0,0 +1,53 @@ +#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->text_buf, "google.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_https_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + 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, NfcMakerSceneName); + 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 new file mode 100644 index 000000000..98c648f6a --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c @@ -0,0 +1,53 @@ +#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 EMail Address:"); + + strlcpy(app->text_buf, "ben.dover@example.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_mail_text_input_callback, + app, + app->text_buf, + TEXT_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, NfcMakerSceneName); + 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_menu.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c new file mode 100644 index 000000000..4268e7e2f --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c @@ -0,0 +1,61 @@ +#include "../nfc_maker.h" + +void nfc_maker_scene_menu_submenu_callback(void* context, uint32_t index) { + NfcMaker* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void nfc_maker_scene_menu_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_menu_submenu_callback, + app); + + submenu_add_item( + submenu, "HTTPS Link", NfcMakerSceneHttps, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Mail Address", NfcMakerSceneMail, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Phone Number", NfcMakerScenePhone, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Text Note", NfcMakerSceneText, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Plain URL", NfcMakerSceneUrl, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "WiFi Login", NfcMakerSceneWifi, nfc_maker_scene_menu_submenu_callback, app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneMenu)); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); +} + +bool nfc_maker_scene_menu_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneMenu, event.event); + consumed = true; + scene_manager_next_scene(app->scene_manager, event.event); + } + + return consumed; +} + +void nfc_maker_scene_menu_on_exit(void* context) { + NfcMaker* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c new file mode 100644 index 000000000..dd5170d94 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c @@ -0,0 +1,57 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_name_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_name_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Name the NFC tag:"); + + set_random_name(app->name_buf, TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_name_text_input_callback, + app, + app->name_buf, + TEXT_INPUT_LEN, + true); + + ValidatorIsFile* validator_is_file = + validator_is_file_alloc_init(NFC_APP_FOLDER, NFC_APP_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_name_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_name_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 new file mode 100644 index 000000000..4e70bcb09 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c @@ -0,0 +1,53 @@ +#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->text_buf, "+", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_phone_text_input_callback, + app, + app->text_buf, + TEXT_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, NfcMakerSceneName); + 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 new file mode 100644 index 000000000..912bf3c9f --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c @@ -0,0 +1,359 @@ +#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_EXTENSION, app->name_buf); + do { + if(!flipper_format_file_open_new(file, furi_string_get_cstr(path))) break; + + uint32_t pages = 42; + size_t size = pages * 4; + uint8_t* buf = malloc(size); + + if(!flipper_format_write_header_cstr(file, "Flipper NFC device", 3)) break; + if(!flipper_format_write_string_cstr(file, "Device type", "NTAG203")) break; + + // Serial number + buf[0] = 0x04; + furi_hal_random_fill_buf(&buf[1], 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 00 00 00 00 00 00 00")) + 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[9] = 0x48; // Internal + buf[10] = 0x00; // Lock bytes + buf[11] = 0x00; // ... + buf[12] = 0xE1; // Capability container + buf[13] = 0x10; // ... + buf[14] = 0x12; // ... + buf[15] = 0x00; // ... + buf[16] = 0x01; // ... + buf[17] = 0x03; // ... + buf[18] = 0xA0; // ... + buf[19] = 0x10; // ... + buf[20] = 0x44; // ... + buf[21] = 0x03; // Message flags + + size_t msg_len = 0; + switch(scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneMenu)) { + case NfcMakerSceneBluetooth: { + msg_len = 0x2B; + + buf[23] = 0xD2; + buf[24] = 0x20; + buf[25] = 0x08; + buf[26] = 0x61; + buf[27] = 0x70; + + buf[28] = 0x70; + buf[29] = 0x6C; + buf[30] = 0x69; + buf[31] = 0x63; + + buf[32] = 0x61; + buf[33] = 0x74; + buf[34] = 0x69; + buf[35] = 0x6F; + + buf[36] = 0x6E; + buf[37] = 0x2F; + buf[38] = 0x76; + buf[39] = 0x6E; + + buf[40] = 0x64; + buf[41] = 0x2E; + buf[42] = 0x62; + buf[43] = 0x6C; + + buf[44] = 0x75; + buf[45] = 0x65; + buf[46] = 0x74; + buf[47] = 0x6F; + + buf[48] = 0x6F; + buf[49] = 0x74; + buf[50] = 0x68; + buf[51] = 0x2E; + + buf[52] = 0x65; + buf[53] = 0x70; + buf[54] = 0x2E; + buf[55] = 0x6F; + + buf[56] = 0x6F; + buf[57] = 0x62; + buf[58] = 0x08; + buf[59] = 0x00; + + memcpy(&buf[60], app->mac_buf, GAP_MAC_ADDR_SIZE); + break; + } + case NfcMakerSceneHttps: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x04; // Prepend "https://" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneMail: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x06; // Prepend "mailto:" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerScenePhone: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x05; // Prepend "tel:" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneText: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 7; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 3; + buf[26] = 0x54; + + buf[27] = 0x02; + buf[28] = 0x65; // e + buf[29] = 0x6E; // n + memcpy(&buf[30], app->text_buf, data_len); + break; + } + case NfcMakerSceneUrl: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x00; // No prepend + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneWifi: { + uint8_t ssid_len = strnlen(app->text_buf, WIFI_INPUT_LEN); + uint8_t pass_len = strnlen(app->pass_buf, WIFI_INPUT_LEN); + uint8_t data_len = ssid_len + pass_len; + msg_len = data_len + 73; + + buf[23] = 0xD2; + buf[24] = 0x17; + buf[25] = data_len + 47; + buf[26] = 0x61; + buf[27] = 0x70; + + buf[28] = 0x70; + buf[29] = 0x6C; + buf[30] = 0x69; + buf[31] = 0x63; + + buf[32] = 0x61; + buf[33] = 0x74; + buf[34] = 0x69; + buf[35] = 0x6F; + + buf[36] = 0x6E; + buf[37] = 0x2F; + buf[38] = 0x76; + buf[39] = 0x6E; + + buf[40] = 0x64; + buf[41] = 0x2E; + buf[42] = 0x77; + buf[43] = 0x66; + + buf[44] = 0x61; + buf[45] = 0x2E; + buf[46] = 0x77; + buf[47] = 0x73; + + buf[48] = 0x63; + buf[49] = 0x10; + buf[50] = 0x0E; + buf[51] = 0x00; + + buf[52] = data_len + 43; + buf[53] = 0x10; + buf[54] = 0x26; + buf[55] = 0x00; + + buf[56] = 0x01; + buf[57] = 0x01; + buf[58] = 0x10; + buf[59] = 0x45; + + buf[60] = 0x00; + buf[61] = ssid_len; + memcpy(&buf[62], app->text_buf, ssid_len); + size_t ssid = 62 + ssid_len; + buf[ssid + 0] = 0x10; + buf[ssid + 1] = 0x03; + + buf[ssid + 2] = 0x00; + buf[ssid + 3] = 0x02; + buf[ssid + 4] = 0x00; + buf[ssid + 5] = + scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiAuth); + + buf[ssid + 6] = 0x10; + buf[ssid + 7] = 0x0F; + buf[ssid + 8] = 0x00; + buf[ssid + 9] = 0x02; + + buf[ssid + 10] = 0x00; + buf[ssid + 11] = + scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiEncr); + buf[ssid + 12] = 0x10; + buf[ssid + 13] = 0x27; + + buf[ssid + 14] = 0x00; + buf[ssid + 15] = pass_len; + memcpy(&buf[ssid + 16], app->pass_buf, pass_len); + size_t pass = ssid + 16 + pass_len; + buf[pass + 0] = 0x10; + buf[pass + 1] = 0x20; + + buf[pass + 2] = 0x00; + buf[pass + 3] = 0x06; + buf[pass + 4] = 0xFF; + buf[pass + 5] = 0xFF; + + buf[pass + 6] = 0xFF; + buf[pass + 7] = 0xFF; + buf[pass + 8] = 0xFF; + buf[pass + 9] = 0xFF; + + break; + } + default: + break; + } + + // Message length and terminator + buf[22] = msg_len; + size_t msg_end = 23 + msg_len; + buf[msg_end] = 0xFE; + + // Padding + for(size_t i = msg_end + 1; i < size; i++) { + buf[i] = 0x00; + } + + 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; + + free(buf); + success = true; + + } while(false); + 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, NfcMakerSceneMenu); + 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_text.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c new file mode 100644 index 000000000..17d84e0a9 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c @@ -0,0 +1,53 @@ +#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->text_buf, "Lorem ipsum", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_text_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + 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, NfcMakerSceneName); + 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 new file mode 100644 index 000000000..e5a4996b2 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c @@ -0,0 +1,53 @@ +#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->text_buf, "https://google.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_url_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + 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, NfcMakerSceneName); + 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 new file mode 100644 index 000000000..68efaf7f6 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c @@ -0,0 +1,55 @@ +#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->text_buf, "Bill Wi the Science Fi", WIFI_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_wifi_text_input_callback, + app, + app->text_buf, + WIFI_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 new file mode 100644 index 000000000..4cb90dabe --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c @@ -0,0 +1,83 @@ +#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->pass_buf, ""); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + } 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 new file mode 100644 index 000000000..d1a21f51a --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c @@ -0,0 +1,48 @@ +#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 new file mode 100644 index 000000000..3f5b4bd76 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c @@ -0,0 +1,53 @@ +#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->pass_buf, "244466666", WIFI_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_wifi_pass_text_input_callback, + app, + app->pass_buf, + WIFI_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, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_wifi_pass_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} From 2211314900138dadb8c9027e982b2feac1ed91fb Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 18:58:34 +0300 Subject: [PATCH 38/40] merge fixes --- applications/main/subghz/scenes/subghz_scene_start.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/applications/main/subghz/scenes/subghz_scene_start.c b/applications/main/subghz/scenes/subghz_scene_start.c index 45505d5a4..5abab8f61 100644 --- a/applications/main/subghz/scenes/subghz_scene_start.c +++ b/applications/main/subghz/scenes/subghz_scene_start.c @@ -107,11 +107,6 @@ bool subghz_scene_start_on_event(void* context, SceneManagerEvent event) { scene_manager_next_scene(subghz->scene_manager, SubGhzSceneFrequencyAnalyzer); dolphin_deed(DolphinDeedSubGhzFrequencyAnalyzer); return true; - } else if(event.event == SubmenuIndexTest) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexTest); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTest); - return true; } } } From 3f4887e8d3bb91a10652a21ef261e2e48eacd600 Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 19:28:29 +0300 Subject: [PATCH 39/40] Fix nfc maker includes --- applications/external/nfc_maker/application.fam | 1 + .../nfc_maker/assets/DolphinNice_96x59.png | Bin 0 -> 2459 bytes applications/external/nfc_maker/nfc_maker.h | 3 ++- applications/external/nfc_maker/strnlen.c | 11 +++++++++++ applications/external/nfc_maker/strnlen.h | 6 ++++++ 5 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 applications/external/nfc_maker/assets/DolphinNice_96x59.png create mode 100644 applications/external/nfc_maker/strnlen.c create mode 100644 applications/external/nfc_maker/strnlen.h diff --git a/applications/external/nfc_maker/application.fam b/applications/external/nfc_maker/application.fam index 89bbb202e..95bcd8878 100644 --- a/applications/external/nfc_maker/application.fam +++ b/applications/external/nfc_maker/application.fam @@ -11,4 +11,5 @@ App( stack_size=1 * 1024, fap_icon="nfc_maker_10px.png", fap_category="NFC", + fap_icon_assets="assets", ) diff --git a/applications/external/nfc_maker/assets/DolphinNice_96x59.png b/applications/external/nfc_maker/assets/DolphinNice_96x59.png new file mode 100644 index 0000000000000000000000000000000000000000..a299d3630239b4486e249cc501872bed5996df3b GIT binary patch literal 2459 zcmbVO3s4i+8V(M(gEFORwSrA`4O0uPn|M|5y* zB*aMDxC&7(gP9JN;POOi-9khrC>Z9YJs2U!LnVcQEEC0fDtKo&ILlzb30%M}3J^;~ zv7RzcsilOs4Mq@tD*&R;!LMSk2A~{(`HK9|hQBqEX)3sQr9Je6SZU*F-^fD-p+~Hs; zHLkO%v?>ZoxEv+F#whudr%615FkA0DYR0tMEo}3OOY#xecLWe>xV?u5KtSmC^ z7)Fmj6gjfKstiEV-*Cxbbb+&rRWuI_rBJ)ybs_f1Rn&f2>q3pYwI^|J(hdn{j{0EZIm_F zpIyIWLsRUgOItR-dUbVd|6Zo=_BU_Tj4|{{jxO#=JH4o8er(5{!nZD_j4}MH&zh~9 zVLC~y(0-D6GO0ghZD8BYzP?o{>22~lT6^d@X{SwQ8vrNY-PPIMajIwC)`s14Ep72@ zeq7YOzM`?U{+W)ocXBr`eSOcpk?Rxc=ou5&)fWW|pD};-Z0mvk9}=&`Rb&y<77W~a z(>6YM;6Y5aIU~JKZ}mQZynKHiSTQ#Bczn@&jTiN^?vPJ(jhm7cXLx0oum5P$`TceG zU+wR;OO^)8CVlnM)5p$CO&e94KJt>HccCaHGusmW_b`T6m| z-R6V6Db1pErTot?^d22ojm+2>_)FbD`_+WbDGMx9f@hO27maS2`csiV(D&Fs`PS2& zvrq18du_&zXID(!KIxsU$)iuTYuZ?zmYiP&n&i@Be{IdbS-jA2c0QAlu5NXQv_0K< z3Hvs4eeu6B7yD&CNT~gIkMV&UkRU=V!iQ(+_(O&u^ah$+s{_yn(yBYeD40HeU{xGsIT6W Zfq!wOp!Q #include #include -#include +#include "nfc_maker_icons.h" #include #include #include @@ -16,6 +16,7 @@ #include #include #include +#include "strnlen.h" #define TEXT_INPUT_LEN 248 #define WIFI_INPUT_LEN 90 diff --git a/applications/external/nfc_maker/strnlen.c b/applications/external/nfc_maker/strnlen.c new file mode 100644 index 000000000..54d183895 --- /dev/null +++ b/applications/external/nfc_maker/strnlen.c @@ -0,0 +1,11 @@ +#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/nfc_maker/strnlen.h b/applications/external/nfc_maker/strnlen.h new file mode 100644 index 000000000..4fe0d540c --- /dev/null +++ b/applications/external/nfc_maker/strnlen.h @@ -0,0 +1,6 @@ +#pragma once +#pragma weak strnlen + +#include + +size_t strnlen(const char* s, size_t maxlen); \ No newline at end of file From 7e14f997e72bfbd2d0f3b9f45e384edda69dcd1f Mon Sep 17 00:00:00 2001 From: MX <10697207+xMasterX@users.noreply.github.com> Date: Thu, 6 Jul 2023 19:41:07 +0300 Subject: [PATCH 40/40] Update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05aba5e16..74bf3dc9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ * Infrared: Updated universal remote assets (by @amec0e | PR #529) * Plugins: Use correct categories for all plugins (extra pack too) * Plugins: Various fixes for uFBT (by @hedger) +* Plugins: Added **NFC Maker** plugin (make tags with URLs, Wifi and other things) [(by Willy-JL)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/external/nfc_maker) +* Plugins: Added JetPack Joyride [(by timstrasser)](https://github.com/timstrasser) * Plugins: Moved Barcode Generator [(by Kingal1337)](https://github.com/Kingal1337/flipper-barcode-generator) from extra pack into base fw, old barcode generator was removed * Plugins: Updated ESP32: WiFi Marauder companion plugin [(by 0xchocolate)](https://github.com/0xchocolate/flipperzero-wifi-marauder) * Plugins: Updated i2c Tools [(by NaejEL)](https://github.com/NaejEL/flipperzero-i2ctools) @@ -15,6 +17,8 @@ * WIP OFW PR 2825: NFC: Improved MFC emulation on some readers (by AloneLiberty) * OFW PR 2829: Decode only supported Oregon 3 sensor (by @wosk) * OFW PR: Update OFW PR 2782 +* OFW: SubGhz: add "SubGhz test" external application and the ability to work "SubGhz" as an external application +* OFW: API: explicitly add math.h * OFW: NFC: Mf Ultralight emulation optimization * OFW: Furi_Power: fix furi_hal_power_enable_otg * OFW: FuriHal: allow nulling null isr