MX 2 лет назад
Родитель
Сommit
5b4cd59b88
59 измененных файлов с 4968 добавлено и 2646 удалено
  1. 45 14
      base_pack/gps_nmea_uart/README.md
  2. 7 0
      base_pack/gps_nmea_uart/application.fam
  3. 95 32
      base_pack/gps_nmea_uart/gps.c
  4. 17 10
      base_pack/gps_nmea_uart/gps_uart.c
  5. 14 2
      base_pack/gps_nmea_uart/gps_uart.h
  6. 14 0
      base_pack/gps_nmea_uart/lib/minmea/.github/workflows/c-cpp.yml
  7. 10 0
      base_pack/gps_nmea_uart/lib/minmea/.gitignore
  8. 1 0
      base_pack/gps_nmea_uart/lib/minmea/.gitsubtree
  9. 39 0
      base_pack/gps_nmea_uart/lib/minmea/CMakeLists.txt
  10. 13 0
      base_pack/gps_nmea_uart/lib/minmea/COPYING
  11. 165 0
      base_pack/gps_nmea_uart/lib/minmea/LICENSE.LGPL-3.0
  12. 9 0
      base_pack/gps_nmea_uart/lib/minmea/LICENSE.MIT
  13. 7 0
      base_pack/gps_nmea_uart/lib/minmea/LICENSE.grants
  14. 175 0
      base_pack/gps_nmea_uart/lib/minmea/README.md
  15. 27 0
      base_pack/gps_nmea_uart/lib/minmea/compat/minmea_compat_ti-rtos.h
  16. 23 0
      base_pack/gps_nmea_uart/lib/minmea/compat/minmea_compat_windows.h
  17. 140 0
      base_pack/gps_nmea_uart/lib/minmea/example.c
  18. 679 0
      base_pack/gps_nmea_uart/lib/minmea/minmea.c
  19. 42 42
      base_pack/gps_nmea_uart/lib/minmea/minmea.h
  20. 1207 0
      base_pack/gps_nmea_uart/lib/minmea/tests.c
  21. 0 640
      base_pack/gps_nmea_uart/minmea.c
  22. BIN
      base_pack/gps_nmea_uart/ui.png
  23. BIN
      base_pack/gps_nmea_uart/wiring.png
  24. 3 4
      base_pack/hc_sr04/hc_sr04.c
  25. 6 6
      base_pack/sentry_safe/sentry_safe.c
  26. 23 21
      base_pack/uart_terminal/scenes/uart_terminal_scene_console_output.c
  27. 16 18
      base_pack/uart_terminal/uart_terminal_uart.c
  28. 1 1
      base_pack/uart_terminal/uart_terminal_uart.h
  29. 17 11
      base_pack/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c
  30. 16 2
      base_pack/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c
  31. 59 54
      base_pack/wifi_marauder_companion/script/wifi_marauder_script_executor.c
  32. 2 1
      base_pack/wifi_marauder_companion/script/wifi_marauder_script_worker.c
  33. 1 0
      base_pack/wifi_marauder_companion/script/wifi_marauder_script_worker.h
  34. 0 2
      base_pack/wifi_marauder_companion/wifi_marauder_app.c
  35. 0 1
      base_pack/wifi_marauder_companion/wifi_marauder_app_i.h
  36. 95 33
      base_pack/wifi_marauder_companion/wifi_marauder_uart.c
  37. 4 3
      base_pack/wifi_marauder_companion/wifi_marauder_uart.h
  38. 2 0
      base_pack/wifi_scanner/FlipperZeroWiFiModuleDefines.h
  39. 23 28
      base_pack/wifi_scanner/wifi_scanner.c
  40. 2 1
      non_catalog_apps/flipper_evil_portal/evil_portal_app.c
  41. 1 1
      non_catalog_apps/flipper_evil_portal/evil_portal_app_i.h
  42. 64 22
      non_catalog_apps/flipper_evil_portal/evil_portal_uart.c
  43. 1 1
      non_catalog_apps/flipper_evil_portal/evil_portal_uart.h
  44. 18 11
      non_catalog_apps/flipper_evil_portal/scenes/evil_portal_scene_console_output.c
  45. 3 3
      non_catalog_apps/flipperzero_gpioreader/scenes/gpio_scene_usb_uart_config.c
  46. 15 17
      non_catalog_apps/flipperzero_gpioreader/usb_uart_bridge.c
  47. 1 1
      non_catalog_apps/ifttt/application.fam
  48. 16 6
      non_catalog_apps/ifttt/ifttt_virtual_button.c
  49. 3 1
      non_catalog_apps/ifttt/ifttt_virtual_button.h
  50. 8 8
      non_catalog_apps/ifttt/views/send_view.c
  51. 10 1
      non_catalog_apps/magspoof_flipper/README.md
  52. 1 0
      non_catalog_apps/magspoof_flipper/mag_i.h
  53. 10 10
      non_catalog_apps/magspoof_flipper/scenes/mag_scene_read.c
  54. 1 2
      non_catalog_apps/magspoof_flipper/scenes/mag_scene_read.h
  55. 1789 1621
      non_catalog_apps/nrf24-batch/nrf24batch.c
  56. 10 3
      non_catalog_apps/uhf_rfid/uhf_app.c
  57. 2 0
      non_catalog_apps/wifi_deauther/wifi_deauther_app_i.h
  58. 15 11
      non_catalog_apps/wifi_deauther/wifi_deauther_uart.c
  59. 1 1
      non_catalog_apps/wifi_deauther/wifi_deauther_uart.h

+ 45 - 14
base_pack/gps_nmea_uart/README.md

@@ -1,9 +1,21 @@
 # GPS for Flipper Zero
 
-A simple Flipper Zero application for NMEA 0183 serial GPS modules, such as the
-- Adafruit Ultimate GPS Breakout.
+[![FAP Build](https://github.com/ezod/flipperzero-gps/actions/workflows/build.yml/badge.svg)](https://github.com/ezod/flipperzero-gps/actions/workflows/build.yml)
 
-Heavy lifting (NMEA parsing) provided by minmea.
+A simple Flipper Zero application for NMEA 0183 serial GPS modules.
+
+![ui](ui.png)
+
+Heavy lifting (NMEA parsing) provided by [minmea].
+
+## Installation
+
+1. Navigate to the [FAP Build](https://github.com/ezod/flipperzero-gps/actions/workflows/build.yml)
+   GitHub action workflow, and select the most recent run.
+2. The FAP is built for both the `dev` and `release` channels of the official
+   firmware. Download the artifact corresponding to your firmware version.
+3. Extract `gps_nmea.fap` from the ZIP file to `apps/GPIO` on your Flipper
+   Zero SD card.
 
 ## Usage
 
@@ -11,7 +23,7 @@ This is a single-screen app, and a few interactions are provided via the
 hardware buttons:
 
 - Long press the up button to change the **baud rate**. The default baud rate
-  is 9600, but 19200, 38400, 57600, and 115200 baud are also supported.
+  is 9600, but 4800, 19200, 38400, 57600, and 115200 baud are also supported.
 - Long press the right button to change **speed units** from knots to
   kilometers per hour.
 - Press the OK button to set the **backlight** to always on mode. Press it
@@ -23,24 +35,43 @@ hardware buttons:
 Connect the GPS module to power and the USART using GPIO pins 9 (3.3V), 11
 (GND), 13 (TX), and 14 (RX), as appropriate.
 
+![wiring](wiring.png)
 
-See the tutorial video - https://www.youtube.com/watch?v=5vSGFzEBp-k from
-Lab401 by RocketGod - https://github.com/RocketGod-git for a visual guide to
+See the [tutorial video](https://www.youtube.com/watch?v=5vSGFzEBp-k) from
+Lab401 by [RocketGod](https://github.com/RocketGod-git) for a visual guide to
 the hardware setup.
 
-## Confirmed Compatible Modules
+### Confirmed Compatible Modules
 
-* Adafruit Ultimate GPS Breakout
+* [Adafruit Ultimate GPS Breakout]
+* ATGM336H
 * Beitian BN-180
+* Beitian BN-220
+* Beitian BN-280
+* Beitian BN-880
+* Beitian BK-250
+* Beitian BK-357
+* Beitian BK-880Q
+* Beitian BE-280
+* Beitian BN-280ZF
+* Beitian BN-357ZF
 * Royaltek RBT-2100LP
-* u-blox NEO-6M
+* [u-blox NEO-6M]
+* [u-blox NEO-7M]
+* [Uputronics u-blox MAX-M8C Pico]
 
 If you have verified this application working with a module not listed here,
 please submit a PR adding it to the list.
 
-## Links
+## Building
+
+This application can be compiled using [uFBT]. Run `ufbt` in the root directory
+of the repository.
 
-Original repo link - https://github.com/ezod/flipperzero-gps
-Adafruit Ultimate GPS Breakout: https://www.adafruit.com/product/746
-minmea: https://github.com/kosma/minmea
-u-blox NEO-6M: https://www.u-blox.com/en/product/neo-6-series
+[Adafruit Ultimate GPS Breakout]: https://www.adafruit.com/product/746
+[minmea]: https://github.com/kosma/minmea
+[qFlipper]: https://flipperzero.one/update
+[u-blox NEO-6M]: https://www.u-blox.com/en/product/neo-6-series
+[u-blox NEO-7M]: https://www.u-blox.com/en/product/neo-7-series
+[uFBT]: https://github.com/flipperdevices/flipperzero-ufbt
+[Uputronics u-blox MAX-M8C Pico]: https://store.uputronics.com/index.php?route=product/product&product_id=72

+ 7 - 0
base_pack/gps_nmea_uart/application.fam

@@ -8,6 +8,13 @@ App(
     order=35,
     fap_icon="gps_10px.png",
     fap_category="GPIO",
+    fap_private_libs=[
+        Lib(
+            name="minmea",
+            sources=["minmea.c"],
+            cdefines=["timegm=mktime"],
+        ),
+    ],
     fap_author="@ezod & @xMasterX",
     fap_version="1.2",
     fap_description="Works with GPS modules via UART, using NMEA protocol.",

+ 95 - 32
base_pack/gps_nmea_uart/gps.c

@@ -2,7 +2,6 @@
 #include "constants.h"
 
 #include <furi.h>
-#include <furi_hal_power.h>
 #include <gui/gui.h>
 #include <string.h>
 
@@ -21,7 +20,53 @@ static void render_callback(Canvas* const canvas, void* context) {
     GpsUart* gps_uart = context;
     furi_mutex_acquire(gps_uart->mutex, FuriWaitForever);
 
-    if(!gps_uart->changing_baudrate) {
+    char buffer[64];
+
+    switch(gps_uart->view_state) {
+    case CHANGE_BAUDRATE:
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignBottom, "Baudrate set to:");
+        snprintf(buffer, 64, "%ld baud", gps_uart->baudrate);
+        canvas_draw_str_aligned(canvas, 64, 47, AlignCenter, AlignBottom, buffer);
+        break;
+    case CHANGE_BACKLIGHT:
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(
+            canvas,
+            64,
+            32,
+            AlignCenter,
+            AlignBottom,
+            gps_uart->backlight_enabled ? "Backlight enabled" : "Backlight disabled");
+        break;
+    case CHANGE_DEEPSLEEP:
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(
+            canvas,
+            64,
+            32,
+            AlignCenter,
+            AlignBottom,
+            gps_uart->deep_sleep_enabled ? "Deep sleep enabled" : "Deep sleep disabled");
+        break;
+    case CHANGE_SPEEDUNIT:
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignBottom, "Speed unit set to:");
+        switch(gps_uart->speed_units) {
+        case KPH:
+            canvas_draw_str_aligned(canvas, 64, 47, AlignCenter, AlignBottom, "km/h");
+            break;
+        case MPH:
+            canvas_draw_str_aligned(canvas, 64, 47, AlignCenter, AlignBottom, "mi/h");
+            break;
+        case KNOTS:
+        default:
+            canvas_draw_str_aligned(canvas, 64, 47, AlignCenter, AlignBottom, "kn");
+            break;
+        }
+        break;
+    case NORMAL:
+    default:
         canvas_set_font(canvas, FontPrimary);
         canvas_draw_str_aligned(canvas, 32, 8, AlignCenter, AlignBottom, "Latitude");
         canvas_draw_str_aligned(canvas, 96, 8, AlignCenter, AlignBottom, "Longitude");
@@ -32,7 +77,6 @@ static void render_callback(Canvas* const canvas, void* context) {
         canvas_draw_str_aligned(canvas, 96, 52, AlignCenter, AlignBottom, "Last Fix");
 
         canvas_set_font(canvas, FontSecondary);
-        char buffer[64];
         snprintf(buffer, 64, "%f", (double)gps_uart->status.latitude);
         canvas_draw_str_aligned(canvas, 32, 18, AlignCenter, AlignBottom, buffer);
         snprintf(buffer, 64, "%f", (double)gps_uart->status.longitude);
@@ -42,10 +86,10 @@ static void render_callback(Canvas* const canvas, void* context) {
 
         switch(gps_uart->speed_units) {
         case KPH:
-            snprintf(buffer, 64, "%.2f km", (double)(gps_uart->status.speed * KNOTS_TO_KPH));
+            snprintf(buffer, 64, "%.2f km/h", (double)(gps_uart->status.speed * KNOTS_TO_KPH));
             break;
         case MPH:
-            snprintf(buffer, 64, "%.2f mi", (double)(gps_uart->status.speed * KNOTS_TO_MPH));
+            snprintf(buffer, 64, "%.2f mi/h", (double)(gps_uart->status.speed * KNOTS_TO_MPH));
             break;
         case KNOTS:
         default:
@@ -71,13 +115,7 @@ static void render_callback(Canvas* const canvas, void* context) {
             gps_uart->status.time_minutes,
             gps_uart->status.time_seconds);
         canvas_draw_str_aligned(canvas, 96, 62, AlignCenter, AlignBottom, buffer);
-    } else {
-        char buffer[64];
-        canvas_set_font(canvas, FontPrimary);
-        canvas_draw_str_aligned(canvas, 64, 32, AlignCenter, AlignBottom, "Baudrate set to:");
-
-        snprintf(buffer, 64, "%ld baud", gps_uart->baudrate);
-        canvas_draw_str_aligned(canvas, 64, 47, AlignCenter, AlignBottom, buffer);
+        break;
     }
 
     furi_mutex_release(gps_uart->mutex);
@@ -95,14 +133,6 @@ int32_t gps_app(void* p) {
 
     FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
 
-    uint8_t attempts = 0;
-    bool otg_was_enabled = furi_hal_power_is_otg_enabled();
-    while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
-        furi_hal_power_enable_otg();
-        furi_delay_ms(10);
-    }
-    furi_delay_ms(200);
-
     GpsUart* gps_uart = gps_uart_enable();
 
     gps_uart->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
@@ -112,6 +142,14 @@ int32_t gps_app(void* p) {
         return 255;
     }
 
+    uint8_t attempts = 0;
+    bool otg_was_enabled = furi_hal_power_is_otg_enabled();
+    while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
+        furi_hal_power_enable_otg();
+        furi_delay_ms(10);
+    }
+    furi_delay_ms(200);
+
     // set system callbacks
     ViewPort* view_port = view_port_alloc();
     view_port_draw_callback_set(view_port, render_callback, gps_uart);
@@ -132,24 +170,27 @@ int32_t gps_app(void* p) {
             if(event.type == EventTypeKey) {
                 if(event.input.type == InputTypeShort) {
                     switch(event.input.key) {
-                    case InputKeyUp:
-                    case InputKeyDown:
-                    case InputKeyRight:
-                    case InputKeyLeft:
                     case InputKeyBack:
+                        processing = false;
                         break;
                     case InputKeyOk:
-                        if(!gps_uart->backlight_on) {
+                        if(!gps_uart->backlight_enabled) {
                             notification_message_block(
                                 gps_uart->notifications, &sequence_display_backlight_enforce_on);
-                            gps_uart->backlight_on = true;
+                            gps_uart->backlight_enabled = true;
                         } else {
                             notification_message_block(
                                 gps_uart->notifications, &sequence_display_backlight_enforce_auto);
                             notification_message(
                                 gps_uart->notifications, &sequence_display_backlight_off);
-                            gps_uart->backlight_on = false;
+                            gps_uart->backlight_enabled = false;
                         }
+
+                        gps_uart->view_state = CHANGE_BACKLIGHT;
+                        furi_mutex_release(gps_uart->mutex);
+                        view_port_update(view_port);
+                        furi_delay_ms(1000);
+                        gps_uart->view_state = NORMAL;
                         break;
                     default:
                         break;
@@ -167,15 +208,39 @@ int32_t gps_app(void* p) {
                         gps_uart->baudrate = gps_baudrates[current_gps_baudrate];
 
                         gps_uart_init_thread(gps_uart);
-                        gps_uart->changing_baudrate = true;
+                        gps_uart->view_state = CHANGE_BAUDRATE;
+
                         furi_mutex_release(gps_uart->mutex);
                         view_port_update(view_port);
+                        furi_delay_ms(1000);
+                        gps_uart->view_state = NORMAL;
                         break;
                     case InputKeyRight:
                         gps_uart->speed_units++;
                         if(gps_uart->speed_units == INVALID) {
                             gps_uart->speed_units = KNOTS;
                         }
+
+                        gps_uart->view_state = CHANGE_SPEEDUNIT;
+                        furi_mutex_release(gps_uart->mutex);
+                        view_port_update(view_port);
+                        furi_delay_ms(1000);
+                        gps_uart->view_state = NORMAL;
+                        break;
+                    case InputKeyDown:
+                        gps_uart->view_state = CHANGE_DEEPSLEEP;
+                        gps_uart->deep_sleep_enabled = !gps_uart->deep_sleep_enabled;
+
+                        // tested on Telit SE868-A and SL871L-S
+                        furi_hal_serial_tx(
+                            gps_uart->serial_handle,
+                            (uint8_t*)"$PMTK161,0*28\r\n",
+                            strlen("$PMTK161,0*28\r\n"));
+
+                        furi_mutex_release(gps_uart->mutex);
+                        view_port_update(view_port);
+                        furi_delay_ms(1000);
+                        gps_uart->view_state = NORMAL;
                         break;
                     case InputKeyBack:
                         processing = false;
@@ -186,12 +251,10 @@ int32_t gps_app(void* p) {
                 }
             }
         }
-        if(!gps_uart->changing_baudrate) {
+
+        if(gps_uart->view_state == NORMAL) {
             furi_mutex_release(gps_uart->mutex);
             view_port_update(view_port);
-        } else {
-            furi_delay_ms(1000);
-            gps_uart->changing_baudrate = false;
         }
     }
 

+ 17 - 10
base_pack/gps_nmea_uart/gps_uart.c

@@ -1,6 +1,6 @@
 #include <string.h>
 
-#include "minmea.h"
+#include <minmea.h>
 #include "gps_uart.h"
 
 typedef enum {
@@ -10,25 +10,31 @@ typedef enum {
 
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
 
-static void gps_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+static void
+    gps_uart_on_irq_cb(FuriHalSerialHandle* handle, FuriHalSerialRxEvent event, void* context) {
     GpsUart* gps_uart = (GpsUart*)context;
 
-    if(ev == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         furi_stream_buffer_send(gps_uart->rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(gps_uart->thread), WorkerEvtRxDone);
     }
 }
 
 static void gps_uart_serial_init(GpsUart* gps_uart) {
-    furi_hal_console_disable();
-    furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, gps_uart_on_irq_cb, gps_uart);
-    furi_hal_uart_set_br(FuriHalUartIdUSART1, gps_uart->baudrate);
+    gps_uart->serial_handle = furi_hal_serial_control_acquire(UART_CH);
+    furi_check(gps_uart->serial_handle);
+    furi_hal_serial_init(gps_uart->serial_handle, gps_uart->baudrate);
+    furi_hal_serial_async_rx_start(gps_uart->serial_handle, gps_uart_on_irq_cb, gps_uart, false);
+
+    furi_hal_serial_tx(
+        gps_uart->serial_handle, (uint8_t*)"wakey wakey\r\n", strlen("wakey wakey\r\n"));
 }
 
 static void gps_uart_serial_deinit(GpsUart* gps_uart) {
     UNUSED(gps_uart);
-    furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, NULL, NULL);
-    furi_hal_console_enable();
+    furi_hal_serial_deinit(gps_uart->serial_handle);
+    furi_hal_serial_control_release(gps_uart->serial_handle);
 }
 
 static void gps_uart_parse_nmea(GpsUart* gps_uart, char* line) {
@@ -202,9 +208,10 @@ GpsUart* gps_uart_enable() {
     gps_uart->notifications = furi_record_open(RECORD_NOTIFICATION);
 
     gps_uart->baudrate = gps_baudrates[current_gps_baudrate];
-    gps_uart->changing_baudrate = false;
-    gps_uart->backlight_on = false;
     gps_uart->speed_units = KNOTS;
+    gps_uart->backlight_enabled = false;
+    gps_uart->deep_sleep_enabled = false;
+    gps_uart->view_state = NORMAL;
 
     gps_uart_init_thread(gps_uart);
 

+ 14 - 2
base_pack/gps_nmea_uart/gps_uart.h

@@ -3,6 +3,8 @@
 #include <furi_hal.h>
 #include <notification/notification_messages.h>
 
+#define UART_CH (FuriHalSerialIdUsart)
+
 #define RX_BUF_SIZE 1024
 
 static const int gps_baudrates[6] = {4800, 9600, 19200, 38400, 57600, 115200};
@@ -25,17 +27,27 @@ typedef struct {
 
 typedef enum { KNOTS, KPH, MPH, INVALID } SpeedUnit;
 
+typedef enum {
+    CHANGE_BAUDRATE,
+    CHANGE_BACKLIGHT,
+    CHANGE_DEEPSLEEP,
+    CHANGE_SPEEDUNIT,
+    NORMAL
+} ViewState;
+
 typedef struct {
     FuriMutex* mutex;
     FuriThread* thread;
     FuriStreamBuffer* rx_stream;
     uint8_t rx_buf[RX_BUF_SIZE];
+    FuriHalSerialHandle* serial_handle;
 
     NotificationApp* notifications;
     uint32_t baudrate;
-    bool changing_baudrate;
-    bool backlight_on;
+    bool backlight_enabled;
+    bool deep_sleep_enabled;
     SpeedUnit speed_units;
+    ViewState view_state;
 
     GpsStatus status;
 } GpsUart;

+ 14 - 0
base_pack/gps_nmea_uart/lib/minmea/.github/workflows/c-cpp.yml

@@ -0,0 +1,14 @@
+name: C/C++ CI
+
+on: [push, pull_request]
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@v3
+    - name: Install dependencies
+      run: sudo apt-get install -y clang-tools check cmake
+    - name: cmake
+      run: "( rm -rf build && mkdir build && cd build && cmake .. && make && CTEST_OUTPUT_ON_FAILURE=1 make 
+test && echo OK )"

+ 10 - 0
base_pack/gps_nmea_uart/lib/minmea/.gitignore

@@ -0,0 +1,10 @@
+build/
+cmake-build-*/
+*.o
+*~
+*.diff
+.*.swp
+minmea
+tests
+example
+*.exe

+ 1 - 0
base_pack/gps_nmea_uart/lib/minmea/.gitsubtree

@@ -0,0 +1 @@
+https://github.com/kosma/minmea master /

+ 39 - 0
base_pack/gps_nmea_uart/lib/minmea/CMakeLists.txt

@@ -0,0 +1,39 @@
+cmake_minimum_required(VERSION 3.3)
+
+enable_testing()
+
+project(minmea)
+
+find_package(Threads REQUIRED) # Workaround for https://github.com/libcheck/check/issues/48#issuecomment-322965461
+find_package(PkgConfig)
+pkg_check_modules(CHECK REQUIRED check)
+link_directories(${CHECK_LIBRARY_DIRS})
+
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -Wextra -Werror -std=c99")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_POSIX_C_SOURCE=199309L -D_BSD_SOURCE -D_DEFAULT_SOURCE -D_DARWIN_C_SOURCE")
+
+set(minmea_SRCS minmea.c minmea.h)
+add_library(minmea ${minmea_SRCS})
+
+add_executable(example example.c)
+target_link_libraries(example minmea)
+
+add_executable(tests tests.c)
+target_link_libraries(tests minmea ${CHECK_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
+target_include_directories(tests PUBLIC ${CHECK_INCLUDE_DIRS})
+target_compile_options(tests PUBLIC ${CHECK_CFLAGS_OTHER})
+
+add_test(NAME tests COMMAND $<TARGET_FILE:tests>)
+list(APPEND CMAKE_CTEST_ARGUMENTS "--output-on-failure")
+
+find_program(SCAN_FOUND scan-build)
+
+if (SCAN_FOUND)
+    add_test(
+        NAME clang_static_analysis
+        COMMAND scan-build make
+        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+    )
+else()
+    MESSAGE(STATUS "scan-build not found, not scanning code")
+endif()

+ 13 - 0
base_pack/gps_nmea_uart/lib/minmea/COPYING

@@ -0,0 +1,13 @@
+        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+                    Version 2, December 2004
+
+ Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
+
+ Everyone is permitted to copy and distribute verbatim or modified
+ copies of this license document, and changing it is allowed as long
+ as the name is changed.
+
+            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. You just DO WHAT THE FUCK YOU WANT TO.

+ 165 - 0
base_pack/gps_nmea_uart/lib/minmea/LICENSE.LGPL-3.0

@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser 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
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.

+ 9 - 0
base_pack/gps_nmea_uart/lib/minmea/LICENSE.MIT

@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2023 Kosma Moczek
+
+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 (including the next paragraph) 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.

+ 7 - 0
base_pack/gps_nmea_uart/lib/minmea/LICENSE.grants

@@ -0,0 +1,7 @@
+At your option, if WTFPL is unacceptable for your legal department, I hereby
+explicitly grant you the right to use any the following licenses for minmea:
+
+1. MIT License
+2. LGPL-3.0 License or later
+
+See accompanying license files for full license text.

+ 175 - 0
base_pack/gps_nmea_uart/lib/minmea/README.md

@@ -0,0 +1,175 @@
+# minmea, a lightweight GPS NMEA 0183 parser library
+
+[![C/C++ 
+CI](https://github.com/kosma/minmea/actions/workflows/c-cpp.yml/badge.svg)](https://github.com/kosma/minmea/actions/workflows/c-cpp.yml)
+
+Minmea is a minimalistic GPS parser library written in pure C intended for
+resource-constrained platforms, especially microcontrollers and other embedded
+systems.
+
+## Features
+
+* Written in ISO C99.
+* No dynamic memory allocation.
+* No floating point usage in the core library.
+* Supports both fixed and floating point values.
+* One source file and one header - can't get any simpler.
+* Tested under Linux, OS X, Windows and embedded ARM GCC.
+* Easily extendable to support new sentences.
+* Complete with a test suite and static analysis.
+
+## Supported sentences
+
+* ``GBS`` (Satellite Fault Detection)
+* ``GGA`` (Fix Data)
+* ``GLL`` (Geographic Position: Latitude/Longitude)
+* ``GSA`` (DOP and active satellites)
+* ``GST`` (Pseudorange Noise Statistics)
+* ``GSV`` (Satellites in view)
+* ``RMC`` (Recommended Minimum: position, velocity, time)
+* ``VTG`` (Track made good and Ground speed)
+* ``ZDA`` (Time & Date - UTC, day, month, year and local time zone)
+
+Adding support for more sentences is trivial; see ``minmea.c`` source. Good documentation
+on NMEA is at https://gpsd.gitlab.io/gpsd/NMEA.html
+
+## Compatibility
+
+Minmea runs out-of-the-box under most Unix-compatible systems. Support for non-Unix systems
+(including native Windows builds under MSVC) is provided via compatibility headers:
+
+1. Define `MINMEA_INCLUDE_COMPAT` in the build environment.
+2. Add appropriate compatibility header from under `compat/` directory as `minmea_compat.h`.
+
+If your GPS receiver outputs very long sentences, consider increasing `MINMEA_MAX_SENTENCE_LENGTH`
+in your build environment.
+
+## Fractional number format
+
+Internally, minmea stores fractional numbers as pairs of two integers: ``{value, scale}``.
+For example, a value of ``"-123.456"`` would be parsed as ``{-123456, 1000}``. As this
+format is quite unwieldy, minmea provides the following convenience functions for converting
+to either fixed-point or floating-point format:
+
+* ``minmea_rescale({-123456, 1000}, 10) => -1235``
+* ``minmea_float({-123456, 1000}) => -123.456``
+
+The compound type ``struct minmea_float`` uses ``int_least32_t`` internally. Therefore,
+the coordinate precision is guaranteed to be at least ``[+-]DDDMM.MMMMM`` (five decimal digits)
+or ±2cm LSB at the equator. Note that GPS modules commonly only provide four decimal digits
+(``[+-]DDDMM.MMMM``), which equates to ±20cm (0.0001 minute is 0.0001/60 degrees and one degree
+is about 111km) at the equator.
+
+## Coordinate format
+
+NMEA uses the clunky ``DDMM.MMMM`` format which, honestly, is not good in the internet era.
+Internally, minmea stores it as a fractional number (see above); for practical uses,
+the value should be probably converted to the DD.DDDDD floating point format using the
+following function:
+
+* ``minmea_tocoord({-375165, 100}) => -37.860832``
+
+The library doesn't perform this conversion automatically for the following reasons:
+
+* The conversion is not reversible.
+* It requires floating point support.
+* The user might want to perform this conversion later on or retain the original values.
+
+## Example
+
+```c
+char line[MINMEA_MAX_SENTENCE_LENGTH];
+while (fgets(line, sizeof(line), stdin) != NULL) {
+    switch (minmea_sentence_id(line, false)) {
+        case MINMEA_SENTENCE_RMC: {
+            struct minmea_sentence_rmc frame;
+            if (minmea_parse_rmc(&frame, line)) {
+                printf("$RMC: raw coordinates and speed: (%d/%d,%d/%d) %d/%d\n",
+                        frame.latitude.value, frame.latitude.scale,
+                        frame.longitude.value, frame.longitude.scale,
+                        frame.speed.value, frame.speed.scale);
+                printf("$RMC fixed-point coordinates and speed scaled to three decimal places: (%d,%d) %d\n",
+                        minmea_rescale(&frame.latitude, 1000),
+                        minmea_rescale(&frame.longitude, 1000),
+                        minmea_rescale(&frame.speed, 1000));
+                printf("$RMC floating point degree coordinates and speed: (%f,%f) %f\n",
+                        minmea_tocoord(&frame.latitude),
+                        minmea_tocoord(&frame.longitude),
+                        minmea_tofloat(&frame.speed));
+            }
+        } break;
+
+        case MINMEA_SENTENCE_GGA: {
+            struct minmea_sentence_gga frame;
+            if (minmea_parse_gga(&frame, line)) {
+                printf("$GGA: fix quality: %d\n", frame.fix_quality);
+            }
+        } break;
+
+        case MINMEA_SENTENCE_GSV: {
+            struct minmea_sentence_gsv frame;
+            if (minmea_parse_gsv(&frame, line)) {
+                printf("$GSV: message %d of %d\n", frame.msg_nr, frame.total_msgs);
+                printf("$GSV: satellites in view: %d\n", frame.total_sats);
+                for (int i = 0; i < 4; i++)
+                    printf("$GSV: sat nr %d, elevation: %d, azimuth: %d, snr: %d dbm\n",
+                        frame.sats[i].nr,
+                        frame.sats[i].elevation,
+                        frame.sats[i].azimuth,
+                        frame.sats[i].snr);
+            }
+        } break;
+    }
+}
+```
+
+## Integration with your project
+
+Simply add ``minmea.[ch]`` to your project, ``#include "minmea.h"`` and you're
+good to go.
+
+## Running unit tests
+
+Building and running the tests requires the following:
+
+* CMake
+* Check Framework (https://libcheck.github.io/check/).
+* Clang Static Analyzer (https://clang-analyzer.llvm.org/).
+
+If you have both in your ``$PATH``, running the tests should be as simple as:
+
+```
+mkdir build
+cd build
+cmake ../
+make
+make test
+```
+
+## Limitations
+
+* Only a handful of frames is supported right now.
+* There's no support for omitting parts of the library from building. As
+  a workaround, use the ``-ffunction-sections -Wl,--gc-sections`` linker flags
+  (or equivalent) to remove the unused functions (parsers) from the final image.
+* Some systems lack ``timegm``. On these systems, the recommended course of
+  action is to build with ``-Dtimegm=mktime`` which will work correctly as long
+  the system runs in the default ``UTC`` timezone.
+
+## Contributing
+
+1. Use the GitHub pull request system.
+2. Make sure to follow to existing style (naming, indentation, etc.)
+3. Write unit tests for any new functionality you add.
+4. Be aware you're submitting your work under the repository's license.
+
+## Licensing
+
+Minmea is open source software; see ``COPYING`` for amusement. Email me if the
+license bothers you and I'll happily re-license under anything else under the sun.
+
+## Author
+
+Minmea was written by Kosma Moczek &lt;kosma@kosma.pl&gt; and Patryk Szymczak
+&lt;patryk.szymczak@gmail.com&gt; at Cloud Your Car, with bugs fixed by countless
+good people.

+ 27 - 0
base_pack/gps_nmea_uart/lib/minmea/compat/minmea_compat_ti-rtos.h

@@ -0,0 +1,27 @@
+/*
+ * Copyright © 2017 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#ifndef MINMEA_COMPAT_H_
+#define MINMEA_COMPAT_H_
+
+#if defined(__TI_ARM__)
+    #include <ti/posix/ccs/sys/types.h>
+    #include <ti/posix/ccs/time.h>
+#elif defined(__IAR_SYSTEMS_ICC__)
+    #include <ti/posix/iar/sys/types.h>
+    #include <ti/posix/iar/time.h>
+#elif defined(gcc)
+    #include <ti/posix/gcc/sys/types.h>
+    #include <ti/posix/gcc/time.h>
+#endif /* __TI_ARM__ */
+
+#define timegm  mktime
+
+#endif /* MINMEA_COMPAT_H */
+
+/* vim: set ts=4 sw=4 et: */

+ 23 - 0
base_pack/gps_nmea_uart/lib/minmea/compat/minmea_compat_windows.h

@@ -0,0 +1,23 @@
+/*
+ * Copyright © 2017 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#if defined(_MSC_VER)
+
+#if !defined(HAVE_STRUCT_TIMESPEC)
+struct timespec {
+    time_t tv_sec;
+    long tv_nsec;
+};
+#endif
+
+#define inline __inline
+#define timegm _mkgmtime
+
+#endif
+
+/* vim: set ts=4 sw=4 et: */

+ 140 - 0
base_pack/gps_nmea_uart/lib/minmea/example.c

@@ -0,0 +1,140 @@
+/*
+ * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "minmea.h"
+
+#define INDENT_SPACES "  "
+
+int main(void)
+{
+    char line[MINMEA_MAX_SENTENCE_LENGTH];
+    while (fgets(line, sizeof(line), stdin) != NULL) {
+        printf("%s", line);
+        switch (minmea_sentence_id(line, false)) {
+            case MINMEA_SENTENCE_RMC: {
+                struct minmea_sentence_rmc frame;
+                if (minmea_parse_rmc(&frame, line)) {
+                    printf(INDENT_SPACES "$xxRMC: raw coordinates and speed: (%d/%d,%d/%d) %d/%d\n",
+                            frame.latitude.value, frame.latitude.scale,
+                            frame.longitude.value, frame.longitude.scale,
+                            frame.speed.value, frame.speed.scale);
+                    printf(INDENT_SPACES "$xxRMC fixed-point coordinates and speed scaled to three decimal places: (%d,%d) %d\n",
+                            minmea_rescale(&frame.latitude, 1000),
+                            minmea_rescale(&frame.longitude, 1000),
+                            minmea_rescale(&frame.speed, 1000));
+                    printf(INDENT_SPACES "$xxRMC floating point degree coordinates and speed: (%f,%f) %f\n",
+                            minmea_tocoord(&frame.latitude),
+                            minmea_tocoord(&frame.longitude),
+                            minmea_tofloat(&frame.speed));
+                }
+                else {
+                    printf(INDENT_SPACES "$xxRMC sentence is not parsed\n");
+                }
+            } break;
+
+            case MINMEA_SENTENCE_GGA: {
+                struct minmea_sentence_gga frame;
+                if (minmea_parse_gga(&frame, line)) {
+                    printf(INDENT_SPACES "$xxGGA: fix quality: %d\n", frame.fix_quality);
+                }
+                else {
+                    printf(INDENT_SPACES "$xxGGA sentence is not parsed\n");
+                }
+            } break;
+
+            case MINMEA_SENTENCE_GST: {
+                struct minmea_sentence_gst frame;
+                if (minmea_parse_gst(&frame, line)) {
+                    printf(INDENT_SPACES "$xxGST: raw latitude,longitude and altitude error deviation: (%d/%d,%d/%d,%d/%d)\n",
+                            frame.latitude_error_deviation.value, frame.latitude_error_deviation.scale,
+                            frame.longitude_error_deviation.value, frame.longitude_error_deviation.scale,
+                            frame.altitude_error_deviation.value, frame.altitude_error_deviation.scale);
+                    printf(INDENT_SPACES "$xxGST fixed point latitude,longitude and altitude error deviation"
+                           " scaled to one decimal place: (%d,%d,%d)\n",
+                            minmea_rescale(&frame.latitude_error_deviation, 10),
+                            minmea_rescale(&frame.longitude_error_deviation, 10),
+                            minmea_rescale(&frame.altitude_error_deviation, 10));
+                    printf(INDENT_SPACES "$xxGST floating point degree latitude, longitude and altitude error deviation: (%f,%f,%f)",
+                            minmea_tofloat(&frame.latitude_error_deviation),
+                            minmea_tofloat(&frame.longitude_error_deviation),
+                            minmea_tofloat(&frame.altitude_error_deviation));
+                }
+                else {
+                    printf(INDENT_SPACES "$xxGST sentence is not parsed\n");
+                }
+            } break;
+
+            case MINMEA_SENTENCE_GSV: {
+                struct minmea_sentence_gsv frame;
+                if (minmea_parse_gsv(&frame, line)) {
+                    printf(INDENT_SPACES "$xxGSV: message %d of %d\n", frame.msg_nr, frame.total_msgs);
+                    printf(INDENT_SPACES "$xxGSV: satellites in view: %d\n", frame.total_sats);
+                    for (int i = 0; i < 4; i++)
+                        printf(INDENT_SPACES "$xxGSV: sat nr %d, elevation: %d, azimuth: %d, snr: %d dbm\n",
+                            frame.sats[i].nr,
+                            frame.sats[i].elevation,
+                            frame.sats[i].azimuth,
+                            frame.sats[i].snr);
+                }
+                else {
+                    printf(INDENT_SPACES "$xxGSV sentence is not parsed\n");
+                }
+            } break;
+
+            case MINMEA_SENTENCE_VTG: {
+               struct minmea_sentence_vtg frame;
+               if (minmea_parse_vtg(&frame, line)) {
+                    printf(INDENT_SPACES "$xxVTG: true track degrees = %f\n",
+                           minmea_tofloat(&frame.true_track_degrees));
+                    printf(INDENT_SPACES "        magnetic track degrees = %f\n",
+                           minmea_tofloat(&frame.magnetic_track_degrees));
+                    printf(INDENT_SPACES "        speed knots = %f\n",
+                            minmea_tofloat(&frame.speed_knots));
+                    printf(INDENT_SPACES "        speed kph = %f\n",
+                            minmea_tofloat(&frame.speed_kph));
+               }
+               else {
+                    printf(INDENT_SPACES "$xxVTG sentence is not parsed\n");
+               }
+            } break;
+
+            case MINMEA_SENTENCE_ZDA: {
+                struct minmea_sentence_zda frame;
+                if (minmea_parse_zda(&frame, line)) {
+                    printf(INDENT_SPACES "$xxZDA: %d:%d:%d %02d.%02d.%d UTC%+03d:%02d\n",
+                           frame.time.hours,
+                           frame.time.minutes,
+                           frame.time.seconds,
+                           frame.date.day,
+                           frame.date.month,
+                           frame.date.year,
+                           frame.hour_offset,
+                           frame.minute_offset);
+                }
+                else {
+                    printf(INDENT_SPACES "$xxZDA sentence is not parsed\n");
+                }
+            } break;
+
+            case MINMEA_INVALID: {
+                printf(INDENT_SPACES "$xxxxx sentence is not valid\n");
+            } break;
+
+            default: {
+                printf(INDENT_SPACES "$xxxxx sentence is not parsed\n");
+            } break;
+        }
+    }
+
+    return 0;
+}
+
+/* vim: set ts=4 sw=4 et: */

+ 679 - 0
base_pack/gps_nmea_uart/lib/minmea/minmea.c

@@ -0,0 +1,679 @@
+/*
+ * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#include "minmea.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#define boolstr(s) ((s) ? "true" : "false")
+
+static int hex2int(char c)
+{
+    if (c >= '0' && c <= '9')
+        return c - '0';
+    if (c >= 'A' && c <= 'F')
+        return c - 'A' + 10;
+    if (c >= 'a' && c <= 'f')
+        return c - 'a' + 10;
+    return -1;
+}
+
+uint8_t minmea_checksum(const char *sentence)
+{
+    // Support senteces with or without the starting dollar sign.
+    if (*sentence == '$')
+        sentence++;
+
+    uint8_t checksum = 0x00;
+
+    // The optional checksum is an XOR of all bytes between "$" and "*".
+    while (*sentence && *sentence != '*')
+        checksum ^= *sentence++;
+
+    return checksum;
+}
+
+bool minmea_check(const char *sentence, bool strict)
+{
+    uint8_t checksum = 0x00;
+
+    // A valid sentence starts with "$".
+    if (*sentence++ != '$')
+        return false;
+
+    // The optional checksum is an XOR of all bytes between "$" and "*".
+    while (*sentence && *sentence != '*' && isprint((unsigned char) *sentence))
+        checksum ^= *sentence++;
+
+    // If checksum is present...
+    if (*sentence == '*') {
+        // Extract checksum.
+        sentence++;
+        int upper = hex2int(*sentence++);
+        if (upper == -1)
+            return false;
+        int lower = hex2int(*sentence++);
+        if (lower == -1)
+            return false;
+        int expected = upper << 4 | lower;
+
+        // Check for checksum mismatch.
+        if (checksum != expected)
+            return false;
+    } else if (strict) {
+        // Discard non-checksummed frames in strict mode.
+        return false;
+    }
+
+    // The only stuff allowed at this point is a newline.
+    while (*sentence == '\r' || *sentence == '\n') {
+        sentence++;
+    }
+    
+    if (*sentence) {
+        return false;
+    }
+
+    return true;
+}
+
+bool minmea_scan(const char *sentence, const char *format, ...)
+{
+    bool result = false;
+    bool optional = false;
+
+    if (sentence == NULL)
+        return false;
+
+    va_list ap;
+    va_start(ap, format);
+
+    const char *field = sentence;
+#define next_field() \
+    do { \
+        /* Progress to the next field. */ \
+        while (minmea_isfield(*sentence)) \
+            sentence++; \
+        /* Make sure there is a field there. */ \
+        if (*sentence == ',') { \
+            sentence++; \
+            field = sentence; \
+        } else { \
+            field = NULL; \
+        } \
+    } while (0)
+
+    while (*format) {
+        char type = *format++;
+
+        if (type == ';') {
+            // All further fields are optional.
+            optional = true;
+            continue;
+        }
+
+        if (!field && !optional) {
+            // Field requested but we ran out if input. Bail out.
+            goto parse_error;
+        }
+
+        switch (type) {
+            case 'c': { // Single character field (char).
+                char value = '\0';
+
+                if (field && minmea_isfield(*field))
+                    value = *field;
+
+                *va_arg(ap, char *) = value;
+            } break;
+
+            case 'd': { // Single character direction field (int).
+                int value = 0;
+
+                if (field && minmea_isfield(*field)) {
+                    switch (*field) {
+                        case 'N':
+                        case 'E':
+                            value = 1;
+                            break;
+                        case 'S':
+                        case 'W':
+                            value = -1;
+                            break;
+                        default:
+                            goto parse_error;
+                    }
+                }
+
+                *va_arg(ap, int *) = value;
+            } break;
+
+            case 'f': { // Fractional value with scale (struct minmea_float).
+                int sign = 0;
+                int_least32_t value = -1;
+                int_least32_t scale = 0;
+
+                if (field) {
+                    while (minmea_isfield(*field)) {
+                        if (*field == '+' && !sign && value == -1) {
+                            sign = 1;
+                        } else if (*field == '-' && !sign && value == -1) {
+                            sign = -1;
+                        } else if (isdigit((unsigned char) *field)) {
+                            int digit = *field - '0';
+                            if (value == -1)
+                                value = 0;
+                            if (value > (INT_LEAST32_MAX-digit) / 10) {
+                                /* we ran out of bits, what do we do? */
+                                if (scale) {
+                                    /* truncate extra precision */
+                                    break;
+                                } else {
+                                    /* integer overflow. bail out. */
+                                    goto parse_error;
+                                }
+                            }
+                            value = (10 * value) + digit;
+                            if (scale)
+                                scale *= 10;
+                        } else if (*field == '.' && scale == 0) {
+                            scale = 1;
+                        } else if (*field == ' ') {
+                            /* Allow spaces at the start of the field. Not NMEA
+                             * conformant, but some modules do this. */
+                            if (sign != 0 || value != -1 || scale != 0)
+                                goto parse_error;
+                        } else {
+                            goto parse_error;
+                        }
+                        field++;
+                    }
+                }
+
+                if ((sign || scale) && value == -1)
+                    goto parse_error;
+
+                if (value == -1) {
+                    /* No digits were scanned. */
+                    value = 0;
+                    scale = 0;
+                } else if (scale == 0) {
+                    /* No decimal point. */
+                    scale = 1;
+                }
+                if (sign)
+                    value *= sign;
+
+                *va_arg(ap, struct minmea_float *) = (struct minmea_float) {value, scale};
+            } break;
+
+            case 'i': { // Integer value, default 0 (int).
+                int value = 0;
+
+                if (field) {
+                    char *endptr;
+                    value = strtol(field, &endptr, 10);
+                    if (minmea_isfield(*endptr))
+                        goto parse_error;
+                }
+
+                *va_arg(ap, int *) = value;
+            } break;
+
+            case 's': { // String value (char *).
+                char *buf = va_arg(ap, char *);
+
+                if (field) {
+                    while (minmea_isfield(*field))
+                        *buf++ = *field++;
+                }
+
+                *buf = '\0';
+            } break;
+
+            case 't': { // NMEA talker+sentence identifier (char *).
+                // This field is always mandatory.
+                if (!field)
+                    goto parse_error;
+
+                if (field[0] != '$')
+                    goto parse_error;
+                for (int f=0; f<5; f++)
+                    if (!minmea_isfield(field[1+f]))
+                        goto parse_error;
+
+                char *buf = va_arg(ap, char *);
+                memcpy(buf, field+1, 5);
+                buf[5] = '\0';
+            } break;
+
+            case 'D': { // Date (int, int, int), -1 if empty.
+                struct minmea_date *date = va_arg(ap, struct minmea_date *);
+
+                int d = -1, m = -1, y = -1;
+
+                if (field && minmea_isfield(*field)) {
+                    // Always six digits.
+                    for (int f=0; f<6; f++)
+                        if (!isdigit((unsigned char) field[f]))
+                            goto parse_error;
+
+                    char dArr[] = {field[0], field[1], '\0'};
+                    char mArr[] = {field[2], field[3], '\0'};
+                    char yArr[] = {field[4], field[5], '\0'};
+                    d = strtol(dArr, NULL, 10);
+                    m = strtol(mArr, NULL, 10);
+                    y = strtol(yArr, NULL, 10);
+                }
+
+                date->day = d;
+                date->month = m;
+                date->year = y;
+            } break;
+
+            case 'T': { // Time (int, int, int, int), -1 if empty.
+                struct minmea_time *time_ = va_arg(ap, struct minmea_time *);
+
+                int h = -1, i = -1, s = -1, u = -1;
+
+                if (field && minmea_isfield(*field)) {
+                    // Minimum required: integer time.
+                    for (int f=0; f<6; f++)
+                        if (!isdigit((unsigned char) field[f]))
+                            goto parse_error;
+
+                    char hArr[] = {field[0], field[1], '\0'};
+                    char iArr[] = {field[2], field[3], '\0'};
+                    char sArr[] = {field[4], field[5], '\0'};
+                    h = strtol(hArr, NULL, 10);
+                    i = strtol(iArr, NULL, 10);
+                    s = strtol(sArr, NULL, 10);
+                    field += 6;
+
+                    // Extra: fractional time. Saved as microseconds.
+                    if (*field++ == '.') {
+                        uint32_t value = 0;
+                        uint32_t scale = 1000000LU;
+                        while (isdigit((unsigned char) *field) && scale > 1) {
+                            value = (value * 10) + (*field++ - '0');
+                            scale /= 10;
+                        }
+                        u = value * scale;
+                    } else {
+                        u = 0;
+                    }
+                }
+
+                time_->hours = h;
+                time_->minutes = i;
+                time_->seconds = s;
+                time_->microseconds = u;
+            } break;
+
+            case '_': { // Ignore the field.
+            } break;
+
+            default: { // Unknown.
+                goto parse_error;
+            }
+        }
+
+        next_field();
+    }
+
+    result = true;
+
+parse_error:
+    va_end(ap);
+    return result;
+}
+
+bool minmea_talker_id(char talker[3], const char *sentence)
+{
+    char type[6];
+    if (!minmea_scan(sentence, "t", type))
+        return false;
+
+    talker[0] = type[0];
+    talker[1] = type[1];
+    talker[2] = '\0';
+
+    return true;
+}
+
+enum minmea_sentence_id minmea_sentence_id(const char *sentence, bool strict)
+{
+    if (!minmea_check(sentence, strict))
+        return MINMEA_INVALID;
+
+    char type[6];
+    if (!minmea_scan(sentence, "t", type))
+        return MINMEA_INVALID;
+
+    if (!strcmp(type+2, "GBS"))
+        return MINMEA_SENTENCE_GBS;
+    if (!strcmp(type+2, "GGA"))
+        return MINMEA_SENTENCE_GGA;
+    if (!strcmp(type+2, "GLL"))
+        return MINMEA_SENTENCE_GLL;
+    if (!strcmp(type+2, "GSA"))
+        return MINMEA_SENTENCE_GSA;
+    if (!strcmp(type+2, "GST"))
+        return MINMEA_SENTENCE_GST;
+    if (!strcmp(type+2, "GSV"))
+        return MINMEA_SENTENCE_GSV;
+    if (!strcmp(type+2, "RMC"))
+        return MINMEA_SENTENCE_RMC;
+    if (!strcmp(type+2, "VTG"))
+        return MINMEA_SENTENCE_VTG;
+    if (!strcmp(type+2, "ZDA"))
+        return MINMEA_SENTENCE_ZDA;
+
+    return MINMEA_UNKNOWN;
+}
+
+bool minmea_parse_gbs(struct minmea_sentence_gbs *frame, const char *sentence)
+{
+    // $GNGBS,170556.00,3.0,2.9,8.3,,,,*5C
+    char type[6];
+    if (!minmea_scan(sentence, "tTfffifff",
+            type,
+            &frame->time,
+            &frame->err_latitude,
+            &frame->err_longitude,
+            &frame->err_altitude,
+            &frame->svid,
+            &frame->prob,
+            &frame->bias,
+            &frame->stddev
+            ))
+        return false;
+    if (strcmp(type+2, "GBS"))
+        return false;
+
+    return true;
+}
+
+bool minmea_parse_rmc(struct minmea_sentence_rmc *frame, const char *sentence)
+{
+    // $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
+    char type[6];
+    char validity;
+    int latitude_direction;
+    int longitude_direction;
+    int variation_direction;
+    if (!minmea_scan(sentence, "tTcfdfdffDfd",
+            type,
+            &frame->time,
+            &validity,
+            &frame->latitude, &latitude_direction,
+            &frame->longitude, &longitude_direction,
+            &frame->speed,
+            &frame->course,
+            &frame->date,
+            &frame->variation, &variation_direction))
+        return false;
+    if (strcmp(type+2, "RMC"))
+        return false;
+
+    frame->valid = (validity == 'A');
+    frame->latitude.value *= latitude_direction;
+    frame->longitude.value *= longitude_direction;
+    frame->variation.value *= variation_direction;
+
+    return true;
+}
+
+bool minmea_parse_gga(struct minmea_sentence_gga *frame, const char *sentence)
+{
+    // $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
+    char type[6];
+    int latitude_direction;
+    int longitude_direction;
+
+    if (!minmea_scan(sentence, "tTfdfdiiffcfcf_",
+            type,
+            &frame->time,
+            &frame->latitude, &latitude_direction,
+            &frame->longitude, &longitude_direction,
+            &frame->fix_quality,
+            &frame->satellites_tracked,
+            &frame->hdop,
+            &frame->altitude, &frame->altitude_units,
+            &frame->height, &frame->height_units,
+            &frame->dgps_age))
+        return false;
+    if (strcmp(type+2, "GGA"))
+        return false;
+
+    frame->latitude.value *= latitude_direction;
+    frame->longitude.value *= longitude_direction;
+
+    return true;
+}
+
+bool minmea_parse_gsa(struct minmea_sentence_gsa *frame, const char *sentence)
+{
+    // $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
+    char type[6];
+
+    if (!minmea_scan(sentence, "tciiiiiiiiiiiiifff",
+            type,
+            &frame->mode,
+            &frame->fix_type,
+            &frame->sats[0],
+            &frame->sats[1],
+            &frame->sats[2],
+            &frame->sats[3],
+            &frame->sats[4],
+            &frame->sats[5],
+            &frame->sats[6],
+            &frame->sats[7],
+            &frame->sats[8],
+            &frame->sats[9],
+            &frame->sats[10],
+            &frame->sats[11],
+            &frame->pdop,
+            &frame->hdop,
+            &frame->vdop))
+        return false;
+    if (strcmp(type+2, "GSA"))
+        return false;
+
+    return true;
+}
+
+bool minmea_parse_gll(struct minmea_sentence_gll *frame, const char *sentence)
+{
+    // $GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41$;
+    char type[6];
+    int latitude_direction;
+    int longitude_direction;
+
+    if (!minmea_scan(sentence, "tfdfdTc;c",
+            type,
+            &frame->latitude, &latitude_direction,
+            &frame->longitude, &longitude_direction,
+            &frame->time,
+            &frame->status,
+            &frame->mode))
+        return false;
+    if (strcmp(type+2, "GLL"))
+        return false;
+
+    frame->latitude.value *= latitude_direction;
+    frame->longitude.value *= longitude_direction;
+
+    return true;
+}
+
+bool minmea_parse_gst(struct minmea_sentence_gst *frame, const char *sentence)
+{
+    // $GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58
+    char type[6];
+
+    if (!minmea_scan(sentence, "tTfffffff",
+            type,
+            &frame->time,
+            &frame->rms_deviation,
+            &frame->semi_major_deviation,
+            &frame->semi_minor_deviation,
+            &frame->semi_major_orientation,
+            &frame->latitude_error_deviation,
+            &frame->longitude_error_deviation,
+            &frame->altitude_error_deviation))
+        return false;
+    if (strcmp(type+2, "GST"))
+        return false;
+
+    return true;
+}
+
+bool minmea_parse_gsv(struct minmea_sentence_gsv *frame, const char *sentence)
+{
+    // $GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74
+    // $GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D
+    // $GPGSV,4,2,11,08,51,203,30,09,45,215,28*75
+    // $GPGSV,4,4,13,39,31,170,27*40
+    // $GPGSV,4,4,13*7B
+    char type[6];
+
+    if (!minmea_scan(sentence, "tiii;iiiiiiiiiiiiiiii",
+            type,
+            &frame->total_msgs,
+            &frame->msg_nr,
+            &frame->total_sats,
+            &frame->sats[0].nr,
+            &frame->sats[0].elevation,
+            &frame->sats[0].azimuth,
+            &frame->sats[0].snr,
+            &frame->sats[1].nr,
+            &frame->sats[1].elevation,
+            &frame->sats[1].azimuth,
+            &frame->sats[1].snr,
+            &frame->sats[2].nr,
+            &frame->sats[2].elevation,
+            &frame->sats[2].azimuth,
+            &frame->sats[2].snr,
+            &frame->sats[3].nr,
+            &frame->sats[3].elevation,
+            &frame->sats[3].azimuth,
+            &frame->sats[3].snr
+            )) {
+        return false;
+    }
+    if (strcmp(type+2, "GSV"))
+        return false;
+
+    return true;
+}
+
+bool minmea_parse_vtg(struct minmea_sentence_vtg *frame, const char *sentence)
+{
+    // $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48
+    // $GPVTG,156.1,T,140.9,M,0.0,N,0.0,K*41
+    // $GPVTG,096.5,T,083.5,M,0.0,N,0.0,K,D*22
+    // $GPVTG,188.36,T,,M,0.820,N,1.519,K,A*3F
+    char type[6];
+    char c_true, c_magnetic, c_knots, c_kph, c_faa_mode;
+
+    if (!minmea_scan(sentence, "t;fcfcfcfcc",
+            type,
+            &frame->true_track_degrees,
+            &c_true,
+            &frame->magnetic_track_degrees,
+            &c_magnetic,
+            &frame->speed_knots,
+            &c_knots,
+            &frame->speed_kph,
+            &c_kph,
+            &c_faa_mode))
+        return false;
+    if (strcmp(type+2, "VTG"))
+        return false;
+    // values are only valid with the accompanying characters
+    if (c_true != 'T')
+        frame->true_track_degrees.scale = 0;
+    if (c_magnetic != 'M')
+        frame->magnetic_track_degrees.scale = 0;
+    if (c_knots != 'N')
+        frame->speed_knots.scale = 0;
+    if (c_kph != 'K')
+        frame->speed_kph.scale = 0;
+    frame->faa_mode = (enum minmea_faa_mode)c_faa_mode;
+
+    return true;
+}
+
+bool minmea_parse_zda(struct minmea_sentence_zda *frame, const char *sentence)
+{
+  // $GPZDA,201530.00,04,07,2002,00,00*60
+  char type[6];
+
+  if(!minmea_scan(sentence, "tTiiiii",
+          type,
+          &frame->time,
+          &frame->date.day,
+          &frame->date.month,
+          &frame->date.year,
+          &frame->hour_offset,
+          &frame->minute_offset))
+      return false;
+  if (strcmp(type+2, "ZDA"))
+      return false;
+
+  // check offsets
+  if (abs(frame->hour_offset) > 13 ||
+      frame->minute_offset > 59 ||
+      frame->minute_offset < 0)
+      return false;
+
+  return true;
+}
+
+int minmea_getdatetime(struct tm *tm, const struct minmea_date *date, const struct minmea_time *time_)
+{
+    if (date->year == -1 || time_->hours == -1)
+        return -1;
+
+    memset(tm, 0, sizeof(*tm));
+    if (date->year < 80) {
+        tm->tm_year = 2000 + date->year - 1900; // 2000-2079
+    } else if (date->year >= 1900) {
+        tm->tm_year = date->year - 1900;        // 4 digit year, use directly
+    } else {
+        tm->tm_year = date->year;               // 1980-1999
+    }
+    tm->tm_mon = date->month - 1;
+    tm->tm_mday = date->day;
+    tm->tm_hour = time_->hours;
+    tm->tm_min = time_->minutes;
+    tm->tm_sec = time_->seconds;
+
+    return 0;
+}
+
+int minmea_gettime(struct timespec *ts, const struct minmea_date *date, const struct minmea_time *time_)
+{
+    struct tm tm;
+    if (minmea_getdatetime(&tm, date, time_))
+        return -1;
+
+    time_t timestamp = timegm(&tm); /* See README.md if your system lacks timegm(). */
+    if (timestamp != (time_t)-1) {
+        ts->tv_sec = timestamp;
+        ts->tv_nsec = time_->microseconds * 1000;
+        return 0;
+    } else {
+        return -1;
+    }
+}
+
+/* vim: set ts=4 sw=4 et: */

+ 42 - 42
base_pack/gps_nmea_uart/minmea.h → base_pack/gps_nmea_uart/lib/minmea/minmea.h

@@ -87,10 +87,8 @@ struct minmea_sentence_gga {
     int fix_quality;
     int satellites_tracked;
     struct minmea_float hdop;
-    struct minmea_float altitude;
-    char altitude_units;
-    struct minmea_float height;
-    char height_units;
+    struct minmea_float altitude; char altitude_units;
+    struct minmea_float height; char height_units;
     struct minmea_float dgps_age;
 };
 
@@ -181,22 +179,22 @@ struct minmea_sentence_zda {
 /**
  * Calculate raw sentence checksum. Does not check sentence integrity.
  */
-uint8_t minmea_checksum(const char* sentence);
+uint8_t minmea_checksum(const char *sentence);
 
 /**
  * Check sentence validity and checksum. Returns true for valid sentences.
  */
-bool minmea_check(const char* sentence, bool strict);
+bool minmea_check(const char *sentence, bool strict);
 
 /**
  * Determine talker identifier.
  */
-bool minmea_talker_id(char talker[3], const char* sentence);
+bool minmea_talker_id(char talker[3], const char *sentence);
 
 /**
  * Determine sentence identifier.
  */
-enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict);
+enum minmea_sentence_id minmea_sentence_id(const char *sentence, bool strict);
 
 /**
  * Scanf-like processor for NMEA sentences. Supports the following formats:
@@ -212,70 +210,72 @@ enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict);
  * ; - following fields are optional
  * Returns true on success. See library source code for details.
  */
-bool minmea_scan(const char* sentence, const char* format, ...);
+bool minmea_scan(const char *sentence, const char *format, ...);
 
 /*
  * Parse a specific type of sentence. Return true on success.
  */
-bool minmea_parse_gbs(struct minmea_sentence_gbs* frame, const char* sentence);
-bool minmea_parse_rmc(struct minmea_sentence_rmc* frame, const char* sentence);
-bool minmea_parse_gga(struct minmea_sentence_gga* frame, const char* sentence);
-bool minmea_parse_gsa(struct minmea_sentence_gsa* frame, const char* sentence);
-bool minmea_parse_gll(struct minmea_sentence_gll* frame, const char* sentence);
-bool minmea_parse_gst(struct minmea_sentence_gst* frame, const char* sentence);
-bool minmea_parse_gsv(struct minmea_sentence_gsv* frame, const char* sentence);
-bool minmea_parse_vtg(struct minmea_sentence_vtg* frame, const char* sentence);
-bool minmea_parse_zda(struct minmea_sentence_zda* frame, const char* sentence);
+bool minmea_parse_gbs(struct minmea_sentence_gbs *frame, const char *sentence);
+bool minmea_parse_rmc(struct minmea_sentence_rmc *frame, const char *sentence);
+bool minmea_parse_gga(struct minmea_sentence_gga *frame, const char *sentence);
+bool minmea_parse_gsa(struct minmea_sentence_gsa *frame, const char *sentence);
+bool minmea_parse_gll(struct minmea_sentence_gll *frame, const char *sentence);
+bool minmea_parse_gst(struct minmea_sentence_gst *frame, const char *sentence);
+bool minmea_parse_gsv(struct minmea_sentence_gsv *frame, const char *sentence);
+bool minmea_parse_vtg(struct minmea_sentence_vtg *frame, const char *sentence);
+bool minmea_parse_zda(struct minmea_sentence_zda *frame, const char *sentence);
 
 /**
  * Convert GPS UTC date/time representation to a UNIX calendar time.
  */
-int minmea_getdatetime(
-    struct tm* tm,
-    const struct minmea_date* date,
-    const struct minmea_time* time_);
+int minmea_getdatetime(struct tm *tm, const struct minmea_date *date, const struct minmea_time *time_);
 
 /**
  * Convert GPS UTC date/time representation to a UNIX timestamp.
  */
-int minmea_gettime(
-    struct timespec* ts,
-    const struct minmea_date* date,
-    const struct minmea_time* time_);
+int minmea_gettime(struct timespec *ts, const struct minmea_date *date, const struct minmea_time *time_);
 
 /**
  * Rescale a fixed-point value to a different scale. Rounds towards zero.
  */
-static inline int_least32_t minmea_rescale(const struct minmea_float* f, int_least32_t new_scale) {
-    if(f->scale == 0) return 0;
-    if(f->scale == new_scale) return f->value;
-    if(f->scale > new_scale)
-        return (f->value + ((f->value > 0) - (f->value < 0)) * f->scale / new_scale / 2) /
-               (f->scale / new_scale);
+static inline int_least32_t minmea_rescale(const struct minmea_float *f, int_least32_t new_scale)
+{
+    if (f->scale == 0)
+        return 0;
+    if (f->scale == new_scale)
+        return f->value;
+    if (f->scale > new_scale)
+        return (f->value + ((f->value > 0) - (f->value < 0)) * f->scale/new_scale/2) / (f->scale/new_scale);
     else
-        return f->value * (new_scale / f->scale);
+        return f->value * (new_scale/f->scale);
 }
 
 /**
  * Convert a fixed-point value to a floating-point value.
  * Returns NaN for "unknown" values.
  */
-static inline float minmea_tofloat(const struct minmea_float* f) {
-    if(f->scale == 0) return NAN;
-    return (float)f->value / (float)f->scale;
+static inline float minmea_tofloat(const struct minmea_float *f)
+{
+    if (f->scale == 0)
+        return NAN;
+    return (float) f->value / (float) f->scale;
 }
 
 /**
  * Convert a raw coordinate to a floating point DD.DDD... value.
  * Returns NaN for "unknown" values.
  */
-static inline float minmea_tocoord(const struct minmea_float* f) {
-    if(f->scale == 0) return NAN;
-    if(f->scale > (INT_LEAST32_MAX / 100)) return NAN;
-    if(f->scale < (INT_LEAST32_MIN / 100)) return NAN;
+static inline float minmea_tocoord(const struct minmea_float *f)
+{
+    if (f->scale == 0)
+        return NAN;
+    if (f->scale  > (INT_LEAST32_MAX / 100))
+        return NAN;
+    if (f->scale < (INT_LEAST32_MIN / 100))
+        return NAN;
     int_least32_t degrees = f->value / (f->scale * 100);
     int_least32_t minutes = f->value % (f->scale * 100);
-    return (float)degrees + (float)minutes / (60 * f->scale);
+    return (float) degrees + (float) minutes / (60 * f->scale);
 }
 
 /**
@@ -283,7 +283,7 @@ static inline float minmea_tocoord(const struct minmea_float* f) {
  * sentence data field.
  */
 static inline bool minmea_isfield(char c) {
-    return isprint((unsigned char)c) && c != ',' && c != '*';
+    return isprint((unsigned char) c) && c != ',' && c != '*';
 }
 
 #ifdef __cplusplus

+ 1207 - 0
base_pack/gps_nmea_uart/lib/minmea/tests.c

@@ -0,0 +1,1207 @@
+/*
+ * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
+ * This program is free software. It comes without any warranty, to the extent
+ * permitted by applicable law. You can redistribute it and/or modify it under
+ * the terms of the Do What The Fuck You Want To Public License, Version 2, as
+ * published by Sam Hocevar. See the COPYING file for more details.
+ */
+
+#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
+#pragma GCC diagnostic ignored "-Wtype-limits"
+
+#include <stdlib.h>
+#include <string.h>
+#include <check.h>
+
+#include "minmea.h"
+
+static const char *valid_sentences_nochecksum[] = {
+    "$GPTXT,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+    "$GPTXT,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
+    "$GPTXT,hello\n",
+    "$GPTXT,hello\r",
+    "$GPTXT,hello\r\n",
+    "$GPTXT,hello\r\n\r\n",
+    "$GPTXT,hello\n\r\r\n",
+    NULL,
+};
+
+static const char *valid_sentences_checksum[] = {
+    "$GPTXT,01,01,02,ANTSTATUS=INIT*25",
+    "$GPRMC,,V,,,,,,,,,,N*53",
+    "$GPVTG,,,,,,,,,N*30",
+    "$GPGGA,,,,,,0,00,99.99,,,,,,*48",
+    "$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30",
+    "$GPGLL,,,,,,V,N*64",
+    "$GPXTE,A,A,0.67,L,N*6F",
+    "$GPXTE,A,A,0.67,L,N*6f",
+    "$GPGGA,123204.00,5106.94086,N,01701.51680,E,1,06,3.86,127.9,M,40.5,M,,*51",
+    "$GPGSA,A,3,02,08,09,05,04,26,,,,,,,4.92,3.86,3.05*00",
+    "$GPGSV,4,1,13,02,28,259,33,04,12,212,27,05,34,305,30,07,79,138,*7F",
+    "$GPGSV,4,2,13,08,51,203,30,09,45,215,28,10,69,197,19,13,47,081,*76",
+    "$GPGSV,4,3,13,16,20,040,17,26,08,271,30,28,01,168,18,33,24,219,27*74",
+    "$GPGSV,4,4,13,39,31,170,27*40",
+    "$GPGLL,5106.94086,N,01701.51680,E,123204.00,A,A*63",
+    "$GPRMC,123205.00,A,5106.94085,N,01701.51689,E,0.016,,280214,,,A*7B",
+    "$GPVTG,,T,,M,0.016,N,0.030,K,A*27",
+    "$GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58",
+    "$GPZDA,160012.71,11,03,2004,-1,00*7D",
+    "$GNGBS,170556.00,3.0,2.9,8.3,,,,*5C",
+    NULL,
+};
+
+static const char *invalid_sentences[] = {
+    "$GPTXT,01,01,02,ANTSTATUS=INIT*26",
+    "$GPRMC,,V,,,,,,,,,,N*532",
+    "$GPVTG,,,,\xff,,,,,N*30",
+    "$$GPGGA,,,,,,0,00,99.99,,,,,,*48",
+    "GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30",
+    "gps: $GPGLL,,,,,,V,N",
+    "$GPXTE,A,A,0.67,L,N*6e",
+    "$GPXTE,A,A,0.67,L,N*6g",
+    "$GPTXT,hello\n ",
+    "$GPTXT,hello\r*24",
+    "$GPTXT,hello\r\n$",
+    NULL,
+};
+
+START_TEST(test_minmea_checksum)
+{
+    ck_assert_int_eq(minmea_checksum(""), 0x00);
+    ck_assert_int_eq(minmea_checksum("$"), 0x00);
+    ck_assert_int_eq(minmea_checksum("*"), 0x00);
+    ck_assert_int_eq(minmea_checksum("$*"), 0x00);
+    ck_assert_int_eq(minmea_checksum("$GPTXT,01,01,02,ANTSTATUS=INIT*25"), 0x25);
+    ck_assert_int_eq(minmea_checksum("$GPTXT,01,01,02,ANTSTATUS=INIT"), 0x25);
+    ck_assert_int_eq(minmea_checksum("GPTXT,01,01,02,ANTSTATUS=INIT*25"), 0x25);
+    ck_assert_int_eq(minmea_checksum("GPTXT,01,01,02,ANTSTATUS=INIT"), 0x25);
+    ck_assert_int_eq(minmea_checksum("$GPXTE,A,A,0.67,L,N*6F"), 0x6f);
+    ck_assert_int_eq(minmea_checksum("GPXTE,A,A,0.67,L,N*6f"), 0x6f);
+}
+END_TEST
+
+START_TEST(test_minmea_check)
+{
+    for (const char **sentence=valid_sentences_nochecksum; *sentence; sentence++) {
+        ck_assert_msg(minmea_check(*sentence, false) == true, "%s", *sentence);
+        ck_assert_msg(minmea_check(*sentence, true) == false, "%s", *sentence);
+    }
+
+    for (const char **sentence=valid_sentences_checksum; *sentence; sentence++) {
+        ck_assert_msg(minmea_check(*sentence, false) == true, "%s", *sentence);
+        ck_assert_msg(minmea_check(*sentence, true) == true, "%s", *sentence);
+    }
+
+    for (const char **sentence=invalid_sentences; *sentence; sentence++) {
+        ck_assert_msg(minmea_check(*sentence, false) == false, "%s", *sentence);
+        ck_assert_msg(minmea_check(*sentence, true) == false, "%s", *sentence);
+    }
+}
+END_TEST
+
+START_TEST(test_minmea_scan_c)
+{
+    char ch, extra;
+
+    ck_assert(minmea_scan("A,123.45", "c", &ch) == true);
+    ck_assert_int_eq(ch, 'A');
+
+    ck_assert(minmea_scan("WUT,123.45", "c", &ch) == true);
+    ck_assert_int_eq(ch, 'W');
+
+    ck_assert(minmea_scan(",123.45", "c", &ch) == true);
+    ck_assert_int_eq(ch, '\0');
+
+    ck_assert(minmea_scan("A,B", "cc", &ch, &extra) == true);
+    ck_assert_int_eq(ch, 'A');
+    ck_assert_int_eq(extra, 'B');
+
+    ck_assert(minmea_scan("C", "cc", &ch, &extra) == false);
+
+    ck_assert(minmea_scan("D", "c;c", &ch, &extra) == true);
+    ck_assert_int_eq(ch, 'D');
+    ck_assert_int_eq(extra, '\0');
+    ck_assert(minmea_scan("E,F", "c;c", &ch, &extra) == true);
+    ck_assert_int_eq(ch, 'E');
+    ck_assert_int_eq(extra, 'F');
+}
+END_TEST
+
+START_TEST(test_minmea_scan_d)
+{
+    int direction;
+
+    ck_assert(minmea_scan("K", "d", &direction) == false);
+
+    ck_assert(minmea_scan("", "d", &direction) == true);
+    ck_assert(minmea_scan(",foo", "d", &direction) == true);
+    ck_assert_int_eq(direction, 0);
+    ck_assert(minmea_scan("N", "d", &direction) == true);
+    ck_assert_int_eq(direction, 1);
+    ck_assert(minmea_scan("S,foo", "d", &direction) == true);
+    ck_assert_int_eq(direction, -1);
+    ck_assert(minmea_scan("W", "d", &direction) == true);
+    ck_assert_int_eq(direction, -1);
+    ck_assert(minmea_scan("E,foo", "d", &direction) == true);
+    ck_assert_int_eq(direction, 1);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_f)
+{
+    struct minmea_float f;
+
+    ck_assert(minmea_scan("-", "f", &f) == false);
+    ck_assert(minmea_scan("10-", "f", &f) == false);
+    ck_assert(minmea_scan("+-10", "f", &f) == false);
+    ck_assert(minmea_scan("12..45", "f", &f) == false);
+    ck_assert(minmea_scan("blah", "f", &f) == false);
+    ck_assert(minmea_scan("12.3.4", "f", &f) == false);
+
+    ck_assert(minmea_scan(",", "f", &f) == true);
+    ck_assert_int_eq(f.scale, 0);
+    ck_assert(minmea_scan("", "f", &f) == true);
+    ck_assert_int_eq(f.scale, 0);
+
+    ck_assert(minmea_scan("42", "f", &f) == true);
+    ck_assert_int_eq(f.value, 42);
+    ck_assert_int_eq(f.scale, 1);
+
+    ck_assert(minmea_scan("15.345", "f", &f) == true);
+    ck_assert_int_eq(f.value, 15345);
+    ck_assert_int_eq(f.scale, 1000);
+
+    ck_assert(minmea_scan("-1.23,V", "f", &f) == true);
+    ck_assert_int_eq(f.value, -123);
+    ck_assert_int_eq(f.scale, 100);
+
+    /* the guaranteed range is 32 bits which translates to +-180 degrees
+     * with 5 decimal digits. make sure we support that. */
+    ck_assert(minmea_scan("18000.00000", "f", &f) == true);
+    ck_assert_int_eq(f.value, 1800000000);
+    ck_assert_int_eq(f.scale, 100000);
+    ck_assert(minmea_scan("-18000.00000", "f", &f) == true);
+    ck_assert_int_eq(f.value, -1800000000);
+    ck_assert_int_eq(f.scale, 100000);
+
+    if (sizeof(int_least32_t) == 4) {
+        /* fits in 32 bits */
+        ck_assert(minmea_scan("2147483647", "f", &f) == true);
+        ck_assert_int_eq(f.value, 2147483647);
+        ck_assert_int_eq(f.scale, 1);
+        /* doesn't fit, truncate precision */
+        ck_assert(minmea_scan("2147483.648", "f", &f) == true);
+        ck_assert_int_eq(f.value, 214748364);
+        ck_assert_int_eq(f.scale, 100);
+        /* doesn't fit, bail out */
+        ck_assert(minmea_scan("2147483648", "f", &f) == false);
+    } else if (sizeof(int_least32_t) == 8) {
+        /* Casting to int64_t is ugly, but otherwise we get this on machines with 32-bit int_least32_t:
+         * error: comparison is always false due to limited range of data type [-Werror=type-limits] */
+        /* fits in 64 bits */
+        ck_assert(minmea_scan("9223372036854775807", "f", &f) == true);
+        ck_assert_int_eq((int64_t) f.value, 9223372036854775807LL);
+        ck_assert_int_eq(f.scale, 1);
+        /* doesn't fit, truncate precision */
+        ck_assert(minmea_scan("9223372036854775.808", "f", &f) == true);
+        ck_assert_int_eq((int64_t) f.value, 922337203685477580LL);
+        ck_assert_int_eq(f.scale, 100);
+        /* doesn't fit, bail out */
+        ck_assert(minmea_scan("9223372036854775808", "f", &f) == false);
+    } else {
+        ck_abort_msg("your platform is esoteric. please fix this unit test.");
+    }
+
+    /* optional f.values */
+    ck_assert(minmea_scan("foo", "_;f", &f) == true);
+    ck_assert_int_eq(f.scale, 0);
+    ck_assert(minmea_scan("foo,", "_;f", &f) == true);
+    ck_assert_int_eq(f.scale, 0);
+    ck_assert(minmea_scan("foo,12.3", "_;f", &f) == true);
+    ck_assert_int_eq(f.value, 123);
+    ck_assert_int_eq(f.scale, 10);
+
+    /* accept spaces at the start of the field. some modules do this, unfortunately. */
+    ck_assert(minmea_scan(" -1.23,V", "f", &f) == true);
+    ck_assert_int_eq(f.value, -123);
+    ck_assert_int_eq(f.scale, 100);
+    ck_assert(minmea_scan("     -4.56,V", "f", &f) == true);
+    ck_assert_int_eq(f.value, -456);
+    ck_assert_int_eq(f.scale, 100);
+    ck_assert(minmea_scan("-3.33 ,V", "f", &f) == false);
+    ck_assert(minmea_scan(" -3.33 ,V", "f", &f) == false);
+    ck_assert(minmea_scan("-3. 33,V", "f", &f) == false);
+    ck_assert(minmea_scan("0 .0,V", "f", &f) == false);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_i)
+{
+    int value, extra;
+
+    // valid parses
+    ck_assert(minmea_scan("14", "i", &value) == true);
+    ck_assert_int_eq(value, 14);
+    ck_assert(minmea_scan("-1234", "i", &value) == true);
+    ck_assert_int_eq(value, -1234);
+
+    // empty field
+    ck_assert(minmea_scan("", "i", &value) == true);
+    ck_assert_int_eq(value, 0);
+
+    // invalid value
+    ck_assert(minmea_scan("foo", "i", &value) == false);
+
+    // missing field
+    ck_assert(minmea_scan("41", "ii", &value, &extra) == false);
+
+    /* optional values */
+    ck_assert(minmea_scan("10", "i;i", &value, &extra) == true);
+    ck_assert_int_eq(value, 10);
+    ck_assert(minmea_scan("20,30", "i;i", &value, &extra) == true);
+    ck_assert_int_eq(value, 20);
+    ck_assert_int_eq(extra, 30);
+    ck_assert(minmea_scan("42,foo", "i;i", &value, &extra) == false);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_s)
+{
+    char value[MINMEA_MAX_SENTENCE_LENGTH];
+
+    ck_assert(minmea_scan(",bar,baz", "s", value) == true);
+    ck_assert_str_eq(value, "");
+    ck_assert(minmea_scan("foo,bar,baz", "s", value) == true);
+    ck_assert_str_eq(value, "foo");
+
+    ck_assert(minmea_scan("dummy", "_;s", value) == true);
+    ck_assert_str_eq(value, "");
+    ck_assert(minmea_scan("dummy,foo", "_;s", value) == true);
+    ck_assert_str_eq(value, "foo");
+    ck_assert(minmea_scan("dummy,", "_;s", value) == true);
+    ck_assert_str_eq(value, "");
+}
+END_TEST
+
+START_TEST(test_minmea_scan_t)
+{
+    char buf[7];
+    buf[sizeof(buf)-1] = 0x42;
+
+    ck_assert(minmea_scan("$GPRM,foo,bar,baz", "t", buf) == false);
+    ck_assert(minmea_scan("GPRMC,foo,bar,baz", "t", buf) == false);
+
+    ck_assert(minmea_scan("$GPRMC,foo,bar,baz", "t", buf) == true);
+    ck_assert_str_eq(buf, "GPRMC");
+
+    ck_assert(buf[sizeof(buf)-1] == 0x42);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_D)
+{
+    struct minmea_date d;
+
+    ck_assert(minmea_scan("$GPXXX,3112", "_D", &d) == false);
+    ck_assert(minmea_scan("$GPXXX,foobar", "_D", &d) == false);
+
+    ck_assert(minmea_scan("$GPXXX,311299", "_D", &d) == true);
+    ck_assert_int_eq(d.day, 31);
+    ck_assert_int_eq(d.month, 12);
+    ck_assert_int_eq(d.year, 99);
+
+    ck_assert(minmea_scan("$GPXXX,,,,,,,,,nope", "_D", &d) == true);
+    ck_assert_int_eq(d.day, -1);
+    ck_assert_int_eq(d.month, -1);
+    ck_assert_int_eq(d.year, -1);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_T)
+{
+    struct minmea_time t;
+
+    ck_assert(minmea_scan("$GPXXX,2359", "_T", &t) == false);
+    ck_assert(minmea_scan("$GPXXX,foobar", "_T", &t) == false);
+
+    ck_assert(minmea_scan("$GPXXX,235960", "_T", &t) == true);
+    ck_assert_int_eq(t.hours, 23);
+    ck_assert_int_eq(t.minutes, 59);
+    ck_assert_int_eq(t.seconds, 60);
+    ck_assert_int_eq(t.microseconds, 0);
+
+    ck_assert(minmea_scan("$GPXXX,213700.001", "_T", &t) == true);
+    ck_assert_int_eq(t.hours, 21);
+    ck_assert_int_eq(t.minutes, 37);
+    ck_assert_int_eq(t.seconds, 0);
+    ck_assert_int_eq(t.microseconds, 1000);
+
+    ck_assert(minmea_scan("$GPXXX,,,,,,,nope", "_T", &t) == true);
+    ck_assert_int_eq(t.hours, -1);
+    ck_assert_int_eq(t.minutes, -1);
+    ck_assert_int_eq(t.seconds, -1);
+    ck_assert_int_eq(t.microseconds, -1);
+}
+END_TEST
+
+START_TEST(test_minmea_scan_complex1)
+{
+    const char *sentence = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n";
+    char type[6];
+    struct minmea_time t;
+    struct minmea_float latitude; int latitude_direction;
+    struct minmea_float longitude; int longitude_direction;
+    int fix_quality;
+    int satellites;
+    struct minmea_float hdop;
+    struct minmea_float altitude; char altitude_units;
+    struct minmea_float height; char height_units;
+    ck_assert(minmea_scan(sentence, "tTfdfdiiffcfc__",
+        type,
+        &t,
+        &latitude, &latitude_direction,
+        &longitude, &longitude_direction,
+        &fix_quality,
+        &satellites,
+        &hdop,
+        &altitude, &altitude_units,
+        &height, &height_units) == true);
+    ck_assert_str_eq(type, "GPGGA");
+    ck_assert_int_eq(t.hours, 12);
+    ck_assert_int_eq(t.minutes, 35);
+    ck_assert_int_eq(t.seconds, 19);
+    ck_assert_int_eq(latitude.value, 4807038);
+    ck_assert_int_eq(latitude.scale, 1000);
+    ck_assert_int_eq(latitude_direction, 1);
+    ck_assert_int_eq(longitude.value, 1131000);
+    ck_assert_int_eq(longitude.scale, 1000);
+    ck_assert_int_eq(longitude_direction, 1);
+    ck_assert_int_eq(fix_quality, 1);
+    ck_assert_int_eq(satellites, 8);
+    ck_assert_int_eq(hdop.value, 9);
+    ck_assert_int_eq(hdop.scale, 10);
+    ck_assert_int_eq(altitude.value, 5454);
+    ck_assert_int_eq(altitude.scale, 10);
+    ck_assert_int_eq(altitude_units, 'M');
+    ck_assert_int_eq(height.value, 469);
+    ck_assert_int_eq(height.scale, 10);
+    ck_assert_int_eq(height_units, 'M');
+
+}
+END_TEST
+
+START_TEST(test_minmea_scan_complex2)
+{
+    const char *sentence = "$GPBWC,081837,,,,,,T,,M,,N,*13";
+    char type[6];
+    struct minmea_time t;
+    struct minmea_float latitude; int latitude_direction;
+    struct minmea_float longitude; int longitude_direction;
+    struct minmea_float bearing_true; char bearing_true_mark;
+    struct minmea_float bearing_magnetic; char bearing_magnetic_mark;
+    struct minmea_float distance; char distance_units;
+    char name[MINMEA_MAX_SENTENCE_LENGTH];
+    ck_assert(minmea_scan(sentence, "tTfdfdfcfcfcs",
+        type,
+        &t,
+        &latitude, &latitude_direction,
+        &longitude, &longitude_direction,
+        &bearing_true, &bearing_true_mark,
+        &bearing_magnetic, &bearing_magnetic_mark,
+        &distance, &distance_units,
+        name) == true);
+    ck_assert_str_eq(type, "GPBWC");
+    ck_assert_int_eq(t.hours, 8);
+    ck_assert_int_eq(t.minutes, 18);
+    ck_assert_int_eq(t.seconds, 37);
+    ck_assert_int_eq(latitude.scale, 0);
+    ck_assert_int_eq(latitude_direction, 0);
+    ck_assert_int_eq(longitude.scale, 0);
+    ck_assert_int_eq(longitude_direction, 0);
+    ck_assert_int_eq(bearing_true.scale, 0);
+    ck_assert_int_eq(bearing_true_mark, 'T');
+    ck_assert_int_eq(bearing_magnetic.scale, 0);
+    ck_assert_int_eq(bearing_magnetic_mark, 'M');
+    ck_assert_int_eq(distance.scale, 0);
+    ck_assert_int_eq(distance_units, 'N');
+    ck_assert_str_eq(name, "");
+}
+END_TEST
+
+START_TEST(test_minmea_scan_complex3)
+{
+    const char *sentence = "$GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58";
+    char type[6];
+    struct minmea_time t;
+    struct minmea_float rms_deviation;
+    struct minmea_float semi_major_deviation;
+    struct minmea_float semi_minor_deviation;
+    struct minmea_float semi_major_orientation;
+    struct minmea_float latitude_error_deviation;
+    struct minmea_float longitude_error_deviation;
+    struct minmea_float altitude_error_deviation;
+    ck_assert(minmea_scan(sentence, "tTfffffff",
+        type,
+        &t,
+        &rms_deviation,
+        &semi_major_deviation,
+        &semi_minor_deviation,
+        &semi_major_orientation,
+        &latitude_error_deviation,
+        &longitude_error_deviation,
+        &altitude_error_deviation) == true);
+    ck_assert_str_eq(type, "GPGST");
+    ck_assert_int_eq(t.hours, 2);
+    ck_assert_int_eq(t.minutes, 46);
+    ck_assert_int_eq(t.seconds, 3);
+    ck_assert_int_eq(t.microseconds, 0);
+    ck_assert_int_eq(rms_deviation.value, 32);
+    ck_assert_int_eq(rms_deviation.scale, 10);
+    ck_assert_int_eq(semi_major_deviation.value, 66);
+    ck_assert_int_eq(semi_major_deviation.scale, 10);
+    ck_assert_int_eq(semi_minor_deviation.value, 47);
+    ck_assert_int_eq(semi_minor_deviation.scale, 10);
+    ck_assert_int_eq(semi_major_orientation.value, 473);
+    ck_assert_int_eq(semi_major_orientation.scale, 10);
+    ck_assert_int_eq(latitude_error_deviation.value, 58);
+    ck_assert_int_eq(latitude_error_deviation.scale, 10);
+    ck_assert_int_eq(longitude_error_deviation.value, 56);
+    ck_assert_int_eq(longitude_error_deviation.scale, 10);
+    ck_assert_int_eq(altitude_error_deviation.value, 220);
+    ck_assert_int_eq(altitude_error_deviation.scale, 10);
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gbs1)
+{
+    const char *sentence = "$GNGBS,170556.00,3.0,2.9,8.3,,,,";
+    struct minmea_sentence_gbs frame = {};
+    static const struct minmea_sentence_gbs expected = {
+	    .time = { 17, 5, 56, 0 },
+	    .err_latitude = { 30, 10 },
+	    .err_longitude = { 29, 10 },
+	    .err_altitude = { 83, 10 },
+	    .svid = 0,
+	    .prob = { 0, 0 },
+	    .bias = { 0, 0 },
+	    .stddev = { 0, 0 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == false);
+    ck_assert(minmea_parse_gbs(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gbs2)
+{
+    const char *sentence = "$GPGBS,015509.00,-0.031,-0.186,0.219,19,0.000,-0.354,6.972*4D";
+    struct minmea_sentence_gbs frame = {};
+    static const struct minmea_sentence_gbs expected = {
+        .time = { 1, 55, 9 },
+        .err_latitude = { -31, 1000 },
+        .err_longitude = { -186, 1000 },
+        .err_altitude = { 219, 1000 },
+        .svid = 19,
+        .prob = { 0, 1000 },
+        .bias = { -354, 1000 },
+        .stddev = { 6972, 1000 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gbs(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_rmc1)
+{
+    const char *sentence = "$GPRMC,081836.75,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E";
+    struct minmea_sentence_rmc frame = {};
+    static const struct minmea_sentence_rmc expected = {
+        .time = { 8, 18, 36, 750000 },
+        .valid = true,
+        .latitude = { -375165, 100 },
+        .longitude = { 1450736, 100 },
+        .speed = { 0, 10 },
+        .course = { 3600, 10 },
+        .date = { 13, 9, 98 },
+        .variation = { 113, 10 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == false);
+    ck_assert(minmea_parse_rmc(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_rmc2)
+{
+    const char *sentence = "$GPRMC,,A,3751.65,N,14507.36,W,,,,,";
+    struct minmea_sentence_rmc frame = {};
+    static const struct minmea_sentence_rmc expected = {
+        .time = { -1, -1, -1, -1 },
+        .valid = true,
+        .latitude = { 375165, 100 },
+        .longitude = { -1450736, 100 },
+        .date = { -1, -1, -1 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == false);
+    ck_assert(minmea_parse_rmc(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gga1)
+{
+    const char *sentence = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47";
+    struct minmea_sentence_gga frame = {};
+    struct minmea_sentence_gga expected = {};
+    expected.time = (struct minmea_time) { 12, 35, 19, 0 };
+    expected.latitude = (struct minmea_float) { 4807038, 1000 };
+    expected.longitude = (struct minmea_float) { 1131000, 1000 };
+    expected.fix_quality = 1;
+    expected.satellites_tracked = 8;
+    expected.hdop = (struct minmea_float) { 9, 10 };
+    expected.altitude = (struct minmea_float) { 5454, 10 };
+    expected.altitude_units = 'M';
+    expected.height = (struct minmea_float) { 469, 10 };
+    expected.height_units = 'M';
+    expected.dgps_age = (struct minmea_float) { 0, 0 };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gga(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gst1)
+{
+    const char *sentence = "$GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58";
+    struct minmea_sentence_gst frame = {};
+    struct minmea_sentence_gst expected = {
+        .time = { 2, 46, 3, 0 },
+        .rms_deviation = { 32, 10 },
+        .semi_major_deviation = { 66, 10 },
+        .semi_minor_deviation = { 47, 10 },
+        .semi_major_orientation = { 473, 10 },
+        .latitude_error_deviation = { 58, 10 },
+        .longitude_error_deviation = { 56, 10 },
+        .altitude_error_deviation = { 220, 10 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gst(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsa1)
+{
+    const char *sentence = "$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39";
+    struct minmea_sentence_gsa frame = {};
+    static const struct minmea_sentence_gsa expected = {
+        .mode = MINMEA_GPGSA_MODE_AUTO,
+        .fix_type = MINMEA_GPGSA_FIX_3D,
+        .sats = { 4, 5, 0, 9, 12, 0, 0, 24, 0, 0, 0, 0 },
+        .pdop = { 25, 10 },
+        .hdop = { 13, 10 },
+        .vdop = { 21, 10 },
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsa(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gll1)
+{
+    const char *sentence = "$GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41";
+    struct minmea_sentence_gll frame;
+    struct minmea_sentence_gll expected;
+
+    // clear structs before initialization to enable use of memcmp()
+    // todo: add for other structs
+    memset(&frame, 0, sizeof(frame));
+    memset(&expected, 0, sizeof(expected));
+
+    expected.latitude = (struct minmea_float){ 37232475, 10000 };
+    expected.longitude = (struct minmea_float){ -121583416, 10000 };
+    expected.time = (struct minmea_time){ 16, 12, 29, 487000 };
+    expected.status = MINMEA_GLL_STATUS_DATA_VALID;
+    expected.mode = MINMEA_FAA_MODE_AUTONOMOUS;
+
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gll(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gll2)
+{
+    const char *sentence = "$GPGLL,4916.45,N,12311.12,W,225444,A";
+    struct minmea_sentence_gll frame = {};
+    struct minmea_sentence_gll expected = {
+        .latitude = { 491645, 100 },
+        .longitude = { -1231112, 100 },
+        .time = { 22, 54, 44 },
+        .status = MINMEA_GLL_STATUS_DATA_VALID,
+        .mode = 0,
+    };
+
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == false);
+    ck_assert(minmea_parse_gll(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsv1)
+{
+    const char *sentence = "$GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D";
+    struct minmea_sentence_gsv frame = {};
+    static const struct minmea_sentence_gsv expected = {
+        .total_msgs = 3,
+        .msg_nr = 3,
+        .total_sats = 11,
+        .sats = {
+            {
+                .nr = 22,
+                .elevation = 42,
+                .azimuth = 67,
+                .snr = 42
+            },
+            {
+                .nr = 24,
+                .elevation = 14,
+                .azimuth = 311,
+                .snr = 43
+            },
+            {
+                .nr = 27,
+                .elevation = 5,
+                .azimuth = 244,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            }
+        }
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsv(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsv2)
+{
+    const char *sentence = "$GPGSV,4,2,11,08,51,203,30,09,45,215,28*75";
+    struct minmea_sentence_gsv frame = {};
+    static const struct minmea_sentence_gsv expected = {
+        .total_msgs = 4,
+        .msg_nr = 2,
+        .total_sats = 11,
+        .sats = {
+            {
+                .nr = 8,
+                .elevation = 51,
+                .azimuth = 203,
+                .snr = 30
+            },
+            {
+                .nr = 9,
+                .elevation = 45,
+                .azimuth = 215,
+                .snr = 28
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            }
+        }
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsv(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsv3)
+{
+    const char *sentence = "$GPGSV,4,4,13,39,31,170,27*40";
+    struct minmea_sentence_gsv frame = {};
+    static const struct minmea_sentence_gsv expected = {
+        .total_msgs = 4,
+        .msg_nr = 4,
+        .total_sats = 13,
+        .sats = {
+            {
+                .nr = 39,
+                .elevation = 31,
+                .azimuth = 170,
+                .snr = 27
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            }
+        }
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsv(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsv4)
+{
+    const char *sentence = "$GPGSV,4,4,13*7B";
+    struct minmea_sentence_gsv frame = {};
+    static const struct minmea_sentence_gsv expected = {
+        .total_msgs = 4,
+        .msg_nr = 4,
+        .total_sats = 13,
+        .sats = {
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            },
+            {
+                .nr = 0,
+                .elevation = 0,
+                .azimuth = 0,
+                .snr = 0
+            }
+        }
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsv(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_gsv5)
+{
+    const char *sentence = "$GPGSV,4,1,13,02,28,259,33,04,12,212,27,05,34,305,30,07,79,138,*7F";
+    struct minmea_sentence_gsv frame = {};
+    static const struct minmea_sentence_gsv expected = {
+        .total_msgs = 4,
+        .msg_nr = 1,
+        .total_sats = 13,
+        .sats = {
+            {
+                .nr = 2,
+                .elevation = 28,
+                .azimuth = 259,
+                .snr = 33
+            },
+            {
+                .nr = 4,
+                .elevation = 12,
+                .azimuth = 212,
+                .snr = 27
+            },
+            {
+                .nr = 5,
+                .elevation = 34,
+                .azimuth = 305,
+                .snr = 30
+            },
+            {
+                .nr = 7,
+                .elevation = 79,
+                .azimuth = 138,
+                .snr = 0
+            }
+        }
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_gsv(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+
+START_TEST(test_minmea_parse_vtg1)
+{
+    const char *sentence = "$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48";
+    // clear structs before initialization to enable use of memcmp()
+    struct minmea_sentence_vtg frame = {};
+    struct minmea_sentence_vtg expected = {};
+
+    expected = (struct minmea_sentence_vtg){
+        .true_track_degrees = { 547, 10 },
+        .magnetic_track_degrees = { 344, 10 },
+        .speed_knots = { 55, 10 },
+        .speed_kph = { 102, 10 },
+        .faa_mode = 0,
+    };
+
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_vtg(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_vtg2)
+{
+    const char *sentence = "$GPVTG,188.36,T,,M,0.820,N,1.519,K,A*3F";
+    // clear structs before initialization to enable use of memcmp()
+    struct minmea_sentence_vtg frame = {};
+    struct minmea_sentence_vtg expected = {};
+
+    expected = (struct minmea_sentence_vtg){
+        .true_track_degrees = { 18836, 100 },
+        .magnetic_track_degrees = { 0, 0 },
+        .speed_knots = { 820, 1000 },
+        .speed_kph = { 1519, 1000 },
+        .faa_mode = MINMEA_FAA_MODE_AUTONOMOUS,
+    };
+
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_vtg(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_vtg3)
+{
+    // https://github.com/kosma/minmea/issues/57
+    const char *sentence = "$GNVTG,,,,,,,,,N*2E";
+    // clear structs before initialization to enable use of memcmp()
+    struct minmea_sentence_vtg frame = {};
+    struct minmea_sentence_vtg expected = {};
+    expected = (struct minmea_sentence_vtg){
+        .true_track_degrees = { 0, 0 },
+        .magnetic_track_degrees = { 0, 0 },
+        .speed_knots = { 0, 0 },
+        .speed_kph = { 0, 0 },
+        .faa_mode = MINMEA_FAA_MODE_NOT_VALID,
+    };
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_vtg(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_parse_zda1)
+{
+    const char *sentence = "$GPZDA,160012.71,11,03,2004,-1,00*7D";
+    struct minmea_sentence_zda frame = {};
+    struct minmea_sentence_zda expected = {};
+
+    expected = (struct minmea_sentence_zda) {
+        .time = { 16, 0, 12, 710000 },
+        .date = { 11, 3, 2004 },
+        .hour_offset = -1,
+        .minute_offset = 0,
+    };
+
+    ck_assert(minmea_check(sentence, false) == true);
+    ck_assert(minmea_check(sentence, true) == true);
+    ck_assert(minmea_parse_zda(&frame, sentence) == true);
+    ck_assert(!memcmp(&frame, &expected, sizeof(frame)));
+}
+END_TEST
+
+START_TEST(test_minmea_usage1)
+{
+    const char *sentences[] = {
+        "$GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62",
+        "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47",
+        "$GNGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1",
+        "$GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41",
+        "$GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58",
+        "$GPVTG,096.5,T,083.5,M,0.0,N,0.0,K,D*22",
+        NULL,
+    };
+
+    for (const char **sentence=sentences; *sentence; sentence++) {
+        switch (minmea_sentence_id(*sentence, false)) {
+            case MINMEA_SENTENCE_RMC: {
+                struct minmea_sentence_rmc frame;
+                ck_assert(minmea_parse_rmc(&frame, *sentence) == true);
+            } break;
+
+            case MINMEA_SENTENCE_GGA: {
+                struct minmea_sentence_gga frame;
+                ck_assert(minmea_parse_gga(&frame, *sentence) == true);
+            } break;
+
+            case MINMEA_SENTENCE_GSA: {
+                struct minmea_sentence_gsa frame;
+                ck_assert(minmea_parse_gsa(&frame, *sentence) == true);
+            } break;
+
+            case MINMEA_SENTENCE_GLL: {
+                struct minmea_sentence_gll frame;
+                ck_assert(minmea_parse_gll(&frame, *sentence) == true);
+            } break;
+
+            case MINMEA_SENTENCE_GST: {
+                struct minmea_sentence_gst frame;
+                ck_assert(minmea_parse_gst(&frame, *sentence) == true);
+            } break;
+
+            case MINMEA_SENTENCE_VTG: {
+                struct minmea_sentence_vtg frame;
+                ck_assert(minmea_parse_vtg(&frame, *sentence) == true);
+            } break;
+
+            default: {
+            } break;
+        }
+
+        char talker[3];
+        char expected[3] = { (*sentence)[1], (*sentence)[2], '\0' };
+        ck_assert(minmea_talker_id(talker, *sentence) == true);
+        ck_assert_str_eq(talker, expected);
+    }
+}
+END_TEST
+
+START_TEST(test_minmea_gettime)
+{
+    struct minmea_date d = { 14, 2, 14 };
+    struct minmea_time t = { 13, 0, 9, 123456 };
+    struct tm tm;
+    struct timespec ts;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 2014-1900);
+    ck_assert_int_eq(tm.tm_mon, 1);
+    ck_assert_int_eq(tm.tm_mday, 14);
+    ck_assert_int_eq(tm.tm_hour, 13);
+    ck_assert_int_eq(tm.tm_min, 0);
+    ck_assert_int_eq(tm.tm_sec, 9);
+    ck_assert_int_eq(ts.tv_sec, 1392382809);
+    ck_assert_int_eq(ts.tv_nsec, 123456000);
+
+    d.year = -1;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) != 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) != 0);
+    d.year = 14;
+
+    t.hours = -1;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) != 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) != 0);
+    t.hours = 13;
+
+    /* two digit year conversions */
+    d.year = 80;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 1980-1900);
+    ck_assert_int_eq(ts.tv_sec, 319381209);      /* 1980 */
+    d.year = 37;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 2037-1900);
+    ck_assert_int_eq(ts.tv_sec, 2118229209);     /* 2037 */
+    /* skip >= 2038 tests on 32-bit time_t platforms */
+    if (sizeof(time_t) == sizeof(int64_t)) {
+        d.year = 79;
+        ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+        ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+        ck_assert_int_eq(tm.tm_year, 2079-1900);
+        ck_assert_int_eq(ts.tv_sec, 3443605209); /* 2079 */
+    }
+
+    /* four digit year conversions */
+    d.year = 1979;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 1979-1900);
+    ck_assert_int_eq(ts.tv_sec, 287845209);
+    d.year = 1980;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 1980-1900);
+    ck_assert_int_eq(ts.tv_sec, 319381209);
+    d.year = 2037;
+    ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+    ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+    ck_assert_int_eq(tm.tm_year, 2037-1900);
+    ck_assert_int_eq(ts.tv_sec, 2118229209);
+    /* skip >= 2038 tests on 32-bit time_t platforms */
+    if (sizeof(time_t) == sizeof(int64_t)) {
+        d.year = 2079;
+        ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+        ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+        ck_assert_int_eq(tm.tm_year, 2079-1900);
+        ck_assert_int_eq(ts.tv_sec, 3443605209);
+        d.year = 2080;
+        ck_assert(minmea_getdatetime(&tm, &d, &t) == 0);
+        ck_assert(minmea_gettime(&ts, &d, &t) == 0);
+        ck_assert_int_eq(tm.tm_year, 2080-1900);
+        ck_assert_int_eq(ts.tv_sec, 3475141209);
+    }
+}
+END_TEST
+
+START_TEST(test_minmea_rescale)
+{
+    /* basic and edge cases. */
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { 42, 0 }, 3), 0);
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { 1234, 10 }, 1), 123);
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { 1235, 10 }, 1), 124);
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { 1234, 10 }, 1000), 123400);
+
+    /* round towards zero. */
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { -1234, 10 }, 1), -123);
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { -1235, 10 }, 1), -124);
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { -1236, 10 }, 1), -124);
+
+    /* shouldn't overflow on large numbers. */
+    ck_assert_int_eq(minmea_rescale(&(struct minmea_float) { 510693608, 100000 }, 10000), 51069361);
+}
+END_TEST
+
+/* The float values used in tests should be exactly representable under IEEE754;
+ * false negatives will occur otherwise. */
+
+#define assert_float_eq(x, y) ck_assert(fabsf((x) - (y)) <= 0.0f)
+
+START_TEST(test_minmea_float)
+{
+    ck_assert(isnan(minmea_tofloat(&(struct minmea_float) { 42, 0 })));
+    assert_float_eq(minmea_tofloat(&(struct minmea_float) { 7, 1 }), 7.0f);
+    assert_float_eq(minmea_tofloat(&(struct minmea_float) { -200, 100 }), -2.0f);
+    assert_float_eq(minmea_tofloat(&(struct minmea_float) { 15, 10 }), 1.5f);
+}
+END_TEST
+
+START_TEST(test_minmea_coord)
+{
+    ck_assert(isnan(minmea_tocoord(&(struct minmea_float) { 42, 0 })));
+    assert_float_eq(minmea_tocoord(&(struct minmea_float) { 4200, 1 }), 42.0f);
+    assert_float_eq(minmea_tocoord(&(struct minmea_float) { 420000, 100 }), 42.0f);
+    assert_float_eq(minmea_tocoord(&(struct minmea_float) { 423000, 100 }), 42.5f);
+}
+END_TEST
+
+static Suite *minmea_suite(void)
+{
+    Suite *s = suite_create ("minmea");
+
+    TCase *tc_checksum = tcase_create("minmea_checksum");
+    tcase_add_test(tc_checksum, test_minmea_checksum);
+    suite_add_tcase(s, tc_checksum);
+
+    TCase *tc_check = tcase_create("minmea_check");
+    tcase_add_test(tc_check, test_minmea_check);
+    suite_add_tcase(s, tc_check);
+
+    TCase *tc_scan = tcase_create("minmea_scan");
+    tcase_add_test(tc_scan, test_minmea_scan_c);
+    tcase_add_test(tc_scan, test_minmea_scan_d);
+    tcase_add_test(tc_scan, test_minmea_scan_f);
+    tcase_add_test(tc_scan, test_minmea_scan_i);
+    tcase_add_test(tc_scan, test_minmea_scan_s);
+    tcase_add_test(tc_scan, test_minmea_scan_t);
+    tcase_add_test(tc_scan, test_minmea_scan_D);
+    tcase_add_test(tc_scan, test_minmea_scan_T);
+    tcase_add_test(tc_scan, test_minmea_scan_complex1);
+    tcase_add_test(tc_scan, test_minmea_scan_complex2);
+    tcase_add_test(tc_scan, test_minmea_scan_complex3);
+    suite_add_tcase(s, tc_scan);
+
+    TCase *tc_parse = tcase_create("minmea_parse");
+    tcase_add_test(tc_parse, test_minmea_parse_gbs1);
+    tcase_add_test(tc_parse, test_minmea_parse_gbs2);
+    tcase_add_test(tc_parse, test_minmea_parse_rmc1);
+    tcase_add_test(tc_parse, test_minmea_parse_rmc2);
+    tcase_add_test(tc_parse, test_minmea_parse_gga1);
+    tcase_add_test(tc_parse, test_minmea_parse_gsa1);
+    tcase_add_test(tc_parse, test_minmea_parse_gll1);
+    tcase_add_test(tc_parse, test_minmea_parse_gll2);
+    tcase_add_test(tc_parse, test_minmea_parse_gst1);
+    tcase_add_test(tc_parse, test_minmea_parse_gsv1);
+    tcase_add_test(tc_parse, test_minmea_parse_gsv2);
+    tcase_add_test(tc_parse, test_minmea_parse_gsv3);
+    tcase_add_test(tc_parse, test_minmea_parse_gsv4);
+    tcase_add_test(tc_parse, test_minmea_parse_gsv5);
+    tcase_add_test(tc_parse, test_minmea_parse_vtg1);
+    tcase_add_test(tc_parse, test_minmea_parse_vtg2);
+    tcase_add_test(tc_parse, test_minmea_parse_vtg3);
+    tcase_add_test(tc_parse, test_minmea_parse_zda1);
+    suite_add_tcase(s, tc_parse);
+
+    TCase *tc_usage = tcase_create("minmea_usage");
+    tcase_add_test(tc_usage, test_minmea_usage1);
+    suite_add_tcase(s, tc_usage);
+
+    TCase *tc_utils = tcase_create("minmea_utils");
+    tcase_add_test(tc_utils, test_minmea_gettime);
+    tcase_add_test(tc_utils, test_minmea_rescale);
+    tcase_add_test(tc_utils, test_minmea_float);
+    tcase_add_test(tc_utils, test_minmea_coord);
+    suite_add_tcase(s, tc_utils);
+
+    return s;
+}
+
+int main(void)
+{
+    int number_failed;
+    Suite *s = minmea_suite();
+    SRunner *sr = srunner_create(s);
+    srunner_run_all(sr, CK_NORMAL);
+    number_failed = srunner_ntests_failed(sr);
+    srunner_free(sr);
+    return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+/* vim: set ts=4 sw=4 et: */

+ 0 - 640
base_pack/gps_nmea_uart/minmea.c

@@ -1,640 +0,0 @@
-/*
- * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
- * This program is free software. It comes without any warranty, to the extent
- * permitted by applicable law. You can redistribute it and/or modify it under
- * the terms of the Do What The Fuck You Want To Public License, Version 2, as
- * published by Sam Hocevar. See the COPYING file for more details.
- */
-
-#include "minmea.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include <stdarg.h>
-
-#define boolstr(s) ((s) ? "true" : "false")
-
-static int hex2int(char c) {
-    if(c >= '0' && c <= '9') return c - '0';
-    if(c >= 'A' && c <= 'F') return c - 'A' + 10;
-    if(c >= 'a' && c <= 'f') return c - 'a' + 10;
-    return -1;
-}
-
-uint8_t minmea_checksum(const char* sentence) {
-    // Support senteces with or without the starting dollar sign.
-    if(*sentence == '$') sentence++;
-
-    uint8_t checksum = 0x00;
-
-    // The optional checksum is an XOR of all bytes between "$" and "*".
-    while(*sentence && *sentence != '*') checksum ^= *sentence++;
-
-    return checksum;
-}
-
-bool minmea_check(const char* sentence, bool strict) {
-    uint8_t checksum = 0x00;
-
-    // A valid sentence starts with "$".
-    if(*sentence++ != '$') return false;
-
-    // The optional checksum is an XOR of all bytes between "$" and "*".
-    while(*sentence && *sentence != '*' && isprint((unsigned char)*sentence))
-        checksum ^= *sentence++;
-
-    // If checksum is present...
-    if(*sentence == '*') {
-        // Extract checksum.
-        sentence++;
-        int upper = hex2int(*sentence++);
-        if(upper == -1) return false;
-        int lower = hex2int(*sentence++);
-        if(lower == -1) return false;
-        int expected = upper << 4 | lower;
-
-        // Check for checksum mismatch.
-        if(checksum != expected) return false;
-    } else if(strict) {
-        // Discard non-checksummed frames in strict mode.
-        return false;
-    }
-
-    // The only stuff allowed at this point is a newline.
-    while(*sentence == '\r' || *sentence == '\n') {
-        sentence++;
-    }
-
-    if(*sentence) {
-        return false;
-    }
-
-    return true;
-}
-
-bool minmea_scan(const char* sentence, const char* format, ...) {
-    bool result = false;
-    bool optional = false;
-
-    if(sentence == NULL) return false;
-
-    va_list ap;
-    va_start(ap, format);
-
-    const char* field = sentence;
-#define next_field()                                 \
-    do {                                             \
-        /* Progress to the next field. */            \
-        while(minmea_isfield(*sentence)) sentence++; \
-        /* Make sure there is a field there. */      \
-        if(*sentence == ',') {                       \
-            sentence++;                              \
-            field = sentence;                        \
-        } else {                                     \
-            field = NULL;                            \
-        }                                            \
-    } while(0)
-
-    while(*format) {
-        char type = *format++;
-
-        if(type == ';') {
-            // All further fields are optional.
-            optional = true;
-            continue;
-        }
-
-        if(!field && !optional) {
-            // Field requested but we ran out if input. Bail out.
-            goto parse_error;
-        }
-
-        switch(type) {
-        case 'c': { // Single character field (char).
-            char value = '\0';
-
-            if(field && minmea_isfield(*field)) value = *field;
-
-            *va_arg(ap, char*) = value;
-        } break;
-
-        case 'd': { // Single character direction field (int).
-            int value = 0;
-
-            if(field && minmea_isfield(*field)) {
-                switch(*field) {
-                case 'N':
-                case 'E':
-                    value = 1;
-                    break;
-                case 'S':
-                case 'W':
-                    value = -1;
-                    break;
-                default:
-                    goto parse_error;
-                }
-            }
-
-            *va_arg(ap, int*) = value;
-        } break;
-
-        case 'f': { // Fractional value with scale (struct minmea_float).
-            int sign = 0;
-            int_least32_t value = -1;
-            int_least32_t scale = 0;
-
-            if(field) {
-                while(minmea_isfield(*field)) {
-                    if(*field == '+' && !sign && value == -1) {
-                        sign = 1;
-                    } else if(*field == '-' && !sign && value == -1) {
-                        sign = -1;
-                    } else if(isdigit((unsigned char)*field)) {
-                        int digit = *field - '0';
-                        if(value == -1) value = 0;
-                        if(value > (INT_LEAST32_MAX - digit) / 10) {
-                            /* we ran out of bits, what do we do? */
-                            if(scale) {
-                                /* truncate extra precision */
-                                break;
-                            } else {
-                                /* integer overflow. bail out. */
-                                goto parse_error;
-                            }
-                        }
-                        value = (10 * value) + digit;
-                        if(scale) scale *= 10;
-                    } else if(*field == '.' && scale == 0) {
-                        scale = 1;
-                    } else if(*field == ' ') {
-                        /* Allow spaces at the start of the field. Not NMEA
-                             * conformant, but some modules do this. */
-                        if(sign != 0 || value != -1 || scale != 0) goto parse_error;
-                    } else {
-                        goto parse_error;
-                    }
-                    field++;
-                }
-            }
-
-            if((sign || scale) && value == -1) goto parse_error;
-
-            if(value == -1) {
-                /* No digits were scanned. */
-                value = 0;
-                scale = 0;
-            } else if(scale == 0) {
-                /* No decimal point. */
-                scale = 1;
-            }
-            if(sign) value *= sign;
-
-            *va_arg(ap, struct minmea_float*) = (struct minmea_float){value, scale};
-        } break;
-
-        case 'i': { // Integer value, default 0 (int).
-            int value = 0;
-
-            if(field) {
-                char* endptr;
-                value = strtol(field, &endptr, 10);
-                if(minmea_isfield(*endptr)) goto parse_error;
-            }
-
-            *va_arg(ap, int*) = value;
-        } break;
-
-        case 's': { // String value (char *).
-            char* buf = va_arg(ap, char*);
-
-            if(field) {
-                while(minmea_isfield(*field)) *buf++ = *field++;
-            }
-
-            *buf = '\0';
-        } break;
-
-        case 't': { // NMEA talker+sentence identifier (char *).
-            // This field is always mandatory.
-            if(!field) goto parse_error;
-
-            if(field[0] != '$') goto parse_error;
-            for(int f = 0; f < 5; f++)
-                if(!minmea_isfield(field[1 + f])) goto parse_error;
-
-            char* buf = va_arg(ap, char*);
-            memcpy(buf, field + 1, 5);
-            buf[5] = '\0';
-        } break;
-
-        case 'D': { // Date (int, int, int), -1 if empty.
-            struct minmea_date* date = va_arg(ap, struct minmea_date*);
-
-            int d = -1, m = -1, y = -1;
-
-            if(field && minmea_isfield(*field)) {
-                // Always six digits.
-                for(int f = 0; f < 6; f++)
-                    if(!isdigit((unsigned char)field[f])) goto parse_error;
-
-                char dArr[] = {field[0], field[1], '\0'};
-                char mArr[] = {field[2], field[3], '\0'};
-                char yArr[] = {field[4], field[5], '\0'};
-                d = strtol(dArr, NULL, 10);
-                m = strtol(mArr, NULL, 10);
-                y = strtol(yArr, NULL, 10);
-            }
-
-            date->day = d;
-            date->month = m;
-            date->year = y;
-        } break;
-
-        case 'T': { // Time (int, int, int, int), -1 if empty.
-            struct minmea_time* time_ = va_arg(ap, struct minmea_time*);
-
-            int h = -1, i = -1, s = -1, u = -1;
-
-            if(field && minmea_isfield(*field)) {
-                // Minimum required: integer time.
-                for(int f = 0; f < 6; f++)
-                    if(!isdigit((unsigned char)field[f])) goto parse_error;
-
-                char hArr[] = {field[0], field[1], '\0'};
-                char iArr[] = {field[2], field[3], '\0'};
-                char sArr[] = {field[4], field[5], '\0'};
-                h = strtol(hArr, NULL, 10);
-                i = strtol(iArr, NULL, 10);
-                s = strtol(sArr, NULL, 10);
-                field += 6;
-
-                // Extra: fractional time. Saved as microseconds.
-                if(*field++ == '.') {
-                    uint32_t value = 0;
-                    uint32_t scale = 1000000LU;
-                    while(isdigit((unsigned char)*field) && scale > 1) {
-                        value = (value * 10) + (*field++ - '0');
-                        scale /= 10;
-                    }
-                    u = value * scale;
-                } else {
-                    u = 0;
-                }
-            }
-
-            time_->hours = h;
-            time_->minutes = i;
-            time_->seconds = s;
-            time_->microseconds = u;
-        } break;
-
-        case '_': { // Ignore the field.
-        } break;
-
-        default: { // Unknown.
-            goto parse_error;
-        }
-        }
-
-        next_field();
-    }
-
-    result = true;
-
-parse_error:
-    va_end(ap);
-    return result;
-}
-
-bool minmea_talker_id(char talker[3], const char* sentence) {
-    char type[6];
-    if(!minmea_scan(sentence, "t", type)) return false;
-
-    talker[0] = type[0];
-    talker[1] = type[1];
-    talker[2] = '\0';
-
-    return true;
-}
-
-enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict) {
-    if(!minmea_check(sentence, strict)) return MINMEA_INVALID;
-
-    char type[6];
-    if(!minmea_scan(sentence, "t", type)) return MINMEA_INVALID;
-
-    if(!strcmp(type + 2, "GBS")) return MINMEA_SENTENCE_GBS;
-    if(!strcmp(type + 2, "GGA")) return MINMEA_SENTENCE_GGA;
-    if(!strcmp(type + 2, "GLL")) return MINMEA_SENTENCE_GLL;
-    if(!strcmp(type + 2, "GSA")) return MINMEA_SENTENCE_GSA;
-    if(!strcmp(type + 2, "GST")) return MINMEA_SENTENCE_GST;
-    if(!strcmp(type + 2, "GSV")) return MINMEA_SENTENCE_GSV;
-    if(!strcmp(type + 2, "RMC")) return MINMEA_SENTENCE_RMC;
-    if(!strcmp(type + 2, "VTG")) return MINMEA_SENTENCE_VTG;
-    if(!strcmp(type + 2, "ZDA")) return MINMEA_SENTENCE_ZDA;
-
-    return MINMEA_UNKNOWN;
-}
-
-bool minmea_parse_gbs(struct minmea_sentence_gbs* frame, const char* sentence) {
-    // $GNGBS,170556.00,3.0,2.9,8.3,,,,*5C
-    char type[6];
-    if(!minmea_scan(
-           sentence,
-           "tTfffifff",
-           type,
-           &frame->time,
-           &frame->err_latitude,
-           &frame->err_longitude,
-           &frame->err_altitude,
-           &frame->svid,
-           &frame->prob,
-           &frame->bias,
-           &frame->stddev))
-        return false;
-    if(strcmp(type + 2, "GBS")) return false;
-
-    return true;
-}
-
-bool minmea_parse_rmc(struct minmea_sentence_rmc* frame, const char* sentence) {
-    // $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
-    char type[6];
-    char validity;
-    int latitude_direction;
-    int longitude_direction;
-    int variation_direction;
-    if(!minmea_scan(
-           sentence,
-           "tTcfdfdffDfd",
-           type,
-           &frame->time,
-           &validity,
-           &frame->latitude,
-           &latitude_direction,
-           &frame->longitude,
-           &longitude_direction,
-           &frame->speed,
-           &frame->course,
-           &frame->date,
-           &frame->variation,
-           &variation_direction))
-        return false;
-    if(strcmp(type + 2, "RMC")) return false;
-
-    frame->valid = (validity == 'A');
-    frame->latitude.value *= latitude_direction;
-    frame->longitude.value *= longitude_direction;
-    frame->variation.value *= variation_direction;
-
-    return true;
-}
-
-bool minmea_parse_gga(struct minmea_sentence_gga* frame, const char* sentence) {
-    // $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
-    char type[6];
-    int latitude_direction;
-    int longitude_direction;
-
-    if(!minmea_scan(
-           sentence,
-           "tTfdfdiiffcfcf_",
-           type,
-           &frame->time,
-           &frame->latitude,
-           &latitude_direction,
-           &frame->longitude,
-           &longitude_direction,
-           &frame->fix_quality,
-           &frame->satellites_tracked,
-           &frame->hdop,
-           &frame->altitude,
-           &frame->altitude_units,
-           &frame->height,
-           &frame->height_units,
-           &frame->dgps_age))
-        return false;
-    if(strcmp(type + 2, "GGA")) return false;
-
-    frame->latitude.value *= latitude_direction;
-    frame->longitude.value *= longitude_direction;
-
-    return true;
-}
-
-bool minmea_parse_gsa(struct minmea_sentence_gsa* frame, const char* sentence) {
-    // $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
-    char type[6];
-
-    if(!minmea_scan(
-           sentence,
-           "tciiiiiiiiiiiiifff",
-           type,
-           &frame->mode,
-           &frame->fix_type,
-           &frame->sats[0],
-           &frame->sats[1],
-           &frame->sats[2],
-           &frame->sats[3],
-           &frame->sats[4],
-           &frame->sats[5],
-           &frame->sats[6],
-           &frame->sats[7],
-           &frame->sats[8],
-           &frame->sats[9],
-           &frame->sats[10],
-           &frame->sats[11],
-           &frame->pdop,
-           &frame->hdop,
-           &frame->vdop))
-        return false;
-    if(strcmp(type + 2, "GSA")) return false;
-
-    return true;
-}
-
-bool minmea_parse_gll(struct minmea_sentence_gll* frame, const char* sentence) {
-    // $GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41$;
-    char type[6];
-    int latitude_direction;
-    int longitude_direction;
-
-    if(!minmea_scan(
-           sentence,
-           "tfdfdTc;c",
-           type,
-           &frame->latitude,
-           &latitude_direction,
-           &frame->longitude,
-           &longitude_direction,
-           &frame->time,
-           &frame->status,
-           &frame->mode))
-        return false;
-    if(strcmp(type + 2, "GLL")) return false;
-
-    frame->latitude.value *= latitude_direction;
-    frame->longitude.value *= longitude_direction;
-
-    return true;
-}
-
-bool minmea_parse_gst(struct minmea_sentence_gst* frame, const char* sentence) {
-    // $GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58
-    char type[6];
-
-    if(!minmea_scan(
-           sentence,
-           "tTfffffff",
-           type,
-           &frame->time,
-           &frame->rms_deviation,
-           &frame->semi_major_deviation,
-           &frame->semi_minor_deviation,
-           &frame->semi_major_orientation,
-           &frame->latitude_error_deviation,
-           &frame->longitude_error_deviation,
-           &frame->altitude_error_deviation))
-        return false;
-    if(strcmp(type + 2, "GST")) return false;
-
-    return true;
-}
-
-bool minmea_parse_gsv(struct minmea_sentence_gsv* frame, const char* sentence) {
-    // $GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74
-    // $GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D
-    // $GPGSV,4,2,11,08,51,203,30,09,45,215,28*75
-    // $GPGSV,4,4,13,39,31,170,27*40
-    // $GPGSV,4,4,13*7B
-    char type[6];
-
-    if(!minmea_scan(
-           sentence,
-           "tiii;iiiiiiiiiiiiiiii",
-           type,
-           &frame->total_msgs,
-           &frame->msg_nr,
-           &frame->total_sats,
-           &frame->sats[0].nr,
-           &frame->sats[0].elevation,
-           &frame->sats[0].azimuth,
-           &frame->sats[0].snr,
-           &frame->sats[1].nr,
-           &frame->sats[1].elevation,
-           &frame->sats[1].azimuth,
-           &frame->sats[1].snr,
-           &frame->sats[2].nr,
-           &frame->sats[2].elevation,
-           &frame->sats[2].azimuth,
-           &frame->sats[2].snr,
-           &frame->sats[3].nr,
-           &frame->sats[3].elevation,
-           &frame->sats[3].azimuth,
-           &frame->sats[3].snr)) {
-        return false;
-    }
-    if(strcmp(type + 2, "GSV")) return false;
-
-    return true;
-}
-
-bool minmea_parse_vtg(struct minmea_sentence_vtg* frame, const char* sentence) {
-    // $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48
-    // $GPVTG,156.1,T,140.9,M,0.0,N,0.0,K*41
-    // $GPVTG,096.5,T,083.5,M,0.0,N,0.0,K,D*22
-    // $GPVTG,188.36,T,,M,0.820,N,1.519,K,A*3F
-    char type[6];
-    char c_true, c_magnetic, c_knots, c_kph, c_faa_mode;
-
-    if(!minmea_scan(
-           sentence,
-           "t;fcfcfcfcc",
-           type,
-           &frame->true_track_degrees,
-           &c_true,
-           &frame->magnetic_track_degrees,
-           &c_magnetic,
-           &frame->speed_knots,
-           &c_knots,
-           &frame->speed_kph,
-           &c_kph,
-           &c_faa_mode))
-        return false;
-    if(strcmp(type + 2, "VTG")) return false;
-    // values are only valid with the accompanying characters
-    if(c_true != 'T') frame->true_track_degrees.scale = 0;
-    if(c_magnetic != 'M') frame->magnetic_track_degrees.scale = 0;
-    if(c_knots != 'N') frame->speed_knots.scale = 0;
-    if(c_kph != 'K') frame->speed_kph.scale = 0;
-    frame->faa_mode = (enum minmea_faa_mode)c_faa_mode;
-
-    return true;
-}
-
-bool minmea_parse_zda(struct minmea_sentence_zda* frame, const char* sentence) {
-    // $GPZDA,201530.00,04,07,2002,00,00*60
-    char type[6];
-
-    if(!minmea_scan(
-           sentence,
-           "tTiiiii",
-           type,
-           &frame->time,
-           &frame->date.day,
-           &frame->date.month,
-           &frame->date.year,
-           &frame->hour_offset,
-           &frame->minute_offset))
-        return false;
-    if(strcmp(type + 2, "ZDA")) return false;
-
-    // check offsets
-    if(abs(frame->hour_offset) > 13 || frame->minute_offset > 59 || frame->minute_offset < 0)
-        return false;
-
-    return true;
-}
-
-int minmea_getdatetime(
-    struct tm* tm,
-    const struct minmea_date* date,
-    const struct minmea_time* time_) {
-    if(date->year == -1 || time_->hours == -1) return -1;
-
-    memset(tm, 0, sizeof(*tm));
-    if(date->year < 80) {
-        tm->tm_year = 2000 + date->year - 1900; // 2000-2079
-    } else if(date->year >= 1900) {
-        tm->tm_year = date->year - 1900; // 4 digit year, use directly
-    } else {
-        tm->tm_year = date->year; // 1980-1999
-    }
-    tm->tm_mon = date->month - 1;
-    tm->tm_mday = date->day;
-    tm->tm_hour = time_->hours;
-    tm->tm_min = time_->minutes;
-    tm->tm_sec = time_->seconds;
-
-    return 0;
-}
-
-int minmea_gettime(
-    struct timespec* ts,
-    const struct minmea_date* date,
-    const struct minmea_time* time_) {
-    struct tm tm;
-    if(minmea_getdatetime(&tm, date, time_)) return -1;
-
-    time_t timestamp = mktime(&tm); /* See README.md if your system lacks timegm(). */
-    if(timestamp != (time_t)-1) {
-        ts->tv_sec = timestamp;
-        ts->tv_nsec = time_->microseconds * 1000;
-        return 0;
-    } else {
-        return -1;
-    }
-}
-
-/* vim: set ts=4 sw=4 et: */

BIN
base_pack/gps_nmea_uart/ui.png


BIN
base_pack/gps_nmea_uart/wiring.png


+ 3 - 4
base_pack/hc_sr04/hc_sr04.c

@@ -5,7 +5,6 @@
 #include <furi.h>
 #include <furi_hal.h>
 #include <furi_hal_power.h>
-#include <furi_hal_console.h>
 #include <gui/gui.h>
 #include <input/input.h>
 #include <stdlib.h>
@@ -183,7 +182,7 @@ int32_t hc_sr04_app() {
 
     hc_sr04_state_init(plugin_state);
 
-    furi_hal_console_disable();
+    FuriHalSerialHandle* serial_handle = furi_hal_serial_control_acquire(FuriHalSerialIdUsart);
 
     plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
     if(!plugin_state->mutex) {
@@ -191,7 +190,7 @@ int32_t hc_sr04_app() {
         if(furi_hal_power_is_otg_enabled()) {
             furi_hal_power_disable_otg();
         }
-        furi_hal_console_enable();
+        furi_hal_serial_control_release(serial_handle);
         furi_hal_power_suppress_charge_exit();
         furi_message_queue_free(event_queue);
         free(plugin_state);
@@ -260,7 +259,7 @@ int32_t hc_sr04_app() {
         GpioPullUp,
         GpioSpeedVeryHigh,
         GpioAltFn7USART1);
-    furi_hal_console_enable();
+    furi_hal_serial_control_release(serial_handle);
 
     view_port_enabled_set(view_port, false);
     gui_remove_view_port(gui, view_port);

+ 6 - 6
base_pack/sentry_safe/sentry_safe.c

@@ -59,17 +59,17 @@ void send_request(int command, int a, int b, int c, int d, int e) {
     furi_delay_ms(3.4);
     furi_hal_gpio_write(&gpio_ext_pc1, true);
 
-    furi_hal_uart_init(FuriHalUartIdLPUART1, 4800);
-    //furi_hal_uart_set_br(FuriHalUartIdLPUART1, 4800);
-    //furi_hal_uart_set_irq_cb(FuriHalUartIdLPUART1, usb_uart_on_irq_cb, usb_uart);
+    FuriHalSerialHandle* serial_handle = furi_hal_serial_control_acquire(FuriHalSerialIdLpuart);
+    furi_check(serial_handle);
+    furi_hal_serial_init(serial_handle, 4800);
 
     uint8_t data[8] = {0x0, command, a, b, c, d, e, checksum};
-    furi_hal_uart_tx(FuriHalUartIdLPUART1, data, 8);
+    furi_hal_serial_tx(serial_handle, data, 8);
 
     furi_delay_ms(100);
 
-    furi_hal_uart_set_irq_cb(FuriHalUartIdLPUART1, NULL, NULL);
-    furi_hal_uart_deinit(FuriHalUartIdLPUART1);
+    furi_hal_serial_deinit(serial_handle);
+    furi_hal_serial_control_release(serial_handle);
 }
 
 void reset_code(int a, int b, int c, int d, int e) {

+ 23 - 21
base_pack/uart_terminal/scenes/uart_terminal_scene_console_output.c

@@ -6,19 +6,19 @@ void uart_terminal_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, vo
     FuriString* new_str = furi_string_alloc();
 
     if(app->hex_mode) {
-        while (len--) {
+        while(len--) {
             uint8_t byte = *(buf++);
             if(byte == '\0') break;
             furi_string_cat_printf(new_str, "%02X ", byte);
         }
-    }
-    else {
+    } else {
         buf[len] = '\0';
         furi_string_cat_printf(new_str, "%s", buf);
     }
 
     // If text box store gets too big, then truncate it
-    app->text_box_store_strlen += furi_string_size(new_str);;
+    app->text_box_store_strlen += furi_string_size(new_str);
+    ;
     while(app->text_box_store_strlen >= UART_TERMINAL_TEXT_BOX_STORE_SIZE - 1) {
         furi_string_right(app->text_box_store, app->text_box_store_strlen / 2);
         app->text_box_store_strlen = furi_string_size(app->text_box_store) + len;
@@ -33,13 +33,13 @@ void uart_terminal_console_output_handle_rx_data_cb(uint8_t* buf, size_t len, vo
 
 static uint8_t hex_char_to_byte(const char c) {
     if(c >= '0' && c <= '9') {
-        return c-'0';
+        return c - '0';
     }
     if(c >= 'A' && c <= 'F') {
-        return c-'A'+10;
+        return c - 'A' + 10;
     }
-    if (c >= 'a' && c <= 'f') {
-        return c-'a'+10;
+    if(c >= 'a' && c <= 'f') {
+        return c - 'a' + 10;
     }
     return 0;
 }
@@ -86,19 +86,17 @@ void uart_terminal_scene_console_output_on_enter(void* context) {
     uart_terminal_uart_set_handle_rx_data_cb(
         app->uart, uart_terminal_console_output_handle_rx_data_cb); // setup callback for rx thread
 
-    uint8_t uart_ch = app->uart_ch;
-
     if(app->hex_mode) {
         // Send binary packet
         if(app->selected_tx_string) {
-            const char *str = app->selected_tx_string;
+            const char* str = app->selected_tx_string;
             uint8_t digit_num = 0;
             uint8_t byte = 0;
-            while (*str) {
+            while(*str) {
                 byte |= (hex_char_to_byte(*str) << ((1 - digit_num) * 4));
 
                 if(++digit_num == 2) {
-                    uart_terminal_uart_tx(uart_ch, &byte, 1);
+                    uart_terminal_uart_tx(app->uart, &byte, 1);
                     digit_num = 0;
                     byte = 0;
                 }
@@ -106,20 +104,24 @@ void uart_terminal_scene_console_output_on_enter(void* context) {
             }
 
             if(digit_num) {
-                uart_terminal_uart_tx(uart_ch, &byte, 1);
+                uart_terminal_uart_tx(app->uart, &byte, 1);
             }
         }
     } else {
         // Send command with CR+LF or newline '\n'
         if(app->is_command && app->selected_tx_string) {
-            if(app->TERMINAL_MODE == 1){
-                uart_terminal_uart_tx(uart_ch, 
-                    (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
-                uart_terminal_uart_tx(uart_ch, (uint8_t*)("\r\n"), 2);
+            if(app->TERMINAL_MODE == 1) {
+                uart_terminal_uart_tx(
+                    app->uart,
+                    (uint8_t*)(app->selected_tx_string),
+                    strlen(app->selected_tx_string));
+                uart_terminal_uart_tx(app->uart, (uint8_t*)("\r\n"), 2);
             } else {
-                uart_terminal_uart_tx(uart_ch, 
-                    (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
-                uart_terminal_uart_tx(uart_ch, (uint8_t*)("\n"), 1);
+                uart_terminal_uart_tx(
+                    app->uart,
+                    (uint8_t*)(app->selected_tx_string),
+                    strlen(app->selected_tx_string));
+                uart_terminal_uart_tx(app->uart, (uint8_t*)("\n"), 1);
             }
         }
     }

+ 16 - 18
base_pack/uart_terminal/uart_terminal_uart.c

@@ -7,6 +7,7 @@ struct UART_TerminalUart {
     FuriStreamBuffer* rx_stream;
     uint8_t rx_buf[RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
+    FuriHalSerialHandle* serial_handle;
 };
 
 typedef enum {
@@ -23,10 +24,14 @@ void uart_terminal_uart_set_handle_rx_data_cb(
 
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
 
-void uart_terminal_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+void uart_terminal_uart_on_irq_cb(
+    FuriHalSerialHandle* handle,
+    FuriHalSerialRxEvent event,
+    void* context) {
     UART_TerminalUart* uart = (UART_TerminalUart*)context;
 
-    if(ev == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
     }
@@ -53,8 +58,8 @@ static int32_t uart_worker(void* context) {
     return 0;
 }
 
-void uart_terminal_uart_tx(uint8_t uart_ch, uint8_t* data, size_t len) {
-    furi_hal_uart_tx(uart_ch, data, len);
+void uart_terminal_uart_tx(UART_TerminalUart* uart, uint8_t* data, size_t len) {
+    furi_hal_serial_tx(uart->serial_handle, data, len);
 }
 
 UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app) {
@@ -74,14 +79,11 @@ UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app) {
         app->BAUDRATE = 115200;
     }
 
-    if(app->uart_ch == FuriHalUartIdUSART1) {
-        furi_hal_console_disable();
-		furi_hal_uart_set_br(app->uart_ch, app->BAUDRATE);
-    } else if(app->uart_ch == FuriHalUartIdLPUART1) {
-        furi_hal_uart_init(app->uart_ch, app->BAUDRATE);
-    }
+    uart->serial_handle = furi_hal_serial_control_acquire(app->uart_ch);
+    furi_check(uart->serial_handle);
+    furi_hal_serial_init(uart->serial_handle, app->BAUDRATE);
 
-    furi_hal_uart_set_irq_cb(app->uart_ch, uart_terminal_uart_on_irq_cb, uart);
+    furi_hal_serial_async_rx_start(uart->serial_handle, uart_terminal_uart_on_irq_cb, uart, false);
 
     return uart;
 }
@@ -93,12 +95,8 @@ void uart_terminal_uart_free(UART_TerminalUart* uart) {
     furi_thread_join(uart->rx_thread);
     furi_thread_free(uart->rx_thread);
 
-    furi_hal_uart_set_irq_cb(uart->app->uart_ch, NULL, NULL);
-
-    if(uart->app->uart_ch == FuriHalUartIdUSART1)
-        furi_hal_console_enable();
-    else
-        furi_hal_uart_deinit(uart->app->uart_ch);
+    furi_hal_serial_deinit(uart->serial_handle);
+    furi_hal_serial_control_release(uart->serial_handle);
 
     free(uart);
-}
+}

+ 1 - 1
base_pack/uart_terminal/uart_terminal_uart.h

@@ -9,6 +9,6 @@ typedef struct UART_TerminalUart UART_TerminalUart;
 void uart_terminal_uart_set_handle_rx_data_cb(
     UART_TerminalUart* uart,
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context));
-void uart_terminal_uart_tx(uint8_t uart_ch, uint8_t* data, size_t len);
+void uart_terminal_uart_tx(UART_TerminalUart* uart, uint8_t* data, size_t len);
 UART_TerminalUart* uart_terminal_uart_init(UART_TerminalApp* app);
 void uart_terminal_uart_free(UART_TerminalUart* uart);

+ 17 - 11
base_pack/wifi_marauder_companion/scenes/wifi_marauder_scene_console_output.c

@@ -104,8 +104,8 @@ void wifi_marauder_scene_console_output_on_enter(void* context) {
     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_uart_set_handle_rx_pcap_cb(
+        app->uart,
         wifi_marauder_console_output_handle_rx_packets_cb); // setup callback for packets rx thread
 
     // Get ready to send command
@@ -157,11 +157,15 @@ void wifi_marauder_scene_console_output_on_enter(void* context) {
         // Send command with newline '\n'
         if(app->selected_tx_string) {
             wifi_marauder_uart_tx(
-                (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
-            wifi_marauder_uart_tx((uint8_t*)("\n"), 1);
+                app->uart, (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
+            if(app->is_writing_pcap) {
+                wifi_marauder_uart_tx(app->uart, (uint8_t*)(" -serial\n"), strlen(" -serial\n"));
+            } else {
+                wifi_marauder_uart_tx(app->uart, (uint8_t*)("\n"), 1);
+            }
             if(send_html && the_html) {
-                wifi_marauder_uart_tx(the_html, html_size);
-                wifi_marauder_uart_tx((uint8_t*)("\n"), 1);
+                wifi_marauder_uart_tx(app->uart, the_html, html_size);
+                wifi_marauder_uart_tx(app->uart, (uint8_t*)("\n"), 1);
                 free(the_html);
                 send_html = false;
             }
@@ -169,7 +173,7 @@ void wifi_marauder_scene_console_output_on_enter(void* context) {
 
         // Run the script if the file with the script has been opened
         if(app->script != NULL) {
-            app->script_worker = wifi_marauder_script_worker_alloc();
+            app->script_worker = wifi_marauder_script_worker_alloc(app->uart);
             wifi_marauder_script_worker_start(app->script_worker, app->script);
         }
     }
@@ -195,16 +199,18 @@ void wifi_marauder_scene_console_output_on_exit(void* context) {
 
     // Automatically stop the scan when exiting view
     if(app->is_command) {
-        wifi_marauder_uart_tx((uint8_t*)("stopscan\n"), strlen("stopscan\n"));
+        wifi_marauder_uart_tx(app->uart, (uint8_t*)("stopscan\n"), strlen("stopscan\n"));
         furi_delay_ms(50);
     }
 
     // Unregister rx callback
     wifi_marauder_uart_set_handle_rx_data_cb(app->uart, NULL);
-    wifi_marauder_uart_set_handle_rx_data_cb(app->lp_uart, NULL);
+    wifi_marauder_uart_set_handle_rx_pcap_cb(app->uart, NULL);
 
-    wifi_marauder_script_worker_free(app->script_worker);
-    app->script_worker = NULL;
+    if(app->script_worker) {
+        wifi_marauder_script_worker_free(app->script_worker);
+        app->script_worker = NULL;
+    }
 
     app->is_writing_pcap = false;
     if(app->capture_file && storage_file_is_open(app->capture_file)) {

+ 16 - 2
base_pack/wifi_marauder_companion/scenes/wifi_marauder_scene_start.c

@@ -62,9 +62,23 @@ const WifiMarauderItem items[NUM_MENU_ITEMS] = {
      FOCUS_CONSOLE_END,
      NO_TIP},
     {"Attack",
-     {"deauth", "probe", "rickroll", "sour apple", "swiftpair spam", "samsung spam", "google spam", "bt spam all"},
+     {"deauth",
+      "probe",
+      "rickroll",
+      "sour apple",
+      "swiftpair spam",
+      "samsung spam",
+      "google spam",
+      "bt spam all"},
      8,
-     {"attack -t deauth", "attack -t probe", "attack -t rickroll", "blespam -t apple", "blespam -t windows", "blespam -t samsung", "blespam -t google", "blespam -t all"},
+     {"attack -t deauth",
+      "attack -t probe",
+      "attack -t rickroll",
+      "blespam -t apple",
+      "blespam -t windows",
+      "blespam -t samsung",
+      "blespam -t google",
+      "blespam -t all"},
      NO_ARGS,
      FOCUS_CONSOLE_END,
      SHOW_STOPSCAN_TIP},

+ 59 - 54
base_pack/wifi_marauder_companion/script/wifi_marauder_script_executor.c

@@ -5,20 +5,20 @@ void _wifi_marauder_script_delay(WifiMarauderScriptWorker* worker, uint32_t dela
     for(uint32_t i = 0; i < delay_secs && worker->is_running; i++) furi_delay_ms(1000);
 }
 
-void _send_stop() {
+void _send_stop(WifiMarauderScriptWorker* worker) {
     const char stop_command[] = "stopscan\n";
-    wifi_marauder_uart_tx((uint8_t*)(stop_command), strlen(stop_command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(stop_command), strlen(stop_command));
 }
 
-void _send_line_break() {
-    wifi_marauder_uart_tx((uint8_t*)("\n"), 1);
+void _send_line_break(WifiMarauderScriptWorker* worker) {
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)("\n"), 1);
 }
 
-void _send_channel_select(int channel) {
+void _send_channel_select(WifiMarauderScriptWorker* worker, int channel) {
     char command[30];
-    _send_line_break();
+    _send_line_break(worker);
     snprintf(command, sizeof(command), "channel -s %d\n", channel);
-    wifi_marauder_uart_tx((uint8_t*)(command), strlen(command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(command), strlen(command));
 }
 
 void _wifi_marauder_script_execute_scan(
@@ -27,7 +27,7 @@ void _wifi_marauder_script_execute_scan(
     char command[15];
     // Set channel
     if(stage->channel > 0) {
-        _send_channel_select(stage->channel);
+        _send_channel_select(worker, stage->channel);
     }
     // Start scan
     if(stage->type == WifiMarauderScriptScanTypeAp) {
@@ -35,12 +35,14 @@ void _wifi_marauder_script_execute_scan(
     } else {
         snprintf(command, sizeof(command), "scansta\n");
     }
-    wifi_marauder_uart_tx((uint8_t*)(command), strlen(command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(command), strlen(command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
-void _wifi_marauder_script_execute_select(WifiMarauderScriptStageSelect* stage) {
+void _wifi_marauder_script_execute_select(
+    WifiMarauderScriptStageSelect* stage,
+    WifiMarauderScriptWorker* worker) {
     const char* select_type = NULL;
     switch(stage->type) {
     case WifiMarauderScriptSelectTypeAp:
@@ -79,61 +81,61 @@ void _wifi_marauder_script_execute_select(WifiMarauderScriptStageSelect* stage)
             command, sizeof(command), "select %s -f \"%s\"\n", select_type, stage->filter);
     }
 
-    wifi_marauder_uart_tx((uint8_t*)command, command_length);
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)command, command_length);
 }
 
 void _wifi_marauder_script_execute_deauth(
     WifiMarauderScriptStageDeauth* stage,
     WifiMarauderScriptWorker* worker) {
     const char attack_command[] = "attack -t deauth\n";
-    wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(attack_command), strlen(attack_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_probe(
     WifiMarauderScriptStageProbe* stage,
     WifiMarauderScriptWorker* worker) {
     const char attack_command[] = "attack -t probe\n";
-    wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(attack_command), strlen(attack_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_sniff_raw(
     WifiMarauderScriptStageSniffRaw* stage,
     WifiMarauderScriptWorker* worker) {
-    const char sniff_command[] = "sniffraw\n";
-    wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command));
+    const char sniff_command[] = "sniffraw -serial\n";
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)sniff_command, strlen(sniff_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_sniff_beacon(
     WifiMarauderScriptStageSniffBeacon* stage,
     WifiMarauderScriptWorker* worker) {
-    const char sniff_command[] = "sniffbeacon\n";
-    wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command));
+    const char sniff_command[] = "sniffbeacon -serial\n";
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)sniff_command, strlen(sniff_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_sniff_deauth(
     WifiMarauderScriptStageSniffDeauth* stage,
     WifiMarauderScriptWorker* worker) {
-    const char sniff_command[] = "sniffdeauth\n";
-    wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command));
+    const char sniff_command[] = "sniffdeauth -serial\n";
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)sniff_command, strlen(sniff_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_sniff_esp(
     WifiMarauderScriptStageSniffEsp* stage,
     WifiMarauderScriptWorker* worker) {
-    const char sniff_command[] = "sniffesp\n";
-    wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command));
+    const char sniff_command[] = "sniffesp -serial\n";
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)sniff_command, strlen(sniff_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_sniff_pmkid(
@@ -150,10 +152,10 @@ void _wifi_marauder_script_execute_sniff_pmkid(
                 len += snprintf(attack_command + len, sizeof(attack_command) - len, " -d");
             }
 
-            len += snprintf(attack_command + len, sizeof(attack_command) - len, "\n");
-            wifi_marauder_uart_tx((uint8_t*)attack_command, len);
+            len += snprintf(attack_command + len, sizeof(attack_command) - len, " -serial\n");
+            wifi_marauder_uart_tx(worker->uart, (uint8_t*)attack_command, len);
             _wifi_marauder_script_delay(worker, stage->timeout);
-            _send_stop();
+            _send_stop(worker);
         }
     } else {
         char attack_command[50] = "sniffpmkid";
@@ -167,27 +169,27 @@ void _wifi_marauder_script_execute_sniff_pmkid(
         if(stage->force_deauth) {
             len += snprintf(attack_command + len, sizeof(attack_command) - len, " -d");
         }
-        len += snprintf(attack_command + len, sizeof(attack_command) - len, "\n");
-        wifi_marauder_uart_tx((uint8_t*)attack_command, len);
+        len += snprintf(attack_command + len, sizeof(attack_command) - len, " -serial\n");
+        wifi_marauder_uart_tx(worker->uart, (uint8_t*)attack_command, len);
         _wifi_marauder_script_delay(worker, stage->timeout);
-        _send_stop();
+        _send_stop(worker);
     }
 }
 
 void _wifi_marauder_script_execute_sniff_pwn(
     WifiMarauderScriptStageSniffPwn* stage,
     WifiMarauderScriptWorker* worker) {
-    const char sniff_command[] = "sniffpwn\n";
-    wifi_marauder_uart_tx((uint8_t*)sniff_command, strlen(sniff_command));
+    const char sniff_command[] = "sniffpwn -serial\n";
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)sniff_command, strlen(sniff_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_beacon_list(
     WifiMarauderScriptStageBeaconList* stage,
     WifiMarauderScriptWorker* worker) {
     const char clearlist_command[] = "clearlist -s\n";
-    wifi_marauder_uart_tx((uint8_t*)(clearlist_command), strlen(clearlist_command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(clearlist_command), strlen(clearlist_command));
 
     char command[100];
     char* ssid;
@@ -195,8 +197,8 @@ void _wifi_marauder_script_execute_beacon_list(
     for(int i = 0; i < stage->ssid_count; i++) {
         ssid = stage->ssids[i];
         snprintf(command, sizeof(command), "ssid -a -n \"%s\"", ssid);
-        wifi_marauder_uart_tx((uint8_t*)(command), strlen(command));
-        _send_line_break();
+        wifi_marauder_uart_tx(worker->uart, (uint8_t*)(command), strlen(command));
+        _send_line_break(worker);
     }
     if(stage->random_ssids > 0) {
         char add_random_command[50];
@@ -205,27 +207,30 @@ void _wifi_marauder_script_execute_beacon_list(
             sizeof(add_random_command),
             "ssid -a -r -g %d\n",
             stage->random_ssids);
-        wifi_marauder_uart_tx((uint8_t*)add_random_command, strlen(add_random_command));
+        wifi_marauder_uart_tx(
+            worker->uart, (uint8_t*)add_random_command, strlen(add_random_command));
     }
     const char attack_command[] = "attack -t beacon -l\n";
-    wifi_marauder_uart_tx((uint8_t*)(attack_command), strlen(attack_command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)(attack_command), strlen(attack_command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
 void _wifi_marauder_script_execute_beacon_ap(
     WifiMarauderScriptStageBeaconAp* stage,
     WifiMarauderScriptWorker* worker) {
     const char command[] = "attack -t beacon -a\n";
-    wifi_marauder_uart_tx((uint8_t*)command, strlen(command));
+    wifi_marauder_uart_tx(worker->uart, (uint8_t*)command, strlen(command));
     _wifi_marauder_script_delay(worker, stage->timeout);
-    _send_stop();
+    _send_stop(worker);
 }
 
-void _wifi_marauder_script_execute_exec(WifiMarauderScriptStageExec* stage) {
+void _wifi_marauder_script_execute_exec(
+    WifiMarauderScriptStageExec* stage,
+    WifiMarauderScriptWorker* worker) {
     if(stage->command != NULL) {
-        wifi_marauder_uart_tx((uint8_t*)stage->command, strlen(stage->command));
-        _send_line_break();
+        wifi_marauder_uart_tx(worker->uart, (uint8_t*)stage->command, strlen(stage->command));
+        _send_line_break(worker);
     }
 }
 
@@ -248,8 +253,8 @@ void wifi_marauder_script_execute_start(void* context) {
             sizeof(command),
             "settings -s EnableLED %s",
             script->enable_led ? "enable" : "disable");
-        wifi_marauder_uart_tx((uint8_t*)command, strlen(command));
-        _send_line_break();
+        wifi_marauder_uart_tx(worker->uart, (uint8_t*)command, strlen(command));
+        _send_line_break(worker);
     }
 
     // Enables or disables PCAP saving according to script settings
@@ -259,8 +264,8 @@ void wifi_marauder_script_execute_start(void* context) {
             sizeof(command),
             "settings -s SavePCAP %s",
             script->save_pcap ? "enable" : "disable");
-        wifi_marauder_uart_tx((uint8_t*)command, strlen(command));
-        _send_line_break();
+        wifi_marauder_uart_tx(worker->uart, (uint8_t*)command, strlen(command));
+        _send_line_break(worker);
     }
 }
 
@@ -274,7 +279,7 @@ void wifi_marauder_script_execute_stage(WifiMarauderScriptStage* stage, void* co
         _wifi_marauder_script_execute_scan((WifiMarauderScriptStageScan*)stage_data, worker);
         break;
     case WifiMarauderScriptStageTypeSelect:
-        _wifi_marauder_script_execute_select((WifiMarauderScriptStageSelect*)stage_data);
+        _wifi_marauder_script_execute_select((WifiMarauderScriptStageSelect*)stage_data, worker);
         break;
     case WifiMarauderScriptStageTypeDeauth:
         _wifi_marauder_script_execute_deauth((WifiMarauderScriptStageDeauth*)stage_data, worker);
@@ -315,7 +320,7 @@ void wifi_marauder_script_execute_stage(WifiMarauderScriptStage* stage, void* co
             (WifiMarauderScriptStageBeaconAp*)stage_data, worker);
         break;
     case WifiMarauderScriptStageTypeExec:
-        _wifi_marauder_script_execute_exec((WifiMarauderScriptStageExec*)stage_data);
+        _wifi_marauder_script_execute_exec((WifiMarauderScriptStageExec*)stage_data, worker);
         break;
     case WifiMarauderScriptStageTypeDelay:
         _wifi_marauder_script_execute_delay((WifiMarauderScriptStageDelay*)stage_data, worker);

+ 2 - 1
base_pack/wifi_marauder_companion/script/wifi_marauder_script_worker.c

@@ -1,7 +1,7 @@
 #include "../wifi_marauder_app_i.h"
 #include "wifi_marauder_script_worker.h"
 
-WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc() {
+WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc(WifiMarauderUart* uart) {
     WifiMarauderScriptWorker* worker = malloc(sizeof(WifiMarauderScriptWorker));
     if(worker == NULL) {
         return NULL;
@@ -9,6 +9,7 @@ WifiMarauderScriptWorker* wifi_marauder_script_worker_alloc() {
     worker->callback_start = NULL;
     worker->callback_stage = NULL;
     worker->worker_thread = NULL;
+    worker->uart = uart;
     worker->is_running = false;
     return worker;
 }

+ 1 - 0
base_pack/wifi_marauder_companion/script/wifi_marauder_script_worker.h

@@ -11,6 +11,7 @@ typedef enum {
 typedef struct WifiMarauderScriptWorker {
     WifiMarauderScript* script;
     FuriThread* worker_thread;
+    WifiMarauderUart* uart;
     void (*callback_start)(void*);
     void (*callback_stage)(WifiMarauderScriptStage*, void*);
     void* context;

+ 0 - 2
base_pack/wifi_marauder_companion/wifi_marauder_app.c

@@ -161,7 +161,6 @@ void wifi_marauder_app_free(WifiMarauderApp* app) {
     scene_manager_free(app->scene_manager);
 
     wifi_marauder_uart_free(app->uart);
-    wifi_marauder_uart_free(app->lp_uart);
 
     // Close records
     furi_record_close(RECORD_GUI);
@@ -188,7 +187,6 @@ int32_t wifi_marauder_app(void* p) {
     wifi_marauder_load_settings(wifi_marauder_app);
 
     wifi_marauder_app->uart = wifi_marauder_usart_init(wifi_marauder_app);
-    wifi_marauder_app->lp_uart = wifi_marauder_lp_uart_init(wifi_marauder_app);
 
     view_dispatcher_run(wifi_marauder_app->view_dispatcher);
 

+ 0 - 1
base_pack/wifi_marauder_companion/wifi_marauder_app_i.h

@@ -80,7 +80,6 @@ struct WifiMarauderApp {
     int open_log_file_num_pages;
 
     WifiMarauderUart* uart;
-    WifiMarauderUart* lp_uart;
     int selected_menu_index;
     int selected_option_index[NUM_MENU_ITEMS];
     const char* selected_tx_string;

+ 95 - 33
base_pack/wifi_marauder_companion/wifi_marauder_uart.c

@@ -1,22 +1,27 @@
 #include "wifi_marauder_app_i.h"
 #include "wifi_marauder_uart.h"
 
-#define UART_CH (FuriHalUartIdUSART1)
-#define LP_UART_CH (FuriHalUartIdLPUART1)
+#define UART_CH (FuriHalSerialIdUsart)
 #define BAUDRATE (115200)
 
 struct WifiMarauderUart {
     WifiMarauderApp* app;
-    FuriHalUartId channel;
     FuriThread* rx_thread;
     FuriStreamBuffer* rx_stream;
+    FuriStreamBuffer* pcap_stream;
+    FuriHalSerialHandle* serial_handle;
+    bool pcap;
+    uint8_t mark_test_buf[11];
+    uint8_t mark_test_idx;
     uint8_t rx_buf[RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
+    void (*handle_rx_pcap_cb)(uint8_t* buf, size_t len, void* context);
 };
 
 typedef enum {
     WorkerEvtStop = (1 << 0),
     WorkerEvtRxDone = (1 << 1),
+    WorkerEvtPcapDone = (1 << 2),
 } WorkerEvtFlags;
 
 void wifi_marauder_uart_set_handle_rx_data_cb(
@@ -26,14 +31,75 @@ void wifi_marauder_uart_set_handle_rx_data_cb(
     uart->handle_rx_data_cb = handle_rx_data_cb;
 }
 
-#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
+void wifi_marauder_uart_set_handle_rx_pcap_cb(
+    WifiMarauderUart* uart,
+    void (*handle_rx_pcap_cb)(uint8_t* buf, size_t len, void* context)) {
+    furi_assert(uart);
+    uart->handle_rx_pcap_cb = handle_rx_pcap_cb;
+}
 
-void wifi_marauder_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone | WorkerEvtPcapDone)
+
+void wifi_marauder_uart_on_irq_cb(
+    FuriHalSerialHandle* handle,
+    FuriHalSerialRxEvent event,
+    void* context) {
     WifiMarauderUart* uart = (WifiMarauderUart*)context;
 
-    if(ev == UartIrqEventRXNE) {
-        furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
-        furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
+        const char* mark_begin = "[BUF/BEGIN]";
+        const char* mark_close = "[BUF/CLOSE]";
+        if(uart->mark_test_idx != 0) {
+            // We are trying to match a marker
+            if(data == mark_begin[uart->mark_test_idx] ||
+               data == mark_close[uart->mark_test_idx]) {
+                // Received char matches next char in a marker, append to test buffer
+                uart->mark_test_buf[uart->mark_test_idx++] = data;
+                if(uart->mark_test_idx == sizeof(uart->mark_test_buf)) {
+                    // Test buffer reached max length, parse what marker this is and discard buffer
+                    if(!memcmp(
+                           uart->mark_test_buf, (void*)mark_begin, sizeof(uart->mark_test_buf))) {
+                        uart->pcap = true;
+                    } else if(!memcmp(
+                                  uart->mark_test_buf,
+                                  (void*)mark_close,
+                                  sizeof(uart->mark_test_buf))) {
+                        uart->pcap = false;
+                    }
+                    uart->mark_test_idx = 0;
+                }
+                // Don't pass to stream
+                return;
+            } else {
+                // Received char doesn't match any expected next char, send current test buffer
+                if(uart->pcap) {
+                    furi_stream_buffer_send(
+                        uart->pcap_stream, uart->mark_test_buf, uart->mark_test_idx, 0);
+                    furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtPcapDone);
+                } else {
+                    furi_stream_buffer_send(
+                        uart->rx_stream, uart->mark_test_buf, uart->mark_test_idx, 0);
+                    furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+                }
+                // Reset test buffer and try parsing this char from scratch
+                uart->mark_test_idx = 0;
+            }
+        }
+        // If we reach here the buffer is empty
+        if(data == mark_begin[0]) {
+            // Received marker start, append to test buffer
+            uart->mark_test_buf[uart->mark_test_idx++] = data;
+        } else {
+            // Not a marker start and we aren't matching a marker, this is just data
+            if(uart->pcap) {
+                furi_stream_buffer_send(uart->pcap_stream, &data, 1, 0);
+                furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtPcapDone);
+            } else {
+                furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
+                furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+            }
+        }
     }
 }
 
@@ -51,41 +117,44 @@ static int32_t uart_worker(void* context) {
                 if(uart->handle_rx_data_cb) uart->handle_rx_data_cb(uart->rx_buf, len, uart->app);
             }
         }
+        if(events & WorkerEvtPcapDone) {
+            size_t len =
+                furi_stream_buffer_receive(uart->pcap_stream, uart->rx_buf, RX_BUF_SIZE, 0);
+            if(len > 0) {
+                if(uart->handle_rx_pcap_cb) uart->handle_rx_pcap_cb(uart->rx_buf, len, uart->app);
+            }
+        }
     }
 
     furi_stream_buffer_free(uart->rx_stream);
+    furi_stream_buffer_free(uart->pcap_stream);
 
     return 0;
 }
 
-void wifi_marauder_uart_tx(uint8_t* data, size_t len) {
-    furi_hal_uart_tx(UART_CH, data, len);
-}
-
-void wifi_marauder_lp_uart_tx(uint8_t* data, size_t len) {
-    furi_hal_uart_tx(LP_UART_CH, data, len);
+void wifi_marauder_uart_tx(WifiMarauderUart* uart, uint8_t* data, size_t len) {
+    furi_hal_serial_tx(uart->serial_handle, data, len);
 }
 
-WifiMarauderUart*
-    wifi_marauder_uart_init(WifiMarauderApp* app, FuriHalUartId channel, const char* thread_name) {
+WifiMarauderUart* wifi_marauder_uart_init(
+    WifiMarauderApp* app,
+    FuriHalSerialId channel,
+    const char* thread_name) {
     WifiMarauderUart* uart = malloc(sizeof(WifiMarauderUart));
 
     uart->app = app;
-    uart->channel = channel;
     uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
+    uart->pcap_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
     uart->rx_thread = furi_thread_alloc();
     furi_thread_set_name(uart->rx_thread, thread_name);
     furi_thread_set_stack_size(uart->rx_thread, 1024);
     furi_thread_set_context(uart->rx_thread, uart);
     furi_thread_set_callback(uart->rx_thread, uart_worker);
     furi_thread_start(uart->rx_thread);
-    if(channel == FuriHalUartIdUSART1) {
-        furi_hal_console_disable();
-    } else if(channel == FuriHalUartIdLPUART1) {
-        furi_hal_uart_init(channel, BAUDRATE);
-    }
-    furi_hal_uart_set_br(channel, BAUDRATE);
-    furi_hal_uart_set_irq_cb(channel, wifi_marauder_uart_on_irq_cb, uart);
+    uart->serial_handle = furi_hal_serial_control_acquire(channel);
+    furi_check(uart->serial_handle);
+    furi_hal_serial_init(uart->serial_handle, BAUDRATE);
+    furi_hal_serial_async_rx_start(uart->serial_handle, wifi_marauder_uart_on_irq_cb, uart, false);
 
     return uart;
 }
@@ -94,10 +163,6 @@ WifiMarauderUart* wifi_marauder_usart_init(WifiMarauderApp* app) {
     return wifi_marauder_uart_init(app, UART_CH, "WifiMarauderUartRxThread");
 }
 
-WifiMarauderUart* wifi_marauder_lp_uart_init(WifiMarauderApp* app) {
-    return wifi_marauder_uart_init(app, LP_UART_CH, "WifiMarauderLPUartRxThread");
-}
-
 void wifi_marauder_uart_free(WifiMarauderUart* uart) {
     furi_assert(uart);
 
@@ -105,11 +170,8 @@ void wifi_marauder_uart_free(WifiMarauderUart* uart) {
     furi_thread_join(uart->rx_thread);
     furi_thread_free(uart->rx_thread);
 
-    furi_hal_uart_set_irq_cb(uart->channel, NULL, NULL);
-    if(uart->channel == FuriHalUartIdLPUART1) {
-        furi_hal_uart_deinit(uart->channel);
-    }
-    furi_hal_console_enable();
+    furi_hal_serial_deinit(uart->serial_handle);
+    furi_hal_serial_control_release(uart->serial_handle);
 
     free(uart);
 }

+ 4 - 3
base_pack/wifi_marauder_companion/wifi_marauder_uart.h

@@ -9,8 +9,9 @@ typedef struct WifiMarauderUart WifiMarauderUart;
 void wifi_marauder_uart_set_handle_rx_data_cb(
     WifiMarauderUart* uart,
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context));
-void wifi_marauder_uart_tx(uint8_t* data, size_t len);
-void wifi_marauder_lp_uart_tx(uint8_t* data, size_t len);
+void wifi_marauder_uart_set_handle_rx_pcap_cb(
+    WifiMarauderUart* uart,
+    void (*handle_rx_pcap_cb)(uint8_t* buf, size_t len, void* context));
+void wifi_marauder_uart_tx(WifiMarauderUart* uart, uint8_t* data, size_t len);
 WifiMarauderUart* wifi_marauder_usart_init(WifiMarauderApp* app);
-WifiMarauderUart* wifi_marauder_lp_uart_init(WifiMarauderApp* app);
 void wifi_marauder_uart_free(WifiMarauderUart* uart);

+ 2 - 0
base_pack/wifi_scanner/FlipperZeroWiFiModuleDefines.h

@@ -15,3 +15,5 @@
 #define FLIPPERZERO_SERIAL_BAUD 115200
 
 #define NA 0
+
+#define UART_CH (FuriHalSerialIdUsart)

+ 23 - 28
base_pack/wifi_scanner/wifi_scanner.c

@@ -1,8 +1,8 @@
 #include <furi.h>
-#include <furi_hal_console.h>
 #include <furi_hal_gpio.h>
 #include <furi_hal_power.h>
-#include <furi_hal_uart.h>
+#include <furi_hal_serial_control.h>
+#include <furi_hal_serial.h>
 #include <gui/canvas_i.h>
 #include <gui/gui.h>
 #include <input/input.h>
@@ -26,8 +26,6 @@
 #define WIFI_APP_LOG_E(format, ...)
 #endif // WIFI_APP_DEBUG
 
-#define DISABLE_CONSOLE !WIFI_APP_DEBUG
-
 #define ENABLE_MODULE_POWER 1
 #define ENABLE_MODULE_DETECTION 1
 
@@ -86,6 +84,7 @@ typedef struct SWiFiScannerApp {
     FuriThread* m_worker_thread;
     NotificationApp* m_notification;
     FuriStreamBuffer* m_rx_stream;
+    FuriHalSerialHandle* serial_handle;
 
     bool m_wifiModuleInitialized;
     bool m_wifiModuleAttached;
@@ -643,14 +642,16 @@ static void wifi_module_input_callback(InputEvent* input_event, FuriMessageQueue
     furi_message_queue_put(event_queue, &event, FuriWaitForever);
 }
 
-static void uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+static void
+    uart_on_irq_cb(FuriHalSerialHandle* handle, FuriHalSerialRxEvent event, void* context) {
     furi_assert(context);
 
     SWiFiScannerApp* app = context;
 
     WIFI_APP_LOG_I("uart_echo_on_irq_cb");
 
-    if(ev == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         WIFI_APP_LOG_I("ev == UartIrqEventRXNE");
         furi_stream_buffer_send(app->m_rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(app->m_worker_thread), WorkerEventRx);
@@ -808,11 +809,7 @@ typedef enum ESerialCommand {
     ESerialCommand_Restart
 } ESerialCommand;
 
-void send_serial_command(ESerialCommand command) {
-#if !DISABLE_CONSOLE
-    return;
-#endif
-
+void send_serial_command(SWiFiScannerApp* app, ESerialCommand command) {
     uint8_t data[1] = {0};
 
     switch(command) {
@@ -835,7 +832,7 @@ void send_serial_command(ESerialCommand command) {
         return;
     };
 
-    furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1);
+    furi_hal_serial_tx(app->serial_handle, data, 1);
 }
 
 int32_t wifi_scanner_app(void* p) {
@@ -905,15 +902,14 @@ int32_t wifi_scanner_app(void* p) {
     WIFI_APP_LOG_I("UART thread allocated");
 
     // Enable uart listener
-#if DISABLE_CONSOLE
-    furi_hal_console_disable();
-#endif
-    furi_hal_uart_set_br(FuriHalUartIdUSART1, FLIPPERZERO_SERIAL_BAUD);
-    furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_on_irq_cb, app);
+    app->serial_handle = furi_hal_serial_control_acquire(UART_CH);
+    furi_check(app->serial_handle);
+    furi_hal_serial_init(app->serial_handle, FLIPPERZERO_SERIAL_BAUD);
+    furi_hal_serial_async_rx_start(app->serial_handle, uart_on_irq_cb, app, false);
     WIFI_APP_LOG_I("UART Listener created");
 
     // Because we assume that module was on before we launched the app. We need to ensure that module will be in initial state on app start
-    send_serial_command(ESerialCommand_Restart);
+    send_serial_command(app, ESerialCommand_Restart);
 
     SPluginEvent event;
     for(bool processing = true; processing;) {
@@ -947,20 +943,20 @@ int32_t wifi_scanner_app(void* p) {
                         case InputKeyLeft:
                             if(event.m_input.type == InputTypeShort) {
                                 WIFI_APP_LOG_I("Previous");
-                                send_serial_command(ESerialCommand_Previous);
+                                send_serial_command(app, ESerialCommand_Previous);
                             } else if(event.m_input.type == InputTypeRepeat) {
                                 WIFI_APP_LOG_I("Previous Repeat");
-                                send_serial_command(ESerialCommand_Previous);
+                                send_serial_command(app, ESerialCommand_Previous);
                             }
                             break;
                         case InputKeyDown:
                         case InputKeyRight:
                             if(event.m_input.type == InputTypeShort) {
                                 WIFI_APP_LOG_I("Next");
-                                send_serial_command(ESerialCommand_Next);
+                                send_serial_command(app, ESerialCommand_Next);
                             } else if(event.m_input.type == InputTypeRepeat) {
                                 WIFI_APP_LOG_I("Next Repeat");
-                                send_serial_command(ESerialCommand_Next);
+                                send_serial_command(app, ESerialCommand_Next);
                             }
                             break;
                         default:
@@ -973,18 +969,18 @@ int32_t wifi_scanner_app(void* p) {
                         if(event.m_input.type == InputTypeShort) {
                             if(app->m_context == ScanMode) {
                                 WIFI_APP_LOG_I("Monitor Mode");
-                                send_serial_command(ESerialCommand_MonitorMode);
+                                send_serial_command(app, ESerialCommand_MonitorMode);
                             }
                         } else if(event.m_input.type == InputTypeLong) {
                             WIFI_APP_LOG_I("Scan");
-                            send_serial_command(ESerialCommand_Scan);
+                            send_serial_command(app, ESerialCommand_Scan);
                         }
                         break;
                     case InputKeyBack:
                         if(event.m_input.type == InputTypeShort) {
                             switch(app->m_context) {
                             case MonitorMode:
-                                send_serial_command(ESerialCommand_Scan);
+                                send_serial_command(app, ESerialCommand_Scan);
                                 break;
                             case ScanMode:
                                 processing = false;
@@ -1034,9 +1030,8 @@ int32_t wifi_scanner_app(void* p) {
     // Reset GPIO pins to default state
     furi_hal_gpio_init(&gpio_ext_pc0, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
 
-#if DISABLE_CONSOLE
-    furi_hal_console_enable();
-#endif
+    furi_hal_serial_deinit(app->serial_handle);
+    furi_hal_serial_control_release(app->serial_handle);
 
     view_port_enabled_set(view_port, false);
 

+ 2 - 1
non_catalog_apps/flipper_evil_portal/evil_portal_app.c

@@ -83,7 +83,8 @@ Evil_PortalApp* evil_portal_app_alloc() {
 
 void evil_portal_app_free(Evil_PortalApp* app) {
     // Send reset event to dev board
-    evil_portal_uart_tx((uint8_t*)(RESET_CMD "\nstopscan\n"), strlen(RESET_CMD "\nstopscan\n"));
+    evil_portal_uart_tx(
+        app->uart, (uint8_t*)(RESET_CMD "\nstopscan\n"), strlen(RESET_CMD "\nstopscan\n"));
 
     furi_assert(app);
 

+ 1 - 1
non_catalog_apps/flipper_evil_portal/evil_portal_app_i.h

@@ -19,7 +19,7 @@
 #define NUM_MENU_ITEMS (6)
 
 #define EVIL_PORTAL_TEXT_BOX_STORE_SIZE (4096)
-#define UART_CH (FuriHalUartIdUSART1)
+#define UART_CH (FuriHalSerialIdUsart)
 
 #define SET_HTML_CMD "sethtml"
 #define SET_AP_CMD "setap"

+ 64 - 22
non_catalog_apps/flipper_evil_portal/evil_portal_uart.c

@@ -6,8 +6,12 @@ struct Evil_PortalUart {
     Evil_PortalApp* app;
     FuriThread* rx_thread;
     FuriStreamBuffer* rx_stream;
+    bool pcap;
+    uint8_t mark_test_buf[11];
+    uint8_t mark_test_idx;
     uint8_t rx_buf[RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
+    FuriHalSerialHandle* serial_handle;
 };
 
 typedef enum {
@@ -24,12 +28,60 @@ void evil_portal_uart_set_handle_rx_data_cb(
 
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
 
-void evil_portal_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+void evil_portal_uart_on_irq_cb(
+    FuriHalSerialHandle* handle,
+    FuriHalSerialRxEvent event,
+    void* context) {
     Evil_PortalUart* uart = (Evil_PortalUart*)context;
 
-    if(ev == UartIrqEventRXNE) {
-        furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
-        furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
+        const char* mark_begin = "[BUF/BEGIN]";
+        const char* mark_close = "[BUF/CLOSE]";
+        if(uart->mark_test_idx != 0) {
+            // We are trying to match a marker
+            if(data == mark_begin[uart->mark_test_idx] ||
+               data == mark_close[uart->mark_test_idx]) {
+                // Received char matches next char in a marker, append to test buffer
+                uart->mark_test_buf[uart->mark_test_idx++] = data;
+                if(uart->mark_test_idx == sizeof(uart->mark_test_buf)) {
+                    // Test buffer reached max length, parse what marker this is and discard buffer
+                    if(!memcmp(
+                           uart->mark_test_buf, (void*)mark_begin, sizeof(uart->mark_test_buf))) {
+                        uart->pcap = true;
+                    } else if(!memcmp(
+                                  uart->mark_test_buf,
+                                  (void*)mark_close,
+                                  sizeof(uart->mark_test_buf))) {
+                        uart->pcap = false;
+                    }
+                    uart->mark_test_idx = 0;
+                }
+                // Don't pass to stream
+                return;
+            } else {
+                // Received char doesn't match any expected next char, send current test buffer
+                if(!uart->pcap) {
+                    furi_stream_buffer_send(
+                        uart->rx_stream, uart->mark_test_buf, uart->mark_test_idx, 0);
+                    furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+                }
+                // Reset test buffer and try parsing this char from scratch
+                uart->mark_test_idx = 0;
+            }
+        }
+        // If we reach here the buffer is empty
+        if(data == mark_begin[0]) {
+            // Received marker start, append to test buffer
+            uart->mark_test_buf[uart->mark_test_idx++] = data;
+        } else {
+            // Not a marker start and we aren't matching a marker, this is just data
+            if(!uart->pcap) {
+                // We want to ignore pcap data from marauder
+                furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
+                furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
+            }
+        }
     }
 }
 
@@ -75,14 +127,13 @@ static int32_t uart_worker(void* context) {
         }
     }
 
-    furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL);
     furi_stream_buffer_free(uart->rx_stream);
 
     return 0;
 }
 
-void evil_portal_uart_tx(uint8_t* data, size_t len) {
-    furi_hal_uart_tx(UART_CH, data, len);
+void evil_portal_uart_tx(Evil_PortalUart* uart, uint8_t* data, size_t len) {
+    furi_hal_serial_tx(uart->serial_handle, data, len);
 }
 
 Evil_PortalUart* evil_portal_uart_init(Evil_PortalApp* app) {
@@ -98,19 +149,13 @@ Evil_PortalUart* evil_portal_uart_init(Evil_PortalApp* app) {
 
     furi_thread_start(uart->rx_thread);
 
-    if(UART_CH == FuriHalUartIdUSART1) {
-        furi_hal_console_disable();
-    } else if(UART_CH == FuriHalUartIdLPUART1) {
-        furi_hal_uart_init(UART_CH, app->BAUDRATE);
-    }
-
     if(app->BAUDRATE == 0) {
         app->BAUDRATE = 115200;
     }
-    furi_hal_uart_set_br(UART_CH, app->BAUDRATE);
-    furi_hal_uart_set_irq_cb(UART_CH, evil_portal_uart_on_irq_cb, uart);
-
-    //evil_portal_uart_tx((uint8_t*)("XFW#EVILPORTAL=1\n"), strlen("XFW#EVILPORTAL=1\n"));
+    uart->serial_handle = furi_hal_serial_control_acquire(UART_CH);
+    furi_check(uart->serial_handle);
+    furi_hal_serial_init(uart->serial_handle, app->BAUDRATE);
+    furi_hal_serial_async_rx_start(uart->serial_handle, evil_portal_uart_on_irq_cb, uart, false);
 
     return uart;
 }
@@ -122,11 +167,8 @@ void evil_portal_uart_free(Evil_PortalUart* uart) {
     furi_thread_join(uart->rx_thread);
     furi_thread_free(uart->rx_thread);
 
-    if(UART_CH == FuriHalUartIdLPUART1) {
-        furi_hal_uart_deinit(UART_CH);
-    } else {
-        furi_hal_console_enable();
-    }
+    furi_hal_serial_deinit(uart->serial_handle);
+    furi_hal_serial_control_release(uart->serial_handle);
 
     free(uart);
 }

+ 1 - 1
non_catalog_apps/flipper_evil_portal/evil_portal_uart.h

@@ -9,6 +9,6 @@ typedef struct Evil_PortalUart Evil_PortalUart;
 void evil_portal_uart_set_handle_rx_data_cb(
     Evil_PortalUart* uart,
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context));
-void evil_portal_uart_tx(uint8_t* data, size_t len);
+void evil_portal_uart_tx(Evil_PortalUart* uart, uint8_t* data, size_t len);
 Evil_PortalUart* evil_portal_uart_init(Evil_PortalApp* app);
 void evil_portal_uart_free(Evil_PortalUart* uart);

+ 18 - 11
non_catalog_apps/flipper_evil_portal/scenes/evil_portal_scene_console_output.c

@@ -120,7 +120,8 @@ void evil_portal_scene_console_output_on_enter(void* context) {
             // Test evil portal syntax and response, marauder ignores it
             furi_string_printf(data, "setap=%s\n", (char*)app->ap_name);
             furi_string_reset(app->captured_line);
-            evil_portal_uart_tx((uint8_t*)(furi_string_get_cstr(data)), furi_string_size(data));
+            evil_portal_uart_tx(
+                app->uart, (uint8_t*)(furi_string_get_cstr(data)), furi_string_size(data));
             // TODO: move timeouts and commands elsewhere, can't block input cycle
             for(uint8_t t = 0; t < 69 && !captured(app, "ap set") && !captured(app, "\n>"); t++)
                 furi_delay_ms(100);
@@ -131,7 +132,7 @@ void evil_portal_scene_console_output_on_enter(void* context) {
                 furi_string_printf(data, "clearlist -a -s -c\nssid -a -n '%s'\n", app->ap_name);
                 furi_string_reset(app->captured_line);
                 evil_portal_uart_tx(
-                    (uint8_t*)(furi_string_get_cstr(data)), furi_string_size(data));
+                    app->uart, (uint8_t*)(furi_string_get_cstr(data)), furi_string_size(data));
                 // Marauder echoes the command, maybe still init so wait a while for echo
                 for(uint8_t t = 0; t < 10 && !captured(app, (char*)app->ap_name); t++)
                     furi_delay_ms(100);
@@ -142,6 +143,7 @@ void evil_portal_scene_console_output_on_enter(void* context) {
             if(icanhazmarauder) {
                 furi_string_reset(app->captured_line);
                 evil_portal_uart_tx(
+                    app->uart,
                     (uint8_t*)("evilportal -c sethtmlstr\n"),
                     strlen("evilportal -c sethtmlstr\n"));
                 for(uint8_t t = 0; t < 10 && !captured(app, "\n>") &&
@@ -151,19 +153,24 @@ void evil_portal_scene_console_output_on_enter(void* context) {
                 // Check for active attack
                 if(!(captured(app, "\n>") && !captured(app, "Setting HTML from serial..."))) {
                     furi_string_reset(app->captured_line);
-                    evil_portal_uart_tx(app->index_html, strlen((char*)app->index_html));
-                    evil_portal_uart_tx((uint8_t*)("\n"), 1);
+                    evil_portal_uart_tx(
+                        app->uart, app->index_html, strlen((char*)app->index_html));
+                    evil_portal_uart_tx(app->uart, (uint8_t*)("\n"), 1);
                     for(uint8_t t = 0; t < 20 && !captured(app, "html set"); t++)
                         furi_delay_ms(100);
                     evil_portal_uart_tx(
-                        (uint8_t*)("evilportal -c start\n"), strlen("evilportal -c start\n"));
+                        app->uart,
+                        (uint8_t*)("evilportal -c start\n"),
+                        strlen("evilportal -c start\n"));
                 }
             } else {
                 furi_string_set(data, "sethtml=");
                 furi_string_cat(data, (char*)app->index_html);
                 evil_portal_uart_tx(
-                    (uint8_t*)(furi_string_get_cstr(data)), strlen(furi_string_get_cstr(data)));
-                evil_portal_uart_tx((uint8_t*)("\n"), 1);
+                    app->uart,
+                    (uint8_t*)(furi_string_get_cstr(data)),
+                    strlen(furi_string_get_cstr(data)));
+                evil_portal_uart_tx(app->uart, (uint8_t*)("\n"), 1);
             }
 
             free(app->index_html);
@@ -172,12 +179,12 @@ void evil_portal_scene_console_output_on_enter(void* context) {
             furi_string_free(data);
         } else if(0 == strncmp(RESET_CMD, app->selected_tx_string, strlen(RESET_CMD))) {
             evil_portal_uart_tx(
-                (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
-            evil_portal_uart_tx((uint8_t*)("\nstopscan\n"), strlen("\nstopscan\n"));
+                app->uart, (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
+            evil_portal_uart_tx(app->uart, (uint8_t*)("\nstopscan\n"), strlen("\nstopscan\n"));
         } else if(1 == strncmp("help", app->selected_tx_string, strlen("help"))) {
             evil_portal_uart_tx(
-                (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
-            evil_portal_uart_tx((uint8_t*)("\n"), 1);
+                app->uart, (uint8_t*)(app->selected_tx_string), strlen(app->selected_tx_string));
+            evil_portal_uart_tx(app->uart, (uint8_t*)("\n"), 1);
         }
     }
 }

+ 3 - 3
non_catalog_apps/flipperzero_gpioreader/scenes/gpio_scene_usb_uart_config.c

@@ -42,7 +42,7 @@ void line_ensure_flow_invariant(GpioApp* app) {
     // selected. This function enforces that invariant by resetting flow_pins
     // to None if it is configured to 16,15 when LPUART is selected.
 
-    uint8_t available_flow_pins = app->usb_uart_cfg->uart_ch == FuriHalUartIdLPUART1 ? 3 : 4;
+    uint8_t available_flow_pins = app->usb_uart_cfg->uart_ch == FuriHalSerialIdLpuart ? 3 : 4;
     VariableItem* item = app->var_item_flow;
     variable_item_set_values_count(item, available_flow_pins);
 
@@ -73,9 +73,9 @@ static void line_port_cb(VariableItem* item) {
     variable_item_set_current_value_text(item, uart_ch[index]);
 
     if(index == 0)
-        app->usb_uart_cfg->uart_ch = FuriHalUartIdUSART1;
+        app->usb_uart_cfg->uart_ch = FuriHalSerialIdUsart;
     else if(index == 1)
-        app->usb_uart_cfg->uart_ch = FuriHalUartIdLPUART1;
+        app->usb_uart_cfg->uart_ch = FuriHalSerialIdLpuart;
 
     line_ensure_flow_invariant(app);
     view_dispatcher_send_custom_event(app->view_dispatcher, GpioUsbUartEventConfigSet);

+ 15 - 17
non_catalog_apps/flipperzero_gpioreader/usb_uart_bridge.c

@@ -43,6 +43,7 @@ struct UsbUartBridge {
 
     FuriThread* thread;
     FuriThread* tx_thread;
+    FuriHalSerialHandle* serial_handle;
 
     FuriStreamBuffer* rx_stream;
 
@@ -75,10 +76,12 @@ static const CdcCallbacks cdc_cb = {
 
 static int32_t usb_uart_tx_thread(void* context);
 
-static void usb_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+static void
+    usb_uart_on_irq_cb(FuriHalSerialHandle* handle, FuriHalSerialRxEvent event, void* context) {
     UsbUartBridge* usb_uart = (UsbUartBridge*)context;
 
-    if(ev == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         furi_stream_buffer_send(usb_uart->rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(usb_uart->thread), WorkerEvtRxDone);
     }
@@ -111,32 +114,27 @@ static void usb_uart_vcp_deinit(UsbUartBridge* usb_uart, uint8_t vcp_ch) {
 }
 
 static void usb_uart_serial_init(UsbUartBridge* usb_uart, uint8_t uart_ch) {
-    if(uart_ch == FuriHalUartIdUSART1) {
-        furi_hal_console_disable();
-    } else if(uart_ch == FuriHalUartIdLPUART1) {
-        furi_hal_uart_init(uart_ch, 115200);
-    }
-    furi_hal_uart_set_irq_cb(uart_ch, usb_uart_on_irq_cb, usb_uart);
+    usb_uart->serial_handle = furi_hal_serial_control_acquire(uart_ch);
+    furi_check(usb_uart->serial_handle);
+    furi_hal_serial_init(usb_uart->serial_handle, 115200);
+    furi_hal_serial_async_rx_start(usb_uart->serial_handle, usb_uart_on_irq_cb, usb_uart, false);
 }
 
 static void usb_uart_serial_deinit(UsbUartBridge* usb_uart, uint8_t uart_ch) {
-    UNUSED(usb_uart);
-    furi_hal_uart_set_irq_cb(uart_ch, NULL, NULL);
-    if(uart_ch == FuriHalUartIdUSART1)
-        furi_hal_console_enable();
-    else if(uart_ch == FuriHalUartIdLPUART1)
-        furi_hal_uart_deinit(uart_ch);
+    UNUSED(uart_ch);
+    furi_hal_serial_deinit(usb_uart->serial_handle);
+    furi_hal_serial_control_release(usb_uart->serial_handle);
 }
 
 static void usb_uart_set_baudrate(UsbUartBridge* usb_uart, uint32_t baudrate) {
     if(baudrate != 0) {
-        furi_hal_uart_set_br(usb_uart->cfg.uart_ch, baudrate);
+        furi_hal_serial_set_br(usb_uart->serial_handle, baudrate);
         usb_uart->st.baudrate_cur = baudrate;
     } else {
         struct usb_cdc_line_coding* line_cfg =
             furi_hal_cdc_get_port_settings(usb_uart->cfg.vcp_ch);
         if(line_cfg->dwDTERate > 0) {
-            furi_hal_uart_set_br(usb_uart->cfg.uart_ch, line_cfg->dwDTERate);
+            furi_hal_serial_set_br(usb_uart->serial_handle, baudrate);
             usb_uart->st.baudrate_cur = line_cfg->dwDTERate;
         }
     }
@@ -298,7 +296,7 @@ static int32_t usb_uart_tx_thread(void* context) {
 
             if(len > 0) {
                 usb_uart->st.tx_cnt += len;
-                furi_hal_uart_tx(usb_uart->cfg.uart_ch, data, len);
+                furi_hal_serial_tx(usb_uart->serial_handle, data, len);
             }
         }
     }

+ 1 - 1
non_catalog_apps/ifttt/application.fam

@@ -1,6 +1,6 @@
 App(
     appid="esp8266_ifttt_virtual_button",
-    name="[ESP] IFTTT Button",
+    name="[ESP8266] IFTTT Btn",
     apptype=FlipperAppType.EXTERNAL,
     entry_point="ifttt_virtual_button_app",
     cdefines=["APP_IFTTT_VIRTUAL_BUTTON"],

+ 16 - 6
non_catalog_apps/ifttt/ifttt_virtual_button.c

@@ -55,8 +55,8 @@ Settings* load_settings() {
     if(storage_common_stat(storage, CONFIG_FILE_PATH, NULL) != FSE_OK) {
         if(flipper_format_file_open_new(file, CONFIG_FILE_PATH)) {
             save_settings_file(file, settings);
+            flipper_format_file_close(file);
         }
-        flipper_format_file_close(file);
     } else {
         if(flipper_format_file_open_existing(file, CONFIG_FILE_PATH)) {
             uint32_t value;
@@ -78,8 +78,8 @@ Settings* load_settings() {
                     strcpy(settings->save_event, furi_string_get_cstr(text_event_value));
                 }
             }
+            flipper_format_file_close(file);
         }
-        flipper_format_file_close(file);
     }
 
     furi_string_free(text_ssid_value);
@@ -91,7 +91,10 @@ Settings* load_settings() {
     return settings;
 }
 
-void send_serial_command_config(ESerialCommand command, Settings* settings) {
+void send_serial_command_config(
+    FuriHalSerialHandle* serial_handle,
+    ESerialCommand command,
+    Settings* settings) {
     uint8_t data[1] = {0};
 
     char config_tmp[100];
@@ -126,7 +129,7 @@ void send_serial_command_config(ESerialCommand command, Settings* settings) {
             return;
         }
 
-        furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1);
+        furi_hal_serial_tx(serial_handle, data, 1);
     }
 }
 
@@ -155,6 +158,10 @@ VirtualButtonApp* ifttt_virtual_button_app_alloc(uint32_t first_scene) {
     app->gui = furi_record_open(RECORD_GUI);
     app->power = furi_record_open(RECORD_POWER);
 
+    app->serial_handle = furi_hal_serial_control_acquire(FuriHalSerialIdUsart);
+    furi_check(app->serial_handle);
+    furi_hal_serial_init(app->serial_handle, FLIPPERZERO_SERIAL_BAUD);
+
     // View dispatcher
     app->view_dispatcher = view_dispatcher_alloc();
     app->scene_manager = scene_manager_alloc(&virtual_button_scene_handlers, app);
@@ -169,7 +176,7 @@ VirtualButtonApp* ifttt_virtual_button_app_alloc(uint32_t first_scene) {
     view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
 
     // Views
-    app->sen_view = send_view_alloc();
+    app->sen_view = send_view_alloc(app->serial_handle);
     view_dispatcher_add_view(
         app->view_dispatcher, VirtualButtonAppViewSendView, send_view_get_view(app->sen_view));
 
@@ -212,6 +219,9 @@ void ifttt_virtual_button_app_free(VirtualButtonApp* app) {
     furi_record_close(RECORD_POWER);
     furi_record_close(RECORD_GUI);
 
+    furi_hal_serial_deinit(app->serial_handle);
+    furi_hal_serial_control_release(app->serial_handle);
+
     free(app);
 }
 
@@ -228,7 +238,7 @@ int32_t ifttt_virtual_button_app(void* p) {
     uint32_t first_scene = VirtualButtonAppSceneStart;
     VirtualButtonApp* app = ifttt_virtual_button_app_alloc(first_scene);
     memcpy(&app->settings, load_settings(), sizeof(Settings));
-    send_serial_command_config(ESerialCommand_Config, &(app->settings));
+    send_serial_command_config(app->serial_handle, ESerialCommand_Config, &(app->settings));
 
     view_dispatcher_run(app->view_dispatcher);
     ifttt_virtual_button_app_free(app);

+ 3 - 1
non_catalog_apps/ifttt/ifttt_virtual_button.h

@@ -13,7 +13,8 @@
 #include <flipper_format/flipper_format.h>
 #include <flipper_format/flipper_format_i.h>
 #include <storage/storage.h>
-#include <furi_hal_uart.h>
+#include <furi_hal_serial_control.h>
+#include <furi_hal_serial.h>
 #include "scenes/virtual_button_scene.h"
 
 #define APP_NAME "[ESP8266] IFTTT Virtual Button"
@@ -43,6 +44,7 @@ typedef struct {
     DialogEx* dialog;
     PowerInfo info;
     Settings settings;
+    FuriHalSerialHandle* serial_handle;
 } VirtualButtonApp;
 
 typedef enum {

+ 8 - 8
non_catalog_apps/ifttt/views/send_view.c

@@ -3,16 +3,16 @@
 #include <gui/elements.h>
 #include <notification/notification.h>
 #include <notification/notification_messages.h>
-#include <furi_hal_uart.h>
+#include <furi_hal_serial_control.h>
+#include <furi_hal_serial.h>
 #include <string.h>
 #include <stdio.h>
 
-#define FLIPPERZERO_SERIAL_BAUD 115200
-
 typedef enum ESerialCommand { ESerialCommand_Send } ESerialCommand;
 
 struct SendView {
     View* view;
+    FuriHalSerialHandle* serial_handle;
 };
 
 typedef struct {
@@ -26,7 +26,7 @@ static void Shake(void) {
     furi_record_close(RECORD_NOTIFICATION);
 }
 
-void send_serial_command_send(ESerialCommand command) {
+void send_serial_command_send(FuriHalSerialHandle* serial_handle, ESerialCommand command) {
     uint8_t data[1] = {0};
 
     char name[10] = "send";
@@ -40,7 +40,7 @@ void send_serial_command_send(ESerialCommand command) {
             return;
         };
 
-        furi_hal_uart_tx(FuriHalUartIdUSART1, data, 1);
+        furi_hal_serial_tx(serial_handle, data, 1);
     }
 }
 
@@ -72,7 +72,7 @@ static void send_view_process(SendView* send_view, InputEvent* event) {
                 } else if(event->key == InputKeyRight) {
                     model->right_pressed = true;
                     Shake();
-                    send_serial_command_send(ESerialCommand_Send);
+                    send_serial_command_send(send_view->serial_handle, ESerialCommand_Send);
                 } else if(event->key == InputKeyOk) {
                 } else if(event->key == InputKeyBack) {
                 }
@@ -107,14 +107,14 @@ static bool send_view_input_callback(InputEvent* event, void* context) {
     return consumed;
 }
 
-SendView* send_view_alloc() {
+SendView* send_view_alloc(FuriHalSerialHandle* serial_handle) {
     SendView* send_view = malloc(sizeof(SendView));
     send_view->view = view_alloc();
+    send_view->serial_handle = serial_handle;
     view_set_context(send_view->view, send_view);
     view_allocate_model(send_view->view, ViewModelTypeLocking, sizeof(SendViewModel));
     view_set_draw_callback(send_view->view, send_view_draw_callback);
     view_set_input_callback(send_view->view, send_view_input_callback);
-    furi_hal_uart_set_br(FuriHalUartIdUSART1, FLIPPERZERO_SERIAL_BAUD);
 
     return send_view;
 }

+ 10 - 1
non_catalog_apps/magspoof_flipper/README.md

@@ -1,8 +1,17 @@
-# magspoof_flipper
+# magspoof_flipper by Zachary Weiss
 WIP of MagSpoof for the Flipper Zero. Basic TX of saved files confirmed working against an MSR90 with an external H-bridge module mirroring Samy Kamkar's design. RFID coil output weaker; able to be picked up/detected by more compact mag readers such as Square, but yet to have success with it being decoded/parsed properly. Additional investigation into alternate internal TX options (CC1101, ST25R3916, piezo) underway; tentatively, RFID coil + speaker (`LF + P` config setting) results in the strongest internal TX tested to date but still weaker than a dedicated external module or an actual card swipe (and sounds like a dial-up modem from hell). Sample files with test data are included in `assets` for anyone wishing to experiment.
 
 Disclaimer: use responsibly, and at your own risk. While in my testing, I've seen no reason to believe this could damage the RFID (or other) hardware, this is inherently driving the coil in ways it was not designed or intended for; I take no responsibility for fried/bricked Flippers. Similarly, please only use this with magstripe cards and mag readers you own — this is solely meant as a proof of concept for educational purposes. I neither condone nor am sympathetic to malicious uses of my code.
 
+## Hummus's Fork
+I made this fork initially to add reading capability using UART magnetic card readers.
+
+Things that changed in this fork:
+- Added a basic card reading ability
+- Added a function to parse a new MagDevice from a Card String (%Track1?;Track2;Track3?;)
+- Swapped the pins between A6 to A7 on the card that I'm using, might add this to configuration scene later on
+- Adapted some of the APIs to the most recent firmware changes.
+
 ## Optional GPIO TX Module
 For those desiring better TX than the internal RFID coil can offer, one can build the module below, consisting of an H-bridge, a capacitor, and a coil.
 

+ 1 - 0
non_catalog_apps/magspoof_flipper/mag_i.h

@@ -84,6 +84,7 @@ typedef struct {
     FuriStreamBuffer* uart_rx_stream;
     uint8_t uart_rx_buf[UART_RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
+    FuriHalSerialHandle* serial_handle;
     
     char uart_text_input_store[UART_TERMINAL_TEXT_INPUT_STORE_SIZE + 1];
     FuriString* uart_text_box_store;

+ 10 - 10
non_catalog_apps/magspoof_flipper/scenes/mag_scene_read.c

@@ -7,9 +7,10 @@
 
 #define TAG "MagSceneRead"
 
-void uart_callback(UartIrqEvent event, uint8_t data, void* context) {
+void uart_callback(FuriHalSerialHandle* handle, FuriHalSerialRxEvent event, void* context) {
     Mag* mag = context;
-    if(event == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         furi_stream_buffer_send(mag->uart_rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(mag->uart_rx_thread), WorkerEvtRxDone);
     }
@@ -93,10 +94,10 @@ void mag_scene_read_on_enter(void* context) {
     update_widgets(mag);
 
     // Initialize UART
-    // furi_hal_console_disable();
-    furi_hal_uart_deinit(FuriHalUartIdUSART1);
-    furi_hal_uart_init(FuriHalUartIdUSART1, 9600);
-    furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, uart_callback, mag);
+    mag->serial_handle = furi_hal_serial_control_acquire(FuriHalSerialIdUsart);
+    furi_check(mag->serial_handle);
+    furi_hal_serial_init(mag->serial_handle, 9600);
+    furi_hal_serial_async_rx_start(mag->serial_handle, uart_callback, mag, false);
     FURI_LOG_D(TAG, "UART initialized");
 
     mag->uart_rx_thread = furi_thread_alloc();
@@ -177,9 +178,8 @@ void mag_scene_read_on_exit(void* context) {
 
     furi_string_free(mag->uart_text_box_store);
 
-    furi_hal_uart_set_irq_cb(FuriHalUartIdUSART1, NULL, NULL);
-    furi_hal_uart_deinit(FuriHalUartIdUSART1);
-    // furi_hal_console_enable();
+    furi_hal_serial_deinit(mag->serial_handle);
+    furi_hal_serial_control_release(mag->serial_handle);
 
     notification_message(mag->notifications, &sequence_blink_stop);
-}
+}

+ 1 - 2
non_catalog_apps/magspoof_flipper/scenes/mag_scene_read.h

@@ -5,7 +5,7 @@
 #define UART_RX_BUF_SIZE (320)
 #define UART_TERMINAL_TEXT_BOX_STORE_SIZE (4096)
 #define UART_TERMINAL_TEXT_INPUT_STORE_SIZE (512)
-#define UART_CH (FuriHalUartIdUSART1)
+#define UART_CH (FuriHalSerialIdUsart)
 #define UART_BAUDRATE (9600)
 
 typedef enum {
@@ -17,5 +17,4 @@ typedef enum {
     UARTEventRxData = 100,
 } UARTEvents;
 
-
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)

+ 1789 - 1621
non_catalog_apps/nrf24-batch/nrf24batch.c

@@ -2,7 +2,7 @@
 // Written by vad7, 10.01.2023. vad7@yahoo.com
 //
 #include "nrf24batch.h"
- 
+
 #include <furi.h>
 #include <furi_hal.h>
 #include <gui/gui.h>
@@ -13,16 +13,16 @@
 #include <nrf24.h>
 #include <u8g2.h>
 
-#define TAG 		"nrf24batch"
-#define VERSION		"1.9"
+#define TAG "nrf24batch"
+#define VERSION "1.9"
 
-#define SCAN_APP_PATH_FOLDER 	"/ext/nrf24batch"
-#define LOG_FILEEXT	 			".txt"
-#define NRF_READ_TIMEOUT		300UL	// ms
-#define WORK_PERIOD				2		// ms, Timer period
-#define MAX_CHANNEL				125
-#define FONT_5x7_SCREEN_WIDTH 	25
-#define NRF_EN_DYN_ACK			0		// does not work on some nrf24l01+ chips, (0/1)
+#define SCAN_APP_PATH_FOLDER STORAGE_APP_DATA_PATH_PREFIX
+#define LOG_FILEEXT ".txt"
+#define NRF_READ_TIMEOUT 300UL // ms
+#define WORK_PERIOD 2 // ms, Timer period
+#define MAX_CHANNEL 125
+#define FONT_5x7_SCREEN_WIDTH 25
+#define NRF_EN_DYN_ACK 0 // does not work on some nrf24l01+ chips, (0/1)
 
 const char SettingsFld_Info[] = "Info:";
 const char SettingsFld_Ch[] = "Ch:";
@@ -37,9 +37,9 @@ const char SettingsFld_WriteStart[] = "Write start:";
 const char SettingsFld_Payload[] = "Payload struct:";
 const char SettingsFld_ReadDefault[] = "R default:";
 const char SettingsFld_WriteDefault[] = "W default:";
-const char SettingsFld_Read[] = "R:";	// Read cmd
-const char SettingsFld_Write[] = "W:";	// Write cmd
-const char SettingsFld_Set[] = "S:";	// Set cmd (like Write but without "Write start" packet)
+const char SettingsFld_Read[] = "R:"; // Read cmd
+const char SettingsFld_Write[] = "W:"; // Write cmd
+const char SettingsFld_Set[] = "S:"; // Set cmd (like Write but without "Write start" packet)
 const char SettingsFld_ReadBatch[] = "RBatch:";
 const char SettingsFld_WriteBatch[] = "WBatch:";
 const char SettingsFld_SetBatch[] = "SBatch:";
@@ -53,27 +53,20 @@ const char AskQuestion_Save[] = "SAVE BATCH?";
 nRF24Batch* APP;
 uint8_t what_doing = 0; // 0 - setup, 1 - cmd list, 2 - read/write/listen cmd
 enum {
-	rwt_set_batch = 0,	// fast send packet without question
-	rwt_read_batch,		// Send read cmd and wait for answer in batch
-	rwt_read_cmd,		// Send read cmd and wait for answer
-	rwt_write_batch,	// Send write cmd (with Write start pkt if available) with a question before it
-	rwt_listen,			// Listen mode (wait incoming pkts)
-	rwt_max
-};
-uint8_t rw_type = rwt_read_batch;	// What to do: rwt_*
-enum {
-	sst_none = 0,
-	sst_sending,
-	sst_receiving,
-	sst_ok,
-	sst_error,
-	sst_timeout
+    rwt_set_batch = 0, // fast send packet without question
+    rwt_read_batch, // Send read cmd and wait for answer in batch
+    rwt_read_cmd, // Send read cmd and wait for answer
+    rwt_write_batch, // Send write cmd (with Write start pkt if available) with a question before it
+    rwt_listen, // Listen mode (wait incoming pkts)
+    rwt_max
 };
-uint8_t send_status = sst_none;// sst_*
+uint8_t rw_type = rwt_read_batch; // What to do: rwt_*
+enum { sst_none = 0, sst_sending, sst_receiving, sst_ok, sst_error, sst_timeout };
+uint8_t send_status = sst_none; // sst_*
 bool cmd_array = false;
 uint8_t cmd_array_idx;
 uint8_t cmd_array_cnt = 0;
-uint8_t cmd_array_type;				//  0 - auto, 1 - hex, 2 - decimal
+bool cmd_array_hex;
 uint8_t save_settings = 0;
 uint16_t view_cmd[rwt_max - 1] = {0}; // SetBatch, ReadBatch, Read, WriteBatch
 uint8_t view_x = 0;
@@ -82,1724 +75,1899 @@ char Info[35] = "";
 char file_name[FONT_5x7_SCREEN_WIDTH];
 char ERR_STR[FONT_5x7_SCREEN_WIDTH];
 uint8_t ERR = 0;
-uint8_t NRF_rate; 	// 0 - 250Kbps, 1 - 1Mbps, 2 - 2Mbps
-uint8_t NRF_channel;// 0..125
-uint8_t NRF_DPL;	// 1 - Dynamic Payload Length
-uint8_t NRF_CRC;	// 1 - No, 1 - CRC 1byte, 2 - CRC 2byte
-uint8_t NRF_RETR = ((0b0011<<4) | 0b1111); // Automatic Retransmission, ARD, ARC
-uint8_t NRF_Payload;// Payload len in bytes, 0..32
+uint8_t NRF_rate; // 0 - 250Kbps, 1 - 1Mbps, 2 - 2Mbps
+uint8_t NRF_channel; // 0..125
+uint8_t NRF_DPL; // 1 - Dynamic Payload Length
+uint8_t NRF_CRC; // 1 - No, 1 - CRC 1byte, 2 - CRC 2byte
+uint8_t NRF_RETR = ((0b0011 << 4) | 0b1111); // Automatic Retransmission, ARD, ARC
+uint8_t NRF_Payload; // Payload len in bytes, 0..32
 bool NRF_ERROR = 0;
-uint8_t NRF_INITED = 0;	// 0 - not, 1 - rw, rwt_listen - listen
+uint8_t NRF_INITED = 0; // 0 - not, 1 - rw, rwt_listen - listen
 bool NRF_BOARD_POWER_5V = false;
 uint8_t NRF_last_packet_send_st = 0;
-uint8_t NRF_resend = 1; // number of transaction attempts 
-int8_t  NRF_repeat = 0; // count number of repeated requests (until < NRF_resend)
+uint8_t NRF_resend = 1; // number of transaction attempts
+int8_t NRF_repeat = 0; // count number of repeated requests (until < NRF_resend)
 uint32_t NRF_time;
 uint16_t ReadCmdRepeatPeriod = 10; // s
 bool ReadRepeat = false;
-uint32_t delay_between_pkt = 10;// ms
+uint32_t delay_between_pkt = 10; // ms
 
-uint8_t addr[5];				// nRF24 address, MSB first
-uint8_t addr_len = 0;			// 2..5
+uint8_t addr[5]; // nRF24 address, MSB first
+uint8_t addr_len = 0; // 2..5
 uint8_t payload[32];
 uint8_t payload_receive[32];
-uint8_t payload_struct[32]; 	// sizeof(1..4) in bytes of each field, example: 2,1,1
+uint8_t payload_struct[32]; // sizeof(1..4) in bytes of each field, example: 2,1,1
 uint8_t payload_fields = 0;
-uint8_t payload_size = 0;		// bytes
-uint16_t view_Batch = 0;		// view pos in Batch or inside WriteBatch (Log[view_Batch])
-uint16_t view_WriteBatch = 0;	// view pos of WriteBatch list
-uint8_t setup_cursor = 0;		// cursor position on Setup scr
+uint8_t payload_size = 0; // bytes
+uint16_t view_Batch = 0; // view pos in Batch or inside WriteBatch (Log[view_Batch])
+uint16_t view_WriteBatch = 0; // view pos of WriteBatch list
+uint8_t setup_cursor = 0; // cursor position on Setup scr
 uint8_t Edit = 0;
-char   *Edit_pos;
-char   *Edit_start;
-bool Edit_hex;					// 0 - decimal, 1 - hex
-bool Edited = false;			// list of cmds edited
+char* Edit_pos;
+char* Edit_start;
+bool Edit_hex; // 0 - decimal, 1 - hex
+bool Edited = false; // list of cmds edited
 
 Stream* file_stream = NULL;
-FuriString *ReadDefault = NULL;
-FuriString *WriteDefault = NULL;
-FuriString *WriteStart = NULL;
-FuriString *Constants = NULL;		// text of STR=x
+FuriString* ReadDefault = NULL;
+FuriString* WriteDefault = NULL;
+FuriString* WriteStart = NULL;
+FuriString* Constants = NULL; // text of STR=x
 uint8_t listen_addr[5];
 uint8_t listen_addr_len = 0;
-char *ListenFields = NULL;			// ptr to string: field1,field2,... max 5 field now
+char* ListenFields = NULL; // ptr to string: field1,field2,... max 5 field now
 bool ListenNew;
-FuriHalRtcDateTime ListenLastTime = { 0 };
+FuriHalRtcDateTime ListenLastTime = {0};
 uint32_t ListenPrev = 0;
 uint32_t ListenLast = 0;
-FuriString **Read_cmd = NULL;		// Names of read cmd
+FuriString** Read_cmd = NULL; // Names of read cmd
 uint16_t Read_cmd_Total = 0;
-FuriString **Log = NULL;			// Strings: var=n
+FuriString** Log = NULL; // Strings: var=n
 uint16_t Log_Total = 0;
-FuriString **ReadBatch_cmd = NULL;	// Names of read batch cmd
+FuriString** ReadBatch_cmd = NULL; // Names of read batch cmd
 uint16_t ReadBatch_cmd_Total = 0;
-char *ReadBatch_cmd_curr = NULL;	// =0xFFFFFFFF - finish
-FuriString **WriteBatch_cmd = NULL;	// Names of write batch cmd
+char* ReadBatch_cmd_curr = NULL; // =0xFFFFFFFF - finish
+FuriString** WriteBatch_cmd = NULL; // Names of write batch cmd
 uint16_t WriteBatch_cmd_Total = 0;
-uint16_t WriteBatch_cmd_curr = 0;	// == _Total - finish
-FuriString **SetBatch_cmd = NULL;	// Names of set batch cmd
+uint16_t WriteBatch_cmd_curr = 0; // == _Total - finish
+FuriString** SetBatch_cmd = NULL; // Names of set batch cmd
 uint16_t SetBatch_cmd_Total = 0;
-uint16_t SetBatch_cmd_curr = 0;	// == _Total - finish
+uint16_t SetBatch_cmd_curr = 0; // == _Total - finish
 
-#define POWER_READ_PERIOD	501		// ms
+#define POWER_READ_PERIOD 501 // ms
 uint16_t pwr_read_timer = 0;
 int Current = 0;
 int CurrentStart = 0;
 
-enum {
-	ask_write_batch = 1,
-	ask_save_batch,
-	ask_skip_cmd,
-	ask_return,
-	ask_exit
-};
-uint8_t ask_question = 0;		// 1 - Ask now - ask_*
-uint8_t ask_question_answer = 0;// 0 - no, 1 - yes
+enum { ask_write_batch = 1, ask_save_batch, ask_skip_cmd, ask_return, ask_exit };
+uint8_t ask_question = 0; // 1 - Ask now - ask_*
+uint8_t ask_question_answer = 0; // 0 - no, 1 - yes
 
-static bool ask_fill_screen_buf(void)
-{
-	if(ask_question == ask_write_batch) strcpy(screen_buf, "RUN WRITE BATCH?");
-	else if(ask_question == ask_save_batch) strcpy(screen_buf, "SAVE AS WRITE BATCH?");
-	else if(ask_question == ask_skip_cmd) strcpy(screen_buf, "SKIP CMD?");
-	else if(ask_question == ask_return) strcpy(screen_buf, "RETURN?");
-	else if(ask_question == ask_exit) strcpy(screen_buf, "EXIT?");
-	else return false;
-	strcat(screen_buf, ask_question_answer ? " YES" : " NO");
-	return true;
+static bool ask_fill_screen_buf(void) {
+    if(ask_question == ask_write_batch)
+        strcpy(screen_buf, "RUN WRITE BATCH?");
+    else if(ask_question == ask_save_batch)
+        strcpy(screen_buf, "SAVE AS WRITE BATCH?");
+    else if(ask_question == ask_skip_cmd)
+        strcpy(screen_buf, "SKIP CMD?");
+    else if(ask_question == ask_return)
+        strcpy(screen_buf, "RETURN?");
+    else if(ask_question == ask_exit)
+        strcpy(screen_buf, "EXIT?");
+    else
+        return false;
+    strcat(screen_buf, ask_question_answer ? " YES" : " NO");
+    return true;
 }
 
 //#define MIN(a, b)  ((a<b)?a:b)
 
 static uint8_t GetHexVal(char hex) {
-	return hex == 0 ? 0 : ((uint8_t)hex - ((uint8_t)hex < 58 ? 48 : ((uint8_t)hex < 97 ? 55 : 87)));
+    return hex == 0 ? 0 :
+                      ((uint8_t)hex - ((uint8_t)hex < 58 ? 48 : ((uint8_t)hex < 97 ? 55 : 87)));
 }
 
-static bool is_digit(char *ptr, bool hex)
-{
-	char c = *ptr;
-	if(c >= '0' && c <= '9') return true;
-	if(hex) {
-		c &= ~0x20;
-		if(c >= 'A' && c <= 'F') return true;
-	} else if(c == '-') return true;
-	return false;
+static bool is_digit(char* ptr, bool hex) {
+    char c = *ptr;
+    if(c >= '0' && c <= '9') return true;
+    if(hex) {
+        c &= ~0x20;
+        if(c >= 'A' && c <= 'F') return true;
+    } else if(c == '-')
+        return true;
+    return false;
 }
 
 // Return num bytes in array
-static uint8_t ConvertHexToArray(char * hex, uint8_t * array, uint8_t maxlen) {
-	uint8_t len = 0;
-	while(maxlen) {
-		uint8_t ch = *hex++;
-		if(ch < ' ') break;
-		if(ch < '0') continue;
-		*array++ = (GetHexVal(ch) << 4) + GetHexVal(*hex++);
-		len++;
-		maxlen--;
-	}
-	return len;
+static uint8_t ConvertHexToArray(char* hex, uint8_t* array, uint8_t maxlen) {
+    uint8_t len = 0;
+    while(maxlen) {
+        uint8_t ch = *hex++;
+        if(ch < ' ') break;
+        if(ch < '0') continue;
+        *array++ = (GetHexVal(ch) << 4) + GetHexVal(*hex++);
+        len++;
+        maxlen--;
+    }
+    return len;
 }
 
-int32_t str_to_int(char *p)
-{
-	if(*(p+1) == 'x') { // hex
-		return strtol(p + 2, NULL, 16);
-	} else return strtol(p, NULL, 10);
+int32_t str_to_int(char* p) {
+    if(*(p + 1) == 'x') { // hex
+        return strtol(p + 2, NULL, 16);
+    } else
+        return strtol(p, NULL, 10);
 }
 
-void str_rtrim(char *p)
-{
-	char *delim_col = strchr(p, '\r'); 
-	if(delim_col) *delim_col = '\0';
-	else { 
-		delim_col = strchr(p, '\n'); 
-		if(delim_col) *delim_col = '\0';
-	}
+void str_rtrim(char* p) {
+    char* delim_col = strchr(p, '\r');
+    if(delim_col)
+        *delim_col = '\0';
+    else {
+        delim_col = strchr(p, '\n');
+        if(delim_col) *delim_col = '\0';
+    }
 }
 
-static void add_to_str_hex_bytes(char *out, uint8_t *arr, int bytes)
-{
-	if(bytes <= 0) return;
-	out += strlen(out);
-	do {
-		snprintf(out, 3, "%02X", *arr++);
-		out += 2;
-	} while(--bytes);
+static void add_to_str_hex_bytes(char* out, uint8_t* arr, int bytes) {
+    if(bytes <= 0) return;
+    out += strlen(out);
+    do {
+        snprintf(out, 3, "%02X", *arr++);
+        out += 2;
+    } while(--bytes);
 }
 
 // skip leading zeros
-static void add_to_str_hex_variable(char *out, uint8_t *arr, int size)
-{
-	if(size <= 0) return;
-	out += strlen(out);
-	arr += size - 1;
-	while(*arr == 0 && size > 1) {
-		arr--;
-		size--;
-	}
-	do {
-		snprintf(out, 3, "%02X", *arr--);
-		out += 2;
-	} while(--size);
+static void add_to_str_hex_variable(char* out, uint8_t* arr, int size) {
+    if(size <= 0) return;
+    out += strlen(out);
+    arr += size - 1;
+    while(*arr == 0 && size > 1) {
+        arr--;
+        size--;
+    }
+    do {
+        snprintf(out, 3, "%02X", *arr--);
+        out += 2;
+    } while(--size);
 }
 
-void Edit_insert_digit(char new)
-{
-	if(*Edit_pos == '-') return;
-	if(what_doing <= 1) {
-		if(strlen(Edit_start) < (what_doing == 0 && setup_cursor == 2 ? 3 : 5 * 2)) {
-			memmove(Edit_pos + 1, Edit_pos, strlen(Edit_pos) + 1);
-			*Edit_pos = new;
-		}
-	} else {
-		FuriString *fs = Log[view_Batch];
-		FuriString *ns = furi_string_alloc();
-		if(ns) {
-			uint16_t len = Edit_pos - (char*)furi_string_get_cstr(fs);
-			furi_string_set_n(ns, fs, 0, len);
-			furi_string_cat_printf(ns, "%c", new);
-			furi_string_cat_str(ns, Edit_pos);
-			Log[view_Batch] = ns;
-			Edit_pos = (char*)furi_string_get_cstr(ns);
-			Edit_start = Edit_pos + (Edit_start - (char*)furi_string_get_cstr(fs));
-			Edit_pos += len;
-			furi_string_free(fs);
-		}
-	}
+void Edit_insert_digit(char new) {
+    if(*Edit_pos == '-') return;
+    if(what_doing <= 1) {
+        if(strlen(Edit_start) < (what_doing == 0 && setup_cursor == 2 ? 3 : 5 * 2)) {
+            memmove(Edit_pos + 1, Edit_pos, strlen(Edit_pos) + 1);
+            *Edit_pos = new;
+        }
+    } else {
+        FuriString* fs = Log[view_Batch];
+        FuriString* ns = furi_string_alloc();
+        if(ns) {
+            uint16_t len = Edit_pos - (char*)furi_string_get_cstr(fs);
+            furi_string_set_n(ns, fs, 0, len);
+            furi_string_cat_printf(ns, "%c", new);
+            furi_string_cat_str(ns, Edit_pos);
+            Log[view_Batch] = ns;
+            Edit_pos = (char*)furi_string_get_cstr(ns);
+            Edit_start = Edit_pos + (Edit_start - (char*)furi_string_get_cstr(fs));
+            Edit_pos += len;
+            furi_string_free(fs);
+        }
+    }
 }
 
-int32_t get_payload_receive_field(uint8_t *var, uint8_t size)
-{
-	if(size <= 1) return *var;
-	else if(size == 2) return *(int16_t*)var;
-	else if(size == 3) return (*(uint32_t*)var) & 0xFFFFFF;
-	else return *(int32_t*)var;
+int32_t get_payload_receive_field(uint8_t* var, uint8_t size) {
+    if(size <= 1)
+        return *var;
+    else if(size == 2)
+        return *(int16_t*)var;
+    else if(size == 3)
+        return (*(uint32_t*)var) & 0xFFFFFF;
+    else
+        return *(int32_t*)var;
 }
 
-void free_Log()
-{
-	if(Log_Total) {
-		for(uint16_t i = 0; i < Log_Total; i++) if(Log[i]) furi_string_free(Log[i]);
-		Log_Total = 0;
-	}
-	if(Log) {
-		free(Log);
-		Log = NULL;
-	}
+void free_Log() {
+    if(Log_Total) {
+        for(uint16_t i = 0; i < Log_Total; i++)
+            if(Log[i]) furi_string_free(Log[i]);
+        Log_Total = 0;
+    }
+    if(Log) {
+        free(Log);
+        Log = NULL;
+    }
 }
 
-void free_store(void)
-{
-	if(Constants) {
-		furi_string_free(Constants);
-		Constants = NULL;
-	}
-	if(ReadDefault) {
-		furi_string_free(ReadDefault);
-		ReadDefault = NULL;
-	}
-	if(WriteDefault) {
-		furi_string_free(WriteDefault);
-		WriteDefault = NULL;
-	}
-	if(WriteStart) {
-		furi_string_free(WriteStart);
-		WriteDefault = NULL;
-	}
-	if(ListenFields) {
-		free(ListenFields);
-		ListenFields = NULL;
-	}
-	if(Read_cmd_Total) {
-		for(uint16_t i = 0; i < Read_cmd_Total; i++) furi_string_free(Read_cmd[i]);
-		Read_cmd_Total = 0;
-	}
-	if(Read_cmd) {
-		free(Read_cmd);
-		Read_cmd = NULL;
-	}
-	if(ReadBatch_cmd_Total) {
-		for(uint16_t i = 0; i < ReadBatch_cmd_Total; i++) furi_string_free(ReadBatch_cmd[i]);
-		ReadBatch_cmd_Total = 0;
-	}
-	if(ReadBatch_cmd) {
-		free(ReadBatch_cmd);
-		ReadBatch_cmd = NULL;
-	}
-	if(WriteBatch_cmd_Total) {
-		for(uint16_t i = 0; i < WriteBatch_cmd_Total; i++) furi_string_free(WriteBatch_cmd[i]);
-		WriteBatch_cmd_Total = 0;
-	}
-	if(WriteBatch_cmd) {
-		free(WriteBatch_cmd);
-		WriteBatch_cmd = NULL;
-	}
-	if(SetBatch_cmd_Total) {
-		for(uint16_t i = 0; i < SetBatch_cmd_Total; i++) furi_string_free(SetBatch_cmd[i]);
-		SetBatch_cmd_Total = 0;
-	}
-	if(SetBatch_cmd) {
-		free(SetBatch_cmd);
-		SetBatch_cmd = NULL;
-	}
-	free_Log();
+void free_store(void) {
+    if(Constants) {
+        furi_string_free(Constants);
+        Constants = NULL;
+    }
+    if(ReadDefault) {
+        furi_string_free(ReadDefault);
+        ReadDefault = NULL;
+    }
+    if(WriteDefault) {
+        furi_string_free(WriteDefault);
+        WriteDefault = NULL;
+    }
+    if(WriteStart) {
+        furi_string_free(WriteStart);
+        WriteDefault = NULL;
+    }
+    if(ListenFields) {
+        free(ListenFields);
+        ListenFields = NULL;
+    }
+    if(Read_cmd_Total) {
+        for(uint16_t i = 0; i < Read_cmd_Total; i++) furi_string_free(Read_cmd[i]);
+        Read_cmd_Total = 0;
+    }
+    if(Read_cmd) {
+        free(Read_cmd);
+        Read_cmd = NULL;
+    }
+    if(ReadBatch_cmd_Total) {
+        for(uint16_t i = 0; i < ReadBatch_cmd_Total; i++) furi_string_free(ReadBatch_cmd[i]);
+        ReadBatch_cmd_Total = 0;
+    }
+    if(ReadBatch_cmd) {
+        free(ReadBatch_cmd);
+        ReadBatch_cmd = NULL;
+    }
+    if(WriteBatch_cmd_Total) {
+        for(uint16_t i = 0; i < WriteBatch_cmd_Total; i++) furi_string_free(WriteBatch_cmd[i]);
+        WriteBatch_cmd_Total = 0;
+    }
+    if(WriteBatch_cmd) {
+        free(WriteBatch_cmd);
+        WriteBatch_cmd = NULL;
+    }
+    if(SetBatch_cmd_Total) {
+        for(uint16_t i = 0; i < SetBatch_cmd_Total; i++) furi_string_free(SetBatch_cmd[i]);
+        SetBatch_cmd_Total = 0;
+    }
+    if(SetBatch_cmd) {
+        free(SetBatch_cmd);
+        SetBatch_cmd = NULL;
+    }
+    free_Log();
 }
 
-void update_power(void)
-{
-	Current = furi_hal_power_get_battery_current(FuriHalPowerICFuelGauge) * 1000;
+void update_power(void) {
+    Current = furi_hal_power_get_battery_current(FuriHalPowerICFuelGauge) * 1000;
 }
 
-void check_en_power_5V(void)
-{
-	if(!furi_hal_power_is_otg_enabled() && !furi_hal_power_is_charging()) {
-		FURI_LOG_D("PWR", "NO 5V, TURN ON");
-		notification_message(APP->notification, &sequence_blink_yellow_100);
-		furi_delay_ms(10);
-		update_power();
-		CurrentStart = Current;
-		furi_hal_power_enable_otg();
-		NRF_BOARD_POWER_5V = true;
-		furi_delay_ms(100);
-		NRF_INITED = 0;
-	}
+void check_en_power_5V(void) {
+    if(!furi_hal_power_is_otg_enabled() && !furi_hal_power_is_charging()) {
+        FURI_LOG_D("PWR", "NO 5V, TURN ON");
+        notification_message(APP->notification, &sequence_blink_yellow_100);
+        furi_delay_ms(10);
+        update_power();
+        CurrentStart = Current;
+        furi_hal_power_enable_otg();
+        NRF_BOARD_POWER_5V = true;
+        furi_delay_ms(100);
+        NRF_INITED = 0;
+    }
 }
 
 static bool select_settings_file() {
-	DialogsApp* dialogs = furi_record_open("dialogs");
-	bool result = false;
-	FuriString* path;
-	path = furi_string_alloc();
-	furi_string_set(path, SCAN_APP_PATH_FOLDER);
-	DialogsFileBrowserOptions browser_options;
-	dialog_file_browser_set_basic_options(&browser_options, ".txt", NULL);
-	browser_options.hide_ext = false;
-	bool ret = dialog_file_browser_show(dialogs, path, path, &browser_options);
-	furi_record_close("dialogs");
-	if(ret) {
-		if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
-			FURI_LOG_D(TAG, "Cannot open file \"%s\"", furi_string_get_cstr(path));
-			file_stream_close(file_stream);
-		} else {
-			FURI_LOG_D(TAG, "Open file \"%s\"", furi_string_get_cstr(path));
-			strncpy(file_name, furi_string_get_cstr(path) + sizeof(SCAN_APP_PATH_FOLDER), sizeof(file_name));
-			result = true;
-		}
-	}
-	furi_string_free(path);
-	return result;
+    DialogsApp* dialogs = furi_record_open("dialogs");
+    bool result = false;
+    FuriString* path;
+    path = furi_string_alloc();
+    furi_string_set(path, SCAN_APP_PATH_FOLDER);
+    DialogsFileBrowserOptions browser_options;
+    dialog_file_browser_set_basic_options(&browser_options, ".txt", NULL);
+    browser_options.hide_ext = false;
+    bool ret = dialog_file_browser_show(dialogs, path, path, &browser_options);
+    furi_record_close("dialogs");
+    if(ret) {
+        if(!file_stream_open(
+               file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
+            FURI_LOG_D(TAG, "Cannot open file \"%s\"", furi_string_get_cstr(path));
+            file_stream_close(file_stream);
+        } else {
+            FURI_LOG_D(TAG, "Open file \"%s\"", furi_string_get_cstr(path));
+            strncpy(
+                file_name,
+                furi_string_get_cstr(path) + sizeof(SCAN_APP_PATH_FOLDER),
+                sizeof(file_name));
+            result = true;
+        }
+    }
+    furi_string_free(path);
+    return result;
 }
 
-static void prepare_nrf24(void)
-{
-	check_en_power_5V();
-	if(!NRF_INITED || rw_type == rwt_listen || NRF_INITED == rwt_listen) {
-		FURI_LOG_D("NRF", "Prepare");
-		uint8_t adrlen, *adr;
-		if(rw_type == rwt_listen) {
-			adrlen = listen_addr_len;
-			adr = listen_addr;
-			NRF_INITED = rwt_listen;
-		} else {
-			adrlen = addr_len;
-			adr = addr;
-			NRF_INITED = 1;
-		}
-		furi_hal_gpio_write(nrf24_CE_PIN, false);
-		nrf24_set_mac(REG_RX_ADDR_P0, adr, adrlen);
-		uint8_t tmp[5] = { 0 };
-		nrf24_read_reg(nrf24_HANDLE, REG_RX_ADDR_P0, tmp, adrlen);
-		for(uint8_t i = 0; i < adrlen / 2; i++) {
-			uint8_t tb = tmp[i];
-			tmp[i] = tmp[adrlen - i - 1];
-			tmp[adrlen - i - 1] = tb;
-		}
-		NRF_ERROR = memcmp(adr, tmp, adrlen) != 0;
-		if(NRF_ERROR) {
-			NRF_INITED = 0;
-			return;
-		}
-		// EN_DYN_ACK(0x01) option for W_TX_PAYLOAD_NOACK cmd broke AA on some fake nRF24l01+, i.e. set it to 0
-		nrf24_write_reg(nrf24_HANDLE, REG_FEATURE, NRF_EN_DYN_ACK + (NRF_DPL ? 4 : 0)); // Dynamic Payload, Payload with ACK, W_TX_PAYLOAD_NOACK command
-		nrf24_write_reg(nrf24_HANDLE, REG_RF_CH, NRF_channel);
-		nrf24_write_reg(nrf24_HANDLE, REG_RF_SETUP, (NRF_rate == 0 ? 0b00100000 : NRF_rate == 1 ? 0 : 0b00001000) | 0b111); // +TX high power
-		nrf24_write_reg(nrf24_HANDLE, REG_CONFIG, 0x70 | ((NRF_CRC == 1 ? 0b1000 : NRF_CRC == 2 ? 0b1100 : 0))); // Mask all interrupts
-		nrf24_write_reg(nrf24_HANDLE, REG_SETUP_RETR, NRF_RETR); // Automatic Retransmission, ARD<<4 + ARC
-		nrf24_write_reg(nrf24_HANDLE, REG_EN_AA, 0x01); // Auto acknowledgement
-		nrf24_write_reg(nrf24_HANDLE, REG_DYNPD, NRF_DPL ? 0x3F : 0); // Enable dynamic payload reg
-		nrf24_write_reg(nrf24_HANDLE, RX_PW_P0, payload_size);
-		nrf24_set_maclen(nrf24_HANDLE, adrlen);
-		nrf24_set_mac(REG_TX_ADDR, adr, adrlen);
-		nrf24_write_reg(nrf24_HANDLE, REG_EN_RXADDR, 1);
-		//nrf24_set_idle(nrf24_HANDLE);
-	}
-	nrf24_flush_tx(nrf24_HANDLE);
-	nrf24_flush_rx(nrf24_HANDLE);
-	nrf24_write_reg(nrf24_HANDLE, REG_STATUS, MAX_RT | RX_DR | TX_DS);
+static void prepare_nrf24(void) {
+    check_en_power_5V();
+    if(!NRF_INITED || rw_type == rwt_listen || NRF_INITED == rwt_listen) {
+        FURI_LOG_D("NRF", "Prepare");
+        uint8_t adrlen, *adr;
+        if(rw_type == rwt_listen) {
+            adrlen = listen_addr_len;
+            adr = listen_addr;
+            NRF_INITED = rwt_listen;
+        } else {
+            adrlen = addr_len;
+            adr = addr;
+            NRF_INITED = 1;
+        }
+        furi_hal_gpio_write(nrf24_CE_PIN, false);
+        nrf24_set_mac(REG_RX_ADDR_P0, adr, adrlen);
+        uint8_t tmp[5] = {0};
+        nrf24_read_reg(nrf24_HANDLE, REG_RX_ADDR_P0, tmp, adrlen);
+        for(uint8_t i = 0; i < adrlen / 2; i++) {
+            uint8_t tb = tmp[i];
+            tmp[i] = tmp[adrlen - i - 1];
+            tmp[adrlen - i - 1] = tb;
+        }
+        NRF_ERROR = memcmp(adr, tmp, adrlen) != 0;
+        if(NRF_ERROR) {
+            NRF_INITED = 0;
+            return;
+        }
+        // EN_DYN_ACK(0x01) option for W_TX_PAYLOAD_NOACK cmd broke AA on some fake nRF24l01+, i.e. set it to 0
+        nrf24_write_reg(
+            nrf24_HANDLE,
+            REG_FEATURE,
+            NRF_EN_DYN_ACK +
+                (NRF_DPL ? 4 :
+                           0)); // Dynamic Payload, Payload with ACK, W_TX_PAYLOAD_NOACK command
+        nrf24_write_reg(nrf24_HANDLE, REG_RF_CH, NRF_channel);
+        nrf24_write_reg(
+            nrf24_HANDLE,
+            REG_RF_SETUP,
+            (NRF_rate == 0 ? 0b00100000 :
+             NRF_rate == 1 ? 0 :
+                             0b00001000) |
+                0b111); // +TX high power
+        nrf24_write_reg(
+            nrf24_HANDLE,
+            REG_CONFIG,
+            0x70 | ((NRF_CRC == 1 ? 0b1000 :
+                     NRF_CRC == 2 ? 0b1100 :
+                                    0))); // Mask all interrupts
+        nrf24_write_reg(
+            nrf24_HANDLE, REG_SETUP_RETR, NRF_RETR); // Automatic Retransmission, ARD<<4 + ARC
+        nrf24_write_reg(nrf24_HANDLE, REG_EN_AA, 0x01); // Auto acknowledgement
+        nrf24_write_reg(nrf24_HANDLE, REG_DYNPD, NRF_DPL ? 0x3F : 0); // Enable dynamic payload reg
+        nrf24_write_reg(nrf24_HANDLE, RX_PW_P0, payload_size);
+        nrf24_set_maclen(nrf24_HANDLE, adrlen);
+        nrf24_set_mac(REG_TX_ADDR, adr, adrlen);
+        nrf24_write_reg(nrf24_HANDLE, REG_EN_RXADDR, 1);
+        //nrf24_set_idle(nrf24_HANDLE);
+    }
+    nrf24_flush_tx(nrf24_HANDLE);
+    nrf24_flush_rx(nrf24_HANDLE);
+    nrf24_write_reg(nrf24_HANDLE, REG_STATUS, MAX_RT | RX_DR | TX_DS);
 }
 
 // true - ok
-uint8_t nrf24_send_packet()
-{
-	if(furi_log_get_level() == FuriLogLevelDebug) {
-		char buf[65]; buf[0] = 0; add_to_str_hex_bytes(buf, payload, payload_size); FURI_LOG_D(TAG, "SEND: %s", buf);
-	}
-	//nrf24_flush_tx(nrf24_HANDLE);
-	//nrf24_write_reg(nrf24_HANDLE, REG_STATUS, RX_DR | TX_DS | MAX_RT);
-	NRF_last_packet_send_st = nrf24_txpacket(nrf24_HANDLE, payload, payload_size, true); // ACK
-	if(NRF_last_packet_send_st) { 
-		if((rw_type == rwt_read_cmd || rw_type == rwt_read_batch) && send_status == sst_sending) { // Read
-			nrf24_set_rx_mode(nrf24_HANDLE);
-			send_status = sst_receiving; // receiving
-		}
-	} else notification_message(APP->notification, &sequence_blink_red_100);
-	NRF_time = furi_get_tick();
-	FURI_LOG_D(TAG, "Send packet: %d%s", NRF_last_packet_send_st, send_status == sst_receiving ? ", Receiving" : "");
-	return NRF_last_packet_send_st;
+uint8_t nrf24_send_packet() {
+    if(furi_log_get_level() == FuriLogLevelDebug) {
+        char buf[65];
+        buf[0] = 0;
+        add_to_str_hex_bytes(buf, payload, payload_size);
+        FURI_LOG_D(TAG, "SEND: %s", buf);
+    }
+    //nrf24_flush_tx(nrf24_HANDLE);
+    //nrf24_write_reg(nrf24_HANDLE, REG_STATUS, RX_DR | TX_DS | MAX_RT);
+    NRF_last_packet_send_st = nrf24_txpacket(nrf24_HANDLE, payload, payload_size, true); // ACK
+    if(NRF_last_packet_send_st) {
+        if((rw_type == rwt_read_cmd || rw_type == rwt_read_batch) &&
+           send_status == sst_sending) { // Read
+            nrf24_set_rx_mode(nrf24_HANDLE);
+            send_status = sst_receiving; // receiving
+        }
+    } else
+        notification_message(APP->notification, &sequence_blink_red_100);
+    NRF_time = furi_get_tick();
+    FURI_LOG_D(
+        TAG,
+        "Send packet: %d%s",
+        NRF_last_packet_send_st,
+        send_status == sst_receiving ? ", Receiving" : "");
+    return NRF_last_packet_send_st;
 }
 
-uint8_t nrf24_resend_read_packet()
-{
-	if(Log_Total && !cmd_array) {
-		FuriString *str = Log[Log_Total - 1];
-		char *p = strstr(furi_string_get_cstr(str), ": ");
-		if(p) {
-			if(strncmp(p + 2, "0x", 2) == 0) p += 2;
-			furi_string_left(str, p - furi_string_get_cstr(str) + 2);
-		}
-	}
-	return nrf24_send_packet();
+uint8_t nrf24_resend_read_packet() {
+    if(Log_Total && !cmd_array) {
+        FuriString* str = Log[Log_Total - 1];
+        char* p = strstr(furi_string_get_cstr(str), ": ");
+        if(p) {
+            if(strncmp(p + 2, "0x", 2) == 0) p += 2;
+            furi_string_left(str, p - furi_string_get_cstr(str) + 2);
+        }
+    }
+    return nrf24_send_packet();
 }
 
 // true - new packet
 bool nrf24_read_newpacket() {
-	bool found = false;
-	uint8_t packetsize;
-	uint8_t st = nrf24_rxpacket(nrf24_HANDLE, payload_receive, &packetsize, NRF_DPL ? 0 : payload_size);
-	if(st & RX_DR) {
-		NRF_time = furi_get_tick();
-		if(furi_log_get_level() == FuriLogLevelDebug) {
-			char buf[65]; buf[0] = 0; add_to_str_hex_bytes(buf, payload_receive, packetsize); FURI_LOG_D(TAG, "READ(%X): %s", st, buf);
-		}
-		if(Log_Total) {
-			FuriString *str = Log[Log_Total - 1];
-			uint8_t size = 1;
-			char *p = strchr((char*)furi_string_get_cstr(str), '*');
-			if(p) {
-				p++;
-				if(*p == '=') size = 0; // string
-				else {
-					size = *p - '0';
-					if(size > 4) size = 0;
-				}
-			}
-			int32_t var = get_payload_receive_field(payload_receive, size);
-			//FURI_LOG_D(TAG, "VAR(%d): %ld", size, var);
-			if(size == 0) furi_string_cat_printf(str, "%c", (char)var);
-			else {
-				char hex[9];
-				hex[0] = '\0';
-				add_to_str_hex_variable(hex, (uint8_t*)&var, size);
-				if((cmd_array && cmd_array_type == 1) || furi_string_end_with_str(str, "0x")) furi_string_cat_str(str, hex);
-				else {
-					if((var >= 0 && var <= 9) || cmd_array_type == 2) furi_string_cat_printf(str, "%ld", var);
-					else furi_string_cat_printf(str, "%ld (%s)", var, hex);
-				}
-			}
-			if(cmd_array) {
-				if(--cmd_array_cnt) {
-					furi_string_cat_str(str, ",");
-					if(cmd_array_type == 1) furi_string_cat_str(str, "0x");
-					payload[cmd_array_idx] += size;	// next array element
-					NRF_repeat = -1;
-					send_status = sst_sending;	// Will be send after delay_between_pkt
-				} else send_status = sst_ok;
-			} else {
-				if(size == 0) { // string, until '\0'
-					if(var == 0) send_status = sst_ok;
-				} else send_status = sst_ok;
-			}
-		}
-		//notification_message(APP->notification, &sequence_blink_white_100);
-		found = true;
-	} else if(st & 0x80) { // NRF24 hardware error
-		NRF_ERROR = 1;
-		NRF_INITED = 0;
-	}
-	return found;
+    bool found = false;
+    uint8_t packetsize;
+    uint8_t st =
+        nrf24_rxpacket(nrf24_HANDLE, payload_receive, &packetsize, NRF_DPL ? 0 : payload_size);
+    if(st & RX_DR) {
+        NRF_time = furi_get_tick();
+        if(furi_log_get_level() == FuriLogLevelDebug) {
+            char buf[65];
+            buf[0] = 0;
+            add_to_str_hex_bytes(buf, payload_receive, packetsize);
+            FURI_LOG_D(TAG, "READ(%X): %s", st, buf);
+        }
+        if(Log_Total) {
+            FuriString* str = Log[Log_Total - 1];
+            uint8_t size = 1;
+            char* p = strchr((char*)furi_string_get_cstr(str), '*');
+            if(p) {
+                p++;
+                if(*p == '=')
+                    size = 0; // string
+                else {
+                    size = *p - '0';
+                    if(size > 4) size = 0;
+                }
+            }
+            int32_t var = get_payload_receive_field(payload_receive, size);
+            //FURI_LOG_D(TAG, "VAR(%d): %ld", size, var);
+            if(size == 0)
+                furi_string_cat_printf(str, "%c", (char)var);
+            else {
+                char hex[9];
+                hex[0] = '\0';
+                add_to_str_hex_variable(hex, (uint8_t*)&var, size);
+                if((cmd_array && cmd_array_hex) || furi_string_end_with_str(str, "0x"))
+                    furi_string_cat_str(str, hex);
+                else {
+                    if(var >= 0 && var <= 9)
+                        furi_string_cat_printf(str, "%ld", var);
+                    else
+                        furi_string_cat_printf(str, "%ld (%s)", var, hex);
+                }
+            }
+            if(cmd_array) {
+                if(--cmd_array_cnt) {
+                    furi_string_cat_str(str, ",");
+                    if(cmd_array_hex) furi_string_cat_str(str, "0x");
+                    payload[cmd_array_idx] += size; // next array element
+                    NRF_repeat = -1;
+                    send_status = sst_sending; // Will be send after delay_between_pkt
+                } else
+                    send_status = sst_ok;
+            } else {
+                if(size == 0) { // string, until '\0'
+                    if(var == 0) send_status = sst_ok;
+                } else
+                    send_status = sst_ok;
+            }
+        }
+        //notification_message(APP->notification, &sequence_blink_white_100);
+        found = true;
+    } else if(st & 0x80) { // NRF24 hardware error
+        NRF_ERROR = 1;
+        NRF_INITED = 0;
+    }
+    return found;
 }
 
 // Search in constatnt pull (Const1=n; Const2=n;...)
 // VAR_EMPTY - not found
-int32_t subs_constant(char *p, uint8_t len)
-{
-	char *c = (char*)furi_string_get_cstr(Constants);
-	while((c = strchr(c, *p))) {
-		if(strncmp(c, p, len) != 0) {
-			c++;
-			continue;
-		}
-		if(c == (char*)furi_string_get_cstr(Constants) || *(c-1) == ';' ||  *(c-1) <= ' ') {
-			c += len;
-			if(*c == '=') {
-				c++;
-				return str_to_int(c);
-			}
-		} else c += len;
-	}
-	return VAR_EMPTY;
+int32_t subs_constant(char* p, uint8_t len) {
+    char* c = (char*)furi_string_get_cstr(Constants);
+    while((c = strchr(c, *p))) {
+        if(strncmp(c, p, len) != 0) {
+            c++;
+            continue;
+        }
+        if(c == (char*)furi_string_get_cstr(Constants) || *(c - 1) == ';' || *(c - 1) <= ' ') {
+            c += len;
+            if(*c == '=') {
+                c++;
+                return str_to_int(c);
+            }
+        } else
+            c += len;
+    }
+    return VAR_EMPTY;
 }
 
 // fill payload with default = p
 // if var_n = VAR_EMPTY - skip filling var_*
-bool fill_payload(char *p, uint8_t *idx_i, int32_t var_n)
-{
-	if(idx_i) *idx_i = 255;
-	uint8_t fld = 0; // field #
-	uint8_t idx = 0; // byte index
-	do {
-		int32_t b = 0;
-		char *end = strchr(p, ',');
-		if(*p >= '0' && *p <= '9') { // Number found
-			b = str_to_int(p);
-		} else if(*p == 'i' && *(p + 1) == ':') { // 'i:' array index
-			b = str_to_int(p + 2);
-		 	if(idx_i) *idx_i = idx;
-		} else if(*p == 'n' && *(p + 1) < '0') { // var_n
-			if(var_n != VAR_EMPTY) b = var_n;
-		} else if(*p >= 'A') { // constant found
-			uint8_t len;
-			if(end) len =  end - p;
-			else {
-				len = strlen(p);
-				if(*(p + len - 1) == '#' || *(p + len - 1) == '$') len--;
-			}
-			b = subs_constant(p, len);
-			if(b == VAR_EMPTY) {
-				ERR = 1;
-				memset(ERR_STR, 0, sizeof(ERR_STR));
-				strcpy(ERR_STR, "No ");
-				strncpy(ERR_STR + strlen(ERR_STR), p, sizeof(ERR_STR) - 4);
-				FURI_LOG_D(TAG, "Constant not found: %s", p);
-				return false;
-			}
-		} else if(end == p) {
-			idx += payload_struct[fld];
-		} else if(*p == '#' || *p == '$') { // value forced in Hex/Dec, end string
-			break;
-		} else {
-			ERR = 2;
-			strcpy(ERR_STR, "char: ");
-			uint8_t l = strlen(ERR_STR);
-			ERR_STR[l] = *p;
-			ERR_STR[l+1] = '\0';
-			FURI_LOG_D(TAG, "Wrong format char(%c)", *p);
-			return false;
-		}
-		if(end != p) {
-			payload[idx++] = b;
-			if(payload_struct[fld] > 1) payload[idx++] = b >> 8;
-			if(payload_struct[fld] > 2) payload[idx++] = b >> 16;
-			if(payload_struct[fld] > 3) payload[idx++] = b >> 24;
-		}
-		if(++fld == payload_fields || idx >= sizeof(payload) || end == NULL) break;
-		p = end + 1;
-	} while(1);
-	return true;
+bool fill_payload(char* p, uint8_t* idx_i, int32_t var_n) {
+    if(idx_i) *idx_i = 255;
+    uint8_t fld = 0; // field #
+    uint8_t idx = 0; // byte index
+    do {
+        int32_t b = 0;
+        char* end = strchr(p, ',');
+        if(*p >= '0' && *p <= '9') { // Number found
+            b = str_to_int(p);
+        } else if(*p == 'i' && *(p + 1) == ':') { // 'i:' array index
+            b = str_to_int(p + 2);
+            if(idx_i) *idx_i = idx;
+        } else if(*p == 'n' && *(p + 1) < '0') { // var_n
+            if(var_n != VAR_EMPTY) b = var_n;
+        } else if(*p >= 'A') { // constant found
+            uint8_t len;
+            if(end)
+                len = end - p;
+            else {
+                len = strlen(p);
+                if(*(p + len - 1) == '#') len--;
+            }
+            b = subs_constant(p, len);
+            if(b == VAR_EMPTY) {
+                ERR = 1;
+                memset(ERR_STR, 0, sizeof(ERR_STR));
+                strcpy(ERR_STR, "No ");
+                strncpy(ERR_STR + strlen(ERR_STR), p, sizeof(ERR_STR) - 4);
+                FURI_LOG_D(TAG, "Constant not found: %s", p);
+                return false;
+            }
+        } else if(end == p) {
+            idx += payload_struct[fld];
+        } else if(*p == '#') { // value in Hexadecimal, end string
+            break;
+        } else {
+            ERR = 2;
+            strcpy(ERR_STR, "char: ");
+            uint8_t l = strlen(ERR_STR);
+            ERR_STR[l] = *p;
+            ERR_STR[l + 1] = '\0';
+            FURI_LOG_D(TAG, "Wrong format char(%c)", *p);
+            return false;
+        }
+        if(end != p) {
+            payload[idx++] = b;
+            if(payload_struct[fld] > 1) payload[idx++] = b >> 8;
+            if(payload_struct[fld] > 2) payload[idx++] = b >> 16;
+            if(payload_struct[fld] > 3) payload[idx++] = b >> 24;
+        }
+        if(++fld == payload_fields || idx >= sizeof(payload) || end == NULL) break;
+        p = end + 1;
+    } while(1);
+    return true;
 }
 
 // Cmd: "name=payload"
-bool Run_Read_cmd(FuriString *cmd)
-{
-	char *p = (char*)furi_string_get_cstr(cmd);
-	p = strchr(p, '=');
-	if(p == NULL) return false;
-	if(Log == NULL) Log = malloc(sizeof(Log));
-	else Log = realloc(Log, sizeof(Log) * (Log_Total + 1));
-	if(Log == NULL) {
-		ERR = 3;
-		strcpy(ERR_STR, "Memory low");
-		FURI_LOG_D(TAG, ERR_STR);
-		return false;
-	}
-	FuriString *fs = furi_string_alloc();
-	furi_string_set_strn(fs, (char*)furi_string_get_cstr(cmd), p - (char*)furi_string_get_cstr(cmd));
-	furi_string_cat_str(fs, ": ");
-	uint8_t valtype;
-	char c = *(p + strlen(p) - 1);
-	valtype = c == '#' ? 1 : c == '$' ? 2 : 0;
-	if(valtype == 1) furi_string_cat_str(fs, "0x"); // value in Hex format
-	Log[Log_Total++] = fs;
-	p++;
-	memset(payload, 0, sizeof(payload));
-	if(ReadDefault && !fill_payload((char*)furi_string_get_cstr(ReadDefault), NULL, VAR_EMPTY)) return false;
-	if(!fill_payload(p, &cmd_array_idx, VAR_EMPTY)) return false;
-	memset(payload_receive, 0, sizeof(payload_receive));
-	cmd_array = false;
-	if(*(p - 2) == ']' && cmd_array_idx != 255) { // array
-		p = strchr(furi_string_get_cstr(cmd), '[');
-		if(p) {
-			cmd_array_cnt = str_to_int(p + 1);
-			if(cmd_array_cnt > 1) {
-				cmd_array_type = valtype;
-				cmd_array = true; // array
-			}
-		}
-	}
-	prepare_nrf24();
-	if(NRF_ERROR) return false;
-	what_doing = 2;
-	NRF_repeat = 0;
-	send_status = sst_sending; // Read - sending
-	nrf24_send_packet();
-	return true;
+bool Run_Read_cmd(FuriString* cmd) {
+    char* p = (char*)furi_string_get_cstr(cmd);
+    p = strchr(p, '=');
+    if(p == NULL) return false;
+    if(Log == NULL)
+        Log = malloc(sizeof(Log));
+    else
+        Log = realloc(Log, sizeof(Log) * (Log_Total + 1));
+    if(Log == NULL) {
+        ERR = 3;
+        strcpy(ERR_STR, "Memory low");
+        FURI_LOG_D(TAG, ERR_STR);
+        return false;
+    }
+    FuriString* fs = furi_string_alloc();
+    furi_string_set_strn(
+        fs, (char*)furi_string_get_cstr(cmd), p - (char*)furi_string_get_cstr(cmd));
+    furi_string_cat_str(fs, ": ");
+    bool hexval;
+    if((hexval = *(p + strlen(p) - 1) == '#'))
+        furi_string_cat_str(fs, "0x"); // value in Hex format
+    Log[Log_Total++] = fs;
+    p++;
+    memset(payload, 0, sizeof(payload));
+    if(ReadDefault && !fill_payload((char*)furi_string_get_cstr(ReadDefault), NULL, VAR_EMPTY))
+        return false;
+    if(!fill_payload(p, &cmd_array_idx, VAR_EMPTY)) return false;
+    memset(payload_receive, 0, sizeof(payload_receive));
+    cmd_array = false;
+    if(*(p - 2) == ']' && cmd_array_idx != 255) { // array
+        p = strchr(furi_string_get_cstr(cmd), '[');
+        if(p) {
+            cmd_array_cnt = str_to_int(p + 1);
+            if(cmd_array_cnt > 1) {
+                cmd_array_hex = hexval;
+                cmd_array = true; // array
+            }
+        }
+    }
+    prepare_nrf24();
+    if(NRF_ERROR) return false;
+    what_doing = 2;
+    NRF_repeat = 0;
+    send_status = sst_sending; // Read - sending
+    nrf24_send_packet();
+    return true;
 }
 
 // run commands one by one, true - command running
-bool Run_ReadBatch_cmd(FuriString *cmd)
-{
-	char *p;
-	if(cmd) {
-		p = strchr((char*)furi_string_get_cstr(cmd), ':');
-		if(p == NULL) {
-			ERR = 5;
-			strcpy(ERR_STR, "WRONG FORMAT");
-			return false;
-		}
-		p += 2;
-		ReadBatch_cmd_curr = NULL;
-		free_Log();
-	} else {
-		if(ReadBatch_cmd_curr) p = ReadBatch_cmd_curr; else return false;
-	}
-	char *end = strchr(p, ';');
-	uint8_t len;
-	if(end) len = end - p;
-	else {
-		str_rtrim(p);
-		len = strlen(p);
-	}
-	for(uint16_t i = 0; i < Read_cmd_Total; i++) {
-		FuriString *fs = Read_cmd[i];
-		if(strncmp((char*)furi_string_get_cstr(fs), p, len) == 0) {
-			char c = *((char*)furi_string_get_cstr(fs) + len);
-			if(c != '=' && c != '*' && c != '[') continue;
-			if(end) ReadBatch_cmd_curr = end + 1; else ReadBatch_cmd_curr = (char*)0xFFFFFFFF;
-			if(!Run_Read_cmd(fs)) break;
-			return true;
-		}
-	}
-	if(NRF_ERROR) return false;
-	if(ERR == 0) {
-		ERR = 4;
-		strcpy(ERR_STR, "NOT FOUND");
-		FuriString *fs = furi_string_alloc();
-		furi_string_set_strn(fs, p, len);
-		Log[Log_Total++] = fs;
-		FURI_LOG_D(TAG, "CMD %s: %s", ERR_STR, p);
-	}
-	view_Batch = Log_Total ? Log_Total - 1 : 0;
-	return false;
+bool Run_ReadBatch_cmd(FuriString* cmd) {
+    char* p;
+    if(cmd) {
+        p = strchr((char*)furi_string_get_cstr(cmd), ':');
+        if(p == NULL) {
+            ERR = 5;
+            strcpy(ERR_STR, "WRONG FORMAT");
+            return false;
+        }
+        p += 2;
+        ReadBatch_cmd_curr = NULL;
+        free_Log();
+    } else {
+        if(ReadBatch_cmd_curr)
+            p = ReadBatch_cmd_curr;
+        else
+            return false;
+    }
+    char* end = strchr(p, ';');
+    uint8_t len;
+    if(end)
+        len = end - p;
+    else {
+        str_rtrim(p);
+        len = strlen(p);
+    }
+    for(uint16_t i = 0; i < Read_cmd_Total; i++) {
+        FuriString* fs = Read_cmd[i];
+        if(strncmp((char*)furi_string_get_cstr(fs), p, len) == 0) {
+            char c = *((char*)furi_string_get_cstr(fs) + len);
+            if(c != '=' && c != '*' && c != '[') continue;
+            if(end)
+                ReadBatch_cmd_curr = end + 1;
+            else
+                ReadBatch_cmd_curr = (char*)0xFFFFFFFF;
+            if(!Run_Read_cmd(fs)) break;
+            return true;
+        }
+    }
+    if(NRF_ERROR) return false;
+    if(ERR == 0) {
+        ERR = 4;
+        strcpy(ERR_STR, "NOT FOUND");
+        FuriString* fs = furi_string_alloc();
+        furi_string_set_strn(fs, p, len);
+        Log[Log_Total++] = fs;
+        FURI_LOG_D(TAG, "CMD %s: %s", ERR_STR, p);
+    }
+    view_Batch = Log_Total ? Log_Total - 1 : 0;
+    return false;
 }
 
-void Prepare_Write_cmd(FuriString *cmd)
-{
-	free_Log();
-	if(cmd == NULL) return;
-	char *end, *p = strchr((char*)furi_string_get_cstr(cmd), ':');
-	if(p == NULL) {
-		ERR = 8;
-		strcpy(ERR_STR, "Wrong batch");
-		FURI_LOG_D(TAG, ERR_STR);
-		return;
-	}
-	p += 2;
-	Log = malloc(sizeof(Log));
-	do {
-		end = strchr(p, ';');
-		uint8_t len;
-		if(end) {
-			len = end - p;
-			end++;
-		} else {
-			str_rtrim(p);
-			len = strlen(p);
-		}
-		FuriString *fs = furi_string_alloc();
-		if(Log_Total) Log = realloc(Log, sizeof(Log) * (Log_Total + 1));
-		if(Log == NULL) {
-			ERR = 3;
-			strcpy(ERR_STR, "Memory low");
-			FURI_LOG_D(TAG, ERR_STR);
-			return;
-		}
-		furi_string_set_strn(fs, p, len);
-		Log[Log_Total++] = fs;
-	} while((p = end));
+void Prepare_Write_cmd(FuriString* cmd) {
+    free_Log();
+    if(cmd == NULL) return;
+    char *end, *p = strchr((char*)furi_string_get_cstr(cmd), ':');
+    if(p == NULL) {
+        ERR = 8;
+        strcpy(ERR_STR, "Wrong batch");
+        FURI_LOG_D(TAG, ERR_STR);
+        return;
+    }
+    p += 2;
+    Log = malloc(sizeof(Log));
+    do {
+        end = strchr(p, ';');
+        uint8_t len;
+        if(end) {
+            len = end - p;
+            end++;
+        } else {
+            str_rtrim(p);
+            len = strlen(p);
+        }
+        FuriString* fs = furi_string_alloc();
+        if(Log_Total) Log = realloc(Log, sizeof(Log) * (Log_Total + 1));
+        if(Log == NULL) {
+            ERR = 3;
+            strcpy(ERR_STR, "Memory low");
+            FURI_LOG_D(TAG, ERR_STR);
+            return;
+        }
+        furi_string_set_strn(fs, p, len);
+        Log[Log_Total++] = fs;
+    } while((p = end));
 }
 
 // Write / Set batch
-bool Run_WriteBatch_cmd()
-{
-	if(Log_Total == 0) return false;
-	uint16_t cmd_curr = rw_type == rwt_write_batch ? WriteBatch_cmd_curr : SetBatch_cmd_curr;
-	if(cmd_curr == 0) { // first
-		prepare_nrf24();
-		if(NRF_ERROR) return false;
-		if(rw_type == rwt_write_batch && WriteStart) {
-			if(!fill_payload((char*)furi_string_get_cstr(WriteStart), NULL, VAR_EMPTY)) return false;
-			send_status = sst_sending;
-			if(!nrf24_send_packet()) return false;
-		}
-	}
-	char *p = (char*)furi_string_get_cstr(Log[cmd_curr]);
-	uint16_t len = furi_string_size(Log[cmd_curr]);
-	char *arr = NULL;
-	cmd_array = false;
-	int32_t new = 0;
-	for(uint16_t i = 0; i < len; i++) {
-		if(p[i] == '=') {
-			len = i;
-			char *p2 = p + i + 1;
-			if(*p2 == '{') {
-				arr = ++p2; // array
-				cmd_array = true;
-			}
-			new = str_to_int(p2);
-			break;
-		}
-	}
-	FURI_LOG_D(TAG, "%cBatch: =%d, (%d)%s", rw_type == rwt_write_batch ? 'W' : 'S', (int)new, len, p);
-	char *w, *delim_col, i, size;
-	FuriString* str = furi_string_alloc();
-	stream_rewind(file_stream);
-	while(stream_read_line(file_stream, str)) {
-		w = (char*)furi_string_get_cstr(str);
-		if(strncmp(w, SettingsFld_Write, sizeof(SettingsFld_Write)-1) == 0) w +=  sizeof(SettingsFld_Write);
-		else if(strncmp(w, SettingsFld_Set, sizeof(SettingsFld_Set)-1) == 0) w +=  sizeof(SettingsFld_Set);
-		else continue;
-		delim_col = strchr(w, '=');
-		if(delim_col == NULL) continue;
-		size = 1;
-		if(*(delim_col - 2) == '*') {
-			if(len != delim_col - w - 2) continue;
-			size = *(delim_col - 1) - '0';
-			new = new & (size == 1 ? 0xFF : size == 2 ? 0xFFFF : size == 3 ? 0xFFFFFF : 0xFFFFFFFF);
-		} else if(len != delim_col - w) continue;
-		if(strncmp(p, w, len) != 0) continue;
-		delim_col++;
-		str_rtrim(delim_col);
-		cmd_array_cnt = 255;
-		do {
-			memset(payload, 0, sizeof(payload));
-			if(WriteDefault && !fill_payload((char*)furi_string_get_cstr(WriteDefault), NULL, new)) {
-				view_Batch = cmd_curr;
-				return false;
-			}
-			if(!fill_payload(delim_col, &cmd_array_idx, VAR_EMPTY)) {
-				view_Batch = cmd_curr;
-				return false;
-			}
-			if(cmd_array && cmd_array_idx != 255) {
- 				if(cmd_array_cnt != 255) payload[cmd_array_idx] = cmd_array_cnt;
-			} else cmd_array = false;
-			send_status = sst_sending;
-			NRF_repeat = 0;
-			i = 0;
-			do {
-				if(nrf24_send_packet()) break;
-				furi_delay_ms(delay_between_pkt);
-			} while(i++ < NRF_resend);
-			if(i < NRF_resend || i == 0) { // ok
-				if(cmd_array) { // array
-					for(; arr != NULL;) {
-						if(*arr == ',') break;
-						if(*arr == '}' || *arr < ' ') arr = NULL; else arr++;
-					}
-					if(arr == NULL) {
-						send_status = sst_ok; 
-						break;
-					}
-					arr++;
-					new = str_to_int(arr);
-					cmd_array_cnt = payload[cmd_array_idx] + size;
-					//furi_delay_ms(delay_between_pkt); // do it fast
-					continue; // send next array element
-				} else send_status = sst_ok; 
-			}
-			break;
-		} while(1);
-		if(send_status != sst_ok) { 
-			send_status = sst_error;
-			view_Batch = cmd_curr;
-			return false;
-		}
-		return true;
-	}
-	ERR = 7;
-	strcpy(ERR_STR, "NOT FOUND!");
-	send_status = sst_error;
-	view_Batch = cmd_curr;
-	return false;
+bool Run_WriteBatch_cmd() {
+    if(Log_Total == 0) return false;
+    uint16_t cmd_curr = rw_type == rwt_write_batch ? WriteBatch_cmd_curr : SetBatch_cmd_curr;
+    if(cmd_curr == 0) { // first
+        prepare_nrf24();
+        if(NRF_ERROR) return false;
+        if(rw_type == rwt_write_batch && WriteStart) {
+            if(!fill_payload((char*)furi_string_get_cstr(WriteStart), NULL, VAR_EMPTY))
+                return false;
+            send_status = sst_sending;
+            if(!nrf24_send_packet()) return false;
+        }
+    }
+    char* p = (char*)furi_string_get_cstr(Log[cmd_curr]);
+    uint16_t len = furi_string_size(Log[cmd_curr]);
+    char* arr = NULL;
+    cmd_array = false;
+    int32_t new = 0;
+    for(uint16_t i = 0; i < len; i++) {
+        if(p[i] == '=') {
+            len = i;
+            char* p2 = p + i + 1;
+            if(*p2 == '{') {
+                arr = ++p2; // array
+                cmd_array = true;
+            }
+            new = str_to_int(p2);
+            break;
+        }
+    }
+    FURI_LOG_D(
+        TAG, "%cBatch: =%d, (%d)%s", rw_type == rwt_write_batch ? 'W' : 'S', (int)new, len, p);
+    char *w, *delim_col, i, size;
+    FuriString* str = furi_string_alloc();
+    stream_rewind(file_stream);
+    while(stream_read_line(file_stream, str)) {
+        w = (char*)furi_string_get_cstr(str);
+        if(strncmp(w, SettingsFld_Write, sizeof(SettingsFld_Write) - 1) == 0)
+            w += sizeof(SettingsFld_Write);
+        else if(strncmp(w, SettingsFld_Set, sizeof(SettingsFld_Set) - 1) == 0)
+            w += sizeof(SettingsFld_Set);
+        else
+            continue;
+        delim_col = strchr(w, '=');
+        if(delim_col == NULL) continue;
+        size = 1;
+        if(*(delim_col - 2) == '*') {
+            if(len != delim_col - w - 2) continue;
+            size = *(delim_col - 1) - '0';
+            new = new&(size == 1 ? 0xFF : size == 2 ? 0xFFFF : size == 3 ? 0xFFFFFF : 0xFFFFFFFF);
+        } else if(len != delim_col - w)
+            continue;
+        if(strncmp(p, w, len) != 0) continue;
+        delim_col++;
+        str_rtrim(delim_col);
+        cmd_array_cnt = 255;
+        do {
+            memset(payload, 0, sizeof(payload));
+            if(WriteDefault &&
+               !fill_payload((char*)furi_string_get_cstr(WriteDefault), NULL, new)) {
+                view_Batch = cmd_curr;
+                return false;
+            }
+            if(!fill_payload(delim_col, &cmd_array_idx, VAR_EMPTY)) {
+                view_Batch = cmd_curr;
+                return false;
+            }
+            if(cmd_array && cmd_array_idx != 255) {
+                if(cmd_array_cnt != 255) payload[cmd_array_idx] = cmd_array_cnt;
+            } else
+                cmd_array = false;
+            send_status = sst_sending;
+            NRF_repeat = 0;
+            i = 0;
+            do {
+                if(nrf24_send_packet()) break;
+                furi_delay_ms(delay_between_pkt);
+            } while(i++ < NRF_resend);
+            if(i < NRF_resend || i == 0) { // ok
+                if(cmd_array) { // array
+                    for(; arr != NULL;) {
+                        if(*arr == ',') break;
+                        if(*arr == '}' || *arr < ' ')
+                            arr = NULL;
+                        else
+                            arr++;
+                    }
+                    if(arr == NULL) {
+                        send_status = sst_ok;
+                        break;
+                    }
+                    arr++;
+                    new = str_to_int(arr);
+                    cmd_array_cnt = payload[cmd_array_idx] + size;
+                    //furi_delay_ms(delay_between_pkt); // do it fast
+                    continue; // send next array element
+                } else
+                    send_status = sst_ok;
+            }
+            break;
+        } while(1);
+        if(send_status != sst_ok) {
+            send_status = sst_error;
+            view_Batch = cmd_curr;
+            return false;
+        }
+        return true;
+    }
+    ERR = 7;
+    strcpy(ERR_STR, "NOT FOUND!");
+    send_status = sst_error;
+    view_Batch = cmd_curr;
+    return false;
 }
 
 // Return 0 - success, otherwise an error
 static uint8_t load_settings_file() {
-	uint8_t err = 0;
-	FURI_LOG_D(TAG, "Loading settings file");
-	FuriString* str = furi_string_alloc();
-	free_store();
-	Info[0] = '\0';
-	NRF_INITED = false;
-	while(stream_read_line(file_stream, str)) {
-		char *p = (char*)furi_string_get_cstr(str);
-		if(*p <= '!' || *p == ';') continue;
-		//char* delim_eq = strchr(p, '=');
-		char *delim_col = strchr(p, ':');
-		if(delim_col == NULL) { // Constant found - no ':'
-			if(Constants == NULL) {
-				Constants = furi_string_alloc_set(str);
-			} else furi_string_cat(Constants, str);
-		} else {
-			str_rtrim(p);
-			if(strncmp(p, SettingsFld_Rate, sizeof(SettingsFld_Rate)-1) == 0) {
-				NRF_rate = str_to_int(p + sizeof(SettingsFld_Rate));
-			} else if(strncmp(p, SettingsFld_Info, sizeof(SettingsFld_Info)-1) == 0) {
-				strncpy(Info, p + sizeof(SettingsFld_Info), sizeof(Info)-1);
-			} else if(strncmp(p, SettingsFld_Ch, sizeof(SettingsFld_Ch)-1) == 0) {
-				NRF_channel = str_to_int(p + sizeof(SettingsFld_Ch));
-			} else if(strncmp(p, SettingsFld_Address, sizeof(SettingsFld_Address)-1) == 0) {
-				p += sizeof(SettingsFld_Address);
-				addr_len = ConvertHexToArray(p, addr, 5);
-			} else if(strncmp(p, SettingsFld_CRC, sizeof(SettingsFld_CRC)-1) == 0) {
-				NRF_CRC = str_to_int(p + sizeof(SettingsFld_CRC));
-			} else if(strncmp(p, SettingsFld_DPL, sizeof(SettingsFld_DPL)-1) == 0) {
-				NRF_DPL = str_to_int(p + sizeof(SettingsFld_DPL));
-			} else if(strncmp(p, SettingsFld_RETR, sizeof(SettingsFld_RETR)-1) == 0) {
-				NRF_RETR = str_to_int(p + sizeof(SettingsFld_RETR));
-			} else if(strncmp(p, SettingsFld_Resend, sizeof(SettingsFld_Resend)-1) == 0) {
-				NRF_resend = str_to_int(p + sizeof(SettingsFld_Resend));
-			} else if(strncmp(p, SettingsFld_Delay, sizeof(SettingsFld_Delay)-1) == 0) {
-				delay_between_pkt = str_to_int(p + sizeof(SettingsFld_Delay));
-			} else if(strncmp(p, SettingsFld_ReadCmdRepeatPeriod, sizeof(SettingsFld_ReadCmdRepeatPeriod)-1) == 0) {
-				ReadCmdRepeatPeriod = str_to_int(p + sizeof(SettingsFld_ReadCmdRepeatPeriod));
-			} else if(strncmp(p, SettingsFld_Payload, sizeof(SettingsFld_Payload)-1) == 0) {
-				p += sizeof(SettingsFld_Payload);
-				payload_fields = 0;
-				payload_size = 0;
-				do {
-					uint8_t b = str_to_int(p);
-					if(b < 1 || b > 4) {
-						FURI_LOG_D(TAG, "Wrong payload format (%d)", b);
-						err = 3;
-						break;
-					}
-					payload_struct[payload_fields++] = b;
-					payload_size += b;
-					if(payload_fields == sizeof(payload_struct) - 1) break;
-					if((p = strchr(p, ',')) == NULL) break;
-					p++;
-				} while(1);
-				FURI_LOG_D(TAG, "Payload fields %d: %d,%d,%d", payload_fields, payload_struct[0], payload_struct[1], payload_struct[2]);
-			} else if(strncmp(p, SettingsFld_ReadDefault, sizeof(SettingsFld_ReadDefault)-1) == 0) {
-				ReadDefault = furi_string_alloc_set_str(p + sizeof(SettingsFld_ReadDefault));
-			} else if(strncmp(p, SettingsFld_WriteStart, sizeof(SettingsFld_WriteStart)-1) == 0) {
-				WriteStart = furi_string_alloc_set_str(p + sizeof(SettingsFld_WriteStart));
-			} else if(strncmp(p, SettingsFld_WriteDefault, sizeof(SettingsFld_WriteDefault)-1) == 0) {
-				WriteDefault = furi_string_alloc_set_str(p + sizeof(SettingsFld_WriteDefault));
-			} else if(strncmp(p, SettingsFld_Read, sizeof(SettingsFld_Read)-1) == 0) {
-				p += sizeof(SettingsFld_Read);
-				if(Read_cmd == NULL) Read_cmd = malloc(sizeof(Read_cmd));
-				else {
-					Read_cmd = realloc(Read_cmd, sizeof(Read_cmd) * (Read_cmd_Total + 1));
-				}
-				if(Read_cmd == NULL) {
-					FURI_LOG_D(TAG, "Memory low, err 4");
-					err = 4;
-					break;
-				}
-				Read_cmd[Read_cmd_Total++] = furi_string_alloc_set_str(p);
-			} else if(strncmp(p, SettingsFld_ReadBatch, sizeof(SettingsFld_ReadBatch)-1) == 0) {
-				p += sizeof(SettingsFld_ReadBatch);
-				if(ReadBatch_cmd == NULL) ReadBatch_cmd = malloc(sizeof(ReadBatch_cmd));
-				else {
-					ReadBatch_cmd = realloc(ReadBatch_cmd, sizeof(ReadBatch_cmd) * (ReadBatch_cmd_Total + 1));
-				}
-				if(ReadBatch_cmd == NULL) {
-					FURI_LOG_D(TAG, "Memory low, err 5");
-					err = 5;
-					break;
-				}
-				ReadBatch_cmd[ReadBatch_cmd_Total++] = furi_string_alloc_set_str(p);
-			} else if(strncmp(p, SettingsFld_WriteBatch, sizeof(SettingsFld_WriteBatch)-1) == 0) {
-				p += sizeof(SettingsFld_WriteBatch);
-				if(WriteBatch_cmd == NULL) WriteBatch_cmd = malloc(sizeof(WriteBatch_cmd));
-				else {
-					WriteBatch_cmd = realloc(WriteBatch_cmd, sizeof(WriteBatch_cmd) * (WriteBatch_cmd_Total + 1));
-				}
-				if(WriteBatch_cmd == NULL) {
-					FURI_LOG_D(TAG, "Memory low, err 6");
-					err = 6;
-					break;
-				}
-				WriteBatch_cmd[WriteBatch_cmd_Total++] = furi_string_alloc_set_str(p);
-			} else if(strncmp(p, SettingsFld_SetBatch, sizeof(SettingsFld_SetBatch)-1) == 0) {
-				p += sizeof(SettingsFld_SetBatch);
-				if(SetBatch_cmd == NULL) SetBatch_cmd = malloc(sizeof(SetBatch_cmd));
-				else {
-					SetBatch_cmd = realloc(SetBatch_cmd, sizeof(SetBatch_cmd) * (SetBatch_cmd_Total + 1));
-				}
-				if(SetBatch_cmd == NULL) {
-					FURI_LOG_D(TAG, "Memory low, err 7");
-					err = 7;
-					break;
-				}
-				SetBatch_cmd[SetBatch_cmd_Total++] = furi_string_alloc_set_str(p);
-			} else if(strncmp(p, SettingsFld_Listen, sizeof(SettingsFld_Listen)-1) == 0) {
-				p += sizeof(SettingsFld_Listen);
-				char *p2 = strchr(p, '=');
-				if(p2) {
-					listen_addr_len = ConvertHexToArray(p, listen_addr, (p2 - p) / 2);
-					p2++;
-					uint8_t len = strlen(p2);
-					ListenFields = malloc(len + 1);
-					if(ListenFields) memcpy(ListenFields, p2, len);
-				}
-			}
-		}
-	}
-	furi_string_free(str);
-	return err;
+    uint8_t err = 0;
+    FURI_LOG_D(TAG, "Loading settings file");
+    FuriString* str = furi_string_alloc();
+    free_store();
+    Info[0] = '\0';
+    NRF_INITED = false;
+    while(stream_read_line(file_stream, str)) {
+        char* p = (char*)furi_string_get_cstr(str);
+        if(*p <= '!' || *p == ';') continue;
+        //char* delim_eq = strchr(p, '=');
+        char* delim_col = strchr(p, ':');
+        if(delim_col == NULL) { // Constant found - no ':'
+            if(Constants == NULL) {
+                Constants = furi_string_alloc_set(str);
+            } else
+                furi_string_cat(Constants, str);
+        } else {
+            str_rtrim(p);
+            if(strncmp(p, SettingsFld_Rate, sizeof(SettingsFld_Rate) - 1) == 0) {
+                NRF_rate = str_to_int(p + sizeof(SettingsFld_Rate));
+            } else if(strncmp(p, SettingsFld_Info, sizeof(SettingsFld_Info) - 1) == 0) {
+                strncpy(Info, p + sizeof(SettingsFld_Info), sizeof(Info) - 1);
+            } else if(strncmp(p, SettingsFld_Ch, sizeof(SettingsFld_Ch) - 1) == 0) {
+                NRF_channel = str_to_int(p + sizeof(SettingsFld_Ch));
+            } else if(strncmp(p, SettingsFld_Address, sizeof(SettingsFld_Address) - 1) == 0) {
+                p += sizeof(SettingsFld_Address);
+                addr_len = ConvertHexToArray(p, addr, 5);
+            } else if(strncmp(p, SettingsFld_CRC, sizeof(SettingsFld_CRC) - 1) == 0) {
+                NRF_CRC = str_to_int(p + sizeof(SettingsFld_CRC));
+            } else if(strncmp(p, SettingsFld_DPL, sizeof(SettingsFld_DPL) - 1) == 0) {
+                NRF_DPL = str_to_int(p + sizeof(SettingsFld_DPL));
+            } else if(strncmp(p, SettingsFld_RETR, sizeof(SettingsFld_RETR) - 1) == 0) {
+                NRF_RETR = str_to_int(p + sizeof(SettingsFld_RETR));
+            } else if(strncmp(p, SettingsFld_Resend, sizeof(SettingsFld_Resend) - 1) == 0) {
+                NRF_resend = str_to_int(p + sizeof(SettingsFld_Resend));
+            } else if(strncmp(p, SettingsFld_Delay, sizeof(SettingsFld_Delay) - 1) == 0) {
+                delay_between_pkt = str_to_int(p + sizeof(SettingsFld_Delay));
+            } else if(
+                strncmp(
+                    p,
+                    SettingsFld_ReadCmdRepeatPeriod,
+                    sizeof(SettingsFld_ReadCmdRepeatPeriod) - 1) == 0) {
+                ReadCmdRepeatPeriod = str_to_int(p + sizeof(SettingsFld_ReadCmdRepeatPeriod));
+            } else if(strncmp(p, SettingsFld_Payload, sizeof(SettingsFld_Payload) - 1) == 0) {
+                p += sizeof(SettingsFld_Payload);
+                payload_fields = 0;
+                payload_size = 0;
+                do {
+                    uint8_t b = str_to_int(p);
+                    if(b < 1 || b > 4) {
+                        FURI_LOG_D(TAG, "Wrong payload format (%d)", b);
+                        err = 3;
+                        break;
+                    }
+                    payload_struct[payload_fields++] = b;
+                    payload_size += b;
+                    if(payload_fields == sizeof(payload_struct) - 1) break;
+                    if((p = strchr(p, ',')) == NULL) break;
+                    p++;
+                } while(1);
+                FURI_LOG_D(
+                    TAG,
+                    "Payload fields %d: %d,%d,%d",
+                    payload_fields,
+                    payload_struct[0],
+                    payload_struct[1],
+                    payload_struct[2]);
+            } else if(strncmp(p, SettingsFld_ReadDefault, sizeof(SettingsFld_ReadDefault) - 1) == 0) {
+                ReadDefault = furi_string_alloc_set_str(p + sizeof(SettingsFld_ReadDefault));
+            } else if(strncmp(p, SettingsFld_WriteStart, sizeof(SettingsFld_WriteStart) - 1) == 0) {
+                WriteStart = furi_string_alloc_set_str(p + sizeof(SettingsFld_WriteStart));
+            } else if(strncmp(p, SettingsFld_WriteDefault, sizeof(SettingsFld_WriteDefault) - 1) == 0) {
+                WriteDefault = furi_string_alloc_set_str(p + sizeof(SettingsFld_WriteDefault));
+            } else if(strncmp(p, SettingsFld_Read, sizeof(SettingsFld_Read) - 1) == 0) {
+                p += sizeof(SettingsFld_Read);
+                if(Read_cmd == NULL)
+                    Read_cmd = malloc(sizeof(Read_cmd));
+                else {
+                    Read_cmd = realloc(Read_cmd, sizeof(Read_cmd) * (Read_cmd_Total + 1));
+                }
+                if(Read_cmd == NULL) {
+                    FURI_LOG_D(TAG, "Memory low, err 4");
+                    err = 4;
+                    break;
+                }
+                Read_cmd[Read_cmd_Total++] = furi_string_alloc_set_str(p);
+            } else if(strncmp(p, SettingsFld_ReadBatch, sizeof(SettingsFld_ReadBatch) - 1) == 0) {
+                p += sizeof(SettingsFld_ReadBatch);
+                if(ReadBatch_cmd == NULL)
+                    ReadBatch_cmd = malloc(sizeof(ReadBatch_cmd));
+                else {
+                    ReadBatch_cmd =
+                        realloc(ReadBatch_cmd, sizeof(ReadBatch_cmd) * (ReadBatch_cmd_Total + 1));
+                }
+                if(ReadBatch_cmd == NULL) {
+                    FURI_LOG_D(TAG, "Memory low, err 5");
+                    err = 5;
+                    break;
+                }
+                ReadBatch_cmd[ReadBatch_cmd_Total++] = furi_string_alloc_set_str(p);
+            } else if(strncmp(p, SettingsFld_WriteBatch, sizeof(SettingsFld_WriteBatch) - 1) == 0) {
+                p += sizeof(SettingsFld_WriteBatch);
+                if(WriteBatch_cmd == NULL)
+                    WriteBatch_cmd = malloc(sizeof(WriteBatch_cmd));
+                else {
+                    WriteBatch_cmd = realloc(
+                        WriteBatch_cmd, sizeof(WriteBatch_cmd) * (WriteBatch_cmd_Total + 1));
+                }
+                if(WriteBatch_cmd == NULL) {
+                    FURI_LOG_D(TAG, "Memory low, err 6");
+                    err = 6;
+                    break;
+                }
+                WriteBatch_cmd[WriteBatch_cmd_Total++] = furi_string_alloc_set_str(p);
+            } else if(strncmp(p, SettingsFld_SetBatch, sizeof(SettingsFld_SetBatch) - 1) == 0) {
+                p += sizeof(SettingsFld_SetBatch);
+                if(SetBatch_cmd == NULL)
+                    SetBatch_cmd = malloc(sizeof(SetBatch_cmd));
+                else {
+                    SetBatch_cmd =
+                        realloc(SetBatch_cmd, sizeof(SetBatch_cmd) * (SetBatch_cmd_Total + 1));
+                }
+                if(SetBatch_cmd == NULL) {
+                    FURI_LOG_D(TAG, "Memory low, err 7");
+                    err = 7;
+                    break;
+                }
+                SetBatch_cmd[SetBatch_cmd_Total++] = furi_string_alloc_set_str(p);
+            } else if(strncmp(p, SettingsFld_Listen, sizeof(SettingsFld_Listen) - 1) == 0) {
+                p += sizeof(SettingsFld_Listen);
+                char* p2 = strchr(p, '=');
+                if(p2) {
+                    listen_addr_len = ConvertHexToArray(p, listen_addr, (p2 - p) / 2);
+                    p2++;
+                    uint8_t len = strlen(p2);
+                    ListenFields = malloc(len + 1);
+                    if(ListenFields) memcpy(ListenFields, p2, len);
+                }
+            }
+        }
+    }
+    furi_string_free(str);
+    return err;
 }
 
-static void save_batch(void)
-{
-	FURI_LOG_D(TAG, "Save Batch");
-	char *p, *p2;
-	stream_seek(file_stream, 0, StreamOffsetFromEnd); 
+static void save_batch(void) {
+    FURI_LOG_D(TAG, "Save Batch");
+    char *p, *p2;
+    stream_seek(file_stream, 0, StreamOffsetFromEnd);
     FuriHalRtcDateTime dt;
     furi_hal_rtc_get_datetime(&dt);
-	stream_write_format(file_stream, "\n%s ", SettingsFld_WriteBatch);
-	p = (char*)furi_string_get_cstr(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
-	p2 = strchr(p, ':');
-	if(p2 == NULL) p2 = p + strlen(p);
-	stream_write(file_stream, (uint8_t*)p, p2 - p);
-	stream_write_format(file_stream, " %02d.%02d.%02d %02d.%02d: ", dt.day, dt.month, dt.year % 100, dt.hour, dt.minute);
-	for(uint16_t i = 0; i < Log_Total; i++) {
-		p = (char*) furi_string_get_cstr(Log[i]);
-		p2 = strchr(p, ':');
-		if(p2 && *(p2-1) != '*') {	// skip string
-			if(*(p2-1) == ']') { // array
-				char *p3 = strchr(p, '[');
-				if(p3) {
-					stream_write(file_stream, (uint8_t*)p, p3 - p - (*(p3-2) == '*' ? 2 : 0));
-					stream_write_cstring(file_stream, "={");
-					p = (p2 += 2);
-					do {
-						while(is_digit(p2, true) || *p2 == 'x') p2++;
-						stream_write(file_stream, (uint8_t*)p, p2 - p);
-						char c = *p2;
-						if(c == '\0') break;
-						if(c != ',') {
-							p2 = strchr(p2, ',');
-							if(p2 == NULL) break;
-						}
-						stream_write_char(file_stream, ',');
-						p = ++p2;
-					} while(1);
-					stream_write_char(file_stream, '}');
-				}
-			} else {
-				stream_write(file_stream, (uint8_t*)p, p2 - p - (*(p2-2) == '*' ? 2 : 0));
-				stream_write_char(file_stream, '=');
-				p2 += 2;
-				p = strchr(p2, ' ');
-				if(p == NULL) p = p2 + strlen(p2);
-				stream_write(file_stream, (uint8_t*)p2, p - p2);
-			}
-			if(i < Log_Total - 1) stream_write_char(file_stream, ';');
-		}
-	}
+    stream_write_format(file_stream, "\n%s ", SettingsFld_WriteBatch);
+    p = (char*)furi_string_get_cstr(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
+    p2 = strchr(p, ':');
+    if(p2 == NULL) p2 = p + strlen(p);
+    stream_write(file_stream, (uint8_t*)p, p2 - p);
+    stream_write_format(
+        file_stream,
+        " %02d.%02d.%02d %02d.%02d: ",
+        dt.day,
+        dt.month,
+        dt.year % 100,
+        dt.hour,
+        dt.minute);
+    for(uint16_t i = 0; i < Log_Total; i++) {
+        p = (char*)furi_string_get_cstr(Log[i]);
+        p2 = strchr(p, ':');
+        if(p2 && *(p2 - 1) != '*') { // skip string
+            if(*(p2 - 1) == ']') { // array
+                char* p3 = strchr(p, '[');
+                if(p3) {
+                    stream_write(file_stream, (uint8_t*)p, p3 - p - (*(p3 - 2) == '*' ? 2 : 0));
+                    stream_write_cstring(file_stream, "={");
+                    p = (p2 += 2);
+                    do {
+                        while(is_digit(p2, true) || *p2 == 'x') p2++;
+                        stream_write(file_stream, (uint8_t*)p, p2 - p);
+                        char c = *p2;
+                        if(c == '\0') break;
+                        if(c != ',') {
+                            p2 = strchr(p2, ',');
+                            if(p2 == NULL) break;
+                        }
+                        stream_write_char(file_stream, ',');
+                        p = ++p2;
+                    } while(1);
+                    stream_write_char(file_stream, '}');
+                }
+            } else {
+                stream_write(file_stream, (uint8_t*)p, p2 - p - (*(p2 - 2) == '*' ? 2 : 0));
+                stream_write_char(file_stream, '=');
+                p2 += 2;
+                p = strchr(p2, ' ');
+                if(p == NULL) p = p2 + strlen(p2);
+                stream_write(file_stream, (uint8_t*)p2, p - p2);
+            }
+            if(i < Log_Total - 1) stream_write_char(file_stream, ';');
+        }
+    }
 }
 
 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);
+    furi_assert(event_queue);
+    PluginEvent event = {.type = EventTypeKey, .input = *input_event};
+    furi_message_queue_put(event_queue, &event, FuriWaitForever);
 }
 
-void display_remove_asterisk(char *fsp, uint8_t vx)
-{
-	char *p2 = strchr(fsp, '*');
-	if(p2) { // remove '*' or '*n'
-		int pos = p2 - fsp;
-		if((pos -= vx) < 0) pos = 0;
-		char c = *(p2 + 1);
-		if(*(screen_buf + pos))
-			memmove(screen_buf + pos, screen_buf + pos + (c == ':' || c == '=' ? 1 : 2), FONT_5x7_SCREEN_WIDTH + 1 + 2 - pos);
-	}
+void display_remove_asterisk(char* fsp, uint8_t vx) {
+    char* p2 = strchr(fsp, '*');
+    if(p2) { // remove '*' or '*n'
+        int pos = p2 - fsp;
+        if((pos -= vx) < 0) pos = 0;
+        char c = *(p2 + 1);
+        if(*(screen_buf + pos))
+            memmove(
+                screen_buf + pos,
+                screen_buf + pos + (c == ':' || c == '=' ? 1 : 2),
+                FONT_5x7_SCREEN_WIDTH + 1 + 2 - pos);
+    }
 }
 
-void render_display_list(Canvas* const canvas, FuriString ***fsa, char delim, uint16_t view_pos, uint16_t max_i)
-{
-	uint16_t page = view_pos & ~7;
-	char *p, *end;
-	uint16_t y, len;
-	for(uint8_t i = 0; i < 8 && page + i < max_i; i++) {
-		y = 14 + i * 7;
-		p = (char*) furi_string_get_cstr((*fsa)[page + i]);
-		end = strchr(p, delim);
-		if(end) {
-			len = MIN(end - p, view_x);
-			len = MIN(end - p - len, FONT_5x7_SCREEN_WIDTH);
-			strncpy(screen_buf, p + view_x, len);
-			screen_buf[len] = '\0';
-			display_remove_asterisk(p, MIN(end - p, view_x));
-			canvas_draw_str(canvas, 5, y, screen_buf);
-		}
-		if((view_pos & 7) == i) {
-			canvas_draw_str(canvas, 0, y, ">");
-			canvas_draw_str(canvas, -1, y, ">");
-		}
-	}
+void render_display_list(
+    Canvas* const canvas,
+    FuriString*** fsa,
+    char delim,
+    uint16_t view_pos,
+    uint16_t max_i) {
+    uint16_t page = view_pos & ~7;
+    char *p, *end;
+    uint16_t y, len;
+    for(uint8_t i = 0; i < 8 && page + i < max_i; i++) {
+        y = 14 + i * 7;
+        p = (char*)furi_string_get_cstr((*fsa)[page + i]);
+        end = strchr(p, delim);
+        if(end) {
+            len = MIN(end - p, view_x);
+            len = MIN(end - p - len, FONT_5x7_SCREEN_WIDTH);
+            strncpy(screen_buf, p + view_x, len);
+            screen_buf[len] = '\0';
+            display_remove_asterisk(p, MIN(end - p, view_x));
+            canvas_draw_str(canvas, 5, y, screen_buf);
+        }
+        if((view_pos & 7) == i) {
+            canvas_draw_str(canvas, 0, y, ">");
+            canvas_draw_str(canvas, -1, y, ">");
+        }
+    }
 }
 
-void display_edit_ttf_font(Canvas* const canvas, uint8_t start_x, uint8_t start_y)
-{
-	screen_buf[0] = *Edit_pos; screen_buf[1] = '\0';
-	int n = canvas_string_width(canvas, screen_buf);
-	int len = Edit_pos - Edit_start;
-	memcpy(screen_buf, Edit_start, len);
-	screen_buf[len] = '\0';
-	int x = start_x + canvas_string_width(canvas, screen_buf);
-	int len2 = strlen(Edit_pos);
-	memcpy(screen_buf + len, Edit_pos, len2);
-	screen_buf[len + len2] = '\0';
-	canvas_draw_str(canvas, start_x, start_y, screen_buf);
-	start_y += 1;
-	canvas_draw_line(canvas, x + (len ? 1 : 0), start_y, x + n + (*Edit_pos == '1' && len ? 1 : 0), start_y);
+void display_edit_ttf_font(Canvas* const canvas, uint8_t start_x, uint8_t start_y) {
+    screen_buf[0] = *Edit_pos;
+    screen_buf[1] = '\0';
+    int n = canvas_string_width(canvas, screen_buf);
+    int len = Edit_pos - Edit_start;
+    memcpy(screen_buf, Edit_start, len);
+    screen_buf[len] = '\0';
+    int x = start_x + canvas_string_width(canvas, screen_buf);
+    int len2 = strlen(Edit_pos);
+    memcpy(screen_buf + len, Edit_pos, len2);
+    screen_buf[len + len2] = '\0';
+    canvas_draw_str(canvas, start_x, start_y, screen_buf);
+    start_y += 1;
+    canvas_draw_line(
+        canvas, x + (len ? 1 : 0), start_y, x + n + (*Edit_pos == '1' && len ? 1 : 0), start_y);
 }
 
-void display_add_status(void)
-{
-	if(NRF_ERROR) strcat(screen_buf, "nRF24 ERROR!");
-	else if(ERR) snprintf(screen_buf, sizeof(screen_buf), "ERROR %s", ERR_STR); 
-	else if(send_status == sst_error) strcat(screen_buf, "NO ACK!");
-	else if(send_status == sst_timeout) strcat(screen_buf, "TIMEOUT!");
-	else if(send_status == sst_none) ;
-	else if(send_status == sst_sending) strcat(screen_buf, "sending");
-	else if(send_status == sst_receiving) strcat(screen_buf, "receiving");
-	else if(send_status == sst_ok && 
-		(rw_type == rwt_read_cmd
-		|| (rw_type == rwt_read_batch && (uint32_t)ReadBatch_cmd_curr == 0xFFFFFFFF) 
-		|| (rw_type == rwt_set_batch && SetBatch_cmd_curr == Log_Total) 
-		|| (rw_type == rwt_write_batch && WriteBatch_cmd_curr == Log_Total)))
-			strcat(screen_buf, "OK");
-	else strcat(screen_buf, "working");
+void display_add_status(void) {
+    if(NRF_ERROR)
+        strcat(screen_buf, "nRF24 ERROR!");
+    else if(ERR)
+        snprintf(screen_buf, sizeof(screen_buf), "ERROR %s", ERR_STR);
+    else if(send_status == sst_error)
+        strcat(screen_buf, "NO ACK!");
+    else if(send_status == sst_timeout)
+        strcat(screen_buf, "TIMEOUT!");
+    else if(send_status == sst_none)
+        ;
+    else if(send_status == sst_sending)
+        strcat(screen_buf, "sending");
+    else if(send_status == sst_receiving)
+        strcat(screen_buf, "receiving");
+    else if(
+        send_status == sst_ok &&
+        (rw_type == rwt_read_cmd ||
+         (rw_type == rwt_read_batch && (uint32_t)ReadBatch_cmd_curr == 0xFFFFFFFF) ||
+         (rw_type == rwt_set_batch && SetBatch_cmd_curr == Log_Total) ||
+         (rw_type == rwt_write_batch && WriteBatch_cmd_curr == Log_Total)))
+        strcat(screen_buf, "OK");
+    else
+        strcat(screen_buf, "working");
 }
 
 static void render_callback(Canvas* const canvas, void* ctx) {
-	if(ctx == NULL) return;
-	const PluginState* plugin_state = ctx;
-	if(furi_mutex_acquire(plugin_state->mutex, 5) != FuriStatusOk) return;
+    if(ctx == NULL) return;
+    const PluginState* plugin_state = ctx;
+    if(furi_mutex_acquire(plugin_state->mutex, 5) != FuriStatusOk) return;
 
-	//canvas_draw_frame(canvas, 0, 0, 128, 64); // border around the edge of the screen
-	if(what_doing == 0) {
-		canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
-		snprintf(screen_buf, sizeof(screen_buf), "%s: %s", addr_len ? "File" : "Open", file_name);
-		canvas_draw_str(canvas, 8, 10, screen_buf);
-		if(addr_len) {
-			if(Edit) {
-				if(setup_cursor == 1) display_edit_ttf_font(canvas, 45, 20);
-				else if(setup_cursor == 2) display_edit_ttf_font(canvas, 55, 30);
-			}
-			if(!Edit || setup_cursor != 1) {
-				screen_buf[0] = '\0';
-				add_to_str_hex_bytes(screen_buf, addr, addr_len);
-				canvas_draw_str(canvas, 45, 20, screen_buf);
-			}
-			if(!Edit || setup_cursor != 2) {
-				snprintf(screen_buf, sizeof(screen_buf), "%d", NRF_channel);
-				canvas_draw_str(canvas, 55, 30, screen_buf);
-			}
-			canvas_draw_str(canvas, 8, 20, "Address:");
-			snprintf(screen_buf, sizeof(screen_buf), "Rate: %d, Ch:", NRF_rate);
-			canvas_draw_str(canvas, 8, 30, screen_buf);
-			snprintf(screen_buf, sizeof(screen_buf), "RB: %d, R: %d, WB: %d", ReadBatch_cmd_Total, Read_cmd_Total, WriteBatch_cmd_Total);
-			canvas_draw_str(canvas, 8, 40, screen_buf);
-			canvas_draw_str(canvas, 0, 64, Info);
-			canvas_draw_str(canvas, 0, 10 + setup_cursor * 10, ">");
-		} else {
-			snprintf(screen_buf, sizeof(screen_buf), "Ver. %s,  vad7", VERSION);
-			canvas_draw_str(canvas, 10, 60, screen_buf);
-			canvas_draw_str(canvas, 0, 10, ">");
-		}
-	} else if(what_doing == 1){
-		if(rw_type == rwt_listen) {
-			canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
-			canvas_draw_str(canvas, 0, 10, "Listen mode");
-			canvas_draw_str(canvas, 0, 25, "Address:");
-			if(Edit) display_edit_ttf_font(canvas, 40, 25); 
-			else if(listen_addr_len) {
-				screen_buf[0] = '\0';
-				add_to_str_hex_bytes(screen_buf, listen_addr, listen_addr_len);
-				canvas_draw_str(canvas, 40, 25, screen_buf);
-			}
-			snprintf(screen_buf, sizeof(screen_buf), "I: %d +(%d) mA", Current - CurrentStart, CurrentStart);
-			canvas_draw_str(canvas, 0, 60, screen_buf);
-		} else {
-			canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
-			if(rw_type == rwt_read_batch) {
-				canvas_draw_str(canvas, 0, 7, "Read Batch:");
-				render_display_list(canvas, &ReadBatch_cmd, ':', view_cmd[rw_type], ReadBatch_cmd_Total);
-			} else if(rw_type == rwt_read_cmd) {
-				canvas_draw_str(canvas, 0, 7, "Read Command:");
-				render_display_list(canvas, &Read_cmd, '=', view_cmd[rw_type], Read_cmd_Total);
-			} else if(rw_type == rwt_write_batch) {
-				if(!ask_fill_screen_buf()) strcpy(screen_buf, "Write Batch:");
-				canvas_draw_str(canvas, 0, 7, screen_buf);
-				render_display_list(canvas, &WriteBatch_cmd, ':', view_cmd[rw_type], WriteBatch_cmd_Total);
-			} else if(rw_type == rwt_set_batch) {
-				strcpy(screen_buf, "Set: ");
-				display_add_status();
-				canvas_draw_str(canvas, 0, 7, screen_buf);
-				render_display_list(canvas, &SetBatch_cmd, ':', view_cmd[rw_type], SetBatch_cmd_Total);
-			}
-		}
-	} else { // what_doing == 2
-		if(rw_type == rwt_listen) {
-			canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
-			strcpy(screen_buf, "Listen: ");
-			if(NRF_ERROR) strcat(screen_buf, "nRF24 ERROR!");
-			else if(ListenNew) {
-				snprintf(screen_buf + strlen(screen_buf), 16, "%02d:%02d:%02d", ListenLastTime.hour, ListenLastTime.minute, ListenLastTime.second);
-				if(ListenPrev) snprintf(screen_buf + strlen(screen_buf), 16, " (%lu)", ListenLast - ListenPrev);
-			} else strcat(screen_buf, "receiving");
-			snprintf(screen_buf + strlen(screen_buf), 16, " %dmA", Current - CurrentStart);
-			canvas_draw_str(canvas, 0, 10, screen_buf);
-			if(ListenFields) {
-				char *p2, *p = ListenFields;
-				uint8_t valtype, len, *pld = payload_receive;
-				for(uint8_t i = 0; i < 5 && *p; i++) {
-					p2 = strchr(p, ',');
-					if(p2 == NULL) p2 = p + strlen(p);
-					valtype = *(p2 - 1) == '#' ? 1 : *(p2 - 1) == '$' ? 2 : 0;
-					memcpy(screen_buf, p, len = p2 - p);
-					strcpy(screen_buf + len, ": ");
-					if(ListenNew) {
-						len = payload_struct[i];
-						int32_t n = get_payload_receive_field(pld, len);
-						if(valtype == 1) {
-							strcat(screen_buf, "0x");
-							add_to_str_hex_variable(screen_buf, pld, len);
-						} else {
-							snprintf(screen_buf + strlen(screen_buf), 20, "%ld", n);
-							if(n > 9 && valtype == 0) {
-								strcat(screen_buf, " (");
-								add_to_str_hex_variable(screen_buf, pld, len);
-								strcat(screen_buf, ")");
-							}
-						}
-						pld += len;
-					}
-					canvas_draw_str(canvas, 0, 20 + i * 10, screen_buf);
-					if(*p2 == '\0') break;
-					p = p2 + 1;
-				}
-			}
-		} else if(rw_type == rwt_read_cmd) {	// Read command
-			canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
-			if(!ask_fill_screen_buf()) {
-				strcpy(screen_buf, "Read ");
-				strcat(screen_buf, ReadRepeat ? "rep: " : "cmd: ");
-			}
-			display_add_status();
-			canvas_draw_str(canvas, 0, 10, screen_buf);
-			if(Log_Total) {
-				char *p = (char*)furi_string_get_cstr(Log[Log_Total - 1]);
-				uint8_t vx = MIN(view_x, strlen(p));
-				strncpy(screen_buf, p + vx, 30);
-				display_remove_asterisk(p, vx);
-				canvas_draw_str(canvas, 0, 15 + 10, screen_buf);
-			}
-		} else if(rw_type == rwt_set_batch) {
-				canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
-				strcpy(screen_buf, "Set: ");
-				display_add_status();
-				canvas_draw_str(canvas, 0, 7, screen_buf);
-				render_display_list(canvas, &SetBatch_cmd, ':', view_cmd[rw_type], SetBatch_cmd_Total);
-		} else { // rwt_read_batch, rwt_write_batch
-			canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
-			if(!ask_fill_screen_buf()) {
-				strcpy(screen_buf, rw_type == rwt_read_batch ? "Read Batch: " : "Write: ");
-				if(rw_type == rwt_read_batch || send_status != sst_none) {
-					display_add_status();
-				} else if(rw_type == rwt_write_batch) {
-					char *p = (char*)furi_string_get_cstr(WriteBatch_cmd[view_cmd[rwt_write_batch]]);
-					char *end = strchr(p, ':');
-					if(end) {
-						uint8_t len = end - p;
-						uint8_t lenb = strlen(screen_buf);
-						end = screen_buf + lenb;
-						lenb = FONT_5x7_SCREEN_WIDTH - lenb;
-						if(len > lenb) {
-							if(view_x < len) {
-								strncpy(end, p + view_x, len = MIN(lenb, len - view_x));
-								end[len] = '\0';
-							}
-						} else {
-							strncpy(end, p, len);
-							end[len] = '\0';
-						}
-					}
-				}
-			}
-			canvas_draw_str(canvas, 0, 7, screen_buf);
-			if(Log_Total) {
-				char *p;
-				uint16_t y, page = view_Batch & ~7;
-				uint8_t vx;
-				for(uint8_t i = 0; i < 8 && page + i < Log_Total; i++) {
-					p = (char*)furi_string_get_cstr(Log[page + i]);
-					y = 14 + i * 7;
-					vx = MIN(view_x, strlen(p));
-					if((view_Batch & 7) == i) {
-						canvas_draw_str(canvas, 0, y, ">");
-						canvas_draw_str(canvas, -1, y, ">");
-						if(Edit) {
-							int n = Edit_pos - p - vx - (FONT_5x7_SCREEN_WIDTH - 4);
-							if(n > 0) vx += n;	// fix out of screen
-							int x = 6 + (Edit_pos - p - vx) * 5;
-							canvas_draw_line(canvas, x - 1, y, x - 1, y - 1);
-							canvas_draw_line(canvas, x - 1, y, n = x + 1 * 5, y);
-							canvas_draw_line(canvas, n, y, n, y - 1);
-						}
-					}
-					strncpy(screen_buf, p + vx, FONT_5x7_SCREEN_WIDTH + 2);
-					screen_buf[FONT_5x7_SCREEN_WIDTH + 2] = '\0';
-					display_remove_asterisk(p, vx);
-					canvas_draw_str(canvas, 6, y, screen_buf);
-				}
-			}
-		}
-	}
-	furi_mutex_release(plugin_state->mutex);
-} 
+    //canvas_draw_frame(canvas, 0, 0, 128, 64); // border around the edge of the screen
+    if(what_doing == 0) {
+        canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
+        snprintf(screen_buf, sizeof(screen_buf), "%s: %s", addr_len ? "File" : "Open", file_name);
+        canvas_draw_str(canvas, 8, 10, screen_buf);
+        if(addr_len) {
+            if(Edit) {
+                if(setup_cursor == 1)
+                    display_edit_ttf_font(canvas, 45, 20);
+                else if(setup_cursor == 2)
+                    display_edit_ttf_font(canvas, 55, 30);
+            }
+            if(!Edit || setup_cursor != 1) {
+                screen_buf[0] = '\0';
+                add_to_str_hex_bytes(screen_buf, addr, addr_len);
+                canvas_draw_str(canvas, 45, 20, screen_buf);
+            }
+            if(!Edit || setup_cursor != 2) {
+                snprintf(screen_buf, sizeof(screen_buf), "%d", NRF_channel);
+                canvas_draw_str(canvas, 55, 30, screen_buf);
+            }
+            canvas_draw_str(canvas, 8, 20, "Address:");
+            snprintf(screen_buf, sizeof(screen_buf), "Rate: %d, Ch:", NRF_rate);
+            canvas_draw_str(canvas, 8, 30, screen_buf);
+            snprintf(
+                screen_buf,
+                sizeof(screen_buf),
+                "RB: %d, R: %d, WB: %d",
+                ReadBatch_cmd_Total,
+                Read_cmd_Total,
+                WriteBatch_cmd_Total);
+            canvas_draw_str(canvas, 8, 40, screen_buf);
+            canvas_draw_str(canvas, 0, 64, Info);
+            canvas_draw_str(canvas, 0, 10 + setup_cursor * 10, ">");
+        } else {
+            snprintf(screen_buf, sizeof(screen_buf), "Ver. %s,  vad7", VERSION);
+            canvas_draw_str(canvas, 10, 60, screen_buf);
+            canvas_draw_str(canvas, 0, 10, ">");
+        }
+    } else if(what_doing == 1) {
+        if(rw_type == rwt_listen) {
+            canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
+            canvas_draw_str(canvas, 0, 10, "Listen mode");
+            canvas_draw_str(canvas, 0, 25, "Address:");
+            if(Edit)
+                display_edit_ttf_font(canvas, 40, 25);
+            else if(listen_addr_len) {
+                screen_buf[0] = '\0';
+                add_to_str_hex_bytes(screen_buf, listen_addr, listen_addr_len);
+                canvas_draw_str(canvas, 40, 25, screen_buf);
+            }
+            snprintf(
+                screen_buf,
+                sizeof(screen_buf),
+                "I: %d +(%d) mA",
+                Current - CurrentStart,
+                CurrentStart);
+            canvas_draw_str(canvas, 0, 60, screen_buf);
+        } else {
+            canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
+            if(rw_type == rwt_read_batch) {
+                canvas_draw_str(canvas, 0, 7, "Read Batch:");
+                render_display_list(
+                    canvas, &ReadBatch_cmd, ':', view_cmd[rw_type], ReadBatch_cmd_Total);
+            } else if(rw_type == rwt_read_cmd) {
+                canvas_draw_str(canvas, 0, 7, "Read Command:");
+                render_display_list(canvas, &Read_cmd, '=', view_cmd[rw_type], Read_cmd_Total);
+            } else if(rw_type == rwt_write_batch) {
+                if(!ask_fill_screen_buf()) strcpy(screen_buf, "Write Batch:");
+                canvas_draw_str(canvas, 0, 7, screen_buf);
+                render_display_list(
+                    canvas, &WriteBatch_cmd, ':', view_cmd[rw_type], WriteBatch_cmd_Total);
+            } else if(rw_type == rwt_set_batch) {
+                strcpy(screen_buf, "Set: ");
+                display_add_status();
+                canvas_draw_str(canvas, 0, 7, screen_buf);
+                render_display_list(
+                    canvas, &SetBatch_cmd, ':', view_cmd[rw_type], SetBatch_cmd_Total);
+            }
+        }
+    } else { // what_doing == 2
+        if(rw_type == rwt_listen) {
+            canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
+            strcpy(screen_buf, "Listen: ");
+            if(NRF_ERROR)
+                strcat(screen_buf, "nRF24 ERROR!");
+            else if(ListenNew) {
+                snprintf(
+                    screen_buf + strlen(screen_buf),
+                    16,
+                    "%02d:%02d:%02d",
+                    ListenLastTime.hour,
+                    ListenLastTime.minute,
+                    ListenLastTime.second);
+                if(ListenPrev)
+                    snprintf(
+                        screen_buf + strlen(screen_buf), 16, " (%lu)", ListenLast - ListenPrev);
+            } else
+                strcat(screen_buf, "receiving");
+            snprintf(screen_buf + strlen(screen_buf), 16, " %dmA", Current - CurrentStart);
+            canvas_draw_str(canvas, 0, 10, screen_buf);
+            if(ListenFields) {
+                char *p2, *p = ListenFields;
+                uint8_t hex, len, *pld = payload_receive;
+                for(uint8_t i = 0; i < 5 && *p; i++) {
+                    hex = false;
+                    p2 = strchr(p, ',');
+                    if(p2 == NULL) p2 = p + strlen(p);
+                    if(*(p2 - 1) == '#') hex = true;
+                    memcpy(screen_buf, p, len = p2 - p);
+                    strcpy(screen_buf + len, ": ");
+                    if(ListenNew) {
+                        len = payload_struct[i];
+                        int32_t n = get_payload_receive_field(pld, len);
+                        if(hex) {
+                            strcat(screen_buf, "0x");
+                            add_to_str_hex_variable(screen_buf, pld, len);
+                        } else {
+                            snprintf(screen_buf + strlen(screen_buf), 20, "%ld", n);
+                            if(n > 9) {
+                                strcat(screen_buf, " (");
+                                add_to_str_hex_variable(screen_buf, pld, len);
+                                strcat(screen_buf, ")");
+                            }
+                        }
+                        pld += len;
+                    }
+                    canvas_draw_str(canvas, 0, 20 + i * 10, screen_buf);
+                    if(*p2 == '\0') break;
+                    p = p2 + 1;
+                }
+            }
+        } else if(rw_type == rwt_read_cmd) { // Read command
+            canvas_set_font(canvas, FontSecondary); // 8x10 font, 6 lines
+            if(!ask_fill_screen_buf()) {
+                strcpy(screen_buf, "Read ");
+                strcat(screen_buf, ReadRepeat ? "rep: " : "cmd: ");
+            }
+            display_add_status();
+            canvas_draw_str(canvas, 0, 10, screen_buf);
+            if(Log_Total) {
+                char* p = (char*)furi_string_get_cstr(Log[Log_Total - 1]);
+                uint8_t vx = MIN(view_x, strlen(p));
+                strncpy(screen_buf, p + vx, 30);
+                display_remove_asterisk(p, vx);
+                canvas_draw_str(canvas, 0, 15 + 10, screen_buf);
+            }
+        } else if(rw_type == rwt_set_batch) {
+            canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
+            strcpy(screen_buf, "Set: ");
+            display_add_status();
+            canvas_draw_str(canvas, 0, 7, screen_buf);
+            render_display_list(canvas, &SetBatch_cmd, ':', view_cmd[rw_type], SetBatch_cmd_Total);
+        } else { // rwt_read_batch, rwt_write_batch
+            canvas_set_font(canvas, FontBatteryPercent); // 5x7 font, 9 lines, 25 cols
+            if(!ask_fill_screen_buf()) {
+                strcpy(screen_buf, rw_type == rwt_read_batch ? "Read Batch: " : "Write: ");
+                if(rw_type == rwt_read_batch || send_status != sst_none) {
+                    display_add_status();
+                } else if(rw_type == rwt_write_batch) {
+                    char* p =
+                        (char*)furi_string_get_cstr(WriteBatch_cmd[view_cmd[rwt_write_batch]]);
+                    char* end = strchr(p, ':');
+                    if(end) {
+                        uint8_t len = end - p;
+                        uint8_t lenb = strlen(screen_buf);
+                        end = screen_buf + lenb;
+                        lenb = FONT_5x7_SCREEN_WIDTH - lenb;
+                        if(len > lenb) {
+                            if(view_x < len) {
+                                strncpy(end, p + view_x, len = MIN(lenb, len - view_x));
+                                end[len] = '\0';
+                            }
+                        } else {
+                            strncpy(end, p, len);
+                            end[len] = '\0';
+                        }
+                    }
+                }
+            }
+            canvas_draw_str(canvas, 0, 7, screen_buf);
+            if(Log_Total) {
+                char* p;
+                uint16_t y, page = view_Batch & ~7;
+                uint8_t vx;
+                for(uint8_t i = 0; i < 8 && page + i < Log_Total; i++) {
+                    p = (char*)furi_string_get_cstr(Log[page + i]);
+                    y = 14 + i * 7;
+                    vx = MIN(view_x, strlen(p));
+                    if((view_Batch & 7) == i) {
+                        canvas_draw_str(canvas, 0, y, ">");
+                        canvas_draw_str(canvas, -1, y, ">");
+                        if(Edit) {
+                            int n = Edit_pos - p - vx - (FONT_5x7_SCREEN_WIDTH - 4);
+                            if(n > 0) vx += n; // fix out of screen
+                            int x = 6 + (Edit_pos - p - vx) * 5;
+                            canvas_draw_line(canvas, x - 1, y, x - 1, y - 1);
+                            canvas_draw_line(canvas, x - 1, y, n = x + 1 * 5, y);
+                            canvas_draw_line(canvas, n, y, n, y - 1);
+                        }
+                    }
+                    strncpy(screen_buf, p + vx, FONT_5x7_SCREEN_WIDTH + 2);
+                    screen_buf[FONT_5x7_SCREEN_WIDTH + 2] = '\0';
+                    display_remove_asterisk(p, vx);
+                    canvas_draw_str(canvas, 6, y, screen_buf);
+                }
+            }
+        }
+    }
+    furi_mutex_release(plugin_state->mutex);
+}
 
-void work_timer_callback(void* ctx)
-{
-	if(ctx == NULL) return;
-	if(rw_type == rwt_listen && (pwr_read_timer += WORK_PERIOD) >= POWER_READ_PERIOD) {
-		pwr_read_timer = 0;
-		update_power();
-	}
-	if(what_doing == 2) {
-		const PluginState* plugin_state = ctx;
-		if(furi_mutex_acquire(plugin_state->mutex, 0) != FuriStatusOk) return;
-		if(rw_type == rwt_write_batch || rw_type == rwt_set_batch) {
-			uint16_t *cmd_curr = rw_type == rwt_set_batch ? &SetBatch_cmd_curr : &WriteBatch_cmd_curr;
-			if(ERR == 0 && furi_get_tick() - NRF_time >= delay_between_pkt) {
-				if(send_status == sst_ok) {
-					if(ERR == 0 && *cmd_curr < Log_Total) {
-						if(++(*cmd_curr) < Log_Total) Run_WriteBatch_cmd(); 
-						else { // finished ok
-							if(rw_type == rwt_set_batch) what_doing = 1;
-							Edited = false;
-						}
-					}
-				} else if(send_status == sst_sending) {
-					if(NRF_repeat++ < NRF_resend) nrf24_send_packet(); 
-					else {
-						view_Batch = *cmd_curr;
-						send_status = sst_error; // error NO_ACK
-					}
-				}
-			}
-			if((ERR || send_status == sst_error) && rw_type == rwt_set_batch) {
-				what_doing = 1;
-			}
-		// ReadBatch or ReadCmd
-		} else if(send_status == sst_sending) { // sending
-			if(furi_get_tick() - NRF_time > delay_between_pkt) {
-				if(NRF_repeat++ < NRF_resend) {
-					nrf24_resend_read_packet();
-				} else send_status = sst_error; // error NO_ACK
-			}
-		} else if(send_status == sst_receiving) { // receiving
-			for(uint8_t i = 0; i < 3; i++) {
-				if(nrf24_read_newpacket()) {
-					if(rw_type == rwt_listen) {
-						ListenPrev = ListenLast;
-						furi_hal_rtc_get_datetime(&ListenLastTime);
-						ListenLast = furi_hal_rtc_datetime_to_timestamp(&ListenLastTime);
-						ListenNew = true;
-					} else if(send_status != sst_receiving) break;
-				} else {
-					if(rw_type != rwt_listen && furi_get_tick() - NRF_time > NRF_READ_TIMEOUT) {
-						if(NRF_repeat++ < NRF_resend) {
-							send_status = sst_sending;
-							nrf24_resend_read_packet();
-						} else {
-							FURI_LOG_D(TAG, "TIMEOUT: %lu", furi_get_tick() - NRF_time);
-							send_status = sst_timeout;
-						}
-					}
-					break;
-				}
-			}
-		} else if(send_status == sst_ok) {
-			if(rw_type == rwt_read_batch) {
-				if((uint32_t)ReadBatch_cmd_curr != 0xFFFFFFFF && ERR == 0 && furi_get_tick() - NRF_time >= delay_between_pkt) {
-					Run_ReadBatch_cmd(NULL);
-				}
-			}
-		}
-		furi_mutex_release(plugin_state->mutex);
-	}
+void work_timer_callback(void* ctx) {
+    if(ctx == NULL) return;
+    if(rw_type == rwt_listen && (pwr_read_timer += WORK_PERIOD) >= POWER_READ_PERIOD) {
+        pwr_read_timer = 0;
+        update_power();
+    }
+    if(what_doing == 2) {
+        const PluginState* plugin_state = ctx;
+        if(furi_mutex_acquire(plugin_state->mutex, 0) != FuriStatusOk) return;
+        if(rw_type == rwt_write_batch || rw_type == rwt_set_batch) {
+            uint16_t* cmd_curr = rw_type == rwt_set_batch ? &SetBatch_cmd_curr :
+                                                            &WriteBatch_cmd_curr;
+            if(ERR == 0 && furi_get_tick() - NRF_time >= delay_between_pkt) {
+                if(send_status == sst_ok) {
+                    if(ERR == 0 && *cmd_curr < Log_Total) {
+                        if(++(*cmd_curr) < Log_Total)
+                            Run_WriteBatch_cmd();
+                        else { // finished ok
+                            if(rw_type == rwt_set_batch) what_doing = 1;
+                            Edited = false;
+                        }
+                    }
+                } else if(send_status == sst_sending) {
+                    if(NRF_repeat++ < NRF_resend)
+                        nrf24_send_packet();
+                    else {
+                        view_Batch = *cmd_curr;
+                        send_status = sst_error; // error NO_ACK
+                    }
+                }
+            }
+            if((ERR || send_status == sst_error) && rw_type == rwt_set_batch) {
+                what_doing = 1;
+            }
+            // ReadBatch or ReadCmd
+        } else if(send_status == sst_sending) { // sending
+            if(furi_get_tick() - NRF_time > delay_between_pkt) {
+                if(NRF_repeat++ < NRF_resend) {
+                    nrf24_resend_read_packet();
+                } else
+                    send_status = sst_error; // error NO_ACK
+            }
+        } else if(send_status == sst_receiving) { // receiving
+            for(uint8_t i = 0; i < 3; i++) {
+                if(nrf24_read_newpacket()) {
+                    if(rw_type == rwt_listen) {
+                        ListenPrev = ListenLast;
+                        furi_hal_rtc_get_datetime(&ListenLastTime);
+                        ListenLast = furi_hal_rtc_datetime_to_timestamp(&ListenLastTime);
+                        ListenNew = true;
+                    } else if(send_status != sst_receiving)
+                        break;
+                } else {
+                    if(rw_type != rwt_listen && furi_get_tick() - NRF_time > NRF_READ_TIMEOUT) {
+                        if(NRF_repeat++ < NRF_resend) {
+                            send_status = sst_sending;
+                            nrf24_resend_read_packet();
+                        } else {
+                            FURI_LOG_D(TAG, "TIMEOUT: %lu", furi_get_tick() - NRF_time);
+                            send_status = sst_timeout;
+                        }
+                    }
+                    break;
+                }
+            }
+        } else if(send_status == sst_ok) {
+            if(rw_type == rwt_read_batch) {
+                if((uint32_t)ReadBatch_cmd_curr != 0xFFFFFFFF && ERR == 0 &&
+                   furi_get_tick() - NRF_time >= delay_between_pkt) {
+                    Run_ReadBatch_cmd(NULL);
+                }
+            }
+        }
+        furi_mutex_release(plugin_state->mutex);
+    }
 }
 
-void next_rw_type(int8_t add)
-{
-	do {
-		rw_type += add;
-		if(rw_type >= rwt_max) {
-			if(add > 0) rw_type = 0; else rw_type = rwt_max - 1;
-		}
-		if(rw_type == rwt_set_batch && SetBatch_cmd_Total) break;
-		if(rw_type == rwt_read_batch && ReadBatch_cmd_Total) break;
-		if(rw_type == rwt_read_cmd && Read_cmd_Total) break;
-		if(rw_type == rwt_write_batch && WriteBatch_cmd_Total) break;
-	} while(rw_type != rwt_listen);
-	send_status = sst_none;
+void next_rw_type(int8_t add) {
+    do {
+        rw_type += add;
+        if(rw_type >= rwt_max) {
+            if(add > 0)
+                rw_type = 0;
+            else
+                rw_type = rwt_max - 1;
+        }
+        if(rw_type == rwt_set_batch && SetBatch_cmd_Total) break;
+        if(rw_type == rwt_read_batch && ReadBatch_cmd_Total) break;
+        if(rw_type == rwt_read_cmd && Read_cmd_Total) break;
+        if(rw_type == rwt_write_batch && WriteBatch_cmd_Total) break;
+    } while(rw_type != rwt_listen);
+    send_status = sst_none;
 }
 
-void next_view_cmd(int8_t add)
-{
-	if(rw_type == rwt_listen) return;
-	uint16_t max = (rw_type == rwt_read_batch ? ReadBatch_cmd_Total : 
-					rw_type == rwt_read_cmd ? Read_cmd_Total : 
-					rw_type == rwt_set_batch ? SetBatch_cmd_Total : WriteBatch_cmd_Total);
-	if((view_cmd[rw_type] += add) >= max) view_cmd[rw_type] = add > 0 ? 0 : max - 1;
+void next_view_cmd(int8_t add) {
+    if(rw_type == rwt_listen) return;
+    uint16_t max =
+        (rw_type == rwt_read_batch ? ReadBatch_cmd_Total :
+         rw_type == rwt_read_cmd   ? Read_cmd_Total :
+         rw_type == rwt_set_batch  ? SetBatch_cmd_Total :
+                                     WriteBatch_cmd_Total);
+    if((view_cmd[rw_type] += add) >= max) view_cmd[rw_type] = add > 0 ? 0 : max - 1;
 }
 
 int32_t nrf24batch_app(void* p) {
-	UNUSED(p);
-	APP = malloc(sizeof(nRF24Batch));
-	FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
-	APP->plugin_state = malloc(sizeof(PluginState));
-	APP->plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
-	if(!APP->plugin_state->mutex) {
-		furi_message_queue_free(event_queue);
-		FURI_LOG_E(TAG, "cannot create mutex");
-		free(APP->plugin_state);
-		return 255;
-	}
-	// Set system callbacks
-	ViewPort* view_port = view_port_alloc();
-	view_port_draw_callback_set(view_port, render_callback, APP->plugin_state);
-	view_port_input_callback_set(view_port, input_callback, event_queue);
+    UNUSED(p);
+    APP = malloc(sizeof(nRF24Batch));
+    FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
+    APP->plugin_state = malloc(sizeof(PluginState));
+    APP->plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    if(!APP->plugin_state->mutex) {
+        furi_message_queue_free(event_queue);
+        FURI_LOG_E(TAG, "cannot create mutex");
+        free(APP->plugin_state);
+        return 255;
+    }
+    // Set system callbacks
+    ViewPort* view_port = view_port_alloc();
+    view_port_draw_callback_set(view_port, render_callback, APP->plugin_state);
+    view_port_input_callback_set(view_port, input_callback, event_queue);
+
+    // Open GUI and register view_port
+    APP->gui = furi_record_open(RECORD_GUI);
+    gui_add_view_port(APP->gui, view_port, GuiLayerFullscreen);
+    APP->notification = furi_record_open(RECORD_NOTIFICATION);
+    APP->storage = furi_record_open(RECORD_STORAGE);
+    storage_common_migrate(APP->storage, EXT_PATH("nrf24batch"), SCAN_APP_PATH_FOLDER);
+    storage_common_mkdir(APP->storage, SCAN_APP_PATH_FOLDER);
+    file_stream = file_stream_alloc(APP->storage);
+    FuriTimer* work_timer =
+        furi_timer_alloc(work_timer_callback, FuriTimerTypePeriodic, APP->plugin_state);
+    furi_timer_start(work_timer, WORK_PERIOD);
+    nrf24_init();
+    check_en_power_5V();
 
-	// Open GUI and register view_port
-	APP->gui = furi_record_open(RECORD_GUI);
-	gui_add_view_port(APP->gui, view_port, GuiLayerFullscreen);
-	APP->notification = furi_record_open(RECORD_NOTIFICATION);
-	APP->storage = furi_record_open(RECORD_STORAGE);
-	storage_common_mkdir(APP->storage, SCAN_APP_PATH_FOLDER);
-	file_stream = file_stream_alloc(APP->storage);
-	FuriTimer *work_timer = furi_timer_alloc(work_timer_callback, FuriTimerTypePeriodic, APP->plugin_state);
-	furi_timer_start(work_timer, WORK_PERIOD);
-	nrf24_init();
-	check_en_power_5V();
+    PluginEvent event;
+    for(bool processing = true; processing;) {
+        FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
+        furi_mutex_acquire(APP->plugin_state->mutex, FuriWaitForever);
 
-	PluginEvent event;
-	for(bool processing = true; processing;) {
-		FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
-		furi_mutex_acquire(APP->plugin_state->mutex, FuriWaitForever);
-		
-		static FuriLogLevel FuriLogLevel = FuriLogLevelDefault;
-		if(furi_log_get_level() != FuriLogLevel) {
-		 	FuriLogLevel = furi_log_get_level();
-		 	if(FuriLogLevel == FuriLogLevelDebug) furi_hal_uart_set_br(FuriHalUartIdUSART1, 1843200);
-		}
-		if(what_doing == 2 && rw_type == rwt_read_cmd && ReadRepeat && furi_get_tick() - NRF_time > (uint32_t)(ReadCmdRepeatPeriod * 1000)) {
-			ERR = 0;
-			free_Log();
-			Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
-			notification_message(APP->notification, &sequence_blink_blue_100);
-		}
+        // static FuriLogLevel FuriLogLevel = FuriLogLevelDefault;
+        // if(furi_log_get_level() != FuriLogLevel) {
+        //     FuriLogLevel = furi_log_get_level();
+        //     if(FuriLogLevel == FuriLogLevelDebug)
+        //         furi_hal_uart_set_br(FuriHalUartIdUSART1, 1843200);
+        // }
+        if(what_doing == 2 && rw_type == rwt_read_cmd && ReadRepeat &&
+           furi_get_tick() - NRF_time > (uint32_t)(ReadCmdRepeatPeriod * 1000)) {
+            ERR = 0;
+            free_Log();
+            Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
+            notification_message(APP->notification, &sequence_blink_blue_100);
+        }
 
-		if(event_status == FuriStatusOk) {
-			// press events
-			if(event.type == EventTypeKey) {
-				switch(event.input.key) {
-				case InputKeyUp:
-					if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
-						if(!ask_question) {
-							if(Edit) {
-								char c = *Edit_pos;
-								if(Edit_hex) {
-									if(c == '9') *Edit_pos = 'A';
-									else if(c < 'F' || c < '9') *Edit_pos = c + 1;
-								} else {
-									if(c == '-') *Edit_pos = '0';
-									else if(c < '9') *Edit_pos = c + 1;
-									else {
-										c = *(Edit_pos - 1);
-										if(Edit_pos > Edit_start && c < '9' && c >= '0') {
-											*Edit_pos = '0';
-											(*(Edit_pos - 1)) = c + 1;
-										}
-									}
-								}	
-							} else if(what_doing == 0) {
-								if(addr_len) {
-									if(setup_cursor > 0) setup_cursor--; else setup_cursor = 2;
-								}
-							} else if(what_doing == 1) next_view_cmd(-1);
-							else if(what_doing == 2) if(view_Batch) view_Batch--;
-						}
-					}
-					break;
-				case InputKeyDown:
-					if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
-						if(!ask_question) {
-							if(Edit) {
-								if(*Edit_pos != '-') {
-									if(Edit_hex && *Edit_pos == 'A') (*Edit_pos) = '9';
-									else if(*Edit_pos > '0') (*Edit_pos)--;
-									else if(!Edit_hex) {
-										if(Edit_pos > Edit_start) {
-											if(*(Edit_pos - 1) > '0' && *(Edit_pos - 1) <= '9') {
-												*Edit_pos = '9';
-												(*(Edit_pos - 1))--;
-											}
-										} else Edit_insert_digit('-'); // negative
-									}
-								}
-							} else if(what_doing == 0) {
-								if(addr_len) {
-									if(setup_cursor < 2) setup_cursor++; else setup_cursor = 0;
-								}
-							} else if(what_doing == 1) next_view_cmd(+1);
-							else if(what_doing == 2) if(view_Batch < Log_Total - 1) view_Batch++;
-						}
-					}
-					break;
-				case InputKeyLeft:
-					if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
-						if(ask_question) {
-							if(event.input.type == InputTypeShort) ask_question_answer ^= 1;
-						} else if(Edit) {
-							if(Edit_pos > Edit_start) {
-								if(is_digit(Edit_pos - 1, Edit_hex)) Edit_pos--;
-								else if(*(Edit_pos - 1) == 'x' && *(Edit_pos - 3) == ',') Edit_pos -= 4;
-								else if(*(Edit_pos - 1) == ',') Edit_pos -= 2;
-							}
-						} else if(what_doing == 0) {
-							if(addr_len) {
-								rw_type = rwt_listen;
-								what_doing = 1;
-							}
-						} else if(what_doing == 1) {
-							if(event.input.type == InputTypeShort) next_rw_type(-1); else if(view_x) view_x--;
-						} else if(what_doing == 2) if(view_x) view_x--;
-					} else if(event.input.type == InputTypeLong) {
-						if(!ask_question && view_x == 0 && what_doing == 2 && (rw_type == rwt_write_batch || rw_type == rwt_read_batch) 
-								&& Log_Total && Log[view_Batch] != NULL) {
-							ask_question = ask_skip_cmd;
-							ask_question_answer = 1;
-						}
-					}
-					break;
-				case InputKeyRight:
-					if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
-						if(ask_question) {
-							ask_question_answer ^= 1;
-						} else if(Edit) {
-							if(is_digit(Edit_pos + 1, Edit_hex)) Edit_pos++;
-							else if(*(Edit_pos + 1) == ',') {
-								Edit_pos += 2;
-								if(*(Edit_pos + 1) == 'x') Edit_pos += 2;
-							}
-						} else if(what_doing == 0) {
-							if(addr_len) {
-								rw_type = rwt_set_batch;
-								what_doing = 1;
-							}
-						} else if(what_doing == 1) {
-							if(event.input.type == InputTypeShort) next_rw_type(+1); else view_x++;
-						} else if(what_doing == 2) view_x++;
-					}
-					break;
-				case InputKeyOk:
-					if(event.input.type == InputTypeShort) {
-						if(ask_question) {
-							if(ask_question_answer) {
-								if(ask_question == ask_save_batch) {
-									save_batch();
-								} else if(ask_question == ask_write_batch) {
-									if(WriteBatch_cmd_Total) {
-										if(what_doing == 1) {
-											Prepare_Write_cmd(WriteBatch_cmd[view_cmd[rwt_write_batch]]);
-											send_status = sst_none;
-											Edited = false;
-											view_x = 0;
-											view_Batch = 0;
-										}
-										if(Log_Total) {
-											ERR = 0;
-											WriteBatch_cmd_curr = 0;
-											Run_WriteBatch_cmd();
-											what_doing = 2;
-										}
-									}
-								} else if(ask_question == ask_skip_cmd) {
-									if(rw_type == rwt_write_batch || rw_type == rwt_read_batch) {
-										furi_string_free(Log[view_Batch]);
-										if(view_Batch < Log_Total - 1) memmove(&Log[view_Batch], &Log[view_Batch + 1], sizeof(Log) * (Log_Total - view_Batch - 1));
-										else view_Batch--;
-										Log_Total--;
-									}
-								} else if(ask_question == ask_exit) {
-									processing = false;
-								} else if(ask_question == ask_return) {
-									if(what_doing == 2) {
-										ERR = 0;
-										send_status = sst_none;
-										Edited = false;
-										what_doing--;
-									}
-								}
-							}
-							ask_question = 0;
-						} else if(Edit) { // insert digit
-							Edit_insert_digit('0');
-						} else if(what_doing == 0) {
-							if(setup_cursor == 0) { // open file
-								file_stream_close(file_stream);
-								if(select_settings_file()) {
-									uint8_t err = load_settings_file();
-									if(err) snprintf(file_name, sizeof(file_name), "LOAD ERROR #%d", err);
-								}
-							} else if(setup_cursor == 1) { // change address
-								char *ebuf = (char*)payload;
-								ebuf[0] = '\0';
-								add_to_str_hex_bytes(ebuf, addr, addr_len);
-								Edit_hex = true;
-								Edit_pos = ebuf + strlen(ebuf) - 1;
-								Edit_start = ebuf;
-								Edit = 1;
-								NRF_INITED = 0;
-							} else if(setup_cursor == 2) { // change channel
-								char *ebuf = (char*)payload;
-								snprintf(ebuf, sizeof(payload), "%d", NRF_channel);
-								Edit_hex = false;
-								Edit_pos = ebuf + strlen(ebuf) - 1;
-								Edit_start = ebuf;
-								Edit = 1;
-								NRF_INITED = 0;
-							}
-						} else if(what_doing == 1) {
-							if(rw_type == rwt_set_batch) {
-								if(SetBatch_cmd_Total) {
-									ERR = 0;
-									send_status = sst_none;
-									Prepare_Write_cmd(SetBatch_cmd[view_cmd[rwt_set_batch]]);
-									if(!ERR) {
-										SetBatch_cmd_curr = 0;
-										Run_WriteBatch_cmd();
-										what_doing = 2;
-									}
-									Edited = false;
-								}
-							} else if(rw_type == rwt_read_batch) {
-								if(ReadBatch_cmd_Total) {
-									ERR = 0;
-									Run_ReadBatch_cmd(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
-									view_x = 0;
-									view_Batch = 0;
-									what_doing = 2;
-								}
-							} else if(rw_type == rwt_read_cmd) {
-								if(Read_cmd_Total) {
-									ERR = 0;
-									free_Log();
-									Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
-									view_x = 0;
-									what_doing = 2;
-								}
-							} else if(rw_type == rwt_write_batch) {
-								if(WriteBatch_cmd_Total) {
-									ERR = 0;
-									Prepare_Write_cmd(WriteBatch_cmd[view_cmd[rwt_write_batch]]);
-									send_status = sst_none;
-									Edited = false;
-									view_x = 0;
-									view_Batch = 0;
-									what_doing = 2;
-								}
-							} else if(rw_type == rwt_listen) {
-								if(listen_addr_len) {
-									free_Log();
-									prepare_nrf24();
-									if(!NRF_ERROR) {
-										nrf24_set_rx_mode(nrf24_HANDLE);
-										ListenNew = false;
-										send_status = sst_receiving; // receiving
-									}
-									what_doing = 2;
-								}
-							}
-						} else if(what_doing == 2) {		
-							if(rw_type == rwt_read_cmd) {
-								ERR = 0;
-								free_Log();
-								Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
-							} else if(Log_Total) {
-								if(rw_type == rwt_read_batch) {
-									ask_question = ask_save_batch;
-									ask_question_answer = 0;
-								} else if(rw_type == rwt_write_batch) {
-									ask_question = ask_write_batch;
-									ask_question_answer = 0;
-								}
-							}
-						}
-					} else if(event.input.type == InputTypeLong) {
-						if(Edit) { // delete
-							if(what_doing <= 1) {
-								if(strlen(Edit_start) > 1) {
-									memmove(Edit_pos, Edit_pos + 1, strlen(Edit_pos));
-									if(*Edit_pos == '\0') Edit_pos--;
-								}
-							} else {
-								FuriString *fs = Log[view_Batch];
-								if(is_digit(Edit_pos + 1, Edit_hex) || (Edit_pos > Edit_start && is_digit(Edit_pos - 1, Edit_hex))) { 
-									memmove(Edit_pos, Edit_pos + 1, strlen(Edit_pos));
-									if(*Edit_pos == '\0') Edit_pos--;
-									furi_string_left(fs, furi_string_size(fs) - 1);
-								}
-							}
-						} else if(what_doing == 1) {
-							if(rw_type == rwt_listen) {
-								if(listen_addr_len) {
-									char *ebuf = (char*)payload;
-									ebuf[0] = '\0';
-									add_to_str_hex_bytes(ebuf, listen_addr, listen_addr_len);
-									Edit_hex = true;
-									Edit_pos = ebuf + strlen(ebuf) - 1;
-									Edit_start = ebuf;
-									Edit = 1;
-									NRF_INITED = 0;
-								}
-							} else if(rw_type == rwt_read_batch) {
-								if(ReadBatch_cmd_Total) {
-									ERR = 0;
-									Run_ReadBatch_cmd(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
-									view_x = 0;
-									view_Batch = 0;
-									what_doing = 2;
-								}
-							} else if(rw_type == rwt_write_batch) {
-								ask_question = ask_write_batch;
-								ask_question_answer = 0;
-							}
-						} else if(what_doing == 2) {
-							if(rw_type == rwt_read_cmd) {
-								ReadRepeat = !ReadRepeat;
-							} else if(Log_Total) {
-								if(rw_type == rwt_write_batch) {
-									if(!Edit) {
-										Edit = 0;
-										Edit_hex = 0;
-										char *s = (char*)furi_string_get_cstr(Log[view_Batch]);
-										char *p = strchr(s, '=');
-										if(p) {
-											p++;
-											if(*p == '{') p++; // array
-											if(*(p + 1) == 'x') { 
-												p += 2;
-												Edit_hex = 1; // hex
-											}
-											if(is_digit(p, Edit_hex)) {
-												Edit_start = p;
-												while(is_digit(p, Edit_hex)) p++;
-												Edit_pos = p - 1;
-												Edited = true;
-												Edit = 1;
-											}
-										}
-									}
-								} else if(rw_type == rwt_read_batch) {
-									ask_question = ask_save_batch;
-									ask_question_answer = 0;
-								}
-							}
-						}
-					}
-					break;
-				case InputKeyBack:
-					if(event.input.type == InputTypeLong) {
-						if(what_doing == 2 && Edited) {
-							if(!ask_question) ask_question_answer = 1;
-							ask_question = ask_exit;
-						} else processing = false;
-					} else if(event.input.type == InputTypeShort) {
-						if(ask_question) ask_question = 0;
-						else if(Edit) {
-							if(what_doing == 0) {
-								if(setup_cursor == 1) {
-									addr_len = ConvertHexToArray((char*)payload, addr, 5);
-								} else if(setup_cursor == 2) {
-									NRF_channel = str_to_int((char*)payload);
-									if(NRF_channel > MAX_CHANNEL) NRF_channel = MAX_CHANNEL;
-								}
-							} else if(what_doing == 1 && rw_type == rwt_listen) {
-								listen_addr_len = ConvertHexToArray((char*)payload, listen_addr, 5);
-							}
-							Edit = 0;
-						} else {
-							if(what_doing == 2 && Edited) {
-								ask_question = ask_return;
-								ask_question_answer = 1;
-							} else if(what_doing != 0) {
-								if(what_doing) what_doing--;
-								if(what_doing == 0) rw_type = rwt_read_batch;
-								if(what_doing <= 1) view_x = 0;
-								ERR = 0;
-								send_status = sst_none;
-							}
-						}
-					}
-					break;
-				default:
-					break;
-				}
-			}
-		}
+        if(event_status == FuriStatusOk) {
+            // press events
+            if(event.type == EventTypeKey) {
+                switch(event.input.key) {
+                case InputKeyUp:
+                    if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
+                        if(!ask_question) {
+                            if(Edit) {
+                                char c = *Edit_pos;
+                                if(Edit_hex) {
+                                    if(c == '9')
+                                        *Edit_pos = 'A';
+                                    else if(c < 'F' || c < '9')
+                                        *Edit_pos = c + 1;
+                                } else {
+                                    if(c == '-')
+                                        *Edit_pos = '0';
+                                    else if(c < '9')
+                                        *Edit_pos = c + 1;
+                                    else {
+                                        c = *(Edit_pos - 1);
+                                        if(Edit_pos > Edit_start && c < '9' && c >= '0') {
+                                            *Edit_pos = '0';
+                                            (*(Edit_pos - 1)) = c + 1;
+                                        }
+                                    }
+                                }
+                            } else if(what_doing == 0) {
+                                if(addr_len) {
+                                    if(setup_cursor > 0)
+                                        setup_cursor--;
+                                    else
+                                        setup_cursor = 2;
+                                }
+                            } else if(what_doing == 1)
+                                next_view_cmd(-1);
+                            else if(what_doing == 2)
+                                if(view_Batch) view_Batch--;
+                        }
+                    }
+                    break;
+                case InputKeyDown:
+                    if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
+                        if(!ask_question) {
+                            if(Edit) {
+                                if(*Edit_pos != '-') {
+                                    if(Edit_hex && *Edit_pos == 'A')
+                                        (*Edit_pos) = '9';
+                                    else if(*Edit_pos > '0')
+                                        (*Edit_pos)--;
+                                    else if(!Edit_hex) {
+                                        if(Edit_pos > Edit_start) {
+                                            if(*(Edit_pos - 1) > '0' && *(Edit_pos - 1) <= '9') {
+                                                *Edit_pos = '9';
+                                                (*(Edit_pos - 1))--;
+                                            }
+                                        } else
+                                            Edit_insert_digit('-'); // negative
+                                    }
+                                }
+                            } else if(what_doing == 0) {
+                                if(addr_len) {
+                                    if(setup_cursor < 2)
+                                        setup_cursor++;
+                                    else
+                                        setup_cursor = 0;
+                                }
+                            } else if(what_doing == 1)
+                                next_view_cmd(+1);
+                            else if(what_doing == 2)
+                                if(view_Batch < Log_Total - 1) view_Batch++;
+                        }
+                    }
+                    break;
+                case InputKeyLeft:
+                    if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
+                        if(ask_question) {
+                            if(event.input.type == InputTypeShort) ask_question_answer ^= 1;
+                        } else if(Edit) {
+                            if(Edit_pos > Edit_start) {
+                                if(is_digit(Edit_pos - 1, Edit_hex))
+                                    Edit_pos--;
+                                else if(*(Edit_pos - 1) == 'x' && *(Edit_pos - 3) == ',')
+                                    Edit_pos -= 4;
+                                else if(*(Edit_pos - 1) == ',')
+                                    Edit_pos -= 2;
+                            }
+                        } else if(what_doing == 0) {
+                            if(addr_len) {
+                                rw_type = rwt_listen;
+                                what_doing = 1;
+                            }
+                        } else if(what_doing == 1) {
+                            if(event.input.type == InputTypeShort)
+                                next_rw_type(-1);
+                            else if(view_x)
+                                view_x--;
+                        } else if(what_doing == 2)
+                            if(view_x) view_x--;
+                    } else if(event.input.type == InputTypeLong) {
+                        if(!ask_question && view_x == 0 && what_doing == 2 &&
+                           (rw_type == rwt_write_batch || rw_type == rwt_read_batch) &&
+                           Log_Total && Log[view_Batch] != NULL) {
+                            ask_question = ask_skip_cmd;
+                            ask_question_answer = 1;
+                        }
+                    }
+                    break;
+                case InputKeyRight:
+                    if(event.input.type == InputTypeShort || event.input.type == InputTypeRepeat) {
+                        if(ask_question) {
+                            ask_question_answer ^= 1;
+                        } else if(Edit) {
+                            if(is_digit(Edit_pos + 1, Edit_hex))
+                                Edit_pos++;
+                            else if(*(Edit_pos + 1) == ',') {
+                                Edit_pos += 2;
+                                if(*(Edit_pos + 1) == 'x') Edit_pos += 2;
+                            }
+                        } else if(what_doing == 0) {
+                            if(addr_len) {
+                                rw_type = rwt_set_batch;
+                                what_doing = 1;
+                            }
+                        } else if(what_doing == 1) {
+                            if(event.input.type == InputTypeShort)
+                                next_rw_type(+1);
+                            else
+                                view_x++;
+                        } else if(what_doing == 2)
+                            view_x++;
+                    }
+                    break;
+                case InputKeyOk:
+                    if(event.input.type == InputTypeShort) {
+                        if(ask_question) {
+                            if(ask_question_answer) {
+                                if(ask_question == ask_save_batch) {
+                                    save_batch();
+                                } else if(ask_question == ask_write_batch) {
+                                    if(WriteBatch_cmd_Total) {
+                                        if(what_doing == 1) {
+                                            Prepare_Write_cmd(
+                                                WriteBatch_cmd[view_cmd[rwt_write_batch]]);
+                                            send_status = sst_none;
+                                            Edited = false;
+                                            view_x = 0;
+                                            view_Batch = 0;
+                                        }
+                                        if(Log_Total) {
+                                            ERR = 0;
+                                            WriteBatch_cmd_curr = 0;
+                                            Run_WriteBatch_cmd();
+                                            what_doing = 2;
+                                        }
+                                    }
+                                } else if(ask_question == ask_skip_cmd) {
+                                    if(rw_type == rwt_write_batch || rw_type == rwt_read_batch) {
+                                        furi_string_free(Log[view_Batch]);
+                                        if(view_Batch < Log_Total - 1)
+                                            memmove(
+                                                &Log[view_Batch],
+                                                &Log[view_Batch + 1],
+                                                sizeof(Log) * (Log_Total - view_Batch - 1));
+                                        else
+                                            view_Batch--;
+                                        Log_Total--;
+                                    }
+                                } else if(ask_question == ask_exit) {
+                                    processing = false;
+                                } else if(ask_question == ask_return) {
+                                    if(what_doing == 2) {
+                                        ERR = 0;
+                                        send_status = sst_none;
+                                        Edited = false;
+                                        what_doing--;
+                                    }
+                                }
+                            }
+                            ask_question = 0;
+                        } else if(Edit) { // insert digit
+                            Edit_insert_digit('0');
+                        } else if(what_doing == 0) {
+                            if(setup_cursor == 0) { // open file
+                                file_stream_close(file_stream);
+                                if(select_settings_file()) {
+                                    uint8_t err = load_settings_file();
+                                    if(err)
+                                        snprintf(
+                                            file_name, sizeof(file_name), "LOAD ERROR #%d", err);
+                                }
+                            } else if(setup_cursor == 1) { // change address
+                                char* ebuf = (char*)payload;
+                                ebuf[0] = '\0';
+                                add_to_str_hex_bytes(ebuf, addr, addr_len);
+                                Edit_hex = true;
+                                Edit_pos = ebuf + strlen(ebuf) - 1;
+                                Edit_start = ebuf;
+                                Edit = 1;
+                                NRF_INITED = 0;
+                            } else if(setup_cursor == 2) { // change channel
+                                char* ebuf = (char*)payload;
+                                snprintf(ebuf, sizeof(payload), "%d", NRF_channel);
+                                Edit_hex = false;
+                                Edit_pos = ebuf + strlen(ebuf) - 1;
+                                Edit_start = ebuf;
+                                Edit = 1;
+                                NRF_INITED = 0;
+                            }
+                        } else if(what_doing == 1) {
+                            if(rw_type == rwt_set_batch) {
+                                if(SetBatch_cmd_Total) {
+                                    ERR = 0;
+                                    send_status = sst_none;
+                                    Prepare_Write_cmd(SetBatch_cmd[view_cmd[rwt_set_batch]]);
+                                    if(!ERR) {
+                                        SetBatch_cmd_curr = 0;
+                                        Run_WriteBatch_cmd();
+                                        what_doing = 2;
+                                    }
+                                    Edited = false;
+                                }
+                            } else if(rw_type == rwt_read_batch) {
+                                if(ReadBatch_cmd_Total) {
+                                    ERR = 0;
+                                    Run_ReadBatch_cmd(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
+                                    view_x = 0;
+                                    view_Batch = 0;
+                                    what_doing = 2;
+                                }
+                            } else if(rw_type == rwt_read_cmd) {
+                                if(Read_cmd_Total) {
+                                    ERR = 0;
+                                    free_Log();
+                                    Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
+                                    view_x = 0;
+                                    what_doing = 2;
+                                }
+                            } else if(rw_type == rwt_write_batch) {
+                                if(WriteBatch_cmd_Total) {
+                                    ERR = 0;
+                                    Prepare_Write_cmd(WriteBatch_cmd[view_cmd[rwt_write_batch]]);
+                                    send_status = sst_none;
+                                    Edited = false;
+                                    view_x = 0;
+                                    view_Batch = 0;
+                                    what_doing = 2;
+                                }
+                            } else if(rw_type == rwt_listen) {
+                                if(listen_addr_len) {
+                                    free_Log();
+                                    prepare_nrf24();
+                                    if(!NRF_ERROR) {
+                                        nrf24_set_rx_mode(nrf24_HANDLE);
+                                        ListenNew = false;
+                                        send_status = sst_receiving; // receiving
+                                    }
+                                    what_doing = 2;
+                                }
+                            }
+                        } else if(what_doing == 2) {
+                            if(rw_type == rwt_read_cmd) {
+                                ERR = 0;
+                                free_Log();
+                                Run_Read_cmd(Read_cmd[view_cmd[rwt_read_cmd]]);
+                            } else if(Log_Total) {
+                                if(rw_type == rwt_read_batch) {
+                                    ask_question = ask_save_batch;
+                                    ask_question_answer = 0;
+                                } else if(rw_type == rwt_write_batch) {
+                                    ask_question = ask_write_batch;
+                                    ask_question_answer = 0;
+                                }
+                            }
+                        }
+                    } else if(event.input.type == InputTypeLong) {
+                        if(Edit) { // delete
+                            if(what_doing <= 1) {
+                                if(strlen(Edit_start) > 1) {
+                                    memmove(Edit_pos, Edit_pos + 1, strlen(Edit_pos));
+                                    if(*Edit_pos == '\0') Edit_pos--;
+                                }
+                            } else {
+                                FuriString* fs = Log[view_Batch];
+                                if(is_digit(Edit_pos + 1, Edit_hex) ||
+                                   (Edit_pos > Edit_start && is_digit(Edit_pos - 1, Edit_hex))) {
+                                    memmove(Edit_pos, Edit_pos + 1, strlen(Edit_pos));
+                                    if(*Edit_pos == '\0') Edit_pos--;
+                                    furi_string_left(fs, furi_string_size(fs) - 1);
+                                }
+                            }
+                        } else if(what_doing == 1) {
+                            if(rw_type == rwt_listen) {
+                                if(listen_addr_len) {
+                                    char* ebuf = (char*)payload;
+                                    ebuf[0] = '\0';
+                                    add_to_str_hex_bytes(ebuf, listen_addr, listen_addr_len);
+                                    Edit_hex = true;
+                                    Edit_pos = ebuf + strlen(ebuf) - 1;
+                                    Edit_start = ebuf;
+                                    Edit = 1;
+                                    NRF_INITED = 0;
+                                }
+                            } else if(rw_type == rwt_read_batch) {
+                                if(ReadBatch_cmd_Total) {
+                                    ERR = 0;
+                                    Run_ReadBatch_cmd(ReadBatch_cmd[view_cmd[rwt_read_batch]]);
+                                    view_x = 0;
+                                    view_Batch = 0;
+                                    what_doing = 2;
+                                }
+                            } else if(rw_type == rwt_write_batch) {
+                                ask_question = ask_write_batch;
+                                ask_question_answer = 0;
+                            }
+                        } else if(what_doing == 2) {
+                            if(rw_type == rwt_read_cmd) {
+                                ReadRepeat = !ReadRepeat;
+                            } else if(Log_Total) {
+                                if(rw_type == rwt_write_batch) {
+                                    if(!Edit) {
+                                        Edit = 0;
+                                        Edit_hex = 0;
+                                        char* s = (char*)furi_string_get_cstr(Log[view_Batch]);
+                                        char* p = strchr(s, '=');
+                                        if(p) {
+                                            p++;
+                                            if(*p == '{') p++; // array
+                                            if(*(p + 1) == 'x') {
+                                                p += 2;
+                                                Edit_hex = 1; // hex
+                                            }
+                                            if(is_digit(p, Edit_hex)) {
+                                                Edit_start = p;
+                                                while(is_digit(p, Edit_hex)) p++;
+                                                Edit_pos = p - 1;
+                                                Edited = true;
+                                                Edit = 1;
+                                            }
+                                        }
+                                    }
+                                } else if(rw_type == rwt_read_batch) {
+                                    ask_question = ask_save_batch;
+                                    ask_question_answer = 0;
+                                }
+                            }
+                        }
+                    }
+                    break;
+                case InputKeyBack:
+                    if(event.input.type == InputTypeLong) {
+                        if(what_doing == 2 && Edited) {
+                            if(!ask_question) ask_question_answer = 1;
+                            ask_question = ask_exit;
+                        } else
+                            processing = false;
+                    } else if(event.input.type == InputTypeShort) {
+                        if(ask_question)
+                            ask_question = 0;
+                        else if(Edit) {
+                            if(what_doing == 0) {
+                                if(setup_cursor == 1) {
+                                    addr_len = ConvertHexToArray((char*)payload, addr, 5);
+                                } else if(setup_cursor == 2) {
+                                    NRF_channel = str_to_int((char*)payload);
+                                    if(NRF_channel > MAX_CHANNEL) NRF_channel = MAX_CHANNEL;
+                                }
+                            } else if(what_doing == 1 && rw_type == rwt_listen) {
+                                listen_addr_len =
+                                    ConvertHexToArray((char*)payload, listen_addr, 5);
+                            }
+                            Edit = 0;
+                        } else {
+                            if(what_doing == 2 && Edited) {
+                                ask_question = ask_return;
+                                ask_question_answer = 1;
+                            } else if(what_doing != 0) {
+                                if(what_doing) what_doing--;
+                                if(what_doing == 0) rw_type = rwt_read_batch;
+                                if(what_doing <= 1) view_x = 0;
+                                ERR = 0;
+                                send_status = sst_none;
+                            }
+                        }
+                    }
+                    break;
+                default:
+                    break;
+                }
+            }
+        }
 
-		view_port_update(view_port);
-		furi_mutex_release(APP->plugin_state->mutex);
-	}
-	nrf24_set_idle(nrf24_HANDLE);
-	nrf24_deinit();
-	if(NRF_BOARD_POWER_5V) furi_hal_power_disable_otg();
+        view_port_update(view_port);
+        furi_mutex_release(APP->plugin_state->mutex);
+    }
+    nrf24_set_idle(nrf24_HANDLE);
+    nrf24_deinit();
+    if(NRF_BOARD_POWER_5V) furi_hal_power_disable_otg();
 
-	view_port_enabled_set(view_port, false);
-	gui_remove_view_port(APP->gui, view_port);
-	furi_record_close(RECORD_GUI);
-	furi_record_close(RECORD_NOTIFICATION);
-	furi_record_close(RECORD_STORAGE);
-	if(file_stream) {
-		file_stream_close(file_stream);
-		stream_free(file_stream);
-	}
-	view_port_free(view_port);
-	furi_message_queue_free(event_queue);
-	free_store();
-	furi_timer_stop(work_timer);
-	furi_timer_free(work_timer);
-	furi_mutex_free(APP->plugin_state->mutex);
-	free(APP->plugin_state);
-	free(APP);
-	return 0;
+    view_port_enabled_set(view_port, false);
+    gui_remove_view_port(APP->gui, view_port);
+    furi_record_close(RECORD_GUI);
+    furi_record_close(RECORD_NOTIFICATION);
+    furi_record_close(RECORD_STORAGE);
+    if(file_stream) {
+        file_stream_close(file_stream);
+        stream_free(file_stream);
+    }
+    view_port_free(view_port);
+    furi_message_queue_free(event_queue);
+    free_store();
+    furi_timer_stop(work_timer);
+    furi_timer_free(work_timer);
+    furi_mutex_free(APP->plugin_state->mutex);
+    free(APP->plugin_state);
+    free(APP);
+    return 0;
 }

+ 10 - 3
non_catalog_apps/uhf_rfid/uhf_app.c

@@ -197,15 +197,22 @@ int32_t uhf_app_main(void* ctx) {
     UHFApp* uhf_app = uhf_alloc();
 
     // enable 5v pin
-    furi_hal_power_enable_otg();
+     uint8_t attempts = 0;
+    bool otg_was_enabled = furi_hal_power_is_otg_enabled();
+    while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
+        furi_hal_power_enable_otg();
+        furi_delay_ms(10);
+    }
+    furi_delay_ms(200);
     // init pin a2
     // furi_hal_gpio_init_simple(&gpio_ext_pa7, GpioModeOutputPushPull);
-    furi_hal_uart_set_br(FuriHalUartIdUSART1, DEFAULT_BAUDRATE);
     scene_manager_next_scene(uhf_app->scene_manager, UHFSceneModuleInfo);
     view_dispatcher_run(uhf_app->view_dispatcher);
 
     // disable 5v pin
-    furi_hal_power_disable_otg();
+     if(furi_hal_power_is_otg_enabled() && !otg_was_enabled) {
+        furi_hal_power_disable_otg();
+    }
     // furi_hal_gpio_disable_int_callback()
     // exit app
     uhf_free(uhf_app);

+ 2 - 0
non_catalog_apps/wifi_deauther/wifi_deauther_app_i.h

@@ -12,6 +12,8 @@
 #include <gui/modules/text_input.h>
 #include <gui/modules/variable_item_list.h>
 
+#define UART_CH (FuriHalSerialIdUsart)
+
 #define NUM_MENU_ITEMS (11)
 
 #define WIFI_deauther_TEXT_BOX_STORE_SIZE (4096)

+ 15 - 11
non_catalog_apps/wifi_deauther/wifi_deauther_uart.c

@@ -4,16 +4,15 @@
 #include <FreeRTOS.h>
 #include <stream_buffer.h>
 
-#define UART_CH (FuriHalUartIdUSART1)
 #define BAUDRATE (115200)
 
 struct WifideautherUart {
     WifideautherApp* app;
-    FuriHalUartId channel;
     FuriThread* rx_thread;
     FuriStreamBuffer* rx_stream;
     uint8_t rx_buf[RX_BUF_SIZE + 1];
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context);
+    FuriHalSerialHandle* serial_handle;
 };
 
 typedef enum {
@@ -30,10 +29,14 @@ void wifi_deauther_uart_set_handle_rx_data_cb(
 
 #define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
 
-void wifi_deauther_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+void wifi_deauther_uart_on_irq_cb(
+    FuriHalSerialHandle* handle,
+    FuriHalSerialRxEvent event,
+    void* context) {
     WifideautherUart* uart = (WifideautherUart*)context;
 
-    if(ev == UartIrqEventRXNE) {
+    if(event == FuriHalSerialRxEventData) {
+        uint8_t data = furi_hal_serial_async_rx(handle);
         furi_stream_buffer_send(uart->rx_stream, &data, 1, 0);
         furi_thread_flags_set(furi_thread_get_id(uart->rx_thread), WorkerEvtRxDone);
     }
@@ -60,8 +63,8 @@ static int32_t uart_worker(void* context) {
     return 0;
 }
 
-void wifi_deauther_uart_tx(uint8_t* data, size_t len) {
-    furi_hal_uart_tx(UART_CH, data, len);
+void wifi_deauther_uart_tx(WifideautherUart* uart, uint8_t* data, size_t len) {
+    furi_hal_serial_tx(uart->serial_handle, data, len);
 }
 
 WifideautherUart* wifi_deauther_uart_init(WifideautherApp* app) {
@@ -77,9 +80,10 @@ WifideautherUart* wifi_deauther_uart_init(WifideautherApp* app) {
 
     furi_thread_start(uart->rx_thread);
 
-    furi_hal_console_disable();
-    furi_hal_uart_set_br(UART_CH, BAUDRATE);
-    furi_hal_uart_set_irq_cb(UART_CH, wifi_deauther_uart_on_irq_cb, uart);
+    uart->serial_handle = furi_hal_serial_control_acquire(UART_CH);
+    furi_check(uart->serial_handle);
+    furi_hal_serial_init(uart->serial_handle, BAUDRATE);
+    furi_hal_serial_async_rx_start(uart->serial_handle, wifi_deauther_uart_on_irq_cb, uart, false);
 
     return uart;
 }
@@ -91,8 +95,8 @@ void wifi_deauther_uart_free(WifideautherUart* uart) {
     furi_thread_join(uart->rx_thread);
     furi_thread_free(uart->rx_thread);
 
-    furi_hal_uart_set_irq_cb(UART_CH, NULL, NULL);
-    furi_hal_console_enable();
+    furi_hal_serial_deinit(uart->serial_handle);
+    furi_hal_serial_control_release(uart->serial_handle);
 
     free(uart);
 }

+ 1 - 1
non_catalog_apps/wifi_deauther/wifi_deauther_uart.h

@@ -9,6 +9,6 @@ typedef struct WifideautherUart WifideautherUart;
 void wifi_deauther_uart_set_handle_rx_data_cb(
     WifideautherUart* uart,
     void (*handle_rx_data_cb)(uint8_t* buf, size_t len, void* context));
-void wifi_deauther_uart_tx(uint8_t* data, size_t len);
+void wifi_deauther_uart_tx(WifideautherUart* uart, uint8_t* data, size_t len);
 WifideautherUart* wifi_deauther_uart_init(WifideautherApp* app);
 void wifi_deauther_uart_free(WifideautherUart* uart);