diff --git a/.vscode/example/tasks.json b/.vscode/example/tasks.json index 107808ef3..f2522668d 100644 --- a/.vscode/example/tasks.json +++ b/.vscode/example/tasks.json @@ -13,7 +13,7 @@ "label": "[Debug] Build", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack" + "command": "./fbt" }, { "label": "[Release] Flash (ST-Link)", @@ -25,7 +25,7 @@ "label": "[Debug] Flash (ST-Link)", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack FORCE=1 flash" + "command": "./fbt FORCE=1 flash" }, { "label": "[Release] Flash (blackmagic)", @@ -37,7 +37,7 @@ "label": "[Debug] Flash (blackmagic)", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack FORCE=1 flash_blackmagic" + "command": "./fbt FORCE=1 flash_blackmagic" }, { "label": "[Release] Flash (JLink)", @@ -49,7 +49,7 @@ "label": "[Debug] Flash (JLink)", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack FORCE=1 jflash" + "command": "./fbt FORCE=1 jflash" }, { "label": "[Release] Build update bundle", @@ -61,7 +61,7 @@ "label": "[Debug] Build update bundle", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack updater_package" + "command": "./fbt updater_package" }, { "label": "[Release] Build updater", @@ -73,13 +73,13 @@ "label": "[Debug] Build updater", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack updater_all" + "command": "./fbt updater_all" }, { "label": "[Debug] Flash (USB, w/o resources)", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack FORCE=1 flash_usb" + "command": "./fbt FORCE=1 flash_usb" }, { "label": "[Release] Flash (USB, w/o resources)", @@ -97,7 +97,7 @@ "label": "[Debug] Flash (USB, with resources)", "group": "build", "type": "shell", - "command": "./fbt FIRMWARE_APP_SET=debug_pack FORCE=1 flash_usb_full" + "command": "./fbt FORCE=1 flash_usb_full" }, { "label": "[Release] Flash (USB, with resources)", 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 000000000..089aaed83 Binary files /dev/null and b/applications/debug/subghz_test/images/DolphinCommon_56x48.png differ 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 000000000..10dac0eca Binary files /dev/null and b/applications/debug/subghz_test/subghz_test_10px.png differ diff --git a/applications/debug/subghz_test/subghz_test_app.c b/applications/debug/subghz_test/subghz_test_app.c new file mode 100644 index 000000000..704941fb2 --- /dev/null +++ b/applications/debug/subghz_test/subghz_test_app.c @@ -0,0 +1,139 @@ +#include "subghz_test_app_i.h" + +#include +#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 72% rename from applications/main/subghz/views/subghz_test_carrier.c rename to applications/debug/subghz_test/views/subghz_test_carrier.c index 2cbde6e32..ec64e2d9b 100644 --- a/applications/main/subghz/views/subghz_test_carrier.c +++ b/applications/debug/subghz_test/views/subghz_test_carrier.c @@ -1,6 +1,7 @@ #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 #include @@ -11,6 +12,7 @@ struct SubGhzTestCarrier { View* view; FuriTimer* timer; SubGhzTestCarrierCallback callback; + // const SubGhzDevice* radio_device; void* context; }; @@ -83,6 +85,7 @@ void subghz_test_carrier_draw(Canvas* canvas, SubGhzTestCarrierModel* model) { bool subghz_test_carrier_input(InputEvent* event, void* context) { furi_assert(context); SubGhzTestCarrier* subghz_test_carrier = context; + // const SubGhzDevice* radio_device = subghz_test_carrier->radio_device; if(event->key == InputKeyBack || event->type != InputTypeShort) { return false; @@ -93,6 +96,7 @@ bool subghz_test_carrier_input(InputEvent* event, void* context) { SubGhzTestCarrierModel * model, { furi_hal_subghz_idle(); + // subghz_devices_idle(radio_device); if(event->key == InputKeyLeft) { if(model->frequency > 0) model->frequency--; @@ -113,24 +117,36 @@ bool subghz_test_carrier_input(InputEvent* event, void* context) { model->real_frequency = furi_hal_subghz_set_frequency(subghz_frequencies_testing[model->frequency]); furi_hal_subghz_set_path(model->path); + // model->real_frequency = subghz_devices_set_frequency( + // radio_device, subghz_frequencies_testing[model->frequency]); if(model->status == SubGhzTestCarrierModelStatusRx) { - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); furi_hal_subghz_rx(); + // furi_hal_gpio_init( + // subghz_devices_get_data_gpio(radio_device), + // GpioModeInput, + // GpioPullNo, + // GpioSpeedLow); + // subghz_devices_set_rx(radio_device); } else { furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, - GpioModeOutputPushPull, - GpioPullNo, - GpioSpeedLow); - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, true); + &gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_write(&gpio_cc1101_g0, true); if(!furi_hal_subghz_tx()) { - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); subghz_test_carrier->callback( SubGhzTestCarrierEventOnlyRx, subghz_test_carrier->context); } + // if(!subghz_devices_set_tx(radio_device)) { + // furi_hal_gpio_init( + // subghz_devices_get_data_gpio(radio_device), + // GpioModeInput, + // GpioPullNo, + // GpioSpeedLow); + // subghz_test_carrier->callback( + // SubGhzTestCarrierEventOnlyRx, subghz_test_carrier->context); + // } } }, true); @@ -141,11 +157,19 @@ bool subghz_test_carrier_input(InputEvent* event, void* context) { void subghz_test_carrier_enter(void* context) { furi_assert(context); SubGhzTestCarrier* subghz_test_carrier = context; + // furi_assert(subghz_test_carrier->radio_device); + // const SubGhzDevice* radio_device = subghz_test_carrier->radio_device; 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(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); + + // subghz_devices_reset(radio_device); + // subghz_devices_load_preset(radio_device, FuriHalSubGhzPresetOok650Async, NULL); + + // furi_hal_gpio_init( + // subghz_devices_get_data_gpio(radio_device), GpioModeInput, GpioPullNo, GpioSpeedLow); with_view_model( subghz_test_carrier->view, @@ -154,6 +178,8 @@ void subghz_test_carrier_enter(void* context) { model->frequency = subghz_frequencies_433_92_testing; // 433 model->real_frequency = furi_hal_subghz_set_frequency(subghz_frequencies_testing[model->frequency]); + // model->real_frequency = subghz_devices_set_frequency( + // radio_device, subghz_frequencies_testing[model->frequency]); model->path = FuriHalSubGhzPathIsolate; // isolate model->rssi = 0.0f; model->status = SubGhzTestCarrierModelStatusRx; @@ -161,6 +187,7 @@ void subghz_test_carrier_enter(void* context) { true); furi_hal_subghz_rx(); + // subghz_devices_set_rx(radio_device); furi_timer_start(subghz_test_carrier->timer, furi_kernel_get_tick_frequency() / 4); } @@ -173,6 +200,7 @@ void subghz_test_carrier_exit(void* context) { // Reinitialize IC to default state furi_hal_subghz_sleep(); + // subghz_devices_sleep(subghz_test_carrier->radio_device); } void subghz_test_carrier_rssi_timer_callback(void* context) { @@ -185,6 +213,7 @@ void subghz_test_carrier_rssi_timer_callback(void* context) { { if(model->status == SubGhzTestCarrierModelStatusRx) { model->rssi = furi_hal_subghz_get_rssi(); + // model->rssi = subghz_devices_get_rssi(subghz_test_carrier->radio_device); } }, false); @@ -220,3 +249,10 @@ View* subghz_test_carrier_get_view(SubGhzTestCarrier* subghz_test_carrier) { furi_assert(subghz_test_carrier); return subghz_test_carrier->view; } + +// void subghz_test_carrier_set_radio( +// SubGhzTestCarrier* subghz_test_carrier, +// const SubGhzDevice* radio_device) { +// furi_assert(subghz_test_carrier); +// subghz_test_carrier->radio_device = radio_device; +// } diff --git a/applications/main/subghz/views/subghz_test_carrier.h b/applications/debug/subghz_test/views/subghz_test_carrier.h similarity index 77% rename from applications/main/subghz/views/subghz_test_carrier.h rename to applications/debug/subghz_test/views/subghz_test_carrier.h index 7db3343ed..d171d19f4 100644 --- a/applications/main/subghz/views/subghz_test_carrier.h +++ b/applications/debug/subghz_test/views/subghz_test_carrier.h @@ -1,6 +1,7 @@ #pragma once #include +// #include typedef enum { SubGhzTestCarrierEventOnlyRx, @@ -20,3 +21,7 @@ SubGhzTestCarrier* subghz_test_carrier_alloc(); void subghz_test_carrier_free(SubGhzTestCarrier* subghz_test_carrier); View* subghz_test_carrier_get_view(SubGhzTestCarrier* subghz_test_carrier); + +// void subghz_test_carrier_set_radio( +// SubGhzTestCarrier* subghz_test_carrier, +// const SubGhzDevice* radio_device); diff --git a/applications/main/subghz/views/subghz_test_packet.c b/applications/debug/subghz_test/views/subghz_test_packet.c similarity index 97% rename from applications/main/subghz/views/subghz_test_packet.c rename to applications/debug/subghz_test/views/subghz_test_packet.c index 43502180c..bab83ab5b 100644 --- a/applications/main/subghz/views/subghz_test_packet.c +++ b/applications/debug/subghz_test/views/subghz_test_packet.c @@ -1,13 +1,14 @@ #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 #include #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define SUBGHZ_TEST_PACKET_COUNT 500 @@ -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_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 93% rename from applications/main/subghz/views/subghz_test_static.c rename to applications/debug/subghz_test/views/subghz_test_static.c index b9e5a8c9c..6764fd5ca 100644 --- a/applications/main/subghz/views/subghz_test_static.c +++ b/applications/debug/subghz_test/views/subghz_test_static.c @@ -1,13 +1,14 @@ #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 #include #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define TAG "SubGhzTestStatic" @@ -141,11 +142,10 @@ 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( - furi_hal_subghz.cc1101_g0_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, false); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_write(&gpio_cc1101_g0, false); instance->status_tx = SubGhzTestStaticStatusIDLE; with_view_model( 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/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/applications/drivers/subghz/cc1101_ext/cc1101_ext.c b/applications/drivers/subghz/cc1101_ext/cc1101_ext.c new file mode 100644 index 000000000..964317f9b --- /dev/null +++ b/applications/drivers/subghz/cc1101_ext/cc1101_ext.c @@ -0,0 +1,813 @@ +#include "cc1101_ext.h" +#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 +#define SUBGHZ_DEVICE_CC1101_EXT_DANGEROUS_RANGE false + +/* 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; + CC1101Status cc1101_status = {0}; + + 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); + furi_hal_gpio_init( + subghz_device_cc1101_ext->spi_bus_handle->miso, + GpioModeInput, + GpioPullUp, + GpioSpeedLow); + + cc1101_status = cc1101_reset(subghz_device_cc1101_ext->spi_bus_handle); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + cc1101_status = cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + // Prepare GD0 for power on self test + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeInput, GpioPullUp, GpioSpeedLow); + + // GD0 low + cc1101_status = cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHW); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + 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 + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeInput, GpioPullDown, GpioSpeedLow); + cc1101_status = cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, + CC1101_IOCFG0, + CC1101IocfgHW | CC1101_IOCFG_INV); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + 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_status = cc1101_write_reg( + subghz_device_cc1101_ext->spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + + // Go to sleep + cc1101_status = cc1101_shutdown(subghz_device_cc1101_ext->spi_bus_handle); + if(cc1101_status.CHIP_RDYn != 0) { + //timeout or error + break; + } + 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"); + furi_hal_gpio_init( + subghz_device_cc1101_ext->g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + } + 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 >= 281000000 && value <= 361000000) && + !(value >= 378000000 && value <= 481000000) && + !(value >= 749000000 && value <= 962000000)) { + return false; + } + + return true; +} + +bool subghz_device_cc1101_ext_is_tx_allowed(uint32_t value) { + if(!(SUBGHZ_DEVICE_CC1101_EXT_DANGEROUS_RANGE) && + !(value >= 299999755 && value <= 350000335) && // was increased from 348 to 350 + !(value >= 386999938 && value <= 467750000) && // was increased from 464 to 467.75 + !(value >= 778999847 && value <= 928000000)) { + FURI_LOG_I(TAG, "Frequency blocked - outside default range"); + return false; + } else if( + (SUBGHZ_DEVICE_CC1101_EXT_DANGEROUS_RANGE) && + !subghz_device_cc1101_ext_is_frequency_valid(value)) { + FURI_LOG_I(TAG, "Frequency blocked - outside dangerous range"); + return false; + } + + return true; +} + +uint32_t subghz_device_cc1101_ext_set_frequency(uint32_t value) { + if(subghz_device_cc1101_ext_is_tx_allowed(value)) { + subghz_device_cc1101_ext->regulation = SubGhzDeviceCC1101ExtRegulationTxRx; + } else { + subghz_device_cc1101_ext->regulation = SubGhzDeviceCC1101ExtRegulationTxRx; + } + + 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/external/bomberduck/bomberduck.c b/applications/external/bomberduck/bomberduck.c index 29bd15abb..7cc7842c9 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" int max(int a, int b) { diff --git a/applications/external/camera_suite/application.fam b/applications/external/camera_suite/application.fam new file mode 100644 index 000000000..40131ae9a --- /dev/null +++ b/applications/external/camera_suite/application.fam @@ -0,0 +1,16 @@ +App( + appid="camerasuite", + apptype=FlipperAppType.EXTERNAL, + cdefines=["APP_CAMERA_SUITE"], + entry_point="camera_suite_app", + fap_author="Cody Tolene", + fap_category="GPIO", + fap_description="A camera suite application for the Flipper Zero ESP32-CAM module.", + fap_icon="icons/camera_suite.png", + fap_libs=["assets"], + fap_weburl="https://github.com/CodyTolene/Flipper-Zero-Cam", + name="[ESP32] Camera Suite", + order=1, + requires=["gui", "storage"], + stack_size=8 * 1024, +) diff --git a/applications/external/camera_suite/camera_suite.c b/applications/external/camera_suite/camera_suite.c new file mode 100644 index 000000000..13ee09c22 --- /dev/null +++ b/applications/external/camera_suite/camera_suite.c @@ -0,0 +1,139 @@ +#include "camera_suite.h" +#include + +bool camera_suite_custom_event_callback(void* context, uint32_t event) { + furi_assert(context); + CameraSuite* app = context; + return scene_manager_handle_custom_event(app->scene_manager, event); +} + +void camera_suite_tick_event_callback(void* context) { + furi_assert(context); + CameraSuite* app = context; + scene_manager_handle_tick_event(app->scene_manager); +} + +//leave app if back button pressed +bool camera_suite_navigation_event_callback(void* context) { + furi_assert(context); + CameraSuite* app = context; + return scene_manager_handle_back_event(app->scene_manager); +} + +CameraSuite* camera_suite_app_alloc() { + CameraSuite* app = malloc(sizeof(CameraSuite)); + app->gui = furi_record_open(RECORD_GUI); + app->notification = furi_record_open(RECORD_NOTIFICATION); + + //Turn backlight on, believe me this makes testing your app easier + notification_message(app->notification, &sequence_display_backlight_on); + + //Scene additions + app->view_dispatcher = view_dispatcher_alloc(); + view_dispatcher_enable_queue(app->view_dispatcher); + + app->scene_manager = scene_manager_alloc(&camera_suite_scene_handlers, app); + view_dispatcher_set_event_callback_context(app->view_dispatcher, app); + view_dispatcher_set_navigation_event_callback( + app->view_dispatcher, camera_suite_navigation_event_callback); + view_dispatcher_set_tick_event_callback( + app->view_dispatcher, camera_suite_tick_event_callback, 100); + view_dispatcher_set_custom_event_callback( + app->view_dispatcher, camera_suite_custom_event_callback); + app->submenu = submenu_alloc(); + + // Set defaults, in case no config loaded + app->orientation = 0; // Orientation is "portrait", zero degrees by default. + app->haptic = 1; // Haptic is on by default + app->speaker = 1; // Speaker is on by default + app->led = 1; // LED is on by default + + // Load configs + camera_suite_read_settings(app); + + view_dispatcher_add_view( + app->view_dispatcher, CameraSuiteViewIdMenu, submenu_get_view(app->submenu)); + + app->camera_suite_view_start = camera_suite_view_start_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + CameraSuiteViewIdStartscreen, + camera_suite_view_start_get_view(app->camera_suite_view_start)); + + app->camera_suite_view_style_1 = camera_suite_view_style_1_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + CameraSuiteViewIdScene1, + camera_suite_view_style_1_get_view(app->camera_suite_view_style_1)); + + app->camera_suite_view_style_2 = camera_suite_view_style_2_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + CameraSuiteViewIdScene2, + camera_suite_view_style_2_get_view(app->camera_suite_view_style_2)); + + app->camera_suite_view_guide = camera_suite_view_guide_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + CameraSuiteViewIdGuide, + camera_suite_view_guide_get_view(app->camera_suite_view_guide)); + + app->button_menu = button_menu_alloc(); + + app->variable_item_list = variable_item_list_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, + CameraSuiteViewIdSettings, + variable_item_list_get_view(app->variable_item_list)); + + //End Scene Additions + + return app; +} + +void camera_suite_app_free(CameraSuite* app) { + furi_assert(app); + + // Scene manager + scene_manager_free(app->scene_manager); + + // View Dispatcher + view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdMenu); + view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdScene1); + view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdScene2); + view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdGuide); + view_dispatcher_remove_view(app->view_dispatcher, CameraSuiteViewIdSettings); + submenu_free(app->submenu); + + view_dispatcher_free(app->view_dispatcher); + furi_record_close(RECORD_GUI); + + // Free remaining resources + camera_suite_view_start_free(app->camera_suite_view_start); + camera_suite_view_style_1_free(app->camera_suite_view_style_1); + camera_suite_view_style_2_free(app->camera_suite_view_style_2); + camera_suite_view_guide_free(app->camera_suite_view_guide); + button_menu_free(app->button_menu); + variable_item_list_free(app->variable_item_list); + + app->gui = NULL; + app->notification = NULL; + + //Remove whatever is left + free(app); +} + +/** Main entry point for initialization. */ +int32_t camera_suite_app(void* p) { + UNUSED(p); + CameraSuite* app = camera_suite_app_alloc(); + view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); + // Init with start scene. + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneStart); + furi_hal_power_suppress_charge_enter(); + view_dispatcher_run(app->view_dispatcher); + camera_suite_save_settings(app); + furi_hal_power_suppress_charge_exit(); + camera_suite_app_free(app); + return 0; +} diff --git a/applications/external/camera_suite/camera_suite.h b/applications/external/camera_suite/camera_suite.h new file mode 100644 index 000000000..2b6a7748b --- /dev/null +++ b/applications/external/camera_suite/camera_suite.h @@ -0,0 +1,71 @@ +#pragma once + +#include "helpers/camera_suite_storage.h" +#include "scenes/camera_suite_scene.h" +#include "views/camera_suite_view_guide.h" +#include "views/camera_suite_view_start.h" +#include "views/camera_suite_view_style_1.h" +#include "views/camera_suite_view_style_2.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TAG "Camera Suite" + +typedef struct { + Gui* gui; + NotificationApp* notification; + ViewDispatcher* view_dispatcher; + Submenu* submenu; + SceneManager* scene_manager; + VariableItemList* variable_item_list; + CameraSuiteViewStart* camera_suite_view_start; + CameraSuiteViewStyle1* camera_suite_view_style_1; + CameraSuiteViewStyle2* camera_suite_view_style_2; + CameraSuiteViewGuide* camera_suite_view_guide; + uint32_t orientation; + uint32_t haptic; + uint32_t speaker; + uint32_t led; + ButtonMenu* button_menu; +} CameraSuite; + +typedef enum { + CameraSuiteViewIdStartscreen, + CameraSuiteViewIdMenu, + CameraSuiteViewIdScene1, + CameraSuiteViewIdScene2, + CameraSuiteViewIdGuide, + CameraSuiteViewIdSettings, +} CameraSuiteViewId; + +typedef enum { + CameraSuiteOrientation0, + CameraSuiteOrientation90, + CameraSuiteOrientation180, + CameraSuiteOrientation270, +} CameraSuiteOrientationState; + +typedef enum { + CameraSuiteHapticOff, + CameraSuiteHapticOn, +} CameraSuiteHapticState; + +typedef enum { + CameraSuiteSpeakerOff, + CameraSuiteSpeakerOn, +} CameraSuiteSpeakerState; + +typedef enum { + CameraSuiteLedOff, + CameraSuiteLedOn, +} CameraSuiteLedState; diff --git a/applications/external/camera_suite/helpers/camera_suite_custom_event.h b/applications/external/camera_suite/helpers/camera_suite_custom_event.h new file mode 100644 index 000000000..7727a0de3 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_custom_event.h @@ -0,0 +1,74 @@ +#pragma once + +typedef enum { + // Scene events: Start menu + CameraSuiteCustomEventStartUp, + CameraSuiteCustomEventStartDown, + CameraSuiteCustomEventStartLeft, + CameraSuiteCustomEventStartRight, + CameraSuiteCustomEventStartOk, + CameraSuiteCustomEventStartBack, + // Scene events: Camera style 1 + CameraSuiteCustomEventSceneStyle1Up, + CameraSuiteCustomEventSceneStyle1Down, + CameraSuiteCustomEventSceneStyle1Left, + CameraSuiteCustomEventSceneStyle1Right, + CameraSuiteCustomEventSceneStyle1Ok, + CameraSuiteCustomEventSceneStyle1Back, + // Scene events: Camera style 2 + CameraSuiteCustomEventSceneStyle2Up, + CameraSuiteCustomEventSceneStyle2Down, + CameraSuiteCustomEventSceneStyle2Left, + CameraSuiteCustomEventSceneStyle2Right, + CameraSuiteCustomEventSceneStyle2Ok, + CameraSuiteCustomEventSceneStyle2Back, + // Scene events: Guide + CameraSuiteCustomEventSceneGuideUp, + CameraSuiteCustomEventSceneGuideDown, + CameraSuiteCustomEventSceneGuideLeft, + CameraSuiteCustomEventSceneGuideRight, + CameraSuiteCustomEventSceneGuideOk, + CameraSuiteCustomEventSceneGuideBack, +} CameraSuiteCustomEvent; + +enum CameraSuiteCustomEventType { + // Reserve first 100 events for button types and indexes, starting from 0. + CameraSuiteCustomEventMenuVoid, + CameraSuiteCustomEventMenuSelected, +}; + +#pragma pack(push, 1) + +typedef union { + uint32_t packed_value; + struct { + uint16_t type; + int16_t value; + } content; +} CameraSuiteCustomEventMenu; + +#pragma pack(pop) + +static inline uint32_t camera_suite_custom_menu_event_pack(uint16_t type, int16_t value) { + CameraSuiteCustomEventMenu event = {.content = {.type = type, .value = value}}; + return event.packed_value; +} + +static inline void + camera_suite_custom_menu_event_unpack(uint32_t packed_value, uint16_t* type, int16_t* value) { + CameraSuiteCustomEventMenu event = {.packed_value = packed_value}; + if(type) *type = event.content.type; + if(value) *value = event.content.value; +} + +static inline uint16_t camera_suite_custom_menu_event_get_type(uint32_t packed_value) { + uint16_t type; + camera_suite_custom_menu_event_unpack(packed_value, &type, NULL); + return type; +} + +static inline int16_t camera_suite_custom_menu_event_get_value(uint32_t packed_value) { + int16_t value; + camera_suite_custom_menu_event_unpack(packed_value, NULL, &value); + return value; +} diff --git a/applications/external/camera_suite/helpers/camera_suite_haptic.c b/applications/external/camera_suite/helpers/camera_suite_haptic.c new file mode 100644 index 000000000..237a96004 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_haptic.c @@ -0,0 +1,35 @@ +#include "camera_suite_haptic.h" +#include "../camera_suite.h" + +void camera_suite_play_happy_bump(void* context) { + CameraSuite* app = context; + if(app->haptic != 1) { + return; + } + notification_message(app->notification, &sequence_set_vibro_on); + furi_thread_flags_wait(0, FuriFlagWaitAny, 20); + notification_message(app->notification, &sequence_reset_vibro); +} + +void camera_suite_play_bad_bump(void* context) { + CameraSuite* app = context; + if(app->haptic != 1) { + return; + } + notification_message(app->notification, &sequence_set_vibro_on); + furi_thread_flags_wait(0, FuriFlagWaitAny, 100); + notification_message(app->notification, &sequence_reset_vibro); +} + +void camera_suite_play_long_bump(void* context) { + CameraSuite* app = context; + if(app->haptic != 1) { + return; + } + for(int i = 0; i < 4; i++) { + notification_message(app->notification, &sequence_set_vibro_on); + furi_thread_flags_wait(0, FuriFlagWaitAny, 50); + notification_message(app->notification, &sequence_reset_vibro); + furi_thread_flags_wait(0, FuriFlagWaitAny, 100); + } +} diff --git a/applications/external/camera_suite/helpers/camera_suite_haptic.h b/applications/external/camera_suite/helpers/camera_suite_haptic.h new file mode 100644 index 000000000..9b7651f97 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_haptic.h @@ -0,0 +1,7 @@ +#include + +void camera_suite_play_happy_bump(void* context); + +void camera_suite_play_bad_bump(void* context); + +void camera_suite_play_long_bump(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_led.c b/applications/external/camera_suite/helpers/camera_suite_led.c new file mode 100644 index 000000000..c4f1a85d7 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_led.c @@ -0,0 +1,38 @@ +#include "camera_suite_led.h" +#include "../camera_suite.h" + +void camera_suite_led_set_rgb(void* context, int red, int green, int blue) { + CameraSuite* app = context; + if(app->led != 1) { + return; + } + NotificationMessage notification_led_message_1; + notification_led_message_1.type = NotificationMessageTypeLedRed; + NotificationMessage notification_led_message_2; + notification_led_message_2.type = NotificationMessageTypeLedGreen; + NotificationMessage notification_led_message_3; + notification_led_message_3.type = NotificationMessageTypeLedBlue; + + notification_led_message_1.data.led.value = red; + notification_led_message_2.data.led.value = green; + notification_led_message_3.data.led.value = blue; + const NotificationSequence notification_sequence = { + ¬ification_led_message_1, + ¬ification_led_message_2, + ¬ification_led_message_3, + &message_do_not_reset, + NULL, + }; + notification_message(app->notification, ¬ification_sequence); + //Delay, prevent removal from RAM before LED value set. + furi_thread_flags_wait(0, FuriFlagWaitAny, 10); +} + +void camera_suite_led_reset(void* context) { + CameraSuite* app = context; + notification_message(app->notification, &sequence_reset_red); + notification_message(app->notification, &sequence_reset_green); + notification_message(app->notification, &sequence_reset_blue); + //Delay, prevent removal from RAM before LED value set. + furi_thread_flags_wait(0, FuriFlagWaitAny, 300); +} diff --git a/applications/external/camera_suite/helpers/camera_suite_led.h b/applications/external/camera_suite/helpers/camera_suite_led.h new file mode 100644 index 000000000..074947da1 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_led.h @@ -0,0 +1,3 @@ +void camera_suite_led_set_rgb(void* context, int red, int green, int blue); + +void camera_suite_led_reset(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_speaker.c b/applications/external/camera_suite/helpers/camera_suite_speaker.c new file mode 100644 index 000000000..c2a5a7dd0 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_speaker.c @@ -0,0 +1,26 @@ +#include "camera_suite_speaker.h" +#include "../camera_suite.h" + +#define NOTE_INPUT 587.33f + +void camera_suite_play_input_sound(void* context) { + CameraSuite* app = context; + if(app->speaker != 1) { + return; + } + float volume = 1.0f; + if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(30)) { + furi_hal_speaker_start(NOTE_INPUT, volume); + } +} + +void camera_suite_stop_all_sound(void* context) { + CameraSuite* app = context; + if(app->speaker != 1) { + return; + } + if(furi_hal_speaker_is_mine()) { + furi_hal_speaker_stop(); + furi_hal_speaker_release(); + } +} diff --git a/applications/external/camera_suite/helpers/camera_suite_speaker.h b/applications/external/camera_suite/helpers/camera_suite_speaker.h new file mode 100644 index 000000000..2119bbec5 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_speaker.h @@ -0,0 +1,5 @@ +#define NOTE_INPUT 587.33f + +void camera_suite_play_input_sound(void* context); + +void camera_suite_stop_all_sound(void* context); diff --git a/applications/external/camera_suite/helpers/camera_suite_storage.c b/applications/external/camera_suite/helpers/camera_suite_storage.c new file mode 100644 index 000000000..38a5f0813 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_storage.c @@ -0,0 +1,113 @@ +#include "camera_suite_storage.h" + +static Storage* camera_suite_open_storage() { + return furi_record_open(RECORD_STORAGE); +} + +static void camera_suite_close_storage() { + furi_record_close(RECORD_STORAGE); +} + +static void camera_suite_close_config_file(FlipperFormat* file) { + if(file == NULL) return; + flipper_format_file_close(file); + flipper_format_free(file); +} + +void camera_suite_save_settings(void* context) { + CameraSuite* app = context; + + FURI_LOG_D(TAG, "Saving Settings"); + Storage* storage = camera_suite_open_storage(); + FlipperFormat* fff_file = flipper_format_file_alloc(storage); + + // Overwrite wont work, so delete first + if(storage_file_exists(storage, BOILERPLATE_SETTINGS_SAVE_PATH)) { + storage_simply_remove(storage, BOILERPLATE_SETTINGS_SAVE_PATH); + } + + // Open File, create if not exists + if(!storage_common_stat(storage, BOILERPLATE_SETTINGS_SAVE_PATH, NULL) == FSE_OK) { + FURI_LOG_D( + TAG, "Config file %s is not found. Will create new.", BOILERPLATE_SETTINGS_SAVE_PATH); + if(storage_common_stat(storage, CONFIG_FILE_DIRECTORY_PATH, NULL) == FSE_NOT_EXIST) { + FURI_LOG_D( + TAG, "Directory %s doesn't exist. Will create new.", CONFIG_FILE_DIRECTORY_PATH); + if(!storage_simply_mkdir(storage, CONFIG_FILE_DIRECTORY_PATH)) { + FURI_LOG_E(TAG, "Error creating directory %s", CONFIG_FILE_DIRECTORY_PATH); + } + } + } + + if(!flipper_format_file_open_new(fff_file, BOILERPLATE_SETTINGS_SAVE_PATH)) { + //totp_close_config_file(fff_file); + FURI_LOG_E(TAG, "Error creating new file %s", BOILERPLATE_SETTINGS_SAVE_PATH); + camera_suite_close_storage(); + return; + } + + // Store Settings + flipper_format_write_header_cstr( + fff_file, BOILERPLATE_SETTINGS_HEADER, BOILERPLATE_SETTINGS_FILE_VERSION); + flipper_format_write_uint32( + fff_file, BOILERPLATE_SETTINGS_KEY_ORIENTATION, &app->orientation, 1); + flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_HAPTIC, &app->haptic, 1); + flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_SPEAKER, &app->speaker, 1); + flipper_format_write_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_LED, &app->led, 1); + + if(!flipper_format_rewind(fff_file)) { + camera_suite_close_config_file(fff_file); + FURI_LOG_E(TAG, "Rewind error"); + camera_suite_close_storage(); + return; + } + + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); +} + +void camera_suite_read_settings(void* context) { + CameraSuite* app = context; + Storage* storage = camera_suite_open_storage(); + FlipperFormat* fff_file = flipper_format_file_alloc(storage); + + if(storage_common_stat(storage, BOILERPLATE_SETTINGS_SAVE_PATH, NULL) != FSE_OK) { + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); + return; + } + uint32_t file_version; + FuriString* temp_str = furi_string_alloc(); + + if(!flipper_format_file_open_existing(fff_file, BOILERPLATE_SETTINGS_SAVE_PATH)) { + FURI_LOG_E(TAG, "Cannot open file %s", BOILERPLATE_SETTINGS_SAVE_PATH); + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); + return; + } + + if(!flipper_format_read_header(fff_file, temp_str, &file_version)) { + FURI_LOG_E(TAG, "Missing Header Data"); + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); + return; + } + + if(file_version < BOILERPLATE_SETTINGS_FILE_VERSION) { + FURI_LOG_I(TAG, "old config version, will be removed."); + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); + return; + } + + flipper_format_read_uint32( + fff_file, BOILERPLATE_SETTINGS_KEY_ORIENTATION, &app->orientation, 1); + flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_HAPTIC, &app->haptic, 1); + flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_SPEAKER, &app->speaker, 1); + flipper_format_read_uint32(fff_file, BOILERPLATE_SETTINGS_KEY_LED, &app->led, 1); + + flipper_format_rewind(fff_file); + + camera_suite_close_config_file(fff_file); + camera_suite_close_storage(); +} \ No newline at end of file diff --git a/applications/external/camera_suite/helpers/camera_suite_storage.h b/applications/external/camera_suite/helpers/camera_suite_storage.h new file mode 100644 index 000000000..37e82d722 --- /dev/null +++ b/applications/external/camera_suite/helpers/camera_suite_storage.h @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include "../camera_suite.h" + +#define BOILERPLATE_SETTINGS_FILE_VERSION 1 +#define CONFIG_FILE_DIRECTORY_PATH EXT_PATH("apps_data/camera_suite") +#define BOILERPLATE_SETTINGS_SAVE_PATH CONFIG_FILE_DIRECTORY_PATH "/camera_suite.conf" +#define BOILERPLATE_SETTINGS_SAVE_PATH_TMP BOILERPLATE_SETTINGS_SAVE_PATH ".tmp" +#define BOILERPLATE_SETTINGS_HEADER "Camera Suite Config File" +#define BOILERPLATE_SETTINGS_KEY_ORIENTATION "Orientation" +#define BOILERPLATE_SETTINGS_KEY_HAPTIC "Haptic" +#define BOILERPLATE_SETTINGS_KEY_LED "Led" +#define BOILERPLATE_SETTINGS_KEY_SPEAKER "Speaker" +#define BOILERPLATE_SETTINGS_KEY_SAVE_SETTINGS "SaveSettings" + +void camera_suite_save_settings(void* context); + +void camera_suite_read_settings(void* context); diff --git a/applications/external/camera_suite/icons/camera_suite.png b/applications/external/camera_suite/icons/camera_suite.png new file mode 100644 index 000000000..cee545bb9 Binary files /dev/null and b/applications/external/camera_suite/icons/camera_suite.png differ diff --git a/applications/external/camera_suite/scenes/camera_suite_scene.c b/applications/external/camera_suite/scenes/camera_suite_scene.c new file mode 100644 index 000000000..c503fab5d --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene.c @@ -0,0 +1,30 @@ +#include "camera_suite_scene.h" + +// Generate scene on_enter handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, +void (*const camera_suite_on_enter_handlers[])(void*) = { +#include "camera_suite_scene_config.h" +}; +#undef ADD_SCENE + +// Generate scene on_event handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, +bool (*const camera_suite_on_event_handlers[])(void* context, SceneManagerEvent event) = { +#include "camera_suite_scene_config.h" +}; +#undef ADD_SCENE + +// Generate scene on_exit handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, +void (*const camera_suite_on_exit_handlers[])(void* context) = { +#include "camera_suite_scene_config.h" +}; +#undef ADD_SCENE + +// Initialize scene handlers configuration structure +const SceneManagerHandlers camera_suite_scene_handlers = { + .on_enter_handlers = camera_suite_on_enter_handlers, + .on_event_handlers = camera_suite_on_event_handlers, + .on_exit_handlers = camera_suite_on_exit_handlers, + .scene_num = CameraSuiteSceneNum, +}; diff --git a/applications/external/camera_suite/scenes/camera_suite_scene.h b/applications/external/camera_suite/scenes/camera_suite_scene.h new file mode 100644 index 000000000..2d88b126d --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +// Generate scene id and total number +#define ADD_SCENE(prefix, name, id) CameraSuiteScene##id, +typedef enum { +#include "camera_suite_scene_config.h" + CameraSuiteSceneNum, +} CameraSuiteScene; +#undef ADD_SCENE + +extern const SceneManagerHandlers camera_suite_scene_handlers; + +// Generate scene on_enter handlers declaration +#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); +#include "camera_suite_scene_config.h" +#undef ADD_SCENE + +// Generate scene on_event handlers declaration +#define ADD_SCENE(prefix, name, id) \ + bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); +#include "camera_suite_scene_config.h" +#undef ADD_SCENE + +// Generate scene on_exit handlers declaration +#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); +#include "camera_suite_scene_config.h" +#undef ADD_SCENE diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_config.h b/applications/external/camera_suite/scenes/camera_suite_scene_config.h new file mode 100644 index 000000000..fca73ae16 --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_config.h @@ -0,0 +1,6 @@ +ADD_SCENE(camera_suite, start, Start) +ADD_SCENE(camera_suite, menu, Menu) +ADD_SCENE(camera_suite, style_1, Style_1) +ADD_SCENE(camera_suite, style_2, Style_2) +ADD_SCENE(camera_suite, guide, Guide) +ADD_SCENE(camera_suite, settings, Settings) \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_guide.c b/applications/external/camera_suite/scenes/camera_suite_scene_guide.c new file mode 100644 index 000000000..6599058ef --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_guide.c @@ -0,0 +1,51 @@ +#include "../camera_suite.h" +#include "../helpers/camera_suite_custom_event.h" +#include "../views/camera_suite_view_guide.h" + +void camera_suite_view_guide_callback(CameraSuiteCustomEvent event, void* context) { + furi_assert(context); + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void camera_suite_scene_guide_on_enter(void* context) { + furi_assert(context); + CameraSuite* app = context; + camera_suite_view_guide_set_callback( + app->camera_suite_view_guide, camera_suite_view_guide_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdGuide); +} + +bool camera_suite_scene_guide_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + switch(event.event) { + case CameraSuiteCustomEventSceneGuideLeft: + case CameraSuiteCustomEventSceneGuideRight: + case CameraSuiteCustomEventSceneGuideUp: + case CameraSuiteCustomEventSceneGuideDown: + // Do nothing. + break; + case CameraSuiteCustomEventSceneGuideBack: + notification_message(app->notification, &sequence_reset_red); + notification_message(app->notification, &sequence_reset_green); + notification_message(app->notification, &sequence_reset_blue); + if(!scene_manager_search_and_switch_to_previous_scene( + app->scene_manager, CameraSuiteSceneMenu)) { + scene_manager_stop(app->scene_manager); + view_dispatcher_stop(app->view_dispatcher); + } + consumed = true; + break; + } + } + + return consumed; +} + +void camera_suite_scene_guide_on_exit(void* context) { + CameraSuite* app = context; + UNUSED(app); +} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_menu.c b/applications/external/camera_suite/scenes/camera_suite_scene_menu.c new file mode 100644 index 000000000..09c4dade7 --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_menu.c @@ -0,0 +1,87 @@ +#include "../camera_suite.h" + +enum SubmenuIndex { + /** Atkinson Dithering Algorithm. */ + SubmenuIndexSceneStyle1 = 10, + /** Floyd-Steinberg Dithering Algorithm. */ + SubmenuIndexSceneStyle2, + /** Guide/how-to. */ + SubmenuIndexGuide, + /** Settings menu. */ + SubmenuIndexSettings, +}; + +void camera_suite_scene_menu_submenu_callback(void* context, uint32_t index) { + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void camera_suite_scene_menu_on_enter(void* context) { + CameraSuite* app = context; + + submenu_add_item( + app->submenu, + "Open Camera", + SubmenuIndexSceneStyle1, + camera_suite_scene_menu_submenu_callback, + app); + // Staged view for the future. + // submenu_add_item( + // app->submenu, + // "Test", + // SubmenuIndexSceneStyle2, + // camera_suite_scene_menu_submenu_callback, + // app); + submenu_add_item( + app->submenu, "Guide", SubmenuIndexGuide, camera_suite_scene_menu_submenu_callback, app); + submenu_add_item( + app->submenu, + "Settings", + SubmenuIndexSettings, + camera_suite_scene_menu_submenu_callback, + app); + + submenu_set_selected_item( + app->submenu, scene_manager_get_scene_state(app->scene_manager, CameraSuiteSceneMenu)); + + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdMenu); +} + +bool camera_suite_scene_menu_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + UNUSED(app); + if(event.type == SceneManagerEventTypeBack) { + // Exit application. + scene_manager_stop(app->scene_manager); + view_dispatcher_stop(app->view_dispatcher); + return true; + } else if(event.type == SceneManagerEventTypeCustom) { + if(event.event == SubmenuIndexSceneStyle1) { + scene_manager_set_scene_state( + app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexSceneStyle1); + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneStyle_1); + return true; + } else if(event.event == SubmenuIndexSceneStyle2) { + scene_manager_set_scene_state( + app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexSceneStyle2); + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneStyle_2); + return true; + } else if(event.event == SubmenuIndexGuide) { + scene_manager_set_scene_state( + app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexGuide); + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneGuide); + return true; + } else if(event.event == SubmenuIndexSettings) { + scene_manager_set_scene_state( + app->scene_manager, CameraSuiteSceneMenu, SubmenuIndexSettings); + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneSettings); + return true; + } + } + return false; +} + +void camera_suite_scene_menu_on_exit(void* context) { + CameraSuite* app = context; + submenu_reset(app->submenu); +} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_settings.c b/applications/external/camera_suite/scenes/camera_suite_scene_settings.c new file mode 100644 index 000000000..a06b45fe9 --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_settings.c @@ -0,0 +1,137 @@ +#include "../camera_suite.h" +#include + +// Camera orientation, in degrees. +const char* const orientation_text[4] = { + "0", + "90", + "180", + "270", +}; + +const uint32_t orientation_value[4] = { + CameraSuiteOrientation0, + CameraSuiteOrientation90, + CameraSuiteOrientation180, + CameraSuiteOrientation270, +}; + +const char* const haptic_text[2] = { + "OFF", + "ON", +}; + +const uint32_t haptic_value[2] = { + CameraSuiteHapticOff, + CameraSuiteHapticOn, +}; + +const char* const speaker_text[2] = { + "OFF", + "ON", +}; + +const uint32_t speaker_value[2] = { + CameraSuiteSpeakerOff, + CameraSuiteSpeakerOn, +}; + +const char* const led_text[2] = { + "OFF", + "ON", +}; + +const uint32_t led_value[2] = { + CameraSuiteLedOff, + CameraSuiteLedOn, +}; + +static void camera_suite_scene_settings_set_camera_orientation(VariableItem* item) { + CameraSuite* app = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + + variable_item_set_current_value_text(item, orientation_text[index]); + app->orientation = orientation_value[index]; +} + +static void camera_suite_scene_settings_set_haptic(VariableItem* item) { + CameraSuite* app = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + + variable_item_set_current_value_text(item, haptic_text[index]); + app->haptic = haptic_value[index]; +} + +static void camera_suite_scene_settings_set_speaker(VariableItem* item) { + CameraSuite* app = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + variable_item_set_current_value_text(item, speaker_text[index]); + app->speaker = speaker_value[index]; +} + +static void camera_suite_scene_settings_set_led(VariableItem* item) { + CameraSuite* app = variable_item_get_context(item); + uint8_t index = variable_item_get_current_value_index(item); + variable_item_set_current_value_text(item, led_text[index]); + app->led = led_value[index]; +} + +void camera_suite_scene_settings_submenu_callback(void* context, uint32_t index) { + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void camera_suite_scene_settings_on_enter(void* context) { + CameraSuite* app = context; + VariableItem* item; + uint8_t value_index; + + // Camera Orientation + item = variable_item_list_add( + app->variable_item_list, + "Orientation:", + 4, + camera_suite_scene_settings_set_camera_orientation, + app); + value_index = value_index_uint32(app->orientation, orientation_value, 4); + variable_item_set_current_value_index(item, value_index); + variable_item_set_current_value_text(item, orientation_text[value_index]); + + // Haptic FX ON/OFF + item = variable_item_list_add( + app->variable_item_list, "Haptic FX:", 2, camera_suite_scene_settings_set_haptic, app); + value_index = value_index_uint32(app->haptic, haptic_value, 2); + variable_item_set_current_value_index(item, value_index); + variable_item_set_current_value_text(item, haptic_text[value_index]); + + // Sound FX ON/OFF + item = variable_item_list_add( + app->variable_item_list, "Sound FX:", 2, camera_suite_scene_settings_set_speaker, app); + value_index = value_index_uint32(app->speaker, speaker_value, 2); + variable_item_set_current_value_index(item, value_index); + variable_item_set_current_value_text(item, speaker_text[value_index]); + + // LED FX ON/OFF + item = variable_item_list_add( + app->variable_item_list, "LED FX:", 2, camera_suite_scene_settings_set_led, app); + value_index = value_index_uint32(app->led, led_value, 2); + variable_item_set_current_value_index(item, value_index); + variable_item_set_current_value_text(item, led_text[value_index]); + + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdSettings); +} + +bool camera_suite_scene_settings_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + UNUSED(app); + bool consumed = false; + if(event.type == SceneManagerEventTypeCustom) { + } + return consumed; +} + +void camera_suite_scene_settings_on_exit(void* context) { + CameraSuite* app = context; + variable_item_list_set_selected_item(app->variable_item_list, 0); + variable_item_list_reset(app->variable_item_list); +} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_start.c b/applications/external/camera_suite/scenes/camera_suite_scene_start.c new file mode 100644 index 000000000..12591760c --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_start.c @@ -0,0 +1,55 @@ +#include "../camera_suite.h" +#include "../helpers/camera_suite_custom_event.h" +#include "../views/camera_suite_view_start.h" + +void camera_suite_scene_start_callback(CameraSuiteCustomEvent event, void* context) { + furi_assert(context); + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void camera_suite_scene_start_on_enter(void* context) { + furi_assert(context); + CameraSuite* app = context; + camera_suite_view_start_set_callback( + app->camera_suite_view_start, camera_suite_scene_start_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdStartscreen); +} + +bool camera_suite_scene_start_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + switch(event.event) { + case CameraSuiteCustomEventStartLeft: + case CameraSuiteCustomEventStartRight: + break; + case CameraSuiteCustomEventStartUp: + case CameraSuiteCustomEventStartDown: + break; + case CameraSuiteCustomEventStartOk: + scene_manager_next_scene(app->scene_manager, CameraSuiteSceneMenu); + consumed = true; + break; + case CameraSuiteCustomEventStartBack: + notification_message(app->notification, &sequence_reset_red); + notification_message(app->notification, &sequence_reset_green); + notification_message(app->notification, &sequence_reset_blue); + if(!scene_manager_search_and_switch_to_previous_scene( + app->scene_manager, CameraSuiteSceneStart)) { + scene_manager_stop(app->scene_manager); + view_dispatcher_stop(app->view_dispatcher); + } + consumed = true; + break; + } + } + + return consumed; +} + +void camera_suite_scene_start_on_exit(void* context) { + CameraSuite* app = context; + UNUSED(app); +} \ No newline at end of file diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_style_1.c b/applications/external/camera_suite/scenes/camera_suite_scene_style_1.c new file mode 100644 index 000000000..1aeecec7a --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_style_1.c @@ -0,0 +1,52 @@ +#include "../camera_suite.h" +#include "../helpers/camera_suite_custom_event.h" +#include "../views/camera_suite_view_style_1.h" + +static void camera_suite_view_style_1_callback(CameraSuiteCustomEvent event, void* context) { + furi_assert(context); + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void camera_suite_scene_style_1_on_enter(void* context) { + furi_assert(context); + CameraSuite* app = context; + camera_suite_view_style_1_set_callback( + app->camera_suite_view_style_1, camera_suite_view_style_1_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdScene1); +} + +bool camera_suite_scene_style_1_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + switch(event.event) { + case CameraSuiteCustomEventSceneStyle1Left: + case CameraSuiteCustomEventSceneStyle1Right: + case CameraSuiteCustomEventSceneStyle1Up: + case CameraSuiteCustomEventSceneStyle1Down: + case CameraSuiteCustomEventSceneStyle1Ok: + // Do nothing. + break; + case CameraSuiteCustomEventSceneStyle1Back: + notification_message(app->notification, &sequence_reset_red); + notification_message(app->notification, &sequence_reset_green); + notification_message(app->notification, &sequence_reset_blue); + if(!scene_manager_search_and_switch_to_previous_scene( + app->scene_manager, CameraSuiteSceneMenu)) { + scene_manager_stop(app->scene_manager); + view_dispatcher_stop(app->view_dispatcher); + } + consumed = true; + break; + } + } + + return consumed; +} + +void camera_suite_scene_style_1_on_exit(void* context) { + CameraSuite* app = context; + UNUSED(app); +} diff --git a/applications/external/camera_suite/scenes/camera_suite_scene_style_2.c b/applications/external/camera_suite/scenes/camera_suite_scene_style_2.c new file mode 100644 index 000000000..b74d33784 --- /dev/null +++ b/applications/external/camera_suite/scenes/camera_suite_scene_style_2.c @@ -0,0 +1,54 @@ +#include "../camera_suite.h" +#include "../helpers/camera_suite_custom_event.h" +#include "../helpers/camera_suite_haptic.h" +#include "../helpers/camera_suite_led.h" +#include "../views/camera_suite_view_style_2.h" + +void camera_suite_view_style_2_callback(CameraSuiteCustomEvent event, void* context) { + furi_assert(context); + CameraSuite* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, event); +} + +void camera_suite_scene_style_2_on_enter(void* context) { + furi_assert(context); + CameraSuite* app = context; + camera_suite_view_style_2_set_callback( + app->camera_suite_view_style_2, camera_suite_view_style_2_callback, app); + view_dispatcher_switch_to_view(app->view_dispatcher, CameraSuiteViewIdScene2); +} + +bool camera_suite_scene_style_2_on_event(void* context, SceneManagerEvent event) { + CameraSuite* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + switch(event.event) { + case CameraSuiteCustomEventSceneStyle2Left: + case CameraSuiteCustomEventSceneStyle2Right: + case CameraSuiteCustomEventSceneStyle2Up: + case CameraSuiteCustomEventSceneStyle2Down: + case CameraSuiteCustomEventSceneStyle2Ok: + // Do nothing. + break; + case CameraSuiteCustomEventSceneStyle2Back: + notification_message(app->notification, &sequence_reset_red); + notification_message(app->notification, &sequence_reset_green); + notification_message(app->notification, &sequence_reset_blue); + if(!scene_manager_search_and_switch_to_previous_scene( + app->scene_manager, CameraSuiteSceneMenu)) { + scene_manager_stop(app->scene_manager); + view_dispatcher_stop(app->view_dispatcher); + } + consumed = true; + break; + } + } + + return consumed; +} + +void camera_suite_scene_style_2_on_exit(void* context) { + CameraSuite* app = context; + UNUSED(app); +} diff --git a/applications/external/camera_suite/views/camera_suite_view_guide.c b/applications/external/camera_suite/views/camera_suite_view_guide.c new file mode 100644 index 000000000..479f8d4d1 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_guide.c @@ -0,0 +1,120 @@ +#include "../camera_suite.h" +#include +#include +#include +#include +#include + +struct CameraSuiteViewGuide { + View* view; + CameraSuiteViewGuideCallback callback; + void* context; +}; + +typedef struct { + int some_value; +} CameraSuiteViewGuideModel; + +void camera_suite_view_guide_set_callback( + CameraSuiteViewGuide* instance, + CameraSuiteViewGuideCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + instance->callback = callback; + instance->context = context; +} + +void camera_suite_view_guide_draw(Canvas* canvas, CameraSuiteViewGuideModel* model) { + UNUSED(model); + canvas_clear(canvas); + canvas_set_color(canvas, ColorBlack); + canvas_set_font(canvas, FontPrimary); + canvas_draw_str_aligned(canvas, 0, 0, AlignLeft, AlignTop, "Guide"); + canvas_set_font(canvas, FontSecondary); + canvas_draw_str_aligned(canvas, 0, 12, AlignLeft, AlignTop, "Left = Toggle Invert"); + canvas_draw_str_aligned(canvas, 0, 22, AlignLeft, AlignTop, "Right = Toggle Dithering"); + canvas_draw_str_aligned(canvas, 0, 32, AlignLeft, AlignTop, "Up = Contrast Up"); + canvas_draw_str_aligned(canvas, 0, 42, AlignLeft, AlignTop, "Down = Contrast Down"); + // TODO: Possibly update to take picture instead. + canvas_draw_str_aligned(canvas, 0, 52, AlignLeft, AlignTop, "Center = Toggle Dither Type"); +} + +static void camera_suite_view_guide_model_init(CameraSuiteViewGuideModel* const model) { + model->some_value = 1; +} + +bool camera_suite_view_guide_input(InputEvent* event, void* context) { + furi_assert(context); + CameraSuiteViewGuide* instance = context; + if(event->type == InputTypeRelease) { + switch(event->key) { + case InputKeyBack: + with_view_model( + instance->view, + CameraSuiteViewGuideModel * model, + { + UNUSED(model); + instance->callback(CameraSuiteCustomEventSceneGuideBack, instance->context); + }, + true); + break; + case InputKeyLeft: + case InputKeyRight: + case InputKeyUp: + case InputKeyDown: + case InputKeyOk: + case InputKeyMAX: + // Do nothing. + break; + } + } + return true; +} + +void camera_suite_view_guide_exit(void* context) { + furi_assert(context); +} + +void camera_suite_view_guide_enter(void* context) { + furi_assert(context); + CameraSuiteViewGuide* instance = (CameraSuiteViewGuide*)context; + with_view_model( + instance->view, + CameraSuiteViewGuideModel * model, + { camera_suite_view_guide_model_init(model); }, + true); +} + +CameraSuiteViewGuide* camera_suite_view_guide_alloc() { + CameraSuiteViewGuide* instance = malloc(sizeof(CameraSuiteViewGuide)); + instance->view = view_alloc(); + view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(CameraSuiteViewGuideModel)); + view_set_context(instance->view, instance); // furi_assert crashes in events without this + view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_guide_draw); + view_set_input_callback(instance->view, camera_suite_view_guide_input); + view_set_enter_callback(instance->view, camera_suite_view_guide_enter); + view_set_exit_callback(instance->view, camera_suite_view_guide_exit); + + with_view_model( + instance->view, + CameraSuiteViewGuideModel * model, + { camera_suite_view_guide_model_init(model); }, + true); + + return instance; +} + +void camera_suite_view_guide_free(CameraSuiteViewGuide* instance) { + furi_assert(instance); + + with_view_model( + instance->view, CameraSuiteViewGuideModel * model, { UNUSED(model); }, true); + view_free(instance->view); + free(instance); +} + +View* camera_suite_view_guide_get_view(CameraSuiteViewGuide* instance) { + furi_assert(instance); + return instance->view; +} diff --git a/applications/external/camera_suite/views/camera_suite_view_guide.h b/applications/external/camera_suite/views/camera_suite_view_guide.h new file mode 100644 index 000000000..cd78d4b01 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_guide.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "../helpers/camera_suite_custom_event.h" + +typedef struct CameraSuiteViewGuide CameraSuiteViewGuide; + +typedef void (*CameraSuiteViewGuideCallback)(CameraSuiteCustomEvent event, void* context); + +void camera_suite_view_guide_set_callback( + CameraSuiteViewGuide* camera_suite_view_guide, + CameraSuiteViewGuideCallback callback, + void* context); + +View* camera_suite_view_guide_get_view(CameraSuiteViewGuide* camera_suite_static); + +CameraSuiteViewGuide* camera_suite_view_guide_alloc(); + +void camera_suite_view_guide_free(CameraSuiteViewGuide* camera_suite_static); \ No newline at end of file diff --git a/applications/external/camera_suite/views/camera_suite_view_start.c b/applications/external/camera_suite/views/camera_suite_view_start.c new file mode 100644 index 000000000..a84ee50c2 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_start.c @@ -0,0 +1,126 @@ +#include "../camera_suite.h" +#include +#include +#include +#include + +struct CameraSuiteViewStart { + View* view; + CameraSuiteViewStartCallback callback; + void* context; +}; + +typedef struct { + int some_value; +} CameraSuiteViewStartModel; + +void camera_suite_view_start_set_callback( + CameraSuiteViewStart* instance, + CameraSuiteViewStartCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + instance->callback = callback; + instance->context = context; +} + +void camera_suite_view_start_draw(Canvas* canvas, CameraSuiteViewStartModel* model) { + UNUSED(model); + canvas_clear(canvas); + canvas_set_color(canvas, ColorBlack); + canvas_set_font(canvas, FontPrimary); + canvas_draw_str_aligned(canvas, 64, 10, AlignCenter, AlignTop, "Camera Suite"); + canvas_set_font(canvas, FontSecondary); + canvas_draw_str_aligned(canvas, 64, 22, AlignCenter, AlignTop, "Flipper Zero"); + canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignTop, "ESP32 CAM"); + elements_button_center(canvas, "Start"); +} + +static void camera_suite_view_start_model_init(CameraSuiteViewStartModel* const model) { + model->some_value = 1; +} + +bool camera_suite_view_start_input(InputEvent* event, void* context) { + furi_assert(context); + CameraSuiteViewStart* instance = context; + if(event->type == InputTypeRelease) { + switch(event->key) { + case InputKeyBack: + // Exit application. + with_view_model( + instance->view, + CameraSuiteViewStartModel * model, + { + UNUSED(model); + instance->callback(CameraSuiteCustomEventStartBack, instance->context); + }, + true); + break; + case InputKeyOk: + // Start the application. + with_view_model( + instance->view, + CameraSuiteViewStartModel * model, + { + UNUSED(model); + instance->callback(CameraSuiteCustomEventStartOk, instance->context); + }, + true); + break; + case InputKeyMAX: + case InputKeyLeft: + case InputKeyRight: + case InputKeyUp: + case InputKeyDown: + // Do nothing. + break; + } + } + return true; +} + +void camera_suite_view_start_exit(void* context) { + furi_assert(context); +} + +void camera_suite_view_start_enter(void* context) { + furi_assert(context); + CameraSuiteViewStart* instance = (CameraSuiteViewStart*)context; + with_view_model( + instance->view, + CameraSuiteViewStartModel * model, + { camera_suite_view_start_model_init(model); }, + true); +} + +CameraSuiteViewStart* camera_suite_view_start_alloc() { + CameraSuiteViewStart* instance = malloc(sizeof(CameraSuiteViewStart)); + instance->view = view_alloc(); + view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(CameraSuiteViewStartModel)); + // furi_assert crashes in events without this + view_set_context(instance->view, instance); + view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_start_draw); + view_set_input_callback(instance->view, camera_suite_view_start_input); + + with_view_model( + instance->view, + CameraSuiteViewStartModel * model, + { camera_suite_view_start_model_init(model); }, + true); + + return instance; +} + +void camera_suite_view_start_free(CameraSuiteViewStart* instance) { + furi_assert(instance); + + with_view_model( + instance->view, CameraSuiteViewStartModel * model, { UNUSED(model); }, true); + view_free(instance->view); + free(instance); +} + +View* camera_suite_view_start_get_view(CameraSuiteViewStart* instance) { + furi_assert(instance); + return instance->view; +} diff --git a/applications/external/camera_suite/views/camera_suite_view_start.h b/applications/external/camera_suite/views/camera_suite_view_start.h new file mode 100644 index 000000000..e991cce92 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_start.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "../helpers/camera_suite_custom_event.h" + +typedef struct CameraSuiteViewStart CameraSuiteViewStart; + +typedef void (*CameraSuiteViewStartCallback)(CameraSuiteCustomEvent event, void* context); + +void camera_suite_view_start_set_callback( + CameraSuiteViewStart* camera_suite_view_start, + CameraSuiteViewStartCallback callback, + void* context); + +View* camera_suite_view_start_get_view(CameraSuiteViewStart* camera_suite_static); + +CameraSuiteViewStart* camera_suite_view_start_alloc(); + +void camera_suite_view_start_free(CameraSuiteViewStart* camera_suite_static); \ No newline at end of file diff --git a/applications/external/camera_suite/views/camera_suite_view_style_1.c b/applications/external/camera_suite/views/camera_suite_view_style_1.c new file mode 100644 index 000000000..6d16d0231 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_style_1.c @@ -0,0 +1,401 @@ +#include "../camera_suite.h" +#include +#include +#include +#include +#include +#include "../helpers/camera_suite_haptic.h" +#include "../helpers/camera_suite_speaker.h" +#include "../helpers/camera_suite_led.h" + +static CameraSuiteViewStyle1* current_instance = NULL; +// Dithering type: +// 0 = Floyd Steinberg (default) +// 1 = Atkinson +static int current_dithering = 0; + +struct CameraSuiteViewStyle1 { + CameraSuiteViewStyle1Callback callback; + FuriStreamBuffer* rx_stream; + FuriThread* worker_thread; + View* view; + void* context; +}; + +void camera_suite_view_style_1_set_callback( + CameraSuiteViewStyle1* instance, + CameraSuiteViewStyle1Callback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + instance->callback = callback; + instance->context = context; +} + +static void camera_suite_view_style_1_draw(Canvas* canvas, UartDumpModel* model) { + // Clear the screen. + canvas_set_color(canvas, ColorBlack); + + // Draw the frame. + canvas_draw_frame(canvas, 0, 0, FRAME_WIDTH, FRAME_HEIGHT); + + CameraSuite* app = current_instance->context; + + // Draw the pixels with rotation. + for(size_t p = 0; p < FRAME_BUFFER_LENGTH; ++p) { + uint8_t x = p % ROW_BUFFER_LENGTH; // 0 .. 15 + uint8_t y = p / ROW_BUFFER_LENGTH; // 0 .. 63 + + // Apply rotation + int16_t rotated_x, rotated_y; + switch(app->orientation) { + case 1: // 90 degrees + rotated_x = y; + rotated_y = FRAME_WIDTH - 1 - x; + break; + case 2: // 180 degrees + rotated_x = FRAME_WIDTH - 1 - x; + rotated_y = FRAME_HEIGHT - 1 - y; + break; + case 3: // 270 degrees + rotated_x = FRAME_HEIGHT - 1 - y; + rotated_y = x; + break; + case 0: // 0 degrees + default: + rotated_x = x; + rotated_y = y; + break; + } + + for(uint8_t i = 0; i < 8; ++i) { + if((model->pixels[p] & (1 << i)) != 0) { + // Adjust the coordinates based on the new screen dimensions + uint16_t screen_x, screen_y; + switch(app->orientation) { + case 1: // 90 degrees + screen_x = rotated_x; + screen_y = FRAME_HEIGHT - 8 + (rotated_y * 8) + i; + break; + case 2: // 180 degrees + screen_x = FRAME_WIDTH - 8 + (rotated_x * 8) + i; + screen_y = FRAME_HEIGHT - 1 - rotated_y; + break; + case 3: // 270 degrees + screen_x = FRAME_WIDTH - 1 - rotated_x; + screen_y = rotated_y * 8 + i; + break; + case 0: // 0 degrees + default: + screen_x = rotated_x * 8 + i; + screen_y = rotated_y; + break; + } + canvas_draw_dot(canvas, screen_x, screen_y); + } + } + } + // Draw the guide if the camera is not initialized. + if(!model->initialized) { + canvas_draw_icon(canvas, 74, 16, &I_DolphinCommon_56x48); + canvas_set_font(canvas, FontSecondary); + canvas_draw_str(canvas, 8, 12, "Connect the ESP32-CAM"); + canvas_draw_str(canvas, 20, 24, "VCC - 3V3"); + canvas_draw_str(canvas, 20, 34, "GND - GND"); + canvas_draw_str(canvas, 20, 44, "U0R - TX"); + canvas_draw_str(canvas, 20, 54, "U0T - RX"); + } +} + +static void camera_suite_view_style_1_model_init(UartDumpModel* const model) { + for(size_t i = 0; i < FRAME_BUFFER_LENGTH; i++) { + model->pixels[i] = 0; + } +} + +static bool camera_suite_view_style_1_input(InputEvent* event, void* context) { + furi_assert(context); + CameraSuiteViewStyle1* instance = context; + if(event->type == InputTypeRelease) { + switch(event->key) { + default: // Stop all sounds, reset the LED. + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 0); + }, + true); + break; + } + // Send `data` to the ESP32-CAM + } else if(event->type == InputTypePress) { + uint8_t data[1]; + switch(event->key) { + case InputKeyBack: + // Stop the camera stream. + data[0] = 's'; + // Go back to the main menu. + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + instance->callback(CameraSuiteCustomEventSceneStyle1Back, instance->context); + }, + true); + break; + case InputKeyLeft: + // Camera: Invert. + data[0] = '<'; + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 255); + instance->callback(CameraSuiteCustomEventSceneStyle1Left, instance->context); + }, + true); + break; + case InputKeyRight: + // Camera: Enable/disable dithering. + data[0] = '>'; + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 255); + instance->callback(CameraSuiteCustomEventSceneStyle1Right, instance->context); + }, + true); + break; + case InputKeyUp: + // Camera: Increase contrast. + data[0] = 'C'; + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 255); + instance->callback(CameraSuiteCustomEventSceneStyle1Up, instance->context); + }, + true); + break; + case InputKeyDown: + // Camera: Reduce contrast. + data[0] = 'c'; + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 255); + instance->callback(CameraSuiteCustomEventSceneStyle1Down, instance->context); + }, + true); + break; + case InputKeyOk: + if(current_dithering == 0) { + data[0] = 'd'; // Update to Floyd Steinberg dithering. + current_dithering = 1; + } else { + data[0] = 'D'; // Update to Atkinson dithering. + current_dithering = 0; + } + with_view_model( + instance->view, + UartDumpModel * model, + { + UNUSED(model); + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 0, 255); + instance->callback(CameraSuiteCustomEventSceneStyle1Ok, instance->context); + }, + true); + break; + case InputKeyMAX: + break; + } + // Send `data` to the ESP32-CAM + furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1); + } + return true; +} + +static void camera_suite_view_style_1_exit(void* context) { + furi_assert(context); +} + +static void camera_suite_view_style_1_enter(void* context) { + // Check `context` for null. If it is null, abort program, else continue. + furi_assert(context); + + // Cast `context` to `CameraSuiteViewStyle1*` and store it in `instance`. + CameraSuiteViewStyle1* instance = (CameraSuiteViewStyle1*)context; + + // Assign the current instance to the global variable + current_instance = instance; + + uint8_t data[1]; + data[0] = 'S'; // Uppercase `S` to start the camera + // Send `data` to the ESP32-CAM + furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1); + + with_view_model( + instance->view, + UartDumpModel * model, + { camera_suite_view_style_1_model_init(model); }, + true); +} + +static void camera_on_irq_cb(UartIrqEvent uartIrqEvent, uint8_t data, void* context) { + // Check `context` for null. If it is null, abort program, else continue. + furi_assert(context); + + // Cast `context` to `CameraSuiteViewStyle1*` and store it in `instance`. + CameraSuiteViewStyle1* instance = context; + + // If `uartIrqEvent` is `UartIrqEventRXNE`, send the data to the + // `rx_stream` and set the `WorkerEventRx` flag. + if(uartIrqEvent == UartIrqEventRXNE) { + furi_stream_buffer_send(instance->rx_stream, &data, 1, 0); + furi_thread_flags_set(furi_thread_get_id(instance->worker_thread), WorkerEventRx); + } +} + +static void process_ringbuffer(UartDumpModel* model, uint8_t byte) { + // First char has to be 'Y' in the buffer. + if(model->ringbuffer_index == 0 && byte != 'Y') { + return; + } + + // Second char has to be ':' in the buffer or reset. + if(model->ringbuffer_index == 1 && byte != ':') { + model->ringbuffer_index = 0; + process_ringbuffer(model, byte); + return; + } + + // Assign current byte to the ringbuffer. + model->row_ringbuffer[model->ringbuffer_index] = byte; + // Increment the ringbuffer index. + ++model->ringbuffer_index; + + // Let's wait 'till the buffer fills. + if(model->ringbuffer_index < RING_BUFFER_LENGTH) { + return; + } + + // Flush the ringbuffer to the framebuffer. + model->ringbuffer_index = 0; // Reset the ringbuffer + model->initialized = true; // Established the connection successfully. + size_t row_start_index = + model->row_ringbuffer[2] * ROW_BUFFER_LENGTH; // Third char will determine the row number + + if(row_start_index > LAST_ROW_INDEX) { // Failsafe + row_start_index = 0; + } + + for(size_t i = 0; i < ROW_BUFFER_LENGTH; ++i) { + model->pixels[row_start_index + i] = + model->row_ringbuffer[i + 3]; // Writing the remaining 16 bytes into the frame buffer + } +} + +static int32_t camera_worker(void* context) { + furi_assert(context); + CameraSuiteViewStyle1* instance = context; + + while(1) { + uint32_t events = + furi_thread_flags_wait(WORKER_EVENTS_MASK, FuriFlagWaitAny, FuriWaitForever); + furi_check((events & FuriFlagError) == 0); + + if(events & WorkerEventStop) { + break; + } else if(events & WorkerEventRx) { + size_t length = 0; + do { + size_t intended_data_size = 64; + uint8_t data[intended_data_size]; + length = + furi_stream_buffer_receive(instance->rx_stream, data, intended_data_size, 0); + + if(length > 0) { + with_view_model( + instance->view, + UartDumpModel * model, + { + for(size_t i = 0; i < length; i++) { + process_ringbuffer(model, data[i]); + } + }, + false); + } + } while(length > 0); + } + } + + return 0; +} + +CameraSuiteViewStyle1* camera_suite_view_style_1_alloc() { + CameraSuiteViewStyle1* instance = malloc(sizeof(CameraSuiteViewStyle1)); + + instance->view = view_alloc(); + + instance->rx_stream = furi_stream_buffer_alloc(2048, 1); + + // Set up views + view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(UartDumpModel)); + view_set_context(instance->view, instance); // furi_assert crashes in events without this + view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_style_1_draw); + view_set_input_callback(instance->view, camera_suite_view_style_1_input); + view_set_enter_callback(instance->view, camera_suite_view_style_1_enter); + view_set_exit_callback(instance->view, camera_suite_view_style_1_exit); + + with_view_model( + instance->view, + UartDumpModel * model, + { camera_suite_view_style_1_model_init(model); }, + true); + + instance->worker_thread = furi_thread_alloc_ex("UsbUartWorker", 2048, camera_worker, instance); + furi_thread_start(instance->worker_thread); + + // Enable uart listener + furi_hal_console_disable(); + furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); + furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, camera_on_irq_cb, instance); + + return instance; +} + +void camera_suite_view_style_1_free(CameraSuiteViewStyle1* instance) { + furi_assert(instance); + + with_view_model( + instance->view, UartDumpModel * model, { UNUSED(model); }, true); + view_free(instance->view); + free(instance); +} + +View* camera_suite_view_style_1_get_view(CameraSuiteViewStyle1* instance) { + furi_assert(instance); + return instance->view; +} diff --git a/applications/external/camera_suite/views/camera_suite_view_style_1.h b/applications/external/camera_suite/views/camera_suite_view_style_1.h new file mode 100644 index 000000000..c460c94ba --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_style_1.h @@ -0,0 +1,60 @@ +#include "../helpers/camera_suite_custom_event.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma once + +#define FRAME_WIDTH 128 +#define FRAME_HEIGHT 64 +#define FRAME_BIT_DEPTH 1 +#define FRAME_BUFFER_LENGTH \ + (FRAME_WIDTH * FRAME_HEIGHT * FRAME_BIT_DEPTH / 8) // 128*64*1 / 8 = 1024 +#define ROW_BUFFER_LENGTH (FRAME_WIDTH / 8) // 128/8 = 16 +#define RING_BUFFER_LENGTH (ROW_BUFFER_LENGTH + 3) // ROW_BUFFER_LENGTH + Header => 16 + 3 = 19 +#define LAST_ROW_INDEX (FRAME_BUFFER_LENGTH - ROW_BUFFER_LENGTH) // 1024 - 16 = 1008 + +typedef struct UartDumpModel UartDumpModel; + +struct UartDumpModel { + bool initialized; + int rotation_angle; + uint8_t pixels[FRAME_BUFFER_LENGTH]; + uint8_t ringbuffer_index; + uint8_t row_ringbuffer[RING_BUFFER_LENGTH]; +}; + +typedef struct CameraSuiteViewStyle1 CameraSuiteViewStyle1; + +typedef void (*CameraSuiteViewStyle1Callback)(CameraSuiteCustomEvent event, void* context); + +void camera_suite_view_style_1_set_callback( + CameraSuiteViewStyle1* camera_suite_view_style_1, + CameraSuiteViewStyle1Callback callback, + void* context); + +CameraSuiteViewStyle1* camera_suite_view_style_1_alloc(); + +void camera_suite_view_style_1_free(CameraSuiteViewStyle1* camera_suite_static); + +View* camera_suite_view_style_1_get_view(CameraSuiteViewStyle1* camera_suite_static); + +typedef enum { + // Reserved for StreamBuffer internal event + WorkerEventReserved = (1 << 0), + WorkerEventStop = (1 << 1), + WorkerEventRx = (1 << 2), +} WorkerEventFlags; + +#define WORKER_EVENTS_MASK (WorkerEventStop | WorkerEventRx) diff --git a/applications/external/camera_suite/views/camera_suite_view_style_2.c b/applications/external/camera_suite/views/camera_suite_view_style_2.c new file mode 100644 index 000000000..0a7ac0b83 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_style_2.c @@ -0,0 +1,249 @@ +#include "../camera_suite.h" +#include +#include +#include +#include +#include +#include "../helpers/camera_suite_haptic.h" +#include "../helpers/camera_suite_speaker.h" +#include "../helpers/camera_suite_led.h" + +struct CameraSuiteViewStyle2 { + View* view; + CameraSuiteViewStyle2Callback callback; + void* context; +}; + +typedef struct { + int screen_text; +} CameraSuiteViewStyle2Model; + +char buttonText[11][14] = { + "", + "Press Up", + "Press Down", + "Press Left", + "Press Right", + "Press Ok", + "Release Up", + "Release Down", + "Release Left", + "Release Right", + "Release Ok", +}; + +void camera_suite_view_style_2_set_callback( + CameraSuiteViewStyle2* instance, + CameraSuiteViewStyle2Callback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + instance->callback = callback; + instance->context = context; +} + +void camera_suite_view_style_2_draw(Canvas* canvas, CameraSuiteViewStyle2Model* model) { + canvas_clear(canvas); + canvas_set_color(canvas, ColorBlack); + canvas_set_font(canvas, FontPrimary); + canvas_draw_str_aligned(canvas, 0, 10, AlignLeft, AlignTop, "Scene 2: Input Examples"); + canvas_set_font(canvas, FontSecondary); + char* strInput = malloc(15); + strcpy(strInput, buttonText[model->screen_text]); + canvas_draw_str_aligned(canvas, 0, 22, AlignLeft, AlignTop, strInput); + free(strInput); +} + +static void camera_suite_view_style_2_model_init(CameraSuiteViewStyle2Model* const model) { + model->screen_text = 0; +} + +bool camera_suite_view_style_2_input(InputEvent* event, void* context) { + furi_assert(context); + CameraSuiteViewStyle2* instance = context; + if(event->type == InputTypeRelease) { + switch(event->key) { + case InputKeyBack: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + UNUSED(model); + camera_suite_stop_all_sound(instance->context); + instance->callback(CameraSuiteCustomEventSceneStyle2Back, instance->context); + camera_suite_play_long_bump(instance->context); + }, + true); + break; + case InputKeyUp: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 6; + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 255, 0, 255); + }, + true); + break; + case InputKeyDown: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 7; + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 255, 255, 0); + }, + true); + break; + case InputKeyLeft: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 8; + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 0, 255, 255); + }, + true); + break; + case InputKeyRight: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 9; + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 255, 0, 0); + }, + true); + break; + case InputKeyOk: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 10; + camera_suite_play_bad_bump(instance->context); + camera_suite_stop_all_sound(instance->context); + camera_suite_led_set_rgb(instance->context, 255, 255, 255); + }, + true); + break; + case InputKeyMAX: + break; + } + } else if(event->type == InputTypePress) { + switch(event->key) { + case InputKeyUp: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 1; + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + }, + true); + break; + case InputKeyDown: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 2; + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + }, + true); + break; + case InputKeyLeft: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 3; + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + }, + true); + break; + case InputKeyRight: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 4; + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + }, + true); + break; + case InputKeyOk: + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { + model->screen_text = 5; + camera_suite_play_happy_bump(instance->context); + camera_suite_play_input_sound(instance->context); + }, + true); + break; + case InputKeyBack: + case InputKeyMAX: + break; + } + } + + return true; +} + +void camera_suite_view_style_2_exit(void* context) { + furi_assert(context); + CameraSuite* app = context; + camera_suite_stop_all_sound(app); + //camera_suite_led_reset(app); +} + +void camera_suite_view_style_2_enter(void* context) { + furi_assert(context); + dolphin_deed(DolphinDeedPluginStart); +} + +CameraSuiteViewStyle2* camera_suite_view_style_2_alloc() { + CameraSuiteViewStyle2* instance = malloc(sizeof(CameraSuiteViewStyle2)); + instance->view = view_alloc(); + view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(CameraSuiteViewStyle2Model)); + view_set_context(instance->view, instance); + view_set_draw_callback(instance->view, (ViewDrawCallback)camera_suite_view_style_2_draw); + view_set_input_callback(instance->view, camera_suite_view_style_2_input); + //view_set_enter_callback(instance->view, camera_suite_view_style_2_enter); + view_set_exit_callback(instance->view, camera_suite_view_style_2_exit); + + with_view_model( + instance->view, + CameraSuiteViewStyle2Model * model, + { camera_suite_view_style_2_model_init(model); }, + true); + + return instance; +} + +void camera_suite_view_style_2_free(CameraSuiteViewStyle2* instance) { + furi_assert(instance); + + view_free(instance->view); + free(instance); +} + +View* camera_suite_view_style_2_get_view(CameraSuiteViewStyle2* instance) { + furi_assert(instance); + + return instance->view; +} diff --git a/applications/external/camera_suite/views/camera_suite_view_style_2.h b/applications/external/camera_suite/views/camera_suite_view_style_2.h new file mode 100644 index 000000000..d24b895f8 --- /dev/null +++ b/applications/external/camera_suite/views/camera_suite_view_style_2.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "../helpers/camera_suite_custom_event.h" + +typedef struct CameraSuiteViewStyle2 CameraSuiteViewStyle2; + +typedef void (*CameraSuiteViewStyle2Callback)(CameraSuiteCustomEvent event, void* context); + +void camera_suite_view_style_2_set_callback( + CameraSuiteViewStyle2* instance, + CameraSuiteViewStyle2Callback callback, + void* context); + +CameraSuiteViewStyle2* camera_suite_view_style_2_alloc(); + +void camera_suite_view_style_2_free(CameraSuiteViewStyle2* camera_suite_static); + +View* camera_suite_view_style_2_get_view(CameraSuiteViewStyle2* boilerpate_static); 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 4dd85b751..b51efbb26 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 #define TAG "Flappy" @@ -29,6 +28,14 @@ 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; @@ -37,7 +44,6 @@ typedef struct { typedef struct { float gravity; POINT point; - IconAnimation* sprite; } BIRD; typedef struct { @@ -92,7 +98,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; @@ -105,7 +110,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); } @@ -223,14 +227,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/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 b810b2377..2d1d51316 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="[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", ) 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 000000000..94e796872 Binary files /dev/null and b/applications/external/flipper_i2ctools/images/Voltage_16x16.png differ 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 34fad74fa..6e476c6dd 100644 --- a/applications/external/flipper_i2ctools/views/main_view.h +++ b/applications/external/flipper_i2ctools/views/main_view.h @@ -1,21 +1,25 @@ #include #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 { @@ -23,6 +27,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 a38d9a917..9b571ed9b 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 #include "../i2cscanner.h" diff --git a/applications/external/flipper_i2ctools/views/sender_view.h b/applications/external/flipper_i2ctools/views/sender_view.h index 9b2e75a5c..3c2000703 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 #include "../i2csender.h" diff --git a/applications/external/flipper_i2ctools/views/sniffer_view.h b/applications/external/flipper_i2ctools/views/sniffer_view.h index b827294f8..1b586d568 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 #include "../i2csniffer.h" diff --git a/applications/external/heap_defence_game/heap_defence.c b/applications/external/heap_defence_game/heap_defence.c index 7feba107c..c88c3e5cb 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 #define Y_FIELD_SIZE 6 #define Y_LAST (Y_FIELD_SIZE - 1) diff --git a/applications/external/hex_viewer/application.fam b/applications/external/hex_viewer/application.fam index 34e52b9c7..be8a7a0dd 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 f0df85800..25a72def1 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="Tools", + 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="Tools", + fap_category="Bluetooth", fap_icon="hid_ble_10px.png", fap_icon_assets="assets", fap_icon_assets_symbol="hid", 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.", diff --git a/applications/external/mifare_nested/application.fam b/applications/external/mifare_nested/application.fam index 7f3606b36..b8e2aa0dd 100644 --- a/applications/external/mifare_nested/application.fam +++ b/applications/external/mifare_nested/application.fam @@ -13,5 +13,5 @@ App( fap_author="AloneLiberty", fap_description="Recover Mifare Classic keys", fap_weburl="https://github.com/AloneLiberty/FlipperNested", - fap_version="1.5.0", + fap_version="1.5.2", ) diff --git a/applications/external/mifare_nested/mifare_nested_i.h b/applications/external/mifare_nested/mifare_nested_i.h index 69907dcd0..b13a6c098 100644 --- a/applications/external/mifare_nested/mifare_nested_i.h +++ b/applications/external/mifare_nested/mifare_nested_i.h @@ -21,7 +21,7 @@ #include #include "mifare_nested_icons.h" -#define NESTED_VERSION_APP "1.5.0" +#define NESTED_VERSION_APP "1.5.2" #define NESTED_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNested" #define NESTED_RECOVER_KEYS_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNestedRecovery" #define NESTED_NONCE_FORMAT_VERSION "3" diff --git a/applications/external/mifare_nested/mifare_nested_worker.c b/applications/external/mifare_nested/mifare_nested_worker.c index 965fcc245..884dd1685 100644 --- a/applications/external/mifare_nested/mifare_nested_worker.c +++ b/applications/external/mifare_nested/mifare_nested_worker.c @@ -478,9 +478,13 @@ SaveNoncesResult_t* mifare_nested_worker_write_nonces( for(uint8_t sector = 0; sector < sector_count; sector++) { for(uint8_t key_type = 0; key_type < 2; key_type++) { if(nonces->nonces[sector][key_type][tries]->invalid) { - result->invalid++; + if(tries == 0) { + result->invalid++; + } } else if(nonces->nonces[sector][key_type][tries]->skipped) { - result->skipped++; + if(tries == 0) { + result->skipped++; + } } else if(nonces->nonces[sector][key_type][tries]->collected) { if(nonces->nonces[sector][key_type][tries]->hardnested) { FuriString* hardnested_path = furi_string_alloc(); @@ -574,6 +578,7 @@ bool mifare_nested_worker_check_initial_keys( info->block = mifare_nested_worker_get_block_by_sector(sector); info->collected = false; info->skipped = true; + info->from_start = false; nonces->nonces[sector][key_type][tries] = info; } @@ -591,6 +596,7 @@ bool mifare_nested_worker_check_initial_keys( Nonces* info = nonces->nonces[sector][0][tries]; info->collected = true; info->skipped = true; + info->from_start = true; nonces->nonces[sector][0][tries] = info; } @@ -612,6 +618,7 @@ bool mifare_nested_worker_check_initial_keys( Nonces* info = nonces->nonces[sector][1][tries]; info->collected = true; info->skipped = true; + info->from_start = true; nonces->nonces[sector][1][tries] = info; } diff --git a/applications/external/mifare_nested/mifare_nested_worker.h b/applications/external/mifare_nested/mifare_nested_worker.h index 2421b35eb..99c691749 100644 --- a/applications/external/mifare_nested/mifare_nested_worker.h +++ b/applications/external/mifare_nested/mifare_nested_worker.h @@ -66,6 +66,7 @@ typedef struct { uint32_t target_ks[2]; uint8_t parity[2][4]; bool skipped; + bool from_start; bool invalid; bool collected; bool hardnested; diff --git a/applications/external/mifare_nested/scenes/mifare_nested_scene_collecting.c b/applications/external/mifare_nested/scenes/mifare_nested_scene_collecting.c index 281210107..0e319bbcf 100644 --- a/applications/external/mifare_nested/scenes/mifare_nested_scene_collecting.c +++ b/applications/external/mifare_nested/scenes/mifare_nested_scene_collecting.c @@ -18,12 +18,15 @@ bool mifare_nested_collecting_worker_callback(MifareNestedWorkerEvent event, voi mifare_nested_blink_nonce_collection_start(mifare_nested); uint8_t collected = 0; + uint8_t skip = 0; NonceList_t* nonces = mifare_nested->nonces; for(uint8_t tries = 0; tries < nonces->tries; tries++) { for(uint8_t sector = 0; sector < nonces->sector_count; sector++) { for(uint8_t keyType = 0; keyType < 2; keyType++) { Nonces* info = nonces->nonces[sector][keyType][tries]; - if(info->collected) { + if(info->from_start) { + skip++; + } else if(info->collected) { collected++; } } @@ -37,7 +40,7 @@ bool mifare_nested_collecting_worker_callback(MifareNestedWorkerEvent event, voi model->calibrating = false; model->lost_tag = false; model->nonces_collected = collected; - model->keys_count = nonces->sector_count * nonces->tries * 2; + model->keys_count = (nonces->sector_count * nonces->tries * 2) - skip; }, true); } else if(event == MifareNestedWorkerEventNoTagDetected) { @@ -155,4 +158,4 @@ void mifare_nested_scene_collecting_on_exit(void* context) { mifare_nested_blink_stop(mifare_nested); popup_reset(mifare_nested->popup); widget_reset(mifare_nested->widget); -} +} \ No newline at end of file diff --git a/applications/external/minesweeper/minesweeper.c b/applications/external/minesweeper/minesweeper.c index a5a7d808b..77d054384 100644 --- a/applications/external/minesweeper/minesweeper.c +++ b/applications/external/minesweeper/minesweeper.c @@ -6,7 +6,6 @@ #include #include -#include #include "assets.h" diff --git a/applications/external/multi_converter/application.fam b/applications/external/multi_converter/application.fam index 3fb2557b4..6844c73b3 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=160, 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 9a765fd08..4d20930ba 100644 --- a/applications/external/multi_fuzzer/application.fam +++ b/applications/external/multi_fuzzer/application.fam @@ -12,7 +12,7 @@ App( ], stack_size=2 * 1024, fap_icon="ibutt_10px.png", - fap_category="Tools", + fap_category="iButton", fap_private_libs=[ Lib( name="worker", @@ -37,7 +37,7 @@ App( ], stack_size=2 * 1024, fap_icon="icons/rfid_10px.png", - fap_category="Tools", + fap_category="RFID", fap_private_libs=[ Lib( name="worker", diff --git a/applications/external/picopass/picopass_device.c b/applications/external/picopass/picopass_device.c index c4cb6aed0..3502f253e 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); @@ -78,6 +79,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; @@ -260,6 +262,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 96a586a93..48c306654 100644 --- a/applications/external/picopass/picopass_device.h +++ b/applications/external/picopass/picopass_device.h @@ -84,6 +84,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 815d10cbb..25ba7ebba 100644 --- a/applications/external/picopass/picopass_worker.c +++ b/applications/external/picopass/picopass_worker.c @@ -581,6 +581,7 @@ void picopass_worker_elite_dict_attack(PicopassWorker* picopass_worker) { if(err == ERR_NONE) { FURI_LOG_I(TAG, "Found key"); memcpy(pacs->key, key, RFAL_PICOPASS_BLOCK_LEN); + pacs->elite_kdf = elite; err = picopass_read_card(AA1); if(err != ERR_NONE) { FURI_LOG_E(TAG, "picopass_read_card error %d", err); @@ -758,7 +759,7 @@ void picopass_worker_write_key(PicopassWorker* picopass_worker) { uint8_t* oldKey = AA1[PICOPASS_SECURE_KD_BLOCK_INDEX].data; uint8_t newKey[RFAL_PICOPASS_BLOCK_LEN] = {0}; - loclass_iclass_calc_div_key(csn, pacs->key, newKey, 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 c9456468b..08adffed2 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, RFAL_PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCE) { scene_manager_set_scene_state( picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); memcpy(picopass->dev->dev_data.pacs.key, picopass_xice_key, RFAL_PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = true; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCL) { scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCL); memcpy(picopass->dev->dev_data.pacs.key, picopass_xicl_key, RFAL_PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCS) { scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCS); memcpy(picopass->dev->dev_data.pacs.key, picopass_xics_key, RFAL_PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } diff --git a/applications/external/pocsag_pager/helpers/radio_device_loader.c b/applications/external/pocsag_pager/helpers/radio_device_loader.c new file mode 100644 index 000000000..ce0920755 --- /dev/null +++ b/applications/external/pocsag_pager/helpers/radio_device_loader.c @@ -0,0 +1,66 @@ +#include "radio_device_loader.h" + +#include +#include + +static void radio_device_loader_power_on() { + uint8_t attempts = 0; + while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { + furi_hal_power_enable_otg(); + //CC1101 power-up time + furi_delay_ms(10); + } +} + +static void radio_device_loader_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + +bool radio_device_loader_is_connect_external(const char* name) { + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + radio_device_loader_power_on(); + } + + is_connect = subghz_devices_is_connect(subghz_devices_get_by_name(name)); + + if(!is_otg_enabled) { + radio_device_loader_power_off(); + } + return is_connect; +} + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type) { + const SubGhzDevice* radio_device; + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + radio_device_loader_power_on(); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(radio_device); + } else if(current_radio_device == NULL) { + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } else { + radio_device_loader_end(current_radio_device); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } + + return radio_device; +} + +bool radio_device_loader_is_external(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + return (radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)); +} + +void radio_device_loader_end(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + radio_device_loader_power_off(); + if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { + subghz_devices_end(radio_device); + } +} \ No newline at end of file diff --git a/applications/external/pocsag_pager/helpers/radio_device_loader.h b/applications/external/pocsag_pager/helpers/radio_device_loader.h new file mode 100644 index 000000000..bae4bacf2 --- /dev/null +++ b/applications/external/pocsag_pager/helpers/radio_device_loader.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type); + +bool radio_device_loader_is_external(const SubGhzDevice* radio_device); + +void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file diff --git a/applications/external/pocsag_pager/pocsag_pager_app.c b/applications/external/pocsag_pager/pocsag_pager_app.c index dc61c35f9..a381cf7fd 100644 --- a/applications/external/pocsag_pager/pocsag_pager_app.c +++ b/applications/external/pocsag_pager/pocsag_pager_app.c @@ -92,6 +92,16 @@ POCSAGPagerApp* pocsag_pager_app_alloc() { app->txrx->preset = malloc(sizeof(SubGhzRadioPreset)); app->txrx->preset->name = furi_string_alloc(); + furi_hal_power_suppress_charge_enter(); + + // Radio Devices init & load + subghz_devices_init(); + app->txrx->radio_device = + radio_device_loader_set(app->txrx->radio_device, SubGhzRadioDeviceTypeExternalCC1101); + + subghz_devices_reset(app->txrx->radio_device); + subghz_devices_idle(app->txrx->radio_device); + // Custom Presets load without using config file FlipperFormat* temp_fm_preset = flipper_format_string_alloc(); @@ -123,17 +133,6 @@ POCSAGPagerApp* pocsag_pager_app_alloc() { app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode); subghz_worker_set_context(app->txrx->worker, app->txrx->receiver); - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - - furi_hal_power_suppress_charge_enter(); - scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneStart); return app; @@ -142,13 +141,11 @@ POCSAGPagerApp* pocsag_pager_app_alloc() { void pocsag_pager_app_free(POCSAGPagerApp* app) { furi_assert(app); - //CC1101 off + // Radio Devices sleep & off pcsg_sleep(app); + radio_device_loader_end(app->txrx->radio_device); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); + subghz_devices_deinit(); // Submenu view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewSubmenu); diff --git a/applications/external/pocsag_pager/pocsag_pager_app_i.c b/applications/external/pocsag_pager/pocsag_pager_app_i.c index 85e2a4bcf..88c3a8c30 100644 --- a/applications/external/pocsag_pager/pocsag_pager_app_i.c +++ b/applications/external/pocsag_pager/pocsag_pager_app_i.c @@ -36,29 +36,34 @@ void pcsg_get_frequency_modulation( void pcsg_begin(POCSAGPagerApp* app, uint8_t* preset_data) { furi_assert(app); - UNUSED(preset_data); - furi_hal_subghz_reset(); - furi_hal_subghz_idle(); - furi_hal_subghz_load_custom_preset(preset_data); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + + subghz_devices_reset(app->txrx->radio_device); + subghz_devices_idle(app->txrx->radio_device); + subghz_devices_load_preset(app->txrx->radio_device, FuriHalSubGhzPresetCustom, preset_data); + + // furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); app->txrx->txrx_state = PCSGTxRxStateIDLE; } uint32_t pcsg_rx(POCSAGPagerApp* app, uint32_t frequency) { furi_assert(app); - if(!furi_hal_subghz_is_frequency_valid(frequency)) { + if(!subghz_devices_is_frequency_valid(app->txrx->radio_device, frequency)) { furi_crash("POCSAGPager: Incorrect RX frequency."); } furi_assert( app->txrx->txrx_state != PCSGTxRxStateRx && app->txrx->txrx_state != PCSGTxRxStateSleep); - furi_hal_subghz_idle(); - uint32_t value = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + subghz_devices_idle(app->txrx->radio_device); + uint32_t value = subghz_devices_set_frequency(app->txrx->radio_device, frequency); - furi_hal_subghz_start_async_rx(subghz_worker_rx_callback, app->txrx->worker); + // Not need. init in subghz_devices_start_async_tx + // furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + + subghz_devices_flush_rx(app->txrx->radio_device); + subghz_devices_set_rx(app->txrx->radio_device); + + subghz_devices_start_async_rx( + app->txrx->radio_device, subghz_worker_rx_callback, app->txrx->worker); subghz_worker_start(app->txrx->worker); app->txrx->txrx_state = PCSGTxRxStateRx; return value; @@ -67,7 +72,7 @@ uint32_t pcsg_rx(POCSAGPagerApp* app, uint32_t frequency) { void pcsg_idle(POCSAGPagerApp* app) { furi_assert(app); furi_assert(app->txrx->txrx_state != PCSGTxRxStateSleep); - furi_hal_subghz_idle(); + subghz_devices_idle(app->txrx->radio_device); app->txrx->txrx_state = PCSGTxRxStateIDLE; } @@ -76,15 +81,15 @@ void pcsg_rx_end(POCSAGPagerApp* app) { furi_assert(app->txrx->txrx_state == PCSGTxRxStateRx); if(subghz_worker_is_running(app->txrx->worker)) { subghz_worker_stop(app->txrx->worker); - furi_hal_subghz_stop_async_rx(); + subghz_devices_stop_async_rx(app->txrx->radio_device); } - furi_hal_subghz_idle(); + subghz_devices_idle(app->txrx->radio_device); app->txrx->txrx_state = PCSGTxRxStateIDLE; } void pcsg_sleep(POCSAGPagerApp* app) { furi_assert(app); - furi_hal_subghz_sleep(); + subghz_devices_sleep(app->txrx->radio_device); app->txrx->txrx_state = PCSGTxRxStateSleep; } @@ -110,7 +115,7 @@ void pcsg_hopper_update(POCSAGPagerApp* app) { float rssi = -127.0f; if(app->txrx->hopper_state != PCSGHopperStateRSSITimeOut) { // See RSSI Calculation timings in CC1101 17.3 RSSI - rssi = furi_hal_subghz_get_rssi(); + rssi = subghz_devices_get_rssi(app->txrx->radio_device); // Stay if RSSI is high enough if(rssi > -90.0f) { diff --git a/applications/external/pocsag_pager/pocsag_pager_app_i.h b/applications/external/pocsag_pager/pocsag_pager_app_i.h index 8a0426dc5..c31e5ae1a 100644 --- a/applications/external/pocsag_pager/pocsag_pager_app_i.h +++ b/applications/external/pocsag_pager/pocsag_pager_app_i.h @@ -1,6 +1,7 @@ #pragma once #include "helpers/pocsag_pager_types.h" +#include "helpers/radio_device_loader.h" #include "scenes/pocsag_pager_scene.h" #include @@ -19,6 +20,7 @@ #include #include #include +#include typedef struct POCSAGPagerApp POCSAGPagerApp; @@ -35,6 +37,8 @@ struct POCSAGPagerTxRx { uint8_t hopper_timeout; uint8_t hopper_idx_frequency; PCSGRxKeyState rx_key_state; + + const SubGhzDevice* radio_device; }; typedef struct POCSAGPagerTxRx POCSAGPagerTxRx; diff --git a/applications/external/pocsag_pager/scenes/pocsag_pager_receiver.c b/applications/external/pocsag_pager/scenes/pocsag_pager_receiver.c index 60dca01c9..58af9a64a 100644 --- a/applications/external/pocsag_pager/scenes/pocsag_pager_receiver.c +++ b/applications/external/pocsag_pager/scenes/pocsag_pager_receiver.c @@ -112,6 +112,8 @@ void pocsag_pager_scene_receiver_on_enter(void* context) { } pcsg_view_receiver_set_lock(app->pcsg_receiver, app->lock); + pcsg_view_receiver_set_ext_module_state( + app->pcsg_receiver, radio_device_loader_is_external(app->txrx->radio_device)); //Load history to receiver pcsg_view_receiver_exit(app->pcsg_receiver); @@ -136,6 +138,7 @@ void pocsag_pager_scene_receiver_on_enter(void* context) { } if((app->txrx->txrx_state == PCSGTxRxStateIDLE) || (app->txrx->txrx_state == PCSGTxRxStateSleep)) { + // Start RX pcsg_begin( app, subghz_setting_get_preset_data_by_name( @@ -157,7 +160,7 @@ bool pocsag_pager_scene_receiver_on_event(void* context, SceneManagerEvent event // Stop CC1101 Rx if(app->txrx->txrx_state == PCSGTxRxStateRx) { pcsg_rx_end(app); - pcsg_sleep(app); + pcsg_idle(app); } app->txrx->hopper_state = PCSGHopperStateOFF; app->txrx->idx_menu_chosen = 0; @@ -196,7 +199,7 @@ bool pocsag_pager_scene_receiver_on_event(void* context, SceneManagerEvent event pocsag_pager_scene_receiver_update_statusbar(app); } // Get current RSSI - float rssi = furi_hal_subghz_get_rssi(); + float rssi = subghz_devices_get_rssi(app->txrx->radio_device); pcsg_receiver_rssi(app->pcsg_receiver, rssi); if(app->txrx->txrx_state == PCSGTxRxStateRx) { diff --git a/applications/external/pocsag_pager/views/pocsag_pager_receiver.c b/applications/external/pocsag_pager/views/pocsag_pager_receiver.c index fd4461cee..755102682 100644 --- a/applications/external/pocsag_pager/views/pocsag_pager_receiver.c +++ b/applications/external/pocsag_pager/views/pocsag_pager_receiver.c @@ -62,6 +62,7 @@ typedef struct { uint16_t history_item; PCSGReceiverBarShow bar_show; uint8_t u_rssi; + bool ext_module; } PCSGReceiverModel; void pcsg_receiver_rssi(PCSGReceiver* instance, float rssi) { @@ -99,6 +100,12 @@ void pcsg_view_receiver_set_lock(PCSGReceiver* pcsg_receiver, PCSGLock lock) { } } +void pcsg_view_receiver_set_ext_module_state(PCSGReceiver* pcsg_receiver, bool is_external) { + furi_assert(pcsg_receiver); + with_view_model( + pcsg_receiver->view, PCSGReceiverModel * model, { model->ext_module = is_external; }, true); +} + void pcsg_view_receiver_set_callback( PCSGReceiver* pcsg_receiver, PCSGReceiverCallback callback, @@ -208,8 +215,6 @@ void pcsg_view_receiver_draw(Canvas* canvas, PCSGReceiverModel* model) { FuriString* str_buff; str_buff = furi_string_alloc(); - bool ext_module = furi_hal_subghz_get_radio_type(); - PCSGReceiverMenuItem* item_menu; for(size_t i = 0; i < MIN(model->history_item, MENU_ITEMS); ++i) { @@ -235,11 +240,11 @@ void pcsg_view_receiver_draw(Canvas* canvas, PCSGReceiverModel* model) { canvas_set_color(canvas, ColorBlack); if(model->history_item == 0) { - canvas_draw_icon(canvas, 0, 0, ext_module ? &I_Fishing_123x52 : &I_Scanning_123x52); + canvas_draw_icon(canvas, 0, 0, model->ext_module ? &I_Fishing_123x52 : &I_Scanning_123x52); canvas_set_font(canvas, FontPrimary); canvas_draw_str(canvas, 63, 46, "Scanning..."); canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 44, 10, ext_module ? "Ext" : "Int"); + canvas_draw_str(canvas, 44, 10, model->ext_module ? "Ext" : "Int"); } // Draw RSSI diff --git a/applications/external/pocsag_pager/views/pocsag_pager_receiver.h b/applications/external/pocsag_pager/views/pocsag_pager_receiver.h index a13f5cdc7..87900748f 100644 --- a/applications/external/pocsag_pager/views/pocsag_pager_receiver.h +++ b/applications/external/pocsag_pager/views/pocsag_pager_receiver.h @@ -12,6 +12,8 @@ void pcsg_receiver_rssi(PCSGReceiver* instance, float rssi); void pcsg_view_receiver_set_lock(PCSGReceiver* pcsg_receiver, PCSGLock keyboard); +void pcsg_view_receiver_set_ext_module_state(PCSGReceiver* pcsg_receiver, bool is_external); + void pcsg_view_receiver_set_callback( PCSGReceiver* pcsg_receiver, PCSGReceiverCallback callback, diff --git a/applications/external/protoview/app.c b/applications/external/protoview/app.c index 0f72fb927..656c35373 100644 --- a/applications/external/protoview/app.c +++ b/applications/external/protoview/app.c @@ -119,6 +119,8 @@ static void app_switch_view(ProtoViewApp* app, ProtoViewCurrentView switchto) { /* Allocate the application state and initialize a number of stuff. * This is called in the entry point to create the application state. */ ProtoViewApp* protoview_app_alloc() { + furi_hal_power_suppress_charge_enter(); + ProtoViewApp* app = malloc(sizeof(ProtoViewApp)); // Init shared data structures @@ -168,16 +170,14 @@ ProtoViewApp* protoview_app_alloc() { app->frequency = subghz_setting_get_default_frequency(app->setting); app->modulation = 0; /* Defaults to ProtoViewModulations[0]. */ - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } + // Init & set radio_device + subghz_devices_init(); + app->radio_device = + radio_device_loader_set(app->radio_device, SubGhzRadioDeviceTypeExternalCC1101); + + subghz_devices_reset(app->radio_device); + subghz_devices_idle(app->radio_device); - furi_hal_power_suppress_charge_enter(); app->running = 1; return app; @@ -189,13 +189,10 @@ ProtoViewApp* protoview_app_alloc() { void protoview_app_free(ProtoViewApp* app) { furi_assert(app); - // Put CC1101 on sleep, this also restores charging. - radio_sleep(app); + subghz_devices_sleep(app->radio_device); + radio_device_loader_end(app->radio_device); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); + subghz_devices_deinit(); // View related. view_port_enabled_set(app->view_port, false); diff --git a/applications/external/protoview/app.h b/applications/external/protoview/app.h index 624c118e2..5fb0adf34 100644 --- a/applications/external/protoview/app.h +++ b/applications/external/protoview/app.h @@ -19,6 +19,7 @@ #include #include #include "raw_samples.h" +#include "helpers/radio_device_loader.h" #define TAG "ProtoView" #define PROTOVIEW_RAW_VIEW_DEFAULT_SCALE 100 // 100us is 1 pixel by default @@ -132,6 +133,8 @@ struct ProtoViewApp { ProtoViewTxRx* txrx; /* Radio state. */ SubGhzSetting* setting; /* A list of valid frequencies. */ + const SubGhzDevice* radio_device; + /* Generic app state. */ int running; /* Once false exists the app. */ uint32_t signal_bestlen; /* Longest coherent signal observed so far. */ diff --git a/applications/external/protoview/app_subghz.c b/applications/external/protoview/app_subghz.c index dcb6d492b..204dcba0d 100644 --- a/applications/external/protoview/app_subghz.c +++ b/applications/external/protoview/app_subghz.c @@ -37,22 +37,23 @@ ProtoViewModulation ProtoViewModulations[] = { * subghz system and put it into idle state. */ void radio_begin(ProtoViewApp* app) { furi_assert(app); - furi_hal_subghz_reset(); - furi_hal_subghz_idle(); - - /* Power circuits are noisy. Suppressing the charge while we use - * ProtoView will improve the RF performances. */ - furi_hal_power_suppress_charge_enter(); + subghz_devices_reset(app->radio_device); + subghz_devices_idle(app->radio_device); /* The CC1101 preset can be either one of the standard presets, if * the modulation "custom" field is NULL, or a custom preset we * defined in custom_presets.h. */ if(ProtoViewModulations[app->modulation].custom == NULL) { - furi_hal_subghz_load_preset(ProtoViewModulations[app->modulation].preset); + subghz_devices_load_preset( + app->radio_device, ProtoViewModulations[app->modulation].preset, NULL); } else { - furi_hal_subghz_load_custom_preset(ProtoViewModulations[app->modulation].custom); + subghz_devices_load_preset( + app->radio_device, + FuriHalSubGhzPresetCustom, + ProtoViewModulations[app->modulation].custom); } - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init( + subghz_devices_get_data_gpio(app->radio_device), GpioModeInput, GpioPullNo, GpioSpeedLow); app->txrx->txrx_state = TxRxStateIDLE; } @@ -71,21 +72,28 @@ void protoview_rx_callback(bool level, uint32_t duration, void* context) { /* Setup the CC1101 to start receiving using a background worker. */ uint32_t radio_rx(ProtoViewApp* app) { furi_assert(app); - if(!furi_hal_subghz_is_frequency_valid(app->frequency)) { + + if(!subghz_devices_is_frequency_valid(app->radio_device, app->frequency)) { furi_crash(TAG " Incorrect RX frequency."); } if(app->txrx->txrx_state == TxRxStateRx) return app->frequency; - furi_hal_subghz_idle(); /* Put it into idle state in case it is sleeping. */ - uint32_t value = furi_hal_subghz_set_frequency_and_path(app->frequency); + subghz_devices_idle(app->radio_device); /* Put it into idle state in case it is sleeping. */ + uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency); FURI_LOG_E(TAG, "Switched to frequency: %lu", value); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + + subghz_devices_flush_rx(app->radio_device); + subghz_devices_set_rx(app->radio_device); + if(!app->txrx->debug_timer_sampling) { - furi_hal_subghz_start_async_rx(protoview_rx_callback, NULL); + subghz_devices_start_async_rx(app->radio_device, protoview_rx_callback, NULL); } else { + furi_hal_gpio_init( + subghz_devices_get_data_gpio(app->radio_device), + GpioModeInput, + GpioPullNo, + GpioSpeedLow); raw_sampling_worker_start(app); } app->txrx->txrx_state = TxRxStateRx; @@ -98,12 +106,12 @@ void radio_rx_end(ProtoViewApp* app) { if(app->txrx->txrx_state == TxRxStateRx) { if(!app->txrx->debug_timer_sampling) { - furi_hal_subghz_stop_async_rx(); + subghz_devices_stop_async_rx(app->radio_device); } else { raw_sampling_worker_stop(app); } } - furi_hal_subghz_idle(); + subghz_devices_idle(app->radio_device); app->txrx->txrx_state = TxRxStateIDLE; } @@ -115,9 +123,8 @@ void radio_sleep(ProtoViewApp* app) { * chip into sleep. */ radio_rx_end(app); } - furi_hal_subghz_sleep(); + subghz_devices_sleep(app->radio_device); app->txrx->txrx_state = TxRxStateSleep; - furi_hal_power_suppress_charge_exit(); } /* =============================== Transmission ============================= */ @@ -131,17 +138,14 @@ void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder if(oldstate == TxRxStateRx) radio_rx_end(app); radio_begin(app); - furi_hal_subghz_idle(); - uint32_t value = furi_hal_subghz_set_frequency_and_path(app->frequency); + subghz_devices_idle(app->radio_device); + uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency); FURI_LOG_E(TAG, "Switched to frequency: %lu", value); - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, false); - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); - furi_hal_subghz_start_async_tx(data_feeder, ctx); - while(!furi_hal_subghz_is_async_tx_complete()) furi_delay_ms(10); - furi_hal_subghz_stop_async_tx(); - furi_hal_subghz_idle(); + subghz_devices_start_async_tx(app->radio_device, data_feeder, ctx); + while(!subghz_devices_is_async_complete_tx(app->radio_device)) furi_delay_ms(10); + subghz_devices_stop_async_tx(app->radio_device); + subghz_devices_idle(app->radio_device); radio_begin(app); if(oldstate == TxRxStateRx) radio_rx(app); @@ -157,7 +161,7 @@ void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder void protoview_timer_isr(void* ctx) { ProtoViewApp* app = ctx; - bool level = furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin); + bool level = furi_hal_gpio_read(subghz_devices_get_data_gpio(app->radio_device)); if(app->txrx->last_g0_value != level) { uint32_t now = DWT->CYCCNT; uint32_t dur = now - app->txrx->last_g0_change_time; diff --git a/applications/external/protoview/helpers/radio_device_loader.c b/applications/external/protoview/helpers/radio_device_loader.c new file mode 100644 index 000000000..d2cffde58 --- /dev/null +++ b/applications/external/protoview/helpers/radio_device_loader.c @@ -0,0 +1,64 @@ +#include "radio_device_loader.h" + +#include +#include + +static void radio_device_loader_power_on() { + uint8_t attempts = 0; + while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { + furi_hal_power_enable_otg(); + //CC1101 power-up time + furi_delay_ms(10); + } +} + +static void radio_device_loader_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + +bool radio_device_loader_is_connect_external(const char* name) { + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + radio_device_loader_power_on(); + } + + const SubGhzDevice* device = subghz_devices_get_by_name(name); + if(device) { + is_connect = subghz_devices_is_connect(device); + } + + if(!is_otg_enabled) { + radio_device_loader_power_off(); + } + return is_connect; +} + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type) { + const SubGhzDevice* radio_device; + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + radio_device_loader_power_on(); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(radio_device); + } else if(current_radio_device == NULL) { + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } else { + radio_device_loader_end(current_radio_device); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } + + return radio_device; +} + +void radio_device_loader_end(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + radio_device_loader_power_off(); + if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { + subghz_devices_end(radio_device); + } +} \ No newline at end of file diff --git a/applications/external/protoview/helpers/radio_device_loader.h b/applications/external/protoview/helpers/radio_device_loader.h new file mode 100644 index 000000000..bee4e2c36 --- /dev/null +++ b/applications/external/protoview/helpers/radio_device_loader.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type); + +void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file diff --git a/applications/external/protoview/view_direct_sampling.c b/applications/external/protoview/view_direct_sampling.c index 84486dc51..dc812901e 100644 --- a/applications/external/protoview/view_direct_sampling.c +++ b/applications/external/protoview/view_direct_sampling.c @@ -88,14 +88,18 @@ void view_enter_direct_sampling(ProtoViewApp* app) { privdata->show_usage_info = true; if(app->txrx->txrx_state == TxRxStateRx && !app->txrx->debug_timer_sampling) { - furi_hal_subghz_stop_async_rx(); + subghz_devices_stop_async_rx(app->radio_device); /* To read data asynchronously directly from the view, we need * to put the CC1101 back into reception mode (the previous call * to stop the async RX will put it into idle) and configure the * G0 pin for reading. */ - furi_hal_subghz_rx(); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + subghz_devices_set_rx(app->radio_device); + furi_hal_gpio_init( + subghz_devices_get_data_gpio(app->radio_device), + GpioModeInput, + GpioPullNo, + GpioSpeedLow); } else { raw_sampling_worker_stop(app); } @@ -114,8 +118,13 @@ void view_exit_direct_sampling(ProtoViewApp* app) { /* Restart normal data feeding. */ if(app->txrx->txrx_state == TxRxStateRx && !app->txrx->debug_timer_sampling) { - furi_hal_subghz_start_async_rx(protoview_rx_callback, NULL); + subghz_devices_start_async_rx(app->radio_device, protoview_rx_callback, NULL); } else { + furi_hal_gpio_init( + subghz_devices_get_data_gpio(app->radio_device), + GpioModeInput, + GpioPullNo, + GpioSpeedLow); raw_sampling_worker_start(app); } } @@ -127,7 +136,7 @@ static void ds_timer_isr(void* ctx) { DirectSamplingViewPrivData* privdata = app->view_privdata; if(app->direct_sampling_enabled) { - bool level = furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin); + bool level = furi_hal_gpio_read(subghz_devices_get_data_gpio(app->radio_device)); bitmap_set(privdata->captured, CAPTURED_BITMAP_BYTES, privdata->captured_idx, level); privdata->captured_idx = (privdata->captured_idx + 1) % CAPTURED_BITMAP_BITS; } diff --git a/applications/external/spectrum_analyzer/helpers/radio_device_loader.c b/applications/external/spectrum_analyzer/helpers/radio_device_loader.c new file mode 100644 index 000000000..d2cffde58 --- /dev/null +++ b/applications/external/spectrum_analyzer/helpers/radio_device_loader.c @@ -0,0 +1,64 @@ +#include "radio_device_loader.h" + +#include +#include + +static void radio_device_loader_power_on() { + uint8_t attempts = 0; + while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { + furi_hal_power_enable_otg(); + //CC1101 power-up time + furi_delay_ms(10); + } +} + +static void radio_device_loader_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + +bool radio_device_loader_is_connect_external(const char* name) { + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + radio_device_loader_power_on(); + } + + const SubGhzDevice* device = subghz_devices_get_by_name(name); + if(device) { + is_connect = subghz_devices_is_connect(device); + } + + if(!is_otg_enabled) { + radio_device_loader_power_off(); + } + return is_connect; +} + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type) { + const SubGhzDevice* radio_device; + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + radio_device_loader_power_on(); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(radio_device); + } else if(current_radio_device == NULL) { + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } else { + radio_device_loader_end(current_radio_device); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } + + return radio_device; +} + +void radio_device_loader_end(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + radio_device_loader_power_off(); + if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { + subghz_devices_end(radio_device); + } +} \ No newline at end of file diff --git a/applications/external/spectrum_analyzer/helpers/radio_device_loader.h b/applications/external/spectrum_analyzer/helpers/radio_device_loader.h new file mode 100644 index 000000000..bee4e2c36 --- /dev/null +++ b/applications/external/spectrum_analyzer/helpers/radio_device_loader.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type); + +void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file diff --git a/applications/external/spectrum_analyzer/spectrum_analyzer.c b/applications/external/spectrum_analyzer/spectrum_analyzer.c index be3e043d9..fd31a6935 100644 --- a/applications/external/spectrum_analyzer/spectrum_analyzer.c +++ b/applications/external/spectrum_analyzer/spectrum_analyzer.c @@ -390,14 +390,6 @@ void spectrum_analyzer_free(SpectrumAnalyzer* instance) { free(instance->model); free(instance); - - furi_hal_subghz_idle(); - furi_hal_subghz_sleep(); - - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); } int32_t spectrum_analyzer_app(void* p) { @@ -407,21 +399,18 @@ int32_t spectrum_analyzer_app(void* p) { SpectrumAnalyzer* spectrum_analyzer = spectrum_analyzer_alloc(); InputEvent input; - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - furi_hal_power_suppress_charge_enter(); FURI_LOG_D("Spectrum", "Main Loop - Starting worker"); furi_delay_ms(50); spectrum_analyzer_worker_start(spectrum_analyzer->worker); + spectrum_analyzer_calculate_frequencies(spectrum_analyzer->model); + spectrum_analyzer_worker_set_frequencies( + spectrum_analyzer->worker, + spectrum_analyzer->model->channel0_frequency, + spectrum_analyzer->model->spacing, + spectrum_analyzer->model->width); FURI_LOG_D("Spectrum", "Main Loop - Wait on queue"); furi_delay_ms(50); diff --git a/applications/external/spectrum_analyzer/spectrum_analyzer_worker.c b/applications/external/spectrum_analyzer/spectrum_analyzer_worker.c index e670d2808..5b35a47a2 100644 --- a/applications/external/spectrum_analyzer/spectrum_analyzer_worker.c +++ b/applications/external/spectrum_analyzer/spectrum_analyzer_worker.c @@ -4,6 +4,8 @@ #include #include +#include "helpers/radio_device_loader.h" + #include struct SpectrumAnalyzerWorker { @@ -13,6 +15,8 @@ struct SpectrumAnalyzerWorker { SpectrumAnalyzerWorkerCallback callback; void* callback_context; + const SubGhzDevice* radio_device; + uint32_t channel0_frequency; uint32_t spacing; uint8_t width; @@ -44,7 +48,9 @@ void spectrum_analyzer_worker_set_filter(SpectrumAnalyzerWorker* instance) { filter_config[0][1] = 0x6C; /* 196 kHz / .8 = 245 kHz --> 270 kHz */ break; } - furi_hal_subghz_load_registers((uint8_t*)filter_config); + + UNUSED(filter_config); + // furi_hal_subghz_load_registers((uint8_t*)filter_config); } static int32_t spectrum_analyzer_worker_thread(void* context) { @@ -54,32 +60,53 @@ static int32_t spectrum_analyzer_worker_thread(void* context) { FURI_LOG_D("SpectrumWorker", "spectrum_analyzer_worker_thread: Start"); // Start CC1101 - furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); - furi_hal_subghz_set_frequency(433920000); - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + subghz_devices_reset(instance->radio_device); + subghz_devices_load_preset(instance->radio_device, FuriHalSubGhzPresetOok650Async, NULL); + subghz_devices_set_frequency(instance->radio_device, 433920000); + subghz_devices_flush_rx(instance->radio_device); + subghz_devices_set_rx(instance->radio_device); - static const uint8_t radio_config[][2] = { - {CC1101_FSCTRL1, 0x12}, - {CC1101_FSCTRL0, 0x00}, + const uint8_t radio_config[] = { - {CC1101_AGCCTRL2, 0xC0}, + CC1101_FSCTRL0, + 0x00, + CC1101_FSCTRL1, + 0x12, + + CC1101_AGCCTRL2, + 0xC0, + + CC1101_MDMCFG4, + 0x6C, + CC1101_TEST2, + 0x88, + CC1101_TEST1, + 0x31, + CC1101_TEST0, + 0x09, - {CC1101_MDMCFG4, 0x6C}, - {CC1101_TEST2, 0x88}, - {CC1101_TEST1, 0x31}, - {CC1101_TEST0, 0x09}, /* End */ - {0, 0}, + 0, + 0, + + // ook_async_patable + 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, }; while(instance->should_work) { furi_delay_ms(50); // FURI_LOG_T("SpectrumWorker", "spectrum_analyzer_worker_thread: Worker Loop"); - furi_hal_subghz_idle(); - furi_hal_subghz_load_registers((uint8_t*)radio_config); + subghz_devices_idle(instance->radio_device); + subghz_devices_load_preset( + instance->radio_device, FuriHalSubGhzPresetCustom, (uint8_t*)radio_config); // TODO: Check filter! // spectrum_analyzer_worker_set_filter(instance); @@ -90,9 +117,15 @@ static int32_t spectrum_analyzer_worker_thread(void* context) { for(uint8_t ch_offset = 0, chunk = 0; ch_offset < CHUNK_SIZE; ++chunk >= NUM_CHUNKS && ++ch_offset && (chunk = 0)) { uint8_t ch = chunk * CHUNK_SIZE + ch_offset; - furi_hal_subghz_set_frequency(instance->channel0_frequency + (ch * instance->spacing)); - furi_hal_subghz_rx(); + if(subghz_devices_is_frequency_valid( + instance->radio_device, + instance->channel0_frequency + (ch * instance->spacing))) + subghz_devices_set_frequency( + instance->radio_device, + instance->channel0_frequency + (ch * instance->spacing)); + + subghz_devices_set_rx(instance->radio_device); furi_delay_ms(3); // dec dBm @@ -100,7 +133,7 @@ static int32_t spectrum_analyzer_worker_thread(void* context) { //max_ss = 0 -> -74.0 //max_ss = 255 -> -74.5 //max_ss = 128 -> -138.0 - instance->channel_ss[ch] = (furi_hal_subghz_get_rssi() + 138) * 2; + instance->channel_ss[ch] = (subghz_devices_get_rssi(instance->radio_device) + 138) * 2; if(instance->channel_ss[ch] > instance->max_rssi_dec) { instance->max_rssi_dec = instance->channel_ss[ch]; @@ -108,7 +141,7 @@ static int32_t spectrum_analyzer_worker_thread(void* context) { instance->max_rssi_channel = ch; } - furi_hal_subghz_idle(); + subghz_devices_idle(instance->radio_device); } // FURI_LOG_T("SpectrumWorker", "channel_ss[0]: %u", instance->channel_ss[0]); @@ -138,6 +171,11 @@ SpectrumAnalyzerWorker* spectrum_analyzer_worker_alloc() { furi_thread_set_context(instance->thread, instance); furi_thread_set_callback(instance->thread, spectrum_analyzer_worker_thread); + subghz_devices_init(); + + instance->radio_device = + radio_device_loader_set(instance->radio_device, SubGhzRadioDeviceTypeExternalCC1101); + FURI_LOG_D("Spectrum", "spectrum_analyzer_worker_alloc: End"); return instance; @@ -147,6 +185,12 @@ void spectrum_analyzer_worker_free(SpectrumAnalyzerWorker* instance) { FURI_LOG_D("Spectrum", "spectrum_analyzer_worker_free"); furi_assert(instance); furi_thread_free(instance->thread); + + subghz_devices_sleep(instance->radio_device); + radio_device_loader_end(instance->radio_device); + + subghz_devices_deinit(); + free(instance); } diff --git a/applications/external/subghz_playlist/playlist.c b/applications/external/subghz_playlist/playlist.c index 12191dc96..dc7b7a45b 100644 --- a/applications/external/subghz_playlist/playlist.c +++ b/applications/external/subghz_playlist/playlist.c @@ -10,7 +10,8 @@ #include #include -#include + +#include "helpers/radio_device_loader.h" #include "flipper_format_stream.h" #include "flipper_format_stream_i.h" @@ -57,6 +58,7 @@ typedef struct { DisplayMeta* meta; FuriString* file_path; // path to the playlist file + const SubGhzDevice* radio_device; bool ctl_request_exit; // can be set to true if the worker should exit bool ctl_pause; // can be set to true if the worker should pause @@ -134,7 +136,9 @@ static int playlist_worker_process( FURI_LOG_W(TAG, " (TX) Missing Frequency, defaulting to 433.92MHz"); frequency = 433920000; } - if(!furi_hal_subghz_is_tx_allowed(frequency)) { + if(!subghz_devices_is_frequency_valid(worker->radio_device, frequency)) { + FURI_LOG_E( + TAG, " (TX) The SubGhz device used does not support the frequency %lu", frequency); return -2; } @@ -151,12 +155,13 @@ static int playlist_worker_process( } if(!furi_string_cmp_str(protocol, "RAW")) { - subghz_protocol_raw_gen_fff_data(fff_data, path); + subghz_protocol_raw_gen_fff_data( + fff_data, path, subghz_devices_get_name(worker->radio_device)); } else { stream_copy_full( flipper_format_get_raw_stream(fff_file), flipper_format_get_raw_stream(fff_data)); } - flipper_format_free(fff_file); + flipper_format_file_close(fff_file); // (try to) send file SubGhzEnvironment* environment = subghz_environment_alloc(); @@ -166,16 +171,23 @@ static int playlist_worker_process( subghz_transmitter_deserialize(transmitter, fff_data); - furi_hal_subghz_reset(); - furi_hal_subghz_load_preset(str_to_preset(preset)); - - frequency = furi_hal_subghz_set_frequency_and_path(frequency); + subghz_devices_load_preset(worker->radio_device, str_to_preset(preset), NULL); + // there is no check for a custom preset + frequency = subghz_devices_set_frequency(worker->radio_device, frequency); + // Set device to TX and check frequency is alowed to TX + if(!subghz_devices_set_tx(worker->radio_device)) { + FURI_LOG_E( + TAG, + " (TX) The SubGhz device used does not support the frequency for transmitеing, %lu", + frequency); + return -5; + } FURI_LOG_D(TAG, " (TX) Start sending ..."); int status = 0; - furi_hal_subghz_start_async_tx(subghz_transmitter_yield, transmitter); - while(!furi_hal_subghz_is_async_tx_complete()) { + subghz_devices_start_async_tx(worker->radio_device, subghz_transmitter_yield, transmitter); + while(!subghz_devices_is_async_complete_tx(worker->radio_device)) { if(worker->ctl_request_exit) { FURI_LOG_D(TAG, " (TX) Requested to exit. Cancelling sending..."); status = 2; @@ -203,8 +215,8 @@ static int playlist_worker_process( FURI_LOG_D(TAG, " (TX) Done sending."); - furi_hal_subghz_stop_async_tx(); - furi_hal_subghz_sleep(); + subghz_devices_stop_async_tx(worker->radio_device); + subghz_devices_idle(worker->radio_device); subghz_transmitter_free(transmitter); @@ -286,6 +298,7 @@ static bool playlist_worker_play_playlist_once( // if there was an error, fff_file is not already freed if(status < 0) { + flipper_format_file_close(fff_file); flipper_format_free(fff_file); } @@ -436,6 +449,14 @@ PlaylistWorker* playlist_worker_alloc(DisplayMeta* meta) { instance->file_path = furi_string_alloc(); + subghz_devices_init(); + + instance->radio_device = + radio_device_loader_set(instance->radio_device, SubGhzRadioDeviceTypeExternalCC1101); + + subghz_devices_reset(instance->radio_device); + subghz_devices_idle(instance->radio_device); + return instance; } @@ -443,6 +464,12 @@ void playlist_worker_free(PlaylistWorker* instance) { furi_assert(instance); furi_thread_free(instance->thread); furi_string_free(instance->file_path); + + subghz_devices_sleep(instance->radio_device); + radio_device_loader_end(instance->radio_device); + + subghz_devices_deinit(); + free(instance); } @@ -711,15 +738,6 @@ int32_t playlist_app(char* p) { Playlist* app = playlist_alloc(meta); meta->view_port = app->view_port; - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - furi_hal_power_suppress_charge_enter(); // select playlist file @@ -810,10 +828,6 @@ int32_t playlist_app(char* p) { exit_cleanup: furi_hal_power_suppress_charge_exit(); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); if(app->worker != NULL) { if(playlist_worker_running(app->worker)) { diff --git a/applications/external/subghz_playlist/radio_device_loader.c b/applications/external/subghz_playlist/radio_device_loader.c new file mode 100644 index 000000000..d2cffde58 --- /dev/null +++ b/applications/external/subghz_playlist/radio_device_loader.c @@ -0,0 +1,64 @@ +#include "radio_device_loader.h" + +#include +#include + +static void radio_device_loader_power_on() { + uint8_t attempts = 0; + while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { + furi_hal_power_enable_otg(); + //CC1101 power-up time + furi_delay_ms(10); + } +} + +static void radio_device_loader_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + +bool radio_device_loader_is_connect_external(const char* name) { + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + radio_device_loader_power_on(); + } + + const SubGhzDevice* device = subghz_devices_get_by_name(name); + if(device) { + is_connect = subghz_devices_is_connect(device); + } + + if(!is_otg_enabled) { + radio_device_loader_power_off(); + } + return is_connect; +} + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type) { + const SubGhzDevice* radio_device; + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + radio_device_loader_power_on(); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(radio_device); + } else if(current_radio_device == NULL) { + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } else { + radio_device_loader_end(current_radio_device); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } + + return radio_device; +} + +void radio_device_loader_end(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + radio_device_loader_power_off(); + if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { + subghz_devices_end(radio_device); + } +} \ No newline at end of file diff --git a/applications/external/subghz_playlist/radio_device_loader.h b/applications/external/subghz_playlist/radio_device_loader.h new file mode 100644 index 000000000..bee4e2c36 --- /dev/null +++ b/applications/external/subghz_playlist/radio_device_loader.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type); + +void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file diff --git a/applications/external/subghz_remote/application.fam b/applications/external/subghz_remote/application.fam index 14c7f14ec..4af6a1275 100644 --- a/applications/external/subghz_remote/application.fam +++ b/applications/external/subghz_remote/application.fam @@ -1,6 +1,7 @@ App( appid="subghz_remote", name="Sub-GHz Remote", +<<<<<<< HEAD:applications/external/subghz_remote/application.fam apptype=FlipperAppType.EXTERNAL, entry_point="subghz_remote_app", cdefines=[ @@ -15,4 +16,14 @@ App( order=11, fap_icon="subrem_10px.png", fap_category="Sub-GHz", +======= + apptype=FlipperAppType.MENUEXTERNAL, + entry_point="subghz_remote_app", + icon="A_SubGHzRemote_14", + stack_size=2 * 1024, + order=11, + fap_libs=["assets",], + fap_icon="icon.png", + fap_category="Sub-Ghz", +>>>>>>> ea357b8eafe91c3a07cb89c3b90d03b78e2633ff:applications/main/subghz_remote/application.fam ) diff --git a/applications/external/subghz_remote/helpers/subrem_presets.c b/applications/external/subghz_remote/helpers/subrem_presets.c index e5823b721..75ced8e00 100644 --- a/applications/external/subghz_remote/helpers/subrem_presets.c +++ b/applications/external/subghz_remote/helpers/subrem_presets.c @@ -84,8 +84,8 @@ SubRemLoadSubState subrem_sub_preset_load( if(!flipper_format_read_uint32(fff_data_file, "Frequency", &temp_data32, 1)) { FURI_LOG_W(TAG, "Cannot read frequency. Set default frequency"); sub_preset->freq_preset.frequency = subghz_setting_get_default_frequency(setting); - } else if(!furi_hal_subghz_is_tx_allowed(temp_data32)) { - FURI_LOG_E(TAG, "This frequency can only be used for RX"); + } else if(!subghz_txrx_radio_device_is_frequecy_valid(txrx, temp_data32)) { + FURI_LOG_E(TAG, "Frequency not supported on chosen radio module"); break; } sub_preset->freq_preset.frequency = temp_data32; @@ -124,7 +124,9 @@ SubRemLoadSubState subrem_sub_preset_load( if(!strcmp(furi_string_get_cstr(temp_str), "RAW")) { //if RAW subghz_protocol_raw_gen_fff_data( - fff_data, furi_string_get_cstr(sub_preset->file_path)); + fff_data, + furi_string_get_cstr(sub_preset->file_path), + subghz_txrx_radio_device_get_name(txrx)); } else { stream_copy_full( flipper_format_get_raw_stream(fff_data_file), diff --git a/applications/external/subghz_remote/helpers/txrx/subghz_txrx.c b/applications/external/subghz_remote/helpers/txrx/subghz_txrx.c new file mode 100644 index 000000000..8def9cf01 --- /dev/null +++ b/applications/external/subghz_remote/helpers/txrx/subghz_txrx.c @@ -0,0 +1,670 @@ +#include "subghz_txrx_i.h" + +#include +#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(); + subghz_setting_load(instance->setting, EXT_PATH("subghz/assets/setting_user")); + + instance->preset = malloc(sizeof(SubGhzRadioPreset)); + instance->preset->name = furi_string_alloc(); + subghz_txrx_set_preset( + instance, "AM650", subghz_setting_get_default_frequency(instance->setting), NULL, 0); + + instance->txrx_state = SubGhzTxRxStateSleep; + + subghz_txrx_hopper_set_state(instance, SubGhzHopperStateOFF); + subghz_txrx_speaker_set_state(instance, SubGhzSpeakerStateDisable); + subghz_txrx_set_debug_pin_state(instance, false); + + instance->worker = subghz_worker_alloc(); + instance->fff_data = flipper_format_string_alloc(); + + instance->environment = subghz_environment_alloc(); + 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, SUBGHZ_CAME_ATOMO_DIR_NAME); + subghz_environment_set_alutech_at_4n_rainbow_table_file_name( + instance->environment, SUBGHZ_ALUTECH_AT_4N_DIR_NAME); + subghz_environment_set_nice_flor_s_rainbow_table_file_name( + 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); + + subghz_worker_set_overrun_callback( + instance->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset); + subghz_worker_set_pair_callback( + instance->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode); + subghz_worker_set_context(instance->worker, instance->receiver); + + //set default device Internal + 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); +} + +bool subghz_txrx_is_database_loaded(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->is_database_loaded; +} + +void subghz_txrx_set_preset( + SubGhzTxRx* instance, + const char* preset_name, + uint32_t frequency, + uint8_t* preset_data, + size_t preset_data_size) { + furi_assert(instance); + furi_string_set(instance->preset->name, preset_name); + SubGhzRadioPreset* preset = instance->preset; + preset->frequency = frequency; + preset->data = preset_data; + preset->data_size = preset_data_size; +} + +const char* subghz_txrx_get_preset_name(SubGhzTxRx* instance, const char* preset) { + UNUSED(instance); + const char* preset_name = ""; + if(!strcmp(preset, "FuriHalSubGhzPresetOok270Async")) { + preset_name = "AM270"; + } else if(!strcmp(preset, "FuriHalSubGhzPresetOok650Async")) { + preset_name = "AM650"; + } else if(!strcmp(preset, "FuriHalSubGhzPreset2FSKDev238Async")) { + preset_name = "FM238"; + } else if(!strcmp(preset, "FuriHalSubGhzPreset2FSKDev476Async")) { + preset_name = "FM476"; + } else if(!strcmp(preset, "FuriHalSubGhzPresetCustom")) { + preset_name = "CUSTOM"; + } else { + FURI_LOG_E(TAG, "Unknown preset"); + } + return preset_name; +} + +SubGhzRadioPreset subghz_txrx_get_preset(SubGhzTxRx* instance) { + furi_assert(instance); + return *instance->preset; +} + +void subghz_txrx_get_frequency_and_modulation( + SubGhzTxRx* instance, + FuriString* frequency, + FuriString* modulation, + bool long_name) { + furi_assert(instance); + SubGhzRadioPreset* preset = instance->preset; + if(frequency != NULL) { + furi_string_printf( + frequency, + "%03ld.%02ld", + preset->frequency / 1000000 % 1000, + preset->frequency / 10000 % 100); + } + if(modulation != NULL) { + if(long_name) { + furi_string_printf(modulation, "%s", furi_string_get_cstr(preset->name)); + } else { + furi_string_printf(modulation, "%.2s", furi_string_get_cstr(preset->name)); + } + } +} + +static void subghz_txrx_begin(SubGhzTxRx* instance, uint8_t* preset_data) { + furi_assert(instance); + 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); + furi_assert( + instance->txrx_state != SubGhzTxRxStateRx && instance->txrx_state != SubGhzTxRxStateSleep); + + subghz_devices_idle(instance->radio_device); + + 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; +} + +static void subghz_txrx_idle(SubGhzTxRx* instance) { + furi_assert(instance); + furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); + subghz_devices_idle(instance->radio_device); + subghz_txrx_speaker_off(instance); + instance->txrx_state = SubGhzTxRxStateIDLE; +} + +static void subghz_txrx_rx_end(SubGhzTxRx* instance) { + furi_assert(instance); + furi_assert(instance->txrx_state == SubGhzTxRxStateRx); + + if(subghz_worker_is_running(instance->worker)) { + subghz_worker_stop(instance->worker); + subghz_devices_stop_async_rx(instance->radio_device); + } + subghz_devices_idle(instance->radio_device); + subghz_txrx_speaker_off(instance); + instance->txrx_state = SubGhzTxRxStateIDLE; +} + +void subghz_txrx_sleep(SubGhzTxRx* instance) { + furi_assert(instance); + subghz_devices_sleep(instance->radio_device); + instance->txrx_state = SubGhzTxRxStateSleep; +} + +static bool subghz_txrx_tx(SubGhzTxRx* instance, uint32_t frequency) { + furi_assert(instance); + furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); + + 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; + } + + return ret; +} + +SubGhzTxRxStartTxState subghz_txrx_tx_start(SubGhzTxRx* instance, FlipperFormat* flipper_format) { + furi_assert(instance); + furi_assert(flipper_format); + + subghz_txrx_stop(instance); + + SubGhzTxRxStartTxState ret = SubGhzTxRxStartTxStateErrorParserOthers; + FuriString* temp_str = furi_string_alloc(); + uint32_t repeat = 200; + do { + if(!flipper_format_rewind(flipper_format)) { + FURI_LOG_E(TAG, "Rewind error"); + break; + } + if(!flipper_format_read_string(flipper_format, "Protocol", temp_str)) { + FURI_LOG_E(TAG, "Missing Protocol"); + break; + } + if(!flipper_format_insert_or_update_uint32(flipper_format, "Repeat", &repeat, 1)) { + FURI_LOG_E(TAG, "Unable Repeat"); + break; + } + ret = SubGhzTxRxStartTxStateOk; + + SubGhzRadioPreset* preset = instance->preset; + instance->transmitter = + subghz_transmitter_alloc_init(instance->environment, furi_string_get_cstr(temp_str)); + + if(instance->transmitter) { + if(subghz_transmitter_deserialize(instance->transmitter, flipper_format) == + SubGhzProtocolStatusOk) { + if(strcmp(furi_string_get_cstr(preset->name), "") != 0) { + subghz_txrx_begin( + instance, + subghz_setting_get_preset_data_by_name( + instance->setting, furi_string_get_cstr(preset->name))); + if(preset->frequency) { + if(!subghz_txrx_tx(instance, preset->frequency)) { + FURI_LOG_E(TAG, "Only Rx"); + ret = SubGhzTxRxStartTxStateErrorOnlyRx; + } + } else { + ret = SubGhzTxRxStartTxStateErrorParserOthers; + } + + } else { + FURI_LOG_E( + TAG, "Unknown name preset \" %s \"", furi_string_get_cstr(preset->name)); + ret = SubGhzTxRxStartTxStateErrorParserOthers; + } + + if(ret == SubGhzTxRxStartTxStateOk) { + //Start TX + subghz_devices_start_async_tx( + instance->radio_device, subghz_transmitter_yield, instance->transmitter); + } + } else { + ret = SubGhzTxRxStartTxStateErrorParserOthers; + } + } else { + ret = SubGhzTxRxStartTxStateErrorParserOthers; + } + if(ret != SubGhzTxRxStartTxStateOk) { + subghz_transmitter_free(instance->transmitter); + if(instance->txrx_state != SubGhzTxRxStateIDLE) { + subghz_txrx_idle(instance); + } + } + + } while(false); + furi_string_free(temp_str); + return ret; +} + +void subghz_txrx_rx_start(SubGhzTxRx* instance) { + furi_assert(instance); + subghz_txrx_stop(instance); + subghz_txrx_begin( + instance, + subghz_setting_get_preset_data_by_name( + subghz_txrx_get_setting(instance), furi_string_get_cstr(instance->preset->name))); + subghz_txrx_rx(instance, instance->preset->frequency); +} + +void subghz_txrx_set_need_save_callback( + SubGhzTxRx* instance, + SubGhzTxRxNeedSaveCallback callback, + void* context) { + furi_assert(instance); + instance->need_save_callback = callback; + instance->need_save_context = context; +} + +static void subghz_txrx_tx_stop(SubGhzTxRx* instance) { + furi_assert(instance); + furi_assert(instance->txrx_state == SubGhzTxRxStateTx); + //Stop TX + subghz_devices_stop_async_tx(instance->radio_device); + subghz_transmitter_stop(instance->transmitter); + subghz_transmitter_free(instance->transmitter); + + //if protocol dynamic then we save the last upload + if(instance->decoder_result->protocol->type == SubGhzProtocolTypeDynamic) { + if(instance->need_save_callback) { + instance->need_save_callback(instance->need_save_context); + } + } + subghz_txrx_idle(instance); + subghz_txrx_speaker_off(instance); + //Todo: Show message +} + +FlipperFormat* subghz_txrx_get_fff_data(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->fff_data; +} + +SubGhzSetting* subghz_txrx_get_setting(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->setting; +} + +void subghz_txrx_stop(SubGhzTxRx* instance) { + furi_assert(instance); + + switch(instance->txrx_state) { + case SubGhzTxRxStateTx: + subghz_txrx_tx_stop(instance); + subghz_txrx_speaker_unmute(instance); + break; + case SubGhzTxRxStateRx: + subghz_txrx_rx_end(instance); + subghz_txrx_speaker_mute(instance); + break; + + default: + break; + } +} + +void subghz_txrx_hopper_update(SubGhzTxRx* instance) { + furi_assert(instance); + + switch(instance->hopper_state) { + case SubGhzHopperStateOFF: + case SubGhzHopperStatePause: + return; + case SubGhzHopperStateRSSITimeOut: + if(instance->hopper_timeout != 0) { + instance->hopper_timeout--; + return; + } + break; + default: + break; + } + float rssi = -127.0f; + if(instance->hopper_state != SubGhzHopperStateRSSITimeOut) { + // See RSSI Calculation timings in CC1101 17.3 RSSI + rssi = subghz_devices_get_rssi(instance->radio_device); + + // Stay if RSSI is high enough + if(rssi > -90.0f) { + instance->hopper_timeout = 10; + instance->hopper_state = SubGhzHopperStateRSSITimeOut; + return; + } + } else { + instance->hopper_state = SubGhzHopperStateRunning; + } + // Select next frequency + if(instance->hopper_idx_frequency < + subghz_setting_get_hopper_frequency_count(instance->setting) - 1) { + instance->hopper_idx_frequency++; + } else { + instance->hopper_idx_frequency = 0; + } + + if(instance->txrx_state == SubGhzTxRxStateRx) { + subghz_txrx_rx_end(instance); + }; + if(instance->txrx_state == SubGhzTxRxStateIDLE) { + subghz_receiver_reset(instance->receiver); + instance->preset->frequency = + subghz_setting_get_hopper_frequency(instance->setting, instance->hopper_idx_frequency); + subghz_txrx_rx(instance, instance->preset->frequency); + } +} + +SubGhzHopperState subghz_txrx_hopper_get_state(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->hopper_state; +} + +void subghz_txrx_hopper_set_state(SubGhzTxRx* instance, SubGhzHopperState state) { + furi_assert(instance); + instance->hopper_state = state; +} + +void subghz_txrx_hopper_unpause(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->hopper_state == SubGhzHopperStatePause) { + instance->hopper_state = SubGhzHopperStateRunning; + } +} + +void subghz_txrx_hopper_pause(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->hopper_state == SubGhzHopperStateRunning) { + instance->hopper_state = SubGhzHopperStatePause; + } +} + +void subghz_txrx_speaker_on(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); + } + + if(instance->speaker_state == SubGhzSpeakerStateEnable) { + if(furi_hal_speaker_acquire(30)) { + if(!instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); + } + } else { + instance->speaker_state = SubGhzSpeakerStateDisable; + } + } +} + +void subghz_txrx_speaker_off(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); + } + if(instance->speaker_state != SubGhzSpeakerStateDisable) { + if(furi_hal_speaker_is_mine()) { + if(!instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); + } + furi_hal_speaker_release(); + if(instance->speaker_state == SubGhzSpeakerStateShutdown) + instance->speaker_state = SubGhzSpeakerStateDisable; + } + } +} + +void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); + } + if(instance->speaker_state == SubGhzSpeakerStateEnable) { + if(furi_hal_speaker_is_mine()) { + if(!instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); + } + } + } +} + +void subghz_txrx_speaker_unmute(SubGhzTxRx* instance) { + furi_assert(instance); + if(instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); + } + if(instance->speaker_state == SubGhzSpeakerStateEnable) { + if(furi_hal_speaker_is_mine()) { + if(!instance->debug_pin_state) { + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); + } + } + } +} + +void subghz_txrx_speaker_set_state(SubGhzTxRx* instance, SubGhzSpeakerState state) { + furi_assert(instance); + instance->speaker_state = state; +} + +SubGhzSpeakerState subghz_txrx_speaker_get_state(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->speaker_state; +} + +bool subghz_txrx_load_decoder_by_name_protocol(SubGhzTxRx* instance, const char* name_protocol) { + furi_assert(instance); + furi_assert(name_protocol); + bool res = false; + instance->decoder_result = + subghz_receiver_search_decoder_base_by_name(instance->receiver, name_protocol); + if(instance->decoder_result) { + res = true; + } + return res; +} + +SubGhzProtocolDecoderBase* subghz_txrx_get_decoder(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->decoder_result; +} + +bool subghz_txrx_protocol_is_serializable(SubGhzTxRx* instance) { + furi_assert(instance); + return ( + (instance->decoder_result->protocol->flag & SubGhzProtocolFlag_Save) == + SubGhzProtocolFlag_Save); +} + +bool subghz_txrx_protocol_is_transmittable(SubGhzTxRx* instance, bool check_type) { + furi_assert(instance); + const SubGhzProtocol* protocol = instance->decoder_result->protocol; + if(check_type) { + return ( + ((protocol->flag & SubGhzProtocolFlag_Send) == SubGhzProtocolFlag_Send) && + protocol->encoder->deserialize && protocol->type == SubGhzProtocolTypeStatic); + } + return ( + ((protocol->flag & SubGhzProtocolFlag_Send) == SubGhzProtocolFlag_Send) && + protocol->encoder->deserialize); +} + +void subghz_txrx_receiver_set_filter(SubGhzTxRx* instance, SubGhzProtocolFlag filter) { + furi_assert(instance); + subghz_receiver_set_filter(instance->receiver, filter); +} + +void subghz_txrx_set_rx_calback( + SubGhzTxRx* instance, + SubGhzReceiverCallback callback, + void* context) { + subghz_receiver_set_rx_callback(instance->receiver, callback, context); +} + +void subghz_txrx_set_raw_file_encoder_worker_callback_end( + SubGhzTxRx* instance, + SubGhzProtocolEncoderRAWCallbackEnd callback, + void* context) { + subghz_protocol_raw_file_encoder_worker_set_callback_end( + (SubGhzProtocolEncoderRAW*)subghz_transmitter_get_protocol_instance(instance->transmitter), + 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); + } + + 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); + } + 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); +} + +bool subghz_txrx_radio_device_is_tx_alowed(SubGhzTxRx* instance, uint32_t frequency) { + furi_assert(instance); + furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); + + subghz_devices_idle(instance->radio_device); + subghz_devices_set_frequency(instance->radio_device, frequency); + + bool ret = subghz_devices_set_tx(instance->radio_device); + subghz_devices_idle(instance->radio_device); + + return ret; +} + +void subghz_txrx_set_debug_pin_state(SubGhzTxRx* instance, bool state) { + furi_assert(instance); + instance->debug_pin_state = state; +} + +bool subghz_txrx_get_debug_pin_state(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->debug_pin_state; +} + +void subghz_txrx_reset_dynamic_and_custom_btns(SubGhzTxRx* instance) { + furi_assert(instance); + subghz_environment_reset_keeloq(instance->environment); + + subghz_custom_btns_reset(); +} + +SubGhzReceiver* subghz_txrx_get_receiver(SubGhzTxRx* instance) { + furi_assert(instance); + return instance->receiver; +} \ No newline at end of file diff --git a/applications/external/subghz_remote/helpers/txrx/subghz_txrx.h b/applications/external/subghz_remote/helpers/txrx/subghz_txrx.h deleted file mode 100644 index 0ca780b43..000000000 --- a/applications/external/subghz_remote/helpers/txrx/subghz_txrx.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -#include "../../../../main/subghz/helpers/subghz_txrx.h" diff --git a/applications/external/subghz_remote/helpers/txrx/subghz_txrx_i.h b/applications/external/subghz_remote/helpers/txrx/subghz_txrx_i.h new file mode 100644 index 000000000..f058c2282 --- /dev/null +++ b/applications/external/subghz_remote/helpers/txrx/subghz_txrx_i.h @@ -0,0 +1,31 @@ +#pragma once + +#include "subghz_txrx.h" + +struct SubGhzTxRx { + SubGhzWorker* worker; + + SubGhzEnvironment* environment; + SubGhzReceiver* receiver; + SubGhzTransmitter* transmitter; + SubGhzProtocolDecoderBase* decoder_result; + FlipperFormat* fff_data; + + SubGhzRadioPreset* preset; + SubGhzSetting* setting; + + uint8_t hopper_timeout; + uint8_t hopper_idx_frequency; + bool is_database_loaded; + SubGhzHopperState hopper_state; + + SubGhzTxRxState txrx_state; + SubGhzSpeakerState speaker_state; + const SubGhzDevice* radio_device; + SubGhzRadioDeviceType radio_device_type; + + SubGhzTxRxNeedSaveCallback need_save_callback; + void* need_save_context; + + bool debug_pin_state; +}; diff --git a/applications/external/subghz_remote/icon.png b/applications/external/subghz_remote/icon.png new file mode 100644 index 000000000..c6b410f4c Binary files /dev/null and b/applications/external/subghz_remote/icon.png differ diff --git a/applications/external/subghz_remote/scenes/subrem_scene_remote.c b/applications/external/subghz_remote/scenes/subrem_scene_remote.c index a2e307fd9..ebc582991 100644 --- a/applications/external/subghz_remote/scenes/subrem_scene_remote.c +++ b/applications/external/subghz_remote/scenes/subrem_scene_remote.c @@ -80,7 +80,7 @@ bool subrem_scene_remote_on_event(void* context, SceneManagerEvent event) { } else { subrem_view_remote_set_state( app->subrem_remote_view, SubRemViewRemoteStateIdle, 0); - notification_message(app->notifications, &sequence_blink_stop); + notification_message(app->notifications, &sequence_blink_red_100); } return true; } else if(event.event == SubRemCustomEventViewRemoteForcedStop) { diff --git a/applications/external/subghz_remote/subghz_remote_app.c b/applications/external/subghz_remote/subghz_remote_app.c index c0682c75e..1f04ffc08 100644 --- a/applications/external/subghz_remote/subghz_remote_app.c +++ b/applications/external/subghz_remote/subghz_remote_app.c @@ -31,14 +31,14 @@ SubGhzRemoteApp* subghz_remote_app_alloc(char* p) { } furi_record_close(RECORD_STORAGE); - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } + // // Enable power for External CC1101 if it is connected + // furi_hal_subghz_enable_ext_power(); + // // Auto switch to internal radio if external radio is not available + // furi_delay_ms(15); + // if(!furi_hal_subghz_check_radio()) { + // furi_hal_subghz_select_radio_type(SubGhzRadioInternal); + // furi_hal_subghz_init_radio_type(SubGhzRadioInternal); + // } furi_hal_power_suppress_charge_enter(); @@ -113,10 +113,10 @@ void subghz_remote_app_free(SubGhzRemoteApp* app) { furi_hal_power_suppress_charge_exit(); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); + // // Disable power for External CC1101 if it was enabled and module is connected + // furi_hal_subghz_disable_ext_power(); + // // Reinit SPI handles for internal radio / nfc + // furi_hal_subghz_init_radio_type(SubGhzRadioInternal); // Submenu view_dispatcher_remove_view(app->view_dispatcher, SubRemViewIDSubmenu); diff --git a/applications/external/subghz_remote/subghz_remote_app_i.h b/applications/external/subghz_remote/subghz_remote_app_i.h index 0d25134ad..fbcc55111 100644 --- a/applications/external/subghz_remote/subghz_remote_app_i.h +++ b/applications/external/subghz_remote/subghz_remote_app_i.h @@ -1,5 +1,8 @@ #pragma once +#define SUBREM_LIGHT 1 +#define APP_SUBGHZREMOTE 1 + #include "helpers/subrem_types.h" #include "helpers/subrem_presets.h" #include "scenes/subrem_scene.h" diff --git a/applications/external/subghz_remote_configurator/helpers/subrem_presets.c b/applications/external/subghz_remote_configurator/helpers/subrem_presets.c index e5823b721..75ced8e00 100644 --- a/applications/external/subghz_remote_configurator/helpers/subrem_presets.c +++ b/applications/external/subghz_remote_configurator/helpers/subrem_presets.c @@ -84,8 +84,8 @@ SubRemLoadSubState subrem_sub_preset_load( if(!flipper_format_read_uint32(fff_data_file, "Frequency", &temp_data32, 1)) { FURI_LOG_W(TAG, "Cannot read frequency. Set default frequency"); sub_preset->freq_preset.frequency = subghz_setting_get_default_frequency(setting); - } else if(!furi_hal_subghz_is_tx_allowed(temp_data32)) { - FURI_LOG_E(TAG, "This frequency can only be used for RX"); + } else if(!subghz_txrx_radio_device_is_frequecy_valid(txrx, temp_data32)) { + FURI_LOG_E(TAG, "Frequency not supported on chosen radio module"); break; } sub_preset->freq_preset.frequency = temp_data32; @@ -124,7 +124,9 @@ SubRemLoadSubState subrem_sub_preset_load( if(!strcmp(furi_string_get_cstr(temp_str), "RAW")) { //if RAW subghz_protocol_raw_gen_fff_data( - fff_data, furi_string_get_cstr(sub_preset->file_path)); + fff_data, + furi_string_get_cstr(sub_preset->file_path), + subghz_txrx_radio_device_get_name(txrx)); } else { stream_copy_full( flipper_format_get_raw_stream(fff_data_file), diff --git a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.c b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.c index c1f519ba0..db485a2aa 100644 --- a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.c +++ b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.c @@ -1,8 +1,28 @@ #include "subghz_txrx_i.h" + #include +#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 +43,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 +62,32 @@ SubGhzTxRx* subghz_txrx_alloc() { instance->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode); subghz_worker_set_context(instance->worker, instance->receiver); + //set default device Internal + subghz_devices_init(); + instance->radio_device_type = SubGhzRadioDeviceTypeInternal; + instance->radio_device_type = + subghz_txrx_radio_device_set(instance, SubGhzRadioDeviceTypeInternal); + 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); } @@ -127,29 +160,25 @@ 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(furi_hal_subghz.cc1101_g0_pin, 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(furi_hal_subghz.cc1101_g0_pin, 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; @@ -158,7 +187,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; } @@ -169,31 +198,27 @@ 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(furi_hal_subghz.cc1101_g0_pin, false); - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, 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; @@ -255,8 +280,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; @@ -299,7 +324,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); @@ -312,7 +337,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) { @@ -362,7 +386,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) { @@ -419,13 +443,13 @@ void subghz_txrx_hopper_pause(SubGhzTxRx* instance) { void subghz_txrx_speaker_on(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_ibutton); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_acquire(30)) { if(!instance->debug_pin_state) { - 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; @@ -436,12 +460,12 @@ void subghz_txrx_speaker_on(SubGhzTxRx* instance) { void subghz_txrx_speaker_off(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } if(instance->speaker_state != SubGhzSpeakerStateDisable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - 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) @@ -453,12 +477,12 @@ void subghz_txrx_speaker_off(SubGhzTxRx* instance) { void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } } } @@ -467,12 +491,12 @@ void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { void subghz_txrx_speaker_unmute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_ibutton); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_speaker); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); } } } @@ -547,6 +571,82 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( 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); + } + + 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); + } + 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); +} + +bool subghz_txrx_radio_device_is_tx_alowed(SubGhzTxRx* instance, uint32_t frequency) { + furi_assert(instance); + furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); + + subghz_devices_idle(instance->radio_device); + subghz_devices_set_frequency(instance->radio_device, frequency); + + bool ret = subghz_devices_set_tx(instance->radio_device); + subghz_devices_idle(instance->radio_device); + + return ret; +} + void subghz_txrx_set_debug_pin_state(SubGhzTxRx* instance, bool state) { furi_assert(instance); instance->debug_pin_state = state; @@ -557,6 +657,13 @@ bool subghz_txrx_get_debug_pin_state(SubGhzTxRx* instance) { return instance->debug_pin_state; } +void subghz_txrx_reset_dynamic_and_custom_btns(SubGhzTxRx* instance) { + furi_assert(instance); + subghz_environment_reset_keeloq(instance->environment); + + subghz_custom_btns_reset(); +} + SubGhzReceiver* subghz_txrx_get_receiver(SubGhzTxRx* instance) { furi_assert(instance); return instance->receiver; diff --git a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.h b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.h index b2ebcc5f3..8bb7f2aee 100644 --- a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.h +++ b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx.h @@ -5,6 +5,7 @@ #include #include #include +#include typedef struct SubGhzTxRx SubGhzTxRx; @@ -40,6 +41,13 @@ typedef enum { SubGhzSpeakerStateEnable, } SubGhzSpeakerState; +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeAuto, + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + /** * Allocate SubGhzTxRx * @@ -312,7 +320,56 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( 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); + +bool subghz_txrx_radio_device_is_tx_alowed(SubGhzTxRx* instance, uint32_t frequency); + void subghz_txrx_set_debug_pin_state(SubGhzTxRx* instance, bool state); bool subghz_txrx_get_debug_pin_state(SubGhzTxRx* instance); +void subghz_txrx_reset_dynamic_and_custom_btns(SubGhzTxRx* instance); + SubGhzReceiver* subghz_txrx_get_receiver(SubGhzTxRx* instance); // TODO use only in DecodeRaw diff --git a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx_i.h b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx_i.h index 680d27158..f058c2282 100644 --- a/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx_i.h +++ b/applications/external/subghz_remote_configurator/helpers/txrx/subghz_txrx_i.h @@ -1,5 +1,5 @@ - #pragma once + #include "subghz_txrx.h" struct SubGhzTxRx { @@ -21,9 +21,11 @@ struct SubGhzTxRx { SubGhzTxRxState txrx_state; SubGhzSpeakerState speaker_state; + const SubGhzDevice* radio_device; + SubGhzRadioDeviceType radio_device_type; SubGhzTxRxNeedSaveCallback need_save_callback; void* need_save_context; bool debug_pin_state; -}; \ No newline at end of file +}; diff --git a/applications/external/subghz_remote_configurator/subghz_remote_app.c b/applications/external/subghz_remote_configurator/subghz_remote_app.c index 73408b739..7cbbabfcb 100644 --- a/applications/external/subghz_remote_configurator/subghz_remote_app.c +++ b/applications/external/subghz_remote_configurator/subghz_remote_app.c @@ -29,18 +29,9 @@ SubGhzRemoteApp* subghz_remote_app_alloc() { //FURI_LOG_E(TAG, "Could not create folder %s", SUBREM_APP_FOLDER); } furi_record_close(RECORD_STORAGE); - /* - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - furi_hal_power_suppress_charge_enter(); -*/ + // furi_hal_power_suppress_charge_enter(); + app->file_path = furi_string_alloc(); furi_string_set(app->file_path, SUBREM_APP_FOLDER); @@ -126,14 +117,9 @@ SubGhzRemoteApp* subghz_remote_app_alloc() { void subghz_remote_app_free(SubGhzRemoteApp* app) { furi_assert(app); - /* - furi_hal_power_suppress_charge_exit(); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); -*/ + // furi_hal_power_suppress_charge_exit(); + // Submenu view_dispatcher_remove_view(app->view_dispatcher, SubRemViewIDSubmenu); submenu_free(app->submenu); diff --git a/applications/external/swd_probe/swd_probe_app.c b/applications/external/swd_probe/swd_probe_app.c index 9795f12de..04a0165b0 100644 --- a/applications/external/swd_probe/swd_probe_app.c +++ b/applications/external/swd_probe/swd_probe_app.c @@ -682,7 +682,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); @@ -707,17 +707,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 */ @@ -942,41 +944,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) { diff --git a/applications/external/swd_probe/swd_probe_app.h b/applications/external/swd_probe/swd_probe_app.h index 203da2b1f..b60617e98 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 @@ -17,10 +17,6 @@ #include #include #include -#include -#include -#include -#include #include "usb_uart.h" 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 94e85aae2..fcac78700 100644 --- a/applications/external/totp/application.fam +++ b/applications/external/totp/application.fam @@ -3,14 +3,13 @@ App( name="Authenticator", apptype=FlipperAppType.EXTERNAL, entry_point="totp_app", - cdefines=["APP_TOTP"], 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=[ diff --git a/applications/external/weather_station/helpers/radio_device_loader.c b/applications/external/weather_station/helpers/radio_device_loader.c new file mode 100644 index 000000000..0d99549eb --- /dev/null +++ b/applications/external/weather_station/helpers/radio_device_loader.c @@ -0,0 +1,69 @@ +#include "radio_device_loader.h" + +#include +#include + +static void radio_device_loader_power_on() { + uint8_t attempts = 0; + while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) { + furi_hal_power_enable_otg(); + //CC1101 power-up time + furi_delay_ms(10); + } +} + +static void radio_device_loader_power_off() { + if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg(); +} + +bool radio_device_loader_is_connect_external(const char* name) { + bool is_connect = false; + bool is_otg_enabled = furi_hal_power_is_otg_enabled(); + + if(!is_otg_enabled) { + radio_device_loader_power_on(); + } + + const SubGhzDevice* device = subghz_devices_get_by_name(name); + if(device) { + is_connect = subghz_devices_is_connect(device); + } + + if(!is_otg_enabled) { + radio_device_loader_power_off(); + } + return is_connect; +} + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type) { + const SubGhzDevice* radio_device; + + if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 && + radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) { + radio_device_loader_power_on(); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME); + subghz_devices_begin(radio_device); + } else if(current_radio_device == NULL) { + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } else { + radio_device_loader_end(current_radio_device); + radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + } + + return radio_device; +} + +bool radio_device_loader_is_external(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + return (radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)); +} + +void radio_device_loader_end(const SubGhzDevice* radio_device) { + furi_assert(radio_device); + radio_device_loader_power_off(); + if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) { + subghz_devices_end(radio_device); + } +} \ No newline at end of file diff --git a/applications/external/weather_station/helpers/radio_device_loader.h b/applications/external/weather_station/helpers/radio_device_loader.h new file mode 100644 index 000000000..bae4bacf2 --- /dev/null +++ b/applications/external/weather_station/helpers/radio_device_loader.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +/** SubGhzRadioDeviceType */ +typedef enum { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, +} SubGhzRadioDeviceType; + +const SubGhzDevice* radio_device_loader_set( + const SubGhzDevice* current_radio_device, + SubGhzRadioDeviceType radio_device_type); + +bool radio_device_loader_is_external(const SubGhzDevice* radio_device); + +void radio_device_loader_end(const SubGhzDevice* radio_device); \ No newline at end of file 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; } diff --git a/applications/external/weather_station/scenes/weather_station_receiver.c b/applications/external/weather_station/scenes/weather_station_receiver.c index 79d01f13d..64df21fc5 100644 --- a/applications/external/weather_station/scenes/weather_station_receiver.c +++ b/applications/external/weather_station/scenes/weather_station_receiver.c @@ -48,13 +48,18 @@ static void weather_station_scene_receiver_update_statusbar(void* context) { app->ws_receiver, furi_string_get_cstr(frequency_str), furi_string_get_cstr(modulation_str), - furi_string_get_cstr(history_stat_str)); + furi_string_get_cstr(history_stat_str), + radio_device_loader_is_external(app->txrx->radio_device)); furi_string_free(frequency_str); furi_string_free(modulation_str); } else { ws_view_receiver_add_data_statusbar( - app->ws_receiver, furi_string_get_cstr(history_stat_str), "", ""); + app->ws_receiver, + furi_string_get_cstr(history_stat_str), + "", + "", + radio_device_loader_is_external(app->txrx->radio_device)); } furi_string_free(history_stat_str); } @@ -196,7 +201,7 @@ bool weather_station_scene_receiver_on_event(void* context, SceneManagerEvent ev weather_station_scene_receiver_update_statusbar(app); } // Get current RSSI - float rssi = furi_hal_subghz_get_rssi(); + float rssi = subghz_devices_get_rssi(app->txrx->radio_device); ws_view_receiver_set_rssi(app->ws_receiver, rssi); if(app->txrx->txrx_state == WSTxRxStateRx) { diff --git a/applications/external/weather_station/views/weather_station_receiver.c b/applications/external/weather_station/views/weather_station_receiver.c index 22f5343f1..b3bcde591 100644 --- a/applications/external/weather_station/views/weather_station_receiver.c +++ b/applications/external/weather_station/views/weather_station_receiver.c @@ -62,6 +62,7 @@ typedef struct { uint16_t history_item; WSReceiverBarShow bar_show; uint8_t u_rssi; + bool external_redio; } WSReceiverModel; void ws_view_receiver_set_rssi(WSReceiver* instance, float rssi) { @@ -155,7 +156,8 @@ void ws_view_receiver_add_data_statusbar( WSReceiver* ws_receiver, const char* frequency_str, const char* preset_str, - const char* history_stat_str) { + const char* history_stat_str, + bool external) { furi_assert(ws_receiver); with_view_model( ws_receiver->view, @@ -164,6 +166,7 @@ void ws_view_receiver_add_data_statusbar( furi_string_set_str(model->frequency_str, frequency_str); furi_string_set_str(model->preset_str, preset_str); furi_string_set_str(model->history_stat_str, history_stat_str); + model->external_redio = external; }, true); } @@ -203,7 +206,7 @@ void ws_view_receiver_draw(Canvas* canvas, WSReceiverModel* model) { FuriString* str_buff; str_buff = furi_string_alloc(); - bool ext_module = furi_hal_subghz_get_radio_type(); + // bool ext_module = furi_hal_subghz_get_radio_type(); WSReceiverMenuItem* item_menu; @@ -229,11 +232,12 @@ void ws_view_receiver_draw(Canvas* canvas, WSReceiverModel* model) { canvas_set_color(canvas, ColorBlack); if(model->history_item == 0) { - canvas_draw_icon(canvas, 0, 0, ext_module ? &I_Fishing_123x52 : &I_Scanning_123x52); + canvas_draw_icon( + canvas, 0, 0, model->external_redio ? &I_Fishing_123x52 : &I_Scanning_123x52); canvas_set_font(canvas, FontPrimary); canvas_draw_str(canvas, 63, 46, "Scanning..."); canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 44, 10, ext_module ? "Ext" : "Int"); + canvas_draw_str(canvas, 44, 10, model->external_redio ? "Ext" : "Int"); } // Draw RSSI @@ -409,6 +413,7 @@ WSReceiver* ws_view_receiver_alloc() { model->history_stat_str = furi_string_alloc(); model->bar_show = WSReceiverBarShowDefault; model->history = malloc(sizeof(WSReceiverHistory)); + model->external_redio = false; WSReceiverMenuItemArray_init(model->history->data); }, true); diff --git a/applications/external/weather_station/views/weather_station_receiver.h b/applications/external/weather_station/views/weather_station_receiver.h index f81aa1f5e..ade61e2dc 100644 --- a/applications/external/weather_station/views/weather_station_receiver.h +++ b/applications/external/weather_station/views/weather_station_receiver.h @@ -27,7 +27,8 @@ void ws_view_receiver_add_data_statusbar( WSReceiver* ws_receiver, const char* frequency_str, const char* preset_str, - const char* history_stat_str); + const char* history_stat_str, + bool external); void ws_view_receiver_add_item_to_menu(WSReceiver* ws_receiver, const char* name, uint8_t type); diff --git a/applications/external/weather_station/weather_station_app.c b/applications/external/weather_station/weather_station_app.c index 8bea4961d..2305fa77b 100644 --- a/applications/external/weather_station/weather_station_app.c +++ b/applications/external/weather_station/weather_station_app.c @@ -98,6 +98,14 @@ WeatherStationApp* weather_station_app_alloc() { app->txrx->environment, (void*)&weather_station_protocol_registry); app->txrx->receiver = subghz_receiver_alloc_init(app->txrx->environment); + subghz_devices_init(); + + app->txrx->radio_device = + radio_device_loader_set(app->txrx->radio_device, SubGhzRadioDeviceTypeExternalCC1101); + + subghz_devices_reset(app->txrx->radio_device); + subghz_devices_idle(app->txrx->radio_device); + subghz_receiver_set_filter(app->txrx->receiver, SubGhzProtocolFlag_Decodable); subghz_worker_set_overrun_callback( app->txrx->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset); @@ -105,15 +113,6 @@ WeatherStationApp* weather_station_app_alloc() { app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode); subghz_worker_set_context(app->txrx->worker, app->txrx->receiver); - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - furi_hal_power_suppress_charge_enter(); scene_manager_next_scene(app->scene_manager, WeatherStationSceneStart); @@ -124,13 +123,10 @@ WeatherStationApp* weather_station_app_alloc() { void weather_station_app_free(WeatherStationApp* app) { furi_assert(app); - //CC1101 off - ws_sleep(app); + subghz_devices_sleep(app->txrx->radio_device); + radio_device_loader_end(app->txrx->radio_device); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); + subghz_devices_deinit(); // Submenu view_dispatcher_remove_view(app->view_dispatcher, WeatherStationViewSubmenu); diff --git a/applications/external/weather_station/weather_station_app_i.c b/applications/external/weather_station/weather_station_app_i.c index 2e83a6e30..9437f4cf4 100644 --- a/applications/external/weather_station/weather_station_app_i.c +++ b/applications/external/weather_station/weather_station_app_i.c @@ -54,29 +54,28 @@ void ws_get_frequency_modulation( void ws_begin(WeatherStationApp* app, uint8_t* preset_data) { furi_assert(app); - UNUSED(preset_data); - furi_hal_subghz_reset(); - furi_hal_subghz_idle(); - furi_hal_subghz_load_custom_preset(preset_data); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + subghz_devices_reset(app->txrx->radio_device); + subghz_devices_idle(app->txrx->radio_device); + subghz_devices_load_preset(app->txrx->radio_device, FuriHalSubGhzPresetCustom, preset_data); app->txrx->txrx_state = WSTxRxStateIDLE; } uint32_t ws_rx(WeatherStationApp* app, uint32_t frequency) { furi_assert(app); - if(!furi_hal_subghz_is_frequency_valid(frequency)) { + if(!subghz_devices_is_frequency_valid(app->txrx->radio_device, frequency)) { furi_crash("WeatherStation: Incorrect RX frequency."); } furi_assert( app->txrx->txrx_state != WSTxRxStateRx && app->txrx->txrx_state != WSTxRxStateSleep); - furi_hal_subghz_idle(); - uint32_t value = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); - furi_hal_subghz_flush_rx(); - furi_hal_subghz_rx(); + subghz_devices_idle(app->txrx->radio_device); + uint32_t value = subghz_devices_set_frequency(app->txrx->radio_device, frequency); + subghz_devices_flush_rx(app->txrx->radio_device); + subghz_devices_set_rx(app->txrx->radio_device); + + subghz_devices_start_async_rx( + app->txrx->radio_device, subghz_worker_rx_callback, app->txrx->worker); - furi_hal_subghz_start_async_rx(subghz_worker_rx_callback, app->txrx->worker); subghz_worker_start(app->txrx->worker); app->txrx->txrx_state = WSTxRxStateRx; return value; @@ -85,7 +84,7 @@ uint32_t ws_rx(WeatherStationApp* app, uint32_t frequency) { void ws_idle(WeatherStationApp* app) { furi_assert(app); furi_assert(app->txrx->txrx_state != WSTxRxStateSleep); - furi_hal_subghz_idle(); + subghz_devices_idle(app->txrx->radio_device); app->txrx->txrx_state = WSTxRxStateIDLE; } @@ -94,15 +93,15 @@ void ws_rx_end(WeatherStationApp* app) { furi_assert(app->txrx->txrx_state == WSTxRxStateRx); if(subghz_worker_is_running(app->txrx->worker)) { subghz_worker_stop(app->txrx->worker); - furi_hal_subghz_stop_async_rx(); + subghz_devices_stop_async_rx(app->txrx->radio_device); } - furi_hal_subghz_idle(); + subghz_devices_idle(app->txrx->radio_device); app->txrx->txrx_state = WSTxRxStateIDLE; } void ws_sleep(WeatherStationApp* app) { furi_assert(app); - furi_hal_subghz_sleep(); + subghz_devices_sleep(app->txrx->radio_device); app->txrx->txrx_state = WSTxRxStateSleep; } @@ -125,7 +124,7 @@ void ws_hopper_update(WeatherStationApp* app) { float rssi = -127.0f; if(app->txrx->hopper_state != WSHopperStateRSSITimeOut) { // See RSSI Calculation timings in CC1101 17.3 RSSI - rssi = furi_hal_subghz_get_rssi(); + rssi = subghz_devices_get_rssi(app->txrx->radio_device); // Stay if RSSI is high enough if(rssi > -90.0f) { diff --git a/applications/external/weather_station/weather_station_app_i.h b/applications/external/weather_station/weather_station_app_i.h index 41e248112..0950f5975 100644 --- a/applications/external/weather_station/weather_station_app_i.h +++ b/applications/external/weather_station/weather_station_app_i.h @@ -20,11 +20,14 @@ #include #include +#include "helpers/radio_device_loader.h" + typedef struct WeatherStationApp WeatherStationApp; struct WeatherStationTxRx { SubGhzWorker* worker; + const SubGhzDevice* radio_device; SubGhzEnvironment* environment; SubGhzReceiver* receiver; SubGhzRadioPreset* preset; diff --git a/applications/external/wifi_marauder_companion/application.fam b/applications/external/wifi_marauder_companion/application.fam index e1694897d..782f858d5 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="WiFi", + 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..9e1719d08 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 = @@ -169,6 +182,11 @@ bool wifi_marauder_scene_console_output_on_event(void* context, SceneManagerEven consumed = true; } else if(event.type == SceneManagerEventTypeTick) { consumed = true; + } else { + if(app->flash_worker_busy) { + // ignore button presses while flashing + consumed = true; + } } return consumed; @@ -183,6 +201,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..2d6b8ea50 --- /dev/null +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c @@ -0,0 +1,266 @@ +#include "../wifi_marauder_app_i.h" +#include "../wifi_marauder_flasher.h" + +enum SubmenuIndex { + SubmenuIndexS3Mode, + SubmenuIndexBoot, + SubmenuIndexPart, + SubmenuIndexNvs, + SubmenuIndexBootApp0, + SubmenuIndexApp, + SubmenuIndexCustom, + 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 SubmenuIndexS3Mode: + // toggle S3 mode + app->selected_flash_options[SelectedFlashS3Mode] = + !app->selected_flash_options[SelectedFlashS3Mode]; + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexBoot: + app->selected_flash_options[SelectedFlashBoot] = + !app->selected_flash_options[SelectedFlashBoot]; + if(app->selected_flash_options[SelectedFlashBoot]) { + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_boot, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_boot)); + } + } + if(app->bin_file_path_boot[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashBoot] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexPart: + app->selected_flash_options[SelectedFlashPart] = + !app->selected_flash_options[SelectedFlashPart]; + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_part, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_part)); + } + if(app->bin_file_path_part[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashPart] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexNvs: + app->selected_flash_options[SelectedFlashNvs] = + !app->selected_flash_options[SelectedFlashNvs]; + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_nvs, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_nvs)); + } + if(app->bin_file_path_nvs[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashNvs] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexBootApp0: + app->selected_flash_options[SelectedFlashBootApp0] = + !app->selected_flash_options[SelectedFlashBootApp0]; + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_boot_app0, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_boot_app0)); + } + if(app->bin_file_path_boot_app0[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashBootApp0] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexApp: + app->selected_flash_options[SelectedFlashApp] = + !app->selected_flash_options[SelectedFlashApp]; + 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)); + } + if(app->bin_file_path_app[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashApp] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexCustom: + app->selected_flash_options[SelectedFlashCustom] = + !app->selected_flash_options[SelectedFlashCustom]; + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_custom, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_custom)); + } + if(app->bin_file_path_custom[0] == '\0') { + // if user didn't select a file, leave unselected + app->selected_flash_options[SelectedFlashCustom] = false; + } + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventRefreshSubmenu); + break; + case SubmenuIndexFlash: + // count how many options are selected + app->num_selected_flash_options = 0; + for(bool* option = &app->selected_flash_options[SelectedFlashBoot]; + option < &app->selected_flash_options[NUM_FLASH_OPTIONS]; + ++option) { + if(*option) { + ++app->num_selected_flash_options; + } + } + if(app->num_selected_flash_options) { + // only start next scene if at least one option is selected + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); + } + break; + } + + furi_string_free(selected_filepath); + furi_string_free(predefined_filepath); +} + +#define STR_SELECT "[x]" +#define STR_UNSELECT "[ ]" +#define STR_BOOT "Bootloader (" TOSTRING(ESP_ADDR_BOOT) ")" +#define STR_BOOT_S3 "Bootloader (" TOSTRING(ESP_ADDR_BOOT_S3) ")" +#define STR_PART "Part Table (" TOSTRING(ESP_ADDR_PART) ")" +#define STR_NVS "NVS (" TOSTRING(ESP_ADDR_NVS) ")" +#define STR_BOOT_APP0 "boot_app0 (" TOSTRING(ESP_ADDR_BOOT_APP0) ")" +#define STR_APP "Firmware (" TOSTRING(ESP_ADDR_APP) ")" +#define STR_CUSTOM "Custom" +#define STR_FLASH_S3 "[>] FLASH (ESP32-S3)" +#define STR_FLASH "[>] FLASH" +static void _refresh_submenu(WifiMarauderApp* app) { + Submenu* submenu = app->submenu; + + submenu_reset(app->submenu); + + submenu_set_header(submenu, "Browse for files to flash"); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashS3Mode] ? "[x] Using ESP32-S3" : + "[ ] Check if using S3", + SubmenuIndexS3Mode, + wifi_marauder_scene_flasher_callback, + app); + const char* strSelectBootloader = STR_UNSELECT " " STR_BOOT; + if(app->selected_flash_options[SelectedFlashS3Mode]) { + if(app->selected_flash_options[SelectedFlashBoot]) { + strSelectBootloader = STR_SELECT " " STR_BOOT_S3; + } else { + strSelectBootloader = STR_UNSELECT " " STR_BOOT_S3; + } + } else { + if(app->selected_flash_options[SelectedFlashBoot]) { + strSelectBootloader = STR_SELECT " " STR_BOOT; + } else { + strSelectBootloader = STR_UNSELECT " " STR_BOOT; + } + } + submenu_add_item( + submenu, strSelectBootloader, SubmenuIndexBoot, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashPart] ? STR_SELECT " " STR_PART : + STR_UNSELECT " " STR_PART, + SubmenuIndexPart, + wifi_marauder_scene_flasher_callback, + app); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashNvs] ? STR_SELECT " " STR_NVS : + STR_UNSELECT " " STR_NVS, + SubmenuIndexNvs, + wifi_marauder_scene_flasher_callback, + app); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashBootApp0] ? STR_SELECT " " STR_BOOT_APP0 : + STR_UNSELECT " " STR_BOOT_APP0, + SubmenuIndexBootApp0, + wifi_marauder_scene_flasher_callback, + app); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashApp] ? STR_SELECT " " STR_APP : + STR_UNSELECT " " STR_APP, + SubmenuIndexApp, + wifi_marauder_scene_flasher_callback, + app); + // TODO: custom addr + //submenu_add_item( + // submenu, app->selected_flash_options[SelectedFlashCustom] ? STR_SELECT " " STR_CUSTOM : STR_UNSELECT " " STR_CUSTOM, SubmenuIndexCustom, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, + app->selected_flash_options[SelectedFlashS3Mode] ? STR_FLASH_S3 : STR_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); +} + +void wifi_marauder_scene_flasher_on_enter(void* context) { + WifiMarauderApp* app = context; + + memset(app->selected_flash_options, 0, sizeof(app->selected_flash_options)); + app->bin_file_path_boot[0] = '\0'; + app->bin_file_path_part[0] = '\0'; + app->bin_file_path_nvs[0] = '\0'; + app->bin_file_path_boot_app0[0] = '\0'; + app->bin_file_path_app[0] = '\0'; + app->bin_file_path_custom[0] = '\0'; + + _refresh_submenu(app); +} + +bool wifi_marauder_scene_flasher_on_event(void* context, SceneManagerEvent event) { + WifiMarauderApp* app = context; + bool consumed = false; + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == WifiMarauderEventRefreshSubmenu) { + _refresh_submenu(app); + consumed = true; + } + } + + 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..97b26fc7f 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); @@ -231,7 +243,6 @@ void wifi_marauder_scene_start_on_enter(void* context) { } bool wifi_marauder_scene_start_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); WifiMarauderApp* app = context; bool consumed = false; @@ -260,6 +271,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 c7f03061a..a9faffb82 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app.c +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app.c @@ -88,6 +88,9 @@ WifiMarauderApp* wifi_marauder_app_alloc() { view_dispatcher_add_view( app->view_dispatcher, WifiMarauderAppViewSubmenu, submenu_get_view(app->submenu)); + app->flash_mode = false; + app->flash_worker_busy = 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..187a0aaaa 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.1" 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 9e24d3964..10301e544 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h @@ -27,7 +27,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) @@ -49,6 +49,17 @@ typedef enum WifiMarauderUserInputType { WifiMarauderUserInputTypeFileName } WifiMarauderUserInputType; +typedef enum SelectedFlashOptions { + SelectedFlashS3Mode, + SelectedFlashBoot, + SelectedFlashPart, + SelectedFlashNvs, + SelectedFlashBootApp0, + SelectedFlashApp, + SelectedFlashCustom, + NUM_FLASH_OPTIONS +} SelectedFlashOptions; + struct WifiMarauderApp { Gui* gui; ViewDispatcher* view_dispatcher; @@ -114,6 +125,19 @@ 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? + bool selected_flash_options[NUM_FLASH_OPTIONS]; + int num_selected_flash_options; + char bin_file_path_boot[100]; + char bin_file_path_part[100]; + char bin_file_path_nvs[100]; + char bin_file_path_boot_app0[100]; + char bin_file_path_app[100]; + char bin_file_path_custom[100]; + FuriThread* flash_worker; + bool flash_worker_busy; + 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..ff03f31dd 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,7 @@ typedef enum { WifiMarauderEventStartSettingsInit, WifiMarauderEventStartLogViewer, WifiMarauderEventStartScriptSelect, - WifiMarauderEventStartSniffPmkidOptions + WifiMarauderEventStartSniffPmkidOptions, + WifiMarauderEventStartFlasher, + WifiMarauderEventRefreshSubmenu } 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..ffc1acb78 --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c @@ -0,0 +1,251 @@ +#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); + + char user_msg[256]; + + // open file + if(!storage_file_open(bin_file, filepath, FSAM_READ, FSOM_OPEN_EXISTING)) { + storage_file_close(bin_file); + storage_file_free(bin_file); + dialog_message_show_storage_error(app->dialogs, "Cannot open file"); + return ESP_LOADER_ERROR_FAIL; + } + + uint64_t size = storage_file_size(bin_file); + + loader_port_debug_print("Erasing flash...this may take a while\n"); + err = esp_loader_flash_start(addr, size, sizeof(payload)); + if(err != ESP_LOADER_SUCCESS) { + storage_file_close(bin_file); + storage_file_free(bin_file); + snprintf(user_msg, sizeof(user_msg), "Erasing flash failed with error %d\n", err); + loader_port_debug_print(user_msg); + return err; + } + + loader_port_debug_print("Start programming\n"); + uint64_t last_updated = size; + while(size > 0) { + if((last_updated - size) > 50000) { + // inform user every 50k bytes + // TODO: draw a progress bar next update + snprintf(user_msg, sizeof(user_msg), "%llu bytes left.\n", size); + loader_port_debug_print(user_msg); + last_updated = size; + } + size_t to_read = MIN(size, sizeof(payload)); + uint16_t num_bytes = storage_file_read(bin_file, payload, to_read); + err = esp_loader_flash_write(payload, num_bytes); + if(err != ESP_LOADER_SUCCESS) { + snprintf(user_msg, sizeof(user_msg), "Packet could not be written! Error: %u\n", err); + storage_file_close(bin_file); + storage_file_free(bin_file); + loader_port_debug_print(user_msg); + return err; + } + + size -= num_bytes; + } + + loader_port_debug_print("Finished programming\n"); + + // TODO verify + + storage_file_close(bin_file); + storage_file_free(bin_file); + + return ESP_LOADER_SUCCESS; +} + +typedef struct { + SelectedFlashOptions selected; + const char* description; + char* path; + uint32_t addr; +} FlashItem; + +static void _flash_all_files(WifiMarauderApp* app) { + esp_loader_error_t err; + const int num_steps = app->num_selected_flash_options; + +#define NUM_FLASH_ITEMS 6 + FlashItem items[NUM_FLASH_ITEMS] = { + {SelectedFlashBoot, + "bootloader", + app->bin_file_path_boot, + app->selected_flash_options[SelectedFlashS3Mode] ? ESP_ADDR_BOOT_S3 : ESP_ADDR_BOOT}, + {SelectedFlashPart, "partition table", app->bin_file_path_part, ESP_ADDR_PART}, + {SelectedFlashNvs, "NVS", app->bin_file_path_nvs, ESP_ADDR_NVS}, + {SelectedFlashBootApp0, "boot_app0", app->bin_file_path_boot_app0, ESP_ADDR_BOOT_APP0}, + {SelectedFlashApp, "firmware", app->bin_file_path_app, ESP_ADDR_APP}, + {SelectedFlashCustom, "custom data", app->bin_file_path_custom, 0x0}, + /* if you add more entries, update NUM_FLASH_ITEMS above! */ + }; + + char user_msg[256]; + + int current_step = 1; + for(FlashItem* item = &items[0]; item < &items[NUM_FLASH_ITEMS]; ++item) { + if(app->selected_flash_options[item->selected]) { + snprintf( + user_msg, + sizeof(user_msg), + "Flashing %s (%d/%d) to address 0x%lx\n", + item->description, + current_step++, + num_steps, + item->addr); + loader_port_debug_print(user_msg); + err = _flash_file(app, item->path, item->addr); + if(err) { + break; + } + } + } +} + +static int32_t wifi_marauder_flash_bin(void* context) { + WifiMarauderApp* app = (void*)context; + esp_loader_error_t err; + + app->flash_worker_busy = true; + + // alloc global objects + flash_rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); + timer = furi_timer_alloc(_timer_callback, FuriTimerTypePeriodic, app); + + 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 0 // still getting packet drops with this + // higher BR + if(!err) { + loader_port_debug_print("Increasing speed for faster flash\n"); + err = esp_loader_change_transmission_rate(230400); + if (err != ESP_LOADER_SUCCESS) { + char err_msg[256]; + snprintf( + err_msg, + sizeof(err_msg), + "Cannot change transmission rate. Error: %u\n", + err); + loader_port_debug_print(err_msg); + } + furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); + } +#endif + + if(!err) { + loader_port_debug_print("Connected\n"); + _flash_all_files(app); +#if 0 + loader_port_debug_print("Restoring transmission rate\n"); + furi_hal_uart_set_br(FuriHalUartIdUSART1, 115200); +#endif + loader_port_debug_print("Done flashing. Please reset the board manually.\n"); + } + + // done + app->flash_worker_busy = false; + + // 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..d875c2dbe --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h @@ -0,0 +1,17 @@ +#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" + +#define ESP_ADDR_BOOT_S3 0x0 +#define ESP_ADDR_BOOT 0x1000 +#define ESP_ADDR_PART 0x8000 +#define ESP_ADDR_NVS 0x9000 +#define ESP_ADDR_BOOT_APP0 0xE000 +#define ESP_ADDR_APP 0x10000 + +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 +} diff --git a/applications/main/application.fam b/applications/main/application.fam index f3409d5c9..bf7843ff1 100644 --- a/applications/main/application.fam +++ b/applications/main/application.fam @@ -3,16 +3,33 @@ App( name="Basic applications for main menu", apptype=FlipperAppType.METAPACKAGE, provides=[ - "subghz", + "gpio", + "ibutton", + "infrared", "lfrfid", "nfc", "infrared", "gpio", - "onewire", "ibutton", "bad_kb", "u2f", - "xtreme_app", "archive", + "clock", + "subghz_remote", + "main_apps_on_start", + ], +) + +App( + appid="main_apps_on_start", + name="On start hooks", + apptype=FlipperAppType.METAPACKAGE, + provides=[ + "ibutton_start", + "onewire_start", + "subghz_start", + "infrared_start", + "lfrfid_start", + "nfc_start", ], ) diff --git a/applications/main/bad_kb/application.fam b/applications/main/bad_kb/application.fam index 165634967..00897a505 100644 --- a/applications/main/bad_kb/application.fam +++ b/applications/main/bad_kb/application.fam @@ -1,14 +1,12 @@ App( appid="bad_kb", name="Bad KB", - apptype=FlipperAppType.FAPP, + apptype=FlipperAppType.MENUEXTERNAL, entry_point="bad_kb_app", - cdefines=["APP_BAD_KB"], - requires=[ - "gui", - "dialogs", - ], stack_size=2 * 1024, icon="A_BadKb_14", order=70, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="USB", ) diff --git a/applications/main/bad_kb/icon.png b/applications/main/bad_kb/icon.png new file mode 100644 index 000000000..037474aa3 Binary files /dev/null and b/applications/main/bad_kb/icon.png differ diff --git a/applications/main/gpio/application.fam b/applications/main/gpio/application.fam index 0e99eb45a..763919921 100644 --- a/applications/main/gpio/application.fam +++ b/applications/main/gpio/application.fam @@ -1,11 +1,12 @@ App( appid="gpio", name="GPIO", - apptype=FlipperAppType.FAPP, + apptype=FlipperAppType.MENUEXTERNAL, entry_point="gpio_app", - cdefines=["APP_GPIO"], - requires=["gui"], stack_size=1 * 1024, icon="A_GPIO_14", order=50, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="GPIO", ) diff --git a/applications/main/gpio/icon.png b/applications/main/gpio/icon.png new file mode 100644 index 000000000..4a6eccf05 Binary files /dev/null and b/applications/main/gpio/icon.png differ diff --git a/applications/main/ibutton/application.fam b/applications/main/ibutton/application.fam index f37f98a5c..a8faa629c 100644 --- a/applications/main/ibutton/application.fam +++ b/applications/main/ibutton/application.fam @@ -1,24 +1,21 @@ App( appid="ibutton", name="iButton", - apptype=FlipperAppType.FAPP, + apptype=FlipperAppType.MENUEXTERNAL, targets=["f7"], entry_point="ibutton_app", - cdefines=["APP_IBUTTON"], - requires=[ - "gui", - "dialogs", - ], - provides=["ibutton_start"], icon="A_iButton_14", stack_size=2 * 1024, order=60, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="iButton", ) App( appid="ibutton_start", apptype=FlipperAppType.STARTUP, + targets=["f7"], entry_point="ibutton_on_system_start", - requires=["ibutton"], order=60, ) diff --git a/applications/main/ibutton/icon.png b/applications/main/ibutton/icon.png new file mode 100644 index 000000000..2fdaf123a Binary files /dev/null and b/applications/main/ibutton/icon.png differ diff --git a/applications/main/infrared/application.fam b/applications/main/infrared/application.fam index 5c65cd079..b78b088a7 100644 --- a/applications/main/infrared/application.fam +++ b/applications/main/infrared/application.fam @@ -1,24 +1,21 @@ App( appid="infrared", name="Infrared", - apptype=FlipperAppType.FAPP, + apptype=FlipperAppType.MENUEXTERNAL, entry_point="infrared_app", targets=["f7"], - cdefines=["APP_INFRARED"], - requires=[ - "gui", - "dialogs", - ], - provides=["infrared_start"], icon="A_Infrared_14", stack_size=3 * 1024, order=40, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="Infrared", ) App( appid="infrared_start", apptype=FlipperAppType.STARTUP, + targets=["f7"], entry_point="infrared_on_system_start", - requires=["infrared"], order=20, ) diff --git a/applications/main/infrared/icon.png b/applications/main/infrared/icon.png new file mode 100644 index 000000000..22c986180 Binary files /dev/null and b/applications/main/infrared/icon.png differ diff --git a/applications/main/lfrfid/application.fam b/applications/main/lfrfid/application.fam index aa887cdd7..cad07fbf7 100644 --- a/applications/main/lfrfid/application.fam +++ b/applications/main/lfrfid/application.fam @@ -1,26 +1,21 @@ App( appid="lfrfid", - name="RFID", - apptype=FlipperAppType.FAPP, + name="125 kHz RFID", + apptype=FlipperAppType.MENUEXTERNAL, targets=["f7"], entry_point="lfrfid_app", - cdefines=["APP_LF_RFID"], - requires=[ - "gui", - "dialogs", - ], - provides=[ - "lfrfid_start", - ], icon="A_125khz_14", stack_size=2 * 1024, order=20, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="RFID", ) App( appid="lfrfid_start", + targets=["f7"], apptype=FlipperAppType.STARTUP, entry_point="lfrfid_on_system_start", - requires=["lfrfid"], order=50, ) diff --git a/applications/main/lfrfid/icon.png b/applications/main/lfrfid/icon.png new file mode 100644 index 000000000..ce01284a2 Binary files /dev/null and b/applications/main/lfrfid/icon.png differ diff --git a/applications/main/nfc/application.fam b/applications/main/nfc/application.fam index f09127045..bc34d4e65 100644 --- a/applications/main/nfc/application.fam +++ b/applications/main/nfc/application.fam @@ -1,24 +1,21 @@ App( appid="nfc", name="NFC", - apptype=FlipperAppType.APP, + apptype=FlipperAppType.MENUEXTERNAL, targets=["f7"], entry_point="nfc_app", - cdefines=["APP_NFC"], - requires=[ - "gui", - "dialogs", - ], - provides=["nfc_start"], icon="A_NFC_14", stack_size=5 * 1024, order=30, + fap_libs=["assets"], + fap_icon="icon.png", + fap_category="NFC", ) App( appid="nfc_start", + targets=["f7"], apptype=FlipperAppType.STARTUP, entry_point="nfc_on_system_start", - requires=["nfc"], order=30, ) diff --git a/applications/main/nfc/icon.png b/applications/main/nfc/icon.png new file mode 100644 index 000000000..6bc027111 Binary files /dev/null and b/applications/main/nfc/icon.png differ diff --git a/applications/main/onewire/application.fam b/applications/main/onewire/application.fam index 68d4f6716..3d35abce9 100644 --- a/applications/main/onewire/application.fam +++ b/applications/main/onewire/application.fam @@ -1,14 +1,6 @@ -App( - appid="onewire", - name="1-Wire", - apptype=FlipperAppType.METAPACKAGE, - provides=["onewire_start"], -) - App( appid="onewire_start", apptype=FlipperAppType.STARTUP, entry_point="onewire_on_system_start", - requires=["onewire"], order=60, ) diff --git a/applications/main/subghz/application.fam b/applications/main/subghz/application.fam index eba89267f..76553d695 100644 --- a/applications/main/subghz/application.fam +++ b/applications/main/subghz/application.fam @@ -1,10 +1,9 @@ App( appid="subghz", name="SubGHz", - apptype=FlipperAppType.APP, + apptype=FlipperAppType.MENUEXTERNAL, targets=["f7"], entry_point="subghz_app", - cdefines=["APP_SUBGHZ"], requires=[ "gui", "cli", @@ -20,13 +19,16 @@ App( icon="A_Sub1ghz_14", stack_size=3 * 1024, order=10, + fap_libs=["assets", "hwdrivers"], + fap_icon="icon.png", + fap_category="Sub-GHz", ) App( appid="subghz_start", + targets=["f7"], apptype=FlipperAppType.STARTUP, entry_point="subghz_on_system_start", - requires=["subghz"], order=40, ) 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/helpers/subghz_frequency_analyzer_worker.c b/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.c index 6fec29565..6551e0425 100644 --- a/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.c +++ b/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.c @@ -28,6 +28,10 @@ struct SubGhzFrequencyAnalyzerWorker { FrequencyRSSI frequency_rssi_buf; SubGhzSetting* setting; + const SubGhzDevice* radio_device; + FuriHalSpiBusHandle* spi_bus; + bool ext_radio; + float filVal; float trigger_level; @@ -35,14 +39,16 @@ struct SubGhzFrequencyAnalyzerWorker { void* context; }; -static void subghz_frequency_analyzer_worker_load_registers(const uint8_t data[][2]) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); +static void subghz_frequency_analyzer_worker_load_registers( + FuriHalSpiBusHandle* spi_bus, + const uint8_t data[][2]) { + furi_hal_spi_acquire(spi_bus); size_t i = 0; while(data[i][0]) { - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, data[i][0], data[i][1]); + cc1101_write_reg(spi_bus, data[i][0], data[i][1]); i++; } - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(spi_bus); } // running average with adaptive coefficient @@ -77,29 +83,35 @@ static int32_t subghz_frequency_analyzer_worker_thread(void* context) { uint32_t frequency_temp = 0; CC1101Status status; - //Start CC1101 - furi_hal_subghz_reset(); + FuriHalSpiBusHandle* spi_bus = instance->spi_bus; + const SubGhzDevice* radio_device = instance->radio_device; - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_flush_rx(furi_hal_subghz.spi_bus_handle); - cc1101_flush_tx(furi_hal_subghz.spi_bus_handle); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHW); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_MDMCFG3, + //Start CC1101 + // furi_hal_subghz_reset(); + subghz_devices_reset(radio_device); + + furi_hal_spi_acquire(spi_bus); + cc1101_flush_rx(spi_bus); + cc1101_flush_tx(spi_bus); + + // TODO probably can be used device.load_preset(FuriHalSubGhzPresetCustom, ...) for external cc1101 + cc1101_write_reg(spi_bus, CC1101_IOCFG0, CC1101IocfgHW); + cc1101_write_reg(spi_bus, CC1101_MDMCFG3, 0b01111111); // symbol rate cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, + spi_bus, CC1101_AGCCTRL2, 0b00000111); // 00 - DVGA all; 000 - MAX LNA+LNA2; 111 - MAGN_TARGET 42 dB cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, + spi_bus, CC1101_AGCCTRL1, 0b00001000); // 0; 0 - LNA 2 gain is decreased to minimum before decreasing LNA gain; 00 - Relative carrier sense threshold disabled; 1000 - Absolute carrier sense threshold disabled cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, + spi_bus, CC1101_AGCCTRL0, 0b00110000); // 00 - No hysteresis, medium asymmetric dead zone, medium gain ; 11 - 64 samples agc; 00 - Normal AGC, 00 - 4dB boundary - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(spi_bus); furi_hal_subghz_set_path(FuriHalSubGhzPathIsolate); @@ -112,34 +124,36 @@ static int32_t subghz_frequency_analyzer_worker_thread(void* context) { frequency_rssi.rssi_coarse = -127.0f; frequency_rssi.rssi_fine = -127.0f; - furi_hal_subghz_idle(); - subghz_frequency_analyzer_worker_load_registers(subghz_preset_ook_650khz); + // furi_hal_subghz_idle(); + subghz_devices_idle(radio_device); + subghz_frequency_analyzer_worker_load_registers(spi_bus, subghz_preset_ook_650khz); // First stage: coarse scan for(size_t i = 0; i < subghz_setting_get_frequency_count(instance->setting); i++) { uint32_t current_frequency = subghz_setting_get_frequency(instance->setting, i); - if(furi_hal_subghz_is_frequency_valid(current_frequency) && + // if(furi_hal_subghz_is_frequency_valid(current_frequency) && + if(subghz_devices_is_frequency_valid(radio_device, current_frequency) && (current_frequency != 467750000) && (current_frequency != 464000000) && - !((furi_hal_subghz.radio_type == SubGhzRadioExternal) && + !((instance->ext_radio) && ((current_frequency == 390000000) || (current_frequency == 312000000) || (current_frequency == 312100000) || (current_frequency == 312200000) || (current_frequency == 440175000)))) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_switch_to_idle(furi_hal_subghz.spi_bus_handle); - frequency = - cc1101_set_frequency(furi_hal_subghz.spi_bus_handle, current_frequency); + furi_hal_spi_acquire(spi_bus); + cc1101_switch_to_idle(spi_bus); + frequency = cc1101_set_frequency(spi_bus, current_frequency); - cc1101_calibrate(furi_hal_subghz.spi_bus_handle); + cc1101_calibrate(spi_bus); do { - status = cc1101_get_status(furi_hal_subghz.spi_bus_handle); + status = cc1101_get_status(spi_bus); } while(status.STATE != CC1101StateIDLE); - cc1101_switch_to_rx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_switch_to_rx(spi_bus); + furi_hal_spi_release(spi_bus); furi_delay_ms(2); - rssi = furi_hal_subghz_get_rssi(); + // rssi = furi_hal_subghz_get_rssi(); + rssi = subghz_devices_get_rssi(radio_device); rssi_avg += rssi; rssi_avg_samples++; @@ -163,28 +177,31 @@ static int32_t subghz_frequency_analyzer_worker_thread(void* context) { // Second stage: fine scan if(frequency_rssi.rssi_coarse > instance->trigger_level) { - furi_hal_subghz_idle(); - subghz_frequency_analyzer_worker_load_registers(subghz_preset_ook_58khz); + // furi_hal_subghz_idle(); + subghz_devices_idle(radio_device); + subghz_frequency_analyzer_worker_load_registers(spi_bus, subghz_preset_ook_58khz); //for example -0.3 ... 433.92 ... +0.3 step 20KHz for(uint32_t i = frequency_rssi.frequency_coarse - 300000; i < frequency_rssi.frequency_coarse + 300000; i += 20000) { - if(furi_hal_subghz_is_frequency_valid(i)) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_switch_to_idle(furi_hal_subghz.spi_bus_handle); - frequency = cc1101_set_frequency(furi_hal_subghz.spi_bus_handle, i); + // if(furi_hal_subghz_is_frequency_valid(i)) { + if(subghz_devices_is_frequency_valid(radio_device, i)) { + furi_hal_spi_acquire(spi_bus); + cc1101_switch_to_idle(spi_bus); + frequency = cc1101_set_frequency(spi_bus, i); - cc1101_calibrate(furi_hal_subghz.spi_bus_handle); + cc1101_calibrate(spi_bus); do { - status = cc1101_get_status(furi_hal_subghz.spi_bus_handle); + status = cc1101_get_status(spi_bus); } while(status.STATE != CC1101StateIDLE); - cc1101_switch_to_rx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_switch_to_rx(spi_bus); + furi_hal_spi_release(spi_bus); furi_delay_ms(2); - rssi = furi_hal_subghz_get_rssi(); + // rssi = furi_hal_subghz_get_rssi(); + rssi = subghz_devices_get_rssi(radio_device); FURI_LOG_T(TAG, "#:%lu:%f", frequency, (double)rssi); @@ -261,8 +278,10 @@ static int32_t subghz_frequency_analyzer_worker_thread(void* context) { } //Stop CC1101 - furi_hal_subghz_idle(); - furi_hal_subghz_sleep(); + // furi_hal_subghz_idle(); + // furi_hal_subghz_sleep(); + subghz_devices_idle(radio_device); + subghz_devices_sleep(radio_device); return 0; } @@ -301,10 +320,26 @@ void subghz_frequency_analyzer_worker_set_pair_callback( instance->context = context; } -void subghz_frequency_analyzer_worker_start(SubGhzFrequencyAnalyzerWorker* instance) { +void subghz_frequency_analyzer_worker_start( + SubGhzFrequencyAnalyzerWorker* instance, + SubGhzTxRx* txrx) { furi_assert(instance); furi_assert(!instance->worker_running); + SubGhzRadioDeviceType radio_type = subghz_txrx_radio_device_get(txrx); + + if(radio_type == SubGhzRadioDeviceTypeExternalCC1101) { + instance->spi_bus = &furi_hal_spi_bus_handle_external; + instance->ext_radio = true; + } else if(radio_type == SubGhzRadioDeviceTypeInternal) { + instance->spi_bus = &furi_hal_spi_bus_handle_subghz; + instance->ext_radio = false; + } else { + furi_crash("Unsuported external module"); + } + + instance->radio_device = subghz_devices_get_by_name(subghz_txrx_radio_device_get_name(txrx)); + instance->worker_running = true; furi_thread_start(instance->thread); diff --git a/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.h b/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.h index eba4409ce..eeb1804d9 100644 --- a/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.h +++ b/applications/main/subghz/helpers/subghz_frequency_analyzer_worker.h @@ -45,8 +45,11 @@ void subghz_frequency_analyzer_worker_set_pair_callback( /** Start SubGhzFrequencyAnalyzerWorker * * @param instance SubGhzFrequencyAnalyzerWorker instance + * @param txrx pointer to SubGhzTxRx */ -void subghz_frequency_analyzer_worker_start(SubGhzFrequencyAnalyzerWorker* instance); +void subghz_frequency_analyzer_worker_start( + SubGhzFrequencyAnalyzerWorker* instance, + SubGhzTxRx* txrx); /** Stop SubGhzFrequencyAnalyzerWorker * diff --git a/applications/main/subghz/helpers/subghz_txrx.c b/applications/main/subghz/helpers/subghz_txrx.c index 3275b7288..db833d272 100644 --- a/applications/main/subghz/helpers/subghz_txrx.c +++ b/applications/main/subghz/helpers/subghz_txrx.c @@ -1,5 +1,9 @@ #include "subghz_txrx_i.h" + #include +#include +#include + #include #define TAG "SubGhz" @@ -128,27 +132,18 @@ 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(furi_hal_subghz.cc1101_g0_pin, 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(furi_hal_subghz.cc1101_g0_pin, 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); subghz_worker_start(instance->worker); @@ -189,12 +184,11 @@ static bool subghz_txrx_tx(SubGhzTxRx* instance, uint32_t 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(furi_hal_subghz.cc1101_g0_pin, false); - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, 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; @@ -420,13 +414,13 @@ void subghz_txrx_hopper_pause(SubGhzTxRx* instance) { void subghz_txrx_speaker_on(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_ibutton); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_acquire(30)) { if(!instance->debug_pin_state) { - 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; @@ -437,12 +431,12 @@ void subghz_txrx_speaker_on(SubGhzTxRx* instance) { void subghz_txrx_speaker_off(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } if(instance->speaker_state != SubGhzSpeakerStateDisable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - 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) @@ -454,12 +448,12 @@ void subghz_txrx_speaker_off(SubGhzTxRx* instance) { void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(NULL); + subghz_devices_set_async_mirror_pin(instance->radio_device, NULL); } } } @@ -468,12 +462,12 @@ void subghz_txrx_speaker_mute(SubGhzTxRx* instance) { void subghz_txrx_speaker_unmute(SubGhzTxRx* instance) { furi_assert(instance); if(instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_ibutton); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_ibutton); } if(instance->speaker_state == SubGhzSpeakerStateEnable) { if(furi_hal_speaker_is_mine()) { if(!instance->debug_pin_state) { - furi_hal_subghz_set_async_mirror_pin(&gpio_speaker); + subghz_devices_set_async_mirror_pin(instance->radio_device, &gpio_speaker); } } } @@ -548,6 +542,82 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( 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); + } + + 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); + } + 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); +} + +bool subghz_txrx_radio_device_is_tx_alowed(SubGhzTxRx* instance, uint32_t frequency) { + furi_assert(instance); + furi_assert(instance->txrx_state != SubGhzTxRxStateSleep); + + subghz_devices_idle(instance->radio_device); + subghz_devices_set_frequency(instance->radio_device, frequency); + + bool ret = subghz_devices_set_tx(instance->radio_device); + subghz_devices_idle(instance->radio_device); + + return ret; +} + void subghz_txrx_set_debug_pin_state(SubGhzTxRx* instance, bool state) { furi_assert(instance); instance->debug_pin_state = state; @@ -568,4 +638,4 @@ void subghz_txrx_reset_dynamic_and_custom_btns(SubGhzTxRx* instance) { SubGhzReceiver* subghz_txrx_get_receiver(SubGhzTxRx* instance) { furi_assert(instance); return instance->receiver; -} \ 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 8aa717684..d6d420352 100644 --- a/applications/main/subghz/helpers/subghz_txrx.h +++ b/applications/main/subghz/helpers/subghz_txrx.h @@ -294,13 +294,56 @@ void subghz_txrx_set_raw_file_encoder_worker_callback_end( 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); + +bool subghz_txrx_radio_device_is_tx_alowed(SubGhzTxRx* instance, uint32_t frequency); + void subghz_txrx_set_debug_pin_state(SubGhzTxRx* instance, bool state); bool subghz_txrx_get_debug_pin_state(SubGhzTxRx* instance); void subghz_txrx_reset_dynamic_and_custom_btns(SubGhzTxRx* instance); SubGhzReceiver* subghz_txrx_get_receiver(SubGhzTxRx* instance); // TODO use only in DecodeRaw - -#ifdef __cplusplus -} -#endif diff --git a/applications/main/subghz/helpers/subghz_txrx_i.h b/applications/main/subghz/helpers/subghz_txrx_i.h index 680d27158..5240884ff 100644 --- a/applications/main/subghz/helpers/subghz_txrx_i.h +++ b/applications/main/subghz/helpers/subghz_txrx_i.h @@ -1,5 +1,5 @@ - #pragma once + #include "subghz_txrx.h" struct SubGhzTxRx { @@ -26,4 +26,4 @@ struct SubGhzTxRx { void* need_save_context; bool debug_pin_state; -}; \ No newline at end of file +}; diff --git a/applications/main/subghz/helpers/subghz_types.h b/applications/main/subghz/helpers/subghz_types.h index 1cddfc8d5..2e7ca468d 100644 --- a/applications/main/subghz/helpers/subghz_types.h +++ b/applications/main/subghz/helpers/subghz_types.h @@ -54,6 +54,7 @@ typedef enum { SubGhzLoadKeyStateOK, SubGhzLoadKeyStateParseErr, SubGhzLoadKeyStateOnlyRx, + SubGhzLoadKeyStateUnsuportedFreq, SubGhzLoadKeyStateProtocolDescriptionErr, } SubGhzLoadKeyState; @@ -75,9 +76,6 @@ typedef enum { SubGhzViewIdFrequencyAnalyzer, SubGhzViewIdReadRAW, - SubGhzViewIdStatic, - SubGhzViewIdTestCarrier, - SubGhzViewIdTestPacket, } SubGhzViewId; /** SubGhz load type file */ diff --git a/applications/main/subghz/icon.png b/applications/main/subghz/icon.png new file mode 100644 index 000000000..5a25fdf4e Binary files /dev/null and b/applications/main/subghz/icon.png differ diff --git a/applications/main/subghz/scenes/subghz_scene_config.h b/applications/main/subghz/scenes/subghz_scene_config.h index 269ec4c72..ddff47208 100644 --- a/applications/main/subghz/scenes/subghz_scene_config.h +++ b/applications/main/subghz/scenes/subghz_scene_config.h @@ -12,12 +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_carrier, TestCarrier) -#if FURI_DEBUG -ADD_SCENE(subghz, test_static, TestStatic) -ADD_SCENE(subghz, test_packet, TestPacket) -#endif ADD_SCENE(subghz, set_type, SetType) ADD_SCENE(subghz, set_fix, SetFix) ADD_SCENE(subghz, set_cnt, SetCnt) diff --git a/applications/main/subghz/scenes/subghz_scene_decode_raw.c b/applications/main/subghz/scenes/subghz_scene_decode_raw.c index 102965df5..988a61c8b 100644 --- a/applications/main/subghz/scenes/subghz_scene_decode_raw.c +++ b/applications/main/subghz/scenes/subghz_scene_decode_raw.c @@ -93,7 +93,9 @@ bool subghz_scene_decode_raw_start(SubGhz* subghz) { subghz->decode_raw_file_worker_encoder = subghz_file_encoder_worker_alloc(); if(subghz_file_encoder_worker_start( - subghz->decode_raw_file_worker_encoder, furi_string_get_cstr(file_name))) { + subghz->decode_raw_file_worker_encoder, + furi_string_get_cstr(file_name), + subghz_txrx_radio_device_get_name(subghz->txrx))) { //the worker needs a file in order to open and read part of the file furi_delay_ms(100); } else { diff --git a/applications/main/subghz/scenes/subghz_scene_radio_settings.c b/applications/main/subghz/scenes/subghz_scene_radio_settings.c index 80f05ad17..484058560 100644 --- a/applications/main/subghz/scenes/subghz_scene_radio_settings.c +++ b/applications/main/subghz/scenes/subghz_scene_radio_settings.c @@ -1,16 +1,17 @@ #include "../subghz_i.h" #include "../helpers/subghz_custom_event.h" +#include +#include -#define EXT_MODULES_COUNT (sizeof(radio_modules_variables_text) / sizeof(char* const)) -const char* const radio_modules_variables_text[] = { +#define RADIO_DEVICE_COUNT 2 +const char* const radio_device_text[RADIO_DEVICE_COUNT] = { "Internal", "External", }; -#define EXT_MOD_POWER_COUNT 2 -const char* const ext_mod_power_text[EXT_MOD_POWER_COUNT] = { - "ON", - "OFF", +const uint32_t radio_device_value[RADIO_DEVICE_COUNT] = { + SubGhzRadioDeviceTypeInternal, + SubGhzRadioDeviceTypeExternalCC1101, }; #define TIMESTAMP_NAMES_COUNT 2 @@ -35,19 +36,18 @@ const char* const debug_counter_text[DEBUG_COUNTER_COUNT] = { "+10", }; -static void subghz_scene_ext_module_changed(VariableItem* item) { +static void subghz_scene_radio_settings_set_device(VariableItem* item) { SubGhz* subghz = variable_item_get_context(item); - uint8_t value_index_exm = variable_item_get_current_value_index(item); + uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, radio_modules_variables_text[value_index_exm]); - - subghz->last_settings->external_module_enabled = value_index_exm == 1; - subghz_last_settings_save(subghz->last_settings); -} - -static void subghz_ext_module_start_var_list_enter_callback(void* context, uint32_t index) { - SubGhz* subghz = context; - view_dispatcher_send_custom_event(subghz->view_dispatcher, index); + 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]); } static void subghz_scene_receiver_config_set_debug_pin(VariableItem* item) { @@ -88,22 +88,22 @@ static void subghz_scene_receiver_config_set_debug_counter(VariableItem* item) { } } -static void subghz_scene_receiver_config_set_ext_mod_power(VariableItem* item) { - SubGhz* subghz = variable_item_get_context(item); - uint8_t index = variable_item_get_current_value_index(item); +// static void subghz_scene_receiver_config_set_ext_mod_power(VariableItem* item) { +// SubGhz* subghz = variable_item_get_context(item); +// uint8_t index = variable_item_get_current_value_index(item); - variable_item_set_current_value_text(item, ext_mod_power_text[index]); +// variable_item_set_current_value_text(item, ext_mod_power_text[index]); - furi_hal_subghz_set_external_power_disable(index == 1); - if(index == 1) { - furi_hal_subghz_disable_ext_power(); - } else { - furi_hal_subghz_enable_ext_power(); - } +// furi_hal_subghz_set_external_power_disable(index == 1); +// if(index == 1) { +// furi_hal_subghz_disable_ext_power(); +// } else { +// furi_hal_subghz_enable_ext_power(); +// } - subghz->last_settings->external_module_power_5v_disable = index == 1; - subghz_last_settings_save(subghz->last_settings); -} +// subghz->last_settings->external_module_power_5v_disable = index == 1; +// subghz_last_settings_save(subghz->last_settings); +// } static void subghz_scene_receiver_config_set_timestamp_file_names(VariableItem* item) { SubGhz* subghz = variable_item_get_context(item); @@ -120,29 +120,25 @@ void subghz_scene_radio_settings_on_enter(void* context) { VariableItemList* variable_item_list = subghz->variable_item_list; uint8_t value_index; + VariableItem* item; - value_index = furi_hal_subghz.radio_type; - VariableItem* item = variable_item_list_add( - variable_item_list, "Module", EXT_MODULES_COUNT, subghz_scene_ext_module_changed, subghz); - - variable_item_list_set_enter_callback( - variable_item_list, subghz_ext_module_start_var_list_enter_callback, subghz); - - variable_item_set_current_value_index(item, value_index); - variable_item_set_current_value_text(item, radio_modules_variables_text[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; // Only 1 item if external disconnected item = variable_item_list_add( subghz->variable_item_list, - "Ext Radio 5v", - EXT_MOD_POWER_COUNT, - subghz_scene_receiver_config_set_ext_mod_power, + "Module", + value_count_device, + subghz_scene_radio_settings_set_device, subghz); - value_index = furi_hal_subghz_get_external_power_disable(); + 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, ext_mod_power_text[value_index]); + variable_item_set_current_value_text(item, radio_device_text[value_index]); item = variable_item_list_add( - subghz->variable_item_list, + variable_item_list, "Time in names", TIMESTAMP_NAMES_COUNT, subghz_scene_receiver_config_set_timestamp_file_names, @@ -153,7 +149,7 @@ void subghz_scene_radio_settings_on_enter(void* context) { if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { item = variable_item_list_add( - subghz->variable_item_list, + variable_item_list, "Counter incr.", DEBUG_COUNTER_COUNT, subghz_scene_receiver_config_set_debug_counter, @@ -182,7 +178,7 @@ void subghz_scene_radio_settings_on_enter(void* context) { } } else { item = variable_item_list_add( - subghz->variable_item_list, + variable_item_list, "Counter incr.", 3, subghz_scene_receiver_config_set_debug_counter, @@ -208,7 +204,7 @@ void subghz_scene_radio_settings_on_enter(void* context) { variable_item_set_current_value_text(item, debug_counter_text[value_index]); item = variable_item_list_add( - subghz->variable_item_list, + variable_item_list, "Debug Pin", DEBUG_P_COUNT, subghz_scene_receiver_config_set_debug_pin, @@ -227,25 +223,11 @@ bool subghz_scene_radio_settings_on_event(void* context, SceneManagerEvent event UNUSED(subghz); UNUSED(event); - // Set selected radio module - furi_hal_subghz_select_radio_type(subghz->last_settings->external_module_enabled); - furi_hal_subghz_init_radio_type(subghz->last_settings->external_module_enabled); - - furi_hal_subghz_enable_ext_power(); - - // Check if module is present, if no -> show error - if(!furi_hal_subghz_check_radio()) { - subghz->last_settings->external_module_enabled = false; - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - furi_string_set(subghz->error_str, "Please connect\nexternal radio"); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowErrorSub); - } - return false; } 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_receiver.c b/applications/main/subghz/scenes/subghz_scene_receiver.c index 343c803cd..427e5e3de 100644 --- a/applications/main/subghz/scenes/subghz_scene_receiver.c +++ b/applications/main/subghz/scenes/subghz_scene_receiver.c @@ -55,7 +55,9 @@ static void subghz_scene_receiver_update_statusbar(void* context) { furi_string_printf( modulation_str, "%s Mod: %s", - furi_hal_subghz_get_radio_type() ? "Ext" : "Int", + (subghz_txrx_radio_device_get(subghz->txrx) == SubGhzRadioDeviceTypeInternal) ? + "Int" : + "Ext", furi_string_get_cstr(temp_str)); furi_string_free(temp_str); } @@ -253,8 +255,8 @@ bool subghz_scene_receiver_on_event(void* context, SceneManagerEvent event) { subghz_scene_receiver_update_statusbar(subghz); } - //get RSSI - 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_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/applications/main/subghz/scenes/subghz_scene_start.c b/applications/main/subghz/scenes/subghz_scene_start.c index 0bcfe719f..7beb62651 100644 --- a/applications/main/subghz/scenes/subghz_scene_start.c +++ b/applications/main/subghz/scenes/subghz_scene_start.c @@ -6,11 +6,11 @@ enum SubmenuIndex { SubmenuIndexRead = 10, SubmenuIndexSaved, - SubmenuIndexTest, SubmenuIndexAddManually, SubmenuIndexFrequencyAnalyzer, SubmenuIndexReadRAW, SubmenuIndexExtSettings, + SubmenuIndexRadioSetting, }; void subghz_scene_start_submenu_callback(void* context, uint32_t index) { @@ -52,14 +52,6 @@ void subghz_scene_start_on_enter(void* context) { SubmenuIndexExtSettings, subghz_scene_start_submenu_callback, subghz); - submenu_add_lockable_item( - subghz->submenu, - "Test", - SubmenuIndexTest, - subghz_scene_start_submenu_callback, - subghz, - !furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug), - "Enable\nDebug!"); submenu_set_selected_item( subghz->submenu, scene_manager_get_scene_state(subghz->scene_manager, SubGhzSceneStart)); @@ -74,54 +66,38 @@ bool subghz_scene_start_on_event(void* context, SceneManagerEvent event) { view_dispatcher_stop(subghz->view_dispatcher); return true; } else if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexExtSettings) { + if(event.event == SubmenuIndexReadRAW) { scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexExtSettings); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneExtModuleSettings); + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexReadRAW); + subghz_rx_key_state_set(subghz, SubGhzRxKeyStateIDLE); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneReadRAW); + return true; + } else if(event.event == SubmenuIndexRead) { + scene_manager_set_scene_state( + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexRead); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneReceiver); + return true; + } else if(event.event == SubmenuIndexSaved) { + scene_manager_set_scene_state( + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexSaved); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneSaved); return true; } else if(event.event == SubmenuIndexAddManually) { scene_manager_set_scene_state( subghz->scene_manager, SubGhzSceneStart, SubmenuIndexAddManually); scene_manager_next_scene(subghz->scene_manager, SubGhzSceneSetType); return true; - } else { - furi_hal_subghz_enable_ext_power(); - - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - subghz->last_settings->external_module_enabled = false; - furi_string_set(subghz->error_str, "Please connect\nexternal radio"); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneShowErrorSub); - return true; - } else if(event.event == SubmenuIndexReadRAW) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexReadRAW); - subghz_rx_key_state_set(subghz, SubGhzRxKeyStateIDLE); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneReadRAW); - return true; - } else if(event.event == SubmenuIndexRead) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexRead); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneReceiver); - return true; - } else if(event.event == SubmenuIndexSaved) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexSaved); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneSaved); - return true; - } else if(event.event == SubmenuIndexFrequencyAnalyzer) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexFrequencyAnalyzer); - 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 == SubmenuIndexFrequencyAnalyzer) { + scene_manager_set_scene_state( + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexFrequencyAnalyzer); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneFrequencyAnalyzer); + dolphin_deed(DolphinDeedSubGhzFrequencyAnalyzer); + return true; + } else if(event.event == SubmenuIndexExtSettings) { + scene_manager_set_scene_state( + subghz->scene_manager, SubGhzSceneStart, SubmenuIndexExtSettings); + scene_manager_next_scene(subghz->scene_manager, SubGhzSceneExtModuleSettings); + return true; } } return false; 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 fa333edca..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test.c +++ /dev/null @@ -1,65 +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); -#if FURI_DEBUG - 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); -#endif - 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; - } -#if FURI_DEBUG - 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; - } -#endif - } - 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 2e1ec4d9c..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); -} \ No newline at end of file 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 4757f9f3a..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_packet.c +++ /dev/null @@ -1,32 +0,0 @@ -#if FURI_DEBUG -#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); -} -#endif \ No newline at end of file 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 959eb75b8..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_static.c +++ /dev/null @@ -1,32 +0,0 @@ -#if FURI_DEBUG -#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); -} -#endif \ No newline at end of file diff --git a/applications/main/subghz/subghz.c b/applications/main/subghz/subghz.c index f03ad39b2..bd17cbbdd 100644 --- a/applications/main/subghz/subghz.c +++ b/applications/main/subghz/subghz.c @@ -114,6 +114,8 @@ SubGhz* subghz_alloc(bool alloc_for_tx_only) { // Open Notification record subghz->notifications = furi_record_open(RECORD_NOTIFICATION); + subghz->txrx = subghz_txrx_alloc(); + if(!alloc_for_tx_only) { // SubMenu subghz->submenu = submenu_alloc(); @@ -169,18 +171,12 @@ SubGhz* subghz_alloc(bool alloc_for_tx_only) { variable_item_list_get_view(subghz->variable_item_list)); // Frequency Analyzer - subghz->subghz_frequency_analyzer = subghz_frequency_analyzer_alloc(); + // View knows too much + subghz->subghz_frequency_analyzer = subghz_frequency_analyzer_alloc(subghz->txrx); view_dispatcher_add_view( subghz->view_dispatcher, SubGhzViewIdFrequencyAnalyzer, subghz_frequency_analyzer_get_view(subghz->subghz_frequency_analyzer)); - - // 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)); } // Read RAW subghz->subghz_read_raw = subghz_read_raw_alloc(alloc_for_tx_only); @@ -189,30 +185,12 @@ SubGhz* subghz_alloc(bool alloc_for_tx_only) { SubGhzViewIdReadRAW, subghz_read_raw_get_view(subghz->subghz_read_raw)); -#if FURI_DEBUG - // 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)); -#endif - //init threshold rssi subghz->threshold_rssi = subghz_threshold_rssi_alloc(); //init TxRx & Protocol & History & KeyBoard subghz_unlock(subghz); - subghz->txrx = subghz_txrx_alloc(); - SubGhzSetting* setting = subghz_txrx_get_setting(subghz->txrx); subghz_load_custom_presets(setting); @@ -268,21 +246,7 @@ void subghz_free(SubGhz* subghz, bool alloc_for_tx_only) { subghz_txrx_stop(subghz->txrx); subghz_txrx_sleep(subghz->txrx); -#if FURI_DEBUG - // Packet Test - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdTestPacket); - subghz_test_packet_free(subghz->subghz_test_packet); - - // Static - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdStatic); - subghz_test_static_free(subghz->subghz_test_static); -#endif - if(!alloc_for_tx_only) { - // Carrier Test - view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdTestCarrier); - subghz_test_carrier_free(subghz->subghz_test_carrier); - // Receiver view_dispatcher_remove_view(subghz->view_dispatcher, SubGhzViewIdReceiver); subghz_view_receiver_free(subghz->subghz_receiver); @@ -381,15 +345,6 @@ int32_t subghz_app(char* p) { subghz->raw_send_only = false; } - // Call enable power for external module - furi_hal_subghz_enable_ext_power(); - - // Auto switch to internal radio if external radio is not available - if(!furi_hal_subghz_check_radio()) { - subghz->last_settings->external_module_enabled = false; - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } // Check argument and run corresponding scene bool is_favorite = process_favorite_launch(&p) && XTREME_SETTINGS()->favorite_timeout; if(p && strlen(p)) { @@ -449,10 +404,6 @@ int32_t subghz_app(char* p) { } furi_hal_power_suppress_charge_exit(); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); subghz_free(subghz, alloc_for_tx); diff --git a/applications/main/subghz/subghz_cli.c b/applications/main/subghz/subghz_cli.c index e0e2e4865..1d49038eb 100644 --- a/applications/main/subghz/subghz_cli.c +++ b/applications/main/subghz/subghz_cli.c @@ -19,6 +19,32 @@ #define SUBGHZ_FREQUENCY_RANGE_STR \ "299999755...348000000 or 386999938...464000000 or 778999847...928000000" +// Tx/Rx Carrier | only internal module +// Tx/Rx command | both +// Rx RAW | only internal module +// Chat | both + +#define TAG "SubGhz CLI" + +static void subghz_cli_radio_device_power_on() { + uint8_t attempts = 5; + while(--attempts > 0) { + if(furi_hal_power_enable_otg()) break; + } + if(attempts == 0) { + if(furi_hal_power_get_usb_voltage() < 4.5f) { + FURI_LOG_E( + "TAG", + "Error power otg enable. BQ2589 check otg fault = %d", + furi_hal_power_check_otg_fault() ? 1 : 0); + } + } +} + +static void 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; @@ -42,9 +68,8 @@ void subghz_cli_command_tx_carrier(Cli* cli, FuriString* args, void* context) { furi_hal_subghz_load_preset(FuriHalSubGhzPresetOok650Async); frequency = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, true); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_write(&gpio_cc1101_g0, true); furi_hal_power_suppress_charge_enter(); @@ -105,6 +130,27 @@ 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; + } + //check if the device is connected + if(!subghz_devices_is_connect(device)) { + subghz_cli_radio_device_power_off(); + device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); + *device_ind = 0; + } + return device; +} + void subghz_cli_command_tx(Cli* cli, FuriString* args, void* context) { UNUSED(context); uint32_t frequency = 433920000; @@ -129,14 +175,16 @@ void subghz_cli_command_tx(Cli* cli, FuriString* args, void* context) { 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", frequency, @@ -181,7 +229,7 @@ void subghz_cli_command_tx(Cli* cli, FuriString* args, void* context) { furi_hal_subghz_stop_async_tx(); } else { - printf("Transmission on this frequency is restricted in your region\r\n"); + printf("Frequency is outside of default range. Check docs.\r\n"); } furi_hal_subghz_sleep(); @@ -236,12 +284,15 @@ void subghz_cli_command_rx(Cli* cli, FuriString* args, void* context) { cli_print_usage("subghz rx", "", 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; } // Allocate context and buffers @@ -266,10 +317,10 @@ 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(furi_hal_subghz.cc1101_g0_pin, 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(); @@ -336,9 +387,9 @@ 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_650khz_async_regs); frequency = furi_hal_subghz_set_frequency_and_path(frequency); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); furi_hal_power_suppress_charge_enter(); @@ -609,13 +660,18 @@ static void subghz_cli_command_chat(Cli* cli, FuriString* args, void* context) { 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); - 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; + } + + // TODO if(!furi_hal_subghz_is_tx_allowed(frequency)) { printf( "In your settings, only reception on this frequency (%lu) is allowed,\r\n" @@ -780,15 +836,6 @@ static void subghz_cli_command_chat(Cli* cli, FuriString* args, void* context) { static void subghz_cli_command(Cli* cli, FuriString* args, void* context) { FuriString* cmd = furi_string_alloc(); - // Enable power for External CC1101 if it is connected - furi_hal_subghz_enable_ext_power(); - // Auto switch to internal radio if external radio is not available - furi_delay_ms(15); - if(!furi_hal_subghz_check_radio()) { - furi_hal_subghz_select_radio_type(SubGhzRadioInternal); - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - } - do { if(!args_read_string_and_trim(args, cmd)) { subghz_cli_command_print_usage(); @@ -845,11 +892,6 @@ static void subghz_cli_command(Cli* cli, FuriString* args, void* context) { subghz_cli_command_print_usage(); } while(false); - // Disable power for External CC1101 if it was enabled and module is connected - furi_hal_subghz_disable_ext_power(); - // Reinit SPI handles for internal radio / nfc - furi_hal_subghz_init_radio_type(SubGhzRadioInternal); - furi_string_free(cmd); } diff --git a/applications/main/subghz/subghz_i.c b/applications/main/subghz/subghz_i.c index 70812ed11..b16900177 100644 --- a/applications/main/subghz/subghz_i.c +++ b/applications/main/subghz/subghz_i.c @@ -46,7 +46,7 @@ bool subghz_tx_start(SubGhz* subghz, FlipperFormat* flipper_format) { subghz->dialogs, "Error in protocol\nparameters\ndescription"); break; case SubGhzTxRxStartTxStateErrorOnlyRx: - subghz_dialog_message_show_only_rx(subghz); + subghz_dialog_message_freq_error(subghz, true); break; default: @@ -56,12 +56,16 @@ bool subghz_tx_start(SubGhz* subghz, FlipperFormat* flipper_format) { return false; } -void subghz_dialog_message_show_only_rx(SubGhz* subghz) { +void subghz_dialog_message_freq_error(SubGhz* subghz, bool only_rx) { DialogsApp* dialogs = subghz->dialogs; DialogMessage* message = dialog_message_alloc(); + const char* header_text = "Frequency not supported"; + const char* message_text = "Frequency\nis outside of\nsuported range."; - const char* header_text = "Transmission is blocked"; - const char* message_text = "Frequency\nis outside of\ndefault range.\nCheck docs."; + if(only_rx) { + header_text = "Transmission is blocked"; + message_text = "Frequency\nis outside of\ndefault range.\nCheck docs."; + } dialog_message_set_header(message, header_text, 63, 3, AlignCenter, AlignTop); dialog_message_set_text(message, message_text, 0, 17, AlignLeft, AlignTop); @@ -111,13 +115,14 @@ bool subghz_key_load(SubGhz* subghz, const char* file_path, bool show_dialog) { break; } - if(!furi_hal_subghz_is_frequency_valid(temp_data32)) { - FURI_LOG_E(TAG, "Frequency not supported"); + if(!subghz_txrx_radio_device_is_frequecy_valid(subghz->txrx, temp_data32)) { + FURI_LOG_E(TAG, "Frequency not supported on chosen radio module"); + load_key_state = SubGhzLoadKeyStateUnsuportedFreq; break; } - if(!furi_hal_subghz_is_tx_allowed(temp_data32)) { - FURI_LOG_E(TAG, "This frequency can only be used for RX"); + if(!subghz_txrx_radio_device_is_tx_alowed(subghz->txrx, temp_data32)) { + FURI_LOG_E(TAG, "This frequency can only be used for RX on chosen radio module"); load_key_state = SubGhzLoadKeyStateOnlyRx; break; } @@ -206,9 +211,15 @@ bool subghz_key_load(SubGhz* subghz, const char* file_path, bool show_dialog) { } return false; + case SubGhzLoadKeyStateUnsuportedFreq: + if(show_dialog) { + subghz_dialog_message_freq_error(subghz, false); + } + return false; + case SubGhzLoadKeyStateOnlyRx: if(show_dialog) { - subghz_dialog_message_show_only_rx(subghz); + subghz_dialog_message_freq_error(subghz, true); } return false; diff --git a/applications/main/subghz/subghz_i.h b/applications/main/subghz/subghz_i.h index 4b5de724e..340cdb137 100644 --- a/applications/main/subghz/subghz_i.h +++ b/applications/main/subghz/subghz_i.h @@ -9,11 +9,6 @@ #include "views/subghz_frequency_analyzer.h" #include "views/subghz_read_raw.h" -#include "views/subghz_test_carrier.h" -#if FURI_DEBUG -#include "views/subghz_test_static.h" -#include "views/subghz_test_packet.h" -#endif #include #include #include @@ -81,11 +76,7 @@ struct SubGhz { SubGhzFrequencyAnalyzer* subghz_frequency_analyzer; SubGhzReadRAW* subghz_read_raw; bool raw_send_only; - SubGhzTestCarrier* subghz_test_carrier; -#if FURI_DEBUG - SubGhzTestStatic* subghz_test_static; - SubGhzTestPacket* subghz_test_packet; -#endif + SubGhzLastSettings* last_settings; SubGhzProtocolFlag filter; @@ -115,7 +106,7 @@ void subghz_blink_start(SubGhz* subghz); void subghz_blink_stop(SubGhz* subghz); bool subghz_tx_start(SubGhz* subghz, FlipperFormat* flipper_format); -void subghz_dialog_message_show_only_rx(SubGhz* subghz); +void subghz_dialog_message_freq_error(SubGhz* subghz, bool only_rx); bool subghz_key_load(SubGhz* subghz, const char* file_path, bool show_dialog); bool subghz_get_next_name_file(SubGhz* subghz, uint8_t max_len); diff --git a/applications/main/subghz/subghz_last_settings.c b/applications/main/subghz/subghz_last_settings.c index 614e0baa6..b61ed3769 100644 --- a/applications/main/subghz/subghz_last_settings.c +++ b/applications/main/subghz/subghz_last_settings.c @@ -119,17 +119,6 @@ void subghz_last_settings_load(SubGhzLastSettings* instance, size_t preset_count instance->timestamp_file_names = temp_timestamp_file_names; - if(instance->external_module_power_5v_disable) { - furi_hal_subghz_set_external_power_disable(true); - furi_hal_subghz_disable_ext_power(); - } - - // Set selected radio module - if(instance->external_module_enabled) { - furi_hal_subghz_select_radio_type(SubGhzRadioExternal); - furi_hal_subghz_init_radio_type(SubGhzRadioExternal); - } - /*/} else { instance->preset = temp_preset; }*/ diff --git a/applications/main/subghz/subghz_last_settings.h b/applications/main/subghz/subghz_last_settings.h index 260c879f4..d1a5b495f 100644 --- a/applications/main/subghz/subghz_last_settings.h +++ b/applications/main/subghz/subghz_last_settings.h @@ -10,8 +10,10 @@ typedef struct { int32_t preset; uint32_t frequency_analyzer_feedback_level; float frequency_analyzer_trigger; + // TODO not using but saved so as not to change the version bool external_module_enabled; bool external_module_power_5v_disable; + // saved so as not to change the version bool timestamp_file_names; } SubGhzLastSettings; diff --git a/applications/main/subghz/views/receiver.c b/applications/main/subghz/views/receiver.c index eb7a5a154..9d514b8ca 100644 --- a/applications/main/subghz/views/receiver.c +++ b/applications/main/subghz/views/receiver.c @@ -69,7 +69,11 @@ typedef struct { SubGhzViewReceiverBarShow bar_show; SubGhzViewReceiverMode mode; uint8_t u_rssi; + + SubGhzRadioDeviceType device_type; + bool show_time; + bool nodraw; } SubGhzViewReceiverModel; @@ -220,6 +224,17 @@ void subghz_view_receiver_add_data_progress( 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); @@ -296,12 +311,14 @@ void subghz_view_receiver_draw(Canvas* canvas, SubGhzViewReceiverModel* model) { canvas_set_color(canvas, ColorBlack); if(model->history_item == 0) { + // TODO if(model->mode == SubGhzViewReceiverModeLive) { canvas_draw_icon( canvas, 0, 0, - furi_hal_subghz_get_radio_type() ? &I_Fishing_123x52 : &I_Scanning_123x52); + (model->device_type == SubGhzRadioDeviceTypeInternal) ? &I_Scanning_123x52 : + &I_Fishing_123x52); canvas_set_font(canvas, FontPrimary); canvas_draw_str(canvas, 63, 46, "Scanning..."); //canvas_draw_line(canvas, 46, 51, 125, 51); @@ -311,7 +328,8 @@ void subghz_view_receiver_draw(Canvas* canvas, SubGhzViewReceiverModel* model) { canvas, 0, 0, - furi_hal_subghz_get_radio_type() ? &I_Fishing_123x52 : &I_Scanning_123x52); + (model->device_type == SubGhzRadioDeviceTypeInternal) ? &I_Scanning_123x52 : + &I_Fishing_123x52); canvas_set_font(canvas, FontPrimary); canvas_draw_str(canvas, 63, 46, "Decoding..."); canvas_set_font(canvas, FontSecondary); diff --git a/applications/main/subghz/views/receiver.h b/applications/main/subghz/views/receiver.h index f239331d5..57718cfc4 100644 --- a/applications/main/subghz/views/receiver.h +++ b/applications/main/subghz/views/receiver.h @@ -33,6 +33,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_data_progress( SubGhzViewReceiver* subghz_receiver, const char* progress_str); diff --git a/applications/main/subghz/views/subghz_frequency_analyzer.c b/applications/main/subghz/views/subghz_frequency_analyzer.c index 30545d4b7..7800c9081 100644 --- a/applications/main/subghz/views/subghz_frequency_analyzer.c +++ b/applications/main/subghz/views/subghz_frequency_analyzer.c @@ -38,6 +38,7 @@ struct SubGhzFrequencyAnalyzer { SubGhzFrequencyAnalyzerWorker* worker; SubGhzFrequencyAnalyzerCallback callback; void* context; + SubGhzTxRx* txrx; bool locked; SubGHzFrequencyAnalyzerFeedbackLevel feedback_level; // 0 - no feedback, 1 - vibro only, 2 - vibro and sound @@ -60,6 +61,7 @@ typedef struct { uint8_t selected_index; uint8_t max_index; bool show_frame; + bool is_ext_radio; } SubGhzFrequencyAnalyzerModel; void subghz_frequency_analyzer_set_callback( @@ -166,7 +168,8 @@ void subghz_frequency_analyzer_draw(Canvas* canvas, SubGhzFrequencyAnalyzerModel // Title canvas_set_color(canvas, ColorBlack); canvas_set_font(canvas, FontSecondary); - canvas_draw_str(canvas, 0, 7, furi_hal_subghz_get_radio_type() ? "Ext" : "Int"); + + canvas_draw_str(canvas, 0, 7, model->is_ext_radio ? "Ext" : "Int"); canvas_draw_str(canvas, 20, 7, "Frequency Analyzer"); // RSSI @@ -311,7 +314,9 @@ bool subghz_frequency_analyzer_input(InputEvent* event, void* context) { uint32_t prev_freq_to_save = model->frequency_to_save; uint32_t frequency_candidate = model->history_frequency[model->selected_index]; if(frequency_candidate == 0 || - !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + // !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + !subghz_txrx_radio_device_is_frequecy_valid( + instance->txrx, frequency_candidate) || prev_freq_to_save == frequency_candidate) { frequency_candidate = 0; } else { @@ -333,7 +338,9 @@ bool subghz_frequency_analyzer_input(InputEvent* event, void* context) { uint32_t prev_freq_to_save = model->frequency_to_save; uint32_t frequency_candidate = subghz_frequency_find_correct(model->frequency); if(frequency_candidate == 0 || - !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + // !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + !subghz_txrx_radio_device_is_frequecy_valid( + instance->txrx, frequency_candidate) || prev_freq_to_save == frequency_candidate) { frequency_candidate = 0; } else { @@ -348,7 +355,9 @@ bool subghz_frequency_analyzer_input(InputEvent* event, void* context) { uint32_t prev_freq_to_save = model->frequency_to_save; uint32_t frequency_candidate = subghz_frequency_find_correct(model->frequency); if(frequency_candidate == 0 || - !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + // !furi_hal_subghz_is_frequency_valid(frequency_candidate) || + !subghz_txrx_radio_device_is_frequecy_valid( + instance->txrx, frequency_candidate) || prev_freq_to_save == frequency_candidate) { frequency_candidate = 0; } else { @@ -539,7 +548,7 @@ void subghz_frequency_analyzer_enter(void* context) { (SubGhzFrequencyAnalyzerWorkerPairCallback)subghz_frequency_analyzer_pair_callback, instance); - subghz_frequency_analyzer_worker_start(instance->worker); + subghz_frequency_analyzer_worker_start(instance->worker, instance->txrx); instance->rssi_last = 0; instance->selected_index = 0; @@ -567,6 +576,8 @@ void subghz_frequency_analyzer_enter(void* context) { model->history_frequency_rx_count[0] = 0; model->frequency_to_save = 0; model->trigger = RSSI_MIN; + model->is_ext_radio = + (subghz_txrx_radio_device_get(instance->txrx) != SubGhzRadioDeviceTypeInternal); }, true); } @@ -584,7 +595,7 @@ void subghz_frequency_analyzer_exit(void* context) { furi_record_close(RECORD_NOTIFICATION); } -SubGhzFrequencyAnalyzer* subghz_frequency_analyzer_alloc() { +SubGhzFrequencyAnalyzer* subghz_frequency_analyzer_alloc(SubGhzTxRx* txrx) { SubGhzFrequencyAnalyzer* instance = malloc(sizeof(SubGhzFrequencyAnalyzer)); instance->feedback_level = 2; @@ -599,6 +610,8 @@ SubGhzFrequencyAnalyzer* subghz_frequency_analyzer_alloc() { view_set_enter_callback(instance->view, subghz_frequency_analyzer_enter); view_set_exit_callback(instance->view, subghz_frequency_analyzer_exit); + instance->txrx = txrx; + return instance; } diff --git a/applications/main/subghz/views/subghz_frequency_analyzer.h b/applications/main/subghz/views/subghz_frequency_analyzer.h index 95169c08d..f8c643222 100644 --- a/applications/main/subghz/views/subghz_frequency_analyzer.h +++ b/applications/main/subghz/views/subghz_frequency_analyzer.h @@ -2,6 +2,7 @@ #include #include "../helpers/subghz_custom_event.h" +#include "../helpers/subghz_txrx.h" typedef enum { SubGHzFrequencyAnalyzerFeedbackLevelAll, @@ -18,7 +19,7 @@ void subghz_frequency_analyzer_set_callback( SubGhzFrequencyAnalyzerCallback callback, void* context); -SubGhzFrequencyAnalyzer* subghz_frequency_analyzer_alloc(); +SubGhzFrequencyAnalyzer* subghz_frequency_analyzer_alloc(SubGhzTxRx* txrx); void subghz_frequency_analyzer_free(SubGhzFrequencyAnalyzer* subghz_static); diff --git a/applications/main/subghz/views/subghz_read_raw.c b/applications/main/subghz/views/subghz_read_raw.c index 7676c527d..2a10e9d2e 100644 --- a/applications/main/subghz/views/subghz_read_raw.c +++ b/applications/main/subghz/views/subghz_read_raw.c @@ -11,6 +11,29 @@ #define SUBGHZ_READ_RAW_RSSI_HISTORY_SIZE 100 #define TAG "SubGhzReadRAW" +struct SubGhzReadRAW { + View* view; + SubGhzReadRAWCallback callback; + void* context; +}; + +typedef struct { + FuriString* frequency_str; + FuriString* preset_str; + FuriString* sample_write; + FuriString* file_name; + uint8_t* rssi_history; + uint8_t rssi_current; + bool rssi_history_end; + uint8_t ind_write; + uint8_t ind_sin; + SubGhzReadRAWStatus status; + bool raw_send_only; + float raw_threshold_rssi; + bool not_showing_samples; + SubGhzRadioDeviceType device_type; +} SubGhzReadRAWModel; + void subghz_read_raw_set_callback( SubGhzReadRAW* subghz_read_raw, SubGhzReadRAWCallback callback, @@ -266,9 +289,15 @@ void subghz_read_raw_draw(Canvas* canvas, SubGhzReadRAWModel* model) { canvas_draw_str(canvas, 35, 7, furi_string_get_cstr(model->preset_str)); if(model->not_showing_samples) { - canvas_draw_str(canvas, 77, 7, furi_hal_subghz_get_radio_type() ? "R: Ext" : "R: Int"); + // TODO + canvas_draw_str( + canvas, + 77, + 7, + (model->device_type == SubGhzRadioDeviceTypeInternal) ? "R: Int" : "R: Ext"); } else { - canvas_draw_str(canvas, 70, 7, furi_hal_subghz_get_radio_type() ? "E" : "I"); + canvas_draw_str( + canvas, 70, 7, (model->device_type == SubGhzRadioDeviceTypeInternal) ? "I" : "E"); } canvas_draw_str_aligned( diff --git a/applications/main/subghz/views/transmitter.c b/applications/main/subghz/views/transmitter.c index b035e53ae..d555b2244 100644 --- a/applications/main/subghz/views/transmitter.c +++ b/applications/main/subghz/views/transmitter.c @@ -6,6 +6,22 @@ #include +struct SubGhzViewTransmitter { + View* view; + SubGhzViewTransmitterCallback callback; + void* context; +}; + +typedef struct { + FuriString* frequency_str; + FuriString* preset_str; + FuriString* key_str; + bool show_button; + SubGhzRadioDeviceType device_type; + FuriString* temp_button_id; + bool draw_temp_button; +} SubGhzViewTransmitterModel; + void subghz_view_transmitter_set_callback( SubGhzViewTransmitter* subghz_transmitter, SubGhzViewTransmitterCallback callback, @@ -85,7 +101,12 @@ void subghz_view_transmitter_draw(Canvas* canvas, SubGhzViewTransmitterModel* mo } if(model->show_button) { - canvas_draw_str(canvas, 58, 62, furi_hal_subghz_get_radio_type() ? "R: Ext" : "R: Int"); + // TODO + canvas_draw_str( + canvas, + 58, + 62, + (model->device_type == SubGhzRadioDeviceTypeInternal) ? "R: Int" : "R: Ext"); subghz_view_transmitter_button_right(canvas, "Send"); } } diff --git a/applications/main/u2f/application.fam b/applications/main/u2f/application.fam index 6b32e0225..8167e6277 100644 --- a/applications/main/u2f/application.fam +++ b/applications/main/u2f/application.fam @@ -1,14 +1,12 @@ App( appid="u2f", name="U2F", - apptype=FlipperAppType.APP, + apptype=FlipperAppType.MENUEXTERNAL, entry_point="u2f_app", - cdefines=["APP_U2F"], - requires=[ - "gui", - "dialogs", - ], stack_size=2 * 1024, icon="A_U2F_14", order=80, + fap_libs=["assets"], + fap_category="USB", + fap_icon="icon.png", ) diff --git a/applications/main/u2f/icon.png b/applications/main/u2f/icon.png new file mode 100644 index 000000000..fcd87a2ef Binary files /dev/null and b/applications/main/u2f/icon.png differ diff --git a/applications/services/applications.h b/applications/services/applications.h index 45b050a06..426d6d2d2 100644 --- a/applications/services/applications.h +++ b/applications/services/applications.h @@ -17,6 +17,12 @@ typedef struct { const FlipperInternalApplicationFlag flags; } FlipperInternalApplication; +typedef struct { + const char* name; + const Icon* icon; + const char* path; +} FlipperExternalApplication; + typedef void (*FlipperInternalOnStartHook)(void); extern const char* FLIPPER_AUTORUN_APP_NAME; @@ -52,3 +58,9 @@ extern const FlipperInternalApplication FLIPPER_ARCHIVE; */ extern const FlipperInternalApplication FLIPPER_SETTINGS_APPS[]; extern const size_t FLIPPER_SETTINGS_APPS_COUNT; + +/* External Menu Apps list + * Spawned by loader + */ +extern const FlipperExternalApplication FLIPPER_EXTERNAL_APPS[]; +extern const size_t FLIPPER_EXTERNAL_APPS_COUNT; diff --git a/applications/services/cli/cli_commands.c b/applications/services/cli/cli_commands.c index fc71aa31f..42ff5e195 100644 --- a/applications/services/cli/cli_commands.c +++ b/applications/services/cli/cli_commands.c @@ -175,24 +175,23 @@ void cli_command_log_tx_callback(const uint8_t* buffer, size_t size, void* conte furi_stream_buffer_send(context, buffer, size, 0); } -void cli_command_log_level_set_from_string(FuriString* level) { - if(furi_string_cmpi_str(level, "default") == 0) { - furi_log_set_level(FuriLogLevelDefault); - } else if(furi_string_cmpi_str(level, "none") == 0) { - furi_log_set_level(FuriLogLevelNone); - } else if(furi_string_cmpi_str(level, "error") == 0) { - furi_log_set_level(FuriLogLevelError); - } else if(furi_string_cmpi_str(level, "warn") == 0) { - furi_log_set_level(FuriLogLevelWarn); - } else if(furi_string_cmpi_str(level, "info") == 0) { - furi_log_set_level(FuriLogLevelInfo); - } else if(furi_string_cmpi_str(level, "debug") == 0) { - furi_log_set_level(FuriLogLevelDebug); - } else if(furi_string_cmpi_str(level, "trace") == 0) { - furi_log_set_level(FuriLogLevelTrace); +bool cli_command_log_level_set_from_string(FuriString* level) { + FuriLogLevel log_level; + if(furi_log_level_from_string(furi_string_get_cstr(level), &log_level)) { + furi_log_set_level(log_level); + return true; } else { - printf("Unknown log level\r\n"); + printf(" — start logging using the current level from the system settings\r\n"); + printf(" — only critical errors and other important messages\r\n"); + printf(" — non-critical errors and warnings including \r\n"); + printf(" — non-critical information including \r\n"); + printf(" — the default system log level (equivalent to )\r\n"); + printf( + " — debug information including (may impact system performance)\r\n"); + printf( + " — system traces including (may impact system performance)\r\n"); } + return false; } void cli_command_log(Cli* cli, FuriString* args, void* context) { @@ -203,12 +202,20 @@ void cli_command_log(Cli* cli, FuriString* args, void* context) { bool restore_log_level = false; if(furi_string_size(args) > 0) { - cli_command_log_level_set_from_string(args); + if(!cli_command_log_level_set_from_string(args)) { + furi_stream_buffer_free(ring); + return; + } restore_log_level = true; } + const char* current_level; + furi_log_level_to_string(furi_log_get_level(), ¤t_level); + printf("Current log level: %s\r\n", current_level); + furi_hal_console_set_tx_callback(cli_command_log_tx_callback, ring); + printf("Use to list available log levels\r\n"); printf("Press CTRL+C to stop...\r\n"); while(!cli_cmd_interrupt_received(cli)) { size_t ret = furi_stream_buffer_receive(ring, buffer, CLI_COMMAND_LOG_BUFFER_SIZE, 50); diff --git a/applications/services/loader/loader.c b/applications/services/loader/loader.c index f3c606fa0..74da6728c 100644 --- a/applications/services/loader/loader.c +++ b/applications/services/loader/loader.c @@ -245,6 +245,16 @@ static const FlipperInternalApplication* loader_find_application_by_name(const c return application; } +static const char* loader_find_external_application_by_name(const char* app_name) { + for(size_t i = 0; i < FLIPPER_EXTERNAL_APPS_COUNT; i++) { + if(strcmp(FLIPPER_EXTERNAL_APPS[i].name, app_name) == 0) { + return FLIPPER_EXTERNAL_APPS[i].path; + } + } + + return NULL; +} + static void loader_start_app_thread(Loader* loader, FlipperInternalApplicationFlag flags) { // setup heap trace FuriHalRtcHeapTrackMode mode = furi_hal_rtc_get_heap_track_mode(); @@ -493,6 +503,14 @@ static LoaderStatus loader_do_start_by_name( break; } + // check External Applications + { + const char* path = loader_find_external_application_by_name(name); + if(path) { + name = path; + } + } + // check external apps { Storage* storage = furi_record_open(RECORD_STORAGE); diff --git a/applications/services/loader/loader_applications.c b/applications/services/loader/loader_applications.c index 1801edef9..7bf189e55 100644 --- a/applications/services/loader/loader_applications.c +++ b/applications/services/loader/loader_applications.c @@ -38,6 +38,11 @@ typedef struct { FuriString* fap_path; DialogsApp* dialogs; Storage* storage; + Loader* loader; + + Gui* gui; + ViewHolder* view_holder; + Loading* loading; } LoaderApplicationsApp; static LoaderApplicationsApp* loader_applications_app_alloc() { @@ -45,15 +50,30 @@ static LoaderApplicationsApp* loader_applications_app_alloc() { app->fap_path = furi_string_alloc_set(EXT_PATH("apps")); app->dialogs = furi_record_open(RECORD_DIALOGS); app->storage = furi_record_open(RECORD_STORAGE); + app->loader = furi_record_open(RECORD_LOADER); + + app->gui = furi_record_open(RECORD_GUI); + app->view_holder = view_holder_alloc(); + app->loading = loading_alloc(); + + view_holder_attach_to_gui(app->view_holder, app->gui); + view_holder_set_view(app->view_holder, loading_get_view(app->loading)); + return app; } //-V773 -static void loader_applications_app_free(LoaderApplicationsApp* loader_applications_app) { - furi_assert(loader_applications_app); +static void loader_applications_app_free(LoaderApplicationsApp* app) { + furi_assert(app); + + view_holder_free(app->view_holder); + loading_free(app->loading); + furi_record_close(RECORD_GUI); + + furi_record_close(RECORD_LOADER); furi_record_close(RECORD_DIALOGS); furi_record_close(RECORD_STORAGE); - furi_string_free(loader_applications_app->fap_path); - free(loader_applications_app); + furi_string_free(app->fap_path); + free(app); } static bool loader_applications_item_callback( @@ -96,47 +116,38 @@ static void loader_pubsub_callback(const void* message, void* context) { } } -static void loader_applications_start_app(const char* name) { - // start loading animation - Gui* gui = furi_record_open(RECORD_GUI); - ViewHolder* view_holder = view_holder_alloc(); - Loading* loading = loading_alloc(); - - view_holder_attach_to_gui(view_holder, gui); - view_holder_set_view(view_holder, loading_get_view(loading)); - view_holder_start(view_holder); +static void loader_applications_start_app(LoaderApplicationsApp* app) { + const char* name = furi_string_get_cstr(app->fap_path); // load app FuriThreadId thread_id = furi_thread_get_current_id(); - Loader* loader = furi_record_open(RECORD_LOADER); FuriPubSubSubscription* subscription = - furi_pubsub_subscribe(loader_get_pubsub(loader), loader_pubsub_callback, thread_id); + furi_pubsub_subscribe(loader_get_pubsub(app->loader), loader_pubsub_callback, thread_id); - LoaderStatus status = loader_start_with_gui_error(loader, name, NULL); + LoaderStatus status = loader_start_with_gui_error(app->loader, name, NULL); if(status == LoaderStatusOk) { furi_thread_flags_wait(APPLICATION_STOP_EVENT, FuriFlagWaitAny, FuriWaitForever); } - furi_pubsub_unsubscribe(loader_get_pubsub(loader), subscription); - furi_record_close(RECORD_LOADER); - - // stop loading animation - view_holder_stop(view_holder); - view_holder_free(view_holder); - loading_free(loading); - furi_record_close(RECORD_GUI); + furi_pubsub_unsubscribe(loader_get_pubsub(app->loader), subscription); } static int32_t loader_applications_thread(void* p) { LoaderApplications* loader_applications = p; - LoaderApplicationsApp* loader_applications_app = loader_applications_app_alloc(); + LoaderApplicationsApp* app = loader_applications_app_alloc(); - while(loader_applications_select_app(loader_applications_app)) { - loader_applications_start_app(furi_string_get_cstr(loader_applications_app->fap_path)); + // start loading animation + view_holder_start(app->view_holder); + + while(loader_applications_select_app(app)) { + loader_applications_start_app(app); } - loader_applications_app_free(loader_applications_app); + // stop loading animation + view_holder_stop(app->view_holder); + + loader_applications_app_free(app); if(loader_applications->closed_cb) { loader_applications->closed_cb(loader_applications->context); diff --git a/applications/services/loader/loader_menu.c b/applications/services/loader/loader_menu.c index de063083c..279efe904 100644 --- a/applications/services/loader/loader_menu.c +++ b/applications/services/loader/loader_menu.c @@ -56,12 +56,18 @@ static void loader_menu_start(const char* name) { furi_record_close(RECORD_LOADER); } -static void loader_menu_callback(void* context, uint32_t index) { +static void loader_menu_apps_callback(void* context, uint32_t index) { UNUSED(context); const char* name_or_path = (const char*)index; loader_menu_start(name_or_path); } +static void loader_menu_external_apps_callback(void* context, uint32_t index) { + UNUSED(context); + const char* path = FLIPPER_EXTERNAL_APPS[index].path; + loader_menu_start(path); +} + static void loader_menu_applications_callback(void* context, uint32_t index) { UNUSED(index); UNUSED(context); @@ -92,20 +98,14 @@ static uint32_t loader_menu_exit(void* context) { } static void loader_menu_build_menu(LoaderMenuApp* app, LoaderMenu* menu) { - menu_add_item( - app->primary_menu, - LOADER_APPLICATIONS_NAME, - &A_Plugins_14, - 0, - loader_menu_applications_callback, - (void*)menu); - for(size_t i = 0; i < FLIPPER_APPS_COUNT; i++) { + size_t i; + for(i = 0; i < FLIPPER_APPS_COUNT; i++) { menu_add_item( app->primary_menu, FLIPPER_APPS[i].name, FLIPPER_APPS[i].icon, - (uint32_t)FLIPPER_APPS[i].name, - loader_menu_callback, + i, + loader_menu_apps_callback, (void*)menu); } menu_add_item( diff --git a/applications/settings/about/about.c b/applications/settings/about/about.c index b7ebbd159..5e2fe6432 100644 --- a/applications/settings/about/about.c +++ b/applications/settings/about/about.c @@ -82,7 +82,9 @@ static DialogMessageButton icon1_screen(DialogsApp* dialogs, DialogMessage* mess static DialogMessageButton icon2_screen(DialogsApp* dialogs, DialogMessage* message) { DialogMessageButton result; - dialog_message_set_icon(message, &I_Certification2_98x33, 15, 10); + dialog_message_set_icon(message, &I_Certification2_46x33, 15, 10); + dialog_message_set_text( + message, furi_hal_version_get_mic_id(), 63, 27, AlignLeft, AlignCenter); result = dialog_message_show(dialogs, message); dialog_message_set_icon(message, NULL, 0, 0); diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_0.png b/assets/dolphin/external/L1_My_dude_128x64/frame_0.png new file mode 100644 index 000000000..bf07d03d6 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_0.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_1.png b/assets/dolphin/external/L1_My_dude_128x64/frame_1.png new file mode 100644 index 000000000..4402654c7 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_1.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_10.png b/assets/dolphin/external/L1_My_dude_128x64/frame_10.png new file mode 100644 index 000000000..10dabe4c5 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_10.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_11.png b/assets/dolphin/external/L1_My_dude_128x64/frame_11.png new file mode 100644 index 000000000..878712fe2 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_11.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_12.png b/assets/dolphin/external/L1_My_dude_128x64/frame_12.png new file mode 100644 index 000000000..19fc985ac Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_12.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_13.png b/assets/dolphin/external/L1_My_dude_128x64/frame_13.png new file mode 100644 index 000000000..39172f26f Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_13.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_14.png b/assets/dolphin/external/L1_My_dude_128x64/frame_14.png new file mode 100644 index 000000000..9a3a84fff Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_14.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_15.png b/assets/dolphin/external/L1_My_dude_128x64/frame_15.png new file mode 100644 index 000000000..2472c2729 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_15.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_16.png b/assets/dolphin/external/L1_My_dude_128x64/frame_16.png new file mode 100644 index 000000000..4940aef67 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_16.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_17.png b/assets/dolphin/external/L1_My_dude_128x64/frame_17.png new file mode 100644 index 000000000..fd910ce5a Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_17.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_18.png b/assets/dolphin/external/L1_My_dude_128x64/frame_18.png new file mode 100644 index 000000000..ed33f18a7 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_18.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_19.png b/assets/dolphin/external/L1_My_dude_128x64/frame_19.png new file mode 100644 index 000000000..d602a01d5 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_19.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_2.png b/assets/dolphin/external/L1_My_dude_128x64/frame_2.png new file mode 100644 index 000000000..b680b4ae0 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_2.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_20.png b/assets/dolphin/external/L1_My_dude_128x64/frame_20.png new file mode 100644 index 000000000..2dfa931f2 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_20.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_21.png b/assets/dolphin/external/L1_My_dude_128x64/frame_21.png new file mode 100644 index 000000000..272064d90 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_21.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_22.png b/assets/dolphin/external/L1_My_dude_128x64/frame_22.png new file mode 100644 index 000000000..35d0149ad Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_22.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_23.png b/assets/dolphin/external/L1_My_dude_128x64/frame_23.png new file mode 100644 index 000000000..83d02ef88 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_23.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_24.png b/assets/dolphin/external/L1_My_dude_128x64/frame_24.png new file mode 100644 index 000000000..f3ac44178 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_24.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_25.png b/assets/dolphin/external/L1_My_dude_128x64/frame_25.png new file mode 100644 index 000000000..832c2bde9 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_25.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_26.png b/assets/dolphin/external/L1_My_dude_128x64/frame_26.png new file mode 100644 index 000000000..3836a3b01 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_26.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_27.png b/assets/dolphin/external/L1_My_dude_128x64/frame_27.png new file mode 100644 index 000000000..ff621b73e Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_27.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_28.png b/assets/dolphin/external/L1_My_dude_128x64/frame_28.png new file mode 100644 index 000000000..94e05f94d Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_28.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_29.png b/assets/dolphin/external/L1_My_dude_128x64/frame_29.png new file mode 100644 index 000000000..1ce384b16 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_29.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_3.png b/assets/dolphin/external/L1_My_dude_128x64/frame_3.png new file mode 100644 index 000000000..a5056eb4b Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_3.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_30.png b/assets/dolphin/external/L1_My_dude_128x64/frame_30.png new file mode 100644 index 000000000..8d42b8b48 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_30.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_31.png b/assets/dolphin/external/L1_My_dude_128x64/frame_31.png new file mode 100644 index 000000000..ac926d7be Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_31.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_32.png b/assets/dolphin/external/L1_My_dude_128x64/frame_32.png new file mode 100644 index 000000000..35070eb6b Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_32.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_33.png b/assets/dolphin/external/L1_My_dude_128x64/frame_33.png new file mode 100644 index 000000000..a6c973f67 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_33.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_34.png b/assets/dolphin/external/L1_My_dude_128x64/frame_34.png new file mode 100644 index 000000000..3f9407f38 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_34.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_35.png b/assets/dolphin/external/L1_My_dude_128x64/frame_35.png new file mode 100644 index 000000000..6059e00d5 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_35.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_36.png b/assets/dolphin/external/L1_My_dude_128x64/frame_36.png new file mode 100644 index 000000000..d2cd0c970 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_36.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_37.png b/assets/dolphin/external/L1_My_dude_128x64/frame_37.png new file mode 100644 index 000000000..e60fd08de Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_37.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_38.png b/assets/dolphin/external/L1_My_dude_128x64/frame_38.png new file mode 100644 index 000000000..70e56b168 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_38.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_39.png b/assets/dolphin/external/L1_My_dude_128x64/frame_39.png new file mode 100644 index 000000000..450b4d4f6 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_39.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_4.png b/assets/dolphin/external/L1_My_dude_128x64/frame_4.png new file mode 100644 index 000000000..2d9f4e963 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_4.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_40.png b/assets/dolphin/external/L1_My_dude_128x64/frame_40.png new file mode 100644 index 000000000..369200345 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_40.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_41.png b/assets/dolphin/external/L1_My_dude_128x64/frame_41.png new file mode 100644 index 000000000..e0f882268 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_41.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_42.png b/assets/dolphin/external/L1_My_dude_128x64/frame_42.png new file mode 100644 index 000000000..a8a23536a Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_42.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_43.png b/assets/dolphin/external/L1_My_dude_128x64/frame_43.png new file mode 100644 index 000000000..6a402b350 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_43.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_44.png b/assets/dolphin/external/L1_My_dude_128x64/frame_44.png new file mode 100644 index 000000000..f425bcc17 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_44.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_45.png b/assets/dolphin/external/L1_My_dude_128x64/frame_45.png new file mode 100644 index 000000000..b0ea1a7e7 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_45.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_46.png b/assets/dolphin/external/L1_My_dude_128x64/frame_46.png new file mode 100644 index 000000000..3113ff2e6 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_46.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_47.png b/assets/dolphin/external/L1_My_dude_128x64/frame_47.png new file mode 100644 index 000000000..87403c610 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_47.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_48.png b/assets/dolphin/external/L1_My_dude_128x64/frame_48.png new file mode 100644 index 000000000..2734e2fcd Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_48.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_5.png b/assets/dolphin/external/L1_My_dude_128x64/frame_5.png new file mode 100644 index 000000000..df2255949 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_5.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_6.png b/assets/dolphin/external/L1_My_dude_128x64/frame_6.png new file mode 100644 index 000000000..4c00552ea Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_6.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_7.png b/assets/dolphin/external/L1_My_dude_128x64/frame_7.png new file mode 100644 index 000000000..970380940 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_7.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_8.png b/assets/dolphin/external/L1_My_dude_128x64/frame_8.png new file mode 100644 index 000000000..86e41e913 Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_8.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/frame_9.png b/assets/dolphin/external/L1_My_dude_128x64/frame_9.png new file mode 100644 index 000000000..4334eefaf Binary files /dev/null and b/assets/dolphin/external/L1_My_dude_128x64/frame_9.png differ diff --git a/assets/dolphin/external/L1_My_dude_128x64/meta.txt b/assets/dolphin/external/L1_My_dude_128x64/meta.txt new file mode 100644 index 000000000..8c326cf42 --- /dev/null +++ b/assets/dolphin/external/L1_My_dude_128x64/meta.txt @@ -0,0 +1,32 @@ +Filetype: Flipper Animation +Version: 1 + +Width: 128 +Height: 64 +Passive frames: 19 +Active frames: 51 +Frames order: 0 1 2 3 4 5 6 0 1 2 7 8 9 10 11 12 7 8 9 13 14 15 14 13 14 15 7 8 9 16 17 18 13 14 19 20 21 22 23 24 21 25 26 27 28 29 30 31 32 33 32 34 35 36 35 34 37 38 39 40 41 42 43 44 45 46 17 47 48 7 +Active cycles: 1 +Frame rate: 2 +Duration: 3600 +Active cooldown: 7 + +Bubble slots: 1 + +Slot: 0 +X: 41 +Y: 43 +Text: My dude +AlignH: Right +AlignV: Top +StartFrame: 50 +EndFrame: 50 + +Slot: 0 +X: 59 +Y: 43 +Text: My dude +AlignH: Left +AlignV: Top +StartFrame: 54 +EndFrame: 54 \ No newline at end of file diff --git a/assets/dolphin/external/manifest.txt b/assets/dolphin/external/manifest.txt index 24dd8ab9d..297c04a20 100644 --- a/assets/dolphin/external/manifest.txt +++ b/assets/dolphin/external/manifest.txt @@ -99,6 +99,13 @@ Min level: 13 Max level: 30 Weight: 4 +Name: L1_My_dude_128x64 +Min butthurt: 0 +Max butthurt: 14 +Min level: 17 +Max level: 30 +Weight: 4 + Name: L2_Wake_up_128x64 Min butthurt: 0 Max butthurt: 14 diff --git a/assets/icons/About/Certification2_46x33.png b/assets/icons/About/Certification2_46x33.png new file mode 100644 index 000000000..d421b8291 Binary files /dev/null and b/assets/icons/About/Certification2_46x33.png differ diff --git a/assets/icons/About/Certification2_98x33.png b/assets/icons/About/Certification2_98x33.png deleted file mode 100644 index 49c5581c7..000000000 Binary files a/assets/icons/About/Certification2_98x33.png and /dev/null differ 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/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 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/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 +# diff --git a/fbt_options.py b/fbt_options.py index 2cd82501d..efafce09d 100644 --- a/fbt_options.py +++ b/fbt_options.py @@ -77,22 +77,6 @@ FIRMWARE_APPS = { "updater_app", "unit_tests", ], - "debug_pack": [ - # Svc - "basic_services", - # Apps - "main_apps", - "system_apps", - # Settings - "settings_apps", - # Plugins - # "basic_plugins", - # Debug - # "debug_apps", - # "updater_app", - # "unit_tests", - # "nfc", - ], } FIRMWARE_APP_SET = "default" diff --git a/firmware/targets/f18/api_symbols.csv b/firmware/targets/f18/api_symbols.csv index a689d5a21..12229e5b8 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,+,34.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,, @@ -288,12 +289,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 @@ -306,6 +313,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" @@ -458,6 +468,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" @@ -473,11 +489,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* @@ -570,6 +601,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* @@ -590,6 +627,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* @@ -659,6 +705,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" @@ -686,10 +734,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* @@ -734,6 +805,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*" @@ -811,10 +885,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*, ..." @@ -827,6 +916,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" @@ -1029,12 +1121,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, @@ -1169,6 +1262,7 @@ Function,+,furi_hal_version_get_hw_target,uint8_t, Function,+,furi_hal_version_get_hw_timestamp,uint32_t, Function,+,furi_hal_version_get_hw_version,uint8_t, Function,+,furi_hal_version_get_ic_id,const char*, +Function,+,furi_hal_version_get_mic_id,const char*, Function,+,furi_hal_version_get_model_code,const char*, Function,+,furi_hal_version_get_model_name,const char*, Function,+,furi_hal_version_get_name_ptr,const char*, @@ -1186,6 +1280,8 @@ Function,+,furi_kernel_restore_lock,int32_t,int32_t Function,+,furi_kernel_unlock,int32_t, Function,+,furi_log_get_level,FuriLogLevel, Function,-,furi_log_init,void, +Function,+,furi_log_level_from_string,_Bool,"const char*, FuriLogLevel*" +Function,+,furi_log_level_to_string,_Bool,"FuriLogLevel, const char**" Function,+,furi_log_print_format,void,"FuriLogLevel, const char*, const char*, ..." Function,+,furi_log_print_raw_format,void,"FuriLogLevel, const char*, ..." Function,+,furi_log_set_level,void,FuriLogLevel @@ -1336,6 +1432,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, @@ -1368,6 +1468,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* @@ -1379,7 +1482,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 @@ -1399,8 +1507,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 @@ -1412,13 +1524,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* @@ -1441,7 +1573,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*" @@ -1519,6 +1672,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* @@ -1532,6 +1688,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*" @@ -1599,12 +1767,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, ..." @@ -1662,11 +1835,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* @@ -1691,6 +1876,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* @@ -1730,11 +1921,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 @@ -1889,6 +2091,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* @@ -1921,6 +2129,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" @@ -1932,6 +2143,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" @@ -2164,6 +2378,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/f18/furi_hal/furi_hal_version_device.c b/firmware/targets/f18/furi_hal/furi_hal_version_device.c index 1b5090b93..e038b98d7 100644 --- a/firmware/targets/f18/furi_hal/furi_hal_version_device.c +++ b/firmware/targets/f18/furi_hal/furi_hal_version_device.c @@ -5,17 +5,21 @@ bool furi_hal_version_do_i_belong_here() { } const char* furi_hal_version_get_model_name() { - return "Komi"; + return "Flipper Nano"; } const char* furi_hal_version_get_model_code() { - return "N/A"; + return "FN.1"; } const char* furi_hal_version_get_fcc_id() { - return "N/A"; + return "Pending"; } const char* furi_hal_version_get_ic_id() { - return "N/A"; + return "Pending"; +} + +const char* furi_hal_version_get_mic_id() { + return "Pending"; } diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index a81793f5b..2e372506f 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,+,34.1,, Header,+,applications/main/archive/helpers/favorite_timeout.h,, Header,+,applications/main/subghz/helpers/subghz_txrx.h,, Header,+,applications/services/bt/bt_service/bt.h,, @@ -65,6 +65,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,, @@ -152,7 +153,12 @@ Header,+,lib/mlib/m-rbtree.h,, Header,+,lib/mlib/m-tuple.h,, Header,+,lib/mlib/m-variant.h,, Header,+,lib/music_worker/music_worker.h,, +Header,+,lib/nfc/helpers/mfkey32.h,, +Header,+,lib/nfc/helpers/nfc_generators.h,, Header,+,lib/nfc/nfc_device.h,, +Header,+,lib/nfc/nfc_types.h,, +Header,+,lib/nfc/nfc_worker.h,, +Header,+,lib/nfc/parsers/nfc_supported_card.h,, Header,+,lib/nfc/protocols/nfc_util.h,, Header,+,lib/one_wire/maxim_crc.h,, Header,+,lib/one_wire/one_wire_host.h,, @@ -196,6 +202,7 @@ Header,+,lib/subghz/environment.h,, Header,+,lib/subghz/protocols/raw.h,, Header,+,lib/subghz/receiver.h,, Header,+,lib/subghz/registry.h,, +Header,+,lib/subghz/subghz_file_encoder_worker.h,, Header,+,lib/subghz/subghz_protocol_registry.h,, Header,+,lib/subghz/subghz_setting.h,, Header,+,lib/subghz/subghz_tx_rx_worker.h,, @@ -1332,12 +1339,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, @@ -1458,26 +1466,20 @@ Function,-,furi_hal_spi_config_init,void, Function,-,furi_hal_spi_config_init_early,void, Function,-,furi_hal_spi_dma_init,void, Function,+,furi_hal_spi_release,void,FuriHalSpiBusHandle* -Function,+,furi_hal_subghz_check_radio,_Bool, -Function,+,furi_hal_subghz_disable_ext_power,void, Function,-,furi_hal_subghz_dump_state,void, -Function,+,furi_hal_subghz_enable_ext_power,_Bool, Function,+,furi_hal_subghz_flush_rx,void, Function,+,furi_hal_subghz_flush_tx,void, -Function,+,furi_hal_subghz_get_external_power_disable,_Bool, +Function,+,furi_hal_subghz_get_data_gpio,const GpioPin*, Function,+,furi_hal_subghz_get_lqi,uint8_t, -Function,+,furi_hal_subghz_get_radio_type,SubGhzRadioType, Function,+,furi_hal_subghz_get_rolling_counter_mult,uint8_t, Function,+,furi_hal_subghz_get_rssi,float, Function,+,furi_hal_subghz_idle,void, Function,-,furi_hal_subghz_init,void, -Function,-,furi_hal_subghz_init_check,_Bool, -Function,+,furi_hal_subghz_init_radio_type,_Bool,SubGhzRadioType 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_is_tx_allowed,_Bool,uint32_t -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* @@ -1485,14 +1487,12 @@ Function,+,furi_hal_subghz_read_packet,void,"uint8_t*, uint8_t*" Function,+,furi_hal_subghz_reset,void, Function,+,furi_hal_subghz_rx,void, Function,+,furi_hal_subghz_rx_pipe_not_empty,_Bool, -Function,+,furi_hal_subghz_select_radio_type,void,SubGhzRadioType Function,+,furi_hal_subghz_set_async_mirror_pin,void,const GpioPin* -Function,+,furi_hal_subghz_set_external_power_disable,void,_Bool 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_rolling_counter_mult,void,uint8_t -Function,-,furi_hal_subghz_shutdown,void, +Function,+,furi_hal_subghz_set_rolling_counter_mult,void,uint8_t +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*" @@ -1537,6 +1537,7 @@ Function,+,furi_hal_version_get_hw_target,uint8_t, Function,+,furi_hal_version_get_hw_timestamp,uint32_t, Function,+,furi_hal_version_get_hw_version,uint8_t, Function,+,furi_hal_version_get_ic_id,const char*, +Function,+,furi_hal_version_get_mic_id,const char*, Function,+,furi_hal_version_get_model_code,const char*, Function,+,furi_hal_version_get_model_name,const char*, Function,+,furi_hal_version_get_name_ptr,const char*, @@ -1556,6 +1557,8 @@ Function,+,furi_kernel_restore_lock,int32_t,int32_t Function,+,furi_kernel_unlock,int32_t, Function,+,furi_log_get_level,FuriLogLevel, Function,-,furi_log_init,void, +Function,+,furi_log_level_from_string,_Bool,"const char*, FuriLogLevel*" +Function,+,furi_log_level_to_string,_Bool,"FuriLogLevel, const char**" Function,+,furi_log_print_format,void,"FuriLogLevel, const char*, const char*, ..." Function,+,furi_log_print_raw_format,void,"FuriLogLevel, const char*, ..." Function,+,furi_log_set_level,void,FuriLogLevel @@ -2051,40 +2054,40 @@ Function,-,mf_classic_authenticate,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint6 Function,-,mf_classic_authenticate_skip_activate,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint64_t, MfClassicKey, _Bool, uint32_t" Function,-,mf_classic_block_to_value,_Bool,"const uint8_t*, int32_t*, uint8_t*" Function,-,mf_classic_check_card_type,_Bool,FuriHalNfcADevData* -Function,-,mf_classic_dict_add_key,_Bool,"MfClassicDict*, uint8_t*" +Function,+,mf_classic_dict_add_key,_Bool,"MfClassicDict*, uint8_t*" Function,-,mf_classic_dict_add_key_str,_Bool,"MfClassicDict*, FuriString*" -Function,-,mf_classic_dict_alloc,MfClassicDict*,MfClassicDictType -Function,-,mf_classic_dict_check_presence,_Bool,MfClassicDictType -Function,-,mf_classic_dict_delete_index,_Bool,"MfClassicDict*, uint32_t" +Function,+,mf_classic_dict_alloc,MfClassicDict*,MfClassicDictType +Function,+,mf_classic_dict_check_presence,_Bool,MfClassicDictType +Function,+,mf_classic_dict_delete_index,_Bool,"MfClassicDict*, uint32_t" Function,-,mf_classic_dict_find_index,_Bool,"MfClassicDict*, uint8_t*, uint32_t*" Function,-,mf_classic_dict_find_index_str,_Bool,"MfClassicDict*, FuriString*, uint32_t*" -Function,-,mf_classic_dict_free,void,MfClassicDict* +Function,+,mf_classic_dict_free,void,MfClassicDict* Function,-,mf_classic_dict_get_key_at_index,_Bool,"MfClassicDict*, uint64_t*, uint32_t" -Function,-,mf_classic_dict_get_key_at_index_str,_Bool,"MfClassicDict*, FuriString*, uint32_t" +Function,+,mf_classic_dict_get_key_at_index_str,_Bool,"MfClassicDict*, FuriString*, uint32_t" Function,-,mf_classic_dict_get_next_key,_Bool,"MfClassicDict*, uint64_t*" -Function,-,mf_classic_dict_get_next_key_str,_Bool,"MfClassicDict*, FuriString*" -Function,-,mf_classic_dict_get_total_keys,uint32_t,MfClassicDict* -Function,-,mf_classic_dict_is_key_present,_Bool,"MfClassicDict*, uint8_t*" +Function,+,mf_classic_dict_get_next_key_str,_Bool,"MfClassicDict*, FuriString*" +Function,+,mf_classic_dict_get_total_keys,uint32_t,MfClassicDict* +Function,+,mf_classic_dict_is_key_present,_Bool,"MfClassicDict*, uint8_t*" Function,-,mf_classic_dict_is_key_present_str,_Bool,"MfClassicDict*, FuriString*" Function,-,mf_classic_dict_rewind,_Bool,MfClassicDict* Function,-,mf_classic_emulator,_Bool,"MfClassicEmulator*, FuriHalNfcTxRxContext*, _Bool" Function,-,mf_classic_get_classic_type,MfClassicType,FuriHalNfcADevData* -Function,-,mf_classic_get_read_sectors_and_keys,void,"MfClassicData*, uint8_t*, uint8_t*" -Function,-,mf_classic_get_sector_by_block,uint8_t,uint8_t +Function,+,mf_classic_get_read_sectors_and_keys,void,"MfClassicData*, uint8_t*, uint8_t*" +Function,+,mf_classic_get_sector_by_block,uint8_t,uint8_t Function,-,mf_classic_get_sector_trailer_block_num_by_sector,uint8_t,uint8_t -Function,-,mf_classic_get_sector_trailer_by_sector,MfClassicSectorTrailer*,"MfClassicData*, uint8_t" +Function,+,mf_classic_get_sector_trailer_by_sector,MfClassicSectorTrailer*,"MfClassicData*, uint8_t" Function,-,mf_classic_get_total_block_num,uint16_t,MfClassicType -Function,-,mf_classic_get_total_sectors_num,uint8_t,MfClassicType +Function,+,mf_classic_get_total_sectors_num,uint8_t,MfClassicType Function,-,mf_classic_get_type_str,const char*,MfClassicType Function,-,mf_classic_halt,void,"FuriHalNfcTxRxContext*, Crypto1*" Function,-,mf_classic_is_allowed_access_data_block,_Bool,"MfClassicData*, uint8_t, MfClassicKey, MfClassicAction" Function,-,mf_classic_is_allowed_access_sector_trailer,_Bool,"MfClassicData*, uint8_t, MfClassicKey, MfClassicAction" -Function,-,mf_classic_is_block_read,_Bool,"MfClassicData*, uint8_t" -Function,-,mf_classic_is_card_read,_Bool,MfClassicData* -Function,-,mf_classic_is_key_found,_Bool,"MfClassicData*, uint8_t, MfClassicKey" +Function,+,mf_classic_is_block_read,_Bool,"MfClassicData*, uint8_t" +Function,+,mf_classic_is_card_read,_Bool,MfClassicData* +Function,+,mf_classic_is_key_found,_Bool,"MfClassicData*, uint8_t, MfClassicKey" Function,-,mf_classic_is_sector_data_read,_Bool,"MfClassicData*, uint8_t" Function,-,mf_classic_is_sector_read,_Bool,"MfClassicData*, uint8_t" -Function,-,mf_classic_is_sector_trailer,_Bool,uint8_t +Function,+,mf_classic_is_sector_trailer,_Bool,uint8_t Function,-,mf_classic_is_value_block,_Bool,"MfClassicData*, uint8_t" Function,-,mf_classic_read_block,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t, MfClassicBlock*" Function,-,mf_classic_read_card,uint8_t,"FuriHalNfcTxRxContext*, MfClassicReader*, MfClassicData*" @@ -2102,10 +2105,10 @@ Function,-,mf_classic_value_to_block,void,"int32_t, uint8_t, uint8_t*" Function,-,mf_classic_write_block,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t, MfClassicBlock*" Function,-,mf_classic_write_sector,_Bool,"FuriHalNfcTxRxContext*, MfClassicData*, MfClassicData*, uint8_t" Function,-,mf_df_cat_application,void,"MifareDesfireApplication*, FuriString*" -Function,-,mf_df_cat_application_info,void,"MifareDesfireApplication*, FuriString*" -Function,-,mf_df_cat_card_info,void,"MifareDesfireData*, FuriString*" +Function,+,mf_df_cat_application_info,void,"MifareDesfireApplication*, FuriString*" +Function,+,mf_df_cat_card_info,void,"MifareDesfireData*, FuriString*" Function,-,mf_df_cat_data,void,"MifareDesfireData*, FuriString*" -Function,-,mf_df_cat_file,void,"MifareDesfireFile*, FuriString*" +Function,+,mf_df_cat_file,void,"MifareDesfireFile*, FuriString*" Function,-,mf_df_cat_free_mem,void,"MifareDesfireFreeMemory*, FuriString*" Function,-,mf_df_cat_key_settings,void,"MifareDesfireKeySettings*, FuriString*" Function,-,mf_df_cat_version,void,"MifareDesfireVersion*, FuriString*" @@ -2135,8 +2138,8 @@ Function,-,mf_df_prepare_read_records,uint16_t,"uint8_t*, uint8_t, uint32_t, uin Function,-,mf_df_prepare_select_application,uint16_t,"uint8_t*, uint8_t[3]" Function,-,mf_df_read_card,_Bool,"FuriHalNfcTxRxContext*, MifareDesfireData*" Function,-,mf_ul_check_card_type,_Bool,FuriHalNfcADevData* -Function,-,mf_ul_emulation_supported,_Bool,MfUltralightData* -Function,-,mf_ul_is_full_capture,_Bool,MfUltralightData* +Function,+,mf_ul_emulation_supported,_Bool,MfUltralightData* +Function,+,mf_ul_is_full_capture,_Bool,MfUltralightData* Function,-,mf_ul_prepare_emulation,void,"MfUltralightEmulator*, MfUltralightData*" Function,-,mf_ul_prepare_emulation_response,_Bool,"uint8_t*, uint16_t, uint8_t*, uint16_t*, uint32_t*, void*" Function,-,mf_ul_pwdgen_amiibo,uint32_t,FuriHalNfcDevData* @@ -2146,13 +2149,18 @@ Function,-,mf_ul_reset,void,MfUltralightData* Function,-,mf_ul_reset_emulation,void,"MfUltralightEmulator*, _Bool" Function,-,mf_ultralight_authenticate,_Bool,"FuriHalNfcTxRxContext*, uint32_t, uint16_t*" Function,-,mf_ultralight_fast_read_pages,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" -Function,-,mf_ultralight_get_config_pages,MfUltralightConfigPages*,MfUltralightData* +Function,+,mf_ultralight_get_config_pages,MfUltralightConfigPages*,MfUltralightData* Function,-,mf_ultralight_read_counters,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" Function,-,mf_ultralight_read_pages,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" Function,-,mf_ultralight_read_pages_direct,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint8_t*" Function,-,mf_ultralight_read_signature,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" Function,-,mf_ultralight_read_tearing_flags,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" Function,-,mf_ultralight_read_version,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" +Function,-,mfkey32_alloc,Mfkey32*,uint32_t +Function,-,mfkey32_free,void,Mfkey32* +Function,+,mfkey32_get_auth_sectors,uint16_t,FuriString* +Function,-,mfkey32_process_data,void,"Mfkey32*, uint8_t*, uint16_t, _Bool, _Bool" +Function,-,mfkey32_set_callback,void,"Mfkey32*, Mfkey32ParseDataCallback, void*" Function,-,mkdtemp,char*,char* Function,-,mkostemp,int,"char*, int" Function,-,mkostemps,int,"char*, int, int" @@ -2201,11 +2209,25 @@ Function,+,nfc_device_save_shadow,_Bool,"NfcDevice*, const char*" Function,+,nfc_device_set_loading_callback,void,"NfcDevice*, NfcLoadingCallback, void*" Function,+,nfc_device_set_name,void,"NfcDevice*, const char*" Function,+,nfc_file_select,_Bool,NfcDevice* +Function,-,nfc_generate_mf_classic,void,"NfcDeviceData*, uint8_t, MfClassicType" +Function,+,nfc_get_dev_type,const char*,FuriHalNfcType +Function,-,nfc_guess_protocol,const char*,NfcProtocol +Function,+,nfc_mf_classic_type,const char*,MfClassicType +Function,+,nfc_mf_ul_type,const char*,"MfUltralightType, _Bool" +Function,+,nfc_supported_card_verify_and_parse,_Bool,NfcDeviceData* Function,+,nfc_util_bytes2num,uint64_t,"const uint8_t*, uint8_t" Function,+,nfc_util_even_parity32,uint8_t,uint32_t Function,+,nfc_util_num2bytes,void,"uint64_t, uint8_t, uint8_t*" Function,+,nfc_util_odd_parity,void,"const uint8_t*, uint8_t*, uint8_t" Function,+,nfc_util_odd_parity8,uint8_t,uint8_t +Function,+,nfc_worker_alloc,NfcWorker*, +Function,+,nfc_worker_free,void,NfcWorker* +Function,+,nfc_worker_get_state,NfcWorkerState,NfcWorker* +Function,-,nfc_worker_nfcv_emulate,void,NfcWorker* +Function,-,nfc_worker_nfcv_sniff,void,NfcWorker* +Function,-,nfc_worker_nfcv_unlock,void,NfcWorker* +Function,+,nfc_worker_start,void,"NfcWorker*, NfcWorkerState, NfcDeviceData*, NfcWorkerCallback, void*" +Function,+,nfc_worker_stop,void,NfcWorker* Function,-,nfca_append_crc16,void,"uint8_t*, uint16_t" Function,-,nfca_emulation_handler,_Bool,"uint8_t*, uint16_t, uint8_t*, uint16_t*" Function,-,nfca_get_crc16,uint16_t,"uint8_t*, uint16_t" @@ -2794,15 +2816,46 @@ Function,-,strupr,char*,char* Function,-,strverscmp,int,"const char*, const char*" Function,-,strxfrm,size_t,"char*, const char*, size_t" Function,-,strxfrm_l,size_t,"char*, const char*, size_t, locale_t" +Function,-,stub_parser_verify_read,_Bool,"NfcWorker*, FuriHalNfcTxRxContext*" Function,+,subghz_block_generic_deserialize,SubGhzProtocolStatus,"SubGhzBlockGeneric*, FlipperFormat*" 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_custom_btn_get,uint8_t, -Function,-,subghz_custom_btn_get_original,uint8_t, -Function,-,subghz_custom_btn_is_allowed,_Bool, -Function,-,subghz_custom_btn_set,_Bool,uint8_t +Function,+,subghz_custom_btn_get,uint8_t, +Function,+,subghz_custom_btn_get_original,uint8_t, +Function,+,subghz_custom_btn_is_allowed,_Bool, +Function,+,subghz_custom_btn_set,_Bool,uint8_t Function,+,subghz_custom_btns_reset,void, +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* @@ -2817,6 +2870,14 @@ Function,+,subghz_environment_set_alutech_at_4n_rainbow_table_file_name,void,"Su Function,+,subghz_environment_set_came_atomo_rainbow_table_file_name,void,"SubGhzEnvironment*, const char*" Function,+,subghz_environment_set_nice_flor_s_rainbow_table_file_name,void,"SubGhzEnvironment*, const char*" Function,+,subghz_environment_set_protocol_registry,void,"SubGhzEnvironment*, const SubGhzProtocolRegistry*" +Function,+,subghz_file_encoder_worker_alloc,SubGhzFileEncoderWorker*, +Function,+,subghz_file_encoder_worker_callback_end,void,"SubGhzFileEncoderWorker*, SubGhzFileEncoderWorkerCallbackEnd, void*" +Function,+,subghz_file_encoder_worker_free,void,SubGhzFileEncoderWorker* +Function,+,subghz_file_encoder_worker_get_level_duration,LevelDuration,void* +Function,+,subghz_file_encoder_worker_get_text_progress,void,"SubGhzFileEncoderWorker*, FuriString*" +Function,+,subghz_file_encoder_worker_is_running,_Bool,SubGhzFileEncoderWorker* +Function,+,subghz_file_encoder_worker_start,_Bool,"SubGhzFileEncoderWorker*, const char*, const char*" +Function,+,subghz_file_encoder_worker_stop,void,SubGhzFileEncoderWorker* Function,-,subghz_keystore_alloc,SubGhzKeystore*, Function,-,subghz_keystore_free,void,SubGhzKeystore* Function,-,subghz_keystore_get_data,SubGhzKeyArray_t*,SubGhzKeystore* @@ -2825,6 +2886,7 @@ Function,-,subghz_keystore_raw_encrypted_save,_Bool,"const char*, const char*, u Function,-,subghz_keystore_raw_get_data,_Bool,"const char*, size_t, uint8_t*, size_t" Function,-,subghz_keystore_reset_kl,void,SubGhzKeystore* Function,-,subghz_keystore_save,_Bool,"SubGhzKeystore*, const char*, uint8_t*" +Function,+,subghz_protocol_alutech_at_4n_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, SubGhzRadioPreset*" Function,+,subghz_protocol_blocks_add_bit,void,"SubGhzBlockDecoder*, uint8_t" Function,+,subghz_protocol_blocks_add_bytes,uint8_t,"const uint8_t[], size_t" Function,+,subghz_protocol_blocks_add_to_128_bit,void,"SubGhzBlockDecoder*, uint8_t, uint64_t*" @@ -2846,11 +2908,13 @@ Function,+,subghz_protocol_blocks_parity_bytes,uint8_t,"const uint8_t[], size_t" Function,+,subghz_protocol_blocks_reverse_key,uint64_t,"uint64_t, uint8_t" Function,+,subghz_protocol_blocks_set_bit_array,void,"_Bool, uint8_t[], size_t, size_t" Function,+,subghz_protocol_blocks_xor_bytes,uint8_t,"const uint8_t[], size_t" +Function,+,subghz_protocol_came_atomo_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint16_t, SubGhzRadioPreset*" Function,+,subghz_protocol_decoder_base_deserialize,SubGhzProtocolStatus,"SubGhzProtocolDecoderBase*, FlipperFormat*" Function,+,subghz_protocol_decoder_base_get_hash_data,uint8_t,SubGhzProtocolDecoderBase* 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" @@ -2862,6 +2926,10 @@ 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_faac_slh_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint32_t, uint32_t, const char*, SubGhzRadioPreset*" +Function,+,subghz_protocol_keeloq_bft_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, uint32_t, const char*, SubGhzRadioPreset*" +Function,+,subghz_protocol_keeloq_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, const char*, SubGhzRadioPreset*" +Function,+,subghz_protocol_nice_flor_s_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, SubGhzRadioPreset*, _Bool" 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_get_sample_write,size_t,SubGhzProtocolDecoderRAW* @@ -2871,6 +2939,9 @@ 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_protocol_somfy_telis_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, SubGhzRadioPreset*" Function,+,subghz_receiver_alloc_init,SubGhzReceiver*,SubGhzEnvironment* Function,+,subghz_receiver_decode,void,"SubGhzReceiver*, _Bool, uint32_t" Function,+,subghz_receiver_free,void,SubGhzReceiver* @@ -2879,7 +2950,7 @@ Function,+,subghz_receiver_search_decoder_base_by_name,SubGhzProtocolDecoderBase Function,+,subghz_receiver_set_filter,void,"SubGhzReceiver*, SubGhzProtocolFlag" Function,+,subghz_receiver_set_rx_callback,void,"SubGhzReceiver*, SubGhzReceiverCallback, void*" Function,+,subghz_setting_alloc,SubGhzSetting*, -Function,-,subghz_setting_customs_presets_to_log,uint8_t,SubGhzSetting* +Function,+,subghz_setting_customs_presets_to_log,uint8_t,SubGhzSetting* Function,+,subghz_setting_delete_custom_preset,_Bool,"SubGhzSetting*, const char*" Function,+,subghz_setting_free,void,SubGhzSetting* Function,+,subghz_setting_get_default_frequency,uint32_t,SubGhzSetting* @@ -3502,15 +3573,12 @@ Variable,+,furi_hal_spi_bus_handle_nfc,FuriHalSpiBusHandle, Variable,+,furi_hal_spi_bus_handle_sd_fast,FuriHalSpiBusHandle, Variable,+,furi_hal_spi_bus_handle_sd_slow,FuriHalSpiBusHandle, Variable,+,furi_hal_spi_bus_handle_subghz,FuriHalSpiBusHandle, -Variable,+,furi_hal_spi_bus_handle_subghz_ext,FuriHalSpiBusHandle, -Variable,+,furi_hal_spi_bus_handle_subghz_int,FuriHalSpiBusHandle, Variable,+,furi_hal_spi_bus_r,FuriHalSpiBus, Variable,+,furi_hal_spi_preset_1edge_low_16m,const LL_SPI_InitTypeDef, Variable,+,furi_hal_spi_preset_1edge_low_2m,const LL_SPI_InitTypeDef, Variable,+,furi_hal_spi_preset_1edge_low_4m,const LL_SPI_InitTypeDef, Variable,+,furi_hal_spi_preset_1edge_low_8m,const LL_SPI_InitTypeDef, Variable,+,furi_hal_spi_preset_2edge_low_8m,const LL_SPI_InitTypeDef, -Variable,+,furi_hal_subghz,volatile FuriHalSubGhz, Variable,+,gpio_button_back,const GpioPin, Variable,+,gpio_button_down,const GpioPin, Variable,+,gpio_button_left,const GpioPin, @@ -3518,7 +3586,6 @@ Variable,+,gpio_button_ok,const GpioPin, Variable,+,gpio_button_right,const GpioPin, Variable,+,gpio_button_up,const GpioPin, Variable,+,gpio_cc1101_g0,const GpioPin, -Variable,+,gpio_cc1101_g0_ext,const GpioPin, Variable,+,gpio_display_cs,const GpioPin, Variable,+,gpio_display_di,const GpioPin, Variable,+,gpio_display_rst_n,const GpioPin, @@ -3551,13 +3618,9 @@ Variable,+,gpio_spi_d_miso,const GpioPin, Variable,+,gpio_spi_d_mosi,const GpioPin, Variable,+,gpio_spi_d_sck,const GpioPin, Variable,+,gpio_spi_r_miso,const GpioPin, -Variable,+,gpio_spi_r_miso_ext,const GpioPin, Variable,+,gpio_spi_r_mosi,const GpioPin, -Variable,+,gpio_spi_r_mosi_ext,const GpioPin, Variable,+,gpio_spi_r_sck,const GpioPin, -Variable,+,gpio_spi_r_sck_ext,const GpioPin, Variable,+,gpio_subghz_cs,const GpioPin, -Variable,+,gpio_subghz_cs_ext,const GpioPin, Variable,+,gpio_swclk,const GpioPin, Variable,+,gpio_swdio,const GpioPin, Variable,+,gpio_usart_rx,const GpioPin, @@ -3714,6 +3777,8 @@ Variable,+,message_red_255,const NotificationMessage, Variable,+,message_sound_off,const NotificationMessage, Variable,+,message_vibro_off,const NotificationMessage, Variable,+,message_vibro_on,const NotificationMessage, +Variable,+,nfc_generators,const NfcGenerator*[], +Variable,-,nfc_supported_card,NfcSupportedCard[NfcSupportedCardTypeEnd], Variable,+,sequence_audiovisual_alert,const NotificationSequence, Variable,+,sequence_blink_blue_10,const NotificationSequence, Variable,+,sequence_blink_blue_100,const NotificationSequence, diff --git a/firmware/targets/f7/ble_glue/gap.c b/firmware/targets/f7/ble_glue/gap.c index 94c556e54..6a675f5c4 100644 --- a/firmware/targets/f7/ble_glue/gap.c +++ b/firmware/targets/f7/ble_glue/gap.c @@ -501,7 +501,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); @@ -515,7 +515,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); diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/firmware/targets/f7/furi_hal/furi_hal_bt.c index 3bd93552c..51866e402 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_bt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_bt.c @@ -251,7 +251,7 @@ bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, } // 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) { + strnlen(config->adv_name + 1, FURI_HAL_VERSION_DEVICE_NAME_LENGTH - 1) < 1) { snprintf( config->adv_name, FURI_HAL_VERSION_DEVICE_NAME_LENGTH, @@ -499,13 +499,10 @@ 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); } 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); } } diff --git a/firmware/targets/f7/furi_hal/furi_hal_infrared.c b/firmware/targets/f7/furi_hal/furi_hal_infrared.c index e6fb69307..e76582dac 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_infrared.c +++ b/firmware/targets/f7/furi_hal/furi_hal_infrared.c @@ -378,9 +378,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..c508dac72 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,14 @@ 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_hal_interrupt_disable(index); furi_hal_interrupt_clear_pending(index); } 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/f7/furi_hal/furi_hal_resources.c b/firmware/targets/f7/furi_hal/furi_hal_resources.c index 63507bd7b..34b26b831 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_resources.c +++ b/firmware/targets/f7/furi_hal/furi_hal_resources.c @@ -14,11 +14,9 @@ const GpioPin gpio_vibro = {.port = VIBRO_GPIO_Port, .pin = VIBRO_Pin}; const GpioPin gpio_ibutton = {.port = iBTN_GPIO_Port, .pin = iBTN_Pin}; const GpioPin gpio_cc1101_g0 = {.port = CC1101_G0_GPIO_Port, .pin = CC1101_G0_Pin}; -const GpioPin gpio_cc1101_g0_ext = {.port = GPIOB, .pin = LL_GPIO_PIN_2}; const GpioPin gpio_rf_sw_0 = {.port = RF_SW_0_GPIO_Port, .pin = RF_SW_0_Pin}; const GpioPin gpio_subghz_cs = {.port = CC1101_CS_GPIO_Port, .pin = CC1101_CS_Pin}; -const GpioPin gpio_subghz_cs_ext = {.port = GPIOA, .pin = LL_GPIO_PIN_4}; const GpioPin gpio_display_cs = {.port = DISPLAY_CS_GPIO_Port, .pin = DISPLAY_CS_Pin}; const GpioPin gpio_display_rst_n = {.port = DISPLAY_RST_GPIO_Port, .pin = DISPLAY_RST_Pin}; const GpioPin gpio_display_di = {.port = DISPLAY_DI_GPIO_Port, .pin = DISPLAY_DI_Pin}; @@ -39,9 +37,6 @@ const GpioPin gpio_spi_d_sck = {.port = SPI_D_SCK_GPIO_Port, .pin = SPI_D_SCK_Pi const GpioPin gpio_spi_r_miso = {.port = SPI_R_MISO_GPIO_Port, .pin = SPI_R_MISO_Pin}; const GpioPin gpio_spi_r_mosi = {.port = SPI_R_MOSI_GPIO_Port, .pin = SPI_R_MOSI_Pin}; const GpioPin gpio_spi_r_sck = {.port = SPI_R_SCK_GPIO_Port, .pin = SPI_R_SCK_Pin}; -const GpioPin gpio_spi_r_miso_ext = {.port = GPIOA, .pin = LL_GPIO_PIN_6}; -const GpioPin gpio_spi_r_mosi_ext = {.port = GPIOA, .pin = LL_GPIO_PIN_7}; -const GpioPin gpio_spi_r_sck_ext = {.port = GPIOB, .pin = LL_GPIO_PIN_3}; const GpioPin gpio_ext_pc0 = {.port = GPIOC, .pin = LL_GPIO_PIN_0}; const GpioPin gpio_ext_pc1 = {.port = GPIOC, .pin = LL_GPIO_PIN_1}; diff --git a/firmware/targets/f7/furi_hal/furi_hal_resources.h b/firmware/targets/f7/furi_hal/furi_hal_resources.h index 391f8f4ff..6e585c518 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_resources.h +++ b/firmware/targets/f7/furi_hal/furi_hal_resources.h @@ -57,11 +57,9 @@ extern const GpioPin gpio_vibro; extern const GpioPin gpio_ibutton; extern const GpioPin gpio_cc1101_g0; -extern const GpioPin gpio_cc1101_g0_ext; extern const GpioPin gpio_rf_sw_0; extern const GpioPin gpio_subghz_cs; -extern const GpioPin gpio_subghz_cs_ext; extern const GpioPin gpio_display_cs; extern const GpioPin gpio_display_rst_n; extern const GpioPin gpio_display_di; @@ -82,9 +80,6 @@ extern const GpioPin gpio_spi_d_sck; extern const GpioPin gpio_spi_r_miso; extern const GpioPin gpio_spi_r_mosi; extern const GpioPin gpio_spi_r_sck; -extern const GpioPin gpio_spi_r_miso_ext; -extern const GpioPin gpio_spi_r_mosi_ext; -extern const GpioPin gpio_spi_r_sck_ext; extern const GpioPin gpio_ext_pc0; extern const GpioPin gpio_ext_pc1; diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi_config.c b/firmware/targets/f7/furi_hal/furi_hal_spi_config.c index c73c71a4f..757ac2366 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_spi_config.c +++ b/firmware/targets/f7/furi_hal/furi_hal_spi_config.c @@ -3,7 +3,6 @@ #include #include #include -#include #define TAG "FuriHalSpiConfig" @@ -91,7 +90,7 @@ void furi_hal_spi_config_deinit_early() { void furi_hal_spi_config_init() { furi_hal_spi_bus_init(&furi_hal_spi_bus_r); - furi_hal_spi_bus_handle_init(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_subghz); furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_nfc); furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_sd_fast); furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_sd_slow); @@ -193,6 +192,52 @@ inline static void furi_hal_spi_bus_r_handle_event_callback( } } +inline static void furi_hal_spi_bus_external_handle_event_callback( + FuriHalSpiBusHandle* handle, + FuriHalSpiBusHandleEvent event, + const LL_SPI_InitTypeDef* preset) { + if(event == FuriHalSpiBusHandleEventInit) { + furi_hal_gpio_write(handle->cs, true); + furi_hal_gpio_init(handle->cs, GpioModeOutputPushPull, GpioPullUp, GpioSpeedVeryHigh); + } else if(event == FuriHalSpiBusHandleEventDeinit) { + furi_hal_gpio_write(handle->cs, true); + furi_hal_gpio_init(handle->cs, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + } else if(event == FuriHalSpiBusHandleEventActivate) { + LL_SPI_Init(handle->bus->spi, (LL_SPI_InitTypeDef*)preset); + LL_SPI_SetRxFIFOThreshold(handle->bus->spi, LL_SPI_RX_FIFO_TH_QUARTER); + LL_SPI_Enable(handle->bus->spi); + + furi_hal_gpio_init_ex( + handle->miso, + GpioModeAltFunctionPushPull, + GpioPullDown, + GpioSpeedVeryHigh, + GpioAltFn5SPI1); + furi_hal_gpio_init_ex( + handle->mosi, + GpioModeAltFunctionPushPull, + GpioPullDown, + GpioSpeedVeryHigh, + GpioAltFn5SPI1); + furi_hal_gpio_init_ex( + handle->sck, + GpioModeAltFunctionPushPull, + GpioPullDown, + GpioSpeedVeryHigh, + GpioAltFn5SPI1); + + furi_hal_gpio_write(handle->cs, false); + } else if(event == FuriHalSpiBusHandleEventDeactivate) { + furi_hal_gpio_write(handle->cs, true); + + furi_hal_gpio_init(handle->miso, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(handle->mosi, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(handle->sck, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + + LL_SPI_Disable(handle->bus->spi); + } +} + inline static void furi_hal_spi_bus_nfc_handle_event_callback( FuriHalSpiBusHandle* handle, FuriHalSpiBusHandleEvent event, @@ -265,15 +310,6 @@ static void furi_hal_spi_bus_handle_subghz_event_callback( furi_hal_spi_bus_r_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_8m); } -FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz_int = { - .bus = &furi_hal_spi_bus_r, - .callback = furi_hal_spi_bus_handle_subghz_event_callback, - .miso = &gpio_spi_r_miso, - .mosi = &gpio_spi_r_mosi, - .sck = &gpio_spi_r_sck, - .cs = &gpio_subghz_cs, -}; - FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz = { .bus = &furi_hal_spi_bus_r, .callback = furi_hal_spi_bus_handle_subghz_event_callback, @@ -283,15 +319,6 @@ FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz = { .cs = &gpio_subghz_cs, }; -FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz_ext = { - .bus = &furi_hal_spi_bus_r, - .callback = furi_hal_spi_bus_handle_subghz_event_callback, - .miso = &gpio_ext_pa6, - .mosi = &gpio_ext_pa7, - .sck = &gpio_ext_pb3, - .cs = &gpio_ext_pa4, -}; - static void furi_hal_spi_bus_handle_nfc_event_callback( FuriHalSpiBusHandle* handle, FuriHalSpiBusHandleEvent event) { @@ -310,7 +337,8 @@ FuriHalSpiBusHandle furi_hal_spi_bus_handle_nfc = { static void furi_hal_spi_bus_handle_external_event_callback( FuriHalSpiBusHandle* handle, FuriHalSpiBusHandleEvent event) { - furi_hal_spi_bus_r_handle_event_callback(handle, event, &furi_hal_spi_preset_1edge_low_2m); + furi_hal_spi_bus_external_handle_event_callback( + handle, event, &furi_hal_spi_preset_1edge_low_2m); } FuriHalSpiBusHandle furi_hal_spi_bus_handle_external = { diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi_config.h b/firmware/targets/f7/furi_hal/furi_hal_spi_config.h index 8ea138bdc..eab633a19 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_spi_config.h +++ b/firmware/targets/f7/furi_hal/furi_hal_spi_config.h @@ -27,12 +27,8 @@ extern FuriHalSpiBus furi_hal_spi_bus_r; /** Furi Hal Spi Bus D (Display, SdCard) */ extern FuriHalSpiBus furi_hal_spi_bus_d; -/** CC1101 on current SPI bus */ -extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz; /** CC1101 on `furi_hal_spi_bus_r` */ -extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz_int; -/** CC1101 on external `furi_hal_spi_bus_r` */ -extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz_ext; +extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_subghz; /** ST25R3916 on `furi_hal_spi_bus_r` */ extern FuriHalSpiBusHandle furi_hal_spi_bus_handle_nfc; diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.c b/firmware/targets/f7/furi_hal/furi_hal_subghz.c index f8c0ad999..98e1af326 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz.c +++ b/firmware/targets/f7/furi_hal/furi_hal_subghz.c @@ -1,25 +1,20 @@ #include -#include +#include #include #include #include #include #include -#include #include #include -#include - #include #include #include #define TAG "FuriHalSubGhz" -//Initialisation timeout (ms) -#define INIT_TIMEOUT 10 static uint32_t furi_hal_subghz_debug_gpio_buff[2]; @@ -31,48 +26,46 @@ 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; + const GpioPin* async_mirror_pin; + + uint8_t rolling_counter_mult; + bool timestamp_file_names : 1; + bool dangerous_frequency_i : 1; +} FuriHalSubGhz; + volatile FuriHalSubGhz furi_hal_subghz = { .state = SubGhzStateInit, .regulation = SubGhzRegulationTxRx, .preset = FuriHalSubGhzPresetIDLE, .async_mirror_pin = NULL, - .radio_type = SubGhzRadioInternal, - .spi_bus_handle = &furi_hal_spi_bus_handle_subghz, - .cc1101_g0_pin = &gpio_cc1101_g0, .rolling_counter_mult = 1, - .ext_module_power_disabled = false, - .extended_frequency_i = false, + .dangerous_frequency_i = false, }; -void furi_hal_subghz_select_radio_type(SubGhzRadioType state) { - furi_hal_subghz.radio_type = state; -} - -bool furi_hal_subghz_init_radio_type(SubGhzRadioType state) { - if(state == SubGhzRadioInternal && furi_hal_subghz.cc1101_g0_pin == &gpio_cc1101_g0) { - return true; - } else if(state == SubGhzRadioExternal && furi_hal_subghz.cc1101_g0_pin == &gpio_cc1101_g0_ext) { - return true; - } - furi_hal_spi_bus_handle_deinit(furi_hal_subghz.spi_bus_handle); - - if(state == SubGhzRadioInternal) { - furi_hal_subghz.spi_bus_handle = &furi_hal_spi_bus_handle_subghz; - furi_hal_subghz.cc1101_g0_pin = &gpio_cc1101_g0; - } else { - furi_hal_subghz.spi_bus_handle = &furi_hal_spi_bus_handle_subghz_ext; - furi_hal_subghz.cc1101_g0_pin = &gpio_cc1101_g0_ext; - } - - furi_hal_spi_bus_handle_init(furi_hal_subghz.spi_bus_handle); - furi_hal_subghz_init_check(); - return true; -} - -SubGhzRadioType furi_hal_subghz_get_radio_type(void) { - return furi_hal_subghz.radio_type; -} - uint8_t furi_hal_subghz_get_rolling_counter_mult(void) { return furi_hal_subghz.rolling_counter_mult; } @@ -89,143 +82,84 @@ bool furi_hal_subghz_get_external_power_disable(void) { return furi_hal_subghz.ext_module_power_disabled; } -void furi_hal_subghz_set_extended_frequency(bool state_i) { - furi_hal_subghz.extended_frequency_i = state_i; +void furi_hal_subghz_set_dangerous_frequency(bool state_i) { + furi_hal_subghz.dangerous_frequency_i = state_i; } void furi_hal_subghz_set_async_mirror_pin(const GpioPin* pin) { furi_hal_subghz.async_mirror_pin = pin; } -void furi_hal_subghz_init(void) { - furi_hal_subghz_init_check(); +const GpioPin* furi_hal_subghz_get_data_gpio() { + return &gpio_cc1101_g0; } -bool furi_hal_subghz_enable_ext_power(void) { - if(furi_hal_subghz.ext_module_power_disabled) { - return false; - } - if(furi_hal_subghz.radio_type != SubGhzRadioInternal) { - 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); - } - } - return furi_hal_power_is_otg_enabled(); -} - -void furi_hal_subghz_disable_ext_power(void) { - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } -} - -bool furi_hal_subghz_check_radio(void) { - bool result = true; - - furi_hal_subghz_init_radio_type(furi_hal_subghz.radio_type); - - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - - uint8_t ver = cc1101_get_version(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); - - if((ver != 0) && (ver != 255)) { - FURI_LOG_D(TAG, "Radio check ok"); - } else { - FURI_LOG_D(TAG, "Radio check failed, revert to default"); - - result = false; - } - return result; -} - -bool furi_hal_subghz_init_check(void) { - bool result = true; - +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_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); #ifdef FURI_HAL_SUBGHZ_TX_GPIO furi_hal_gpio_init(&FURI_HAL_SUBGHZ_TX_GPIO, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); #endif // Reset - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - cc1101_reset(furi_hal_subghz.spi_bus_handle); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_reset(&furi_hal_spi_bus_handle_subghz); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance); // Prepare GD0 for power on self test - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); // GD0 low - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHW); - uint32_t test_start_time = furi_get_tick(); - while(furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin) != false && result) { - if(furi_get_tick() - test_start_time > INIT_TIMEOUT) { - result = false; - } - } + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHW); + while(furi_hal_gpio_read(&gpio_cc1101_g0) != false) + ; // GD0 high cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHW | CC1101_IOCFG_INV); - test_start_time = furi_get_tick(); - while(furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin) != true && result) { - if(furi_get_tick() - test_start_time > INIT_TIMEOUT) { - result = false; - } - } + &furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHW | CC1101_IOCFG_INV); + while(furi_hal_gpio_read(&gpio_cc1101_g0) != true) + ; // Reset GD0 to floating state - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); // RF switches furi_hal_gpio_init(&gpio_rf_sw_0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW); // Go to sleep - cc1101_shutdown(furi_hal_subghz.spi_bus_handle); + cc1101_shutdown(&furi_hal_spi_bus_handle_subghz); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); - - if(result) { - FURI_LOG_I(TAG, "Init OK"); - } else { - FURI_LOG_E(TAG, "Selected CC1101 module init failed, revert to default"); - } - return result; + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); + FURI_LOG_I(TAG, "Init OK"); } void furi_hal_subghz_sleep() { furi_assert(furi_hal_subghz.state == SubGhzStateIdle); - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); - cc1101_switch_to_idle(furi_hal_subghz.spi_bus_handle); + cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - cc1101_shutdown(furi_hal_subghz.spi_bus_handle); + cc1101_shutdown(&furi_hal_spi_bus_handle_subghz); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); - - furi_hal_subghz.preset = FuriHalSubGhzPresetIDLE; + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_dump_state() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); printf( "[furi_hal_subghz] cc1101 chip %d, version %d\r\n", - cc1101_get_partnumber(furi_hal_subghz.spi_bus_handle), - cc1101_get_version(furi_hal_subghz.spi_bus_handle)); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_get_partnumber(&furi_hal_spi_bus_handle_subghz), + cc1101_get_version(&furi_hal_spi_bus_handle_subghz)); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_load_preset(FuriHalSubGhzPreset preset) { @@ -257,15 +191,15 @@ void furi_hal_subghz_load_preset(FuriHalSubGhzPreset preset) { void furi_hal_subghz_load_custom_preset(uint8_t* preset_data) { //load config - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_reset(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_reset(&furi_hal_spi_bus_handle_subghz); uint32_t i = 0; uint8_t pa[8] = {0}; while(preset_data[i]) { - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, preset_data[i], preset_data[i + 1]); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, preset_data[i], preset_data[i + 1]); i += 2; } - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); //load pa table memcpy(&pa[0], &preset_data[i + 2], 8); @@ -286,49 +220,49 @@ void furi_hal_subghz_load_custom_preset(uint8_t* preset_data) { } } -void furi_hal_subghz_load_registers(uint8_t* data) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_reset(furi_hal_subghz.spi_bus_handle); +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; while(data[i]) { - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, data[i], data[i + 1]); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, data[i], data[i + 1]); i += 2; } - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_load_patable(const uint8_t data[8]) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_set_pa_table(furi_hal_subghz.spi_bus_handle, data); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_set_pa_table(&furi_hal_spi_bus_handle_subghz, data); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_write_packet(const uint8_t* data, uint8_t size) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_flush_tx(furi_hal_subghz.spi_bus_handle); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_FIFO, size); - cc1101_write_fifo(furi_hal_subghz.spi_bus_handle, data, size); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_flush_tx(&furi_hal_spi_bus_handle_subghz); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_FIFO, size); + cc1101_write_fifo(&furi_hal_spi_bus_handle_subghz, data, size); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_flush_rx() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_flush_rx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_flush_rx(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_flush_tx() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_flush_tx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_flush_tx(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } bool furi_hal_subghz_rx_pipe_not_empty() { CC1101RxBytes status[1]; - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); cc1101_read_reg( - furi_hal_subghz.spi_bus_handle, (CC1101_STATUS_RXBYTES) | CC1101_BURST, (uint8_t*)status); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + &furi_hal_spi_bus_handle_subghz, (CC1101_STATUS_RXBYTES) | CC1101_BURST, (uint8_t*)status); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); // TODO: you can add a buffer overflow flag if needed if(status->NUM_RXBYTES > 0) { return true; @@ -338,10 +272,10 @@ bool furi_hal_subghz_rx_pipe_not_empty() { } bool furi_hal_subghz_is_rx_data_crc_valid() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); uint8_t data[1]; - cc1101_read_reg(furi_hal_subghz.spi_bus_handle, CC1101_STATUS_LQI | CC1101_BURST, data); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_read_reg(&furi_hal_spi_bus_handle_subghz, CC1101_STATUS_LQI | CC1101_BURST, data); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); if(((data[0] >> 7) & 0x01)) { return true; } else { @@ -350,51 +284,51 @@ bool furi_hal_subghz_is_rx_data_crc_valid() { } void furi_hal_subghz_read_packet(uint8_t* data, uint8_t* size) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_read_fifo(furi_hal_subghz.spi_bus_handle, data, size); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_read_fifo(&furi_hal_spi_bus_handle_subghz, data, size); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_shutdown() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); // Reset and shutdown - cc1101_shutdown(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_shutdown(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_reset() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); - cc1101_switch_to_idle(furi_hal_subghz.spi_bus_handle); - cc1101_reset(furi_hal_subghz.spi_bus_handle); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG0, CC1101IocfgHighImpedance); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz); + cc1101_reset(&furi_hal_spi_bus_handle_subghz); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG0, CC1101IocfgHighImpedance); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_idle() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_switch_to_idle(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_switch_to_idle(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } void furi_hal_subghz_rx() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_switch_to_rx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_switch_to_rx(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } bool furi_hal_subghz_tx() { if(furi_hal_subghz.regulation != SubGhzRegulationTxRx) return false; - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - cc1101_switch_to_tx(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + cc1101_switch_to_tx(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); return true; } float furi_hal_subghz_get_rssi() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - int32_t rssi_dec = cc1101_get_rssi(furi_hal_subghz.spi_bus_handle); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + int32_t rssi_dec = cc1101_get_rssi(&furi_hal_spi_bus_handle_subghz); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); float rssi = rssi_dec; if(rssi_dec >= 128) { @@ -407,10 +341,10 @@ float furi_hal_subghz_get_rssi() { } uint8_t furi_hal_subghz_get_lqi() { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); uint8_t data[1]; - cc1101_read_reg(furi_hal_subghz.spi_bus_handle, CC1101_STATUS_LQI | CC1101_BURST, data); - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + cc1101_read_reg(&furi_hal_spi_bus_handle_subghz, CC1101_STATUS_LQI | CC1101_BURST, data); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); return data[0] & 0x7F; } @@ -456,10 +390,8 @@ bool furi_hal_subghz_is_tx_allowed(uint32_t value) { return false; } else if( (allow_extended_for_int) && // - !(value >= 281000000 && value <= 361000000) && - !(value >= 378000000 && value <= 481000000) && - !(value >= 749000000 && value <= 962000000)) { - FURI_LOG_I(TAG, "Frequency blocked - outside extended range"); + !furi_hal_subghz_is_frequency_valid(value)) { + FURI_LOG_I(TAG, "Frequency blocked - outside dangerous range"); return false; } @@ -467,41 +399,45 @@ bool furi_hal_subghz_is_tx_allowed(uint32_t value) { } uint32_t furi_hal_subghz_set_frequency(uint32_t value) { - furi_hal_subghz.regulation = SubGhzRegulationTxRx; + if(furi_hal_subghz_is_tx_allowed(value)) { + furi_hal_subghz.regulation = SubGhzRegulationTxRx; + } else { + furi_hal_subghz.regulation = SubGhzRegulationOnlyRx; + } - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); - uint32_t real_frequency = cc1101_set_frequency(furi_hal_subghz.spi_bus_handle, value); - cc1101_calibrate(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); + uint32_t real_frequency = cc1101_set_frequency(&furi_hal_spi_bus_handle_subghz, value); + cc1101_calibrate(&furi_hal_spi_bus_handle_subghz); while(true) { - CC1101Status status = cc1101_get_status(furi_hal_subghz.spi_bus_handle); + CC1101Status status = cc1101_get_status(&furi_hal_spi_bus_handle_subghz); if(status.STATE == CC1101StateIDLE) break; } - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); return real_frequency; } void furi_hal_subghz_set_path(FuriHalSubGhzPath path) { - furi_hal_spi_acquire(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_subghz); if(path == FuriHalSubGhzPath433) { furi_hal_gpio_write(&gpio_rf_sw_0, 0); cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV); + &furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV); } else if(path == FuriHalSubGhzPath315) { furi_hal_gpio_write(&gpio_rf_sw_0, 1); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW); } else if(path == FuriHalSubGhzPath868) { furi_hal_gpio_write(&gpio_rf_sw_0, 1); cc1101_write_reg( - furi_hal_subghz.spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV); + &furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW | CC1101_IOCFG_INV); } else if(path == FuriHalSubGhzPathIsolate) { furi_hal_gpio_write(&gpio_rf_sw_0, 0); - cc1101_write_reg(furi_hal_subghz.spi_bus_handle, CC1101_IOCFG2, CC1101IocfgHW); + cc1101_write_reg(&furi_hal_spi_bus_handle_subghz, CC1101_IOCFG2, CC1101IocfgHW); } else { furi_crash("SubGhz: Incorrect path during set."); } - furi_hal_spi_release(furi_hal_subghz.spi_bus_handle); + furi_hal_spi_release(&furi_hal_spi_bus_handle_subghz); } static bool furi_hal_subghz_start_debug() { @@ -531,7 +467,7 @@ volatile uint32_t furi_hal_subghz_capture_delta_duration = 0; volatile FuriHalSubGhzCaptureCallback furi_hal_subghz_capture_callback = NULL; volatile void* furi_hal_subghz_capture_callback_context = NULL; -static void furi_hal_subghz_capture_int_ISR() { +static void furi_hal_subghz_capture_ISR() { // Channel 1 if(LL_TIM_IsActiveFlag_CC1(TIM2)) { LL_TIM_ClearFlag_CC1(TIM2); @@ -561,27 +497,6 @@ static void furi_hal_subghz_capture_int_ISR() { } } -static void furi_hal_subghz_capture_ext_ISR() { - if(!furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin)) { - if(furi_hal_subghz_capture_callback) { - if(furi_hal_subghz.async_mirror_pin != NULL) - furi_hal_gpio_write(furi_hal_subghz.async_mirror_pin, false); - - furi_hal_subghz_capture_callback( - true, TIM2->CNT, (void*)furi_hal_subghz_capture_callback_context); - } - } else { - if(furi_hal_subghz_capture_callback) { - if(furi_hal_subghz.async_mirror_pin != NULL) - furi_hal_gpio_write(furi_hal_subghz.async_mirror_pin, true); - - furi_hal_subghz_capture_callback( - false, TIM2->CNT, (void*)furi_hal_subghz_capture_callback_context); - } - } - TIM2->CNT = 6; -} - void furi_hal_subghz_start_async_rx(FuriHalSubGhzCaptureCallback callback, void* context) { furi_assert(furi_hal_subghz.state == SubGhzStateIdle); furi_hal_subghz.state = SubGhzStateAsyncRx; @@ -589,6 +504,9 @@ void furi_hal_subghz_start_async_rx(FuriHalSubGhzCaptureCallback callback, void* furi_hal_subghz_capture_callback = callback; furi_hal_subghz_capture_callback_context = context; + furi_hal_gpio_init_ex( + &gpio_cc1101_g0, GpioModeAltFunctionPushPull, GpioPullNo, GpioSpeedLow, GpioAltFn1TIM2); + furi_hal_bus_enable(FuriHalBusTIM2); // Timer: base @@ -596,62 +514,42 @@ void furi_hal_subghz_start_async_rx(FuriHalSubGhzCaptureCallback callback, void* TIM_InitStruct.Prescaler = 64 - 1; TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP; TIM_InitStruct.Autoreload = 0x7FFFFFFE; - // Clock division for capture filter (for internal radio) + // Clock division for capture filter TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV4; LL_TIM_Init(TIM2, &TIM_InitStruct); // Timer: advanced LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL); LL_TIM_DisableARRPreload(TIM2); + LL_TIM_SetTriggerInput(TIM2, LL_TIM_TS_TI2FP2); + LL_TIM_SetSlaveMode(TIM2, LL_TIM_SLAVEMODE_RESET); + LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_RESET); + LL_TIM_EnableMasterSlaveMode(TIM2); LL_TIM_DisableDMAReq_TRIG(TIM2); LL_TIM_DisableIT_TRIG(TIM2); - if(furi_hal_subghz.radio_type == SubGhzRadioInternal) { - LL_TIM_SetTriggerInput(TIM2, LL_TIM_TS_TI2FP2); - LL_TIM_SetSlaveMode(TIM2, LL_TIM_SLAVEMODE_RESET); - LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_RESET); - LL_TIM_EnableMasterSlaveMode(TIM2); + // Timer: channel 1 indirect + LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ACTIVEINPUT_INDIRECTTI); + LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ICPSC_DIV1); + LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_POLARITY_FALLING); - // Timer: channel 1 indirect - LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ACTIVEINPUT_INDIRECTTI); - LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_ICPSC_DIV1); - LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_POLARITY_FALLING); - LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH1, LL_TIM_IC_FILTER_FDIV1); + // Timer: channel 2 direct + LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ACTIVEINPUT_DIRECTTI); + LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ICPSC_DIV1); + LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_POLARITY_RISING); + LL_TIM_IC_SetFilter( + TIM2, + LL_TIM_CHANNEL_CH2, + LL_TIM_IC_FILTER_FDIV32_N8); // Capture filter: 1/(64000000/64/4/32*8) = 16us - // Timer: channel 2 direct - LL_TIM_IC_SetActiveInput(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ACTIVEINPUT_DIRECTTI); - LL_TIM_IC_SetPrescaler(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_ICPSC_DIV1); - LL_TIM_IC_SetPolarity(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_POLARITY_RISING); - LL_TIM_IC_SetFilter(TIM2, LL_TIM_CHANNEL_CH2, LL_TIM_IC_FILTER_FDIV32_N8); + // ISR setup + furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, furi_hal_subghz_capture_ISR, NULL); - // ISR setup - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, furi_hal_subghz_capture_int_ISR, NULL); - - // Interrupts and channels - LL_TIM_EnableIT_CC1(TIM2); - LL_TIM_EnableIT_CC2(TIM2); - LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH1); - LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH2); - - furi_hal_gpio_init_ex( - furi_hal_subghz.cc1101_g0_pin, - GpioModeAltFunctionPushPull, - GpioPullNo, - GpioSpeedLow, - GpioAltFn1TIM2); - } else { - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, - GpioModeInterruptRiseFall, - GpioPullUp, - GpioSpeedVeryHigh); - furi_hal_gpio_disable_int_callback(furi_hal_subghz.cc1101_g0_pin); - furi_hal_gpio_remove_int_callback(furi_hal_subghz.cc1101_g0_pin); - furi_hal_gpio_add_int_callback( - furi_hal_subghz.cc1101_g0_pin, - furi_hal_subghz_capture_ext_ISR, - furi_hal_subghz_capture_callback); - } + // Interrupts and channels + LL_TIM_EnableIT_CC1(TIM2); + LL_TIM_EnableIT_CC2(TIM2); + LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH1); + LL_TIM_CC_EnableChannel(TIM2, LL_TIM_CHANNEL_CH2); // Start timer LL_TIM_SetCounter(TIM2, 0); @@ -681,14 +579,9 @@ void furi_hal_subghz_stop_async_rx() { furi_hal_subghz_stop_debug(); FURI_CRITICAL_EXIT(); - if(furi_hal_subghz.radio_type == SubGhzRadioInternal) { - furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL); - } else { - furi_hal_gpio_disable_int_callback(furi_hal_subghz.cc1101_g0_pin); - furi_hal_gpio_remove_int_callback(furi_hal_subghz.cc1101_g0_pin); - } + furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL); - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); } typedef struct { @@ -792,8 +685,7 @@ static void furi_hal_subghz_async_tx_timer_isr() { } else if(furi_hal_subghz.state == SubGhzStateAsyncTxLast) { furi_hal_subghz.state = SubGhzStateAsyncTxEnd; //forcibly pulls the pin to the ground so that there is no carrier - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullDown, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullDown, GpioSpeedLow); LL_TIM_DisableCounter(TIM2); } else { furi_crash(NULL); @@ -820,20 +712,9 @@ bool furi_hal_subghz_start_async_tx(FuriHalSubGhzAsyncTxCallback callback, void* furi_hal_subghz_async_tx.buffer = malloc(API_HAL_SUBGHZ_ASYNC_TX_BUFFER_FULL * sizeof(uint32_t)); - if(furi_hal_subghz.radio_type == SubGhzRadioInternal) { - // Connect CC1101_GD0 to TIM2 as output - furi_hal_gpio_init_ex( - furi_hal_subghz.cc1101_g0_pin, - GpioModeAltFunctionPushPull, - GpioPullDown, - GpioSpeedLow, - GpioAltFn1TIM2); - } else { - //Signal generation with mem-to-mem DMA - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, true); - furi_hal_gpio_init( - furi_hal_subghz.cc1101_g0_pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - } + // Connect CC1101_GD0 to TIM2 as output + furi_hal_gpio_init_ex( + &gpio_cc1101_g0, GpioModeAltFunctionPushPull, GpioPullDown, GpioSpeedLow, GpioAltFn1TIM2); // Configure DMA LL_DMA_InitTypeDef dma_config = {0}; @@ -896,27 +777,15 @@ bool furi_hal_subghz_start_async_tx(FuriHalSubGhzAsyncTxCallback callback, void* LL_TIM_EnableCounter(TIM2); // Start debug - if(furi_hal_subghz_start_debug() || furi_hal_subghz.radio_type == SubGhzRadioExternal) { - const GpioPin* gpio = furi_hal_subghz.cc1101_g0_pin; - //Preparing bit mask - //Debug pin is may be only PORTB! (PB0, PB1, .., PB15) - furi_hal_subghz_debug_gpio_buff[0] = 0; - furi_hal_subghz_debug_gpio_buff[1] = 0; + if(furi_hal_subghz_start_debug()) { + const GpioPin* gpio = furi_hal_subghz.async_mirror_pin; + // //Preparing bit mask + // //Debug pin is may be only PORTB! (PB0, PB1, .., PB15) + // furi_hal_subghz_debug_gpio_buff[0] = 0; + // furi_hal_subghz_debug_gpio_buff[1] = 0; - //Mirror pin (for example, speaker) - if(furi_hal_subghz.async_mirror_pin != NULL) { - furi_hal_subghz_debug_gpio_buff[0] |= (uint32_t)furi_hal_subghz.async_mirror_pin->pin - << GPIO_NUMBER; - furi_hal_subghz_debug_gpio_buff[1] |= furi_hal_subghz.async_mirror_pin->pin; - gpio = furi_hal_subghz.async_mirror_pin; - } - - //G0 singnal generation for external radio - if(furi_hal_subghz.radio_type == SubGhzRadioExternal) { - furi_hal_subghz_debug_gpio_buff[0] |= (uint32_t)furi_hal_subghz.cc1101_g0_pin->pin - << GPIO_NUMBER; - furi_hal_subghz_debug_gpio_buff[1] |= furi_hal_subghz.cc1101_g0_pin->pin; - } + furi_hal_subghz_debug_gpio_buff[0] = (uint32_t)gpio->pin << GPIO_NUMBER; + furi_hal_subghz_debug_gpio_buff[1] = gpio->pin; dma_config.MemoryOrM2MDstAddress = (uint32_t)furi_hal_subghz_debug_gpio_buff; dma_config.PeriphOrM2MSrcAddress = (uint32_t) & (gpio->port->BSRR); @@ -949,9 +818,9 @@ void furi_hal_subghz_stop_async_tx() { // Shutdown radio furi_hal_subghz_idle(); - if(furi_hal_subghz.radio_type == SubGhzRadioExternal) { - furi_hal_gpio_write(furi_hal_subghz.cc1101_g0_pin, false); - } +#ifdef FURI_HAL_SUBGHZ_TX_GPIO + furi_hal_gpio_write(&FURI_HAL_SUBGHZ_TX_GPIO, false); +#endif // Deinitialize Timer FURI_CRITICAL_ENTER(); @@ -964,14 +833,10 @@ void furi_hal_subghz_stop_async_tx() { furi_hal_interrupt_set_isr(SUBGHZ_DMA_CH1_IRQ, NULL, NULL); // Deinitialize GPIO - furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeAnalog, GpioPullNo, GpioSpeedLow); + furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeAnalog, GpioPullNo, GpioSpeedLow); // Stop debug - furi_hal_subghz_stop_debug(); - - if(((furi_hal_subghz.async_mirror_pin != NULL) && - (furi_hal_subghz.radio_type == SubGhzRadioInternal)) || - (furi_hal_subghz.radio_type == SubGhzRadioExternal)) { + if(furi_hal_subghz_stop_debug()) { LL_DMA_DisableChannel(SUBGHZ_DMA_CH2_DEF); } diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.h b/firmware/targets/f7/furi_hal/furi_hal_subghz.h index 9b6056d77..5098eec1c 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz.h +++ b/firmware/targets/f7/furi_hal/furi_hal_subghz.h @@ -10,7 +10,7 @@ #include #include #include -#include +// #include #ifdef __cplusplus extern "C" { @@ -41,50 +41,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; - -/** SubGhz radio types */ -typedef enum { - SubGhzRadioInternal, - SubGhzRadioExternal, -} SubGhzRadioType; - -/** Structure for accessing SubGhz settings*/ -typedef struct { - volatile SubGhzState state; - volatile SubGhzRegulation regulation; - volatile FuriHalSubGhzPreset preset; - const GpioPin* async_mirror_pin; - SubGhzRadioType radio_type; - FuriHalSpiBusHandle* spi_bus_handle; - const GpioPin* cc1101_g0_pin; - uint8_t rolling_counter_mult; - bool ext_module_power_disabled : 1; - bool timestamp_file_names : 1; - bool extended_frequency_i : 1; -} FuriHalSubGhz; - -extern volatile FuriHalSubGhz furi_hal_subghz; - /* Mirror RX/TX async modulation signal to specified pin * * @warning Configures pin to output mode. Make sure it is not connected @@ -100,13 +56,6 @@ void furi_hal_subghz_set_async_mirror_pin(const GpioPin* pin); */ void furi_hal_subghz_init(); -/** 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 - * @return true if initialisation is successfully - */ -bool furi_hal_subghz_init_check(void); - /** Send device to sleep mode */ void furi_hal_subghz_sleep(); @@ -234,6 +183,16 @@ uint32_t furi_hal_subghz_set_frequency_and_path(uint32_t value); */ bool furi_hal_subghz_is_tx_allowed(uint32_t value); +/** Get the current rolling protocols counter ++ value + * @return uint8_t current value + */ +uint8_t furi_hal_subghz_get_rolling_counter_mult(void); + +/** Set the current rolling protocols counter ++ value + * @param mult uint8_t = 1, 2, 4, 8 + */ +void furi_hal_subghz_set_rolling_counter_mult(uint8_t mult); + /** Set frequency * * @param value frequency in Hz @@ -289,52 +248,49 @@ bool furi_hal_subghz_is_async_tx_complete(); */ void furi_hal_subghz_stop_async_tx(); -/** Switching between internal and external radio - * @param state SubGhzRadioInternal or SubGhzRadioExternal - * @return true if switching is successful - */ -bool furi_hal_subghz_init_radio_type(SubGhzRadioType state); +// /** 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 +// * @return true if initialisation is successfully +// */ +// bool furi_hal_subghz_init_check(void); -/** Get current radio - * @return SubGhzRadioInternal or SubGhzRadioExternal - */ -SubGhzRadioType furi_hal_subghz_get_radio_type(void); +// /** Switching between internal and external radio +// * @param state SubGhzRadioInternal or SubGhzRadioExternal +// * @return true if switching is successful +// */ +// bool furi_hal_subghz_init_radio_type(SubGhzRadioType state); -/** Check for a radio module - * @return true if check is successful - */ -bool furi_hal_subghz_check_radio(void); +// /** Get current radio +// * @return SubGhzRadioInternal or SubGhzRadioExternal +// */ +// SubGhzRadioType furi_hal_subghz_get_radio_type(void); -/** Turn on the power of the external radio module - * @return true if power-up is successful - */ -bool furi_hal_subghz_enable_ext_power(void); +// /** Check for a radio module +// * @return true if check is successful +// */ +// bool furi_hal_subghz_check_radio(void); -/** Turn off the power of the external radio module - */ -void furi_hal_subghz_disable_ext_power(void); +// /** Turn on the power of the external radio module +// * @return true if power-up is successful +// */ +// bool furi_hal_subghz_enable_ext_power(void); -/** Get the current rolling protocols counter ++ value - * @return uint8_t current value - */ -uint8_t furi_hal_subghz_get_rolling_counter_mult(void); +// /** Turn off the power of the external radio module +// */ +// void furi_hal_subghz_disable_ext_power(void); -/** Set the current rolling protocols counter ++ value - * @param mult uint8_t = 1, 2, 4, 8 - */ -void furi_hal_subghz_set_rolling_counter_mult(uint8_t mult); +// /** If true - disable 5v power of the external radio module +// */ +// void furi_hal_subghz_set_external_power_disable(bool state); -/** If true - disable 5v power of the external radio module - */ -void furi_hal_subghz_set_external_power_disable(bool state); +// /** Get the current state of the external power disable flag +// */ +// bool furi_hal_subghz_get_external_power_disable(void); -/** Get the current state of the external power disable flag - */ -bool furi_hal_subghz_get_external_power_disable(void); - -/** Set what radio module we will be using - */ -void furi_hal_subghz_select_radio_type(SubGhzRadioType state); +// /** Set what radio module we will be using +// */ +// void furi_hal_subghz_select_radio_type(SubGhzRadioType state); #ifdef __cplusplus } 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 b2b5760fd..000000000 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz_configs.h +++ /dev/null @@ -1,304 +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_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/furi_hal/furi_hal_version.c b/firmware/targets/f7/furi_hal/furi_hal_version.c index 66580945e..ce8700fc8 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_version.c +++ b/firmware/targets/f7/furi_hal/furi_hal_version.c @@ -112,9 +112,9 @@ void furi_hal_version_set_name(const char* name) { uint32_t company_id = LL_FLASH_GetSTCompanyID(); // uint32_t device_id = LL_FLASH_GetDeviceID(); - // Somehow some new flippers return 0x27 instead of 0x26 - // Mobile apps expects it to return 0x26 (and clearly STM too) - // Hardcoded here instead of the stupid "Flipper" name "fix" + // 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); diff --git a/firmware/targets/f7/furi_hal/furi_hal_version_device.c b/firmware/targets/f7/furi_hal/furi_hal_version_device.c index c059c2cbe..be3f4bf3f 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_version_device.c +++ b/firmware/targets/f7/furi_hal/furi_hal_version_device.c @@ -19,3 +19,7 @@ const char* furi_hal_version_get_fcc_id() { const char* furi_hal_version_get_ic_id() { return "27624-FZ"; } + +const char* furi_hal_version_get_mic_id() { + return "210-175991"; +} diff --git a/firmware/targets/f7/platform_specific/intrinsic_export.h b/firmware/targets/f7/platform_specific/intrinsic_export.h index 8dbc4bd03..c0d76fb89 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 #ifdef __cplusplus 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 diff --git a/firmware/targets/furi_hal_include/furi_hal_bt.h b/firmware/targets/furi_hal_include/furi_hal_bt.h index 132d0b95d..21df2cf92 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 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/firmware/targets/furi_hal_include/furi_hal_version.h b/firmware/targets/furi_hal_include/furi_hal_version.h index 92f2ec9ca..95bb61db7 100644 --- a/firmware/targets/furi_hal_include/furi_hal_version.h +++ b/firmware/targets/furi_hal_include/furi_hal_version.h @@ -20,12 +20,6 @@ extern "C" { #define FURI_HAL_VERSION_DEVICE_NAME_LENGTH \ (1 + FURI_HAL_BT_ADV_NAME_LENGTH) // Used for custom BT name, BLE symbol + name -#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 } - /** OTP Versions enum */ typedef enum { FuriHalVersionOtpVersion0 = 0x00, @@ -92,6 +86,12 @@ const char* furi_hal_version_get_fcc_id(); */ const char* furi_hal_version_get_ic_id(); +/** Get MIC id + * + * @return MIC id as C-string + */ +const char* furi_hal_version_get_mic_id(); + /** Get OTP version * * @return OTP Version 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" \ diff --git a/furi/core/log.c b/furi/core/log.c index d910ecf21..53467ecdb 100644 --- a/furi/core/log.c +++ b/furi/core/log.c @@ -14,6 +14,21 @@ typedef struct { static FuriLogParams furi_log; +typedef struct { + const char* str; + FuriLogLevel level; +} FuriLogLevelDescription; + +static const FuriLogLevelDescription FURI_LOG_LEVEL_DESCRIPTIONS[] = { + {"default", FuriLogLevelDefault}, + {"none", FuriLogLevelNone}, + {"error", FuriLogLevelError}, + {"warn", FuriLogLevelWarn}, + {"info", FuriLogLevelInfo}, + {"debug", FuriLogLevelDebug}, + {"trace", FuriLogLevelTrace}, +}; + void furi_log_init() { // Set default logging parameters furi_log.log_level = FURI_LOG_LEVEL_DEFAULT; @@ -117,3 +132,23 @@ void furi_log_set_timestamp(FuriLogTimestamp timestamp) { furi_assert(timestamp); furi_log.timestamp = timestamp; } + +bool furi_log_level_to_string(FuriLogLevel level, const char** str) { + for(size_t i = 0; i < COUNT_OF(FURI_LOG_LEVEL_DESCRIPTIONS); i++) { + if(level == FURI_LOG_LEVEL_DESCRIPTIONS[i].level) { + *str = FURI_LOG_LEVEL_DESCRIPTIONS[i].str; + return true; + } + } + return false; +} + +bool furi_log_level_from_string(const char* str, FuriLogLevel* level) { + for(size_t i = 0; i < COUNT_OF(FURI_LOG_LEVEL_DESCRIPTIONS); i++) { + if(strcmp(str, FURI_LOG_LEVEL_DESCRIPTIONS[i].str) == 0) { + *level = FURI_LOG_LEVEL_DESCRIPTIONS[i].level; + return true; + } + } + return false; +} \ No newline at end of file diff --git a/furi/core/log.h b/furi/core/log.h index 46ae7f007..5d11add9b 100644 --- a/furi/core/log.h +++ b/furi/core/log.h @@ -7,6 +7,7 @@ #include #include #include +#include #ifdef __cplusplus extern "C" { @@ -87,6 +88,23 @@ void furi_log_set_puts(FuriLogPuts puts); */ void furi_log_set_timestamp(FuriLogTimestamp timestamp); +/** Log level to string + * + * @param[in] level The level + * + * @return The string + */ +bool furi_log_level_to_string(FuriLogLevel level, const char** str); + +/** Log level from string + * + * @param[in] str The string + * @param level The level + * + * @return True if success, False otherwise + */ +bool furi_log_level_from_string(const char* str, FuriLogLevel* level); + /** Log methods * * @param tag The application tag 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 diff --git a/lib/drivers/cc1101.c b/lib/drivers/cc1101.c index d0feb0218..85d915acd 100644 --- a/lib/drivers/cc1101.c +++ b/lib/drivers/cc1101.c @@ -1,14 +1,27 @@ #include "cc1101.h" #include #include +#include + +static bool cc1101_spi_trx(FuriHalSpiBusHandle* handle, uint8_t* tx, uint8_t* rx, uint8_t size) { + FuriHalCortexTimer timer = furi_hal_cortex_timer_get(CC1101_TIMEOUT * 1000); + + while(furi_hal_gpio_read(handle->miso)) { + if(furi_hal_cortex_timer_is_expired(timer)) { + //timeout + return false; + } + } + if(!furi_hal_spi_bus_trx(handle, tx, rx, size, CC1101_TIMEOUT)) return false; + return true; +} CC1101Status cc1101_strobe(FuriHalSpiBusHandle* handle, uint8_t strobe) { uint8_t tx[1] = {strobe}; CC1101Status rx[1] = {0}; + rx[0].CHIP_RDYn = 1; - while(furi_hal_gpio_read(handle->miso)) - ; - furi_hal_spi_bus_trx(handle, tx, (uint8_t*)rx, 1, CC1101_TIMEOUT); + cc1101_spi_trx(handle, tx, (uint8_t*)rx, 1); assert(rx[0].CHIP_RDYn == 0); return rx[0]; @@ -17,10 +30,10 @@ CC1101Status cc1101_strobe(FuriHalSpiBusHandle* handle, uint8_t strobe) { CC1101Status cc1101_write_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t data) { uint8_t tx[2] = {reg, data}; CC1101Status rx[2] = {0}; + rx[0].CHIP_RDYn = 1; + rx[1].CHIP_RDYn = 1; - while(furi_hal_gpio_read(handle->miso)) - ; - furi_hal_spi_bus_trx(handle, tx, (uint8_t*)rx, 2, CC1101_TIMEOUT); + cc1101_spi_trx(handle, tx, (uint8_t*)rx, 2); assert((rx[0].CHIP_RDYn | rx[1].CHIP_RDYn) == 0); return rx[1]; @@ -30,10 +43,9 @@ CC1101Status cc1101_read_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* assert(sizeof(CC1101Status) == 1); uint8_t tx[2] = {reg | CC1101_READ, 0}; CC1101Status rx[2] = {0}; + rx[0].CHIP_RDYn = 1; - while(furi_hal_gpio_read(handle->miso)) - ; - furi_hal_spi_bus_trx(handle, tx, (uint8_t*)rx, 2, CC1101_TIMEOUT); + cc1101_spi_trx(handle, tx, (uint8_t*)rx, 2); assert((rx[0].CHIP_RDYn) == 0); *data = *(uint8_t*)&rx[1]; @@ -58,40 +70,40 @@ uint8_t cc1101_get_rssi(FuriHalSpiBusHandle* handle) { return rssi; } -void cc1101_reset(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SRES); +CC1101Status cc1101_reset(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SRES); } CC1101Status cc1101_get_status(FuriHalSpiBusHandle* handle) { return cc1101_strobe(handle, CC1101_STROBE_SNOP); } -void cc1101_shutdown(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SPWD); +CC1101Status cc1101_shutdown(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SPWD); } -void cc1101_calibrate(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SCAL); +CC1101Status cc1101_calibrate(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SCAL); } -void cc1101_switch_to_idle(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SIDLE); +CC1101Status cc1101_switch_to_idle(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SIDLE); } -void cc1101_switch_to_rx(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SRX); +CC1101Status cc1101_switch_to_rx(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SRX); } -void cc1101_switch_to_tx(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_STX); +CC1101Status cc1101_switch_to_tx(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_STX); } -void cc1101_flush_rx(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SFRX); +CC1101Status cc1101_flush_rx(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SFRX); } -void cc1101_flush_tx(FuriHalSpiBusHandle* handle) { - cc1101_strobe(handle, CC1101_STROBE_SFTX); +CC1101Status cc1101_flush_tx(FuriHalSpiBusHandle* handle) { + return cc1101_strobe(handle, CC1101_STROBE_SFTX); } uint32_t cc1101_set_frequency(FuriHalSpiBusHandle* handle, uint32_t value) { @@ -123,12 +135,12 @@ uint32_t cc1101_set_intermediate_frequency(FuriHalSpiBusHandle* handle, uint32_t void cc1101_set_pa_table(FuriHalSpiBusHandle* handle, const uint8_t value[8]) { uint8_t tx[9] = {CC1101_PATABLE | CC1101_BURST}; //-V1009 CC1101Status rx[9] = {0}; + rx[0].CHIP_RDYn = 1; + rx[8].CHIP_RDYn = 1; memcpy(&tx[1], &value[0], 8); - while(furi_hal_gpio_read(handle->miso)) - ; - furi_hal_spi_bus_trx(handle, tx, (uint8_t*)rx, sizeof(rx), CC1101_TIMEOUT); + cc1101_spi_trx(handle, tx, (uint8_t*)rx, sizeof(rx)); assert((rx[0].CHIP_RDYn | rx[8].CHIP_RDYn) == 0); } @@ -139,12 +151,7 @@ uint8_t cc1101_write_fifo(FuriHalSpiBusHandle* handle, const uint8_t* data, uint buff_tx[0] = CC1101_FIFO | CC1101_BURST; memcpy(&buff_tx[1], data, size); - // Start transaction - // Wait IC to become ready - while(furi_hal_gpio_read(handle->miso)) - ; - // Tell IC what we want - furi_hal_spi_bus_trx(handle, buff_tx, (uint8_t*)buff_rx, size + 1, CC1101_TIMEOUT); + cc1101_spi_trx(handle, buff_tx, (uint8_t*)buff_rx, size + 1); return size; } @@ -153,13 +160,7 @@ uint8_t cc1101_read_fifo(FuriHalSpiBusHandle* handle, uint8_t* data, uint8_t* si uint8_t buff_trx[2]; buff_trx[0] = CC1101_FIFO | CC1101_READ | CC1101_BURST; - // Start transaction - // Wait IC to become ready - while(furi_hal_gpio_read(handle->miso)) - ; - - // First byte - packet length - furi_hal_spi_bus_trx(handle, buff_trx, buff_trx, 2, CC1101_TIMEOUT); + cc1101_spi_trx(handle, buff_trx, buff_trx, 2); // Check that the packet is placed in the receive buffer if(buff_trx[1] > 64) { diff --git a/lib/drivers/cc1101.h b/lib/drivers/cc1101.h index af1f15569..d8ee05d52 100644 --- a/lib/drivers/cc1101.h +++ b/lib/drivers/cc1101.h @@ -46,8 +46,10 @@ CC1101Status cc1101_read_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* /** Reset * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_reset(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_reset(FuriHalSpiBusHandle* handle); /** Get status * @@ -60,8 +62,10 @@ CC1101Status cc1101_get_status(FuriHalSpiBusHandle* handle); /** Enable shutdown mode * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_shutdown(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_shutdown(FuriHalSpiBusHandle* handle); /** Get Partnumber * @@ -90,38 +94,46 @@ uint8_t cc1101_get_rssi(FuriHalSpiBusHandle* handle); /** Calibrate oscillator * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_calibrate(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_calibrate(FuriHalSpiBusHandle* handle); /** Switch to idle * * @param handle - pointer to FuriHalSpiHandle */ -void cc1101_switch_to_idle(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_switch_to_idle(FuriHalSpiBusHandle* handle); /** Switch to RX * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_switch_to_rx(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_switch_to_rx(FuriHalSpiBusHandle* handle); /** Switch to TX * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_switch_to_tx(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_switch_to_tx(FuriHalSpiBusHandle* handle); /** Flush RX FIFO * * @param handle - pointer to FuriHalSpiHandle + * + * @return CC1101Status structure */ -void cc1101_flush_rx(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_flush_rx(FuriHalSpiBusHandle* handle); /** Flush TX FIFO * * @param handle - pointer to FuriHalSpiHandle */ -void cc1101_flush_tx(FuriHalSpiBusHandle* handle); +CC1101Status cc1101_flush_tx(FuriHalSpiBusHandle* handle); /** Set Frequency * diff --git a/lib/drivers/cc1101_regs.h b/lib/drivers/cc1101_regs.h index a326dc92c..e0aed6bd9 100644 --- a/lib/drivers/cc1101_regs.h +++ b/lib/drivers/cc1101_regs.h @@ -14,7 +14,7 @@ extern "C" { #define CC1101_IFDIV 0x400 /* IO Bus constants */ -#define CC1101_TIMEOUT 500 +#define CC1101_TIMEOUT 250 /* Bits and pieces */ #define CC1101_READ (1 << 7) /** Read Bit */ diff --git a/lib/nfc/SConscript b/lib/nfc/SConscript index b8551db84..7a0859ee4 100644 --- a/lib/nfc/SConscript +++ b/lib/nfc/SConscript @@ -6,6 +6,11 @@ env.Append( ], SDK_HEADERS=[ File("nfc_device.h"), + File("nfc_worker.h"), + File("nfc_types.h"), + File("helpers/mfkey32.h"), + File("parsers/nfc_supported_card.h"), + File("helpers/nfc_generators.h"), File("protocols/nfc_util.h"), ], ) 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; } diff --git a/lib/nfc/helpers/mf_classic_dict.h b/lib/nfc/helpers/mf_classic_dict.h index 1884fdda1..71002664a 100644 --- a/lib/nfc/helpers/mf_classic_dict.h +++ b/lib/nfc/helpers/mf_classic_dict.h @@ -6,6 +6,10 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + typedef enum { MfClassicDictTypeUser, MfClassicDictTypeSystem, @@ -97,3 +101,7 @@ bool mf_classic_dict_find_index_str(MfClassicDict* dict, FuriString* key, uint32 * @return true on success */ bool mf_classic_dict_delete_index(MfClassicDict* dict, uint32_t target); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/helpers/mfkey32.h b/lib/nfc/helpers/mfkey32.h index e1f472e50..e29043224 100644 --- a/lib/nfc/helpers/mfkey32.h +++ b/lib/nfc/helpers/mfkey32.h @@ -2,6 +2,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + typedef struct Mfkey32 Mfkey32; typedef enum { @@ -24,3 +28,7 @@ void mfkey32_process_data( void mfkey32_set_callback(Mfkey32* instance, Mfkey32ParseDataCallback callback, void* context); uint16_t mfkey32_get_auth_sectors(FuriString* string); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/nfc_types.h b/lib/nfc/nfc_types.h index 9d0bab1d7..206d99fde 100644 --- a/lib/nfc/nfc_types.h +++ b/lib/nfc/nfc_types.h @@ -2,6 +2,10 @@ #include "nfc_device.h" +#ifdef __cplusplus +extern "C" { +#endif + const char* nfc_get_dev_type(FuriHalNfcType type); const char* nfc_guess_protocol(NfcProtocol protocol); @@ -10,4 +14,7 @@ const char* nfc_mf_ul_type(MfUltralightType type, bool full_name); const char* nfc_mf_classic_type(MfClassicType type); -const char* nfc_felica_type(FelicaICType type); \ No newline at end of file +const char* nfc_felica_type(FelicaICType type); +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_worker.c b/lib/nfc/nfc_worker.c index 984108a92..bc97d743d 100644 --- a/lib/nfc/nfc_worker.c +++ b/lib/nfc/nfc_worker.c @@ -869,6 +869,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( @@ -888,6 +890,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( @@ -1163,7 +1167,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) { @@ -1436,8 +1442,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) { @@ -1448,7 +1452,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++; @@ -1460,6 +1466,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/nfc_worker.h b/lib/nfc/nfc_worker.h index a175c212e..3407a2d7c 100644 --- a/lib/nfc/nfc_worker.h +++ b/lib/nfc/nfc_worker.h @@ -2,6 +2,10 @@ #include "nfc_device.h" +#ifdef __cplusplus +extern "C" { +#endif + typedef struct NfcWorker NfcWorker; typedef enum { @@ -100,3 +104,7 @@ void nfc_worker_stop(NfcWorker* nfc_worker); void nfc_worker_nfcv_unlock(NfcWorker* nfc_worker); void nfc_worker_nfcv_emulate(NfcWorker* nfc_worker); void nfc_worker_nfcv_sniff(NfcWorker* nfc_worker); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/parsers/nfc_supported_card.h b/lib/nfc/parsers/nfc_supported_card.h index 877bda737..2e8c48a87 100644 --- a/lib/nfc/parsers/nfc_supported_card.h +++ b/lib/nfc/parsers/nfc_supported_card.h @@ -4,6 +4,10 @@ #include "../nfc_worker.h" #include "../nfc_device.h" +#ifdef __cplusplus +extern "C" { +#endif + typedef enum { NfcSupportedCardTypePlantain, NfcSupportedCardTypeTroika, @@ -37,3 +41,7 @@ bool nfc_supported_card_verify_and_parse(NfcDeviceData* dev_data); // support the card. This is needed for DESFire card parsers which can't // provide keys, and only use NfcSupportedCard->parse. bool stub_parser_verify_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/protocols/crypto1.h b/lib/nfc/protocols/crypto1.h index 450d1534e..bbf6dc239 100644 --- a/lib/nfc/protocols/crypto1.h +++ b/lib/nfc/protocols/crypto1.h @@ -3,6 +3,10 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + typedef struct { uint32_t odd; uint32_t even; @@ -35,3 +39,7 @@ void crypto1_encrypt( uint16_t plain_data_bits, uint8_t* encrypted_data, uint8_t* encrypted_parity); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/protocols/mifare_classic.c b/lib/nfc/protocols/mifare_classic.c index f11d81f37..8fd396cff 100644 --- a/lib/nfc/protocols/mifare_classic.c +++ b/lib/nfc/protocols/mifare_classic.c @@ -856,16 +856,20 @@ bool mf_classic_emulator( bool is_reader_analyzer) { furi_assert(emulator); furi_assert(tx_rx); - bool command_processed = false; - bool is_encrypted = false; uint8_t plain_data[MF_CLASSIC_MAX_DATA_SIZE]; MfClassicKey access_key = MfClassicKeyA; + bool need_reset = false; + bool need_nack = false; + bool is_encrypted = false; + uint8_t sector = 0; + // Used for decrement and increment - copy to block on transfer - uint8_t transfer_buf[MF_CLASSIC_BLOCK_SIZE] = {}; + uint8_t transfer_buf[MF_CLASSIC_BLOCK_SIZE]; bool transfer_buf_valid = false; - // Read command - while(!command_processed) { //-V654 + // Process commands + while(!need_reset && !need_nack) { //-V654 + memset(plain_data, 0, MF_CLASSIC_MAX_DATA_SIZE); if(!is_encrypted) { crypto1_reset(&emulator->crypto); memcpy(plain_data, tx_rx->rx_data, tx_rx->rx_bits / 8); @@ -873,9 +877,10 @@ 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); + need_reset = true; break; } crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); @@ -884,19 +889,28 @@ bool mf_classic_emulator( // After increment, decrement or restore the only allowed command is transfer uint8_t cmd = plain_data[0]; if(transfer_buf_valid && cmd != MF_CLASSIC_TRANSFER_CMD) { + need_nack = true; 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; + need_reset = true; break; } + + if(cmd == NFCA_CMD_RATS) { + // Mifare Classic doesn't support ATS, NACK it and start listening again + FURI_LOG_T(TAG, "RATS received"); + need_nack = true; + 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; uint8_t sector_trailer_block = mf_classic_get_sector_trailer_num_by_block(block); + sector = mf_classic_get_sector_by_block(block); MfClassicSectorTrailer* sector_trailer = (MfClassicSectorTrailer*)emulator->data.block[sector_trailer_block].value; if(cmd == MF_CLASSIC_AUTH_KEY_A_CMD) { @@ -907,7 +921,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyA; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; + need_nack = true; break; } } else { @@ -918,7 +932,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyB; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; + need_nack = true; break; } } @@ -947,15 +961,15 @@ 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; + need_reset = true; break; } if(tx_rx->rx_bits != 64) { - FURI_LOG_W(TAG, "Incorrect nr + ar length: %d", tx_rx->rx_bits); - command_processed = true; + need_reset = true; break; } @@ -965,9 +979,14 @@ bool mf_classic_emulator( crypto1_word(&emulator->crypto, nr, 1); uint32_t cardRr = ar ^ crypto1_word(&emulator->crypto, 0, 0); if(cardRr != prng_successor(nonce, 64)) { - FURI_LOG_T(TAG, "Wrong AUTH! %08lX != %08lX", cardRr, prng_successor(nonce, 64)); + FURI_LOG_T( + TAG, + "Wrong AUTH on block %u! %08lX != %08lX", + block, + cardRr, + prng_successor(nonce, 64)); // Don't send NACK, as the tag doesn't send it - command_processed = true; + need_reset = true; break; } @@ -990,11 +1009,25 @@ bool mf_classic_emulator( if(!is_encrypted) { FURI_LOG_T(TAG, "Invalid command before auth session established: %02X", cmd); + need_nack = true; break; } - if(cmd == MF_CLASSIC_READ_BLOCK_CMD) { - uint8_t block = plain_data[1]; + // Mifare Classic commands always have block number after command + uint8_t block = plain_data[1]; + if(mf_classic_get_sector_by_block(block) != sector) { + // Don't allow access to sectors other than authorized + FURI_LOG_T( + TAG, + "Trying to access block %u from not authorized sector (command: %02X)", + block, + cmd); + need_nack = true; + break; + } + + switch(cmd) { + case MF_CLASSIC_READ_BLOCK_CMD: { uint8_t block_data[MF_CLASSIC_BLOCK_SIZE + 2] = {}; memcpy(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE); if(mf_classic_is_sector_trailer(block)) { @@ -1010,17 +1043,14 @@ bool mf_classic_emulator( emulator, block, access_key, MfClassicActionACRead)) { memset(&block_data[6], 0, 4); } - } else if(!mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionDataRead)) { - // Send NACK - uint8_t nack = 0x04; - crypto1_encrypt( - &emulator->crypto, NULL, &nack, 4, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - furi_hal_nfc_tx_rx(tx_rx, 300); + } else if( + !mf_classic_is_allowed_access( + emulator, block, access_key, MfClassicActionDataRead) || + !mf_classic_is_block_read(&emulator->data, block)) { + need_nack = true; break; } + nfca_append_crc16(block_data, 16); crypto1_encrypt( @@ -1032,23 +1062,36 @@ bool mf_classic_emulator( tx_rx->tx_parity); tx_rx->tx_bits = (MF_CLASSIC_BLOCK_SIZE + 2) * 8; tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - } else if(cmd == MF_CLASSIC_WRITE_BLOCK_CMD) { - uint8_t block = plain_data[1]; - if(block > mf_classic_get_total_block_num(emulator->data.type)) { - break; - } + break; + } + + case MF_CLASSIC_WRITE_BLOCK_CMD: { // Send ACK uint8_t ack = MF_CLASSIC_ACK_CMD; crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - if(tx_rx->rx_bits != (MF_CLASSIC_BLOCK_SIZE + 2) * 8) break; + if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { + need_reset = true; + break; + } + + if(tx_rx->rx_bits != (MF_CLASSIC_BLOCK_SIZE + 2) * 8) { + need_reset = true; + break; + } crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); uint8_t block_data[MF_CLASSIC_BLOCK_SIZE] = {}; memcpy(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE); + + if(!mf_classic_is_block_read(&emulator->data, block)) { + // Don't allow writing to the block for which we haven't read data yet + need_nack = true; + break; + } + if(mf_classic_is_sector_trailer(block)) { if(mf_classic_is_allowed_access( emulator, block, access_key, MfClassicActionKeyAWrite)) { @@ -1067,38 +1110,39 @@ bool mf_classic_emulator( emulator, block, access_key, MfClassicActionDataWrite)) { memcpy(block_data, plain_data, MF_CLASSIC_BLOCK_SIZE); } else { + need_nack = true; break; } } + if(memcmp(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE) != 0) { memcpy(emulator->data.block[block].value, block_data, MF_CLASSIC_BLOCK_SIZE); emulator->data_changed = true; } + // Send ACK ack = MF_CLASSIC_ACK_CMD; crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; - } else if( - cmd == MF_CLASSIC_DECREMENT_CMD || cmd == MF_CLASSIC_INCREMENT_CMD || - cmd == MF_CLASSIC_RESTORE_CMD) { - uint8_t block = plain_data[1]; + break; + } - if(block > mf_classic_get_total_block_num(emulator->data.type)) { - break; - } + case MF_CLASSIC_DECREMENT_CMD: + case MF_CLASSIC_INCREMENT_CMD: + case MF_CLASSIC_RESTORE_CMD: { + MfClassicAction action = (cmd == MF_CLASSIC_INCREMENT_CMD) ? MfClassicActionDataInc : + MfClassicActionDataDec; - MfClassicAction action = MfClassicActionDataDec; - if(cmd == MF_CLASSIC_INCREMENT_CMD) { - action = MfClassicActionDataInc; - } if(!mf_classic_is_allowed_access(emulator, block, access_key, action)) { + need_nack = true; break; } int32_t prev_value; uint8_t addr; if(!mf_classic_block_to_value(emulator->data.block[block].value, &prev_value, &addr)) { + need_nack = true; break; } @@ -1108,8 +1152,15 @@ bool mf_classic_emulator( tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - if(tx_rx->rx_bits != (sizeof(int32_t) + 2) * 8) break; + if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { + need_reset = true; + break; + } + + if(tx_rx->rx_bits != (sizeof(int32_t) + 2) * 8) { + need_reset = true; + break; + } crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); int32_t value = *(int32_t*)&plain_data[0]; @@ -1126,9 +1177,12 @@ bool mf_classic_emulator( transfer_buf_valid = true; // Commands do not ACK tx_rx->tx_bits = 0; - } else if(cmd == MF_CLASSIC_TRANSFER_CMD) { - uint8_t block = plain_data[1]; + break; + } + + case MF_CLASSIC_TRANSFER_CMD: { if(!mf_classic_is_allowed_access(emulator, block, access_key, MfClassicActionDataDec)) { + need_nack = true; break; } if(memcmp(transfer_buf, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE) != @@ -1142,13 +1196,17 @@ bool mf_classic_emulator( crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; - } else { + break; + } + + default: FURI_LOG_T(TAG, "Unknown command: %02X", cmd); + need_nack = true; break; } } - if(!command_processed) { + if(need_nack && !need_reset) { // Send NACK uint8_t nack = transfer_buf_valid ? MF_CLASSIC_NACK_BUF_VALID_CMD : MF_CLASSIC_NACK_BUF_INVALID_CMD; @@ -1160,15 +1218,16 @@ bool mf_classic_emulator( tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; furi_hal_nfc_tx_rx(tx_rx, 300); + need_reset = true; } - return true; + return !need_reset; } 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/mifare_classic.h b/lib/nfc/protocols/mifare_classic.h index 4e35ac671..60d9ab743 100644 --- a/lib/nfc/protocols/mifare_classic.h +++ b/lib/nfc/protocols/mifare_classic.h @@ -4,6 +4,10 @@ #include "crypto1.h" +#ifdef __cplusplus +extern "C" { +#endif + #define MF_CLASSIC_BLOCK_SIZE (16) #define MF_CLASSIC_TOTAL_BLOCKS_MAX (256) #define MF_MINI_TOTAL_SECTORS_NUM (5) @@ -241,3 +245,7 @@ bool mf_classic_write_sector( MfClassicData* dest_data, MfClassicData* src_data, uint8_t sec_num); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/protocols/mifare_desfire.h b/lib/nfc/protocols/mifare_desfire.h index 93d61c925..7d5915b76 100644 --- a/lib/nfc/protocols/mifare_desfire.h +++ b/lib/nfc/protocols/mifare_desfire.h @@ -5,6 +5,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + #define MF_DF_GET_VERSION (0x60) #define MF_DF_GET_FREE_MEMORY (0x6E) #define MF_DF_GET_KEY_SETTINGS (0x45) @@ -169,3 +173,7 @@ uint16_t mf_df_prepare_read_records(uint8_t* dest, uint8_t file_id, uint32_t off bool mf_df_parse_read_data_response(uint8_t* buf, uint16_t len, MifareDesfireFile* out); bool mf_df_read_card(FuriHalNfcTxRxContext* tx_rx, MifareDesfireData* data); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/nfc/protocols/mifare_ultralight.h b/lib/nfc/protocols/mifare_ultralight.h index ae16a9182..64d61da56 100644 --- a/lib/nfc/protocols/mifare_ultralight.h +++ b/lib/nfc/protocols/mifare_ultralight.h @@ -2,6 +2,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + // Largest tag is NTAG I2C Plus 2K, both data sectors plus SRAM #define MF_UL_MAX_DUMP_SIZE ((238 + 256 + 16) * 4) @@ -259,3 +263,7 @@ uint32_t mf_ul_pwdgen_amiibo(FuriHalNfcDevData* data); uint32_t mf_ul_pwdgen_xiaomi(FuriHalNfcDevData* data); bool mf_ul_is_full_capture(MfUltralightData* data); + +#ifdef __cplusplus +} +#endif \ No newline at end of file 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; diff --git a/lib/subghz/SConscript b/lib/subghz/SConscript index 40e5a9b63..ae0816582 100644 --- a/lib/subghz/SConscript +++ b/lib/subghz/SConscript @@ -10,6 +10,7 @@ env.Append( File("registry.h"), File("subghz_worker.h"), File("subghz_tx_rx_worker.h"), + File("subghz_file_encoder_worker.h"), File("transmitter.h"), File("protocols/raw.h"), File("blocks/const.h"), @@ -18,6 +19,7 @@ env.Append( File("blocks/encoder.h"), File("blocks/generic.h"), File("blocks/math.h"), + File("blocks/custom_btn.h"), File("subghz_setting.h"), File("subghz_protocol_registry.h"), ], diff --git a/lib/subghz/devices/cc1101_configs.c b/lib/subghz/devices/cc1101_configs.c new file mode 100644 index 000000000..6b5b9f1f7 --- /dev/null +++ b/lib/subghz/devices/cc1101_configs.c @@ -0,0 +1,482 @@ +#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, +}; + +// Shpargalka +// const uint8_t subghz_device_cc1101_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}; + +// const uint8_t subghz_device_cc1101_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}; + +// const uint8_t subghz_device_cc1101_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}; + +// const uint8_t subghz_device_cc1101_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}; + +// const uint8_t subghz_device_cc1101_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}; \ No newline at end of file diff --git a/lib/subghz/devices/cc1101_configs.h b/lib/subghz/devices/cc1101_configs.h new file mode 100644 index 000000000..0e1ffb0c7 --- /dev/null +++ b/lib/subghz/devices/cc1101_configs.h @@ -0,0 +1,23 @@ +#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[]; + +// extern const uint8_t subghz_device_cc1101_preset_ook_async_patable[8]; +// extern const uint8_t subghz_device_cc1101_preset_ook_async_patable_au[8]; +// extern const uint8_t subghz_device_cc1101_preset_2fsk_async_patable[8]; +// extern const uint8_t subghz_device_cc1101_preset_msk_async_patable[8]; +// extern const uint8_t subghz_device_cc1101_preset_gfsk_async_patable[8]; + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/lib/subghz/devices/devices.c b/lib/subghz/devices/devices.c new file mode 100644 index 000000000..a90bf73a3 --- /dev/null +++ b/lib/subghz/devices/devices.c @@ -0,0 +1,237 @@ +#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); + 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/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); + } } 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: diff --git a/lib/subghz/subghz_file_encoder_worker.h b/lib/subghz/subghz_file_encoder_worker.h index 19a46f1e6..f90875c98 100644 --- a/lib/subghz/subghz_file_encoder_worker.h +++ b/lib/subghz/subghz_file_encoder_worker.h @@ -2,6 +2,10 @@ #include +#ifdef __cplusplus +extern "C" { +#endif + typedef void (*SubGhzFileEncoderWorkerCallbackEnd)(void* context); typedef struct SubGhzFileEncoderWorker SubGhzFileEncoderWorker; @@ -63,3 +67,7 @@ void subghz_file_encoder_worker_stop(SubGhzFileEncoderWorker* instance); * @return bool - true if running */ bool subghz_file_encoder_worker_is_running(SubGhzFileEncoderWorker* instance); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/subghz_protocol_registry.h b/lib/subghz/subghz_protocol_registry.h index 6a27da992..e5cf75cda 100644 --- a/lib/subghz/subghz_protocol_registry.h +++ b/lib/subghz/subghz_protocol_registry.h @@ -8,6 +8,83 @@ 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); + +bool subghz_protocol_keeloq_bft_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + uint32_t seed, + 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); + +bool subghz_protocol_faac_slh_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint32_t cnt, + uint32_t seed, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +bool subghz_protocol_came_atomo_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint16_t cnt, + SubGhzRadioPreset* preset); + +bool subghz_protocol_somfy_telis_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset); + +bool subghz_protocol_nice_flor_s_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset, + bool nice_one); + +bool subghz_protocol_alutech_at_4n_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset); + #ifdef __cplusplus } #endif diff --git a/lib/subghz/subghz_tx_rx_worker.c b/lib/subghz/subghz_tx_rx_worker.c index 21568dab1..b9d2f3c61 100644 --- a/lib/subghz/subghz_tx_rx_worker.c +++ b/lib/subghz/subghz_tx_rx_worker.c @@ -70,7 +70,7 @@ bool subghz_tx_rx_worker_rx(SubGhzTxRxWorker* instance, uint8_t* data, uint8_t* furi_delay_tick(1); } //waiting for reception to complete - while(furi_hal_gpio_read(furi_hal_subghz.cc1101_g0_pin)) { + while(furi_hal_gpio_read(instance->device_data_gpio)) { furi_delay_tick(1); if(!--timeout) { FURI_LOG_W(TAG, "RX cc1101_g0 timeout"); @@ -105,7 +105,7 @@ void subghz_tx_rx_worker_tx(SubGhzTxRxWorker* instance, uint8_t* data, size_t si furi_hal_subghz_tx(); //start send instance->status = SubGhzTxRxWorkerStatusTx; while(!furi_hal_gpio_read( - furi_hal_subghz.cc1101_g0_pin)) { // Wait for GDO0 to be set -> sync transmitted + 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"); @@ -113,7 +113,7 @@ void subghz_tx_rx_worker_tx(SubGhzTxRxWorker* instance, uint8_t* data, size_t si } } while(furi_hal_gpio_read( - furi_hal_subghz.cc1101_g0_pin)) { // Wait for GDO0 to be cleared -> end of packet + 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"); @@ -132,11 +132,11 @@ static int32_t subghz_tx_rx_worker_thread(void* context) { SubGhzTxRxWorker* instance = context; 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(furi_hal_subghz.cc1101_g0_pin, 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(); diff --git a/scripts/fbt/appmanifest.py b/scripts/fbt/appmanifest.py index f570491ea..a4b83f3c9 100644 --- a/scripts/fbt/appmanifest.py +++ b/scripts/fbt/appmanifest.py @@ -19,6 +19,7 @@ class FlipperAppType(Enum): SETTINGS = "Settings" STARTUP = "StartupHook" EXTERNAL = "External" + MENUEXTERNAL = "MenuExternal" METAPACKAGE = "Package" PLUGIN = "Plugin" @@ -209,7 +210,7 @@ class AppBuildset: appmgr: AppManager, appnames: List[str], hw_target: str, - message_writer: Callable = None, + message_writer: Callable | None = None, ): self.appmgr = appmgr self.appnames = set(appnames) @@ -364,6 +365,11 @@ class ApplicationsCGenerator: ), } + APP_EXTERNAL_TYPE = ( + "FlipperExternalApplication", + "FLIPPER_EXTERNAL_APPS", + ) + def __init__(self, buildset: AppBuildset, autorun_app: str = ""): self.buildset = buildset self.autorun = autorun_app @@ -392,6 +398,17 @@ class ApplicationsCGenerator: .icon = {f"&{app.icon}" if app.icon else "NULL"}, .flags = {'|'.join(f"FlipperInternalApplicationFlag{flag}" for flag in app.flags)}}}""" + def get_external_app_descr(self, app: FlipperApplication): + app_path = "/ext/apps" + if app.fap_category: + app_path += f"/{app.fap_category}" + app_path += f"/{app.appid}.fap" + return f""" + {{ + .name = "{app.name}", + .icon = {f"&{app.icon}" if app.icon else "NULL"}, + .path = "{app_path}" }}""" + def generate(self): contents = [ '#include "applications.h"', @@ -423,4 +440,11 @@ class ApplicationsCGenerator: ] ) + entry_type, entry_block = self.APP_EXTERNAL_TYPE + external_apps = self.buildset.get_apps_of_type(FlipperAppType.MENUEXTERNAL) + contents.append(f"const {entry_type} {entry_block}[] = {{") + contents.append(",\n".join(map(self.get_external_app_descr, external_apps))) + contents.append("};") + contents.append(f"const size_t {entry_block}_COUNT = COUNT_OF({entry_block});") + return "\n".join(contents) diff --git a/scripts/fbt_tools/fbt_extapps.py b/scripts/fbt_tools/fbt_extapps.py index 083b3e972..951da0560 100644 --- a/scripts/fbt_tools/fbt_extapps.py +++ b/scripts/fbt_tools/fbt_extapps.py @@ -426,7 +426,10 @@ def AddAppLaunchTarget(env, appname, launch_target_name): host_app = env["APPMGR"].get(artifacts_app_to_run.app.requires[0]) if host_app: - if host_app.apptype == FlipperAppType.EXTERNAL: + if host_app.apptype in [ + FlipperAppType.EXTERNAL, + FlipperAppType.MENUEXTERNAL, + ]: _add_host_app_to_targets(host_app) else: # host app is a built-in app diff --git a/scripts/toolchain/fbtenv.cmd b/scripts/toolchain/fbtenv.cmd index 4ae04e2a2..51708b8c4 100644 --- a/scripts/toolchain/fbtenv.cmd +++ b/scripts/toolchain/fbtenv.cmd @@ -13,7 +13,7 @@ if not ["%FBT_NOENV%"] == [""] ( exit /b 0 ) -set "FLIPPER_TOOLCHAIN_VERSION=22" +set "FLIPPER_TOOLCHAIN_VERSION=23" if ["%FBT_TOOLCHAIN_PATH%"] == [""] ( set "FBT_TOOLCHAIN_PATH=%FBT_ROOT%" diff --git a/scripts/toolchain/fbtenv.sh b/scripts/toolchain/fbtenv.sh index 81df6c0af..a3310a063 100755 --- a/scripts/toolchain/fbtenv.sh +++ b/scripts/toolchain/fbtenv.sh @@ -4,7 +4,7 @@ # public variables DEFAULT_SCRIPT_PATH="$(pwd -P)"; -FBT_TOOLCHAIN_VERSION="${FBT_TOOLCHAIN_VERSION:-"22"}"; +FBT_TOOLCHAIN_VERSION="${FBT_TOOLCHAIN_VERSION:-"23"}"; if [ -z ${FBT_TOOLCHAIN_PATH+x} ] ; then FBT_TOOLCHAIN_PATH_WAS_SET=0; diff --git a/scripts/ufbt/SConstruct b/scripts/ufbt/SConstruct index 8812a4e55..703a9187a 100644 --- a/scripts/ufbt/SConstruct +++ b/scripts/ufbt/SConstruct @@ -262,6 +262,7 @@ apps_artifacts = appenv["EXT_APPS"] apps_to_build_as_faps = [ FlipperAppType.PLUGIN, FlipperAppType.EXTERNAL, + FlipperAppType.MENUEXTERNAL, ] known_extapps = [ diff --git a/site_scons/extapps.scons b/site_scons/extapps.scons index 1005ab1a6..195d75c81 100644 --- a/site_scons/extapps.scons +++ b/site_scons/extapps.scons @@ -68,6 +68,7 @@ apps_to_build_as_faps = [ FlipperAppType.FAPP, FlipperAppType.PLUGIN, FlipperAppType.EXTERNAL, + FlipperAppType.MENUEXTERNAL, FlipperAppType.DEBUG, ]