diff --git a/CHANGELOG.md b/CHANGELOG.md index 37d8c680d..74bf3dc9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ ## New changes +* SubGHz: Keeloq: Centurion Nova read and emulate support (+ add manually) +* SubGHz: FAAC SLH - UI Fixes, Fix sending signals with no seed +* SubGHz: Code cleanup, proper handling of protocols ignore options (by @gid9798 | PR #516) +* SubGHz: Various UI fixes (by @wosk | PR #527) +* NFC: Fixed issue #532 (Mifare classic user dict - delete removes more than selected key) +* Infrared: Updated universal remote assets (by @amec0e | PR #529) +* Plugins: Use correct categories for all plugins (extra pack too) +* Plugins: Various fixes for uFBT (by @hedger) +* Plugins: Added **NFC Maker** plugin (make tags with URLs, Wifi and other things) [(by Willy-JL)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/external/nfc_maker) +* Plugins: Added JetPack Joyride [(by timstrasser)](https://github.com/timstrasser) +* Plugins: Moved Barcode Generator [(by Kingal1337)](https://github.com/Kingal1337/flipper-barcode-generator) from extra pack into base fw, old barcode generator was removed +* Plugins: Updated ESP32: WiFi Marauder companion plugin [(by 0xchocolate)](https://github.com/0xchocolate/flipperzero-wifi-marauder) +* Plugins: Updated i2c Tools [(by NaejEL)](https://github.com/NaejEL/flipperzero-i2ctools) +* Settings: Change LED and volume settings by 5% steps (by @cokyrain) +* BLE: BadBT fixes and furi_hal_bt cleanup (by @Willy-JL) +* WIP OFW PR 2825: NFC: Improved MFC emulation on some readers (by AloneLiberty) +* OFW PR 2829: Decode only supported Oregon 3 sensor (by @wosk) * OFW PR: Update OFW PR 2782 +* OFW: SubGhz: add "SubGhz test" external application and the ability to work "SubGhz" as an external application +* OFW: API: explicitly add math.h +* OFW: NFC: Mf Ultralight emulation optimization +* OFW: Furi_Power: fix furi_hal_power_enable_otg +* OFW: FuriHal: allow nulling null isr +* OFW: FuriHal, Infrared, Protobuf: various fixes and improvements +* OFW: Picopass fix ice +* OFW: Desktop settings: show icon and name for external applications +* OFW: Furi,FuriHal: various improvements +* OFW: Debug apps: speaker, uart_echo with baudrate * OFW: Add Mitsubishi MSZ-AP25VGK universal ac remote * OFW: Fix roll-over in file browser and archive * OFW: Fix fr-FR-mac keylayout diff --git a/ReadMe.md b/ReadMe.md index 3ab8e4b4a..f57256713 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -93,6 +93,7 @@ Encoders or sending made by @xMasterX: - Keeloq: Stilmatic - Keeloq: CAME Space - Keeloq: Aprimatic (model TR and similar) +- Keeloq: Centurion Nova (thanks Carlos !) Encoders or sending made by @Eng1n33r(first implementation in Q2 2022) & @xMasterX (current version): - CAME Atomo -> Update! check out new [instructions](https://github.com/DarkFlippers/unleashed-firmware/blob/dev/documentation/SubGHzRemoteProg.md) @@ -144,7 +145,7 @@ You can support us by using links or addresses below: - WiFi Scanner plugin [(by SequoiaSan)](https://github.com/SequoiaSan/FlipperZero-WiFi-Scanner_Module) - MultiConverter plugin [(by theisolinearchip)](https://github.com/theisolinearchip/flipperzero_stuff) - WAV Player [(OFW: DrZlo13)](https://github.com/flipperdevices/flipperzero-firmware/tree/zlo/wav-player) - Fixed and improved by [LTVA1](https://github.com/LTVA1/wav_player) -> Also outputs audio on `PA6` - `3(A6)` pin -- Barcode generator plugin [(original by McAzzaMan)](https://github.com/McAzzaMan/flipperzero-firmware/tree/UPC-A_Barcode_Generator/applications/barcode_generator) - [EAN-8 and refactoring](https://github.com/DarkFlippers/unleashed-firmware/pull/154) by @msvsergey +- Barcode Generator [(by Kingal1337)](https://github.com/Kingal1337/flipper-barcode-generator) - GPIO: Sentry Safe plugin [(by H4ckd4ddy)](https://github.com/H4ckd4ddy/flipperzero-sentry-safe-plugin) - ESP32: WiFi Marauder companion plugin [(by 0xchocolate)](https://github.com/0xchocolate/flipperzero-wifi-marauder) - Saving .pcap on flipper microSD [by tcpassos](https://github.com/tcpassos/flipperzero-firmware-with-wifi-marauder-companion) -> Only with custom marauder build (It is necessary to uncomment "#define WRITE_PACKETS_SERIAL" in configs.h (in marauder fw) and compile the firmware for the wifi board.) Or download precompiled build -> [Download esp32_marauder_ver_flipper_sd_serial.bin](https://github.com/justcallmekoko/ESP32Marauder/releases/latest) - NRF24: Sniffer & MouseJacker (with changes) [(by mothball187)](https://github.com/mothball187/flipperzero-nrf24/tree/main/mousejacker) @@ -169,6 +170,7 @@ You can support us by using links or addresses below: - IR Scope [(by kallanreed)](https://github.com/DarkFlippers/unleashed-firmware/pull/407) - **BadBT** plugin (BT version of BadKB) [(by Willy-JL, ClaraCrazy, XFW contributors)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/main/bad_kb) (See in Applications->Tools) - (aka BadUSB via Bluetooth) - **Mifare Nested** [(by AloneLiberty)](https://github.com/AloneLiberty/FlipperNested) - Works with PC and python app `FlipperNested` +- **NFC Maker** plugin (make tags with URLs, Wifi and other things) [(by Willy-JL)](https://github.com/ClaraCrazy/Flipper-Xtreme/tree/dev/applications/external/nfc_maker) Games: - DOOM (fixed) [(by p4nic4ttack)](https://github.com/p4nic4ttack/doom-flipper-zero/) @@ -184,6 +186,7 @@ Games: - BlackJack [(by teeebor)](https://github.com/teeebor/flipper_games) - 2048 game [(by eugene-kirzhanov)](https://github.com/eugene-kirzhanov/flipper-zero-2048-game) - Bomberduck [(by leo-need-more-coffee)](https://github.com/leo-need-more-coffee/flipperzero-bomberduck) +- JetPack Joyride [(by timstrasser)](https://github.com/timstrasser) # Instructions diff --git a/applications/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 69% rename from applications/main/subghz/views/subghz_test_carrier.c rename to applications/debug/subghz_test/views/subghz_test_carrier.c index 87ab81ca4..ec64e2d9b 100644 --- a/applications/main/subghz/views/subghz_test_carrier.c +++ b/applications/debug/subghz_test/views/subghz_test_carrier.c @@ -1,6 +1,6 @@ #include "subghz_test_carrier.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include @@ -12,7 +12,7 @@ struct SubGhzTestCarrier { View* view; FuriTimer* timer; SubGhzTestCarrierCallback callback; - const SubGhzDevice* radio_device; + // const SubGhzDevice* radio_device; void* context; }; @@ -85,7 +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; + // const SubGhzDevice* radio_device = subghz_test_carrier->radio_device; if(event->key == InputKeyBack || event->type != InputTypeShort) { return false; @@ -95,8 +95,8 @@ bool subghz_test_carrier_input(InputEvent* event, void* context) { subghz_test_carrier->view, SubGhzTestCarrierModel * model, { - // furi_hal_subghz_idle(); - subghz_devices_idle(radio_device); + furi_hal_subghz_idle(); + // subghz_devices_idle(radio_device); if(event->key == InputKeyLeft) { if(model->frequency > 0) model->frequency--; @@ -114,36 +114,39 @@ bool subghz_test_carrier_input(InputEvent* event, void* context) { } } - // model->real_frequency = - // furi_hal_subghz_set_frequency(subghz_frequencies_testing[model->frequency]); + 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]); + // model->real_frequency = subghz_devices_set_frequency( + // radio_device, subghz_frequencies_testing[model->frequency]); if(model->status == SubGhzTestCarrierModelStatusRx) { - // 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); + 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( &gpio_cc1101_g0, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow); furi_hal_gpio_write(&gpio_cc1101_g0, true); - // if(!furi_hal_subghz_tx()) { - // furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullNo, GpioSpeedLow); - if(!subghz_devices_set_tx(radio_device)) { - furi_hal_gpio_init( - subghz_devices_get_data_gpio(radio_device), - GpioModeInput, - GpioPullNo, - GpioSpeedLow); + if(!furi_hal_subghz_tx()) { + 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); @@ -154,37 +157,37 @@ 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_assert(subghz_test_carrier->radio_device); + // const SubGhzDevice* radio_device = subghz_test_carrier->radio_device; - // furi_hal_subghz_reset(); - // furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); + furi_hal_subghz_reset(); + furi_hal_subghz_load_custom_preset(subghz_device_cc1101_preset_ook_650khz_async_regs); - // furi_hal_gpio_init(&gpio_cc1101_g0, 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); + // 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); + // furi_hal_gpio_init( + // subghz_devices_get_data_gpio(radio_device), GpioModeInput, GpioPullNo, GpioSpeedLow); with_view_model( subghz_test_carrier->view, SubGhzTestCarrierModel * model, { 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->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; }, true); - // furi_hal_subghz_rx(); - subghz_devices_set_rx(radio_device); + furi_hal_subghz_rx(); + // subghz_devices_set_rx(radio_device); furi_timer_start(subghz_test_carrier->timer, furi_kernel_get_tick_frequency() / 4); } @@ -196,8 +199,8 @@ void subghz_test_carrier_exit(void* context) { furi_timer_stop(subghz_test_carrier->timer); // Reinitialize IC to default state - // furi_hal_subghz_sleep(); - subghz_devices_sleep(subghz_test_carrier->radio_device); + furi_hal_subghz_sleep(); + // subghz_devices_sleep(subghz_test_carrier->radio_device); } void subghz_test_carrier_rssi_timer_callback(void* context) { @@ -209,8 +212,8 @@ void subghz_test_carrier_rssi_timer_callback(void* context) { SubGhzTestCarrierModel * model, { if(model->status == SubGhzTestCarrierModelStatusRx) { - // model->rssi = furi_hal_subghz_get_rssi(); - model->rssi = subghz_devices_get_rssi(subghz_test_carrier->radio_device); + model->rssi = furi_hal_subghz_get_rssi(); + // model->rssi = subghz_devices_get_rssi(subghz_test_carrier->radio_device); } }, false); @@ -247,9 +250,9 @@ View* subghz_test_carrier_get_view(SubGhzTestCarrier* 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; -} +// 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 52d6b6f18..d171d19f4 100644 --- a/applications/main/subghz/views/subghz_test_carrier.h +++ b/applications/debug/subghz_test/views/subghz_test_carrier.h @@ -1,7 +1,7 @@ #pragma once #include -#include +// #include typedef enum { SubGhzTestCarrierEventOnlyRx, @@ -22,6 +22,6 @@ 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); +// 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 98% rename from applications/main/subghz/views/subghz_test_packet.c rename to applications/debug/subghz_test/views/subghz_test_packet.c index bc2c474b5..bab83ab5b 100644 --- a/applications/main/subghz/views/subghz_test_packet.c +++ b/applications/debug/subghz_test/views/subghz_test_packet.c @@ -1,6 +1,6 @@ #include "subghz_test_packet.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include @@ -8,7 +8,7 @@ #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define SUBGHZ_TEST_PACKET_COUNT 500 diff --git a/applications/main/subghz/views/subghz_test_packet.h b/applications/debug/subghz_test/views/subghz_test_packet.h similarity index 100% rename from applications/main/subghz/views/subghz_test_packet.h rename to applications/debug/subghz_test/views/subghz_test_packet.h diff --git a/applications/main/subghz/views/subghz_test_static.c b/applications/debug/subghz_test/views/subghz_test_static.c similarity index 97% rename from applications/main/subghz/views/subghz_test_static.c rename to applications/debug/subghz_test/views/subghz_test_static.c index d696eb1dd..6764fd5ca 100644 --- a/applications/main/subghz/views/subghz_test_static.c +++ b/applications/debug/subghz_test/views/subghz_test_static.c @@ -1,6 +1,6 @@ #include "subghz_test_static.h" -#include "../subghz_i.h" -#include "../helpers/subghz_testing.h" +#include "../subghz_test_app_i.h" +#include "../helpers/subghz_test_frequency.h" #include #include @@ -8,12 +8,10 @@ #include #include #include -#include +#include "../protocol/princeton_for_testing.h" #define TAG "SubGhzTestStatic" -// TODO add external module - typedef enum { SubGhzTestStaticStatusIDLE, SubGhzTestStaticStatusTX, 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/external/bad_bt/helpers/ducky_script.c b/applications/external/bad_bt/helpers/ducky_script.c index a59d377f2..96807f44d 100644 --- a/applications/external/bad_bt/helpers/ducky_script.c +++ b/applications/external/bad_bt/helpers/ducky_script.c @@ -64,10 +64,11 @@ static inline void update_bt_timeout(Bt* bt) { } typedef enum { - WorkerEvtToggle = (1 << 0), - WorkerEvtEnd = (1 << 1), - WorkerEvtConnect = (1 << 2), - WorkerEvtDisconnect = (1 << 3), + WorkerEvtStartStop = (1 << 0), + WorkerEvtPauseResume = (1 << 1), + WorkerEvtEnd = (1 << 2), + WorkerEvtConnect = (1 << 3), + WorkerEvtDisconnect = (1 << 4), } WorkerEvtFlags; static const char ducky_cmd_id[] = {"ID"}; @@ -280,6 +281,7 @@ static bool ducky_set_bt_id(BadBtScript* bad_bt, const char* line) { return false; } } + furi_hal_bt_reverse_mac_addr(mac); furi_hal_bt_set_profile_adv_name(FuriHalBtProfileHidKeyboard, line + mac_len); bt_set_profile_mac_address(bad_bt->bt, mac); @@ -498,24 +500,26 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateNotConnected) { // State: Not connected uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtConnect | WorkerEvtToggle, FuriWaitForever); + WorkerEvtEnd | WorkerEvtConnect | WorkerEvtDisconnect | WorkerEvtStartStop, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; } else if(flags & WorkerEvtConnect) { worker_state = BadBtStateIdle; // Ready to run - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateWillRun; // Will run when connected } bad_bt->st.state = worker_state; } else if(worker_state == BadBtStateIdle) { // State: ready to start uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriWaitForever); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtConnect | WorkerEvtDisconnect, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { // Start executing script + } else if(flags & WorkerEvtStartStop) { // Start executing script delay_val = 0; bad_bt->buf_len = 0; bad_bt->st.line_cur = 0; @@ -534,7 +538,8 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateWillRun) { // State: start on connection uint32_t flags = bad_bt_flags_get( - WorkerEvtEnd | WorkerEvtConnect | WorkerEvtToggle, FuriWaitForever); + WorkerEvtEnd | WorkerEvtConnect | WorkerEvtDisconnect | WorkerEvtStartStop, + FuriWaitForever); if(flags & WorkerEvtEnd) { break; @@ -549,21 +554,21 @@ static int32_t bad_bt_worker(void* context) { storage_file_seek(script_file, 0, true); // extra time for PC to recognize Flipper as keyboard flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtDisconnect | WorkerEvtToggle, + WorkerEvtEnd | WorkerEvtDisconnect | WorkerEvtStartStop, FuriFlagWaitAny | FuriFlagNoClear, 1500); if(flags == (unsigned)FuriFlagErrorTimeout) { // If nothing happened - start script execution worker_state = BadBtStateRunning; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; - furi_thread_flags_clear(WorkerEvtToggle); + furi_thread_flags_clear(WorkerEvtStartStop); } update_bt_timeout(bad_bt->bt); bad_bt_script_set_keyboard_layout(bad_bt, bad_bt->keyboard_layout); - } else if(flags & WorkerEvtToggle) { // Cancel scheduled execution + } else if(flags & WorkerEvtStartStop) { // Cancel scheduled execution worker_state = BadBtStateNotConnected; } bad_bt->st.state = worker_state; @@ -571,13 +576,15 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateRunning) { // State: running uint16_t delay_cur = (delay_val > 1000) ? (1000) : (delay_val); uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriFlagWaitAny, delay_cur); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtConnect | WorkerEvtDisconnect, + FuriFlagWaitAny, + delay_cur); delay_val -= delay_cur; if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; // Stop executing script furi_hal_bt_hid_kb_release_all(); @@ -630,11 +637,14 @@ static int32_t bad_bt_worker(void* context) { } else if(worker_state == BadBtStateWaitForBtn) { // State: Wait for button Press uint16_t delay_cur = (delay_val > 1000) ? (1000) : (delay_val); uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, FuriFlagWaitAny, delay_cur); + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtPauseResume | WorkerEvtConnect | + WorkerEvtDisconnect, + FuriFlagWaitAny, + delay_cur); if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { delay_val = 0; worker_state = BadBtStateRunning; } else if(flags & WorkerEvtDisconnect) { @@ -646,14 +656,15 @@ static int32_t bad_bt_worker(void* context) { } } else if(worker_state == BadBtStateStringDelay) { // State: print string with delays uint32_t flags = furi_thread_flags_wait( - WorkerEvtEnd | WorkerEvtToggle | WorkerEvtDisconnect, + WorkerEvtEnd | WorkerEvtStartStop | WorkerEvtPauseResume | WorkerEvtConnect | + WorkerEvtDisconnect, FuriFlagWaitAny, bad_bt->stringdelay); if(!(flags & FuriFlagError)) { if(flags & WorkerEvtEnd) { break; - } else if(flags & WorkerEvtToggle) { + } else if(flags & WorkerEvtStartStop) { worker_state = BadBtStateIdle; // Stop executing script furi_hal_bt_hid_kb_release_all(); @@ -768,7 +779,7 @@ void bad_bt_script_set_keyboard_layout(BadBtScript* bad_bt, FuriString* layout_p void bad_bt_script_toggle(BadBtScript* bad_bt) { furi_assert(bad_bt); - furi_thread_flags_set(furi_thread_get_id(bad_bt->thread), WorkerEvtToggle); + furi_thread_flags_set(furi_thread_get_id(bad_bt->thread), WorkerEvtStartStop); } BadBtState* bad_bt_script_get_state(BadBtScript* bad_bt) { diff --git a/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c b/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c index 47f63e08c..dcc783f0f 100644 --- a/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c +++ b/applications/external/bad_bt/scenes/bad_bt_scene_config_mac.c @@ -11,6 +11,8 @@ void bad_bt_scene_config_mac_byte_input_callback(void* context) { void bad_bt_scene_config_mac_on_enter(void* context) { BadBtApp* bad_bt = context; + furi_hal_bt_reverse_mac_addr(bad_bt->config.bt_mac); + // Setup view ByteInput* byte_input = bad_bt->byte_input; byte_input_set_header_text(byte_input, "Set BT MAC address"); @@ -30,7 +32,6 @@ bool bad_bt_scene_config_mac_on_event(void* context, SceneManagerEvent event) { if(event.type == SceneManagerEventTypeCustom) { if(event.event == BadBtAppCustomEventByteInputDone) { - bt_set_profile_mac_address(bad_bt->bt, bad_bt->config.bt_mac); scene_manager_previous_scene(bad_bt->scene_manager); consumed = true; } @@ -41,6 +42,10 @@ bool bad_bt_scene_config_mac_on_event(void* context, SceneManagerEvent event) { void bad_bt_scene_config_mac_on_exit(void* context) { BadBtApp* bad_bt = context; + furi_hal_bt_reverse_mac_addr(bad_bt->config.bt_mac); + + bt_set_profile_mac_address(bad_bt->bt, bad_bt->config.bt_mac); + // Clear view byte_input_set_result_callback(bad_bt->byte_input, NULL, NULL, NULL, NULL, 0); byte_input_set_header_text(bad_bt->byte_input, ""); diff --git a/applications/external/barcode_gen/LICENSE b/applications/external/barcode_gen/LICENSE new file mode 100644 index 000000000..4c02d8221 --- /dev/null +++ b/applications/external/barcode_gen/LICENSE @@ -0,0 +1,22 @@ + +MIT License + +Copyright (c) 2023 Alan Tsui + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/applications/external/barcode_gen/README.md b/applications/external/barcode_gen/README.md new file mode 100644 index 000000000..ec944cb26 --- /dev/null +++ b/applications/external/barcode_gen/README.md @@ -0,0 +1,88 @@ +

+

Barcode Generator

+

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

+ +Note: Barcode save locations have been moved from `/barcodes` to `/apps_data/barcodes` + +## Table of Contents +- [Table of Contents](#table-of-contents) +- [Installing](#installing) +- [Building](#building) +- [Usage](#usage) + - [Creating a barcode](#creating-a-barcode) + - [Editing a barcode](#editing-a-barcode) + - [Deleting a barcode](#deleting-a-barcode) + - [Viewing a barcode](#viewing-a-barcode) +- [Screenshots](#screenshots) +- [Credits](#credits) + + +## Installing +1) Download the `.zip` file from the release section +2) Extract/unzip the `.zip` file onto your computer +3) Open qFlipper and go to the file manager +4) Navigate to the `apps` folder +5) Drag & drop the `.fap` file into the `apps` folder +6) Navigate back to the root folder of the SD card and create the folder `apps_data`, if not already there +7) Navigate into `apps_data` and create another folder called `barcode_data` +8) Navigate into `barcode_data` +9) Drag & drop the encoding txts (`code39_encodings.txt`, `code128_encodings.txt` & `codabar_encodings.txt`) into the `barcode_data` folder + +## Building +1) Clone the [flipperzero-firmware](https://github.com/flipperdevices/flipperzero-firmware) repository or a firmware of your choice +2) Clone this repository and put it in the `applications_user` folder +3) Build this app by using the command `./fbt fap_Barcode_App` +4) Copy the `.fap` from `build\f7-firmware-D\.extapps\Barcode_App.fap` to `apps\Misc` using the qFlipper app +5) While still in the qFlipper app, navigate to the root folder of the SD card and create the folder `apps_data`, if not already there +6) Navigate into `apps_data` and create another folder called `barcode_data` +7) Navigate into `barcode_data` +8) Drag & drop the encoding txts (`code39_encodings.txt`, `code128_encodings.txt` & `codabar_encodings.txt`) from the `encoding_tables` folder in this repository into the `barcode_data` folder + +## Usage + +### Creating a barcode +1) To create a barcode click on `Create Barcode` +2) Next select your type using the left and right arrows +3) Enter your filename and then your barcode data +4) Click save + +**Note**: For Codabar barcodes, you must manually add the start and stop codes to the barcode data +Start/Stop codes can be A, B, C, or D +For example, if you wanted to represent `1234` as a barcode you will need to enter something like `A1234A`. (You can replace the letters A with either A, B, C, or D) + +![Codabar Data Example](screenshots/Codabar%20Data%20Example.png "Codabar Data Example") + +### Editing a barcode +1) To edit a barcode click on `Edit Barcode` +2) Next select the barcode file you want to edit +3) Edit the type, name, or data +4) Click save + +### Deleting a barcode +1) To delete a barcode click on `Edit Barcode` +2) Next select the barcode file you want to delete +3) Scroll all the way to the bottom +4) Click delete + +### Viewing a barcode +1) To view a barcode click on `Load Barcode` +2) Next select the barcode file you want to view + +## Screenshots +![Barcode Create Screen](screenshots/Creating%20Barcode.png "Barcode Create Screen") + +![Flipper Code-128 Barcode](screenshots/Flipper%20Barcode.png "Flipper Code-128 Barcode") + +![Flipper Box EAN-13 Barcode](screenshots/Flipper%20Box%20Barcode.png "Flipper Box EAN-13 Barcode") + +## Credits + +- [Kingal1337](https://github.com/Kingal1337) - Developer +- [Z0wl](https://github.com/Z0wl) - Added Code128-C Support +- [@teeebor](https://github.com/teeebor) - Menu Code Snippet + + +[1] - supports Set B (only the characters from 0-94). Also supports Set C diff --git a/applications/external/barcode_gen/application.fam b/applications/external/barcode_gen/application.fam new file mode 100644 index 000000000..371e52c04 --- /dev/null +++ b/applications/external/barcode_gen/application.fam @@ -0,0 +1,16 @@ +App( + appid="barcode_app", + name="Barcode App", + apptype=FlipperAppType.EXTERNAL, + entry_point="barcode_main", + requires=["gui", "storage"], + stack_size=2 * 1024, + fap_category="Tools", + fap_icon="images/barcode_10.png", + fap_icon_assets="images", + fap_icon_assets_symbol="barcode_app", + fap_author="@Kingal1337", + fap_weburl="https://github.com/Kingal1337/flipper-barcode-generator", + fap_version="1.0", + fap_description="App allows you to display various barcodes on flipper screen", +) diff --git a/applications/external/barcode_gen/barcode_app.c b/applications/external/barcode_gen/barcode_app.c new file mode 100644 index 000000000..99e5769d2 --- /dev/null +++ b/applications/external/barcode_gen/barcode_app.c @@ -0,0 +1,348 @@ +#include "barcode_app.h" + +#include "barcode_app_icons.h" + +/** + * Opens a file browser dialog and returns the filepath of the selected file + * + * @param folder the folder to view when the browser opens + * @param file_path a string pointer for the file_path when a file is selected, + * file_path will be the folder path is nothing is selected + * @returns true if a file is selected +*/ +static bool select_file(const char* folder, FuriString* file_path) { + DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); + DialogsFileBrowserOptions browser_options; + dialog_file_browser_set_basic_options(&browser_options, "", &I_barcode_10); + browser_options.base_path = DEFAULT_USER_BARCODES; + furi_string_set(file_path, folder); + + bool res = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options); + + furi_record_close(RECORD_DIALOGS); + + return res; +} + +/** + * Reads the data from a file and stores them in the FuriStrings raw_type and raw_data +*/ +ErrorCode read_raw_data(FuriString* file_path, FuriString* raw_type, FuriString* raw_data) { + //Open Storage + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + ErrorCode reason = OKCode; + + if(!flipper_format_file_open_existing(ff, furi_string_get_cstr(file_path))) { + FURI_LOG_E(TAG, "Could not open file %s", furi_string_get_cstr(file_path)); + reason = FileOpening; + } else { + if(!flipper_format_read_string(ff, "Type", raw_type)) { + FURI_LOG_E(TAG, "Could not read \"Type\" string"); + reason = InvalidFileData; + } + if(!flipper_format_read_string(ff, "Data", raw_data)) { + FURI_LOG_E(TAG, "Could not read \"Data\" string"); + reason = InvalidFileData; + } + } + + //Close Storage + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + return reason; +} + +/** + * Gets the file name from a file path + * @param file_path the file path + * @param file_name the FuriString to store the file name + * @param remove_extension true if the extension should be removed, otherwise false +*/ +bool get_file_name_from_path(FuriString* file_path, FuriString* file_name, bool remove_extension) { + if(file_path == NULL || file_name == NULL) { + return false; + } + uint32_t slash_index = furi_string_search_rchar(file_path, '/', 0); + if(slash_index == FURI_STRING_FAILURE || slash_index >= (furi_string_size(file_path) - 1)) { + return false; + } + + furi_string_set(file_name, file_path); + furi_string_right(file_name, slash_index + 1); + if(remove_extension) { + uint32_t ext_index = furi_string_search_rchar(file_name, '.', 0); + if(ext_index != FURI_STRING_FAILURE && ext_index < (furi_string_size(file_path))) { + furi_string_left(file_name, ext_index); + } + } + + return true; +} + +/** + * Creates the barcode folder +*/ +void init_folder() { + Storage* storage = furi_record_open(RECORD_STORAGE); + FURI_LOG_I(TAG, "Creating barcodes folder"); + if(storage_simply_mkdir(storage, DEFAULT_USER_BARCODES)) { + FURI_LOG_I(TAG, "Barcodes folder successfully created!"); + } else { + FURI_LOG_I(TAG, "Barcodes folder already exists."); + } + furi_record_close(RECORD_STORAGE); +} + +void select_barcode_item(BarcodeApp* app) { + FuriString* file_path = furi_string_alloc(); + FuriString* raw_type = furi_string_alloc(); + FuriString* raw_data = furi_string_alloc(); + + //this determines if the data was read correctly or if the + bool loaded_success = true; + ErrorCode reason = OKCode; + + bool file_selected = select_file(DEFAULT_USER_BARCODES, file_path); + if(file_selected) { + FURI_LOG_I(TAG, "The file selected is %s", furi_string_get_cstr(file_path)); + Barcode* barcode = app->barcode_view; + + reason = read_raw_data(file_path, raw_type, raw_data); + if(reason != OKCode) { + loaded_success = false; + FURI_LOG_E(TAG, "Could not read data correctly"); + } + + //Free the data from the previous barcode + barcode_free_model(barcode); + + with_view_model( + barcode->view, + BarcodeModel * model, + { + model->file_path = furi_string_alloc_set(file_path); + + model->data = malloc(sizeof(BarcodeData)); + model->data->valid = loaded_success; + + if(loaded_success) { + model->data->raw_data = furi_string_alloc_set(raw_data); + model->data->correct_data = furi_string_alloc(); + + model->data->type_obj = get_type(raw_type); + + barcode_loader(model->data); + } else { + model->data->reason = reason; + } + }, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, BarcodeView); + } + + furi_string_free(raw_type); + furi_string_free(raw_data); + furi_string_free(file_path); +} + +void edit_barcode_item(BarcodeApp* app) { + FuriString* file_path = furi_string_alloc(); + FuriString* file_name = furi_string_alloc(); + FuriString* raw_type = furi_string_alloc(); + FuriString* raw_data = furi_string_alloc(); + + //this determines if the data was read correctly or if the + ErrorCode reason = OKCode; + + bool file_selected = select_file(DEFAULT_USER_BARCODES, file_path); + if(file_selected) { + FURI_LOG_I(TAG, "The file selected is %s", furi_string_get_cstr(file_path)); + CreateView* create_view_object = app->create_view; + + reason = read_raw_data(file_path, raw_type, raw_data); + if(reason != OKCode) { + FURI_LOG_E(TAG, "Could not read data correctly"); + with_view_model( + app->message_view->view, + MessageViewModel * model, + { model->message = get_error_code_message(reason); }, + true); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, MessageErrorView); + + } else { + BarcodeTypeObj* type_obj = get_type(raw_type); + if(type_obj->type == UNKNOWN) { + type_obj = barcode_type_objs[0]; + } + get_file_name_from_path(file_path, file_name, true); + + create_view_free_model(create_view_object); + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + model->selected_menu_item = 0; + model->barcode_type = type_obj; + model->file_path = furi_string_alloc_set(file_path); + model->file_name = furi_string_alloc_set(file_name); + model->barcode_data = furi_string_alloc_set(raw_data); + model->mode = EditMode; + }, + true); + view_dispatcher_switch_to_view(app->view_dispatcher, CreateBarcodeView); + } + } + + furi_string_free(raw_type); + furi_string_free(raw_data); + furi_string_free(file_name); + furi_string_free(file_path); +} + +void create_barcode_item(BarcodeApp* app) { + CreateView* create_view_object = app->create_view; + + create_view_free_model(create_view_object); + + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + model->selected_menu_item = 0; + model->barcode_type = barcode_type_objs[0]; + model->file_path = furi_string_alloc(); + model->file_name = furi_string_alloc(); + model->barcode_data = furi_string_alloc(); + model->mode = NewMode; + }, + true); + view_dispatcher_switch_to_view(app->view_dispatcher, CreateBarcodeView); +} + +void submenu_callback(void* context, uint32_t index) { + furi_assert(context); + + BarcodeApp* app = context; + + if(index == SelectBarcodeItem) { + select_barcode_item(app); + } else if(index == EditBarcodeItem) { + edit_barcode_item(app); + } else if(index == CreateBarcodeItem) { + create_barcode_item(app); + } +} + +uint32_t create_view_callback(void* context) { + UNUSED(context); + return CreateBarcodeView; +} + +uint32_t main_menu_callback(void* context) { + UNUSED(context); + return MainMenuView; +} + +uint32_t exit_callback(void* context) { + UNUSED(context); + return VIEW_NONE; +} + +void free_app(BarcodeApp* app) { + FURI_LOG_I(TAG, "Freeing Data"); + + init_folder(); + free_types(); + + view_dispatcher_remove_view(app->view_dispatcher, TextInputView); + text_input_free(app->text_input); + + view_dispatcher_remove_view(app->view_dispatcher, MessageErrorView); + message_view_free(app->message_view); + + view_dispatcher_remove_view(app->view_dispatcher, MainMenuView); + submenu_free(app->main_menu); + + view_dispatcher_remove_view(app->view_dispatcher, CreateBarcodeView); + create_view_free(app->create_view); + + view_dispatcher_remove_view(app->view_dispatcher, BarcodeView); + barcode_free(app->barcode_view); + + //free the dispatcher + view_dispatcher_free(app->view_dispatcher); + + furi_message_queue_free(app->event_queue); + + furi_record_close(RECORD_GUI); + app->gui = NULL; + + free(app); +} + +int32_t barcode_main(void* p) { + UNUSED(p); + BarcodeApp* app = malloc(sizeof(BarcodeApp)); + init_types(); + app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent)); + + // Register view port in GUI + app->gui = furi_record_open(RECORD_GUI); + + app->view_dispatcher = view_dispatcher_alloc(); + view_dispatcher_enable_queue(app->view_dispatcher); + view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); + + app->main_menu = submenu_alloc(); + submenu_add_item(app->main_menu, "Load Barcode", SelectBarcodeItem, submenu_callback, app); + view_set_previous_callback(submenu_get_view(app->main_menu), exit_callback); + view_dispatcher_add_view(app->view_dispatcher, MainMenuView, submenu_get_view(app->main_menu)); + + submenu_add_item(app->main_menu, "Edit Barcode", EditBarcodeItem, submenu_callback, app); + + /***************************** + * Creating Text Input View + ******************************/ + app->text_input = text_input_alloc(); + view_set_previous_callback(text_input_get_view(app->text_input), create_view_callback); + view_dispatcher_add_view( + app->view_dispatcher, TextInputView, text_input_get_view(app->text_input)); + + /***************************** + * Creating Message View + ******************************/ + app->message_view = message_view_allocate(app); + view_dispatcher_add_view( + app->view_dispatcher, MessageErrorView, message_get_view(app->message_view)); + + /***************************** + * Creating Create View + ******************************/ + app->create_view = create_view_allocate(app); + submenu_add_item(app->main_menu, "Create Barcode", CreateBarcodeItem, submenu_callback, app); + view_set_previous_callback(create_get_view(app->create_view), main_menu_callback); + view_dispatcher_add_view( + app->view_dispatcher, CreateBarcodeView, create_get_view(app->create_view)); + + /***************************** + * Creating Barcode View + ******************************/ + app->barcode_view = barcode_view_allocate(app); + view_set_previous_callback(barcode_get_view(app->barcode_view), main_menu_callback); + view_dispatcher_add_view( + app->view_dispatcher, BarcodeView, barcode_get_view(app->barcode_view)); + + //switch view to submenu and run dispatcher + view_dispatcher_switch_to_view(app->view_dispatcher, MainMenuView); + view_dispatcher_run(app->view_dispatcher); + + free_app(app); + + return 0; +} diff --git a/applications/external/barcode_gen/barcode_app.h b/applications/external/barcode_gen/barcode_app.h new file mode 100644 index 000000000..3150bff1f --- /dev/null +++ b/applications/external/barcode_gen/barcode_app.h @@ -0,0 +1,91 @@ +#pragma once +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "barcode_utils.h" + +#define TAG "BARCODE" +#define VERSION "1.1" +#define FILE_VERSION "1" + +#define TEXT_BUFFER_SIZE 128 + +#define BARCODE_HEIGHT 50 +#define BARCODE_Y_START 3 + +//the folder where the encodings are located +#define BARCODE_DATA_FILE_DIR_PATH EXT_PATH("apps_data/barcode_data") + +//the folder where the codabar encoding table is located +#define CODABAR_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/codabar_encodings.txt" + +//the folder where the code 39 encoding table is located +#define CODE39_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/code39_encodings.txt" + +//the folder where the code 128 encoding table is located +#define CODE128_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/code128_encodings.txt" + +//the folder where the code 128 C encoding table is located +#define CODE128C_DICT_FILE_PATH BARCODE_DATA_FILE_DIR_PATH "/code128c_encodings.txt" + +//the folder where the user stores their barcodes +#define DEFAULT_USER_BARCODES EXT_PATH("apps_data/barcodes") + +//The extension barcode files use +#define BARCODE_EXTENSION ".txt" +#define BARCODE_EXTENSION_LENGTH 4 + +#include "views/barcode_view.h" +#include "views/create_view.h" +#include "views/message_view.h" +#include "barcode_validator.h" + +typedef struct BarcodeApp BarcodeApp; + +struct BarcodeApp { + Submenu* main_menu; + ViewDispatcher* view_dispatcher; + Gui* gui; + + FuriMessageQueue* event_queue; + + CreateView* create_view; + Barcode* barcode_view; + + MessageView* message_view; + TextInput* text_input; +}; + +enum SubmenuItems { + SelectBarcodeItem, + EditBarcodeItem, + + CreateBarcodeItem +}; + +enum Views { + TextInputView, + MessageErrorView, + MainMenuView, + CreateBarcodeView, + + BarcodeView +}; + +void submenu_callback(void* context, uint32_t index); + +uint32_t main_menu_callback(void* context); + +uint32_t exit_callback(void* context); + +int32_t barcode_main(void* p); diff --git a/applications/external/barcode_gen/barcode_utils.c b/applications/external/barcode_gen/barcode_utils.c new file mode 100644 index 000000000..31274c1fe --- /dev/null +++ b/applications/external/barcode_gen/barcode_utils.c @@ -0,0 +1,147 @@ +#include "barcode_utils.h" + +BarcodeTypeObj* barcode_type_objs[NUMBER_OF_BARCODE_TYPES] = {NULL}; + +void init_types() { + BarcodeTypeObj* upc_a = malloc(sizeof(BarcodeTypeObj)); + upc_a->name = "UPC-A"; + upc_a->type = UPCA; + upc_a->min_digits = 11; + upc_a->max_digits = 12; + upc_a->start_pos = 16; + barcode_type_objs[UPCA] = upc_a; + + BarcodeTypeObj* ean_8 = malloc(sizeof(BarcodeTypeObj)); + ean_8->name = "EAN-8"; + ean_8->type = EAN8; + ean_8->min_digits = 7; + ean_8->max_digits = 8; + ean_8->start_pos = 32; + barcode_type_objs[EAN8] = ean_8; + + BarcodeTypeObj* ean_13 = malloc(sizeof(BarcodeTypeObj)); + ean_13->name = "EAN-13"; + ean_13->type = EAN13; + ean_13->min_digits = 12; + ean_13->max_digits = 13; + ean_13->start_pos = 16; + barcode_type_objs[EAN13] = ean_13; + + BarcodeTypeObj* code_39 = malloc(sizeof(BarcodeTypeObj)); + code_39->name = "CODE-39"; + code_39->type = CODE39; + code_39->min_digits = 1; + code_39->max_digits = -1; + code_39->start_pos = 0; + barcode_type_objs[CODE39] = code_39; + + BarcodeTypeObj* code_128 = malloc(sizeof(BarcodeTypeObj)); + code_128->name = "CODE-128"; + code_128->type = CODE128; + code_128->min_digits = 1; + code_128->max_digits = -1; + code_128->start_pos = 0; + barcode_type_objs[CODE128] = code_128; + + BarcodeTypeObj* code_128c = malloc(sizeof(BarcodeTypeObj)); + code_128c->name = "CODE-128C"; + code_128c->type = CODE128C; + code_128c->min_digits = 2; + code_128c->max_digits = -1; + code_128c->start_pos = 0; + barcode_type_objs[CODE128C] = code_128c; + + BarcodeTypeObj* codabar = malloc(sizeof(BarcodeTypeObj)); + codabar->name = "Codabar"; + codabar->type = CODABAR; + codabar->min_digits = 1; + codabar->max_digits = -1; + codabar->start_pos = 0; + barcode_type_objs[CODABAR] = codabar; + + BarcodeTypeObj* unknown = malloc(sizeof(BarcodeTypeObj)); + unknown->name = "Unknown"; + unknown->type = UNKNOWN; + unknown->min_digits = 0; + unknown->max_digits = 0; + unknown->start_pos = 0; + barcode_type_objs[UNKNOWN] = unknown; +} + +void free_types() { + for(int i = 0; i < NUMBER_OF_BARCODE_TYPES; i++) { + free(barcode_type_objs[i]); + } +} + +BarcodeTypeObj* get_type(FuriString* type_string) { + if(furi_string_cmp_str(type_string, "UPC-A") == 0) { + return barcode_type_objs[UPCA]; + } + if(furi_string_cmp_str(type_string, "EAN-8") == 0) { + return barcode_type_objs[EAN8]; + } + if(furi_string_cmp_str(type_string, "EAN-13") == 0) { + return barcode_type_objs[EAN13]; + } + if(furi_string_cmp_str(type_string, "CODE-39") == 0) { + return barcode_type_objs[CODE39]; + } + if(furi_string_cmp_str(type_string, "CODE-128") == 0) { + return barcode_type_objs[CODE128]; + } + if(furi_string_cmp_str(type_string, "CODE-128C") == 0) { + return barcode_type_objs[CODE128C]; + } + if(furi_string_cmp_str(type_string, "Codabar") == 0) { + return barcode_type_objs[CODABAR]; + } + + return barcode_type_objs[UNKNOWN]; +} + +const char* get_error_code_name(ErrorCode error_code) { + switch(error_code) { + case WrongNumberOfDigits: + return "Wrong Number Of Digits"; + case InvalidCharacters: + return "Invalid Characters"; + case UnsupportedType: + return "Unsupported Type"; + case FileOpening: + return "File Opening Error"; + case InvalidFileData: + return "Invalid File Data"; + case MissingEncodingTable: + return "Missing Encoding Table"; + case EncodingTableError: + return "Encoding Table Error"; + case OKCode: + return "OK"; + default: + return "Unknown Code"; + }; +} + +const char* get_error_code_message(ErrorCode error_code) { + switch(error_code) { + case WrongNumberOfDigits: + return "Wrong # of characters"; + case InvalidCharacters: + return "Invalid characters"; + case UnsupportedType: + return "Unsupported barcode type"; + case FileOpening: + return "Could not open file"; + case InvalidFileData: + return "Invalid file data"; + case MissingEncodingTable: + return "Missing encoding table"; + case EncodingTableError: + return "Encoding table error"; + case OKCode: + return "OK"; + default: + return "Could not read barcode data"; + }; +} diff --git a/applications/external/barcode_gen/barcode_utils.h b/applications/external/barcode_gen/barcode_utils.h new file mode 100644 index 000000000..0a27785cf --- /dev/null +++ b/applications/external/barcode_gen/barcode_utils.h @@ -0,0 +1,55 @@ + +#pragma once +#include +#include + +#define NUMBER_OF_BARCODE_TYPES 8 + +typedef enum { + WrongNumberOfDigits, //There is too many or too few digits in the barcode + InvalidCharacters, //The barcode contains invalid characters + UnsupportedType, //the barcode type is not supported + FileOpening, //A problem occurred when opening the barcode data file + InvalidFileData, //One of the key in the file doesn't exist or there is a typo + MissingEncodingTable, //The encoding table txt for the barcode type is missing + EncodingTableError, //Something is wrong with the encoding table, probably missing data or typo + OKCode +} ErrorCode; + +typedef enum { + UPCA, + EAN8, + EAN13, + CODE39, + CODE128, + CODE128C, + CODABAR, + + UNKNOWN +} BarcodeType; + +typedef struct { + char* name; //The name of the barcode type + BarcodeType type; //The barcode type enum + int min_digits; //the minimum number of digits + int max_digits; //the maximum number of digits + int start_pos; //where to start drawing the barcode, set to -1 to dynamically draw barcode +} BarcodeTypeObj; + +typedef struct { + BarcodeTypeObj* type_obj; + int check_digit; //A place to store the check digit + FuriString* raw_data; //the data directly from the file + FuriString* correct_data; //the corrected/processed data + bool valid; //true if the raw data is correctly formatted, such as correct num of digits, valid characters, etc. + ErrorCode reason; //the reason why this barcode is invalid +} BarcodeData; + +//All available barcode types +extern BarcodeTypeObj* barcode_type_objs[NUMBER_OF_BARCODE_TYPES]; + +void init_types(); +void free_types(); +BarcodeTypeObj* get_type(FuriString* type_string); +const char* get_error_code_name(ErrorCode error_code); +const char* get_error_code_message(ErrorCode error_code); diff --git a/applications/external/barcode_gen/barcode_validator.c b/applications/external/barcode_gen/barcode_validator.c new file mode 100644 index 000000000..cb493f3e9 --- /dev/null +++ b/applications/external/barcode_gen/barcode_validator.c @@ -0,0 +1,532 @@ +#include "barcode_validator.h" + +void barcode_loader(BarcodeData* barcode_data) { + switch(barcode_data->type_obj->type) { + case UPCA: + case EAN8: + case EAN13: + ean_upc_loader(barcode_data); + break; + case CODE39: + code_39_loader(barcode_data); + break; + case CODE128: + code_128_loader(barcode_data); + break; + case CODE128C: + code_128c_loader(barcode_data); + break; + case CODABAR: + codabar_loader(barcode_data); + break; + case UNKNOWN: + barcode_data->reason = UnsupportedType; + barcode_data->valid = false; + default: + break; + } +} + +/** + * Calculates the check digit of a barcode if they have one + * @param barcode_data the barcode data + * @returns a check digit or -1 for either an invalid +*/ +int calculate_check_digit(BarcodeData* barcode_data) { + int check_digit = -1; + switch(barcode_data->type_obj->type) { + case UPCA: + case EAN8: + case EAN13: + check_digit = calculate_ean_upc_check_digit(barcode_data); + break; + case CODE39: + case CODE128: + case CODE128C: + case CODABAR: + case UNKNOWN: + default: + break; + } + + return check_digit; +} + +/** + * Calculates the check digit of barcode types UPC-A, EAN-8, & EAN-13 +*/ +int calculate_ean_upc_check_digit(BarcodeData* barcode_data) { + int check_digit = 0; + int odd = 0; + int even = 0; + + int length = barcode_data->type_obj->min_digits; + + //Get sum of odd digits + for(int i = 0; i < length; i += 2) { + odd += furi_string_get_char(barcode_data->raw_data, i) - '0'; + } + + //Get sum of even digits + for(int i = 1; i < length; i += 2) { + even += furi_string_get_char(barcode_data->raw_data, i) - '0'; + } + + if(barcode_data->type_obj->type == EAN13) { + check_digit = even * 3 + odd; + } else { + check_digit = odd * 3 + even; + } + + check_digit = check_digit % 10; + + return (10 - check_digit) % 10; +} + +/** + * Loads and validates Barcode Types EAN-8, EAN-13, and UPC-A + * barcode_data and its strings should already be allocated; +*/ +void ean_upc_loader(BarcodeData* barcode_data) { + int barcode_length = furi_string_size(barcode_data->raw_data); + + int min_digits = barcode_data->type_obj->min_digits; + int max_digit = barcode_data->type_obj->max_digits; + + //check the length of the barcode + if(barcode_length < min_digits || barcode_length > max_digit) { + barcode_data->reason = WrongNumberOfDigits; + barcode_data->valid = false; + return; + } + + //checks if the barcode contains any characters that aren't a number + for(int i = 0; i < barcode_length; i++) { + char character = furi_string_get_char(barcode_data->raw_data, i); + int digit = character - '0'; //convert the number into an int (also the index) + if(digit < 0 || digit > 9) { + barcode_data->reason = InvalidCharacters; + barcode_data->valid = false; + return; + } + } + + int check_digit = calculate_check_digit(barcode_data); + char check_digit_char = check_digit + '0'; + + barcode_data->check_digit = check_digit; + + //if the barcode length is at max length then we will verify if the check digit is correct + if(barcode_length == max_digit) { + //append the raw_data to the correct data string + furi_string_cat(barcode_data->correct_data, barcode_data->raw_data); + + //append the check digit to the correct data string + furi_string_set_char(barcode_data->correct_data, min_digits, check_digit_char); + } + //if the barcode length is at min length, we will calculate the check digit + if(barcode_length == min_digits) { + //append the raw_data to the correct data string + furi_string_cat(barcode_data->correct_data, barcode_data->raw_data); + + //append the check digit to the correct data string + furi_string_push_back(barcode_data->correct_data, check_digit_char); + } +} + +void code_39_loader(BarcodeData* barcode_data) { + int barcode_length = furi_string_size(barcode_data->raw_data); + + int min_digits = barcode_data->type_obj->min_digits; + + //check the length of the barcode, must contain atleast a character, + //this can have as many characters as it wants, it might not fit on the screen + if(barcode_length < min_digits) { + barcode_data->reason = WrongNumberOfDigits; + barcode_data->valid = false; + return; + } + + FuriString* barcode_bits = furi_string_alloc(); + FuriString* temp_string = furi_string_alloc(); + + //add starting and ending * + if(!furi_string_start_with(barcode_data->raw_data, "*")) { + furi_string_push_back(temp_string, '*'); + furi_string_cat(temp_string, barcode_data->raw_data); + furi_string_set(barcode_data->raw_data, temp_string); + } + + if(!furi_string_end_with(barcode_data->raw_data, "*")) { + furi_string_push_back(barcode_data->raw_data, '*'); + } + + furi_string_free(temp_string); + barcode_length = furi_string_size(barcode_data->raw_data); + + //Open Storage + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + if(!flipper_format_file_open_existing(ff, CODE39_DICT_FILE_PATH)) { + FURI_LOG_E(TAG, "Could not open file %s", CODE39_DICT_FILE_PATH); + barcode_data->reason = MissingEncodingTable; + barcode_data->valid = false; + } else { + FuriString* char_bits = furi_string_alloc(); + for(int i = 0; i < barcode_length; i++) { + char barcode_char = toupper(furi_string_get_char(barcode_data->raw_data, i)); + + //convert a char into a string so it used in flipper_format_read_string + char current_character[2]; + snprintf(current_character, 2, "%c", barcode_char); + + if(!flipper_format_read_string(ff, current_character, char_bits)) { + FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); + barcode_data->reason = InvalidCharacters; + barcode_data->valid = false; + break; + } else { + FURI_LOG_I( + TAG, "\"%c\" string: %s", barcode_char, furi_string_get_cstr(char_bits)); + furi_string_cat(barcode_bits, char_bits); + } + flipper_format_rewind(ff); + } + furi_string_free(char_bits); + } + + //Close Storage + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + furi_string_cat(barcode_data->correct_data, barcode_bits); + furi_string_free(barcode_bits); +} + +/** + * Loads a code 128 barcode + * + * Only supports character set B +*/ +void code_128_loader(BarcodeData* barcode_data) { + int barcode_length = furi_string_size(barcode_data->raw_data); + + //the start code for character set B + int start_code_value = 104; + + //The bits for the start code + const char* start_code_bits = "11010010000"; + + //The bits for the stop code + const char* stop_code_bits = "1100011101011"; + + int min_digits = barcode_data->type_obj->min_digits; + + /** + * A sum of all of the characters values + * Ex: + * Barcode Data : ABC + * A has a value of 33 + * B has a value of 34 + * C has a value of 35 + * + * the checksum_adder would be (33 * 1) + (34 * 2) + (35 * 3) + 104 = 310 + * + * Add 104 since we are using set B + */ + int checksum_adder = start_code_value; + /** + * Checksum digits is the number of characters it has read so far + * In the above example the checksum_digits would be 3 + */ + int checksum_digits = 0; + + //the calculated check digit + int final_check_digit = 0; + + //check the length of the barcode, must contain atleast a character, + //this can have as many characters as it wants, it might not fit on the screen + if(barcode_length < min_digits) { + barcode_data->reason = WrongNumberOfDigits; + barcode_data->valid = false; + return; + } + + //Open Storage + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + FuriString* barcode_bits = furi_string_alloc(); + + //add the start code + furi_string_cat(barcode_bits, start_code_bits); + + if(!flipper_format_file_open_existing(ff, CODE128_DICT_FILE_PATH)) { + FURI_LOG_E(TAG, "Could not open file %s", CODE128_DICT_FILE_PATH); + barcode_data->reason = MissingEncodingTable; + barcode_data->valid = false; + } else { + FuriString* value = furi_string_alloc(); + FuriString* char_bits = furi_string_alloc(); + for(int i = 0; i < barcode_length; i++) { + char barcode_char = furi_string_get_char(barcode_data->raw_data, i); + + //convert a char into a string so it used in flipper_format_read_string + char current_character[2]; + snprintf(current_character, 2, "%c", barcode_char); + + //get the value of the character + if(!flipper_format_read_string(ff, current_character, value)) { + FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); + barcode_data->reason = InvalidCharacters; + barcode_data->valid = false; + break; + } + //using the value of the character, get the characters bits + if(!flipper_format_read_string(ff, furi_string_get_cstr(value), char_bits)) { + FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); + barcode_data->reason = EncodingTableError; + barcode_data->valid = false; + break; + } else { + //add the bits to the full barcode + furi_string_cat(barcode_bits, char_bits); + + //calculate the checksum + checksum_digits += 1; + checksum_adder += (atoi(furi_string_get_cstr(value)) * checksum_digits); + + FURI_LOG_D( + TAG, + "\"%c\" string: %s : %s : %d : %d : %d", + barcode_char, + furi_string_get_cstr(char_bits), + furi_string_get_cstr(value), + checksum_digits, + (atoi(furi_string_get_cstr(value)) * checksum_digits), + checksum_adder); + } + //bring the file pointer back to the beginning + flipper_format_rewind(ff); + } + + //calculate the check digit and convert it into a c string for lookup in the encoding table + final_check_digit = checksum_adder % 103; + int length = snprintf(NULL, 0, "%d", final_check_digit); + char* final_check_digit_string = malloc(length + 1); + snprintf(final_check_digit_string, length + 1, "%d", final_check_digit); + + //after the checksum has been calculated, add the bits to the full barcode + if(!flipper_format_read_string(ff, final_check_digit_string, char_bits)) { + FURI_LOG_E(TAG, "Could not read \"%s\" string", final_check_digit_string); + barcode_data->reason = EncodingTableError; + barcode_data->valid = false; + } else { + //add the check digit bits to the full barcode + furi_string_cat(barcode_bits, char_bits); + + FURI_LOG_D( + TAG, + "\"%s\" string: %s", + final_check_digit_string, + furi_string_get_cstr(char_bits)); + } + + free(final_check_digit_string); + furi_string_free(value); + furi_string_free(char_bits); + } + + //add the stop code + furi_string_cat(barcode_bits, stop_code_bits); + + //Close Storage + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + furi_string_cat(barcode_data->correct_data, barcode_bits); + furi_string_free(barcode_bits); +} + +/** + * Loads a code 128 C barcode +*/ +void code_128c_loader(BarcodeData* barcode_data) { + int barcode_length = furi_string_size(barcode_data->raw_data); + + //the start code for character set C + int start_code_value = 105; + + //The bits for the start code + const char* start_code_bits = "11010011100"; + + //The bits for the stop code + const char* stop_code_bits = "1100011101011"; + + int min_digits = barcode_data->type_obj->min_digits; + + int checksum_adder = start_code_value; + int checksum_digits = 0; + + //the calculated check digit + int final_check_digit = 0; + + // check the length of the barcode, must contain atleast 2 character, + // this can have as many characters as it wants, it might not fit on the screen + // code 128 C: the length must be even + if((barcode_length < min_digits) || (barcode_length & 1)) { + barcode_data->reason = WrongNumberOfDigits; + barcode_data->valid = false; + return; + } + //Open Storage + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + FuriString* barcode_bits = furi_string_alloc(); + + //add the start code + furi_string_cat(barcode_bits, start_code_bits); + + if(!flipper_format_file_open_existing(ff, CODE128C_DICT_FILE_PATH)) { + FURI_LOG_E(TAG, "c128c Could not open file %s", CODE128C_DICT_FILE_PATH); + barcode_data->reason = MissingEncodingTable; + barcode_data->valid = false; + } else { + FuriString* value = furi_string_alloc(); + FuriString* char_bits = furi_string_alloc(); + for(int i = 0; i < barcode_length; i += 2) { + char barcode_char1 = furi_string_get_char(barcode_data->raw_data, i); + char barcode_char2 = furi_string_get_char(barcode_data->raw_data, i + 1); + FURI_LOG_I(TAG, "c128c bc1='%c' bc2='%c'", barcode_char1, barcode_char2); + + char current_chars[4]; + snprintf(current_chars, 3, "%c%c", barcode_char1, barcode_char2); + FURI_LOG_I(TAG, "c128c current_chars='%s'", current_chars); + + //using the value of the characters, get the characters bits + if(!flipper_format_read_string(ff, current_chars, char_bits)) { + FURI_LOG_E(TAG, "c128c Could not read \"%s\" string", current_chars); + barcode_data->reason = EncodingTableError; + barcode_data->valid = false; + break; + } else { + //add the bits to the full barcode + furi_string_cat(barcode_bits, char_bits); + + // calculate the checksum + checksum_digits += 1; + checksum_adder += (atoi(current_chars) * checksum_digits); + + FURI_LOG_I( + TAG, + "c128c \"%s\" string: %s : %s : %d : %d : %d", + current_chars, + furi_string_get_cstr(char_bits), + furi_string_get_cstr(value), + checksum_digits, + (atoi(furi_string_get_cstr(value)) * checksum_digits), + checksum_adder); + } + //bring the file pointer back to the begining + flipper_format_rewind(ff); + } + //calculate the check digit and convert it into a c string for lookup in the encoding table + final_check_digit = checksum_adder % 103; + FURI_LOG_I(TAG, "c128c finale_check_digit=%d", final_check_digit); + + int length = snprintf(NULL, 0, "%d", final_check_digit); + if(final_check_digit < 100) length = 2; + char* final_check_digit_string = malloc(length + 1); + snprintf(final_check_digit_string, length + 1, "%02d", final_check_digit); + + //after the checksum has been calculated, add the bits to the full barcode + if(!flipper_format_read_string(ff, final_check_digit_string, char_bits)) { + FURI_LOG_E(TAG, "c128c cksum Could not read \"%s\" string", final_check_digit_string); + barcode_data->reason = EncodingTableError; + barcode_data->valid = false; + } else { + //add the check digit bits to the full barcode + furi_string_cat(barcode_bits, char_bits); + + FURI_LOG_I( + TAG, + "check digit \"%s\" string: %s", + final_check_digit_string, + furi_string_get_cstr(char_bits)); + } + + free(final_check_digit_string); + furi_string_free(value); + furi_string_free(char_bits); + } + + //add the stop code + furi_string_cat(barcode_bits, stop_code_bits); + + //Close Storage + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + FURI_LOG_I(TAG, "c128c %s", furi_string_get_cstr(barcode_bits)); + furi_string_cat(barcode_data->correct_data, barcode_bits); + furi_string_free(barcode_bits); +} + +void codabar_loader(BarcodeData* barcode_data) { + int barcode_length = furi_string_size(barcode_data->raw_data); + + int min_digits = barcode_data->type_obj->min_digits; + + //check the length of the barcode, must contain atleast a character, + //this can have as many characters as it wants, it might not fit on the screen + if(barcode_length < min_digits) { + barcode_data->reason = WrongNumberOfDigits; + barcode_data->valid = false; + return; + } + + FuriString* barcode_bits = furi_string_alloc(); + + barcode_length = furi_string_size(barcode_data->raw_data); + + //Open Storage + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + if(!flipper_format_file_open_existing(ff, CODABAR_DICT_FILE_PATH)) { + FURI_LOG_E(TAG, "Could not open file %s", CODABAR_DICT_FILE_PATH); + barcode_data->reason = MissingEncodingTable; + barcode_data->valid = false; + } else { + FuriString* char_bits = furi_string_alloc(); + for(int i = 0; i < barcode_length; i++) { + char barcode_char = toupper(furi_string_get_char(barcode_data->raw_data, i)); + + //convert a char into a string so it used in flipper_format_read_string + char current_character[2]; + snprintf(current_character, 2, "%c", barcode_char); + + if(!flipper_format_read_string(ff, current_character, char_bits)) { + FURI_LOG_E(TAG, "Could not read \"%c\" string", barcode_char); + barcode_data->reason = InvalidCharacters; + barcode_data->valid = false; + break; + } else { + FURI_LOG_I( + TAG, "\"%c\" string: %s", barcode_char, furi_string_get_cstr(char_bits)); + furi_string_cat(barcode_bits, char_bits); + } + flipper_format_rewind(ff); + } + furi_string_free(char_bits); + } + + //Close Storage + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + furi_string_cat(barcode_data->correct_data, barcode_bits); + furi_string_free(barcode_bits); +} diff --git a/applications/external/barcode_gen/barcode_validator.h b/applications/external/barcode_gen/barcode_validator.h new file mode 100644 index 000000000..2138124dd --- /dev/null +++ b/applications/external/barcode_gen/barcode_validator.h @@ -0,0 +1,15 @@ +#pragma once + +#include "barcode_app.h" + +int calculate_check_digit(BarcodeData* barcode_data); +int calculate_ean_upc_check_digit(BarcodeData* barcode_data); +void ean_upc_loader(BarcodeData* barcode_data); +void upc_a_loader(BarcodeData* barcode_data); +void ean_8_loader(BarcodeData* barcode_data); +void ean_13_loader(BarcodeData* barcode_data); +void code_39_loader(BarcodeData* barcode_data); +void code_128_loader(BarcodeData* barcode_data); +void code_128c_loader(BarcodeData* barcode_data); +void codabar_loader(BarcodeData* barcode_data); +void barcode_loader(BarcodeData* barcode_data); diff --git a/applications/external/barcode_gen/encodings.c b/applications/external/barcode_gen/encodings.c new file mode 100644 index 000000000..764fde796 --- /dev/null +++ b/applications/external/barcode_gen/encodings.c @@ -0,0 +1,52 @@ +#include "encodings.h" + +const char EAN_13_STRUCTURE_CODES[10][6] = { + "LLLLLL", + "LLGLGG", + "LLGGLG", + "LLGGGL", + "LGLLGG", + "LGGLLG", + "LGGGLL", + "LGLGLG", + "LGLGGL", + "LGGLGL"}; + +const char UPC_EAN_L_CODES[10][8] = { + "0001101", // 0 + "0011001", // 1 + "0010011", // 2 + "0111101", // 3 + "0100011", // 4 + "0110001", // 5 + "0101111", // 6 + "0111011", // 7 + "0110111", // 8 + "0001011" // 9 +}; + +const char EAN_G_CODES[10][8] = { + "0100111", // 0 + "0110011", // 1 + "0011011", // 2 + "0100001", // 3 + "0011101", // 4 + "0111001", // 5 + "0000101", // 6 + "0010001", // 7 + "0001001", // 8 + "0010111" // 9 +}; + +const char UPC_EAN_R_CODES[10][8] = { + "1110010", // 0 + "1100110", // 1 + "1101100", // 2 + "1000010", // 3 + "1011100", // 4 + "1001110", // 5 + "1010000", // 6 + "1000100", // 7 + "1001000", // 8 + "1110100" // 9 +}; \ No newline at end of file diff --git a/applications/external/barcode_gen/encodings.h b/applications/external/barcode_gen/encodings.h new file mode 100644 index 000000000..c5b8d61ff --- /dev/null +++ b/applications/external/barcode_gen/encodings.h @@ -0,0 +1,6 @@ +#pragma once + +extern const char EAN_13_STRUCTURE_CODES[10][6]; +extern const char UPC_EAN_L_CODES[10][8]; +extern const char EAN_G_CODES[10][8]; +extern const char UPC_EAN_R_CODES[10][8]; \ No newline at end of file diff --git a/applications/external/barcode_gen/images/barcode_10.png b/applications/external/barcode_gen/images/barcode_10.png new file mode 100644 index 000000000..32d4971ad Binary files /dev/null and b/applications/external/barcode_gen/images/barcode_10.png differ diff --git a/applications/external/barcode_gen/screenshots/Codabar Data Example.png b/applications/external/barcode_gen/screenshots/Codabar Data Example.png new file mode 100644 index 000000000..907dfd901 Binary files /dev/null and b/applications/external/barcode_gen/screenshots/Codabar Data Example.png differ diff --git a/applications/external/barcode_gen/screenshots/Creating Barcode.png b/applications/external/barcode_gen/screenshots/Creating Barcode.png new file mode 100644 index 000000000..e976b5682 Binary files /dev/null and b/applications/external/barcode_gen/screenshots/Creating Barcode.png differ diff --git a/applications/external/barcode_gen/screenshots/Flipper Barcode.png b/applications/external/barcode_gen/screenshots/Flipper Barcode.png new file mode 100644 index 000000000..a6758c621 Binary files /dev/null and b/applications/external/barcode_gen/screenshots/Flipper Barcode.png differ diff --git a/applications/external/barcode_gen/screenshots/Flipper Box Barcode.png b/applications/external/barcode_gen/screenshots/Flipper Box Barcode.png new file mode 100644 index 000000000..8dbd7d2a9 Binary files /dev/null and b/applications/external/barcode_gen/screenshots/Flipper Box Barcode.png differ diff --git a/applications/external/barcode_gen/views/barcode_view.c b/applications/external/barcode_gen/views/barcode_view.c new file mode 100644 index 000000000..55ab52046 --- /dev/null +++ b/applications/external/barcode_gen/views/barcode_view.c @@ -0,0 +1,510 @@ +#include "../barcode_app.h" +#include "barcode_view.h" +#include "../encodings.h" + +/** + * @brief Draws a single bit from a barcode at a specified location + * @param canvas + * @param bit a 1 or a 0 to signify a bit of data + * @param x the top left x coordinate + * @param y the top left y coordinate + * @param width the width of the bit + * @param height the height of the bit + */ +static void draw_bit(Canvas* canvas, int bit, int x, int y, int width, int height) { + if(bit == 1) { + canvas_set_color(canvas, ColorBlack); + } else { + canvas_set_color(canvas, ColorWhite); + } + canvas_draw_box(canvas, x, y, width, height); +} + +/** + * +*/ +static void draw_error_str(Canvas* canvas, const char* error) { + canvas_clear(canvas); + canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); +} + +/** + * @param bits a string of 1's and 0's + * @returns the x coordinate after the bits have been drawn, useful for drawing the next section of bits +*/ +static int draw_bits(Canvas* canvas, const char* bits, int x, int y, int width, int height) { + int bits_length = strlen(bits); + for(int i = 0; i < bits_length; i++) { + char c = bits[i]; + int num = c - '0'; + + draw_bit(canvas, num, x, y, width, height); + + x += width; + } + return x; +} + +/** + * Draws an EAN-8 type barcode, does not check if the barcode is valid + * @param canvas the canvas + * @param barcode_digits the digits in the barcode, must be 8 characters long +*/ +static void draw_ean_8(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* barcode_digits = barcode_data->correct_data; + BarcodeTypeObj* type_obj = barcode_data->type_obj; + + int barcode_length = furi_string_size(barcode_digits); + + int x = type_obj->start_pos; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + + //the guard patterns for the beginning, center, ending + const char* end_bits = "101"; + const char* center_bits = "01010"; + + //draw the starting guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); + + FuriString* code_part = furi_string_alloc(); + + //loop through each digit, find the encoding, and draw it + for(int i = 0; i < barcode_length; i++) { + char current_digit = furi_string_get_char(barcode_digits, i); + + //the actual number and the index of the bits + int index = current_digit - '0'; + //use the L-codes for the first 4 digits and the R-Codes for the last 4 digits + if(i <= 3) { + furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); + } else { + furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); + } + + //convert the current_digit char into a string so it can be printed + char current_digit_string[2]; + snprintf(current_digit_string, 2, "%c", current_digit); + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); + + //draw the bits of the barcode + x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); + + //if the index has reached 3, that means 4 digits have been drawn and now draw the center guard pattern + if(i == 3) { + x = draw_bits(canvas, center_bits, x, y, width, height + 5); + } + } + furi_string_free(code_part); + + //draw the ending guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); +} + +static void draw_ean_13(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* barcode_digits = barcode_data->correct_data; + BarcodeTypeObj* type_obj = barcode_data->type_obj; + + int barcode_length = furi_string_size(barcode_digits); + + int x = type_obj->start_pos; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + + //the guard patterns for the beginning, center, ending + const char* end_bits = "101"; + const char* center_bits = "01010"; + + //draw the starting guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); + + FuriString* left_structure = furi_string_alloc(); + FuriString* code_part = furi_string_alloc(); + + //loop through each digit, find the encoding, and draw it + for(int i = 0; i < barcode_length; i++) { + char current_digit = furi_string_get_char(barcode_digits, i); + int index = current_digit - '0'; + + if(i == 0) { + furi_string_set_str(left_structure, EAN_13_STRUCTURE_CODES[index]); + + //convert the current_digit char into a string so it can be printed + char current_digit_string[2]; + snprintf(current_digit_string, 2, "%c", current_digit); + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + canvas_draw_str(canvas, x - 10, y + height + 8, current_digit_string); + + continue; + } else { + //use the L-codes for the first 6 digits and the R-Codes for the last 6 digits + if(i <= 6) { + //get the encoding type at the current barcode bit position + char encoding_type = furi_string_get_char(left_structure, i - 1); + if(encoding_type == 'L') { + furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); + } else { + furi_string_set_str(code_part, EAN_G_CODES[index]); + } + } else { + furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); + } + + //convert the current_digit char into a string so it can be printed + char current_digit_string[2]; + snprintf(current_digit_string, 2, "%c", current_digit); + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); + + //draw the bits of the barcode + x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); + + //if the index has reached 6, that means 6 digits have been drawn and we now draw the center guard pattern + if(i == 6) { + x = draw_bits(canvas, center_bits, x, y, width, height + 5); + } + } + } + + furi_string_free(left_structure); + furi_string_free(code_part); + + //draw the ending guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); +} + +/** + * Draw a UPC-A barcode +*/ +static void draw_upc_a(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* barcode_digits = barcode_data->correct_data; + BarcodeTypeObj* type_obj = barcode_data->type_obj; + + int barcode_length = furi_string_size(barcode_digits); + + int x = type_obj->start_pos; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + + //the guard patterns for the beginning, center, ending + char* end_bits = "101"; + char* center_bits = "01010"; + + //draw the starting guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); + + FuriString* code_part = furi_string_alloc(); + + //loop through each digit, find the encoding, and draw it + for(int i = 0; i < barcode_length; i++) { + char current_digit = furi_string_get_char(barcode_digits, i); + int index = current_digit - '0'; //convert the number into an int (also the index) + + //use the L-codes for the first 6 digits and the R-Codes for the last 6 digits + if(i <= 5) { + furi_string_set_str(code_part, UPC_EAN_L_CODES[index]); + } else { + furi_string_set_str(code_part, UPC_EAN_R_CODES[index]); + } + + //convert the current_digit char into a string so it can be printed + char current_digit_string[2]; + snprintf(current_digit_string, 2, "%c", current_digit); + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + canvas_draw_str(canvas, x + 1, y + height + 8, current_digit_string); + + //draw the bits of the barcode + x = draw_bits(canvas, furi_string_get_cstr(code_part), x, y, width, height); + + //if the index has reached 6, that means 6 digits have been drawn and we now draw the center guard pattern + if(i == 5) { + x = draw_bits(canvas, center_bits, x, y, width, height + 5); + } + } + + furi_string_free(code_part); + + //draw the ending guard pattern + x = draw_bits(canvas, end_bits, x, y, width, height + 5); +} + +static void draw_code_39(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* raw_data = barcode_data->raw_data; + FuriString* barcode_digits = barcode_data->correct_data; + //BarcodeTypeObj* type_obj = barcode_data->type_obj; + + int barcode_length = furi_string_size(barcode_digits); + int total_pixels = 0; + + for(int i = 0; i < barcode_length; i++) { + //1 for wide, 0 for narrow + char wide_or_narrow = furi_string_get_char(barcode_digits, i); + int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit + + if(wn_digit == 1) { + total_pixels += 3; + } else { + total_pixels += 1; + } + if((i + 1) % 9 == 0) { + total_pixels += 1; + } + } + + int x = (128 - total_pixels) / 2; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + bool filled_in = true; + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); + canvas_draw_str_aligned( + canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); + + for(int i = 0; i < barcode_length; i++) { + //1 for wide, 0 for narrow + char wide_or_narrow = furi_string_get_char(barcode_digits, i); + int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit + + if(filled_in) { + if(wn_digit == 1) { + x = draw_bits(canvas, "111", x, y, width, height); + } else { + x = draw_bits(canvas, "1", x, y, width, height); + } + filled_in = false; + } else { + if(wn_digit == 1) { + x = draw_bits(canvas, "000", x, y, width, height); + } else { + x = draw_bits(canvas, "0", x, y, width, height); + } + filled_in = true; + } + if((i + 1) % 9 == 0) { + x = draw_bits(canvas, "0", x, y, width, height); + filled_in = true; + } + } +} + +static void draw_code_128(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* raw_data = barcode_data->raw_data; + FuriString* barcode_digits = barcode_data->correct_data; + + int barcode_length = furi_string_size(barcode_digits); + + int x = (128 - barcode_length) / 2; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + + x = draw_bits(canvas, furi_string_get_cstr(barcode_digits), x, y, width, height); + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); + canvas_draw_str_aligned( + canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); +} + +static void draw_codabar(Canvas* canvas, BarcodeData* barcode_data) { + FuriString* raw_data = barcode_data->raw_data; + FuriString* barcode_digits = barcode_data->correct_data; + //BarcodeTypeObj* type_obj = barcode_data->type_obj; + + int barcode_length = furi_string_size(barcode_digits); + int total_pixels = 0; + + for(int i = 0; i < barcode_length; i++) { + //1 for wide, 0 for narrow + char wide_or_narrow = furi_string_get_char(barcode_digits, i); + int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit + + if(wn_digit == 1) { + total_pixels += 3; + } else { + total_pixels += 1; + } + if((i + 1) % 7 == 0) { + total_pixels += 1; + } + } + + int x = (128 - total_pixels) / 2; + int y = BARCODE_Y_START; + int width = 1; + int height = BARCODE_HEIGHT; + bool filled_in = true; + + //set the canvas color to black to print the digit + canvas_set_color(canvas, ColorBlack); + // canvas_draw_str_aligned(canvas, 62, 30, AlignCenter, AlignCenter, error); + canvas_draw_str_aligned( + canvas, 62, y + height + 8, AlignCenter, AlignBottom, furi_string_get_cstr(raw_data)); + + for(int i = 0; i < barcode_length; i++) { + //1 for wide, 0 for narrow + char wide_or_narrow = furi_string_get_char(barcode_digits, i); + int wn_digit = wide_or_narrow - '0'; //wide(1) or narrow(0) digit + + if(filled_in) { + if(wn_digit == 1) { + x = draw_bits(canvas, "111", x, y, width, height); + } else { + x = draw_bits(canvas, "1", x, y, width, height); + } + filled_in = false; + } else { + if(wn_digit == 1) { + x = draw_bits(canvas, "000", x, y, width, height); + } else { + x = draw_bits(canvas, "0", x, y, width, height); + } + filled_in = true; + } + if((i + 1) % 7 == 0) { + x = draw_bits(canvas, "0", x, y, width, height); + filled_in = true; + } + } +} + +static void barcode_draw_callback(Canvas* canvas, void* ctx) { + furi_assert(ctx); + BarcodeModel* barcode_model = ctx; + BarcodeData* data = barcode_model->data; + // const char* barcode_digits =; + + canvas_clear(canvas); + if(data->valid) { + switch(data->type_obj->type) { + case UPCA: + draw_upc_a(canvas, data); + break; + case EAN8: + draw_ean_8(canvas, data); + break; + case EAN13: + draw_ean_13(canvas, data); + break; + case CODE39: + draw_code_39(canvas, data); + break; + case CODE128: + case CODE128C: + draw_code_128(canvas, data); + break; + case CODABAR: + draw_codabar(canvas, data); + break; + case UNKNOWN: + default: + break; + } + } else { + switch(data->reason) { + case WrongNumberOfDigits: + draw_error_str(canvas, "Wrong # of characters"); + break; + case InvalidCharacters: + draw_error_str(canvas, "Invalid characters"); + break; + case UnsupportedType: + draw_error_str(canvas, "Unsupported barcode type"); + break; + case FileOpening: + draw_error_str(canvas, "Could not open file"); + break; + case InvalidFileData: + draw_error_str(canvas, "Invalid file data"); + break; + case MissingEncodingTable: + draw_error_str(canvas, "Missing encoding table"); + break; + case EncodingTableError: + draw_error_str(canvas, "Encoding table error"); + break; + default: + draw_error_str(canvas, "Could not read barcode data"); + break; + } + } +} + +bool barcode_input_callback(InputEvent* input_event, void* ctx) { + UNUSED(ctx); + //furi_assert(ctx); + + //Barcode* test_view_object = ctx; + + if(input_event->key == InputKeyBack) { + return false; + } else { + return true; + } +} + +Barcode* barcode_view_allocate(BarcodeApp* barcode_app) { + furi_assert(barcode_app); + + Barcode* barcode = malloc(sizeof(Barcode)); + + barcode->view = view_alloc(); + barcode->barcode_app = barcode_app; + + view_set_context(barcode->view, barcode); + view_allocate_model(barcode->view, ViewModelTypeLocking, sizeof(BarcodeModel)); + view_set_draw_callback(barcode->view, barcode_draw_callback); + view_set_input_callback(barcode->view, barcode_input_callback); + + return barcode; +} + +void barcode_free_model(Barcode* barcode) { + with_view_model( + barcode->view, + BarcodeModel * model, + { + if(model->file_path != NULL) { + furi_string_free(model->file_path); + } + if(model->data != NULL) { + if(model->data->raw_data != NULL) { + furi_string_free(model->data->raw_data); + } + if(model->data->correct_data != NULL) { + furi_string_free(model->data->correct_data); + } + free(model->data); + } + }, + false); +} + +void barcode_free(Barcode* barcode) { + furi_assert(barcode); + + barcode_free_model(barcode); + view_free(barcode->view); + free(barcode); +} + +View* barcode_get_view(Barcode* barcode) { + furi_assert(barcode); + return barcode->view; +} diff --git a/applications/external/barcode_gen/views/barcode_view.h b/applications/external/barcode_gen/views/barcode_view.h new file mode 100644 index 000000000..828428c08 --- /dev/null +++ b/applications/external/barcode_gen/views/barcode_view.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +typedef struct BarcodeApp BarcodeApp; + +typedef struct { + View* view; + BarcodeApp* barcode_app; +} Barcode; + +typedef struct { + FuriString* file_path; + BarcodeData* data; +} BarcodeModel; + +Barcode* barcode_view_allocate(BarcodeApp* barcode_app); + +void barcode_free_model(Barcode* barcode); + +void barcode_free(Barcode* barcode); + +View* barcode_get_view(Barcode* barcode); diff --git a/applications/external/barcode_gen/views/create_view.c b/applications/external/barcode_gen/views/create_view.c new file mode 100644 index 000000000..e4e489113 --- /dev/null +++ b/applications/external/barcode_gen/views/create_view.c @@ -0,0 +1,494 @@ +#include "../barcode_app.h" +#include "create_view.h" +#include + +#define LINE_HEIGHT 16 +#define TEXT_PADDING 4 +#define TOTAL_MENU_ITEMS 5 + +typedef enum { + TypeMenuItem, + FileNameMenuItem, + BarcodeDataMenuItem, + SaveMenuButton, + DeleteMenuButton +} MenuItems; + +/** + * Took this function from blackjack + * @author @teeebor +*/ +void draw_menu_item( + Canvas* const canvas, + const char* text, + const char* value, + int y, + bool left_caret, + bool right_caret, + bool selected) { + UNUSED(selected); + if(y < 0 || y >= 64) { + return; + } + + if(selected) { + canvas_set_color(canvas, ColorBlack); + canvas_draw_box(canvas, 0, y, 123, LINE_HEIGHT); + canvas_set_color(canvas, ColorWhite); + } + + canvas_draw_str_aligned(canvas, 4, y + TEXT_PADDING, AlignLeft, AlignTop, text); + if(left_caret) { + canvas_draw_str_aligned(canvas, 60, y + TEXT_PADDING, AlignLeft, AlignTop, "<"); + } + + canvas_draw_str_aligned(canvas, 90, y + TEXT_PADDING, AlignCenter, AlignTop, value); + if(right_caret) { + canvas_draw_str_aligned(canvas, 120, y + TEXT_PADDING, AlignRight, AlignTop, ">"); + } + + canvas_set_color(canvas, ColorBlack); +} + +void draw_button(Canvas* const canvas, const char* text, int y, bool selected) { + if(selected) { + canvas_set_color(canvas, ColorBlack); + canvas_draw_box(canvas, 0, y, 123, LINE_HEIGHT); + canvas_set_color(canvas, ColorWhite); + } + + canvas_draw_str_aligned(canvas, 64, y + TEXT_PADDING, AlignCenter, AlignTop, text); + + canvas_set_color(canvas, ColorBlack); +} + +static void app_draw_callback(Canvas* canvas, void* ctx) { + furi_assert(ctx); + + CreateViewModel* create_view_model = ctx; + + BarcodeTypeObj* type_obj = create_view_model->barcode_type; + if(create_view_model->barcode_type == NULL) { + return; + } + BarcodeType selected_type = type_obj->type; + + int selected_menu_item = create_view_model->selected_menu_item; + + int total_menu_items = create_view_model->mode == EditMode ? TOTAL_MENU_ITEMS : + TOTAL_MENU_ITEMS - 1; + + int startY = 0; + + //the menu items index that is/would be in view + //int current_last_menu_item = selected_menu_item + 3; + if(selected_menu_item > 1) { + int offset = 2; + if(selected_menu_item + offset > total_menu_items) { + offset = 3; + } + startY -= (LINE_HEIGHT * (selected_menu_item - offset)); + } + + //ensure that the scroll height is atleast 1 + int scrollHeight = ceil(64.0 / total_menu_items); + int scrollPos = scrollHeight * selected_menu_item; + + canvas_set_color(canvas, ColorBlack); + //draw the scroll bar box + canvas_draw_box(canvas, 125, scrollPos, 3, scrollHeight); + //draw the scroll bar track + canvas_draw_box(canvas, 126, 0, 1, 64); + + draw_menu_item( + canvas, + "Type", + type_obj->name, + TypeMenuItem * LINE_HEIGHT + startY, + selected_type > 0, + selected_type < NUMBER_OF_BARCODE_TYPES - 2, + selected_menu_item == TypeMenuItem); + + draw_menu_item( + canvas, + "Name", + furi_string_empty(create_view_model->file_name) ? + "--" : + furi_string_get_cstr(create_view_model->file_name), + FileNameMenuItem * LINE_HEIGHT + startY, + false, + false, + selected_menu_item == FileNameMenuItem); + + draw_menu_item( + canvas, + "Data", + furi_string_empty(create_view_model->barcode_data) ? + "--" : + furi_string_get_cstr(create_view_model->barcode_data), + BarcodeDataMenuItem * LINE_HEIGHT + startY, + false, + false, + selected_menu_item == BarcodeDataMenuItem); + + draw_button( + canvas, + "Save", + SaveMenuButton * LINE_HEIGHT + startY, + selected_menu_item == SaveMenuButton); + + if(create_view_model->mode == EditMode) { + draw_button( + canvas, + "Delete", + DeleteMenuButton * LINE_HEIGHT + startY, + selected_menu_item == DeleteMenuButton); + } +} + +void text_input_callback(void* ctx) { + CreateView* create_view_object = ctx; + + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + if(create_view_object->setter == FileNameSetter) { + furi_string_set_str(model->file_name, create_view_object->input); + } + if(create_view_object->setter == BarcodeDataSetter) { + furi_string_set_str(model->barcode_data, create_view_object->input); + } + }, + true); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, CreateBarcodeView); +} + +static bool app_input_callback(InputEvent* input_event, void* ctx) { + furi_assert(ctx); + + if(input_event->key == InputKeyBack) { + return false; + } + + CreateView* create_view_object = ctx; + + //get the currently selected menu item from the model + int selected_menu_item = 0; + BarcodeTypeObj* barcode_type = NULL; + FuriString* file_name; + FuriString* barcode_data; + CreateMode mode; + + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + selected_menu_item = model->selected_menu_item; + barcode_type = model->barcode_type; + file_name = model->file_name; + barcode_data = model->barcode_data; + mode = model->mode; + }, + true); + + int total_menu_items = mode == EditMode ? TOTAL_MENU_ITEMS : TOTAL_MENU_ITEMS - 1; + + if(input_event->type == InputTypePress) { + if(input_event->key == InputKeyUp && selected_menu_item > 0) { + selected_menu_item--; + } else if(input_event->key == InputKeyDown && selected_menu_item < total_menu_items - 1) { + selected_menu_item++; + } else if(input_event->key == InputKeyLeft) { + if(selected_menu_item == TypeMenuItem && barcode_type != NULL) { //Select Barcode Type + if(barcode_type->type > 0) { + barcode_type = barcode_type_objs[barcode_type->type - 1]; + } + } + } else if(input_event->key == InputKeyRight) { + if(selected_menu_item == TypeMenuItem && barcode_type != NULL) { //Select Barcode Type + if(barcode_type->type < NUMBER_OF_BARCODE_TYPES - 2) { + barcode_type = barcode_type_objs[barcode_type->type + 1]; + } + } + } else if(input_event->key == InputKeyOk) { + if(selected_menu_item == FileNameMenuItem && barcode_type != NULL) { + create_view_object->setter = FileNameSetter; + + snprintf( + create_view_object->input, + sizeof(create_view_object->input), + "%s", + furi_string_get_cstr(file_name)); + + text_input_set_result_callback( + create_view_object->barcode_app->text_input, + text_input_callback, + create_view_object, + create_view_object->input, + TEXT_BUFFER_SIZE - BARCODE_EXTENSION_LENGTH, //remove the barcode length + //clear default text + false); + text_input_set_header_text( + create_view_object->barcode_app->text_input, "File Name"); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, TextInputView); + } + if(selected_menu_item == BarcodeDataMenuItem && barcode_type != NULL) { + create_view_object->setter = BarcodeDataSetter; + + snprintf( + create_view_object->input, + sizeof(create_view_object->input), + "%s", + furi_string_get_cstr(barcode_data)); + + text_input_set_result_callback( + create_view_object->barcode_app->text_input, + text_input_callback, + create_view_object, + create_view_object->input, + TEXT_BUFFER_SIZE, + //clear default text + false); + text_input_set_header_text( + create_view_object->barcode_app->text_input, "Barcode Data"); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, TextInputView); + } + if(selected_menu_item == SaveMenuButton && barcode_type != NULL) { + save_barcode(create_view_object); + } + if(selected_menu_item == DeleteMenuButton && barcode_type != NULL) { + if(mode == EditMode) { + remove_barcode(create_view_object); + } else if(mode == NewMode) { + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, MainMenuView); + } + } + } + } + + //change the currently selected menu item + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + model->selected_menu_item = selected_menu_item; + model->barcode_type = barcode_type; + }, + true); + + return true; +} + +CreateView* create_view_allocate(BarcodeApp* barcode_app) { + furi_assert(barcode_app); + + CreateView* create_view_object = malloc(sizeof(CreateView)); + + create_view_object->view = view_alloc(); + create_view_object->barcode_app = barcode_app; + + view_set_context(create_view_object->view, create_view_object); + view_allocate_model(create_view_object->view, ViewModelTypeLocking, sizeof(CreateViewModel)); + view_set_draw_callback(create_view_object->view, app_draw_callback); + view_set_input_callback(create_view_object->view, app_input_callback); + + return create_view_object; +} + +void create_view_free_model(CreateView* create_view_object) { + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + if(model->file_path != NULL) { + furi_string_free(model->file_path); + } + if(model->file_name != NULL) { + furi_string_free(model->file_name); + } + if(model->barcode_data != NULL) { + furi_string_free(model->barcode_data); + } + }, + true); +} + +void remove_barcode(CreateView* create_view_object) { + Storage* storage = furi_record_open(RECORD_STORAGE); + + bool success = false; + + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + FURI_LOG_I(TAG, "Attempting to remove file"); + if(model->file_path != NULL) { + FURI_LOG_I(TAG, "Removing File: %s", furi_string_get_cstr(model->file_path)); + if(storage_simply_remove(storage, furi_string_get_cstr(model->file_path))) { + FURI_LOG_I( + TAG, + "File: \"%s\" was successfully removed", + furi_string_get_cstr(model->file_path)); + success = true; + } else { + FURI_LOG_E(TAG, "Unable to remove file!"); + success = false; + } + } else { + FURI_LOG_E(TAG, "Could not remove barcode file"); + success = false; + } + }, + true); + furi_record_close(RECORD_STORAGE); + + with_view_model( + create_view_object->barcode_app->message_view->view, + MessageViewModel * model, + { + if(success) { + model->message = "File Deleted"; + } else { + model->message = "Could not delete file"; + } + }, + true); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, MessageErrorView); +} + +void save_barcode(CreateView* create_view_object) { + BarcodeTypeObj* barcode_type = NULL; + FuriString* file_path; //this may be empty + FuriString* file_name; + FuriString* barcode_data; + CreateMode mode; + + with_view_model( + create_view_object->view, + CreateViewModel * model, + { + file_path = model->file_path; + file_name = model->file_name; + barcode_data = model->barcode_data; + barcode_type = model->barcode_type; + mode = model->mode; + }, + true); + + if(file_name == NULL || furi_string_empty(file_name)) { + FURI_LOG_E(TAG, "File Name cannot be empty"); + return; + } + if(barcode_data == NULL || furi_string_empty(barcode_data)) { + FURI_LOG_E(TAG, "Barcode Data cannot be empty"); + return; + } + if(barcode_type == NULL) { + FURI_LOG_E(TAG, "Type not defined"); + return; + } + + bool success = false; + + FuriString* full_file_path = furi_string_alloc_set(DEFAULT_USER_BARCODES); + furi_string_push_back(full_file_path, '/'); + furi_string_cat(full_file_path, file_name); + furi_string_cat_str(full_file_path, BARCODE_EXTENSION); + + Storage* storage = furi_record_open(RECORD_STORAGE); + + if(mode == EditMode) { + if(!furi_string_empty(file_path)) { + if(!furi_string_equal(file_path, full_file_path)) { + FS_Error error = storage_common_rename( + storage, + furi_string_get_cstr(file_path), + furi_string_get_cstr(full_file_path)); + if(error != FSE_OK) { + FURI_LOG_E(TAG, "Rename error: %s", storage_error_get_desc(error)); + } else { + FURI_LOG_I(TAG, "Rename Success"); + } + } + } + } + + FlipperFormat* ff = flipper_format_file_alloc(storage); + + FURI_LOG_I(TAG, "Saving Barcode to: %s", furi_string_get_cstr(full_file_path)); + + bool file_opened_status = false; + if(mode == NewMode) { + file_opened_status = + flipper_format_file_open_new(ff, furi_string_get_cstr(full_file_path)); + } else if(mode == EditMode) { + file_opened_status = + flipper_format_file_open_always(ff, furi_string_get_cstr(full_file_path)); + } + + if(file_opened_status) { + // Filetype: Barcode + // Version: 1 + + // # Types - UPC-A, EAN-8, EAN-13, CODE-39 + // Type: CODE-39 + // Data: AB + flipper_format_write_string_cstr(ff, "Filetype", "Barcode"); + + flipper_format_write_string_cstr(ff, "Version", FILE_VERSION); + + flipper_format_write_comment_cstr( + ff, "Types - UPC-A, EAN-8, EAN-13, CODE-39, CODE-128, Codabar"); + + flipper_format_write_string_cstr(ff, "Type", barcode_type->name); + + flipper_format_write_string_cstr(ff, "Data", furi_string_get_cstr(barcode_data)); + + success = true; + } else { + FURI_LOG_E(TAG, "Save error"); + success = false; + } + furi_string_free(full_file_path); + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + with_view_model( + create_view_object->barcode_app->message_view->view, + MessageViewModel * model, + { + if(success) { + model->message = "File Saved!"; + } else { + model->message = "A saving error has occurred"; + } + }, + true); + + view_dispatcher_switch_to_view( + create_view_object->barcode_app->view_dispatcher, MessageErrorView); +} + +void create_view_free(CreateView* create_view_object) { + furi_assert(create_view_object); + + create_view_free_model(create_view_object); + view_free(create_view_object->view); + free(create_view_object); +} + +View* create_get_view(CreateView* create_view_object) { + furi_assert(create_view_object); + return create_view_object->view; +} \ No newline at end of file diff --git a/applications/external/barcode_gen/views/create_view.h b/applications/external/barcode_gen/views/create_view.h new file mode 100644 index 000000000..6063786d9 --- /dev/null +++ b/applications/external/barcode_gen/views/create_view.h @@ -0,0 +1,46 @@ +#pragma once + +#include + +typedef struct BarcodeApp BarcodeApp; + +typedef enum { + FileNameSetter, + BarcodeDataSetter +} InputSetter; //what value to set for the text input view + +typedef enum { + EditMode, + + NewMode +} CreateMode; + +typedef struct { + View* view; + BarcodeApp* barcode_app; + + InputSetter setter; + char input[TEXT_BUFFER_SIZE]; +} CreateView; + +typedef struct { + int selected_menu_item; + + CreateMode mode; + BarcodeTypeObj* barcode_type; + FuriString* file_path; //the current file that is opened + FuriString* file_name; + FuriString* barcode_data; +} CreateViewModel; + +CreateView* create_view_allocate(BarcodeApp* barcode_app); + +void remove_barcode(CreateView* create_view_object); + +void save_barcode(CreateView* create_view_object); + +void create_view_free_model(CreateView* create_view_object); + +void create_view_free(CreateView* create_view_object); + +View* create_get_view(CreateView* create_view_object); diff --git a/applications/external/barcode_gen/views/message_view.c b/applications/external/barcode_gen/views/message_view.c new file mode 100644 index 000000000..3a9aa90b3 --- /dev/null +++ b/applications/external/barcode_gen/views/message_view.c @@ -0,0 +1,66 @@ +#include "../barcode_app.h" +#include "message_view.h" + +static void app_draw_callback(Canvas* canvas, void* ctx) { + furi_assert(ctx); + + MessageViewModel* message_view_model = ctx; + + canvas_clear(canvas); + if(message_view_model->message != NULL) { + canvas_draw_str_aligned( + canvas, 62, 30, AlignCenter, AlignCenter, message_view_model->message); + } + + canvas_set_color(canvas, ColorBlack); + canvas_draw_box(canvas, 100, 52, 28, 12); + canvas_set_color(canvas, ColorWhite); + canvas_draw_str_aligned(canvas, 114, 58, AlignCenter, AlignCenter, "OK"); +} + +static bool app_input_callback(InputEvent* input_event, void* ctx) { + furi_assert(ctx); + + MessageView* message_view_object = ctx; + + if(input_event->key == InputKeyBack) { + view_dispatcher_switch_to_view( + message_view_object->barcode_app->view_dispatcher, MainMenuView); + } + if(input_event->type == InputTypeShort) { + if(input_event->key == InputKeyOk) { + view_dispatcher_switch_to_view( + message_view_object->barcode_app->view_dispatcher, MainMenuView); + } + } + + return true; +} + +MessageView* message_view_allocate(BarcodeApp* barcode_app) { + furi_assert(barcode_app); + + MessageView* message_view_object = malloc(sizeof(MessageView)); + + message_view_object->view = view_alloc(); + message_view_object->barcode_app = barcode_app; + + view_set_context(message_view_object->view, message_view_object); + view_allocate_model(message_view_object->view, ViewModelTypeLocking, sizeof(MessageViewModel)); + view_set_draw_callback(message_view_object->view, app_draw_callback); + view_set_input_callback(message_view_object->view, app_input_callback); + + return message_view_object; +} + +void message_view_free(MessageView* message_view_object) { + furi_assert(message_view_object); + + view_free(message_view_object->view); + free(message_view_object); +} + +View* message_get_view(MessageView* message_view_object) { + furi_assert(message_view_object); + return message_view_object->view; +} \ No newline at end of file diff --git a/applications/external/barcode_gen/views/message_view.h b/applications/external/barcode_gen/views/message_view.h new file mode 100644 index 000000000..33acc3d0c --- /dev/null +++ b/applications/external/barcode_gen/views/message_view.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +typedef struct BarcodeApp BarcodeApp; + +typedef struct { + View* view; + BarcodeApp* barcode_app; +} MessageView; + +typedef struct { + const char* message; +} MessageViewModel; + +MessageView* message_view_allocate(BarcodeApp* barcode_app); + +void message_view_free_model(MessageView* message_view_object); + +void message_view_free(MessageView* message_view_object); + +View* message_get_view(MessageView* message_view_object); diff --git a/applications/external/barcode_generator/application.fam b/applications/external/barcode_generator/application.fam deleted file mode 100644 index 61d6b7394..000000000 --- a/applications/external/barcode_generator/application.fam +++ /dev/null @@ -1,17 +0,0 @@ -App( - appid="barcode_generator", - name="Barcode Generator", - apptype=FlipperAppType.EXTERNAL, - entry_point="barcode_generator_app", - requires=[ - "gui", - "dialogs", - ], - stack_size=1 * 1024, - order=50, - fap_icon="barcode_10px.png", - fap_category="Misc", - fap_author="@xMasterX & @msvsergey & @McAzzaMan", - fap_version="1.0", - fap_description="App displays Barcode on flipper screen and allows to edit it", -) \ No newline at end of file diff --git a/applications/external/barcode_generator/barcode_10px.png b/applications/external/barcode_generator/barcode_10px.png deleted file mode 100644 index 7c19c6656..000000000 Binary files a/applications/external/barcode_generator/barcode_10px.png and /dev/null differ diff --git a/applications/external/barcode_generator/barcode_generator.c b/applications/external/barcode_generator/barcode_generator.c deleted file mode 100644 index 2645bbcea..000000000 --- a/applications/external/barcode_generator/barcode_generator.c +++ /dev/null @@ -1,447 +0,0 @@ -#include "barcode_generator.h" - -static BarcodeType* barcodeTypes[NUMBER_OF_BARCODE_TYPES]; - -void init_types() { - BarcodeType* upcA = malloc(sizeof(BarcodeType)); - upcA->name = "UPC-A"; - upcA->numberOfDigits = 12; - upcA->startPos = 19; - upcA->bartype = BarTypeUPCA; - barcodeTypes[0] = upcA; - - BarcodeType* ean8 = malloc(sizeof(BarcodeType)); - ean8->name = "EAN-8"; - ean8->numberOfDigits = 8; - ean8->startPos = 33; - ean8->bartype = BarTypeEAN8; - barcodeTypes[1] = ean8; - - BarcodeType* ean13 = malloc(sizeof(BarcodeType)); - ean13->name = "EAN-13"; - ean13->numberOfDigits = 13; - ean13->startPos = 19; - ean13->bartype = BarTypeEAN13; - barcodeTypes[2] = ean13; -} - -void draw_digit( - Canvas* canvas, - int digit, - BarEncodingType rightHand, - int startingPosition, - bool drawlines) { - char digitStr[2]; - snprintf(digitStr, 2, "%u", digit); - canvas_set_color(canvas, ColorBlack); - canvas_draw_str( - canvas, startingPosition, BARCODE_Y_START + BARCODE_HEIGHT + BARCODE_TEXT_OFFSET, digitStr); - - if(drawlines) { - switch(rightHand) { - case BarEncodingTypeLeft: - case BarEncodingTypeRight: - canvas_set_color( - canvas, (rightHand == BarEncodingTypeRight) ? ColorBlack : ColorWhite); - //int count = 0; - for(int i = 0; i < 4; i++) { - canvas_draw_box( - canvas, startingPosition, BARCODE_Y_START, DIGITS[digit][i], BARCODE_HEIGHT); - canvas_invert_color(canvas); - startingPosition += DIGITS[digit][i]; - } - break; - case BarEncodingTypeG: - canvas_set_color(canvas, ColorWhite); - //int count = 0; - for(int i = 3; i >= 0; i--) { - canvas_draw_box( - canvas, startingPosition, BARCODE_Y_START, DIGITS[digit][i], BARCODE_HEIGHT); - canvas_invert_color(canvas); - startingPosition += DIGITS[digit][i]; - } - break; - default: - break; - } - } -} - -int get_digit_position(int index, BarcodeType* type) { - int pos = 0; - switch(type->bartype) { - case BarTypeEAN8: - case BarTypeUPCA: - pos = type->startPos + index * 7; - if(index >= type->numberOfDigits / 2) { - pos += 5; - } - break; - case BarTypeEAN13: - if(index == 0) - pos = type->startPos - 10; - else { - pos = type->startPos + (index - 1) * 7; - if((index - 1) >= type->numberOfDigits / 2) { - pos += 5; - } - } - break; - default: - break; - } - return pos; -} - -int get_menu_text_location(int index) { - return 20 + 10 * index; -} - -int get_barcode_max_index(PluginState* plugin_state) { - return plugin_state->barcode_state.doParityCalculation ? - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]->numberOfDigits - 1 : - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]->numberOfDigits; -} - -int calculate_check_digit(PluginState* plugin_state, BarcodeType* type) { - int checkDigit = 0; - int checkDigitOdd = 0; - int checkDigitEven = 0; - //add all odd positions. Confusing because 0index - for(int i = 0; i < type->numberOfDigits - 1; i += 2) { - checkDigitOdd += plugin_state->barcode_state.barcodeNumeral[i]; - } - - //add all even positions to above. Confusing because 0index - for(int i = 1; i < type->numberOfDigits - 1; i += 2) { - checkDigitEven += plugin_state->barcode_state.barcodeNumeral[i]; - } - - if(type->bartype == BarTypeEAN13) { - checkDigit = checkDigitEven * 3 + checkDigitOdd; - } else { - checkDigit = checkDigitOdd * 3 + checkDigitEven; - } - - checkDigit = checkDigit % 10; //mod 10 - - //if m = 0 then x12 = 0, otherwise x12 is 10 - m - return (10 - checkDigit) % 10; -} - -static void render_callback(Canvas* const canvas, void* ctx) { - furi_assert(ctx); - PluginState* plugin_state = ctx; - furi_mutex_acquire(plugin_state->mutex, FuriWaitForever); - - if(plugin_state->mode == MenuMode) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_str_aligned(canvas, 64, 6, AlignCenter, AlignCenter, "MENU"); - canvas_draw_frame(canvas, 50, 0, 29, 11); //box around Menu - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(0), AlignCenter, AlignCenter, "View"); - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(1), AlignCenter, AlignCenter, "Edit"); - canvas_draw_str_aligned( - canvas, 64, get_menu_text_location(2), AlignCenter, AlignCenter, "Parity?"); - - canvas_draw_frame(canvas, 83, get_menu_text_location(2) - 3, 6, 6); - if(plugin_state->barcode_state.doParityCalculation == true) { - canvas_draw_box(canvas, 85, get_menu_text_location(2) - 1, 2, 2); - } - canvas_draw_str_aligned( - canvas, - 64, - get_menu_text_location(3), - AlignCenter, - AlignCenter, - (barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex])->name); - canvas_draw_disc( - canvas, - 40, - get_menu_text_location(plugin_state->menuIndex) - 1, - 2); //draw menu cursor - } else { - BarcodeType* type = barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]; - - //start saftey - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, type->startPos - 3, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, (type->startPos - 1), BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - - int startpos = 0; - int endpos = type->numberOfDigits; - if(type->bartype == BarTypeEAN13) { - startpos++; - draw_digit( - canvas, - plugin_state->barcode_state.barcodeNumeral[0], - BarEncodingTypeRight, - get_digit_position(0, barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]), - false); - } - if(plugin_state->barcode_state.doParityCalculation) { //calculate the check digit - plugin_state->barcode_state.barcodeNumeral[type->numberOfDigits - 1] = - calculate_check_digit(plugin_state, type); - } - for(int index = startpos; index < endpos; index++) { - BarEncodingType barEncodingType = BarEncodingTypeLeft; - if(type->bartype == BarTypeEAN13) { - if(index - 1 >= (type->numberOfDigits - 1) / 2) { - barEncodingType = BarEncodingTypeRight; - } else { - barEncodingType = - (FURI_BIT( - EAN13ENCODE[plugin_state->barcode_state.barcodeNumeral[0]], - index - 1)) ? - BarEncodingTypeG : - BarEncodingTypeLeft; - } - } else { - if(index >= type->numberOfDigits / 2) { - barEncodingType = BarEncodingTypeRight; - } - } - - int digitPosition = get_digit_position( - index, barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]); - draw_digit( - canvas, - plugin_state->barcode_state.barcodeNumeral[index], - barEncodingType, - digitPosition, - true); - } - - //central separator - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, 62, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, 64, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - - if(plugin_state->mode == EditMode) { - canvas_set_color(canvas, ColorBlack); - canvas_draw_box( - canvas, - get_digit_position( - plugin_state->editingIndex, - barcodeTypes[plugin_state->barcode_state.barcodeTypeIndex]) - - 1, - 63, - 7, - 1); //draw editing cursor - } - - //end safety - int endSafetyPosition = get_digit_position(type->numberOfDigits - 1, type) + 7; - canvas_set_color(canvas, ColorBlack); - canvas_draw_box(canvas, endSafetyPosition, BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - canvas_draw_box(canvas, (endSafetyPosition + 2), BARCODE_Y_START, 1, BARCODE_HEIGHT + 2); - } - - furi_mutex_release(plugin_state->mutex); -} - -static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { - furi_assert(event_queue); - - PluginEvent event = {.type = EventTypeKey, .input = *input_event}; - furi_message_queue_put(event_queue, &event, FuriWaitForever); -} - -static void barcode_generator_state_init(PluginState* plugin_state) { - plugin_state->editingIndex = 0; - plugin_state->mode = ViewMode; - plugin_state->menuIndex = MENU_INDEX_VIEW; - if(!LOAD_BARCODE_SETTINGS(&plugin_state->barcode_state)) { - for(int i = 0; i < BARCODE_MAX_LENS; ++i) { - plugin_state->barcode_state.barcodeNumeral[i] = i % 10; - } - plugin_state->barcode_state.doParityCalculation = true; - plugin_state->barcode_state.barcodeTypeIndex = 0; - } -} - -static bool handle_key_press_view(InputKey key, PluginState* plugin_state) { - switch(key) { - case InputKeyOk: - case InputKeyBack: - plugin_state->mode = MenuMode; - break; - - default: - break; - } - - return true; -} - -static bool handle_key_press_edit(InputKey key, PluginState* plugin_state) { - int barcodeMaxIndex = get_barcode_max_index(plugin_state); - - switch(key) { - case InputKeyUp: - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] = - (plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] + 1) % 10; - break; - - case InputKeyDown: - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] = - (plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] == 0) ? - 9 : - plugin_state->barcode_state.barcodeNumeral[plugin_state->editingIndex] - 1; - break; - - case InputKeyRight: - plugin_state->editingIndex = (plugin_state->editingIndex + 1) % barcodeMaxIndex; - break; - - case InputKeyLeft: - plugin_state->editingIndex = (plugin_state->editingIndex == 0) ? - barcodeMaxIndex - 1 : - plugin_state->editingIndex - 1; - break; - - case InputKeyOk: - case InputKeyBack: - plugin_state->mode = MenuMode; - break; - - default: - break; - } - - return true; -} - -static bool handle_key_press_menu(InputKey key, PluginState* plugin_state) { - switch(key) { - case InputKeyUp: - plugin_state->menuIndex = (plugin_state->menuIndex == MENU_INDEX_VIEW) ? - MENU_INDEX_TYPE : - plugin_state->menuIndex - 1; - break; - - case InputKeyDown: - plugin_state->menuIndex = (plugin_state->menuIndex + 1) % 4; - break; - - case InputKeyRight: - if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == NUMBER_OF_BARCODE_TYPES - 1) ? - 0 : - plugin_state->barcode_state.barcodeTypeIndex + 1; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } - break; - case InputKeyLeft: - if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == 0) ? - NUMBER_OF_BARCODE_TYPES - 1 : - plugin_state->barcode_state.barcodeTypeIndex - 1; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } - break; - - case InputKeyOk: - if(plugin_state->menuIndex == MENU_INDEX_VIEW) { - plugin_state->mode = ViewMode; - } else if(plugin_state->menuIndex == MENU_INDEX_EDIT) { - plugin_state->mode = EditMode; - } else if(plugin_state->menuIndex == MENU_INDEX_PARITY) { - plugin_state->barcode_state.doParityCalculation = - !plugin_state->barcode_state.doParityCalculation; - } else if(plugin_state->menuIndex == MENU_INDEX_TYPE) { - plugin_state->barcode_state.barcodeTypeIndex = - (plugin_state->barcode_state.barcodeTypeIndex == NUMBER_OF_BARCODE_TYPES - 1) ? - 0 : - plugin_state->barcode_state.barcodeTypeIndex + 1; - } - break; - - case InputKeyBack: - return false; - - default: - break; - } - int barcodeMaxIndex = get_barcode_max_index(plugin_state); - if(plugin_state->editingIndex >= barcodeMaxIndex) - plugin_state->editingIndex = barcodeMaxIndex - 1; - - return true; -} - -int32_t barcode_generator_app(void* p) { - UNUSED(p); - - init_types(); - - FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent)); - - PluginState* plugin_state = malloc(sizeof(PluginState)); - barcode_generator_state_init(plugin_state); - - plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); - if(!plugin_state->mutex) { - FURI_LOG_E("barcode_generator", "cannot create mutex\r\n"); - furi_message_queue_free(event_queue); - free(plugin_state); - return 255; - } - - // Set system callbacks - ViewPort* view_port = view_port_alloc(); - view_port_draw_callback_set(view_port, render_callback, plugin_state); - view_port_input_callback_set(view_port, input_callback, event_queue); - - // Open GUI and register view_port - Gui* gui = furi_record_open(RECORD_GUI); - gui_add_view_port(gui, view_port, GuiLayerFullscreen); - - PluginEvent event; - for(bool processing = true; processing;) { - FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); - furi_mutex_acquire(plugin_state->mutex, FuriWaitForever); - - if(event_status == FuriStatusOk) { - // press events - if(event.type == EventTypeKey && - ((event.input.type == InputTypePress) || (event.input.type == InputTypeRepeat))) { - switch(plugin_state->mode) { - case ViewMode: - processing = handle_key_press_view(event.input.key, plugin_state); - break; - case EditMode: - processing = handle_key_press_edit(event.input.key, plugin_state); - break; - case MenuMode: - processing = handle_key_press_menu(event.input.key, plugin_state); - break; - default: - break; - } - } - } - - view_port_update(view_port); - furi_mutex_release(plugin_state->mutex); - } - - view_port_enabled_set(view_port, false); - gui_remove_view_port(gui, view_port); - furi_record_close(RECORD_GUI); - view_port_free(view_port); - furi_message_queue_free(event_queue); - furi_mutex_free(plugin_state->mutex); - // save settings - SAVE_BARCODE_SETTINGS(&plugin_state->barcode_state); - free(plugin_state); - - return 0; -} diff --git a/applications/external/barcode_generator/barcode_generator.h b/applications/external/barcode_generator/barcode_generator.h deleted file mode 100644 index 5d2c8307e..000000000 --- a/applications/external/barcode_generator/barcode_generator.h +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#define BARCODE_SETTINGS_FILE_NAME "apps/Misc/barcodegen.save" - -#define BARCODE_SETTINGS_VER (1) -#define BARCODE_SETTINGS_PATH EXT_PATH(BARCODE_SETTINGS_FILE_NAME) -#define BARCODE_SETTINGS_MAGIC (0xC2) - -#define SAVE_BARCODE_SETTINGS(x) \ - saved_struct_save( \ - BARCODE_SETTINGS_PATH, \ - (x), \ - sizeof(BarcodeState), \ - BARCODE_SETTINGS_MAGIC, \ - BARCODE_SETTINGS_VER) - -#define LOAD_BARCODE_SETTINGS(x) \ - saved_struct_load( \ - BARCODE_SETTINGS_PATH, \ - (x), \ - sizeof(BarcodeState), \ - BARCODE_SETTINGS_MAGIC, \ - BARCODE_SETTINGS_VER) - -#define BARCODE_HEIGHT 50 -#define BARCODE_Y_START 3 -#define BARCODE_TEXT_OFFSET 9 -#define BARCODE_MAX_LENS 13 -#define NUMBER_OF_BARCODE_TYPES 3 -#define MENU_INDEX_VIEW 0 -#define MENU_INDEX_EDIT 1 -#define MENU_INDEX_PARITY 2 -#define MENU_INDEX_TYPE 3 - -typedef enum { - EventTypeTick, - EventTypeKey, -} EventType; - -typedef struct { - EventType type; - InputEvent input; -} PluginEvent; - -typedef enum { - ViewMode, - EditMode, - MenuMode, -} Mode; - -typedef enum { - BarEncodingTypeLeft, - BarEncodingTypeRight, - BarEncodingTypeG, -} BarEncodingType; - -typedef enum { - BarTypeEAN8, - BarTypeUPCA, - BarTypeEAN13, -} BarType; - -typedef struct { - char* name; - int numberOfDigits; - int startPos; - BarType bartype; -} BarcodeType; - -typedef struct { - int barcodeNumeral[BARCODE_MAX_LENS]; //The current barcode number - bool doParityCalculation; //Should do parity check? - int barcodeTypeIndex; -} BarcodeState; - -typedef struct { - FuriMutex* mutex; - BarcodeState barcode_state; - int editingIndex; //The index of the editing symbol - int menuIndex; //The index of the menu cursor - Mode mode; //View, edit or menu -} PluginState; - -static const int DIGITS[10][4] = { - {3, 2, 1, 1}, - {2, 2, 2, 1}, - {2, 1, 2, 2}, - {1, 4, 1, 1}, - {1, 1, 3, 2}, - {1, 2, 3, 1}, - {1, 1, 1, 4}, - {1, 3, 1, 2}, - {1, 2, 1, 3}, - {3, 1, 1, 2}, -}; - -static const uint8_t EAN13ENCODE[10] = { - 0b000000, - 0b110100, - 0b101100, - 0b011100, - 0b110010, - 0b100110, - 0b001110, - 0b101010, - 0b011010, - 0b010110, -}; \ No newline at end of file diff --git a/applications/external/bomberduck/bomberduck.c b/applications/external/bomberduck/bomberduck.c index 79471c99e..3e9d52f56 100644 --- a/applications/external/bomberduck/bomberduck.c +++ b/applications/external/bomberduck/bomberduck.c @@ -5,7 +5,6 @@ #include #include #include -#include #include "bomberduck_icons.h" #include diff --git a/applications/external/flappy_bird/assets/bird/frame_01.png b/applications/external/flappy_bird/assets/bird_01.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_01.png rename to applications/external/flappy_bird/assets/bird_01.png diff --git a/applications/external/flappy_bird/assets/bird/frame_02.png b/applications/external/flappy_bird/assets/bird_02.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_02.png rename to applications/external/flappy_bird/assets/bird_02.png diff --git a/applications/external/flappy_bird/assets/bird/frame_03.png b/applications/external/flappy_bird/assets/bird_03.png similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_03.png rename to applications/external/flappy_bird/assets/bird_03.png diff --git a/applications/external/flappy_bird/flappy_bird.c b/applications/external/flappy_bird/flappy_bird.c index 2a50868f2..2052488bf 100644 --- a/applications/external/flappy_bird/flappy_bird.c +++ b/applications/external/flappy_bird/flappy_bird.c @@ -3,7 +3,6 @@ #include #include #include -#include #include #include @@ -30,6 +29,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; @@ -38,7 +45,6 @@ typedef struct { typedef struct { float gravity; POINT point; - IconAnimation* sprite; } BIRD; typedef struct { @@ -93,7 +99,6 @@ static void flappy_game_state_init(GameState* const game_state) { bird.gravity = 0.0f; bird.point.x = 15; bird.point.y = 32; - bird.sprite = icon_animation_alloc(&A_bird); game_state->debug = DEBUG; game_state->bird = bird; @@ -106,7 +111,6 @@ static void flappy_game_state_init(GameState* const game_state) { } static void flappy_game_state_free(GameState* const game_state) { - icon_animation_free(game_state->bird.sprite); free(game_state); } @@ -224,14 +228,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 f91bcceba..c576c71b0 100644 --- a/applications/external/flipper_i2ctools/application.fam +++ b/applications/external/flipper_i2ctools/application.fam @@ -1,5 +1,5 @@ App( - appid="i2c_tools", + appid="i2ctools", name="[GPIO] i2c Tools", apptype=FlipperAppType.EXTERNAL, entry_point="i2ctools_app", @@ -10,6 +10,6 @@ App( fap_category="GPIO", fap_icon_assets="images", fap_author="@NaejEL", - fap_version="1.0", + fap_version="1.1", fap_description="Set of i2c tools", ) \ No newline at end of file diff --git a/applications/external/flipper_i2ctools/i2ctools.c b/applications/external/flipper_i2ctools/i2ctools.c index 6d4cc739f..7be6e5961 100644 --- a/applications/external/flipper_i2ctools/i2ctools.c +++ b/applications/external/flipper_i2ctools/i2ctools.c @@ -22,6 +22,10 @@ void i2ctools_draw_callback(Canvas* canvas, void* ctx) { draw_sender_view(canvas, i2ctools->sender); break; + case INFOS_VIEW: + draw_infos_view(canvas); + break; + default: break; } diff --git a/applications/external/flipper_i2ctools/i2ctools_i.h b/applications/external/flipper_i2ctools/i2ctools_i.h index f31e42478..2e32d3fd4 100644 --- a/applications/external/flipper_i2ctools/i2ctools_i.h +++ b/applications/external/flipper_i2ctools/i2ctools_i.h @@ -10,6 +10,7 @@ #include "views/sniffer_view.h" #include "views/scanner_view.h" #include "views/sender_view.h" +#include "views/infos_view.h" // App datas typedef struct { diff --git a/applications/external/flipper_i2ctools/images/Voltage_16x16.png b/applications/external/flipper_i2ctools/images/Voltage_16x16.png new file mode 100644 index 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 f0ce5e8ad..118a8f5f9 100644 --- a/applications/external/flipper_i2ctools/views/main_view.h +++ b/applications/external/flipper_i2ctools/views/main_view.h @@ -1,20 +1,24 @@ #include #include #include -#include +#include #define APP_NAME "I2C Tools" #define SCAN_MENU_TEXT "Scan" #define SCAN_MENU_X 90 -#define SCAN_MENU_Y 13 +#define SCAN_MENU_Y 7 #define SNIFF_MENU_TEXT "Sniff" #define SNIFF_MENU_X 90 -#define SNIFF_MENU_Y 27 +#define SNIFF_MENU_Y 21 #define SEND_MENU_TEXT "Send" #define SEND_MENU_X 90 -#define SEND_MENU_Y 41 +#define SEND_MENU_Y 35 + +#define INFOS_MENU_TEXT "Infos" +#define INFOS_MENU_X 90 +#define INFOS_MENU_Y 49 // Menu typedef enum { @@ -22,6 +26,7 @@ typedef enum { SCAN_VIEW, SNIFF_VIEW, SEND_VIEW, + INFOS_VIEW, /* Know menu Size*/ MENU_SIZE diff --git a/applications/external/flipper_i2ctools/views/scanner_view.h b/applications/external/flipper_i2ctools/views/scanner_view.h index 52f30a7bf..4c59f8836 100644 --- a/applications/external/flipper_i2ctools/views/scanner_view.h +++ b/applications/external/flipper_i2ctools/views/scanner_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2cscanner.h" #define SCAN_TEXT "SCAN" diff --git a/applications/external/flipper_i2ctools/views/sender_view.h b/applications/external/flipper_i2ctools/views/sender_view.h index c4fdd98a2..c5192d0b6 100644 --- a/applications/external/flipper_i2ctools/views/sender_view.h +++ b/applications/external/flipper_i2ctools/views/sender_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2csender.h" #define SEND_TEXT "SEND" diff --git a/applications/external/flipper_i2ctools/views/sniffer_view.h b/applications/external/flipper_i2ctools/views/sniffer_view.h index 8f2140bba..db4dbd1ff 100644 --- a/applications/external/flipper_i2ctools/views/sniffer_view.h +++ b/applications/external/flipper_i2ctools/views/sniffer_view.h @@ -1,7 +1,7 @@ #include #include #include -#include +#include #include "../i2csniffer.h" #define SNIFF_TEXT "SNIFF" diff --git a/applications/external/heap_defence_game/heap_defence.c b/applications/external/heap_defence_game/heap_defence.c index 3c8483c75..111c22dce 100644 --- a/applications/external/heap_defence_game/heap_defence.c +++ b/applications/external/heap_defence_game/heap_defence.c @@ -14,7 +14,6 @@ #include #include #include -#include #include #define Y_FIELD_SIZE 6 diff --git a/applications/external/hex_viewer/application.fam b/applications/external/hex_viewer/application.fam index 03967ffa5..5d6d3959d 100644 --- a/applications/external/hex_viewer/application.fam +++ b/applications/external/hex_viewer/application.fam @@ -10,7 +10,7 @@ App( stack_size=2 * 1024, order=20, fap_icon="icons/hex_10px.png", - fap_category="Misc", + fap_category="Tools", fap_icon_assets="icons", fap_author="@QtRoS", fap_version="1.0", diff --git a/applications/external/hid_app/application.fam b/applications/external/hid_app/application.fam index e96e956d8..c27ad9c81 100644 --- a/applications/external/hid_app/application.fam +++ b/applications/external/hid_app/application.fam @@ -4,7 +4,7 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="hid_usb_app", stack_size=1 * 1024, - fap_category="Misc", + fap_category="USB", fap_icon="hid_usb_10px.png", fap_icon_assets="assets", fap_icon_assets_symbol="hid", @@ -17,7 +17,7 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="hid_ble_app", stack_size=1 * 1024, - fap_category="Misc", + fap_category="Bluetooth", fap_icon="hid_ble_10px.png", fap_icon_assets="assets", fap_icon_assets_symbol="hid", diff --git a/applications/external/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/jetpack_joyride/application.fam b/applications/external/jetpack_joyride/application.fam new file mode 100644 index 000000000..1b98e11ce --- /dev/null +++ b/applications/external/jetpack_joyride/application.fam @@ -0,0 +1,15 @@ +# For details & more options, see documentation/AppManifests.md in firmware repo + +App( + appid="jetpack_joyride", + name="Jetpack Joyride", + apptype=FlipperAppType.EXTERNAL, + entry_point="jetpack_game_app", + cdefines=["APP_JETPACK_GAME"], + requires=["gui"], + stack_size=4 * 1024, + order=100, + fap_icon="icon.png", + fap_category="Games", + fap_icon_assets="assets", +) diff --git a/applications/external/jetpack_joyride/assets/air_vent.png b/applications/external/jetpack_joyride/assets/air_vent.png new file mode 100644 index 000000000..a7fcf0b20 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/air_vent.png differ diff --git a/applications/external/jetpack_joyride/assets/alert/frame_01.png b/applications/external/jetpack_joyride/assets/alert/frame_01.png new file mode 100644 index 000000000..ac4cca1b1 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/alert/frame_01.png differ diff --git a/applications/external/jetpack_joyride/assets/alert/frame_02.png b/applications/external/jetpack_joyride/assets/alert/frame_02.png new file mode 100644 index 000000000..c3955f090 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/alert/frame_02.png differ diff --git a/applications/external/flappy_bird/assets/bird/frame_rate b/applications/external/jetpack_joyride/assets/alert/frame_rate similarity index 100% rename from applications/external/flappy_bird/assets/bird/frame_rate rename to applications/external/jetpack_joyride/assets/alert/frame_rate diff --git a/applications/external/jetpack_joyride/assets/barry/frame_01.png b/applications/external/jetpack_joyride/assets/barry/frame_01.png new file mode 100644 index 000000000..8abdcaf61 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/barry/frame_01.png differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_02.png b/applications/external/jetpack_joyride/assets/barry/frame_02.png new file mode 100644 index 000000000..5a4587ac8 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/barry/frame_02.png differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_03.png b/applications/external/jetpack_joyride/assets/barry/frame_03.png new file mode 100644 index 000000000..d188aed3c Binary files /dev/null and b/applications/external/jetpack_joyride/assets/barry/frame_03.png differ diff --git a/applications/external/jetpack_joyride/assets/barry/frame_rate b/applications/external/jetpack_joyride/assets/barry/frame_rate new file mode 100644 index 000000000..e440e5c84 --- /dev/null +++ b/applications/external/jetpack_joyride/assets/barry/frame_rate @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/applications/external/jetpack_joyride/assets/barry_infill.png b/applications/external/jetpack_joyride/assets/barry_infill.png new file mode 100644 index 000000000..9462801f0 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/barry_infill.png differ diff --git a/applications/external/jetpack_joyride/assets/bg1.png b/applications/external/jetpack_joyride/assets/bg1.png new file mode 100644 index 000000000..82d614e1c Binary files /dev/null and b/applications/external/jetpack_joyride/assets/bg1.png differ diff --git a/applications/external/jetpack_joyride/assets/bg2.png b/applications/external/jetpack_joyride/assets/bg2.png new file mode 100644 index 000000000..ec8590d3a Binary files /dev/null and b/applications/external/jetpack_joyride/assets/bg2.png differ diff --git a/applications/external/jetpack_joyride/assets/bg3.png b/applications/external/jetpack_joyride/assets/bg3.png new file mode 100644 index 000000000..ebb1dd66b Binary files /dev/null and b/applications/external/jetpack_joyride/assets/bg3.png differ diff --git a/applications/external/jetpack_joyride/assets/coin.png b/applications/external/jetpack_joyride/assets/coin.png new file mode 100644 index 000000000..a2b5a409e Binary files /dev/null and b/applications/external/jetpack_joyride/assets/coin.png differ diff --git a/applications/external/jetpack_joyride/assets/coin_infill.png b/applications/external/jetpack_joyride/assets/coin_infill.png new file mode 100644 index 000000000..ab37874ff Binary files /dev/null and b/applications/external/jetpack_joyride/assets/coin_infill.png differ diff --git a/applications/external/jetpack_joyride/assets/dead_scientist.png b/applications/external/jetpack_joyride/assets/dead_scientist.png new file mode 100644 index 000000000..cd7a9993a Binary files /dev/null and b/applications/external/jetpack_joyride/assets/dead_scientist.png differ diff --git a/applications/external/jetpack_joyride/assets/dead_scientist_infill.png b/applications/external/jetpack_joyride/assets/dead_scientist_infill.png new file mode 100644 index 000000000..6f036fde2 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/dead_scientist_infill.png differ diff --git a/applications/external/jetpack_joyride/assets/door.png b/applications/external/jetpack_joyride/assets/door.png new file mode 100644 index 000000000..1ef861054 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/door.png differ diff --git a/applications/external/jetpack_joyride/assets/missile/frame_01.png b/applications/external/jetpack_joyride/assets/missile/frame_01.png new file mode 100644 index 000000000..f0b62ed03 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/missile/frame_01.png differ diff --git a/applications/external/jetpack_joyride/assets/missile/frame_rate b/applications/external/jetpack_joyride/assets/missile/frame_rate new file mode 100644 index 000000000..e440e5c84 --- /dev/null +++ b/applications/external/jetpack_joyride/assets/missile/frame_rate @@ -0,0 +1 @@ +3 \ No newline at end of file diff --git a/applications/external/jetpack_joyride/assets/missile_infill.png b/applications/external/jetpack_joyride/assets/missile_infill.png new file mode 100644 index 000000000..d15f5a88e Binary files /dev/null and b/applications/external/jetpack_joyride/assets/missile_infill.png differ diff --git a/applications/external/jetpack_joyride/assets/pillar.png b/applications/external/jetpack_joyride/assets/pillar.png new file mode 100644 index 000000000..61979b393 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/pillar.png differ diff --git a/applications/external/jetpack_joyride/assets/scientist_left.png b/applications/external/jetpack_joyride/assets/scientist_left.png new file mode 100644 index 000000000..a9e880b6b Binary files /dev/null and b/applications/external/jetpack_joyride/assets/scientist_left.png differ diff --git a/applications/external/jetpack_joyride/assets/scientist_left_infill.png b/applications/external/jetpack_joyride/assets/scientist_left_infill.png new file mode 100644 index 000000000..4639cb957 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/scientist_left_infill.png differ diff --git a/applications/external/jetpack_joyride/assets/scientist_right.png b/applications/external/jetpack_joyride/assets/scientist_right.png new file mode 100644 index 000000000..dc40b560d Binary files /dev/null and b/applications/external/jetpack_joyride/assets/scientist_right.png differ diff --git a/applications/external/jetpack_joyride/assets/scientist_right_infill.png b/applications/external/jetpack_joyride/assets/scientist_right_infill.png new file mode 100644 index 000000000..e4bc7def8 Binary files /dev/null and b/applications/external/jetpack_joyride/assets/scientist_right_infill.png differ diff --git a/applications/external/jetpack_joyride/icon.png b/applications/external/jetpack_joyride/icon.png new file mode 100644 index 000000000..0d2d6cf42 Binary files /dev/null and b/applications/external/jetpack_joyride/icon.png differ diff --git a/applications/external/jetpack_joyride/includes/background_asset.c b/applications/external/jetpack_joyride/includes/background_asset.c new file mode 100644 index 000000000..0a5ecdda9 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/background_asset.c @@ -0,0 +1,81 @@ +#include + +#include "background_assets.h" + +static AssetProperties assetProperties[BG_ASSETS_MAX] = { + {.width = 27, .spawn_chance = 1, .x_offset = 24, .y_offset = 36, .sprite = &I_door}, + {.width = 12, .spawn_chance = 6, .x_offset = 33, .y_offset = 14, .sprite = &I_air_vent}}; + +void background_assets_tick(BackgroundAsset* const assets) { + // Move assets towards the player + for(int i = 0; i < BG_ASSETS_MAX; i++) { + if(assets[i].visible) { + assets[i].point.x -= 1; // move left by 2 units + if(assets[i].point.x <= + -assets[i].properties->width) { // if the asset is out of screen + assets[i].visible = false; // set asset x coordinate to 0 to mark it as "inactive" + } + } + } +} + +void spawn_random_background_asset(BackgroundAsset* const assets) { + // Calculate the total spawn chances for all assets + int total_spawn_chance = 0; + for(int i = 0; i < BG_ASSETS_MAX; ++i) { + total_spawn_chance += assetProperties[i].spawn_chance; + } + + // Generate a random number between 0 and total_spawn_chance + int random_number = rand() % total_spawn_chance; + + // Select the asset based on the random number + int chosen_asset = -1; + int accumulated_chance = 0; + for(int i = 0; i < BG_ASSETS_MAX; ++i) { + accumulated_chance += assetProperties[i].spawn_chance; + if(random_number < accumulated_chance) { + chosen_asset = i; + break; + } + } + + // If no asset is chosen, return + if(chosen_asset == -1) { + return; + } + + // Look for an available slot for the chosen asset + for(int i = 0; i < BG_ASSETS_MAX; ++i) { + if(assets[i].visible == false) { + // Spawn the asset + assets[i].point.x = 127 + assetProperties[chosen_asset].x_offset; + assets[i].point.y = assetProperties[chosen_asset].y_offset; + assets[i].properties = &assetProperties[chosen_asset]; + assets[i].visible = true; + break; + } + } +} + +void draw_background_assets(const BackgroundAsset* assets, Canvas* const canvas, int distance) { + canvas_draw_box(canvas, 0, 6, 128, 1); + canvas_draw_box(canvas, 0, 56, 128, 2); + + // Calculate the pillar offset based on the traveled distance + int pillar_offset = distance % 64; + + // Draw pillars + for(int x = -pillar_offset; x < 128; x += 64) { + canvas_draw_icon(canvas, x, 6, &I_pillar); + } + + // Draw assets + for(int i = 0; i < BG_ASSETS_MAX; ++i) { + if(assets[i].visible) { + canvas_set_color(canvas, ColorBlack); + canvas_draw_icon( + canvas, assets[i].point.x, assets[i].point.y, assets[i].properties->sprite); + } + } +} diff --git a/applications/external/jetpack_joyride/includes/background_assets.h b/applications/external/jetpack_joyride/includes/background_assets.h new file mode 100644 index 000000000..d42fcfd71 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/background_assets.h @@ -0,0 +1,34 @@ +#ifndef BACKGROUND_ASSETS_H +#define BACKGROUND_ASSETS_H + +#include +#include + +#include + +#include "point.h" +#include "states.h" +#include "game_sprites.h" +#include + +#define BG_ASSETS_MAX 3 + +typedef struct { + int width; + int spawn_chance; + int x_offset; + int y_offset; + const Icon* sprite; +} AssetProperties; + +typedef struct { + POINT point; + AssetProperties* properties; + bool visible; +} BackgroundAsset; + +void background_assets_tick(BackgroundAsset* const assets); +void spawn_random_background_asset(BackgroundAsset* const assets); +void draw_background_assets(const BackgroundAsset* assets, Canvas* const canvas, int distance); + +#endif // BACKGROUND_ASSETS_H diff --git a/applications/external/jetpack_joyride/includes/barry.c b/applications/external/jetpack_joyride/includes/barry.c new file mode 100644 index 000000000..61d3a6fc4 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/barry.c @@ -0,0 +1,33 @@ +#include "barry.h" +#include "game_sprites.h" + +#include +#include + +void barry_tick(BARRY* const barry) { + // Do jetpack things + if(barry->isBoosting) { + barry->gravity += GRAVITY_BOOST; // Increase upward momentum + } else { + barry->gravity += GRAVITY_FALL; // Increase downward momentum faster + } + + barry->point.y += barry->gravity; + + // Constrain barry's height within sprite_height and 64 - sprite_height + if(barry->point.y > (64 - BARRY_HEIGHT)) { + barry->point.y = 64 - BARRY_HEIGHT; + barry->gravity = 0; // stop upward momentum + } else if(barry->point.y < 0) { + barry->point.y = 0; + barry->gravity = 0; // stop downward momentum + } +} + +void draw_barry(const BARRY* barry, Canvas* const canvas, const GameSprites* sprites) { + canvas_set_color(canvas, ColorBlack); + canvas_draw_icon_animation(canvas, barry->point.x, barry->point.y, sprites->barry); + + canvas_set_color(canvas, ColorWhite); + canvas_draw_icon(canvas, barry->point.x, barry->point.y, sprites->barry_infill); +} \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/barry.h b/applications/external/jetpack_joyride/includes/barry.h new file mode 100644 index 000000000..494af434d --- /dev/null +++ b/applications/external/jetpack_joyride/includes/barry.h @@ -0,0 +1,23 @@ +#ifndef BARRY_H +#define BARRY_H + +#include + +#include +#include "point.h" +#include "game_sprites.h" + +#define GRAVITY_TICK 0.2 +#define GRAVITY_BOOST -0.4 +#define GRAVITY_FALL 0.3 + +typedef struct { + float gravity; + POINT point; + bool isBoosting; +} BARRY; + +void barry_tick(BARRY* const barry); +void draw_barry(const BARRY* barry, Canvas* const canvas, const GameSprites* sprites); + +#endif // BARRY_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/coin.c b/applications/external/jetpack_joyride/includes/coin.c new file mode 100644 index 000000000..7a3811a8c --- /dev/null +++ b/applications/external/jetpack_joyride/includes/coin.c @@ -0,0 +1,98 @@ +#include +#include + +#include +#include + +#include "coin.h" +#include "barry.h" + +#define PATTERN_MAX_HEIGHT 40 + +// Patterns +const COIN_PATTERN coin_patterns[] = { + {// Square pattern + .count = 9, + .coins = {{0, 0}, {8, 0}, {16, 0}, {0, 8}, {8, 8}, {16, 8}, {0, 16}, {8, 16}, {16, 16}}}, + {// Wavy pattern (approximate sine wave) + .count = 8, + .coins = {{0, 8}, {8, 16}, {16, 24}, {24, 16}, {32, 8}, {40, 0}, {48, 8}, {56, 16}}}, + {// Diagonal pattern + .count = 5, + .coins = {{0, 0}, {8, 8}, {16, 16}, {24, 24}, {32, 32}}}, + // Add more patterns here +}; + +void coin_tick(COIN* const coins, BARRY* const barry, int* const total_coins) { + // Move coins towards the player + for(int i = 0; i < COINS_MAX; i++) { + if(coin_colides(&coins[i], barry)) { + coins[i].point.x = 0; // Remove the coin + (*total_coins)++; + } + if(coins[i].point.x > 0) { + coins[i].point.x -= 1; // move left by 1 unit + if(coins[i].point.x < -COIN_WIDTH) { // if the coin is out of screen + coins[i].point.x = 0; // set coin x coordinate to 0 to mark it as "inactive" + } + } + } +} + +bool coin_colides(COIN* const coin, BARRY* const barry) { + return !( + barry->point.x > coin->point.x + COIN_WIDTH || // Barry is to the right of the coin + barry->point.x + BARRY_WIDTH < coin->point.x || // Barry is to the left of the coin + barry->point.y > coin->point.y + COIN_WIDTH || // Barry is below the coin + barry->point.y + BARRY_HEIGHT < coin->point.y); // Barry is above the coin +} + +void spawn_random_coin(COIN* const coins) { + // Select a random pattern + int pattern_index = rand() % (sizeof(coin_patterns) / sizeof(coin_patterns[0])); + const COIN_PATTERN* pattern = &coin_patterns[pattern_index]; + + // Count available slots for new coins + int available_slots = 0; + for(int i = 0; i < COINS_MAX; ++i) { + if(coins[i].point.x <= 0) { + ++available_slots; + } + } + + // If there aren't enough slots, return without spawning coins + if(available_slots < pattern->count) return; + + // Spawn coins according to the selected pattern + int coin_index = 0; + int random_offset = rand() % (SCREEN_HEIGHT - PATTERN_MAX_HEIGHT); + int random_offset_x = rand() % 16; + for(int i = 0; i < pattern->count; ++i) { + // Find an available slot for a new coin + while(coins[coin_index].point.x > 0 && coin_index < COINS_MAX) { + ++coin_index; + } + // If no slot is available, stop spawning coins + if(coin_index == COINS_MAX) break; + + // Spawn the coin + coins[coin_index].point.x = SCREEN_WIDTH - 1 + pattern->coins[i].x + random_offset_x; + coins[coin_index].point.y = + random_offset + + pattern->coins[i] + .y; // The pattern is spawned at a random y position, but not too close to the screen edge + } +} + +void draw_coins(const COIN* coins, Canvas* const canvas, const GameSprites* sprites) { + canvas_set_color(canvas, ColorBlack); + for(int i = 0; i < COINS_MAX; ++i) { + if(coins[i].point.x > 0) { + canvas_set_color(canvas, ColorBlack); + canvas_draw_icon(canvas, coins[i].point.x, coins[i].point.y, sprites->coin); + + canvas_set_color(canvas, ColorWhite); + canvas_draw_icon(canvas, coins[i].point.x, coins[i].point.y, sprites->coin_infill); + } + } +} diff --git a/applications/external/jetpack_joyride/includes/coin.h b/applications/external/jetpack_joyride/includes/coin.h new file mode 100644 index 000000000..41fd21ddc --- /dev/null +++ b/applications/external/jetpack_joyride/includes/coin.h @@ -0,0 +1,26 @@ +#ifndef COIN_H +#define COIN_H + +#include + +#include "point.h" +#include "barry.h" + +#define COINS_MAX 15 + +typedef struct { + float gravity; + POINT point; +} COIN; + +typedef struct { + int count; + POINT coins[COINS_MAX]; +} COIN_PATTERN; + +void coin_tick(COIN* const coins, BARRY* const barry, int* const poins); +void spawn_random_coin(COIN* const coins); +bool coin_colides(COIN* const coin, BARRY* const barry); +void draw_coins(const COIN* coins, Canvas* const canvas, const GameSprites* sprites); + +#endif // COIN_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/game_sprites.h b/applications/external/jetpack_joyride/includes/game_sprites.h new file mode 100644 index 000000000..d38494bf8 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_sprites.h @@ -0,0 +1,35 @@ +#ifndef GAME_SPRITES_H +#define GAME_SPRITES_H + +#include "point.h" +#include + +#define SCREEN_WIDTH 128 +#define SCREEN_HEIGHT 64 + +#define BARRY_WIDTH 11 +#define BARRY_HEIGHT 15 + +#define MISSILE_WIDTH 26 +#define MISSILE_HEIGHT 12 + +#define SCIENTIST_WIDTH 9 +#define SCIENTIST_HEIGHT 14 + +#define COIN_WIDTH 7 + +typedef struct { + IconAnimation* barry; + const Icon* barry_infill; + const Icon* scientist_left; + const Icon* scientist_left_infill; + const Icon* scientist_right; + const Icon* scientist_right_infill; + const Icon* coin; + const Icon* coin_infill; + IconAnimation* missile; + IconAnimation* alert; + const Icon* missile_infill; +} GameSprites; + +#endif // GAME_SPRITES_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/game_state.c b/applications/external/jetpack_joyride/includes/game_state.c new file mode 100644 index 000000000..a8a9db618 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_state.c @@ -0,0 +1,5 @@ +#include "game_state.h" + +void game_state_tick(GameState* const game_state) { + game_state->distance++; +} diff --git a/applications/external/jetpack_joyride/includes/game_state.h b/applications/external/jetpack_joyride/includes/game_state.h new file mode 100644 index 000000000..1e97aaf18 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/game_state.h @@ -0,0 +1,34 @@ +#ifndef GAMESTATE_H +#define GAMESTATE_H + +#include +#include + +#include "barry.h" +#include "scientist.h" +#include "coin.h" +#include "particle.h" +#include "game_sprites.h" +#include "states.h" +#include "missile.h" +#include "background_assets.h" +typedef struct { + int total_coins; + int distance; + bool new_highscore; + BARRY barry; + COIN coins[COINS_MAX]; + PARTICLE particles[PARTICLES_MAX]; + SCIENTIST scientists[SCIENTISTS_MAX]; + MISSILE missiles[MISSILES_MAX]; + BackgroundAsset bg_assets[BG_ASSETS_MAX]; + State state; + GameSprites sprites; + FuriMutex* mutex; + FuriTimer* timer; + void (*death_handler)(); +} GameState; + +void game_state_tick(GameState* const game_state); + +#endif // GAMESTATE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/missile.c b/applications/external/jetpack_joyride/includes/missile.c new file mode 100644 index 000000000..af47e8478 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/missile.c @@ -0,0 +1,86 @@ +#include +#include + +#include +#include + +#include "states.h" +#include "game_sprites.h" +#include "missile.h" +#include "barry.h" + +void missile_tick(MISSILE* const missiles, BARRY* const barry, void (*death_handler)()) { + // Move missiles towards the player + for(int i = 0; i < MISSILES_MAX; i++) { + if(missiles[i].visible && missile_colides(&missiles[i], barry)) { + death_handler(); + } + if(missiles[i].visible) { + missiles[i].point.x -= 2; // move left by 2 units + if(missiles[i].point.x < -MISSILE_WIDTH) { // if the missile is out of screen + missiles[i].visible = false; // set missile as "inactive" + } + } + } +} + +void spawn_random_missile(MISSILE* const missiles) { + // Check for an available slot for a new missile + for(int i = 0; i < MISSILES_MAX; ++i) { + if(!missiles[i].visible) { + missiles[i].point.x = 2 * SCREEN_WIDTH; + missiles[i].point.y = rand() % (SCREEN_HEIGHT - MISSILE_HEIGHT); + missiles[i].visible = true; + break; + } + } +} + +void draw_missiles(const MISSILE* missiles, Canvas* const canvas, const GameSprites* sprites) { + for(int i = 0; i < MISSILES_MAX; ++i) { + if(missiles[i].visible) { + canvas_set_color(canvas, ColorBlack); + + if(missiles[i].point.x > 128) { + canvas_draw_icon_animation( + canvas, SCREEN_WIDTH - 7, missiles[i].point.y, sprites->alert); + } else { + canvas_draw_icon_animation( + canvas, missiles[i].point.x, missiles[i].point.y, sprites->missile); + + canvas_set_color(canvas, ColorWhite); + canvas_draw_icon( + canvas, missiles[i].point.x, missiles[i].point.y, sprites->missile_infill); + } + } + } +} + +bool missile_colides(MISSILE* const missile, BARRY* const barry) { + return !( + barry->point.x > + missile->point.x + MISSILE_WIDTH - 14 || // Barry is to the right of the missile + barry->point.x + BARRY_WIDTH - 3 < + missile->point.x || // Barry is to the left of the missile + barry->point.y > missile->point.y + MISSILE_HEIGHT || // Barry is below the missile + barry->point.y + BARRY_HEIGHT < missile->point.y); // Barry is above the missile +} + +int get_rocket_spawn_distance(int player_distance) { + // Define the start and end points for rocket spawn distance + int start_distance = 256; + int end_distance = 24; + + // Define the maximum player distance at which the spawn distance should be at its minimum + int max_player_distance = 5000; // Adjust this value based on your game's difficulty curve + + if(player_distance >= max_player_distance) { + return end_distance; + } + + // Calculate the linear interpolation factor + float t = (float)player_distance / max_player_distance; + + // Interpolate the rocket spawn distance + return start_distance + t * (end_distance - start_distance); +} diff --git a/applications/external/jetpack_joyride/includes/missile.h b/applications/external/jetpack_joyride/includes/missile.h new file mode 100644 index 000000000..a5af4e885 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/missile.h @@ -0,0 +1,24 @@ +#ifndef MISSILE_H +#define MISSILE_H + +#include +#include "game_sprites.h" + +#include "states.h" +#include "point.h" +#include "barry.h" + +#define MISSILES_MAX 5 + +typedef struct { + POINT point; + bool visible; +} MISSILE; + +void missile_tick(MISSILE* const missiles, BARRY* const barry, void (*death_handler)()); +void spawn_random_missile(MISSILE* const MISSILEs); +bool missile_colides(MISSILE* const MISSILE, BARRY* const barry); +int get_rocket_spawn_distance(int player_distance); +void draw_missiles(const MISSILE* missiles, Canvas* const canvas, const GameSprites* sprites); + +#endif // MISSILE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/particle.c b/applications/external/jetpack_joyride/includes/particle.c new file mode 100644 index 000000000..cf8e6e0a6 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/particle.c @@ -0,0 +1,57 @@ +#include + +#include "particle.h" +#include "scientist.h" +#include "barry.h" + +void particle_tick(PARTICLE* const particles, SCIENTIST* const scientists) { + // Move particles + for(int i = 0; i < PARTICLES_MAX; i++) { + if(particles[i].point.y > 0) { + particles[i].point.y += PARTICLE_VELOCITY; + + // Check collision with scientists + for(int j = 0; j < SCIENTISTS_MAX; j++) { + if(scientists[j].state == ScientistStateAlive && scientists[j].point.x > 0) { + // Check whether the particle lies within the scientist's bounding box + if(!(particles[i].point.x > scientists[j].point.x + SCIENTIST_WIDTH || + particles[i].point.x < scientists[j].point.x || + particles[i].point.y > scientists[j].point.y + SCIENTIST_HEIGHT || + particles[i].point.y < scientists[j].point.y)) { + scientists[j].state = ScientistStateDead; + // (*points) += 2; // Increase the score by 2 + } + } + } + + if(particles[i].point.x < 0 || particles[i].point.x > SCREEN_WIDTH || + particles[i].point.y < 0 || particles[i].point.y > SCREEN_HEIGHT) { + particles[i].point.y = 0; + } + } + } +} + +void spawn_random_particles(PARTICLE* const particles, BARRY* const barry) { + for(int i = 0; i < PARTICLES_MAX; i++) { + if(particles[i].point.y <= 0) { + particles[i].point.x = barry->point.x + (rand() % 4); + particles[i].point.y = barry->point.y + 14; + break; + } + } +} + +void draw_particles(const PARTICLE* particles, Canvas* const canvas) { + canvas_set_color(canvas, ColorBlack); + for(int i = 0; i < PARTICLES_MAX; i++) { + if(particles[i].point.y > 0) { + canvas_draw_line( + canvas, + particles[i].point.x, + particles[i].point.y, + particles[i].point.x, + particles[i].point.y + 3); + } + } +} diff --git a/applications/external/jetpack_joyride/includes/particle.h b/applications/external/jetpack_joyride/includes/particle.h new file mode 100644 index 000000000..3442c9c4e --- /dev/null +++ b/applications/external/jetpack_joyride/includes/particle.h @@ -0,0 +1,21 @@ + + +#ifndef PARTICLE_H +#define PARTICLE_H + +#include "point.h" +#include "scientist.h" +#include "barry.h" + +#define PARTICLES_MAX 50 +#define PARTICLE_VELOCITY 2 + +typedef struct { + POINT point; +} PARTICLE; + +void particle_tick(PARTICLE* const particles, SCIENTIST* const scientists); +void spawn_random_particles(PARTICLE* const particles, BARRY* const barry); +void draw_particles(const PARTICLE* particles, Canvas* const canvas); + +#endif // PARTICLE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/point.h b/applications/external/jetpack_joyride/includes/point.h new file mode 100644 index 000000000..02c9a6ce4 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/point.h @@ -0,0 +1,14 @@ +#ifndef POINT_H +#define POINT_H + +typedef struct { + int x; + int y; +} POINT; + +typedef struct { + float x; + float y; +} POINTF; + +#endif // POINT_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/scientist.c b/applications/external/jetpack_joyride/includes/scientist.c new file mode 100644 index 000000000..b1a8a14c0 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/scientist.c @@ -0,0 +1,77 @@ +#include "scientist.h" +#include "game_sprites.h" + +#include +#include + +void scientist_tick(SCIENTIST* const scientists) { + for(int i = 0; i < SCIENTISTS_MAX; i++) { + if(scientists[i].visible) { + if(scientists[i].point.x < 64) scientists[i].velocity_x = 0.5f; + + scientists[i].point.x -= scientists[i].state == ScientistStateAlive ? + 1 - scientists[i].velocity_x : + 1; // move based on velocity_x + int width = (scientists[i].state == ScientistStateAlive) ? SCIENTIST_WIDTH : + SCIENTIST_HEIGHT; + if(scientists[i].point.x <= -width) { // if the scientist is out of screen + scientists[i].visible = false; + } + } + } +} + +void spawn_random_scientist(SCIENTIST* const scientists) { + float velocities[] = {-0.5f, 0.0f, 0.5f, -1.0f}; + // Check for an available slot for a new scientist + for(int i = 0; i < SCIENTISTS_MAX; ++i) { + if(!scientists[i].visible && + (rand() % 1000) < 10) { // Spawn rate is less frequent than coins + scientists[i].state = ScientistStateAlive; + scientists[i].point.x = 127; + scientists[i].point.y = 49; + scientists[i].velocity_x = velocities[rand() % 4]; + scientists[i].visible = true; + break; + } + } +} + +void draw_scientists(const SCIENTIST* scientists, Canvas* const canvas, const GameSprites* sprites) { + for(int i = 0; i < SCIENTISTS_MAX; ++i) { + if(scientists[i].visible) { + canvas_set_color(canvas, ColorBlack); + if(scientists[i].state == ScientistStateAlive) { + canvas_draw_icon( + canvas, + (int)scientists[i].point.x, + scientists[i].point.y, + scientists[i].velocity_x >= 0 ? sprites->scientist_right : + sprites->scientist_left); + + canvas_set_color(canvas, ColorWhite); + canvas_draw_icon( + canvas, + (int)scientists[i].point.x, + scientists[i].point.y, + scientists[i].velocity_x >= 0 ? sprites->scientist_right_infill : + sprites->scientist_left_infill); + + } else { + canvas_set_color(canvas, ColorBlack); + canvas_draw_icon( + canvas, + (int)scientists[i].point.x, + scientists[i].point.y + 5, + &I_dead_scientist); + + canvas_set_color(canvas, ColorWhite); + canvas_draw_icon( + canvas, + (int)scientists[i].point.x, + scientists[i].point.y + 5, + &I_dead_scientist_infill); + } + } + } +} \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/scientist.h b/applications/external/jetpack_joyride/includes/scientist.h new file mode 100644 index 000000000..a49e8028c --- /dev/null +++ b/applications/external/jetpack_joyride/includes/scientist.h @@ -0,0 +1,29 @@ +#ifndef SCIENTIST_H +#define SCIENTIST_H + +#include "point.h" +#include "game_sprites.h" +#include + +#define SCIENTIST_VELOCITY_MIN -0.5f +#define SCIENTIST_VELOCITY_MAX 0.5f + +#define SCIENTISTS_MAX 6 + +typedef enum { + ScientistStateAlive, + ScientistStateDead, +} ScientistState; + +typedef struct { + bool visible; + POINTF point; + float velocity_x; + ScientistState state; +} SCIENTIST; + +void scientist_tick(SCIENTIST* const scientist); +void spawn_random_scientist(SCIENTIST* const scientists); +void draw_scientists(const SCIENTIST* scientists, Canvas* const canvas, const GameSprites* sprites); + +#endif // SCIENTIST_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/includes/states.h b/applications/external/jetpack_joyride/includes/states.h new file mode 100644 index 000000000..d58e3e1f6 --- /dev/null +++ b/applications/external/jetpack_joyride/includes/states.h @@ -0,0 +1,9 @@ +#ifndef STATE_H +#define STATE_H + +typedef enum { + GameStateLife, + GameStateGameOver, +} State; + +#endif // STATE_H \ No newline at end of file diff --git a/applications/external/jetpack_joyride/jetpack.c b/applications/external/jetpack_joyride/jetpack.c new file mode 100644 index 000000000..c12f094c9 --- /dev/null +++ b/applications/external/jetpack_joyride/jetpack.c @@ -0,0 +1,379 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "includes/point.h" +#include "includes/barry.h" +#include "includes/scientist.h" +#include "includes/particle.h" +#include "includes/coin.h" +#include "includes/missile.h" +#include "includes/background_assets.h" + +#include "includes/game_state.h" + +#define TAG "Jetpack Joyride" +#define SAVING_DIRECTORY "/ext/apps/Games" +#define SAVING_FILENAME SAVING_DIRECTORY "/jetpack.save" +static GameState* global_state; + +typedef enum { + EventTypeTick, + EventTypeKey, +} EventType; + +typedef struct { + EventType type; + InputEvent input; +} GameEvent; + +typedef struct { + int max_distance; + int total_coins; +} SaveGame; + +static SaveGame save_game; + +static bool storage_game_state_load() { + Storage* storage = furi_record_open(RECORD_STORAGE); + File* file = storage_file_alloc(storage); + + uint16_t bytes_readed = 0; + if(storage_file_open(file, SAVING_FILENAME, FSAM_READ, FSOM_OPEN_EXISTING)) + bytes_readed = storage_file_read(file, &save_game, sizeof(SaveGame)); + storage_file_close(file); + storage_file_free(file); + furi_record_close(RECORD_STORAGE); + return bytes_readed == sizeof(SaveGame); +} + +static void storage_game_state_save() { + Storage* storage = furi_record_open(RECORD_STORAGE); + + if(storage_common_stat(storage, SAVING_DIRECTORY, NULL) == FSE_NOT_EXIST) { + if(!storage_simply_mkdir(storage, SAVING_DIRECTORY)) { + return; + } + } + + File* file = storage_file_alloc(storage); + if(storage_file_open(file, SAVING_FILENAME, FSAM_WRITE, FSOM_CREATE_ALWAYS)) { + storage_file_write(file, &save_game, sizeof(SaveGame)); + } + storage_file_close(file); + storage_file_free(file); + furi_record_close(RECORD_STORAGE); +} + +void handle_death() { + global_state->state = GameStateGameOver; + global_state->new_highscore = global_state->distance > save_game.max_distance; + + if(global_state->distance > save_game.max_distance) { + save_game.max_distance = global_state->distance; + } + + save_game.total_coins += global_state->total_coins; + + storage_game_state_save(); +} + +static void jetpack_game_state_init(GameState* const game_state) { + UNUSED(game_state); + UNUSED(storage_game_state_save); + BARRY barry; + barry.gravity = 0; + barry.point.x = 32 + 5; + barry.point.y = 32; + barry.isBoosting = false; + + GameSprites sprites; + sprites.barry = icon_animation_alloc(&A_barry); + sprites.barry_infill = &I_barry_infill; + + sprites.scientist_left = (&I_scientist_left); + sprites.scientist_left_infill = (&I_scientist_left_infill); + sprites.scientist_right = (&I_scientist_right); + sprites.scientist_right_infill = (&I_scientist_right_infill); + + sprites.coin = (&I_coin); + sprites.coin_infill = (&I_coin_infill); + + sprites.missile = icon_animation_alloc(&A_missile); + sprites.missile_infill = &I_missile_infill; + + sprites.alert = icon_animation_alloc(&A_alert); + + icon_animation_start(sprites.barry); + icon_animation_start(sprites.missile); + icon_animation_start(sprites.alert); + + game_state->barry = barry; + game_state->total_coins = 0; + game_state->distance = 0; + game_state->new_highscore = false; + game_state->sprites = sprites; + game_state->state = GameStateLife; + game_state->death_handler = handle_death; + + memset(game_state->bg_assets, 0, sizeof(game_state->bg_assets)); + + memset(game_state->scientists, 0, sizeof(game_state->scientists)); + memset(game_state->coins, 0, sizeof(game_state->coins)); + memset(game_state->particles, 0, sizeof(game_state->particles)); + memset(game_state->missiles, 0, sizeof(game_state->missiles)); +} + +static void jetpack_game_state_free(GameState* const game_state) { + icon_animation_free(game_state->sprites.barry); + icon_animation_free(game_state->sprites.missile); + icon_animation_free(game_state->sprites.alert); + + free(game_state); +} + +static void jetpack_game_tick(GameState* const game_state) { + if(game_state->state == GameStateGameOver) return; + barry_tick(&game_state->barry); + game_state_tick(game_state); + coin_tick(game_state->coins, &game_state->barry, &game_state->total_coins); + particle_tick(game_state->particles, game_state->scientists); + scientist_tick(game_state->scientists); + missile_tick(game_state->missiles, &game_state->barry, game_state->death_handler); + + background_assets_tick(game_state->bg_assets); + + // generate background every 64px aka. ticks + if(game_state->distance % 64 == 0 && rand() % 3 == 0) { + spawn_random_background_asset(game_state->bg_assets); + } + + if(game_state->distance % 48 == 0 && rand() % 2 == 0) { + spawn_random_coin(game_state->coins); + } + + if(game_state->distance % get_rocket_spawn_distance(game_state->distance) == 0 && + rand() % 2 == 0) { + spawn_random_missile(game_state->missiles); + } + + spawn_random_scientist(game_state->scientists); + + if(game_state->barry.isBoosting) { + spawn_random_particles(game_state->particles, &game_state->barry); + } +} + +static void jetpack_game_render_callback(Canvas* const canvas, void* ctx) { + furi_assert(ctx); + const GameState* game_state = ctx; + furi_mutex_acquire(game_state->mutex, FuriWaitForever); + + if(game_state->state == GameStateLife) { + canvas_set_bitmap_mode(canvas, false); + + draw_background_assets(game_state->bg_assets, canvas, game_state->distance); + + canvas_set_bitmap_mode(canvas, true); + + draw_coins(game_state->coins, canvas, &game_state->sprites); + draw_scientists(game_state->scientists, canvas, &game_state->sprites); + draw_particles(game_state->particles, canvas); + draw_missiles(game_state->missiles, canvas, &game_state->sprites); + + draw_barry(&game_state->barry, canvas, &game_state->sprites); + + canvas_set_color(canvas, ColorBlack); + canvas_set_font(canvas, FontSecondary); + char buffer[12]; + snprintf(buffer, sizeof(buffer), "%u m", game_state->distance / 10); + canvas_draw_str_aligned(canvas, 123, 15, AlignRight, AlignBottom, buffer); + + snprintf(buffer, sizeof(buffer), "$%u", game_state->total_coins); + canvas_draw_str_aligned(canvas, 5, 15, AlignLeft, AlignBottom, buffer); + } + + if(game_state->state == GameStateGameOver) { + // Show highscore + char buffer[64]; + + canvas_set_font(canvas, FontSecondary); + canvas_draw_str_aligned(canvas, 64, 5, AlignCenter, AlignTop, "You flew"); + + snprintf( + buffer, + sizeof(buffer), + game_state->new_highscore ? "%u m (new best)" : "%u m", + game_state->distance / 10); + canvas_set_font(canvas, FontPrimary); + canvas_draw_str_aligned(canvas, 64, 16, AlignCenter, AlignTop, buffer); + + canvas_set_font(canvas, FontSecondary); + canvas_draw_str_aligned(canvas, 64, 30, AlignCenter, AlignTop, "and collected"); + + snprintf(buffer, sizeof(buffer), "$%u", game_state->total_coins); + canvas_set_font(canvas, FontPrimary); + canvas_draw_str_aligned(canvas, 64, 41, AlignCenter, AlignTop, buffer); + + snprintf( + buffer, + sizeof(buffer), + "Best: %u m, Tot: $%u", + save_game.max_distance / 10, + save_game.total_coins); + canvas_set_font(canvas, FontSecondary); + canvas_draw_str_aligned(canvas, 64, 63, AlignCenter, AlignBottom, buffer); + + canvas_draw_rframe(canvas, 0, 3, 128, 49, 5); + + // char buffer[12]; + // snprintf(buffer, sizeof(buffer), "Dist: %u", game_state->distance); + // canvas_draw_str_aligned(canvas, 123, 12, AlignRight, AlignBottom, buffer); + + // snprintf(buffer, sizeof(buffer), "Score: %u", game_state->points); + // canvas_draw_str_aligned(canvas, 5, 12, AlignLeft, AlignBottom, buffer); + + // canvas_draw_str_aligned(canvas, 64, 34, AlignCenter, AlignCenter, "Highscore:"); + // snprintf(buffer, sizeof(buffer), "Dist: %u", save_game.max_distance); + // canvas_draw_str_aligned(canvas, 123, 50, AlignRight, AlignBottom, buffer); + + // snprintf(buffer, sizeof(buffer), "Score: %u", save_game.max_score); + // canvas_draw_str_aligned(canvas, 5, 50, AlignLeft, AlignBottom, buffer); + + // canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignCenter, "boom."); + + // if(furi_timer_is_running(game_state->timer)) { + // furi_timer_start(game_state->timer, 0); + // } + } + + // canvas_draw_frame(canvas, 0, 0, 128, 64); + + furi_mutex_release(game_state->mutex); +} + +static void jetpack_game_input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) { + furi_assert(event_queue); + + GameEvent event = {.type = EventTypeKey, .input = *input_event}; + furi_message_queue_put(event_queue, &event, FuriWaitForever); +} + +static void jetpack_game_update_timer_callback(FuriMessageQueue* event_queue) { + furi_assert(event_queue); + + GameEvent event = {.type = EventTypeTick}; + furi_message_queue_put(event_queue, &event, 0); +} + +int32_t jetpack_game_app(void* p) { + UNUSED(p); + int32_t return_code = 0; + + if(!storage_game_state_load()) { + memset(&save_game, 0, sizeof(save_game)); + } + + FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(GameEvent)); + + GameState* game_state = malloc(sizeof(GameState)); + + global_state = game_state; + jetpack_game_state_init(game_state); + + game_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal); + if(!game_state->mutex) { + FURI_LOG_E(TAG, "cannot create mutex\r\n"); + return_code = 255; + goto free_and_exit; + } + + // Set system callbacks + ViewPort* view_port = view_port_alloc(); + view_port_draw_callback_set(view_port, jetpack_game_render_callback, game_state); + view_port_input_callback_set(view_port, jetpack_game_input_callback, event_queue); + + FuriTimer* timer = + furi_timer_alloc(jetpack_game_update_timer_callback, FuriTimerTypePeriodic, event_queue); + furi_timer_start(timer, furi_kernel_get_tick_frequency() / 25); + + game_state->timer = timer; + + // Open GUI and register view_port + Gui* gui = furi_record_open(RECORD_GUI); + gui_add_view_port(gui, view_port, GuiLayerFullscreen); + + GameEvent event; + for(bool processing = true; processing;) { + FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100); + furi_mutex_acquire(game_state->mutex, FuriWaitForever); + + if(event_status == FuriStatusOk) { + // press events + if(event.type == EventTypeKey) { + if(event.input.type == InputTypeRelease && event.input.key == InputKeyOk) { + game_state->barry.isBoosting = false; + } + + // Reset highscore, for debug purposes + if(event.input.type == InputTypeLong && event.input.key == InputKeyLeft) { + save_game.max_distance = 0; + save_game.total_coins = 0; + storage_game_state_save(); + } + + if(event.input.type == InputTypePress) { + switch(event.input.key) { + case InputKeyUp: + break; + case InputKeyDown: + break; + case InputKeyRight: + break; + case InputKeyLeft: + break; + case InputKeyOk: + if(game_state->state == GameStateGameOver) { + jetpack_game_state_init(game_state); + } + + if(game_state->state == GameStateLife) { + // Do something + game_state->barry.isBoosting = true; + } + + break; + case InputKeyBack: + processing = false; + break; + default: + break; + } + } + } else if(event.type == EventTypeTick) { + jetpack_game_tick(game_state); + } + } + + view_port_update(view_port); + furi_mutex_release(game_state->mutex); + } + + furi_timer_free(timer); + view_port_enabled_set(view_port, false); + gui_remove_view_port(gui, view_port); + furi_record_close(RECORD_GUI); + view_port_free(view_port); + furi_mutex_free(game_state->mutex); + +free_and_exit: + jetpack_game_state_free(game_state); + furi_message_queue_free(event_queue); + + return return_code; +} \ No newline at end of file diff --git a/applications/external/minesweeper/minesweeper.c b/applications/external/minesweeper/minesweeper.c index c169b075e..4e92fba33 100644 --- a/applications/external/minesweeper/minesweeper.c +++ b/applications/external/minesweeper/minesweeper.c @@ -6,7 +6,6 @@ #include #include -#include #include diff --git a/applications/external/multi_converter/application.fam b/applications/external/multi_converter/application.fam index 84eaa805b..3a8a488b4 100644 --- a/applications/external/multi_converter/application.fam +++ b/applications/external/multi_converter/application.fam @@ -7,7 +7,7 @@ App( stack_size=1 * 1024, order=19, fap_icon="converter_10px.png", - fap_category="Misc", + fap_category="Tools", fap_author="@theisolinearchip", fap_version="1.0", fap_description="A multi-unit converter written with an easy and expandable system for adding new units and conversion methods", diff --git a/applications/external/multi_fuzzer/application.fam b/applications/external/multi_fuzzer/application.fam index a0ce1be0a..b5205803d 100644 --- a/applications/external/multi_fuzzer/application.fam +++ b/applications/external/multi_fuzzer/application.fam @@ -4,21 +4,21 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="fuzzer_start_ibtn", requires=[ - "gui", + "gui", "storage", - "dialogs", - "input", + "dialogs", + "input", "notification", ], stack_size=2 * 1024, fap_icon="icons/ibutt_10px.png", - fap_category="Tools", + fap_category="iButton", fap_private_libs=[ - Lib( - name="worker", - cdefines=["IBUTTON_PROTOCOL"], - ), - ], + Lib( + name="worker", + cdefines=["IBUTTON_PROTOCOL"], + ), + ], fap_icon_assets="icons", fap_icon_assets_symbol="fuzzer", ) @@ -29,21 +29,21 @@ App( apptype=FlipperAppType.EXTERNAL, entry_point="fuzzer_start_rfid", requires=[ - "gui", + "gui", "storage", - "dialogs", - "input", + "dialogs", + "input", "notification", ], stack_size=2 * 1024, fap_icon="icons/rfid_10px.png", - fap_category="Tools", + fap_category="RFID", fap_private_libs=[ - Lib( - name="worker", - cdefines=["RFID_125_PROTOCOL"], - ), - ], + Lib( + name="worker", + cdefines=["RFID_125_PROTOCOL"], + ), + ], fap_icon_assets="icons", fap_icon_assets_symbol="fuzzer", ) diff --git a/applications/external/nfc_maker/application.fam b/applications/external/nfc_maker/application.fam new file mode 100644 index 000000000..95bcd8878 --- /dev/null +++ b/applications/external/nfc_maker/application.fam @@ -0,0 +1,15 @@ +App( + appid="nfc_maker", + name="NFC Maker", + apptype=FlipperAppType.EXTERNAL, + entry_point="nfc_maker", + cdefines=["APP_NFC_MAKER"], + requires=[ + "storage", + "gui", + ], + stack_size=1 * 1024, + fap_icon="nfc_maker_10px.png", + fap_category="NFC", + fap_icon_assets="assets", +) diff --git a/applications/external/nfc_maker/assets/DolphinNice_96x59.png b/applications/external/nfc_maker/assets/DolphinNice_96x59.png new file mode 100644 index 000000000..a299d3630 Binary files /dev/null and b/applications/external/nfc_maker/assets/DolphinNice_96x59.png differ diff --git a/applications/external/nfc_maker/nfc_maker.c b/applications/external/nfc_maker/nfc_maker.c new file mode 100644 index 000000000..578054ade --- /dev/null +++ b/applications/external/nfc_maker/nfc_maker.c @@ -0,0 +1,81 @@ +#include "nfc_maker.h" + +static bool nfc_maker_custom_event_callback(void* context, uint32_t event) { + furi_assert(context); + NfcMaker* app = context; + return scene_manager_handle_custom_event(app->scene_manager, event); +} + +static bool nfc_maker_back_event_callback(void* context) { + furi_assert(context); + NfcMaker* app = context; + + return scene_manager_handle_back_event(app->scene_manager); +} + +NfcMaker* nfc_maker_alloc() { + NfcMaker* app = malloc(sizeof(NfcMaker)); + app->gui = furi_record_open(RECORD_GUI); + + // View Dispatcher and Scene Manager + app->view_dispatcher = view_dispatcher_alloc(); + app->scene_manager = scene_manager_alloc(&nfc_maker_scene_handlers, app); + view_dispatcher_enable_queue(app->view_dispatcher); + view_dispatcher_set_event_callback_context(app->view_dispatcher, app); + + view_dispatcher_set_custom_event_callback( + app->view_dispatcher, nfc_maker_custom_event_callback); + view_dispatcher_set_navigation_event_callback( + app->view_dispatcher, nfc_maker_back_event_callback); + + view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen); + + // Gui Modules + app->submenu = submenu_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, NfcMakerViewSubmenu, submenu_get_view(app->submenu)); + + app->text_input = text_input_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, NfcMakerViewTextInput, text_input_get_view(app->text_input)); + + app->byte_input = byte_input_alloc(); + view_dispatcher_add_view( + app->view_dispatcher, NfcMakerViewByteInput, byte_input_get_view(app->byte_input)); + + app->popup = popup_alloc(); + view_dispatcher_add_view(app->view_dispatcher, NfcMakerViewPopup, popup_get_view(app->popup)); + + return app; +} + +void nfc_maker_free(NfcMaker* app) { + furi_assert(app); + + // Gui modules + view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewSubmenu); + submenu_free(app->submenu); + view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewTextInput); + text_input_free(app->text_input); + view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewByteInput); + byte_input_free(app->byte_input); + view_dispatcher_remove_view(app->view_dispatcher, NfcMakerViewPopup); + popup_free(app->popup); + + // View Dispatcher and Scene Manager + view_dispatcher_free(app->view_dispatcher); + scene_manager_free(app->scene_manager); + + // Records + furi_record_close(RECORD_GUI); + free(app); +} + +extern int32_t nfc_maker(void* p) { + UNUSED(p); + NfcMaker* app = nfc_maker_alloc(); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneMenu); + view_dispatcher_run(app->view_dispatcher); + nfc_maker_free(app); + return 0; +} diff --git a/applications/external/nfc_maker/nfc_maker.h b/applications/external/nfc_maker/nfc_maker.h new file mode 100644 index 000000000..76a7a2538 --- /dev/null +++ b/applications/external/nfc_maker/nfc_maker.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "nfc_maker_icons.h" +#include +#include +#include +#include +#include "scenes/nfc_maker_scene.h" +#include +#include +#include +#include +#include "strnlen.h" + +#define TEXT_INPUT_LEN 248 +#define WIFI_INPUT_LEN 90 + +typedef enum { + WifiAuthenticationOpen = 0x01, + WifiAuthenticationWpa2Personal = 0x20, + WifiAuthenticationWpa2Enterprise = 0x10, + WifiAuthenticationWpaPersonal = 0x02, + WifiAuthenticationWpaEnterprise = 0x08, + WifiAuthenticationShared = 0x04, +} WifiAuthentication; + +typedef enum { + WifiEncryptionAes = 0x08, + WifiEncryptionWep = 0x02, + WifiEncryptionTkip = 0x04, + WifiEncryptionNone = 0x01, +} WifiEncryption; + +typedef struct { + Gui* gui; + SceneManager* scene_manager; + ViewDispatcher* view_dispatcher; + Submenu* submenu; + TextInput* text_input; + ByteInput* byte_input; + Popup* popup; + + uint8_t mac_buf[GAP_MAC_ADDR_SIZE]; + char text_buf[TEXT_INPUT_LEN]; + char pass_buf[WIFI_INPUT_LEN]; + char name_buf[TEXT_INPUT_LEN]; +} NfcMaker; + +typedef enum { + NfcMakerViewSubmenu, + NfcMakerViewTextInput, + NfcMakerViewByteInput, + NfcMakerViewPopup, +} NfcMakerView; diff --git a/applications/external/nfc_maker/nfc_maker_10px.png b/applications/external/nfc_maker/nfc_maker_10px.png new file mode 100644 index 000000000..a9e2443f1 Binary files /dev/null and b/applications/external/nfc_maker/nfc_maker_10px.png differ diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene.c b/applications/external/nfc_maker/scenes/nfc_maker_scene.c new file mode 100644 index 000000000..3a8b7d502 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene.c @@ -0,0 +1,30 @@ +#include "nfc_maker_scene.h" + +// Generate scene on_enter handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter, +void (*const nfc_maker_on_enter_handlers[])(void*) = { +#include "nfc_maker_scene_config.h" +}; +#undef ADD_SCENE + +// Generate scene on_event handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event, +bool (*const nfc_maker_on_event_handlers[])(void* context, SceneManagerEvent event) = { +#include "nfc_maker_scene_config.h" +}; +#undef ADD_SCENE + +// Generate scene on_exit handlers array +#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit, +void (*const nfc_maker_on_exit_handlers[])(void* context) = { +#include "nfc_maker_scene_config.h" +}; +#undef ADD_SCENE + +// Initialize scene handlers configuration structure +const SceneManagerHandlers nfc_maker_scene_handlers = { + .on_enter_handlers = nfc_maker_on_enter_handlers, + .on_event_handlers = nfc_maker_on_event_handlers, + .on_exit_handlers = nfc_maker_on_exit_handlers, + .scene_num = NfcMakerSceneNum, +}; diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene.h b/applications/external/nfc_maker/scenes/nfc_maker_scene.h new file mode 100644 index 000000000..5ad69f233 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +// Generate scene id and total number +#define ADD_SCENE(prefix, name, id) NfcMakerScene##id, +typedef enum { +#include "nfc_maker_scene_config.h" + NfcMakerSceneNum, +} NfcMakerScene; +#undef ADD_SCENE + +extern const SceneManagerHandlers nfc_maker_scene_handlers; + +// Generate scene on_enter handlers declaration +#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*); +#include "nfc_maker_scene_config.h" +#undef ADD_SCENE + +// Generate scene on_event handlers declaration +#define ADD_SCENE(prefix, name, id) \ + bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event); +#include "nfc_maker_scene_config.h" +#undef ADD_SCENE + +// Generate scene on_exit handlers declaration +#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context); +#include "nfc_maker_scene_config.h" +#undef ADD_SCENE diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c new file mode 100644 index 000000000..4e70a184d --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_bluetooth.c @@ -0,0 +1,57 @@ +#include "../nfc_maker.h" + +enum ByteInputResult { + ByteInputResultOk, +}; + +static void nfc_maker_scene_bluetooth_byte_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, ByteInputResultOk); +} + +void nfc_maker_scene_bluetooth_on_enter(void* context) { + NfcMaker* app = context; + ByteInput* byte_input = app->byte_input; + + byte_input_set_header_text(byte_input, "Enter Bluetooth MAC:"); + + for(size_t i = 0; i < GAP_MAC_ADDR_SIZE; i++) { + app->mac_buf[i] = 0x69; + } + + byte_input_set_result_callback( + byte_input, + nfc_maker_scene_bluetooth_byte_input_callback, + NULL, + app, + app->mac_buf, + GAP_MAC_ADDR_SIZE); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewByteInput); +} + +bool nfc_maker_scene_bluetooth_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case ByteInputResultOk: + furi_hal_bt_reverse_mac_addr(app->mac_buf); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_bluetooth_on_exit(void* context) { + NfcMaker* app = context; + byte_input_set_result_callback(app->byte_input, NULL, NULL, NULL, NULL, 0); + byte_input_set_header_text(app->byte_input, ""); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h b/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h new file mode 100644 index 000000000..a89b4198c --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_config.h @@ -0,0 +1,13 @@ +ADD_SCENE(nfc_maker, menu, Menu) +ADD_SCENE(nfc_maker, bluetooth, Bluetooth) +ADD_SCENE(nfc_maker, https, Https) +ADD_SCENE(nfc_maker, mail, Mail) +ADD_SCENE(nfc_maker, phone, Phone) +ADD_SCENE(nfc_maker, text, Text) +ADD_SCENE(nfc_maker, url, Url) +ADD_SCENE(nfc_maker, wifi, Wifi) +ADD_SCENE(nfc_maker, wifi_auth, WifiAuth) +ADD_SCENE(nfc_maker, wifi_encr, WifiEncr) +ADD_SCENE(nfc_maker, wifi_pass, WifiPass) +ADD_SCENE(nfc_maker, name, Name) +ADD_SCENE(nfc_maker, result, Result) diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c new file mode 100644 index 000000000..77b32afe1 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_https.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_https_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_https_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter HTTPS Link:"); + + strlcpy(app->text_buf, "google.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_https_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_https_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_https_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c new file mode 100644 index 000000000..98c648f6a --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_mail.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_mail_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_mail_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter EMail Address:"); + + strlcpy(app->text_buf, "ben.dover@example.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_mail_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_mail_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_mail_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c new file mode 100644 index 000000000..4268e7e2f --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_menu.c @@ -0,0 +1,61 @@ +#include "../nfc_maker.h" + +void nfc_maker_scene_menu_submenu_callback(void* context, uint32_t index) { + NfcMaker* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void nfc_maker_scene_menu_on_enter(void* context) { + NfcMaker* app = context; + Submenu* submenu = app->submenu; + + submenu_set_header(submenu, "NFC Tag Maker:"); + + submenu_add_item( + submenu, + "Bluetooth MAC", + NfcMakerSceneBluetooth, + nfc_maker_scene_menu_submenu_callback, + app); + + submenu_add_item( + submenu, "HTTPS Link", NfcMakerSceneHttps, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Mail Address", NfcMakerSceneMail, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Phone Number", NfcMakerScenePhone, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Text Note", NfcMakerSceneText, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "Plain URL", NfcMakerSceneUrl, nfc_maker_scene_menu_submenu_callback, app); + + submenu_add_item( + submenu, "WiFi Login", NfcMakerSceneWifi, nfc_maker_scene_menu_submenu_callback, app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneMenu)); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); +} + +bool nfc_maker_scene_menu_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneMenu, event.event); + consumed = true; + scene_manager_next_scene(app->scene_manager, event.event); + } + + return consumed; +} + +void nfc_maker_scene_menu_on_exit(void* context) { + NfcMaker* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c new file mode 100644 index 000000000..dd5170d94 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_name.c @@ -0,0 +1,57 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_name_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_name_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Name the NFC tag:"); + + set_random_name(app->name_buf, TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_name_text_input_callback, + app, + app->name_buf, + TEXT_INPUT_LEN, + true); + + ValidatorIsFile* validator_is_file = + validator_is_file_alloc_init(NFC_APP_FOLDER, NFC_APP_EXTENSION, NULL); + text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_name_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneResult); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_name_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c new file mode 100644 index 000000000..4e70bcb09 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_phone.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_phone_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_phone_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter Phone Number:"); + + strlcpy(app->text_buf, "+", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_phone_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + false); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_phone_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_phone_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c new file mode 100644 index 000000000..912bf3c9f --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_result.c @@ -0,0 +1,359 @@ +#include "../nfc_maker.h" + +enum PopupEvent { + PopupEventExit, +}; + +static void nfc_maker_scene_result_popup_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, PopupEventExit); +} + +void nfc_maker_scene_result_on_enter(void* context) { + NfcMaker* app = context; + Popup* popup = app->popup; + bool success = false; + + FlipperFormat* file = flipper_format_file_alloc(furi_record_open(RECORD_STORAGE)); + FuriString* path = furi_string_alloc(); + furi_string_printf(path, NFC_APP_FOLDER "/%s" NFC_APP_EXTENSION, app->name_buf); + do { + if(!flipper_format_file_open_new(file, furi_string_get_cstr(path))) break; + + uint32_t pages = 42; + size_t size = pages * 4; + uint8_t* buf = malloc(size); + + if(!flipper_format_write_header_cstr(file, "Flipper NFC device", 3)) break; + if(!flipper_format_write_string_cstr(file, "Device type", "NTAG203")) break; + + // Serial number + buf[0] = 0x04; + furi_hal_random_fill_buf(&buf[1], 8); + uint8_t uid[7]; + memcpy(&uid[0], &buf[0], 3); + memcpy(&uid[3], &buf[4], 4); + + if(!flipper_format_write_hex(file, "UID", uid, sizeof(uid))) break; + if(!flipper_format_write_string_cstr(file, "ATQA", "00 44")) break; + if(!flipper_format_write_string_cstr(file, "SAK", "00")) break; + // TODO: Maybe randomize? + if(!flipper_format_write_string_cstr( + file, + "Signature", + "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")) + break; + if(!flipper_format_write_string_cstr(file, "Mifare version", "00 00 00 00 00 00 00 00")) + break; + + if(!flipper_format_write_string_cstr(file, "Counter 0", "0")) break; + if(!flipper_format_write_string_cstr(file, "Tearing 0", "00")) break; + if(!flipper_format_write_string_cstr(file, "Counter 1", "0")) break; + if(!flipper_format_write_string_cstr(file, "Tearing 1", "00")) break; + if(!flipper_format_write_string_cstr(file, "Counter 2", "0")) break; + if(!flipper_format_write_string_cstr(file, "Tearing 2", "00")) break; + if(!flipper_format_write_uint32(file, "Pages total", &pages, 1)) break; + + // Static data + buf[9] = 0x48; // Internal + buf[10] = 0x00; // Lock bytes + buf[11] = 0x00; // ... + buf[12] = 0xE1; // Capability container + buf[13] = 0x10; // ... + buf[14] = 0x12; // ... + buf[15] = 0x00; // ... + buf[16] = 0x01; // ... + buf[17] = 0x03; // ... + buf[18] = 0xA0; // ... + buf[19] = 0x10; // ... + buf[20] = 0x44; // ... + buf[21] = 0x03; // Message flags + + size_t msg_len = 0; + switch(scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneMenu)) { + case NfcMakerSceneBluetooth: { + msg_len = 0x2B; + + buf[23] = 0xD2; + buf[24] = 0x20; + buf[25] = 0x08; + buf[26] = 0x61; + buf[27] = 0x70; + + buf[28] = 0x70; + buf[29] = 0x6C; + buf[30] = 0x69; + buf[31] = 0x63; + + buf[32] = 0x61; + buf[33] = 0x74; + buf[34] = 0x69; + buf[35] = 0x6F; + + buf[36] = 0x6E; + buf[37] = 0x2F; + buf[38] = 0x76; + buf[39] = 0x6E; + + buf[40] = 0x64; + buf[41] = 0x2E; + buf[42] = 0x62; + buf[43] = 0x6C; + + buf[44] = 0x75; + buf[45] = 0x65; + buf[46] = 0x74; + buf[47] = 0x6F; + + buf[48] = 0x6F; + buf[49] = 0x74; + buf[50] = 0x68; + buf[51] = 0x2E; + + buf[52] = 0x65; + buf[53] = 0x70; + buf[54] = 0x2E; + buf[55] = 0x6F; + + buf[56] = 0x6F; + buf[57] = 0x62; + buf[58] = 0x08; + buf[59] = 0x00; + + memcpy(&buf[60], app->mac_buf, GAP_MAC_ADDR_SIZE); + break; + } + case NfcMakerSceneHttps: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x04; // Prepend "https://" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneMail: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x06; // Prepend "mailto:" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerScenePhone: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x05; // Prepend "tel:" + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneText: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 7; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 3; + buf[26] = 0x54; + + buf[27] = 0x02; + buf[28] = 0x65; // e + buf[29] = 0x6E; // n + memcpy(&buf[30], app->text_buf, data_len); + break; + } + case NfcMakerSceneUrl: { + uint8_t data_len = strnlen(app->text_buf, TEXT_INPUT_LEN); + msg_len = data_len + 5; + + buf[23] = 0xD1; + buf[24] = 0x01; + buf[25] = data_len + 1; + buf[26] = 0x55; + + buf[27] = 0x00; // No prepend + memcpy(&buf[28], app->text_buf, data_len); + break; + } + case NfcMakerSceneWifi: { + uint8_t ssid_len = strnlen(app->text_buf, WIFI_INPUT_LEN); + uint8_t pass_len = strnlen(app->pass_buf, WIFI_INPUT_LEN); + uint8_t data_len = ssid_len + pass_len; + msg_len = data_len + 73; + + buf[23] = 0xD2; + buf[24] = 0x17; + buf[25] = data_len + 47; + buf[26] = 0x61; + buf[27] = 0x70; + + buf[28] = 0x70; + buf[29] = 0x6C; + buf[30] = 0x69; + buf[31] = 0x63; + + buf[32] = 0x61; + buf[33] = 0x74; + buf[34] = 0x69; + buf[35] = 0x6F; + + buf[36] = 0x6E; + buf[37] = 0x2F; + buf[38] = 0x76; + buf[39] = 0x6E; + + buf[40] = 0x64; + buf[41] = 0x2E; + buf[42] = 0x77; + buf[43] = 0x66; + + buf[44] = 0x61; + buf[45] = 0x2E; + buf[46] = 0x77; + buf[47] = 0x73; + + buf[48] = 0x63; + buf[49] = 0x10; + buf[50] = 0x0E; + buf[51] = 0x00; + + buf[52] = data_len + 43; + buf[53] = 0x10; + buf[54] = 0x26; + buf[55] = 0x00; + + buf[56] = 0x01; + buf[57] = 0x01; + buf[58] = 0x10; + buf[59] = 0x45; + + buf[60] = 0x00; + buf[61] = ssid_len; + memcpy(&buf[62], app->text_buf, ssid_len); + size_t ssid = 62 + ssid_len; + buf[ssid + 0] = 0x10; + buf[ssid + 1] = 0x03; + + buf[ssid + 2] = 0x00; + buf[ssid + 3] = 0x02; + buf[ssid + 4] = 0x00; + buf[ssid + 5] = + scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiAuth); + + buf[ssid + 6] = 0x10; + buf[ssid + 7] = 0x0F; + buf[ssid + 8] = 0x00; + buf[ssid + 9] = 0x02; + + buf[ssid + 10] = 0x00; + buf[ssid + 11] = + scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiEncr); + buf[ssid + 12] = 0x10; + buf[ssid + 13] = 0x27; + + buf[ssid + 14] = 0x00; + buf[ssid + 15] = pass_len; + memcpy(&buf[ssid + 16], app->pass_buf, pass_len); + size_t pass = ssid + 16 + pass_len; + buf[pass + 0] = 0x10; + buf[pass + 1] = 0x20; + + buf[pass + 2] = 0x00; + buf[pass + 3] = 0x06; + buf[pass + 4] = 0xFF; + buf[pass + 5] = 0xFF; + + buf[pass + 6] = 0xFF; + buf[pass + 7] = 0xFF; + buf[pass + 8] = 0xFF; + buf[pass + 9] = 0xFF; + + break; + } + default: + break; + } + + // Message length and terminator + buf[22] = msg_len; + size_t msg_end = 23 + msg_len; + buf[msg_end] = 0xFE; + + // Padding + for(size_t i = msg_end + 1; i < size; i++) { + buf[i] = 0x00; + } + + char str[16]; + bool ok = true; + for(size_t page = 0; page < pages; page++) { + snprintf(str, sizeof(str), "Page %u", page); + if(!flipper_format_write_hex(file, str, &buf[page * 4], 4)) { + ok = false; + break; + } + } + if(!ok) break; + + free(buf); + success = true; + + } while(false); + furi_string_free(path); + flipper_format_free(file); + furi_record_close(RECORD_STORAGE); + + if(success) { + popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); + popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); + } else { + popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); + popup_set_header(popup, "Saved!", 13, 22, AlignLeft, AlignBottom); + } + popup_set_timeout(popup, 1500); + popup_set_context(popup, app); + popup_set_callback(popup, nfc_maker_scene_result_popup_callback); + popup_enable_timeout(popup); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewPopup); +} + +bool nfc_maker_scene_result_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case PopupEventExit: + scene_manager_search_and_switch_to_previous_scene( + app->scene_manager, NfcMakerSceneMenu); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_result_on_exit(void* context) { + NfcMaker* app = context; + popup_reset(app->popup); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c new file mode 100644 index 000000000..17d84e0a9 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_text.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_text_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_text_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter Text Note:"); + + strlcpy(app->text_buf, "Lorem ipsum", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_text_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_text_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_text_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c new file mode 100644 index 000000000..e5a4996b2 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_url.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_url_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_url_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter Plain URL:"); + + strlcpy(app->text_buf, "https://google.com", TEXT_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_url_text_input_callback, + app, + app->text_buf, + TEXT_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_url_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_url_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c new file mode 100644 index 000000000..68efaf7f6 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi.c @@ -0,0 +1,55 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_wifi_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_wifi_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter WiFi SSID:"); + + strlcpy(app->text_buf, "Bill Wi the Science Fi", WIFI_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_wifi_text_input_callback, + app, + app->text_buf, + WIFI_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_wifi_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_set_scene_state( + app->scene_manager, NfcMakerSceneWifiAuth, WifiAuthenticationWpa2Personal); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiAuth); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_wifi_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c new file mode 100644 index 000000000..4cb90dabe --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_auth.c @@ -0,0 +1,83 @@ +#include "../nfc_maker.h" + +void nfc_maker_scene_wifi_auth_submenu_callback(void* context, uint32_t index) { + NfcMaker* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void nfc_maker_scene_wifi_auth_on_enter(void* context) { + NfcMaker* app = context; + Submenu* submenu = app->submenu; + + submenu_set_header(submenu, "Authentication Type:"); + + submenu_add_item( + submenu, "Open", WifiAuthenticationOpen, nfc_maker_scene_wifi_auth_submenu_callback, app); + + submenu_add_item( + submenu, + "WPA 2 Personal", + WifiAuthenticationWpa2Personal, + nfc_maker_scene_wifi_auth_submenu_callback, + app); + + submenu_add_item( + submenu, + "WPA 2 Enterprise", + WifiAuthenticationWpa2Enterprise, + nfc_maker_scene_wifi_auth_submenu_callback, + app); + + submenu_add_item( + submenu, + "WPA Personal", + WifiAuthenticationWpaPersonal, + nfc_maker_scene_wifi_auth_submenu_callback, + app); + + submenu_add_item( + submenu, + "WPA Enterprise", + WifiAuthenticationWpaEnterprise, + nfc_maker_scene_wifi_auth_submenu_callback, + app); + + submenu_add_item( + submenu, + "Shared", + WifiAuthenticationShared, + nfc_maker_scene_wifi_auth_submenu_callback, + app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiAuth)); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); +} + +bool nfc_maker_scene_wifi_auth_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneWifiAuth, event.event); + consumed = true; + if(event.event == WifiAuthenticationOpen) { + scene_manager_set_scene_state( + app->scene_manager, NfcMakerSceneWifiEncr, WifiEncryptionNone); + strcpy(app->pass_buf, ""); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + } else { + scene_manager_set_scene_state( + app->scene_manager, NfcMakerSceneWifiEncr, WifiEncryptionAes); + scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiEncr); + } + } + + return consumed; +} + +void nfc_maker_scene_wifi_auth_on_exit(void* context) { + NfcMaker* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c new file mode 100644 index 000000000..d1a21f51a --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_encr.c @@ -0,0 +1,48 @@ +#include "../nfc_maker.h" + +void nfc_maker_scene_wifi_encr_submenu_callback(void* context, uint32_t index) { + NfcMaker* app = context; + view_dispatcher_send_custom_event(app->view_dispatcher, index); +} + +void nfc_maker_scene_wifi_encr_on_enter(void* context) { + NfcMaker* app = context; + Submenu* submenu = app->submenu; + + submenu_set_header(submenu, "Encryption Type:"); + + submenu_add_item( + submenu, "AES", WifiEncryptionAes, nfc_maker_scene_wifi_encr_submenu_callback, app); + + submenu_add_item( + submenu, "WEP", WifiEncryptionWep, nfc_maker_scene_wifi_encr_submenu_callback, app); + + submenu_add_item( + submenu, "TKIP", WifiEncryptionTkip, nfc_maker_scene_wifi_encr_submenu_callback, app); + + submenu_add_item( + submenu, "None", WifiEncryptionNone, nfc_maker_scene_wifi_encr_submenu_callback, app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, NfcMakerSceneWifiEncr)); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewSubmenu); +} + +bool nfc_maker_scene_wifi_encr_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(app->scene_manager, NfcMakerSceneWifiEncr, event.event); + consumed = true; + scene_manager_next_scene(app->scene_manager, NfcMakerSceneWifiPass); + } + + return consumed; +} + +void nfc_maker_scene_wifi_encr_on_exit(void* context) { + NfcMaker* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c new file mode 100644 index 000000000..3f5b4bd76 --- /dev/null +++ b/applications/external/nfc_maker/scenes/nfc_maker_scene_wifi_pass.c @@ -0,0 +1,53 @@ +#include "../nfc_maker.h" + +enum TextInputResult { + TextInputResultOk, +}; + +static void nfc_maker_scene_wifi_pass_text_input_callback(void* context) { + NfcMaker* app = context; + + view_dispatcher_send_custom_event(app->view_dispatcher, TextInputResultOk); +} + +void nfc_maker_scene_wifi_pass_on_enter(void* context) { + NfcMaker* app = context; + TextInput* text_input = app->text_input; + + text_input_set_header_text(text_input, "Enter WiFi Password:"); + + strlcpy(app->pass_buf, "244466666", WIFI_INPUT_LEN); + + text_input_set_result_callback( + text_input, + nfc_maker_scene_wifi_pass_text_input_callback, + app, + app->pass_buf, + WIFI_INPUT_LEN, + true); + + view_dispatcher_switch_to_view(app->view_dispatcher, NfcMakerViewTextInput); +} + +bool nfc_maker_scene_wifi_pass_on_event(void* context, SceneManagerEvent event) { + NfcMaker* app = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + consumed = true; + switch(event.event) { + case TextInputResultOk: + scene_manager_next_scene(app->scene_manager, NfcMakerSceneName); + break; + default: + break; + } + } + + return consumed; +} + +void nfc_maker_scene_wifi_pass_on_exit(void* context) { + NfcMaker* app = context; + text_input_reset(app->text_input); +} diff --git a/applications/external/nfc_maker/strnlen.c b/applications/external/nfc_maker/strnlen.c new file mode 100644 index 000000000..54d183895 --- /dev/null +++ b/applications/external/nfc_maker/strnlen.c @@ -0,0 +1,11 @@ +#include "strnlen.h" + +size_t strnlen(const char* s, size_t maxlen) { + size_t len; + + for(len = 0; len < maxlen; len++, s++) { + if(!*s) break; + } + + return len; +} \ No newline at end of file diff --git a/applications/external/nfc_maker/strnlen.h b/applications/external/nfc_maker/strnlen.h new file mode 100644 index 000000000..4fe0d540c --- /dev/null +++ b/applications/external/nfc_maker/strnlen.h @@ -0,0 +1,6 @@ +#pragma once +#pragma weak strnlen + +#include + +size_t strnlen(const char* s, size_t maxlen); \ No newline at end of file diff --git a/applications/external/picopass/picopass_device.c b/applications/external/picopass/picopass_device.c index 53778cfb3..de43b0bb7 100644 --- a/applications/external/picopass/picopass_device.c +++ b/applications/external/picopass/picopass_device.c @@ -16,6 +16,7 @@ PicopassDevice* picopass_device_alloc() { PicopassDevice* picopass_dev = malloc(sizeof(PicopassDevice)); picopass_dev->dev_data.pacs.legacy = false; picopass_dev->dev_data.pacs.se_enabled = false; + picopass_dev->dev_data.pacs.elite_kdf = false; picopass_dev->dev_data.pacs.pin_length = 0; picopass_dev->storage = furi_record_open(RECORD_STORAGE); picopass_dev->dialogs = furi_record_open(RECORD_DIALOGS); @@ -77,6 +78,7 @@ static bool picopass_device_save_file( break; } } + // TODO: Add elite if(!flipper_format_write_comment_cstr(file, "Picopass blocks")) break; bool block_saved = true; @@ -256,6 +258,7 @@ void picopass_device_data_clear(PicopassDeviceData* dev_data) { } dev_data->pacs.legacy = false; dev_data->pacs.se_enabled = false; + dev_data->pacs.elite_kdf = false; dev_data->pacs.pin_length = 0; } diff --git a/applications/external/picopass/picopass_device.h b/applications/external/picopass/picopass_device.h index 7fc35ebda..b45df346c 100644 --- a/applications/external/picopass/picopass_device.h +++ b/applications/external/picopass/picopass_device.h @@ -62,6 +62,7 @@ typedef struct { bool sio; bool biometrics; uint8_t key[8]; + bool elite_kdf; uint8_t pin_length; PicopassEncryption encryption; uint8_t credential[8]; diff --git a/applications/external/picopass/picopass_worker.c b/applications/external/picopass/picopass_worker.c index 5e85e6eda..d7f7cf144 100644 --- a/applications/external/picopass/picopass_worker.c +++ b/applications/external/picopass/picopass_worker.c @@ -550,6 +550,7 @@ void picopass_worker_elite_dict_attack(PicopassWorker* picopass_worker) { if(err == ERR_NONE) { FURI_LOG_I(TAG, "Found key"); memcpy(pacs->key, key, PICOPASS_BLOCK_LEN); + pacs->elite_kdf = elite; err = picopass_read_card(AA1); if(err != ERR_NONE) { FURI_LOG_E(TAG, "picopass_read_card error %d", err); @@ -720,7 +721,7 @@ void picopass_worker_write_key(PicopassWorker* picopass_worker) { uint8_t* oldKey = AA1[PICOPASS_KD_BLOCK_INDEX].data; uint8_t newKey[PICOPASS_BLOCK_LEN] = {0}; - loclass_iclass_calc_div_key(csn, pacs->key, newKey, false); + loclass_iclass_calc_div_key(csn, pacs->key, newKey, pacs->elite_kdf); if((fuses & 0x80) == 0x80) { FURI_LOG_D(TAG, "Plain write for personalized mode key change"); diff --git a/applications/external/picopass/scenes/picopass_scene_key_menu.c b/applications/external/picopass/scenes/picopass_scene_key_menu.c index 8aac6cb24..15a32ff44 100644 --- a/applications/external/picopass/scenes/picopass_scene_key_menu.c +++ b/applications/external/picopass/scenes/picopass_scene_key_menu.c @@ -60,24 +60,28 @@ bool picopass_scene_key_menu_on_event(void* context, SceneManagerEvent event) { scene_manager_set_scene_state( picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteStandard); memcpy(picopass->dev->dev_data.pacs.key, picopass_iclass_key, PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCE) { scene_manager_set_scene_state( picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); memcpy(picopass->dev->dev_data.pacs.key, picopass_xice_key, PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = true; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCL) { scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCL); memcpy(picopass->dev->dev_data.pacs.key, picopass_xicl_key, PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } else if(event.event == SubmenuIndexWriteiCS) { scene_manager_set_scene_state( - picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCE); + picopass->scene_manager, PicopassSceneKeyMenu, SubmenuIndexWriteiCS); memcpy(picopass->dev->dev_data.pacs.key, picopass_xics_key, PICOPASS_BLOCK_LEN); + picopass->dev->dev_data.pacs.elite_kdf = false; scene_manager_next_scene(picopass->scene_manager, PicopassSceneWriteKey); consumed = true; } diff --git a/applications/external/swd_probe/swd_probe_app.c b/applications/external/swd_probe/swd_probe_app.c index 27ef03f5d..63f219508 100644 --- a/applications/external/swd_probe/swd_probe_app.c +++ b/applications/external/swd_probe/swd_probe_app.c @@ -679,7 +679,7 @@ static bool swd_apscan_test(AppFSM* const ctx, uint32_t ap) { static void swd_script_log(ScriptContext* ctx, FuriLogLevel level, const char* format, ...) { bool commandline = false; ScriptContext* cur = ctx; - char buffer[256]; + FuriString* buffer = furi_string_alloc(); va_list argp; va_start(argp, format); @@ -704,17 +704,19 @@ static void swd_script_log(ScriptContext* ctx, FuriLogLevel level, const char* f break; } - strcpy(buffer, prefix); - size_t pos = strlen(buffer); - vsnprintf(&buffer[pos], sizeof(buffer) - pos - 2, format, argp); - strcat(buffer, "\n"); - if(!usb_uart_tx_data(ctx->app->uart, (uint8_t*)buffer, strlen(buffer))) { + furi_string_cat_str(buffer, prefix); + furi_string_cat_printf(buffer, format, argp); + furi_string_cat_str(buffer, "\n"); + + if(!usb_uart_tx_data( + ctx->app->uart, (uint8_t*)furi_string_get_cstr(buffer), furi_string_size(buffer))) { DBGS("Sending via USB failed"); } } else { - LOG(buffer); + LOG(furi_string_get_cstr(buffer)); } va_end(argp); + furi_string_free(buffer); } /* read characters until newline was read */ @@ -939,41 +941,44 @@ static bool swd_scriptfunc_goto(ScriptContext* ctx) { return true; } +#include + static bool swd_scriptfunc_call(ScriptContext* ctx) { DBGS("call"); swd_script_skip_whitespace(ctx); /* fetch previous file directory */ - char filename[MAX_FILE_LENGTH]; - strncpy(filename, ctx->filename, sizeof(filename)); - char* path = strrchr(filename, '/'); - path[1] = '\000'; + FuriString* filepath = furi_string_alloc(); + path_extract_dirname(ctx->filename, filepath); + // strncpy(filename, ctx->filename, sizeof(filename)); - /* append filename */ - if(!swd_script_get_string(ctx, &path[1], sizeof(filename) - strlen(path))) { - swd_script_log(ctx, FuriLogLevelError, "failed to parse filename"); - return false; - } + char filename[MAX_FILE_LENGTH] = {}; + bool success = false; + do { + /* append filename */ + if(!swd_script_get_string(ctx, filename, sizeof(filename))) { + swd_script_log(ctx, FuriLogLevelError, "failed to parse filename"); + break; + } - swd_script_seek_newline(ctx); + swd_script_seek_newline(ctx); + /* append extension */ + furi_string_cat_str(filepath, ".swd"); - /* append extension */ - if(strlen(filename) + 5 >= sizeof(filename)) { - swd_script_log(ctx, FuriLogLevelError, "name too long"); - return false; - } + bool ret = swd_execute_script(ctx->app, furi_string_get_cstr(filepath)); - strcat(filename, ".swd"); + if(!ret) { + swd_script_log( + ctx, FuriLogLevelError, "failed to exec '%s'", furi_string_get_cstr(filepath)); + break; + } - bool ret = swd_execute_script(ctx->app, filename); + success = true; + } while(false); + furi_string_free(filepath); - if(!ret) { - swd_script_log(ctx, FuriLogLevelError, "failed to exec '%s'", filename); - return false; - } - - return true; + return success; } static bool swd_scriptfunc_status(ScriptContext* ctx) { diff --git a/applications/external/swd_probe/swd_probe_app.h b/applications/external/swd_probe/swd_probe_app.h index ff7154caf..5a45a4fd9 100644 --- a/applications/external/swd_probe/swd_probe_app.h +++ b/applications/external/swd_probe/swd_probe_app.h @@ -1,5 +1,5 @@ -#ifndef __ARHA_FLIPPERAPP_DEMO -#define __ARHA_FLIPPERAPP_DEMO +#ifndef __SWD_PROBE_APP_H +#define __SWD_PROBE_APP_H #include #include @@ -18,10 +18,6 @@ #include #include #include -#include -#include -#include -#include #include "usb_uart.h" diff --git a/applications/external/text_viewer/application.fam b/applications/external/text_viewer/application.fam index e36b7a870..6222dc643 100644 --- a/applications/external/text_viewer/application.fam +++ b/applications/external/text_viewer/application.fam @@ -10,7 +10,7 @@ App( stack_size=2 * 1024, order=20, fap_icon="icons/text_10px.png", - fap_category="Misc", + fap_category="Tools", fap_icon_assets="icons", fap_author="@kowalski7cc & @kyhwana", fap_version="1.0", diff --git a/applications/external/totp/application.fam b/applications/external/totp/application.fam index 4f71c2ce8..fcac78700 100644 --- a/applications/external/totp/application.fam +++ b/applications/external/totp/application.fam @@ -3,21 +3,13 @@ App( name="Authenticator", apptype=FlipperAppType.EXTERNAL, entry_point="totp_app", - requires=[ - "gui", - "cli", - "dialogs", - "storage", - "input", - "notification", - "bt" - ], + requires=["gui", "cli", "dialogs", "storage", "input", "notification", "bt"], stack_size=2 * 1024, order=20, fap_author="Alexander Kopachov (@akopachov)", fap_description="Software-based TOTP authenticator for Flipper Zero device", fap_weburl="https://github.com/akopachov/flipper-zero_authenticator", - fap_category="Misc", + fap_category="Tools", fap_icon_assets="images", fap_icon="totp_10px.png", fap_private_libs=[ 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/wifi_marauder_companion/LICENSE b/applications/external/wifi_marauder_companion/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/applications/external/wifi_marauder_companion/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/applications/external/wifi_marauder_companion/ReadMe.md b/applications/external/wifi_marauder_companion/ReadMe.md index fd690ece6..bc14e0f8c 100644 --- a/applications/external/wifi_marauder_companion/ReadMe.md +++ b/applications/external/wifi_marauder_companion/ReadMe.md @@ -1,8 +1,41 @@ # WiFi Marauder companion app for Flipper Zero +Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information) + ## https://github.com/0xchocolate/flipperzero-wifi-marauder -Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information) +## Get the app +1. Make sure you're logged in with a github account (otherwise the downloads in step 2 won't work) +2. Navigate to the [FAP Build](https://github.com/0xchocolate/flipperzero-wifi-marauder/actions/workflows/build.yml) + GitHub action workflow, and select the most recent run, scroll down to artifacts. +3. The FAP is built for the `dev` and `release` channels of both official and unleashed + firmware. Download the artifact corresponding to your firmware version. +4. (Optional step to avoid confusion) Go to "Apps/GPIO" on the Flipper SD Card, delete any existing Marauder app, on some firmwares there will be a `ESP32CAM_Marauder.fap` or similar. +5. Extract `esp32_wifi_marauder.fap` from the ZIP file downloaded in step 3 to your Flipper Zero SD card, preferably under Apps/GPIO along with the rest of the GPIO apps. (If you're using qFlipper to transfer files you need to extract the content of the ZIP file to your computer before you drag it to qFlipper, as qFlipper does not support direct dragging from a ZIP file (at least on Windows)). + +From a local clone of this repo, you can also build the app yourself using ufbt. + +## In-app ESP32 flasher (WIP) +Guide by [@francis2054](https://github.com/francis2054) + +The app now contains a work-in-progress of an ESP32 flasher (close to the bottom of the marauder menu). Use at your own risk. This hardcodes addresses for non-S3 ESP32 chips. + +To use this method: +1. Make sure you follow the instructions for how to get the Marauder app on your Flipper Zero, they can be found on the top of this page. Latest release needs to be downloaded and installed. +2. Go to [Justcallmekoko's firmware page](https://github.com/justcallmekoko/ESP32Marauder/wiki/update-firmware#using-spacehuhn-web-updater) and download all files necessary for the board you are flashing, most boards will want all 4 files but for the Wifi Devboard you want to download these 3 files: `0x1000` (Bootloader), `0x8000` (partitions), `0x10000` (Firmware). The `Boot App` is not needed for the Wifi Devboard with this method. The Firmware one will redirect you to the releases page where you'll need to pick the one relevant to the board you're flashing, if you are using the official Wi-Fi Devboard you want to pick the one ending in `_flipper_sd_serial.bin`. +3. Place all files downloaded in step 2 in a new folder on your desktop, the name does not matter. Rename the `_flipper_sd_serial.bin` file you downloaded in step 2 to `Firmware.bin`. +4. Now for transferring the files to the Flipper Zero, drag all the files from the folder on your desktop to the "Marauder" folder inside "apps_data" folder on the Flipper Zero SD card. Preferred method to transfer these files is plugging the SD card into your computer with an adapter, but qFlipper works as well. Insert the Flipper Zero SD Card back into the Flipper before proceeding to the next step. +5. Plug your Wi-Fi Devboard into the Flipper. +6. Press and keep holding the boot button while you press the reset button once, release the boot button after 2 seconds. +7. Open the Marauder app on your Flipper Zero, it should be named "esp32_wifi_marauder" and be located under Apps->GPIO from the main menu if you followed the instructions for how to install the app further up on this page. (You might get an API mismatch error if the Flipper firmware you are running doesn't match the files you've downloaded, you can try "Continue" anyway, otherwise the app needs to be rebuilt or you might need to update the firmware on your Flipper). +8. Press the up arrow on the Flipper three times to get to "Reflash ESP32 (WIP)" and open it. +9. For "Bootloader" scroll down in the list and select `esp32_marauder.ino.bootloader.bin`, for "Paritition table" select `esp32_marauder.ino.partitions.bin` and for "Firmware" select `Firmware.bin`. +10. Scroll down and click "[>] FLASH" and wait for it to complete. (If you get errors here, press back button once and repeat step 6 then try "[>] FLASH" again). +11. Once it says "Done flashing" on the screen, restart the Flipper and you are done :) + +## For future updates, just repeat from step 2 and only download the new "Firmware" bin + +This process will improve with future updates! :) ## Support diff --git a/applications/external/wifi_marauder_companion/application.fam b/applications/external/wifi_marauder_companion/application.fam index 59e53b725..6b3403f39 100644 --- a/applications/external/wifi_marauder_companion/application.fam +++ b/applications/external/wifi_marauder_companion/application.fam @@ -8,5 +8,22 @@ App( order=90, fap_icon="wifi_10px.png", fap_category="GPIO", + fap_private_libs=[ + Lib( + name="esp-serial-flasher", + fap_include_paths=["include"], + sources=[ + "src/esp_loader.c", + "src/esp_targets.c", + "src/md5_hash.c", + "src/protocol_common.c", + "src/protocol_uart.c", + "src/slip.c" + ], + cincludes=["lib/esp-serial-flasher/private_include"], + cdefines=["SERIAL_FLASHER_INTERFACE_UART=1", "MD5_ENABLED=1"], + ), + ], + cdefines=["SERIAL_FLASHER_INTERFACE_UART=1"], fap_icon_assets="assets", ) diff --git a/applications/external/wifi_marauder_companion/docs/README.md b/applications/external/wifi_marauder_companion/docs/README.md new file mode 100644 index 000000000..40b7a5ad0 --- /dev/null +++ b/applications/external/wifi_marauder_companion/docs/README.md @@ -0,0 +1,9 @@ +## WiFi Marauder companion app for Flipper Zero + +Requires a connected dev board running Marauder FW. See install instructions from UberGuidoZ here: https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information + +## Support + +For app feedback, bugs, and feature requests, please create an issue here: https://github.com/0xchocolate/flipperzero-wifi-marauder/issues + +You can find me (0xchocolate) on discord as @cococode. diff --git a/applications/external/wifi_marauder_companion/docs/changelog.md b/applications/external/wifi_marauder_companion/docs/changelog.md new file mode 100644 index 000000000..ae0f328e7 --- /dev/null +++ b/applications/external/wifi_marauder_companion/docs/changelog.md @@ -0,0 +1,5 @@ +## v0.4.0 + +Added Signal Monitor (thanks @justcallmekoko!) to support new sigmon command in Marauder v0.10.5: https://github.com/justcallmekoko/ESP32Marauder/releases + +Added keyboard and +5V support from unleashed (thanks @xMasterX!) diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md new file mode 100644 index 000000000..b1ae448d7 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/README.md @@ -0,0 +1,154 @@ +# esp-serial-flasher + +`esp-serial-flasher` is a portable C library for flashing or loading apps to RAM of Espressif SoCs from other host microcontrollers. + +## Using the library +Espressif SoCs are normally programmed via serial interface (UART). The port layer for the given host microcontroller has to be implemented if not available. Details can be found in section below. + +Supported **host** microcontrollers: + +- STM32 +- Raspberry Pi SBC +- ESP32 +- Any MCU running Zephyr OS + +Supported **target** microcontrollers: + +- ESP32 +- ESP8266 +- ESP32-S2 +- ESP32-S3 +- ESP32-C3 +- ESP32-C2 +- ESP32-H2 + +Supported hardware interfaces: +- UART +- SPI (only for RAM download, experimental) + +For example usage check the `examples` directory. + +## Supporting a new host target + +In order to support a new target, following functions have to be implemented by user: + +- `loader_port_read()` +- `loader_port_write()` +- `loader_port_enter_bootloader()` +- `loader_port_delay_ms()` +- `loader_port_start_timer()` +- `loader_port_remaining_time()` + +For the SPI interface ports +- `loader_port_spi_set_cs()` +needs to be implemented as well. + +The following functions are part of the [io.h](include/io.h) header for convenience, however, the user does not have to strictly follow function signatures, as there are not called directly from library. + +- `loader_port_change_transmission_rate()` +- `loader_port_reset_target()` +- `loader_port_debug_print()` + +Prototypes of all functions mentioned above can be found in [io.h](include/io.h). + +## Configuration + +These are the configuration toggles available to the user: + +* `SERIAL_FLASHER_INTERFACE_UART/SERIAL_FLASHER_INTERFACE_SPI` + +This defines the hardware interface to use. SPI interface only supports RAM download mode and is in experimental stage and can undergo changes. + +Default: SERIAL_FLASHER_INTERFACE_UART + +* `MD5_ENABLED` + +If enabled, `esp-serial-flasher` is capable of verifying flash integrity after writing to flash. + +Default: Enabled +> Warning: As ROM bootloader of the ESP8266 does not support MD5_CHECK, this option has to be disabled! + +* `SERIAL_FLASHER_RESET_HOLD_TIME_MS` + +This is the time for which the reset pin is asserted when doing a hard reset in milliseconds. + +Default: 100 + +* `SERIAL_FLASHER_BOOT_HOLD_TIME_MS` + +This is the time for which the boot pin is asserted when doing a hard reset in milliseconds. + +Default: 50 + +Configuration can be passed to `cmake` via command line: + +``` +cmake -DMD5_ENABLED=1 .. && cmake --build . +``` + +### STM32 support + +The STM32 port makes use of STM32 HAL libraries, and these do not come with CMake support. In order to compile the project, `stm32-cmake` (a `CMake` support package) has to be pulled as submodule. + +``` +git clone --recursive https://github.com/espressif/esp-serial-flasher.git +``` + +If you have cloned this repository without the `--recursive` flag, you can initialize the submodule using the following command: + +``` +git submodule update --init +``` + +In addition to configuration parameters mentioned above, following definitions has to be set: + +- TOOLCHAIN_PREFIX: path to arm toolchain (i.e /home/user/gcc-arm-none-eabi-9-2019-q4-major) +- STM32Cube_DIR: path to STM32 Cube libraries (i.e /home/user/STM32Cube/Repository/STM32Cube_FW_F4_V1.25.0) +- STM32_CHIP: name of STM32 for which project should be compiled (i.e STM32F407VG) +- PORT: STM32 + +This can be achieved by passing definitions to the command line, such as: + +``` +cmake -DTOOLCHAIN_PREFIX="/path_to_toolchain" -DSTM32Cube_DIR="path_to_stm32Cube" -DSTM32_CHIP="STM32F407VG" -DPORT="STM32" .. && cmake --build . +``` + +Alternatively, those variables can be set in the top level `cmake` directory: + +``` +set(TOOLCHAIN_PREFIX path_to_toolchain) +set(STM32Cube_DIR path_to_stm32_HAL) +set(STM32_CHIP STM32F407VG) +set(PORT STM32) +``` + +### Zephyr support + +The Zephyr port is ready to be integrated into Zephyr apps as a Zephyr module. In the manifest file (west.yml), add: + +``` + - name: esp-flasher + url: https://github.com/espressif/esp-serial-flasher + revision: master + path: modules/lib/esp_flasher +``` + +And add + +``` +CONFIG_ESP_SERIAL_FLASHER=y +CONFIG_CONSOLE_GETCHAR=y +CONFIG_SERIAL_FLASHER_MD5_ENABLED=y +``` + +to the project configuration `prj.conf`. + +For the C/C++ source code, the example code provided in `examples/zephyr_example` can be used as a starting point. + +## Licence + +Code is distributed under Apache 2.0 license. + +## Known limitations + +Size of new binary image has to be known before flashing. diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h new file mode 100644 index 000000000..43f4fb9d9 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader.h @@ -0,0 +1,313 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Used for backwards compatibility with the previous API */ +#define esp_loader_change_baudrate esp_loader_change_transmission_rate + +/** + * Macro which can be used to check the error code, + * and return in case the code is not ESP_LOADER_SUCCESS. + */ +#define RETURN_ON_ERROR(x) do { \ + esp_loader_error_t _err_ = (x); \ + if (_err_ != ESP_LOADER_SUCCESS) { \ + return _err_; \ + } \ +} while(0) + +/** + * @brief Error codes + */ +typedef enum { + ESP_LOADER_SUCCESS, /*!< Success */ + ESP_LOADER_ERROR_FAIL, /*!< Unspecified error */ + ESP_LOADER_ERROR_TIMEOUT, /*!< Timeout elapsed */ + ESP_LOADER_ERROR_IMAGE_SIZE, /*!< Image size to flash is larger than flash size */ + ESP_LOADER_ERROR_INVALID_MD5, /*!< Computed and received MD5 does not match */ + ESP_LOADER_ERROR_INVALID_PARAM, /*!< Invalid parameter passed to function */ + ESP_LOADER_ERROR_INVALID_TARGET, /*!< Connected target is invalid */ + ESP_LOADER_ERROR_UNSUPPORTED_CHIP, /*!< Attached chip is not supported */ + ESP_LOADER_ERROR_UNSUPPORTED_FUNC, /*!< Function is not supported on attached target */ + ESP_LOADER_ERROR_INVALID_RESPONSE /*!< Internal error */ +} esp_loader_error_t; + +/** + * @brief Supported targets + */ +typedef enum { + ESP8266_CHIP = 0, + ESP32_CHIP = 1, + ESP32S2_CHIP = 2, + ESP32C3_CHIP = 3, + ESP32S3_CHIP = 4, + ESP32C2_CHIP = 5, + ESP32H4_CHIP = 6, + ESP32H2_CHIP = 7, + ESP_MAX_CHIP = 8, + ESP_UNKNOWN_CHIP = 8 +} target_chip_t; + +/** + * @brief Application binary header + */ +typedef struct { + uint8_t magic; + uint8_t segments; + uint8_t flash_mode; + uint8_t flash_size_freq; + uint32_t entrypoint; +} esp_loader_bin_header_t; + +/** + * @brief Segment binary header + */ +typedef struct { + uint32_t addr; + uint32_t size; + uint8_t *data; +} esp_loader_bin_segment_t; + +/** + * @brief SPI pin configuration arguments + */ +typedef union { + struct { + uint32_t pin_clk: 6; + uint32_t pin_q: 6; + uint32_t pin_d: 6; + uint32_t pin_cs: 6; + uint32_t pin_hd: 6; + uint32_t zero: 2; + }; + uint32_t val; +} esp_loader_spi_config_t; + +/** + * @brief Connection arguments + */ +typedef struct { + uint32_t sync_timeout; /*!< Maximum time to wait for response from serial interface. */ + int32_t trials; /*!< Number of trials to connect to target. If greater than 1, + 100 millisecond delay is inserted after each try. */ +} esp_loader_connect_args_t; + +#define ESP_LOADER_CONNECT_DEFAULT() { \ + .sync_timeout = 100, \ + .trials = 10, \ +} + +/** + * @brief Connects to the target + * + * @param connect_args[in] Timing parameters to be used for connecting to target. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args); + +/** + * @brief Returns attached target chip. + * + * @warning This function can only be called after connection with target + * has been successfully established by calling esp_loader_connect(). + * + * @return One of target_chip_t + */ +target_chip_t esp_loader_get_target(void); + + +#ifdef SERIAL_FLASHER_INTERFACE_UART +/** + * @brief Initiates flash operation + * + * @param offset[in] Address from which flash operation will be performed. + * @param image_size[in] Size of the whole binary to be loaded into flash. + * @param block_size[in] Size of buffer used in subsequent calls to esp_loader_flash_write. + * + * @note image_size is size of the whole image, whereas, block_size is chunk of data sent + * to the target, each time esp_loader_flash_write function is called. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size); + +/** + * @brief Writes supplied data to target's flash memory. + * + * @param payload[in] Data to be flashed into target's memory. + * @param size[in] Size of payload in bytes. + * + * @note size must not be greater that block_size supplied to previously called + * esp_loader_flash_start function. If size is less than block_size, + * remaining bytes of payload buffer will be padded with 0xff. + * Therefore, size of payload buffer has to be equal or greater than block_size. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size); + +/** + * @brief Ends flash operation. + * + * @param reboot[in] reboot the target if true. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_flash_finish(bool reboot); +#endif /* SERIAL_FLASHER_INTERFACE_UART */ + + +/** + * @brief Initiates mem operation, initiates loading for program into target RAM + * + * @param offset[in] Address from which mem operation will be performed. + * @param size[in] Size of the whole binary to be loaded into mem. + * @param block_size[in] Size of buffer used in subsequent calls to esp_loader_mem_write. + * + * @note image_size is size of the whole image, whereas, block_size is chunk of data sent + * to the target, each time esp_mem_flash_write function is called. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size); + + +/** + * @brief Writes supplied data to target's mem memory. + * + * @param payload[in] Data to be loaded into target's memory. + * @param size[in] Size of data in bytes. + * + * @note size must not be greater that block_size supplied to previously called + * esp_loader_mem_start function. + * Therefore, size of data buffer has to be equal or greater than block_size. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size); + + +/** + * @brief Ends mem operation, finish loading for program into target RAM + * and send the entrypoint of ram_loadable app + * + * @param entrypoint[in] entrypoint of ram program. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint); + + +/** + * @brief Writes register. + * + * @param address[in] Address of register. + * @param reg_value[in] New register value. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value); + +/** + * @brief Reads register. + * + * @param address[in] Address of register. + * @param reg_value[out] Register value. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + */ +esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value); + +/** + * @brief Change baud rate. + * + * @note Baud rate has to be also adjusted accordingly on host MCU, as + * target's baud rate is changed upon return from this function. + * + * @param transmission_rate[in] new baud rate to be set. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + * - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target + */ +esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate); + +/** + * @brief Verify target's flash integrity by checking MD5. + * MD5 checksum is computed from data pushed to target's memory by calling + * esp_loader_flash_write() function and compared against target's MD5. + * Target computes checksum based on offset and image_size passed to + * esp_loader_flash_start() function. + * + * @note This function is only available if MD5_ENABLED is set. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match + * - ESP_LOADER_ERROR_TIMEOUT Timeout + * - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error + * - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target + */ +#if MD5_ENABLED +esp_loader_error_t esp_loader_flash_verify(void); +#endif +/** + * @brief Toggles reset pin. + */ +void esp_loader_reset_target(void); + + + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h new file mode 100644 index 000000000..2ff99b4f9 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/esp_loader_io.h @@ -0,0 +1,112 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #pragma once + +#include +#include "esp_loader.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Changes the transmission rate of the used peripheral. + */ +esp_loader_error_t loader_port_change_transmission_rate(uint32_t transmission_rate); + +/** + * @brief Writes data over the io interface. + * + * @param data[in] Buffer with data to be written. + * @param size[in] Size of data in bytes. + * @param timeout[in] Timeout in milliseconds. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed + */ +esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout); + +/** + * @brief Reads data from the io interface. + * + * @param data[out] Buffer into which received data will be written. + * @param size[in] Number of bytes to read. + * @param timeout[in] Timeout in milliseconds. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed + */ +esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout); + +/** + * @brief Delay in milliseconds. + * + * @param ms[in] Number of milliseconds. + * + */ +void loader_port_delay_ms(uint32_t ms); + +/** + * @brief Starts timeout timer. + * + * @param ms[in] Number of milliseconds. + * + */ +void loader_port_start_timer(uint32_t ms); + +/** + * @brief Returns remaining time since timer was started by calling esp_loader_start_timer. + * 0 if timer has elapsed. + * + * @return Number of milliseconds. + * + */ +uint32_t loader_port_remaining_time(void); + +/** + * @brief Asserts bootstrap pins to enter boot mode and toggles reset pin. + * + * @note Reset pin should stay asserted for at least 20 milliseconds. + */ +void loader_port_enter_bootloader(void); + +/** + * @brief Toggles reset pin. + * + * @note Reset pin should stay asserted for at least 20 milliseconds. + */ +void loader_port_reset_target(void); + +/** + * @brief Function can be defined by user to print debug message. + * + * @note Empty weak function is used, otherwise. + * + */ +void loader_port_debug_print(const char *str); + +#ifdef SERIAL_FLASHER_INTERFACE_SPI +/** + * @brief Sets the chip select to a defined level + */ +void loader_port_spi_set_cs(uint32_t level); +#endif /* SERIAL_FLASHER_INTERFACE_SPI */ + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h new file mode 100644 index 000000000..e34939300 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/include/serial_io.h @@ -0,0 +1,24 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#warning Please replace serial_io.h with esp_loader_io.h and change the function names \ + to match the new API + +/* Defines used to avoid breaking existing ports */ +#define loader_port_change_baudrate loader_port_change_transmission_rate +#define loader_port_serial_write loader_port_write +#define loader_port_serial_read loader_port_read + +#include "esp_loader_io.h" diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c new file mode 100644 index 000000000..a6c8687c6 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.c @@ -0,0 +1,181 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp32_port.h" +#include "driver/uart.h" +#include "driver/gpio.h" +#include "esp_timer.h" +#include "esp_log.h" +#include "esp_idf_version.h" +#include + +#ifdef SERIAL_FLASHER_DEBUG_TRACE +static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) +{ + static bool write_prev = false; + + if (write_prev != write) { + write_prev = write; + printf("\n--- %s ---\n", write ? "WRITE" : "READ"); + } + + for (uint32_t i = 0; i < size; i++) { + printf("%02x ", data[i]); + } +} +#endif + +static int64_t s_time_end; +static int32_t s_uart_port; +static int32_t s_reset_trigger_pin; +static int32_t s_gpio0_trigger_pin; + +esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config) +{ + s_uart_port = config->uart_port; + s_reset_trigger_pin = config->reset_trigger_pin; + s_gpio0_trigger_pin = config->gpio0_trigger_pin; + + // Initialize UART + uart_config_t uart_config = { + .baud_rate = config->baud_rate, + .data_bits = UART_DATA_8_BITS, + .parity = UART_PARITY_DISABLE, + .stop_bits = UART_STOP_BITS_1, + .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) + .source_clk = UART_SCLK_DEFAULT, +#endif + }; + + int rx_buffer_size = config->rx_buffer_size ? config->rx_buffer_size : 400; + int tx_buffer_size = config->tx_buffer_size ? config->tx_buffer_size : 400; + QueueHandle_t *uart_queue = config->uart_queue ? config->uart_queue : NULL; + int queue_size = config->queue_size ? config->queue_size : 0; + + if ( uart_param_config(s_uart_port, &uart_config) != ESP_OK ) { + return ESP_LOADER_ERROR_FAIL; + } + if ( uart_set_pin(s_uart_port, config->uart_tx_pin, config->uart_rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE) != ESP_OK ) { + return ESP_LOADER_ERROR_FAIL; + } + if ( uart_driver_install(s_uart_port, rx_buffer_size, tx_buffer_size, queue_size, uart_queue, 0) != ESP_OK ) { + return ESP_LOADER_ERROR_FAIL; + } + + // Initialize boot pin selection pins + gpio_reset_pin(s_reset_trigger_pin); + gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT); + + gpio_reset_pin(s_gpio0_trigger_pin); + gpio_set_pull_mode(s_gpio0_trigger_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_gpio0_trigger_pin, GPIO_MODE_OUTPUT); + + return ESP_LOADER_SUCCESS; +} + +void loader_port_esp32_deinit(void) +{ + uart_driver_delete(s_uart_port); +} + + +esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) +{ + uart_write_bytes(s_uart_port, (const char *)data, size); + esp_err_t err = uart_wait_tx_done(s_uart_port, pdMS_TO_TICKS(timeout)); + + if (err == ESP_OK) { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, size, true); +#endif + return ESP_LOADER_SUCCESS; + } else if (err == ESP_ERR_TIMEOUT) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + + +esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) +{ + int read = uart_read_bytes(s_uart_port, data, size, pdMS_TO_TICKS(timeout)); + + if (read < 0) { + return ESP_LOADER_ERROR_FAIL; + } else if (read < size) { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, read, false); +#endif + return ESP_LOADER_ERROR_TIMEOUT; + } else { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, read, false); +#endif + return ESP_LOADER_SUCCESS; + } +} + + +// Set GPIO0 LOW, then +// assert reset pin for 50 milliseconds. +void loader_port_enter_bootloader(void) +{ + gpio_set_level(s_gpio0_trigger_pin, 0); + loader_port_reset_target(); + loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); + gpio_set_level(s_gpio0_trigger_pin, 1); +} + + +void loader_port_reset_target(void) +{ + gpio_set_level(s_reset_trigger_pin, 0); + loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); + gpio_set_level(s_reset_trigger_pin, 1); +} + + +void loader_port_delay_ms(uint32_t ms) +{ + usleep(ms * 1000); +} + + +void loader_port_start_timer(uint32_t ms) +{ + s_time_end = esp_timer_get_time() + ms * 1000; +} + + +uint32_t loader_port_remaining_time(void) +{ + int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000; + return (remaining > 0) ? (uint32_t)remaining : 0; +} + + +void loader_port_debug_print(const char *str) +{ + printf("DEBUG: %s\n", str); +} + +esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) +{ + esp_err_t err = uart_set_baudrate(s_uart_port, baudrate); + return (err == ESP_OK) ? ESP_LOADER_SUCCESS : ESP_LOADER_ERROR_FAIL; +} \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h new file mode 100644 index 000000000..c098762d2 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_port.h @@ -0,0 +1,59 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #pragma once + +#include "esp_loader_io.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + uint32_t baud_rate; /*!< Initial baud rate, can be changed later */ + uint32_t uart_port; /*!< UART port */ + uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */ + uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */ + uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */ + uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */ + uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */ + uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */ + uint32_t queue_size; /*!< Set to zero for default UART queue size */ + QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not + necessary. Otherwise, it will be assigned here */ +} loader_esp32_config_t; + +/** + * @brief Initializes serial interface. + * + * @param baud_rate[in] Communication speed. + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_FAIL Initialization failure + */ +esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config); + +/** + * @brief Deinitialize serial interface. + */ +void loader_port_esp32_deinit(void); + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c new file mode 100644 index 000000000..55e8f3e57 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.c @@ -0,0 +1,298 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp32_spi_port.h" +#include "esp_log.h" +#include "driver/gpio.h" +#include "esp_timer.h" +#include "esp_log.h" +#include "esp_idf_version.h" +#include + +// #define SERIAL_DEBUG_ENABLE + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0) +#define DMA_CHAN SPI_DMA_CH_AUTO +#else +#define DMA_CHAN 1 +#endif + +#define WORD_ALIGNED(ptr) ((size_t)ptr % sizeof(size_t) == 0) + +#ifdef SERIAL_DEBUG_ENABLE + +static void dec_to_hex_str(const uint8_t dec, uint8_t hex_str[3]) +{ + static const uint8_t dec_to_hex[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + hex_str[0] = dec_to_hex[dec >> 4]; + hex_str[1] = dec_to_hex[dec & 0xF]; + hex_str[2] = '\0'; +} + +static void serial_debug_print(const uint8_t *data, uint16_t size, bool write) +{ + static bool write_prev = false; + uint8_t hex_str[3]; + + if(write_prev != write) { + write_prev = write; + printf("\n--- %s ---\n", write ? "WRITE" : "READ"); + } + + for(uint32_t i = 0; i < size; i++) { + dec_to_hex_str(data[i], hex_str); + printf("%s ", hex_str); + } +} + +#else +static void serial_debug_print(const uint8_t *data, uint16_t size, bool write) { } +#endif + +static spi_host_device_t s_spi_bus; +static spi_bus_config_t s_spi_config; +static spi_device_handle_t s_device_h; +static spi_device_interface_config_t s_device_config; +static int64_t s_time_end; +static uint32_t s_reset_trigger_pin; +static uint32_t s_strap_bit0_pin; +static uint32_t s_strap_bit1_pin; +static uint32_t s_strap_bit2_pin; +static uint32_t s_strap_bit3_pin; +static uint32_t s_spi_cs_pin; + +esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config) +{ + /* Initialize the global static variables*/ + s_spi_bus = config->spi_bus; + s_reset_trigger_pin = config->reset_trigger_pin; + s_strap_bit0_pin = config->strap_bit0_pin; + s_strap_bit1_pin = config->strap_bit1_pin; + s_strap_bit2_pin = config->strap_bit2_pin; + s_strap_bit3_pin = config->strap_bit3_pin; + s_spi_cs_pin = config->spi_cs_pin; + + /* Configure and initialize the SPI bus*/ + s_spi_config.mosi_io_num = config->spi_mosi_pin; + s_spi_config.miso_io_num = config->spi_miso_pin; + s_spi_config.sclk_io_num = config->spi_clk_pin; + s_spi_config.quadwp_io_num = config->spi_quadwp_pin; + s_spi_config.quadhd_io_num = config->spi_quadhd_pin; + s_spi_config.max_transfer_sz = 4096 * 4; + + if (spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN) != ESP_OK) { + return ESP_LOADER_ERROR_FAIL; + } + + /* Configure and add the device */ + s_device_config.clock_speed_hz = config->frequency; + s_device_config.spics_io_num = -1; /* We're using the chip select pin as GPIO as we need to + chain multiple transactions with CS pulled down */ + s_device_config.flags = SPI_DEVICE_HALFDUPLEX; + s_device_config.queue_size = 16; + + if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) { + return ESP_LOADER_ERROR_FAIL; + } + + /* Initialize the pins except for the strapping ones */ + gpio_reset_pin(s_reset_trigger_pin); + gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT); + gpio_set_level(s_reset_trigger_pin, 1); + + gpio_reset_pin(s_spi_cs_pin); + gpio_set_pull_mode(s_spi_cs_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_spi_cs_pin, GPIO_MODE_OUTPUT); + gpio_set_level(s_spi_cs_pin, 1); + + return ESP_LOADER_SUCCESS; +} + + +void loader_port_esp32_spi_deinit(void) +{ + gpio_reset_pin(s_reset_trigger_pin); + gpio_reset_pin(s_spi_cs_pin); + spi_bus_remove_device(s_device_h); + spi_bus_free(s_spi_bus); +} + + +void loader_port_spi_set_cs(const uint32_t level) { + gpio_set_level(s_spi_cs_pin, level); +} + + +esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout) +{ + /* Due to the fact that the SPI driver uses DMA for larger transfers, + and the DMA requirements, the buffer must be word aligned */ + if (data == NULL || !WORD_ALIGNED(data)) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + serial_debug_print(data, size, true); + + spi_transaction_t transaction = { + .tx_buffer = data, + .rx_buffer = NULL, + .length = size * 8U, + .rxlength = 0, + }; + + esp_err_t err = spi_device_transmit(s_device_h, &transaction); + + if (err == ESP_OK) { + serial_debug_print(data, size, false); + return ESP_LOADER_SUCCESS; + } else if (err == ESP_ERR_TIMEOUT) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + + +esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout) +{ + /* Due to the fact that the SPI driver uses DMA for larger transfers, + and the DMA requirements, the buffer must be word aligned */ + if (data == NULL || !WORD_ALIGNED(data)) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + serial_debug_print(data, size, true); + + spi_transaction_t transaction = { + .tx_buffer = NULL, + .rx_buffer = data, + .rxlength = size * 8, + }; + + esp_err_t err = spi_device_transmit(s_device_h, &transaction); + + if (err == ESP_OK) { + serial_debug_print(data, size, false); + return ESP_LOADER_SUCCESS; + } else if (err == ESP_ERR_TIMEOUT) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + + +void loader_port_enter_bootloader(void) +{ + /* + We have to initialize the GPIO pins for the target strapping pins here, + as they may overlap with target SPI pins. + For instance in the case of ESP32C3 MISO and strapping bit 0 pins overlap. + */ + spi_bus_remove_device(s_device_h); + spi_bus_free(s_spi_bus); + + gpio_reset_pin(s_strap_bit0_pin); + gpio_set_pull_mode(s_strap_bit0_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_strap_bit0_pin, GPIO_MODE_OUTPUT); + + gpio_reset_pin(s_strap_bit1_pin); + gpio_set_pull_mode(s_strap_bit1_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_strap_bit1_pin, GPIO_MODE_OUTPUT); + + gpio_reset_pin(s_strap_bit2_pin); + gpio_set_pull_mode(s_strap_bit2_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_strap_bit2_pin, GPIO_MODE_OUTPUT); + + gpio_reset_pin(s_strap_bit3_pin); + gpio_set_pull_mode(s_strap_bit3_pin, GPIO_PULLUP_ONLY); + gpio_set_direction(s_strap_bit3_pin, GPIO_MODE_OUTPUT); + + /* Set the strapping pins and perform the reset sequence */ + gpio_set_level(s_strap_bit0_pin, 1); + gpio_set_level(s_strap_bit1_pin, 0); + gpio_set_level(s_strap_bit2_pin, 0); + gpio_set_level(s_strap_bit3_pin, 0); + loader_port_reset_target(); + loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); + gpio_set_level(s_strap_bit3_pin, 1); + gpio_set_level(s_strap_bit0_pin, 0); + + /* Disable the strapping pins so they can be used by the slave later */ + gpio_reset_pin(s_strap_bit0_pin); + gpio_reset_pin(s_strap_bit1_pin); + gpio_reset_pin(s_strap_bit2_pin); + gpio_reset_pin(s_strap_bit3_pin); + + /* Restore the SPI bus pins */ + spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN); + spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h); +} + + +void loader_port_reset_target(void) +{ + gpio_set_level(s_reset_trigger_pin, 0); + loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); + gpio_set_level(s_reset_trigger_pin, 1); +} + + +void loader_port_delay_ms(const uint32_t ms) +{ + usleep(ms * 1000); +} + + +void loader_port_start_timer(const uint32_t ms) +{ + s_time_end = esp_timer_get_time() + ms * 1000; +} + + +uint32_t loader_port_remaining_time(void) +{ + int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000; + return (remaining > 0) ? (uint32_t)remaining : 0; +} + + +void loader_port_debug_print(const char *str) +{ + printf("DEBUG: %s\n", str); +} + + +esp_loader_error_t loader_port_change_transmission_rate(const uint32_t frequency) +{ + if (spi_bus_remove_device(s_device_h) != ESP_OK) { + return ESP_LOADER_ERROR_FAIL; + } + + uint32_t old_frequency = s_device_config.clock_speed_hz; + s_device_config.clock_speed_hz = frequency; + + if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) { + s_device_config.clock_speed_hz = old_frequency; + return ESP_LOADER_ERROR_FAIL; + } + + return ESP_LOADER_SUCCESS; +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h new file mode 100644 index 000000000..72304c5df --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/esp32_spi_port.h @@ -0,0 +1,60 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + #pragma once + +#include "esp_loader_io.h" +#include "driver/spi_master.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + spi_host_device_t spi_bus; + uint32_t frequency; + uint32_t spi_clk_pin; + uint32_t spi_miso_pin; + uint32_t spi_mosi_pin; + uint32_t spi_cs_pin; + uint32_t spi_quadwp_pin; + uint32_t spi_quadhd_pin; + uint32_t reset_trigger_pin; + uint32_t strap_bit0_pin; + uint32_t strap_bit1_pin; + uint32_t strap_bit2_pin; + uint32_t strap_bit3_pin; +} loader_esp32_spi_config_t; + +/** + * @brief Initializes the SPI interface. + * + * @param config[in] Configuration structure + * + * @return + * - ESP_LOADER_SUCCESS Success + * - ESP_LOADER_ERROR_FAIL Initialization failure + */ +esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config); + +/** + * @brief Deinitializes the SPI interface. + */ +void loader_port_esp32_spi_deinit(void); + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c new file mode 100644 index 000000000..d733db702 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.c @@ -0,0 +1,302 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_loader_io.h" +#include "protocol.h" +#include +#include "raspberry_port.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef SERIAL_FLASHER_DEBUG_TRACE +static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) +{ + static bool write_prev = false; + + if (write_prev != write) { + write_prev = write; + printf("\n--- %s ---\n", write ? "WRITE" : "READ"); + } + + for (uint32_t i = 0; i < size; i++) { + printf("%02x ", data[i]); + } +} +#endif + +static int serial; +static int64_t s_time_end; +static int32_t s_reset_trigger_pin; +static int32_t s_gpio0_trigger_pin; + + +static speed_t convert_baudrate(int baud) +{ + switch (baud) { + case 50: return B50; + case 75: return B75; + case 110: return B110; + case 134: return B134; + case 150: return B150; + case 200: return B200; + case 300: return B300; + case 600: return B600; + case 1200: return B1200; + case 1800: return B1800; + case 2400: return B2400; + case 4800: return B4800; + case 9600: return B9600; + case 19200: return B19200; + case 38400: return B38400; + case 57600: return B57600; + case 115200: return B115200; + case 230400: return B230400; + case 460800: return B460800; + case 500000: return B500000; + case 576000: return B576000; + case 921600: return B921600; + case 1000000: return B1000000; + case 1152000: return B1152000; + case 1500000: return B1500000; + case 2000000: return B2000000; + case 2500000: return B2500000; + case 3000000: return B3000000; + case 3500000: return B3500000; + case 4000000: return B4000000; + default: return -1; + } +} + +static int serialOpen (const char *device, uint32_t baudrate) +{ + struct termios options; + int status, fd; + + if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1) { + printf("Error occured while opening serial port !\n"); + return -1 ; + } + + fcntl (fd, F_SETFL, O_RDWR) ; + + // Get and modify current options: + + tcgetattr (fd, &options); + speed_t baud = convert_baudrate(baudrate); + + if(baud < 0) { + printf("Invalid baudrate!\n"); + return -1; + } + + cfmakeraw (&options) ; + cfsetispeed (&options, baud) ; + cfsetospeed (&options, baud) ; + + options.c_cflag |= (CLOCAL | CREAD) ; + options.c_cflag &= ~(PARENB | CSTOPB | CSIZE) ; + options.c_cflag |= CS8 ; + options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ; + options.c_oflag &= ~OPOST ; + options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl + options.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable any special handling of received bytes + + options.c_cc [VMIN] = 0 ; + options.c_cc [VTIME] = 10 ; // 1 Second + + tcsetattr (fd, TCSANOW, &options) ; + + ioctl (fd, TIOCMGET, &status); + + status |= TIOCM_DTR ; + status |= TIOCM_RTS ; + + ioctl (fd, TIOCMSET, &status); + + usleep (10000) ; // 10mS + + return fd ; +} + +static esp_loader_error_t change_baudrate(int file_desc, int baudrate) +{ + struct termios options; + speed_t baud = convert_baudrate(baudrate); + + if(baud < 0) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + tcgetattr (file_desc, &options); + + cfmakeraw (&options) ; + cfsetispeed (&options, baud); + cfsetospeed (&options, baud); + + tcsetattr (file_desc, TCSANOW, &options); + + return ESP_LOADER_SUCCESS; +} + +static void set_timeout(uint32_t timeout) +{ + struct termios options; + + timeout /= 100; + timeout = MAX(timeout, 1); + + tcgetattr(serial, &options); + options.c_cc[VTIME] = timeout; + tcsetattr(serial, TCSANOW, &options); +} + +static esp_loader_error_t read_char(char *c, uint32_t timeout) +{ + set_timeout(timeout); + int read_bytes = read(serial, c, 1); + + if (read_bytes == 1) { + return ESP_LOADER_SUCCESS; + } else if (read_bytes == 0) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + +static esp_loader_error_t read_data(char *buffer, uint32_t size) +{ + for (int i = 0; i < size; i++) { + uint32_t remaining_time = loader_port_remaining_time(); + RETURN_ON_ERROR( read_char(&buffer[i], remaining_time) ); + } + + return ESP_LOADER_SUCCESS; +} + +esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config) +{ + s_reset_trigger_pin = config->reset_trigger_pin; + s_gpio0_trigger_pin = config->gpio0_trigger_pin; + + serial = serialOpen(config->device, config->baudrate); + if (serial < 0) { + printf("Serial port could not be opened!\n"); + return ESP_LOADER_ERROR_FAIL; + } + + if (gpioInitialise() < 0) { + printf("pigpio initialisation failed\n"); + return ESP_LOADER_ERROR_FAIL; + } + + gpioSetMode(config->reset_trigger_pin, PI_OUTPUT); + gpioSetMode(config->gpio0_trigger_pin, PI_OUTPUT); + + return ESP_LOADER_SUCCESS; +} + + +esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) +{ + int written = write(serial, data, size); + + if (written < 0) { + return ESP_LOADER_ERROR_FAIL; + } else if (written < size) { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, written, true); +#endif + return ESP_LOADER_ERROR_TIMEOUT; + } else { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, written, true); +#endif + return ESP_LOADER_SUCCESS; + } +} + + +esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) +{ + RETURN_ON_ERROR( read_data(data, size) ); + +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, size, false); +#endif + + return ESP_LOADER_SUCCESS; +} + + +// Set GPIO0 LOW, then assert reset pin for 50 milliseconds. +void loader_port_enter_bootloader(void) +{ + gpioWrite(s_gpio0_trigger_pin, 0); + loader_port_reset_target(); + loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); + gpioWrite(s_gpio0_trigger_pin, 1); +} + + +void loader_port_reset_target(void) +{ + gpioWrite(s_reset_trigger_pin, 0); + loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS); + gpioWrite(s_reset_trigger_pin, 1); +} + + +void loader_port_delay_ms(uint32_t ms) +{ + usleep(ms * 1000); +} + + +void loader_port_start_timer(uint32_t ms) +{ + s_time_end = clock() + (ms * (CLOCKS_PER_SEC / 1000)); +} + + +uint32_t loader_port_remaining_time(void) +{ + int64_t remaining = (s_time_end - clock()) / 1000; + return (remaining > 0) ? (uint32_t)remaining : 0; +} + + +void loader_port_debug_print(const char *str) +{ + printf("DEBUG: %s\n", str); +} + +esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) +{ + return change_baudrate(serial, baudrate); +} \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h new file mode 100644 index 000000000..803ab72dd --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/raspberry_port.h @@ -0,0 +1,36 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include "esp_loader_io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + const char *device; + uint32_t baudrate; + uint32_t reset_trigger_pin; + uint32_t gpio0_trigger_pin; +} loader_raspberry_config_t; + +esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config); + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c new file mode 100644 index 000000000..716c9c91b --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.c @@ -0,0 +1,140 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "stm32_port.h" + +static UART_HandleTypeDef *uart; +static GPIO_TypeDef* gpio_port_io0, *gpio_port_rst; +static uint16_t gpio_num_io0, gpio_num_rst; + +#ifdef SERIAL_FLASHER_DEBUG_TRACE +static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) +{ + static bool write_prev = false; + + if (write_prev != write) { + write_prev = write; + printf("\n--- %s ---\n", write ? "WRITE" : "READ"); + } + + for (uint32_t i = 0; i < size; i++) { + printf("%02x ", data[i]); + } +} +#endif + +static uint32_t s_time_end; + +esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout) +{ + HAL_StatusTypeDef err = HAL_UART_Transmit(uart, (uint8_t *)data, size, timeout); + + if (err == HAL_OK) { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, size, true); +#endif + return ESP_LOADER_SUCCESS; + } else if (err == HAL_TIMEOUT) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + + +esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout) +{ + HAL_StatusTypeDef err = HAL_UART_Receive(uart, data, size, timeout); + + if (err == HAL_OK) { +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, size, false); +#endif + return ESP_LOADER_SUCCESS; + } else if (err == HAL_TIMEOUT) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_ERROR_FAIL; + } +} + +void loader_port_stm32_init(loader_stm32_config_t *config) + +{ + uart = config->huart; + gpio_port_io0 = config->port_io0; + gpio_port_rst = config->port_rst; + gpio_num_io0 = config->pin_num_io0; + gpio_num_rst = config->pin_num_rst; +} + +// Set GPIO0 LOW, then +// assert reset pin for 100 milliseconds. +void loader_port_enter_bootloader(void) +{ + HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_RESET); + loader_port_reset_target(); + HAL_Delay(SERIAL_FLASHER_BOOT_HOLD_TIME_MS); + HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_SET); +} + + +void loader_port_reset_target(void) +{ + HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_RESET); + HAL_Delay(SERIAL_FLASHER_RESET_HOLD_TIME_MS); + HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_SET); +} + + +void loader_port_delay_ms(uint32_t ms) +{ + HAL_Delay(ms); +} + + +void loader_port_start_timer(uint32_t ms) +{ + s_time_end = HAL_GetTick() + ms; +} + + +uint32_t loader_port_remaining_time(void) +{ + int32_t remaining = s_time_end - HAL_GetTick(); + return (remaining > 0) ? (uint32_t)remaining : 0; +} + + +void loader_port_debug_print(const char *str) +{ + printf("DEBUG: %s", str); +} + +esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) +{ + uart->Init.BaudRate = baudrate; + + if( HAL_UART_Init(uart) != HAL_OK ) { + return ESP_LOADER_ERROR_FAIL; + } + + return ESP_LOADER_SUCCESS; +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h new file mode 100644 index 000000000..a3a89a733 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/stm32_port.h @@ -0,0 +1,38 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include "esp_loader_io.h" +#include "stm32f4xx_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + UART_HandleTypeDef *huart; + GPIO_TypeDef *port_io0; + uint16_t pin_num_io0; + GPIO_TypeDef *port_rst; + uint16_t pin_num_rst; +} loader_stm32_config_t; + +void loader_port_stm32_init(loader_stm32_config_t *config); + +#ifdef __cplusplus +} +#endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c new file mode 100644 index 000000000..21270ba0a --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.c @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "zephyr_port.h" +#include +#include + +static const struct device *uart_dev; +static struct gpio_dt_spec enable_spec; +static struct gpio_dt_spec boot_spec; + +static struct tty_serial tty; +static char tty_rx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE]; +static char tty_tx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE]; + +#ifdef SERIAL_FLASHER_DEBUG_TRACE +static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write) +{ + static bool write_prev = false; + + if (write_prev != write) { + write_prev = write; + printk("\n--- %s ---\n", write ? "WRITE" : "READ"); + } + + for (uint32_t i = 0; i < size; i++) { + printk("%02x ", data[i]); + } +} +#endif + +esp_loader_error_t configure_tty() +{ + if (tty_init(&tty, uart_dev) < 0 || + tty_set_rx_buf(&tty, tty_rx_buf, sizeof(tty_rx_buf)) < 0 || + tty_set_tx_buf(&tty, tty_tx_buf, sizeof(tty_tx_buf)) < 0) { + return ESP_LOADER_ERROR_FAIL; + } + + return ESP_LOADER_SUCCESS; +} + +esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout) +{ + if (!device_is_ready(uart_dev) || data == NULL || size == 0) { + return ESP_LOADER_ERROR_FAIL; + } + + ssize_t total_read = 0; + ssize_t remaining = size; + + tty_set_rx_timeout(&tty, timeout); + while (remaining > 0) { + const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ? + remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE; + ssize_t read = tty_read(&tty, &data[total_read], chunk_size); + if (read < 0) { + return ESP_LOADER_ERROR_TIMEOUT; + } +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, read, false); +#endif + total_read += read; + remaining -= read; + } + + return ESP_LOADER_SUCCESS; +} + +esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout) +{ + if (!device_is_ready(uart_dev) || data == NULL || size == 0) { + return ESP_LOADER_ERROR_FAIL; + } + + ssize_t total_written = 0; + ssize_t remaining = size; + + tty_set_tx_timeout(&tty, timeout); + while (remaining > 0) { + const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ? + remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE; + ssize_t written = tty_write(&tty, &data[total_written], chunk_size); + if (written < 0) { + return ESP_LOADER_ERROR_TIMEOUT; + } +#ifdef SERIAL_FLASHER_DEBUG_TRACE + transfer_debug_print(data, written, true); +#endif + total_written += written; + remaining -= written; + } + + return ESP_LOADER_SUCCESS; +} + +esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config) +{ + uart_dev = config->uart_dev; + enable_spec = config->enable_spec; + boot_spec = config->boot_spec; + return configure_tty(); +} + +void loader_port_reset_target(void) +{ + gpio_pin_set_dt(&enable_spec, false); + loader_port_delay_ms(CONFIG_SERIAL_FLASHER_RESET_HOLD_TIME_MS); + gpio_pin_set_dt(&enable_spec, true); +} + +void loader_port_enter_bootloader(void) +{ + gpio_pin_set_dt(&boot_spec, false); + loader_port_reset_target(); + loader_port_delay_ms(CONFIG_SERIAL_FLASHER_BOOT_HOLD_TIME_MS); + gpio_pin_set_dt(&boot_spec, true); +} + +void loader_port_delay_ms(uint32_t ms) +{ + k_msleep(ms); +} + +static uint64_t s_time_end; + +void loader_port_start_timer(uint32_t ms) +{ + s_time_end = sys_clock_timeout_end_calc(Z_TIMEOUT_MS(ms)); +} + +uint32_t loader_port_remaining_time(void) +{ + int64_t remaining = k_ticks_to_ms_floor64(s_time_end - k_uptime_ticks()); + return (remaining > 0) ? (uint32_t)remaining : 0; +} + +esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate) +{ + struct uart_config uart_config; + + if (!device_is_ready(uart_dev)) { + return ESP_LOADER_ERROR_FAIL; + } + + if (uart_config_get(uart_dev, &uart_config) != 0) { + return ESP_LOADER_ERROR_FAIL; + } + uart_config.baudrate = baudrate; + + if (uart_configure(uart_dev, &uart_config) != 0) { + return ESP_LOADER_ERROR_FAIL; + } + + /* bitrate-change can require tty re-configuration */ + return configure_tty(); +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h new file mode 100644 index 000000000..0b104e375 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/port/zephyr_port.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "esp_loader_io.h" +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + const struct device *uart_dev; + const struct gpio_dt_spec enable_spec; + const struct gpio_dt_spec boot_spec; +} loader_zephyr_config_t; + +esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config); + +#ifdef __cplusplus +} +#endif + diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h new file mode 100644 index 000000000..cf8af91fa --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/esp_targets.h @@ -0,0 +1,33 @@ +/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include "esp_loader.h" + +typedef struct { + uint32_t cmd; + uint32_t usr; + uint32_t usr1; + uint32_t usr2; + uint32_t w0; + uint32_t mosi_dlen; + uint32_t miso_dlen; +} target_registers_t; + +esp_loader_error_t loader_detect_chip(target_chip_t *target, const target_registers_t **regs); +esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config); +bool encryption_in_begin_flash_cmd(target_chip_t target); \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h new file mode 100644 index 000000000..eb5738c8b --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/md5_hash.h @@ -0,0 +1,28 @@ +/* + * MD5 hash implementation and interface functions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); +void MD5Final(unsigned char digest[16], struct MD5Context *context); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h new file mode 100644 index 000000000..fb8b086fd --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol.h @@ -0,0 +1,230 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include "esp_loader.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define STATUS_FAILURE 1 +#define STATUS_SUCCESS 0 + +#define READ_DIRECTION 1 +#define WRITE_DIRECTION 0 + +#define MD5_SIZE 32 + +typedef enum __attribute__((packed)) +{ + FLASH_BEGIN = 0x02, + FLASH_DATA = 0x03, + FLASH_END = 0x04, + MEM_BEGIN = 0x05, + MEM_END = 0x06, + MEM_DATA = 0x07, + SYNC = 0x08, + WRITE_REG = 0x09, + READ_REG = 0x0a, + + SPI_SET_PARAMS = 0x0b, + SPI_ATTACH = 0x0d, + CHANGE_BAUDRATE = 0x0f, + FLASH_DEFL_BEGIN = 0x10, + FLASH_DEFL_DATA = 0x11, + FLASH_DEFL_END = 0x12, + SPI_FLASH_MD5 = 0x13, +} command_t; + +typedef enum __attribute__((packed)) +{ + RESPONSE_OK = 0x00, + INVALID_COMMAND = 0x05, // parameters or length field is invalid + COMMAND_FAILED = 0x06, // Failed to act on received message + INVALID_CRC = 0x07, // Invalid CRC in message + FLASH_WRITE_ERR = 0x08, // After writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned. + FLASH_READ_ERR = 0x09, // SPI read failed + READ_LENGTH_ERR = 0x0a, // SPI read request length is too long + DEFLATE_ERROR = 0x0b, // ESP32 compressed uploads only +} error_code_t; + +typedef struct __attribute__((packed)) +{ + uint8_t direction; + uint8_t command; // One of command_t + uint16_t size; + uint32_t checksum; +} command_common_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t erase_size; + uint32_t packet_count; + uint32_t packet_size; + uint32_t offset; + uint32_t encrypted; +} flash_begin_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t data_size; + uint32_t sequence_number; + uint32_t zero_0; + uint32_t zero_1; +} data_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t stay_in_loader; +} flash_end_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t total_size; + uint32_t blocks; + uint32_t block_size; + uint32_t offset; +} mem_begin_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t stay_in_loader; + uint32_t entry_point_address; +} mem_end_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint8_t sync_sequence[36]; +} sync_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t address; + uint32_t value; + uint32_t mask; + uint32_t delay_us; +} write_reg_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t address; +} read_reg_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t configuration; + uint32_t zero; // ESP32 ROM only +} spi_attach_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t new_baudrate; + uint32_t old_baudrate; +} change_baudrate_command_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t address; + uint32_t size; + uint32_t reserved_0; + uint32_t reserved_1; +} spi_flash_md5_command_t; + +typedef struct __attribute__((packed)) +{ + uint8_t direction; + uint8_t command; // One of command_t + uint16_t size; + uint32_t value; +} common_response_t; + +typedef struct __attribute__((packed)) +{ + uint8_t failed; + uint8_t error; +} response_status_t; + +typedef struct __attribute__((packed)) +{ + common_response_t common; + response_status_t status; +} response_t; + +typedef struct __attribute__((packed)) +{ + common_response_t common; + uint8_t md5[MD5_SIZE]; // ROM only + response_status_t status; +} rom_md5_response_t; + +typedef struct __attribute__((packed)) +{ + command_common_t common; + uint32_t id; + uint32_t total_size; + uint32_t block_size; + uint32_t sector_size; + uint32_t page_size; + uint32_t status_mask; +} write_spi_command_t; + +esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args); + +#ifdef SERIAL_FLASHER_INTERFACE_UART +esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, uint32_t erase_size, uint32_t block_size, uint32_t blocks_to_write, bool encryption); + +esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size); + +esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader); + +esp_loader_error_t loader_sync_cmd(void); + +esp_loader_error_t loader_spi_attach_cmd(uint32_t config); + +esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out); + +esp_loader_error_t loader_spi_parameters(uint32_t total_size); +#endif /* SERIAL_FLASHER_INTERFACE_UART */ + +esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size); + +esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size); + +esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint); + +esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, uint32_t mask, uint32_t delay_us); + +esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg); + +esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h new file mode 100644 index 000000000..3b9575606 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/protocol_prv.h @@ -0,0 +1,31 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include "esp_loader.h" +#include "protocol.h" + +void log_loader_internal_error(error_code_t error); + +esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value); + +esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, + const void *data, size_t data_size); + +esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]); diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h new file mode 100644 index 000000000..00f1f7d0d --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/private_include/slip.h @@ -0,0 +1,28 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "esp_loader.h" +#include +#include + +esp_loader_error_t SLIP_receive_data(uint8_t *buff, size_t size); + +esp_loader_error_t SLIP_receive_packet(uint8_t *buff, size_t size); + +esp_loader_error_t SLIP_send(const uint8_t *data, size_t size); + +esp_loader_error_t SLIP_send_delimiter(void); diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c new file mode 100644 index 000000000..6ef32673c --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_loader.c @@ -0,0 +1,415 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "protocol.h" +#include "esp_loader_io.h" +#include "esp_loader.h" +#include "esp_targets.h" +#include "md5_hash.h" +#include +#include + +#ifndef MAX +#define MAX(a, b) ((a) > (b)) ? (a) : (b) +#endif + +#ifndef MIN +#define MIN(a, b) ((a) < (b)) ? (a) : (b) +#endif + +#ifndef ROUNDUP +#define ROUNDUP(a, b) (((int)a + (int)b - 1) / (int)b) +#endif + +static const uint32_t DEFAULT_TIMEOUT = 1000; +static const uint32_t DEFAULT_FLASH_TIMEOUT = 3000; // timeout for most flash operations +static const uint32_t LOAD_RAM_TIMEOUT_PER_MB = 2000000; // timeout (per megabyte) for erasing a region + +typedef enum { + SPI_FLASH_READ_ID = 0x9F +} spi_flash_cmd_t; + +static const target_registers_t *s_reg = NULL; +static target_chip_t s_target = ESP_UNKNOWN_CHIP; + +#if MD5_ENABLED + +static const uint32_t MD5_TIMEOUT_PER_MB = 800; +static struct MD5Context s_md5_context; +static uint32_t s_start_address; +static uint32_t s_image_size; + +static inline void init_md5(uint32_t address, uint32_t size) +{ + s_start_address = address; + s_image_size = size; + MD5Init(&s_md5_context); +} + +static inline void md5_update(const uint8_t *data, uint32_t size) +{ + MD5Update(&s_md5_context, data, size); +} + +static inline void md5_final(uint8_t digets[16]) +{ + MD5Final(digets, &s_md5_context); +} + +#else + +static inline void init_md5(uint32_t address, uint32_t size) { } +static inline void md5_update(const uint8_t *data, uint32_t size) { } +static inline void md5_final(uint8_t digets[16]) { } + +#endif + + +static uint32_t timeout_per_mb(uint32_t size_bytes, uint32_t time_per_mb) +{ + uint32_t timeout = time_per_mb * (size_bytes / 1e6); + return MAX(timeout, DEFAULT_FLASH_TIMEOUT); +} + +esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args) +{ + loader_port_enter_bootloader(); + + RETURN_ON_ERROR(loader_initialize_conn(connect_args)); + + RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg)); + +#ifdef SERIAL_FLASHER_INTERFACE_UART + esp_loader_error_t err; + uint32_t spi_config; + if (s_target == ESP8266_CHIP) { + err = loader_flash_begin_cmd(0, 0, 0, 0, s_target); + } else { + RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) ); + loader_port_start_timer(DEFAULT_TIMEOUT); + err = loader_spi_attach_cmd(spi_config); + } + return err; +#endif /* SERIAL_FLASHER_INTERFACE_UART */ + return ESP_LOADER_SUCCESS; +} + +target_chip_t esp_loader_get_target(void) +{ + return s_target; +} + +#ifdef SERIAL_FLASHER_INTERFACE_UART +static uint32_t s_flash_write_size = 0; + +static esp_loader_error_t spi_set_data_lengths(size_t mosi_bits, size_t miso_bits) +{ + if (mosi_bits > 0) { + RETURN_ON_ERROR( esp_loader_write_register(s_reg->mosi_dlen, mosi_bits - 1) ); + } + if (miso_bits > 0) { + RETURN_ON_ERROR( esp_loader_write_register(s_reg->miso_dlen, miso_bits - 1) ); + } + + return ESP_LOADER_SUCCESS; +} + +static esp_loader_error_t spi_set_data_lengths_8266(size_t mosi_bits, size_t miso_bits) +{ + uint32_t mosi_mask = (mosi_bits == 0) ? 0 : mosi_bits - 1; + uint32_t miso_mask = (miso_bits == 0) ? 0 : miso_bits - 1; + return esp_loader_write_register(s_reg->usr1, (miso_mask << 8) | (mosi_mask << 17)); +} + +static esp_loader_error_t spi_flash_command(spi_flash_cmd_t cmd, void *data_tx, size_t tx_size, void *data_rx, size_t rx_size) +{ + assert(rx_size <= 32); // Reading more than 32 bits back from a SPI flash operation is unsupported + assert(tx_size <= 64); // Writing more than 64 bytes of data with one SPI command is unsupported + + uint32_t SPI_USR_CMD = (1 << 31); + uint32_t SPI_USR_MISO = (1 << 28); + uint32_t SPI_USR_MOSI = (1 << 27); + uint32_t SPI_CMD_USR = (1 << 18); + uint32_t CMD_LEN_SHIFT = 28; + + // Save SPI configuration + uint32_t old_spi_usr; + uint32_t old_spi_usr2; + RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr, &old_spi_usr) ); + RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr2, &old_spi_usr2) ); + + if (s_target == ESP8266_CHIP) { + RETURN_ON_ERROR( spi_set_data_lengths_8266(tx_size, rx_size) ); + } else { + RETURN_ON_ERROR( spi_set_data_lengths(tx_size, rx_size) ); + } + + uint32_t usr_reg_2 = (7 << CMD_LEN_SHIFT) | cmd; + uint32_t usr_reg = SPI_USR_CMD; + if (rx_size > 0) { + usr_reg |= SPI_USR_MISO; + } + if (tx_size > 0) { + usr_reg |= SPI_USR_MOSI; + } + + RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, usr_reg) ); + RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, usr_reg_2 ) ); + + if (tx_size == 0) { + // clear data register before we read it + RETURN_ON_ERROR( esp_loader_write_register(s_reg->w0, 0) ); + } else { + uint32_t *data = (uint32_t *)data_tx; + uint32_t words_to_write = (tx_size + 31) / (8 * 4); + uint32_t data_reg_addr = s_reg->w0; + + while (words_to_write--) { + uint32_t word = *data++; + RETURN_ON_ERROR( esp_loader_write_register(data_reg_addr, word) ); + data_reg_addr += 4; + } + } + + RETURN_ON_ERROR( esp_loader_write_register(s_reg->cmd, SPI_CMD_USR) ); + + uint32_t trials = 10; + while (trials--) { + uint32_t cmd_reg; + RETURN_ON_ERROR( esp_loader_read_register(s_reg->cmd, &cmd_reg) ); + if ((cmd_reg & SPI_CMD_USR) == 0) { + break; + } + } + + if (trials == 0) { + return ESP_LOADER_ERROR_TIMEOUT; + } + + RETURN_ON_ERROR( esp_loader_read_register(s_reg->w0, data_rx) ); + + // Restore SPI configuration + RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, old_spi_usr) ); + RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, old_spi_usr2) ); + + return ESP_LOADER_SUCCESS; +} + +static esp_loader_error_t detect_flash_size(size_t *flash_size) +{ + uint32_t flash_id = 0; + + RETURN_ON_ERROR( spi_flash_command(SPI_FLASH_READ_ID, NULL, 0, &flash_id, 24) ); + uint32_t size_id = flash_id >> 16; + + if (size_id < 0x12 || size_id > 0x18) { + return ESP_LOADER_ERROR_UNSUPPORTED_CHIP; + } + + *flash_size = 1 << size_id; + + return ESP_LOADER_SUCCESS; +} + +static uint32_t calc_erase_size(const target_chip_t target, const uint32_t offset, + const uint32_t image_size) +{ + if (target != ESP8266_CHIP) { + return image_size; + } else { + /* Needed to fix a bug in the ESP8266 ROM */ + const uint32_t sectors_per_block = 16U; + const uint32_t sector_size = 4096U; + + const uint32_t num_sectors = (image_size + sector_size - 1) / sector_size; + const uint32_t start_sector = offset / sector_size; + + uint32_t head_sectors = sectors_per_block - (start_sector % sectors_per_block); + + /* The ROM bug deletes extra num_sectors if we don't cross the block boundary + and extra head_sectors if we do */ + if (num_sectors <= head_sectors) { + return ((num_sectors + 1) / 2) * sector_size; + } else { + return (num_sectors - head_sectors) * sector_size; + } + } +} + +esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size) +{ + s_flash_write_size = block_size; + + size_t flash_size = 0; + if (detect_flash_size(&flash_size) == ESP_LOADER_SUCCESS) { + if (image_size > flash_size) { + return ESP_LOADER_ERROR_IMAGE_SIZE; + } + loader_port_start_timer(DEFAULT_TIMEOUT); + RETURN_ON_ERROR( loader_spi_parameters(flash_size) ); + } else { + loader_port_debug_print("Flash size detection failed, falling back to default"); + } + + init_md5(offset, image_size); + + bool encryption_in_cmd = encryption_in_begin_flash_cmd(s_target); + const uint32_t erase_size = calc_erase_size(esp_loader_get_target(), offset, image_size); + const uint32_t blocks_to_write = (image_size + block_size - 1) / block_size; + + const uint32_t erase_region_timeout_per_mb = 10000; + loader_port_start_timer(timeout_per_mb(erase_size, erase_region_timeout_per_mb)); + return loader_flash_begin_cmd(offset, erase_size, block_size, blocks_to_write, encryption_in_cmd); +} + + +esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size) +{ + uint32_t padding_bytes = s_flash_write_size - size; + uint8_t *data = (uint8_t *)payload; + uint32_t padding_index = size; + + if (size > s_flash_write_size) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + const uint8_t padding_pattern = 0xFF; + while (padding_bytes--) { + data[padding_index++] = padding_pattern; + } + + md5_update(payload, (size + 3) & ~3); + + loader_port_start_timer(DEFAULT_TIMEOUT); + + return loader_flash_data_cmd(data, s_flash_write_size); +} + + +esp_loader_error_t esp_loader_flash_finish(bool reboot) +{ + loader_port_start_timer(DEFAULT_TIMEOUT); + + return loader_flash_end_cmd(!reboot); +} +#endif /* SERIAL_FLASHER_INTERFACE_UART */ + +esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size) +{ + uint32_t blocks_to_write = ROUNDUP(size, block_size); + loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB)); + return loader_mem_begin_cmd(offset, size, blocks_to_write, block_size); +} + + +esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size) +{ + const uint8_t *data = (const uint8_t *)payload; + loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB)); + return loader_mem_data_cmd(data, size); +} + + +esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint) +{ + loader_port_start_timer(DEFAULT_TIMEOUT); + return loader_mem_end_cmd(entrypoint); +} + + +esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value) +{ + loader_port_start_timer(DEFAULT_TIMEOUT); + + return loader_read_reg_cmd(address, reg_value); +} + + +esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value) +{ + loader_port_start_timer(DEFAULT_TIMEOUT); + + return loader_write_reg_cmd(address, reg_value, 0xFFFFFFFF, 0); +} + +esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate) +{ + if (s_target == ESP8266_CHIP) { + return ESP_LOADER_ERROR_UNSUPPORTED_FUNC; + } + + loader_port_start_timer(DEFAULT_TIMEOUT); + + return loader_change_baudrate_cmd(transmission_rate); +} + +#if MD5_ENABLED + +static void hexify(const uint8_t raw_md5[16], uint8_t hex_md5_out[32]) +{ + static const uint8_t dec_to_hex[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + for (int i = 0; i < 16; i++) { + *hex_md5_out++ = dec_to_hex[raw_md5[i] >> 4]; + *hex_md5_out++ = dec_to_hex[raw_md5[i] & 0xF]; + } +} + + +esp_loader_error_t esp_loader_flash_verify(void) +{ + if (s_target == ESP8266_CHIP) { + return ESP_LOADER_ERROR_UNSUPPORTED_FUNC; + } + + uint8_t raw_md5[16] = {0}; + + /* Zero termination and new line character require 2 bytes */ + uint8_t hex_md5[MD5_SIZE + 2] = {0}; + uint8_t received_md5[MD5_SIZE + 2] = {0}; + + md5_final(raw_md5); + hexify(raw_md5, hex_md5); + + loader_port_start_timer(timeout_per_mb(s_image_size, MD5_TIMEOUT_PER_MB)); + + RETURN_ON_ERROR( loader_md5_cmd(s_start_address, s_image_size, received_md5) ); + + bool md5_match = memcmp(hex_md5, received_md5, MD5_SIZE) == 0; + + if (!md5_match) { + hex_md5[MD5_SIZE] = '\n'; + received_md5[MD5_SIZE] = '\n'; + + loader_port_debug_print("Error: MD5 checksum does not match:\n"); + loader_port_debug_print("Expected:\n"); + loader_port_debug_print((char *)received_md5); + loader_port_debug_print("Actual:\n"); + loader_port_debug_print((char *)hex_md5); + + return ESP_LOADER_ERROR_INVALID_MD5; + } + + return ESP_LOADER_SUCCESS; +} + +#endif + +void esp_loader_reset_target(void) +{ + loader_port_reset_target(); +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c new file mode 100644 index 000000000..8764d2369 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/esp_targets.c @@ -0,0 +1,263 @@ +/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_targets.h" +#include + +#define MAX_MAGIC_VALUES 2 + +typedef esp_loader_error_t (*read_spi_config_t)(uint32_t efuse_base, uint32_t *spi_config); + +typedef struct { + target_registers_t regs; + uint32_t efuse_base; + uint32_t chip_magic_value[MAX_MAGIC_VALUES]; + read_spi_config_t read_spi_config; + bool encryption_in_begin_flash_cmd; +} esp_target_t; + +// This ROM address has a different value on each chip model +#define CHIP_DETECT_MAGIC_REG_ADDR 0x40001000 + +#define ESP8266_SPI_REG_BASE 0x60000200 +#define ESP32S2_SPI_REG_BASE 0x3f402000 +#define ESP32xx_SPI_REG_BASE 0x60002000 +#define ESP32_SPI_REG_BASE 0x3ff42000 + +static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config); +static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config); + +static const esp_target_t esp_target[ESP_MAX_CHIP] = { + + // ESP8266 + { + .regs = { + .cmd = ESP8266_SPI_REG_BASE + 0x00, + .usr = ESP8266_SPI_REG_BASE + 0x1c, + .usr1 = ESP8266_SPI_REG_BASE + 0x20, + .usr2 = ESP8266_SPI_REG_BASE + 0x24, + .w0 = ESP8266_SPI_REG_BASE + 0x40, + .mosi_dlen = 0, + .miso_dlen = 0, + }, + .efuse_base = 0, // Not used + .chip_magic_value = { 0xfff0c101, 0 }, + .read_spi_config = NULL, // Not used + }, + + // ESP32 + { + .regs = { + .cmd = ESP32_SPI_REG_BASE + 0x00, + .usr = ESP32_SPI_REG_BASE + 0x1c, + .usr1 = ESP32_SPI_REG_BASE + 0x20, + .usr2 = ESP32_SPI_REG_BASE + 0x24, + .w0 = ESP32_SPI_REG_BASE + 0x80, + .mosi_dlen = ESP32_SPI_REG_BASE + 0x28, + .miso_dlen = ESP32_SPI_REG_BASE + 0x2c, + }, + .efuse_base = 0x3ff5A000, + .chip_magic_value = { 0x00f01d83, 0 }, + .read_spi_config = spi_config_esp32, + }, + + // ESP32S2 + { + .regs = { + .cmd = ESP32S2_SPI_REG_BASE + 0x00, + .usr = ESP32S2_SPI_REG_BASE + 0x18, + .usr1 = ESP32S2_SPI_REG_BASE + 0x1c, + .usr2 = ESP32S2_SPI_REG_BASE + 0x20, + .w0 = ESP32S2_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32S2_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32S2_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x3f41A000, + .chip_magic_value = { 0x000007c6, 0 }, + .read_spi_config = spi_config_esp32xx, + }, + + // ESP32C3 + { + .regs = { + .cmd = ESP32xx_SPI_REG_BASE + 0x00, + .usr = ESP32xx_SPI_REG_BASE + 0x18, + .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, + .usr2 = ESP32xx_SPI_REG_BASE + 0x20, + .w0 = ESP32xx_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x60008800, + .chip_magic_value = { 0x6921506f, 0x1b31506f }, + .read_spi_config = spi_config_esp32xx, + }, + + // ESP32S3 + { + .regs = { + .cmd = ESP32xx_SPI_REG_BASE + 0x00, + .usr = ESP32xx_SPI_REG_BASE + 0x18, + .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, + .usr2 = ESP32xx_SPI_REG_BASE + 0x20, + .w0 = ESP32xx_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x60007000, + .chip_magic_value = { 0x00000009, 0 }, + .read_spi_config = spi_config_esp32xx, + }, + + // ESP32C2 + { + .regs = { + .cmd = ESP32xx_SPI_REG_BASE + 0x00, + .usr = ESP32xx_SPI_REG_BASE + 0x18, + .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, + .usr2 = ESP32xx_SPI_REG_BASE + 0x20, + .w0 = ESP32xx_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x60008800, + .chip_magic_value = { 0x6f51306f, 0x7c41a06f }, + .read_spi_config = spi_config_esp32xx, + }, + // ESP32H4 + { + .regs = { + .cmd = ESP32xx_SPI_REG_BASE + 0x00, + .usr = ESP32xx_SPI_REG_BASE + 0x18, + .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, + .usr2 = ESP32xx_SPI_REG_BASE + 0x20, + .w0 = ESP32xx_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x6001A000, + .chip_magic_value = {0xca26cc22, 0x6881b06f}, // ESP32H4-BETA1, ESP32H4-BETA2 + .read_spi_config = spi_config_esp32xx, + }, + // ESP32H2 + { + .regs = { + .cmd = ESP32xx_SPI_REG_BASE + 0x00, + .usr = ESP32xx_SPI_REG_BASE + 0x18, + .usr1 = ESP32xx_SPI_REG_BASE + 0x1c, + .usr2 = ESP32xx_SPI_REG_BASE + 0x20, + .w0 = ESP32xx_SPI_REG_BASE + 0x58, + .mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24, + .miso_dlen = ESP32xx_SPI_REG_BASE + 0x28, + }, + .efuse_base = 0x6001A000, + .chip_magic_value = {0xd7b73e80, 0}, + .read_spi_config = spi_config_esp32xx, + }, +}; + +const target_registers_t *get_esp_target_data(target_chip_t chip) +{ + return (const target_registers_t *)&esp_target[chip]; +} + +esp_loader_error_t loader_detect_chip(target_chip_t *target_chip, const target_registers_t **target_data) +{ + uint32_t magic_value; + RETURN_ON_ERROR( esp_loader_read_register(CHIP_DETECT_MAGIC_REG_ADDR, &magic_value) ); + + for (int chip = 0; chip < ESP_MAX_CHIP; chip++) { + for(int index = 0; index < MAX_MAGIC_VALUES; index++) { + if (magic_value == esp_target[chip].chip_magic_value[index]) { + *target_chip = (target_chip_t)chip; + *target_data = (target_registers_t *)&esp_target[chip]; + return ESP_LOADER_SUCCESS; + } + } + } + + return ESP_LOADER_ERROR_INVALID_TARGET; +} + +esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config) +{ + const esp_target_t *target = &esp_target[target_chip]; + return target->read_spi_config(target->efuse_base, spi_config); +} + +static inline uint32_t efuse_word_addr(uint32_t efuse_base, uint32_t n) +{ + return efuse_base + (n * 4); +} + +// 30->GPIO32 | 31->GPIO33 +static inline uint8_t adjust_pin_number(uint8_t num) +{ + return (num >= 30) ? num + 2 : num; +} + + +static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config) +{ + *spi_config = 0; + + uint32_t reg5, reg3; + RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 5), ®5) ); + RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 3), ®3) ); + + uint32_t pins = reg5 & 0xfffff; + + if (pins == 0 || pins == 0xfffff) { + return ESP_LOADER_SUCCESS; + } + + uint8_t clk = adjust_pin_number( (pins >> 0) & 0x1f ); + uint8_t q = adjust_pin_number( (pins >> 5) & 0x1f ); + uint8_t d = adjust_pin_number( (pins >> 10) & 0x1f ); + uint8_t cs = adjust_pin_number( (pins >> 15) & 0x1f ); + uint8_t hd = adjust_pin_number( (reg3 >> 4) & 0x1f ); + + if (clk == cs || clk == d || clk == q || q == cs || q == d || q == d) { + return ESP_LOADER_SUCCESS; + } + + *spi_config = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk; + + return ESP_LOADER_SUCCESS; +} + +// Applies for esp32s2, esp32c3 and esp32c3 +static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config) +{ + *spi_config = 0; + + uint32_t reg1, reg2; + RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 18), ®1) ); + RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 19), ®2) ); + + uint32_t pins = ((reg1 >> 16) | ((reg2 & 0xfffff) << 16)) & 0x3fffffff; + + if (pins == 0 || pins == 0xffffffff) { + return ESP_LOADER_SUCCESS; + } + + *spi_config = pins; + return ESP_LOADER_SUCCESS; +} + +bool encryption_in_begin_flash_cmd(target_chip_t target) +{ + return target == ESP32_CHIP || target == ESP8266_CHIP; +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c new file mode 100644 index 000000000..4da76bcb5 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/md5_hash.c @@ -0,0 +1,262 @@ +/* + * MD5 hash implementation and interface functions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + + +#include "md5_hash.h" +#include +#include + + +static void MD5Transform(uint32_t buf[4], uint32_t const in[16]); + + +/* ===== start - public domain MD5 implementation ===== */ +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ + +#ifndef WORDS_BIGENDIAN +#define byteReverse(buf, len) /* Nothing */ +#else +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse(unsigned char *buf, unsigned longs) +{ + uint32_t t; + do { + t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); + *(uint32_t *) buf = t; + buf += 4; + } while (--longs); +} +#endif + +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +void MD5Init(struct MD5Context *ctx) +{ + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bits[0] = 0; + ctx->bits[1] = 0; +} + +/* + * Update context to reflect the concatenation of another buffer full + * of bytes. + */ +void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) +{ + uint32_t t; + + /* Update bitcount */ + + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) { + ctx->bits[1]++; /* Carry from low to high */ + } + ctx->bits[1] += len >> 29; + + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + + /* Handle any leading odd-sized chunks */ + + if (t) { + unsigned char *p = (unsigned char *) ctx->in + t; + + t = 64 - t; + if (len < t) { + memcpy(p, buf, len); + return; + } + memcpy(p, buf, t); + byteReverse(ctx->in, 16); + MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); + buf += t; + len -= t; + } + /* Process data in 64-byte chunks */ + + while (len >= 64) { + memcpy(ctx->in, buf, 64); + byteReverse(ctx->in, 16); + MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); + buf += 64; + len -= 64; + } + + /* Handle any remaining bytes of data. */ + + memcpy(ctx->in, buf, len); +} + +/* + * Final wrapup - pad to 64-byte boundary with the bit pattern + * 1 0* (64-bit count of bits processed, MSB-first) + */ +void MD5Final(unsigned char digest[16], struct MD5Context *ctx) +{ + unsigned count; + unsigned char *p; + + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; + + /* Pad out to 56 mod 64 */ + if (count < 8) { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset(p, 0, count); + byteReverse(ctx->in, 16); + MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); + + /* Now fill the next block with 56 bytes */ + memset(ctx->in, 0, 56); + } else { + /* Pad block to 56 bytes */ + memset(p, 0, count - 8); + } + byteReverse(ctx->in, 14); + + /* Append length in bits and transform */ + ((uint32_t *) ctx->in)[14] = ctx->bits[0]; + ((uint32_t *) ctx->in)[15] = ctx->bits[1]; + + MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in); + byteReverse((unsigned char *) ctx->buf, 4); + memcpy(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */ +} + +/* The four core functions - F1 is optimized somewhat */ + +/* #define F1(x, y, z) (x & y | ~x & z) */ +#define F1(x, y, z) (z ^ (x & (y ^ z))) +#define F2(x, y, z) F1(z, x, y) +#define F3(x, y, z) (x ^ y ^ z) +#define F4(x, y, z) (y ^ (x | ~z)) + +/* This is the central step in the MD5 algorithm. */ +#define MD5STEP(f, w, x, y, z, data, s) \ + ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* + * The core of the MD5 algorithm, this alters an existing MD5 hash to + * reflect the addition of 16 longwords of new data. MD5Update blocks + * the data and converts bytes into longwords for this routine. + */ +static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) +{ + register uint32_t a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} +/* ===== end - public domain MD5 implementation ===== */ diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c new file mode 100644 index 000000000..8d1d9dd53 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_common.c @@ -0,0 +1,301 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "protocol.h" +#include "protocol_prv.h" +#include "esp_loader_io.h" +#include +#include + +#define CMD_SIZE(cmd) ( sizeof(cmd) - sizeof(command_common_t) ) + +static uint32_t s_sequence_number = 0; + +static uint8_t compute_checksum(const uint8_t *data, uint32_t size) +{ + uint8_t checksum = 0xEF; + + while (size--) { + checksum ^= *data++; + } + + return checksum; +} + +void log_loader_internal_error(error_code_t error) +{ + loader_port_debug_print("Error: "); + + switch (error) { + case INVALID_CRC: loader_port_debug_print("INVALID_CRC"); break; + case INVALID_COMMAND: loader_port_debug_print("INVALID_COMMAND"); break; + case COMMAND_FAILED: loader_port_debug_print("COMMAND_FAILED"); break; + case FLASH_WRITE_ERR: loader_port_debug_print("FLASH_WRITE_ERR"); break; + case FLASH_READ_ERR: loader_port_debug_print("FLASH_READ_ERR"); break; + case READ_LENGTH_ERR: loader_port_debug_print("READ_LENGTH_ERR"); break; + case DEFLATE_ERROR: loader_port_debug_print("DEFLATE_ERROR"); break; + default: loader_port_debug_print("UNKNOWN ERROR"); break; + } + + loader_port_debug_print("\n"); +} + + +esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, + uint32_t erase_size, + uint32_t block_size, + uint32_t blocks_to_write, + bool encryption) +{ + uint32_t encryption_size = encryption ? sizeof(uint32_t) : 0; + + flash_begin_command_t flash_begin_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = FLASH_BEGIN, + .size = CMD_SIZE(flash_begin_cmd) - encryption_size, + .checksum = 0 + }, + .erase_size = erase_size, + .packet_count = blocks_to_write, + .packet_size = block_size, + .offset = offset, + .encrypted = 0 + }; + + s_sequence_number = 0; + + return send_cmd(&flash_begin_cmd, sizeof(flash_begin_cmd) - encryption_size, NULL); +} + + +esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size) +{ + data_command_t data_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = FLASH_DATA, + .size = CMD_SIZE(data_cmd) + size, + .checksum = compute_checksum(data, size) + }, + .data_size = size, + .sequence_number = s_sequence_number++, + }; + + return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size); +} + + +esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader) +{ + flash_end_command_t end_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = FLASH_END, + .size = CMD_SIZE(end_cmd), + .checksum = 0 + }, + .stay_in_loader = stay_in_loader + }; + + return send_cmd(&end_cmd, sizeof(end_cmd), NULL); +} + + +esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size) +{ + + mem_begin_command_t mem_begin_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = MEM_BEGIN, + .size = CMD_SIZE(mem_begin_cmd), + .checksum = 0 + }, + .total_size = size, + .blocks = blocks_to_write, + .block_size = block_size, + .offset = offset + }; + + s_sequence_number = 0; + + return send_cmd(&mem_begin_cmd, sizeof(mem_begin_cmd), NULL); +} + + +esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size) +{ + data_command_t data_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = MEM_DATA, + .size = CMD_SIZE(data_cmd) + size, + .checksum = compute_checksum(data, size) + }, + .data_size = size, + .sequence_number = s_sequence_number++, + }; + return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size); +} + +esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint) +{ + mem_end_command_t end_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = MEM_END, + .size = CMD_SIZE(end_cmd), + }, + .stay_in_loader = (entrypoint == 0), + .entry_point_address = entrypoint + }; + + return send_cmd(&end_cmd, sizeof(end_cmd), NULL); +} + + +esp_loader_error_t loader_sync_cmd(void) +{ + sync_command_t sync_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = SYNC, + .size = CMD_SIZE(sync_cmd), + .checksum = 0 + }, + .sync_sequence = { + 0x07, 0x07, 0x12, 0x20, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + } + }; + + return send_cmd(&sync_cmd, sizeof(sync_cmd), NULL); +} + + +esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, + uint32_t mask, uint32_t delay_us) +{ + write_reg_command_t write_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = WRITE_REG, + .size = CMD_SIZE(write_cmd), + .checksum = 0 + }, + .address = address, + .value = value, + .mask = mask, + .delay_us = delay_us + }; + + return send_cmd(&write_cmd, sizeof(write_cmd), NULL); +} + + +esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg) +{ + read_reg_command_t read_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = READ_REG, + .size = CMD_SIZE(read_cmd), + .checksum = 0 + }, + .address = address, + }; + + return send_cmd(&read_cmd, sizeof(read_cmd), reg); +} + + +esp_loader_error_t loader_spi_attach_cmd(uint32_t config) +{ + spi_attach_command_t attach_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = SPI_ATTACH, + .size = CMD_SIZE(attach_cmd), + .checksum = 0 + }, + .configuration = config, + .zero = 0 + }; + + return send_cmd(&attach_cmd, sizeof(attach_cmd), NULL); +} + +esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate) +{ + change_baudrate_command_t baudrate_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = CHANGE_BAUDRATE, + .size = CMD_SIZE(baudrate_cmd), + .checksum = 0 + }, + .new_baudrate = baudrate, + .old_baudrate = 0 // ESP32 ROM only + }; + + return send_cmd(&baudrate_cmd, sizeof(baudrate_cmd), NULL); +} + +esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out) +{ + spi_flash_md5_command_t md5_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = SPI_FLASH_MD5, + .size = CMD_SIZE(md5_cmd), + .checksum = 0 + }, + .address = address, + .size = size, + .reserved_0 = 0, + .reserved_1 = 0 + }; + + return send_cmd_md5(&md5_cmd, sizeof(md5_cmd), md5_out); +} + +esp_loader_error_t loader_spi_parameters(uint32_t total_size) +{ + write_spi_command_t spi_cmd = { + .common = { + .direction = WRITE_DIRECTION, + .command = SPI_SET_PARAMS, + .size = 24, + .checksum = 0 + }, + .id = 0, + .total_size = total_size, + .block_size = 64 * 1024, + .sector_size = 4 * 1024, + .page_size = 0x100, + .status_mask = 0xFFFF, + }; + + return send_cmd(&spi_cmd, sizeof(spi_cmd), NULL); +} + +__attribute__ ((weak)) void loader_port_debug_print(const char *str) +{ + (void)(str); +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c new file mode 100644 index 000000000..bd04fe79f --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_spi.c @@ -0,0 +1,312 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "protocol.h" +#include "protocol_prv.h" +#include "esp_loader_io.h" +#include +#include + +typedef struct __attribute__((packed)) { + uint8_t cmd; + uint8_t addr; + uint8_t dummy; +} transaction_preamble_t; + +typedef enum { + TRANS_CMD_WRBUF = 0x01, + TRANS_CMD_RDBUF = 0x02, + TRANS_CMD_WRDMA = 0x03, + TRANS_CMD_RDDMA = 0x04, + TRANS_CMD_SEG_DONE = 0x05, + TRANS_CMD_ENQPI = 0x06, + TRANS_CMD_WR_DONE = 0x07, + TRANS_CMD_CMD8 = 0x08, + TRANS_CMD_CMD9 = 0x09, + TRANS_CMD_CMDA = 0x0A, + TRANS_CMD_EXQPI = 0xDD, +} transaction_cmd_t; + +/* Slave protocol registers */ +typedef enum { + SLAVE_REGISTER_VER = 0, + SLAVE_REGISTER_RXSTA = 4, + SLAVE_REGISTER_TXSTA = 8, + SLAVE_REGISTER_CMD = 12, +} slave_register_addr_t; + +#define SLAVE_STA_TOGGLE_BIT (0x01U << 0) +#define SLAVE_STA_INIT_BIT (0x01U << 1) +#define SLAVE_STA_BUF_LENGTH_POS 2U + +typedef enum { + SLAVE_STATE_INIT = SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT, + SLAVE_STATE_FIRST_PACKET = SLAVE_STA_INIT_BIT, +} slave_state_t; + +typedef enum { + /* Target to host */ + SLAVE_CMD_IDLE = 0xAA, + SLAVE_CMD_READY = 0xA5, + /* Host to target */ + SLAVE_CMD_REBOOT = 0xFE, + SLAVE_CMD_COMM_REINIT = 0x5A, + SLAVE_CMD_DONE = 0x55, +} slave_cmd_t; + +static uint8_t s_slave_seq_tx; +static uint8_t s_slave_seq_rx; + +static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr, + const uint8_t size); +static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr, + const uint8_t size); +static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state, + bool *slave_ready, uint32_t *buf_size); +static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value); + +esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) +{ + for (uint8_t trial = 0; trial < connect_args->trials; trial++) { + uint8_t slave_ready_flag; + RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD, + sizeof(slave_ready_flag))); + + if (slave_ready_flag != SLAVE_CMD_IDLE) { + loader_port_debug_print("Waiting for Slave to be idle...\n"); + loader_port_delay_ms(100); + } else { + break; + } + } + + const uint8_t reg_val = SLAVE_CMD_READY; + RETURN_ON_ERROR(write_slave_reg(®_val, SLAVE_REGISTER_CMD, sizeof(reg_val))); + + for (uint8_t trial = 0; trial < connect_args->trials; trial++) { + uint8_t slave_ready_flag; + RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD, + sizeof(slave_ready_flag))); + + if (slave_ready_flag != SLAVE_CMD_READY) { + loader_port_debug_print("Waiting for Slave to be ready...\n"); + loader_port_delay_ms(100); + } else { + break; + } + } + + return ESP_LOADER_SUCCESS; +} + + +esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value) +{ + command_t command = ((const command_common_t *)cmd_data)->command; + + uint32_t buf_size; + bool slave_ready = false; + while (!slave_ready) { + RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready, + &buf_size)); + } + + if (size > buf_size) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + /* Start and write the command */ + transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA}; + + loader_port_spi_set_cs(0); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, size, + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + /* Terminate the write */ + loader_port_spi_set_cs(0); + preamble.cmd = TRANS_CMD_WR_DONE; + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + return check_response(command, reg_value); +} + + +esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, + const void *data, size_t data_size) +{ + uint32_t buf_size; + bool slave_ready = false; + while (!slave_ready) { + RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready, + &buf_size)); + } + + if (cmd_size + data_size > buf_size) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + /* Start and write the command and the data */ + transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA}; + + loader_port_spi_set_cs(0); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, cmd_size, + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)data, data_size, + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + /* Terminate the write */ + loader_port_spi_set_cs(0); + preamble.cmd = TRANS_CMD_WR_DONE; + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + command_t command = ((const command_common_t *)cmd_data)->command; + return check_response(command, NULL); +} + + +static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr, + const uint8_t size) +{ + transaction_preamble_t preamble = { + .cmd = TRANS_CMD_RDBUF, + .addr = addr, + }; + + loader_port_spi_set_cs(0); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_read(out_data, size, loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + return ESP_LOADER_SUCCESS; +} + + +static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr, + const uint8_t size) +{ + transaction_preamble_t preamble = { + .cmd = TRANS_CMD_WRBUF, + .addr = addr, + }; + + loader_port_spi_set_cs(0); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_write(data, size, loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + return ESP_LOADER_SUCCESS; +} + + +static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state, + bool *slave_ready, uint32_t *buf_size) +{ + uint32_t status_reg; + RETURN_ON_ERROR(read_slave_reg((uint8_t *)&status_reg, status_reg_addr, + sizeof(status_reg))); + const slave_state_t state = status_reg & (SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT); + + switch(state) { + case SLAVE_STATE_INIT: { + const uint32_t initial = 0U; + RETURN_ON_ERROR(write_slave_reg((uint8_t *)&initial, status_reg_addr, sizeof(initial))); + break; + } + + case SLAVE_STATE_FIRST_PACKET: { + *seq_state = state & SLAVE_STA_TOGGLE_BIT; + *buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS; + *slave_ready = true; + break; + } + + default: { + const uint8_t new_seq = state & SLAVE_STA_TOGGLE_BIT; + if (new_seq != *seq_state) { + *seq_state = new_seq; + *buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS; + *slave_ready = true; + } + break; + } + } + + return ESP_LOADER_SUCCESS; +} + + +static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value) +{ + response_t resp; + + uint32_t buf_size; + bool slave_ready = false; + while (!slave_ready) { + RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_TXSTA, &s_slave_seq_tx, &slave_ready, + &buf_size)); + } + + if (sizeof(resp) > buf_size) { + return ESP_LOADER_ERROR_INVALID_PARAM; + } + + transaction_preamble_t preamble = { + .cmd = TRANS_CMD_RDDMA, + }; + + loader_port_spi_set_cs(0); + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + RETURN_ON_ERROR(loader_port_read((uint8_t *)&resp, sizeof(resp), + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + /* Terminate the read */ + loader_port_spi_set_cs(0); + preamble.cmd = TRANS_CMD_CMD8; + RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble), + loader_port_remaining_time())); + loader_port_spi_set_cs(1); + + common_response_t *common = (common_response_t *)&resp; + if ((common->direction != READ_DIRECTION) || (common->command != cmd)) { + return ESP_LOADER_ERROR_INVALID_RESPONSE; + } + + response_status_t *status = + (response_status_t *)((uint8_t *)&resp + sizeof(resp) - sizeof(response_status_t)); + if (status->failed) { + log_loader_internal_error(status->error); + return ESP_LOADER_ERROR_INVALID_RESPONSE; + } + + if (reg_value != NULL) { + *reg_value = common->value; + } + + return ESP_LOADER_SUCCESS; +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c new file mode 100644 index 000000000..c5a51cec6 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/protocol_uart.c @@ -0,0 +1,114 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "protocol.h" +#include "protocol_prv.h" +#include "esp_loader_io.h" +#include "slip.h" +#include +#include + +static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size); + +esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) { + esp_loader_error_t err; + int32_t trials = connect_args->trials; + + do { + loader_port_start_timer(connect_args->sync_timeout); + err = loader_sync_cmd(); + if (err == ESP_LOADER_ERROR_TIMEOUT) { + if (--trials == 0) { + return ESP_LOADER_ERROR_TIMEOUT; + } + loader_port_delay_ms(100); + } else if (err != ESP_LOADER_SUCCESS) { + return err; + } + } while (err != ESP_LOADER_SUCCESS); + + return err; +} + +esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value) +{ + response_t response; + command_t command = ((const command_common_t *)cmd_data)->command; + + RETURN_ON_ERROR( SLIP_send_delimiter() ); + RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, size) ); + RETURN_ON_ERROR( SLIP_send_delimiter() ); + + return check_response(command, reg_value, &response, sizeof(response)); +} + + +esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size, + const void *data, size_t data_size) +{ + response_t response; + command_t command = ((const command_common_t *)cmd_data)->command; + + RETURN_ON_ERROR( SLIP_send_delimiter() ); + RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) ); + RETURN_ON_ERROR( SLIP_send(data, data_size) ); + RETURN_ON_ERROR( SLIP_send_delimiter() ); + + return check_response(command, NULL, &response, sizeof(response)); +} + + +esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]) +{ + rom_md5_response_t response; + command_t command = ((const command_common_t *)cmd_data)->command; + + RETURN_ON_ERROR( SLIP_send_delimiter() ); + RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) ); + RETURN_ON_ERROR( SLIP_send_delimiter() ); + + RETURN_ON_ERROR( check_response(command, NULL, &response, sizeof(response)) ); + + memcpy(md5_out, response.md5, MD5_SIZE); + + return ESP_LOADER_SUCCESS; +} + + +static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size) +{ + esp_loader_error_t err; + common_response_t *response = (common_response_t *)resp; + + do { + err = SLIP_receive_packet(resp, resp_size); + if (err != ESP_LOADER_SUCCESS) { + return err; + } + } while ((response->direction != READ_DIRECTION) || (response->command != cmd)); + + response_status_t *status = (response_status_t *)((uint8_t *)resp + resp_size - sizeof(response_status_t)); + + if (status->failed) { + log_loader_internal_error(status->error); + return ESP_LOADER_ERROR_INVALID_RESPONSE; + } + + if (reg_value != NULL) { + *reg_value = response->value; + } + + return ESP_LOADER_SUCCESS; +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c new file mode 100644 index 000000000..ba926169c --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/src/slip.c @@ -0,0 +1,125 @@ +/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "slip.h" +#include "esp_loader_io.h" + +static const uint8_t DELIMITER = 0xC0; +static const uint8_t C0_REPLACEMENT[2] = {0xDB, 0xDC}; +static const uint8_t DB_REPLACEMENT[2] = {0xDB, 0xDD}; + +static inline esp_loader_error_t peripheral_read(uint8_t *buff, const size_t size) +{ + return loader_port_read(buff, size, loader_port_remaining_time()); +} + +static inline esp_loader_error_t peripheral_write(const uint8_t *buff, const size_t size) +{ + return loader_port_write(buff, size, loader_port_remaining_time()); +} + +esp_loader_error_t SLIP_receive_data(uint8_t *buff, const size_t size) +{ + uint8_t ch; + + for (uint32_t i = 0; i < size; i++) { + RETURN_ON_ERROR( peripheral_read(&ch, 1) ); + + if (ch == 0xDB) { + RETURN_ON_ERROR( peripheral_read(&ch, 1) ); + if (ch == 0xDC) { + buff[i] = 0xC0; + } else if (ch == 0xDD) { + buff[i] = 0xDB; + } else { + return ESP_LOADER_ERROR_INVALID_RESPONSE; + } + } else { + buff[i] = ch; + } + } + + return ESP_LOADER_SUCCESS; +} + + +esp_loader_error_t SLIP_receive_packet(uint8_t *buff, const size_t size) +{ + uint8_t ch; + + // Wait for delimiter + do { + RETURN_ON_ERROR( peripheral_read(&ch, 1) ); + } while (ch != DELIMITER); + + // Workaround: bootloader sends two dummy(0xC0) bytes after response when baud rate is changed. + do { + RETURN_ON_ERROR( peripheral_read(&ch, 1) ); + } while (ch == DELIMITER); + + buff[0] = ch; + + RETURN_ON_ERROR( SLIP_receive_data(&buff[1], size - 1) ); + + // Wait for delimiter + do { + RETURN_ON_ERROR( peripheral_read(&ch, 1) ); + } while (ch != DELIMITER); + + return ESP_LOADER_SUCCESS; +} + + +esp_loader_error_t SLIP_send(const uint8_t *data, const size_t size) +{ + uint32_t to_write = 0; // Bytes ready to write as they are + uint32_t written = 0; // Bytes already written + + for (uint32_t i = 0; i < size; i++) { + if (data[i] != 0xC0 && data[i] != 0xDB) { + to_write++; // Queue this byte for writing + continue; + } + + // We have a byte that needs encoding, write the queue first + if (to_write > 0) { + RETURN_ON_ERROR( peripheral_write(&data[written], to_write) ); + } + + // Write the encoded byte + if (data[i] == 0xC0) { + RETURN_ON_ERROR( peripheral_write(C0_REPLACEMENT, 2) ); + } else { + RETURN_ON_ERROR( peripheral_write(DB_REPLACEMENT, 2) ); + } + + // Update to start again after the encoded byte + written = i + 1; + to_write = 0; + } + + // Write the rest of the bytes that didn't need encoding + if (to_write > 0) { + RETURN_ON_ERROR( peripheral_write(&data[written], to_write) ); + } + + return ESP_LOADER_SUCCESS; +} + + +esp_loader_error_t SLIP_send_delimiter(void) +{ + return peripheral_write(&DELIMITER, 1); +} diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt new file mode 100644 index 000000000..97da4eaae --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/CMakeLists.txt @@ -0,0 +1,30 @@ +cmake_minimum_required(VERSION 3.5) + +if (CONFIG_ESP_SERIAL_FLASHER) + zephyr_include_directories( + "${ZEPHYR_CURRENT_MODULE_DIR}/include" + "${ZEPHYR_CURRENT_MODULE_DIR}/port" + "${ZEPHYR_CURRENT_MODULE_DIR}/private_include" + ) + + zephyr_interface_library_named(esp_flasher) + + zephyr_library() + + zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_loader.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_targets.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_common.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_uart.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/slip.c + ${ZEPHYR_CURRENT_MODULE_DIR}/src/md5_hash.c + ${ZEPHYR_CURRENT_MODULE_DIR}/port/zephyr_port.c + ) + + target_compile_definitions(esp_flasher INTERFACE SERIAL_FLASHER_INTERFACE_UART) + + zephyr_library_link_libraries(esp_flasher) + + if(DEFINED MD5_ENABLED OR CONFIG_SERIAL_FLASHER_MD5_ENABLED) + target_compile_definitions(esp_flasher INTERFACE -DMD5_ENABLED=1) + endif() +endif() diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig new file mode 100644 index 000000000..ebb524c86 --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/Kconfig @@ -0,0 +1,16 @@ +config ESP_SERIAL_FLASHER + bool "Enable ESP serial flasher library" + default y + select CONSOLE_SUBSYS + help + Select this option to enable the ESP serial flasher library. + +config ESP_SERIAL_FLASHER_UART_BUFSIZE + int "ESP Serial Flasher UART buffer size" + default 512 + help + Buffer size for UART TX and RX packets + +if ESP_SERIAL_FLASHER + rsource "../Kconfig" +endif diff --git a/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml new file mode 100644 index 000000000..01d484fcb --- /dev/null +++ b/applications/external/wifi_marauder_companion/lib/esp-serial-flasher/zephyr/module.yml @@ -0,0 +1,5 @@ +name: esp-flasher + +build: + cmake: zephyr + kconfig: zephyr/Kconfig diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h index d223af79a..402fca479 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_config.h @@ -13,3 +13,4 @@ ADD_SCENE(wifi_marauder, script_stage_edit, ScriptStageEdit) ADD_SCENE(wifi_marauder, script_stage_add, ScriptStageAdd) ADD_SCENE(wifi_marauder, script_stage_edit_list, ScriptStageEditList) ADD_SCENE(wifi_marauder, sniffpmkid_options, SniffPmkidOptions) +ADD_SCENE(wifi_marauder, flasher, Flasher) diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c index 05d94fe80..236fe4eff 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c @@ -1,5 +1,7 @@ #include "../wifi_marauder_app_i.h" +#include "../wifi_marauder_flasher.h" + char* _wifi_marauder_get_prefix_from_cmd(const char* command) { int end = strcspn(command, " "); char* prefix = (char*)malloc(sizeof(char) * (end + 1)); @@ -101,13 +103,24 @@ void wifi_marauder_scene_console_output_on_enter(void* context) { view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewConsoleOutput); // Register callbacks to receive data - wifi_marauder_uart_set_handle_rx_data_cb( - app->uart, - wifi_marauder_console_output_handle_rx_data_cb); // setup callback for general log rx thread + // setup callback for general log rx thread + if(app->flash_mode) { + wifi_marauder_uart_set_handle_rx_data_cb( + app->uart, + wifi_marauder_flash_handle_rx_data_cb); // setup callback for general log rx thread + } else { + wifi_marauder_uart_set_handle_rx_data_cb( + app->uart, + wifi_marauder_console_output_handle_rx_data_cb); // setup callback for general log rx thread + } wifi_marauder_uart_set_handle_rx_data_cb( app->lp_uart, wifi_marauder_console_output_handle_rx_packets_cb); // setup callback for packets rx thread + if(app->flash_mode) { + wifi_marauder_flash_start_thread(app); + } + // Get ready to send command if((app->is_command && app->selected_tx_string) || app->script) { const char* prefix = @@ -183,6 +196,10 @@ void wifi_marauder_scene_console_output_on_exit(void* context) { furi_delay_ms(50); } + if(app->flash_mode) { + wifi_marauder_flash_stop_thread(app); + } + // Unregister rx callback wifi_marauder_uart_set_handle_rx_data_cb(app->uart, NULL); wifi_marauder_uart_set_handle_rx_data_cb(app->lp_uart, NULL); diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c new file mode 100644 index 000000000..79682879d --- /dev/null +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_flasher.c @@ -0,0 +1,92 @@ +#include "../wifi_marauder_app_i.h" + +enum SubmenuIndex { + SubmenuIndexBoot, + SubmenuIndexPart, + SubmenuIndexApp, + SubmenuIndexFlash, +}; + +static void wifi_marauder_scene_flasher_callback(void* context, uint32_t index) { + WifiMarauderApp* app = context; + + scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneFlasher, index); + + // browse for files + FuriString* predefined_filepath = furi_string_alloc_set_str(MARAUDER_APP_FOLDER); + FuriString* selected_filepath = furi_string_alloc(); + DialogsFileBrowserOptions browser_options; + dialog_file_browser_set_basic_options(&browser_options, ".bin", &I_Text_10x10); + + // TODO refactor + switch(index) { + case SubmenuIndexBoot: + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_boot, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_boot)); + } + break; + case SubmenuIndexPart: + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_part, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_part)); + } + break; + case SubmenuIndexApp: + if(dialog_file_browser_show( + app->dialogs, selected_filepath, predefined_filepath, &browser_options)) { + strncpy( + app->bin_file_path_app, + furi_string_get_cstr(selected_filepath), + sizeof(app->bin_file_path_app)); + } + break; + case SubmenuIndexFlash: + // TODO error checking + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput); + break; + } + + furi_string_free(selected_filepath); + furi_string_free(predefined_filepath); +} + +void wifi_marauder_scene_flasher_on_enter(void* context) { + WifiMarauderApp* app = context; + + Submenu* submenu = app->submenu; + + submenu_set_header(submenu, "Browse for files to flash"); + submenu_add_item( + submenu, "Bootloader", SubmenuIndexBoot, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "Partition Table", SubmenuIndexPart, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "Application", SubmenuIndexApp, wifi_marauder_scene_flasher_callback, app); + submenu_add_item( + submenu, "[>] FLASH", SubmenuIndexFlash, wifi_marauder_scene_flasher_callback, app); + + submenu_set_selected_item( + submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneFlasher)); + view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu); +} + +bool wifi_marauder_scene_flasher_on_event(void* context, SceneManagerEvent event) { + //WifiMarauderApp* app = context; + UNUSED(context); + UNUSED(event); + bool consumed = false; + + return consumed; +} + +void wifi_marauder_scene_flasher_on_exit(void* context) { + WifiMarauderApp* app = context; + submenu_reset(app->submenu); +} diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c index b2bd39d3e..06dcd7fd7 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c @@ -121,6 +121,7 @@ const WifiMarauderItem items[NUM_MENU_ITEMS] = { {"Update", {"ota", "sd"}, 2, {"update -w", "update -s"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Reboot", {""}, 1, {"reboot"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Help", {""}, 1, {"help"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP}, + {"Reflash ESP32 (WIP)", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Scripts", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP}, {"Save to flipper sdcard", // keep as last entry or change logic in callback below {""}, @@ -149,6 +150,17 @@ static void wifi_marauder_scene_start_var_list_enter_callback(void* context, uin item->focus_console; app->show_stopscan_tip = item->show_stopscan_tip; + // TODO cleanup + if(index == NUM_MENU_ITEMS - 3) { + // flasher + app->is_command = false; + app->flash_mode = true; + view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartFlasher); + return; + } + + app->flash_mode = false; + if(!app->is_command && selected_option_index == 0) { // View Log from start view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartLogViewer); @@ -260,6 +272,10 @@ bool wifi_marauder_scene_start_on_event(void* context, SceneManagerEvent event) scene_manager_set_scene_state( app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSniffPmkidOptions); + } else if(event.event == WifiMarauderEventStartFlasher) { + scene_manager_set_scene_state( + app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index); + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneFlasher); } consumed = true; } else if(event.type == SceneManagerEventTypeTick) { diff --git a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c index e6091a410..66a508f66 100644 --- a/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c +++ b/applications/external/wifi_marauder_companion/scenes/wifi_marauder_scene_text_input.c @@ -46,7 +46,9 @@ void wifi_marauder_scene_text_input_on_enter(void* context) { // Setup view WIFI_TextInput* text_input = app->text_input; // Add help message to header - if(app->special_case_input_step == 1) { + if(app->flash_mode) { + wifi_text_input_set_header_text(text_input, "Enter destination address"); + } else if(app->special_case_input_step == 1) { wifi_text_input_set_header_text(text_input, "Enter source MAC"); } else if(0 == strncmp("ssid -a -g", app->selected_tx_string, strlen("ssid -a -g"))) { wifi_text_input_set_header_text(text_input, "Enter # SSIDs to generate"); diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app.c b/applications/external/wifi_marauder_companion/wifi_marauder_app.c index 97b1d9715..91fcb2372 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app.c +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app.c @@ -86,6 +86,8 @@ WifiMarauderApp* wifi_marauder_app_alloc() { view_dispatcher_add_view( app->view_dispatcher, WifiMarauderAppViewSubmenu, submenu_get_view(app->submenu)); + app->flash_mode = false; + scene_manager_next_scene(app->scene_manager, WifiMarauderSceneStart); return app; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app.h b/applications/external/wifi_marauder_companion/wifi_marauder_app.h index 3a342bbba..b6664fdab 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app.h @@ -4,7 +4,7 @@ extern "C" { #endif -#define WIFI_MARAUDER_APP_VERSION "v0.4.0" +#define WIFI_MARAUDER_APP_VERSION "v0.5.0" typedef struct WifiMarauderApp WifiMarauderApp; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h b/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h index d6a0d37c7..cd248648a 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_app_i.h @@ -26,7 +26,7 @@ #include #include -#define NUM_MENU_ITEMS (18) +#define NUM_MENU_ITEMS (19) #define WIFI_MARAUDER_TEXT_BOX_STORE_SIZE (4096) #define WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE (512) @@ -113,6 +113,13 @@ struct WifiMarauderApp { int special_case_input_step; char special_case_input_src_addr[20]; char special_case_input_dst_addr[20]; + + // For flashing - TODO: put into its own struct? + char bin_file_path_boot[100]; + char bin_file_path_part[100]; + char bin_file_path_app[100]; + FuriThread* flash_worker; + bool flash_mode; }; // Supported commands: diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h b/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h index b6d9f8274..8f020b754 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h +++ b/applications/external/wifi_marauder_companion/wifi_marauder_custom_event.h @@ -9,5 +9,6 @@ typedef enum { WifiMarauderEventStartSettingsInit, WifiMarauderEventStartLogViewer, WifiMarauderEventStartScriptSelect, - WifiMarauderEventStartSniffPmkidOptions + WifiMarauderEventStartSniffPmkidOptions, + WifiMarauderEventStartFlasher } WifiMarauderCustomEvent; diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c new file mode 100644 index 000000000..8d30c1539 --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.c @@ -0,0 +1,200 @@ +#include "wifi_marauder_flasher.h" + +FuriStreamBuffer* flash_rx_stream; // TODO make safe +WifiMarauderApp* global_app; // TODO make safe +FuriTimer* timer; // TODO make + +static uint32_t _remaining_time = 0; +static void _timer_callback(void* context) { + UNUSED(context); + if(_remaining_time > 0) { + _remaining_time--; + } +} + +static esp_loader_error_t _flash_file(WifiMarauderApp* app, char* filepath, uint32_t addr) { + // TODO cleanup + esp_loader_error_t err; + static uint8_t payload[1024]; + File* bin_file = storage_file_alloc(app->storage); + + // open file + if(!storage_file_open(bin_file, filepath, FSAM_READ, FSOM_OPEN_EXISTING)) { + storage_file_close(bin_file); + storage_file_free(bin_file); + dialog_message_show_storage_error(app->dialogs, "Cannot open file"); + return ESP_LOADER_ERROR_FAIL; + } + + uint64_t size = storage_file_size(bin_file); + + /* + // TODO packet drops with higher BR? + err = esp_loader_change_transmission_rate(230400); + if (err != ESP_LOADER_SUCCESS) { + char err_msg[256]; + snprintf( + err_msg, + sizeof(err_msg), + "Cannot change transmission rate. Error: %u\n", + err); + storage_file_close(bin_file); + storage_file_free(bin_file); + loader_port_debug_print(err_msg); + return; + } + + furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400); + // TODO remember to change BR back! + */ + + loader_port_debug_print("Erasing flash...this may take a while\n"); + err = esp_loader_flash_start(addr, size, sizeof(payload)); + if(err != ESP_LOADER_SUCCESS) { + storage_file_close(bin_file); + storage_file_free(bin_file); + char err_msg[256]; + snprintf(err_msg, sizeof(err_msg), "Erasing flash failed with error %d\n", err); + loader_port_debug_print(err_msg); + return err; + } + + loader_port_debug_print("Start programming\n"); + while(size > 0) { + size_t to_read = MIN(size, sizeof(payload)); + uint16_t num_bytes = storage_file_read(bin_file, payload, to_read); + err = esp_loader_flash_write(payload, num_bytes); + if(err != ESP_LOADER_SUCCESS) { + char err_msg[256]; + snprintf(err_msg, sizeof(err_msg), "Packet could not be written! Error: %u\n", err); + storage_file_close(bin_file); + storage_file_free(bin_file); + loader_port_debug_print(err_msg); + return err; + } + + size -= num_bytes; + } + + loader_port_debug_print("Finished programming\n"); + + // TODO verify + + storage_file_close(bin_file); + storage_file_free(bin_file); + + return ESP_LOADER_SUCCESS; +} + +static int32_t wifi_marauder_flash_bin(void* context) { + WifiMarauderApp* app = (void*)context; + esp_loader_error_t err; + + // alloc global objects + flash_rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1); + timer = furi_timer_alloc(_timer_callback, FuriTimerTypePeriodic, app); + + loader_port_debug_print("Connecting\n"); + esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT(); + err = esp_loader_connect(&connect_config); + if(err != ESP_LOADER_SUCCESS) { + char err_msg[256]; + snprintf(err_msg, sizeof(err_msg), "Cannot connect to target. Error: %u\n", err); + loader_port_debug_print(err_msg); + } + + if(!err) { + loader_port_debug_print("Connected\n"); + loader_port_debug_print("Flashing bootloader (1/3)\n"); + err = _flash_file(app, app->bin_file_path_boot, 0x1000); + } + if(!err) { + loader_port_debug_print("Flashing partition table (2/3)\n"); + err = _flash_file(app, app->bin_file_path_part, 0x8000); + } + if(!err) { + loader_port_debug_print("Flashing app (3/3)\n"); + err = _flash_file(app, app->bin_file_path_app, 0x10000); + loader_port_debug_print("Done flashing. Please reset the board manually.\n"); + } + + // done + + // cleanup + furi_stream_buffer_free(flash_rx_stream); + flash_rx_stream = NULL; + furi_timer_free(timer); + return 0; +} + +void wifi_marauder_flash_start_thread(WifiMarauderApp* app) { + global_app = app; + + app->flash_worker = furi_thread_alloc(); + furi_thread_set_name(app->flash_worker, "WifiMarauderFlashWorker"); + furi_thread_set_stack_size(app->flash_worker, 2048); + furi_thread_set_context(app->flash_worker, app); + furi_thread_set_callback(app->flash_worker, wifi_marauder_flash_bin); + furi_thread_start(app->flash_worker); +} + +void wifi_marauder_flash_stop_thread(WifiMarauderApp* app) { + furi_thread_join(app->flash_worker); + furi_thread_free(app->flash_worker); +} + +esp_loader_error_t loader_port_read(uint8_t* data, uint16_t size, uint32_t timeout) { + size_t read = furi_stream_buffer_receive(flash_rx_stream, data, size, pdMS_TO_TICKS(timeout)); + if(read < size) { + return ESP_LOADER_ERROR_TIMEOUT; + } else { + return ESP_LOADER_SUCCESS; + } +} + +esp_loader_error_t loader_port_write(const uint8_t* data, uint16_t size, uint32_t timeout) { + UNUSED(timeout); + wifi_marauder_uart_tx((uint8_t*)data, size); + return ESP_LOADER_SUCCESS; +} + +void loader_port_enter_bootloader(void) { + // unimplemented +} + +void loader_port_delay_ms(uint32_t ms) { + furi_delay_ms(ms); +} + +void loader_port_start_timer(uint32_t ms) { + _remaining_time = ms; + furi_timer_start(timer, pdMS_TO_TICKS(1)); +} + +uint32_t loader_port_remaining_time(void) { + return _remaining_time; +} + +extern void wifi_marauder_console_output_handle_rx_data_cb( + uint8_t* buf, + size_t len, + void* context); // TODO cleanup +void loader_port_debug_print(const char* str) { + if(global_app) + wifi_marauder_console_output_handle_rx_data_cb((uint8_t*)str, strlen(str), global_app); +} + +void loader_port_spi_set_cs(uint32_t level) { + UNUSED(level); + // unimplemented +} + +void wifi_marauder_flash_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) { + UNUSED(context); + if(flash_rx_stream) { + furi_stream_buffer_send(flash_rx_stream, buf, len, 0); + } else { + // done flashing + if(global_app) wifi_marauder_console_output_handle_rx_data_cb(buf, len, global_app); + } +} \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h new file mode 100644 index 000000000..796e258e5 --- /dev/null +++ b/applications/external/wifi_marauder_companion/wifi_marauder_flasher.h @@ -0,0 +1,10 @@ +#pragma once + +#include "wifi_marauder_app_i.h" +#include "wifi_marauder_uart.h" +#define SERIAL_FLASHER_INTERFACE_UART /* TODO why is application.fam not passing this via cdefines */ +#include "esp_loader_io.h" + +void wifi_marauder_flash_start_thread(WifiMarauderApp* app); +void wifi_marauder_flash_stop_thread(WifiMarauderApp* app); +void wifi_marauder_flash_handle_rx_data_cb(uint8_t* buf, size_t len, void* context); \ No newline at end of file diff --git a/applications/external/wifi_marauder_companion/wifi_marauder_uart.c b/applications/external/wifi_marauder_companion/wifi_marauder_uart.c index 080280b5f..0c9147752 100644 --- a/applications/external/wifi_marauder_companion/wifi_marauder_uart.c +++ b/applications/external/wifi_marauder_companion/wifi_marauder_uart.c @@ -112,4 +112,4 @@ void wifi_marauder_uart_free(WifiMarauderUart* uart) { furi_hal_console_enable(); free(uart); -} \ No newline at end of file +} diff --git a/applications/main/application.fam b/applications/main/application.fam index c8884f934..43aea2e5d 100644 --- a/applications/main/application.fam +++ b/applications/main/application.fam @@ -18,19 +18,20 @@ App( ], ) +# Enable apps that you need in DEBUG firmware here: App( appid="main_apps_default", name="Basic applications for main menu", apptype=FlipperAppType.METAPACKAGE, provides=[ - #"gpio", - #"ibutton", - #"infrared", + # "gpio", + # "ibutton", + # "infrared", "lfrfid", - "nfc", + # "nfc", "subghz", - #"bad_usb", - #"u2f", + # "bad_usb", + # "u2f", "archive", ], ) diff --git a/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_types.h b/applications/main/subghz/helpers/subghz_types.h index 3c928c3b5..0d748a80b 100644 --- a/applications/main/subghz/helpers/subghz_types.h +++ b/applications/main/subghz/helpers/subghz_types.h @@ -83,9 +83,6 @@ typedef enum { SubGhzViewIdFrequencyAnalyzer, SubGhzViewIdReadRAW, - SubGhzViewIdStatic, - SubGhzViewIdTestCarrier, - SubGhzViewIdTestPacket, } SubGhzViewId; /** SubGhz load type file */ diff --git a/applications/main/subghz/scenes/subghz_scene_config.h b/applications/main/subghz/scenes/subghz_scene_config.h index 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_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 08159f8dc..7beb62651 100644 --- a/applications/main/subghz/scenes/subghz_scene_start.c +++ b/applications/main/subghz/scenes/subghz_scene_start.c @@ -6,7 +6,6 @@ enum SubmenuIndex { SubmenuIndexRead = 10, SubmenuIndexSaved, - SubmenuIndexTest, SubmenuIndexAddManually, SubmenuIndexFrequencyAnalyzer, SubmenuIndexReadRAW, @@ -53,10 +52,6 @@ void subghz_scene_start_on_enter(void* context) { SubmenuIndexExtSettings, subghz_scene_start_submenu_callback, subghz); - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - submenu_add_item( - subghz->submenu, "Test", SubmenuIndexTest, subghz_scene_start_submenu_callback, subghz); - } submenu_set_selected_item( subghz->submenu, scene_manager_get_scene_state(subghz->scene_manager, SubGhzSceneStart)); @@ -98,11 +93,6 @@ bool subghz_scene_start_on_event(void* context, SceneManagerEvent event) { scene_manager_next_scene(subghz->scene_manager, SubGhzSceneFrequencyAnalyzer); dolphin_deed(DolphinDeedSubGhzFrequencyAnalyzer); return true; - } else if(event.event == SubmenuIndexTest) { - scene_manager_set_scene_state( - subghz->scene_manager, SubGhzSceneStart, SubmenuIndexTest); - scene_manager_next_scene(subghz->scene_manager, SubGhzSceneTest); - return true; } else if(event.event == SubmenuIndexExtSettings) { scene_manager_set_scene_state( subghz->scene_manager, SubGhzSceneStart, SubmenuIndexExtSettings); 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 6d294ca2c..000000000 --- a/applications/main/subghz/scenes/subghz_scene_test_carrier.c +++ /dev/null @@ -1,33 +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); - subghz_test_carrier_set_radio( - subghz->subghz_test_carrier, - subghz_devices_get_by_name(subghz_txrx_radio_device_get_name(subghz->txrx))); - 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 16bc496b5..2af334db6 100644 --- a/applications/main/subghz/subghz.c +++ b/applications/main/subghz/subghz.c @@ -175,13 +175,6 @@ SubGhz* subghz_alloc(bool alloc_for_tx_only) { 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); @@ -190,22 +183,6 @@ 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(); @@ -267,21 +244,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); diff --git a/applications/main/subghz/subghz_i.h b/applications/main/subghz/subghz_i.h index a0c9341c3..8d01c845d 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; diff --git a/applications/services/desktop/scenes/desktop_scene_main.c b/applications/services/desktop/scenes/desktop_scene_main.c index 420775489..8b9a4b986 100644 --- a/applications/services/desktop/scenes/desktop_scene_main.c +++ b/applications/services/desktop/scenes/desktop_scene_main.c @@ -70,12 +70,10 @@ static void desktop_scene_main_open_app_or_profile(Desktop* desktop, const char* } static void desktop_scene_main_start_favorite(Desktop* desktop, FavoriteApp* application) { - if(strlen(application->name_or_path) > 0) { + if(strlen(application->name_or_path) > 2) { loader_start_with_gui_error(desktop->loader, application->name_or_path, NULL); - } else { - // No favourite app is set! So we skipping this part - return; - //status = loader_start(desktop->loader, FAP_LOADER_APP_NAME, NULL); + } else if((strlen(application->name_or_path) < 2) && (application->is_external == true)) { + loader_start(desktop->loader, LOADER_APPLICATIONS_NAME, NULL, NULL); } } diff --git a/applications/services/loader/loader.c b/applications/services/loader/loader.c index 833954bf7..94b699748 100644 --- a/applications/services/loader/loader.c +++ b/applications/services/loader/loader.c @@ -273,7 +273,7 @@ static LoaderStatus loader_start_external_app( DialogMessage* message = dialog_message_alloc(); dialog_message_set_header( message, "API Mismatch", 64, 0, AlignCenter, AlignTop); - dialog_message_set_buttons(message, "Cancel", NULL, "Continue"); + dialog_message_set_buttons(message, NULL, NULL, "Continue"); dialog_message_set_text( message, "This app might not\nwork correctly\nContinue anyways?", @@ -284,6 +284,9 @@ static LoaderStatus loader_start_external_app( if(dialog_message_show(dialogs, message) == DialogMessageButtonRight) { status = loader_make_status_error( LoaderStatusErrorApiMismatch, error_message, "API Mismatch"); + } else { + status = loader_make_status_error( + LoaderStatusErrorApiMismatchExit, error_message, "API Mismatch"); } dialog_message_free(message); furi_record_close(RECORD_DIALOGS); diff --git a/applications/services/loader/loader.h b/applications/services/loader/loader.h index 550d3d508..62c198b37 100644 --- a/applications/services/loader/loader.h +++ b/applications/services/loader/loader.h @@ -16,6 +16,7 @@ typedef enum { LoaderStatusErrorUnknownApp, LoaderStatusErrorInternal, LoaderStatusErrorApiMismatch, + LoaderStatusErrorApiMismatchExit, } LoaderStatus; typedef enum { diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c index d54989814..eb6261cd1 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_favorite.c @@ -1,12 +1,17 @@ #include "../desktop_settings_app.h" #include "applications.h" #include "desktop_settings_scene.h" +#include #include #include +#define EXTERNAL_BROWSER_NAME ("Applications") +#define EXTERNAL_BROWSER_INDEX (FLIPPER_APPS_COUNT + 1) + #define EXTERNAL_APPLICATION_NAME ("[External Application]") -#define EXTERNAL_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 1) -#define NONE_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 2) +#define EXTERNAL_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 2) + +#define NONE_APPLICATION_INDEX (FLIPPER_APPS_COUNT + 3) static bool favorite_fap_selector_item_callback( FuriString* file_path, @@ -14,16 +19,9 @@ static bool favorite_fap_selector_item_callback( uint8_t** icon_ptr, FuriString* item_name) { UNUSED(context); -#ifdef APP_FAP_LOADER Storage* storage = furi_record_open(RECORD_STORAGE); - bool success = fap_loader_load_name_and_icon(file_path, storage, icon_ptr, item_name); + bool success = flipper_application_load_name_and_icon(file_path, storage, icon_ptr, item_name); furi_record_close(RECORD_STORAGE); -#else - UNUSED(file_path); - UNUSED(icon_ptr); - UNUSED(item_name); - bool success = false; -#endif return success; } @@ -77,14 +75,28 @@ void desktop_settings_scene_favorite_on_enter(void* context) { } } + // Special case: Application browser + submenu_add_item( + submenu, + EXTERNAL_BROWSER_NAME, + EXTERNAL_BROWSER_INDEX, + desktop_settings_scene_favorite_submenu_callback, + app); + + // Special case: Specific application submenu_add_item( submenu, EXTERNAL_APPLICATION_NAME, EXTERNAL_APPLICATION_INDEX, desktop_settings_scene_favorite_submenu_callback, app); + if(curr_favorite_app->is_external) { - pre_select_item = EXTERNAL_APPLICATION_INDEX; + if(curr_favorite_app->name_or_path[0] == '\0') { + pre_select_item = EXTERNAL_BROWSER_INDEX; + } else { + pre_select_item = EXTERNAL_APPLICATION_INDEX; + } } submenu_add_item( @@ -130,7 +142,11 @@ bool desktop_settings_scene_favorite_on_event(void* context, SceneManagerEvent e } if(event.type == SceneManagerEventTypeCustom) { - if(event.event == EXTERNAL_APPLICATION_INDEX) { + if(event.event == EXTERNAL_BROWSER_INDEX) { + curr_favorite_app->is_external = true; + curr_favorite_app->name_or_path[0] = '\0'; + consumed = true; + } else if(event.event == EXTERNAL_APPLICATION_INDEX) { const DialogsFileBrowserOptions browser_options = { .extension = ".fap", .icon = &I_unknown_10px, @@ -157,7 +173,7 @@ bool desktop_settings_scene_favorite_on_event(void* context, SceneManagerEvent e } } else if(event.event == NONE_APPLICATION_INDEX) { curr_favorite_app->is_external = false; - strncpy(curr_favorite_app->name_or_path, "no", MAX_APP_LENGTH); + strncpy(curr_favorite_app->name_or_path, "n", MAX_APP_LENGTH); consumed = true; } else { curr_favorite_app->is_external = false; diff --git a/applications/settings/notification_settings/notification_settings_app.c b/applications/settings/notification_settings/notification_settings_app.c index 565d4f1f6..195501210 100644 --- a/applications/settings/notification_settings/notification_settings_app.c +++ b/applications/settings/notification_settings/notification_settings_app.c @@ -48,31 +48,25 @@ const int32_t contrast_value[CONTRAST_COUNT] = { 5, }; -#define BACKLIGHT_COUNT 5 +#define BACKLIGHT_COUNT 21 const char* const backlight_text[BACKLIGHT_COUNT] = { - "0%", - "25%", - "50%", - "75%", - "100%", + "0%", "5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", + "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", }; const float backlight_value[BACKLIGHT_COUNT] = { - 0.0f, - 0.25f, - 0.5f, - 0.75f, - 1.0f, + 0.00f, 0.05f, 0.10f, 0.15f, 0.20f, 0.25f, 0.30f, 0.35f, 0.40f, 0.45f, 0.50f, + 0.55f, 0.60f, 0.65f, 0.70f, 0.75f, 0.80f, 0.85f, 0.90f, 0.95f, 1.00f, }; -#define VOLUME_COUNT 5 +#define VOLUME_COUNT 21 const char* const volume_text[VOLUME_COUNT] = { - "0%", - "25%", - "50%", - "75%", - "100%", + "0%", "5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", + "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "100%", +}; +const float volume_value[VOLUME_COUNT] = { + 0.00f, 0.05f, 0.10f, 0.15f, 0.20f, 0.25f, 0.30f, 0.35f, 0.40f, 0.45f, 0.50f, + 0.55f, 0.60f, 0.65f, 0.70f, 0.75f, 0.80f, 0.85f, 0.90f, 0.95f, 1.00f, }; -const float volume_value[VOLUME_COUNT] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}; #define DELAY_COUNT 11 const char* const delay_text[DELAY_COUNT] = { diff --git a/applications/system/storage_move_to_sd/storage_move_to_sd.c b/applications/system/storage_move_to_sd/storage_move_to_sd.c index 4a0f3f4ad..5aaacd736 100644 --- a/applications/system/storage_move_to_sd/storage_move_to_sd.c +++ b/applications/system/storage_move_to_sd/storage_move_to_sd.c @@ -28,6 +28,14 @@ static void storage_move_to_sd_remove_region() { if(storage_common_exists(storage, INT_PATH(".region_data"))) { storage_common_remove(storage, INT_PATH(".region_data")); } + if(storage_common_exists(storage, EXT_PATH("apps/Misc/totp.conf"))) { + storage_common_rename( + storage, EXT_PATH("apps/Misc/totp.conf"), EXT_PATH("authenticator/totp.conf")); + } + if(storage_common_exists(storage, EXT_PATH("apps/Misc/barcodegen.save"))) { + storage_common_remove(storage, EXT_PATH("apps/Misc/barcodegen.save")); + storage_common_remove(storage, EXT_PATH("apps/Misc")); + } furi_record_close(RECORD_STORAGE); } 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/barcode_data/codabar_encodings.txt b/assets/resources/apps_data/barcode_data/codabar_encodings.txt new file mode 100644 index 000000000..5f0684cbd --- /dev/null +++ b/assets/resources/apps_data/barcode_data/codabar_encodings.txt @@ -0,0 +1,22 @@ +# alternates between bars and spaces, always begins with bar +# 0 for narrow, 1 for wide +0: 0000011 +1: 0000110 +2: 0001001 +3: 1100000 +4: 0010010 +5: 1000010 +6: 0100001 +7: 0100100 +8: 0110000 +9: 1001000 +-: 0001100 +$: 0011000 +:: 1000101 +/: 1010001 +.: 1010100 ++: 0010101 +A: 0011010 +B: 0101001 +C: 0001011 +D: 0001110 \ No newline at end of file diff --git a/assets/resources/apps_data/barcode_data/code128_encodings.txt b/assets/resources/apps_data/barcode_data/code128_encodings.txt new file mode 100644 index 000000000..394a34520 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code128_encodings.txt @@ -0,0 +1,202 @@ + : 00 +!: 01 +": 02 +#: 03 +$: 04 +%: 05 +&: 06 +': 07 +(: 08 +): 09 +*: 10 ++: 11 +,: 12 +-: 13 +.: 14 +/: 15 +0: 16 +1: 17 +2: 18 +3: 19 +4: 20 +5: 21 +6: 22 +7: 23 +8: 24 +9: 25 +:: 26 +;: 27 +<: 28 +=: 29 +>: 30 +?: 31 +@: 32 +A: 33 +B: 34 +C: 35 +D: 36 +E: 37 +F: 38 +G: 39 +H: 40 +I: 41 +J: 42 +K: 43 +L: 44 +M: 45 +N: 46 +O: 47 +P: 48 +Q: 49 +R: 50 +S: 51 +T: 52 +U: 53 +V: 54 +W: 55 +X: 56 +Y: 57 +Z: 58 +[: 59 +\: 60 +]: 61 +^: 62 +_: 63 +`: 64 +a: 65 +b: 66 +c: 67 +d: 68 +e: 69 +f: 70 +g: 71 +h: 72 +i: 73 +j: 74 +k: 75 +l: 76 +m: 77 +n: 78 +o: 79 +p: 80 +q: 81 +r: 82 +s: 83 +t: 84 +u: 85 +v: 86 +w: 87 +x: 88 +y: 89 +z: 90 +{: 91 +|: 92 +}: 93 +~: 94 + +00: 11011001100 +01: 11001101100 +02: 11001100110 +03: 10010011000 +04: 10010001100 +05: 10001001100 +06: 10011001000 +07: 10011000100 +08: 10001100100 +09: 11001001000 +10: 11001000100 +11: 11000100100 +12: 10110011100 +13: 10011011100 +14: 10011001110 +15: 10111001100 +16: 10011101100 +17: 10011100110 +18: 11001110010 +19: 11001011100 +20: 11001001110 +21: 11011100100 +22: 11001110100 +23: 11101101110 +24: 11101001100 +25: 11100101100 +26: 11100100110 +27: 11101100100 +28: 11100110100 +29: 11100110010 +30: 11011011000 +31: 11011000110 +32: 11000110110 +33: 10100011000 +34: 10001011000 +35: 10001000110 +36: 10110001000 +37: 10001101000 +38: 10001100010 +39: 11010001000 +40: 11000101000 +41: 11000100010 +42: 10110111000 +43: 10110001110 +44: 10001101110 +45: 10111011000 +46: 10111000110 +47: 10001110110 +48: 11101110110 +49: 11010001110 +50: 11000101110 +51: 11011101000 +52: 11011100010 +53: 11011101110 +54: 11101011000 +55: 11101000110 +56: 11100010110 +57: 11101101000 +58: 11101100010 +59: 11100011010 +60: 11101111010 +61: 11001000010 +62: 11110001010 +63: 10100110000 +64: 10100001100 +65: 10010110000 +66: 10010000110 +67: 10000101100 +68: 10000100110 +69: 10110010000 +70: 10110000100 +71: 10011010000 +72: 10011000010 +73: 10000110100 +74: 10000110010 +75: 11000010010 +76: 11001010000 +77: 11110111010 +78: 11000010100 +79: 10001111010 +80: 10100111100 +81: 10010111100 +82: 10010011110 +83: 10111100100 +84: 10011110100 +85: 10011110010 +86: 11110100100 +87: 11110010100 +88: 11110010010 +89: 11011011110 +90: 11011110110 +91: 11110110110 +92: 10101111000 +93: 10100011110 +94: 10001011110 +95: 10111101000 +96: 10111100010 +97: 11110101000 +98: 11110100010 +99: 10111011110 +100: 10111101110 +101: 11101011110 +102: 11110101110 +103: 11010000100 +104: 11010010000 +105: 11010011100 \ No newline at end of file diff --git a/assets/resources/apps_data/barcode_data/code128c_encodings.txt b/assets/resources/apps_data/barcode_data/code128c_encodings.txt new file mode 100644 index 000000000..75cc71135 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code128c_encodings.txt @@ -0,0 +1,106 @@ +00: 11011001100 +01: 11001101100 +02: 11001100110 +03: 10010011000 +04: 10010001100 +05: 10001001100 +06: 10011001000 +07: 10011000100 +08: 10001100100 +09: 11001001000 +10: 11001000100 +11: 11000100100 +12: 10110011100 +13: 10011011100 +14: 10011001110 +15: 10111001100 +16: 10011101100 +17: 10011100110 +18: 11001110010 +19: 11001011100 +20: 11001001110 +21: 11011100100 +22: 11001110100 +23: 11101101110 +24: 11101001100 +25: 11100101100 +26: 11100100110 +27: 11101100100 +28: 11100110100 +29: 11100110010 +30: 11011011000 +31: 11011000110 +32: 11000110110 +33: 10100011000 +34: 10001011000 +35: 10001000110 +36: 10110001000 +37: 10001101000 +38: 10001100010 +39: 11010001000 +40: 11000101000 +41: 11000100010 +42: 10110111000 +43: 10110001110 +44: 10001101110 +45: 10111011000 +46: 10111000110 +47: 10001110110 +48: 11101110110 +49: 11010001110 +50: 11000101110 +51: 11011101000 +52: 11011100010 +53: 11011101110 +54: 11101011000 +55: 11101000110 +56: 11100010110 +57: 11101101000 +58: 11101100010 +59: 11100011010 +60: 11101111010 +61: 11001000010 +62: 11110001010 +63: 10100110000 +64: 10100001100 +65: 10010110000 +66: 10010000110 +67: 10000101100 +68: 10000100110 +69: 10110010000 +70: 10110000100 +71: 10011010000 +72: 10011000010 +73: 10000110100 +74: 10000110010 +75: 11000010010 +76: 11001010000 +77: 11110111010 +78: 11000010100 +79: 10001111010 +80: 10100111100 +81: 10010111100 +82: 10010011110 +83: 10111100100 +84: 10011110100 +85: 10011110010 +86: 11110100100 +87: 11110010100 +88: 11110010010 +89: 11011011110 +90: 11011110110 +91: 11110110110 +92: 10101111000 +93: 10100011110 +94: 10001011110 +95: 10111101000 +96: 10111100010 +97: 11110101000 +98: 11110100010 +99: 10111011110 +100: 10111101110 +101: 11101011110 +102: 11110101110 +103: 11010000100 +104: 11010010000 +105: 11010011100 diff --git a/assets/resources/apps_data/barcode_data/code39_encodings.txt b/assets/resources/apps_data/barcode_data/code39_encodings.txt new file mode 100644 index 000000000..a41ad16e9 --- /dev/null +++ b/assets/resources/apps_data/barcode_data/code39_encodings.txt @@ -0,0 +1,44 @@ +0: 000110100 +1: 100100001 +2: 001100001 +3: 101100000 +4: 000110001 +5: 100110000 +6: 001110000 +7: 000100101 +8: 100100100 +9: 001100100 +A: 100001001 +B: 001001001 +C: 101001000 +D: 000011001 +E: 100011000 +F: 001011000 +G: 000001101 +H: 100001100 +I: 001001100 +J: 000011100 +K: 100000011 +L: 001000011 +M: 101000010 +N: 000010011 +O: 100010010 +P: 001010010 +Q: 000000111 +R: 100000110 +S: 001000110 +T: 000010110 +U: 110000001 +V: 011000001 +W: 111000000 +X: 010010001 +Y: 110010000 +Z: 011010000 +-: 010000101 +.: 110000100 + : 011000100 +*: 010010100 +$: 010101000 +/: 010100010 ++: 010001010 +%: 000101010 \ No newline at end of file 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/documentation/HowToBuild.md b/documentation/HowToBuild.md index 80b93b1c3..76830063f 100644 --- a/documentation/HowToBuild.md +++ b/documentation/HowToBuild.md @@ -31,6 +31,9 @@ Check out `documentation/fbt.md` for details on building and flashing firmware. ### Compile everything for development +Edit this file to enable/disable Main apps that you need in DEBUG mode, flash space doesn't allows us to fit them all in DEBUG currently +- `applications/main/application.fam` + ```sh ./fbt FIRMWARE_APP_SET=debug_pack updater_package ``` @@ -52,6 +55,9 @@ Check out `documentation/fbt.md` for details on building and flashing firmware. ### Compile everything for development +Edit this file to enable/disable Main apps that you need in DEBUG mode, flash space doesn't allows us to fit them all in DEBUG currently +- `applications/main/application.fam` + ```sh ./fbt.cmd FIRMWARE_APP_SET=debug_pack updater_package ``` diff --git a/firmware/targets/f18/api_symbols.csv b/firmware/targets/f18/api_symbols.csv index a689d5a21..c6d1b46db 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,+,33.1,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -56,6 +56,7 @@ Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_types.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, +Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, Header,+,firmware/targets/furi_hal_include/furi_hal.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, @@ -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, @@ -1336,6 +1429,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 +1465,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 +1479,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 +1504,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 +1521,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 +1570,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 +1669,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 +1685,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 +1764,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 +1832,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 +1873,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 +1918,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 +2088,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 +2126,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 +2140,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 +2375,12 @@ Function,-,xTimerGetTimerDaemonTaskHandle,TaskHandle_t, Function,-,xTimerIsTimerActive,BaseType_t,TimerHandle_t Function,-,xTimerPendFunctionCall,BaseType_t,"PendedFunction_t, void*, uint32_t, TickType_t" Function,-,xTimerPendFunctionCallFromISR,BaseType_t,"PendedFunction_t, void*, uint32_t, BaseType_t*" +Function,-,y0,double,double +Function,-,y0f,float,float +Function,-,y1,double,double +Function,-,y1f,float,float +Function,-,yn,double,"int, double" +Function,-,ynf,float,"int, float" Variable,-,AHBPrescTable,const uint32_t[16], Variable,-,APBPrescTable,const uint32_t[8], Variable,-,ITM_RxBuffer,volatile int32_t, diff --git a/firmware/targets/f7/api_symbols.csv b/firmware/targets/f7/api_symbols.csv index 81b0e7bf7..0e1d186e3 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/firmware/targets/f7/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,33.0,, +Version,+,33.1,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -60,6 +60,7 @@ Header,+,firmware/targets/f7/furi_hal/furi_hal_target_hw.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, +Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, Header,+,firmware/targets/furi_hal_include/furi_hal.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, @@ -1053,6 +1054,7 @@ Function,+,furi_hal_bt_lock_core2,void, Function,+,furi_hal_bt_nvm_sram_sem_acquire,void, Function,+,furi_hal_bt_nvm_sram_sem_release,void, Function,+,furi_hal_bt_reinit,void, +Function,+,furi_hal_bt_reverse_mac_addr,void,uint8_t[( 6 )] Function,+,furi_hal_bt_serial_notify_buffer_is_empty,void, Function,+,furi_hal_bt_serial_set_event_callback,void,"uint16_t, FuriHalBtSerialCallback, void*" Function,+,furi_hal_bt_serial_set_rpc_status,void,FuriHalBtSerialRpcStatus @@ -1060,7 +1062,7 @@ Function,+,furi_hal_bt_serial_start,void, Function,+,furi_hal_bt_serial_stop,void, Function,+,furi_hal_bt_serial_tx,_Bool,"uint8_t*, uint16_t" Function,+,furi_hal_bt_set_key_storage_change_callback,void,"BleGlueKeyStorageChangedCallback, void*" -Function,+,furi_hal_bt_set_profile_adv_name,void,"FuriHalBtProfile, const char[( 18 + 1 )]" +Function,+,furi_hal_bt_set_profile_adv_name,void,"FuriHalBtProfile, const char[( ( 1 + 8 + ( 8 + 1 ) ) + 1 )]" Function,+,furi_hal_bt_set_profile_mac_addr,void,"FuriHalBtProfile, const uint8_t[( 6 )]" Function,+,furi_hal_bt_set_profile_pairing_method,void,"FuriHalBtProfile, GapPairing" Function,+,furi_hal_bt_start_advertising,void, @@ -1259,12 +1261,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, @@ -1407,9 +1410,9 @@ Function,+,furi_hal_subghz_rx_pipe_not_empty,_Bool, Function,+,furi_hal_subghz_set_async_mirror_pin,void,const GpioPin* Function,+,furi_hal_subghz_set_frequency,uint32_t,uint32_t Function,+,furi_hal_subghz_set_frequency_and_path,uint32_t,uint32_t -Function,+,furi_hal_subghz_set_path,void,FuriHalSubGhzPath Function,-,furi_hal_subghz_set_rolling_counter_mult,void,uint8_t -Function,-,furi_hal_subghz_shutdown,void, +Function,+,furi_hal_subghz_shutdown,void, +Function,+,furi_hal_subghz_set_path,void,FuriHalSubGhzPath 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*" @@ -2778,6 +2781,7 @@ Function,+,subghz_protocol_decoder_base_get_hash_data,uint8_t,SubGhzProtocolDeco Function,+,subghz_protocol_decoder_base_get_string,_Bool,"SubGhzProtocolDecoderBase*, FuriString*" Function,+,subghz_protocol_decoder_base_serialize,SubGhzProtocolStatus,"SubGhzProtocolDecoderBase*, FlipperFormat*, SubGhzRadioPreset*" Function,-,subghz_protocol_decoder_base_set_decoder_callback,void,"SubGhzProtocolDecoderBase*, SubGhzProtocolDecoderBaseRxCallback, void*" +Function,+,subghz_protocol_decoder_bin_raw_data_input_rssi,void,"SubGhzProtocolDecoderBinRAW*, float" Function,+,subghz_protocol_decoder_raw_alloc,void*,SubGhzEnvironment* Function,+,subghz_protocol_decoder_raw_deserialize,SubGhzProtocolStatus,"void*, FlipperFormat*" Function,+,subghz_protocol_decoder_raw_feed,void,"void*, _Bool, uint32_t" @@ -2789,6 +2793,7 @@ Function,+,subghz_protocol_encoder_raw_deserialize,SubGhzProtocolStatus,"void*, Function,+,subghz_protocol_encoder_raw_free,void,void* Function,+,subghz_protocol_encoder_raw_stop,void,void* Function,+,subghz_protocol_encoder_raw_yield,LevelDuration,void* +Function,+,subghz_protocol_keeloq_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, const char*, SubGhzRadioPreset*" Function,+,subghz_protocol_raw_file_encoder_worker_set_callback_end,void,"SubGhzProtocolEncoderRAW*, SubGhzProtocolEncoderRAWCallbackEnd, void*" Function,+,subghz_protocol_raw_gen_fff_data,void,"FlipperFormat*, const char*, const char*" Function,+,subghz_protocol_raw_get_sample_write,size_t,SubGhzProtocolDecoderRAW* @@ -2798,6 +2803,8 @@ Function,+,subghz_protocol_raw_save_to_file_stop,void,SubGhzProtocolDecoderRAW* Function,+,subghz_protocol_registry_count,size_t,const SubGhzProtocolRegistry* Function,+,subghz_protocol_registry_get_by_index,const SubGhzProtocol*,"const SubGhzProtocolRegistry*, size_t" Function,+,subghz_protocol_registry_get_by_name,const SubGhzProtocol*,"const SubGhzProtocolRegistry*, const char*" +Function,+,subghz_protocol_secplus_v1_check_fixed,_Bool,uint32_t +Function,+,subghz_protocol_secplus_v2_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint32_t, SubGhzRadioPreset*" Function,+,subghz_receiver_alloc_init,SubGhzReceiver*,SubGhzEnvironment* Function,+,subghz_receiver_decode,void,"SubGhzReceiver*, _Bool, uint32_t" Function,+,subghz_receiver_free,void,SubGhzReceiver* diff --git a/firmware/targets/f7/ble_glue/gap.c b/firmware/targets/f7/ble_glue/gap.c index 55ddc5faf..ab7b9d16c 100644 --- a/firmware/targets/f7/ble_glue/gap.c +++ b/firmware/targets/f7/ble_glue/gap.c @@ -500,7 +500,7 @@ void gap_stop_advertising() { furi_mutex_release(gap->state_mutex); } -static void gap_advetise_timer_callback(void* context) { +static void gap_advertise_timer_callback(void* context) { UNUSED(context); GapCommand command = GapCommandAdvLowPower; furi_check(furi_message_queue_put(gap->command_queue, &command, 0) == FuriStatusOk); @@ -514,7 +514,7 @@ bool gap_init(GapConfig* config, GapEventCallback on_event_cb, void* context) { gap = malloc(sizeof(Gap)); gap->config = config; // Create advertising timer - gap->advertise_timer = furi_timer_alloc(gap_advetise_timer_callback, FuriTimerTypeOnce, NULL); + gap->advertise_timer = furi_timer_alloc(gap_advertise_timer_callback, FuriTimerTypeOnce, NULL); // Initialization of GATT & GAP layer gap->service.adv_name = config->adv_name; gap_init_svc(gap); diff --git a/firmware/targets/f7/ble_glue/gap.h b/firmware/targets/f7/ble_glue/gap.h index 7b317e06c..396d64e67 100644 --- a/firmware/targets/f7/ble_glue/gap.h +++ b/firmware/targets/f7/ble_glue/gap.h @@ -67,7 +67,7 @@ typedef struct { bool bonding_mode; GapPairing pairing_method; uint8_t mac_address[GAP_MAC_ADDR_SIZE]; - char adv_name[FURI_HAL_VERSION_DEVICE_NAME_LENGTH]; + char adv_name[FURI_HAL_BT_ADV_NAME_LENGTH]; GapConnectionParamsRequest conn_param; } GapConfig; diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/firmware/targets/f7/furi_hal/furi_hal_bt.c index 2fc028d7c..5a150d388 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_bt.c +++ b/firmware/targets/f7/furi_hal/furi_hal_bt.c @@ -14,9 +14,6 @@ #define TAG "FuriHalBt" -#define FURI_HAL_BT_DEFAULT_MAC_ADDR \ - { 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 } - /* Time, in ms, to wait for mode transition before crashing */ #define C2_MODE_SWITCH_TIMEOUT 10000 @@ -238,28 +235,29 @@ bool furi_hal_bt_start_app(FuriHalBtProfile profile, GapEventCallback event_cb, strlcpy( config->adv_name, furi_hal_version_get_ble_local_device_name_ptr(), - FURI_HAL_VERSION_DEVICE_NAME_LENGTH); + FURI_HAL_BT_ADV_NAME_LENGTH); config->adv_service_uuid |= furi_hal_version_get_hw_color(); } else if(profile == FuriHalBtProfileHidKeyboard) { // Change MAC address for HID profile - uint8_t default_mac[sizeof(config->mac_address)] = FURI_HAL_BT_DEFAULT_MAC_ADDR; const uint8_t* normal_mac = furi_hal_version_get_ble_mac(); - if(memcmp(config->mac_address, default_mac, sizeof(config->mac_address)) == 0) { + uint8_t empty_mac[sizeof(config->mac_address)] = FURI_HAL_BT_EMPTY_MAC_ADDR; + uint8_t default_mac[sizeof(config->mac_address)] = FURI_HAL_BT_DEFAULT_MAC_ADDR; + if(memcmp(config->mac_address, empty_mac, sizeof(config->mac_address)) == 0 || + memcmp(config->mac_address, normal_mac, sizeof(config->mac_address)) == 0 || + memcmp(config->mac_address, default_mac, sizeof(config->mac_address)) == 0) { memcpy(config->mac_address, normal_mac, sizeof(config->mac_address)); - } - if(memcmp(config->mac_address, normal_mac, sizeof(config->mac_address)) == 0) { config->mac_address[2]++; } // Change name Flipper -> Control - if(strnlen(config->adv_name, FURI_HAL_VERSION_DEVICE_NAME_LENGTH) < 2 || - strnlen(config->adv_name + 1, FURI_HAL_VERSION_DEVICE_NAME_LENGTH) < 1) { + if(strnlen(config->adv_name, FURI_HAL_BT_ADV_NAME_LENGTH) < 2 || + strnlen(config->adv_name + 1, FURI_HAL_BT_ADV_NAME_LENGTH - 1) < 1) { snprintf( config->adv_name, - FURI_HAL_VERSION_DEVICE_NAME_LENGTH, + FURI_HAL_BT_ADV_NAME_LENGTH, "%cControl %s", - *furi_hal_version_get_ble_local_device_name_ptr(), - furi_hal_version_get_ble_local_device_name_ptr() + 9); + AD_TYPE_COMPLETE_LOCAL_NAME, + furi_hal_version_get_name_ptr()); } } if(!gap_init(config, event_cb, context)) { @@ -485,6 +483,15 @@ uint32_t furi_hal_bt_get_conn_rssi(uint8_t* rssi) { return since; } +void furi_hal_bt_reverse_mac_addr(uint8_t mac_addr[GAP_MAC_ADDR_SIZE]) { + uint8_t tmp; + for(size_t i = 0; i < GAP_MAC_ADDR_SIZE / 2; i++) { + tmp = mac_addr[i]; + mac_addr[i] = mac_addr[GAP_MAC_ADDR_SIZE - 1 - i]; + mac_addr[GAP_MAC_ADDR_SIZE - 1 - i] = tmp; + } +} + void furi_hal_bt_set_profile_adv_name( FuriHalBtProfile profile, const char name[FURI_HAL_BT_ADV_NAME_LENGTH]) { @@ -492,13 +499,13 @@ void furi_hal_bt_set_profile_adv_name( furi_assert(name); if(strlen(name) == 0) { - memset( - &(profile_config[profile].config.adv_name[1]), - 0, - strlen(&(profile_config[profile].config.adv_name[1]))); + memset(&(profile_config[profile].config.adv_name[1]), 0, FURI_HAL_BT_ADV_NAME_LENGTH - 1); } else { profile_config[profile].config.adv_name[0] = AD_TYPE_COMPLETE_LOCAL_NAME; - memcpy(&(profile_config[profile].config.adv_name[1]), name, FURI_HAL_BT_ADV_NAME_LENGTH); + strlcpy( + &(profile_config[profile].config.adv_name[1]), + name, + FURI_HAL_BT_ADV_NAME_LENGTH - 1 /* BLE symbol */); } } diff --git a/firmware/targets/f7/furi_hal/furi_hal_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_version.c b/firmware/targets/f7/furi_hal/furi_hal_version.c index 0e5f428ba..b6460cc5f 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_version.c +++ b/firmware/targets/f7/furi_hal/furi_hal_version.c @@ -111,7 +111,11 @@ void furi_hal_version_set_name(const char* name) { } uint32_t company_id = LL_FLASH_GetSTCompanyID(); - uint32_t device_id = LL_FLASH_GetDeviceID(); + // uint32_t device_id = LL_FLASH_GetDeviceID(); + // Some flippers return 0x27 (flippers with chip revision 2003 6495) instead of 0x26 (flippers with chip revision 2001 6495) + // Mobile apps expects it to return 0x26 + // Hardcoded here temporarily until mobile apps is updated to handle 0x27 + uint32_t device_id = 0x26; furi_hal_version.ble_mac[0] = (uint8_t)(udn & 0x000000FF); furi_hal_version.ble_mac[1] = (uint8_t)((udn & 0x0000FF00) >> 8); furi_hal_version.ble_mac[2] = (uint8_t)((udn & 0x00FF0000) >> 16); diff --git a/firmware/targets/f7/platform_specific/intrinsic_export.h b/firmware/targets/f7/platform_specific/intrinsic_export.h index ca343a128..d3c7be5e0 100644 --- a/firmware/targets/f7/platform_specific/intrinsic_export.h +++ b/firmware/targets/f7/platform_specific/intrinsic_export.h @@ -1,3 +1,4 @@ +#pragma once #include #include diff --git a/firmware/targets/f7/platform_specific/math_wrapper.h b/firmware/targets/f7/platform_specific/math_wrapper.h new file mode 100644 index 000000000..83f5a8b75 --- /dev/null +++ b/firmware/targets/f7/platform_specific/math_wrapper.h @@ -0,0 +1,2 @@ +#pragma once +#include \ No newline at end of file diff --git a/firmware/targets/furi_hal_include/furi_hal_bt.h b/firmware/targets/furi_hal_include/furi_hal_bt.h index f128b1064..7354d8770 100644 --- a/firmware/targets/furi_hal_include/furi_hal_bt.h +++ b/firmware/targets/furi_hal_include/furi_hal_bt.h @@ -18,6 +18,12 @@ #define FURI_HAL_BT_STACK_VERSION_MINOR (12) #define FURI_HAL_BT_C2_START_TIMEOUT 1000 +#define FURI_HAL_BT_EMPTY_MAC_ADDR \ + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } + +#define FURI_HAL_BT_DEFAULT_MAC_ADDR \ + { 0x6c, 0x7a, 0xd8, 0xac, 0x57, 0x72 } + #ifdef __cplusplus extern "C" { #endif @@ -218,7 +224,12 @@ float furi_hal_bt_get_rssi(); */ uint32_t furi_hal_bt_get_transmitted_packets(); -// BadBT stuff +// BadBT Stuff +/** Reverse a MAC address byte order in-place + * @param[in] mac mac address to reverse +*/ +void furi_hal_bt_reverse_mac_addr(uint8_t mac_addr[GAP_MAC_ADDR_SIZE]); + /** Modify profile advertisement name and restart bluetooth * @param[in] profile profile type * @param[in] name new adv name diff --git a/firmware/targets/furi_hal_include/furi_hal_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 4a3f4c170..351a7849b 100644 --- a/firmware/targets/furi_hal_include/furi_hal_version.h +++ b/firmware/targets/furi_hal_include/furi_hal_version.h @@ -16,9 +16,10 @@ extern "C" { #define FURI_HAL_VERSION_NAME_LENGTH 8 #define FURI_HAL_VERSION_ARRAY_NAME_LENGTH (FURI_HAL_VERSION_NAME_LENGTH + 1) -#define FURI_HAL_BT_ADV_NAME_LENGTH (18 + 1) // 18 characters + null terminator /** BLE symbol + "Flipper " + name */ #define FURI_HAL_VERSION_DEVICE_NAME_LENGTH (1 + 8 + FURI_HAL_VERSION_ARRAY_NAME_LENGTH) +// 18 characters + null terminator +#define FURI_HAL_BT_ADV_NAME_LENGTH (FURI_HAL_VERSION_DEVICE_NAME_LENGTH + 1) /** OTP Versions enum */ typedef enum { 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/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/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/nfc_worker.c b/lib/nfc/nfc_worker.c index 60847c3c7..959696e7c 100644 --- a/lib/nfc/nfc_worker.c +++ b/lib/nfc/nfc_worker.c @@ -809,6 +809,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( @@ -828,6 +830,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( @@ -1103,7 +1107,9 @@ void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker) { furi_hal_nfc_listen_start(nfc_data); while(nfc_worker->state == NfcWorkerStateMfClassicEmulate) { //-V1044 if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { - mf_classic_emulator(&emulator, &tx_rx, false); + if(!mf_classic_emulator(&emulator, &tx_rx, false)) { + furi_hal_nfc_listen_start(nfc_data); + } } } if(emulator.data_changed) { @@ -1378,8 +1384,6 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { bool reader_no_data_notified = true; while(nfc_worker->state == NfcWorkerStateAnalyzeReader) { - furi_hal_nfc_stop_cmd(); - furi_delay_ms(5); furi_hal_nfc_listen_start(nfc_data); if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { if(reader_no_data_notified) { @@ -1390,7 +1394,9 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { NfcProtocol protocol = reader_analyzer_guess_protocol(reader_analyzer, tx_rx.rx_data, tx_rx.rx_bits / 8); if(protocol == NfcDeviceProtocolMifareClassic) { - mf_classic_emulator(&emulator, &tx_rx, true); + if(!mf_classic_emulator(&emulator, &tx_rx, true)) { + furi_hal_nfc_listen_start(nfc_data); + } } } else { reader_no_data_received_cnt++; @@ -1402,6 +1408,7 @@ void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { FURI_LOG_D(TAG, "No data from reader"); continue; } + furi_delay_ms(1); } rfal_platform_spi_release(); diff --git a/lib/nfc/protocols/mifare_classic.c b/lib/nfc/protocols/mifare_classic.c index 9547c68d0..a6d521dc5 100644 --- a/lib/nfc/protocols/mifare_classic.c +++ b/lib/nfc/protocols/mifare_classic.c @@ -869,7 +869,7 @@ bool mf_classic_emulator( if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { FURI_LOG_D( TAG, - "Error in tx rx. Tx :%d bits, Rx: %d bits", + "Error in tx rx. Tx: %d bits, Rx: %d bits", tx_rx->tx_bits, tx_rx->rx_bits); break; @@ -883,12 +883,17 @@ bool mf_classic_emulator( break; } - if(cmd == 0x50 && plain_data[1] == 0x00) { + if(cmd == NFCA_CMD_HALT && plain_data[1] == 0x00) { FURI_LOG_T(TAG, "Halt received"); - furi_hal_nfc_listen_sleep(); - command_processed = true; + return false; + } + + if(cmd == NFCA_CMD_RATS && !is_encrypted) { + // Mifare Classic doesn't support ATS, NACK it and start listening again + FURI_LOG_T(TAG, "RATS received"); break; } + if(cmd == MF_CLASSIC_AUTH_KEY_A_CMD || cmd == MF_CLASSIC_AUTH_KEY_B_CMD) { uint8_t block = plain_data[1]; uint64_t key = 0; @@ -903,8 +908,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyA; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; - break; + return false; } } else { if(mf_classic_is_key_found( @@ -914,8 +918,7 @@ bool mf_classic_emulator( access_key = MfClassicKeyB; } else { FURI_LOG_D(TAG, "Key not known"); - command_processed = true; - break; + return false; } } @@ -943,16 +946,14 @@ bool mf_classic_emulator( tx_rx->tx_bits = sizeof(nt) * 8; tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; } + if(!furi_hal_nfc_tx_rx(tx_rx, 500)) { FURI_LOG_E(TAG, "Error in NT exchange"); - command_processed = true; - break; + return false; } if(tx_rx->rx_bits != 64) { - FURI_LOG_W(TAG, "Incorrect nr + ar length: %d", tx_rx->rx_bits); - command_processed = true; - break; + return false; } uint32_t nr = nfc_util_bytes2num(tx_rx->rx_data, 4); @@ -963,8 +964,7 @@ bool mf_classic_emulator( if(cardRr != prng_successor(nonce, 64)) { FURI_LOG_T(TAG, "Wrong AUTH! %08lX != %08lX", cardRr, prng_successor(nonce, 64)); // Don't send NACK, as the tag doesn't send it - command_processed = true; - break; + return false; } uint32_t ans = prng_successor(nonce, 96); @@ -1156,6 +1156,7 @@ bool mf_classic_emulator( tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; tx_rx->tx_bits = 4; furi_hal_nfc_tx_rx(tx_rx, 300); + return false; } return true; @@ -1164,7 +1165,7 @@ bool mf_classic_emulator( void mf_classic_halt(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto) { furi_assert(tx_rx); - uint8_t plain_data[4] = {0x50, 0x00, 0x00, 0x00}; + uint8_t plain_data[4] = {NFCA_CMD_HALT, 0x00, 0x00, 0x00}; nfca_append_crc16(plain_data, 2); if(crypto) { diff --git a/lib/nfc/protocols/nfca.c b/lib/nfc/protocols/nfca.c index c401f8cc5..ab4f3f23c 100644 --- a/lib/nfc/protocols/nfca.c +++ b/lib/nfc/protocols/nfca.c @@ -3,8 +3,6 @@ #include #include -#define NFCA_CMD_RATS (0xE0U) - #define NFCA_CRC_INIT (0x6363) #define NFCA_F_SIG (13560000.0) @@ -22,7 +20,7 @@ typedef struct { static uint8_t nfca_default_ats[] = {0x05, 0x78, 0x80, 0x80, 0x00}; -static uint8_t nfca_sleep_req[] = {0x50, 0x00}; +static uint8_t nfca_halt_req[] = {NFCA_CMD_HALT, 0x00}; uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) { uint16_t crc = NFCA_CRC_INIT; @@ -50,17 +48,17 @@ bool nfca_emulation_handler( uint16_t buff_rx_len, uint8_t* buff_tx, uint16_t* buff_tx_len) { - bool sleep = false; + bool halt = false; uint8_t rx_bytes = buff_rx_len / 8; - if(rx_bytes == sizeof(nfca_sleep_req) && !memcmp(buff_rx, nfca_sleep_req, rx_bytes)) { - sleep = true; + if(rx_bytes == sizeof(nfca_halt_req) && !memcmp(buff_rx, nfca_halt_req, rx_bytes)) { + halt = true; } else if(rx_bytes == sizeof(nfca_cmd_rats) && buff_rx[0] == NFCA_CMD_RATS) { memcpy(buff_tx, nfca_default_ats, sizeof(nfca_default_ats)); *buff_tx_len = sizeof(nfca_default_ats) * 8; } - return sleep; + return halt; } static void nfca_add_bit(DigitalSignal* signal, bool bit) { diff --git a/lib/nfc/protocols/nfca.h b/lib/nfc/protocols/nfca.h index 498ef2843..e4978a3e0 100644 --- a/lib/nfc/protocols/nfca.h +++ b/lib/nfc/protocols/nfca.h @@ -5,6 +5,9 @@ #include +#define NFCA_CMD_RATS (0xE0U) +#define NFCA_CMD_HALT (0x50U) + typedef struct { DigitalSignal* one; DigitalSignal* zero; 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_protocol_registry.h b/lib/subghz/subghz_protocol_registry.h index 6a27da992..8e80071b5 100644 --- a/lib/subghz/subghz_protocol_registry.h +++ b/lib/subghz/subghz_protocol_registry.h @@ -8,6 +8,31 @@ extern "C" { extern const SubGhzProtocolRegistry subghz_protocol_registry; +typedef struct SubGhzProtocolDecoderBinRAW SubGhzProtocolDecoderBinRAW; + +bool subghz_protocol_secplus_v2_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint32_t cnt, + SubGhzRadioPreset* preset); + +bool subghz_protocol_keeloq_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +void subghz_protocol_decoder_bin_raw_data_input_rssi( + SubGhzProtocolDecoderBinRAW* instance, + float rssi); + +bool subghz_protocol_secplus_v1_check_fixed(uint32_t fixed); + #ifdef __cplusplus } #endif